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,479 @@
1
+ // The creator's pick for the big choices of a space, asked in the chat as
2
+ // cards with pictures (agent/cards.cjs kinds "pictures" and "assets"):
3
+ // nw_ask_pictures candidate reference pictures, each with its measured
4
+ // palette; the ones picked are what the brief is measured
5
+ // from: they stay with the agent (the board's "for the
6
+ // brief", .nowhere/refs/index.json), the rest are kept on
7
+ // the board but no longer handed over, and brief.json
8
+ // cites the picks (R1, R2...)
9
+ // nw_ask_asset a few library candidates for one role (the floor, the
10
+ // walls, the sky, a hero prop) with their real size, licence,
11
+ // downloads and texel density against the brief; the one
12
+ // picked is imported as the browser imported it
13
+ // (agent/panels.mjs: asset_fetch, asset_import with the
14
+ // ledger and the credits, asset_inspect), and the chat
15
+ // shows the inspection under the card
16
+ //
17
+ // Both wait on the creator only so long (cards.cjs gives these cards ten
18
+ // minutes) and take "you choose" for an answer: the agent then picks and
19
+ // says which, and the creator changes it later in the chat. The agent's own
20
+ // pick of pictures is recorded as the creator's is (nw_ask_pictures with
21
+ // decide, no card); until then a picture this call brought onto the board
22
+ // from quarantine is set aside there, so a web find nobody picked is never
23
+ // handed over in place of the creator's own pictures. Once a card goes
24
+ // unanswered the creator is away: cards.cjs shows no more of them in that
25
+ // request, and the agent makes the rest of its big choices itself.
26
+ //
27
+ // Tool modules export TOOLS (ToolDefs) and RPC_METHODS; handlers never throw
28
+ // and are testable with a stub ctx (makeChoiceTools takes the asset tools,
29
+ // so a check passes fakes for the libraries and Blender).
30
+
31
+ import { z } from 'zod'
32
+ import { createRequire } from 'node:module'
33
+ import path from 'node:path'
34
+
35
+ const require = createRequire(import.meta.url)
36
+ const refBoard = require('../../refBoard.cjs')
37
+ let localeModule
38
+ try {
39
+ localeModule = require('../locale.cjs')
40
+ } catch {
41
+ localeModule = null
42
+ }
43
+
44
+ export const RPC_METHODS = ['ask', 'card-update']
45
+
46
+ // cards.cjs closes these cards after ten minutes; the rpc waits longer, so
47
+ // its "timeout" is what comes back rather than a bare rpc timeout.
48
+ const ASK_TIMEOUT_MS = 11 * 60_000
49
+ const WAIT_MINUTES = 10
50
+
51
+ const fail = (text) => ({ text, isError: true })
52
+ const issues = (error) =>
53
+ error.issues
54
+ .slice(0, 6)
55
+ .map((i) => `${i.path.join('.') || 'input'}: ${i.message}`)
56
+ .join('; ')
57
+
58
+ /** The words of a card the creator could not read, or null (as nw_ask). */
59
+ function languageProblem(words, locale) {
60
+ const writtenIn = localeModule?.writtenIn
61
+ if (typeof writtenIn !== 'function' || !locale) return null
62
+ if (writtenIn(words.filter((w) => typeof w === 'string').join('\n'), locale) !== false) return null
63
+ const name = localeModule.LANGUAGE_NAMES?.[localeModule.languageOf?.(locale) ?? locale] ?? locale
64
+ return `Cards are in the screen language, ${name}, and this card is not in it. Write its title, body and labels in ${name} (the screen language, not the one the creator writes in), then call it again.`
65
+ }
66
+
67
+ async function askCard(ctx, card) {
68
+ try {
69
+ return await ctx.rpc('ask', { runId: ctx.runId, locale: ctx.locale, card }, ASK_TIMEOUT_MS)
70
+ } catch (err) {
71
+ return { ok: false, error: err?.message ?? String(err) }
72
+ }
73
+ }
74
+
75
+ /** The answers every card can end in that are not the creator's pick:
76
+ * what: what the agent now chooses; how: how it records its choice. */
77
+ function unanswered(r, what, how) {
78
+ const rest = 'Make the rest of this request\'s big choices yourself too, without cards: they would not be shown.'
79
+ if (r.answer === 'timeout' && r.away) {
80
+ return `Not shown: the creator did not answer an earlier card in this request and is away. Choose ${what} yourself, ${how}. ${rest} Say in your reply which you took; the creator can change them in the chat.`
81
+ }
82
+ switch (r.answer) {
83
+ case 'timeout':
84
+ return `No answer in ${WAIT_MINUTES} minutes: the creator is away. Choose ${what} yourself, as for "you choose", ${how}. ${rest} Say in your reply which you took; the creator can change them in the chat.`
85
+ case 'cancelled':
86
+ return 'The request was stopped.'
87
+ case 'unavailable':
88
+ return `There is no studio window to ask in. Choose ${what} yourself, ${how}, and say in your reply which you took.`
89
+ }
90
+ // A request shows only so many picture cards (cards.cjs PICKS_PER_RUN).
91
+ if (r.ok === false && r.code === 'enough') return `${r.error} Choose ${what} yourself, ${how}, and say in your reply which you took.`
92
+ return null
93
+ }
94
+
95
+ // ---------------------------------------------------------------- nw_ask_pictures
96
+
97
+ const PICTURES_SHAPE = {
98
+ title: z.string().min(1).max(80).describe("The question, in the screen language."),
99
+ body: z.string().max(600).optional().describe("A line on what the pictures are for, in the screen language."),
100
+ pictures: z
101
+ .array(
102
+ z.object({
103
+ path: z
104
+ .string()
105
+ .min(1)
106
+ .max(300)
107
+ .describe('A picture in the project: one the creator attached (.nowhere/refs/<file>, the studio context lists them), one you gathered under refs/, or one you downloaded and checked (in .nowhere/quarantine/).'),
108
+ what: z.string().min(1).max(300).describe('In the screen language: what it shows and what the space would take from it. The brief cites it with these words when it is picked, and the reference board shows them.'),
109
+ label: z.string().max(60).optional().describe("A few words under it on the card, in the screen language."),
110
+ url: z.string().url().max(600).optional().describe('The page it came from, when you found it on the web.'),
111
+ }),
112
+ )
113
+ .min(2)
114
+ .max(8)
115
+ .describe('2 to 8 candidates.'),
116
+ multiple: z.boolean().default(true).describe('The creator may pick several (the default): a reference set.'),
117
+ purpose: z
118
+ .enum(['style'])
119
+ .optional()
120
+ .describe('style: the card that picks how the space is drawn. Each picture is one direction\'s sample (image_generate kind direction), its label the direction\'s name, its what the medium and why it suits the request; the creator picks one. Asked once a request, also after the kickoff. The pick is written to style.json (from "chosen", with every direction under directions).'),
121
+ decide: z
122
+ .array(z.string().min(1).max(300))
123
+ .min(1)
124
+ .max(8)
125
+ .optional()
126
+ .describe('Only after "you choose" or no answer: the pictures you take, by their paths in pictures (or the board paths the answer gave). Records them as the creator\'s pick is recorded, and shows no card.'),
127
+ }
128
+
129
+ const PICTURES_DESCRIPTION =
130
+ "Shows candidate reference pictures in the chat, each with the palette nw_reference measures from it, and waits for the creator to pick the ones the space is measured from, or to leave it to you. For the reference set only, once per space or when the creator asks to change it; not for every picture. With purpose style it is the style card instead: one sample picture per proposed direction, one pick. Pictures come from the project: the ones the creator attached (.nowhere/refs/), ones you gathered under refs/, or ones you found on the web (after the web consent) and downloaded into quarantine, each with its page as url; one from refs/ or quarantine is copied onto the board, and the board's copy is what you are handed from then on. The picks are recorded as the board records them: they stay with you on every request, the other candidates are kept on the board but no longer handed over, and brief.json cites each pick in its references (R1, R2...) with your what and the measured numbers; without a brief.json yet, the answer gives the references to write into it. On \"you choose\" or no answer within 10 minutes, choose yourself, record it by calling again with the same pictures and decide (no card is shown), and say which in your reply."
131
+
132
+ async function askPictures(args, ctx) {
133
+ const parsed = z.object(PICTURES_SHAPE).safeParse(args ?? {})
134
+ if (!parsed.success) return fail(`nw_ask_pictures: ${issues(parsed.error)}`)
135
+ const a = parsed.data
136
+ if (!ctx?.projectRoot) return fail('No project is open.')
137
+ // Only a card's words are checked against the screen language; decide shows none.
138
+ const unreadable = a.decide ? null : languageProblem([a.title, a.body, ...a.pictures.map((p) => p.label)], ctx.locale)
139
+ if (unreadable) return fail(unreadable)
140
+ const root = ctx.projectRoot
141
+ const { readReference } = await import('./look.mjs')
142
+ const panels = await import('../panels.mjs')
143
+
144
+ // Each candidate onto the board (one from quarantine or refs/ is copied
145
+ // there under its content's name, with the page it came from and the path
146
+ // it was copied from, which the agent's board then lists as this copy),
147
+ // then measured once. A
148
+ // picture that was not on the board before is fresh: set aside again
149
+ // below unless it is picked.
150
+ const listed = refBoard.list(root)
151
+ const before = new Set((listed.ok ? listed.pictures : []).map((p) => p.file))
152
+ const offered = []
153
+ const refused = []
154
+ for (const p of a.pictures) {
155
+ const ref = await readReference(root, p.path, 'nw_ask_pictures')
156
+ if (ref.error) {
157
+ refused.push(`${p.path}: ${ref.error}`)
158
+ continue
159
+ }
160
+ let file = /^\.nowhere\/refs\/[^/]+$/.test(ref.rel) ? ref.rel.slice('.nowhere/refs/'.length) : null
161
+ if (!file || p.url) {
162
+ const added = refBoard.add(root, [{ name: path.basename(ref.rel), mime: ref.mime, data: Buffer.from(ref.data, 'base64'), ...(file ? {} : { from: ref.rel }), ...(p.url ? { url: p.url } : {}) }])
163
+ file = added.ok && added.added.length ? added.added[0] : file
164
+ if (!file) {
165
+ refused.push(`${p.path}: ${added.refused?.[0]?.why ?? added.error ?? 'it could not be put on the board'}`)
166
+ continue
167
+ }
168
+ }
169
+ if (offered.some((o) => o.file === file)) continue
170
+ offered.push({ file, from: ref.rel, what: p.what.trim(), label: p.label?.trim() || undefined, url: p.url, fresh: !before.has(file) })
171
+ }
172
+ if (refused.length) return fail(`Not shown, as some pictures cannot be used:\n- ${refused.join('\n- ')}`)
173
+ if (offered.length < 2) return fail('Offer at least two different pictures.')
174
+
175
+ const board = () => {
176
+ const now = refBoard.list(root)
177
+ return new Map((now.ok ? now.pictures : []).map((p) => [p.file, p]))
178
+ }
179
+ let pics = board()
180
+ for (const o of offered) {
181
+ if (pics.get(o.file)?.measured) continue
182
+ const m = await panels.measurePicture(root, o.file, { rpc: ctx.rpc })
183
+ if (m.ok) refBoard.setMeasured(root, m.file, m.sha256, m.measured)
184
+ else ctx.log?.(`[choices] ${o.file} was not measured: ${m.error}`)
185
+ }
186
+ pics = board()
187
+
188
+ // The agent's own pick, after "you choose" or no answer: recorded as the
189
+ // creator's would be, with no card.
190
+ if (a.decide) {
191
+ const norm = (v) => String(v).replace(/\\/g, '/').replace(/^\.\//, '')
192
+ const named = (d) => offered.find((o) => [o.from, `.nowhere/refs/${o.file}`, o.file].includes(norm(d)))
193
+ const unknown = a.decide.filter((d) => !named(d))
194
+ if (unknown.length) return fail(`decide names ${unknown.join(', ')}, which ${unknown.length === 1 ? 'is' : 'are'} not among the pictures given.`)
195
+ return record(root, offered, [...new Set(a.decide.map(named))], 'agent', panels)
196
+ }
197
+
198
+ // Nobody picked them: the fresh ones go back to being set aside, so a web
199
+ // find is not handed over in place of the creator's pictures until the
200
+ // agent takes it (decide) or the brief cites it.
201
+ const setAside = () => {
202
+ const aside = offered.filter((o) => o.fresh && refBoard.setUse(root, o.file, false)?.ok)
203
+ return aside.length ? ` The ${aside.length === 1 ? 'picture' : `${aside.length} pictures`} new on the board (${aside.map((o) => `.nowhere/refs/${o.file}`).join(', ')}) ${aside.length === 1 ? 'is' : 'are'} set aside there until you take ${aside.length === 1 ? 'it' : 'them'}.` : ''
204
+ }
205
+ const onBoard = offered.filter((o) => o.from !== `.nowhere/refs/${o.file}`).map((o) => ({ path: o.from, board: `.nowhere/refs/${o.file}` }))
206
+
207
+ const card = {
208
+ kind: 'pictures',
209
+ origin: 'agent',
210
+ title: a.title,
211
+ ...(a.body ? { body: a.body } : {}),
212
+ multiple: a.purpose === 'style' ? false : a.multiple,
213
+ ...(a.purpose === 'style' ? { purpose: 'style' } : {}),
214
+ pictures: offered.map((o) => {
215
+ const m = pics.get(o.file)?.measured
216
+ return {
217
+ file: o.file,
218
+ ...(o.label ? { label: o.label } : {}),
219
+ ...(o.url ?? pics.get(o.file)?.url ? { url: o.url ?? pics.get(o.file).url } : {}),
220
+ palette: (m?.palette ?? []).slice(0, 8).map((c) => ({ hex: c.hex, share: c.share })),
221
+ ...(m ? { key: m.value.key, warmth: m.warmth, haze: m.haze.direction, size: { width: m.size.width, height: m.size.height } } : {}),
222
+ }
223
+ }),
224
+ }
225
+ const r = await askCard(ctx, card)
226
+ const how = 'then record it by calling nw_ask_pictures again with the same pictures and decide: the paths you take (no card is shown)'
227
+ const other = r && typeof r === 'object' ? unanswered(r, 'the reference set', how) : null
228
+ if (other) return { text: `${JSON.stringify({ answer: r.answer ?? r.code, ...(onBoard.length ? { onBoard } : {}) })}\n${other}${setAside()}` }
229
+ if (!r || typeof r !== 'object' || r.ok === false || r.answer === undefined) {
230
+ const aside = setAside()
231
+ return fail(`The card could not be shown: ${r?.error ?? 'the studio did not answer'}.${aside}`)
232
+ }
233
+ if (r.answer === 'choose') {
234
+ return {
235
+ text: `${JSON.stringify({ answer: 'choose', ...(onBoard.length ? { onBoard } : {}) })}\nThe creator left the reference set to you. Pick by the request, ${how}: that cites them in brief.json's references and keeps them for the brief on the board. Say in your reply which you took, so the creator can change it.${setAside()}`,
236
+ }
237
+ }
238
+ const picked = Array.isArray(r.answer) ? offered.filter((o) => r.answer.includes(o.file)) : []
239
+ if (!picked.length) return fail('The answer named none of the pictures offered.')
240
+ return record(root, offered, picked, 'creator', panels)
241
+ }
242
+
243
+ /** A pick, the creator's or the agent's, recorded as the board's switch and
244
+ * the brief record it: the picks for the brief, the rest kept on the board
245
+ * but no longer handed over (one the brief cites stays with the agent
246
+ * whatever was picked), and brief.json citing each pick. */
247
+ async function record(root, offered, picked, who, panels) {
248
+ const kept = []
249
+ for (const o of offered) {
250
+ const on = picked.includes(o)
251
+ const set = refBoard.setUse(root, o.file, on)
252
+ if (!on && set?.cited) kept.push(o.file)
253
+ }
254
+ const now = refBoard.list(root)
255
+ const byFile = new Map((now.ok ? now.pictures : []).map((p) => [p.file, p]))
256
+ const cites = await (await import('../assets/brief.mjs')).recordReferences(
257
+ root,
258
+ picked.map((o) => ({ path: `.nowhere/refs/${o.file}`, url: o.url ?? byFile.get(o.file)?.url ?? undefined, what: o.what, measured: panels.briefMeasured(byFile.get(o.file)?.measured) })),
259
+ )
260
+ const refs = cites.refs.map(({ already, ...ref }) => ref)
261
+ const names = cites.refs.map((ref) => `${ref.id} (${ref.path})`).join(', ')
262
+ const rest = offered.length - picked.length
263
+ const lines = [`${who === 'creator' ? 'The creator picked' : 'Recorded your pick:'} ${picked.length} of ${offered.length} for the brief: ${names}.`]
264
+ if (cites.status === 'written') lines.push(`They are cited in brief.json's references now, with your words and their measured numbers; take the palette, light and values from them.`)
265
+ else if (cites.status === 'unchanged') lines.push('brief.json already cites them.')
266
+ else if (cites.status === 'absent') lines.push('There is no brief.json yet: when you write it, put the references on the last line into it as they are.')
267
+ else lines.push(`brief.json was left as it is (${cites.error}): when you fix it, put the references on the last line into it.`)
268
+ if (rest) lines.push(`The other ${rest} stay on the board but are no longer handed to you${kept.length ? `, except ${kept.join(', ')}, which the brief cites` : ''}.`)
269
+ const tail = cites.status === 'absent' || cites.status === 'invalid' ? `\n${JSON.stringify(refs)}` : ''
270
+ const answer = who === 'creator' ? { answer: picked.map((o) => o.file) } : { decided: picked.map((o) => o.file) }
271
+ return { text: `${JSON.stringify({ ...answer, brief: cites.status, references: refs.map((x) => x.id) })}\n${lines.join(' ')}${tail}` }
272
+ }
273
+
274
+ // ---------------------------------------------------------------- nw_ask_asset
275
+
276
+ /** The classes a card offers a model in: a small prop is the agent's to
277
+ * choose, with no card (cards.cjs refuses it too). */
278
+ const CLASSES = ['hero', 'prop', 'large', 'character', 'building', 'terrain']
279
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/
280
+
281
+ const ASSET_SHAPE = {
282
+ title: z.string().min(1).max(80).describe("The question, in the screen language: which floor, which sky."),
283
+ body: z.string().max(600).optional().describe("A line on where it goes in the space, in the screen language."),
284
+ kind: z.enum(['material', 'model', 'hdri']),
285
+ name: z.string().regex(NAME).describe("What the pick imports as: assets/<name> for a material (the brief's material of that name sets the texel density it is held to), assets/<name>.glb for a model, assets/<name>.hdr for a sky."),
286
+ class: z.enum(CLASSES).optional().describe('model: its class (the triangles and the texture size it keeps); default hero, as a card is for a hero prop. Never small: a small prop is yours to choose, with no card.'),
287
+ candidates: z
288
+ .array(
289
+ z.object({
290
+ id: z.string().regex(/^(polyhaven|ambientcg):[\w.-]{1,120}$/).describe('An id asset_search listed (Poly Haven or ambientCG).'),
291
+ label: z.string().max(60).optional().describe("A few words on why this one, in the screen language."),
292
+ }),
293
+ )
294
+ .min(2)
295
+ .max(4)
296
+ .describe('2 to 4 candidates for this one role.'),
297
+ query: z.string().max(80).optional().describe('The asset_search query that found them, for a candidate searched in an earlier request.'),
298
+ replace: z.boolean().default(false).describe('Replace what is at that name now (the creator is choosing a new one for the same role).'),
299
+ }
300
+
301
+ const ASSET_DESCRIPTION =
302
+ 'Shows 2 to 4 library candidates (asset_search ids from Poly Haven or ambientCG) for one role of the space in the chat, each with its picture, source, licence, real size, downloads and the texel density each gives against the brief, and waits for the creator to pick one and its resolution, or to leave it to you. Only for the big choices: the main surfaces (floor, walls), the sky and hero props; everything else you choose yourself. The pick is imported as name, through asset_fetch, asset_import (the ledger and CREDITS.md) and asset_inspect, and the inspection shows in the chat under the card; the answer has the import and its inspection, so do not fetch it again. On "you choose" or no answer within 10 minutes, import the one you think best yourself and say which in your reply. A request shows at most 6 of these cards and nw_ask_pictures\' together, and none after one went unanswered. Needs the creator\'s web consent, asked once.'
303
+
304
+ const STEPS = new Set(['fetching', 'importing', 'inspecting'])
305
+
306
+ /** The numbers of asset_inspect's report (assets/inspect.mjs reportLines)
307
+ * that the card labels in the screen language: the texel density
308
+ * against the brief, the 2 x 2 tiling, the maps, a model's triangles and
309
+ * size, and the GPU memory. Read from its lines; a line it does not find
310
+ * is left out, and the card shows the whole report folded beside them. */
311
+ export function inspectFacts(text) {
312
+ const facts = {}
313
+ const num = (v) => Number(String(v).replace(/,/g, ''))
314
+ for (const raw of String(text ?? '').split('\n')) {
315
+ const line = raw.replace(/^\s*- /, '')
316
+ let m
317
+ if ((m = /^texel density: (\d+(?:\.\d+)?) px\/m(.*)$/.exec(line))) {
318
+ const target = /against (\d+(?:\.\d+)?) px\/m/.exec(m[2])
319
+ const words = m[2]
320
+ const verdict = !target ? 'none' : /under half/.test(words) ? 'refuse' : /softer than/.test(words) ? 'low' : /times it/.test(words) ? 'high' : /on target/.test(words) ? 'ok' : 'none'
321
+ facts.density = { px: num(m[1]), verdict, ...(target ? { target: num(target[1]) } : {}) }
322
+ } else if ((m = /^2 x 2 tiling: (.*)$/.exec(line))) {
323
+ const w = m[1]
324
+ const verdict = /^tiles cleanly/.test(w) ? 'clean' : /faint seam/.test(w) ? 'faint' : /visible seam/.test(w) ? 'seam' : /joints/.test(w) ? 'joint' : null
325
+ const score = /score (\d+(?:\.\d+)?)/.exec(w) ?? /steps (\d+(?:\.\d+)?) times/.exec(w)
326
+ if (verdict) facts.tiling = { verdict, ...(score ? { score: num(score[1]) } : {}) }
327
+ } else if ((m = /^maps: (.*)$/.exec(line))) {
328
+ const [have, after = ''] = m[1].split(/; /)
329
+ const missing = /^missing ([a-z, ]+?)(?: \(|$)/.exec(after)
330
+ facts.maps = { have: have.split(', ').filter(Boolean).length, missing: missing ? missing[1].split(', ').filter(Boolean) : [] }
331
+ } else if ((m = /^([\d,]+) triangles, (?:(\d+(?:\.\d+)?) x (\d+(?:\.\d+)?) x (\d+(?:\.\d+)?) m)?/.exec(line))) {
332
+ facts.triangles = num(m[1])
333
+ if (m[2]) facts.size = [num(m[2]), num(m[3]), num(m[4])]
334
+ } else if ((m = /^GPU memory: (\d+(?:\.\d+)?)(?: to (\d+(?:\.\d+)?))? MB(.*)$/.exec(line))) {
335
+ facts.gpu = { mb: num(m[1]), ...(m[2] ? { upTo: num(m[2]) } : {}), ktx2: /^, (?:its textures )?written as KTX2/.test(m[3]) }
336
+ }
337
+ }
338
+ return Object.keys(facts).length ? facts : null
339
+ }
340
+
341
+ /** The import as the chat shows it under the card: no pictures, the
342
+ * inspection's words at most 3,000 characters, and its numbers. */
343
+ function reportFor(r) {
344
+ const licence = (r.imported ?? '').split('\n').find((l) => /^licen[cs]e:/i.test(l)) ?? null
345
+ return {
346
+ ok: r.ok === true,
347
+ ...(r.as ? { as: r.as } : {}),
348
+ ...(r.resolution ? { resolution: r.resolution } : {}),
349
+ ...(r.ok ? {} : { error: String(r.error ?? 'Not imported.').slice(0, 1200), ...(r.conflict ? { conflict: true } : {}) }),
350
+ ...(licence ? { licence: licence.slice(0, 300) } : {}),
351
+ entries: (r.entries ?? []).slice(0, 16).map((e) => ({ path: e.path, bytes: e.bytes, license: e.license ?? 'unknown' })),
352
+ credits: r.credits === true,
353
+ // The chat shows the words, not the 2 x 2 sheet: the line about it goes too.
354
+ ...(r.inspect ? { inspect: { text: String(r.inspect.text ?? '').split('\n').filter((l) => !/^The picture is it tiled/.test(l)).join('\n').slice(0, 3000), isError: r.inspect.isError === true } } : {}),
355
+ ...(r.inspect && !r.inspect.isError && inspectFacts(r.inspect.text) ? { facts: inspectFacts(r.inspect.text) } : {}),
356
+ }
357
+ }
358
+
359
+ /** The density the brief holds this role to, and why, as the browser says it. */
360
+ function targetFor(brief, kind, name, ids) {
361
+ if (!brief || brief.status !== 'ok' || kind === 'hdri') return null
362
+ const own = brief.materials?.find((m) => m.name === name || ids.includes(m.source?.id))
363
+ if (own) return { density: own.texelDensity, why: `the brief's ${own.name}` }
364
+ if (brief.texelDensity) return { density: brief.texelDensity, why: "the brief's texel density" }
365
+ return null
366
+ }
367
+
368
+ async function askAsset(args, ctx, assetTools) {
369
+ const parsed = z.object(ASSET_SHAPE).safeParse(args ?? {})
370
+ if (!parsed.success) return fail(`nw_ask_asset: ${issues(parsed.error)}`)
371
+ const a = parsed.data
372
+ if (!ctx?.projectRoot) return fail('No project is open.')
373
+ if (new Set(a.candidates.map((c) => c.id)).size !== a.candidates.length) return fail('Each candidate once.')
374
+ const unreadable = languageProblem([a.title, a.body, ...a.candidates.map((c) => c.label)], ctx.locale)
375
+ if (unreadable) return fail(unreadable)
376
+ const { searchedCard, webAllowed, makeAssetTools } = await import('./assets.mjs')
377
+ const panels = await import('../panels.mjs')
378
+ const allowed = await webAllowed(ctx)
379
+ if (allowed !== 'allow') return { text: `The web is not allowed (${allowed}), so nothing was shown or downloaded. Choose from what the space has, or make it.` }
380
+ const defs = Object.fromEntries((assetTools ?? makeAssetTools()).map((d) => [d.name, d]))
381
+
382
+ // The hits as asset_search showed them, searched again when one is not
383
+ // among this process's searches.
384
+ const imported = await panels.importedBySource(ctx.projectRoot)
385
+ const hits = new Map()
386
+ for (const c of a.candidates) {
387
+ const card = searchedCard(c.id)
388
+ if (card) hits.set(c.id, panels.hitOf(card, imported))
389
+ }
390
+ const missing = a.candidates.filter((c) => !hits.has(c.id))
391
+ if (missing.length && a.query) {
392
+ const found = await panels.searchLibraries(defs, { query: a.query, kind: a.kind }, ctx)
393
+ if (found.ok) for (const h of found.hits) if (missing.some((c) => c.id === h.id)) hits.set(h.id, h)
394
+ }
395
+ const lost = a.candidates.filter((c) => !hits.has(c.id)).map((c) => c.id)
396
+ if (lost.length) return fail(`${lost.join(', ')} ${lost.length === 1 ? 'is' : 'are'} not among the hits searched: asset_search first (or pass query) and offer ids it listed.`)
397
+ const wrongKind = a.candidates.filter((c) => hits.get(c.id).kind !== a.kind).map((c) => c.id)
398
+ if (wrongKind.length) return fail(`${wrongKind.join(', ')} ${wrongKind.length === 1 ? 'is' : 'are'} not a ${a.kind}.`)
399
+
400
+ const brief = await panels.briefFacts(ctx.projectRoot)
401
+ const ids = a.candidates.map((c) => c.id)
402
+ const card = {
403
+ kind: 'assets',
404
+ origin: 'agent',
405
+ title: a.title,
406
+ ...(a.body ? { body: a.body } : {}),
407
+ assets: {
408
+ kind: a.kind,
409
+ name: a.name,
410
+ ...(a.kind === 'model' ? { class: a.class ?? 'hero' } : {}),
411
+ target: targetFor(brief, a.kind, a.name, ids.map((id) => id.slice(id.indexOf(':') + 1))),
412
+ limits: panels.LIMITS,
413
+ // What the browser showed of each, cut to what the card holds.
414
+ candidates: a.candidates.map((c) => {
415
+ const h = hits.get(c.id)
416
+ return {
417
+ ...h,
418
+ title: String(h.title).slice(0, 120),
419
+ author: String(h.author ?? '').slice(0, 160),
420
+ maps: h.maps.slice(0, 12),
421
+ imported: h.imported.slice(0, 8),
422
+ tags: [],
423
+ name: a.name,
424
+ ...(c.label ? { label: c.label } : {}),
425
+ }
426
+ }),
427
+ },
428
+ }
429
+ const r = await askCard(ctx, card)
430
+ const other = r && typeof r === 'object' ? unanswered(r, `the ${a.kind} for ${a.name}`, `then import it as assets/${a.name}${a.kind === 'model' ? '.glb' : ''} with asset_fetch and asset_import`) : null
431
+ if (other) return { text: `${JSON.stringify({ answer: r.answer ?? r.code })}\n${other}` }
432
+ if (!r || typeof r !== 'object' || r.ok === false || r.answer === undefined) return fail(`The card could not be shown: ${r?.error ?? 'the studio did not answer'}.`)
433
+ if (r.answer === 'choose') {
434
+ return { text: `${JSON.stringify({ answer: 'choose' })}\nThe creator left it to you. Import the candidate you think best as assets/${a.name}${a.kind === 'model' ? '.glb' : ''} (asset_fetch, then asset_import), and say in your reply which you took, so the creator can change it.` }
435
+ }
436
+ const hit = hits.get(r.id)
437
+ if (r.answer !== 'pick' || !hit) return fail('The answer named none of the candidates offered.')
438
+
439
+ // The import, as the browser ran it, with its steps under the card.
440
+ const update = (patch) => ctx.rpc('card-update', { runId: ctx.runId, cardId: r.cardId, ...patch }).catch(() => null)
441
+ const done = await panels.importLibraryHit(
442
+ defs,
443
+ { id: hit.id, kind: a.kind, resolution: r.resolution, name: a.name, ...(a.kind === 'model' ? { class: a.class ?? 'hero' } : {}), replace: a.replace },
444
+ { ctx, step: (s) => (STEPS.has(s) ? void update({ step: s }) : undefined) },
445
+ )
446
+ await update({ step: done.ok ? 'done' : 'failed', report: reportFor(done) })
447
+ const head = `The creator picked ${hit.title} (${hit.id}) at ${r.resolution}.`
448
+ if (!done.ok) {
449
+ const why = done.conflict ? `${done.error} Ask again with replace: true if it should replace it, or import it under another name.` : done.error
450
+ return { text: `${JSON.stringify({ answer: 'pick', id: hit.id, resolution: r.resolution, imported: false })}\n${head} It was not imported: ${why}`, isError: true }
451
+ }
452
+ // asset_import's answer has its own inspection; asset_inspect's, run after
453
+ // it as the browser ran it, is the one the creator sees under the card.
454
+ const lines = [head, `Imported as ${done.as}: ${done.written.length} ${done.written.length === 1 ? 'file' : 'files'}, recorded in assets.lock.json${done.credits ? ' and CREDITS.md' : ''}.`, done.imported ?? (done.inspect ? `Inspection:\n${done.inspect.text}` : '')]
455
+ lines.push('The creator sees the inspection under the card. Use it from there; it needs no other fetch.')
456
+ return { text: `${JSON.stringify({ answer: 'pick', id: hit.id, resolution: r.resolution, as: done.as, written: done.written })}\n${lines.filter(Boolean).join('\n')}` }
457
+ }
458
+
459
+ /** The ToolDefs, with the asset tools replaceable for checks. */
460
+ export function makeChoiceTools({ assetTools } = {}) {
461
+ const guarded = (name, fn) => async (args, ctx) => {
462
+ try {
463
+ return await fn(args, ctx)
464
+ } catch (err) {
465
+ return fail(`${name} failed: ${err?.message ?? err}`)
466
+ }
467
+ }
468
+ return [
469
+ // Not read-only: it puts pictures on the board, sets what is handed over
470
+ // and writes brief.json's references, so a big job asks it after its
471
+ // cost was approved, as it writes the brief.
472
+ { name: 'nw_ask_pictures', description: PICTURES_DESCRIPTION, shape: PICTURES_SHAPE, handler: guarded('nw_ask_pictures', askPictures), readOnly: false, mainOnly: true },
473
+ { name: 'nw_ask_asset', description: ASSET_DESCRIPTION, shape: ASSET_SHAPE, handler: guarded('nw_ask_asset', (a, c) => askAsset(a, c, assetTools)), readOnly: false, mainOnly: true },
474
+ ]
475
+ }
476
+
477
+ export const TOOLS = makeChoiceTools()
478
+
479
+ export { WAIT_MINUTES }
@@ -0,0 +1,74 @@
1
+ // nw_compose: the target and a still of the space now, side by side,
2
+ // labelled "target | now", with marks drawn on the "now" half
3
+ // (reference/compose.mjs). The round's picture (REFERENCE_LOOP.md 2.4): what
4
+ // a round message shows, what the judge is handed, and how a gap is pointed
5
+ // at. The same tool in the studio and in the CLI (`nowhere tool nw_compose`).
6
+ //
7
+ // It writes only under .nowhere/compose/ in the project. The agent's own
8
+ // Write, Edit and Bash are kept out of .nowhere/ (guard.mjs), and this tool
9
+ // must not be the way round that: a round's record (.nowhere/rounds/) is
10
+ // the round tool's to write, and perf.json and the rest are the studio's.
11
+ // The marks are the chat's, with the chat's limits (notes.cjs marksFor), so
12
+ // a creator's note handed on as it came is never refused here.
13
+
14
+ import { createHash } from 'node:crypto'
15
+ import { z } from 'zod'
16
+ import { MARK_TEXT_MAX, compose } from '../reference/compose.mjs'
17
+
18
+ export const RPC_METHODS = []
19
+
20
+ /** The one folder nw_compose writes in. */
21
+ export const COMPOSE_DIR = '.nowhere/compose'
22
+
23
+ const point = z.array(z.number()).length(2)
24
+
25
+ const SHAPE = {
26
+ target: z.string().describe('The target picture, a path in the project (e.g. .nowhere/refs/R2.png).'),
27
+ current: z.string().describe('The still of the space now from the same hero camera, a path in the project (e.g. .nowhere/rounds/3/still-H2.png).'),
28
+ out: z.string().optional().describe(`Where the PNG goes, under ${COMPOSE_DIR}/. Default ${COMPOSE_DIR}/<target>-<current>.png, with the round's number when the still is a round's.`),
29
+ label: z.string().max(120).optional().describe('The view and round, e.g. "H2 round 3"; the bar adds "target | now" itself.'),
30
+ marks: z
31
+ .array(
32
+ z.object({
33
+ kind: z.enum(['pen', 'circle', 'arrow', 'text']),
34
+ points: z.array(point).max(600).optional().describe("In the current picture's pixels: a pen's path, an arrow's tail and head, where text starts."),
35
+ rect: z.array(z.number()).length(4).optional().describe("[x, y, width, height] in the current picture's pixels: the box a circle's ring fills."),
36
+ text: z.string().max(MARK_TEXT_MAX).optional().describe('Words drawn by the mark (any kind may have them).'),
37
+ }),
38
+ )
39
+ .max(40)
40
+ .optional()
41
+ .describe('Drawn on the "now" half, as the chat sends a marked picture.'),
42
+ }
43
+
44
+ const slug = (p) => String(p).split(/[\\/]/).pop().replace(/\.[a-z]+$/i, '').replace(/[^\w-]+/g, '_').slice(0, 40)
45
+
46
+ /** The default name: the two pictures', the round's number when the still
47
+ * is in a round's folder, and a short hash of the still's path, so round
48
+ * 3's still-H2 never overwrites round 2's. */
49
+ export function defaultOut(target, current) {
50
+ const round = /(?:^|[\\/])rounds[\\/](\d+)[\\/]/.exec(String(current))
51
+ const tag = createHash('sha1').update(String(current).split('\\').join('/')).digest('hex').slice(0, 6)
52
+ return `${COMPOSE_DIR}/${slug(target)}-${round ? `r${round[1]}-` : ''}${slug(current)}-${tag}.png`
53
+ }
54
+
55
+ export const TOOLS = [
56
+ {
57
+ name: 'nw_compose',
58
+ description: `Puts a target picture and a still of the space now side by side at one height, labelled "target | now", and draws marks on the "now" half (pen, circle, arrow, text, in the current picture's pixels; a circle's rect is [x, y, width, height]; the "now" half is cut to the target's shape when they differ, and the marks follow). Writes a PNG under ${COMPOSE_DIR}/ and returns it. Use it to look at a hero view against its target, and to point at a gap.`,
59
+ shape: SHAPE,
60
+ handler: async (args, ctx) => {
61
+ const root = ctx?.projectRoot
62
+ if (!root) return { text: 'There is no project open.', isError: true }
63
+ const out = args.out ?? defaultOut(args.target, args.current)
64
+ const r = await compose(args.target, args.current, out, { label: args.label ?? '', marks: args.marks ?? [], root, within: COMPOSE_DIR, rpc: typeof ctx.rpc === 'function' ? ctx.rpc : null })
65
+ if (!r.ok) return { text: r.error, isError: true }
66
+ const fs = await import('node:fs/promises')
67
+ const path = await import('node:path')
68
+ const data = (await fs.readFile(r.path)).toString('base64')
69
+ const rel = path.relative(path.resolve(root), r.path).split(path.sep).join('/')
70
+ const cut = r.cut ? ` The "now" half was cut to the target's shape (${r.cut.w} x ${r.cut.h} from ${r.cut.x}, ${r.cut.y}).` : ''
71
+ return { text: `Wrote ${rel} (${r.width} x ${r.height}): target left, now right${r.marks ? `, ${r.marks} mark${r.marks === 1 ? '' : 's'} drawn` : ''}.${cut}`, images: [{ data, mime: 'image/png' }] }
72
+ },
73
+ },
74
+ ]