@gtanczyk/diorama 0.1.0 → 0.3.0

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.
Files changed (42) hide show
  1. package/README.md +1 -0
  2. package/app/src/actions/budget.ts +11 -3
  3. package/app/src/actions/cast.ts +19 -0
  4. package/app/src/actions/fix.ts +28 -10
  5. package/app/src/actions/index.ts +1 -0
  6. package/app/src/actions/language.ts +52 -0
  7. package/app/src/actions/world.ts +4 -3
  8. package/app/src/commands/backdrop.ts +23 -3
  9. package/app/src/commands/cast.ts +32 -13
  10. package/app/src/commands/export.ts +17 -0
  11. package/app/src/commands/index.ts +1 -0
  12. package/app/src/commands/language.ts +87 -0
  13. package/app/src/commands/play.ts +5 -1
  14. package/app/src/commands/sound.ts +16 -6
  15. package/app/src/meta/memo.ts +14 -0
  16. package/app/src/meta/voice.ts +2 -2
  17. package/app/src/play/geometry.ts +12 -2
  18. package/app/src/play/parallax.ts +2 -0
  19. package/app/src/scene/cast-fixes.ts +5 -3
  20. package/app/src/scene/cast.ts +16 -9
  21. package/app/src/scene/derive.ts +46 -1
  22. package/app/src/scene/held.ts +62 -8
  23. package/app/src/scene/layers.ts +52 -0
  24. package/app/src/scene/rig.ts +6 -2
  25. package/app/src/scene/shadows.ts +10 -2
  26. package/app/src/scene/verify.ts +12 -0
  27. package/app/src/scene/warp.ts +5 -3
  28. package/app/src/setup/checks.ts +2 -2
  29. package/app/src/speech/transcribe.ts +2 -2
  30. package/app/src/studio/agent.ts +10 -8
  31. package/app/src/studio/repair.ts +1 -1
  32. package/app/src/studio/server.ts +4 -2
  33. package/app/src/world/language.ts +116 -0
  34. package/app/studio/build.tsx +5 -3
  35. package/app/studio/main.tsx +3 -2
  36. package/app/web/living.ts +36 -0
  37. package/app/web/main.ts +83 -30
  38. package/docs/characters.md +1 -1
  39. package/docs/releasing.md +22 -0
  40. package/docs/scenes.md +1 -1
  41. package/docs/setup.md +1 -1
  42. package/package.json +3 -3
@@ -122,11 +122,21 @@ export function hides(o: Occluder, x: number, feetY: number, support?: (key: str
122
122
  return feetY < floorYAt(o, x) - BEHIND_MARGIN;
123
123
  }
124
124
 
125
- /** Column runs [x0, x1) inside [left, right) where the occluder hides the person; a few runs per occluder. */
126
- export function hiddenRuns(o: Occluder, left: number, right: number, feetY: number, support?: (key: string) => Occluder | undefined): Array<[number, number]> {
125
+ /**
126
+ * Column runs [x0, x1) inside [left, right) where the occluder hides the person; a few runs per occluder.
127
+ * With `feetX` the person is one body at one distance: the floor line where their feet are decides for their
128
+ * whole box, so a slanted desk whose near leg is nearer than the feet and far leg farther hides all of them or
129
+ * none, never cuts them in half down one column. Past the occluder's ends its nearest column decides.
130
+ */
131
+ export function hiddenRuns(o: Occluder, left: number, right: number, feetY: number, support?: (key: string) => Occluder | undefined, feetX?: number): Array<[number, number]> {
127
132
  const runs: Array<[number, number]> = [];
128
133
  const x0 = Math.max(Math.floor(left), Math.floor(o.box[0]));
129
134
  const x1 = Math.min(Math.ceil(right), Math.ceil(o.box[2]));
135
+ if (feetX !== undefined) {
136
+ if (x1 <= x0) return runs;
137
+ const at = Math.min(o.box[2] - 0.5, Math.max(o.box[0] + 0.5, feetX));
138
+ return hides(o, at, feetY, support) ? [[x0, x1]] : runs;
139
+ }
130
140
  let start = -1;
131
141
  for (let x = x0; x < x1; x++) {
132
142
  const hid = hides(o, x + 0.5, feetY, support);
@@ -164,6 +164,8 @@ export type Layers = {
164
164
  floats?: Array<{ file: string; box: [number, number, number, number] }>;
165
165
  /** Painted waterfalls to set pouring: each a feathered copy of the fall over `box`. */
166
166
  falls?: Array<{ file: string; box: [number, number, number, number] }>;
167
+ /** Small things painted falling (code rain, snow, petals): what stands out of the paint over `box`, to fall column by column inside `region` (a soft mask). */
168
+ streams?: Array<{ file: string; region: string; box: [number, number, number, number] }>;
167
169
  /** Painted animals as small cards to swim (in the water) or fly (in the air), and which way each faces (1 right). */
168
170
  critters?: Array<{ file: string; box: [number, number, number, number]; medium: 'water' | 'air'; facing: 1 | -1 }>;
169
171
  /** The painted clouds as bands (bottom first) to drift with the wind at their own speeds, cut to `clip` over `box`; `keep`: what stays put in the sky. */
@@ -6,6 +6,8 @@ import type { WorldFiles } from '../world/files.ts';
6
6
 
7
7
  export const CastFixes = z.record(z.string(), z.object({
8
8
  looks: z.string().min(10).optional(),
9
+ /** What they hold, as short SAM phrases ("slice of toast"), kept on the cut-out whatever its size (cast_holds); [] keeps nothing. */
10
+ holds: z.array(z.string().min(2)).max(4).optional(),
9
11
  take: z.number().int().min(0).optional(),
10
12
  /** The person asked for a 3D model (cast_animate) though the story would not build one: the model step builds it every time. */
11
13
  animate: z.boolean().optional(),
@@ -25,7 +27,7 @@ export function readCastFixes(files: WorldFiles): CastFixes {
25
27
  }
26
28
 
27
29
  /** A character with the person's description in place of the world's. */
28
- export function fixedLooks<T extends { key: string; looks: string }>(files: WorldFiles, who: T): T {
29
- const looks = readCastFixes(files)[who.key]?.looks;
30
- return looks ? { ...who, looks } : who;
30
+ export function fixedLooks<T extends { key: string; looks: string }>(files: WorldFiles, who: T): T & { holds?: string[] } {
31
+ const { looks, holds } = readCastFixes(files)[who.key] ?? {};
32
+ return { ...who, ...(looks && { looks }), ...(holds && { holds }) };
31
33
  }
@@ -3,7 +3,7 @@ import { STYLE_REFERENCE_PROMPT } from '../world/style-reference.ts';
3
3
  import sharp from 'sharp';
4
4
  import type { Mask } from '../image/mask.ts';
5
5
  import { maskBox, union } from '../image/raster.ts';
6
- import { bodyShare, heldMask, heldThings } from './held.ts';
6
+ import { bodyShare, groundGaps, heldMask, heldThings } from './held.ts';
7
7
  import { companions, silhouette } from './warp.ts';
8
8
  import type { Memo } from '../meta/memo.ts';
9
9
  import { museEdit, musePaint } from '../meta/muse.ts';
@@ -40,7 +40,10 @@ export async function cutOut(painting: Buffer, mask: Mask, held?: Mask): Promise
40
40
  const { data, info } = await sharp(painting).resize(mask.width, mask.height, { fit: 'fill' }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
41
41
  // SAM's person leaves out what they hold (a lantern, a net of fish) and leaves holes where it hangs over them.
42
42
  // ... and what floats beside them as part of who they are (a heart, the bubble they are in).
43
- const whole = companions(data, silhouette(data, held ? union(mask, held) : mask));
43
+ const body = held ? union(mask, held) : mask;
44
+ const whole = companions(data, silhouette(data, body));
45
+ // Held up in both hands, the thing closes a window of plain ground with the arms and head: it stays see-through.
46
+ if (held) for (const gap of groundGaps(data, whole, body)) gap.bits.forEach((b, i) => b && (whole.bits[i] = 0));
44
47
  for (let i = 0; i < whole.bits.length; i++) if (!whole.bits[i]) data[i * info.channels + 3] = 0;
45
48
  const [x0, y0, x1, y1] = maskBox(whole)!;
46
49
  const figure = await sharp(data, { raw: { width: info.width, height: info.height, channels: 4 } })
@@ -112,13 +115,8 @@ export async function paintFigure(memo: Memo, world: World, who: Who, take = 0,
112
115
  : (from?.styleReference ? await edit({ label: `figure:${who.key}`, prompt: figurePrompt(world, who), images: [], take: t }) : await musePaint(memo, { label: `figure:${who.key}`, prompt: figurePrompt(world, who), take: t }));
113
116
  const png = await sharp(painting).png().toBuffer();
114
117
  // Not every character is a person (a flock of pigeons, a cat): SAM is asked by their own description next.
115
- let found: Awaited<ReturnType<typeof samFind>> = [];
116
- for (const prompt of ['person', who.looks.split(/[,.;]/)[0].trim().split(/\s+/).slice(0, 6).join(' '), 'animal']) {
117
- found = await samFind(memo, { label: `figure:${who.key}`, image: png, prompt });
118
- if (found.length) break;
119
- }
120
- if (!found.length) continue;
121
- const biggest = found.reduce((a, b) => (area(b.mask) > area(a.mask) ? b : a));
118
+ const biggest = await findFigure(memo, who, png);
119
+ if (!biggest) continue;
122
120
  const made = { painting: png, ...(await cutOut(png, biggest.mask, await heldMask(memo, who.key, png, biggest.mask, holds))), holds };
123
121
  const why = (await boxed(made.figure)) ?? (upright ? await notStanding(memo, who.key, made.figure, t) : undefined);
124
122
  if (!why) return made;
@@ -132,6 +130,15 @@ export async function paintFigure(memo: Memo, world: World, who: Who, take = 0,
132
130
  throw new Error(`${who.key}: SAM found no one in the painting, two takes; try another take (cast_redo anotherTake)`);
133
131
  }
134
132
 
133
+ /** The biggest one SAM finds of the character: as a person, else by its own description (a flock of pigeons, a cat), else as an animal. */
134
+ export async function findFigure(memo: Memo, who: Who, png: Buffer) {
135
+ for (const prompt of ['person', who.looks.split(/[,.;]/)[0].trim().split(/\s+/).slice(0, 6).join(' '), 'animal']) {
136
+ const found = await samFind(memo, { label: `figure:${who.key}`, image: png, prompt });
137
+ if (found.length) return found.reduce((a, b) => (area(b.mask) > area(a.mask) ? b : a));
138
+ }
139
+ return undefined;
140
+ }
141
+
135
142
  /**
136
143
  * Why a cut-out of a person on two legs is not one standing whole, or undefined when it is. A standing figure is
137
144
  * about twice as tall as wide (robots and big-headed drawn children down to about 1.4), so only a squatter one is
@@ -5,7 +5,7 @@
5
5
  import { emptyMask, maskArea, type Mask } from '../image/mask.ts';
6
6
  import { dilate, maskBox, polygonMask, rectMask, subtract, union, unionAll } from '../image/raster.ts';
7
7
  import type { Memo } from '../meta/memo.ts';
8
- import type { Geometry } from '../play/geometry.ts';
8
+ import type { GeoThing, Geometry } from '../play/geometry.ts';
9
9
  import type { Place } from '../world/schema.ts';
10
10
  import { FRAME, type Layout } from './layout.ts';
11
11
  import type { Kind } from './locate.ts';
@@ -426,6 +426,51 @@ export async function derive(memo: Memo, input: DeriveIn, log: (line: string) =>
426
426
  const stand = thing.kind === 'walk-on' || thing.kind === 'flat' ? spot(cx, (box[1] + box[3]) / 2) : spot(cx, baseY + 14);
427
427
  return { key: t.key, role: t.role, kind: thing.kind, box, mask: `masks/${t.key}.png`, stand, ...(thing.coarse && { coarse: true }), ...(input.plates?.includes(t.key) && { plate: `plates/${t.key}.png` }) };
428
428
  });
429
+ // Npcs are drawn by the game over the painting: one standing in front of an item or an exit (a scientist
430
+ // before the potion on his table) hides it, and nobody can click it. They step aside along their row, to the
431
+ // nearest reachable spot where they hide little of any.
432
+ type Box = [number, number, number, number];
433
+ const covered = (box: Box, by: GeoThing): number => {
434
+ const t = things.find((m) => m.key === by.key);
435
+ if (!t) return 0;
436
+ const [bx0, by0, bx1, by1] = by.box;
437
+ let [all, hid] = [0, 0];
438
+ for (let y = Math.max(0, Math.floor(by0)); y < Math.min(H, Math.ceil(by1)); y++) for (let x = Math.max(0, Math.floor(bx0)); x < Math.min(W, Math.ceil(bx1)); x++) {
439
+ if (!t.mask.bits[y * W + x]) continue;
440
+ all++;
441
+ if (x >= box[0] && x < box[2] && y >= box[1] && y < box[3]) hid++;
442
+ }
443
+ return all ? hid / all : 0;
444
+ };
445
+ for (const npc of geoThings.filter((t) => t.role === 'npc' && !t.mask)) {
446
+ const foot = npc.box[3];
447
+ const behind = geoThings.filter((t) => (t.role === 'item' || t.role === 'exit') && t.mask && t.box[3] < foot + 4 && t.kind !== 'wall');
448
+ const worst = (box: Box) => Math.max(0, ...behind.map((t) => covered(box, t)));
449
+ if (worst(npc.box) < 0.4) continue;
450
+ const w = npc.box[2] - npc.box[0];
451
+ const cx = (npc.box[0] + npc.box[2]) / 2;
452
+ let moved: Box | undefined;
453
+ for (let d = 16; d <= 480 && !moved; d += 16) for (const x of [cx + d, cx - d]) {
454
+ if (x - w / 2 < 0 || x + w / 2 > W) continue;
455
+ const i = nearestRoomy(grid, x, foot, reached);
456
+ if (i === undefined) continue;
457
+ const [gx, gy] = grid.centre(i);
458
+ if (Math.hypot(gx - x, gy - foot) > 2 * CELL) continue;
459
+ const box: Box = [x - w / 2, npc.box[1], x + w / 2, foot];
460
+ if (worst(box) < 0.15) {
461
+ moved = box;
462
+ break;
463
+ }
464
+ }
465
+ const hidden = behind.filter((t) => covered(npc.box, t) >= 0.4).map((t) => t.key).join(', ');
466
+ if (!moved) {
467
+ flag(`${npc.key}: stands in front of ${hidden} and hides it, with nowhere near to step aside to`);
468
+ continue;
469
+ }
470
+ log(`${npc.key}: steps ${Math.round((moved[0] + moved[2]) / 2 - cx)} px aside so ${hidden} stays in sight`);
471
+ npc.box = moved;
472
+ npc.stand = spot((moved[0] + moved[2]) / 2, foot);
473
+ }
429
474
  for (const t of geoThings) {
430
475
  // Npcs stand where the layout put them; wall things (a ship at sea) may be far from any floor.
431
476
  if (role.get(t.key) === 'npc' || t.kind === 'wall' || t.kind === 'on-top') continue;
@@ -2,8 +2,10 @@
2
2
  // net of fish): named from their description, found by SAM on its own and kept on the cut-out. SAM's "person" is
3
3
  // only the body, and the plain-ground heuristics in warp.ts (silhouette, companions) drop anything bigger than the
4
4
  // figure as the scene behind it, so a prop larger than its holder needs its own mask.
5
+ import sharp from 'sharp';
5
6
  import { emptyMask, maskArea, type Mask } from '../image/mask.ts';
6
- import { dilate, maskBox, subtract, union } from '../image/raster.ts';
7
+ import { components, dilate, maskBox, subtract, union } from '../image/raster.ts';
8
+ import { fillHoles } from './warp.ts';
7
9
  import type { Memo } from '../meta/memo.ts';
8
10
  import { samFind } from '../meta/sam.ts';
9
11
  import { askSparkJson } from '../meta/spark.ts';
@@ -28,24 +30,76 @@ export async function heldThings(memo: Memo, who: { key: string; looks: string;
28
30
 
29
31
  /**
30
32
  * Every instance SAM finds of the held things that touches the figure (or comes within a few percent of its height),
31
- * outside SAM's person, as one mask; undefined when there is none. One SAM call per phrase, memoized with the image.
33
+ * outside SAM's person, as one mask; undefined when there is none. One or two SAM calls per phrase, memoized with the
34
+ * image; when SAM finds none of them, what stands out from the plain ground and touches the body (plainHeld).
32
35
  */
33
36
  export async function heldMask(memo: Memo, key: string, image: Buffer, person: Mask, phrases: string[]): Promise<Mask | undefined> {
34
37
  const box = maskBox(person);
35
38
  if (!box || !phrases.length) return undefined;
36
39
  const near = dilate(person, Math.max(3, Math.round(0.04 * (box[3] - box[1]))));
37
40
  let out: Mask | undefined;
38
- for (const prompt of phrases) {
39
- for (const found of await samFind(memo, { label: `figure:${key}:held`, image, prompt })) {
40
- const own = subtract(found.mask, person);
41
- if (maskArea(own) < 0.01 * maskArea(person)) continue;
42
- if (!own.bits.some((b, i) => b && near.bits[i])) continue;
43
- out = union(out ?? emptyMask(person.width, person.height), own);
41
+ for (const phrase of phrases) {
42
+ // "slice of toast" may find nothing where "toast" does: the head noun is asked next.
43
+ const head = /\bof\b/i.test(phrase) ? phrase.split(/\bof\b/i).pop()!.trim() : phrase.trim().split(/\s+/).pop()!;
44
+ for (const prompt of [...new Set([phrase, head])]) {
45
+ let hit = false;
46
+ for (const found of await samFind(memo, { label: `figure:${key}:held`, image, prompt })) {
47
+ const own = subtract(found.mask, person);
48
+ if (maskArea(own) < 0.01 * maskArea(person)) continue;
49
+ if (!own.bits.some((b, i) => b && near.bits[i])) continue;
50
+ out = union(out ?? emptyMask(person.width, person.height), own);
51
+ hit = true;
52
+ }
53
+ if (hit) break;
44
54
  }
45
55
  }
56
+ if (out) return out;
57
+ const { data } = await sharp(image).resize(person.width, person.height, { fit: 'fill' }).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
58
+ return plainHeld(data, person);
59
+ }
60
+
61
+ /**
62
+ * Without SAM: the figure is painted alone on a plain ground, so what stands out from that ground and touches the
63
+ * body (not the picture's edge) is what they hold. Used when the description says they hold something SAM did not find.
64
+ */
65
+ export function plainHeld(rgba: Buffer, person: Mask, tolerance = 64): Mask | undefined {
66
+ const { width: W, height: H } = person;
67
+ const box = maskBox(person);
68
+ if (!box) return undefined;
69
+ const [, py0, , py1] = box;
70
+ const ground = groundColour(rgba, W, H);
71
+ const ink = emptyMask(W, H);
72
+ for (let i = 0; i < W * H; i++) ink.bits[i] = !person.bits[i] && Math.hypot(rgba[i * 4] - ground[0], rgba[i * 4 + 1] - ground[1], rgba[i * 4 + 2] - ground[2]) > tolerance ? 1 : 0;
73
+ // The outline drawn round a thing is ink too, so the thing and its outline join into one piece.
74
+ const near = dilate(person, 3);
75
+ let out: Mask | undefined;
76
+ for (const c of components(fillHoles(ink))) {
77
+ const b = maskBox(c)!;
78
+ if (b[0] <= 1 || b[1] <= 1 || b[2] >= W - 1 || b[3] >= H - 1) continue;
79
+ if (maskArea(c) < 0.05 * maskArea(person) || !c.bits.some((v, i) => v && near.bits[i])) continue;
80
+ // A patch of floor or shadow at the feet is not held.
81
+ if ((b[1] + b[3]) / 2 > py0 + 0.85 * (py1 - py0)) continue;
82
+ out = union(out ?? emptyMask(W, H), subtract(c, person));
83
+ }
46
84
  return out;
47
85
  }
48
86
 
87
+ /** The patches of plain ground (the picture's border colour) inside `whole` that are no part of `body`, bigger than a speck. */
88
+ export function groundGaps(rgba: Buffer, whole: Mask, body: Mask, tolerance = 40): Mask[] {
89
+ const { width: W, height: H } = whole;
90
+ const ground = groundColour(rgba, W, H);
91
+ const gap = emptyMask(W, H);
92
+ for (let i = 0; i < W * H; i++) gap.bits[i] = whole.bits[i] && !body.bits[i] && Math.hypot(rgba[i * 4] - ground[0], rgba[i * 4 + 1] - ground[1], rgba[i * 4 + 2] - ground[2]) <= tolerance ? 1 : 0;
93
+ return components(gap).filter((c) => maskArea(c) > 0.002 * maskArea(body));
94
+ }
95
+
96
+ const groundColour = (rgba: Buffer, W: number, H: number) => {
97
+ const border: number[][] = [];
98
+ for (let x = 0; x < W; x += 4) for (const y of [0, H - 1]) border.push([...rgba.subarray((y * W + x) * 4, (y * W + x) * 4 + 3)]);
99
+ for (let y = 0; y < H; y += 4) for (const x of [0, W - 1]) border.push([...rgba.subarray((y * W + x) * 4, (y * W + x) * 4 + 3)]);
100
+ return [0, 1, 2].map((c) => border.map((p) => p[c]).sort((a, b) => a - b)[border.length >> 1]);
101
+ };
102
+
49
103
  /** The share of the cut-out's height the body takes, its feet at the bottom: a prop held over the head makes it less than 1. */
50
104
  export function bodyShare(person: Mask, whole: Mask): number {
51
105
  const p = maskBox(person);
@@ -597,6 +597,58 @@ export const FALLING = /\b(water ?falls?|cascades?|falls|weir|spillway|wodospad\
597
597
  export const CRITTER = /\b(fish(es)?|goldfish|carp|trout|salmon|koi|eels?|dolphins?|whales?|seals?|ducks?|ducklings?|swans?|geese|goose|frogs?|birds?|gulls?|seagulls?|sparrows?|crows?|ravens?|pigeons?|doves?|swallows?|owls?|bats?|butterfl(y|ies)|dragonfl(y|ies)|jellyfish|ryb\w*|ptak\w*|mew\w*|kacz\w*|łabęd\w*|wron\w*|motyl\w*)\b/i;
598
598
 
599
599
  export type Fall = { png: Buffer; box: [number, number, number, number] };
600
+ /**
601
+ * Small things painted falling in a stream (code rain, falling letters, snowflakes, petals, sparks): the page
602
+ * sets them falling, each column at its own pace, instead of rippling them like water.
603
+ */
604
+ const STREAM_BITS = String.raw`letters?|code|symbols?|characters?|glyphs?|digits?|numbers?|numerals?|pixels?|bits|sparks?|petals?|leaves|snow\w*|stars?|confetti|runes?|litery|liter\w*|znak\w*|kod\w*|cyfr\w*|płatk\w*|liści\w*|gwiazd\w*|iskr\w*`;
605
+ export const STREAM = new RegExp(String.raw`\b(falling|raining|rain of|shower of|showers of|streams? of|stream of|cascad\w*|curtains? of|spadaj\w*|deszcz\w*)\b[\w\s-]{0,30}?\b(${STREAM_BITS})\b|\b(code|digital|matrix|data) rain\b|\b(${STREAM_BITS})[\s-]+(falling|raining|fall|rain|spadaj\w*)\b`, 'i');
606
+
607
+ export type Stream = Fall & { region: Buffer; backdrop: Buffer };
608
+
609
+ /** How far a stream's mask is closed over the glyphs SAM left out of it, px. */
610
+ const STREAM_CLOSE = 16;
611
+
612
+ /**
613
+ * A painted stream of small falling things, cut out to fall on the page: what stands out of the paint behind it
614
+ * (the glyphs: lighter or more coloured than the median around them) under `mask` is the sheet; the backdrop
615
+ * gets the paint behind them in their place, so no still copy stays under the falling one. `region` is the
616
+ * mask, softened, that the falling sheet is cut to. Undefined when nothing stands out.
617
+ */
618
+ export async function streamSheet(backdrop: Buffer, painted: Mask, keepOut?: Mask): Promise<Stream | undefined> {
619
+ const [W, H]: [number, number] = [FRAME.width, FRAME.height];
620
+ // SAM finds the paint between the glyphs more often than the glyphs: closed, the mask holds them too.
621
+ const closed = dilate(dilate(painted, STREAM_CLOSE), -STREAM_CLOSE);
622
+ const mask = keepOut ? subtract(closed, keepOut) : closed;
623
+ if (maskArea(mask) < 1500) return undefined;
624
+ const rgb = new Uint8Array(await sharp(backdrop).resize(W, H, { fit: 'fill' }).removeAlpha().raw().toBuffer());
625
+ const bg = new Uint8Array(await sharp(rgb, { raw: { width: W, height: H, channels: 3 } }).median(15).raw().toBuffer());
626
+ const glyph = emptyMask(W, H);
627
+ let n = 0;
628
+ for (let i = 0; i < W * H; i++) {
629
+ if (!mask.bits[i]) continue;
630
+ const d = [0, 1, 2].map((c) => rgb[i * 3 + c] - bg[i * 3 + c]);
631
+ const luma = 0.3 * d[0] + 0.59 * d[1] + 0.11 * d[2];
632
+ if (luma > 22 || Math.max(...d.map(Math.abs)) > 45) {
633
+ glyph.bits[i] = 1;
634
+ n++;
635
+ }
636
+ }
637
+ if (n < 400) return undefined;
638
+ const cut = intersect(dilate(glyph, 2), mask);
639
+ const [x0, y0, x1, y1] = boxOf(mask);
640
+ const region = { left: x0, top: y0, width: x1 - x0, height: y1 - y0 };
641
+ const alpha = await sharp(await maskToPng(cut)).blur(0.8).extract(region).extractChannel(0).raw().toBuffer();
642
+ const png = await sharp(rgb, { raw: { width: W, height: H, channels: 3 } }).extract(region).joinChannel(alpha, { raw: { width: region.width, height: region.height, channels: 1 } }).png().toBuffer();
643
+ const soft = await sharp(await maskToPng(mask)).blur(6).extract(region).extractChannel(0).raw().toBuffer();
644
+ const regionPng = await sharp(Buffer.alloc(region.width * region.height * 3, 255), { raw: { width: region.width, height: region.height, channels: 3 } }).joinChannel(soft, { raw: { width: region.width, height: region.height, channels: 1 } }).png().toBuffer();
645
+ // The paint behind the glyphs where they were: the median of the paint around them.
646
+ const out = new Uint8Array(rgb);
647
+ for (let i = 0; i < W * H; i++) if (cut.bits[i]) for (let c = 0; c < 3; c++) out[i * 3 + c] = bg[i * 3 + c];
648
+ const filled = await sharp(out, { raw: { width: W, height: H, channels: 3 } }).png().toBuffer();
649
+ return { png, box: [x0, y0, x1, y1], region: regionPng, backdrop: filled };
650
+ }
651
+
600
652
 
601
653
  /**
602
654
  * A painted waterfall for the page to set pouring: its pixels (from the backdrop) under its mask, feathered, over
@@ -7,7 +7,7 @@ import { emptyMask, maskArea, type Mask } from '../image/mask.ts';
7
7
  import { components, dilate, intersect, maskBox, subtract, union, unionAll } from '../image/raster.ts';
8
8
  import type { Memo } from '../meta/memo.ts';
9
9
  import { samFind } from '../meta/sam.ts';
10
- import { heldMask } from './held.ts';
10
+ import { groundGaps, heldMask } from './held.ts';
11
11
  import { labelPixels, Part, silhouette, warpSheet } from './warp.ts';
12
12
  import type { PartName, Rig } from '../play/rig.ts';
13
13
 
@@ -192,7 +192,9 @@ export async function rigFigure(memo: Memo, key: string, painting: Buffer, style
192
192
  const footless = (m: Mask) => feet.reduce((acc, f) => subtract(acc, f), m);
193
193
  // The lower body without the feet: SAM's trousers with the bare legs below them (rolled-up trousers, shorts,
194
194
  // a skirt), else every leg it found.
195
- const legs = legsFound.map((l) => footless(inPerson(l))).filter((l) => maskArea(l) > H * 4).sort((a, b) => maskArea(b) - maskArea(a));
195
+ const shinsOf = legsFound.map((l) => footless(inPerson(l)));
196
+ // Short legs under big boots (a small figure holding something huge over its head) are allowed half the size.
197
+ const legs = (shinsOf.some((l) => maskArea(l) > H * 4) ? shinsOf.filter((l) => maskArea(l) > H * 4) : shinsOf.filter((l) => maskArea(l) > H * 2)).sort((a, b) => maskArea(b) - maskArea(a));
196
198
  const worn = trousers[0] && inPerson(trousers[0]);
197
199
  const lower = footless(worn ? legs.filter((l) => overlap(dilate(worn, 4), l) > 0).reduce((a, l) => union(a, l), worn) : unionAll(W, Hh, legs));
198
200
  if (maskArea(lower) < H * 4) throw new Error(`${key}: no legs found to rig`);
@@ -320,6 +322,8 @@ export async function rigFigure(memo: Memo, key: string, painting: Buffer, style
320
322
  if (style === 'warp') {
321
323
  // The whole painting, held things and all, each pixel labelled with the part whose bones pull it.
322
324
  const whole = silhouette(data, held ? union(person, held) : person);
325
+ // The window of plain ground a thing held up in both hands closes with the arms stays see-through.
326
+ if (held) for (const gap of groundGaps(data, whole, union(person, held))) gap.bits.forEach((b, i) => b && (whole.bits[i] = 0));
323
327
  const labels = labelPixels(whole, [[Part.Body, person], [Part.FarLeg, far], [Part.NearLeg, near], [Part.FarBoot, farBoot], [Part.NearBoot, nearBoot], [Part.FarArm, farArm], [Part.NearArm, nearArm]], person);
324
328
  const [cw, chh] = placed.size;
325
329
  const image = Buffer.alloc(cw * chh * 4);
@@ -24,6 +24,8 @@ export type Shadows = { mask: Mask; light?: Light; casters: CasterShadow[]; sour
24
24
  /** Darker than this share of the lit floor around it is shadow. */
25
25
  export const SHADOW_DARK = 0.74;
26
26
  const REF_CELL = 16;
27
+ /** Dark floor over more than this share of the floor is its pattern, not shadow. */
28
+ export const PATTERN_SHARE = 0.4;
27
29
  const REF_RADIUS = 6;
28
30
 
29
31
  /** The painting's luma, lightly blurred so plank grain and pebbles don't count. */
@@ -135,8 +137,14 @@ export async function findShadows(memo: Memo, label: string, painting: Buffer, f
135
137
  const contact = centroid(intersect(shadow, touch)) ?? [cx, b.baseY];
136
138
  measured.push({ thing: b.key, px: maskArea(shadow), ...measure(shadow, contact, height) });
137
139
  }
138
- const mask = unionAll(W, H, kept);
139
- const directed = measured.filter((m) => m.dir);
140
+ let mask = unionAll(W, H, kept);
141
+ let directed = measured.filter((m) => m.dir);
142
+ // "Shadow" over much of the floor is the floor's own pattern (a black-and-white checkerboard, dark tiles), not
143
+ // light: painted shadows cover a quarter of it at most. Nobody is darkened there; the light is Spark's.
144
+ if (maskArea(mask) > PATTERN_SHARE * Math.max(1, maskArea(floor))) {
145
+ mask = emptyMask(W, H);
146
+ directed = [];
147
+ }
140
148
  // Dark wet planks next to a teapot look like a shadow too: Spark says whether there is sun at all.
141
149
  const sun = await sparkLight(memo, `light:${label}`, askWith);
142
150
  if (!sun) return { mask: emptyMask(W, H), casters: measured, source: 'none' };
@@ -93,6 +93,10 @@ export function verifyPlace(place: Place, g: Geometry, notes: MaskNotes, plates:
93
93
  // of thing: a doubt about details ("but no long rays in its mask", when the painting has none), not a wrong
94
94
  // mask. Brushing a disc of sky onto the mask to please it only gave the thing a round outline.
95
95
  if (check.box && check.seen && rectIou(check.box, t.box) >= 0.6 && sameKind(check.seen, thing.key, thing.looks)) flags.push({ code: 'MASK_DOUBT', key: thing.key, detail: `Spark sees ${seen} in its mask, where the mask is` });
96
+ // A way out in a wall is cut as the opening its frame holds, and Spark judges the opening by what shows through
97
+ // it (green-code-hall: "a desk and servers seen through the doorway"). When the opening lies inside the box
98
+ // Spark gives the doorway, the mask is the way out as meant: a doubt to look at, not a mask to fix again.
99
+ else if (check.box && thing.role === 'exit' && t.kind === 'wall' && inside(t.box, check.box) >= 0.9) flags.push({ code: 'MASK_DOUBT', key: thing.key, detail: `Spark sees ${seen} in its opening, inside the doorway at [${check.box.join(', ')}]` });
96
100
  // Spark points to where the thing really is: the mask is wrong for sure, whatever the thing's role.
97
101
  else if (check.box) errors.push({ code: 'MASK_WRONG', key: thing.key, detail: `Spark sees ${seen} in its mask; it is at [${check.box.join(', ')}]`, box: check.box });
98
102
  // Spark sees no such thing anywhere, and what it sees is not even the same kind of thing: it was never
@@ -154,3 +158,11 @@ export function verifyPlace(place: Place, g: Geometry, notes: MaskNotes, plates:
154
158
  for (const line of g.flagged ?? []) flags.push({ code: 'DERIVE', detail: line });
155
159
  return { ok: errors.length === 0, errors, flags };
156
160
  }
161
+
162
+ /** How much of rect a lies inside rect b, 0 to 1. */
163
+ function inside(a: readonly number[], b: readonly number[]): number {
164
+ const w = Math.max(0, Math.min(a[2], b[2]) - Math.max(a[0], b[0]));
165
+ const h = Math.max(0, Math.min(a[3], b[3]) - Math.max(a[1], b[1]));
166
+ const area = (a[2] - a[0]) * (a[3] - a[1]);
167
+ return area > 0 ? (w * h) / area : 0;
168
+ }
@@ -32,10 +32,12 @@ export function labelPixels(silhouette: Mask, masks: [Part, Mask][], person?: Ma
32
32
  const ring = dilate(c, 2);
33
33
  ring.bits.forEach((b, i) => b && !c.bits[i] && label[i] && touch.set(label[i], (touch.get(label[i]) ?? 0) + 1));
34
34
  if (!touch.size) continue;
35
- // Held up in both hands (a big slice of toast over the head), it goes with the body: neither arm owns it.
35
+ // Held up in both hands (a big slice of toast over the head), it goes with the body and so do both arms:
36
+ // they carry it, they do not swing away from it.
36
37
  const arms = [Part.NearArm, Part.FarArm].filter((a) => touch.has(a)).sort((a, b) => touch.get(b)! - touch.get(a)!);
37
- const arm = arms.length === 2 && maskArea(c) > 0.5 * maskArea(person) ? Part.Body : arms[0];
38
- const part = arm ?? [...touch].sort((a, b) => b[1] - a[1])[0][0];
38
+ const carried = arms.length === 2 && maskArea(c) > 0.5 * maskArea(person);
39
+ if (carried) label.forEach((l, i) => (l === Part.NearArm || l === Part.FarArm) && (label[i] = Part.Body));
40
+ const part = carried ? Part.Body : arms[0] ?? [...touch].sort((a, b) => b[1] - a[1])[0][0];
39
41
  c.bits.forEach((b, i) => b && (label[i] = part));
40
42
  }
41
43
  }
@@ -55,7 +55,7 @@ export async function runChecks(opts: { live?: boolean } = {}): Promise<Check[]>
55
55
 
56
56
  const muse = await sh('muse', ['--version']);
57
57
  // Other agents the Studio can switch to (genaicode drives them the same way, with the Studio's MCP tools).
58
- const others = await Promise.all([['claude', 'Claude Code'], ['codex', 'Codex']].map(async ([cmd, label]) => ({ label, version: await sh(cmd, ['--version']) })));
58
+ const others = await Promise.all([['claude', 'Claude Code'], ['codex', 'Codex'], ['agy', 'Antigravity']].map(async ([cmd, label]) => ({ label, version: await sh(cmd, ['--version']) })));
59
59
  const found = others.filter((o) => o.version);
60
60
  const install = ['curl -fsSL https://dev.meta.ai/install.sh | bash', 'muse login', 'muse --version'];
61
61
  checks.push(muse
@@ -68,7 +68,7 @@ export async function runChecks(opts: { live?: boolean } = {}): Promise<Check[]>
68
68
  id: 'agents',
69
69
  label: 'Other agents',
70
70
  state: found.length ? 'ok' : 'optional',
71
- detail: `${others.map((o) => (o.version ? `${o.label} ${/\d+\.\d+[\w.-]*/.exec(o.version)?.[0] ?? 'found'}` : `${o.label} not found`)).join(' · ')}. Switch in the agent panel; DIORAMA_AGENT=muse, claude or codex sets the default.`,
71
+ detail: `${others.map((o) => (o.version ? `${o.label} ${/\d+\.\d+[\w.-]*/.exec(o.version)?.[0] ?? 'found'}` : `${o.label} not found`)).join(' · ')}. Switch in the agent panel; DIORAMA_AGENT=muse, claude, codex or antigravity sets the default.`,
72
72
  });
73
73
 
74
74
  let chromium: string | null = null;
@@ -1,6 +1,6 @@
1
1
  // Small provider boundary: the video pipeline only knows PCM in, normalized evidence out.
2
2
  import { metaFileStt } from '../meta/voice-file.ts';
3
- import { inputHash, type Memo } from '../meta/memo.ts';
3
+ import { inputHash, MUSE_VOICE, type Memo } from '../meta/memo.ts';
4
4
  import { Transcript, type SpeechOptions, type SttProvider } from './types.ts';
5
5
  export { type SttProvider, type SpeechOptions, Transcript } from './types.ts';
6
6
  export const defaultStt = metaFileStt;
@@ -28,7 +28,7 @@ export async function transcribeFile(memo: Memo, label: string, pcm: Buffer, opt
28
28
  const saved = await memo.remember('voice', label, hash, 'json', async () => {
29
29
  const request = (lanes.get(lane) ?? Promise.resolve()).catch(() => {}).then(() => provider.transcribe(pcm, options));
30
30
  lanes.set(lane, request);
31
- try { return Buffer.from(JSON.stringify(check(await request))); }
31
+ try { return { data: Buffer.from(JSON.stringify(check(await request))), via: MUSE_VOICE }; }
32
32
  finally { if (lanes.get(lane) === request) lanes.delete(lane); }
33
33
  });
34
34
  return check(JSON.parse(saved.toString('utf8')));
@@ -5,7 +5,7 @@
5
5
  import { randomBytes } from 'node:crypto';
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
- import { claude, codexLive, createAgentSession, detectAgents, museLive, type CodingAgent, withoutProviderCredentials, type AgentSession, type ApprovalDecision, type ApprovalRequest, type SessionState, type SessionTurn } from 'genaicode/agents';
8
+ import { antigravity, claude, codexLive, createAgentSession, detectAgents, museLive, type CodingAgent, withoutProviderCredentials, type AgentSession, type ApprovalDecision, type ApprovalRequest, type SessionState, type SessionTurn } from 'genaicode/agents';
9
9
  import { configDir, redact, withoutSecrets } from '../secrets.ts';
10
10
  import type { Events } from './events.ts';
11
11
  import { History } from './history.ts';
@@ -24,13 +24,14 @@ When the person adds pictures and asks to expand this existing game, inspect eac
24
24
  During a staged extension, the log describes work in a private copy: it is not in the game yet. A successful job_wait call may still return state running; report the actual job state and current work, never call it complete or playable until the job says done and the checks have been inspected. The progress display reports build milestones, not an assessment of visual quality or an actual playthrough.
25
25
  When a job seems slow or the person asks what it is doing, call job_inspect for timestamped activity, how long it has been quiet, locally observed operations, and voice/sound counts and failures. job_wait returns a shorter version too. Say what is actually observed, including failed or missing lines; an individual failed attempt can be retried, so distinguish it from a failed job or an item that stayed missing. A long-running local request or quiet log alone does not prove the provider is stuck. job_cancel can stop a running or queued job when the person asks; stopping can discard staged work and does not undo paid calls. Do not cancel just because the log is quiet.
26
26
  To fix a place use the fix tools, which are kept across rebuilds: mask_fix (a better SAM phrase, the real box, or the kind of a thing), floor_cells, mask_brush, stand_set, repaint_region (costs a Muse edit), paint_words (how the place, its things and floors are described to the painter); corrections_get shows what is fixed already, corrections_clear takes fixes back. When asked to go through the person's notes, read feedback_pending, fix each one and close it with feedback_done in one sentence. Check budget before a rebuild of many places.
27
+ When the person wants the game in another language ("make it English", "po polsku"), call world_language: it translates the title, names and the whole story in one pass and casts and records the voices again as native speakers; first without go, tell them what it redoes and what the voices cost, then call it with go true once they agree (voices false when they only want the text now). Never translate it line by line with story_text, and never say the language cannot be changed.
27
28
  When the person wants the game to look different (more realistic, watercolour, like a picture book, less cartoon), call style_set with the style in a few words (medium, palette, light; scope place or cast for only one place or the characters): first without go, tell them what it repaints and about what it costs, then call it with go true once they agree. It repaints each picture keeping where everything is, so masks and their fixes still fit; children's drawings stay the reference; history_undo takes it back. Never write world.json's style by hand.
28
29
  Before a risky change, say what you will do; history_undo can take back a job. Respect locks. Keys are never yours: if a key is missing, ask the person to run \`diorama setup\` in a terminal.
29
- Read files freely to find out why something failed, but do not edit world files or run commands that change them: make every change through the diorama MCP tools, so the person sees it live, can undo it, and it survives the next build (a hand edit is overwritten by the next build). If no tool can make a change you need, say so and describe the tool that is missing instead of working around it. Start from world_status, place_status, place_view, job_wait, corrections_get and feedback_pending: place_view shows you a place as a picture (layer walk, masks or painting), which files and the shell cannot. Reach for the shell only when no Studio tool answers the question.
30
- When a build fails for another reason (a step that broke, a service that did not answer), the Studio wakes you with the error and the job's last lines: job_inspect it, give a service error (HTTP 5xx, a timeout, a busy Space) one job_retry, which picks up at the failed step, and fix anything else with that step's own tool; never retry the same error twice, tell the person instead. A character the 3D service left in 2D (cast_status: the 3D service did not answer) still plays with its 2D rig; cast_animate tries its model again once the service is back. When a build leaves places not playable, repair them one by one: place_status lists each error with its playbook (where to look, the fix tools in order, the last resort), and place_view shows you the walkable floor with the 60 px cells floor_cells takes, the gaps to bridge and the spots off the floor. An unreached patch where nothing is floor (a wall, the sky) is taken back, not bridged: corrections_clear the fix that made it, or mask_brush erase. Try the tools in that order; each fix rebuilds only that place, so read place_status again after its job ends. Stop after three fixes that did not change the error, and tell the person what you tried and what you would do next. Ask before the last resort, except one repaint_region per place.
30
+ Read files freely to find out why something failed, but do not edit world files or run commands that change them: make every change through the diorama MCP tools, so the person sees it live, can undo it, and it survives the next build (a hand edit is overwritten by the next build). When no single tool makes the change the person asks for, do not stop at "there is no tool": find the nearest way with the tools you have (several story_text calls, a story_redo with their wish, a run_step) and offer it with what it costs, using ask_person; mention the missing tool only as a side note, so it can be added later. Refuse only what would need a hand edit or would throw away their work. Start from world_status, place_status, place_view, job_wait, corrections_get and feedback_pending: place_view shows you a place as a picture (layer walk, masks or painting), which files and the shell cannot. Reach for the shell only when no Studio tool answers the question.
31
+ When a build fails for another reason (a step that broke, a service that did not answer), the Studio wakes you with the error and the job's last lines: job_inspect it, give a service error (HTTP 5xx, a timeout, a busy Space) one job_retry, which picks up at the failed step, and fix anything else with that step's own tool; never retry the same error twice, tell the person instead. A character the 3D service left in 2D (cast_status: the 3D service did not answer) still plays with its 2D rig; cast_animate tries its model again once the service is back. When a build leaves places not playable, repair them one by one: place_status lists each error with its playbook (where to look, the fix tools in order, the last resort), and place_view shows you the walkable floor with the 60 px cells floor_cells takes, the gaps to bridge and the spots off the floor. An unreached patch where nothing is floor (a wall, the sky) is taken back, not bridged: corrections_clear the fix that made it, or mask_brush erase. Try the tools in that order; each fix rebuilds only that place, so read place_status again after its job ends. After three fixes that did not change the error, do not repeat one that failed: look again with place_view and take a different path (mask_brush by hand, floor_cells, thing_remove, corrections_clear); the fix tools refuse an exact repeat, and after six they keep repaints and relayouts for the person. If the new path fails too, tell the person briefly what you tried and what you would do next. Ask before the last resort, except one repaint_region per place.
31
32
  When layout failed and there is no picture, do not wait for place_view: inspect place_status errors, then call layout_fix with concrete layout guidance, or place_fix to resume. Both work before the place directory exists. Failed layout batches retain their diagnostics and retry with new feedback instead of replaying the same rejected batch. When paint fails with content_policy_violation, the image safety filter refused a word, not the picture: paint already lets Spark reword the place twice, so call paint_words with calm, plain words for the scene and the looks the brief had (leafless, not bare; a seat that rests, not hangs on chains; no children, blood or weapons), never an edit of world.json. A place that never got past a step is rebuilt from that step: place_fix (the Fix it button on its card) or job_retry does that by itself.
32
33
  Stairs: derive finds the steps of floors and walk-on things named as stairs (stair, step, schody), and people then step from tread to tread; place_view (layer walk) draws the steps it found in blue. Scale: derive measures how tall a person is at each spot (Spark's people, held against a door on the floor: a person by a door is about 0.8 of its height). When the hero looks far too small or too big next to a door, run_step derive with that place, which rebuilds it through verify; when it stays wrong, the door is not named as a door: give it a door phrase with mask_fix. When people glide up stairs as on a ramp, the stairs thing or floor is not named as stairs: give it a stairs phrase with mask_fix (for example "stone stairs"), which rebuilds the place.
33
- A message that starts with "[On screen: …]" says what the person had open in Studio as they wrote ("place", "place / thing", "cast", "cast / character" or "cast / item key"; older messages say "[Looking at: …]"): when they say "this", "it" or "here" without a name, they mean that; look at it (place_view for a place) before you change it. Never mention the prefix. A message that starts with "[Pictures: studio/pictures/01.jpg, …]" comes with pictures the person pasted, uploaded or took with the webcam: look at each with picture_view before you answer, and act on what they show. When the person is playing and your change shows in the game, call play_reload yourself rather than asking them to refresh. You cannot watch the game, but place_motion can: after a change to motion (water flow, fog, fire, weather, an animated thing) call it and check the motion shows before you say it works. A message that starts with "[Studio]" is a private note from the Studio, not from the person: follow it, never mention it or reply to it. The story has story_status, story_text (rewording) and story_redo (a wish to Spark); story_status lists unanswerable questions (a question in a "say" or in a line without choices leaves the player stuck): reword it into a statement with story_text, or story_redo when it needs real answers; it also lists unseen story parts (an item thing whose item has another key stays in the painting; a change on a person is never drawn): fix those with story_redo; the cast has cast_status, cast_redo, cast_animate, cast_rewalk and voice_set; speaking faces have faces_status and faces_prepare. Talking mouths can be off in Setup (faces_get; off by default): then never prepare, repair or calibrate faces and never offer to; characters speak with voice and gestures. Free fixes before paid ones: a 3D figure whose face shows as a patch of another colour, or whose colours look pale or plastic beside its painting, is a render matter; run sprites again (free for UV sprites, no Muse) before ever offering sprites_redo or per-frame Muse repaints, and when you do offer paid work say the real count, not a range. Order: a playable game first, talking mouths last. While any place is unpainted, being built or unplayable, never start face work (faces_prepare, face_frame_repair, face_lips_set, face_calibration_set refuse it); repair the places, and leave lips for after everything plays, or skip them: characters talk with gestures. A failed speaking animation is separate from game readiness; recordings and the previous appearance remain usable. Inspect coverage and repairWork first. Accepted atlases and calibrated mouths are saved, so resume rather than repainting the whole character. For a rejected mouth, faces_inspect with its work id and mouth returns the exact head and reference; face_frame_repair uses the returned revision and concrete visual guidance to edit ONLY that mouth, then revalidate the atlas. For an accepted atlas with uncertain lip corners, inspect the exact mouth image with faces_inspect and use face_lips_set with a normalized tight lip box relative to that single full-head image (not the whole atlas). Never guess coordinates, use it on rejected articulation, or lower validation thresholds. Both tools resume preparation and reject stale revisions/sources. Wait for the job, inspect faces_status again and play_reload after success. Do not repeat an unchanged failed repair; inspect the new stage and use its matching tool. For source-pose or final-patch calibration failures, face_calibration_inspect lists pending targets and shows their exact close-up. Use face_calibration_set with its target, revision, imageHash, tight lip box and visible-cavity open flag. This preserves accepted artwork and resumes the remaining checks. If an inspected mouth remains genuinely ambiguous, stop and explain that specific uncertainty rather than inventing coordinates. Image, 2D rig and talk-sprite faces share audio timing. 3D models articulate when model3d.mouth is true: method morphs uses authored facial poses, painted-surfaces animates calibrated face paint on the actual mesh. Check the reported view coverage and spritePoses pending count; a body skeleton alone does not articulate. Do not claim native mouth geometry for the painted-surface method; a 3D figure that walks straddle-legged with arms held out to the sides (like a zombie) or hands sticking out gets cast_relax (local Blender, free; blender_get says if it is there, else tell the person to install Blender and turn it on in Setup); a walk that tears (holes in clothes, a leg, boot or arm coming off, a lantern left hanging in the air) gets cast_rewalk, not cast_redo; a character with no 3D model the person explicitly wants animated in 3D (a creature, cast_status body upright false, or an NPC with no lines) gets a model with cast_animate, never a cast_redo that makes it stand on two legs: a creature hops, squashes and blinks as one body, then play_reload; a hero painted sitting, lying or with furniture grown into the 3D model (from a photo where they sat or lay) gets cast_redo with looks that describe only the person standing (clothes, trousers, shoes; no pose, bed or "not visible"), then the model again; inventory icons have icons_status, icon_redo (a hint in the person's words, cut or paint, another take) and icon_fix_clear, never a swapped file in items/. Voices are cast from the gender and age Spark sees in each figure: adults get stock voices, children, teens and the old get a voice made for them by ElevenLabs Voice Design (voice "design"). When one sounds wrong, voice_list with slug and key lists the voices that fit that character first; voice_set with voice "design" and a design description in English remakes a designed voice (no word "child" or age in years there: ElevenLabs refuses it). Never give a child an adult's voice or raise an adult voice's pitch to fake one. A character whose voice is "pending-design" in cast_status waits for Voice Design (it was refused or the service was busy): run_step voices or voice_set designs it again; never give them a stock adult instead. Lines with numbers or sums ("10+10=20") are read and checked as words by themselves; voiceFailures lists only lines the story still has. For one missing or rejected line, use voice_retry with slug, key and the exact text from voiceFailures: it keeps the selected voice and every other recording, gives rejected takes fresh seeds, and resumes saved audio after a transcription outage. Do not change voice_set merely to retry a line. Sounds have sound_status (each bed, loop, footstep, one-shot and music: made, or rejected and why) and sound_redo (ids, an optional hint in English, kept across rebuilds): a sound rejected as "mostly hiss" or "nearly silent" stays silent in the game until sound_redo, never an edited sound.json. cast_status says how the game moves each character (moves), why there is no 2D walk (rigIssue) and which walk directions left the pose (spriteIssues): those get sprites_redo, which paints new sheets without repainting the character; a character with no model after flat reconstructions walks with its 2D rig or slides as a cut-out, and cast_animate tries the model again. When the hero starts in front of an NPC or a thing and hides it, hero_start_set moves where they begin; npc_move changes the NPC standing position in the layout. Author a story-triggered trip with story_redo. A still frame in place_motion is a fault only when inTheGame lists water, mist or weather for that place.
34
+ A message that starts with "[On screen: …]" says what the person had open in Studio as they wrote ("place", "place / thing", "cast", "cast / character" or "cast / item key"; older messages say "[Looking at: …]"): when they say "this", "it" or "here" without a name, they mean that; look at it (place_view for a place) before you change it. Never mention the prefix. A message that starts with "[Pictures: studio/pictures/01.jpg, …]" comes with pictures the person pasted, uploaded or took with the webcam: look at each with picture_view before you answer, and act on what they show. When the person is playing and your change shows in the game, call play_reload yourself rather than asking them to refresh. You cannot watch the game, but place_motion can: after a change to motion (water flow, fog, fire, weather, an animated thing) call it and check the motion shows before you say it works. A message that starts with "[Studio]" is a private note from the Studio, not from the person: follow it, never mention it or reply to it. The story has story_status, story_text (rewording) and story_redo (a wish to Spark); story_status lists unanswerable questions (a question in a "say" or in a line without choices leaves the player stuck): reword it into a statement with story_text, or story_redo when it needs real answers; it also lists unseen story parts (an item thing whose item has another key stays in the painting; a change on a person is never drawn): fix those with story_redo; the cast has cast_status, cast_redo, cast_animate, cast_rewalk, cast_holds and voice_set; a figure whose cut-out lost what it holds or carries (a toast over its head, a lantern, a basket; cast_status cut.holds lists what is kept) gets cast_holds, not cast_redo: it cuts the same painting again with the held thing; speaking faces have faces_status and faces_prepare. Talking mouths can be off in Setup (faces_get; off by default): then never prepare, repair or calibrate faces and never offer to; characters speak with voice and gestures. Free fixes before paid ones: a 3D figure whose face shows as a patch of another colour, or whose colours look pale or plastic beside its painting, is a render matter; run sprites again (free for UV sprites, no Muse) before ever offering sprites_redo or per-frame Muse repaints, and when you do offer paid work say the real count, not a range. Order: a playable game first, talking mouths last. While any place is unpainted, being built or unplayable, never start face work (faces_prepare, face_frame_repair, face_lips_set, face_calibration_set refuse it); repair the places, and leave lips for after everything plays, or skip them: characters talk with gestures. A failed speaking animation is separate from game readiness; recordings and the previous appearance remain usable. Inspect coverage and repairWork first. Accepted atlases and calibrated mouths are saved, so resume rather than repainting the whole character. For a rejected mouth, faces_inspect with its work id and mouth returns the exact head and reference; face_frame_repair uses the returned revision and concrete visual guidance to edit ONLY that mouth, then revalidate the atlas. For an accepted atlas with uncertain lip corners, inspect the exact mouth image with faces_inspect and use face_lips_set with a normalized tight lip box relative to that single full-head image (not the whole atlas). Never guess coordinates, use it on rejected articulation, or lower validation thresholds. Both tools resume preparation and reject stale revisions/sources. Wait for the job, inspect faces_status again and play_reload after success. Do not repeat an unchanged failed repair; inspect the new stage and use its matching tool. For source-pose or final-patch calibration failures, face_calibration_inspect lists pending targets and shows their exact close-up. Use face_calibration_set with its target, revision, imageHash, tight lip box and visible-cavity open flag. This preserves accepted artwork and resumes the remaining checks. If an inspected mouth remains genuinely ambiguous, stop and explain that specific uncertainty rather than inventing coordinates. Image, 2D rig and talk-sprite faces share audio timing. 3D models articulate when model3d.mouth is true: method morphs uses authored facial poses, painted-surfaces animates calibrated face paint on the actual mesh. Check the reported view coverage and spritePoses pending count; a body skeleton alone does not articulate. Do not claim native mouth geometry for the painted-surface method; a 3D figure that walks straddle-legged with arms held out to the sides (like a zombie) or hands sticking out gets cast_relax (local Blender, free; blender_get says if it is there, else tell the person to install Blender and turn it on in Setup); a walk that tears (holes in clothes, a leg, boot or arm coming off, a lantern left hanging in the air) gets cast_rewalk, not cast_redo; a character with no 3D model the person explicitly wants animated in 3D (a creature, cast_status body upright false, or an NPC with no lines) gets a model with cast_animate, never a cast_redo that makes it stand on two legs: a creature hops, squashes and blinks as one body, then play_reload; a hero painted sitting, lying or with furniture grown into the 3D model (from a photo where they sat or lay) gets cast_redo with looks that describe only the person standing (clothes, trousers, shoes; no pose, bed or "not visible"), then the model again; inventory icons have icons_status, icon_redo (a hint in the person's words, cut or paint, another take) and icon_fix_clear, never a swapped file in items/. Voices are cast from the gender and age Spark sees in each figure: adults get stock voices, children, teens and the old get a voice made for them by ElevenLabs Voice Design (voice "design"). When one sounds wrong, voice_list with slug and key lists the voices that fit that character first; voice_set with voice "design" and a design description in English remakes a designed voice (no word "child" or age in years there: ElevenLabs refuses it). Never give a child an adult's voice or raise an adult voice's pitch to fake one. A character whose voice is "pending-design" in cast_status waits for Voice Design (it was refused or the service was busy): run_step voices or voice_set designs it again; never give them a stock adult instead. Lines with numbers or sums ("10+10=20") are read and checked as words by themselves; voiceFailures lists only lines the story still has. For one missing or rejected line, use voice_retry with slug, key and the exact text from voiceFailures: it keeps the selected voice and every other recording, gives rejected takes fresh seeds, and resumes saved audio after a transcription outage. Do not change voice_set merely to retry a line. Sounds have sound_status (each bed, loop, footstep, one-shot and music: made, or rejected and why) and sound_redo (ids, an optional hint in English, kept across rebuilds): a sound rejected as "mostly hiss" or "nearly silent" stays silent in the game until sound_redo, never an edited sound.json. cast_status says how the game moves each character (moves), why there is no 2D walk (rigIssue) and which walk directions left the pose (spriteIssues): those get sprites_redo, which paints new sheets without repainting the character; a character with no model after flat reconstructions walks with its 2D rig or slides as a cut-out, and cast_animate tries the model again. When the hero starts in front of an NPC or a thing and hides it, hero_start_set moves where they begin; npc_move changes the NPC standing position in the layout. Author a story-triggered trip with story_redo. A still frame in place_motion is a fault only when inTheGame lists water, mist or weather for that place.
34
35
  When you need the person to decide (yes or no, which of two fixes, go ahead with something that costs calls), ask with ask_person instead of a question in your text: it shows them buttons; then end your turn.
35
36
  After a redo the person asked for (a repaint, a recast), show them the result and stop: if a trace of what they wanted gone is still faintly there, say so and offer one more try with ask_person; never start another paid redo on your own. A message from the person while you wait for a job comes first: read it before waiting again, and job_cancel the job if they no longer want it.
36
37
  Answer in two or three short sentences, in the language the person wrote their newest message in (not the world's language, not an earlier turn's); the steps already show what you did.`;
@@ -50,7 +51,7 @@ export function studioTool(request: ApprovalRequest): boolean {
50
51
  const detail = (request.detail ?? {}) as { subject?: { kind?: string } };
51
52
  if (['shell', 'process', 'fileAccess'].includes(String(detail.subject?.kind))) return false;
52
53
  const text = JSON.stringify(detail);
53
- return /"mcp__diorama__[a-z_]+"/.test(text) || /"(server|serverName|mcpServer)"\s*:\s*"diorama"/.test(text);
54
+ return /"mcp__?diorama__?[a-z_]+"/.test(text) || /"(server|serverName|mcpServer)"\s*:\s*"diorama"/.test(text);
54
55
  }
55
56
 
56
57
  /**
@@ -70,9 +71,9 @@ export function readsOnly(request: ApprovalRequest): boolean {
70
71
 
71
72
  type Call = { turn?: number; name: string; args: Record<string, unknown>; done: boolean; ok?: boolean; summary?: string };
72
73
 
73
- /** A Studio tool's own name, however the agent spells it (mcp__diorama__job_wait, diorama.job_wait). */
74
+ /** A Studio tool's own name, however the agent spells it (mcp__diorama__job_wait, Antigravity's mcp_diorama_job_wait, diorama.job_wait). */
74
75
  export function toolName(name: string): string | undefined {
75
- return /^(?:mcp__diorama__|diorama[.:_/]+)(\w+)$/.exec(name)?.[1];
76
+ return /^(?:mcp__?diorama__?|diorama[.:_/]+)(\w+)$/.exec(name)?.[1];
76
77
  }
77
78
 
78
79
  /** A tool's result in one line for the panel: a job by its name and state, else the result itself, short. */
@@ -224,7 +225,7 @@ class Talk {
224
225
  // A turn's entries only grow, so a turn and a place in it name an entry.
225
226
  if (entry.kind === 'tool' && !this.tools.has(`${turn.id}:${i}`)) {
226
227
  this.tools.add(`${turn.id}:${i}`);
227
- this.publish('tool', { name: entry.name.replace(/^mcp__diorama__/, '') });
228
+ this.publish('tool', { name: toolName(entry.name) ?? entry.name });
228
229
  // The shell sees files, not the pictures the Studio's tools show: after a few shell calls in a turn,
229
230
  // the agent is reminded once which tools look for it. It is still let through.
230
231
  if (shellTool(entry.name) && ++this.shell === NUDGE_AFTER) {
@@ -301,6 +302,7 @@ export const AGENTS = {
301
302
  muse: { label: 'Muse Code', make: (command?: string) => museLive({ command: command ?? process.env.DIORAMA_MUSE_COMMAND ?? 'muse' }) },
302
303
  claude: { label: 'Claude Code', make: () => claude() },
303
304
  codex: { label: 'Codex', make: () => preapproved(codexLive()) },
305
+ antigravity: { label: 'Antigravity', make: () => antigravity({ command: process.env.DIORAMA_AGY_COMMAND ?? 'agy' }) },
304
306
  } satisfies Record<string, { label: string; make(command?: string): CodingAgent }>;
305
307
  export type AgentName = keyof typeof AGENTS;
306
308
  export const isAgentName = (name: string): name is AgentName => Object.hasOwn(AGENTS, name);
@@ -19,7 +19,7 @@ export function repairPrompt(job: Job): string {
19
19
  if (job.unplayable?.length) {
20
20
  const places = job.unplayable.map((u) => `- ${u.place}: ${u.errors.join('; ') || 'see place_status'}`).join('\n');
21
21
  return `[Studio] The build "${job.label}" ended with places that are not playable, and its free fixes did not help:\n${places}\n`
22
- + 'Repair them as your brief says: place_status and place_view first, then the playbook\'s fix tools in order, at most three fixes a place, '
22
+ + 'Repair them as your brief says: place_status and place_view first, then the playbook\'s fix tools in order, after three failed fixes of a place take a different path rather than repeating one, '
23
23
  + 'and ask me before the last resort. Then tell me in two sentences what you fixed and what is left for me.' + animation;
24
24
  }
25
25
  const tail = job.tail.slice(-15).map((l) => ` ${l}`).join('\n');
@@ -3,6 +3,7 @@
3
3
  // Referer), the Host must be ours (no DNS rebinding), cross-site requests are refused (Origin and
4
4
  // Sec-Fetch-Site), writes are JSON only and no CORS header is ever sent. World files are served to <img>
5
5
  // with a SameSite=Strict cookie the page gets in exchange for the token.
6
+ import { callVia } from '../meta/memo.ts';
6
7
  import { randomBytes, timingSafeEqual } from 'node:crypto';
7
8
  import fs from 'node:fs';
8
9
  import http from 'node:http';
@@ -119,8 +120,9 @@ class WorldWatch {
119
120
  for (const line of text.slice(0, complete).split('\n')) {
120
121
  if (!line) continue;
121
122
  try {
122
- const { model, label, ms, hit, via } = JSON.parse(line) as Record<string, unknown>;
123
- this.events.publish('call', { world: this.slug, model, label, ms, hit, via });
123
+ const call = JSON.parse(line) as Record<string, unknown>;
124
+ const { model, label, ms, hit } = call;
125
+ this.events.publish('call', { world: this.slug, model, label, ms, hit, via: callVia(this.dir, call as { model: string; hash?: string; via?: unknown }) });
124
126
  } catch {}
125
127
  }
126
128
  }