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,858 @@
1
+ // The reference loop as tools (REFERENCE_LOOP.md 2): what the agent asks the
2
+ // creator, once, at the start of a space and at its end, and the round it
3
+ // runs in between.
4
+ //
5
+ // nw_ask_kickoff the one card of questions, once a loop: up to four, how
6
+ // the environment is made (in 3D, from a file, or
7
+ // Marble), and the speed level, each with its time and its
8
+ // cost on this model. The creator's answer is the cost
9
+ // approval for the level's upper estimate; no answer
10
+ // approves nothing (the level's times and bar still
11
+ // stand). It sets the level's floor, cap, rounds and bar
12
+ // (brief.json budget and bar), and is the last question
13
+ // that waits on the creator in the request.
14
+ // nw_ask_targets the target pictures (image_generate kind target, or the
15
+ // creator's own photos) with their palettes and hero
16
+ // views: kept, dropped, or sent back with notes to be
17
+ // drawn again (three times at most). The kept ones go on
18
+ // the reference board and into brief.json's references as
19
+ // R ids, which its hero views cite. A target is only one
20
+ // of those two: a still of the space, a web picture or a
21
+ // picture with no record is refused, and "no targets" only
22
+ // stands with no generator here and too few photos.
23
+ // nw_round one round, after the agent's changes: nw_check, a still
24
+ // at each hero view from the target's own camera once
25
+ // the space has loaded, the "target | now" picture,
26
+ // look_compare's numbers, the zero-context judge's score
27
+ // (loop/judge.mjs), the round's folder
28
+ // (.nowhere/rounds/<n>/) and its message in the chat. It
29
+ // never waits on the creator, and runs only on a brief
30
+ // whose hero views cite the settled targets from their
31
+ // cameras; past the time cap it runs once more, the last.
32
+ // nw_ask_approval the last card: the final pictures, the scores round by
33
+ // round, what the planet weighs and its frame time. Only
34
+ // the creator's Publish publishes: its token goes back to
35
+ // the studio's publish path and never to the model.
36
+ //
37
+ // The loop's state is the host's (loop/state.mjs, ctx.loop), and so are the
38
+ // judge (ctx.judge), the chat message (ctx.post) and the perf reading
39
+ // (ctx.run.perf). A host without them (a check's bare ctx) gets the answer
40
+ // that it cannot run the loop. The cards are cards.cjs's kickoff, targets
41
+ // and approval.
42
+
43
+ import { createHash } from 'node:crypto'
44
+ import fs from 'node:fs'
45
+ import fsp from 'node:fs/promises'
46
+ import { createRequire } from 'node:module'
47
+ import path from 'node:path'
48
+ import { z } from 'zod'
49
+ import { compareLook } from '../../schema/dist/index.js'
50
+ import { readBrief, recordLoop, recordReferences } from '../assets/brief.mjs'
51
+ import { IMAGE_PROVIDERS } from '../assets/images/index.mjs'
52
+ import { capacityOf } from '../loop/capacity.mjs'
53
+ import { compose } from '../loop/compose.mjs'
54
+ import { perfVerdict } from '../loop/gate.mjs'
55
+ import { openaiJudgeModel, slopForJudge } from '../loop/judge.mjs'
56
+ import { DEFAULT_LEVEL, JUDGE_PX, MAX_TARGETS, MIN_TARGETS, QUALITY, SLOP, environmentsFor, estimateLevels, estimateQuality, levelFor, levelsFor, qualityOf, targetPrice } from '../loop/levels.mjs'
57
+ import { ROUNDS_DIR, judgedAll } from '../loop/state.mjs'
58
+ import { decodeImage } from '../reference/decode.mjs'
59
+ import { fitEdge, shapeOf } from '../reference/facts.mjs'
60
+ import { encodePng } from '../reference/png.mjs'
61
+ import { briefWebReferences } from '../reference/web.mjs'
62
+ import { pricingFor } from '../shared.mjs'
63
+ import { viewTimeout } from './eyes.mjs'
64
+ import { LOOK_SETTLE_MS, notJudged, readReference } from './look.mjs'
65
+
66
+ const require = createRequire(import.meta.url)
67
+ const refBoard = require('../../refBoard.cjs')
68
+ let localeModule
69
+ try {
70
+ localeModule = require('../locale.cjs')
71
+ } catch {
72
+ localeModule = null
73
+ }
74
+
75
+ export const RPC_METHODS = ['ask', 'build', 'view', 'pixels', 'publish']
76
+
77
+ /** cards.cjs closes a kickoff or targets card after ten minutes; the rpc waits longer. */
78
+ const TIMED_ASK_MS = 11 * 60_000
79
+ /** The approval card waits as long as any card. */
80
+ const APPROVAL_ASK_MS = 31 * 60_000
81
+ /** A publish takes as long as its upload (a 100 MB planet on a slow line);
82
+ * past this the tool says it is still running rather than that it failed. */
83
+ const PUBLISH_MS = 45 * 60_000
84
+ const HERO = z.enum(['H1', 'H2', 'H3', 'H4', 'H5', 'H6'])
85
+ const OPTION_ID = /^[a-z0-9-]{1,30}$/
86
+
87
+ const fail = (text) => ({ text, isError: true })
88
+ const fmt = (n, d = 1) => (Number.isFinite(n) ? String(Number(n.toFixed(d))) : '?')
89
+ const slash = (p) => p.split(path.sep).join('/')
90
+
91
+ /** The words of a card that are not in the screen language its labels are
92
+ * drawn in (ctx.locale), or null (as nw_ask). */
93
+ function languageProblem(words, locale, what = 'this card', parts = 'its title, questions and labels') {
94
+ const writtenIn = localeModule?.writtenIn
95
+ if (typeof writtenIn !== 'function' || !locale) return null
96
+ if (writtenIn(words.filter((w) => typeof w === 'string').join('\n'), locale) !== false) return null
97
+ const name = localeModule.LANGUAGE_NAMES?.[localeModule.languageOf?.(locale) ?? locale] ?? locale
98
+ return `Cards are in the screen language, ${name}, and ${what} is not in it. Write ${parts} in ${name} (the screen language, not the one the creator writes in), then call it again.`
99
+ }
100
+
101
+ async function askCard(ctx, card, timeoutMs) {
102
+ try {
103
+ return await ctx.rpc('ask', { runId: ctx.runId, locale: ctx.locale, card }, timeoutMs)
104
+ } catch (err) {
105
+ return { ok: false, error: err?.message ?? String(err) }
106
+ }
107
+ }
108
+
109
+ /** A loop card nobody answered: the contract's timedOut, or the older bare "timeout". */
110
+ const unanswered = (r) => r?.timedOut === true || r?.answer === 'timeout'
111
+
112
+ /** The loop this request runs, or the reason there is none. */
113
+ function loopOf(ctx) {
114
+ if (!ctx?.projectRoot) return { error: 'No project is open.' }
115
+ if (!ctx.loop) return { error: 'This host does not run the reference loop (no loop state here).' }
116
+ return { loop: ctx.loop }
117
+ }
118
+
119
+ /** brief.json takes the loop's numbers where there is one; the answer says where they go otherwise. */
120
+ async function briefNote(root, patch) {
121
+ const r = await recordLoop(root, patch)
122
+ if (r.status === 'written' || r.status === 'unchanged') return 'brief.json carries them now.'
123
+ if (r.status === 'absent') return `When you write brief.json, put these in it: ${JSON.stringify(patch)} (budget beside assetsMb).`
124
+ return `brief.json was left as it is (${r.error}); put these in it when you fix it: ${JSON.stringify(patch)}.`
125
+ }
126
+
127
+ // ---------------------------------------------------------------- nw_ask_kickoff
128
+
129
+ const KICKOFF_SHAPE = {
130
+ title: z.string().min(1).max(80).describe("The card's title, in the screen language: the space in a few words."),
131
+ questions: z
132
+ .array(
133
+ z.object({
134
+ id: z.string().regex(OPTION_ID),
135
+ text: z.string().min(1).max(200).describe("In the screen language."),
136
+ options: z.array(z.object({ id: z.string().regex(OPTION_ID), label: z.string().min(1).max(60), detail: z.string().max(160).optional() })).min(2).max(6).optional(),
137
+ free: z.boolean().optional().describe('A short typed answer instead of (or beside) options.'),
138
+ }),
139
+ )
140
+ .max(4)
141
+ .default([])
142
+ .describe('0 to 4 questions whose answers change the space: for a place, its size, its hour, what it is for; for a game, the goal, how a visitor wins and loses, and how long one play should last. Ask everything here: nothing after this card waits on the creator.'),
143
+ imageProvider: z.string().optional().describe('The generator the target pictures will come from (codex, openai, gemini, fal, stability), for their price on the card. Default openai.'),
144
+ }
145
+
146
+ const KICKOFF_DESCRIPTION =
147
+ "The kickoff card for a new space or a large change, before anything else: up to four questions and how the environment is made (built in 3D, a file the creator uploads, or generated with Marble, which is paid and asks its own cost card first). When the request carries no quality step, the card also offers the speed level (quick, standard or deep), each with its time and its cost on this model, the target pictures and the judge included, and its answer approves the cost of the level picked; with a quality step the creator set it already, and the card does not ask it. The creator answers once; with no answer in 10 minutes it builds in 3D. It sets the time floor, the time cap, the round cap and the judge's bar the request is held to (written into brief.json). Ask every question here: after it, nothing waits on the creator."
148
+
149
+ async function askKickoff(args, ctx) {
150
+ const { loop, error } = loopOf(ctx)
151
+ if (error) return fail(error)
152
+ // Once a loop: a second kickoff would approve its cost again and start its
153
+ // rounds and its clock over, with or without the creator.
154
+ if (loop.kickoff) {
155
+ const k = loop.kickoff
156
+ return fail(`The kickoff card was shown already for this space (${k.level}${k.timedOut ? ', with no answer' : k.unavailable ? ', with no studio to ask' : ''}${k.approvedUsd !== null && k.approvedUsd !== undefined ? `, cost approved up to $${Number(k.approvedUsd).toFixed(2)}` : ', no cost approved'}). It is asked once: go on at that level. ${k.approvedUsd === null || k.approvedUsd === undefined ? 'For a cost approval, ask with nw_ask kind "cost".' : 'When the spend will pass the approval, ask again with nw_ask kind "cost".'}`)
157
+ }
158
+ const unreadable = languageProblem([args.title, ...args.questions.flatMap((q) => [q.text, ...(q.options ?? []).flatMap((o) => [o.label, o.detail])])], ctx.locale)
159
+ if (unreadable) return fail(unreadable)
160
+ if (args.questions.some((q) => !q.options && q.free !== true)) return fail('Each question needs options, or free: true for a short typed answer.')
161
+ const provider = args.imageProvider && IMAGE_PROVIDERS[args.imageProvider] ? args.imageProvider : 'openai'
162
+ const second = typeof ctx.secret === 'function' && ctx.judgeKeys?.openai ? openaiJudgeModel() : null
163
+ const secondCard = second ? pricingFor(second.model) : null
164
+ // A quality step (the composer's gauge, --quality) set the level already:
165
+ // the card asks the rest, and offers no level.
166
+ const quality = qualityOf(ctx.quality)
167
+ const levels = quality ? [] : levelsFor(ctx.locale, estimateLevels({ pricing: ctx.model?.pricing ?? null, judge: secondCard, targetUsd: targetPrice(provider) }))
168
+ const card = { kind: 'kickoff', origin: 'agent', title: args.title, questions: args.questions, environment: { options: environmentsFor(ctx.locale) }, levels, ...(quality ? {} : { defaultLevel: DEFAULT_LEVEL }) }
169
+ const r = await askCard(ctx, card, TIMED_ASK_MS)
170
+ if (r?.answer === 'cancelled') return { text: 'The request was stopped.' }
171
+ if (r && r.ok === false && r.answer === undefined && !unanswered(r)) return fail(`The card could not be shown: ${r.error ?? 'the studio did not answer'}.`)
172
+ // The card's own no-answer shape (cards.cjs) is timedOut with answer
173
+ // saying why: no window showed it is unavailable, not the creator away.
174
+ const unavailable = !r || r.answer === 'unavailable'
175
+ const timedOut = !unavailable && unanswered(r)
176
+ const answered = !timedOut && !unavailable
177
+ const level = quality ? null : answered && levels.some((l) => l.id === r.level) ? r.level : DEFAULT_LEVEL
178
+ const environment = answered && ['mesh', 'upload', 'marble'].includes(r.environment) ? r.environment : null
179
+ const answers = answered && r.answers && typeof r.answers === 'object' ? r.answers : {}
180
+ const usd = quality
181
+ ? estimateQuality(quality, { pricing: ctx.model?.pricing ?? null, judge: secondCard, targetUsd: targetPrice(provider) }).usd
182
+ : (levels.find((l) => l.id === level)?.usd ?? null)
183
+ // The creator's answer approves the level's upper estimate, once a loop
184
+ // (the kickoff is asked once). No answer, or no studio to ask, approves
185
+ // nothing: money is asked first (REFERENCE_LOOP.md 1), so the level's
186
+ // times and bar stand and a cost card still has to be answered before
187
+ // anything is built. With a quality step the card offers no level, so its
188
+ // answer approves nothing: what the request was sent with stands.
189
+ let approvedUsd = quality ? (ctx.ledger?.approvedUsd?.() ?? null) : null
190
+ if (!quality && answered && usd && typeof ctx.ledger?.approve === 'function') {
191
+ ctx.ledger.approve(usd.hi)
192
+ approvedUsd = usd.hi
193
+ }
194
+ await loop.kick({ level, quality, answers, environment, timedOut, unavailable, usd, approvedUsd })
195
+ const l = levelFor({ level, quality })
196
+ const named = quality ? `quality step ${quality} (${QUALITY[quality].name})` : level
197
+ const note = await briefNote(ctx.projectRoot, { budget: loop.budget, bar: loop.bar })
198
+ const how = {
199
+ mesh: 'Build the environment in 3D: code first (terrain, buildings, rocks, trees, water, sky and surfaces as procedural geometry and TSL), scanned CC0 libraries only for what code cannot bring to the targets, generated models for props alone.',
200
+ upload: "The creator gives the environment as a file of their own (a model, or a splat with its collider): use the one they attached or dropped into the project; until it is there, build around where it goes and say in your reply that it waits for their file.",
201
+ marble: 'Generate the environment with Marble (environment_generate): it is paid and not in this estimate, so run its estimate and ask its own cost card with nw_ask kind "cost" (the world, and the rest of the level, since an approval covers what is left) before you submit it.',
202
+ }
203
+ const range = usd ? `this level is about $${usd.lo.toFixed(2)} to $${usd.hi.toFixed(2)}` : 'this model has no price here'
204
+ const lines = [
205
+ JSON.stringify({ level: l.id, ...(quality ? { quality } : {}), environment, answers, ...(timedOut ? { timedOut: true } : {}), ...(unavailable ? { unavailable: true } : {}) }),
206
+ timedOut
207
+ ? `No answer in 10 minutes: the creator is away. It goes on at ${named}, and the environment is built in 3D (never Marble unasked).`
208
+ : unavailable
209
+ ? `There is no studio window to ask in: it goes on at ${named}, built in 3D.`
210
+ : quality
211
+ ? `The creator answered${environment ? ` and chose ${environment}` : ''}; it goes on at ${named}, which they set when they sent the request.`
212
+ : `The creator chose ${level}${environment ? ` and ${environment}` : ''}.`,
213
+ quality
214
+ ? `The level: no time floor, at least ${l.minRounds} judged round${l.minRounds === 1 ? '' : 's'} before the bar may end it, a cap of ${l.timeCapMin} minutes and ${l.roundCap} rounds, and the judge's bar ${fmt(l.bar)} of 10. Start each step by recalling the bar and the time left.`
215
+ : `The level: a time floor of ${l.timeFloorMin} minutes, a cap of ${l.timeCapMin} minutes and ${l.roundCap} rounds, and the judge's bar ${fmt(l.bar)} of 10. Start each step by recalling the bar and the time left; finishing before the floor means something is missing.`,
216
+ approvedUsd !== null
217
+ ? `Cost approved up to $${approvedUsd.toFixed(2)} for this request.`
218
+ : quality
219
+ ? `No cost was approved for this request: ask once with nw_ask kind "cost" (${range}) before you change anything.`
220
+ : answered
221
+ ? 'This model has no price here, so the kickoff approved no amount: ask with nw_ask kind "cost" before you change anything.'
222
+ : `No cost was approved: an unanswered card approves nothing. Ask once with nw_ask kind "cost" (${range}) before you change anything; if nobody answers that either, change nothing and say in your reply that the space waits for the creator's approval.`,
223
+ how[environment ?? 'mesh'],
224
+ `Next: the target pictures. With four or more photos from the creator, they are the targets (find each one's camera with nw_reference); otherwise plan ${MIN_TARGETS} to ${MAX_TARGETS} hero views (H1 is where the visitor arrives) with their cameras and make them with image_generate kind "target", then nw_ask_targets. Ask nothing more that waits on the creator: choose, and say what you chose.`,
225
+ note,
226
+ ]
227
+ return { text: lines.join('\n') }
228
+ }
229
+
230
+ // ---------------------------------------------------------------- nw_ask_targets
231
+
232
+ const TARGETS_SHAPE = {
233
+ title: z.string().min(1).max(80).optional().describe("The card's title, in the screen language (needed unless none or decide)."),
234
+ images: z
235
+ .array(
236
+ z.object({
237
+ path: z.string().min(1).max(300).describe('A target in the project: one image_generate kind "target" made (.nowhere/targets/<n>/H1.png), or a photo the creator attached (.nowhere/refs/<file>). Nothing else: never a still of the space, a capture or a picture from the web.'),
238
+ hero: HERO.describe('The hero view it stands for; brief.json\'s heroViews take its camera.'),
239
+ what: z.string().min(1).max(300).describe('In the screen language: what this view shows. brief.json cites the target with these words.'),
240
+ }),
241
+ )
242
+ .max(MAX_TARGETS)
243
+ .default([])
244
+ .describe(`${MIN_TARGETS} to ${MAX_TARGETS} targets, one hero view each.`),
245
+ none: z.string().min(1).max(300).optional().describe('Only when no target can be made or attached: no image generator is connected (no key, and Codex not allowed or not on this computer) and the creator attached fewer than four photos. Why, in a line. The rounds are then not judged against pictures, which your reply and the approval card say.'),
246
+ decide: z.boolean().optional().describe('Only after the targets card came back "you choose" or unanswered in this loop: record these as the targets with no card.'),
247
+ }
248
+
249
+ const TARGETS_DESCRIPTION =
250
+ 'Shows the target pictures in the chat (how the finished space should look from each hero view), each with its measured palette and its hero view, and waits for the creator to keep or drop each, add notes and accept, send them back to be drawn again by the notes (three times at most), or leave it to you. Comes after the kickoff and before brief.json: the kept targets go on the reference board, measured, and are recorded as brief.json references (R ids, origin target or attached); each hero view of brief.json cites its target and takes the camera it was drawn from, so every round looks from the same place. On no answer in 10 minutes they are kept as they are.'
251
+
252
+ /** A drawn target's record in its folder's source.json (image_generate kind
253
+ * target), or null when the folder does not list it. */
254
+ function targetRecord(root, rel) {
255
+ try {
256
+ const doc = JSON.parse(fs.readFileSync(path.join(root, path.dirname(rel), 'source.json'), 'utf8'))
257
+ return (doc?.targets ?? []).find((x) => x.path === rel) ?? null
258
+ } catch {
259
+ return null
260
+ }
261
+ }
262
+
263
+ /** The camera image_generate drew a target from, from its folder's record. */
264
+ function cameraOf(root, rel) {
265
+ const t = targetRecord(root, rel)
266
+ return t ? { position: t.position ?? null, lookAt: t.lookAt ?? null, fov: t.fov ?? null, view: t.view ?? null } : null
267
+ }
268
+
269
+ const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex')
270
+ const DRAWN = /^\.nowhere\/targets\/\d{1,3}\/H[1-6]\.png$/
271
+ const ON_BOARD = /^\.nowhere\/refs\/([^/]+)$/
272
+
273
+ /** A picture image_generate kind target drew: listed in its folder's
274
+ * source.json, with the bytes it recorded. */
275
+ function isDrawnTarget(root, rel, bytes) {
276
+ if (!DRAWN.test(rel)) return false
277
+ const t = targetRecord(root, rel)
278
+ return !!t && (!t.sha256 || t.sha256 === sha256(bytes))
279
+ }
280
+
281
+ /** The bytes of every still the rounds took: a still is the space itself,
282
+ * and a target made of one would judge every round against itself. */
283
+ function stillHashes(root) {
284
+ const out = new Set()
285
+ for (const n of fs.existsSync(path.join(root, ROUNDS_DIR)) ? fs.readdirSync(path.join(root, ROUNDS_DIR)) : []) {
286
+ const dir = path.join(root, ROUNDS_DIR, n)
287
+ let names = []
288
+ try {
289
+ names = fs.readdirSync(dir).filter((f) => /^(still|composite)-/.test(f))
290
+ } catch {
291
+ continue
292
+ }
293
+ for (const f of names) {
294
+ try {
295
+ out.add(sha256(fs.readFileSync(path.join(dir, f))))
296
+ } catch {
297
+ // gone since: nothing to compare
298
+ }
299
+ }
300
+ }
301
+ return out
302
+ }
303
+
304
+ /**
305
+ * Where a picture offered as a target comes from: 'target' (drawn by
306
+ * image_generate, in .nowhere/targets/ or its copy on the board), 'attached'
307
+ * (a photo the creator gave: in the chat, which keeps it under the hash of
308
+ * its bytes, or dropped on the board, with no web page or project path
309
+ * behind it), or { error } for anything else.
310
+ */
311
+ function originOf(root, rel, bytes, ctx, stills) {
312
+ if (/^\.nowhere\/rounds\//.test(rel) || stills.has(sha256(bytes))) return { error: 'that is a still of the space (a round\'s), and a target is what the space should become, never the space itself' }
313
+ if (isDrawnTarget(root, rel, bytes)) return { origin: 'target' }
314
+ const m = ON_BOARD.exec(rel)
315
+ if (!m) return { error: 'a target is a picture image_generate kind "target" drew (.nowhere/targets/<n>/H#.png) or a photo the creator attached (.nowhere/refs/<file>), and this is neither' }
316
+ const entry = refBoard.readIndex(root)?.pictures?.[m[1]] ?? {}
317
+ if (typeof entry.from === 'string') {
318
+ // A drawn target's copy on the board stands for the drawn one.
319
+ let original = null
320
+ try {
321
+ original = fs.readFileSync(path.join(root, entry.from))
322
+ } catch {
323
+ original = null
324
+ }
325
+ if (original && original.equals(bytes) && isDrawnTarget(root, entry.from, original)) return { origin: 'target', from: entry.from }
326
+ return { error: `it was copied onto the board from ${entry.from}, which is not a drawn target` }
327
+ }
328
+ if (typeof entry.url === 'string') return { error: 'it came from the web, and only the creator\'s own photos stand as targets' }
329
+ const attachedNow = (ctx.attached ?? []).some((a) => path.resolve(a) === path.resolve(root, rel))
330
+ const hashName = createHash('sha1').update(bytes).digest('hex').slice(0, 12) === m[1].replace(/\.[a-z]+$/i, '')
331
+ if (attachedNow || hashName) return { origin: 'attached' }
332
+ return { error: 'it is not a photo the creator attached (the chat keeps those under the hash of their bytes), nor a drawn target' }
333
+ }
334
+
335
+ /** The creator's photos on the board (attached in the chat or dropped on it). */
336
+ function creatorPhotos(root, ctx) {
337
+ const listed = refBoard.list(root)
338
+ if (!listed.ok) return 0
339
+ let n = 0
340
+ for (const p of listed.pictures) {
341
+ try {
342
+ const bytes = fs.readFileSync(path.join(root, p.path))
343
+ if (originOf(root, p.path, bytes, ctx, new Set()).origin === 'attached') n++
344
+ } catch {
345
+ // unreadable: not counted
346
+ }
347
+ }
348
+ return n
349
+ }
350
+
351
+ /** The image generators this run could draw targets with: a paid one whose
352
+ * key is here, or Codex once the creator allowed it. */
353
+ function generatorsHere(ctx) {
354
+ const out = []
355
+ for (const [id, provider] of Object.entries(IMAGE_PROVIDERS)) {
356
+ if (id === 'codex') {
357
+ if (typeof ctx.codexState === 'function' && ctx.codexState() === 'allow') out.push(id)
358
+ continue
359
+ }
360
+ let key = null
361
+ try {
362
+ key = provider.envVar ? ctx.secret?.(provider.envVar) : null
363
+ } catch {
364
+ key = null
365
+ }
366
+ if (typeof key === 'string' && key.trim()) out.push(id)
367
+ }
368
+ return out
369
+ }
370
+
371
+ async function askTargets(args, ctx) {
372
+ const { loop, error } = loopOf(ctx)
373
+ if (error) return fail(error)
374
+ if (!loop.kickoff) return fail('The kickoff card comes first (nw_ask_kickoff): the targets are drawn for its answers.')
375
+ const root = ctx.projectRoot
376
+ if (args.none) {
377
+ // No targets only when none can be made or attached: the bar is then out
378
+ // of reach, and the model's word alone must not get it there.
379
+ const generators = generatorsHere(ctx)
380
+ const photos = creatorPhotos(root, ctx)
381
+ if (generators.length) return fail(`Targets can be drawn here (${generators.join(', ')}): make them with image_generate kind "target" at the hero views, then show them with nw_ask_targets.`)
382
+ if (photos >= MIN_TARGETS) return fail(`The creator attached ${photos} photos: they are the targets. Give ${MIN_TARGETS} to ${MAX_TARGETS} of them (.nowhere/refs/<file>), one per hero view, with nw_ask_targets.`)
383
+ await loop.settleTargets({ none: args.none })
384
+ return { text: `No targets (${args.none}). The rounds take stills at the hero views and look_compare's numbers, but no judge scores them against pictures, so the bar cannot be reached: your reply and the approval card say plainly that the space was not judged against targets. Write brief.json next.` }
385
+ }
386
+ const images = args.images
387
+ if (images.length < MIN_TARGETS) return fail(`Give ${MIN_TARGETS} to ${MAX_TARGETS} targets (one per hero view), or none with why.`)
388
+ if (new Set(images.map((i) => i.hero)).size !== images.length) return fail('One target for each hero view.')
389
+ if (args.decide && !loop.targets.delegated) return fail('decide records targets with no card only after the creator left them to you (the targets card\'s "you choose", or no answer to it). Show them with nw_ask_targets and a title.')
390
+ if (!args.decide && !args.title) return fail("The card needs a title in the screen language (title).")
391
+ const panels = await import('../panels.mjs')
392
+ // Each onto the board under its content's name (as nw_ask_pictures puts
393
+ // them), measured once.
394
+ const offered = []
395
+ const stills = stillHashes(root)
396
+ for (const [i, img] of images.entries()) {
397
+ const ref = await readReference(root, img.path, 'nw_ask_targets')
398
+ if (ref.error) return fail(`${img.path}: ${ref.error}`)
399
+ const from = originOf(root, ref.rel, Buffer.from(ref.data, 'base64'), ctx, stills)
400
+ if (from.error) return fail(`${img.path} is not a target: ${from.error}.`)
401
+ const origin = from.origin
402
+ const drawn = from.from ?? (origin === 'target' ? ref.rel : null)
403
+ let file = /^\.nowhere\/refs\/[^/]+$/.test(ref.rel) ? ref.rel.slice('.nowhere/refs/'.length) : null
404
+ if (!file) {
405
+ const added = refBoard.add(root, [{ name: path.basename(ref.rel), mime: ref.mime, data: Buffer.from(ref.data, 'base64'), from: ref.rel }])
406
+ file = added.ok && added.added.length ? added.added[0] : null
407
+ if (!file) return fail(`${img.path}: ${added.refused?.[0]?.why ?? added.error ?? 'it could not be put on the board'}`)
408
+ }
409
+ offered.push({ id: `t${i + 1}`, file, from: drawn ?? ref.rel, hero: img.hero, what: img.what.trim(), origin, camera: drawn ? cameraOf(root, drawn) : null })
410
+ }
411
+ const listed = () => {
412
+ const now = refBoard.list(root)
413
+ return new Map((now.ok ? now.pictures : []).map((p) => [p.file, p]))
414
+ }
415
+ let pics = listed()
416
+ for (const o of offered) {
417
+ if (pics.get(o.file)?.measured) continue
418
+ const m = await panels.measurePicture(root, o.file, { rpc: ctx.rpc })
419
+ if (m.ok) refBoard.setMeasured(root, m.file, m.sha256, m.measured)
420
+ }
421
+ pics = listed()
422
+
423
+ const record = async (kept, who, notes = {}) => {
424
+ for (const o of offered) refBoard.setUse(root, o.file, kept.includes(o))
425
+ const cites = await recordReferences(
426
+ root,
427
+ kept.map((o) => ({ path: `.nowhere/refs/${o.file}`, what: o.what, origin: o.origin, measured: panels.briefMeasured(pics.get(o.file)?.measured) })),
428
+ )
429
+ const byPath = new Map(cites.refs.map((r) => [r.path, r.id]))
430
+ const settled = kept.map((o) => ({ hero: o.hero, path: `.nowhere/refs/${o.file}`, ref: byPath.get(`.nowhere/refs/${o.file}`), origin: o.origin, ...(o.camera?.position ? { camera: { position: o.camera.position, lookAt: o.camera.lookAt, fov: o.camera.fov } } : {}) }))
431
+ await loop.settleTargets({ images: settled })
432
+ const views = settled.map((t) => ({ id: t.hero, ...(t.camera ? { position: t.camera.position, lookAt: t.camera.lookAt, fov: t.camera.fov } : {}), reference: t.ref }))
433
+ const refs = cites.refs.map(({ already, ...ref }) => ref)
434
+ const lines = [
435
+ `${who === 'creator' ? 'The creator kept' : 'Kept'} ${kept.length} of ${offered.length} targets: ${settled.map((t) => `${t.hero} = ${t.ref} (${t.path})`).join(', ')}.`,
436
+ cites.status === 'written' ? "They are brief.json's references now." : cites.status === 'absent' ? `Write brief.json next, with these references: ${JSON.stringify(refs)}` : cites.status === 'unchanged' ? 'brief.json already cites them.' : `brief.json was left as it is (${cites.error}); put these references in it: ${JSON.stringify(refs)}`,
437
+ `Its heroViews, one per target, each citing it and drawn from the same camera (a photo's camera from nw_reference): ${JSON.stringify(views)}. The rounds take their stills from these cameras.`,
438
+ Object.keys(notes).length ? `The creator's notes, for the brief and the rounds: ${Object.entries(notes).map(([id, n]) => `${offered.find((o) => o.id === id)?.hero ?? id}: "${n}"`).join('; ')}.` : null,
439
+ ]
440
+ return { text: `${JSON.stringify({ kept: settled.map((t) => t.hero), references: settled.map((t) => t.ref) })}\n${lines.filter(Boolean).join('\n')}` }
441
+ }
442
+
443
+ if (args.decide) return record(offered, 'agent')
444
+ const round = loop.targets.round
445
+ const card = {
446
+ kind: 'targets',
447
+ origin: 'agent',
448
+ title: args.title,
449
+ round,
450
+ images: offered.map((o) => ({ id: o.id, path: `.nowhere/refs/${o.file}`, hero: o.hero, palette: (pics.get(o.file)?.measured?.palette ?? []).slice(0, 8).map((p) => p.hex) })),
451
+ }
452
+ if (args.title) {
453
+ const unreadable = languageProblem([args.title], ctx.locale)
454
+ if (unreadable) return fail(unreadable)
455
+ }
456
+ const r = await askCard(ctx, card, TIMED_ASK_MS)
457
+ if (r?.answer === 'cancelled') return { text: 'The request was stopped.' }
458
+ if (!r || unanswered(r) || r.answer === 'unavailable') {
459
+ await loop.delegateTargets()
460
+ const out = await record(offered, 'agent')
461
+ return { text: `${out.text}\n${!r || r.answer === 'unavailable' ? 'There is no studio window to ask in' : 'No answer in 10 minutes: the creator is away'}, so all of them are the targets. Say so in your reply; the creator can change them later.` }
462
+ }
463
+ if (r.ok === false) return fail(`The card could not be shown: ${r.error ?? 'the studio did not answer'}.`)
464
+ const notes = r.notes && typeof r.notes === 'object' ? r.notes : {}
465
+ const keepIds = Array.isArray(r.keep) && r.keep.length ? r.keep : offered.map((o) => o.id).filter((id) => !(r.drop ?? []).includes(id))
466
+ if (r.action === 'choose') {
467
+ await loop.delegateTargets()
468
+ return record(offered.filter((o) => !(r.drop ?? []).includes(o.id)), 'agent', notes)
469
+ }
470
+ if (r.action === 'redraw') {
471
+ if (loop.redrawsLeft() > 0) {
472
+ await loop.targetsShown(round + 1)
473
+ const again = offered.filter((o) => notes[o.id] || (r.drop ?? []).includes(o.id))
474
+ const keep = offered.filter((o) => !again.includes(o))
475
+ return {
476
+ text: [
477
+ JSON.stringify({ action: 'redraw', redraw: again.map((o) => o.hero), keep: keep.map((o) => o.hero), notes }),
478
+ `The creator sent ${again.length ? again.map((o) => o.hero).join(', ') : 'them'} back to be drawn again${Object.keys(notes).length ? `, with these notes: ${Object.entries(notes).map(([id, n]) => `${offered.find((o) => o.id === id)?.hero}: "${n}"`).join('; ')}` : ''}. Make ${again.length ? 'those' : 'them'} again with image_generate kind "target" (the same cameras, words that answer the notes), then call nw_ask_targets with the whole set: ${keep.length ? `the kept ${keep.map((o) => `${o.hero} (${o.from})`).join(', ')} and ` : ''}the new ones. ${loop.redrawsLeft()} more ${loop.redrawsLeft() === 1 ? 'redraw is' : 'redraws are'} left.`,
479
+ ].join('\n'),
480
+ }
481
+ }
482
+ const out = await record(offered.filter((o) => keepIds.includes(o.id)), 'creator', notes)
483
+ return { text: `${out.text}\nThe three redraws are used: these stand, and the notes go into the brief and the rounds instead.` }
484
+ }
485
+ const kept = offered.filter((o) => keepIds.includes(o.id))
486
+ if (kept.length === 0) return fail('The creator kept none of the targets: make new ones (image_generate kind "target") and ask again.')
487
+ return record(kept, 'creator', notes)
488
+ }
489
+
490
+ // ---------------------------------------------------------------- nw_round
491
+
492
+ const ROUND_SHAPE = {
493
+ changed: z.string().min(1).max(200).describe("One line, in the screen language, on what this round changed (the round message shows it)."),
494
+ heroes: z.array(HERO).min(1).max(6).optional().describe('Only these hero views (default: every one with a target). A round judged on fewer views says so.'),
495
+ }
496
+
497
+ const ROUND_DESCRIPTION =
498
+ "Runs one round of the reference loop on the space as it is now, after your changes: nw_check; a still at each hero view from brief.json's camera (the target's own), once the space's files have arrived; the target beside the still (target | now); look_compare's numbers at each; and a score from a judge that sees only the targets, the stills and the rubric (0 to 10 a view and overall, with the gaps: where, what, how much). Writes .nowhere/rounds/<n>/ (still-H#.png, composite-H#.png, scores.json, notes.md), adds the score to brief.json's scoreHistory and posts the round in the chat; it never waits on the creator. Plan the next round on its top three gaps. The level's round cap and time cap come first."
499
+
500
+ /** A picture as PNG bytes and decoded, from a shot's image or a file. */
501
+ async function pngOf(image, rpc) {
502
+ const bytes = Buffer.from(image.data, 'base64')
503
+ const decoded = await decodeImage(bytes, { mime: image.mime ?? 'image/png', maxEdge: 1600, rpc })
504
+ if (!decoded.ok) return { error: decoded.error }
505
+ return { decoded, png: (image.mime ?? 'image/png') === 'image/png' ? bytes : encodePng(decoded) }
506
+ }
507
+
508
+ /** A picture for the judge: at most JUDGE_PX (1568) on its long edge, as PNG. */
509
+ const forJudge = (decoded) => ({ mime: 'image/png', data: encodePng(fitEdge(decoded, JUDGE_PX)).toString('base64') })
510
+
511
+ const near = (a, b, tol) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => Math.abs(Number(x) - Number(b[i])) <= tol)
512
+
513
+ /**
514
+ * How brief.json's hero views stray from the settled targets: each target's
515
+ * hero view must cite that target (the reference with its path, whatever R
516
+ * id it has) and look from the camera it was drawn from. A brief written
517
+ * some other way (a Bash write, an old space's brief) would have the rounds
518
+ * judge other pictures, or the right ones from another place.
519
+ */
520
+ export function heroMismatch(brief, targets) {
521
+ if (!targets?.settled || targets.none) return []
522
+ const refs = new Map((brief.references ?? []).map((r) => [r.id, r]))
523
+ const out = []
524
+ for (const t of targets.images ?? []) {
525
+ const v = (brief.heroViews ?? []).find((h) => h.id === t.hero)
526
+ if (!v) {
527
+ out.push(`${t.hero} is not a hero view (its target is ${t.path})`)
528
+ continue
529
+ }
530
+ const cited = v.reference ? refs.get(v.reference) : null
531
+ if (!cited || cited.path !== t.path) {
532
+ out.push(`${t.hero} cites ${v.reference ?? 'nothing'}${cited ? ` (${cited.path})` : ''}, not its target ${t.path}${t.ref ? ` (${t.ref})` : ''}`)
533
+ continue
534
+ }
535
+ const cam = t.camera
536
+ if (cam?.position && (!near(v.position, cam.position, 0.05) || (Array.isArray(cam.lookAt) && !near(v.lookAt, cam.lookAt, 0.05)) || (Number.isFinite(cam.fov) && !(Math.abs(Number(v.fov) - cam.fov) <= 0.5)))) {
537
+ out.push(`${t.hero} looks from another camera than its target was drawn from (${JSON.stringify(cam)})`)
538
+ }
539
+ }
540
+ return out
541
+ }
542
+
543
+ async function runRound(args, ctx) {
544
+ const { loop, error } = loopOf(ctx)
545
+ if (error) return fail(error)
546
+ // Its line is on the round message, with the studio's words around it.
547
+ const unreadable = languageProblem([args.changed], ctx.locale, 'the round\'s line (changed)', 'it')
548
+ if (unreadable) return fail(unreadable)
549
+ const root = ctx.projectRoot
550
+ if (!loop.kickoff) return fail('The kickoff card comes first (nw_ask_kickoff): a round is held to its level.')
551
+ if (!loop.targets.settled) return fail('The targets come before the rounds: image_generate kind "target", then nw_ask_targets (or nw_ask_targets with none and why).')
552
+ const budget = loop.budget
553
+ if (budget && loop.rounds.length >= budget.roundCap) return fail(`The level's ${budget.roundCap} rounds are used. Show the approval card (nw_ask_approval) and say where it stands against the bar.`)
554
+ // Past the time cap one round more, the last: it judges what the last
555
+ // changes made, and then the approval card.
556
+ const before = loop.last()
557
+ if (budget && loop.capped().time && before && Number.isFinite(before.elapsedMin) && before.elapsedMin >= budget.timeCapMin) {
558
+ return fail(`The level's ${budget.timeCapMin} minutes are used, and round ${before.n} after them was the last. Show the approval card (nw_ask_approval) and say plainly where it stands against the bar.`)
559
+ }
560
+ const brief = await readBrief(root)
561
+ if (brief.status !== 'ok') return fail(brief.status === 'absent' ? 'There is no brief.json yet: write it (its heroViews cite the targets) before the first round.' : `brief.json does not pass its schema (${brief.error}); fix it first.`)
562
+ const stray = heroMismatch(brief.brief, loop.targets)
563
+ if (stray.length) return fail(`brief.json's hero views do not stand on the settled targets, so this round would judge other pictures or look from other places: ${stray.join('; ')}. Each target's hero view cites it (its reference, with its path) from the camera it was drawn from, as nw_ask_targets gave them; fix brief.json, then nw_round.`)
564
+ const refs = new Map(brief.brief.references.map((r) => [r.id, r]))
565
+ const wanted = new Set(args.heroes ?? brief.brief.heroViews.map((v) => v.id))
566
+ const views = brief.brief.heroViews.filter((v) => wanted.has(v.id))
567
+ if (views.length === 0) return fail(`None of ${[...wanted].join(', ')} is a hero view in brief.json.`)
568
+
569
+ // The check first: a round of a space that does not run is no round.
570
+ const { TOOLS: HARNESS } = await import('./harness.mjs')
571
+ const { runDef } = await import('./index.mjs')
572
+ const checkDef = HARNESS.find((d) => d.name === 'nw_check')
573
+ const checked = checkDef ? await runDef(checkDef, {}, ctx) : { text: 'no nw_check here', isError: false }
574
+ if (checked.isError) return fail(`The round stops at its check: ${checked.text}`)
575
+
576
+ const n = loop.nextRound()
577
+ const dir = path.join(root, ROUNDS_DIR, String(n))
578
+ await fsp.mkdir(dir, { recursive: true })
579
+ const relOf = (abs) => slash(path.relative(root, abs))
580
+ const shots = []
581
+ const problems = []
582
+ for (const v of views) {
583
+ const ref = v.reference ? refs.get(v.reference) : null
584
+ const target = ref?.path ? await readReference(root, ref.path, 'nw_round') : null
585
+ if (target?.error) problems.push(`${v.id}: its target ${ref.path}: ${target.error}`)
586
+ const targetPic = target?.ok ? await decodeImage(Buffer.from(target.data, 'base64'), { mime: target.mime, maxEdge: 1600, rpc: ctx.rpc }) : null
587
+ const aspect = targetPic?.ok ? shapeOf(targetPic.width / targetPic.height) : 'wide'
588
+ const shot = { view: 'free', position: v.position, lookAt: v.lookAt, fov: v.fov, longEdge: JUDGE_PX, aspect }
589
+ const ask = () =>
590
+ ctx.rpc('view', { shots: [shot], ...(target?.ok ? { stats: { reference: { data: target.data, mime: target.mime } } } : {}), settle: { waitMs: LOOK_SETTLE_MS }, record: false }, viewTimeout(1) + LOOK_SETTLE_MS)
591
+ let r = await ask()
592
+ let s = r?.ok && Array.isArray(r.shots) ? r.shots[0] : null
593
+ // A picture drawn before the space's files arrived is another space: once more, then said.
594
+ if (s?.ok && notJudged(s)) {
595
+ r = await ask()
596
+ s = r?.ok && Array.isArray(r.shots) ? r.shots[0] : null
597
+ }
598
+ if (!s?.ok || !s.image) {
599
+ problems.push(`${v.id}: no still (${s?.error ?? r?.error ?? 'the viewport did not answer'})`)
600
+ continue
601
+ }
602
+ const why = notJudged(s)
603
+ const still = await pngOf(s.image, ctx.rpc)
604
+ if (still.error) {
605
+ problems.push(`${v.id}: the still could not be read (${still.error})`)
606
+ continue
607
+ }
608
+ const stillAbs = path.join(dir, `still-${v.id}.png`)
609
+ await fsp.writeFile(stillAbs, still.png)
610
+ const entry = { hero: v.id, still: relOf(stillAbs), stillPic: still.decoded, loading: why }
611
+ if (target?.ok && targetPic?.ok) {
612
+ const compositeAbs = path.join(dir, `composite-${v.id}.png`)
613
+ const made = await compose(path.join(root, target.rel), stillAbs, compositeAbs, { label: `${v.id} target | now`, rpc: ctx.rpc })
614
+ if (made.ok) {
615
+ entry.composite = relOf(compositeAbs)
616
+ // Where each half sits, beside the composite, for marks drawn on it.
617
+ if (made.layout) await fsp.writeFile(path.join(dir, `composite-${v.id}.json`), `${JSON.stringify(made.layout)}\n`).catch(() => {})
618
+ } else problems.push(`${v.id}: the target | now picture could not be made (${made.error})`)
619
+ entry.target = target.rel
620
+ entry.targetPic = targetPic
621
+ if (!why && s.stats && r.referenceStats) {
622
+ const cmp = compareLook(s.stats, r.referenceStats)
623
+ entry.compare = { verdict: cmp.verdict, paletteDeltaE: Math.round(cmp.paletteDeltaE * 10) / 10, deltaMeanL: Math.round(cmp.deltaMeanL * 10) / 10 }
624
+ }
625
+ }
626
+ if (why) problems.push(`${v.id}: not judged: ${why}`)
627
+ shots.push(entry)
628
+ }
629
+ if (shots.length === 0) return fail(`Round ${n} took no still: ${problems.join('; ')}`)
630
+
631
+ // The judge sees the pairs alone: never the brief, the request or this conversation.
632
+ const pairs = shots.filter((s) => s.targetPic && !s.loading).map((s) => ({ hero: s.hero, target: forJudge(s.targetPic), still: forJudge(s.stillPic) }))
633
+ // And up to three web pictures the brief cites, which the place is modelled on.
634
+ const references = []
635
+ for (const rel of pairs.length ? briefWebReferences(brief.brief) : []) {
636
+ const ref = await readReference(root, rel, 'nw_round')
637
+ const pic = ref?.ok ? await decodeImage(Buffer.from(ref.data, 'base64'), { mime: ref.mime, maxEdge: 1600, rpc: ctx.rpc }) : null
638
+ if (pic?.ok) references.push(forJudge(pic))
639
+ }
640
+ let verdict = null
641
+ if (pairs.length && typeof ctx.judge === 'function') {
642
+ try {
643
+ verdict = await ctx.judge({ pairs, slop: [...SLOP, ...slopForJudge(brief.brief.slop)], ...(references.length ? { references } : {}) })
644
+ } catch (err) {
645
+ problems.push(`the judge failed: ${err?.message ?? err}`)
646
+ }
647
+ } else if (!pairs.length) problems.push(loop.targets.none ? `no targets (${loop.targets.none}), so no judge` : 'no view could be judged')
648
+ else problems.push('no judge in this host')
649
+
650
+ // The creator's note for "one more round" is the first gap of the round it
651
+ // asked for. what is the note as the agent reads it (the picture kept and
652
+ // where its marks are); said and hero are what the chat shows back.
653
+ const creatorGaps = loop.creatorNotes().map((n) => ({ where: 'the creator', what: n.gap, severity: 'high', from: 'creator', said: n.said, ...(n.hero ? { hero: n.hero } : {}) }))
654
+ const gaps = [...creatorGaps, ...(verdict?.gaps ?? [])]
655
+ const score = Number.isFinite(verdict?.overall) ? verdict.overall : null
656
+ const viewScores = Object.fromEntries(shots.map((s) => [s.hero, verdict?.views?.[s.hero] ?? null]))
657
+ const scores = { round: n, judgePx: JUDGE_PX, views: viewScores, overall: score, judge: verdict ? verdict.judge : { model: null, notes: problems.join('; ') }, gaps, ...(verdict?.scores?.length > 1 ? { judges: verdict.scores } : {}) }
658
+ await fsp.writeFile(path.join(dir, 'scores.json'), `${JSON.stringify(scores, null, 2)}\n`)
659
+ const history = [...loop.scoreHistory(), ...(score === null ? [] : [score])]
660
+ const bar = loop.bar?.judge ?? null
661
+ const notesMd = [
662
+ `# Round ${n}`,
663
+ '',
664
+ `Changed: ${args.changed}`,
665
+ '',
666
+ `Score: ${score === null ? 'not judged' : `${fmt(score)} of 10`}${bar !== null ? ` (bar ${fmt(bar)})` : ''}. History: ${history.map((h) => fmt(h)).join(', ') || 'none yet'}.`,
667
+ '',
668
+ '## Views',
669
+ ...shots.map((s) => `- ${s.hero}: ${viewScores[s.hero] === null ? 'not judged' : fmt(viewScores[s.hero])}${s.compare ? `, look_compare ${s.compare.verdict} (palette deltaE ${fmt(s.compare.paletteDeltaE)}, L* ${s.compare.deltaMeanL > 0 ? '+' : ''}${fmt(s.compare.deltaMeanL)})` : ''}`),
670
+ '',
671
+ '## Gaps',
672
+ ...(gaps.length ? gaps.map((g) => `- (${g.severity}) ${g.where ? `${g.where}: ` : ''}${g.what}`) : ['- none named']),
673
+ '',
674
+ '## The judge',
675
+ scores.judge.model ? `${scores.judge.model}: ${scores.judge.notes}` : scores.judge.notes || 'none',
676
+ ...(problems.length ? ['', '## Not judged', ...problems.map((p) => `- ${p}`)] : []),
677
+ '',
678
+ ].join('\n')
679
+ await fsp.writeFile(path.join(dir, 'notes.md'), notesMd)
680
+
681
+ const fingerprint = typeof ctx.run?.fingerprint === 'function' ? await ctx.run.fingerprint() : null
682
+ const judgedHeroes = Object.keys(viewScores).filter((h) => Number.isFinite(viewScores[h]))
683
+ const roundRecord = { n, at: new Date().toISOString(), judgePx: JUDGE_PX, elapsedMin: Math.round(loop.elapsedMin() * 10) / 10, score, views: viewScores, heroes: judgedHeroes, gaps: gaps.slice(0, 8), fingerprint, changed: args.changed, compare: Object.fromEntries(shots.filter((s) => s.compare).map((s) => [s.hero, s.compare.verdict])) }
684
+ const complete = judgedAll(loop.targets, roundRecord)
685
+ await loop.addRound({ ...roundRecord, complete })
686
+ await recordLoop(root, { budget: loop.budget, bar: loop.bar, scoreHistory: history })
687
+ const elapsedMin = Math.round(loop.elapsedMin())
688
+ const remainingMin = Math.round(loop.remainingMin() ?? 0)
689
+ const top = gaps.slice(0, 3)
690
+ try {
691
+ // A view with no target shows its still alone (a round with no targets).
692
+ // The creator's own gaps go back to the chat as they wrote them, under
693
+ // their own label (from: 'creator', with the view they marked); the
694
+ // picture's file and the marks' pixels stay in scores.json, notes.md
695
+ // and this tool's result.
696
+ const shown = top.map((g) => (g.from === 'creator' ? { where: g.where, what: g.said, severity: g.severity, from: 'creator', ...(g.hero ? { hero: g.hero } : {}) } : g))
697
+ ctx.post?.({ type: 'round', round: n, elapsedMin, remainingMin, views: shots.map((s) => ({ hero: s.hero, composite: s.composite ?? s.still, score: viewScores[s.hero] })), score, history, gaps: shown, changed: args.changed })
698
+ } catch {
699
+ // the round stands in its folder whatever the chat did with it
700
+ }
701
+
702
+ const capped = loop.capped()
703
+ // A round counts toward the bar only when it scored every hero view that
704
+ // has a target: judging the best views alone would end the loop early.
705
+ const reached = complete && score !== null && bar !== null && score >= bar
706
+ const missing = loop.targets.none ? [] : (loop.targets.images ?? []).map((t) => t.hero).filter((h) => !judgedHeroes.includes(h))
707
+ const floor = budget?.timeFloorMin ?? 0
708
+ // A quality step has no floor: it judges at least its minRounds rounds
709
+ // before its bar may end it (loop/gate.mjs holds the stop the same way).
710
+ const least = loop.minRounds?.() ?? 0
711
+ const judged = loop.judgedRounds?.() ?? loop.rounds?.length ?? n
712
+ const owed = Math.max(0, least - judged)
713
+ // Under a quality step the bar after the least rounds is when the card
714
+ // may be shown; a round that still raised the score, with a round and
715
+ // some time left, is worth one more first. A speed level stops at its bar.
716
+ const worthAnother =
717
+ !!budget?.quality && history.length >= 2 && score !== null && score > history.at(-2) && (loop.remainingMin?.() ?? 0) >= 10 && (Number(budget.roundCap) || 0) - n >= 1
718
+ const next = capped.any
719
+ ? `The ${capped.time ? 'time cap' : 'round cap'} is reached${capped.time && !capped.rounds ? ', and this was the last round' : ''}: show the approval card (nw_ask_approval) and say plainly where it stands against the bar.`
720
+ : reached && elapsedMin >= floor && owed === 0
721
+ ? worthAnother
722
+ ? `At the bar after the least rounds, and this round raised the score (${fmt(history.at(-2))} to ${fmt(score)}): with time and rounds left, take its top gaps into one more round; show the approval card (nw_ask_approval) once a round no longer raises it.`
723
+ : 'At the bar, past the floor: show the approval card (nw_ask_approval).'
724
+ : `Plan round ${n + 1} on the top gaps above, change the space, then nw_round again.${missing.length ? ` This round did not score ${missing.join(', ')}, so it does not count toward the bar: the next one judges every hero view with a target.` : ''}${reached && owed > 0 ? ` At the bar, but this quality step judges at least ${least} rounds before its approval card (${judged} so far): take the next gaps into another round (a round counts when it scores every hero view on a space changed since the one before).` : ''}${reached && elapsedMin < floor ? ` At the bar, but ${floor - elapsedMin} minutes before the floor: something is still missing (the next gap, the far detail, the walk between the views).` : ''}`
725
+ const images = shots
726
+ .filter((s) => s.composite)
727
+ .slice(0, 6)
728
+ .map((s) => ({ mime: 'image/png', data: fs.readFileSync(path.join(root, s.composite)).toString('base64') }))
729
+ return {
730
+ text: [
731
+ JSON.stringify({ round: n, score, views: viewScores, bar, history }),
732
+ `Round ${n} (${elapsedMin} minutes in, ${remainingMin} left before the cap): ${score === null ? 'not judged' : `${fmt(score)} of 10 against the bar of ${fmt(bar)}`}, judged by ${scores.judge.model ?? 'no judge'}.`,
733
+ ...shots.map((s) => `- ${s.hero}: ${viewScores[s.hero] === null ? 'not judged' : fmt(viewScores[s.hero])}${s.compare ? `; look_compare ${s.compare.verdict}, palette deltaE ${fmt(s.compare.paletteDeltaE)}` : ''}${s.composite ? `; ${s.composite}` : ''}`),
734
+ top.length ? `Top gaps: ${top.map((g, i) => `${i + 1}. (${g.severity}) ${g.where ? `${g.where}: ` : ''}${g.what}`).join(' ')}` : 'The judge named no gap.',
735
+ problems.length ? `Not judged: ${problems.join('; ')}.` : null,
736
+ `Written to ${ROUNDS_DIR.split(path.sep).join('/')}/${n}/ and posted in the chat. The pictures are target | now for each view.`,
737
+ next,
738
+ ]
739
+ .filter(Boolean)
740
+ .join('\n'),
741
+ images,
742
+ verifies: 'view',
743
+ }
744
+ }
745
+
746
+ // ---------------------------------------------------------------- nw_ask_approval
747
+
748
+ const APPROVAL_SHAPE = {
749
+ title: z.string().min(1).max(80).describe("The card's title, in the screen language."),
750
+ }
751
+
752
+ const APPROVAL_DESCRIPTION =
753
+ "The last card of a space: the last round's target | now pictures, the score round by round against the bar, what the planet's files weigh (of 100 MB) and its code (of 1 MB), and the frame time by tier. Show it when a round reaches the bar past the time floor (at a quality step: once its least number of rounds has been judged), or when the round cap or the time cap is reached. The creator presses Publish, which starts the studio's own publish (its pre-flight and all) with the approval of this press, or asks for one more round with a note, which becomes the first gap of that round (within the caps). Nothing is published without that press."
754
+
755
+ async function askApproval(args, ctx) {
756
+ const { loop, error } = loopOf(ctx)
757
+ if (error) return fail(error)
758
+ const unreadable = languageProblem([args.title], ctx.locale)
759
+ if (unreadable) return fail(unreadable)
760
+ const last = loop.last()
761
+ if (!last) return fail('Run a round first (nw_round): the approval card shows its pictures and score.')
762
+ // A quality step's least rounds come before its approval card, as they
763
+ // come before its stop (loop/gate.mjs), unless a cap has been reached.
764
+ const least = loop.minRounds?.() ?? 0
765
+ const judged = loop.judgedRounds?.() ?? loop.rounds?.length ?? 0
766
+ if (judged < least && !loop.capped().any) {
767
+ return fail(`This quality step judges at least ${least} rounds before its approval card (${judged} so far): take round ${last.n}'s top differences into another round (nw_round) first.`)
768
+ }
769
+ const root = ctx.projectRoot
770
+ const reading = typeof ctx.run?.perf === 'function' ? await ctx.run.perf().catch(() => null) : null
771
+ const perf = perfVerdict(reading)
772
+ const cap = await capacityOf(root).catch(() => ({ assetsMb: 0, bundleKb: null, problems: [] }))
773
+ const dir = path.join(root, ROUNDS_DIR, String(last.n))
774
+ // Each view's target | now picture, or its still when it had no target.
775
+ const views = Object.keys(last.views ?? {})
776
+ .map((hero) => ({ hero, file: [`composite-${hero}.png`, `still-${hero}.png`].find((f) => fs.existsSync(path.join(dir, f))) }))
777
+ .filter((v) => v.file)
778
+ .map(({ hero, file }) => ({ hero, composite: `${ROUNDS_DIR.split(path.sep).join('/')}/${last.n}/${file}` }))
779
+ const card = {
780
+ kind: 'approval',
781
+ origin: 'agent',
782
+ title: args.title,
783
+ views,
784
+ scores: loop.scoreHistory(),
785
+ finalScore: Number.isFinite(last.score) ? last.score : null,
786
+ bar: loop.bar?.judge ?? 10,
787
+ assetsMb: cap.assetsMb,
788
+ bundleKb: cap.bundleKb,
789
+ // Each measured tier as it was read, its budget and verdict with it, so
790
+ // the card can say which is over (cards.cjs keeps the contract's fields).
791
+ perf: Object.fromEntries(Object.keys(perf.tiers).map((tier) => [tier, { ...reading.tiers[tier], frameMsP95: perf.tiers[tier].frameMsP95 }])),
792
+ rounds: loop.rounds.length,
793
+ }
794
+ // Said beside any answer: the card shows the frame time as not measured.
795
+ const unmeasured = perf.state === 'absent' ? ' The frame time was not measured (no perf reading on the space as it is now), and the card shows it as not measured; say so in your reply.' : ''
796
+ const r = await askCard(ctx, card, APPROVAL_ASK_MS)
797
+ if (r?.answer === 'cancelled') return { text: 'The request was stopped.' }
798
+ if (!r || unanswered(r) || r.answer === 'unavailable') {
799
+ const timedOut = !!r && r.answer !== 'unavailable' && unanswered(r)
800
+ await loop.setApproval({ answer: timedOut ? 'timeout' : 'unavailable' })
801
+ return { text: `${JSON.stringify({ action: null })}\nNo answer${timedOut ? ' in 30 minutes' : ' (no studio window here)'}: nothing is published. End with your reply: the score against the bar, and that the creator can press Publish in the studio when they are ready.${unmeasured}` }
802
+ }
803
+ if (r.ok === false) return fail(`The card could not be shown: ${r.error ?? 'the studio did not answer'}.`)
804
+ if (r.action === 'another') {
805
+ await loop.setApproval({ answer: 'another', note: r.note ?? '' })
806
+ const capped = loop.capped()
807
+ if (capped.any) return { text: `${JSON.stringify({ action: 'another', note: r.note ?? null })}\nThe creator asked for one more round${r.note ? ` ("${r.note}")` : ''}, but the ${capped.time ? 'time cap' : 'round cap'} is reached, so there is none in this request. Say so in your reply: they can ask again in a new message.` }
808
+ return { text: `${JSON.stringify({ action: 'another', note: r.note ?? null })}\nThe creator asked for one more round${r.note ? `: "${r.note}". It is the first gap of the next round` : ''}. Change the space for it, judge it with nw_round, then show this card again.` }
809
+ }
810
+ if (r.action !== 'publish') return fail('The answer was neither publish nor another round.')
811
+ await loop.setApproval({ answer: 'publish' })
812
+ // The token is the creator's press, handed straight back to the studio's
813
+ // publish path; it is never part of what the model reads.
814
+ if (!r.token) return { text: `${JSON.stringify({ action: 'publish', published: false })}\nThe creator pressed Publish, but this studio gave the press no approval, so nothing was published from here. Tell them to press Publish in the studio.` }
815
+ let outcome
816
+ try {
817
+ outcome = await ctx.rpc('publish', { runId: ctx.runId, token: r.token }, PUBLISH_MS)
818
+ } catch (err) {
819
+ outcome = { state: 'failed', error: err?.message ?? String(err) }
820
+ }
821
+ // The studio's publish goes on whatever this call's wait does: a wait that
822
+ // ran out is a publish still running, never a failed one.
823
+ const running = !outcome?.state && /timed out/.test(String(outcome?.error ?? ''))
824
+ const state = outcome?.state ?? (running ? 'running' : 'failed')
825
+ const said =
826
+ state === 'done'
827
+ ? `Published${outcome.result?.url ? ` at ${outcome.result.url}` : ''}.`
828
+ : state === 'running'
829
+ ? `The publish is still running after ${Math.round(PUBLISH_MS / 60_000)} minutes (a large upload); the studio's top bar shows how far it is. Do not say it failed or that it is done.`
830
+ : state === 'signin'
831
+ ? 'The publish stopped before it began: the creator is not signed in to Oda (Settings).'
832
+ : state === 'idle'
833
+ ? 'The publish was cancelled.'
834
+ : `The publish did not go through: ${outcome?.error ?? 'no reason given'}.`
835
+ return { text: `${JSON.stringify({ action: 'publish', state })}\nThe creator pressed Publish, and the studio's publish ${state === 'running' ? 'started' : 'ran'} with that approval. ${said} Say so in your reply.${unmeasured}` }
836
+ }
837
+
838
+ // ---------------------------------------------------------------- the defs
839
+
840
+ export function makeLoopTools() {
841
+ const guarded = (name, fn) => async (args, ctx) => {
842
+ try {
843
+ return await fn(args, ctx)
844
+ } catch (err) {
845
+ return fail(`${name} failed: ${err?.message ?? err}`)
846
+ }
847
+ }
848
+ return [
849
+ // Read-only for the cost gate: the kickoff is what approves the cost of
850
+ // a big job, so it must run before any approval.
851
+ { name: 'nw_ask_kickoff', description: KICKOFF_DESCRIPTION, shape: KICKOFF_SHAPE, handler: guarded('nw_ask_kickoff', askKickoff), readOnly: true, mainOnly: true },
852
+ { name: 'nw_ask_targets', description: TARGETS_DESCRIPTION, shape: TARGETS_SHAPE, handler: guarded('nw_ask_targets', askTargets), readOnly: false, mainOnly: true },
853
+ { name: 'nw_round', description: ROUND_DESCRIPTION, shape: ROUND_SHAPE, handler: guarded('nw_round', runRound), readOnly: false, mainOnly: true },
854
+ { name: 'nw_ask_approval', description: APPROVAL_DESCRIPTION, shape: APPROVAL_SHAPE, handler: guarded('nw_ask_approval', askApproval), readOnly: true, mainOnly: true },
855
+ ]
856
+ }
857
+
858
+ export const TOOLS = makeLoopTools()