oda-engine 0.0.0-stage → 0.1.1

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 (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +131 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CptQkDVX.js +1 -0
  197. package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
  198. package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
  200. package/web-dist/assets/index-Baka-ZO7.js +693 -0
  201. package/web-dist/assets/index-CcjyyQco.css +1 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
@@ -0,0 +1,127 @@
1
+ // The "target | now" picture a round posts for each hero view
2
+ // (REFERENCE_LOOP.md 2.4 step 4, 4): the target on the left, the still on
3
+ // the right at the target's shape, and the creator's marks drawn over the
4
+ // still when a note came with them. The real-time tools stream's compose
5
+ // (WS3: compose(targetPath, currentPath, out, { label, marks })) is used
6
+ // when this tree has it; until then this one, which draws no lettering (a
7
+ // label is the round message's to say, not the picture's), stands in.
8
+
9
+ import fsp from 'node:fs/promises'
10
+ import path from 'node:path'
11
+ import { decodeImage } from '../reference/decode.mjs'
12
+ import { fitAspect } from '../reference/facts.mjs'
13
+ import { blit, canvas, encodePng, line } from '../reference/png.mjs'
14
+
15
+ /** Where the real-time tools stream's compose may live, first found wins. */
16
+ export const COMPOSE_MODULES = ['../reference/compose.mjs', '../reference/composite.mjs', './composite.mjs']
17
+
18
+ const WIDTH = 1600
19
+ const GAP = 4
20
+ const MARK_RGB = [255, 64, 64]
21
+
22
+ let found // undefined: not looked for yet; null: none
23
+ async function externalCompose() {
24
+ if (found !== undefined) return found
25
+ found = null
26
+ for (const rel of COMPOSE_MODULES) {
27
+ try {
28
+ const m = await import(new URL(rel, import.meta.url).href)
29
+ if (typeof m.compose === 'function') {
30
+ found = m.compose
31
+ break
32
+ }
33
+ } catch {
34
+ // not in this tree
35
+ }
36
+ }
37
+ return found
38
+ }
39
+
40
+ /** One mark (REFERENCE_LOOP contract: pen, circle, arrow, text in image
41
+ * pixels; a circle's rect is [x, y, width, height], as the chat sends it)
42
+ * drawn on `pic` at offset (ox, oy), scaled by k. Text is drawn as an
43
+ * underline where it stands: this fallback has no font. */
44
+ function drawMark(pic, mark, ox, oy, k) {
45
+ const pt = (p) => [ox + Math.round(Number(p?.[0] ?? p?.x ?? 0) * k), oy + Math.round(Number(p?.[1] ?? p?.y ?? 0) * k)]
46
+ const points = Array.isArray(mark?.points) ? mark.points.map(pt) : []
47
+ if (mark?.kind === 'circle' && Array.isArray(mark.rect) && mark.rect.length === 4) {
48
+ const [x0, y0] = pt([mark.rect[0], mark.rect[1]])
49
+ const [x1, y1] = pt([Number(mark.rect[0]) + Number(mark.rect[2]), Number(mark.rect[1]) + Number(mark.rect[3])])
50
+ const cx = (x0 + x1) / 2
51
+ const cy = (y0 + y1) / 2
52
+ const rx = Math.abs(x1 - x0) / 2
53
+ const ry = Math.abs(y1 - y0) / 2
54
+ const steps = 48
55
+ for (let i = 0; i < steps; i++) {
56
+ const a = (i / steps) * Math.PI * 2
57
+ const b = ((i + 1) / steps) * Math.PI * 2
58
+ line(pic, Math.round(cx + rx * Math.cos(a)), Math.round(cy + ry * Math.sin(a)), Math.round(cx + rx * Math.cos(b)), Math.round(cy + ry * Math.sin(b)), MARK_RGB, 3)
59
+ }
60
+ return
61
+ }
62
+ if (mark?.kind === 'text' && points.length) {
63
+ const [x, y] = points[0]
64
+ line(pic, x, y + 4, x + 60, y + 4, MARK_RGB, 3)
65
+ return
66
+ }
67
+ for (let i = 1; i < points.length; i++) line(pic, points[i - 1][0], points[i - 1][1], points[i][0], points[i][1], MARK_RGB, 3)
68
+ if (mark?.kind === 'arrow' && points.length >= 2) {
69
+ const [x1, y1] = points.at(-1)
70
+ const [x0, y0] = points.at(-2)
71
+ const a = Math.atan2(y1 - y0, x1 - x0)
72
+ for (const turn of [Math.PI * 0.8, -Math.PI * 0.8]) line(pic, x1, y1, Math.round(x1 + 18 * Math.cos(a + turn)), Math.round(y1 + 18 * Math.sin(a + turn)), MARK_RGB, 3)
73
+ }
74
+ }
75
+
76
+ /**
77
+ * The side by side: decoded pictures in, PNG bytes out. The still is cut to
78
+ * the target's shape (the same framing, so what differs is the space).
79
+ */
80
+ export function sideBySidePng(target, still, { marks = [], stillSize = null } = {}) {
81
+ const half = Math.round((WIDTH - GAP) / 2)
82
+ const aspect = target.width / target.height
83
+ const h = Math.min(1200, Math.max(64, Math.round(half / aspect)))
84
+ const out = canvas(half * 2 + GAP, h, [16, 16, 18])
85
+ blit(out, target, 0, 0, half, h)
86
+ const cut = fitAspect(still, aspect)
87
+ blit(out, cut, half + GAP, 0, half, h)
88
+ // Marks are in the still's own pixels, as the creator drew them.
89
+ const k = half / (stillSize?.width ?? still.width)
90
+ for (const m of Array.isArray(marks) ? marks.slice(0, 64) : []) drawMark(out, m, half + GAP, 0, k)
91
+ return encodePng(out)
92
+ }
93
+
94
+ /**
95
+ * compose(targetPath, currentPath, out, { label, marks }): writes `out`, a
96
+ * PNG of the target beside the still, through WS3's compose when this tree
97
+ * has it. Answers { ok, out, via, layout } or { ok: false, error }; layout
98
+ * is where each half sits ({ width, height, panels: { target, now }, cut }),
99
+ * which the round keeps beside the composite so a mark the creator draws on
100
+ * it can be told in the still's own pixels (rounds.cjs compositeLayout), or
101
+ * null from the fallback.
102
+ */
103
+ export async function compose(targetPath, currentPath, out, { label, marks, rpc } = {}) {
104
+ const external = await externalCompose()
105
+ if (external) {
106
+ try {
107
+ const r = await external(targetPath, currentPath, out, { label, marks })
108
+ if (r === undefined || r === null || r?.ok !== false) {
109
+ const layout = r?.panels?.target && r?.panels?.now ? { width: r.width, height: r.height, panels: r.panels, cut: r.cut ?? null } : null
110
+ return { ok: true, out, via: 'compose', layout }
111
+ }
112
+ } catch {
113
+ // fall back to the one here
114
+ }
115
+ }
116
+ try {
117
+ const [t, s] = await Promise.all([fsp.readFile(targetPath), fsp.readFile(currentPath)])
118
+ const [target, still] = await Promise.all([decodeImage(t, { maxEdge: 1600, rpc }), decodeImage(s, { maxEdge: 1600, rpc })])
119
+ if (!target.ok) return { ok: false, error: target.error }
120
+ if (!still.ok) return { ok: false, error: still.error }
121
+ await fsp.mkdir(path.dirname(out), { recursive: true })
122
+ await fsp.writeFile(out, sideBySidePng(target, still, { marks }))
123
+ return { ok: true, out, via: 'fallback', layout: null }
124
+ } catch (err) {
125
+ return { ok: false, error: err?.message ?? String(err) }
126
+ }
127
+ }
@@ -0,0 +1,205 @@
1
+ // The reference loop's stop gate (REFERENCE_LOOP.md 2.6), on top of the
2
+ // studio's own (stopGate.mjs: nw_check and a look after the last edit, no
3
+ // debug code, the brief and its look). A space whose kickoff stands may say
4
+ // it is done only when all of this holds:
5
+ //
6
+ // - its target pictures are settled (or there are none, and why);
7
+ // - a round was judged on the space as it is now, on every hero view that
8
+ // has a target (a round on some of them plans the next, and ends nothing);
9
+ // - the level's time floor has gone by, and the last round's score is at
10
+ // the bar, unless the time cap or the round cap was reached, which ends
11
+ // it below the bar with that said plainly;
12
+ // - every tier's frame time measured on the space as it is now (the perf
13
+ // field nw_check measures and nw_status reads back) is within its line,
14
+ // and a missing reading is asked for once;
15
+ // - what it carries fits a planet (loop/capacity.mjs);
16
+ // - the approval card was shown after the last round, and a "one more
17
+ // round" from it was run.
18
+ //
19
+ // A space request that built without its kickoff is held too, once it
20
+ // changed something (unkicked): the loop is not optional. A big job still
21
+ // waiting for its cost approval (an unanswered kickoff, then an unanswered
22
+ // cost card) is not held: nothing can be built until the creator answers,
23
+ // and its reply says so.
24
+ //
25
+ // The gate counts only the blocks after which no round was judged: a run
26
+ // that keeps judging rounds is working toward its bar, and its caps end it,
27
+ // while one that only stops again is let go after the level's round cap and
28
+ // four more of those. The last of them says so, and asks the reply to say
29
+ // plainly where it ended (below the bar, before the floor, or not judged);
30
+ // the done event says the same (released), so the chat can show it.
31
+
32
+ import { FRAME_MS } from './levels.mjs'
33
+
34
+ const fmt = (n, d = 1) => (Number.isFinite(n) ? String(Number(n.toFixed(d))) : '?')
35
+
36
+ /**
37
+ * A perf reading ({ tiers: { high?, medium?, low? }, measuredAt }, each tier
38
+ * { frameMsP50, frameMsP95, drawCalls, triangles, gpuMemMB, budgetMs, ok })
39
+ * against each tier's line: { state: 'absent' | 'ok' | 'over', over: [...] }.
40
+ */
41
+ export function perfVerdict(perf) {
42
+ const tiers = perf && typeof perf === 'object' && perf.tiers && typeof perf.tiers === 'object' ? perf.tiers : null
43
+ const measured = tiers ? Object.entries(tiers).filter(([, t]) => t && Number.isFinite(Number(t.frameMsP95))) : []
44
+ if (measured.length === 0) return { state: 'absent', over: [], tiers: {} }
45
+ const over = []
46
+ for (const [tier, t] of measured) {
47
+ const line = Number.isFinite(Number(t.budgetMs)) ? Number(t.budgetMs) : FRAME_MS[tier]
48
+ const p95 = Number(t.frameMsP95)
49
+ // unsure: read before the space had loaded (eyes.mjs), so not a verdict on the space.
50
+ if (t.ok === false || (Number.isFinite(line) && p95 > line)) over.push({ tier, p95, line, unsure: t.unsure === true })
51
+ }
52
+ return { state: over.length ? 'over' : 'ok', over, tiers: Object.fromEntries(measured.map(([tier, t]) => [tier, { frameMsP95: Number(t.frameMsP95) }])) }
53
+ }
54
+
55
+ /** A perf reading wherever a status answer carries it (main's 'status' rpc, a tool result). */
56
+ export function perfIn(value) {
57
+ if (!value || typeof value !== 'object') return null
58
+ if (value.tiers && typeof value.tiers === 'object') return value
59
+ for (const at of [value.perf, value.live?.perf, value.runtime?.perf]) if (at && typeof at === 'object' && at.tiers) return at
60
+ return null
61
+ }
62
+
63
+ const gapLine = (gaps) =>
64
+ (gaps ?? [])
65
+ .slice(0, 3)
66
+ .map((g) => `${g.where ? `${g.where}: ` : ''}${g.what}`)
67
+ .join('; ')
68
+
69
+ /** Where a loop stands against its floor and its bar, in the words a reply
70
+ * owes the creator when it ends there; empty when it is at both. */
71
+ export function standing(loop) {
72
+ const parts = []
73
+ const spent = loop.elapsedMin()
74
+ const floor = loop.budget?.timeFloorMin ?? 0
75
+ if (spent < floor) parts.push(`before the time floor (${Math.floor(spent)} of ${floor} minutes)`)
76
+ const least = loop.minRounds?.() ?? 0
77
+ const judged = loop.judgedRounds?.() ?? loop.rounds?.length ?? 0
78
+ if (judged < least) parts.push(`before its ${least} rounds (${judged} judged)`)
79
+ const last = loop.last()
80
+ const bar = loop.bar?.judge ?? null
81
+ if (loop.targets.none) parts.push(`not judged against target pictures (${loop.targets.none})`)
82
+ else if (!loop.reached()) {
83
+ if (!last) parts.push('with no round judged')
84
+ else if (!loop.judgedAll(last)) parts.push(`below the bar, round ${last.n} not having scored every hero view with a target`)
85
+ else parts.push(`below the bar (round ${last.n}: ${Number.isFinite(last.score) ? fmt(last.score) : 'not judged'} of ${fmt(bar)})`)
86
+ }
87
+ return parts
88
+ }
89
+
90
+ /**
91
+ * @param {{ loop: object, fingerprint: () => Promise<string>, perfNow?: () => Promise<object | null>,
92
+ * capacityNow?: () => Promise<{ problems: string[] } | null>, unkicked?: () => Promise<boolean>,
93
+ * waitingOnCost?: () => boolean }} deps
94
+ * unkicked: whether this request builds a space and changed it with no
95
+ * kickoff yet (host.mjs), which the gate holds until the kickoff is shown.
96
+ * waitingOnCost: a big job with no cost approved whose cost card went
97
+ * unanswered (host.mjs), which can build nothing until the creator
98
+ * approves one.
99
+ */
100
+ export function createLoopGate({ loop, fingerprint, perfNow = async () => null, capacityNow = async () => null, unkicked = async () => false, waitingOnCost = () => false }) {
101
+ let blocks = 0
102
+ let idle = 0
103
+ let roundsAtBlock = loop.rounds?.length ?? 0
104
+ let perfAsked = false
105
+ let released = null
106
+
107
+ const gate = {
108
+ get blocks() {
109
+ return blocks
110
+ },
111
+ /** What the gate let go with when it stopped holding a loop that was not
112
+ * done (its idle blocks used up): { outstanding, standing }, else null. */
113
+ get released() {
114
+ return released
115
+ },
116
+ /** What still holds the loop, as { items, lead, below, honest } (empty items: it may end). */
117
+ async items() {
118
+ if (!loop.active) {
119
+ if (!loop.kickoff && (await unkicked().catch(() => false))) {
120
+ return {
121
+ items: ['show the kickoff card first (nw_ask_kickoff): this request builds a space, and a space is a loop against target pictures. Then the targets (image_generate kind "target", nw_ask_targets), brief.json citing them, rounds judged with nw_round, and the approval card'],
122
+ lead: 'This space was built without its kickoff.',
123
+ below: false,
124
+ honest: '',
125
+ }
126
+ }
127
+ return { items: [], lead: '', below: false, honest: '' }
128
+ }
129
+ if (waitingOnCost()) return { items: [], lead: '', below: false, honest: '' }
130
+ const items = []
131
+ const t = loop.targets
132
+ if (!t.settled) items.push('settle the target pictures: image_generate kind "target" at the hero views you planned (or the creator\'s attached photos when there are four or more), then nw_ask_targets')
133
+ const last = loop.last()
134
+ const fp = await fingerprint()
135
+ const all = !!last && loop.judgedAll(last)
136
+ const capped = loop.capped()
137
+ // At the round cap no round is left, and past the time cap only one
138
+ // (nw_round's final round): the gate never asks for one nw_round refuses.
139
+ const finalTaken = capped.time && !!last && Number.isFinite(last.elapsedMin) && last.elapsedMin >= (loop.budget?.timeCapMin ?? Infinity)
140
+ const canRound = !capped.rounds && !finalTaken
141
+ if (!last) items.push('judge a round with nw_round at the hero views')
142
+ else if (canRound && last.fingerprint !== fp) items.push(`judge a round with nw_round on the space as it is now (it changed after round ${last.n})`)
143
+ else if (canRound && t.settled && !t.none && !all) {
144
+ const missing = t.images.map((i) => i.hero).filter((h) => !Number.isFinite(last.views?.[h]))
145
+ items.push(`judge a round on every hero view with a target (round ${last.n} did not score ${missing.join(', ')}; a view still loading is not scored): nw_round with no heroes`)
146
+ }
147
+ const bar = loop.bar?.judge ?? null
148
+ let below = false
149
+ if (last && !t.none && bar !== null) below = !loop.reached()
150
+ if (!capped.any) {
151
+ const spent = loop.elapsedMin()
152
+ const floor = loop.budget?.timeFloorMin ?? 0
153
+ if (spent < floor) items.push(`keep working to the level's time floor (${Math.floor(spent)} of ${floor} minutes have gone; ending before it means something is missing): take ${last ? `round ${last.n}'s top differences (${gapLine(last.gaps) || 'see its scores.json'})` : 'the targets'} into the next round`)
154
+ // A quality step has no floor: it judges at least its minRounds
155
+ // rounds, and only then may its bar end it.
156
+ const least = loop.minRounds?.() ?? 0
157
+ const judged = loop.judgedRounds?.() ?? loop.rounds?.length ?? 0
158
+ if (last && judged < least && !(below && all)) items.push(`judge at least ${least} rounds at this quality step (${judged} so far, counting only rounds that scored every hero view on a space changed since the one before): take round ${last.n}'s top differences (${gapLine(last.gaps) || 'see its scores.json'}) into the next round and judge it with nw_round`)
159
+ if (below && all) items.push(`round ${last.n} scored ${Number.isFinite(last.score) ? fmt(last.score) : 'nothing (not judged)'} against the bar of ${fmt(bar)}: plan the next round on its top differences (${gapLine(last.gaps) || 'its scores.json'}) and judge it with nw_round`)
160
+ const approval = loop.approval
161
+ if (approval?.answer === 'another' && last && approval.afterRound === last.n) items.push(`run the round the creator asked for on the approval card${approval.note ? ` ("${approval.note}")` : ''}, then show the approval card again`)
162
+ }
163
+ const perf = perfVerdict(await perfNow().catch(() => null))
164
+ if (perf.state === 'over' && perf.over.every((o) => o.unsure)) items.push('measure the frame time again with nw_check once the space has loaded (the last reading was taken before it had, so it says nothing yet)')
165
+ else if (perf.state === 'over') items.push(`bring the frame time within its line (${perf.over.map((o) => `${o.tier} tier p95 ${fmt(o.p95)} ms against ${fmt(o.line)} ms`).join(', ')}): instancing, distance LODs, fewer draw calls and lighter materials, then measure again with nw_check`)
166
+ else if (perf.state === 'absent' && last && !perfAsked) {
167
+ // Asked once: a studio whose status carries no perf has no reading to give.
168
+ perfAsked = true
169
+ items.push('measure the frame time on the space as it is now with nw_check (its perf field, by tier, at the spawn and every hero view; nw_status only reads what nw_check kept); with no reading, the approval card says it was not measured')
170
+ }
171
+ const cap = await capacityNow().catch(() => null)
172
+ if (cap?.problems?.length) items.push(`make it fit a planet: ${cap.problems.slice(0, 4).join(' ')}`)
173
+ // The approval card after the last round, unless the round the creator
174
+ // asked for is still to come (said above).
175
+ const shown = loop.approval && last && loop.approval.afterRound === last.n
176
+ if (last && items.length === 0 && !shown) items.push('show the approval card (nw_ask_approval) with the last round\'s views; publishing waits for the creator\'s press')
177
+ const lead = capped.any && below ? `The ${capped.time ? 'time cap' : 'round cap'} is reached below the bar (round ${last.n}: ${Number.isFinite(last.score) ? fmt(last.score) : 'not judged'} of ${fmt(bar)}).` : 'The reference loop is not done yet.'
178
+ // What the reply owes the creator when it may end here: below the bar
179
+ // at a cap, or rounds that no judge scored.
180
+ const where = (capped.any && below) || t.none ? standing(loop) : []
181
+ return { items, lead, below: capped.any && below, honest: where.length ? ` In your reply, say plainly that it ended ${where.join(', ')}.` : '' }
182
+ },
183
+ /** The Stop decision for the loop: a reason to go on, or null. */
184
+ async stopReason({ max } = {}) {
185
+ if (released) return null
186
+ const limit = Number.isFinite(max) ? max : (loop.budget?.roundCap ?? 2) + 4
187
+ const { items, lead, honest } = await gate.items()
188
+ if (items.length === 0) return null
189
+ // Only a block after which no round was judged counts toward the limit.
190
+ const rounds = loop.rounds?.length ?? 0
191
+ if (rounds === roundsAtBlock) idle++
192
+ roundsAtBlock = rounds
193
+ const where = loop.active ? standing(loop) : ['without its kickoff, its targets or a judged round']
194
+ if (idle > limit) {
195
+ released = { outstanding: items.map((i) => i.split(/[:(]/)[0].trim().slice(0, 120)), standing: where }
196
+ return null
197
+ }
198
+ blocks++
199
+ const lastHold = idle === limit
200
+ const final = lastHold ? ` This is the last time the stop gate holds this request: if you stop instead, your reply must say plainly that it ended ${where.length ? where.join(', ') : 'before the reference loop was done'}, and what is left.` : honest
201
+ return `${lead} Before you finish: ${items.join('; ')}.${final}`
202
+ },
203
+ }
204
+ return gate
205
+ }
@@ -0,0 +1,189 @@
1
+ // The reference loop's judge (REFERENCE_LOOP.md 2.5): a run apart from the
2
+ // build, with no conversation behind it. It sees the target picture and the
3
+ // still at each hero view, the rubric and the slop list, and nothing the
4
+ // builder said: a judge briefed by the builder is the builder's eye again.
5
+ //
6
+ // Claude judges as its own session through the Agent SDK (no tools, one
7
+ // turn, its own system prompt, subagents.mjs JUDGE_PROMPT), run from the
8
+ // scratch folder so it is not one of the project's conversations. With an
9
+ // OpenAI key connected it is asked too, through the other vendors' plumbing
10
+ // (agent-loop.mjs respondOnce), and the lower score stands: two judges that
11
+ // disagree mean the space is not there yet. Both are paid calls; their cost
12
+ // goes into the request's spend (the Claude one as a helper's usage, the
13
+ // OpenAI one as a generation), and every check stands a fake in for them.
14
+
15
+ import { promptFor } from '../../userMessage.mjs'
16
+ import { respondOnce } from '../../agent-loop.mjs'
17
+ import { JUDGE_PROMPT } from '../subagents.mjs'
18
+ import { MODELS, keyedServices, pricingFor } from '../shared.mjs'
19
+ import { judgeCallUsd } from './levels.mjs'
20
+
21
+ const SEVERITY = { high: 0, medium: 1, low: 2 }
22
+ /** The effort the Claude judge thinks at. */
23
+ export const JUDGE_EFFORT = 'xhigh'
24
+ /** Whether a Claude model id thinks adaptively (models.json thinking). */
25
+ const claudeModel = (id) => MODELS.providers.find((p) => p.runtime === 'claude-agent-sdk')?.models.find((m) => m.id === id) ?? null
26
+ const adaptive = (id) => claudeModel(id)?.thinking === 'adaptive'
27
+ /** JUDGE_EFFORT, held to a model's effort ceiling (models.json effortCeiling). */
28
+ const EFFORT_ORDER = ['low', 'medium', 'high', 'xhigh', 'max']
29
+ const judgeEffort = (id) => {
30
+ const ceiling = EFFORT_ORDER.indexOf(claudeModel(id)?.effortCeiling)
31
+ return ceiling >= 0 && ceiling < EFFORT_ORDER.indexOf(JUDGE_EFFORT) ? EFFORT_ORDER[ceiling] : JUDGE_EFFORT
32
+ }
33
+ const clamp10 = (v) => Math.min(10, Math.max(0, v))
34
+ const round1 = (v) => Math.round(v * 10) / 10
35
+
36
+ /** The JSON object in a judge's answer (it may wrap it in a fence or a word). */
37
+ export function parseVerdict(text, heroes) {
38
+ const raw = String(text ?? '')
39
+ const start = raw.indexOf('{')
40
+ const end = raw.lastIndexOf('}')
41
+ if (start < 0 || end <= start) return { ok: false, error: 'the judge answered with no JSON' }
42
+ let doc
43
+ try {
44
+ doc = JSON.parse(raw.slice(start, end + 1))
45
+ } catch {
46
+ return { ok: false, error: 'the judge\'s JSON did not parse' }
47
+ }
48
+ const views = {}
49
+ for (const h of heroes) {
50
+ const v = Number(doc?.views?.[h])
51
+ if (Number.isFinite(v)) views[h] = round1(clamp10(v))
52
+ }
53
+ const scored = Object.values(views)
54
+ if (scored.length === 0) return { ok: false, error: 'the judge scored none of the hero views' }
55
+ const lo = Math.min(...scored)
56
+ const hi = Math.max(...scored)
57
+ const mean = scored.reduce((a, b) => a + b, 0) / scored.length
58
+ const given = Number(doc?.overall)
59
+ // Its own overall, held between its worst and its best view.
60
+ const overall = round1(Number.isFinite(given) ? Math.min(hi, Math.max(lo, clamp10(given))) : mean)
61
+ const gaps = (Array.isArray(doc?.gaps) ? doc.gaps : [])
62
+ .filter((g) => g && typeof g.what === 'string' && g.what.trim())
63
+ .slice(0, 8)
64
+ .map((g) => ({ where: String(g.where ?? '').slice(0, 160), what: String(g.what).trim().slice(0, 300), severity: SEVERITY[g.severity] !== undefined ? g.severity : 'medium' }))
65
+ return { ok: true, views, overall, gaps, notes: String(doc?.notes ?? '').slice(0, 600) }
66
+ }
67
+
68
+ /** Words that turn a slop entry into a message to the judge. */
69
+ const NOT_SLOP = /\b(score|scored|scores|judge|judged|rate|rating|rated|target|targets|match|matches|matched|view|views|bar|pass|passes|ignore|should|must|give|award|perfect|correct|already|done|fine|good|great|excellent|close|same)\b/i
70
+
71
+ /**
72
+ * The brief's own slop entries the judge may read. brief.json is the
73
+ * builder's, and the judge must see only pictures and the rubric, so an
74
+ * entry passes only as a short name of a thing to avoid: at most eight
75
+ * words and 60 characters, no digits, no sentence, and none of the words a
76
+ * claim about the score would need ("every view matches its target").
77
+ */
78
+ export function slopForJudge(extra = []) {
79
+ if (!Array.isArray(extra)) return []
80
+ return extra
81
+ .filter((s) => typeof s === 'string')
82
+ .map((s) => s.trim())
83
+ .filter((s) => s.length > 0 && s.length <= 60 && s.split(/\s+/).length <= 8 && !/\d/.test(s) && !/[.!?:;"]/.test(s) && !NOT_SLOP.test(s))
84
+ .slice(0, 12)
85
+ }
86
+
87
+ /** The words that go with the pictures: which picture is which, the slop,
88
+ * how many pictures of the creator's other spaces follow the pairs, and
89
+ * how many web pictures the place is modelled on come last. */
90
+ export function judgeText(heroes, slop = [], others = 0, references = 0) {
91
+ const lines = ['The pictures come in pairs, one pair per hero view, in this order:']
92
+ heroes.forEach((h, i) => lines.push(`- pictures ${i * 2 + 1} and ${i * 2 + 2}: ${h}, the target, then the still`))
93
+ if (others > 0) lines.push(`- pictures ${heroes.length * 2 + 1} to ${heroes.length * 2 + others}: the creator's other spaces, which this one must not look like`)
94
+ const from = heroes.length * 2 + others + 1
95
+ if (references > 0) lines.push(`- pictures ${from} to ${from + references - 1}: pictures the place is modelled on, found on the web; hold the stills to them only where the targets agree`)
96
+ if (slop.length) lines.push('', 'The slop list (score down whatever of it a still shows):', ...slop.map((s) => `- ${s}`))
97
+ lines.push('', `Answer with the JSON object only, scoring ${heroes.join(', ')}.`)
98
+ return lines.join('\n')
99
+ }
100
+
101
+ /**
102
+ * Claude, as a session of its own. `query` is the SDK's (or a check's
103
+ * stand-in); `onUsage` hears each assistant message for the spend.
104
+ */
105
+ export async function judgeWithClaude({ query, model, env, cwd, pairs, slop, others = [], references = [], onUsage, signal }) {
106
+ const heroes = pairs.map((p) => p.hero)
107
+ const images = [...pairs.flatMap((p) => [p.target, p.still]), ...others, ...references]
108
+ let text = ''
109
+ const session = query({
110
+ prompt: promptFor(judgeText(heroes, slop, others.length, references.length), images),
111
+ options: {
112
+ cwd,
113
+ model,
114
+ tools: [],
115
+ mcpServers: {},
116
+ strictMcpConfig: true,
117
+ settingSources: [],
118
+ systemPrompt: JUDGE_PROMPT,
119
+ maxTurns: 1,
120
+ // xhigh, with adaptive thinking on a model that has it (models.json thinking).
121
+ effort: judgeEffort(model),
122
+ ...(adaptive(model) ? { thinking: { type: 'adaptive' } } : {}),
123
+ env: { ...env, CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS: '1' },
124
+ permissionMode: 'default',
125
+ canUseTool: async () => ({ behavior: 'deny', message: 'The judge has no tools.' }),
126
+ },
127
+ })
128
+ for await (const m of session) {
129
+ if (m.type === 'assistant') {
130
+ onUsage?.(m)
131
+ for (const b of m.message?.content ?? []) if (b.type === 'text') text += b.text
132
+ } else if (m.type === 'result' && typeof m.result === 'string' && m.result) text = m.result
133
+ }
134
+ const verdict = parseVerdict(text, heroes)
135
+ return { ...verdict, model }
136
+ }
137
+
138
+ /** The OpenAI model the second judge runs on: the first that takes pictures. */
139
+ export function openaiJudgeModel() {
140
+ const provider = MODELS.providers.find((p) => p.id === 'openai')
141
+ const model = provider?.models.find((m) => m.images) ?? null
142
+ return provider && model ? { provider, model } : null
143
+ }
144
+
145
+ /** OpenAI's key variable, from the connector catalog. */
146
+ export const openaiKeyVar = () => keyedServices().find((s) => s.id === 'openai')?.envVar ?? 'OPENAI_API_KEY'
147
+
148
+ /** OpenAI through the Responses API, when its key is connected. */
149
+ export async function judgeWithOpenAI({ apiKey, pairs, slop, others = [], references = [], fetchImpl, signal }) {
150
+ const found = openaiJudgeModel()
151
+ if (!found) return { ok: false, error: 'no OpenAI model that takes pictures in models.json' }
152
+ const heroes = pairs.map((p) => p.hero)
153
+ const baseUrl = (process.env.OPENAI_BASE_URL ?? '').trim() || found.provider.baseUrl
154
+ const r = await respondOnce({ baseUrl, apiKey, model: found.model.id, system: JUDGE_PROMPT, text: judgeText(heroes, slop, others.length, references.length), images: [...pairs.flatMap((p) => [p.target, p.still]), ...others, ...references], signal, fetchImpl })
155
+ const usd = judgeCallUsd(pricingFor(found.model), { input_tokens: r.usage.input, output_tokens: r.usage.output })
156
+ return { ...parseVerdict(r.text, heroes), model: found.model.id, usd }
157
+ }
158
+
159
+ /**
160
+ * Both judges' verdicts as one: the lower overall stands, each view at its
161
+ * lower score, the gaps of both with the most severe first. Null when none
162
+ * scored.
163
+ */
164
+ export function lowerOf(verdicts) {
165
+ const ok = verdicts.filter((v) => v?.ok)
166
+ if (ok.length === 0) return null
167
+ const lowest = ok.reduce((a, b) => (b.overall < a.overall ? b : a))
168
+ const views = {}
169
+ for (const v of ok) for (const [h, s] of Object.entries(v.views)) views[h] = views[h] === undefined ? s : Math.min(views[h], s)
170
+ const seen = new Set()
171
+ const gaps = ok
172
+ .flatMap((v) => v.gaps)
173
+ .filter((g) => {
174
+ const k = `${g.where}|${g.what}`.toLowerCase()
175
+ if (seen.has(k)) return false
176
+ seen.add(k)
177
+ return true
178
+ })
179
+ .sort((a, b) => SEVERITY[a.severity] - SEVERITY[b.severity])
180
+ .slice(0, 8)
181
+ const models = ok.map((v) => v.model).filter(Boolean)
182
+ return {
183
+ overall: lowest.overall,
184
+ views,
185
+ gaps,
186
+ judge: { model: ok.length > 1 ? `${models.join(' and ')} (the lower: ${lowest.model})` : lowest.model, notes: ok.filter((v) => v.notes).map((v) => (ok.length > 1 ? `${v.model}: ${v.notes}` : v.notes)).join(' ') },
187
+ scores: ok.map((v) => ({ model: v.model, overall: v.overall })),
188
+ }
189
+ }