@aglyn/plugins-ai 1.0.0-beta.235 → 1.0.0-beta.237
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +17 -17
- package/src/lib/components/ai-credits-prompt.component.d.ts +37 -0
- package/src/lib/components/ai-credits-prompt.component.js +67 -0
- package/src/lib/components/ai-credits-prompt.component.js.map +1 -0
- package/src/lib/components/ai-job-plan.component.d.ts +5 -4
- package/src/lib/components/ai-job-plan.component.js +37 -12
- package/src/lib/components/ai-job-plan.component.js.map +1 -1
- package/src/lib/components/ai-job-requests.d.ts +10 -0
- package/src/lib/components/ai-job-requests.js +12 -4
- package/src/lib/components/ai-job-requests.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.js +26 -7
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/components/ai-site-start-card.component.js +68 -22
- package/src/lib/components/ai-site-start-card.component.js.map +1 -1
- package/src/lib/components/assist-build-card.component.d.ts +3 -1
- package/src/lib/components/assist-build-card.component.js +58 -7
- package/src/lib/components/assist-build-card.component.js.map +1 -1
- package/src/lib/components/assist-jobs-drawer.component.js +54 -6
- package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
- package/src/lib/components/assist-panel.component.js +2 -1
- package/src/lib/components/assist-panel.component.js.map +1 -1
- package/src/lib/jobs/ai-job-admission.d.ts +22 -2
- package/src/lib/jobs/ai-job-admission.js.map +1 -1
- package/src/lib/jobs/ai-job-build-step.d.ts +24 -11
- package/src/lib/jobs/ai-job-build-step.js +50 -34
- package/src/lib/jobs/ai-job-build-step.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-language.js +1 -1
- package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.js +4 -0
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.d.ts +13 -0
- package/src/lib/jobs/ai-job-page-step.js +34 -3
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-plan-step.d.ts +23 -0
- package/src/lib/jobs/ai-job-plan-step.js +75 -15
- package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-content.d.ts +34 -3
- package/src/lib/jobs/ai-job-site-content.js +132 -32
- package/src/lib/jobs/ai-job-site-content.js.map +1 -1
- package/src/lib/jobs/ai-job-site-step.js +45 -15
- package/src/lib/jobs/ai-job-site-step.js.map +1 -1
- package/src/lib/jobs/ai-job-text-step.d.ts +8 -0
- package/src/lib/jobs/ai-job-text-step.js.map +1 -1
- package/src/lib/jobs/ai-jobs.d.ts +18 -1
- package/src/lib/jobs/ai-jobs.js +29 -13
- package/src/lib/jobs/ai-jobs.js.map +1 -1
- package/src/lib/jobs/ai-layout-stock-photos.d.ts +105 -18
- package/src/lib/jobs/ai-layout-stock-photos.js +356 -114
- package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
- package/src/lib/layout-language/ai-layout-compiler.d.ts +27 -0
- package/src/lib/layout-language/ai-layout-compiler.js +78 -11
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-gaps.js +3 -1
- package/src/lib/layout-language/ai-layout-gaps.js.map +1 -1
- package/src/lib/layout-language/ai-layout-language.js +1 -1
- package/src/lib/layout-language/ai-layout-language.js.map +1 -1
- package/src/lib/layout-language/ai-layout-listings.d.ts +37 -1
- package/src/lib/layout-language/ai-layout-listings.js +66 -11
- package/src/lib/layout-language/ai-layout-listings.js.map +1 -1
- package/src/lib/layout-language/ai-layout-pictures.d.ts +2 -1
- package/src/lib/layout-language/ai-layout-pictures.js +5 -2
- package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
- package/src/lib/model/ai-build-job.d.ts +31 -0
- package/src/lib/model/ai-build-job.js +86 -1
- package/src/lib/model/ai-build-job.js.map +1 -1
- package/src/lib/model/ai-build-progress.d.ts +8 -0
- package/src/lib/model/ai-build-progress.js +33 -0
- package/src/lib/model/ai-build-progress.js.map +1 -1
- package/src/lib/model/ai-credit-estimate.d.ts +182 -0
- package/src/lib/model/ai-credit-estimate.js +190 -0
- package/src/lib/model/ai-credit-estimate.js.map +1 -0
- package/src/lib/model/ai-jobs.types.d.ts +15 -0
- package/src/lib/model/ai-jobs.types.js.map +1 -1
- package/src/lib/model/ai-site-job.d.ts +59 -22
- package/src/lib/model/ai-site-job.js +104 -23
- package/src/lib/model/ai-site-job.js.map +1 -1
- package/src/lib/model/ai-site-kinds.js +3 -3
- package/src/lib/model/ai-site-kinds.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.js +10 -1
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-node-tree.d.ts +11 -0
- package/src/lib/runtime/ai-node-tree.js +26 -0
- package/src/lib/runtime/ai-node-tree.js.map +1 -1
- package/src/lib/runtime/ai-palette.generated.js +539 -7
- package/src/lib/runtime/ai-palette.generated.js.map +1 -1
- package/src/lib/server/ai-jobs-resume.js +93 -35
- package/src/lib/server/ai-jobs-resume.js.map +1 -1
- package/src/lib/server/ai-jobs-route.js +45 -4
- package/src/lib/server/ai-jobs-route.js.map +1 -1
- package/src/lib/server/assist-chat.js +4 -1
- package/src/lib/server/assist-chat.js.map +1 -1
- package/src/lib/server/assist-edit.js +3 -1
- package/src/lib/server/assist-edit.js.map +1 -1
- package/src/lib/server/assist-music.d.ts +36 -0
- package/src/lib/server/assist-music.js +36 -0
- package/src/lib/server/assist-music.js.map +1 -0
- package/src/lib/server.js +6 -0
- package/src/lib/server.js.map +1 -1
|
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import {
|
|
17
|
+
*/ import { resolveMediaSrc } from "@aglyn/aglyn/app-utils/media-ref";
|
|
18
|
+
import { hostRoleCanWrite } from "@aglyn/aglyn/app-utils/organizations";
|
|
18
19
|
import { pluginResourceDraftWriter } from "@aglyn/aglyn/plugin-manager/plugin-resource-drafts";
|
|
19
20
|
import { publishContentEntries, writeContentCollection, writeContentEntryDraft } from "@aglyn/tenant-data-admin/server/content-entry-drafts";
|
|
20
21
|
import { aiProductsProposalOf } from "../model/ai-products.js";
|
|
@@ -24,6 +25,7 @@ import { AI_STEP_TIERS } from "../providers/catalog.js";
|
|
|
24
25
|
import { aiModelForStep } from "../providers/routing.js";
|
|
25
26
|
import { AI_BLOG_POST_MAX_TOKENS, AI_BLOG_POST_STEP, generateAiBlogPost } from "../runtime/ai-blog-post-generation.js";
|
|
26
27
|
import { aiLayoutStarterPhotos } from "../layout-language/ai-layout-pictures.js";
|
|
28
|
+
import { aiOriginJobId } from "./ai-job-draft-ids.js";
|
|
27
29
|
import { aiLayoutStockPhotoSource } from "./ai-layout-stock-photos.js";
|
|
28
30
|
import { aiLayoutListingId, aiLayoutListingPlacements } from "../layout-language/ai-layout-listings.js";
|
|
29
31
|
import { aiJobAdmissionFor } from "./ai-job-admission.js";
|
|
@@ -77,6 +79,7 @@ import { aiGenerationSpent, aiUnspentOutcome } from "./ai-job-generation.js";
|
|
|
77
79
|
min: 3,
|
|
78
80
|
max: 6
|
|
79
81
|
};
|
|
82
|
+
/** What a products row says when none of what we made could be written: our failure, refunded. */ export const AI_SITE_PRODUCTS_NOT_WRITTEN_COPY = 'Your first products could not be added this time.';
|
|
80
83
|
/** What each part's row reads. */ export const AI_SITE_POSTS_LABEL = 'Writing your first posts';
|
|
81
84
|
export const AI_SITE_PRODUCTS_LABEL = 'Adding your first products';
|
|
82
85
|
/** The blog the posts go in, and the addresses it may answer at (`model/ai-site-job.ts`). */ export { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS } from "../model/ai-site-job.js";
|
|
@@ -154,7 +157,8 @@ const limitReview = (message)=>({
|
|
|
154
157
|
business: aiSiteWords(job.inputs).about || job.brief,
|
|
155
158
|
sectionNames: [
|
|
156
159
|
'Blog'
|
|
157
|
-
]
|
|
160
|
+
],
|
|
161
|
+
jobId: aiOriginJobId(job)
|
|
158
162
|
}, input.signal ? {
|
|
159
163
|
signal: input.signal
|
|
160
164
|
} : {}));
|
|
@@ -329,7 +333,8 @@ export const runAiSitePostsUnit = createAiSitePostsRunner();
|
|
|
329
333
|
business: aiSiteWords(input.job.inputs).about || input.job.brief,
|
|
330
334
|
sectionNames: [
|
|
331
335
|
'Products'
|
|
332
|
-
]
|
|
336
|
+
],
|
|
337
|
+
jobId: aiOriginJobId(input.job)
|
|
333
338
|
}, input.signal ? {
|
|
334
339
|
signal: input.signal
|
|
335
340
|
} : {}));
|
|
@@ -340,11 +345,31 @@ export const runAiSitePostsUnit = createAiSitePostsRunner();
|
|
|
340
345
|
});
|
|
341
346
|
}
|
|
342
347
|
const starters = aiLayoutStarterPhotos(slots, seed);
|
|
348
|
+
const hostId = input.job.hostId;
|
|
343
349
|
return slots.map((_slot, index)=>{
|
|
344
|
-
var
|
|
350
|
+
var _aiSiteProductPhotoSrc;
|
|
345
351
|
var _found_index, _starters_index;
|
|
346
|
-
return (
|
|
352
|
+
return (_aiSiteProductPhotoSrc = aiSiteProductPhotoSrc((_found_index = found[index]) == null ? void 0 : _found_index.src, hostId)) != null ? _aiSiteProductPhotoSrc : aiSiteProductPhotoSrc((_starters_index = starters[index]) == null ? void 0 : _starters_index.src, hostId);
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* A photo as a product stores it: the form the console's picker writes when
|
|
357
|
+
* an owner picks one from the library (`console-media-picker-provider`), the
|
|
358
|
+
* asset's CDN path `/api/media/cdn/{scope}/{mediaId}`, or a starter's own
|
|
359
|
+
* site path. A page's picture slot holds the library's `media:` reference
|
|
360
|
+
* (`mediaNodeSrc`), which is what the stock source hands back, and the
|
|
361
|
+
* product's rules take only an https address or a path on the site: the
|
|
362
|
+
* candle store's guided start of 2026-10-09 (job FYNasg1h0S) wrote no
|
|
363
|
+
* product at all because every photo was a `media:` reference. The path
|
|
364
|
+
* names the asset, not its bytes, so a replace in the library still reaches
|
|
365
|
+
* the product. Anything else is no photo, never a value the product refuses.
|
|
366
|
+
*/ export function aiSiteProductPhotoSrc(src, hostId) {
|
|
367
|
+
if (!src) return null;
|
|
368
|
+
const path = resolveMediaSrc(src, {
|
|
369
|
+
hostId
|
|
347
370
|
});
|
|
371
|
+
if (!path || path.length > 2000 || /[\s"'<>]/.test(path)) return null;
|
|
372
|
+
return path.startsWith('/') || path.startsWith('https://') ? path : null;
|
|
348
373
|
}
|
|
349
374
|
/** The sentence the products unit's brief ends with, which the catalog's rules read as how many. */ export function aiSiteProductsBriefLine(input = AI_SITE_PRODUCTS) {
|
|
350
375
|
return `Propose between ${input.min} and ${input.max} products: the store's first ones.`;
|
|
@@ -352,9 +377,12 @@ export const runAiSitePostsUnit = createAiSitePostsRunner();
|
|
|
352
377
|
/**
|
|
353
378
|
* The products unit's runner: the `products` step's catalog for the store's
|
|
354
379
|
* brief, then each proposed product, up to the most a site starts with,
|
|
355
|
-
* written
|
|
356
|
-
* past the plan's allowance stops the writing there, and the row
|
|
357
|
-
* many were added; none at all is the allowance's review.
|
|
380
|
+
* written by the plugin that keeps products at its default price, listed. A
|
|
381
|
+
* product past the plan's allowance stops the writing there, and the row
|
|
382
|
+
* says how many were added; none at all is the allowance's review. A photo
|
|
383
|
+
* the product's rules refuse is dropped and the product written without it;
|
|
384
|
+
* a product they refuse outright is skipped, and none written for that
|
|
385
|
+
* reason is our failure, refunded, never the person's review (AGL-3676).
|
|
358
386
|
*/ export function createAiSiteProductsRunner(deps) {
|
|
359
387
|
var _deps_writerFor;
|
|
360
388
|
const writerFor = (_deps_writerFor = deps.writerFor) != null ? _deps_writerFor : pluginResourceDraftWriter;
|
|
@@ -395,9 +423,41 @@ export const runAiSitePostsUnit = createAiSitePostsRunner();
|
|
|
395
423
|
} : {})).catch(()=>proposed.map(()=>null));
|
|
396
424
|
const outputs = [];
|
|
397
425
|
let stopped = null;
|
|
426
|
+
/** The product's rules refusing what we made: ours, never the workspace's (AGL-3676). */ let rejected = null;
|
|
398
427
|
for (const [index, product] of proposed.entries()){
|
|
399
|
-
var _context_org, _catalog_output_hostSubdomain;
|
|
400
|
-
const
|
|
428
|
+
var _photos_index, _context_org, _catalog_output_hostSubdomain;
|
|
429
|
+
const content = {
|
|
430
|
+
name: product.name,
|
|
431
|
+
type: product.type,
|
|
432
|
+
// Listed at once, so no "[gift card terms]" gap reaches a shopper:
|
|
433
|
+
// a sentence that leaves a fact for the owner is left out.
|
|
434
|
+
description: aiSiteProductDescriptionWithoutGaps(product.description),
|
|
435
|
+
tags: product.tags,
|
|
436
|
+
options: product.options,
|
|
437
|
+
seoTitle: product.seoTitle,
|
|
438
|
+
seoDescription: product.seoDescription,
|
|
439
|
+
comingSoon: true
|
|
440
|
+
};
|
|
441
|
+
// A photo we picked that the product's rules refuse is dropped, never
|
|
442
|
+
// the product: its slot stays empty for the owner's own.
|
|
443
|
+
const photo = (_photos_index = photos[index]) != null ? _photos_index : null;
|
|
444
|
+
const withPhoto = photo ? _extends({}, content, {
|
|
445
|
+
mediaUrls: [
|
|
446
|
+
photo
|
|
447
|
+
]
|
|
448
|
+
}) : content;
|
|
449
|
+
const photoRefused = photo !== null && keeper.writer.check(withPhoto, {
|
|
450
|
+
hostId: job.hostId
|
|
451
|
+
}).ok === false && keeper.writer.check(content, {
|
|
452
|
+
hostId: job.hostId
|
|
453
|
+
}).ok;
|
|
454
|
+
if (photoRefused) {
|
|
455
|
+
console.warn('ai site products: the product refused its photo; written without it', {
|
|
456
|
+
orgId: job.orgId,
|
|
457
|
+
jobId: job.$id,
|
|
458
|
+
photo
|
|
459
|
+
});
|
|
460
|
+
}
|
|
401
461
|
const written = await keeper.writer.write({
|
|
402
462
|
orgId: job.orgId,
|
|
403
463
|
hostId: job.hostId,
|
|
@@ -409,24 +469,22 @@ export const runAiSitePostsUnit = createAiSitePostsRunner();
|
|
|
409
469
|
// No price stated: the writer gives it the store's default price
|
|
410
470
|
// for the owner to change (AGL-3676). Listed at once. Its photo
|
|
411
471
|
// slot holds a stock or starter photo for the owner to replace.
|
|
412
|
-
content:
|
|
413
|
-
name: product.name,
|
|
414
|
-
type: product.type,
|
|
415
|
-
// Listed at once, so no "[gift card terms]" gap reaches a shopper:
|
|
416
|
-
// a sentence that leaves a fact for the owner is left out.
|
|
417
|
-
description: aiSiteProductDescriptionWithoutGaps(product.description),
|
|
418
|
-
tags: product.tags,
|
|
419
|
-
options: product.options,
|
|
420
|
-
seoTitle: product.seoTitle,
|
|
421
|
-
seoDescription: product.seoDescription,
|
|
422
|
-
comingSoon: true
|
|
423
|
-
}, photo ? {
|
|
424
|
-
mediaUrls: [
|
|
425
|
-
photo
|
|
426
|
-
]
|
|
427
|
-
} : {})
|
|
472
|
+
content: photoRefused ? content : withPhoto
|
|
428
473
|
});
|
|
429
474
|
if (written.ok === false) {
|
|
475
|
+
// A 400 is the product's rules refusing content we made: that one
|
|
476
|
+
// product is skipped and the rest are still written. Anything else
|
|
477
|
+
// (the allowance, the role, the site) stops the writing there.
|
|
478
|
+
if (written.status === 400) {
|
|
479
|
+
console.error('ai site products: the product writer refused a product we made', {
|
|
480
|
+
orgId: job.orgId,
|
|
481
|
+
jobId: job.$id,
|
|
482
|
+
index,
|
|
483
|
+
error: written.error
|
|
484
|
+
});
|
|
485
|
+
rejected = written.error;
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
430
488
|
stopped = written.error;
|
|
431
489
|
break;
|
|
432
490
|
}
|
|
@@ -440,15 +498,25 @@ export const runAiSitePostsUnit = createAiSitePostsRunner();
|
|
|
440
498
|
});
|
|
441
499
|
}
|
|
442
500
|
if (!outputs.length) {
|
|
501
|
+
// Nothing written because the product's rules refused what we made:
|
|
502
|
+
// the failure is ours, so the item's credits are refunded
|
|
503
|
+
// (`aiUnitFailure` → `ours: true`). Only the workspace's allowance,
|
|
504
|
+
// role or site is the person's to review.
|
|
505
|
+
if (!stopped && rejected) return _extends({}, outcome, {
|
|
506
|
+
outputs: [],
|
|
507
|
+
failure: AI_SITE_PRODUCTS_NOT_WRITTEN_COPY
|
|
508
|
+
});
|
|
443
509
|
return _extends({}, outcome, {
|
|
444
510
|
outputs: [],
|
|
445
511
|
review: limitReview(stopped != null ? stopped : 'No product could be added.')
|
|
446
512
|
});
|
|
447
513
|
}
|
|
448
514
|
// The allowance that stopped the rest is said where the last one added is.
|
|
515
|
+
const last = outputs[outputs.length - 1];
|
|
449
516
|
if (stopped) {
|
|
450
|
-
const last = outputs[outputs.length - 1];
|
|
451
517
|
last.note = `${last.note} ${outputs.length} of ${proposed.length} added: ${stopped}.`;
|
|
518
|
+
} else if (outputs.length < proposed.length) {
|
|
519
|
+
last.note = `${last.note} ${outputs.length} of ${proposed.length} added.`;
|
|
452
520
|
}
|
|
453
521
|
return _extends({}, outcome, {
|
|
454
522
|
outputs
|
|
@@ -557,14 +625,23 @@ export const runAiSitePostsUnit = createAiSitePostsRunner();
|
|
|
557
625
|
var _posts__proposal, _posts_;
|
|
558
626
|
const listings = [];
|
|
559
627
|
const products = input.outputs.filter((output)=>output.resource === 'product' && !output.proposal);
|
|
560
|
-
if (products.length || input.sells) {
|
|
561
|
-
|
|
628
|
+
if (products.length || input.sells || input.store) {
|
|
629
|
+
const contact = aiSiteContactPath(input.screens);
|
|
630
|
+
listings.push(_extends({
|
|
562
631
|
id: aiLayoutListingId('products'),
|
|
563
632
|
kind: 'products',
|
|
564
633
|
name: 'the shop',
|
|
565
|
-
records: products.map((product)=>product.label)
|
|
566
|
-
|
|
567
|
-
|
|
634
|
+
records: products.map((product)=>product.label)
|
|
635
|
+
}, contact ? {
|
|
636
|
+
emptyAction: {
|
|
637
|
+
label: 'Get in touch',
|
|
638
|
+
href: contact
|
|
639
|
+
}
|
|
640
|
+
} : {}, products.length || input.sells ? {} : {
|
|
641
|
+
cart: false
|
|
642
|
+
}, {
|
|
643
|
+
placements: aiLayoutListingPlacements('products', input.screens)
|
|
644
|
+
}));
|
|
568
645
|
}
|
|
569
646
|
const posts = input.outputs.filter((output)=>output.resource === 'entry');
|
|
570
647
|
const slug = str((_posts_ = posts[0]) == null ? void 0 : (_posts__proposal = _posts_.proposal) == null ? void 0 : _posts__proposal['collectionSlug']);
|
|
@@ -579,8 +656,31 @@ export const runAiSitePostsUnit = createAiSitePostsRunner();
|
|
|
579
656
|
placements: aiLayoutListingPlacements('posts', input.screens)
|
|
580
657
|
});
|
|
581
658
|
}
|
|
659
|
+
if (input.music) {
|
|
660
|
+
const placements = aiLayoutListingPlacements('tracks', input.screens);
|
|
661
|
+
if (placements.length) {
|
|
662
|
+
listings.push({
|
|
663
|
+
id: aiLayoutListingId('tracks'),
|
|
664
|
+
kind: 'tracks',
|
|
665
|
+
name: 'the music',
|
|
666
|
+
records: [],
|
|
667
|
+
placements
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
}
|
|
582
671
|
return listings;
|
|
583
672
|
}
|
|
673
|
+
/** The page a visitor gets in touch on, by its path: one whose address or name says contact, else the one placing a form. */ function aiSiteContactPath(screens) {
|
|
674
|
+
const path = (slug)=>`/${slug.trim().replace(/^\/+|\/+$/g, '')}`;
|
|
675
|
+
const isPath = (slug)=>/^\/[a-z0-9-]+(?:\/[a-z0-9-]+)*$/.test(path(slug));
|
|
676
|
+
const named = screens.find((screen)=>isPath(screen.slug) && /\b(contact|get in touch|enquir|inquir)/i.test(`${screen.slug} ${screen.title}`));
|
|
677
|
+
if (named) return path(named.slug);
|
|
678
|
+
const form = screens.find((screen)=>isPath(screen.slug) && screen.sections.some((section)=>{
|
|
679
|
+
var _section_uses;
|
|
680
|
+
return ((_section_uses = section.uses) != null ? _section_uses : []).some((use)=>/form/i.test(use));
|
|
681
|
+
}));
|
|
682
|
+
return form ? path(form.slug) : null;
|
|
683
|
+
}
|
|
584
684
|
/**
|
|
585
685
|
* A proposed product's description with each sentence that leaves a gap for
|
|
586
686
|
* the owner ("Delivery details: [how and when the card is sent].") taken
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-site-content.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 { hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport { pluginResourceDraftWriter } from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport {\n publishContentEntries,\n writeContentCollection,\n writeContentEntryDraft,\n} from '@aglyn/tenant-data-admin/server/content-entry-drafts'\nimport { aiProductsProposalOf } from '../model/ai-products'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS, aiSiteWords } from '../model/ai-site-job'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { aiModelForStep } from '../providers/routing'\nimport {\n AI_BLOG_POST_MAX_TOKENS,\n AI_BLOG_POST_STEP,\n generateAiBlogPost,\n} from '../runtime/ai-blog-post-generation'\nimport {\n aiLayoutStarterPhotos,\n type AiLayoutPicturePhoto,\n type AiLayoutPictureSlot,\n} from '../layout-language/ai-layout-pictures'\nimport { aiLayoutStockPhotoSource } from './ai-layout-stock-photos'\nimport {\n aiLayoutListingId,\n aiLayoutListingPlacements,\n type AiLayoutListing,\n type AiLayoutListingScreen,\n} from '../layout-language/ai-layout-listings'\nimport { aiJobAdmissionFor, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport type { AiJobStepContext, AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\n\n/**\n * A GUIDED START'S FIRST POSTS AND FIRST PRODUCTS (AGL-3676).\n *\n * A site of the kind \"Blog & writing\" or \"Online store\" got the right look\n * and pages, and nothing real in them: the writing page's cards and the\n * shop's grid named posts and products nobody had written. On a paid plan,\n * the scaffold now builds one more part for those two kinds, before the\n * pages, each its own row with its own timer and credits:\n *\n * - WRITING YOUR FIRST POSTS: a content collection \"Blog\" — the platform's\n * own blog, served at `/{slug}` with an entry page per post — and\n * `AI_SITE_POSTS` posts in it, one generation a pass. Each is written as a\n * draft through the same rules the console's routes hold\n * (`content-entry-drafts.ts`), bylined with the business's name the person\n * gave, and given a cover: a stock photo of its own title where the\n * deployment has a library, else a starter (AGL-3676), which the blog's\n * cards show. They go live with the\n * site: the guided start's publish publishes them with its pages\n * (`aiPublishSitePosts`), as a person's Publish would.\n * - ADDING YOUR FIRST PRODUCTS: the `products` step's catalog, asked for\n * `AI_SITE_PRODUCTS` products, each written through the commerce plugin's\n * `product` draft writer. The catalog proposes no price, so each takes\n * the writer's default price (Zach, 2026-10-08: \"default a price\",\n * AGL-3676) for the owner to change; the job's row says so. Since the\n * 2026-10-08 Ember & Wick start, whose store showed no product at all,\n * each is LISTED at once (`comingSoon`: written `active`). Each gets a\n * photo in its slot, a stock photo of its own words where the deployment\n * has a library, else a starter, for the owner to replace with their\n * own.\n *\n * The pages built after them are told their titles or names, and the\n * sections that show them list the real records (`aiSiteListings`,\n * `ai-layout-listings.ts`): the shop's Product grid, the blog's posts.\n *\n * ── Not on the Free taste ────────────────────────────────────────────────\n *\n * A guided start's Free site, built on an empty site with its layout and\n * form, leaves 18 credits once its eight sections and its retried page's\n * room are held (`aiFreeSiteSectionsWithin`, AGL-3660), under the 23 one post\n * costs at its worst; and a Free plan includes neither\n * the `commerce` feature nor a product (`productsPerHost` is 0).\n * `ai-job-free-site.spec.ts` shows the arithmetic. Free sites keep the pages\n * their kind already describes; the owner adds posts and products after.\n */\n\n/** How many first posts a paid blog gets. */\nexport const AI_SITE_POSTS = 3\n\n/** How many first products a paid store gets: asked for, and the most written. */\nexport const AI_SITE_PRODUCTS = { min: 3, max: 6 } as const\n\n/** What each part's row reads. */\nexport const AI_SITE_POSTS_LABEL = 'Writing your first posts'\nexport const AI_SITE_PRODUCTS_LABEL = 'Adding your first products'\n\n/** The blog the posts go in, and the addresses it may answer at (`model/ai-site-job.ts`). */\nexport { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS } from '../model/ai-site-job'\n\n/** The input a site unit's own job carries what the part needs in. */\nexport const AI_SITE_CONTENT_INPUT = 'siteContent'\n\n/** Which part a site of these answers gets; `null` for the Free taste and every other kind. */\nexport function aiSiteContentPart(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n freeTaste: boolean,\n): 'posts' | 'products' | null {\n if (freeTaste) return null\n const kind = aiSiteKindOfInputs(inputs)?.id\n if (kind === 'blog') return 'posts'\n if (kind === 'store') return 'products'\n return null\n}\n\n/**\n * ASSUMED: what one post pass reads and writes beside its generation: the\n * host, the collection's slug claim and the entry's transaction.\n */\nexport const AI_SITE_POST_WRITES_MS = 1_500\n\n/** One post's pass: its generation and re-ask at the `copy.blog` ceiling, and its writes. */\nexport const AI_SITE_POST_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS[AI_BLOG_POST_STEP],\n maxTokens: AI_BLOG_POST_MAX_TOKENS,\n lookups: 0,\n ownReadsMs: AI_SITE_POST_WRITES_MS,\n})\n\n/** What a posts unit's job is told: the posts already written and the addresses the blog must not take. */\nexport interface AiSitePostsInput {\n written: Array<{ id: string; title: string }>\n total: number\n /** Addresses the site's own pages answer at, which the blog must not shadow. */\n avoidSlugs: string[]\n /** Who the posts are by: the business's name as given, else empty. */\n byline: string\n}\n\n/** What a products unit's job is told. */\nexport interface AiSiteProductsInput {\n min: number\n max: number\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\nfunction postsInputOf(job: Pick<AiJob, 'inputs'>): AiSitePostsInput {\n const raw = (job.inputs?.[AI_SITE_CONTENT_INPUT] ?? {}) as Partial<AiSitePostsInput>\n return {\n written: Array.isArray(raw.written) ? raw.written.filter((one) => one && typeof one.id === 'string') : [],\n total: typeof raw.total === 'number' && raw.total > 0 ? Math.floor(raw.total) : AI_SITE_POSTS,\n avoidSlugs: Array.isArray(raw.avoidSlugs) ? raw.avoidSlugs.map(str).filter(Boolean) : [],\n byline: str(raw.byline),\n }\n}\n\n/** The id of the `index`th post, of the blog its unit writes under `unitJobId`. */\nexport function aiSitePostId(unitJobId: string, index: number): string {\n return `${unitJobId}-${index}`\n}\n\n/** The id of the `index`th product a products unit writes. */\nexport function aiSiteProductId(unitJobId: string, index: number): string {\n return `${unitJobId}-${index}`\n}\n\n/** A site's subdomain and name, as its outputs and its posts' byline read them. */\nasync function readSite(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<{ subdomain: string | null; name: string } | null> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return null\n const seo = (host.get('seo') ?? {}) as Record<string, unknown>\n const subdomain = str(host.get('subdomain')) || null\n return { subdomain, name: str(host.get('displayName')) || str(seo['title']) }\n}\n\nconst limitReview = (message: string) => ({ reason: 'limit' as const, message, findings: [] })\n\nexport interface AiSitePostsRunnerDeps {\n generate?: typeof generateAiBlogPost\n writeCollection?: typeof writeContentCollection\n writeEntry?: typeof writeContentEntryDraft\n /** Where each post's cover comes from; the stock library, else the starters, otherwise. */\n cover?: typeof aiSitePostCover\n}\n\n/** A post's cover's shape: the blog's cards' (`COLLECTION_LIST_COVER_RATIO`, the posts listing's). */\nconst AI_SITE_POST_COVER_ASPECT = 3 / 2\n\n/**\n * A post's cover (AGL-3676): a stock photo of the post's own title, copied\n * into the site's library, where the deployment has a stock library; else the\n * starter photo a post was always given, turned by the job so blogs differ.\n * The blog's cards and the post's page show it, for the owner to replace.\n * Never throws: a post whose search fails takes its starter.\n */\nexport async function aiSitePostCover(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief'>\n title: string\n index: number\n total: number\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<string | null> {\n const { job, index } = input\n if (job.hostId && input.title.trim()) {\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId: job.hostId,\n uid: job.createdBy,\n seed: `${job.$id}:posts:${index}`,\n business: aiSiteWords(job.inputs).about || job.brief,\n sectionNames: ['Blog'],\n ...(input.signal ? { signal: input.signal } : {}),\n })\n const [found] = source\n ? await source([\n {\n imageId: `cover${index}`,\n frameId: null,\n iconId: null,\n alt: input.title,\n aspect: AI_SITE_POST_COVER_ASPECT,\n sectionIndex: 0,\n role: 'gallery' as const,\n },\n ])\n : []\n if (found?.src) return found.src\n } catch (error) {\n console.warn('ai site posts: the stock photo failed; the starter covers it', { error: String(error) })\n }\n }\n const starters = aiLayoutStarterPhotos(\n Array.from({ length: Math.max(input.total, index + 1) }, (_, slot) => ({\n imageId: `cover${slot}`,\n frameId: null,\n iconId: null,\n alt: '',\n aspect: 16 / 9,\n sectionIndex: slot + 1,\n role: 'gallery' as const,\n })),\n job.$id,\n )\n return starters[index]?.src ?? null\n}\n\n/**\n * The posts unit's runner, on the job the scaffold derived for it: one post a\n * pass, continuing while posts remain. Its first pass makes the blog; every\n * pass finds it again under the unit's own id, and a post under its own id,\n * so a pass repeated after its write reports the post it already wrote.\n */\nexport function createAiSitePostsRunner(deps: AiSitePostsRunnerDeps = {}): AiJobStepRunner {\n const generate = deps.generate ?? generateAiBlogPost\n const writeCollection = deps.writeCollection ?? writeContentCollection\n const writeEntry = deps.writeEntry ?? writeContentEntryDraft\n const coverFor = deps.cover ?? aiSitePostCover\n return async (context): Promise<AiJobStepOutcome> => {\n const { job, firestore, signal } = context\n const model = context.modelFor?.(AI_BLOG_POST_STEP) ?? aiModelForStep(AI_BLOG_POST_STEP)\n if (!job.hostId) return { ...aiUnspentOutcome(model), failure: 'Open the site before writing its posts.' }\n const input = postsInputOf(job)\n const index = input.written.length\n if (index >= input.total) return aiUnspentOutcome(model)\n const site = await readSite(firestore, job.hostId)\n if (!site) return { ...aiUnspentOutcome(model), failure: 'This site no longer exists.' }\n const avoid = new Set(input.avoidSlugs.map((slug) => slug.toLowerCase()))\n const blog = await writeCollection(firestore, {\n hostId: job.hostId,\n uid: job.createdBy,\n id: job.$id,\n displayName: AI_SITE_BLOG_NAME,\n slugs: AI_SITE_BLOG_SLUGS.filter((slug) => !avoid.has(slug)),\n now: context.now,\n })\n if (blog.ok === false) return aiUnspentOutcome(model, { review: limitReview(blog.error) })\n\n const generation = await generate({\n brief: job.brief,\n merchantWords: job.brief,\n earlierTitles: input.written.map((post) => post.title),\n index: index + 1,\n total: input.total,\n model,\n maxTokens: AI_SITE_POST_BUDGET.maxTokens(model),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(generation)\n if (generation.status === 'refused') return { ...spent, refused: true }\n if (generation.status === 'needs_input') return { ...spent, failure: generation.message }\n const post = generation.value\n // A stock photo of its title as its cover, else a starter (AGL-3676).\n const cover = await coverFor({\n job,\n title: post.title,\n index,\n total: input.total,\n ...(signal ? { signal } : {}),\n }).catch(() => null)\n const byline = input.byline || site.name\n const written = await writeEntry(firestore, {\n hostId: job.hostId,\n collectionId: blog.id,\n uid: job.createdBy,\n id: aiSitePostId(job.$id, index),\n content: {\n title: post.title,\n excerpt: post.excerpt,\n body: post.body,\n seoDescription: post.seoDescription,\n ...(cover ? { coverImage: cover, coverImageAlt: post.title } : {}),\n ...(byline ? { authorName: byline } : {}),\n },\n now: context.now,\n })\n if (written.ok === false) return { ...spent, review: limitReview(written.error) }\n const output: AiJobOutput = {\n resource: 'entry',\n id: written.id,\n hostId: job.hostId,\n hostSubdomain: site.subdomain,\n label: written.title,\n note: `A post in ${blog.displayName}, at /${blog.slug}/${written.slug}. It goes live with the site.`,\n proposal: { collectionId: blog.id, collectionSlug: blog.slug, slug: written.slug },\n }\n return { ...spent, outputs: [output], ...(index + 1 < input.total ? { continue: true } : {}) }\n }\n}\n\nexport const runAiSitePostsUnit = createAiSitePostsRunner()\n\nexport interface AiSiteProductsRunnerDeps {\n /** The catalog's runner: the `products` step's. */\n catalog: AiJobStepRunner\n writerFor?: typeof pluginResourceDraftWriter\n /** Where each product's photo comes from; the stock library, else the starters, otherwise. */\n photos?: typeof aiSiteProductPhotos\n}\n\n/**\n * A photo for each product (AGL-3676), in order: a stock photo of the\n * product's own words, copied into the site's library, where the deployment\n * has a stock library; else a starter photo, as a page's empty picture takes\n * one. It fills the photo slot every product card and product page has, for\n * the owner to replace with their own; the product's note says so. Never\n * throws: a product with no photo is still written.\n */\nexport async function aiSiteProductPhotos(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief'>\n names: readonly string[]\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<Array<string | null>> {\n if (!input.names.length || !input.job.hostId) return input.names.map(() => null)\n const slots: AiLayoutPictureSlot[] = input.names.map((name, index) => ({\n imageId: `product${index}`,\n frameId: null,\n iconId: null,\n alt: name,\n // The product card's own shape (`cardStyle: 'photo'`).\n aspect: 4 / 5,\n sectionIndex: 0,\n role: 'gallery' as const,\n }))\n const seed = `${input.job.$id}:products`\n let found: ReadonlyArray<AiLayoutPicturePhoto | null> = []\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId: input.job.hostId,\n uid: input.job.createdBy,\n seed,\n business: aiSiteWords(input.job.inputs).about || input.job.brief,\n sectionNames: ['Products'],\n ...(input.signal ? { signal: input.signal } : {}),\n })\n if (source) found = await source(slots)\n } catch (error) {\n console.warn('ai site products: the stock photos failed; starter photos fill them', { error: String(error) })\n }\n const starters = aiLayoutStarterPhotos(slots, seed)\n return slots.map((_slot, index) => found[index]?.src ?? starters[index]?.src ?? null)\n}\n\n/** The sentence the products unit's brief ends with, which the catalog's rules read as how many. */\nexport function aiSiteProductsBriefLine(input: AiSiteProductsInput = AI_SITE_PRODUCTS): string {\n return `Propose between ${input.min} and ${input.max} products: the store's first ones.`\n}\n\n/**\n * The products unit's runner: the `products` step's catalog for the store's\n * brief, then each proposed product, up to the most a site starts with,\n * written as an unpriced draft by the plugin that keeps products. A product\n * past the plan's allowance stops the writing there, and the row says how\n * many were added; none at all is the allowance's review.\n */\nexport function createAiSiteProductsRunner(deps: AiSiteProductsRunnerDeps): AiJobStepRunner {\n const writerFor = deps.writerFor ?? pluginResourceDraftWriter\n return async (context): Promise<AiJobStepOutcome> => {\n const { job } = context\n const keeper = writerFor('product')\n const model = context.modelFor?.('job.products') ?? aiModelForStep('job.products')\n if (!keeper || !job.hostId) return { ...aiUnspentOutcome(model), failure: 'Products are not available on this site.' }\n const outcome = await deps.catalog({\n ...context,\n job: { ...job, kind: 'products', inputs: { ...job.inputs, target: 'catalog' } },\n })\n if (outcome.refused || outcome.failure || outcome.review) return outcome\n const catalog = outcome.outputs.map((output) => ({ output, proposal: aiProductsProposalOf(output) })).find(\n (entry) => entry.proposal?.kind === 'catalog',\n )\n if (!catalog || catalog.proposal?.kind !== 'catalog') return { ...outcome, outputs: [] }\n const proposed = catalog.proposal.products.slice(0, AI_SITE_PRODUCTS.max)\n const photos = await (deps.photos ?? aiSiteProductPhotos)({\n job,\n names: proposed.map((product) => product.name),\n ...(context.signal ? { signal: context.signal } : {}),\n }).catch(() => proposed.map(() => null))\n const outputs: AiJobOutput[] = []\n let stopped: string | null = null\n for (const [index, product] of proposed.entries()) {\n const photo = photos[index]\n const written = await keeper.writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n id: aiSiteProductId(job.$id, index),\n name: product.name,\n // No price stated: the writer gives it the store's default price\n // for the owner to change (AGL-3676). Listed at once. Its photo\n // slot holds a stock or starter photo for the owner to replace.\n content: {\n name: product.name,\n type: product.type,\n // Listed at once, so no \"[gift card terms]\" gap reaches a shopper:\n // a sentence that leaves a fact for the owner is left out.\n description: aiSiteProductDescriptionWithoutGaps(product.description),\n tags: product.tags,\n options: product.options,\n seoTitle: product.seoTitle,\n seoDescription: product.seoDescription,\n comingSoon: true,\n ...(photo ? { mediaUrls: [photo] } : {}),\n },\n })\n if (written.ok === false) {\n stopped = written.error\n break\n }\n outputs.push({\n resource: 'product',\n id: written.id,\n hostId: job.hostId,\n hostSubdomain: catalog.output.hostSubdomain ?? null,\n label: written.name,\n note: AI_SITE_PRODUCT_NOTE,\n })\n }\n if (!outputs.length) {\n return { ...outcome, outputs: [], review: limitReview(stopped ?? 'No product could be added.') }\n }\n // The allowance that stopped the rest is said where the last one added is.\n if (stopped) {\n const last = outputs[outputs.length - 1]\n last.note = `${last.note} ${outputs.length} of ${proposed.length} added: ${stopped}.`\n }\n return { ...outcome, outputs }\n }\n}\n\n/**\n * Whether a part may be built for this member on this site, asked before its\n * first pass so a refusal spends nothing; `null` admits. Products ask what a\n * `products` job asks (the plan's commerce feature, Commerce on and released\n * for the site) and the writer's own refusal (role, allowance); posts ask\n * that the member may write the site's content.\n */\nexport async function aiSiteContentRefusal(\n part: 'posts' | 'products',\n context: Pick<AiJobStepContext, 'firestore' | 'org' | 'now'> & { job: Pick<AiJob, 'orgId' | 'hostId' | 'createdBy' | 'inputs'> },\n deps: { writerFor?: typeof pluginResourceDraftWriter; admissionFor?: typeof aiJobAdmissionFor } = {},\n): Promise<string | null> {\n const { job, firestore } = context\n if (!job.hostId) return 'Open the site first.'\n if (part === 'posts') {\n const host = await firestore.collection('hosts').doc(job.hostId).get()\n return hostRoleCanWrite((host.get('memberRoles') ?? {})[job.createdBy]) ? null : 'Editing requires the editor role'\n }\n const admission = (deps.admissionFor ?? aiJobAdmissionFor)('products')\n const refused: AiJobAdmissionRefusal | null = admission\n ? await admission({\n firestore,\n orgId: job.orgId,\n hostId: job.hostId,\n inputs: { target: 'catalog' },\n org: context.org ?? null,\n uid: job.createdBy,\n })\n : { status: 403, error: 'Products are not available on this site.' }\n if (refused) return refused.error\n const keeper = (deps.writerFor ?? pluginResourceDraftWriter)('product')\n if (!keeper) return 'Products are not available on this site.'\n const room = await keeper.writer.refusal({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n })\n return room?.error ?? null\n}\n\n/** The guided start's posts, published with its pages (AGL-3676). */\nexport interface AiSitePostsPublish {\n published: number\n kept: number\n /** The blog's own addresses, for the publish's cache drop. */\n paths: string[]\n}\n\n/**\n * Publishes the posts a guided start wrote, as the entry editor's Publish\n * does, once its pages are live. Never throws: a post that stays a draft is\n * the owner's to publish from Content.\n */\nexport async function aiPublishSitePosts(\n firestore: FirebaseFirestore.Firestore,\n input: { job: Pick<AiJob, '$id' | 'orgId' | 'hostId' | 'createdBy'>; outputs: readonly AiJobOutput[]; now: Date },\n publish: typeof publishContentEntries = publishContentEntries,\n): Promise<AiSitePostsPublish | null> {\n const posts = input.outputs.filter((output) => output.resource === 'entry')\n const collectionId = str(posts[0]?.proposal?.['collectionId'])\n const collectionSlug = str(posts[0]?.proposal?.['collectionSlug'])\n if (!input.job.hostId || !posts.length || !collectionId) return null\n try {\n const result = await publish(firestore, {\n hostId: input.job.hostId,\n collectionId,\n uid: input.job.createdBy,\n ids: posts.map((post) => post.id),\n now: input.now,\n })\n if ('ok' in result) {\n console.warn('ai site posts not published', { jobId: input.job.$id, error: result.error })\n return { published: 0, kept: posts.length, paths: [] }\n }\n const slugs = posts\n .filter((post) => result.published.includes(post.id))\n .map((post) => str(post.proposal?.['slug']))\n .filter(Boolean)\n return {\n published: result.published.length,\n kept: result.kept.length,\n paths: collectionSlug ? [`/${collectionSlug}`, ...slugs.map((slug) => `/${collectionSlug}/${slug}`)] : [],\n }\n } catch (error) {\n console.error('ai site posts publish threw', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\n/**\n * The site's listings a layout or a page unit is handed (AGL-3676,\n * `ai-layout-listings.ts`): the store's catalog once its products are written,\n * the blog once its posts are, each with the sections of the plan's pages\n * that list it. A layout is built before either, so it is told the store will\n * sell (`sells`, its ledger still owing the products part), which puts the\n * cart in its header.\n */\nexport function aiSiteListings(input: {\n outputs: readonly AiJobOutput[]\n screens: readonly AiLayoutListingScreen[]\n /** The ledger owes a store's first products: a layout built before them carries the cart. */\n sells?: boolean\n}): AiLayoutListing[] {\n const listings: AiLayoutListing[] = []\n const products = input.outputs.filter((output) => output.resource === 'product' && !output.proposal)\n if (products.length || input.sells) {\n listings.push({\n id: aiLayoutListingId('products'),\n kind: 'products',\n name: 'the shop',\n records: products.map((product) => product.label),\n placements: products.length ? aiLayoutListingPlacements('products', input.screens) : [],\n })\n }\n const posts = input.outputs.filter((output) => output.resource === 'entry')\n const slug = str(posts[0]?.proposal?.['collectionSlug'])\n if (posts.length && slug) {\n listings.push({\n id: aiLayoutListingId('posts'),\n kind: 'posts',\n name: 'the blog',\n records: posts.map((post) => post.label),\n href: `/${slug}`,\n collectionSlug: slug,\n placements: aiLayoutListingPlacements('posts', input.screens),\n })\n }\n return listings\n}\n\n/**\n * A proposed product's description with each sentence that leaves a gap for\n * the owner (\"Delivery details: [how and when the card is sent].\") taken\n * out (AGL-3676): a start's products are listed as soon as they are written,\n * and a live run's gift card showed its gaps on the product page. A line\n * break is kept; nothing else is changed.\n */\nexport function aiSiteProductDescriptionWithoutGaps(description: string): string {\n return description\n .split('\\n')\n .map((line) =>\n line\n .split(/(?<=[.!?])\\s+/)\n .filter((sentence) => !/\\[[^\\]]+\\]/.test(sentence))\n .join(' '),\n )\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\n/** What each product a start wrote says on the job's page (AGL-3676). */\nexport const AI_SITE_PRODUCT_NOTE =\n 'On your store at a starting price. Set its real price — and your own photo — in Products.'\n\n/** The note a store's products row carries once they are written (AGL-3676): the step left before it sells. */\nexport const AI_SITE_PRODUCTS_PRICE_NOTE =\n 'Your products are on your store at a starting price. Set their real prices in Products.'\n\n/** What a page of a blog or a store is told about the posts or products built before it. */\nexport function aiSiteContentBriefLines(outputs: readonly AiJobOutput[]): string[] {\n const posts = outputs.filter((output) => output.resource === 'entry')\n const products = outputs.filter((output) => output.resource === 'product' && !output.proposal)\n const lines: string[] = []\n if (posts.length) {\n const slug = str(posts[0].proposal?.['collectionSlug'])\n lines.push(\n `This site's blog${slug ? ` at /${slug}` : ''} has these posts: ${posts.map((post) => `“${post.label}”`).join(', ')}.`,\n 'Where a page features writing, feature these posts by their titles; never name a post that is not in this list.',\n )\n }\n if (products.length) {\n lines.push(\n `This store's products are: ${products.map((product) => `“${product.label}”`).join(', ')}.`,\n 'Where a page features products, feature these by their names; never name another product, and never state a price.',\n )\n }\n return lines\n}\n"],"names":["hostRoleCanWrite","pluginResourceDraftWriter","publishContentEntries","writeContentCollection","writeContentEntryDraft","aiProductsProposalOf","aiSiteKindOfInputs","AI_SITE_BLOG_NAME","AI_SITE_BLOG_SLUGS","aiSiteWords","AI_STEP_TIERS","aiModelForStep","AI_BLOG_POST_MAX_TOKENS","AI_BLOG_POST_STEP","generateAiBlogPost","aiLayoutStarterPhotos","aiLayoutStockPhotoSource","aiLayoutListingId","aiLayoutListingPlacements","aiJobAdmissionFor","aiJobStepBudget","aiGenerationSpent","aiUnspentOutcome","AI_SITE_POSTS","AI_SITE_PRODUCTS","min","max","AI_SITE_POSTS_LABEL","AI_SITE_PRODUCTS_LABEL","AI_SITE_CONTENT_INPUT","aiSiteContentPart","inputs","freeTaste","kind","id","AI_SITE_POST_WRITES_MS","AI_SITE_POST_BUDGET","tier","maxTokens","lookups","ownReadsMs","str","value","trim","postsInputOf","job","raw","written","Array","isArray","filter","one","total","Math","floor","avoidSlugs","map","Boolean","byline","aiSitePostId","unitJobId","index","aiSiteProductId","readSite","firestore","hostId","host","collection","doc","get","exists","seo","subdomain","name","limitReview","message","reason","findings","AI_SITE_POST_COVER_ASPECT","aiSitePostCover","input","starters","title","source","stockPhotos","uid","createdBy","seed","$id","business","about","brief","sectionNames","signal","found","imageId","frameId","iconId","alt","aspect","sectionIndex","role","src","error","console","warn","String","from","length","_","slot","createAiSitePostsRunner","deps","generate","writeCollection","writeEntry","coverFor","cover","context","model","modelFor","failure","site","avoid","Set","slug","toLowerCase","blog","displayName","slugs","has","now","ok","review","generation","merchantWords","earlierTitles","post","spent","status","refused","catch","collectionId","content","excerpt","body","seoDescription","coverImage","coverImageAlt","authorName","output","resource","hostSubdomain","label","note","proposal","collectionSlug","outputs","continue","runAiSitePostsUnit","aiSiteProductPhotos","names","slots","_slot","aiSiteProductsBriefLine","createAiSiteProductsRunner","writerFor","catalog","keeper","outcome","target","find","entry","proposed","products","slice","photos","product","stopped","entries","photo","writer","write","orgId","org","type","description","aiSiteProductDescriptionWithoutGaps","tags","options","seoTitle","comingSoon","mediaUrls","push","AI_SITE_PRODUCT_NOTE","last","aiSiteContentRefusal","part","admission","admissionFor","room","refusal","aiPublishSitePosts","publish","posts","result","ids","jobId","published","kept","paths","includes","aiSiteListings","listings","sells","records","placements","screens","href","split","line","sentence","test","join","replace","AI_SITE_PRODUCTS_PRICE_NOTE","aiSiteContentBriefLines","lines"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,yBAAyB,QAAQ,qDAAoD;AAC9F,SACEC,qBAAqB,EACrBC,sBAAsB,EACtBC,sBAAsB,QACjB,uDAAsD;AAC7D,SAASC,oBAAoB,QAAQ,0BAAsB;AAE3D,SAASC,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,iBAAiB,EAAEC,kBAAkB,EAAEC,WAAW,QAAQ,0BAAsB;AACzF,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,cAAc,QAAQ,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/src/lib/jobs/ai-job-site-content.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 { resolveMediaSrc } from '@aglyn/aglyn/app-utils/media-ref'\nimport { hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport { pluginResourceDraftWriter } from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport {\n publishContentEntries,\n writeContentCollection,\n writeContentEntryDraft,\n} from '@aglyn/tenant-data-admin/server/content-entry-drafts'\nimport { aiProductsProposalOf } from '../model/ai-products'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS, aiSiteWords } from '../model/ai-site-job'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { aiModelForStep } from '../providers/routing'\nimport {\n AI_BLOG_POST_MAX_TOKENS,\n AI_BLOG_POST_STEP,\n generateAiBlogPost,\n} from '../runtime/ai-blog-post-generation'\nimport {\n aiLayoutStarterPhotos,\n type AiLayoutPicturePhoto,\n type AiLayoutPictureSlot,\n} from '../layout-language/ai-layout-pictures'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { aiLayoutStockPhotoSource } from './ai-layout-stock-photos'\nimport {\n aiLayoutListingId,\n aiLayoutListingPlacements,\n type AiLayoutListing,\n type AiLayoutListingScreen,\n} from '../layout-language/ai-layout-listings'\nimport { aiJobAdmissionFor, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport type { AiJobStepContext, AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\n\n/**\n * A GUIDED START'S FIRST POSTS AND FIRST PRODUCTS (AGL-3676).\n *\n * A site of the kind \"Blog & writing\" or \"Online store\" got the right look\n * and pages, and nothing real in them: the writing page's cards and the\n * shop's grid named posts and products nobody had written. On a paid plan,\n * the scaffold now builds one more part for those two kinds, before the\n * pages, each its own row with its own timer and credits:\n *\n * - WRITING YOUR FIRST POSTS: a content collection \"Blog\" — the platform's\n * own blog, served at `/{slug}` with an entry page per post — and\n * `AI_SITE_POSTS` posts in it, one generation a pass. Each is written as a\n * draft through the same rules the console's routes hold\n * (`content-entry-drafts.ts`), bylined with the business's name the person\n * gave, and given a cover: a stock photo of its own title where the\n * deployment has a library, else a starter (AGL-3676), which the blog's\n * cards show. They go live with the\n * site: the guided start's publish publishes them with its pages\n * (`aiPublishSitePosts`), as a person's Publish would.\n * - ADDING YOUR FIRST PRODUCTS: the `products` step's catalog, asked for\n * `AI_SITE_PRODUCTS` products, each written through the commerce plugin's\n * `product` draft writer. The catalog proposes no price, so each takes\n * the writer's default price (Zach, 2026-10-08: \"default a price\",\n * AGL-3676) for the owner to change; the job's row says so. Since the\n * 2026-10-08 Ember & Wick start, whose store showed no product at all,\n * each is LISTED at once (`comingSoon`: written `active`). Each gets a\n * photo in its slot, a stock photo of its own words where the deployment\n * has a library, else a starter, for the owner to replace with their\n * own.\n *\n * The pages built after them are told their titles or names, and the\n * sections that show them list the real records (`aiSiteListings`,\n * `ai-layout-listings.ts`): the shop's Product grid, the blog's posts.\n *\n * ── Not on the Free taste ────────────────────────────────────────────────\n *\n * A guided start's Free site, built on an empty site with its layout and\n * form, leaves 18 credits once its eight sections and its retried page's\n * room are held (`aiFreeSiteSectionsWithin`, AGL-3660), under the 23 one post\n * costs at its worst; and a Free plan includes neither\n * the `commerce` feature nor a product (`productsPerHost` is 0).\n * `ai-job-free-site.spec.ts` shows the arithmetic. Free sites keep the pages\n * their kind already describes; the owner adds posts and products after.\n */\n\n/** How many first posts a paid blog gets. */\nexport const AI_SITE_POSTS = 3\n\n/** How many first products a paid store gets: asked for, and the most written. */\nexport const AI_SITE_PRODUCTS = { min: 3, max: 6 } as const\n\n/** What a products row says when none of what we made could be written: our failure, refunded. */\nexport const AI_SITE_PRODUCTS_NOT_WRITTEN_COPY = 'Your first products could not be added this time.'\n\n/** What each part's row reads. */\nexport const AI_SITE_POSTS_LABEL = 'Writing your first posts'\nexport const AI_SITE_PRODUCTS_LABEL = 'Adding your first products'\n\n/** The blog the posts go in, and the addresses it may answer at (`model/ai-site-job.ts`). */\nexport { AI_SITE_BLOG_NAME, AI_SITE_BLOG_SLUGS } from '../model/ai-site-job'\n\n/** The input a site unit's own job carries what the part needs in. */\nexport const AI_SITE_CONTENT_INPUT = 'siteContent'\n\n/** Which part a site of these answers gets; `null` for the Free taste and every other kind. */\nexport function aiSiteContentPart(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n freeTaste: boolean,\n): 'posts' | 'products' | null {\n if (freeTaste) return null\n const kind = aiSiteKindOfInputs(inputs)?.id\n if (kind === 'blog') return 'posts'\n if (kind === 'store') return 'products'\n return null\n}\n\n/**\n * ASSUMED: what one post pass reads and writes beside its generation: the\n * host, the collection's slug claim and the entry's transaction.\n */\nexport const AI_SITE_POST_WRITES_MS = 1_500\n\n/** One post's pass: its generation and re-ask at the `copy.blog` ceiling, and its writes. */\nexport const AI_SITE_POST_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS[AI_BLOG_POST_STEP],\n maxTokens: AI_BLOG_POST_MAX_TOKENS,\n lookups: 0,\n ownReadsMs: AI_SITE_POST_WRITES_MS,\n})\n\n/** What a posts unit's job is told: the posts already written and the addresses the blog must not take. */\nexport interface AiSitePostsInput {\n written: Array<{ id: string; title: string }>\n total: number\n /** Addresses the site's own pages answer at, which the blog must not shadow. */\n avoidSlugs: string[]\n /** Who the posts are by: the business's name as given, else empty. */\n byline: string\n}\n\n/** What a products unit's job is told. */\nexport interface AiSiteProductsInput {\n min: number\n max: number\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\nfunction postsInputOf(job: Pick<AiJob, 'inputs'>): AiSitePostsInput {\n const raw = (job.inputs?.[AI_SITE_CONTENT_INPUT] ?? {}) as Partial<AiSitePostsInput>\n return {\n written: Array.isArray(raw.written) ? raw.written.filter((one) => one && typeof one.id === 'string') : [],\n total: typeof raw.total === 'number' && raw.total > 0 ? Math.floor(raw.total) : AI_SITE_POSTS,\n avoidSlugs: Array.isArray(raw.avoidSlugs) ? raw.avoidSlugs.map(str).filter(Boolean) : [],\n byline: str(raw.byline),\n }\n}\n\n/** The id of the `index`th post, of the blog its unit writes under `unitJobId`. */\nexport function aiSitePostId(unitJobId: string, index: number): string {\n return `${unitJobId}-${index}`\n}\n\n/** The id of the `index`th product a products unit writes. */\nexport function aiSiteProductId(unitJobId: string, index: number): string {\n return `${unitJobId}-${index}`\n}\n\n/** A site's subdomain and name, as its outputs and its posts' byline read them. */\nasync function readSite(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<{ subdomain: string | null; name: string } | null> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n if (!host.exists) return null\n const seo = (host.get('seo') ?? {}) as Record<string, unknown>\n const subdomain = str(host.get('subdomain')) || null\n return { subdomain, name: str(host.get('displayName')) || str(seo['title']) }\n}\n\nconst limitReview = (message: string) => ({ reason: 'limit' as const, message, findings: [] })\n\nexport interface AiSitePostsRunnerDeps {\n generate?: typeof generateAiBlogPost\n writeCollection?: typeof writeContentCollection\n writeEntry?: typeof writeContentEntryDraft\n /** Where each post's cover comes from; the stock library, else the starters, otherwise. */\n cover?: typeof aiSitePostCover\n}\n\n/** A post's cover's shape: the blog's cards' (`COLLECTION_LIST_COVER_RATIO`, the posts listing's). */\nconst AI_SITE_POST_COVER_ASPECT = 3 / 2\n\n/**\n * A post's cover (AGL-3676): a stock photo of the post's own title, copied\n * into the site's library, where the deployment has a stock library; else the\n * starter photo a post was always given, turned by the job so blogs differ.\n * The blog's cards and the post's page show it, for the owner to replace.\n * Never throws: a post whose search fails takes its starter.\n */\nexport async function aiSitePostCover(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief'>\n title: string\n index: number\n total: number\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<string | null> {\n const { job, index } = input\n if (job.hostId && input.title.trim()) {\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId: job.hostId,\n uid: job.createdBy,\n seed: `${job.$id}:posts:${index}`,\n business: aiSiteWords(job.inputs).about || job.brief,\n sectionNames: ['Blog'],\n jobId: aiOriginJobId(job),\n ...(input.signal ? { signal: input.signal } : {}),\n })\n const [found] = source\n ? await source([\n {\n imageId: `cover${index}`,\n frameId: null,\n iconId: null,\n alt: input.title,\n aspect: AI_SITE_POST_COVER_ASPECT,\n sectionIndex: 0,\n role: 'gallery' as const,\n },\n ])\n : []\n if (found?.src) return found.src\n } catch (error) {\n console.warn('ai site posts: the stock photo failed; the starter covers it', { error: String(error) })\n }\n }\n const starters = aiLayoutStarterPhotos(\n Array.from({ length: Math.max(input.total, index + 1) }, (_, slot) => ({\n imageId: `cover${slot}`,\n frameId: null,\n iconId: null,\n alt: '',\n aspect: 16 / 9,\n sectionIndex: slot + 1,\n role: 'gallery' as const,\n })),\n job.$id,\n )\n return starters[index]?.src ?? null\n}\n\n/**\n * The posts unit's runner, on the job the scaffold derived for it: one post a\n * pass, continuing while posts remain. Its first pass makes the blog; every\n * pass finds it again under the unit's own id, and a post under its own id,\n * so a pass repeated after its write reports the post it already wrote.\n */\nexport function createAiSitePostsRunner(deps: AiSitePostsRunnerDeps = {}): AiJobStepRunner {\n const generate = deps.generate ?? generateAiBlogPost\n const writeCollection = deps.writeCollection ?? writeContentCollection\n const writeEntry = deps.writeEntry ?? writeContentEntryDraft\n const coverFor = deps.cover ?? aiSitePostCover\n return async (context): Promise<AiJobStepOutcome> => {\n const { job, firestore, signal } = context\n const model = context.modelFor?.(AI_BLOG_POST_STEP) ?? aiModelForStep(AI_BLOG_POST_STEP)\n if (!job.hostId) return { ...aiUnspentOutcome(model), failure: 'Open the site before writing its posts.' }\n const input = postsInputOf(job)\n const index = input.written.length\n if (index >= input.total) return aiUnspentOutcome(model)\n const site = await readSite(firestore, job.hostId)\n if (!site) return { ...aiUnspentOutcome(model), failure: 'This site no longer exists.' }\n const avoid = new Set(input.avoidSlugs.map((slug) => slug.toLowerCase()))\n const blog = await writeCollection(firestore, {\n hostId: job.hostId,\n uid: job.createdBy,\n id: job.$id,\n displayName: AI_SITE_BLOG_NAME,\n slugs: AI_SITE_BLOG_SLUGS.filter((slug) => !avoid.has(slug)),\n now: context.now,\n })\n if (blog.ok === false) return aiUnspentOutcome(model, { review: limitReview(blog.error) })\n\n const generation = await generate({\n brief: job.brief,\n merchantWords: job.brief,\n earlierTitles: input.written.map((post) => post.title),\n index: index + 1,\n total: input.total,\n model,\n maxTokens: AI_SITE_POST_BUDGET.maxTokens(model),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(generation)\n if (generation.status === 'refused') return { ...spent, refused: true }\n if (generation.status === 'needs_input') return { ...spent, failure: generation.message }\n const post = generation.value\n // A stock photo of its title as its cover, else a starter (AGL-3676).\n const cover = await coverFor({\n job,\n title: post.title,\n index,\n total: input.total,\n ...(signal ? { signal } : {}),\n }).catch(() => null)\n const byline = input.byline || site.name\n const written = await writeEntry(firestore, {\n hostId: job.hostId,\n collectionId: blog.id,\n uid: job.createdBy,\n id: aiSitePostId(job.$id, index),\n content: {\n title: post.title,\n excerpt: post.excerpt,\n body: post.body,\n seoDescription: post.seoDescription,\n ...(cover ? { coverImage: cover, coverImageAlt: post.title } : {}),\n ...(byline ? { authorName: byline } : {}),\n },\n now: context.now,\n })\n if (written.ok === false) return { ...spent, review: limitReview(written.error) }\n const output: AiJobOutput = {\n resource: 'entry',\n id: written.id,\n hostId: job.hostId,\n hostSubdomain: site.subdomain,\n label: written.title,\n note: `A post in ${blog.displayName}, at /${blog.slug}/${written.slug}. It goes live with the site.`,\n proposal: { collectionId: blog.id, collectionSlug: blog.slug, slug: written.slug },\n }\n return { ...spent, outputs: [output], ...(index + 1 < input.total ? { continue: true } : {}) }\n }\n}\n\nexport const runAiSitePostsUnit = createAiSitePostsRunner()\n\nexport interface AiSiteProductsRunnerDeps {\n /** The catalog's runner: the `products` step's. */\n catalog: AiJobStepRunner\n writerFor?: typeof pluginResourceDraftWriter\n /** Where each product's photo comes from; the stock library, else the starters, otherwise. */\n photos?: typeof aiSiteProductPhotos\n}\n\n/**\n * A photo for each product (AGL-3676), in order: a stock photo of the\n * product's own words, copied into the site's library, where the deployment\n * has a stock library; else a starter photo, as a page's empty picture takes\n * one. It fills the photo slot every product card and product page has, for\n * the owner to replace with their own; the product's note says so. Never\n * throws: a product with no photo is still written.\n */\nexport async function aiSiteProductPhotos(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief'>\n names: readonly string[]\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<Array<string | null>> {\n if (!input.names.length || !input.job.hostId) return input.names.map(() => null)\n const slots: AiLayoutPictureSlot[] = input.names.map((name, index) => ({\n imageId: `product${index}`,\n frameId: null,\n iconId: null,\n alt: name,\n // The product card's own shape (`cardStyle: 'photo'`).\n aspect: 4 / 5,\n sectionIndex: 0,\n role: 'gallery' as const,\n }))\n const seed = `${input.job.$id}:products`\n let found: ReadonlyArray<AiLayoutPicturePhoto | null> = []\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId: input.job.hostId,\n uid: input.job.createdBy,\n seed,\n business: aiSiteWords(input.job.inputs).about || input.job.brief,\n sectionNames: ['Products'],\n jobId: aiOriginJobId(input.job),\n ...(input.signal ? { signal: input.signal } : {}),\n })\n if (source) found = await source(slots)\n } catch (error) {\n console.warn('ai site products: the stock photos failed; starter photos fill them', { error: String(error) })\n }\n const starters = aiLayoutStarterPhotos(slots, seed)\n const hostId = input.job.hostId\n return slots.map(\n (_slot, index) =>\n aiSiteProductPhotoSrc(found[index]?.src, hostId) ?? aiSiteProductPhotoSrc(starters[index]?.src, hostId),\n )\n}\n\n/**\n * A photo as a product stores it: the form the console's picker writes when\n * an owner picks one from the library (`console-media-picker-provider`), the\n * asset's CDN path `/api/media/cdn/{scope}/{mediaId}`, or a starter's own\n * site path. A page's picture slot holds the library's `media:` reference\n * (`mediaNodeSrc`), which is what the stock source hands back, and the\n * product's rules take only an https address or a path on the site: the\n * candle store's guided start of 2026-10-09 (job FYNasg1h0S) wrote no\n * product at all because every photo was a `media:` reference. The path\n * names the asset, not its bytes, so a replace in the library still reaches\n * the product. Anything else is no photo, never a value the product refuses.\n */\nexport function aiSiteProductPhotoSrc(src: string | null | undefined, hostId: string): string | null {\n if (!src) return null\n const path = resolveMediaSrc(src, { hostId })\n if (!path || path.length > 2_000 || /[\\s\"'<>]/.test(path)) return null\n return path.startsWith('/') || path.startsWith('https://') ? path : null\n}\n\n/** The sentence the products unit's brief ends with, which the catalog's rules read as how many. */\nexport function aiSiteProductsBriefLine(input: AiSiteProductsInput = AI_SITE_PRODUCTS): string {\n return `Propose between ${input.min} and ${input.max} products: the store's first ones.`\n}\n\n/**\n * The products unit's runner: the `products` step's catalog for the store's\n * brief, then each proposed product, up to the most a site starts with,\n * written by the plugin that keeps products at its default price, listed. A\n * product past the plan's allowance stops the writing there, and the row\n * says how many were added; none at all is the allowance's review. A photo\n * the product's rules refuse is dropped and the product written without it;\n * a product they refuse outright is skipped, and none written for that\n * reason is our failure, refunded, never the person's review (AGL-3676).\n */\nexport function createAiSiteProductsRunner(deps: AiSiteProductsRunnerDeps): AiJobStepRunner {\n const writerFor = deps.writerFor ?? pluginResourceDraftWriter\n return async (context): Promise<AiJobStepOutcome> => {\n const { job } = context\n const keeper = writerFor('product')\n const model = context.modelFor?.('job.products') ?? aiModelForStep('job.products')\n if (!keeper || !job.hostId) return { ...aiUnspentOutcome(model), failure: 'Products are not available on this site.' }\n const outcome = await deps.catalog({\n ...context,\n job: { ...job, kind: 'products', inputs: { ...job.inputs, target: 'catalog' } },\n })\n if (outcome.refused || outcome.failure || outcome.review) return outcome\n const catalog = outcome.outputs.map((output) => ({ output, proposal: aiProductsProposalOf(output) })).find(\n (entry) => entry.proposal?.kind === 'catalog',\n )\n if (!catalog || catalog.proposal?.kind !== 'catalog') return { ...outcome, outputs: [] }\n const proposed = catalog.proposal.products.slice(0, AI_SITE_PRODUCTS.max)\n const photos = await (deps.photos ?? aiSiteProductPhotos)({\n job,\n names: proposed.map((product) => product.name),\n ...(context.signal ? { signal: context.signal } : {}),\n }).catch(() => proposed.map(() => null))\n const outputs: AiJobOutput[] = []\n let stopped: string | null = null\n /** The product's rules refusing what we made: ours, never the workspace's (AGL-3676). */\n let rejected: string | null = null\n for (const [index, product] of proposed.entries()) {\n const content: Record<string, unknown> = {\n name: product.name,\n type: product.type,\n // Listed at once, so no \"[gift card terms]\" gap reaches a shopper:\n // a sentence that leaves a fact for the owner is left out.\n description: aiSiteProductDescriptionWithoutGaps(product.description),\n tags: product.tags,\n options: product.options,\n seoTitle: product.seoTitle,\n seoDescription: product.seoDescription,\n comingSoon: true,\n }\n // A photo we picked that the product's rules refuse is dropped, never\n // the product: its slot stays empty for the owner's own.\n const photo = photos[index] ?? null\n const withPhoto = photo ? { ...content, mediaUrls: [photo] } : content\n const photoRefused =\n photo !== null &&\n keeper.writer.check(withPhoto, { hostId: job.hostId }).ok === false &&\n keeper.writer.check(content, { hostId: job.hostId }).ok\n if (photoRefused) {\n console.warn('ai site products: the product refused its photo; written without it', {\n orgId: job.orgId,\n jobId: job.$id,\n photo,\n })\n }\n const written = await keeper.writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n id: aiSiteProductId(job.$id, index),\n name: product.name,\n // No price stated: the writer gives it the store's default price\n // for the owner to change (AGL-3676). Listed at once. Its photo\n // slot holds a stock or starter photo for the owner to replace.\n content: photoRefused ? content : withPhoto,\n })\n if (written.ok === false) {\n // A 400 is the product's rules refusing content we made: that one\n // product is skipped and the rest are still written. Anything else\n // (the allowance, the role, the site) stops the writing there.\n if (written.status === 400) {\n console.error('ai site products: the product writer refused a product we made', {\n orgId: job.orgId,\n jobId: job.$id,\n index,\n error: written.error,\n })\n rejected = written.error\n continue\n }\n stopped = written.error\n break\n }\n outputs.push({\n resource: 'product',\n id: written.id,\n hostId: job.hostId,\n hostSubdomain: catalog.output.hostSubdomain ?? null,\n label: written.name,\n note: AI_SITE_PRODUCT_NOTE,\n })\n }\n if (!outputs.length) {\n // Nothing written because the product's rules refused what we made:\n // the failure is ours, so the item's credits are refunded\n // (`aiUnitFailure` → `ours: true`). Only the workspace's allowance,\n // role or site is the person's to review.\n if (!stopped && rejected) return { ...outcome, outputs: [], failure: AI_SITE_PRODUCTS_NOT_WRITTEN_COPY }\n return { ...outcome, outputs: [], review: limitReview(stopped ?? 'No product could be added.') }\n }\n // The allowance that stopped the rest is said where the last one added is.\n const last = outputs[outputs.length - 1]\n if (stopped) {\n last.note = `${last.note} ${outputs.length} of ${proposed.length} added: ${stopped}.`\n } else if (outputs.length < proposed.length) {\n last.note = `${last.note} ${outputs.length} of ${proposed.length} added.`\n }\n return { ...outcome, outputs }\n }\n}\n\n/**\n * Whether a part may be built for this member on this site, asked before its\n * first pass so a refusal spends nothing; `null` admits. Products ask what a\n * `products` job asks (the plan's commerce feature, Commerce on and released\n * for the site) and the writer's own refusal (role, allowance); posts ask\n * that the member may write the site's content.\n */\nexport async function aiSiteContentRefusal(\n part: 'posts' | 'products',\n context: Pick<AiJobStepContext, 'firestore' | 'org' | 'now'> & { job: Pick<AiJob, 'orgId' | 'hostId' | 'createdBy' | 'inputs'> },\n deps: { writerFor?: typeof pluginResourceDraftWriter; admissionFor?: typeof aiJobAdmissionFor } = {},\n): Promise<string | null> {\n const { job, firestore } = context\n if (!job.hostId) return 'Open the site first.'\n if (part === 'posts') {\n const host = await firestore.collection('hosts').doc(job.hostId).get()\n return hostRoleCanWrite((host.get('memberRoles') ?? {})[job.createdBy]) ? null : 'Editing requires the editor role'\n }\n const admission = (deps.admissionFor ?? aiJobAdmissionFor)('products')\n const refused: AiJobAdmissionRefusal | null = admission\n ? await admission({\n firestore,\n orgId: job.orgId,\n hostId: job.hostId,\n inputs: { target: 'catalog' },\n org: context.org ?? null,\n uid: job.createdBy,\n })\n : { status: 403, error: 'Products are not available on this site.' }\n if (refused) return refused.error\n const keeper = (deps.writerFor ?? pluginResourceDraftWriter)('product')\n if (!keeper) return 'Products are not available on this site.'\n const room = await keeper.writer.refusal({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n })\n return room?.error ?? null\n}\n\n/** The guided start's posts, published with its pages (AGL-3676). */\nexport interface AiSitePostsPublish {\n published: number\n kept: number\n /** The blog's own addresses, for the publish's cache drop. */\n paths: string[]\n}\n\n/**\n * Publishes the posts a guided start wrote, as the entry editor's Publish\n * does, once its pages are live. Never throws: a post that stays a draft is\n * the owner's to publish from Content.\n */\nexport async function aiPublishSitePosts(\n firestore: FirebaseFirestore.Firestore,\n input: { job: Pick<AiJob, '$id' | 'orgId' | 'hostId' | 'createdBy'>; outputs: readonly AiJobOutput[]; now: Date },\n publish: typeof publishContentEntries = publishContentEntries,\n): Promise<AiSitePostsPublish | null> {\n const posts = input.outputs.filter((output) => output.resource === 'entry')\n const collectionId = str(posts[0]?.proposal?.['collectionId'])\n const collectionSlug = str(posts[0]?.proposal?.['collectionSlug'])\n if (!input.job.hostId || !posts.length || !collectionId) return null\n try {\n const result = await publish(firestore, {\n hostId: input.job.hostId,\n collectionId,\n uid: input.job.createdBy,\n ids: posts.map((post) => post.id),\n now: input.now,\n })\n if ('ok' in result) {\n console.warn('ai site posts not published', { jobId: input.job.$id, error: result.error })\n return { published: 0, kept: posts.length, paths: [] }\n }\n const slugs = posts\n .filter((post) => result.published.includes(post.id))\n .map((post) => str(post.proposal?.['slug']))\n .filter(Boolean)\n return {\n published: result.published.length,\n kept: result.kept.length,\n paths: collectionSlug ? [`/${collectionSlug}`, ...slugs.map((slug) => `/${collectionSlug}/${slug}`)] : [],\n }\n } catch (error) {\n console.error('ai site posts publish threw', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\n/**\n * The site's listings a layout or a page unit is handed (AGL-3676,\n * `ai-layout-listings.ts`): the store's catalog once its products are written,\n * the blog once its posts are, each with the sections of the plan's pages\n * that list it. A layout is built before either, so it is told the store will\n * sell (`sells`, its ledger still owing the products part), which puts the\n * cart in its header.\n */\nexport function aiSiteListings(input: {\n outputs: readonly AiJobOutput[]\n screens: readonly AiLayoutListingScreen[]\n /** The ledger owes a store's first products: a layout built before them carries the cart. */\n sells?: boolean\n /**\n * The site is a store (`siteKind: 'store'`, AGL-3676): its Shop page and\n * its home list the catalog whatever its first products came to — the\n * live Hearth & Wick start's products step failed, and its Shop page was\n * six cards naming kinds of candle. An empty catalog says so in the grid.\n */\n store?: boolean\n /**\n * The site is a music site (`siteKind: 'music'`, AGL-3716): its Music page,\n * or its home, places an empty Music player for the artist's own tracks.\n * Nothing is sourced: the owner uploads the recordings.\n */\n music?: boolean\n}): AiLayoutListing[] {\n const listings: AiLayoutListing[] = []\n const products = input.outputs.filter((output) => output.resource === 'product' && !output.proposal)\n if (products.length || input.sells || input.store) {\n const contact = aiSiteContactPath(input.screens)\n listings.push({\n id: aiLayoutListingId('products'),\n kind: 'products',\n name: 'the shop',\n records: products.map((product) => product.label),\n ...(contact ? { emptyAction: { label: 'Get in touch', href: contact } } : {}),\n // A store whose first products were skipped or failed lists its\n // (empty) catalog, but its header carries no cart until it sells.\n ...(products.length || input.sells ? {} : { cart: false }),\n placements: aiLayoutListingPlacements('products', input.screens),\n })\n }\n const posts = input.outputs.filter((output) => output.resource === 'entry')\n const slug = str(posts[0]?.proposal?.['collectionSlug'])\n if (posts.length && slug) {\n listings.push({\n id: aiLayoutListingId('posts'),\n kind: 'posts',\n name: 'the blog',\n records: posts.map((post) => post.label),\n href: `/${slug}`,\n collectionSlug: slug,\n placements: aiLayoutListingPlacements('posts', input.screens),\n })\n }\n if (input.music) {\n const placements = aiLayoutListingPlacements('tracks', input.screens)\n if (placements.length) {\n listings.push({ id: aiLayoutListingId('tracks'), kind: 'tracks', name: 'the music', records: [], placements })\n }\n }\n return listings\n}\n\n/** The page a visitor gets in touch on, by its path: one whose address or name says contact, else the one placing a form. */\nfunction aiSiteContactPath(screens: readonly AiLayoutListingScreen[]): string | null {\n const path = (slug: string) => `/${slug.trim().replace(/^\\/+|\\/+$/g, '')}`\n const isPath = (slug: string) => /^\\/[a-z0-9-]+(?:\\/[a-z0-9-]+)*$/.test(path(slug))\n const named = screens.find((screen) => isPath(screen.slug) && /\\b(contact|get in touch|enquir|inquir)/i.test(`${screen.slug} ${screen.title}`))\n if (named) return path(named.slug)\n const form = screens.find((screen) => isPath(screen.slug) && screen.sections.some((section) => (section.uses ?? []).some((use) => /form/i.test(use))))\n return form ? path(form.slug) : null\n}\n\n/**\n * A proposed product's description with each sentence that leaves a gap for\n * the owner (\"Delivery details: [how and when the card is sent].\") taken\n * out (AGL-3676): a start's products are listed as soon as they are written,\n * and a live run's gift card showed its gaps on the product page. A line\n * break is kept; nothing else is changed.\n */\nexport function aiSiteProductDescriptionWithoutGaps(description: string): string {\n return description\n .split('\\n')\n .map((line) =>\n line\n .split(/(?<=[.!?])\\s+/)\n .filter((sentence) => !/\\[[^\\]]+\\]/.test(sentence))\n .join(' '),\n )\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim()\n}\n\n/** What each product a start wrote says on the job's page (AGL-3676). */\nexport const AI_SITE_PRODUCT_NOTE =\n 'On your store at a starting price. Set its real price — and your own photo — in Products.'\n\n/** The note a store's products row carries once they are written (AGL-3676): the step left before it sells. */\nexport const AI_SITE_PRODUCTS_PRICE_NOTE =\n 'Your products are on your store at a starting price. Set their real prices in Products.'\n\n/** What a page of a blog or a store is told about the posts or products built before it. */\nexport function aiSiteContentBriefLines(outputs: readonly AiJobOutput[]): string[] {\n const posts = outputs.filter((output) => output.resource === 'entry')\n const products = outputs.filter((output) => output.resource === 'product' && !output.proposal)\n const lines: string[] = []\n if (posts.length) {\n const slug = str(posts[0].proposal?.['collectionSlug'])\n lines.push(\n `This site's blog${slug ? ` at /${slug}` : ''} has these posts: ${posts.map((post) => `“${post.label}”`).join(', ')}.`,\n 'Where a page features writing, feature these posts by their titles; never name a post that is not in this list.',\n )\n }\n if (products.length) {\n lines.push(\n `This store's products are: ${products.map((product) => `“${product.label}”`).join(', ')}.`,\n 'Where a page features products, feature these by their names; never name another product, and never state a price.',\n )\n }\n return lines\n}\n"],"names":["resolveMediaSrc","hostRoleCanWrite","pluginResourceDraftWriter","publishContentEntries","writeContentCollection","writeContentEntryDraft","aiProductsProposalOf","aiSiteKindOfInputs","AI_SITE_BLOG_NAME","AI_SITE_BLOG_SLUGS","aiSiteWords","AI_STEP_TIERS","aiModelForStep","AI_BLOG_POST_MAX_TOKENS","AI_BLOG_POST_STEP","generateAiBlogPost","aiLayoutStarterPhotos","aiOriginJobId","aiLayoutStockPhotoSource","aiLayoutListingId","aiLayoutListingPlacements","aiJobAdmissionFor","aiJobStepBudget","aiGenerationSpent","aiUnspentOutcome","AI_SITE_POSTS","AI_SITE_PRODUCTS","min","max","AI_SITE_PRODUCTS_NOT_WRITTEN_COPY","AI_SITE_POSTS_LABEL","AI_SITE_PRODUCTS_LABEL","AI_SITE_CONTENT_INPUT","aiSiteContentPart","inputs","freeTaste","kind","id","AI_SITE_POST_WRITES_MS","AI_SITE_POST_BUDGET","tier","maxTokens","lookups","ownReadsMs","str","value","trim","postsInputOf","job","raw","written","Array","isArray","filter","one","total","Math","floor","avoidSlugs","map","Boolean","byline","aiSitePostId","unitJobId","index","aiSiteProductId","readSite","firestore","hostId","host","collection","doc","get","exists","seo","subdomain","name","limitReview","message","reason","findings","AI_SITE_POST_COVER_ASPECT","aiSitePostCover","input","starters","title","source","stockPhotos","uid","createdBy","seed","$id","business","about","brief","sectionNames","jobId","signal","found","imageId","frameId","iconId","alt","aspect","sectionIndex","role","src","error","console","warn","String","from","length","_","slot","createAiSitePostsRunner","deps","generate","writeCollection","writeEntry","coverFor","cover","context","model","modelFor","failure","site","avoid","Set","slug","toLowerCase","blog","displayName","slugs","has","now","ok","review","generation","merchantWords","earlierTitles","post","spent","status","refused","catch","collectionId","content","excerpt","body","seoDescription","coverImage","coverImageAlt","authorName","output","resource","hostSubdomain","label","note","proposal","collectionSlug","outputs","continue","runAiSitePostsUnit","aiSiteProductPhotos","names","slots","_slot","aiSiteProductPhotoSrc","path","test","startsWith","aiSiteProductsBriefLine","createAiSiteProductsRunner","writerFor","catalog","keeper","outcome","target","find","entry","proposed","products","slice","photos","product","stopped","rejected","entries","type","description","aiSiteProductDescriptionWithoutGaps","tags","options","seoTitle","comingSoon","photo","withPhoto","mediaUrls","photoRefused","writer","check","orgId","write","org","push","AI_SITE_PRODUCT_NOTE","last","aiSiteContentRefusal","part","admission","admissionFor","room","refusal","aiPublishSitePosts","publish","posts","result","ids","published","kept","paths","includes","aiSiteListings","listings","sells","store","contact","aiSiteContactPath","screens","records","emptyAction","href","cart","placements","music","replace","isPath","named","screen","form","sections","some","section","uses","use","split","line","sentence","join","AI_SITE_PRODUCTS_PRICE_NOTE","aiSiteContentBriefLines","lines"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,eAAe,QAAQ,mCAAkC;AAClE,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,yBAAyB,QAAQ,qDAAoD;AAC9F,SACEC,qBAAqB,EACrBC,sBAAsB,EACtBC,sBAAsB,QACjB,uDAAsD;AAC7D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