@kriya-ai/harness 0.2.4 → 2.0.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 (134) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +49 -0
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +504 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +376 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +426 -0
  33. package/plugins/runstrip/index.js +301 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +82 -5
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +175 -3
  44. package/src/edit/core/plan.js +95 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/transitions.js +17 -0
  51. package/src/edit/core/type-kit.js +173 -0
  52. package/src/edit/director/ask.js +37 -3
  53. package/src/edit/director/assembly.js +829 -0
  54. package/src/edit/director/continuity.js +137 -0
  55. package/src/edit/director/custom-motion.js +88 -0
  56. package/src/edit/director/graphics.js +186 -0
  57. package/src/edit/director/intent.js +125 -0
  58. package/src/edit/director/mentions.js +52 -0
  59. package/src/edit/director/plan.js +89 -12
  60. package/src/edit/director/revise.js +172 -7
  61. package/src/edit/director/viewer.js +136 -0
  62. package/src/edit/director/watch-fix.js +119 -0
  63. package/src/edit/engine/captions.js +110 -5
  64. package/src/edit/engine/confine.js +81 -4
  65. package/src/edit/engine/custom.js +243 -0
  66. package/src/edit/engine/dna2.js +893 -0
  67. package/src/edit/engine/fonts.js +218 -0
  68. package/src/edit/engine/graphics.js +439 -0
  69. package/src/edit/engine/index.js +14 -5
  70. package/src/edit/engine/motion.js +153 -14
  71. package/src/edit/engine/music-bed.js +59 -1
  72. package/src/edit/engine/packs.js +11 -0
  73. package/src/edit/engine/reference2.js +26 -0
  74. package/src/edit/engine/sfx.js +56 -1
  75. package/src/edit/engine/tool.js +21 -5
  76. package/src/edit/gates/assembly.js +194 -0
  77. package/src/edit/gates/copy.js +7 -4
  78. package/src/edit/gates/index.js +76 -8
  79. package/src/edit/gates/picture.js +6 -3
  80. package/src/edit/gates/reference.js +115 -0
  81. package/src/edit/gates/tile.js +96 -0
  82. package/src/edit/host/client.js +4 -3
  83. package/src/edit/host/clips.js +33 -0
  84. package/src/edit/host/jobs.js +9 -3
  85. package/src/edit/host/layers.js +134 -0
  86. package/src/edit/host/main.js +17 -7
  87. package/src/edit/host/paths.js +34 -3
  88. package/src/edit/host/preview.js +108 -0
  89. package/src/edit/host/projects.js +494 -29
  90. package/src/edit/host/server.js +263 -19
  91. package/src/edit/host/tavi.js +77 -0
  92. package/src/edit/loop/make.js +44 -3
  93. package/src/edit/recipes/assembly.js +352 -0
  94. package/src/edit/recipes/graphic-clips.js +59 -0
  95. package/src/edit/recipes/openings.js +36 -0
  96. package/src/edit/recipes/reel.js +138 -17
  97. package/src/edit/recipes/reference-look.js +29 -0
  98. package/src/edit/recipes/short-from-long.js +3 -3
  99. package/src/edit/recipes/sound.js +71 -0
  100. package/src/edit/runtime/cli.js +26 -5
  101. package/src/edit/runtime/fetch.js +4 -3
  102. package/src/edit/runtime/licences.js +7 -1
  103. package/src/explore.js +103 -0
  104. package/src/failure.js +1 -1
  105. package/src/gate-commands.js +114 -0
  106. package/src/gates/api.js +127 -0
  107. package/src/gates/commands.js +111 -0
  108. package/src/gates/detectors.js +370 -0
  109. package/src/gates/http.js +62 -0
  110. package/src/gates/index.js +196 -0
  111. package/src/gates/page.js +264 -0
  112. package/src/gates/sast.js +64 -0
  113. package/src/gates/stack.js +110 -0
  114. package/src/gates/tenant.js +162 -0
  115. package/src/gates/three.js +407 -0
  116. package/src/gates/ui.js +111 -0
  117. package/src/launch.js +15 -3
  118. package/src/loop.js +199 -7
  119. package/src/mcp.js +126 -0
  120. package/src/milestones.js +188 -0
  121. package/src/modes.js +32 -0
  122. package/src/orchestra.js +43 -0
  123. package/src/outcomes.js +88 -0
  124. package/src/profiles.js +5 -0
  125. package/src/receipts.js +238 -0
  126. package/src/release.js +356 -0
  127. package/src/runstrip.js +122 -0
  128. package/src/stack.js +120 -0
  129. package/src/verify.js +67 -20
  130. package/studio/dist/fonts/fraunces.woff2 +0 -0
  131. package/studio/dist/fonts/geist.woff2 +0 -0
  132. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  133. package/studio/dist/studio.css +452 -3
  134. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,211 @@
1
+ // The style brief (TP6, CRAFT_UPGRADE §4.2–4.4, EDD-65), behind editing.referenceIntent: an Edit
2
+ // DNA 2 turned into what Kriya can really do, one line per trait, each `matched`, `nearest` (with
3
+ // the reason in plain words) or `cannot`. The person unticks any line before the make.
4
+ // A reference sets the method; the gates set the floor (§4.3). Where they disagree the gate wins
5
+ // and the line says so: a reference never lowers contrast, loudness, cut hygiene or safe zones.
6
+ // Pure code over numbers and fixed words: no model, no text from the reference (there is none in
7
+ // a DNA). Every sentence here is written by this file.
8
+
9
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
10
+ const one = (v) => (Math.round(v * 10) / 10).toFixed(1)
11
+
12
+ export const TRAIT_IDS = ["pace", "joins", "zooms", "captions", "graphics", "colour", "grain", "corners", "bars", "music", "loudness", "opening", "format"]
13
+ // The floor the gates hold, whatever a reference does (QUALITY_GATES; CRAFT §4.3)
14
+ export const FLOOR = {
15
+ hold: 1.0, // seconds a picture stays at least: shorter cuts into words (cut hygiene, QG-05)
16
+ contrast: 4.5, // QG-09
17
+ lufs: -14, // QG-06, the deliverable's own level
18
+ graphicsPerMinute: 6, // each needs room to be read (QG-08's reading time)
19
+ punches: 8, // a make's most punch-ins
20
+ }
21
+ // Above these a trait is there at all (spike TPX-03: plain references read 0.18–0.26, −0.02–0.06 and 0)
22
+ export const PRESENT = { grain: 0.8, corners: 0.2, bars: 0.04, bed: -30 }
23
+ const JOIN_WORDS = { fade: "Fades", dip: "Dips to black", flash: "Flashes", wipe: "Wipes", slide: "Slides", zoom: "Zooms" }
24
+ const FORMAT_OF = { vertical: "9:16", portrait: "4:5", square: "1:1", landscape: "16:9" }
25
+ const TRAIT_WORDS = { rhythm: "its pace", opening: "how it opens", transitions: "its transitions", moves: "its zooms", captions: "its captions", graphics: "its graphics", colour: "its colour", sound: "its sound", structure: "its sections", format: "its shape" }
26
+ // What Edit DNA 2 doesn't measure at all (TPX-03): said once, so no one thinks it was followed
27
+ export const NEVER_READ = ["how much of the time music plays", "the music's level under the voice", "sound effects", "words on a caption page", "outlined captions", "faces in the shots"]
28
+
29
+ const share = (v) => (v >= 0.9 ? "every join" : v >= 0.6 ? "most joins" : v >= 0.4 ? "half the joins" : v >= 0.25 ? "a third of the joins" : "a few joins")
30
+
31
+ /**
32
+ * @param {object} dna a checked Edit DNA 2
33
+ * @param {{ looks: Record<string, { size: number, box: object | null, highlight: boolean, place?: string }>, lookLabels?: Record<string, string>, moods: Record<string, { bpm: number }>, motion: boolean, craft: boolean, safe?: { top?: number, bottom?: number } }} can what this server and computer allow; `safe` as shares of the height for the format the cut will have
34
+ * @returns {{ version: 1, lines: { id: string, state: "matched" | "nearest" | "cannot", text: string, why?: string, gate?: string, locked?: boolean, set?: object, target?: object }[], unread: string[] }}
35
+ */
36
+ export function styleBrief(dna, can) {
37
+ const lines = []
38
+ const add = (line) => lines.push(line)
39
+ const read = (name) => dna[name]?.read === "yes"
40
+
41
+ if (read("rhythm") && dna.rhythm.cutsPerMinute > 0) {
42
+ // The rate of visual change: every join and every punch-in, in and out, over the running time
43
+ const every = 60 / dna.rhythm.cutsPerMinute
44
+ const held = Math.max(every, FLOOR.hold)
45
+ add({
46
+ id: "pace",
47
+ state: every < FLOOR.hold ? "nearest" : "matched",
48
+ text: `A change of picture about every ${one(every)} s`,
49
+ // A talking cut can't cut faster than its sentences, so the rate is reached with punch-ins between them (§4.3)
50
+ why: every < FLOOR.hold ? `I hold each picture at least ${one(FLOOR.hold)} s: shorter ones cut into words.` : "Reached with punch-ins between the cuts your sentences allow.",
51
+ ...(every < FLOOR.hold ? { gate: "cut hygiene" } : {}),
52
+ set: { paceEvery: held },
53
+ target: { every: held },
54
+ })
55
+ }
56
+
57
+ if (read("transitions")) {
58
+ const per = dna.transitions.perMinute
59
+ const total = Object.values(per).reduce((sum, v) => sum + (v ?? 0), 0) + (dna.transitions.unread ?? 0)
60
+ const [kind, most] = Object.entries(per).filter(([k]) => k !== "cut").sort((a, b) => b[1] - a[1])[0]
61
+ if (total > 0 && most > 0) {
62
+ const part = most / total
63
+ const base = { id: "joins", text: `${JOIN_WORDS[kind]} on ${share(part)}`, target: { kind, share: Math.round(part * 100) / 100 } }
64
+ if (!can.motion) add({ ...base, state: "cannot", why: "Transitions need motion, which is off here." })
65
+ else if (part >= 0.6) add({ ...base, state: "matched", set: { transition: kind, transitionAll: true } })
66
+ else add({ ...base, state: "nearest", why: "I use it where the story changes moment, not by count.", set: { transition: kind } })
67
+ } else if (total > 0) add({ id: "joins", state: "matched", text: "Hard cuts, no transitions", target: { kind: "cut", share: 1 } })
68
+ }
69
+
70
+ if (read("moves") && dna.moves.zoomsPerMinute > 0) {
71
+ const scale = clamp(dna.moves.scale ?? 1.2, 1.05, 1.5)
72
+ const fits = scale === (dna.moves.scale ?? 1.2)
73
+ // How many is the pace line's to say (a talking cut needs more of them than the reference to change as often); this line is their size
74
+ add({ id: "zooms", state: fits ? "matched" : "nearest", text: `Punch-ins at ×${scale.toFixed(2)}`, ...(fits ? {} : { why: `Its own are ×${dna.moves.scale.toFixed(2)}; mine stay between ×1.05 and ×1.50 so a face holds up.` }), set: { punchesPerMinute: dna.moves.zoomsPerMinute, zoom: Math.round(scale * 100) / 100 }, target: { scale: Math.round(scale * 100) / 100 } })
75
+ }
76
+
77
+ if (read("captions") && dna.captions.present) {
78
+ const c = dna.captions
79
+ const centre = (c.top + c.bottom) / 2
80
+ const place = centre < 0.33 ? "top" : centre < 0.6 ? "middle" : "bottom"
81
+ // The nearest of Kriya's own looks: plate, word-by-word marking, place, then size (a look's size is its font's; the letters measure about 0.93 of it)
82
+ const scored = Object.entries(can.looks).map(([id, look]) => [id, (!!look.box === (c.plate === "box") || c.plate === null ? 0 : 2) + (!!look.highlight === !!c.highlight || (look.mark && look.mark !== "none") === !!c.highlight ? 0 : 1) + ((look.place ?? "bottom") === place ? 0 : 1.5) + Math.abs(look.size * 0.93 - (c.height ?? look.size * 0.93)) * 40])
83
+ const [look] = scored.sort((a, b) => a[1] - b[1])[0]
84
+ const words = `${c.highlight ? "Word-by-word captions" : "Captions"}${c.plate === "box" ? " on a plate" : ""}, ${place === "bottom" ? "lower third" : place === "top" ? "at the top" : "in the middle"}`
85
+ const size = `${one(can.looks[look].size * 100)}% of the height`
86
+ // Gates outrank the reference: where its captions sit under an app's buttons, or read under 4.5:1, mine don't follow
87
+ const under = can.safe?.bottom !== undefined && 1 - c.bottom < can.safe.bottom && place === "bottom"
88
+ const over = can.safe?.top !== undefined && c.top < can.safe.top && place === "top"
89
+ const faint = c.plate === "none" && c.contrast !== null && c.contrast < 3
90
+ const gates = [...(under || over ? ["Your reference's captions run under the app's buttons. I kept mine clear of them."] : []), ...(faint ? [`Your reference's captions read at about ${one(c.contrast)}:1 against the picture. Mine hold ${FLOOR.contrast}:1.`] : [])]
91
+ add({ id: "captions", state: "nearest", text: words, why: [`nearest: ${can.lookLabels?.[look] ?? look}, ${size}`, ...gates].join(" "), ...(gates.length ? { gate: under || over ? "safe zones" : "contrast", gateNote: gates.join(" ") } : {}), set: { captions: look }, target: { centre: Math.round(centre * 1000) / 1000, height: c.height, plate: c.plate } })
92
+ }
93
+
94
+ if (read("graphics") && dna.graphics.perMinute > 0) {
95
+ const n = dna.graphics.perMinute
96
+ const strap = dna.graphics.lowerBand ? ", with a name strap lower left" : ""
97
+ const text = `${n >= 1.5 ? `${Math.round(n)} graphics a minute` : "A graphic now and then"}${strap}`
98
+ if (!can.motion) add({ id: "graphics", state: "cannot", text, why: "Graphics need motion, which is off here.", target: { perMinute: n } })
99
+ else if (n > FLOOR.graphicsPerMinute) add({ id: "graphics", state: "nearest", text, why: `I can place ${FLOOR.graphicsPerMinute}: they need room to be read.`, gate: "reading time", set: { graphicsPerMinute: FLOOR.graphicsPerMinute }, target: { perMinute: FLOOR.graphicsPerMinute } })
100
+ else add({ id: "graphics", state: "matched", text, set: { graphicsPerMinute: n }, target: { perMinute: n } })
101
+ }
102
+
103
+ if (read("colour")) {
104
+ const c = dna.colour
105
+ const words = [c.mean[2] > 0.02 ? "warm" : c.mean[2] < -0.02 ? "cool" : "neutral", c.saturation > 0.12 ? "saturated" : c.saturation < 0.04 ? "muted" : "natural colour", c.contrast > 0.22 ? "contrasty" : c.contrast < 0.1 ? "soft contrast" : "even contrast", c.mean[0] > 0.7 ? "bright" : c.mean[0] < 0.4 ? "dark" : "mid brightness"]
106
+ add({ id: "colour", state: "matched", text: `Its colour: ${words.join(", ")}`, why: "Measured against your own footage and matched within limits, so skin stays skin.", set: { colourMatch: true }, target: { mean: c.mean } })
107
+ const craft = (id, text, set, target) => add(can.craft ? { id, state: "matched", text, set, target } : { id, state: "cannot", text, why: "It is one of the effects, which are off here.", target })
108
+ if (c.grain !== null && c.grain > PRESENT.grain) craft("grain", "Film grain", { grain: clamp(Math.round(c.grain * 6.3), 1, 40) }, { grain: c.grain })
109
+ if (c.vignette !== null && c.vignette > PRESENT.corners) craft("corners", "Darker corners", { vignette: Math.round(clamp(c.vignette * 1.9, 0, 1) * 100) / 100 }, { vignette: c.vignette })
110
+ if (c.letterbox !== null && c.letterbox > PRESENT.bars && read("format")) {
111
+ const ratio = dna.format.aspect / (1 - c.letterbox)
112
+ const text = `Black bars, about ${ratio.toFixed(2)}:1`
113
+ // Bars on a tall film would sit where the captions and the app's buttons are
114
+ if (can.tall) add({ id: "bars", state: "cannot", text, why: "On a tall film bars would cover the picture and the captions, so I left them off.", gate: "safe zones", target: { letterbox: c.letterbox } })
115
+ else craft("bars", text, { letterbox: Math.round(clamp(ratio, 1.5, 3) * 100) / 100 }, { letterbox: c.letterbox })
116
+ }
117
+ }
118
+
119
+ if (read("sound")) {
120
+ const s = dna.sound
121
+ if (s.bed !== null && s.bed > PRESENT.bed) {
122
+ const moods = Object.entries(can.moods)
123
+ const [mood, spec] = s.bpm === null ? (moods.find(([id]) => id === "calm") ?? moods[0]) : moods.sort((a, b) => Math.abs(a[1].bpm - s.bpm) - Math.abs(b[1].bpm - s.bpm))[0]
124
+ add({ id: "music", state: "nearest", text: `Music under the voice${s.bpm === null ? "" : `, about ${Math.round(s.bpm)} bpm`}`, why: s.bpm === null ? `I couldn't read its tempo, so ${/^[aeiou]/.test(mood) ? "an" : "a"} ${mood} bed of my own.` : `nearest: ${/^[aeiou]/.test(mood) ? "an" : "a"} ${mood} bed of my own at ${Math.round(clamp(s.bpm, 60, 180))} bpm (its own is ${spec.bpm}).`, set: { music: `generated:${mood}`, ...(s.bpm === null ? {} : { musicBpm: Math.round(clamp(s.bpm, 60, 180)) }) }, target: { bed: s.bed, bpm: s.bpm } })
125
+ }
126
+ // Loudness is the gate's, never the reference's: said, not offered
127
+ if (s.lufs !== null && Math.abs(s.lufs - FLOOR.lufs) > 1.5) add({ id: "loudness", state: "nearest", text: `Mastered at ${one(s.lufs)} LUFS`, why: `Mine is mastered at ${FLOOR.lufs} LUFS, the level the loudness gate holds.`, gate: "loudness", locked: true })
128
+ }
129
+
130
+ if (read("opening") && dna.opening.style) {
131
+ const style = dna.opening.style
132
+ if (style === "title_first") add(can.motion ? { id: "opening", state: "nearest", text: "Text on screen in the first two seconds", why: "nearest: a title card of my own, on your own words.", set: { titles: true }, target: { textEarly: true } } : { id: "opening", state: "cannot", text: "Text on screen in the first two seconds", why: "Title cards need motion, which is off here.", target: { textEarly: true } })
133
+ else if (style === "cold_open") add({ id: "opening", state: "nearest", text: `A short piece first, then a cut at ${one(dna.opening.firstCut)} s`, why: "The Director picks a cold open when it plans the cut; a make without a plan opens on your hook." })
134
+ else add({ id: "opening", state: "matched", text: "Straight in: no title, no cold open" })
135
+ }
136
+
137
+ if (read("format")) {
138
+ const format = FORMAT_OF[dna.format.shape]
139
+ add({ id: "format", state: "matched", text: `${format} ${dna.format.shape === "vertical" || dna.format.shape === "portrait" ? "tall" : dna.format.shape === "square" ? "square" : "wide"} frame`, set: { format }, target: { shape: dna.format.shape } })
140
+ }
141
+
142
+ const unread = [...Object.keys(TRAIT_WORDS).filter((name) => !read(name)).map((name) => TRAIT_WORDS[name]), ...(read("sound") && dna.sound.bpm === null && dna.sound.bed > PRESENT.bed ? ["its tempo"] : []), ...(read("captions") && dna.captions.present && dna.captions.plate === null ? ["whether its captions have a plate"] : []), ...(read("transitions") && dna.transitions.unread > 0 ? ["some of its joins"] : [])]
143
+ return { version: 1, lines, unread }
144
+ }
145
+
146
+ /** The ids a person may untick: every line that would change the cut. */
147
+ export const tickable = (brief) => brief.lines.filter((line) => line.set && !line.locked).map((line) => line.id)
148
+
149
+ /** `off` as the Host takes it: known trait ids only, each once. */
150
+ export const cleanOff = (off) => (Array.isArray(off) ? [...new Set(off.filter((id) => TRAIT_IDS.includes(id)))] : [])
151
+
152
+ /**
153
+ * The lines the person kept, as fields of a make's brief, filled only where the brief says nothing:
154
+ * what the person chose in this brief always wins over a reference.
155
+ * @param {object} brief already cleaned by the Host
156
+ * @param {{ lines: object[] }} style from styleBrief
157
+ * @param {string[]} off the ids the person unticked
158
+ * @param {{ seconds: number }} cut the length the cut aims for
159
+ * @returns {{ brief: object, notes: string[], kept: object[], colourMatch: boolean }} kept: the lines QG-16 compares
160
+ */
161
+ export function applyStyleBrief(brief, style, off, { seconds }) {
162
+ const out = { ...brief }
163
+ const notes = []
164
+ const kept = style.lines.filter((line) => line.state !== "cannot" && !off.includes(line.id))
165
+ const taken = (line, extra = "") => notes.push(`From your reference: ${line.text.charAt(0).toLowerCase()}${line.text.slice(1)}${extra}.`)
166
+ let colourMatch = false
167
+ for (const line of kept) {
168
+ const set = line.set ?? {}
169
+ if (line.gate && line.why) notes.push(line.gateNote ?? line.why)
170
+ if (set.paceEvery !== undefined && out.punches === undefined) {
171
+ out.punches = clamp(Math.round(seconds / set.paceEvery / 2), 1, FLOOR.punches)
172
+ taken(line, `, so ${out.punches} punch-in${out.punches === 1 ? "" : "s"} between your sentences`)
173
+ }
174
+ if (set.punchesPerMinute !== undefined) {
175
+ if (out.punches === undefined) out.punches = clamp(Math.round((set.punchesPerMinute * seconds) / 60), 1, FLOOR.punches)
176
+ if (out.zoom === undefined) out.zoom = set.zoom
177
+ taken(line)
178
+ }
179
+ if (set.transition !== undefined && out.transition === undefined) {
180
+ out.transition = set.transition
181
+ if (set.transitionAll) out.transitionAll = true
182
+ taken(line)
183
+ }
184
+ if (set.captions !== undefined && out.captions === undefined) {
185
+ out.captions = set.captions
186
+ taken(line, ` (${line.why.split(" Your reference")[0]})`)
187
+ }
188
+ if (set.graphicsPerMinute !== undefined && Array.isArray(out.graphics)) {
189
+ const most = Math.max(1, Math.round((set.graphicsPerMinute * seconds) / 60))
190
+ if (out.graphics.length > most) out.graphics = out.graphics.slice(0, most)
191
+ taken(line)
192
+ }
193
+ if (set.colourMatch && out.grade === undefined) colourMatch = true
194
+ const fx = [...(set.grain !== undefined ? [{ effect: "grain", params: { amount: set.grain } }] : []), ...(set.vignette !== undefined ? [{ effect: "vignette", params: { strength: set.vignette } }] : []), ...(set.letterbox !== undefined ? [{ effect: "letterbox", params: { ratio: set.letterbox } }] : [])]
195
+ if (fx.length) {
196
+ out.fx = [...(out.fx ?? []), ...fx]
197
+ taken(line)
198
+ }
199
+ if (set.music !== undefined && out.music === undefined) {
200
+ out.music = set.music
201
+ if (set.musicBpm) out.musicBpm = set.musicBpm
202
+ taken(line, ` (${line.why.replace(/\.$/, "")})`)
203
+ }
204
+ if (set.titles && out.titles === undefined) {
205
+ out.titles = true
206
+ taken(line)
207
+ }
208
+ if (set.format !== undefined && out.format === undefined) out.format = set.format
209
+ }
210
+ return { brief: out, notes, kept, colourMatch }
211
+ }
@@ -0,0 +1,57 @@
1
+ // Style packs (TP7, CRAFT_UPGRADE §5.5, EDD-67): one name for a whole look. Data, like a
2
+ // recipe: no command, path, URL or model (ET-RCP-01's rule, ET-TY-08). Each names a type
3
+ // kit pair, a caption look, the graphics' tone and accent and name strap, a transition, a
4
+ // grade and a generated music mood, all ids of Kriya's own tables. The person picks one, or
5
+ // the Director proposes one and the person approves the plan; nothing here is chosen alone.
6
+ // What a pack names that this computer or server can't do (a mood or grade behind another
7
+ // switch) is left out with a note, never faked.
8
+
9
+ /**
10
+ * @type {Record<string, { label: string, does: string, type: string, caption: string, graphics: { tone: string, accent: string, lower: string }, transition: string | null, grade: string | null, mood: string | null, density: "none" | "light" | "full" }>}
11
+ */
12
+ export const STYLE_PACKS = {
13
+ "clean-explainer": { label: "Clean explainer", does: "plain type, quiet captions, cuts that don't show", type: "clean", caption: "subtle", graphics: { tone: "light", accent: "teal", lower: "underline" }, transition: null, grade: "bright", mood: "calm", density: "light" },
14
+ "bold-promo": { label: "Bold promo", does: "big condensed type, one word at a time, fast joins", type: "bold", caption: "single", graphics: { tone: "dark", accent: "yellow", lower: "box" }, transition: "zoom", grade: "vivid", mood: "upbeat", density: "full" },
15
+ "warm-story": { label: "Warm story", does: "a serif, soft captions, slow fades, a warm grade", type: "story", caption: "story", graphics: { tone: "dark", accent: "amber", lower: "bar" }, transition: "fade", grade: "warm", mood: "warm", density: "light" },
16
+ "creator-pop": { label: "Creator pop", does: "words that pop as they're said, bright colour", type: "modern", caption: "duo", graphics: { tone: "dark", accent: "pink", lower: "pill" }, transition: "slide", grade: "vivid", mood: "upbeat", density: "full" },
17
+ "news-desk": { label: "News desk", does: "headline captions at the top, straps for every speaker", type: "clean", caption: "headline", graphics: { tone: "dark", accent: "white", lower: "split" }, transition: "wipe", grade: null, mood: null, density: "none" },
18
+ "tutorial-steps": { label: "Tutorial", does: "steps on screen, a marker on each word, a plain screen frame", type: "tech", caption: "marker", graphics: { tone: "dark", accent: "teal", lower: "tag" }, transition: null, grade: "bright", mood: "calm", density: "light" },
19
+ "podcast-clip": { label: "Podcast clip", does: "karaoke captions and a quiet look", type: "clean", caption: "karaoke", graphics: { tone: "dark", accent: "yellow", lower: "pill" }, transition: null, grade: null, mood: null, density: "none" },
20
+ "cinematic-title": { label: "Cinematic", does: "a serif title card, slow dips, a filmic grade", type: "story", caption: "minimal", graphics: { tone: "dark", accent: "white", lower: "underline" }, transition: "dip", grade: "cinematic", mood: "warm", density: "light" },
21
+ "handmade-vlog": { label: "Handmade vlog", does: "handwritten titles, friendly captions", type: "hand", caption: "grow", graphics: { tone: "light", accent: "amber", lower: "tag" }, transition: "fade", grade: "warm", mood: "calm", density: "light" },
22
+ "type-on-quote": { label: "Typed quote", does: "captions typed on, mono headings", type: "tech", caption: "typewriter", graphics: { tone: "dark", accent: "amber", lower: "box" }, transition: "dip", grade: "mono", mood: null, density: "none" },
23
+ "minimal-mono": { label: "Minimal", does: "black and white, few words, nothing loud", type: "modern", caption: "minimal", graphics: { tone: "light", accent: "white", lower: "underline" }, transition: "fade", grade: "mono", mood: "calm", density: "none" },
24
+ "launch-energy": { label: "Launch", does: "underlined captions, flash joins, a punchy grade", type: "bold", caption: "underline", graphics: { tone: "dark", accent: "yellow", lower: "split" }, transition: "flash", grade: "vivid", mood: "upbeat", density: "full" },
25
+ }
26
+
27
+ /**
28
+ * A pack as the fields of a make's brief and the kit to store, filled only where the brief
29
+ * says nothing: the person's own choice in this brief always wins.
30
+ * @param {string} id
31
+ * @param {object} brief already cleaned by the Host
32
+ * @param {{ moods: Record<string, unknown>, grades: Record<string, unknown>, transitions: Record<string, unknown>, looks: Record<string, unknown>, motion: boolean }} can what this server and computer allow
33
+ * @returns {{ brief: object, kit: { pair: string, pack: string }, notes: string[] } | null}
34
+ */
35
+ export function applyStylePack(id, brief, can) {
36
+ const pack = Object.hasOwn(STYLE_PACKS, id) ? STYLE_PACKS[id] : null
37
+ if (!pack) return null
38
+ const out = { ...brief }
39
+ const notes = []
40
+ if (out.captions === undefined && Object.hasOwn(can.looks, pack.caption)) out.captions = pack.caption
41
+ if (out.grade === undefined && pack.grade) {
42
+ if (Object.hasOwn(can.grades, pack.grade)) out.grade = pack.grade
43
+ else notes.push(`The ${pack.label} pack's ${pack.grade} grade isn't available here, so it was left out.`)
44
+ }
45
+ if (out.transition === undefined && pack.transition) {
46
+ if (can.motion && Object.hasOwn(can.transitions, pack.transition)) out.transition = pack.transition
47
+ else notes.push(`The ${pack.label} pack's ${pack.transition} joins need motion, which is off here.`)
48
+ }
49
+ if (out.music === undefined && pack.mood) {
50
+ if (Object.hasOwn(can.moods, pack.mood)) out.music = `generated:${pack.mood}`
51
+ else notes.push(`The ${pack.label} pack's ${pack.mood} music isn't available here, so there is none.`)
52
+ }
53
+ if (pack.density === "full") out.cutSound ??= "whoosh"
54
+ // The plan's graphics in the pack's tone, accent and name strap; their words are untouched
55
+ if (Array.isArray(out.graphics)) out.graphics = out.graphics.map((g) => ({ ...g, tone: pack.graphics.tone, accent: pack.graphics.accent, ...(g.kind === "lower" ? { style: pack.graphics.lower } : {}) }))
56
+ return { brief: out, kit: { pair: pack.type, pack: id }, notes }
57
+ }
@@ -0,0 +1,17 @@
1
+ // Transitions (MOTION_GRAPHICS.md §6): how one clip arrives over the last frame of the one
2
+ // before it. The cut never moves: the outgoing clip's last frame is held underneath while the
3
+ // incoming clip comes in over its own first moments, so the sound, the captions and every
4
+ // word anchor stay where they were. The kinds are a fixed list; code names the FFmpeg
5
+ // transition, a model never does.
6
+
7
+ const FLICKS = 705_600_000
8
+
9
+ /** What a person or the Director may ask for → FFmpeg's xfade transition. */
10
+ export const TRANSITIONS = { fade: "fade", dip: "fadeblack", flash: "fadewhite", wipe: "wipeleft", slide: "slideleft", zoom: "zoomin" }
11
+ export const TRANSITION_LABELS = { fade: "Fade", dip: "Dip to black", flash: "Flash", wipe: "Wipe", slide: "Slide", zoom: "Zoom" }
12
+ export const TRANSITION_MIN = Math.round(0.2 * FLICKS)
13
+ export const TRANSITION_MAX = Math.round(0.8 * FLICKS)
14
+ export const TRANSITION_DEFAULT = Math.round(0.3 * FLICKS)
15
+
16
+ /** A length inside the allowed range; anything else is the default. */
17
+ export const transitionLength = (duration) => (Number.isSafeInteger(duration) ? Math.min(TRANSITION_MAX, Math.max(TRANSITION_MIN, duration)) : TRANSITION_DEFAULT)
@@ -0,0 +1,173 @@
1
+ // The type kit and the person's brand (TP7, CRAFT_UPGRADE §5.2, EDD-67): one per film, a
2
+ // heading face and a text face from a fixed table of pairs, a size scale tied to the frame's
3
+ // height, tracking, case and weight; the person's own colours, typed as hex, with the plate or
4
+ // outline chosen by code so text still holds 4.5:1; a logo from the bin as a corner bug; a
5
+ // bar across the cut. Stored on the project (`look.brand.type`) only when the person or an
6
+ // approved plan chooses it (EH-69): a project without one keeps the system stacks, and every
7
+ // box it draws is the box it drew. Data only: font ids, never a path, URL or file.
8
+
9
+ /** The pairs. Font ids are the Media Runtime's pack-fonts artifacts (engine/fonts.js). */
10
+ export const PAIRS = {
11
+ clean: { label: "Clean", heading: { font: "font-inter", weight: 800, case: "none", tracking: -0.01 }, body: { font: "font-inter", weight: 600, case: "none", tracking: 0 } },
12
+ bold: { label: "Bold", heading: { font: "font-oswald", weight: 700, case: "upper", tracking: 0.02 }, body: { font: "font-inter", weight: 700, case: "none", tracking: 0 } },
13
+ modern: { label: "Modern", heading: { font: "font-montserrat", weight: 800, case: "none", tracking: -0.01 }, body: { font: "font-inter", weight: 600, case: "none", tracking: 0 } },
14
+ story: { label: "Story", heading: { font: "font-lora", weight: 700, case: "none", tracking: 0 }, body: { font: "font-lora", weight: 600, case: "none", tracking: 0 } },
15
+ tech: { label: "Technical", heading: { font: "font-jetbrains-mono", weight: 700, case: "none", tracking: -0.02 }, body: { font: "font-inter", weight: 600, case: "none", tracking: 0 } },
16
+ hand: { label: "Handwritten", heading: { font: "font-caveat", weight: 700, case: "none", tracking: 0 }, body: { font: "font-inter", weight: 600, case: "none", tracking: 0 } },
17
+ }
18
+
19
+ /** Sizes as shares of the frame's height (a tall frame and a wide one read alike). The smallest stays over QG-09's 0.02. */
20
+ export const SCALE = { display: 0.085, heading: 0.06, caption: 0.044, body: 0.032, small: 0.024 }
21
+ export const typeScale = (height) => Object.fromEntries(Object.entries(SCALE).map(([step, share]) => [step, Math.round(share * height)]))
22
+
23
+ export const BARS = ["progress", "chapters"]
24
+ export const CORNERS = ["tl", "tr", "bl", "br"]
25
+ export const CONTRAST = 4.5 // QG-09's floor, WCAG AA
26
+ const HEX = /^#[0-9a-f]{6}$/i
27
+ const COLOR_KEYS = ["text", "accent", "plate"]
28
+
29
+ /* ─────────────────────────────── contrast ─────────────────────────────── */
30
+
31
+ const channel = (v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)
32
+ /** WCAG relative luminance of a #rrggbb. */
33
+ export function luminance(hex) {
34
+ const n = Number.parseInt(hex.slice(1), 16)
35
+ return 0.2126 * channel(((n >> 16) & 255) / 255) + 0.7152 * channel(((n >> 8) & 255) / 255) + 0.0722 * channel((n & 255) / 255)
36
+ }
37
+ export function contrastRatio(a, b) {
38
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x)
39
+ return (hi + 0.05) / (lo + 0.05)
40
+ }
41
+
42
+ const DARK = "#0a0a0a"
43
+ const LIGHT = "#ffffff"
44
+ /** Of black and white, the one further from `hex`. */
45
+ export const against = (hex) => (contrastRatio(hex, DARK) >= contrastRatio(hex, LIGHT) ? DARK : LIGHT)
46
+
47
+ /**
48
+ * A box behind `ink` in the colour of `accent`, moved toward black or white in steps until the ink
49
+ * holds 4.5:1 on it (TP7's box marks): the word keeps its own ink and outline, so QG-09 reads it as
50
+ * it reads the page.
51
+ */
52
+ export function boxFor(accent, ink) {
53
+ const toward = against(ink) === DARK ? [10, 10, 10] : [255, 255, 255]
54
+ const n = Number.parseInt(accent.slice(1), 16)
55
+ const rgb = [(n >> 16) & 255, (n >> 8) & 255, n & 255]
56
+ for (let step = 0; step <= 20; step++) {
57
+ const mixed = `#${rgb.map((c, i) => Math.round(c + ((toward[i] - c) * step) / 20).toString(16).padStart(2, "0")).join("")}`
58
+ if (contrastRatio(ink, mixed) >= CONTRAST) return mixed
59
+ }
60
+ return against(ink)
61
+ }
62
+
63
+ /**
64
+ * The person's colours made readable (CRAFT §5.2): text and accent are kept as typed; what
65
+ * is behind them is chosen so both hold 4.5:1. With a plate, the plate is theirs if it
66
+ * holds, else black or white; with no plate, an outline in black or white, and a plate
67
+ * when even that can't hold (a mid grey reads on neither).
68
+ * @param {{ text?: string, accent?: string, plate?: string }} colors hex
69
+ * @param {{ plate: boolean }} look whether the look draws a plate behind the words
70
+ * @returns {{ text: string, accent: string, plate: string | null, stroke: string | null, clamped: string[] }}
71
+ */
72
+ export function readableColors(colors, { plate: hasPlate }) {
73
+ const text = HEX.test(colors.text ?? "") ? colors.text.toLowerCase() : LIGHT
74
+ const accent = HEX.test(colors.accent ?? "") ? colors.accent.toLowerCase() : text
75
+ const holds = (bg) => contrastRatio(text, bg) >= CONTRAST && contrastRatio(accent, bg) >= CONTRAST
76
+ const worst = (bg) => Math.min(contrastRatio(text, bg), contrastRatio(accent, bg))
77
+ const best = worst(DARK) >= worst(LIGHT) ? DARK : LIGHT
78
+ const clamped = []
79
+ // On a plate, what can't hold gives way: the text to black or white, then the accent to the text
80
+ const onPlate = (plate) => {
81
+ let ink = text
82
+ if (contrastRatio(ink, plate) < CONTRAST) {
83
+ ink = against(plate)
84
+ clamped.push(`text ${text} → ${ink}`)
85
+ }
86
+ let mark = accent
87
+ if (contrastRatio(mark, plate) < CONTRAST) {
88
+ mark = ink
89
+ clamped.push(`accent ${accent} → ${ink}`)
90
+ }
91
+ return { text: ink, accent: mark, plate, stroke: null, clamped }
92
+ }
93
+ if (hasPlate) {
94
+ const typed = HEX.test(colors.plate ?? "") ? colors.plate.toLowerCase() : null
95
+ if (typed && holds(typed)) return { text, accent, plate: typed, stroke: null, clamped }
96
+ // Their plate holds their text: keep it, and only the accent gives way
97
+ if (typed && contrastRatio(text, typed) >= CONTRAST) return onPlate(typed)
98
+ if (typed) clamped.push(`plate ${typed} → ${best}`)
99
+ return onPlate(best)
100
+ }
101
+ if (holds(best)) return { text, accent, plate: null, stroke: best, clamped }
102
+ clamped.push("a plate behind the words, since no outline holds 4.5:1")
103
+ return onPlate(best)
104
+ }
105
+
106
+ /* ─────────────────────────────── the stored kit ─────────────────────────────── */
107
+
108
+ /**
109
+ * A type kit at a trust boundary (an operation, a browser, a plan): unknown fields go.
110
+ * @param {unknown} raw
111
+ * @param {{ packs?: Record<string, unknown> }} [tables] style pack ids allowed
112
+ * @returns {{ kit: object | null, problem: string | null }} kit null with no problem: no kit (system stacks)
113
+ */
114
+ export function cleanTypeKit(raw, { packs = {} } = {}) {
115
+ if (raw === null || raw === undefined) return { kit: null, problem: null }
116
+ if (typeof raw !== "object" || Array.isArray(raw)) return { kit: null, problem: "a type kit is an object" }
117
+ if (!Object.hasOwn(PAIRS, raw.pair ?? "")) return { kit: null, problem: `a type kit needs a pair: ${Object.keys(PAIRS).join(", ")}` }
118
+ const kit = { pair: raw.pair }
119
+ if (raw.colors !== undefined) {
120
+ if (!raw.colors || typeof raw.colors !== "object") return { kit: null, problem: "colours are { text, accent, plate } in #rrggbb" }
121
+ const colors = {}
122
+ for (const key of COLOR_KEYS) {
123
+ if (raw.colors[key] === undefined) continue
124
+ if (!HEX.test(raw.colors[key])) return { kit: null, problem: `the ${key} colour must be #rrggbb` }
125
+ colors[key] = raw.colors[key].toLowerCase()
126
+ }
127
+ if (Object.keys(colors).length) kit.colors = colors
128
+ }
129
+ if (raw.logo !== undefined) {
130
+ if (typeof raw.logo !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(raw.logo)) return { kit: null, problem: "the logo is a file of this project, by its id" }
131
+ kit.logo = raw.logo
132
+ kit.corner = CORNERS.includes(raw.corner) ? raw.corner : "tr"
133
+ }
134
+ if (raw.bar !== undefined) {
135
+ if (!BARS.includes(raw.bar)) return { kit: null, problem: `a bar is ${BARS.join(" or ")}` }
136
+ kit.bar = raw.bar
137
+ }
138
+ if (raw.pack !== undefined) {
139
+ if (!Object.hasOwn(packs, raw.pack)) return { kit: null, problem: "there is no style pack by that name" }
140
+ kit.pack = raw.pack
141
+ }
142
+ return { kit, problem: null }
143
+ }
144
+
145
+ /**
146
+ * The kit a project chose, read defensively from `look.brand.type` (an older `set_look`
147
+ * could write anything there): null when there is none or it isn't one.
148
+ */
149
+ export function typeKitOf(project) {
150
+ const raw = project?.look?.brand?.type
151
+ if (!raw || !Object.hasOwn(PAIRS, raw.pair ?? "")) return null
152
+ // The pack's name is only a label here: the pack's choices are already stored as themselves
153
+ const { kit } = cleanTypeKit({ ...raw, pack: undefined })
154
+ return kit && typeof raw.pack === "string" && /^[a-z0-9-]{1,40}$/.test(raw.pack) ? { ...kit, pack: raw.pack } : kit
155
+ }
156
+
157
+ /**
158
+ * The kit as a tile node carries it (plan.js): the pair's faces, the colours, and whether
159
+ * this computer has the shipped fonts. Part of the tile's key, so a change re-renders.
160
+ * @param {object} kit from typeKitOf
161
+ * @param {string[] | undefined} installed the pack's font ids here
162
+ */
163
+ export function kitNode(kit, installed) {
164
+ const pair = PAIRS[kit.pair]
165
+ const have = new Set(installed ?? [])
166
+ return {
167
+ pair: kit.pair,
168
+ heading: pair.heading,
169
+ body: pair.body,
170
+ ...(kit.colors ? { colors: kit.colors } : {}),
171
+ shipped: have.has(pair.heading.font) && have.has(pair.body.font),
172
+ }
173
+ }
@@ -106,7 +106,16 @@ export const SLOT_WAIT_MS = 150_000
106
106
  // Room for a reasoning model's thinking on top of the answer's own budget
107
107
  export const THINKING = 1500
108
108
 
109
- export function createAsk({ governor, record = () => {}, budget = { take: () => true }, slotWaitMs = SLOT_WAIT_MS }) {
109
+ // The one stronger tier a slot may be asked on, once (CRAFT_UPGRADE §6.4, TP8)
110
+ export const ESCALATION_TIER = "balanced"
111
+
112
+ /**
113
+ * tiers: the tiers this person's plan lists (GET /models), given only with editing.directorLoop on. A
114
+ * budget slot whose answer fit its schema and failed its code check twice is asked once more on
115
+ * `balanced`, only when that tier is in this list; refused, failed or still wrong, the slot ends as it
116
+ * would have without it (EH-65, ET-DL-08). Absent: no escalation, as before.
117
+ */
118
+ export function createAsk({ governor, record = () => {}, budget = { take: () => true }, slotWaitMs = SLOT_WAIT_MS, tiers = null }) {
110
119
  // The gateway has been refusing this job for as long as a slot will wait: its other slots
111
120
  // take their defaults at once, so it finishes (TOOLS_AND_CONTRACTS §9) instead of crawling
112
121
  // through the Governor's backoff for half an hour
@@ -114,14 +123,35 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
114
123
  /**
115
124
  * @param {{ task: string, tier?: string, schema: object, recipe?: string, view: string, request: string, maxOutput: number, check?: (value: any) => string[], clean?: (value: any) => any, fallback: () => any, priority?: number, signal?: AbortSignal }} slot
116
125
  * clean: tidies a parsed answer before the schema sees it (a model's nulls for absent fields)
117
- * @returns {Promise<{ value: any, source: "model" | "repaired" | "default", reason?: string, calls: number }>}
126
+ * @returns {Promise<{ value: any, source: "model" | "repaired" | "escalated" | "default", reason?: string, calls: number }>}
118
127
  */
128
+ // One call on the stronger tier, with the slot's own question: an answer that fits and passes, or null
129
+ async function escalate({ task, schema, messages, maxOutput, check, clean, priority, signal }) {
130
+ const started = Date.now()
131
+ const limit = AbortSignal.timeout(slotWaitMs)
132
+ let reply
133
+ try {
134
+ reply = await governor.call({ model: ESCALATION_TIER, messages, response_format: { type: "json_schema", json_schema: { name: task, strict: false, schema } }, reasoning: { effort: "low" } }, { maxTokens: maxOutput + THINKING, priority, signal: signal ? AbortSignal.any([signal, limit]) : limit })
135
+ } catch (error) {
136
+ if (signal?.aborted) throw error
137
+ record({ task, tier: ESCALATION_TIER, ms: Date.now() - started, result: `error:${limit.aborted ? "model_unavailable" : (error.code ?? error.status ?? "unknown")}` })
138
+ return null
139
+ }
140
+ const parsed = parseReply(reply?.choices?.[0]?.message?.content, reply?.choices?.[0]?.finish_reason)
141
+ if (!parsed.problem) parsed.value = clean(parsed.value)
142
+ const problems = parsed.problem ? [parsed.problem] : schemaErrors(schema, parsed.value).length ? ["schema"] : check(parsed.value)
143
+ const usage = reply?.usage ?? {}
144
+ record({ task, tier: ESCALATION_TIER, input_tokens: usage.prompt_tokens ?? null, cached_tokens: usage.prompt_tokens_details?.cached_tokens ?? null, output_tokens: usage.completion_tokens ?? null, ms: Date.now() - started, result: problems.length ? "invalid:escalated" : "escalated" })
145
+ return problems.length ? null : { value: parsed.value, source: "escalated" }
146
+ }
147
+
119
148
  return async function ask({ task, tier = "budget", schema, recipe = "", view, request, maxOutput, check = () => [], clean = (value) => value, fallback, priority = PRIORITY.job, signal }) {
120
149
  const messages = [
121
150
  { role: "system", content: `${DIRECTOR_CORE}\n\n${recipe}`.trim() },
122
151
  { role: "user", content: `${view}\n\n${request}` },
123
152
  ]
124
153
  let calls = 0
154
+ const refusals = []
125
155
  for (let attempt = 0; attempt < 2; attempt++) {
126
156
  if (unavailable) return { value: fallback(), source: "default", reason: "The model wasn't available for this job.", calls }
127
157
  if (!budget.take()) return { value: fallback(), source: "default", reason: "The job's model budget is spent.", calls }
@@ -151,6 +181,7 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
151
181
  const problems = parsed.problem ? [parsed.problem] : [...shape, ...(shape.length ? [] : check(parsed.value))]
152
182
  // Why it was refused, never what it said: the journal holds no answer (ES-12)
153
183
  const why = parsed.kind ?? (shape.length ? "schema" : "meaning")
184
+ refusals.push(why)
154
185
  record({ task, tier, input_tokens: usage.prompt_tokens ?? null, cached_tokens: usage.prompt_tokens_details?.cached_tokens ?? null, output_tokens: usage.completion_tokens ?? null, ms: Date.now() - started, result: problems.length ? `invalid:${why}` : attempt ? "repaired" : "ok" })
155
186
  if (!problems.length) return { value: parsed.value, source: attempt ? "repaired" : "model", calls }
156
187
  if (attempt === 0) {
@@ -158,7 +189,10 @@ export function createAsk({ governor, record = () => {}, budget = { take: () =>
158
189
  messages.push({ role: "assistant", content: String(content ?? "") }, { role: "user", content: `That answer was refused: ${problems.slice(0, 5).join("; ")}. Answer again with only the JSON that fits the schema, shorter if you can, using only ids you were shown. No explanation, no thinking aloud.` })
159
190
  continue
160
191
  }
161
- return { value: fallback(), source: "default", reason: `The model's answer didn't fit, twice: ${problems[0]}.`, calls }
192
+ const ended = { value: fallback(), source: "default", reason: `The model's answer didn't fit, twice: ${problems[0]}.`, calls }
193
+ if (!refusals.every((w) => w === "meaning") || tier !== "budget" || !Array.isArray(tiers) || !tiers.includes(ESCALATION_TIER) || !budget.take()) return ended
194
+ const stronger = await escalate({ task, schema, messages: messages.slice(0, 2), maxOutput, check, clean, priority, signal })
195
+ return stronger ? { ...stronger, calls: calls + 1 } : { ...ended, calls: calls + 1 }
162
196
  }
163
197
  return { value: fallback(), source: "default", reason: "unreachable", calls }
164
198
  }