Open History to see the last commit
1import { randomUUID } from "node:crypto";
2import {
3 streamText,
4 Output,
5 NoObjectGeneratedError,
6 NoOutputGeneratedError,
7} from "ai";
8import { neon } from "@neon/ai-sdk-provider";
9import { z } from "zod";
10import { compileBlueprint, type CompiledBlueprint } from "../shared/blueprint";
11import { COLORS } from "../shared/catalogue";
12import { MAX_AI_PARTS, type AIConversationRow } from "../shared/types";
13import {
14 ASSEMBLIES,
15 DesignError,
16 designCatalogue,
17 designSchema,
18 designGenerationSchema,
19 designPatchSchema,
20 applyDesignPatch,
21 type Design,
22} from "../shared/design";
23import { snapDesign, type DesignAdjustment } from "../shared/design-fit";
24import { bounds } from "../shared/geometry";
25import {
26 fitScore,
27 fitRepairFeedback,
28 fitFailureMessage,
29} from "../shared/design-repair";
30import { DomainError, lockAccess, type Identity } from "./auth";
31import { pool, transaction } from "./db";
32import { aiBuildErrorMessage } from "./ai-errors";
33import { insertWorld, partFromRow } from "./worlds";
34import { executeInTransaction } from "./commands";
35import {
36 aiWorkshopEdit,
37 streamingPreview,
38 workshopReference,
39 sameAISnapshot,
40 type AISnapshot,
41} from "../shared/ai-workshop";
42import type { PoolClient } from "pg";
43import { watchCancellation } from "./ai-lifecycle";
44import { rawSql } from "@neon/realtime/server";
45
46const active = ["queued", "designing", "checking", "repairing"];
47const running = ["designing", "checking", "repairing"];
48const controllers = new Map<string, AbortController>();
49const model = () => process.env.AI_MODEL || "gpt-5-4";
50export const aiConfiguration = () => ({
51 available: aiAvailable(),
52 maxParts: MAX_AI_PARTS,
53 model: model(),
54 version: AI_BUILDER_VERSION,
55});
56export const AI_BUILDER_VERSION = "realtime-lifecycle-2";
57export const aiAvailable = () =>
58 !!(process.env.NEON_AI_GATEWAY_TOKEN && process.env.NEON_AI_GATEWAY_BASE_URL);
59const publicColumns =
60 "g.id::text,g.prompt,g.model,g.status,g.attempt,g.error,g.world::text,g.source::text,g.target::text,g.preview,g.activity,g.preview_version,g.blueprint,g.guest::text AS author,author.name AS author_name,author.color AS author_color,g.created_at::text,g.updated_at::text";
61const conversationColumns =
62 "g.id::text,g.prompt,g.model,g.status,g.attempt,g.error,g.world::text,g.source::text,g.target::text,g.activity,g.preview_version,g.blueprint->>'title' AS title,g.blueprint->>'summary' AS summary,g.guest::text AS author,author.name AS author_name,author.color AS author_color,g.created_at::text,g.updated_at::text,coalesce(jsonb_array_length(g.preview->'parts'),0) AS piece_count";
63const conversationFrom =
64 "ai_generations g JOIN guests author ON author.id=g.guest";
65// Membership/session predicates stay in the live query, so withdrawal removes
66// previously visible conversation rows without waiting for capability renewal.
67const memberAccess = (world: string) =>
68 `EXISTS(SELECT 1 FROM world_memberships m JOIN guest_sessions s ON s.guest=m.guest WHERE m.world=${world} AND m.guest=$2::uuid AND m.active=1 AND s.id=$3::uuid AND s.revoked=0)`;
69
70async function generationAccess(
71 c: PoolClient,
72 a: Identity,
73 id: string,
74 editor = false,
75) {
76 const { rows } = await c.query(
77 "SELECT guest,target FROM ai_generations WHERE id=$1",
78 [id],
79 );
80 const row = rows[0];
81 if (!row) throw new DomainError("Build not found", 404);
82 if (row.target) await lockAccess(c, a, row.target, editor);
83 else if (row.guest !== a.guest) throw new DomainError("Build not found", 404);
84 return row;
85}
86export async function expireGenerations() {
87 await pool.query(
88 "UPDATE ai_generations SET status='failed',error='This build was interrupted. Please try again.',updated_at=clock_timestamp() WHERE status=ANY($1::text[]) AND lease_until<clock_timestamp()",
89 [active],
90 );
91}
92export async function getGeneration(a: Identity, id: string) {
93 const row = await transaction(async (c) => {
94 await generationAccess(c, a, id);
95 const { rows } = await c.query(
96 `SELECT ${publicColumns},(SELECT slug FROM worlds WHERE id=g.target) AS target_slug FROM ${conversationFrom} WHERE g.id=$1`,
97 [id],
98 );
99 return rows[0];
100 });
101 const compiled =
102 row.blueprint && ["ready", "accepted"].includes(row.status)
103 ? compileBlueprint(row.blueprint)
104 : null;
105 if (compiled?.issues.length)
106 throw new DomainError("This build no longer passes validation");
107 return {
108 ...row,
109 parts: compiled?.parts || [],
110 serverTime: Date.now(),
111 };
112}
113export function generationQuery(a: Identity, id: string) {
114 return rawSql<AIConversationRow>(
115 `SELECT ${publicColumns} FROM ${conversationFrom} WHERE g.id=$1::uuid AND ((g.target IS NOT NULL AND ${memberAccess("g.target")}) OR (g.target IS NULL AND g.guest=$2::uuid AND EXISTS(SELECT 1 FROM guest_sessions s WHERE s.id=$3::uuid AND s.guest=g.guest AND s.revoked=0)))`,
116 [id, a.guest, a.session],
117 );
118}
119export function conversationQuery(a: Identity, world: string) {
120 return rawSql<AIConversationRow>(
121 `WITH recent AS (
122 (SELECT g.* FROM ai_generations g WHERE g.target=$1::uuid AND ${memberAccess("$1::uuid")} ORDER BY g.created_at DESC,g.id DESC LIMIT 50)
123 UNION ALL
124 (SELECT g.* FROM ai_generations g WHERE g.target IS NULL AND g.world=$1::uuid AND g.guest=$2::uuid AND ${memberAccess("$1::uuid")} ORDER BY g.created_at DESC,g.id DESC LIMIT 50)
125 ), history AS (SELECT * FROM recent ORDER BY created_at DESC,id DESC LIMIT 50)
126 SELECT ${conversationColumns},CASE WHEN g.status IN ('queued','designing','checking','repairing') OR
127 (g.status='ready' AND NOT EXISTS(SELECT 1 FROM history later WHERE later.status IN ('ready','accepted') AND (later.created_at,later.id)>(g.created_at,g.id)))
128 THEN g.preview ELSE NULL::jsonb END AS preview
129 FROM history g JOIN guests author ON author.id=g.guest ORDER BY g.created_at DESC,g.id DESC`,
130 [world, a.guest, a.session],
131 );
132}
133export async function createGeneration(
134 a: Identity,
135 input: {
136 id: string;
137 prompt: string;
138 source?: string;
139 target?: string;
140 newWorld?: boolean;
141 },
142 options: { dispatch?: boolean } = {},
143) {
144 if (!aiAvailable())
145 throw new DomainError("AI building is not configured yet", 503);
146 await expireGenerations();
147 await transaction(async (c) => {
148 // This lock only serializes AI concurrency admission, never workshop edits.
149 await c.query("SELECT pg_advisory_xact_lock(729411)");
150 const existing = await c.query(
151 "SELECT guest,prompt,source::text,target::text FROM ai_generations WHERE id=$1",
152 [input.id],
153 );
154 if (existing.rows[0]) {
155 if (
156 existing.rows[0].guest !== a.guest ||
157 existing.rows[0].prompt !== input.prompt ||
158 existing.rows[0].source !== (input.source || null) ||
159 (input.target && existing.rows[0].target !== input.target)
160 )
161 throw new DomainError("Build request already used");
162 return;
163 }
164 const { rows } = await c.query(
165 "SELECT count(*)::int AS active,count(*) FILTER(WHERE guest=$1)::int AS personal_active FROM ai_generations WHERE status=ANY($2::text[])",
166 [a.guest, active],
167 );
168 const limits = rows[0];
169 if (limits.personal_active)
170 throw new DomainError("You already have a build in progress", 429);
171 if (limits.active >= 2)
172 throw new DomainError(
173 "AI builders are busy. Please try again shortly.",
174 429,
175 );
176 let reference: unknown = null;
177 let target = input.target || null;
178 let snapshot: AISnapshot | null = null;
179 if (input.newWorld) {
180 const world = await insertWorld(c, "Building with AI", a.guest);
181 target = world.id;
182 await c.query(
183 "INSERT INTO world_memberships(world,guest) VALUES($1,$2)",
184 [target, a.guest],
185 );
186 await c.query(
187 "INSERT INTO guest_world_history(world,guest,generation) VALUES($1,$2,1)",
188 [target, a.guest],
189 );
190 }
191 // Read-lock the source before taking workshop locks, matching application’s
192 // generation-first lock order and preventing cross-editor apply deadlocks.
193 const prior = input.source
194 ? await c.query(
195 "SELECT blueprint,design,target::text,snapshot,status FROM ai_generations WHERE id=$1 AND ((target=$3::uuid AND $3::uuid IS NOT NULL) OR (target IS NULL AND guest=$2)) AND status IN ('ready','accepted') FOR SHARE",
196 [input.source, a.guest, target],
197 )
198 : null;
199 if (target) {
200 await lockAccess(c, a, target);
201 const pending = await c.query(
202 "SELECT id FROM ai_generations WHERE target=$1 AND status=ANY($2::text[])",
203 [target, active],
204 );
205 if (pending.rowCount)
206 throw new DomainError(
207 "This workshop already has an AI build in progress",
208 409,
209 );
210 snapshot = await workshopSnapshot(c, target);
211 if (snapshot.parts.length > MAX_AI_PARTS)
212 throw new DomainError(
213 `AI editing supports models of up to ${MAX_AI_PARTS} pieces`,
214 );
215 reference = workshopReference(snapshot);
216 }
217 if (input.source) {
218 const source = prior?.rows[0];
219 if (!source) throw new DomainError("Reference model not found", 404);
220 if (!target || (source.target === target && source.status === "ready")) {
221 reference = source.design || source.blueprint;
222 if (target) snapshot = source.snapshot;
223 } else if (source.target !== target)
224 throw new DomainError("That draft belongs to another workshop", 409);
225 }
226 await c.query(
227 "INSERT INTO ai_generations(id,guest,prompt,model,source,reference,target,snapshot,session,lease_until) VALUES($1,$2,$3,$4,$5,$6::jsonb,$7,$8::jsonb,$9,clock_timestamp()+interval '3 minutes')",
228 [
229 input.id,
230 a.guest,
231 input.prompt,
232 model(),
233 input.source || null,
234 reference ? JSON.stringify(reference) : null,
235 target,
236 snapshot ? JSON.stringify(snapshot) : null,
237 options.dispatch === false ? null : a.session,
238 ],
239 );
240 });
241 return getGeneration(a, input.id);
242}
243
244async function workshopSnapshot(
245 c: PoolClient,
246 world: string,
247): Promise<AISnapshot> {
248 // Both collections share one SQL statement snapshot, including concurrent edits.
249 const { rows } = await c.query(
250 "SELECT title,generation,(SELECT coalesce(jsonb_agg(p ORDER BY p.id),'[]'::jsonb) FROM part_instances p WHERE p.world=w.id AND p.deleted=0) AS parts,(SELECT coalesce(jsonb_agg(e ORDER BY e.id),'[]'::jsonb) FROM part_connections e WHERE e.world=w.id AND e.deleted=0) AS connections FROM worlds w WHERE id=$1",
251 [world],
252 );
253 const row = rows[0];
254 return {
255 generation: row.generation,
256 title: row.title,
257 parts: row.parts.map(partFromRow),
258 connections: row.connections.map(({ id, a, b, ca, cb, revision }: any) => ({
259 id,
260 a,
261 b,
262 ca,
263 cb,
264 revision,
265 })),
266 };
267}
268
269export async function listGenerations(a: Identity, target: string) {
270 const rows = await transaction(async (c) => {
271 await lockAccess(c, a, target, false);
272 return (
273 await c.query(
274 `SELECT ${publicColumns} FROM ${conversationFrom} WHERE g.target=$1 OR (g.target IS NULL AND g.world=$1 AND g.guest=$2) ORDER BY g.created_at DESC,g.id DESC LIMIT 50`,
275 [target, a.guest],
276 )
277 ).rows;
278 });
279 return rows.reverse().map((row) => ({
280 ...row,
281 parts:
282 row.blueprint && ["ready", "accepted"].includes(row.status)
283 ? compileBlueprint(row.blueprint).parts
284 : [],
285 }));
286}
287
288export async function recordDrawing(
289 id: string,
290 preview: { parts: import("../shared/types").Part[]; title: string },
291) {
292 const result = await pool.query(
293 "UPDATE ai_generations SET preview=$2::jsonb,preview_version=preview_version+1,activity=$3,updated_at=clock_timestamp() WHERE id=$1 AND status=ANY($4::text[]) RETURNING id",
294 [
295 id,
296 JSON.stringify(preview),
297 `Drawing ${preview.parts.length} pieces`,
298 running,
299 ],
300 );
301 return !!result.rowCount;
302}
303
304const system = `You are a skilled brick model designer. Build attractive, recognisable miniature models for Neonbricks.
305Return a version 2 design: title, one-sentence summary, front, pieces. Declare front as +z/-z/+x/-x: the direction toward the main doorway, headlights, face, or other defining details. The compiler rotates the whole model to present that front to the viewer, so this MUST match the actual placements. Each piece has a short unique id, catalogue part, colour, turn, at=[x,y,z], and repeat=null or {count,step:[dx,dy,dz]}. A repeated row expands at at+i*step, keeping its orientation. Use repeat for courses, fence posts, stairs, windows, tree trunks and symmetry. Do not list identical repeated pieces individually. Maximum ${MAX_AI_PARTS} expanded pieces; aim for 40–140 where useful. Small requests can use fewer.
306FIRST plan a coherent silhouette and palette. Choose a few defining features of the requested subject and build those prominently. For a little or small subject, aim for 30–70 pieces, keeping optional scenery modest; add more only when the requested features need it. Plan support levels, wall openings and stair landings before adding detail. Make roofs pitched, animal heads and tails readable, vehicle bodies supported, towers detailed. Use contrasting accent colours, a modest base or scenery where helpful, and a finished composition. Avoid random spare pieces or a mound of disconnected blocks. Most detail belongs on your declared front and sides; make it prominent from an isometric view. Doorways, arches and windows must be real openings: never place a solid wall immediately behind an opening. Do not describe details you did not build.
307Units: x/z studs; y plate heights. One brick=3 plates. at is the minimum corner of the ROTATED bounding box. turn=0/1/2/3 is yaw only; odd turns swap width/depth. brick-1x4 turn=0 is 1 along x, 4 along z; turn=1 is 4 along x, 1 along z. Board x/z=-16..16, y=0..48. Build near centre; prefer integer coordinates. Keep the entire rotated shape inside these bounds.
308Fit: parts may not overlap. Each part must connect to or rest on a supported part, with a path to the board. Studs are at cell centres; stack at the lower part's y+height, aligning integer x/z studs. Add roof plates over supporting walls, then slopes. Tiles/slopes have no studs above; do not float parts above them. Window frames are 3 wide, 1 deep, 6 high; leave a matching hole in the wall. Arches are 4 wide,1 deep,6 high with an open centre. Wall corners belong to only one wall. Chimneys need a real roof gap. A bridge can span a gap if connected at an end. A balcony needs an actual connection or support. Only yaw: horizontal pieces cannot be rotated vertically. Use stepped brick forms for vertical details.
309Mechanical shortcuts are verified multi-piece assemblies, with the same placement/repeat fields. Prefer four-wheel-chassis for vehicles: its body platform top is at y=8, within x=1..5,z=2..6 relative to origin. Add a hood, supported cockpit, headlights and antenna; keep the antenna foot inside the roof footprint. Use wheel-axle for custom wheel fits, rather than guessing axle offsets. A wheel-axle has two tyres and two bearing mounts; a body may rest on bearing tops. Two turn=1 wheel-axles spaced along z make a four-wheel chassis. At turn=1 its size is 6 along x,3 along z; bearings top at y=6, in x=1..2 and 4..5,z=1..2 relative to assembly origin. Keep chassis x within 1..5 to clear tyres. A plate-2x4 at turn=1 is 4 along x and2 along z: at [originX+1,originY+6,originZ+0.5] makes a supported cross-deck. Keep the remainder of the body above that deck. All mechanics are static. Do not promise animation, motors or unsupported rotations.
310Use upright-cross for windmill blades: a supported vertical cross in front of the tower, built from normal plates/bricks. Do NOT use a horizontal beam as a vertical blade, because only yaw is supported. Keep the mast grounded or on a base directly under its bottom at x=3,z=0 relative to origin.
311Architectural shortcuts: prefer gable-roof for a pitched roof and pine-tree for a pine. Both expand to editable ordinary parts. The roof is ONLY 4 studs deep. Repeat along its ridge to cover a 4-stud-deep building; do not cover a deeper building with several parallel ridges. A slope descends from high at z=0 to low at z=depth for turn=0; two opposing slopes form a ridge only when their HIGH edges meet. Roof assemblies have a solid base: run a chimney alongside the wall outside the roof footprint, or build an actual gap using individual plates/slopes. Lay out wall courses around real door/window openings, and support a roof on the remaining wall edges. A 4-stud arch is exactly 6 plates tall, so its top aligns with two brick courses. Use enough pieces to make requested features readable rather than a tiny abstract approximation.
312Assembly catalogue: ${JSON.stringify(Object.values(ASSEMBLIES).map(({ parts, ...a }) => a))}
313Part catalogue size=[x studs,y plates,z studs] at turn=0: ${JSON.stringify(designCatalogue())}
314Palette: ${COLORS.map((c) => `${c.name.toLowerCase()}=${c.hex}`).join(", ")}.
315Example compact stack: {id:"floor",part:"plate-4x4",colour:"sand",turn:0,at:[-2,0,-2],repeat:null}, {id:"tower",part:"brick-2x2",colour:"jade",turn:0,at:[-1,1,-1],repeat:{count:3,step:[0,3,0]}}, {id:"cap",part:"slope-2x2",colour:"poppy",turn:0,at:[-1,10,-1],repeat:null}.
316Validation feedback names expanded pieces as rowId_index or assemblyId_component. Fix the source row or assembly placement, preserving the subject. For an initial design return version 2; for a repair or user refinement return a patch as instructed.`;
317
318export type GenerateCandidate = (
319 prompt: string,
320 repair: string,
321 signal: AbortSignal,
322 model: string,
323 previous?: Design,
324 draw?: (preview: {
325 parts: import("../shared/types").Part[];
326 title: string;
327 }) => Promise<void>,
328) => Promise<{ blueprint: unknown; inputTokens: number; outputTokens: number }>;
329type CandidateAttempt = {
330 blueprint: unknown;
331 inputTokens: number;
332 outputTokens: number;
333 elapsedMs?: number;
334 issues?: unknown;
335 adjustments?: DesignAdjustment[];
336 issueCounts?: Record<string, number>;
337 bestBlueprint?: unknown;
338 bestIssues?: CompiledBlueprint["issues"];
339 bestIssueCounts?: Record<string, number>;
340 retainedPrevious?: boolean;
341};
342export async function recordGenerationAttempt(
343 id: string,
344 attempt: number,
345 stage: string,
346 result?: CandidateAttempt,
347) {
348 const issues = result?.bestIssues || result?.issues;
349 const counts = result?.bestIssueCounts || result?.issueCounts;
350 const count = counts
351 ? Object.values(counts).reduce((sum, n) => sum + n, 0)
352 : Array.isArray(issues)
353 ? issues.length
354 : 0;
355 const update = await pool.query(
356 "UPDATE ai_generations SET status=$2,attempt=$3::int,blueprint=COALESCE($4::jsonb,blueprint),issues=$5::jsonb,input_tokens=input_tokens+$6,output_tokens=output_tokens+$7,attempts=CASE WHEN $4::jsonb IS NULL THEN attempts ELSE attempts||jsonb_build_object(($3::int)::text,$9::jsonb) END,activity=$10,updated_at=clock_timestamp() WHERE id=$1 AND status=ANY($8::text[]) RETURNING id",
357 [
358 id,
359 stage,
360 attempt,
361 result ? JSON.stringify(result.bestBlueprint || result.blueprint) : null,
362 issues ? JSON.stringify(issues) : null,
363 result?.inputTokens || 0,
364 result?.outputTokens || 0,
365 running,
366 result ? JSON.stringify(result) : null,
367 result?.retainedPrevious
368 ? "Keeping the better draft; trying a different repair"
369 : count
370 ? `Found ${count} fit ${count === 1 ? "issue" : "issues"}; adjusting the design`
371 : stage === "checking"
372 ? "Checking collisions and connections"
373 : attempt > 1
374 ? `Adjusting the design · pass ${attempt}`
375 : "Designing the model",
376 ],
377 );
378 return !!update.rows[0];
379}
380export const generateCandidate: GenerateCandidate = async (
381 prompt,
382 repair,
383 signal,
384 modelId,
385 previous,
386 draw,
387) => {
388 let usage = { inputTokens: 0, outputTokens: 0 };
389 let streamError: unknown;
390 try {
391 const result = streamText({
392 model: neon(modelId),
393 output: previous
394 ? Output.object({ schema: designPatchSchema, name: "design_patch" })
395 : Output.object({
396 schema: designGenerationSchema,
397 name: "brick_design",
398 }),
399 system: previous
400 ? `${system}\nPATCH MODE: Output only a patch: title and summary null to preserve them, changes=[{id,row}]. Supply a full replacement row to change/add it; row=null deletes it. Omitted rows stay exactly as they were. IDs in changes refer to original rows, not expanded components. For refinement, make the user's requested changes and preserve the rest. For repair, correct the errors without simplifying away requested features.`
401 : system,
402 prompt: `Build this: ${prompt}${repair}`,
403 maxOutputTokens: 12000,
404 maxRetries: 0,
405 providerOptions: modelId.startsWith("gpt-")
406 ? {
407 openai: {
408 reasoningEffort: repair.startsWith("\nFIT REPAIR")
409 ? "medium"
410 : "low",
411 },
412 }
413 : undefined,
414 abortSignal: signal,
415 onError: ({ error }) => {
416 streamError = error;
417 },
418 onFinish: ({ totalUsage }) => {
419 usage = {
420 inputTokens: totalUsage.inputTokens || 0,
421 outputTokens: totalUsage.outputTokens || 0,
422 };
423 },
424 });
425 let lastDraw = 0;
426 let lastImage = "";
427 for await (const partial of result.partialOutputStream) {
428 signal.throwIfAborted();
429 if (!draw || performance.now() - lastDraw < 800) continue;
430 const image = streamingPreview(partial, previous);
431 if (!image) continue;
432 const signature = JSON.stringify(image);
433 if (signature === lastImage) continue;
434 lastDraw = performance.now();
435 lastImage = signature;
436 await draw(image);
437 }
438 const output = await result.output;
439 const totalUsage = await result.totalUsage;
440 return {
441 blueprint: output,
442 inputTokens: totalUsage.inputTokens || 0,
443 outputTokens: totalUsage.outputTokens || 0,
444 };
445 } catch (error) {
446 if (streamError) throw streamError;
447 if (NoOutputGeneratedError.isInstance(error))
448 return { blueprint: {}, ...usage };
449 if (!NoObjectGeneratedError.isInstance(error)) throw error;
450 let blueprint: unknown = {};
451 try {
452 blueprint = JSON.parse(error.text || "{}");
453 } catch {}
454 return {
455 blueprint,
456 inputTokens: error.usage?.inputTokens || 0,
457 outputTokens: error.usage?.outputTokens || 0,
458 };
459 }
460};
461
462// Exported so the bounded repair behaviour can be tested without paid inference.
463export async function buildCandidate(
464 prompt: string,
465 modelId: string,
466 signal: AbortSignal,
467 generate: GenerateCandidate,
468 report: (
469 attempt: number,
470 stage: string,
471 result?: CandidateAttempt,
472 ) => Promise<void>,
473 reference?: unknown,
474): Promise<CompiledBlueprint & { design?: Design }> {
475 let source =
476 reference &&
477 typeof reference === "object" &&
478 "version" in reference &&
479 reference.version === 2
480 ? designSchema.parse(reference)
481 : undefined;
482 let repair = reference
483 ? `\nRefine this reference model, applying the user's changes and preserving unaffected features: ${JSON.stringify(reference)}`
484 : "";
485 let best: { compiled: CompiledBlueprint; design?: Design } | undefined;
486 for (let attempt = 1; attempt <= 3; attempt++) {
487 signal.throwIfAborted();
488 await report(attempt, attempt === 1 ? "designing" : "repairing");
489 const started = performance.now();
490 const generated = await generate(prompt, repair, signal, modelId, source);
491 const result = {
492 ...generated,
493 elapsedMs: Math.round(performance.now() - started),
494 adjustments: [] as DesignAdjustment[],
495 };
496 signal.throwIfAborted();
497 await report(attempt, "checking");
498 let compiled: CompiledBlueprint;
499 let candidateDesign: Design | undefined;
500 try {
501 if (source) result.blueprint = applyDesignPatch(source, result.blueprint);
502 if (
503 result.blueprint &&
504 typeof result.blueprint === "object" &&
505 "version" in result.blueprint &&
506 result.blueprint.version === 2
507 )
508 candidateDesign = designSchema.parse(result.blueprint);
509 compiled = compileBlueprint(result.blueprint);
510 if (candidateDesign && compiled.issues.length) {
511 const fitted = snapDesign(candidateDesign, compiled);
512 candidateDesign = fitted.design;
513 compiled = fitted.compiled;
514 result.blueprint = candidateDesign;
515 result.adjustments = fitted.adjustments;
516 }
517 } catch (error) {
518 if (!(error instanceof z.ZodError) && !(error instanceof DesignError))
519 throw error;
520 const feedback =
521 error instanceof z.ZodError
522 ? JSON.stringify(
523 error.issues
524 .map((i) => ({ path: i.path, message: i.message }))
525 .slice(0, 15),
526 )
527 : error.message;
528 await report(attempt, "checking", {
529 ...result,
530 issues: [{ code: "schema", parts: [], message: feedback }],
531 bestBlueprint: best?.design || best?.compiled.blueprint,
532 bestIssues: best?.compiled.issues,
533 bestIssueCounts: best?.compiled.issueCounts,
534 retainedPrevious: !!best,
535 });
536 repair = `\nFIT REPAIR: your previous output failed validation: ${feedback}.${source ? `\nPrevious design: ${JSON.stringify(source)}\nReturn a corrected patch.` : " Return a complete corrected version 2 design."}`;
537 if (best) repair += fitRepairFeedback(best.compiled, best.design, true);
538 continue;
539 }
540 const retainedPrevious =
541 !!best && fitScore(compiled) >= fitScore(best.compiled);
542 if (!retainedPrevious) best = { compiled, design: candidateDesign };
543 const chosen = best!;
544 await report(attempt, "checking", {
545 ...result,
546 issues: compiled.issues,
547 issueCounts: compiled.issueCounts,
548 bestBlueprint: chosen.design || chosen.compiled.blueprint,
549 bestIssues: chosen.compiled.issues,
550 bestIssueCounts: chosen.compiled.issueCounts,
551 retainedPrevious,
552 });
553 if (!compiled.issues.length)
554 return { ...compiled, design: candidateDesign };
555 source = chosen.design;
556 repair = fitRepairFeedback(chosen.compiled, source, retainedPrevious);
557 }
558 throw new DomainError(fitFailureMessage(best?.compiled));
559}
560
561export async function runGeneration(
562 a: Identity,
563 id: string,
564 generate: GenerateCandidate = generateCandidate,
565) {
566 await getGeneration(a, id);
567 const claimed = await transaction(async (c) => {
568 await c.query("SELECT id FROM ai_generations WHERE id=$1 FOR UPDATE", [id]);
569 await generationAccess(c, a, id, true);
570 const session = await c.query(
571 "SELECT id FROM guest_sessions WHERE id=$1 AND guest=$2 AND revoked=0 AND expires_at>clock_timestamp() AND absolute_expiry>clock_timestamp() FOR SHARE",
572 [a.session, a.guest],
573 );
574 if (!session.rowCount) throw new DomainError("Session expired", 401);
575 return c.query(
576 "UPDATE ai_generations SET status='designing',lease_until=clock_timestamp()+interval '160 seconds',updated_at=clock_timestamp() WHERE id=$1 AND status='queued' RETURNING prompt,model,reference",
577 [id],
578 );
579 });
580 if (!claimed.rows[0]) return getGeneration(a, id);
581 const controller = new AbortController();
582 controllers.set(id, controller);
583 const signal = AbortSignal.any([
584 controller.signal,
585 AbortSignal.timeout(150_000),
586 ]);
587 let stopCancellation: (() => void) | undefined;
588 try {
589 stopCancellation = await watchCancellation(id, controller);
590 const row = claimed.rows[0];
591 const compiled = await buildCandidate(
592 row.prompt,
593 row.model,
594 signal,
595 (prompt, repair, signal, model, previous) =>
596 generate(prompt, repair, signal, model, previous, async (preview) => {
597 if (!(await recordDrawing(id, preview))) controller.abort();
598 signal.throwIfAborted();
599 }),
600 async (attempt, stage, result) => {
601 if (!(await recordGenerationAttempt(id, attempt, stage, result)))
602 controller.abort();
603 signal.throwIfAborted();
604 },
605 row.reference,
606 );
607 signal.throwIfAborted();
608 await pool.query(
609 "UPDATE ai_generations SET status='ready',blueprint=$2::jsonb,design=$4::jsonb,preview=$5::jsonb,preview_version=preview_version+1,activity='Ready to apply',issues=NULL,lease_until=NULL,updated_at=clock_timestamp() WHERE id=$1 AND status=ANY($3::text[])",
610 [
611 id,
612 JSON.stringify(compiled.blueprint),
613 running,
614 compiled.design ? JSON.stringify(compiled.design) : null,
615 JSON.stringify({
616 parts: compiled.parts,
617 title: compiled.blueprint.title,
618 }),
619 ],
620 );
621 } catch (error) {
622 const statusCode = (error as { statusCode?: number }).statusCode;
623 const message = aiBuildErrorMessage(error, signal.aborted);
624 console.error(
625 "[ai-build]",
626 id,
627 error instanceof Error ? error.name : "Error",
628 statusCode || "",
629 (error as { code?: string }).code || "",
630 );
631 await pool.query(
632 "UPDATE ai_generations SET status='failed',error=$2,updated_at=clock_timestamp() WHERE id=$1 AND status=ANY($3::text[])",
633 [id, message, running],
634 );
635 } finally {
636 stopCancellation?.();
637 controllers.delete(id);
638 }
639 return getGeneration(a, id);
640}
641
642export async function dispatchGeneration(id: string) {
643 const { rows } = await pool.query(
644 `SELECT s.id AS session,s.guest,g.name,g.color FROM ai_generations job
645 JOIN guest_sessions s ON s.guest=job.guest AND job.session=s.id
646 JOIN guests g ON g.id=s.guest
647 WHERE job.id=$1 AND job.status='queued' AND s.revoked=0
648 AND s.expires_at>clock_timestamp() AND s.absolute_expiry>clock_timestamp()
649 ORDER BY s.absolute_expiry DESC LIMIT 1`,
650 [id],
651 );
652 if (!rows[0]) {
653 await pool.query(
654 "UPDATE ai_generations SET status='failed',error='The build session ended. Please ask again.',updated_at=clock_timestamp() WHERE id=$1 AND status='queued'",
655 [id],
656 );
657 return;
658 }
659 try {
660 await runGeneration(rows[0], id);
661 } catch (error) {
662 if (
663 error instanceof DomainError &&
664 [401, 403, 410].includes(error.status)
665 ) {
666 await pool.query(
667 "UPDATE ai_generations SET status='failed',error='Workshop access changed. Please ask again.',updated_at=clock_timestamp() WHERE id=$1 AND status='queued'",
668 [id],
669 );
670 } else throw error;
671 }
672}
673export async function reconcileGenerations() {
674 await expireGenerations();
675 const { rows } = await pool.query(
676 "SELECT id::text FROM ai_generations WHERE status='queued' AND session IS NOT NULL ORDER BY created_at LIMIT 2",
677 );
678 await Promise.all(rows.map(({ id }) => dispatchGeneration(id)));
679}
680
681export async function cancelGeneration(a: Identity, id: string) {
682 await getGeneration(a, id);
683 await transaction(async (c) => {
684 await c.query("SELECT id FROM ai_generations WHERE id=$1 FOR UPDATE", [id]);
685 const row = await generationAccess(c, a, id, true);
686 await c.query(
687 "WITH RECURSIVE drafts AS (SELECT id,source,target FROM ai_generations WHERE id=$1 AND status='ready' UNION ALL SELECT g.id,g.source,g.target FROM ai_generations g JOIN drafts d ON g.id=d.source WHERE g.status='ready' AND g.target IS NOT DISTINCT FROM d.target AND (g.target IS NOT NULL OR g.guest=$2)) UPDATE ai_generations SET status='cancelled',updated_at=clock_timestamp() WHERE (target=$4::uuid OR (target IS NULL AND guest=$2)) AND (id=$1 OR id IN (SELECT id FROM drafts)) AND status=ANY($3::text[])",
688 [id, a.guest, [...active, "ready"], row.target],
689 );
690 });
691 controllers.get(id)?.abort();
692 return getGeneration(a, id);
693}
694
695export async function acceptGeneration(a: Identity, id: string) {
696 await transaction((c) => generationAccess(c, a, id, true));
697 const candidate = await getGeneration(a, id);
698 if (candidate.status !== "ready" && candidate.status !== "accepted")
699 throw new DomainError("This build isn't ready to use");
700 const compiled = compileBlueprint(candidate.blueprint);
701 if (compiled.issues.length)
702 throw new DomainError("This build no longer passes validation");
703 return transaction(async (c) => {
704 const session = await c.query(
705 "SELECT id FROM guest_sessions WHERE id=$1 AND guest=$2 AND revoked=0 AND expires_at>clock_timestamp() AND absolute_expiry>clock_timestamp() FOR SHARE",
706 [a.session, a.guest],
707 );
708 if (!session.rows[0]) throw new DomainError("Session expired", 401);
709 const { rows } = await c.query(
710 "SELECT status,world,blueprint,target,snapshot FROM ai_generations WHERE id=$1 FOR UPDATE",
711 [id],
712 );
713 await generationAccess(c, a, id, true);
714 const row = rows[0];
715 if (row.status === "accepted") {
716 const world = await c.query("SELECT slug FROM worlds WHERE id=$1", [
717 row.world,
718 ]);
719 return world.rows[0];
720 }
721 if (
722 row.status !== "ready" ||
723 JSON.stringify(row.blueprint) !== JSON.stringify(candidate.blueprint)
724 )
725 throw new DomainError(
726 "This build has changed. Please refresh the preview.",
727 );
728 if (row.target) {
729 await lockAccess(c, a, row.target);
730 const snapshot = row.snapshot as AISnapshot | null;
731 if (!snapshot)
732 throw new DomainError("This draft has no workshop snapshot");
733 const current = await workshopSnapshot(c, row.target);
734 if (!sameAISnapshot(current, snapshot))
735 throw new DomainError(
736 "The model changed while AI was building. Keep the current model and ask again.",
737 );
738 const edit = aiWorkshopEdit(snapshot, compiled.parts, id, randomUUID);
739 if (edit.changes?.length) {
740 const receipt = await executeInTransaction(c, a, row.target, edit);
741 if (!receipt.accepted)
742 throw new DomainError(
743 receipt.error || "The workshop changed. Please ask again.",
744 );
745 }
746 await c.query(
747 "UPDATE ai_generations SET status='accepted',world=$2,activity='Applied to the workshop',updated_at=clock_timestamp() WHERE id=$1",
748 [id, row.target],
749 );
750 // Title-only updates do not need an exclusive lock on an occupied workshop.
751 if (!snapshot.parts.length)
752 await c.query("UPDATE worlds SET title=$2 WHERE id=$1", [
753 row.target,
754 compiled.blueprint.title,
755 ]);
756 const world = await c.query("SELECT slug FROM worlds WHERE id=$1", [
757 row.target,
758 ]);
759 return world.rows[0];
760 }
761 const world = await insertWorld(c, compiled.blueprint.title, a.guest);
762 const ids = new Map(compiled.parts.map((p) => [p.id, randomUUID()]));
763 const parts = compiled.parts.map((p) => ({
764 id: ids.get(p.id),
765 world: world.id,
766 key: p.key,
767 color: p.color,
768 ...p.position,
769 rotation: p.rotation,
770 revision: 1,
771 deleted: 0,
772 ...bounds(p),
773 }));
774 await c.query(
775 "INSERT INTO part_instances(id,world,key,color,x,y,z,rotation,revision,deleted,minx,miny,minz,maxx,maxy,maxz) SELECT id,world,key,color,x,y,z,rotation,revision,deleted,minx,miny,minz,maxx,maxy,maxz FROM jsonb_to_recordset($1::jsonb) AS p(id uuid,world uuid,key text,color text,x int,y int,z int,rotation int,revision int,deleted int,minx int,miny int,minz int,maxx int,maxy int,maxz int)",
776 [JSON.stringify(parts)],
777 );
778 const edges = compiled.edges.map((e) => ({
779 ...e,
780 id: randomUUID(),
781 world: world.id,
782 a: ids.get(e.a),
783 b: ids.get(e.b),
784 revision: 1,
785 deleted: 0,
786 }));
787 if (edges.length) {
788 await c.query(
789 "INSERT INTO part_connections(id,world,a,b,ca,cb,revision,deleted) SELECT id,world,a,b,ca,cb,revision,deleted FROM jsonb_to_recordset($1::jsonb) AS e(id uuid,world uuid,a uuid,b uuid,ca text,cb text,revision int,deleted int)",
790 [JSON.stringify(edges)],
791 );
792 const claims = edges.flatMap((e) => [
793 ...(e.exclusiveA
794 ? [{ world: world.id, part: e.a, slot: e.ca, connection: e.id }]
795 : []),
796 ...(e.exclusiveB
797 ? [{ world: world.id, part: e.b, slot: e.cb, connection: e.id }]
798 : []),
799 ]);
800 await c.query(
801 "INSERT INTO connector_slot_claims(world,part,slot,connection) SELECT world,part,slot,connection FROM jsonb_to_recordset($1::jsonb) AS c(world uuid,part uuid,slot text,connection uuid)",
802 [JSON.stringify(claims)],
803 );
804 }
805 await c.query(
806 "UPDATE ai_generations SET status='accepted',world=$2,updated_at=clock_timestamp() WHERE id=$1",
807 [id, world.id],
808 );
809 return { slug: world.slug };
810 });
811}