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,613 @@
1
+ // The fence around the agent's file tools and Bash. The agent works in the
2
+ // project, its scratch folder for the request, and (read-only) the studio's
3
+ // skills, the SDK's and the schema's sources and guide, the Blender install
4
+ // and the usual system folders. Not the studio's example games: finished
5
+ // games to copy are an answer made before the request. It
6
+ // never writes the project's history (.git), the studio's own files under
7
+ // .nowhere (except the download quarantine), the studio's settings folder or
8
+ // ~/.claude, and never reaches the studio's DevTools ports.
9
+ //
10
+ // The Bash part is a heuristic, not a sandbox: it reads the command line the
11
+ // way a person would (paths, redirections, the usual writing commands) and
12
+ // refuses what it can see going wrong. It was written against what a real
13
+ // run did (a2f5f920 listed the studio's settings folder and curled its
14
+ // DevTools port); a command that hides its paths behind variables it does not
15
+ // expand still gets through. A string run by sh -c or eval is read the same
16
+ // way; a key the creator saved is never printed; a download goes into the
17
+ // quarantine, and nothing in the quarantine is run.
18
+
19
+ import fs from 'node:fs'
20
+ import os from 'node:os'
21
+ import path from 'node:path'
22
+ import { BLOCKED_HOSTS, PLUGIN_DIR, SDK_SOURCES, isInside, sessionDir } from './shared.mjs'
23
+
24
+ /** Read-only system folders: compilers, node, Homebrew and the like. */
25
+ const SYSTEM_READ = ['/usr', '/bin', '/sbin', '/opt/homebrew', '/usr/local', '/System', '/Library/Developer/CommandLineTools']
26
+ /** Devices a shell writes to as a matter of course (2>/dev/null). */
27
+ const DEVICES_WRITE = ['/dev/null', '/dev/stdout', '/dev/stderr', '/dev/tty', '/dev/fd']
28
+ const DEVICES_READ = ['/dev/stdin', '/dev/zero', '/dev/random', '/dev/urandom']
29
+
30
+ export const SECRET_REASON =
31
+ 'Refused: that would print a key the creator saved (or every variable, keys included). Use a key only inside the command that needs it, such as curl -H "Authorization: Bearer $MESHY_API_KEY", and never print it.'
32
+
33
+ export const BLOCKED_REASON =
34
+ 'ArtStation, Pinterest and Behance are for the creator\'s eyes only: their terms forbid feeding their images to AI tools. Ask the creator to describe the reference, or use a CC0 or public-domain source.'
35
+
36
+ /** Which input field carries the path, and what the tool does with it. */
37
+ const FILE_TOOLS = {
38
+ Read: ['file_path', 'read'],
39
+ Write: ['file_path', 'write'],
40
+ Edit: ['file_path', 'write'],
41
+ MultiEdit: ['file_path', 'write'],
42
+ NotebookEdit: ['notebook_path', 'write'],
43
+ Glob: ['path', 'read'],
44
+ Grep: ['path', 'read'],
45
+ }
46
+
47
+ /** Commands that change the system or the creator's accounts. */
48
+ const DENIED_COMMANDS = new Set(['sudo', 'su', 'security', 'osascript', 'launchctl', 'diskutil'])
49
+ /** The screen is seen only through nw_capture_screen, whose card the creator
50
+ * answers: the shell's screencapture would bring up macOS's Screen
51
+ * Recording dialog with no card, or take the screen unasked. */
52
+ const SCREEN_REASON = 'Refused: the screen is seen only with nw_capture_screen, which asks the creator on a card in the chat first. Use nw_capture_screen.'
53
+ const SCREEN_COMMAND_RE = /(?:\$\(|`)\s*(?:\S*\/)?screencapture\b/
54
+ /** git subcommands that change the history or the working tree wholesale:
55
+ * the studio commits each request itself, and holds its own save commits
56
+ * while a request runs, so a checkout or a reset would throw away the
57
+ * creator's work since the last one. */
58
+ const GIT_DENIED = new Set(['commit', 'push', 'pull', 'merge', 'rebase', 'stash', 'restore', 'clean', 'cherry-pick', 'revert', 'am', 'checkout', 'switch', 'reset'])
59
+ /** Words in front of a command that run the command after them. */
60
+ const WRAPPERS = new Set(['env', 'command', 'exec', 'nohup', 'time', 'nice', 'xargs', 'builtin'])
61
+ /** The last argument is where they write. */
62
+ const LAST_ARG_WRITES = new Set(['cp', 'mv', 'ln', 'install', 'rsync'])
63
+ /** Every argument is something they change. */
64
+ const ALL_ARGS_WRITE = new Set(['rm', 'rmdir', 'mkdir', 'touch', 'chmod', 'chown', 'truncate', 'tee'])
65
+ /** Shells that run the string after -c. */
66
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish'])
67
+ /** Commands that run (or open, or make runnable) the file they are given. */
68
+ const RUNS_FILE = new Set([...SHELLS, 'source', '.', 'node', 'deno', 'bun', 'perl', 'ruby', 'php', 'lua', 'open', 'chmod'])
69
+ /** The flags after which an interpreter runs inline code, not a file. */
70
+ const INLINE_CODE = new Set(['-c', '-e', '-p', '-m', '-E', '--eval', '--print'])
71
+ /** Commands that print the whole environment, keys and all, when run bare. */
72
+ const PRINTS_ENV = new Set(['printenv', 'set', 'export', 'declare', 'typeset'])
73
+ /** How deep sh -c inside sh -c may go before it is refused. */
74
+ const MAX_NESTING = 4
75
+
76
+ const URL_RE = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>|;&)`]*/gi
77
+ /** What a remote http(s) URL becomes in the command line the per-command checks read. */
78
+ const URL_MARK = '@@url@@'
79
+ const LOCAL_HOST_RE = /^https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?:[:/?#]|$)/i
80
+ const LOCAL_PORT_RE = /(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]):(\d{2,5})/gi
81
+ const DEVTOOLS_PATH_RE = /\/json\/(?:version|list)\b|devtools\//i
82
+ const SUBSHELL_DENIED_RE = /(?:\$\(|`)\s*(?:sudo|su|security|osascript|launchctl|diskutil|defaults\s+write)\b/
83
+
84
+ // A path counts only when its first part exists at the filesystem root:
85
+ // /Users and /etc are paths, the /a/g of a regular expression in `node -e` is not.
86
+ const rootSegments = new Map()
87
+ function rootExists(segment) {
88
+ if (!rootSegments.has(segment)) rootSegments.set(segment, segment !== '' && fs.existsSync(`/${segment}`))
89
+ return rootSegments.get(segment)
90
+ }
91
+
92
+ /**
93
+ * Splits a command line into words and operators the way a POSIX shell
94
+ * would, closely enough for the checks below: quotes and backslashes are
95
+ * resolved, `;` `&&` `||` `|` `&` `(` `)` `$(` and backticks separate
96
+ * commands, and redirections become their own tokens. The body of a heredoc
97
+ * whose delimiter is quoted (<<'EOF', the usual way to write a file) is file
98
+ * content the shell expands nothing in, so it is skipped rather than read as
99
+ * commands; an unquoted one's body can run $(...), so it is still read.
100
+ */
101
+ export function tokenize(s) {
102
+ const out = []
103
+ let cur = null
104
+ let quoted = false // the word being read had quotes or a backslash
105
+ let heredocOp = null // a << was just read: the next word is its delimiter
106
+ let heredocs = [] // delimiters whose bodies start after the next newline
107
+ const push = () => {
108
+ if (cur !== null) {
109
+ out.push({ t: 'word', v: cur })
110
+ if (heredocOp) {
111
+ // The shell's own rule: any quoting makes the delimiter quoted, and
112
+ // the delimiter is the word with its quotes removed.
113
+ heredocs.push({ delim: cur, quoted, strip: heredocOp === '<<-' })
114
+ heredocOp = null
115
+ }
116
+ }
117
+ cur = null
118
+ quoted = false
119
+ }
120
+ /** Past the bodies of the heredocs started on the line that just ended. */
121
+ const skipBodies = (from) => {
122
+ let at = from
123
+ for (const h of heredocs) {
124
+ while (at < s.length) {
125
+ const nl = s.indexOf('\n', at)
126
+ const line = s.slice(at, nl < 0 ? s.length : nl)
127
+ at = nl < 0 ? s.length : nl + 1
128
+ if ((h.strip ? line.replace(/^\t+/, '') : line) === h.delim) break
129
+ }
130
+ }
131
+ heredocs = []
132
+ return at
133
+ }
134
+ let i = 0
135
+ while (i < s.length) {
136
+ const c = s[i]
137
+ if (c === "'") {
138
+ const j = s.indexOf("'", i + 1)
139
+ const end = j < 0 ? s.length : j
140
+ cur = (cur ?? '') + s.slice(i + 1, end)
141
+ quoted = true
142
+ i = end + 1
143
+ } else if (c === '"') {
144
+ let j = i + 1
145
+ let buf = ''
146
+ while (j < s.length && s[j] !== '"') {
147
+ if (s[j] === '\\' && j + 1 < s.length) {
148
+ buf += s[j + 1]
149
+ j += 2
150
+ } else buf += s[j++]
151
+ }
152
+ cur = (cur ?? '') + buf
153
+ quoted = true
154
+ i = j + 1
155
+ } else if (c === '\\' && i + 1 < s.length) {
156
+ cur = (cur ?? '') + s[i + 1]
157
+ quoted = true
158
+ i += 2
159
+ } else if (/\s/.test(c)) {
160
+ push()
161
+ i++
162
+ if (c === '\n') {
163
+ out.push({ t: 'op', v: ';' })
164
+ if (heredocs.length && heredocs.every((h) => h.quoted)) i = skipBodies(i)
165
+ else heredocs = []
166
+ }
167
+ } else if (c === '>' || c === '<' || (c === '&' && s[i + 1] === '>')) {
168
+ // A redirection; a number right before it is the descriptor, not a word.
169
+ if (cur !== null && /^\d+$/.test(cur)) cur = null
170
+ else push()
171
+ let op = c === '&' ? '>' : c
172
+ i += c === '&' ? 2 : 1
173
+ while (s[i] === '>' || s[i] === '<') op += s[i++]
174
+ if (op === '<<' && s[i] === '-') op += s[i++]
175
+ if (s[i] === '|') i++
176
+ if (s[i] === '&') {
177
+ op += '&'
178
+ i++
179
+ }
180
+ out.push({ t: 'redir', v: op })
181
+ if (op === '<<' || op === '<<-') heredocOp = op
182
+ } else if (c === '$' && s[i + 1] === '(') {
183
+ push()
184
+ out.push({ t: 'op', v: '$(' })
185
+ i += 2
186
+ } else if ('|&;()`'.includes(c)) {
187
+ push()
188
+ let op = c
189
+ if ((c === '|' || c === '&') && s[i + 1] === c) op += s[++i]
190
+ out.push({ t: 'op', v: op })
191
+ i++
192
+ } else {
193
+ cur = (cur ?? '') + c
194
+ i++
195
+ }
196
+ }
197
+ push()
198
+ return out
199
+ }
200
+
201
+ /** The commands in a token list: their words, and the files their
202
+ * redirections write. */
203
+ function commandsOf(tokens) {
204
+ const commands = []
205
+ let words = []
206
+ let writes = []
207
+ const end = () => {
208
+ if (words.length || writes.length) commands.push({ words, writes })
209
+ words = []
210
+ writes = []
211
+ }
212
+ for (let k = 0; k < tokens.length; k++) {
213
+ const tok = tokens[k]
214
+ if (tok.t === 'op') end()
215
+ else if (tok.t === 'redir') {
216
+ const next = tokens[k + 1]
217
+ if (next?.t !== 'word') continue
218
+ k++
219
+ // >&2 duplicates a descriptor and <<EOF names a delimiter: no file.
220
+ if (tok.v.endsWith('&') || tok.v.startsWith('<')) continue
221
+ writes.push(next.v)
222
+ } else words.push(tok.v)
223
+ }
224
+ end()
225
+ return commands
226
+ }
227
+
228
+ // ---------------------------------------------------------------- read-only commands
229
+ // What a big job may run before its cost card is approved, besides the file
230
+ // tools: a command line made only of commands that read (ls, cat, grep, git
231
+ // log and the like) and that writes nowhere but /dev/null. A QA run had
232
+ // "pwd && ls -la && git log --oneline -n 5" refused by the cost gate and
233
+ // worked around it with the file tools (2026-10-20). The path fence (the
234
+ // guard's check) still applies to what they read.
235
+
236
+ /** Programs that only read, with the flags that would make one write or
237
+ * run another program (sort -o, rg --pre, find -exec). A short flag may come
238
+ * bundled with others (sort -ro out, tree -ao out), so those are matched
239
+ * anywhere in a cluster. */
240
+ const READS = new Map([
241
+ ...['ls', 'cat', 'head', 'tail', 'wc', 'grep', 'egrep', 'fgrep', 'pwd', 'echo', 'printf', 'which', 'stat', 'du', 'df', 'cut', 'tr', 'diff', 'cmp', 'basename', 'dirname', 'realpath', 'readlink', 'true', 'false', 'test', '[', 'jq', 'nl', 'column', 'od', 'hexdump', 'strings', 'shasum', 'sha1sum', 'sha256sum', 'md5', 'md5sum', 'cd', 'pushd', 'popd', 'whoami', 'uname', 'type', 'date'].map((p) => [p, null]),
242
+ ['find', /^-(delete|exec|execdir|ok|okdir|fprint|fprint0|fprintf|fls)$/],
243
+ ['sort', /^-[A-Za-z]*o|^--(output|compress-program)/],
244
+ ['tree', /^-[A-Za-z]*[oR]/],
245
+ ['file', /^-[A-Za-z]*C|^--compile/],
246
+ // --pre runs a program on every file it searches.
247
+ ['rg', /^--pre(=|$)/],
248
+ // uniq's second operand is a file it writes; see readOnlyCommand.
249
+ ['uniq', null],
250
+ ])
251
+ /** git subcommands that only read. */
252
+ const GIT_READS = new Set(['status', 'log', 'diff', 'show', 'blame', 'rev-parse', 'ls-files', 'ls-tree', 'describe', 'shortlog', 'grep', 'cat-file', 'rev-list'])
253
+ const QUIET = new Set(['/dev/null', '/dev/stdout', '/dev/stderr'])
254
+ /** A command run inside a word: $(...), `...`, <(...) and >(...). tokenize
255
+ * keeps a double-quoted word whole, so echo "$(touch x)" read as an echo of
256
+ * one word; any of them anywhere on the line makes it not read-only. */
257
+ const RUNS_INSIDE = /\$\(|`|[<>]\(/
258
+ /** What may be set in front of a read-only command: the locale, the time
259
+ * zone, colour and width, and a pager that is cat. Anything else can make
260
+ * the command run a program (GIT_EXTERNAL_DIFF, GIT_CONFIG_*,
261
+ * RIPGREP_CONFIG_PATH, DYLD_INSERT_LIBRARIES). */
262
+ const SAFE_ENV = /^(LC_[A-Z]+|LANG|LANGUAGE|TZ|NO_COLOR|CLICOLOR|TERM|COLUMNS|LINES)=|^(GIT_PAGER|PAGER)=(cat)?$/
263
+
264
+ /** Whether a Bash command line only reads: every command one of READS (or a
265
+ * reading git), no write flag, no redirection into a file, no command run
266
+ * inside a word. */
267
+ export function readOnlyCommand(command) {
268
+ if (typeof command !== 'string' || !command.trim()) return false
269
+ if (RUNS_INSIDE.test(command)) return false
270
+ let commands
271
+ try {
272
+ commands = commandsOf(tokenize(command))
273
+ } catch {
274
+ return false
275
+ }
276
+ if (commands.length === 0) return false
277
+ for (const { words, writes } of commands) {
278
+ if (writes.some((w) => !QUIET.has(w))) return false
279
+ let k = 0
280
+ while (k < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[k])) {
281
+ if (!SAFE_ENV.test(words[k])) return false
282
+ k++
283
+ }
284
+ const program = words[k]
285
+ if (program === undefined) {
286
+ if (k > 0) return false // a bare assignment changes the shell
287
+ continue
288
+ }
289
+ const args = words.slice(k + 1)
290
+ if (program === 'git') {
291
+ let n = 0
292
+ while (n < args.length && args[n].startsWith('-')) {
293
+ // -c and --config-env set any setting, and diff.external or
294
+ // core.fsmonitor is a program git runs.
295
+ if (/^(-c|--config-env|--exec-path=)/.test(args[n])) return false
296
+ n += args[n] === '-C' ? 2 : 1
297
+ }
298
+ if (!GIT_READS.has(args[n]) || args.some((a) => /^--output(=|$)|^--ext-diff$/.test(a))) return false
299
+ // git grep -O<program> (--open-files-in-pager) runs it on what it finds.
300
+ if (args[n] === 'grep' && args.slice(n + 1).some((a) => /^-[A-Za-z]*O|^--open-files-in-pager/.test(a))) return false
301
+ continue
302
+ }
303
+ if (!READS.has(program)) return false
304
+ const writeFlag = READS.get(program)
305
+ if (writeFlag && args.some((a) => writeFlag.test(a))) return false
306
+ if (program === 'uniq') {
307
+ // uniq [-c -d -u -i] [-f n] [-s n] [input [output]]
308
+ const operands = args.filter((a, i) => !(a.startsWith('-') && a !== '-') && !/^-[fsw]$/.test(args[i - 1] ?? ''))
309
+ if (operands.length > 1) return false
310
+ }
311
+ }
312
+ return true
313
+ }
314
+
315
+ /**
316
+ * @param {{ projectRoot: string, runDir: string, readOnly?: string[], deny?: string[], devtoolsPorts?: number[],
317
+ * envFile?: string | null, home?: string, sessionFolder?: string, secretNames?: () => Iterable<string> }} options
318
+ * secretNames: the variables that hold keys (the connectors' and any a key
319
+ * card saved), read at each check so a key saved mid-run counts at once.
320
+ */
321
+ export function createGuard({ projectRoot, runDir, readOnly = [], deny = [], devtoolsPorts = [], envFile = null, home = os.homedir(), sessionFolder, secretNames = () => [] }) {
322
+ // The SDK's own sources and guide too: a run that went to read what the
323
+ // SDK really exports was refused, and guessed (2026-10-20).
324
+ const studioRead = [PLUGIN_DIR, ...SDK_SOURCES]
325
+ const readRoots = [...studioRead, ...readOnly.filter(Boolean), ...SYSTEM_READ, ...DEVICES_READ]
326
+ const denied = deny.filter(Boolean)
327
+ // The SDK saves a long tool output under the project's session folder in
328
+ // ~/.claude and tells the model to read it from there; that one folder is
329
+ // readable even though ~/.claude is not.
330
+ const ownSessions = sessionFolder ?? sessionDir(projectRoot)
331
+ const ports = new Set((devtoolsPorts ?? []).map(Number))
332
+ const nowhereDir = path.join(projectRoot, '.nowhere')
333
+ const quarantine = path.join(nowhereDir, 'quarantine')
334
+ const gitDir = path.join(projectRoot, '.git')
335
+
336
+ const sdkHint = SDK_SOURCES.length ? `, the studio's skills and the SDK's sources and guide (${SDK_SOURCES.join(', ')})` : ", the studio's skills"
337
+ const outside = (p) => `Refused: ${p} is outside the project. Work inside the project, your scratch folder ${runDir} or, read-only${sdkHint}.`
338
+ const no = (reason) => ({ ok: false, reason })
339
+ const OK = { ok: true }
340
+
341
+ /** 'write', 'read', or a refusal, for one path (absolute, or relative to the project root). */
342
+ function access(target) {
343
+ const abs = path.resolve(projectRoot, target)
344
+ if (envFile && isInside(envFile, abs)) return { deny: outside(abs) }
345
+ if (isInside(gitDir, abs)) {
346
+ return { deny: `Refused: ${abs} is the project's history, which the studio keeps and commits itself. Read it with git log, git diff or git show instead.` }
347
+ }
348
+ for (const d of denied) {
349
+ if (!isInside(d, abs)) continue
350
+ if (isInside(ownSessions, abs)) return { can: 'read' }
351
+ return { deny: outside(abs) }
352
+ }
353
+ if (isInside(projectRoot, abs)) {
354
+ if (isInside(nowhereDir, abs) && !isInside(quarantine, abs)) return { can: 'read', studio: true }
355
+ return { can: 'write' }
356
+ }
357
+ if (isInside(runDir, abs) || DEVICES_WRITE.some((d) => isInside(d, abs))) return { can: 'write' }
358
+ if (readRoots.some((r) => isInside(r, abs)) || isInside(ownSessions, abs)) return { can: 'read' }
359
+ return { deny: outside(abs) }
360
+ }
361
+
362
+ function canRead(target) {
363
+ const a = access(target)
364
+ return a.deny ? no(a.deny) : OK
365
+ }
366
+
367
+ function canWrite(target) {
368
+ const a = access(target)
369
+ if (a.deny) return no(a.deny)
370
+ if (a.can === 'write') return OK
371
+ const abs = path.resolve(projectRoot, target)
372
+ if (a.studio) return no(`Refused: ${abs} belongs to the studio. Of .nowhere, only .nowhere/quarantine is yours to write; reading the rest is fine.`)
373
+ return no(`Refused: ${abs} is read-only for you. Write inside the project or your scratch folder ${runDir}.`)
374
+ }
375
+
376
+ const expand = (cmd) =>
377
+ cmd
378
+ .replace(/\$\{HOME\}|\$HOME\b/g, home)
379
+ .replace(/\$\{TMPDIR\}|\$TMPDIR\b/g, os.tmpdir())
380
+ .replace(/(^|[\s"'=:(])~(?=\/|$|[\s"')])/g, (_m, pre) => pre + home)
381
+
382
+ /** Absolute paths in a command, quoted ones whole (they may hold spaces). */
383
+ function absolutePaths(cmd) {
384
+ const found = []
385
+ const rest = cmd.replace(/(["'])(\/[^"'\n]*)\1/g, (m, _q, p) => {
386
+ found.push(p)
387
+ return ' '
388
+ })
389
+ for (const m of rest.matchAll(/(?:^|[\s"'=(:,<>|;&])(\/[^\s"'|;&)<>,]+)/g)) found.push(m[1])
390
+ return found.filter((p) => rootExists(p.split('/')[1] ?? ''))
391
+ }
392
+
393
+ const climbs = (word) => /(^|[/\\])\.\.([/\\]|$)/.test(word)
394
+
395
+ function checkGit(args) {
396
+ let k = 0
397
+ while (k < args.length && args[k].startsWith('-')) k += args[k] === '-C' || args[k] === '-c' ? 2 : 1
398
+ const sub = args[k]
399
+ if (!GIT_DENIED.has(sub)) return OK
400
+ return no(`Refused: git ${sub} changes the project's history or files wholesale, and the studio commits each request itself. Read-only git (status, log, diff, show, blame) is fine; to undo your own edit, edit the file back.`)
401
+ }
402
+
403
+ const inQuarantine = (abs) => isInside(quarantine, abs)
404
+ const downloadPlace = (abs) => isInside(quarantine, abs) || isInside(runDir, abs)
405
+ const RAN_DOWNLOAD = no('Refused: that runs a file from .nowhere/quarantine. Downloads are data to check and use, never code to run.')
406
+ const DOWNLOAD_ONLY_THERE = no(
407
+ `Refused: a download goes into .nowhere/quarantine/ (or your scratch folder ${runDir}), where it is checked. Move it into the project with nw_take_download afterwards.`,
408
+ )
409
+
410
+ /** Where a curl or wget with a remote URL saves what it fetches; '-' and none are stdout. */
411
+ function downloadTargets(name, args, cwd) {
412
+ const out = []
413
+ let remoteName = false
414
+ let dir = null
415
+ for (let n = 0; n < args.length; n++) {
416
+ const a = args[n]
417
+ if (name === 'curl') {
418
+ if (a === '-O' || a === '--remote-name' || a === '--remote-name-all' || a === '-J' || a === '--remote-header-name') remoteName = true
419
+ else if ((a === '-o' || a === '--output') && args[n + 1]) out.push(args[++n])
420
+ else if (a.startsWith('--output=')) out.push(a.slice('--output='.length))
421
+ else if (a === '--output-dir' && args[n + 1]) dir = args[++n]
422
+ else if (/^-[A-Za-z]+$/.test(a) && a.length > 2) {
423
+ // Short flags run together: -sLO, -sLo file.
424
+ if (a.includes('O')) remoteName = true
425
+ if (a.endsWith('o') && args[n + 1]) out.push(args[++n])
426
+ }
427
+ } else {
428
+ if ((a === '-O' || a === '--output-document') && args[n + 1]) out.push(args[++n])
429
+ else if (a.startsWith('--output-document=')) out.push(a.slice('--output-document='.length))
430
+ else if ((a === '-P' || a === '--directory-prefix') && args[n + 1]) dir = args[++n]
431
+ else if (a.startsWith('--directory-prefix=')) dir = a.slice('--directory-prefix='.length)
432
+ else if (/^-[A-Za-z]*O-?$/.test(a) && a.length > 2) {
433
+ if (a.endsWith('-')) out.push('-')
434
+ else if (args[n + 1]) out.push(args[++n])
435
+ }
436
+ }
437
+ }
438
+ // wget saves under the URL's own name unless told otherwise; curl only with -O.
439
+ if (remoteName || (name === 'wget' && out.length === 0)) out.push(dir ?? '.')
440
+ return out.filter((t) => t !== '-').map((t) => path.resolve(cwd, t))
441
+ }
442
+
443
+ /** The commands of one command line, from `startCwd`; sh -c and eval strings recurse. */
444
+ function checkCommands(line, startCwd, depth) {
445
+ if (depth > MAX_NESTING) return no('Refused: shells inside shells this deep cannot be checked. Run the commands directly.')
446
+ const secrets = [...secretNames()].filter((n) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(n))
447
+ const expandsSecret = (word) => secrets.some((n) => new RegExp(`\\$\\{?!?${n}\\b`).test(word))
448
+ // Relative paths resolve from where the command line has cd'd to.
449
+ let cwd = startCwd
450
+ for (const { words, writes } of commandsOf(tokenize(line))) {
451
+ // Leading assignments and wrappers (env, xargs, ...) run the command after them.
452
+ let k = 0
453
+ while (k < words.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[k]) || WRAPPERS.has(words[k]) || (k > 0 && WRAPPERS.has(words[k - 1]) && words[k].startsWith('-')))) k++
454
+ const program = words[k] ?? ''
455
+ const name = path.basename(program)
456
+ const args = words.slice(k + 1)
457
+ if (DENIED_COMMANDS.has(name) || (name === 'defaults' && args[0] === 'write')) {
458
+ return no(`Refused: ${name} changes the system or the creator's accounts, which the agent never does.`)
459
+ }
460
+ if (name === 'screencapture') return no(SCREEN_REASON)
461
+ if (name === 'rm' && args.some((a) => a === '/' || a === '/*' || a === home || a === `${home}/`)) {
462
+ return no('Refused: that would delete the whole disk or home folder.')
463
+ }
464
+ if (name === 'git') {
465
+ const r = checkGit(args)
466
+ if (!r.ok) return r
467
+ }
468
+ // The environment holds the creator's keys: never printed whole, and a
469
+ // key never echoed.
470
+ const bareEnv = name === '' && words.slice(0, k).some((w) => path.basename(w) === 'env')
471
+ const printsEnv =
472
+ name === 'printenv' ||
473
+ (name === 'set' && args.length === 0) ||
474
+ (name === 'export' && args.every((a) => a.startsWith('-'))) ||
475
+ ((name === 'declare' || name === 'typeset') && args.every((a) => a.startsWith('-')))
476
+ if (bareEnv || (PRINTS_ENV.has(name) && printsEnv)) return no(SECRET_REASON)
477
+ if ((name === 'echo' || name === 'printf' || name === 'print') && args.some(expandsSecret)) return no(SECRET_REASON)
478
+ if (name === 'cd' || name === 'pushd') {
479
+ const to = args.find((a) => !a.startsWith('-'))
480
+ const next = to === undefined || to === '~' ? home : path.resolve(cwd, to)
481
+ const r = canRead(next)
482
+ if (!r.ok) return r
483
+ cwd = next
484
+ continue
485
+ }
486
+ // A shell started on a string, and eval: the same checks on what they run.
487
+ if (SHELLS.has(name)) {
488
+ const flag = args.findIndex((a) => /^-[A-Za-z]*c[A-Za-z]*$/.test(a))
489
+ const inner = flag >= 0 ? args.slice(flag + 1).find((a) => !a.startsWith('-')) : undefined
490
+ if (inner !== undefined) {
491
+ const r = checkCommands(inner, cwd, depth + 1)
492
+ if (!r.ok) return r
493
+ }
494
+ }
495
+ if (name === 'eval' && args.length) {
496
+ const r = checkCommands(args.join(' '), cwd, depth + 1)
497
+ if (!r.ok) return r
498
+ }
499
+ // Nothing downloaded is run: not as the program, not as the script an
500
+ // interpreter is given, not opened, not made executable.
501
+ if (program.includes('/') && inQuarantine(path.resolve(cwd, program))) return RAN_DOWNLOAD
502
+ if (RUNS_FILE.has(name) || /^python[\d.]*$/.test(name)) {
503
+ const files = []
504
+ if (name === 'chmod' || name === 'open') files.push(...args.filter((a) => !a.startsWith('-')))
505
+ else {
506
+ for (const a of args) {
507
+ if (INLINE_CODE.has(a)) break
508
+ if (a.startsWith('-')) continue
509
+ files.push(a)
510
+ break
511
+ }
512
+ }
513
+ if (files.some((f) => inQuarantine(path.resolve(cwd, f)))) return RAN_DOWNLOAD
514
+ }
515
+ // A relative path that climbs out of the project is outside it, and a
516
+ // word that is there on disk is checked as what it is (a link to / is
517
+ // /). An option's value is not (--exclude-dir=.git names .git, it does
518
+ // not read it).
519
+ for (const word of words) {
520
+ for (const part of [word, ...word.split('=').slice(1)]) {
521
+ if (!part || path.isAbsolute(part) || part.includes(URL_MARK)) continue
522
+ const at = path.resolve(cwd, part)
523
+ if (!climbs(part) && (part !== word || word.startsWith('-') || !fs.existsSync(at))) continue
524
+ const r = canRead(at)
525
+ if (!r.ok) return r
526
+ }
527
+ }
528
+ // A link, a copy or a move reaches whatever its arguments name, the bare / included.
529
+ if (LAST_ARG_WRITES.has(name)) {
530
+ for (const a of args) {
531
+ if (a.startsWith('-') || a.includes(URL_MARK)) continue
532
+ const r = canRead(path.resolve(cwd, a))
533
+ if (!r.ok) return r
534
+ }
535
+ }
536
+ // Where it writes: redirections, -o/--output/of=, tee, and the
537
+ // arguments of the commands that write their arguments.
538
+ const targets = [...writes]
539
+ args.forEach((a, n) => {
540
+ if ((a === '-o' || a === '--output') && args[n + 1]) targets.push(args[n + 1])
541
+ else if (a.startsWith('--output=')) targets.push(a.slice('--output='.length))
542
+ else if (a.startsWith('of=')) targets.push(a.slice(3))
543
+ })
544
+ const plain = args.filter((a) => !a.startsWith('-'))
545
+ if (LAST_ARG_WRITES.has(name) && plain.length >= 2) targets.push(plain[plain.length - 1])
546
+ if (ALL_ARGS_WRITE.has(name)) targets.push(...plain)
547
+ for (const t of targets) {
548
+ if (!t || t === '-') continue
549
+ const r = canWrite(path.resolve(cwd, t))
550
+ if (!r.ok) return r
551
+ }
552
+ // A fetch from the web saves only into the quarantine or the scratch folder.
553
+ if ((name === 'curl' || name === 'wget') && args.some((a) => a.includes(URL_MARK))) {
554
+ const saved = [...downloadTargets(name, args, cwd), ...writes.filter((t) => t && t !== '-').map((t) => path.resolve(cwd, t))]
555
+ if (saved.some((t) => !downloadPlace(t))) return DOWNLOAD_ONLY_THERE
556
+ }
557
+ }
558
+ return OK
559
+ }
560
+
561
+ function checkBash(raw) {
562
+ if (typeof raw !== 'string' || !raw.trim()) return OK
563
+ const cmd = expand(raw)
564
+ if (BLOCKED_HOSTS.test(cmd)) return no(BLOCKED_REASON)
565
+ for (const m of cmd.matchAll(LOCAL_PORT_RE)) {
566
+ if (ports.has(Number(m[1]))) return no(`Refused: port ${m[1]} on this computer is the studio's own debugging port.`)
567
+ }
568
+ if (DEVTOOLS_PATH_RE.test(cmd)) return no('Refused: the DevTools endpoints of this computer are the studio\'s own.')
569
+ if (SUBSHELL_DENIED_RE.test(cmd)) return no('Refused: that command changes the system or the creator\'s accounts, which the agent never does.')
570
+ if (SCREEN_COMMAND_RE.test(cmd)) return no(SCREEN_REASON)
571
+
572
+ // URLs out first; a file:// one is a path like any other, and a remote
573
+ // http(s) one leaves a mark, for the download rule.
574
+ const urlPaths = []
575
+ const bare = cmd.replace(URL_RE, (url) => {
576
+ if (/^file:\/\//i.test(url)) urlPaths.push(decodeURIComponent(url.replace(/^file:\/\/(localhost)?/i, '')))
577
+ return /^https?:\/\//i.test(url) && !LOCAL_HOST_RE.test(url) ? ` ${URL_MARK} ` : ' '
578
+ })
579
+ for (const p of [...urlPaths, ...absolutePaths(bare)]) {
580
+ const r = canRead(p)
581
+ if (!r.ok) return r
582
+ }
583
+ return checkCommands(bare, projectRoot, 0)
584
+ }
585
+
586
+ function checkFileTool(spec, input) {
587
+ const [field, mode] = spec
588
+ const value = input?.[field]
589
+ if (typeof value === 'string' && value) {
590
+ const r = mode === 'write' ? canWrite(value) : canRead(value)
591
+ if (!r.ok) return r
592
+ }
593
+ // An absolute Glob pattern reaches as far as its fixed part.
594
+ if (typeof input?.pattern === 'string' && input.pattern.startsWith('/') && spec === FILE_TOOLS.Glob) {
595
+ const fixed = input.pattern.split(/[*?[{]/)[0]
596
+ return canRead(fixed.endsWith('/') ? fixed : path.dirname(fixed))
597
+ }
598
+ return OK
599
+ }
600
+
601
+ /** @returns {{ ok: true } | { ok: false, reason: string }} */
602
+ function check(toolName, input) {
603
+ const name = String(toolName ?? '').replace(/^mcp__nw__/, '')
604
+ if (name === 'Bash') return checkBash(input?.command)
605
+ if (FILE_TOOLS[name]) return checkFileTool(FILE_TOOLS[name], input)
606
+ if (name === 'WebFetch' || name === 'browser_navigate' || name === 'browser_tabs') {
607
+ if (typeof input?.url === 'string' && BLOCKED_HOSTS.test(input.url)) return no(BLOCKED_REASON)
608
+ }
609
+ return OK
610
+ }
611
+
612
+ return { check, canRead, canWrite }
613
+ }