oda-engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +90 -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-CB77cP9U.js +1 -0
  197. package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
  198. package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
  200. package/web-dist/assets/index-CcjyyQco.css +1 -0
  201. package/web-dist/assets/index-DMyJcoZJ.js +693 -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,643 @@
1
+ // The sessions of a production. Every role attempt and every decision is
2
+ // its own query(), so its own Claude Code subprocess, with its own system
3
+ // prompt, tools, model and effort; their nw tools run here, in the agent
4
+ // host's process, so the eyes, the cards, the ledgers and the asset
5
+ // ledger's write queue are shared. A role session is held to the files its
6
+ // task owns (the write guard, before the run's own guard), to its own
7
+ // acceptance checks (task_check, and a stop gate scoped to its files), and
8
+ // reports through a structured output; a decision session has no tools at
9
+ // all and answers one schema.
10
+ //
11
+ // One attempt (runAttempt): the owned files are snapshotted, the role
12
+ // builds its session from the task (roles/), the router's pick gives the
13
+ // model and effort, the session runs and its report is read. The gate that
14
+ // follows, and the task's next attempt (a resume, or a fresh session with a
15
+ // handoff), are the director's (director.mjs).
16
+
17
+ import { createSdkMcpServer } from '@anthropic-ai/claude-agent-sdk'
18
+ import { z } from 'zod'
19
+ import fs from 'node:fs'
20
+ import fsp from 'node:fs/promises'
21
+ import path from 'node:path'
22
+ import { promptFor } from '../../userMessage.mjs'
23
+ import { LEDGER, putEntries, readLedgerState } from '../assets/ledger.mjs'
24
+ import { readOnlyCommand } from '../guard.mjs'
25
+ import { SDK_SOURCES, realOrSelf, sessionDir } from '../shared.mjs'
26
+ import { runDef, toSdkTool } from '../tools/index.mjs'
27
+ import { createTranscriptTap } from '../transcripts.mjs'
28
+ import { LOOK_KEYS, isDirectorFile, matches, ownerOf, relPath, roleNoun } from './board.mjs'
29
+ import { QAReport, RoleReport, fitTo, jsonSchemaOf, parseWith } from './contracts.mjs'
30
+ import { ATTEMPT_PROMPT, handoffText } from './prompts.mjs'
31
+ import { writeAtomic } from './store.mjs'
32
+ import { createTaskGate, ownedFiles } from './taskGate.mjs'
33
+
34
+ const MCP_INSTRUCTIONS = 'Build, inspect and playtest tools for one task of an Oda game production.'
35
+ /** The file tools and the field that names what they write. */
36
+ const WRITE_TOOLS = { Write: ['file_path', 'path'], Edit: ['file_path', 'path'], MultiEdit: ['file_path', 'path'], NotebookEdit: ['notebook_path', 'path'] }
37
+ /** The nw tools that write files, and the fields that name them. */
38
+ const NW_WRITES = { nw_blender: ['script', 'out', 'blend'], asset_import: ['as'], nw_take_download: ['to'], image_generate: ['out'] }
39
+ /** What a decision session may never do: it has no tools, and a call is refused. */
40
+ const NO_TOOLS = async () => ({ behavior: 'deny', message: 'A decision session answers with its structured output only.' })
41
+ const BASH_REASON = 'Refused: in a team task Bash only reads. Write files with Write or Edit, inside what your task owns.'
42
+ const LOOK_REASON = 'Refused: look_apply sets the look keys of game.config.json, which only an artist task changes. If the look must change, say so in your report under changesNeeded.'
43
+ const LOOK_KEYS_REASON = 'Refused: this change to game.config.json changes its look keys (sky, fog, lighting, bloom, look), which only an artist task sets, through look_apply. Leave them as they are; if the look must change, say so in your report under changesNeeded.'
44
+
45
+ /** A path a tool names, project-relative with forward slashes; null outside the project. */
46
+ export function projectRel(projectRoot, p) {
47
+ if (typeof p !== 'string' || !p) return null
48
+ const root = realOrSelf(projectRoot)
49
+ const abs = realOrSelf(path.resolve(root, p))
50
+ const rel = path.relative(root, abs)
51
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null
52
+ return rel.split(path.sep).join('/')
53
+ }
54
+
55
+ /** The project files one tool call writes. */
56
+ export function writtenPaths(projectRoot, toolName, input) {
57
+ const name = String(toolName ?? '').replace(/^mcp__nw__/, '')
58
+ const fields = WRITE_TOOLS[name] ?? NW_WRITES[name] ?? []
59
+ const out = []
60
+ for (const f of fields) {
61
+ const rel = projectRel(projectRoot, input?.[f])
62
+ if (rel && !out.includes(rel)) out.push(rel)
63
+ if (WRITE_TOOLS[name] && rel) break
64
+ }
65
+ return out
66
+ }
67
+
68
+ // ---------------------------------------------------------------- the config's look keys
69
+
70
+ const CONFIG = 'game.config.json'
71
+
72
+ /** game.config.json as an object, or null. */
73
+ function readConfig(projectRoot) {
74
+ try {
75
+ const v = JSON.parse(fs.readFileSync(path.join(projectRoot, CONFIG), 'utf8'))
76
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : null
77
+ } catch {
78
+ return null
79
+ }
80
+ }
81
+ /** A config's look keys: the values it has and the keys it has not. */
82
+ const lookOf = (config) => ({ values: Object.fromEntries(LOOK_KEYS.filter((k) => k in config).map((k) => [k, config[k]])), absent: LOOK_KEYS.filter((k) => !(k in config)) })
83
+ /** `config` with `look`'s values set and its absent keys left out. */
84
+ function withLook(config, look) {
85
+ const out = { ...config }
86
+ for (const k of look.absent) delete out[k]
87
+ return Object.assign(out, look.values)
88
+ }
89
+ /** Whether two JSON values are equal, whatever the order of their keys. */
90
+ const sameJson = (a, b) => {
91
+ const sorted = (v) => (Array.isArray(v) ? v.map(sorted) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sorted(v[k])])) : v)
92
+ return JSON.stringify(sorted(a)) === JSON.stringify(sorted(b))
93
+ }
94
+ /** How a task's snapshots treat the config's look keys: an artist's work is
95
+ * in them ('restore'); a task that owns the file keeps them ('keep'). */
96
+ export const lookMode = (task, roles) => (roles?.[task.role]?.configKeys?.length ? 'restore' : (task.owns ?? []).some((g) => matches(g, CONFIG)) ? 'keep' : null)
97
+ const writeConfig = (projectRoot, config) => writeAtomic(path.join(projectRoot, CONFIG), `${JSON.stringify(config, null, 2)}\n`)
98
+
99
+ /** game.config.json's text as one file-tool call would leave it; null
100
+ * when that cannot be told. */
101
+ function configAfter(projectRoot, name, input) {
102
+ if (name === 'Write') return typeof input?.content === 'string' ? input.content : null
103
+ let text
104
+ try {
105
+ text = fs.readFileSync(path.join(projectRoot, CONFIG), 'utf8')
106
+ } catch {
107
+ return null
108
+ }
109
+ const edits = name === 'MultiEdit' ? input?.edits : name === 'Edit' ? [input] : null
110
+ if (!Array.isArray(edits)) return null
111
+ for (const e of edits) {
112
+ if (typeof e?.old_string !== 'string' || typeof e?.new_string !== 'string') return null
113
+ text = e.replace_all ? text.split(e.old_string).join(e.new_string) : text.replace(e.old_string, () => e.new_string)
114
+ }
115
+ return text
116
+ }
117
+
118
+ /** Whether a file-tool call would change game.config.json's look keys. */
119
+ function changesLook(projectRoot, name, input) {
120
+ const after = configAfter(projectRoot, name, input)
121
+ const now = readConfig(projectRoot)
122
+ if (after === null || !now) return false
123
+ let next = null
124
+ try {
125
+ next = JSON.parse(after)
126
+ } catch {
127
+ // not JSON: the build says so, and no look key can be told apart
128
+ return false
129
+ }
130
+ return !!next && typeof next === 'object' && !Array.isArray(next) && !sameJson(lookOf(next), lookOf(now))
131
+ }
132
+
133
+ /**
134
+ * The write guard of one task: what its session may change. It runs before
135
+ * the run's own guard (paths outside the project, .git, the studio's files),
136
+ * which still applies. A task that owns game.config.json (the builder's)
137
+ * still may not change its look keys with a file tool.
138
+ *
139
+ * @returns {(toolName: string, input: object) => { ok: true } | { ok: false, reason: string }}
140
+ */
141
+ export function writeGuard({ task, board, roles, projectRoot }) {
142
+ const owns = (task.owns ?? []).map(relPath)
143
+ const refuse = (rel) => {
144
+ const owner = ownerOf(rel, { board, roles })
145
+ // A file no task owns is the director's to give, even inside this role's area.
146
+ const noun = owner === task.role && !board?.tasks?.some((t) => (t.owns ?? []).some((g) => matches(g, rel))) ? roleNoun('director') : roleNoun(owner)
147
+ return { ok: false, reason: `Refused: ${rel} belongs to ${noun}. Your task owns: ${owns.join(', ') || 'nothing'}. If it must change, say so in your report under changesNeeded.` }
148
+ }
149
+ const owned = (rel) => !isDirectorFile(rel) && owns.some((g) => matches(g, rel))
150
+ return (toolName, input) => {
151
+ const name = String(toolName ?? '').replace(/^mcp__nw__/, '')
152
+ if (name === 'Bash') return readOnlyCommand(input?.command) ? { ok: true } : { ok: false, reason: BASH_REASON }
153
+ if (name === 'look_apply' && task.role !== 'artist') return { ok: false, reason: LOOK_REASON }
154
+ if (WRITE_TOOLS[name] || NW_WRITES[name]) {
155
+ const fields = WRITE_TOOLS[name] ?? NW_WRITES[name]
156
+ for (const f of fields) {
157
+ if (typeof input?.[f] !== 'string' || !input[f]) continue
158
+ const rel = projectRel(projectRoot, input[f])
159
+ // Outside the project: the run's own guard answers with its reason.
160
+ if (rel === null) continue
161
+ if (!owned(rel)) return refuse(rel)
162
+ // The file is the builder's, its look keys the artist's (look_apply).
163
+ if (rel === CONFIG && WRITE_TOOLS[name] && changesLook(projectRoot, name, input)) return { ok: false, reason: LOOK_KEYS_REASON }
164
+ if (WRITE_TOOLS[name]) break
165
+ }
166
+ }
167
+ return { ok: true }
168
+ }
169
+ }
170
+
171
+ // ---------------------------------------------------------------- snapshots
172
+
173
+ /**
174
+ * The owned files as they are now, under `dir` (files/ and manifest.json),
175
+ * with what assets.lock.json records of them (a model and its ledger entry
176
+ * go back together). look 'restore' (an artist task) also keeps the look
177
+ * keys of game.config.json, which look_apply sets and no task owns as a file.
178
+ */
179
+ export async function snapshot(projectRoot, owns, dir, { look = null } = {}) {
180
+ const files = await ownedFiles(projectRoot, owns)
181
+ await fsp.rm(dir, { recursive: true, force: true })
182
+ await fsp.mkdir(path.join(dir, 'files'), { recursive: true })
183
+ for (const rel of files) {
184
+ const to = path.join(dir, 'files', rel)
185
+ await fsp.mkdir(path.dirname(to), { recursive: true })
186
+ await fsp.copyFile(path.join(projectRoot, rel), to)
187
+ }
188
+ // The literal paths it owns that were not there: put back means gone.
189
+ const absent = owns.filter((g) => !/[*?[{]/.test(g) && !files.includes(relPath(g))).map(relPath)
190
+ const config = look === 'restore' ? readConfig(projectRoot) : null
191
+ const recorded = (await readLedgerState(projectRoot).catch(() => null))?.lock?.files ?? {}
192
+ const ledger = Object.fromEntries(files.filter((rel) => recorded[rel]).map((rel) => [rel, recorded[rel]]))
193
+ const manifest = { files, absent, ...(config ? { look: lookOf(config) } : {}), ledger }
194
+ await fsp.writeFile(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2))
195
+ return manifest
196
+ }
197
+
198
+ /**
199
+ * Puts the owned files back as `dir` holds them, byte for byte; a file
200
+ * that was not there then is removed. Returns the paths it changed. What
201
+ * assets.lock.json records of them goes back with them: the snapshot's
202
+ * entries, and none for a file it did not have, so the ledger never
203
+ * records another round's model. The look keys of game.config.json are the
204
+ * artist's whoever owns the file: look 'restore' puts the snapshot's back
205
+ * (an artist task), look 'keep' puts the rest of the file back around the
206
+ * look keys it has now (a builder task that owns it).
207
+ */
208
+ export async function restore(projectRoot, owns, dir, { look = null } = {}) {
209
+ const manifest = JSON.parse(await fsp.readFile(path.join(dir, 'manifest.json'), 'utf8'))
210
+ const keep = new Set(manifest.files)
211
+ const changed = []
212
+ for (const rel of await ownedFiles(projectRoot, owns)) {
213
+ if (keep.has(rel)) continue
214
+ await fsp.rm(path.join(projectRoot, rel), { force: true })
215
+ changed.push(rel)
216
+ }
217
+ for (const rel of manifest.files) {
218
+ const from = path.join(dir, 'files', rel)
219
+ const to = path.join(projectRoot, rel)
220
+ if (rel === CONFIG && look === 'keep') {
221
+ const now = readConfig(projectRoot)
222
+ let then = null
223
+ try {
224
+ then = JSON.parse(fs.readFileSync(from, 'utf8'))
225
+ } catch {
226
+ then = null
227
+ }
228
+ if (now && then && typeof then === 'object' && !Array.isArray(then)) {
229
+ const next = withLook(then, lookOf(now))
230
+ if (!sameJson(next, now)) {
231
+ await writeConfig(projectRoot, next)
232
+ changed.push(rel)
233
+ }
234
+ continue
235
+ }
236
+ }
237
+ const same = fs.existsSync(to) && Buffer.compare(fs.readFileSync(to), fs.readFileSync(from)) === 0
238
+ if (same) continue
239
+ await fsp.mkdir(path.dirname(to), { recursive: true })
240
+ await fsp.copyFile(from, to)
241
+ changed.push(rel)
242
+ }
243
+ if (look === 'restore' && manifest.look) {
244
+ const now = readConfig(projectRoot)
245
+ if (now) {
246
+ const next = withLook(now, manifest.look)
247
+ if (!sameJson(next, now)) {
248
+ await writeConfig(projectRoot, next)
249
+ changed.push(`${CONFIG} (its look keys)`)
250
+ }
251
+ }
252
+ }
253
+ // The ledger, for the owned files it records: as the snapshot had them
254
+ // (a snapshot from before it kept them leaves the ledger as it is).
255
+ const recorded = manifest.ledger ? ((await readLedgerState(projectRoot).catch(() => null))?.lock?.files ?? {}) : {}
256
+ const set = manifest.ledger ?? {}
257
+ const remove = Object.keys(recorded).filter((rel) => owns.some((g) => matches(g, rel)) && !set[rel])
258
+ if (Object.keys(set).length || remove.length) {
259
+ const r = await putEntries(projectRoot, { set, remove })
260
+ if (r.changed) changed.push(`${LEDGER} (${[...new Set([...Object.keys(set), ...remove])].join(', ')})`)
261
+ }
262
+ return changed
263
+ }
264
+
265
+ /** What changed in the owned files since a snapshot, as one line. */
266
+ export async function diffStat(projectRoot, owns, dir) {
267
+ let before = { files: [] }
268
+ try {
269
+ before = JSON.parse(await fsp.readFile(path.join(dir, 'manifest.json'), 'utf8'))
270
+ } catch {
271
+ // no snapshot: everything is new
272
+ }
273
+ const now = await ownedFiles(projectRoot, owns)
274
+ const parts = []
275
+ for (const rel of now) {
276
+ const size = fs.statSync(path.join(projectRoot, rel)).size
277
+ const kb = `${(size / 1024).toFixed(1)} KB`
278
+ if (!before.files.includes(rel)) parts.push(`${rel} (new, ${kb})`)
279
+ else if (Buffer.compare(fs.readFileSync(path.join(projectRoot, rel)), fs.readFileSync(path.join(dir, 'files', rel))) !== 0) parts.push(`${rel} (changed, ${kb})`)
280
+ }
281
+ for (const rel of before.files) if (!now.includes(rel)) parts.push(`${rel} (removed)`)
282
+ return parts.join(', ') || 'no change to your files'
283
+ }
284
+
285
+ // ---------------------------------------------------------------- the sessions
286
+
287
+ /** Which of a role's skills shipped in the plugin, so a skill that has not
288
+ * landed yet is not asked for. */
289
+ const skillsIn = (pluginDir, names) => (names ?? []).filter((n) => fs.existsSync(path.join(pluginDir, 'skills', String(n).replace(/^nowhere:/, ''), 'SKILL.md')))
290
+
291
+ /**
292
+ * @param {{ query: Function, send: Function, log: Function, ledger: object, projectRoot: string, runDir: string,
293
+ * runId: string, childEnv: object, guard: { check: Function }, pluginDir: string, withPlugin: boolean }} deps
294
+ */
295
+ export function createSessions({ query, send, log, ledger, projectRoot, runDir, runId, childEnv = {}, guard, pluginDir, withPlugin }) {
296
+ /** key -> the running query */
297
+ const running = new Map()
298
+ const interrupted = []
299
+ let stopped = false
300
+ let turns = 0
301
+
302
+ const envFor = (key) => ({
303
+ ...childEnv,
304
+ NOWHERE_SESSION: key,
305
+ CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS: '1',
306
+ CLAUDE_CODE_ENABLE_TODO_TOOLS: '1',
307
+ CLAUDE_CODE_ENABLE_TASKS: '0',
308
+ })
309
+
310
+ /** Streams one query: its usage into the session's ledger, a role's tool
311
+ * steps into the chat under its task; returns the result message. */
312
+ async function consume(session, { key, taskId, book, tap, timeoutMs }) {
313
+ running.set(key, session)
314
+ let result = null
315
+ let sessionId = null
316
+ let timedOut = false
317
+ const seen = new Map()
318
+ const timer = timeoutMs
319
+ ? setTimeout(() => {
320
+ timedOut = true
321
+ log(`[director] ${key} ran past ${Math.round(timeoutMs / 60_000)} minutes and was interrupted`)
322
+ void Promise.resolve(session.interrupt?.()).catch(() => {})
323
+ }, timeoutMs)
324
+ : null
325
+ timer?.unref?.()
326
+ try {
327
+ for await (const m of session) {
328
+ if (m.type === 'system' && m.subtype === 'init') {
329
+ sessionId = m.session_id ?? sessionId
330
+ tap?.follow(sessionId)
331
+ log(`[director] ${key} init model=${m.model} tools=${(m.tools ?? []).length}`)
332
+ } else if (m.type === 'stream_event') book.addStreamEvent(m)
333
+ else if (m.type === 'assistant') {
334
+ book.addUsage(m)
335
+ if (!taskId) continue
336
+ for (const block of m.message?.content ?? []) {
337
+ if (block.type !== 'tool_use') continue
338
+ seen.set(block.id, block.name)
339
+ send({ type: 'tool', id: runId, toolId: block.id, name: block.name, input: block.input, taskId })
340
+ }
341
+ } else if (m.type === 'user' && taskId) {
342
+ for (const block of m.message?.content ?? []) {
343
+ if (block.type !== 'tool_result') continue
344
+ send({ type: 'tool-result', id: runId, toolId: block.tool_use_id, name: seen.get(block.tool_use_id) ?? 'tool', isError: block.is_error === true, taskId })
345
+ }
346
+ } else if (m.type === 'result') result = m
347
+ }
348
+ } catch (err) {
349
+ // The SDK throws after an error result as well; the result says more.
350
+ if (!result) result = { type: 'result', subtype: 'error_during_execution', is_error: true, result: err?.message ?? String(err) }
351
+ } finally {
352
+ if (timer) clearTimeout(timer)
353
+ running.delete(key)
354
+ }
355
+ turns += Number(result?.num_turns) || 0
356
+ return { result, sessionId: result?.session_id ?? sessionId, timedOut }
357
+ }
358
+
359
+ const failureOf = (result, timedOut) => {
360
+ if (stopped) return 'stopped'
361
+ if (timedOut) return 'the session ran out of time'
362
+ if (!result) return 'the session ended without a result'
363
+ if (result.subtype === 'error_max_structured_output_retries') return 'no report: the structured output did not fit its schema'
364
+ if (result.is_error || result.subtype !== 'success') return String(result.result ?? result.errors?.join(' ') ?? result.subtype)
365
+ return null
366
+ }
367
+
368
+ return {
369
+ running,
370
+ interrupted,
371
+ get turns() {
372
+ return turns
373
+ },
374
+ get stopped() {
375
+ return stopped
376
+ },
377
+
378
+ /**
379
+ * One decision: no tools, the images in the prompt, one schema. Returns
380
+ * { ok, value } or { ok: false, errors }, and what it cost.
381
+ */
382
+ async decide({ key, role = 'director', task = null, systemPrompt, userText, images = [], schema, jsonSchema = null, pick, timeoutMs, maxTurns = 4 }) {
383
+ if (stopped) return { ok: false, errors: ['stopped'], stopped: true, usd: 0 }
384
+ const book = ledger.session({ key, role, task, kind: 'decision', model: pick.model.id })
385
+ const session = query({
386
+ prompt: promptFor(userText, images),
387
+ options: {
388
+ cwd: projectRoot,
389
+ model: pick.model.id,
390
+ effort: pick.effort,
391
+ ...(pick.model.thinking === 'adaptive' ? { thinking: { type: 'adaptive' } } : {}),
392
+ systemPrompt: { type: 'custom', prompt: systemPrompt, snapshot: false },
393
+ tools: [],
394
+ allowedTools: [],
395
+ mcpServers: {},
396
+ agents: {},
397
+ skills: [],
398
+ settingSources: [],
399
+ strictMcpConfig: true,
400
+ permissionMode: 'default',
401
+ outputFormat: { type: 'json_schema', schema: jsonSchema ?? jsonSchemaOf(schema) },
402
+ maxTurns,
403
+ includePartialMessages: true,
404
+ persistSession: false,
405
+ env: envFor(key),
406
+ canUseTool: NO_TOOLS,
407
+ },
408
+ })
409
+ const { result, timedOut } = await consume(session, { key, book, timeoutMs })
410
+ book.reconcile(result, true)
411
+ const failure = failureOf(result, timedOut)
412
+ if (failure) return { ok: false, errors: [failure], usd: book.spentUsd(), stopped }
413
+ const parsed = parseWith(schema, fitTo(schema, result.structured_output))
414
+ return parsed.ok ? { ok: true, value: parsed.value, usd: book.spentUsd() } : { ok: false, errors: parsed.errors, usd: book.spentUsd(), raw: result.structured_output }
415
+ },
416
+
417
+ /**
418
+ * One role session. `defs` are the nw ToolDefs it gets (its role's and
419
+ * task_check), `ctx` what their handlers get, `guardTask` its write
420
+ * guard, `gate` its task gate, `onWrite` each project file it wrote.
421
+ */
422
+ async roleSession({ key, task, spec, pick, resume = null, prompt, images = [], defs, ctx, guardTask, readOnlyTool, taskGate, onWrite, timeoutMs }) {
423
+ if (stopped) return { failure: 'stopped', sessionId: null, usd: 0, turns: 0, peakPrompt: 0 }
424
+ const book = ledger.session({ key, role: task.role, task: task.id, kind: 'role', model: pick.model.id })
425
+ const deny = (reason) => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } })
426
+ const pre = async (input) => {
427
+ const name = input.tool_name
428
+ const toolInput = input.tool_input ?? {}
429
+ const mine = guardTask(name, toolInput)
430
+ if (!mine.ok) return deny(mine.reason)
431
+ const fenced = guard.check(name, toolInput)
432
+ if (!fenced.ok) return deny(fenced.reason)
433
+ const paid = ledger.gate(name, readOnlyTool(name, toolInput))
434
+ if (!paid.ok) return deny(paid.reason)
435
+ return {}
436
+ }
437
+ // Awaited, so what the director does on a write (a seam pointed at the
438
+ // module just written) is there before the session's next tool.
439
+ const post = async (input) => {
440
+ for (const rel of writtenPaths(projectRoot, input.tool_name, input.tool_input)) await onWrite?.(rel)
441
+ return {}
442
+ }
443
+ const stop = async () => {
444
+ const reason = await taskGate.stopReason()
445
+ return reason ? { decision: 'block', reason } : {}
446
+ }
447
+ const canUseTool = async (toolName, input) => {
448
+ const fenced = guard.check(toolName, input)
449
+ return fenced.ok ? { behavior: 'allow', updatedInput: input } : { behavior: 'deny', message: fenced.reason }
450
+ }
451
+ const byName = new Map(defs.map((d) => [d.name, d]))
452
+ // The tap reads the session's transcript as it grows (the stream does
453
+ // not always carry a call's final usage).
454
+ const tap = createTranscriptTap({ dir: sessionDir(projectRoot), onLine: (line) => line?.type === 'assistant' && book.addUsage(line) })
455
+ if (resume) tap.mark(resume)
456
+ const session = query({
457
+ prompt: promptFor(prompt, images),
458
+ options: {
459
+ cwd: projectRoot,
460
+ model: pick.model.id,
461
+ effort: pick.effort,
462
+ ...(pick.model.thinking === 'adaptive' ? { thinking: { type: 'adaptive' } } : {}),
463
+ systemPrompt: { type: 'custom', prompt: spec.systemPrompt, snapshot: false },
464
+ tools: spec.builtIns,
465
+ allowedTools: ['Glob', 'Grep', 'TodoWrite', 'Skill', 'mcp__nw__*'],
466
+ mcpServers: { nw: createSdkMcpServer({ name: 'nw', version: '0.3.0', instructions: MCP_INSTRUCTIONS, alwaysLoad: true, tools: defs.map((d) => toSdkTool(d, () => ctx)) }) },
467
+ agents: {},
468
+ settingSources: [],
469
+ strictMcpConfig: true,
470
+ permissionMode: 'default',
471
+ ...(withPlugin ? { plugins: [{ type: 'local', path: pluginDir, skipMcpDiscovery: true }], skills: skillsIn(pluginDir, spec.skills) } : { skills: [] }),
472
+ outputFormat: { type: 'json_schema', schema: spec.schema },
473
+ hooks: { PreToolUse: [{ hooks: [pre] }], PostToolUse: [{ hooks: [post] }], Stop: [{ hooks: [stop] }] },
474
+ maxTurns: spec.maxTurns,
475
+ includePartialMessages: true,
476
+ persistSession: true,
477
+ ...(resume ? { resume } : {}),
478
+ env: envFor(key),
479
+ additionalDirectories: [runDir, ...SDK_SOURCES, ...(withPlugin ? [pluginDir] : [])].filter(Boolean),
480
+ canUseTool,
481
+ },
482
+ // The real query ignores this; the scripted fake (scripts/lib/fakeModel.mjs)
483
+ // runs the nw tools through it, exactly as the in-process server would.
484
+ tools: {
485
+ names: [...spec.builtIns, ...defs.map((d) => `mcp__nw__${d.name}`)],
486
+ run: async (name, input) => {
487
+ const def = byName.get(String(name).replace(/^mcp__nw__/, ''))
488
+ return def ? runDef(def, input, ctx) : null
489
+ },
490
+ },
491
+ })
492
+ const { result, sessionId, timedOut } = await consume(session, { key, taskId: task.id, book, tap, timeoutMs })
493
+ await tap.poll().catch(() => {})
494
+ book.reconcile(result, !resume)
495
+ return {
496
+ result,
497
+ sessionId,
498
+ failure: failureOf(result, timedOut),
499
+ structured: result?.structured_output,
500
+ turns: Number(result?.num_turns) || 0,
501
+ usd: book.spentUsd(),
502
+ peakPrompt: book.peakPrompt(),
503
+ }
504
+ },
505
+
506
+ /** Every running session is interrupted, then closed; nothing new starts. */
507
+ async stopAll() {
508
+ stopped = true
509
+ for (const [key, session] of [...running]) {
510
+ interrupted.push(key)
511
+ try {
512
+ await session.interrupt?.()
513
+ } catch {
514
+ // already ending
515
+ }
516
+ try {
517
+ session.close?.()
518
+ } catch {
519
+ // already closed
520
+ }
521
+ }
522
+ },
523
+ }
524
+ }
525
+
526
+ // ---------------------------------------------------------------- one attempt
527
+
528
+ /**
529
+ * @param {object} deps
530
+ * sessions (createSessions), gate (gate.mjs), store, roles, projectRoot,
531
+ * defsByName, ctxFor (task, round) -> the ctx a role session's tools get,
532
+ * readOnlyTool, now, log, limits.
533
+ */
534
+ export function createAttemptRunner({ sessions, gate, store, roles, projectRoot, defsByName, ctxFor, readOnlyTool, now = Date.now, log, limits }) {
535
+ /** task_check for one attempt: the task's tool checks, without the critic.
536
+ * A blockout's cameras come from its report, which does not exist yet when
537
+ * it checks itself, so its task_check takes them as they will be reported. */
538
+ const taskCheckDef = (task, round, attempt, taskGate) => ({
539
+ name: 'task_check',
540
+ description: task.makesCameras
541
+ ? "Runs your task's own acceptance checks now, exactly as the director will judge them (without the critic), and answers PASS or FAIL for each with its evidence and pictures. Give it cameras, the list your report will give ([{ \"id\", \"shot\" }] for every brief camera), so the cameras check shoots them before you report. Run it after your changes and before you finish; fix what fails."
542
+ : "Runs your task's own acceptance checks now, exactly as the director will judge them (without the critic), and answers PASS or FAIL for each with its evidence and pictures. Run it after your changes and before you finish; fix what fails.",
543
+ shape: task.makesCameras
544
+ ? { cameras: z.array(z.object({ id: z.string().min(1).max(40), shot: z.looseObject({}) })).max(12).optional().describe('Every brief camera as the nw_view shot your report will give.') }
545
+ : {},
546
+ readOnly: true,
547
+ verifies: 'check',
548
+ handler: async (args = {}) => {
549
+ const checks = await gate.runChecks(task, round, { writes: [...attempt.writes], ...(Array.isArray(args.cameras) ? { cameras: args.cameras } : {}) })
550
+ await taskGate.recordCheck()
551
+ const images = checks.flatMap((c) => c.evidence?.inline ?? []).slice(0, 6)
552
+ const text = checks.map((c) => `${c.ok ? 'PASS' : 'FAIL'} ${c.id} (${c.kind}): ${c.text}`).join('\n')
553
+ const failed = checks.filter((c) => !c.ok).length
554
+ return { text: `${text}\n${failed ? `${failed} of ${checks.length} failed.` : `All ${checks.length} passed.`}`, images }
555
+ },
556
+ })
557
+
558
+ /**
559
+ * Runs one attempt of `task` on `pick`. `c` carries what the role's
560
+ * session input needs, the previous attempt's outcome and onWrite (told
561
+ * each project file the session writes, as it writes it).
562
+ */
563
+ return async function runAttempt(task, pick, c) {
564
+ const role = roles[task.role]
565
+ const round = (task.attempts?.length ?? 0) + 1
566
+ const key = `task:${task.id}:r${round}`
567
+ const startedAt = now()
568
+ const snapDir = store.abs(path.join('snap', task.id, `r${round}`))
569
+ await snapshot(projectRoot, task.owns ?? [], path.join(snapDir, 'before'), { look: lookMode(task, roles) })
570
+ const attempt = { round, rung: pick.rung, model: pick.model.id, modelName: pick.model.name, effort: pick.effort, sessionId: null, resumed: false, startedAt, endedAt: null, usd: 0, turns: 0, report: null, gate: null, restored: false, writes: new Set(), peakPrompt: 0, why: pick.why }
571
+
572
+ const previous = c.previous ?? null
573
+ const input = {
574
+ brief: c.brief,
575
+ vision: c.vision,
576
+ facts: c.facts ?? null,
577
+ cameras: c.cameras ?? null,
578
+ ready: c.ready ?? [],
579
+ round,
580
+ roundLimit: task.roundLimit,
581
+ previous,
582
+ references: c.references ?? [],
583
+ refImages: c.refImages ?? [],
584
+ declinePaid: !!c.declinePaid,
585
+ // The board's paid lines: a modeller task one names gets the paid tools.
586
+ paid: c.board?.paid ?? [],
587
+ locale: c.locale ?? 'en',
588
+ }
589
+ let spec
590
+ try {
591
+ spec = role.session(task, input)
592
+ } catch (err) {
593
+ log(`[director] ${task.role}.session failed for ${task.id}: ${err?.message ?? err}`)
594
+ spec = null
595
+ }
596
+ const resume = pick.resume && previous?.sessionId ? previous.sessionId : null
597
+ const attemptText = ATTEMPT_PROMPT({ round, limit: task.roundLimit, failures: previous?.failures ?? [], changes: previous?.changes ?? previous?.gate?.critic?.changes ?? [], restored: !!previous?.restored, notes: c.notes ?? [] })
598
+ let prompt
599
+ if (resume) prompt = attemptText
600
+ else if (round > 1) prompt = [spec?.userText ?? '', attemptText, handoffText({ reports: previous?.reports ?? [], diffStat: previous?.diffStat ?? '' })].filter(Boolean).join('\n\n')
601
+ else prompt = [spec?.userText ?? '', c.notes?.length ? `Also asked of you:\n${c.notes.map((n) => `- ${n}`).join('\n')}` : ''].filter(Boolean).join('\n\n')
602
+ attempt.resumed = !!resume
603
+
604
+ const taskGate = await createTaskGate({ projectRoot, owns: task.owns ?? [] })
605
+ const tcheck = taskCheckDef(task, round, attempt, taskGate)
606
+ // A tool the production cannot offer (nw_blender without Blender) is left out.
607
+ const defs = [...(spec?.nwTools ?? []).filter((n) => !(c.dropTools ?? []).includes(n)).map((n) => defsByName.get(n)).filter(Boolean), tcheck]
608
+ const ctx = ctxFor(task, round)
609
+ const out = spec
610
+ ? await sessions.roleSession({
611
+ key,
612
+ task,
613
+ spec: { ...spec, schema: spec.schema ?? jsonSchemaOf(task.role === 'qa' ? QAReport : RoleReport) },
614
+ pick,
615
+ resume,
616
+ prompt,
617
+ images: resume ? [] : spec.images ?? [],
618
+ defs,
619
+ ctx,
620
+ guardTask: writeGuard({ task, board: c.board, roles, projectRoot }),
621
+ readOnlyTool,
622
+ taskGate,
623
+ onWrite: (rel) => {
624
+ attempt.writes.add(rel)
625
+ return c.onWrite?.(rel)
626
+ },
627
+ timeoutMs: (limits?.attemptMinutes ?? 25) * 60_000,
628
+ })
629
+ : { failure: `the ${task.role} role could not build its session`, sessionId: null, usd: 0, turns: 0, peakPrompt: 0 }
630
+ attempt.sessionId = out.sessionId ?? null
631
+ attempt.usd = out.usd
632
+ attempt.turns = out.turns
633
+ attempt.peakPrompt = out.peakPrompt
634
+ if (!out.failure) {
635
+ const reportSchema = task.role === 'qa' ? QAReport : RoleReport
636
+ const parsed = parseWith(reportSchema, fitTo(reportSchema, out.structured))
637
+ if (parsed.ok) attempt.report = parsed.value
638
+ else attempt.failure = `no report: ${parsed.errors.join('; ')}`
639
+ } else attempt.failure = out.failure === 'stopped' ? 'stopped' : `no report: ${out.failure}`
640
+ attempt.endedAt = now()
641
+ return { attempt, key, snapDir, stopped: out.failure === 'stopped' }
642
+ }
643
+ }