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,119 @@
1
+ // What a production records, under .nowhere/production/<id>/ in the project
2
+ // (orchestrator spec 2.12): production.json (the request, the route, the
3
+ // phase, the state, the limits, the approvals, the outcome), the reference
4
+ // facts, the interpretation, the brief, the vision, the board (rewritten on
5
+ // each change), the estimate, the cameras, rounds.jsonl (one line per phase
6
+ // change, card, attempt, gate, escalation and stop), the shots, the
7
+ // thumbnails, the snapshots, the cost and the report. The studio and the
8
+ // runner record the same files, so a production can be read back, resumed
9
+ // and compared across runs. .nowhere/ is read-only for the agent (guard.mjs):
10
+ // only the director's code writes here.
11
+ //
12
+ // Every JSON write goes to a temporary file first and is renamed into
13
+ // place, so a reader (the board in the chat, a resume after a crash) never
14
+ // sees half a file.
15
+
16
+ import { randomBytes } from 'node:crypto'
17
+ import fs from 'node:fs'
18
+ import fsp from 'node:fs/promises'
19
+ import path from 'node:path'
20
+
21
+ export const PRODUCTION_DIR = path.join('.nowhere', 'production')
22
+ const ID = /^p-\d{8}-\d{6}-[0-9a-f]{4}$/
23
+
24
+ const pad = (n) => String(n).padStart(2, '0')
25
+ /** p-<yyyymmdd>-<hhmmss>-<4 hex>, in local time, so ids sort by when they began. */
26
+ export function newProductionId(now = Date.now()) {
27
+ const d = new Date(now)
28
+ return `p-${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}-${randomBytes(2).toString('hex')}`
29
+ }
30
+ export const isProductionId = (id) => ID.test(String(id ?? ''))
31
+
32
+ /** Writes `bytes` at `abs` through a temporary file and a rename. */
33
+ export async function writeAtomic(abs, bytes) {
34
+ await fsp.mkdir(path.dirname(abs), { recursive: true })
35
+ const tmp = `${abs}.${process.pid}.${randomBytes(3).toString('hex')}.tmp`
36
+ await fsp.writeFile(tmp, bytes)
37
+ await fsp.rename(tmp, abs)
38
+ }
39
+
40
+ /**
41
+ * @param {string} projectRoot
42
+ * @param {string} id a production id
43
+ */
44
+ export function openStore(projectRoot, id) {
45
+ if (!isProductionId(id)) throw new Error(`"${id}" is not a production id.`)
46
+ const dir = path.join(projectRoot, PRODUCTION_DIR, id)
47
+ const abs = (rel) => path.join(dir, rel)
48
+ // One write at a time per file, in the order asked: two status changes
49
+ // in quick succession must land in that order.
50
+ const queues = new Map()
51
+ const serial = (rel, fn) => {
52
+ const prev = queues.get(rel) ?? Promise.resolve()
53
+ const next = prev.then(fn, fn)
54
+ queues.set(rel, next.catch(() => {}))
55
+ return next
56
+ }
57
+ return {
58
+ id,
59
+ dir,
60
+ /** A path inside the production folder, project-relative with forward slashes. */
61
+ rel: (r) => path.relative(projectRoot, abs(r)).split(path.sep).join('/'),
62
+ abs,
63
+ writeJson: (rel, value) => serial(rel, () => writeAtomic(abs(rel), `${JSON.stringify(value, null, 2)}\n`)),
64
+ writeText: (rel, text) => serial(rel, () => writeAtomic(abs(rel), String(text))),
65
+ writeBytes: (rel, bytes) => serial(rel, () => writeAtomic(abs(rel), bytes)),
66
+ /** One line of rounds.jsonl. */
67
+ append: (entry) =>
68
+ serial('rounds.jsonl', async () => {
69
+ await fsp.mkdir(dir, { recursive: true })
70
+ await fsp.appendFile(abs('rounds.jsonl'), `${JSON.stringify({ t: Date.now(), ...entry })}\n`)
71
+ }),
72
+ async readJson(rel) {
73
+ try {
74
+ return JSON.parse(await fsp.readFile(abs(rel), 'utf8'))
75
+ } catch {
76
+ return null
77
+ }
78
+ },
79
+ async rounds() {
80
+ try {
81
+ return (await fsp.readFile(abs('rounds.jsonl'), 'utf8'))
82
+ .split('\n')
83
+ .filter((l) => l.trim())
84
+ .map((l) => JSON.parse(l))
85
+ } catch {
86
+ return []
87
+ }
88
+ },
89
+ exists: (rel) => fs.existsSync(abs(rel)),
90
+ /** Waits for every write asked so far. */
91
+ async settle() {
92
+ await Promise.all([...queues.values()])
93
+ },
94
+ }
95
+ }
96
+
97
+ /** A new production's folder and store. */
98
+ export async function createStore(projectRoot, now = Date.now()) {
99
+ let id = newProductionId(now)
100
+ while (fs.existsSync(path.join(projectRoot, PRODUCTION_DIR, id))) id = newProductionId(now)
101
+ await fsp.mkdir(path.join(projectRoot, PRODUCTION_DIR, id), { recursive: true })
102
+ return openStore(projectRoot, id)
103
+ }
104
+
105
+ /** The newest production of a project with its production.json, or null. */
106
+ export async function latestProduction(projectRoot) {
107
+ let names = []
108
+ try {
109
+ names = (await fsp.readdir(path.join(projectRoot, PRODUCTION_DIR))).filter(isProductionId).sort()
110
+ } catch {
111
+ return null
112
+ }
113
+ for (const id of names.reverse()) {
114
+ const store = openStore(projectRoot, id)
115
+ const record = await store.readJson('production.json')
116
+ if (record) return { id, store, record }
117
+ }
118
+ return null
119
+ }
@@ -0,0 +1,110 @@
1
+ // The stop gate of one task: stopGate.mjs's bar ("check after your last
2
+ // change, and leave no probes"), scoped to the files the task owns. The
3
+ // project-wide gate fingerprints every file of the game, so with two roles
4
+ // working at once each would be held back by the other's edits; this one
5
+ // sees only its own. It blocks a session once, when an owned file changed
6
+ // after the task's last task_check or when an owned file carries a DBG or
7
+ // DEBUG marker, and its reason names task_check, the tool that runs the
8
+ // same checks the task is judged by.
9
+
10
+ import { createHash } from 'node:crypto'
11
+ import fsp from 'node:fs/promises'
12
+ import path from 'node:path'
13
+ import { MARKER } from '../stopGate.mjs'
14
+ import { isDirectorFile, matches, relPath } from './board.mjs'
15
+
16
+ const SKIP = new Set(['node_modules', '.git', '.nowhere', 'dist', '.DS_Store'])
17
+ const TEXT = /\.(m?[jt]sx?|c[jt]s|json|py|glsl|wgsl|css|html?)$/i
18
+ const MAX_TEXT = 1_000_000
19
+
20
+ /** Every file under the project that one of `owns` names, project-relative. */
21
+ export async function ownedFiles(projectRoot, owns) {
22
+ const out = []
23
+ const walk = async (rel) => {
24
+ let entries = []
25
+ try {
26
+ entries = await fsp.readdir(path.join(projectRoot, rel), { withFileTypes: true })
27
+ } catch {
28
+ return
29
+ }
30
+ for (const e of entries) {
31
+ if (SKIP.has(e.name)) continue
32
+ const child = rel ? `${rel}/${e.name}` : e.name
33
+ if (e.isDirectory()) await walk(child)
34
+ else if (e.isFile() && owns.some((g) => matches(g, child)) && !isDirectorFile(child)) out.push(child)
35
+ if (out.length > 5000) return
36
+ }
37
+ }
38
+ if (owns.length) await walk('')
39
+ return out.sort()
40
+ }
41
+
42
+ /** sha1 over "path:size:mtime" of the owned files. */
43
+ async function fingerprint(projectRoot, owns) {
44
+ const hash = createHash('sha1')
45
+ for (const rel of await ownedFiles(projectRoot, owns)) {
46
+ try {
47
+ const s = await fsp.stat(path.join(projectRoot, rel))
48
+ hash.update(`${rel}:${s.size}:${s.mtimeMs}\n`)
49
+ } catch {
50
+ // gone between the listing and the stat
51
+ }
52
+ }
53
+ return hash.digest('hex')
54
+ }
55
+
56
+ /** Debug markers in the owned text files, as { file, line, text }. */
57
+ export async function ownedMarkers(projectRoot, owns) {
58
+ const found = []
59
+ for (const rel of await ownedFiles(projectRoot, owns)) {
60
+ if (!TEXT.test(rel)) continue
61
+ let text
62
+ try {
63
+ const abs = path.join(projectRoot, rel)
64
+ if ((await fsp.stat(abs)).size > MAX_TEXT) continue
65
+ text = await fsp.readFile(abs, 'utf8')
66
+ } catch {
67
+ continue
68
+ }
69
+ text.split('\n').forEach((line, i) => {
70
+ if (MARKER.test(line)) found.push({ file: rel, line: i + 1, text: line.trim() })
71
+ })
72
+ }
73
+ return found
74
+ }
75
+
76
+ /**
77
+ * @param {{ projectRoot: string, owns: string[], max?: number }} options
78
+ */
79
+ export async function createTaskGate({ projectRoot, owns, max = 1 }) {
80
+ const globs = owns.map(relPath)
81
+ const start = await fingerprint(projectRoot, globs)
82
+ let checked = null
83
+ let blocks = 0
84
+ return {
85
+ get blocks() {
86
+ return blocks
87
+ },
88
+ /** task_check ran against the owned files as they are now. */
89
+ async recordCheck() {
90
+ checked = await fingerprint(projectRoot, globs)
91
+ },
92
+ /** Whether an owned file changed since the attempt began. */
93
+ async changed() {
94
+ return (await fingerprint(projectRoot, globs)) !== start
95
+ },
96
+ markers: () => ownedMarkers(projectRoot, globs),
97
+ /** The Stop decision for the task's session: a reason, or null. */
98
+ async stopReason() {
99
+ if (blocks >= max) return null
100
+ const now = await fingerprint(projectRoot, globs)
101
+ const items = []
102
+ if (now !== start && checked !== now) items.push('run task_check: your files changed after your last task_check')
103
+ const left = await ownedMarkers(projectRoot, globs)
104
+ if (left.length) items.push(`remove the debug code at ${left.slice(0, 8).map((m) => `${m.file}:${m.line}`).join(', ')}`)
105
+ if (items.length === 0) return null
106
+ blocks++
107
+ return `Before you finish: ${items.join('; ')}. Your task is judged by the same checks task_check runs; then finish with your report.`
108
+ },
109
+ }
110
+ }
@@ -0,0 +1,118 @@
1
+ // What a production costs, by session, model, role and task. Each session
2
+ // keeps its own ledger.mjs ledger, so every call is counted once at its
3
+ // largest usage and priced at its own model's card and prompt tier (the one
4
+ // price source, models.json); this sums them, holds the creator's approval
5
+ // and answers the spend gate over the whole production with ledger.mjs's own
6
+ // lines. Decision sessions are the director's, critic sessions the critic's;
7
+ // paid generation is added with the task and role it was for.
8
+
9
+ import { REMIND_FACTOR, REMIND_PLUS, STOP_FACTOR, STOP_PLUS, UNAPPROVED_STOP, createLedger, promptTokens } from '../ledger.mjs'
10
+ import { PRICING } from '../shared.mjs'
11
+
12
+ const usd = (n) => `$${n.toFixed(2)}`
13
+ const add = (map, key, n) => {
14
+ if (!key) return
15
+ map[key] = (map[key] ?? 0) + n
16
+ }
17
+
18
+ /**
19
+ * @param {{ prices?: Record<string, object> }} [options] every model's price
20
+ * card by id (shared.mjs PRICING).
21
+ */
22
+ export function createTeamLedger({ prices = PRICING } = {}) {
23
+ /** { key, role, task, kind, model, ledger, peakPrompt } */
24
+ const sessions = []
25
+ const generation = []
26
+ let approved = null // the latest approval, for what was left when it was given
27
+ let base = 0 // the spend when it was given
28
+
29
+ const generationUsd = () => generation.reduce((s, g) => s + g.usd, 0)
30
+ const spentUsd = () => sessions.reduce((s, x) => s + x.ledger.spentUsd(), 0) + generationUsd()
31
+
32
+ const team = {
33
+ /** A ledger for one session. kind is 'role' or 'decision'. */
34
+ session({ key, role, task = null, kind = 'role', model }) {
35
+ const ledger = createLedger({ price: prices[model] ?? null, prices, model, askable: false })
36
+ const rec = { key, role, task, kind, model, ledger, peakPrompt: 0 }
37
+ sessions.push(rec)
38
+ const notePeak = (usage) => {
39
+ const p = promptTokens(usage)
40
+ if (p > rec.peakPrompt) rec.peakPrompt = p
41
+ }
42
+ return {
43
+ addUsage(msg) {
44
+ if (msg?.message?.usage) notePeak(msg.message.usage)
45
+ return ledger.addUsage(msg)
46
+ },
47
+ addStreamEvent(msg) {
48
+ if (msg?.event?.type === 'message_start') notePeak(msg.event.message?.usage)
49
+ return ledger.addStreamEvent(msg)
50
+ },
51
+ reconcile: (result, fresh) => ledger.reconcile(result, fresh),
52
+ spentUsd: () => ledger.spentUsd(),
53
+ /** The longest prompt one call of this session sent, in tokens. */
54
+ peakPrompt: () => rec.peakPrompt,
55
+ }
56
+ },
57
+ spentUsd,
58
+ /** What the production may cost in all: the spend at the latest approval plus it. */
59
+ approvedUsd: () => (approved === null ? null : base + approved),
60
+ /** The creator approved a cost card for what is left. */
61
+ approve(totalUsd) {
62
+ const n = Number(totalUsd)
63
+ if (!Number.isFinite(n) || n < 0) return
64
+ approved = n
65
+ base = spentUsd()
66
+ },
67
+ /** A paid generation, tagged with the task and role it was for. */
68
+ addGeneration(amount, what, tag = {}) {
69
+ const n = Number(amount)
70
+ if (!Number.isFinite(n) || n < 0) return
71
+ generation.push({ usd: n, what: String(what ?? ''), task: tag?.task ?? null, role: tag?.role ?? 'director' })
72
+ },
73
+ /** Whether a tool may run now: ledger.mjs's stop line over the whole
74
+ * production. A role cannot ask the creator, so its refusal says to
75
+ * report instead; the director asks before the next attempt. */
76
+ gate(_toolName, readOnly) {
77
+ if (readOnly) return { ok: true }
78
+ const spent = spentUsd()
79
+ const over = approved === null ? spent > UNAPPROVED_STOP : spent - base > approved * STOP_FACTOR + STOP_PLUS
80
+ if (!over) return { ok: true }
81
+ const against = approved === null ? 'and no cost was approved' : `against the approved ${usd(base + approved)}`
82
+ return { ok: false, reason: `Refused: this production has spent ${usd(spent)} ${against}. Change nothing more; finish with your report, and the director asks the creator.` }
83
+ },
84
+ /** Whether the projected total passes the reminder line of the approval
85
+ * (ledger.mjs REMIND_FACTOR and REMIND_PLUS): time for a new cost card. */
86
+ overLine(remainingUsd) {
87
+ const total = team.approvedUsd()
88
+ if (total === null) return false
89
+ return spentUsd() + Math.max(0, Number(remainingUsd) || 0) > total * REMIND_FACTOR + REMIND_PLUS
90
+ },
91
+ /** Where the money went. Generation counts under its role and task, so
92
+ * the role sums are the total. */
93
+ breakdown() {
94
+ const byModel = {}
95
+ const byRole = {}
96
+ const byTask = {}
97
+ const byTaskModel = {}
98
+ for (const s of sessions) {
99
+ const n = s.ledger.spentUsd()
100
+ add(byModel, s.model, n)
101
+ add(byRole, s.kind === 'decision' ? (s.role === 'critic' ? 'critic' : 'director') : s.role, n)
102
+ if (s.task) {
103
+ add(byTask, s.task, n)
104
+ byTaskModel[s.task] ??= {}
105
+ add(byTaskModel[s.task], s.model, n)
106
+ }
107
+ }
108
+ for (const g of generation) {
109
+ add(byRole, g.role ?? 'director', g.usd)
110
+ if (g.task) add(byTask, g.task, g.usd)
111
+ }
112
+ return { total: spentUsd(), byModel, byRole, byTask, byTaskModel, generationUsd: generationUsd(), sessions: sessions.length }
113
+ },
114
+ /** One session's figures, for the attempt record. */
115
+ sessionsOf: (task) => sessions.filter((s) => s.task === task).map((s) => ({ key: s.key, model: s.model, usd: s.ledger.spentUsd(), peakPrompt: s.peakPrompt })),
116
+ }
117
+ return team
118
+ }
@@ -0,0 +1,63 @@
1
+ // Which way a request goes: the fast path (today's single agent, unchanged)
2
+ // or a production (the director and its team). Code decides from the
3
+ // signals depth.mjs already reads, and asks a small model only when they
4
+ // leave it open. Only a message that asks for a team can get one: main and
5
+ // the runner send `team: true`, every older check builds messages without
6
+ // it, so they keep testing today's path; and only Claude runs a team (other
7
+ // vendors keep agent-loop.mjs).
8
+ //
9
+ // A continuation ("continue", the task card's Continue, a short "ok")
10
+ // resumes a production only when the turn it continues was that production
11
+ // (main sends its id as msg.continues) and its board still has a task whose
12
+ // work is not in the game (neither passed nor kept), whatever state it
13
+ // ended in. Anything else it continues is the fast path's: a continuation
14
+ // never starts a new production.
15
+
16
+ import { SIGNALS, isContinuation } from '../depth.mjs'
17
+ import { DONE } from './board.mjs'
18
+ import { TriageOutput } from './contracts.mjs'
19
+ import { TRIAGE_PROMPT, triageText } from './prompts.mjs'
20
+
21
+ /** Whether a production has work a resume would pick up: a task on its
22
+ * board that neither passed nor was kept (one from before the kept status
23
+ * says passed, below the bar). */
24
+ async function workLeft(latest) {
25
+ const board = latest?.board ?? (await Promise.resolve(latest?.store?.readJson?.('board.json')).catch(() => null))
26
+ return Array.isArray(board?.tasks) && board.tasks.some((t) => !DONE.has(t?.status))
27
+ }
28
+
29
+ /**
30
+ * @param {{ msg: object, runtime: string, depth: { effort: string, reason: string }, emptyProject: boolean,
31
+ * latest: { id: string, record: object, store?: object, board?: object } | null, decide?: Function, router?: object, images?: number }} input
32
+ * msg.continues: the production the chat's last turn was, when it was one.
33
+ * @returns {Promise<{ route: 'fast' | 'production' | 'resume', why: string, productionId?: string, asked?: boolean }>}
34
+ */
35
+ export async function triage({ msg, runtime, depth, emptyProject, latest, decide, router, images = 0 }) {
36
+ const text = String(msg?.text ?? '')
37
+ if (msg?.team !== true) return { route: 'fast', why: 'the message did not ask for a team' }
38
+ if (runtime !== 'claude-agent-sdk') return { route: 'fast', why: "a team runs on Claude's models only" }
39
+ if (msg.route === 'fast' || msg.route === 'production') return { route: msg.route, why: `the route was set to ${msg.route}` }
40
+ if (isContinuation(text)) {
41
+ if (latest && msg.continues === latest.id && (await workLeft(latest))) return { route: 'resume', why: `it continues the unfinished production ${latest.id}`, productionId: latest.id }
42
+ return { route: 'fast', why: latest && msg.continues === latest.id ? `it continues the production ${latest.id}, which has nothing left to do` : 'it continues a turn that was not an unfinished production' }
43
+ }
44
+ if (depth?.effort === 'low' || depth?.effort === 'medium') return { route: 'fast', why: `${depth.reason} (${depth.effort})` }
45
+ const build = SIGNALS.BUILD_VERB.test(text) && SIGNALS.BUILD_SCOPE.test(text) && (SIGNALS.NEW.test(text) || emptyProject)
46
+ if (build || depth?.effort === 'max') return { route: 'production', why: build ? 'a new game or world' : `${depth.reason} (max)` }
47
+ if (!decide || !router) return { route: 'fast', why: 'unsure, and no model to ask' }
48
+ try {
49
+ const r = await decide({
50
+ key: 'triage',
51
+ role: 'director',
52
+ systemPrompt: TRIAGE_PROMPT,
53
+ userText: triageText({ text, images, emptyProject, history: msg.history }),
54
+ schema: TriageOutput,
55
+ pick: router.decision('triage'),
56
+ timeoutMs: 120_000,
57
+ })
58
+ if (r.ok) return { route: r.value.route, why: r.value.why, asked: true }
59
+ return { route: 'fast', why: `the triage did not answer (${r.errors?.[0] ?? 'no reason'})`, asked: true }
60
+ } catch (err) {
61
+ return { route: 'fast', why: `the triage failed (${err?.message ?? err})`, asked: true }
62
+ }
63
+ }