feat(assistant): the book designer works from a brief, with archetype covers, lively spreads and stickers

- design_book takes a brief (energy, decoration, collages, theme), a cover
  archetype and a cover lockup, and pages.overrides that give single pages of
  the plan another beat or layout. Directives written before parse as they
  did, and a design asked for none of it is composed exactly as before.
- The engine composes the seven cover archetypes from the book's own photos,
  words, theme faces and colours, lockups, shapes and stickers, varied by the
  seed: spine band, poster pop, cut-out, illustrated postcard, grid and
  badge, minimal serif and stamp collage. A title the directives give a
  display tier is held to it, and the notes say when a band, a badge or a
  stamp holds it smaller or a cover leaves a layout out.
- A lively or loud book turns two in five hero and grid spreads into
  collages, script overlays, badge grids, stamp rows or two-tone splits, the
  first of them always, turns and frames the prints of its other pages, sets
  its cover title larger and takes one or two, or three to six, stickers of
  its theme's motifs a spread, never over words, a photo's detail or the
  fold. A calm book asked for collages gets them and nothing else.
- Every turn the engine gives a print or a sticker stays within what the
  brief's energy takes, a calm book's within its theme's own, so a design is
  never judged against its own brief.
- New checks name a flat cover, a page without a lead, colours or faces off
  the theme and, for a design made with a brief, a book livelier or calmer
  than it asked, on the pages the design made and on a page revised in the
  draft. Page edits answer with the art checks too, and the assistant's
  cards name them in every language.
- list_book_assets lists the shapes, faces, lockups, themes and patterns
  beside the stickers, and the Studio's shape groups and photo frames are one
  list the assistant reads too.
- The Studio prompt gains an index of themes, archetypes and faces and JSON
  recipes of the elements to add and style for each cover and three lively
  spreads, and a turn that designs the book may preview sixteen pages, still
  three images a request; a viewer is told of none of it.
This commit is contained in:
Maurice
2026-10-23 23:14:25 +00:00
parent ff749611c6
commit 5651c11803
141 changed files with 6007 additions and 268 deletions
@@ -13,22 +13,22 @@
*/
export const BOOK_DESIGN_PROMPT = `How you design:
- Act as a book designer, not a form filler: decide the story first (chapters, pacing), then the energy of the book, then the pages.
- Map the person's words to design_book's directives: "calm, lots of white" is style minimal and density airy; "like a magazine" is editorial; "bold", "lively" or "loud" is bold and rich; "scrapbook" is scrapbook; a page count is pages.min and pages.max; "only Portugal" is a scope.
- Before you call design_book, state the brief in one line: the energy (calm, lively or loud), the cover photo, the title words and the look.
- Map the person's words to design_book's directives: "calm, lots of white" is style minimal and density airy; "like a magazine" is editorial; "lively" or "loud" is that brief.energy, with a theme and a cover archetype; "bold" is bold; "scrapbook" is scrapbook; a page count is pages.min and pages.max; "only Portugal" is a scope.
- Before you call design_book, state the brief in one line: the energy (calm, lively or loud), the decoration, the theme, the cover archetype, the cover photo and the title words; then pass it as directives.brief and directives.cover.
Always, whatever the energy:
- Never upscale: under 200 dpi make the frame smaller; keep the focal point visible.
- Nothing that matters in the fold, past the trim or outside the safe area; a picture meant to bleed reaches the bleed; mind the binding on a double spread.
- Words on a photo sit on a quiet part of it, a scrim or a colour block; running text at 4.5:1 contrast, display type at 3:1.
- Bound texts keep the journal in sync: prefer bindings over copied words; never invent captions or facts.
The energy decides the rest:
- Calm: one dominant element per page; heading, then body, then captions; whitespace as a beat after a loud spread; margins at least the safe area plus 6 mm; everything on the margin grid and the gutter; one accent from the photos and two typefaces.
- Lively: still one hero per page, now layered: a photo over a colour block or a shape, the title over a photo, photos turned 2 to 6 degrees in a white or polaroid frame, oversize display type, colour blocking in the accent; set a cover title or a chapter mark with add_lockup, and give type on a photo an outline, a hard shadow or a band (style) rather than a scrim.
- Loud: lively pushed further: bigger type, stronger colour, more layers, a title that fills the cover; never two heroes on one page.
- Calm: one dominant element per page; heading, then body, then captions; whitespace as a beat after a loud spread; margins at least the safe area plus 6 mm; everything on the margin grid and the gutter; one accent from the photos and two typefaces; prints straight or turned 2 degrees at most, or as far as the theme turns them.
- Lively: still one hero per page, now layered: a photo over a colour block or a shape, the title over a photo, photos turned 3 to 7 degrees in a white or polaroid frame, oversize display type, colour blocking in the accent; set a cover title or a chapter mark with add_lockup, and give type on a photo an outline, a hard shadow or a band (style) rather than a scrim.
- Loud: lively pushed further: bigger type, stronger colour, more layers, prints turned 4 to 10 degrees, a title that fills the cover; never two heroes on one page.
- A deliberate overlap is a design; an accidental one (two straight photos or texts of a size half over each other) is a fault.
- Vary the beats, never three alike in a row; a quiet page for a long story, grids for bursts.
- A decorated template (list_book_layouts, under decorated) lays a whole designed page with one layout op: the page's photos and words fill its roles in the book's theme; start a cover or a chapter opener from one, then refine it with style.
Type scale, in points for a 210 mm page and scaled with the page width:
- Cover title in a display face, 72 to 180 pt, 12 to 30 % of the page height; title to subtitle at least 3:1. For a big cover raise type.display (up to 6.5, about 180 pt); keep type.scale between 0.9 and 1.1 so body stays 9 to 11 pt.
- Cover title in a display face, 72 to 180 pt, 12 to 30 % of the page height (a band, a badge or a stamp sets it as large as its box holds); title to subtitle at least 3:1. For a big cover raise type.display (up to 6.5, about 180 pt); keep type.scale between 0.9 and 1.1 so body stays 9 to 11 pt.
- Date lines in spaced caps, 7 to 9 pt, tracking 0.25 to 0.4; an accent word over a title in a script (caveat, pacifico, vibes, marker) or the contrasting face (playfair italic), 1.2 to 1.6 times its cap height, with contrast, an outline or a shadow.
- Body 9 to 11 pt in a face whose role is body; captions 6.5 to 8 pt with tracking 0.05 to 0.1; a display face, a body face and one more at most, a script or a mono line not counted; a family sets only the weights its font id lists.
Look, judge, revise:
@@ -16,7 +16,9 @@ import { ASSISTANT_PAGE_IMAGE, previewBookPageRequestSchema } from '@trek/shared
* so a preview and the edit it checks are one shape. A session without that
* tool (a viewer's) previews pages as they stand. Previews are capped per
* step and per turn, since each can wait seconds for the Studio and costs a
* model an image.
* model an image; a turn that designs the whole book (design_book or
* revise_book_design came back with a draft, or a draft was looked at) may
* look at twice as many. Only a session that edits the book designs it.
*/
const EDIT_TOOL = 'edit_book_page';
@@ -31,12 +33,21 @@ const CAPS =
`At most ${ASSISTANT_PAGE_IMAGE.previewsPerStep} previews per step and ${ASSISTANT_PAGE_IMAGE.previewsPerTurn} ` +
'per turn.';
/** An editor's caps: a turn that designs the book may look at more pages. A viewer is offered none of those tools. */
const DESIGN_CAPS =
`At most ${ASSISTANT_PAGE_IMAGE.previewsPerStep} previews per step and ${ASSISTANT_PAGE_IMAGE.previewsPerTurn} ` +
`per turn, ${ASSISTANT_PAGE_IMAGE.previewsPerDesignTurn} in a turn that designs the book (design_book, ` +
'revise_book_design or a draft looked at).';
/** The tools that put a whole-book design in play for the rest of the turn, and with it the larger preview budget. */
const DESIGN_TOOLS: ReadonlySet<string> = new Set(['design_book', 'revise_book_design']);
/** For a session that may change the book: a proposed edit and a design draft can be looked at too. */
const EDITOR_DESCRIPTION =
`Look at one page of the book before you change it or after: ${SEES} With ops (the same ops edit_book_page ` +
'takes) you see the page as that edit would leave it, without saving anything. Preview a page once before you ' +
'propose an edit of it, fix what the findings or the image show, then propose the edit. With designId (from ' +
`design_book) you see the page of that design draft instead of the book. ${CAPS}`;
`design_book) you see the page of that design draft instead of the book. ${DESIGN_CAPS}`;
/** For a session without edit_book_page (a viewer's): the page as it stands, nothing it could not ask for. */
const READER_DESCRIPTION = `Look at one page of the book as it stands: ${SEES} ${CAPS}`;
@@ -48,11 +59,22 @@ const TOO_MANY =
`Too many previews: at most ${ASSISTANT_PAGE_IMAGE.previewsPerStep} in one step and ` +
`${ASSISTANT_PAGE_IMAGE.previewsPerTurn} in one turn. Propose the edit and let its card show the findings.`;
/** The same for an editor, whose turn may have a book design in play. */
const TOO_MANY_DESIGN =
`Too many previews: at most ${ASSISTANT_PAGE_IMAGE.previewsPerStep} in one step and ` +
`${ASSISTANT_PAGE_IMAGE.previewsPerTurn} in one turn (${ASSISTANT_PAGE_IMAGE.previewsPerDesignTurn} while a book ` +
'design is in play). Propose the edit and let its card show the findings.';
/** The session's `edit_book_page` ops schema, when it has that tool. */
function editOps(specs: readonly AiToolSpec[]): unknown {
const edit = specs.find((spec) => spec.name === EDIT_TOOL);
return ((edit?.parameters.properties ?? {}) as Record<string, unknown>).ops;
}
/** The preview's spec, its ops taken from the session's `edit_book_page` when it has that tool. */
function previewSpec(specs: readonly AiToolSpec[]): AiToolSpec {
const edit = specs.find((spec) => spec.name === EDIT_TOOL);
const properties = (edit?.parameters.properties ?? {}) as Record<string, unknown>;
const ops = properties.ops;
const ops = editOps(specs);
// Shared parts the ops point at, where the schema keeps them apart.
const shared: Record<string, unknown> = {};
for (const key of ['$defs', 'definitions']) if (edit?.parameters[key]) shared[key] = edit.parameters[key];
@@ -77,9 +99,14 @@ function previewSpec(specs: readonly AiToolSpec[]): AiToolSpec {
export function withPagePreview(tools: AgentToolPort, vision: TurnVision): AgentToolPort {
let inStep = 0;
let inTurn = 0;
// Only a session that may change the book designs it; a viewer keeps the plain budget whatever it passes.
let edits = false;
// Once the turn designs the book, it may look at more pages: a design is judged on many.
let designing = false;
const preview = async (args: Record<string, unknown>): Promise<AgentToolRun> => {
if (inStep >= ASSISTANT_PAGE_IMAGE.previewsPerStep || inTurn >= ASSISTANT_PAGE_IMAGE.previewsPerTurn) {
return { ok: false, value: TOO_MANY };
const perTurn = designing ? ASSISTANT_PAGE_IMAGE.previewsPerDesignTurn : ASSISTANT_PAGE_IMAGE.previewsPerTurn;
if (inStep >= ASSISTANT_PAGE_IMAGE.previewsPerStep || inTurn >= perTurn) {
return { ok: false, value: edits ? TOO_MANY_DESIGN : TOO_MANY };
}
const parsed = previewBookPageRequestSchema.safeParse(args);
if (!parsed.success) {
@@ -90,13 +117,17 @@ export function withPagePreview(tools: AgentToolPort, vision: TurnVision): Agent
inStep += 1;
inTurn += 1;
const { spreadId, ops, designId } = parsed.data;
return designId ? vision.look(spreadId, ops, designId) : vision.look(spreadId, ops);
const run = await (designId ? vision.look(spreadId, ops, designId) : vision.look(spreadId, ops));
// A draft looked at puts the design in play, once the look found it.
if (edits && designId && run.ok) designing = true;
return run;
};
return {
// The loop asks for the specs once at the start of every step: a new step may preview again.
specs: () => {
inStep = 0;
const listed = tools.specs();
edits = editOps(listed) !== undefined;
return [...listed, previewSpec(listed)];
},
kindOf: (name) => (name === PREVIEW_BOOK_PAGE_TOOL ? 'read' : tools.kindOf(name)),
@@ -106,6 +137,12 @@ export function withPagePreview(tools: AgentToolPort, vision: TurnVision): Agent
const { journeyId: _journeyId, ...rest } = args;
return { args: rest };
},
call: (name, args) => (name === PREVIEW_BOOK_PAGE_TOOL ? preview(args) : tools.call(name, args)),
call: async (name, args) => {
if (name === PREVIEW_BOOK_PAGE_TOOL) return preview(args);
const run = await tools.call(name, args);
// A design tool puts the design in play once its run came back with a draft.
if (edits && run.ok && DESIGN_TOOLS.has(name)) designing = true;
return run;
},
};
}
@@ -0,0 +1,52 @@
import {
BOOK_COVER_ARCHETYPE_LINES,
BOOK_COVER_ARCHETYPES,
BOOK_FONT_ROLES,
BOOK_FONTS_IDS,
BOOK_THEME_PRESETS,
bookFontRole,
} from '@trek/shared';
/**
* The art director's index and recipes for the Studio assistant (the
* expansion plan's section 5): which themes, cover archetypes and faces there
* are, how a brief is written before a design, and short recipes for each
* cover archetype and three lively spreads, as JSON of the elements a model
* adds and styles (add, style, add_lockup, background), with frames in
* percent of the page so they fit any format.
*
* The index is built from the catalogues themselves (the themes, the
* archetype lines the directives describe them with, the faces by role), so
* it never names something the book does not have. Static once built, so the
* prompt cache stays stable. Placed before the designer's rules
* (assistant-book-design.prompt.ts) for those who may change the book.
*/
/** A theme's name: its line up to the colon, "Loud travel poster". */
const themeName = (descr: string) => descr.split(':')[0]?.trim() ?? descr;
const THEMES = BOOK_THEME_PRESETS.map((t) => `${t.id} (${themeName(t.descr)})`).join(', ');
const ARCHETYPES = BOOK_COVER_ARCHETYPES.map((a) => `${a} (${BOOK_COVER_ARCHETYPE_LINES[a]})`).join('; ');
const FACES = BOOK_FONT_ROLES.map(
(role) => `${role}: ${BOOK_FONTS_IDS.filter((id) => bookFontRole(id) === role).join(', ')}`,
).join('; ');
export const BOOK_RECIPES_PROMPT = `Art direction:
- Write the brief before design_book: the energy (calm, lively or loud), the decoration (none, light, rich), collages or not, the theme, the cover archetype, its photo and its words. Say it in one line, then pass it as directives.brief ({ energy, decoration, collage, theme }) and directives.cover ({ archetype, lockup, title }) with photos.coverPhotoId.
- The engine composes the archetype and the lively pages itself; add pages.overrides ({ index, beat or template }) only for a page of the plan you want otherwise, and tweak single pages with revise_book_design.
- Themes: ${THEMES}.
- Cover archetypes: ${ARCHETYPES}.
- Faces by role (fontRole display, heading, body, script): ${FACES}.
- list_book_assets lists stickers, shapes, fonts, lockups, themes and patterns; pick stickers by the theme's motif or the journey's city as a tag.
Recipes, for a cover built or tweaked by hand, as JSON: each object one element in paint order, added with its kind and content (photoId, text or binding, shape, stickerId), frame, rotation and an id of yours, then styled by that id with the rest; {"lockup"} is add_lockup in that box, {"background"} the background operation. Frames are [x, y, w, h] in percent of the page (mm = percent times the page size / 100), -2 and 102 past the trim to the bleed, a turned frame as it stands before its turn. accent, accent2, accent3, paper and ink are the theme's colours (token on a shape or text, the hex elsewhere); photoId cover is the cover photo, 2 to 4 others; motif is a sticker of the theme's motifs, landmark one of a city the journey stopped in. size is points on a 210 mm page: a title takes fit shrink, on the display tier (72 to 180 pt) unless a band, a badge or a stamp holds it smaller; a text of 7 to 10 pt is a meta line, fontRole heading, tracking 0.3, transform upper.
- spine-band: [{"kind":"photo","photoId":"cover","frame":[-2,-2,104,104]},{"kind":"shape","shape":"rect","token":"accent","frame":[-2,-2,18,104]},{"kind":"text","binding":{"source":"journey.title"},"fontRole":"heading","token":"paper","size":44,"transform":"upper","tracking":0.18,"frame":[-29,41,74,10],"rotation":-90},{"kind":"text","text":"2026","token":"paper","size":8,"frame":[2,91,12,4]},{"kind":"text","binding":{"source":"journey.subtitle"},"fontRole":"script","size":30,"color":"#ffffff","outline":{"color":"#1a1a1a","width":0.7},"frame":[23,70,69,16]}]
- poster-pop: [{"kind":"shape","shape":"sunburst-24","token":"accent2","frame":[29,28,62,62]},{"kind":"shape","shape":"rect","token":"accent","frame":[-2,-2,104,57]},{"kind":"photo","photoId":"cover","frame":[38,40,44,33],"rotation":4,"border":{"width":3,"color":"#ffffff"},"shadow":{"dx":1.3,"dy":1.3,"color":"ink","alpha":0.22}},{"kind":"text","binding":{"source":"journey.title"},"fontRole":"display","token":"paper","size":110,"weight":900,"transform":"upper","leading":0.92,"align":"left","frame":[8,8,84,30]},{"kind":"text","text":"2026","size":9,"frame":[8,88,28,4]},{"kind":"sticker","stickerId":"motif","frame":[76,34,14,14],"rotation":-5}]
- cutout: [{"background":"accent"},{"kind":"text","text":"May 2026","token":"paper","size":9,"frame":[8,8,84,4]},{"kind":"text","binding":{"source":"journey.title"},"fontRole":"display","token":"paper","size":80,"weight":800,"transform":"upper","frame":[8,13,84,25]},{"kind":"shape","shape":"leaf-monstera","token":"accent2","frame":[6,46,28,28],"rotation":-25},{"kind":"shape","shape":"coral-1","token":"accent3","frame":[68,62,30,30],"rotation":20},{"kind":"photo","photoId":"cover","frame":[26,40,48,43],"rotation":2,"border":{"width":4.5,"color":"#ffffff"}},{"kind":"shape","shape":"organic-2","token":"accent3","frame":[19,73,16,16],"rotation":20}]
- postcard: [{"kind":"sticker","stickerId":"landmark","frame":[26,8,48,44]},{"kind":"photo","photoId":"2","frame":[72,8,20,24],"rotation":6,"edge":"perforated","edgeSize":3,"border":{"width":1.6,"color":"#ffffff"}},{"kind":"shape","shape":"wave","token":"ink","frame":[72,35,20,4.5]},{"lockup":"title-script-year","box":[8,60,84,32]}] on a pastel paper; without a landmark of its places, the cover photo in the sticker's frame with mask arch-tall and a white cutout of 2 mm.
- grid-badge: [{"kind":"photo","photoId":"cover","frame":[-2,-2,50.8,50.8]},{"kind":"photo","photoId":"2","frame":[51.2,-2,50.8,50.8]},{"kind":"photo","photoId":"3","frame":[-2,51.2,50.8,50.8]},{"kind":"photo","photoId":"4","frame":[51.2,51.2,50.8,50.8]},{"lockup":"circle-badge","box":[29,29,42,42]}], a cross of paper 2.4 % (5 mm) wide, the badge off every photo's focal point.
- minimal-serif: [{"kind":"photo","photoId":"cover","frame":[8,8,84,53],"border":{"width":0.3,"color":"ink"}},{"kind":"text","binding":{"source":"journey.title"},"fontRole":"display","token":"ink","size":80,"leading":1,"frame":[8,64,84,17]},{"kind":"text","binding":{"source":"journey.subtitle"},"fontRole":"heading","token":"ink","size":11,"frame":[8,82,84,3]},{"kind":"shape","shape":"rect","token":"ink","frame":[28,88.4,20,0.15]},{"kind":"shape","shape":"sun","token":"accent","frame":[48.5,87,3,3]},{"kind":"shape","shape":"rect","token":"ink","frame":[52,88.4,20,0.15]},{"kind":"text","text":"2026","size":8,"frame":[8,92,84,3]}]
- stamp-collage: [{"kind":"shape","shape":"rect","paint":{"type":"pattern","pattern":"checker","fg":"accent","bg":"paper","scale":1,"angle":0},"frame":[-2,-2,104,36]},{"kind":"photo","photoId":"cover","frame":[8,19,26,31],"rotation":-4,"edge":"perforated","edgeSize":3,"border":{"width":2.2,"color":"#ffffff"}},{"kind":"photo","photoId":"2","frame":[37,17,26,34],"rotation":3,"mask":"arch-tall","cutout":{"width":1.8,"color":"#ffffff"}},{"kind":"photo","photoId":"3","frame":[66,19,26,31],"rotation":-3,"edge":"perforated","edgeSize":3,"border":{"width":2.2,"color":"#ffffff"}},{"kind":"text","binding":{"source":"journey.title"},"fontRole":"display","token":"ink","size":90,"weight":800,"transform":"upper","align":"left","frame":[8,62,52,18]},{"kind":"text","text":"May 2026","size":9,"frame":[8,81,52,4]},{"lockup":"postmark","box":[62,60,30,30]}]
Lively spreads, in percent of the double page (the fold at 50); photos 1 to 4 are the page's, entry its entry id:
- script overlay: [{"kind":"photo","photoId":"1","focalX":0.3,"frame":[-1,-2,102,104]},{"kind":"text","binding":{"source":"entry.location","entryId":"entry"},"fontRole":"script","size":120,"color":"#ffffff","outline":{"color":"#1a1a1a","width":2.9},"frame":[55,26,40,30],"rotation":-6},{"kind":"text","binding":{"source":"entry.title","entryId":"entry"},"token":"ink","size":9,"highlight":{"color":"paper"},"frame":[57,62,36,4]}], the photo's detail off the fold and the word.
- collage: [{"kind":"photo","photoId":"1","frameStyle":"polaroid","frame":[6,10,26,36],"rotation":-5},{"kind":"photo","photoId":"2","frameStyle":"white","frame":[22,42,24,32],"rotation":4},{"kind":"photo","photoId":"3","frameStyle":"tape","frame":[56,12,30,40],"rotation":-3},{"kind":"photo","photoId":"4","frameStyle":"white","frame":[66,52,26,34],"rotation":6},{"kind":"sticker","stickerId":"motif","frame":[39,8,7,10],"rotation":8}], up to 3 prints a page turned 3 to 7 degrees either way, none across the fold or over another's focal point.
- two-tone: [{"kind":"photo","photoId":"1","frame":[-1,-2,51,104]},{"kind":"shape","shape":"rect","token":"accent","frame":[50,-2,51,66]},{"kind":"shape","shape":"rect","token":"accent2","frame":[50,64,51,38]},{"kind":"text","text":"1 May 2026","token":"paper","size":9,"frame":[57,10,36,4]},{"kind":"text","binding":{"source":"entry.title","entryId":"entry"},"fontRole":"display","token":"paper","size":66,"leading":1,"align":"left","frame":[57,17,36,40]},{"kind":"text","binding":{"source":"entry.location","entryId":"entry"},"token":"paper","size":9,"frame":[57,72,36,4]}]`;
@@ -1,4 +1,5 @@
import { BOOK_DESIGN_PROMPT } from './assistant-book-design.prompt';
import { BOOK_RECIPES_PROMPT } from './assistant-book-recipes.prompt';
import { CARD_PROMPT_LINES } from './cards/registry';
/**
@@ -78,12 +79,13 @@ const READER_PHOTO_SOURCES = 'the book or suggest_book_photos';
/**
* The Studio's standing instructions, telling the model which language to
* answer in. The designer's rules and the design draft come only with the
* right to change the book, as the design's tools do; each of the two
* variants is the same text every turn, so the provider's cache holds.
* answer in. The art director's index and recipes, the designer's rules and
* the design draft come only with the right to change the book, as the
* design's tools do; each of the two variants is the same text every turn,
* so the provider's cache holds.
*/
export function studioPrompt(language: string, canWrite: boolean): string {
const sources = canWrite ? WRITER_PHOTO_SOURCES : READER_PHOTO_SOURCES;
const base = STUDIO_INSTRUCTIONS.replace('{language}', language).replace('{photoSources}', sources);
return canWrite ? `${base}\n\n${BOOK_DESIGN_PROMPT}` : base;
return canWrite ? `${base}\n\n${BOOK_RECIPES_PROMPT}\n\n${BOOK_DESIGN_PROMPT}` : base;
}
@@ -12,6 +12,7 @@ import {
editBookPageArgs,
moveBookPage,
moveBookPageArgs,
pageArtFindings,
setBookCover,
setBookCoverArgs,
spreadFindings,
@@ -191,7 +192,12 @@ function freshOn(was: readonly BookFinding[], now: readonly BookFinding[], creat
function findingsOn(doc: BookDocument, ids: readonly string[], ctx: BookOpsContext): Map<string, BookFinding[]> {
const found = new Map<string, BookFinding[]>();
for (const spread of doc.spreads) {
if (ids.includes(spread.id)) found.set(spread.id, spreadFindings(spread, doc.page, ctx.photos));
if (!ids.includes(spread.id)) continue;
// As the write answers them: the print faults, then whether the page reads as designed.
found.set(spread.id, [
...spreadFindings(spread, doc.page, ctx.photos),
...pageArtFindings(spread, doc.page, doc.theme),
]);
}
return found;
}
@@ -1,6 +1,13 @@
import { DomainError } from '../common/domain-error';
import { Injectable } from '@nestjs/common';
import type { BookDesignLeftOut, BookDesignPlanRow, BookDesignStyleOut, BookDocument, BookFinding } from '@trek/shared';
import type {
BookBriefArt,
BookDesignLeftOut,
BookDesignPlanRow,
BookDesignStyleOut,
BookDocument,
BookFinding,
} from '@trek/shared';
/**
* Whole-book designs waiting for the person's yes (journey-studio-wp13.md
@@ -38,6 +45,8 @@ export interface BookDesignDraft {
leftOut: BookDesignLeftOut[];
findings: BookFinding[];
notes: string[];
/** The brief the design was made against, so a revised page is judged by it too; none for a design without one. */
brief?: BookBriefArt;
/** Epoch milliseconds. */
expiresAt: number;
}
@@ -61,7 +61,7 @@ export class JourneyBookDesignMcp {
@Tool({
name: 'design_book',
description: `Design the whole photo book of a journey as a draft: chapters, pacing, the pages, the photos picked for each, type and colours, with the engine's own check run on every page and repaired where it can. directives says what the person wants (style, density, page count, scope, chapters, photos, cover, type, palette, words, travel pages, what to keep). It answers the draft's design_id, the plan page by page (what each page becomes and its findings), the look, the photos left out and why, and the findings left. ${DRAFT_FLOW} ${LIMITS} Only the book's owner and editors can design it.`,
description: `Design the whole photo book of a journey as a draft: chapters, pacing, the pages, the photos picked for each, type and colours, with the engine's own check run on every page and repaired where it can. directives says what the person wants (style, density, page count, scope, chapters, photos, cover, type, palette, words, travel pages, what to keep) and the art direction: the brief (energy, decoration, collages, theme), the cover's archetype and lockup, and pages.overrides giving single pages of the plan another beat or layout. It answers the draft's design_id, the plan page by page (what each page becomes and its findings), the look, the photos left out and why, and the findings left. ${DRAFT_FLOW} ${LIMITS} Only the book's owner and editors can design it.`,
inputSchema: { journeyId: idSchema, ...designBookArgs },
annotations: TOOL_ANNOTATIONS_READONLY,
when: journeyAddonOn,
@@ -25,9 +25,11 @@ import {
BOOK_DESIGN_LIMITS,
BOOK_OP_LIMITS,
bookPageSetupForPreset,
briefFindings,
describeSpread,
designBook,
normalizeBookDocument,
pageArtFindings,
sortBookFindings,
spreadFindings,
summarizeSpread,
@@ -49,6 +51,7 @@ import {
type RestoreBookRevisionRequest,
type ReviseBookDesignRequest,
} from '@trek/shared';
import { BOOK_STICKERS } from '@trek/shared/stickers';
import { randomUUID } from 'node:crypto';
@@ -109,11 +112,13 @@ export class JourneyBookDesignService {
selection: result.plan
.filter((row) => row.action !== 'keep' && (row.action !== 'drop' || freshBook))
.map((row) => row.spreadId),
style: { style: directives.style ?? 'classic', ...result.style },
// The brief's theme takes the place of the style, as the engine reads it.
style: { style: directives.brief?.theme ?? directives.style ?? 'classic', ...result.style },
usedPhotos: result.photos.used.length,
leftOut: result.photos.left_out,
findings: result.findings,
notes: result.notes,
...(result.brief ? { brief: result.brief } : {}),
expiresAt: Date.now() + BOOK_DESIGN_DRAFTS.ttlMs,
};
await this.drafts.put(draft);
@@ -142,7 +147,9 @@ export class JourneyBookDesignService {
const index = made.doc.spreads.findIndex((s) => s.id === args.spreadId);
const spread = made.doc.spreads[index];
if (!described || !spread) throw new DomainError(404, `No page ${args.spreadId} in this design`);
const findings = described.findings;
// The page judged against the design's brief too: its stickers and turns as the energy asked.
const brief = draft.brief ? briefFindings(made.doc, draft.brief, { only: [args.spreadId] }) : [];
const findings = sortBookFindings([...described.findings, ...brief]);
const count = (severity: 'severe' | 'warn') => findings.filter((f) => f.severity === severity).length;
const plan = draft.plan.map((row): BookDesignPlanRow =>
row.spreadId === args.spreadId
@@ -347,6 +354,8 @@ export class JourneyBookDesignService {
candidates,
photos,
gallery: facts.map((f) => ({ photoId: f.photo_id, width: f.width, height: f.height, caption: f.caption })),
// The sticker library's facts, for the stickers a decorated design places.
stickers: BOOK_STICKERS,
};
}
}
@@ -384,7 +393,12 @@ function pagesAnswer(record: BookRecord, spreadIds: readonly string[]): BookWrit
const doc = record.document;
const named = new Set(spreadIds);
const pages = doc.spreads.flatMap((s, i) => (named.has(s.id) ? [{ spread: s, index: i }] : []));
const findings = sortBookFindings(pages.flatMap(({ spread }) => spreadFindings(spread, doc.page)));
const findings = sortBookFindings(
pages.flatMap(({ spread }) => [
...spreadFindings(spread, doc.page),
...pageArtFindings(spread, doc.page, doc.theme),
]),
);
return {
version: record.version,
spread_ids: pages.map(({ spread }) => spread.id),
@@ -24,8 +24,10 @@ import {
deleteBookPages,
describeSpread,
duplicateBookPage,
listBookCatalogue,
listBookLayouts,
moveBookPage,
pageArtFindings,
removeBookLayout,
restoreBookLayout,
restoreBookPage,
@@ -172,13 +174,16 @@ export class JourneyBookEditService {
}
/**
* `list_book_assets`: the Studio's sticker library, searched. Not of the
* `list_book_assets`: the Studio's catalogues searched, the stickers, the
* shapes, the faces, the lockups, the themes or the patterns. Not of the
* journey, but asked on one, a member's read like the other book reads, so
* the Studio chat keeps it (its tools are pinned to the journey).
*/
async assets(journeyId: number, userId: number, search: Omit<ListBookAssetsRequest, 'kind'>) {
async assets(journeyId: number, userId: number, search: ListBookAssetsRequest) {
await this.readable(journeyId, userId);
return { kind: 'sticker' as const, ...listBookAssets(search) };
const { kind, theme, ...words } = search;
if (kind === 'sticker') return { kind, ...listBookAssets({ ...words, theme }) };
return { kind, ...listBookCatalogue(kind, words) };
}
/**
@@ -514,7 +519,8 @@ function pagesOf(doc: BookDocument, made: BookMade, ctx: BookOpsContext) {
const spread = doc.spreads[index];
if (!spread) continue;
pages.push(summarizeSpread(spread, index));
findings.push(...spreadFindings(spread, doc.page, ctx.photos));
// The print faults, and whether the page reads as designed (a flat cover, a weak lead, colours off the theme).
findings.push(...spreadFindings(spread, doc.page, ctx.photos), ...pageArtFindings(spread, doc.page, doc.theme));
}
const order = { severe: 0, warn: 1, info: 2 } as const;
findings.sort((a, b) => order[a.severity] - order[b.severity]);
+3 -3
View File
@@ -134,14 +134,14 @@ export class JourneyBookMcp {
@Tool({
name: 'list_book_assets',
description:
"The Studio's library of things to put on a page of a journey's book, searchable, the same one the Studio's panels show. kind sticker lists the illustrations: flat, multi-coloured drawings of landmarks, travel things, tropical and Mediterranean motifs, the sea, mountains, the north, Asia, food, paper and tape, hand-drawn doodles and ornaments. Each row has its id, theme, one sentence of what it shows, its tags, its aspect (width over height) and its colour slots with their defaults. query searches ids, tags and descriptions in English; tags and theme narrow it; at most limit rows, 40 by default, with the total found. Place one with edit_book_page add { kind: 'sticker', stickerId }, recolour it with colors (one per slot, in order) and mirror it with flipX. Stickers are decoration: put them beside or over a photo, never over words.",
"The Studio's catalogues of things to put on a page of a journey's book, searchable, the ones the Studio's panels show; every row has its id, one line on what it is and its tags, at most limit rows (40 by default) with the total found. kind sticker: flat, multi-coloured illustrations (landmarks, travel things, tropical and Mediterranean motifs, the sea, mountains, the north, Asia, food, paper and tape, doodles, ornaments) with their aspect and colour slots; place one with edit_book_page add { kind: 'sticker', stickerId }, recolour it with colors and mirror it with flipX; beside or over a photo, never over words. kind shape: the outlines a shape draws and a photo is cut to (mask), tagged frame when it holds a photo and edge when it takes a cut edge. kind font: the typefaces by role (display, heading, body, script, mono) with their weights. kind lockup: the set titles, badges, postmarks and quotes add_lockup places, with the word roles each takes. kind theme: the built-in themes with palette, faces and motifs, for set_book_theme and design_book's brief. kind pattern: the repeats a paint takes. query searches ids, tags and descriptions in English; tags narrow it; theme narrows stickers. Templates are list_book_layouts'.",
inputSchema: { journeyId: idSchema, ...listBookAssetsArgs },
annotations: TOOL_ANNOTATIONS_READONLY,
when: journeyAddonOn,
access: { group: 'journey', mode: 'read' },
})
async listAssets({ journeyId, query, tags, theme, limit }: OnJourney & ListBookAssetsRequest, ctx: McpContext) {
return ok(await this.books.assets(journeyId, ctx.userId, { query, tags, theme, limit }));
async listAssets({ journeyId, ...search }: OnJourney & ListBookAssetsRequest, ctx: McpContext) {
return ok(await this.books.assets(journeyId, ctx.userId, search));
}
// ── Write ───────────────────────────────────────────────────────────────