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.
- package/README.md +151 -2
- package/bin/nowhere.mjs +352 -0
- package/lib/account.mjs +57 -0
- package/lib/agentModules.mjs +57 -0
- package/lib/devServer.mjs +351 -0
- package/lib/headless.mjs +231 -0
- package/lib/headlessPreview.mjs +212 -0
- package/lib/keys.mjs +517 -0
- package/lib/make.mjs +855 -0
- package/lib/mcp.mjs +537 -0
- package/lib/open.mjs +22 -0
- package/lib/preview.mjs +87 -0
- package/lib/previewRpc.mjs +134 -0
- package/lib/project.mjs +359 -0
- package/lib/publishFlow.mjs +90 -0
- package/lib/resources.mjs +50 -0
- package/lib/rules.mjs +60 -0
- package/lib/scaffold.mjs +42 -0
- package/lib/setup.mjs +59 -0
- package/lib/tools.mjs +668 -0
- package/package.json +51 -4
- package/template/game.config.json +9 -0
- package/template/scene.json +4 -0
- package/template/src/main.ts +11 -0
- package/vendor/DOCS.md +447 -0
- package/vendor/agent/appRun.mjs +520 -0
- package/vendor/agent/assets/brief.mjs +242 -0
- package/vendor/agent/assets/collider.mjs +531 -0
- package/vendor/agent/assets/environments/index.mjs +12 -0
- package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
- package/vendor/agent/assets/fetch.mjs +168 -0
- package/vendor/agent/assets/footprint.mjs +13 -0
- package/vendor/agent/assets/gltf.mjs +547 -0
- package/vendor/agent/assets/hdr.mjs +269 -0
- package/vendor/agent/assets/imageOps.mjs +171 -0
- package/vendor/agent/assets/images/codex.mjs +307 -0
- package/vendor/agent/assets/images/fal.mjs +75 -0
- package/vendor/agent/assets/images/gemini.mjs +84 -0
- package/vendor/agent/assets/images/index.mjs +25 -0
- package/vendor/agent/assets/images/openai.mjs +75 -0
- package/vendor/agent/assets/images/stability.mjs +71 -0
- package/vendor/agent/assets/images/views.mjs +31 -0
- package/vendor/agent/assets/import.mjs +1352 -0
- package/vendor/agent/assets/inspect.mjs +465 -0
- package/vendor/agent/assets/jobs.mjs +196 -0
- package/vendor/agent/assets/ktx2.mjs +290 -0
- package/vendor/agent/assets/ledger.mjs +466 -0
- package/vendor/agent/assets/net.mjs +254 -0
- package/vendor/agent/assets/prices.json +39 -0
- package/vendor/agent/assets/providers/fal.mjs +115 -0
- package/vendor/agent/assets/providers/index.mjs +22 -0
- package/vendor/agent/assets/providers/meshy.mjs +119 -0
- package/vendor/agent/assets/providers/tripo.mjs +188 -0
- package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
- package/vendor/agent/assets/sources/index.mjs +23 -0
- package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
- package/vendor/agent/assets/sources/polypizza.mjs +121 -0
- package/vendor/agent/assets/splat.mjs +631 -0
- package/vendor/agent/assets/targets.mjs +122 -0
- package/vendor/agent/assets/tile.mjs +261 -0
- package/vendor/agent/assets/unzip.mjs +180 -0
- package/vendor/agent/blender/cleanup.py +360 -0
- package/vendor/agent/blender/convert.py +167 -0
- package/vendor/agent/blender/find.mjs +192 -0
- package/vendor/agent/blender/nw_export.py +104 -0
- package/vendor/agent/blender/nw_rubric.py +426 -0
- package/vendor/agent/blender/run.mjs +193 -0
- package/vendor/agent/blender/runner.py +252 -0
- package/vendor/agent/blender/sheet.py +743 -0
- package/vendor/agent/depth.mjs +134 -0
- package/vendor/agent/director/board.mjs +451 -0
- package/vendor/agent/director/contracts.mjs +663 -0
- package/vendor/agent/director/director.mjs +2365 -0
- package/vendor/agent/director/estimate.mjs +200 -0
- package/vendor/agent/director/gate.mjs +802 -0
- package/vendor/agent/director/limits.json +16 -0
- package/vendor/agent/director/methods.mjs +457 -0
- package/vendor/agent/director/policy.json +33 -0
- package/vendor/agent/director/prompts.mjs +244 -0
- package/vendor/agent/director/reading.mjs +341 -0
- package/vendor/agent/director/router.mjs +184 -0
- package/vendor/agent/director/seams.mjs +243 -0
- package/vendor/agent/director/session.mjs +643 -0
- package/vendor/agent/director/store.mjs +119 -0
- package/vendor/agent/director/taskGate.mjs +110 -0
- package/vendor/agent/director/teamLedger.mjs +118 -0
- package/vendor/agent/director/triage.mjs +63 -0
- package/vendor/agent/downloads.cjs +363 -0
- package/vendor/agent/flow.mjs +78 -0
- package/vendor/agent/guard.mjs +613 -0
- package/vendor/agent/host.mjs +1736 -0
- package/vendor/agent/language.mjs +58 -0
- package/vendor/agent/ledger.mjs +360 -0
- package/vendor/agent/locale.cjs +186 -0
- package/vendor/agent/loop/capacity.mjs +74 -0
- package/vendor/agent/loop/compose.mjs +127 -0
- package/vendor/agent/loop/gate.mjs +205 -0
- package/vendor/agent/loop/judge.mjs +189 -0
- package/vendor/agent/loop/levels.mjs +273 -0
- package/vendor/agent/loop/state.mjs +358 -0
- package/vendor/agent/notes.cjs +278 -0
- package/vendor/agent/pace.mjs +258 -0
- package/vendor/agent/panels.mjs +431 -0
- package/vendor/agent/prompt.mjs +342 -0
- package/vendor/agent/reference/board.mjs +410 -0
- package/vendor/agent/reference/compose.mjs +364 -0
- package/vendor/agent/reference/decode.mjs +56 -0
- package/vendor/agent/reference/facts.mjs +1874 -0
- package/vendor/agent/reference/png.mjs +107 -0
- package/vendor/agent/reference/records.mjs +63 -0
- package/vendor/agent/reference/web.mjs +252 -0
- package/vendor/agent/roles/artist.mjs +69 -0
- package/vendor/agent/roles/builder.mjs +79 -0
- package/vendor/agent/roles/checks.mjs +223 -0
- package/vendor/agent/roles/common.mjs +188 -0
- package/vendor/agent/roles/critic.mjs +171 -0
- package/vendor/agent/roles/index.mjs +39 -0
- package/vendor/agent/roles/modeller.mjs +142 -0
- package/vendor/agent/roles/qa.mjs +58 -0
- package/vendor/agent/roles/rubrics.mjs +79 -0
- package/vendor/agent/roles/sound.mjs +69 -0
- package/vendor/agent/rounds.cjs +333 -0
- package/vendor/agent/shared.mjs +284 -0
- package/vendor/agent/stopGate.mjs +574 -0
- package/vendor/agent/subagents.mjs +129 -0
- package/vendor/agent/tools/assets.mjs +499 -0
- package/vendor/agent/tools/blender.mjs +754 -0
- package/vendor/agent/tools/cards.mjs +479 -0
- package/vendor/agent/tools/choices.mjs +479 -0
- package/vendor/agent/tools/compose.mjs +74 -0
- package/vendor/agent/tools/environment.mjs +488 -0
- package/vendor/agent/tools/eyes.mjs +733 -0
- package/vendor/agent/tools/generate.mjs +338 -0
- package/vendor/agent/tools/guide.mjs +46 -0
- package/vendor/agent/tools/harness.mjs +193 -0
- package/vendor/agent/tools/image.mjs +643 -0
- package/vendor/agent/tools/index.mjs +162 -0
- package/vendor/agent/tools/look.mjs +578 -0
- package/vendor/agent/tools/loop.mjs +858 -0
- package/vendor/agent/tools/others.mjs +123 -0
- package/vendor/agent/tools/pictures.mjs +535 -0
- package/vendor/agent/tools/reference.mjs +366 -0
- package/vendor/agent/transcripts.mjs +118 -0
- package/vendor/agent-loop.mjs +602 -0
- package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
- package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
- package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
- package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
- package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
- package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
- package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
- package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
- package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
- package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
- package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
- package/vendor/auth.cjs +570 -0
- package/vendor/build.cjs +953 -0
- package/vendor/catalog.json +455 -0
- package/vendor/connectors.cjs +688 -0
- package/vendor/eyes.mjs +733 -0
- package/vendor/gameExports.json +1390 -0
- package/vendor/git.cjs +222 -0
- package/vendor/models.json +57 -0
- package/vendor/publish.cjs +1018 -0
- package/vendor/refBoard.cjs +301 -0
- package/vendor/schema/dist/assets.d.ts +335 -0
- package/vendor/schema/dist/assets.js +439 -0
- package/vendor/schema/dist/brief.d.ts +357 -0
- package/vendor/schema/dist/brief.js +302 -0
- package/vendor/schema/dist/common.d.ts +9 -0
- package/vendor/schema/dist/common.js +13 -0
- package/vendor/schema/dist/config.d.ts +406 -0
- package/vendor/schema/dist/config.js +355 -0
- package/vendor/schema/dist/contract.d.ts +599 -0
- package/vendor/schema/dist/contract.js +1146 -0
- package/vendor/schema/dist/index.d.ts +14 -0
- package/vendor/schema/dist/index.js +21 -0
- package/vendor/schema/dist/look.d.ts +463 -0
- package/vendor/schema/dist/look.js +681 -0
- package/vendor/schema/dist/lookStats.d.ts +230 -0
- package/vendor/schema/dist/lookStats.js +768 -0
- package/vendor/schema/dist/pilot.d.ts +32 -0
- package/vendor/schema/dist/pilot.js +44 -0
- package/vendor/schema/dist/publish.d.ts +214 -0
- package/vendor/schema/dist/publish.js +291 -0
- package/vendor/schema/dist/scene.d.ts +75 -0
- package/vendor/schema/dist/scene.js +120 -0
- package/vendor/schema/dist/skyLight.d.ts +141 -0
- package/vendor/schema/dist/skyLight.js +436 -0
- package/vendor/schema/dist/style.d.ts +131 -0
- package/vendor/schema/dist/style.js +155 -0
- package/vendor/schema/package.json +1 -0
- package/vendor/selectionPrompt.mjs +51 -0
- package/vendor/useTools.mjs +195 -0
- package/vendor/userMessage.mjs +26 -0
- package/web-dist/assets/GaussianSplatUtils-CB77cP9U.js +1 -0
- package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
- package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
- package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
- package/web-dist/assets/index-CcjyyQco.css +1 -0
- package/web-dist/assets/index-DMyJcoZJ.js +693 -0
- package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
- package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
- package/web-dist/index.html +34 -0
|
@@ -0,0 +1,1736 @@
|
|
|
1
|
+
// The build agent's run logic, apart from the process it runs in, so a check
|
|
2
|
+
// script can drive it with a stand-in API and a stub rpc (agent-host.mjs is
|
|
3
|
+
// the thin entry that wires it to the main process).
|
|
4
|
+
//
|
|
5
|
+
// One request, in order: its two languages (the creator's, for the agent's
|
|
6
|
+
// chat replies, and the screen's, the computer's own, for every card and
|
|
7
|
+
// everything else on screen) and the request's depth, fitted to the model; a
|
|
8
|
+
// scratch folder; the reference pictures written into the project; a cost
|
|
9
|
+
// ledger, a stop gate, a guard, a pace and a watch on the language of the
|
|
10
|
+
// replies; then Claude through the Agent SDK, or any other vendor
|
|
11
|
+
// through agent-loop.mjs, with the same tools, hooks and events.
|
|
12
|
+
// A request that fails after changing files gets one short cleanup turn, and
|
|
13
|
+
// the chat is told it is unfinished.
|
|
14
|
+
//
|
|
15
|
+
// A message that asks for a team (main and the runner send `team: true`) is
|
|
16
|
+
// triaged first (director/triage.mjs): a new game or a large rework goes to a
|
|
17
|
+
// production (director/director.mjs, its roles and its gates), everything
|
|
18
|
+
// else, and every message without `team`, takes the path above unchanged.
|
|
19
|
+
//
|
|
20
|
+
// Messages out: started, text, tool, tool-result, cost, cleanup, done, error
|
|
21
|
+
// (the fields are in the phase 1 spec, 2.6), a production's board, and rpc
|
|
22
|
+
// calls through `rpc`.
|
|
23
|
+
|
|
24
|
+
import { createSdkMcpServer, query } from '@anthropic-ai/claude-agent-sdk'
|
|
25
|
+
import { createHash } from 'node:crypto'
|
|
26
|
+
import fs from 'node:fs'
|
|
27
|
+
import fsp from 'node:fs/promises'
|
|
28
|
+
import os from 'node:os'
|
|
29
|
+
import path from 'node:path'
|
|
30
|
+
import { runLoop } from '../agent-loop.mjs'
|
|
31
|
+
import refBoard from '../refBoard.cjs'
|
|
32
|
+
import { describeSelection } from '../selectionPrompt.mjs'
|
|
33
|
+
import { promptFor } from '../userMessage.mjs'
|
|
34
|
+
import { EFFORTS, depthFor, fitDepth, isContinuation } from './depth.mjs'
|
|
35
|
+
import { createDirector } from './director/director.mjs'
|
|
36
|
+
import { createRouter } from './director/router.mjs'
|
|
37
|
+
import { createSessions } from './director/session.mjs'
|
|
38
|
+
import { latestProduction } from './director/store.mjs'
|
|
39
|
+
import { createTeamLedger } from './director/teamLedger.mjs'
|
|
40
|
+
import { triage } from './director/triage.mjs'
|
|
41
|
+
import { BLOCKED_REASON, createGuard, readOnlyCommand } from './guard.mjs'
|
|
42
|
+
import { createLanguageWatch } from './language.mjs'
|
|
43
|
+
import { BIG_REASON, READ_ONLY_TOOLS, createLedger } from './ledger.mjs'
|
|
44
|
+
import { createPace } from './pace.mjs'
|
|
45
|
+
import { CLEANUP_PROMPT, OTHER_VENDOR_NOTE, PROMPT_HASH, SYSTEM_PROMPT, studioContext } from './prompt.mjs'
|
|
46
|
+
import {
|
|
47
|
+
BLOCKED_HOSTS,
|
|
48
|
+
PAID_CATEGORIES,
|
|
49
|
+
PLUGIN_DIR,
|
|
50
|
+
PRICING,
|
|
51
|
+
SDK_SOURCES,
|
|
52
|
+
SKILL_NAMES,
|
|
53
|
+
STUDIO_VERSION,
|
|
54
|
+
TEMPLATE_MAIN,
|
|
55
|
+
TEMPLATE_SCENE,
|
|
56
|
+
failureKind,
|
|
57
|
+
historyPreamble,
|
|
58
|
+
isInside,
|
|
59
|
+
keyedServices,
|
|
60
|
+
lastReplyText,
|
|
61
|
+
lastUserText,
|
|
62
|
+
modelFor,
|
|
63
|
+
pluginReady,
|
|
64
|
+
pricingFor,
|
|
65
|
+
readableFailure,
|
|
66
|
+
sessionDir,
|
|
67
|
+
sessionKept,
|
|
68
|
+
} from './shared.mjs'
|
|
69
|
+
import { appNote, runAgentApp } from './appRun.mjs'
|
|
70
|
+
import { createStopGate } from './stopGate.mjs'
|
|
71
|
+
import { inlineImages, measureBoard } from './reference/board.mjs'
|
|
72
|
+
import { createFlowWatch } from './flow.mjs'
|
|
73
|
+
import creatorNotes from './notes.cjs'
|
|
74
|
+
import { capacityOf } from './loop/capacity.mjs'
|
|
75
|
+
import { createLoopGate, perfIn } from './loop/gate.mjs'
|
|
76
|
+
import { judgeWithClaude, judgeWithOpenAI, lowerOf, openaiJudgeModel, openaiKeyVar } from './loop/judge.mjs'
|
|
77
|
+
import { JUDGE_MODEL, QUALITY, estimateQuality, qualityModel, qualityOf, targetPrice } from './loop/levels.mjs'
|
|
78
|
+
import { otherPictures, otherSpaces } from './tools/others.mjs'
|
|
79
|
+
import { createLoop } from './loop/state.mjs'
|
|
80
|
+
import { subagentsFor } from './subagents.mjs'
|
|
81
|
+
import { loadTools, runDef, toSdkTool } from './tools/index.mjs'
|
|
82
|
+
import { createTranscriptTap } from './transcripts.mjs'
|
|
83
|
+
|
|
84
|
+
/** How many of the creator's other spaces the judge sees beside the pairs. */
|
|
85
|
+
const JUDGE_OTHERS = 6
|
|
86
|
+
|
|
87
|
+
// Bash needs a POSIX shell, which a Windows machine without Git for Windows
|
|
88
|
+
// does not have. There the agent works with the file tools alone.
|
|
89
|
+
const HAS_BASH = process.platform !== 'win32'
|
|
90
|
+
export const AGENT_TOOLS = ['Read', 'Write', 'Edit', 'Glob', 'Grep', ...(HAS_BASH ? ['Bash'] : []), 'TodoWrite', 'Agent', 'WebSearch', 'WebFetch', 'Skill']
|
|
91
|
+
/** What the cleanup turn may not use: it only tidies up. */
|
|
92
|
+
const CLEANUP_DROPS = new Set(['Agent', 'WebSearch', 'WebFetch'])
|
|
93
|
+
// Nor model, fetch, generate or import anything, nor change the look.
|
|
94
|
+
const cleanupDef = (def) => def.name !== 'nw_blender' && def.name !== 'image_generate' && !/^browser/.test(def.name) && !/^asset_/.test(def.name) && !/^environment_/.test(def.name) && def.name !== 'look_apply' && def.name !== 'computer' && def.name !== 'computer_apps'
|
|
95
|
+
|
|
96
|
+
const ASK_TIMEOUT_MS = 31 * 60_000
|
|
97
|
+
// Main's calls that may wait on a permission card in the chat first.
|
|
98
|
+
const PERMISSION_RPCS = new Set(['capture-screen', 'computer', 'computer-apps'])
|
|
99
|
+
const COST_EVERY_MS = 2000
|
|
100
|
+
/** How often the session's transcripts are read for the helpers' and the
|
|
101
|
+
* final usage while a request runs. */
|
|
102
|
+
const TRANSCRIPT_EVERY_MS = 3000
|
|
103
|
+
/** Steps a request may take. Using a browser or an app, and looping on a hero
|
|
104
|
+
* asset, take many. */
|
|
105
|
+
const MAX_TURNS = 400
|
|
106
|
+
/** A space's loop runs for hours (deep: up to twelve) and many rounds: its
|
|
107
|
+
* steps' safety net is wider. The level's caps end it long before. */
|
|
108
|
+
const SPACE_MAX_TURNS = 1500
|
|
109
|
+
/** A space's steps at a quality step (loop/levels.mjs QUALITY): enough for
|
|
110
|
+
* the step's minutes and rounds, so its caps end it, never the steps. */
|
|
111
|
+
const QUALITY_SPACE_TURNS = Object.freeze({ 1: 400, 2: 400, 3: 1000, 4: 1500, 5: 3000 })
|
|
112
|
+
/** How long a request's start may spend measuring new pictures on the
|
|
113
|
+
* reference board; one it does not reach is measured by nw_reference. */
|
|
114
|
+
const BOARD_MEASURE_MS = 20_000
|
|
115
|
+
/** The studio's own tool server, in the order a new space uses them (prompt.mjs, The order for a space). */
|
|
116
|
+
const MCP_INSTRUCTIONS =
|
|
117
|
+
'Build, inspect and walk-through tools for an Oda space project. A new space is a loop against target pictures and uses them in this order: nw_ask_kickoff first (the questions, how the environment is made, the speed level and its cost); style.json, how the space is drawn (nw_guide "style": analysed from the creator\'s pictures, or researched, three directions drawn with image_generate kind "direction" and picked on the style card, nw_ask_pictures purpose "style"); the target pictures (image_generate kind "target" drawn in that style at the hero views, or the creator\'s photos) settled with nw_ask_targets, on the reference board, which nw_reference with board true measures; brief.json (nw_schema kind "brief") and brief.md, its hero views citing the targets; the environment in code first, then scanned CC0 libraries for what code cannot reach (asset_search, asset_fetch, asset_import); the props (asset_generate for a prop only, delit); asset_inspect against the brief\'s texel density; look_apply from the brief until nw_status\'s lookWarnings is empty; rounds with nw_round at the hero views H1 to H6 (stills from the targets\' cameras, look_compare against each target and a judge with no context) until the score is at the bar past the time floor or a cap is reached; nw_ask_approval; then the stop gate (nw_check and a look after the last edit, the loop\'s bar, time, frame time and planet size).'
|
|
118
|
+
/** Blocked for WebSearch, whatever the agent asks for (shared.mjs BLOCKED_HOSTS). */
|
|
119
|
+
const BLOCKED_DOMAINS = ['artstation.com', 'pinterest.com', 'behance.net']
|
|
120
|
+
/** The tools that change the game's files, for the pace's "not checked yet" note. */
|
|
121
|
+
const EDITS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'write_file', 'edit_file', 'mcp__nw__nw_blender', 'nw_blender', 'mcp__nw__look_apply', 'look_apply', 'mcp__nw__asset_import', 'asset_import'])
|
|
122
|
+
/** The file tools whose path could be brief.json, by both names. */
|
|
123
|
+
const FILE_WRITES = new Set(['Write', 'Edit', 'MultiEdit', 'write_file', 'edit_file'])
|
|
124
|
+
|
|
125
|
+
/** Whether a tool call writes the project's brief.json. */
|
|
126
|
+
const writesBrief = (projectRoot, name, input) => {
|
|
127
|
+
if (!FILE_WRITES.has(name)) return false
|
|
128
|
+
const file = input?.file_path ?? input?.path
|
|
129
|
+
return typeof file === 'string' && path.resolve(projectRoot, file) === path.join(projectRoot, 'brief.json')
|
|
130
|
+
}
|
|
131
|
+
/** Said when a brief.json comes before the targets in a loop (REFERENCE_LOOP.md 3). */
|
|
132
|
+
const TARGETS_FIRST =
|
|
133
|
+
'Refused: in the reference loop the target pictures come before the brief, which is measured from them. Draw them with image_generate kind "target" at the hero views you planned (or take the creator\'s four or more photos), settle them with nw_ask_targets (with none and why when no picture can be made), then write brief.json with their R ids as its hero views\' references.'
|
|
134
|
+
/** Added to the cost gate's refusal in a space with no kickoff yet. */
|
|
135
|
+
const KICKOFF_IS_THE_ASK = ' For a new space that ask is the kickoff card: nw_ask_kickoff (its questions, how the environment is made, the speed level and its cost) approves the cost of the level picked.'
|
|
136
|
+
/** Said when a space asks a plain cost card before its kickoff: the loop is
|
|
137
|
+
* not optional (REFERENCE_LOOP.md 2.1, 3), and a cost card would let a whole
|
|
138
|
+
* space be built with no targets, rounds, bar or approval card. */
|
|
139
|
+
const KICKOFF_NOT_COST =
|
|
140
|
+
'Refused: a new space asks its cost on its kickoff card, not on a cost card. Show nw_ask_kickoff (your questions, how the environment is made, the speed level with its time and cost): the creator\'s answer approves the cost of the level they pick. A cost card comes after it: when the kickoff went unanswered, when the spend will pass the approval, or for a paid environment of its own.'
|
|
141
|
+
/** Waits `ms`, or less when `stop()` says so; checked each second. */
|
|
142
|
+
async function holdFor(ms, stop) {
|
|
143
|
+
const until = Date.now() + ms
|
|
144
|
+
while (Date.now() < until && !stop()) await new Promise((r) => setTimeout(r, Math.min(1000, until - Date.now())))
|
|
145
|
+
}
|
|
146
|
+
const HELPER_REASON = "Helpers never use the creator's computer or browser, and never ask the creator; report back to the main agent instead."
|
|
147
|
+
|
|
148
|
+
// Host-only files (the keys a key card saved during a run), outside every
|
|
149
|
+
// root the guard lets the agent reach.
|
|
150
|
+
const HOST_PREFIX = 'nowhere-host-'
|
|
151
|
+
const HOST_DIR = path.join(os.tmpdir(), `${HOST_PREFIX}${process.pid}`)
|
|
152
|
+
|
|
153
|
+
/** The folders of hosts that died without their finally (killed mid-run, a
|
|
154
|
+
* crash), with the keys they held in plain text: removed when a host starts.
|
|
155
|
+
* A pid that is alive, or not ours to signal, is left alone. */
|
|
156
|
+
export function removeStaleHostDirs(tmp = os.tmpdir()) {
|
|
157
|
+
let names = []
|
|
158
|
+
try {
|
|
159
|
+
names = fs.readdirSync(tmp)
|
|
160
|
+
} catch {
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
for (const name of names) {
|
|
164
|
+
const pid = Number(name.slice(HOST_PREFIX.length))
|
|
165
|
+
if (!name.startsWith(HOST_PREFIX) || !Number.isInteger(pid) || pid <= 0 || pid === process.pid) continue
|
|
166
|
+
try {
|
|
167
|
+
process.kill(pid, 0)
|
|
168
|
+
continue
|
|
169
|
+
} catch (err) {
|
|
170
|
+
if (err?.code !== 'ESRCH') continue
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
fs.rmSync(path.join(tmp, name), { recursive: true, force: true })
|
|
174
|
+
} catch {
|
|
175
|
+
// the next host tries again
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Removes this host's own folder, at once: the process is about to go. */
|
|
181
|
+
export function removeHostDir() {
|
|
182
|
+
try {
|
|
183
|
+
fs.rmSync(HOST_DIR, { recursive: true, force: true })
|
|
184
|
+
} catch {
|
|
185
|
+
// nothing to remove
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** The text store.ts sends for a message that is only pictures: no words of
|
|
190
|
+
* the creator's, so not a sample of their language. */
|
|
191
|
+
const IMAGE_ONLY_TEXT = 'Look at the attached image.'
|
|
192
|
+
|
|
193
|
+
const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif' }
|
|
194
|
+
|
|
195
|
+
// ---------------------------------------------------------------- what other streams provide
|
|
196
|
+
// Each is optional: a tree where it has not landed yet still runs.
|
|
197
|
+
|
|
198
|
+
let localeModule
|
|
199
|
+
async function locales(log) {
|
|
200
|
+
if (localeModule !== undefined) return localeModule
|
|
201
|
+
try {
|
|
202
|
+
const m = await import('./locale.cjs')
|
|
203
|
+
localeModule = m.default ?? m
|
|
204
|
+
} catch (err) {
|
|
205
|
+
if (err?.code !== 'ERR_MODULE_NOT_FOUND') log?.(`[agent] locale.cjs did not load: ${err?.message ?? err}`)
|
|
206
|
+
localeModule = null
|
|
207
|
+
}
|
|
208
|
+
return localeModule
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The two languages of locale.cjs in their shortest form, for a tree
|
|
212
|
+
* without it: the creator's, for the replies, from the script of their
|
|
213
|
+
* message; the screen's, from the computer's language alone. */
|
|
214
|
+
const LATIN = new Set(['en', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'sv', 'da', 'nb', 'fi', 'pl', 'cs', 'tr', 'id', 'vi'])
|
|
215
|
+
function fallbackLocale(text, osLocale) {
|
|
216
|
+
if (/\p{Script=Hangul}/u.test(text)) return 'ko'
|
|
217
|
+
if (/\p{Script=Hiragana}|\p{Script=Katakana}/u.test(text)) return 'ja'
|
|
218
|
+
if (/\p{Script=Han}/u.test(text)) return 'zh'
|
|
219
|
+
const system = String(osLocale ?? '').slice(0, 2).toLowerCase()
|
|
220
|
+
if (/\p{L}/u.test(text)) return LATIN.has(system) ? system : 'en'
|
|
221
|
+
return /^[a-z]{2}$/.test(system) ? system : 'en'
|
|
222
|
+
}
|
|
223
|
+
const LABEL_LOCALES = new Set(['en', 'ko', 'ja', 'zh', 'es', 'fr', 'de'])
|
|
224
|
+
function fallbackScreen(osLocale) {
|
|
225
|
+
const system = String(osLocale ?? '').slice(0, 2).toLowerCase()
|
|
226
|
+
return LABEL_LOCALES.has(system) ? system : 'en'
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// The roles of a production (roles/), from the ROLES stream. Until they
|
|
230
|
+
// land a team request takes the single-agent path.
|
|
231
|
+
let teamModule
|
|
232
|
+
async function teamModules(log) {
|
|
233
|
+
if (teamModule !== undefined) return teamModule
|
|
234
|
+
try {
|
|
235
|
+
const [roles, critic, checks] = await Promise.all([import('./roles/index.mjs'), import('./roles/critic.mjs'), import('./roles/checks.mjs')])
|
|
236
|
+
teamModule = { roles: roles.ROLES, critic: { criticSpec: critic.criticSpec, passes: critic.passes, whyNot: critic.whyNot, CRITIC_SCHEMA: critic.CRITIC_SCHEMA }, roleChecks: checks.ROLE_CHECKS ?? {} }
|
|
237
|
+
} catch (err) {
|
|
238
|
+
if (err?.code !== 'ERR_MODULE_NOT_FOUND') log?.(`[director] the roles did not load: ${err?.message ?? err}`)
|
|
239
|
+
teamModule = null
|
|
240
|
+
}
|
|
241
|
+
return teamModule
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** What the studio context says about the project's files and its look:
|
|
245
|
+
* how many files the asset ledger (assets.lock.json) records and the
|
|
246
|
+
* problems that would stop a publish, and whether the config has a look
|
|
247
|
+
* block of its own or none (legacy: Neutral, as the studio drew before
|
|
248
|
+
* looks). Each part is left out when it cannot be read. */
|
|
249
|
+
async function projectFacts(projectRoot, log) {
|
|
250
|
+
const facts = {}
|
|
251
|
+
try {
|
|
252
|
+
const ledger = await import('./assets/ledger.mjs')
|
|
253
|
+
const state = await ledger.readLedgerState(projectRoot)
|
|
254
|
+
const problems = await ledger.ledgerProblems(projectRoot)
|
|
255
|
+
facts.assets = {
|
|
256
|
+
sources: 'Poly Haven and ambientCG (no key), Poly Pizza (key: polypizza)',
|
|
257
|
+
ledger: { files: state.status === 'ok' ? Object.keys(state.lock.files).length : 0, absent: state.status === 'absent', problems: problems.map((p) => p.message) },
|
|
258
|
+
}
|
|
259
|
+
} catch (err) {
|
|
260
|
+
log?.(`[agent] the asset ledger could not be read: ${err?.message ?? err}`)
|
|
261
|
+
}
|
|
262
|
+
try {
|
|
263
|
+
const config = JSON.parse(await fsp.readFile(path.join(projectRoot, 'game.config.json'), 'utf8'))
|
|
264
|
+
const look = config?.look && typeof config.look === 'object' ? config.look : null
|
|
265
|
+
facts.look = { legacy: look === null }
|
|
266
|
+
} catch {
|
|
267
|
+
// no config, or one too broken to read: the agent finds out with nw_check
|
|
268
|
+
}
|
|
269
|
+
return facts
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Blender for the studio context: its version and path, null when it is not
|
|
273
|
+
* installed, undefined when this build has no nw_blender yet. */
|
|
274
|
+
async function blenderInfo(log) {
|
|
275
|
+
const mod = await import('./blender/find.mjs').catch(() => null)
|
|
276
|
+
if (!mod?.findBlender) return { info: undefined, folder: null }
|
|
277
|
+
try {
|
|
278
|
+
const found = await mod.findBlender()
|
|
279
|
+
if (!found?.path) return { info: null, folder: null }
|
|
280
|
+
// The whole app on a Mac (its Python and data live inside it), the
|
|
281
|
+
// executable's folder elsewhere: read-only for Bash. find.mjs says which
|
|
282
|
+
// (root); the same rule by hand for a find.mjs from before it did.
|
|
283
|
+
const app = found.path.match(/^(.*?\.app)(\/|$)/)
|
|
284
|
+
const folder = typeof found.root === 'string' && found.root ? found.root : app ? app[1] : path.dirname(found.path)
|
|
285
|
+
return { info: { version: found.version, path: found.path }, folder }
|
|
286
|
+
} catch (err) {
|
|
287
|
+
log?.(`[agent] findBlender failed: ${err?.message ?? err}`)
|
|
288
|
+
return { info: null, folder: null }
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// ---------------------------------------------------------------- connectors
|
|
293
|
+
// Main resolves which connectors are on and hands the result over with each
|
|
294
|
+
// prompt, so this process never opens the secret store. Secrets travel in the
|
|
295
|
+
// query's own env rather than process.env: a service disconnected between two
|
|
296
|
+
// prompts must not linger in the child's environment.
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* How a Claude run reaches the model (main decides it per run, pay.cjs): on
|
|
300
|
+
* Oda coins, through the relay with its token and no key at all (any key in
|
|
301
|
+
* the inherited environment is blanked, so none is sent to the relay, and
|
|
302
|
+
* background calls use a model the relay prices); on the creator's Claude
|
|
303
|
+
* app (msg.login), with no key either, so the SDK's CLI uses the account
|
|
304
|
+
* Claude Code is signed in to on this Mac; with the creator's own key, as
|
|
305
|
+
* before.
|
|
306
|
+
*/
|
|
307
|
+
export function claudeAuth(msg) {
|
|
308
|
+
const gate = msg?.gate
|
|
309
|
+
if (gate && typeof gate.url === 'string' && /^https:\/\//.test(gate.url) && typeof gate.token === 'string' && gate.token) {
|
|
310
|
+
return {
|
|
311
|
+
ANTHROPIC_BASE_URL: gate.url,
|
|
312
|
+
ANTHROPIC_AUTH_TOKEN: gate.token,
|
|
313
|
+
ANTHROPIC_API_KEY: '',
|
|
314
|
+
ANTHROPIC_SMALL_FAST_MODEL: 'claude-haiku-5-5',
|
|
315
|
+
ANTHROPIC_DEFAULT_HAIKU_MODEL: 'claude-haiku-5-5',
|
|
316
|
+
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
// Blank, not absent: a key inherited from the environment or a connector
|
|
320
|
+
// would otherwise win over the login.
|
|
321
|
+
if (msg?.login === true) return { ANTHROPIC_API_KEY: '', ANTHROPIC_AUTH_TOKEN: '' }
|
|
322
|
+
return msg?.apiKey ? { ANTHROPIC_API_KEY: msg.apiKey } : {}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function connectorOptions(connectors) {
|
|
326
|
+
const mcpServers = connectors?.mcpServers ?? {}
|
|
327
|
+
// `env` REPLACES the child environment rather than extending it, so the
|
|
328
|
+
// parent's own variables have to be carried over by hand.
|
|
329
|
+
const env = { ...process.env, ...(connectors?.env ?? {}) }
|
|
330
|
+
// A vendor key that happens to be exported in the shell that launched the
|
|
331
|
+
// studio is not a connected service: main lists those here and they leave the
|
|
332
|
+
// child's environment, so nothing can be spent against an account the creator
|
|
333
|
+
// never switched on.
|
|
334
|
+
for (const name of connectors?.envRemove ?? []) delete env[name]
|
|
335
|
+
// A nowhere command the agent runs takes this run's keys, never the
|
|
336
|
+
// creator's stored ones, and cannot give the creator's yes or change the
|
|
337
|
+
// creator's key store (packages/cli: bin/nowhere.mjs, lib/tools.mjs, lib/keys.mjs).
|
|
338
|
+
env.NOWHERE_STORED_KEYS = '0'
|
|
339
|
+
env.NOWHERE_AGENT_RUN = '1'
|
|
340
|
+
return {
|
|
341
|
+
env,
|
|
342
|
+
mcpServers,
|
|
343
|
+
allowedTools: Object.keys(mcpServers).map((serverId) => `mcp__${serverId}__*`),
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// ---------------------------------------------------------------- run setup
|
|
348
|
+
|
|
349
|
+
/** The creator's attached pictures, kept in the project so the agent and its
|
|
350
|
+
* helpers can open them by path. Answers { fresh, references }: this
|
|
351
|
+
* message's pictures, and those with up to six earlier ones, newest first,
|
|
352
|
+
* which is what a team production's director reads (it is frozen as it
|
|
353
|
+
* was). The fast path's context lists the whole board instead
|
|
354
|
+
* (reference/board.mjs). An earlier picture set aside on the reference
|
|
355
|
+
* board (refBoard.cjs, use false) is in neither unless the brief cites it;
|
|
356
|
+
* a picture attached now always is. */
|
|
357
|
+
async function writeReferences(projectRoot, images) {
|
|
358
|
+
const dir = path.join(projectRoot, '.nowhere', 'refs')
|
|
359
|
+
const fresh = []
|
|
360
|
+
for (const image of images) {
|
|
361
|
+
const ext = EXT[image?.mime]
|
|
362
|
+
if (!ext || typeof image.data !== 'string') continue
|
|
363
|
+
const bytes = Buffer.from(image.data, 'base64')
|
|
364
|
+
const at = path.join(dir, `${createHash('sha1').update(bytes).digest('hex').slice(0, 12)}.${ext}`)
|
|
365
|
+
try {
|
|
366
|
+
await fsp.mkdir(dir, { recursive: true })
|
|
367
|
+
if (!fs.existsSync(at)) await fsp.writeFile(at, bytes)
|
|
368
|
+
if (!fresh.includes(at)) fresh.push(at)
|
|
369
|
+
} catch {
|
|
370
|
+
// a picture that cannot be kept is still in the message itself
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
let earlier = []
|
|
374
|
+
try {
|
|
375
|
+
const out = refBoard.excluded(projectRoot)
|
|
376
|
+
const names = (await fsp.readdir(dir)).filter((n) => /\.(png|jpe?g|webp|gif)$/i.test(n) && !out.has(n))
|
|
377
|
+
const stats = await Promise.all(names.map(async (n) => ({ at: path.join(dir, n), t: (await fsp.stat(path.join(dir, n))).mtimeMs })))
|
|
378
|
+
earlier = stats
|
|
379
|
+
.filter((s) => !fresh.includes(s.at))
|
|
380
|
+
.sort((a, b) => b.t - a.t)
|
|
381
|
+
.slice(0, refBoard.HANDED_EARLIER)
|
|
382
|
+
.map((s) => s.at)
|
|
383
|
+
} catch {
|
|
384
|
+
// no earlier pictures
|
|
385
|
+
}
|
|
386
|
+
return { fresh, references: [...fresh, ...earlier] }
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Whether the project is still the blank template: its first request is a whole game. */
|
|
390
|
+
async function isEmptyProject(projectRoot) {
|
|
391
|
+
try {
|
|
392
|
+
const [mine, template] = await Promise.all([fsp.readFile(path.join(projectRoot, 'src', 'main.ts')), fsp.readFile(TEMPLATE_MAIN)])
|
|
393
|
+
return mine.equals(template)
|
|
394
|
+
} catch {
|
|
395
|
+
return false
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Starters an older blank template placed, as it placed them. The template
|
|
400
|
+
* places nothing since 2026-10-24 (a new space starts empty), but a project
|
|
401
|
+
* made before then still has its stonehenge there, and comparing with the
|
|
402
|
+
* current template alone stopped naming it: three of the creator's projects
|
|
403
|
+
* had it, and the agent read it as the creator's again. */
|
|
404
|
+
export const RETIRED_STARTERS = Object.freeze([
|
|
405
|
+
{ id: 'stonehenge', asset: 'assets/stonehenge.glb', position: [0.945, 0, -0.0115], rotation: [0, 0, 0], scale: [12.279875, 12.279875, 12.279875] },
|
|
406
|
+
])
|
|
407
|
+
|
|
408
|
+
/** The blank template's starter objects still in the project's scene.json
|
|
409
|
+
* where the template put them (same id, model and placement): a placeholder
|
|
410
|
+
* nobody has moved, not the creator's (2026-10-20: every new game kept the
|
|
411
|
+
* stonehenge as "the creator's only placement"). The current template's
|
|
412
|
+
* starters and the retired ones both count, so a new project answers [] and
|
|
413
|
+
* one made from an older template still has its placeholder named. */
|
|
414
|
+
export async function starterPlaceholders(projectRoot, templateScene = TEMPLATE_SCENE, retired = RETIRED_STARTERS) {
|
|
415
|
+
const read = async (file) => {
|
|
416
|
+
try {
|
|
417
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'))
|
|
418
|
+
} catch {
|
|
419
|
+
return null
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
const [mine, template] = await Promise.all([read(path.join(projectRoot, 'scene.json')), read(templateScene)])
|
|
423
|
+
const objects = Array.isArray(mine?.objects) ? mine.objects : []
|
|
424
|
+
const same = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => Math.abs(Number(v) - Number(b[i])) < 1e-6)
|
|
425
|
+
const starters = [...(Array.isArray(template?.objects) ? template.objects : []), ...retired]
|
|
426
|
+
const out = []
|
|
427
|
+
for (const t of starters) {
|
|
428
|
+
if (typeof t?.id !== 'string' || typeof t.asset !== 'string') continue
|
|
429
|
+
if (out.some((s) => s.id === t.id && s.asset === t.asset)) continue
|
|
430
|
+
if (objects.some((o) => o?.id === t.id && o.asset === t.asset && same(o.position, t.position) && same(o.rotation, t.rotation) && same(o.scale, t.scale))) out.push({ id: t.id, asset: t.asset })
|
|
431
|
+
}
|
|
432
|
+
return out
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** The host's consents for one run, the web and Codex (pictures made on
|
|
436
|
+
* the creator's ChatGPT plan): the saved answer, else the creator's answer
|
|
437
|
+
* to the host's card, asked once, which the studio saves. */
|
|
438
|
+
function createConsent({ saved, rpc, runId, locale }) {
|
|
439
|
+
const topic = (name) => {
|
|
440
|
+
let answer = saved?.[name] === 'allow' || saved?.[name] === 'deny' ? saved[name] : null
|
|
441
|
+
let asking = null
|
|
442
|
+
return {
|
|
443
|
+
ask() {
|
|
444
|
+
if (answer) return Promise.resolve(answer)
|
|
445
|
+
asking ??= rpc('ask', { runId, locale, card: { kind: 'consent', topic: name, origin: 'host' } }, ASK_TIMEOUT_MS).then((r) => {
|
|
446
|
+
answer = typeof r?.answer === 'string' ? r.answer : 'unavailable'
|
|
447
|
+
return answer
|
|
448
|
+
})
|
|
449
|
+
return asking
|
|
450
|
+
},
|
|
451
|
+
set(value) {
|
|
452
|
+
if (value === 'allow' || value === 'deny') answer = value
|
|
453
|
+
},
|
|
454
|
+
state: () => (answer === 'allow' || answer === 'deny' ? answer : 'ask'),
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
const web = topic('web')
|
|
458
|
+
const codex = topic('codex')
|
|
459
|
+
return {
|
|
460
|
+
web: () => web.ask(),
|
|
461
|
+
/** The creator answered an agent's own web card (nw_ask). */
|
|
462
|
+
set: (value) => web.set(value),
|
|
463
|
+
state: () => web.state(),
|
|
464
|
+
codex: () => codex.ask(),
|
|
465
|
+
codexState: () => codex.state(),
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** The creator's Codex for the director's capability list: where it is and
|
|
470
|
+
* how it is logged in, null when this build has no Codex finder. */
|
|
471
|
+
async function codexInfo(log) {
|
|
472
|
+
const mod = await import('./assets/images/codex.mjs').catch(() => null)
|
|
473
|
+
if (!mod?.findCodex) return null
|
|
474
|
+
try {
|
|
475
|
+
return await mod.findCodex()
|
|
476
|
+
} catch (err) {
|
|
477
|
+
log?.(`[agent] findCodex failed: ${err?.message ?? err}`)
|
|
478
|
+
return null
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** An nw_ask web consent's answer, read back from its result. */
|
|
483
|
+
function webAnswerOf(toolInput, resultText) {
|
|
484
|
+
if (toolInput?.kind !== 'consent' || toolInput?.topic !== 'web') return null
|
|
485
|
+
return /"answer"\s*:\s*"(allow|deny)"/.exec(String(resultText ?? ''))?.[1] ?? null
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** A PostToolUse tool_response as text. An MCP tool's is its content blocks
|
|
489
|
+
* (an array, or { content: [...] }), whose text is joined as written:
|
|
490
|
+
* stringified, its quotes would be escaped and no answer could be read. */
|
|
491
|
+
const resultText = (response) => {
|
|
492
|
+
if (typeof response === 'string') return response
|
|
493
|
+
const blocks = Array.isArray(response) ? response : Array.isArray(response?.content) ? response.content : null
|
|
494
|
+
if (blocks) return blocks.filter((b) => b?.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n')
|
|
495
|
+
try {
|
|
496
|
+
return JSON.stringify(response)
|
|
497
|
+
} catch {
|
|
498
|
+
return ''
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '[::1]'])
|
|
503
|
+
/** The hosts of the remote http(s) URLs in a command line. */
|
|
504
|
+
function remoteHosts(command) {
|
|
505
|
+
const hosts = []
|
|
506
|
+
for (const m of String(command ?? '').matchAll(/\bhttps?:\/\/[^\s"'<>|;&)`]+/gi)) {
|
|
507
|
+
try {
|
|
508
|
+
const host = new URL(m[0]).hostname.toLowerCase()
|
|
509
|
+
if (host && !LOCAL_HOSTS.has(host)) hosts.push(host)
|
|
510
|
+
} catch {
|
|
511
|
+
// not a URL after all
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return hosts
|
|
515
|
+
}
|
|
516
|
+
/** Whether a host is a service's API host or under its domain (api.meshy.ai: meshy.ai and its CDN). */
|
|
517
|
+
const underDomain = (host, apiHost) => {
|
|
518
|
+
const domain = apiHost.split('.').slice(-2).join('.')
|
|
519
|
+
return host === domain || host.endsWith(`.${domain}`)
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** The rules about keys in Bash for one run: the variables that hold a key
|
|
523
|
+
* (never printed, the guard), and the paid ones of them (never called before
|
|
524
|
+
* a cost was approved, the hook). */
|
|
525
|
+
function keyRules(connectors, env) {
|
|
526
|
+
const services = keyedServices()
|
|
527
|
+
const secret = new Set([...services.map((s) => s.envVar), ...Object.keys(connectors?.env ?? {})])
|
|
528
|
+
const paid = services.filter((s) => PAID_CATEGORIES.has(s.category) && s.id !== 'anthropic').map((s) => s.envVar)
|
|
529
|
+
// A connected service's own API is not "the web": the creator connected it.
|
|
530
|
+
// Read at each call: a key saved in a key card joins the run's env in place.
|
|
531
|
+
const connectedHosts = () => services.filter((s) => s.apiHost && typeof env?.[s.envVar] === 'string' && env[s.envVar]).map((s) => s.apiHost)
|
|
532
|
+
return {
|
|
533
|
+
secret,
|
|
534
|
+
/** The first paid service's variable a command uses, or null. */
|
|
535
|
+
paidVar: (command) => paid.find((name) => new RegExp(`\\b${name}\\b`).test(String(command ?? ''))) ?? null,
|
|
536
|
+
/** Whether a command reaches the web beyond the connected services' APIs. */
|
|
537
|
+
needsWeb: (command) => {
|
|
538
|
+
const hosts = remoteHosts(command)
|
|
539
|
+
if (hosts.length === 0) return false
|
|
540
|
+
const apis = connectedHosts()
|
|
541
|
+
return hosts.some((host) => !apis.some((api) => underDomain(host, api)))
|
|
542
|
+
},
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** A WebSearch input with the blocked sites kept out. The search takes
|
|
547
|
+
* allowed_domains or blocked_domains, never both (the CLI refuses the pair):
|
|
548
|
+
* one kept to some sites loses the blocked ones from that list instead. */
|
|
549
|
+
function webSearchInput(toolInput) {
|
|
550
|
+
const allowed = Array.isArray(toolInput?.allowed_domains) ? toolInput.allowed_domains.filter((d) => typeof d === 'string' && d) : []
|
|
551
|
+
if (allowed.length > 0) {
|
|
552
|
+
const kept = allowed.filter((d) => !BLOCKED_HOSTS.test(d))
|
|
553
|
+
if (kept.length === 0) return { deny: BLOCKED_REASON }
|
|
554
|
+
const { blocked_domains: _none, ...rest } = toolInput
|
|
555
|
+
return { input: { ...rest, allowed_domains: kept } }
|
|
556
|
+
}
|
|
557
|
+
const blocked = Array.isArray(toolInput?.blocked_domains) ? toolInput.blocked_domains : []
|
|
558
|
+
const { allowed_domains: _empty, ...rest } = toolInput ?? {}
|
|
559
|
+
return { input: { ...rest, blocked_domains: [...new Set([...blocked, ...BLOCKED_DOMAINS])] } }
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const NO_WEB = 'The creator has not allowed the web. Work without it; if it is essential, say so in your reply.'
|
|
563
|
+
const paidReason = (name, helper) =>
|
|
564
|
+
helper
|
|
565
|
+
? `Refused: this command calls a paid service (${name}) and no cost was approved for this request. Report back to the main agent, which asks the creator.`
|
|
566
|
+
: `Refused: this command calls a paid service (${name}) and no cost was approved for this request. Ask with nw_ask kind "cost" first, with a line for this generation call and its price; then run it and record what it cost with nw_spend.`
|
|
567
|
+
|
|
568
|
+
const quote = (s) => `'${String(s).replace(/'/g, "'\\''")}'`
|
|
569
|
+
|
|
570
|
+
// ---------------------------------------------------------------- the host
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* @param {{ send: (msg: object) => void, rpc: (method: string, params?: object, timeoutMs?: number) => Promise<any>,
|
|
574
|
+
* log?: (line: string) => void,
|
|
575
|
+
* test?: { maxTurns?: number, cleanupMaxTurns?: number, pluginDir?: string, extraDefs?: object[], replaceDefs?: object[],
|
|
576
|
+
* query?: Function, route?: 'fast' | 'production', team?: object } }} options
|
|
577
|
+
* test: for the check scripts only. query: the SDK's query, or the scripted
|
|
578
|
+
* fake (scripts/lib/fakeModel.mjs); route: skips the triage; team: the
|
|
579
|
+
* director's deps to use (the roles, the critic, limits, a clock). For the
|
|
580
|
+
* reference loop: now, the clock the loop and the pace keep; fetch, the
|
|
581
|
+
* tools' network; judge, judgeQuery and judgeFetch, the judge or the
|
|
582
|
+
* network its two calls go to; capacity, what a planet would carry;
|
|
583
|
+
* noLoop, for a check from before the loop that builds a new space on a
|
|
584
|
+
* plain cost card to test something else (the loop refuses that card).
|
|
585
|
+
* Nothing in the studio passes any of them.
|
|
586
|
+
*/
|
|
587
|
+
export function createHost({ send, rpc, log = (line) => console.log(line), test = {} }) {
|
|
588
|
+
removeStaleHostDirs()
|
|
589
|
+
let active = null
|
|
590
|
+
let toolsLoaded = null
|
|
591
|
+
const tools = () => (toolsLoaded ??= loadTools({ log }))
|
|
592
|
+
const sdkQuery = test.query ?? query
|
|
593
|
+
/** The clock the loop and the pace keep (a check's own clock). */
|
|
594
|
+
const clock = test.now ?? (() => Date.now())
|
|
595
|
+
|
|
596
|
+
async function run(msg) {
|
|
597
|
+
const { id, projectRoot } = msg
|
|
598
|
+
const text = String(msg.text ?? '')
|
|
599
|
+
const images = Array.isArray(msg.images) ? msg.images : []
|
|
600
|
+
const self = {
|
|
601
|
+
id,
|
|
602
|
+
projectRoot,
|
|
603
|
+
cancelled: false,
|
|
604
|
+
interrupt: null,
|
|
605
|
+
envFile: path.join(HOST_DIR, `env-${String(id).replace(/[^\w-]/g, '_')}.sh`),
|
|
606
|
+
env: null,
|
|
607
|
+
gate: null,
|
|
608
|
+
// The variables that hold keys, grown by secretEnv: the guard never lets Bash print them.
|
|
609
|
+
secretNames: new Set(),
|
|
610
|
+
// What the creator sends while this run works (agent/notes.cjs): given
|
|
611
|
+
// in the main agent's next tool result, or at its Stop.
|
|
612
|
+
notes: creatorNotes.createNoteQueue({ projectRoot, onDelivered: (noteIds) => send({ type: 'note', id, noteIds, state: 'delivered' }) }),
|
|
613
|
+
}
|
|
614
|
+
active = self
|
|
615
|
+
let runDir = null
|
|
616
|
+
try {
|
|
617
|
+
// The two languages, the request's depth, a scratch folder, the
|
|
618
|
+
// reference pictures, Blender.
|
|
619
|
+
const loc = await locales(log)
|
|
620
|
+
// The creator's language, for the agent's chat replies only: from
|
|
621
|
+
// their own words; a picture sent alone has none, and neither has a
|
|
622
|
+
// message whose words are the studio's (Continue, the Describe chip, a
|
|
623
|
+
// marking sent with no note: studioWords, in the screen language), so
|
|
624
|
+
// the creator's last own words in the history; when a long run of
|
|
625
|
+
// Continues has pushed those out of it, the agent's last reply, which
|
|
626
|
+
// is in their language; else the computer's language. Read from the
|
|
627
|
+
// studio's words, or from none, a Korean creator on an English Mac who
|
|
628
|
+
// pressed Continue would be answered, and held to, English.
|
|
629
|
+
const own = msg.studioWords === true || (images.length > 0 && text.trim() === IMAGE_ONLY_TEXT) ? '' : text
|
|
630
|
+
const sample = (own.match(/\p{L}/gu) ?? []).length >= 3 ? own : lastUserText(msg.history) || lastReplyText(msg.history)
|
|
631
|
+
const replyLocale = (loc?.detectLocale ?? fallbackLocale)(sample, msg.osLocale)
|
|
632
|
+
const replyLanguage = loc?.LANGUAGE_NAMES?.[replyLocale] ?? replyLocale
|
|
633
|
+
// The screen language, for everything else the creator reads: every
|
|
634
|
+
// card's labels and every word the agent writes on one, the host's own
|
|
635
|
+
// cards, the brief. The computer's language when the studio has its
|
|
636
|
+
// labels, else English; never the message's, so a Korean message on an
|
|
637
|
+
// English system gets English cards and a Korean reply.
|
|
638
|
+
const screenLocale = (loc?.screenLocale ?? fallbackScreen)(msg.osLocale)
|
|
639
|
+
const screenLanguage = loc?.LANGUAGE_NAMES?.[screenLocale] ?? screenLocale
|
|
640
|
+
// A "continue" goes on at the depth of the request it continues, and
|
|
641
|
+
// no request runs deeper than its model should. A production routes
|
|
642
|
+
// its own models, so it reads the depth before the fit.
|
|
643
|
+
const emptyProject = await isEmptyProject(projectRoot)
|
|
644
|
+
const askedDepth = depthFor({ text, history: msg.history, images: images.length, attachment: !!msg.attachment, emptyProject })
|
|
645
|
+
// The reference loop (loop/state.mjs): held once a kickoff stands in a
|
|
646
|
+
// request that builds a space, or a "continue" of one. Its gate comes
|
|
647
|
+
// after the studio's own (stopGate.mjs), and its time replaces the
|
|
648
|
+
// pace's usual minutes once it has a level.
|
|
649
|
+
const loop = createLoop({ projectRoot, space: askedDepth.space === true, continued: isContinuation(text), now: clock })
|
|
650
|
+
self.loop = loop
|
|
651
|
+
// The quality step (loop/levels.mjs QUALITY): a "continue" keeps the
|
|
652
|
+
// one its loop was started at, else the message's. On Claude it picks
|
|
653
|
+
// the model and caps the effort; another vendor chosen in Settings
|
|
654
|
+
// keeps its model, and the step sets only the rounds, bar and caps.
|
|
655
|
+
const quality = loop.active ? loop.quality : qualityOf(msg.quality)
|
|
656
|
+
const step = quality ? QUALITY[quality] : null
|
|
657
|
+
const chosen = modelFor(msg.model)
|
|
658
|
+
const onClaude = chosen.provider.runtime === 'claude-agent-sdk'
|
|
659
|
+
// oda make --ceiling still holds the step's model (the studio sends none with a step).
|
|
660
|
+
const { provider, model } = step && onClaude ? modelFor(qualityModel(quality, msg.settings?.ceiling ?? null)) : chosen
|
|
661
|
+
// A build (a space, or a "continue" of a loop at a step) runs at the
|
|
662
|
+
// step's effort, raised as well as lowered; any other request (a tweak,
|
|
663
|
+
// a question) keeps the step as a ceiling only.
|
|
664
|
+
const stepBuild = !!step && (askedDepth.space === true || (loop.active && isContinuation(text)))
|
|
665
|
+
// On the creator's Claude login, an effort they picked in the chat holds
|
|
666
|
+
// for every request; otherwise the studio's own pick from the request.
|
|
667
|
+
const picked = msg.login === true && EFFORTS.includes(msg.effort) ? msg.effort : null
|
|
668
|
+
const capped = picked
|
|
669
|
+
? { ...askedDepth, effort: picked, reason: `${askedDepth.reason}, ${picked} as picked for the Claude login` }
|
|
670
|
+
: !(step && onClaude)
|
|
671
|
+
? askedDepth
|
|
672
|
+
: stepBuild
|
|
673
|
+
? { ...askedDepth, effort: step.effort, reason: `${askedDepth.reason}, at quality ${step.step} (${step.name}): ${step.effort}` }
|
|
674
|
+
: EFFORTS.indexOf(askedDepth.effort) > EFFORTS.indexOf(step.effort)
|
|
675
|
+
? { ...askedDepth, effort: step.effort, reason: `${askedDepth.reason}, at most ${step.effort} at quality ${step.step} (${step.name})` }
|
|
676
|
+
: askedDepth
|
|
677
|
+
const depth = fitDepth(capped, model)
|
|
678
|
+
// A production's models are held to the step's model as to the Settings ceiling.
|
|
679
|
+
const ceiling = step && onClaude ? model.id : (msg.settings?.ceiling ?? msg.settings?.ceilingWithoutStep ?? null)
|
|
680
|
+
runDir = fs.realpathSync(await fsp.mkdtemp(path.join(os.tmpdir(), `nowhere-agent-${String(id).replace(/[^\w-]/g, '_').slice(0, 40)}-`)))
|
|
681
|
+
// A picture the creator marked up says what to change, not what the
|
|
682
|
+
// space looks like: it goes in the message, not on the board.
|
|
683
|
+
const { fresh, references } = await writeReferences(projectRoot, msg.marked === true ? [] : images)
|
|
684
|
+
// Every picture on the board, each with what it measured (measured once,
|
|
685
|
+
// then read back): the brief is written from all of them. A message for
|
|
686
|
+
// the team measures nothing new here (the director reads its own board),
|
|
687
|
+
// and a Stop ends the measuring at the next picture.
|
|
688
|
+
const board = await measureBoard(projectRoot, { fresh, rpc, timeMs: msg.team === true ? 0 : (test.boardMs ?? BOARD_MEASURE_MS), cancelled: () => self.cancelled }).catch((err) => {
|
|
689
|
+
log(`[agent] the reference board could not be read: ${err?.message ?? err}`)
|
|
690
|
+
return null
|
|
691
|
+
})
|
|
692
|
+
const inline = inlineImages(images)
|
|
693
|
+
const blender = await blenderInfo(log)
|
|
694
|
+
const facts = await projectFacts(projectRoot, log)
|
|
695
|
+
|
|
696
|
+
// The ledger, the stop gate, the guard and the web consent.
|
|
697
|
+
let defs = await tools()
|
|
698
|
+
for (const extra of test.extraDefs ?? []) if (!defs.some((d) => d.name === extra.name)) defs = [...defs, extra]
|
|
699
|
+
for (const stand of test.replaceDefs ?? []) defs = [...defs.filter((d) => d.name !== stand.name), stand]
|
|
700
|
+
const byName = new Map(defs.map((d) => [d.name, d]))
|
|
701
|
+
const askable = byName.has('nw_ask')
|
|
702
|
+
const big = depth.big && askable
|
|
703
|
+
let escalate = null
|
|
704
|
+
const ledger = createLedger({
|
|
705
|
+
price: pricingFor(model),
|
|
706
|
+
prices: PRICING,
|
|
707
|
+
model: model.id,
|
|
708
|
+
big,
|
|
709
|
+
askable,
|
|
710
|
+
onApprove: () => escalate?.(),
|
|
711
|
+
})
|
|
712
|
+
// A request that builds a space ends with its brief.json and the look
|
|
713
|
+
// set from it; any other answers only for what it changed (stopGate.mjs).
|
|
714
|
+
const gate = await createStopGate(projectRoot, { needView: defs.some((d) => d.verifies === 'view' || d.name === 'nw_play'), space: depth.space === true })
|
|
715
|
+
self.gate = gate
|
|
716
|
+
const maxTurns = test.maxTurns ?? (depth.space ? (step ? QUALITY_SPACE_TURNS[step.step] : SPACE_MAX_TURNS) : MAX_TURNS)
|
|
717
|
+
// Only a build at the step has its time from the step: a tweak or a
|
|
718
|
+
// question keeps the usual wrap-up by time.
|
|
719
|
+
const pace = createPace({ depth, model, maxTurns, now: clock, quality: stepBuild ? step.step : null })
|
|
720
|
+
self.pace = pace
|
|
721
|
+
// The loop holds every new space where the kickoff card exists: a plain
|
|
722
|
+
// cost card is refused before it, and the gate holds a space built
|
|
723
|
+
// without it. noLoop is for the checks that predate the loop and test
|
|
724
|
+
// something else with a space request (the cost card, the guard, the
|
|
725
|
+
// language); nothing in the studio passes it.
|
|
726
|
+
const loopOn = byName.has('nw_ask_kickoff') && test.noLoop !== true
|
|
727
|
+
// The frame time last read, with the space it was read on: a reading
|
|
728
|
+
// from before an edit is not the space's (perfNow reads it again).
|
|
729
|
+
let lastPerf = null
|
|
730
|
+
const notePerf = (value) => {
|
|
731
|
+
const found = perfIn(value)
|
|
732
|
+
if (found) lastPerf = { perf: found, fp: gate.fingerprint().catch(() => null) }
|
|
733
|
+
}
|
|
734
|
+
const perfNow = async (ask = rpc) => {
|
|
735
|
+
const fp = await gate.fingerprint().catch(() => null)
|
|
736
|
+
if (lastPerf && (await lastPerf.fp) === fp) return lastPerf.perf
|
|
737
|
+
const fresh = perfIn(await ask('status', {}, 10_000).catch(() => null))
|
|
738
|
+
lastPerf = fresh ? { perf: fresh, fp: Promise.resolve(fp) } : null
|
|
739
|
+
return fresh
|
|
740
|
+
}
|
|
741
|
+
const loopGate = createLoopGate({
|
|
742
|
+
loop,
|
|
743
|
+
fingerprint: () => gate.fingerprint(),
|
|
744
|
+
perfNow: () => perfNow(),
|
|
745
|
+
capacityNow: () => (test.capacity ? test.capacity(projectRoot) : capacityOf(projectRoot)),
|
|
746
|
+
// A new space built with no kickoff is held until it shows one.
|
|
747
|
+
unkicked: async () => loopOn && depth.space === true && !loop.kickoff && (await gate.changed()),
|
|
748
|
+
// ...and one whose cost card went unanswered, with nothing approved,
|
|
749
|
+
// can build nothing until the creator answers: it is not held.
|
|
750
|
+
waitingOnCost: () => ledger.big() && loop.costUnanswered,
|
|
751
|
+
})
|
|
752
|
+
self.loopGate = loopGate
|
|
753
|
+
/** What the done event says about the loop: where it stood, and what the
|
|
754
|
+
* gate let go with when it stopped holding a loop that was not done. */
|
|
755
|
+
self.loopDone = () => {
|
|
756
|
+
const summary = loop.active ? loop.summary() : null
|
|
757
|
+
const released = loopGate.released
|
|
758
|
+
if (summary) return { loop: { ...summary, ...(released ? { released } : {}) } }
|
|
759
|
+
return released ? { loop: { kickoff: null, released } } : {}
|
|
760
|
+
}
|
|
761
|
+
const syncPace = () => {
|
|
762
|
+
if (pace.loop || !loop.budget) return
|
|
763
|
+
pace.setLoop({ floorMin: loop.budget.timeFloorMin, capMin: loop.budget.timeCapMin, elapsed: () => loop.elapsedMin() })
|
|
764
|
+
}
|
|
765
|
+
if (loop.active) syncPace()
|
|
766
|
+
// The watch is on the replies, in the creator's language; the cards'
|
|
767
|
+
// words are held to the screen language by the card tools (ctx.locale).
|
|
768
|
+
const language = createLanguageWatch({ locale: replyLocale, languageName: replyLanguage, writtenIn: loc?.writtenIn })
|
|
769
|
+
const extra = connectorOptions(msg.connectors)
|
|
770
|
+
self.env = extra.env
|
|
771
|
+
const keys = keyRules(msg.connectors, extra.env)
|
|
772
|
+
for (const name of keys.secret) self.secretNames.add(name)
|
|
773
|
+
const guard = createGuard({
|
|
774
|
+
projectRoot,
|
|
775
|
+
runDir,
|
|
776
|
+
readOnly: [test.pluginDir ?? PLUGIN_DIR, ...SDK_SOURCES, blender.folder],
|
|
777
|
+
deny: [msg.studio?.userData, path.join(os.homedir(), '.claude')],
|
|
778
|
+
devtoolsPorts: msg.studio?.devtoolsPorts ?? [9222, 9229],
|
|
779
|
+
envFile: self.envFile,
|
|
780
|
+
secretNames: () => self.secretNames,
|
|
781
|
+
})
|
|
782
|
+
const consent = createConsent({ saved: msg.settings?.consents, rpc, runId: id, locale: screenLocale })
|
|
783
|
+
|
|
784
|
+
// A build the viewport holds while the creator plays (ran: false) is not
|
|
785
|
+
// what the preview shows, so it is not noted.
|
|
786
|
+
const wrappedRpc = async (method, params, timeoutMs) => {
|
|
787
|
+
// The creator's time over a card is not the loop's working time: an
|
|
788
|
+
// ask card's whole wait, and the part of a screen or computer call
|
|
789
|
+
// spent on its permission card (main.cjs reports it as waitedMs).
|
|
790
|
+
const asked = method === 'ask' || PERMISSION_RPCS.has(method) ? clock() : null
|
|
791
|
+
const r = await rpc(method, params, timeoutMs)
|
|
792
|
+
if (method === 'ask') loop.noteWait(clock() - asked)
|
|
793
|
+
else if (asked !== null && typeof r?.waitedMs === 'number') loop.noteWait(Math.min(r.waitedMs, clock() - asked))
|
|
794
|
+
if (method === 'build' && r?.ok && r.ran !== false) await gate.noteBuilt()
|
|
795
|
+
if (method === 'status') notePerf(r)
|
|
796
|
+
return r
|
|
797
|
+
}
|
|
798
|
+
// What every tool handler gets. web is the host's one consent (asked
|
|
799
|
+
// once, saved); secret reads a connector's key by its variable for the
|
|
800
|
+
// asset tools' own requests, only the names the key rules know, and
|
|
801
|
+
// never reaches the model.
|
|
802
|
+
const ctx = {
|
|
803
|
+
runId: id,
|
|
804
|
+
projectRoot,
|
|
805
|
+
runDir,
|
|
806
|
+
// The screen language: the cards the tools ask are drawn in it, and
|
|
807
|
+
// the words the agent writes on them are held to it.
|
|
808
|
+
locale: screenLocale,
|
|
809
|
+
// This message's pictures, for nw_reference's board (first, and marked).
|
|
810
|
+
attached: fresh,
|
|
811
|
+
rpc: wrappedRpc,
|
|
812
|
+
ledger,
|
|
813
|
+
web: () => consent.web(),
|
|
814
|
+
// Codex's consent, asked once on the host's card and saved, the
|
|
815
|
+
// first time image_generate would run it.
|
|
816
|
+
codex: () => consent.codex(),
|
|
817
|
+
// Whether the creator allowed Codex, without asking (nw_ask_targets' "no targets").
|
|
818
|
+
codexState: () => consent.codexState(),
|
|
819
|
+
secret: (name) => (self.secretNames.has(name) && typeof self.env?.[name] === 'string' ? self.env[name] : undefined),
|
|
820
|
+
host: 'studio',
|
|
821
|
+
version: STUDIO_VERSION,
|
|
822
|
+
run: {
|
|
823
|
+
needsBuild: () => gate.needsBuild(),
|
|
824
|
+
record: async (kind) => {
|
|
825
|
+
// A check counts for the pace only once the game has changed.
|
|
826
|
+
if (kind === 'check') pace.noteCheck({ changed: await gate.changed().catch(() => false) })
|
|
827
|
+
return gate.record(kind)
|
|
828
|
+
},
|
|
829
|
+
// The space as it is now, for a round's record; the frame time a
|
|
830
|
+
// tool or the status brought (the loop's gate and approval card).
|
|
831
|
+
fingerprint: () => gate.fingerprint(),
|
|
832
|
+
notePerf,
|
|
833
|
+
perf: () => perfNow(wrappedRpc),
|
|
834
|
+
},
|
|
835
|
+
// The reference loop's tools (tools/loop.mjs): its state, the model's
|
|
836
|
+
// price card for the kickoff's estimate, which second judge has a key,
|
|
837
|
+
// a chat message of the run's own (the round), and the judge, which
|
|
838
|
+
// runClaude and runOther set for their runtime. quality: the step the
|
|
839
|
+
// request runs at (the kickoff then asks no level), or null.
|
|
840
|
+
loop,
|
|
841
|
+
quality,
|
|
842
|
+
model: { id: model.id, name: model.name, pricing: pricingFor(model) },
|
|
843
|
+
get judgeKeys() {
|
|
844
|
+
return { openai: typeof self.env?.[openaiKeyVar()] === 'string' && !!self.env[openaiKeyVar()] && self.secretNames.has(openaiKeyVar()) }
|
|
845
|
+
},
|
|
846
|
+
post: (event) => send({ ...event, id }),
|
|
847
|
+
judge: null,
|
|
848
|
+
// A check's stand-in for the network, for the tools that fetch (assets/net.mjs fetchOf).
|
|
849
|
+
...(test.fetch ? { fetch: test.fetch } : {}),
|
|
850
|
+
log,
|
|
851
|
+
}
|
|
852
|
+
// Bash is read-only when its whole command line only reads (ls, cat,
|
|
853
|
+
// git log): a big job may look around before its cost is approved.
|
|
854
|
+
const readOnlyTool = (name, input) => {
|
|
855
|
+
if (name === 'Bash') return readOnlyCommand(input?.command)
|
|
856
|
+
const short = name.replace(/^mcp__nw__/, '')
|
|
857
|
+
// A paid generation's estimate spends nothing and is what the cost
|
|
858
|
+
// card is made from; its submit is the call that spends.
|
|
859
|
+
if (short === 'asset_generate' || short === 'image_generate' || short === 'environment_generate') return input?.action === 'estimate'
|
|
860
|
+
return READ_ONLY_TOOLS.has(name) || (name !== short && READ_ONLY_TOOLS.has(short)) || byName.get(short)?.readOnly === true
|
|
861
|
+
}
|
|
862
|
+
let lastCost = 0
|
|
863
|
+
const sendCost = (force) => {
|
|
864
|
+
const now = Date.now()
|
|
865
|
+
if (!force && now - lastCost < COST_EVERY_MS) return
|
|
866
|
+
lastCost = now
|
|
867
|
+
const { helperUsd, generationUsd } = ledger.breakdown()
|
|
868
|
+
send({ type: 'cost', id, usd: ledger.spentUsd(), approvedUsd: ledger.approvedUsd(), helperUsd, generationUsd })
|
|
869
|
+
}
|
|
870
|
+
/** The notes for the main agent's next tool result: the spend, the
|
|
871
|
+
* creator's language, the time and the steps. */
|
|
872
|
+
// The order for a space, said once if the build starts before the brief.
|
|
873
|
+
const flow = createFlowWatch({ projectRoot, building: depth.space === true, loop })
|
|
874
|
+
// What the creator sent while the run works (agent/notes.cjs, host.note
|
|
875
|
+
// below): handed over in the main agent's next tool result, never
|
|
876
|
+
// stopping the run. In a space's loop it is also the next round's first
|
|
877
|
+
// gap (host.note gives it to loop.addNote), and the agent hears so.
|
|
878
|
+
const creatorSaid = () => {
|
|
879
|
+
const said = self.notes?.take()
|
|
880
|
+
if (!said) return null
|
|
881
|
+
return loop.active ? `${said}\n\nIn this space's reference loop it is also the first gap of your next round (nw_round lists it first): change the space for it.` : said
|
|
882
|
+
}
|
|
883
|
+
self.creatorSaid = creatorSaid
|
|
884
|
+
// The creator's own words, sent while it works, come first.
|
|
885
|
+
const notesNow = () => {
|
|
886
|
+
syncPace()
|
|
887
|
+
return [creatorSaid(), ledger.reminder(), language.note(), flow.note(), pace.notes()].filter(Boolean).join('\n\n') || null
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// A new space sent from the studio's composer at a quality step:
|
|
891
|
+
// sending it is the cost approval, for that step's upper estimate. Only
|
|
892
|
+
// the composer's message says so (main.cjs); oda make approves with
|
|
893
|
+
// --approve-cost alone.
|
|
894
|
+
if (step && msg.qualityApproval === true && loopOn && depth.space === true && !loop.active && !isContinuation(text)) {
|
|
895
|
+
const second = ctx.judgeKeys.openai ? openaiJudgeModel() : null
|
|
896
|
+
const est = estimateQuality(quality, { pricing: pricingFor(model), judge: second ? pricingFor(second.model) : null, targetUsd: targetPrice() })
|
|
897
|
+
if (est.usd) {
|
|
898
|
+
ledger.approve(est.usd.hi)
|
|
899
|
+
log(`[agent] quality ${quality}: sending approved up to $${est.usd.hi.toFixed(2)}`)
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
const context = studioContext({
|
|
904
|
+
// A new space with no kickoff yet: the context names the kickoff as its ask.
|
|
905
|
+
// An agent app has none of the studio's own cards (the kickoff, the
|
|
906
|
+
// cost, the rounds): its context names none of them.
|
|
907
|
+
depth: { ...depth, big: msg.app ? false : big, kickoff: !msg.app && loopOn && depth.space === true && !loop.kickoff },
|
|
908
|
+
locale: replyLocale,
|
|
909
|
+
languageName: replyLanguage,
|
|
910
|
+
screenLocale,
|
|
911
|
+
screenLanguage,
|
|
912
|
+
model: { name: model.name, price: Array.isArray(model.price) ? model.price : null, pricing: pricingFor(model) },
|
|
913
|
+
mode: msg.mode,
|
|
914
|
+
references,
|
|
915
|
+
board: board ? { root: projectRoot, pictures: board.pictures, more: board.more, inline: inline.length } : null,
|
|
916
|
+
connectors: { services: msg.connectors?.services ?? [], available: msg.connectors?.available ?? [] },
|
|
917
|
+
web: consent.state(),
|
|
918
|
+
blender: blender.info,
|
|
919
|
+
runDir,
|
|
920
|
+
pace: { minutes: pace.usualMinutes, maxTurns },
|
|
921
|
+
starter: await starterPlaceholders(projectRoot),
|
|
922
|
+
sdkSources: SDK_SOURCES,
|
|
923
|
+
loop: !msg.app && loop.active ? loop.summary() : null,
|
|
924
|
+
quality: step && !msg.app
|
|
925
|
+
? {
|
|
926
|
+
step: step.step,
|
|
927
|
+
name: step.name,
|
|
928
|
+
approvedUsd: ledger.approvedUsd(),
|
|
929
|
+
timeCapMin: step.timeCapMin,
|
|
930
|
+
roundCap: step.roundCap,
|
|
931
|
+
minRounds: step.minRounds,
|
|
932
|
+
bar: step.bar,
|
|
933
|
+
// What a loop that is going on has left of them (a "continue").
|
|
934
|
+
timeLeftMin: loop.active && loop.budget ? Math.max(0, Math.round(loop.remainingMin() ?? step.timeCapMin)) : step.timeCapMin,
|
|
935
|
+
roundsLeft: loop.active && loop.budget ? Math.max(0, (Number(loop.budget.roundCap) || step.roundCap) - loop.rounds.length) : step.roundCap,
|
|
936
|
+
}
|
|
937
|
+
: null,
|
|
938
|
+
...facts,
|
|
939
|
+
})
|
|
940
|
+
const env = { CLAUDE_AGENT_SDK_CLIENT_APP: `nowhere-studio/${STUDIO_VERSION}` }
|
|
941
|
+
// The zero-context judge (loop/judge.mjs): Claude as a session of its
|
|
942
|
+
// own, and OpenAI too with its key; the lower score stands. Their cost
|
|
943
|
+
// is the request's: the Claude one as a helper's usage, OpenAI's as a
|
|
944
|
+
// generation.
|
|
945
|
+
ctx.judge =
|
|
946
|
+
test.judge ??
|
|
947
|
+
(async ({ pairs, slop, references = [] }) => {
|
|
948
|
+
const verdicts = []
|
|
949
|
+
// The creator's other spaces, so a still that could be taken for
|
|
950
|
+
// one of them is scored down (tools/others.mjs).
|
|
951
|
+
let others = []
|
|
952
|
+
try {
|
|
953
|
+
others = (await otherPictures(await otherSpaces(projectRoot, { limit: JUDGE_OTHERS }), { rpc: ctx.rpc })).map((o) => o.image)
|
|
954
|
+
} catch (err) {
|
|
955
|
+
log(`[loop] the other spaces could not be read for the judge: ${err?.message ?? err}`)
|
|
956
|
+
}
|
|
957
|
+
try {
|
|
958
|
+
verdicts.push(
|
|
959
|
+
await judgeWithClaude({
|
|
960
|
+
query: test.judgeQuery ?? sdkQuery,
|
|
961
|
+
// At a quality step the judge's model is fixed, so a score means the same at every step.
|
|
962
|
+
model: step ? JUDGE_MODEL : provider.runtime === 'claude-agent-sdk' ? model.id : modelFor(null).model.id,
|
|
963
|
+
env: { ...extra.env, ...env, ...(provider.runtime === 'claude-agent-sdk' ? claudeAuth(msg) : {}) },
|
|
964
|
+
cwd: runDir,
|
|
965
|
+
pairs,
|
|
966
|
+
slop,
|
|
967
|
+
others,
|
|
968
|
+
references,
|
|
969
|
+
onUsage: (m) => ledger.addUsage({ ...m, helper: true }),
|
|
970
|
+
}),
|
|
971
|
+
)
|
|
972
|
+
} catch (err) {
|
|
973
|
+
log(`[loop] the Claude judge failed: ${err?.message ?? err}`)
|
|
974
|
+
}
|
|
975
|
+
const key = ctx.secret(openaiKeyVar())
|
|
976
|
+
if (key) {
|
|
977
|
+
try {
|
|
978
|
+
const v = await judgeWithOpenAI({ apiKey: key, pairs, slop, others, references, fetchImpl: test.judgeFetch })
|
|
979
|
+
if (v.usd) ledger.addGeneration(v.usd, 'openai judge')
|
|
980
|
+
verdicts.push(v)
|
|
981
|
+
} catch (err) {
|
|
982
|
+
log(`[loop] the OpenAI judge failed: ${err?.message ?? err}`)
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
return lowerOf(verdicts)
|
|
986
|
+
})
|
|
987
|
+
// askedDepth as the quality step holds it: a production's triage,
|
|
988
|
+
// router and director take their effort from it too.
|
|
989
|
+
const shared = { msg, text, images, inline, flow, provider, model, quality, stepBuild, ceiling, screenLocale, screenLanguage, replyLocale, replyLanguage, depth, askedDepth: capped, emptyProject, references, blender, loc, runDir, defs, byName, ledger, gate, guard, consent, extra, keys, askable, ctx, readOnlyTool, sendCost, notesNow, context, env, self, pace, language, maxTurns, loop, loopGate, loopOn }
|
|
990
|
+
|
|
991
|
+
// A Stop while the request was being set up: nothing was asked of a model yet.
|
|
992
|
+
if (self.cancelled) {
|
|
993
|
+
send({ type: 'error', id, message: 'Stopped before it finished.', failure: 'stopped', unfinished: true, costUsd: 0, turns: 0, cleanup: 'skipped', markers: [] })
|
|
994
|
+
return
|
|
995
|
+
}
|
|
996
|
+
// A team, when the message asks for one and the request needs one.
|
|
997
|
+
if (msg.team === true && !msg.app) {
|
|
998
|
+
const route = await routeOf(shared)
|
|
999
|
+
if (self.cancelled) {
|
|
1000
|
+
send({ type: 'error', id, message: 'Stopped before it finished.', failure: 'stopped', unfinished: true, costUsd: ledger.spentUsd(), turns: 0, cleanup: 'skipped', markers: [] })
|
|
1001
|
+
return
|
|
1002
|
+
}
|
|
1003
|
+
if (route.route !== 'fast') {
|
|
1004
|
+
const team = await runTeam(shared, route)
|
|
1005
|
+
if (team !== null) return team
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
// The creator's own agent app (agentApps.cjs), when that is how this
|
|
1009
|
+
// request is built: the app's agent does the work, not a model of ours.
|
|
1010
|
+
if (msg.app) return await runApp(shared)
|
|
1011
|
+
// Claude through the SDK, every other vendor through agent-loop.mjs.
|
|
1012
|
+
if (provider.runtime !== 'claude-agent-sdk') return await runOther(shared)
|
|
1013
|
+
// A quality step sets the effort: no raise after a cost approval.
|
|
1014
|
+
if (!step) escalate = makeEscalation(self, pace, log)
|
|
1015
|
+
return await runClaude(shared)
|
|
1016
|
+
} catch (err) {
|
|
1017
|
+
send({ type: 'error', id, message: err?.message ?? String(err), failure: 'other', unfinished: true, cleanup: 'skipped', markers: [] })
|
|
1018
|
+
} finally {
|
|
1019
|
+
// Nothing of the request outlives it; the loop's minutes are kept.
|
|
1020
|
+
await self.loop?.save().catch(() => {})
|
|
1021
|
+
self.stopTap?.()
|
|
1022
|
+
if (runDir) await fsp.rm(runDir, { recursive: true, force: true }).catch(() => {})
|
|
1023
|
+
await fsp.rm(self.envFile, { force: true }).catch(() => {})
|
|
1024
|
+
await fsp.rmdir(HOST_DIR).catch(() => {}) // only when no other run's file is in it
|
|
1025
|
+
// What the creator sent that the run never got to goes back to the
|
|
1026
|
+
// chat, which sends it as the next message.
|
|
1027
|
+
const left = self.notes?.drain() ?? []
|
|
1028
|
+
self.notes = null
|
|
1029
|
+
if (left.length) send({ type: 'note', id, noteIds: left, state: 'returned' })
|
|
1030
|
+
if (active === self) active = null
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
// ------------------------------------------------------------ the team
|
|
1035
|
+
|
|
1036
|
+
/** The parts of a production the host wires: the team's ledger (the
|
|
1037
|
+
* triage's call is its first), the sessions the triage runs on. */
|
|
1038
|
+
function teamBase(s) {
|
|
1039
|
+
const { msg, ledger, guard, extra, runDir } = s
|
|
1040
|
+
Object.assign(s.env, claudeAuth(msg))
|
|
1041
|
+
s.teamLedger ??= createTeamLedger()
|
|
1042
|
+
const pluginDir = test.pluginDir ?? PLUGIN_DIR
|
|
1043
|
+
// The triage is booked in both ledgers: the host's, should the request go
|
|
1044
|
+
// the fast way, and the team's, should it become a production.
|
|
1045
|
+
const both = {
|
|
1046
|
+
session(spec) {
|
|
1047
|
+
const book = s.teamLedger.session(spec)
|
|
1048
|
+
return { ...book, addUsage: (m) => (ledger.addUsage(m), book.addUsage(m)), addStreamEvent: (m) => (ledger.addStreamEvent(m), book.addStreamEvent(m)) }
|
|
1049
|
+
},
|
|
1050
|
+
}
|
|
1051
|
+
s.teamSessions ??= createSessions({ query: sdkQuery, send, log, ledger: both, projectRoot: msg.projectRoot, runDir, runId: msg.id, childEnv: { ...extra.env, ...s.env }, guard, pluginDir, withPlugin: pluginReady(pluginDir) })
|
|
1052
|
+
return s
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
/** fast, production or resume, with why (director/triage.mjs). */
|
|
1056
|
+
async function routeOf(s) {
|
|
1057
|
+
const { msg, provider, askedDepth, emptyProject, images, self, ceiling } = s
|
|
1058
|
+
teamBase(s)
|
|
1059
|
+
// A Stop during the triage ends its one session.
|
|
1060
|
+
self.interrupt = () => s.teamSessions.stopAll()
|
|
1061
|
+
const latest = await latestProduction(msg.projectRoot).catch(() => null)
|
|
1062
|
+
const r = await triage({
|
|
1063
|
+
msg: test.route ? { ...msg, route: test.route } : msg,
|
|
1064
|
+
runtime: provider.runtime,
|
|
1065
|
+
depth: askedDepth,
|
|
1066
|
+
emptyProject,
|
|
1067
|
+
latest,
|
|
1068
|
+
images: images.length,
|
|
1069
|
+
decide: s.teamSessions.decide,
|
|
1070
|
+
router: createRouter({ ceiling, depth: askedDepth }),
|
|
1071
|
+
})
|
|
1072
|
+
log(`[director] triage: ${r.route} (${r.why})`)
|
|
1073
|
+
return r
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/** A production; null when this build cannot run one (the roles have not
|
|
1077
|
+
* landed), and the request takes the single-agent path. */
|
|
1078
|
+
async function runTeam(s, route) {
|
|
1079
|
+
const { msg, text, images, screenLocale, screenLanguage, replyLocale, replyLanguage, askedDepth, references, blender, loc, runDir, defs, guard, consent, extra, ctx, self, ceiling } = s
|
|
1080
|
+
const team = test.team?.roles ? { roles: test.team.roles, critic: test.team.critic, roleChecks: test.team.roleChecks ?? {} } : await teamModules(log)
|
|
1081
|
+
if (!team?.roles) {
|
|
1082
|
+
log('[director] the roles are not in this build: the request takes the single-agent path')
|
|
1083
|
+
return null
|
|
1084
|
+
}
|
|
1085
|
+
const pluginDir = test.pluginDir ?? PLUGIN_DIR
|
|
1086
|
+
const settings = msg.settings ?? {}
|
|
1087
|
+
const director = createDirector({
|
|
1088
|
+
query: sdkQuery,
|
|
1089
|
+
rpc,
|
|
1090
|
+
send,
|
|
1091
|
+
log,
|
|
1092
|
+
defs,
|
|
1093
|
+
ctxBase: {
|
|
1094
|
+
runId: msg.id,
|
|
1095
|
+
projectRoot: msg.projectRoot,
|
|
1096
|
+
runDir,
|
|
1097
|
+
// The production's cards, board and vision in the screen language,
|
|
1098
|
+
// its report (the chat reply) in the creator's.
|
|
1099
|
+
locale: screenLocale,
|
|
1100
|
+
languageName: screenLanguage,
|
|
1101
|
+
replyLocale,
|
|
1102
|
+
replyLanguage,
|
|
1103
|
+
web: () => consent.web(),
|
|
1104
|
+
webState: consent.state(),
|
|
1105
|
+
codex: () => consent.codex(),
|
|
1106
|
+
codexState: () => consent.codexState(),
|
|
1107
|
+
secret: ctx.secret,
|
|
1108
|
+
host: 'studio',
|
|
1109
|
+
version: STUDIO_VERSION,
|
|
1110
|
+
log,
|
|
1111
|
+
},
|
|
1112
|
+
guard,
|
|
1113
|
+
childEnv: { ...extra.env, ...s.env },
|
|
1114
|
+
pluginDir,
|
|
1115
|
+
withPlugin: pluginReady(pluginDir),
|
|
1116
|
+
roles: team.roles,
|
|
1117
|
+
critic: team.critic,
|
|
1118
|
+
roleChecks: team.roleChecks,
|
|
1119
|
+
settings: { declinePaid: settings.declinePaid === true, ceiling, vision: settings.vision ?? null, ...(Number.isInteger(settings.maxSessions) ? { maxSessions: settings.maxSessions } : {}) },
|
|
1120
|
+
depth: askedDepth,
|
|
1121
|
+
blender: {
|
|
1122
|
+
info: blender.info ?? null,
|
|
1123
|
+
find: async () => (await blenderInfo(log)).info ?? null,
|
|
1124
|
+
stopAll: () => import('./blender/run.mjs').then((m) => m.stopAll?.()).catch(() => {}),
|
|
1125
|
+
},
|
|
1126
|
+
codex: { find: () => codexInfo(log) },
|
|
1127
|
+
ledger: s.teamLedger,
|
|
1128
|
+
writtenIn: loc?.writtenIn ?? null,
|
|
1129
|
+
...(test.team ?? {}),
|
|
1130
|
+
})
|
|
1131
|
+
self.interrupt = () => director.stop('stopped')
|
|
1132
|
+
self.director = director
|
|
1133
|
+
// A Stop while the roles were loading reached only the triage's sessions:
|
|
1134
|
+
// the production stops as soon as it starts.
|
|
1135
|
+
if (self.cancelled) await director.stop('stopped')
|
|
1136
|
+
const outcome = await director.run({ msg, request: { text, images, references }, resume: route.route === 'resume' ? route.productionId : null })
|
|
1137
|
+
log(`[director] ${outcome.productionId}: ${outcome.status}`)
|
|
1138
|
+
return outcome
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
/** Sets the running session's effort; never breaks the run. */
|
|
1142
|
+
function applyEffort(self, effort, why, logLine) {
|
|
1143
|
+
if (!self.session?.applyFlagSettings) return
|
|
1144
|
+
try {
|
|
1145
|
+
self.session
|
|
1146
|
+
.applyFlagSettings({ effortLevel: effort })
|
|
1147
|
+
.then(() => logLine(`[agent] effort set to ${effort} ${why}`))
|
|
1148
|
+
.catch((err) => logLine(`[agent] effort could not be set to ${effort}: ${err?.message ?? err}`))
|
|
1149
|
+
} catch (err) {
|
|
1150
|
+
logLine(`[agent] effort could not be set to ${effort}: ${err?.message ?? err}`)
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/** Effort goes up to xhigh (or the model's ceiling, pace.raise), once,
|
|
1155
|
+
* when the creator approves a cost on a request that started lower. */
|
|
1156
|
+
function makeEscalation(self, pace, logLine) {
|
|
1157
|
+
let done = false
|
|
1158
|
+
return () => {
|
|
1159
|
+
if (done || !self.session?.applyFlagSettings) return
|
|
1160
|
+
done = true
|
|
1161
|
+
const to = pace.raise('xhigh')
|
|
1162
|
+
if (to) applyEffort(self, to, '(raised after the cost approval)', logLine)
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// ------------------------------------------------------------ Claude
|
|
1167
|
+
|
|
1168
|
+
/** Puts back the debug code an unfinished request left in the game
|
|
1169
|
+
* (stopGate revertProbes): no model is needed, so it happens whatever
|
|
1170
|
+
* ended the request. The lines, as "file:line", for the event that
|
|
1171
|
+
* says it ended. */
|
|
1172
|
+
async function putProbesBack(gate) {
|
|
1173
|
+
try {
|
|
1174
|
+
const back = await gate.revertProbes()
|
|
1175
|
+
if (back.length) log(`[agent] put back the debug code the request left: ${back.join(', ')}`)
|
|
1176
|
+
return back
|
|
1177
|
+
} catch (err) {
|
|
1178
|
+
log(`[agent] the debug code could not be put back: ${err?.message ?? err}`)
|
|
1179
|
+
return []
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
async function runClaude(s) {
|
|
1184
|
+
const { msg, text, inline, flow, model, screenLocale, replyLanguage, depth, runDir, defs, byName, ledger, gate, guard, consent, extra, keys, askable, ctx, readOnlyTool, sendCost, notesNow, context, self, pace, language, maxTurns, loop, loopGate } = s
|
|
1185
|
+
const { id, projectRoot } = msg
|
|
1186
|
+
const pluginDir = test.pluginDir ?? PLUGIN_DIR
|
|
1187
|
+
const withPlugin = pluginReady(pluginDir)
|
|
1188
|
+
Object.assign(s.env, claudeAuth(msg))
|
|
1189
|
+
|
|
1190
|
+
// The project's own session, if the SDK still has it and it was started
|
|
1191
|
+
// under this prompt; otherwise a fresh one that is told the recent messages.
|
|
1192
|
+
const record = msg.resume && typeof msg.resume === 'object' ? msg.resume : typeof msg.resume === 'string' ? { id: msg.resume, promptHash: null } : null
|
|
1193
|
+
const resume = record && sessionKept(record.id, projectRoot) && record.promptHash === PROMPT_HASH ? record.id : null
|
|
1194
|
+
|
|
1195
|
+
// The session's transcripts, the helpers' too, read as they grow: the
|
|
1196
|
+
// final usage of every call, which the stream does not always show.
|
|
1197
|
+
const tap = createTranscriptTap({
|
|
1198
|
+
dir: sessionDir(projectRoot),
|
|
1199
|
+
onLine: (line, _file, helper) => {
|
|
1200
|
+
if (line?.type === 'assistant') ledger.addUsage(helper ? { ...line, helper: true } : line)
|
|
1201
|
+
},
|
|
1202
|
+
})
|
|
1203
|
+
if (resume) tap.mark(resume)
|
|
1204
|
+
let tapping = true
|
|
1205
|
+
const tapTimer = setInterval(() => void tap.poll().then(() => tapping && sendCost(false)), TRANSCRIPT_EVERY_MS)
|
|
1206
|
+
tapTimer.unref?.()
|
|
1207
|
+
// After the last read nothing more is sent: the done or error event has the figure.
|
|
1208
|
+
self.stopTap = () => {
|
|
1209
|
+
tapping = false
|
|
1210
|
+
clearInterval(tapTimer)
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// The cleanup turn only tidies up, so the spend gate does not hold it back.
|
|
1214
|
+
let inCleanup = false
|
|
1215
|
+
const preToolUse = async (input) => {
|
|
1216
|
+
const name = input.tool_name
|
|
1217
|
+
const toolInput = input.tool_input ?? {}
|
|
1218
|
+
const short = name.replace(/^mcp__nw__/, '')
|
|
1219
|
+
const deny = (reason) => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } })
|
|
1220
|
+
// 1. Helpers stay off the creator's things.
|
|
1221
|
+
if (input.agent_id) {
|
|
1222
|
+
if (/^mcp__nw__(computer|computer_apps|nw_capture_screen|browser.*|nw_ask)$/.test(name) || name === 'Agent' || (name !== short && byName.get(short)?.mainOnly)) {
|
|
1223
|
+
return deny(HELPER_REASON)
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
// 2. Paths and commands.
|
|
1227
|
+
const fenced = guard.check(name, toolInput)
|
|
1228
|
+
if (!fenced.ok) return deny(fenced.reason)
|
|
1229
|
+
// The plan's five-hour window: a step held a little when the work
|
|
1230
|
+
// would use it up before it resets (pace.mjs holdMs).
|
|
1231
|
+
pace.toolStarted()
|
|
1232
|
+
const hold = inCleanup ? 0 : pace.holdMs()
|
|
1233
|
+
if (hold > 0) await holdFor(hold, () => self.cancelled)
|
|
1234
|
+
// 3. A big job waits for its cost approval, and a paid generation call
|
|
1235
|
+
// for one in any request: a card appears before anything is charged.
|
|
1236
|
+
// A new space asks it on its kickoff card.
|
|
1237
|
+
const paid = inCleanup ? { ok: true } : ledger.gate(name, readOnlyTool(name, toolInput))
|
|
1238
|
+
if (!paid.ok) return deny(depth.space && !loop.kickoff && byName.has('nw_ask_kickoff') && paid.reason === BIG_REASON ? `${paid.reason}${KICKOFF_IS_THE_ASK}` : paid.reason)
|
|
1239
|
+
// A new space asks its cost on the kickoff card, not a plain cost card.
|
|
1240
|
+
if (s.loopOn && depth.space && !loop.kickoff && short === 'nw_ask' && toolInput?.kind === 'cost') return deny(KICKOFF_NOT_COST)
|
|
1241
|
+
// The targets before the brief, once a loop's kickoff stands: for the
|
|
1242
|
+
// helpers too, whose writes are the request's as much.
|
|
1243
|
+
if (loop.active && !loop.targets.settled && writesBrief(msg.projectRoot, name, toolInput)) return deny(TARGETS_FIRST)
|
|
1244
|
+
const paidVar = name === 'Bash' && askable && !inCleanup && ledger.approvedUsd() === null ? keys.paidVar(toolInput.command) : null
|
|
1245
|
+
if (paidVar) return deny(paidReason(paidVar, !!input.agent_id))
|
|
1246
|
+
// 4. The web, once the creator allowed it: search, fetch, and a Bash
|
|
1247
|
+
// command that reaches past the connected services. Asked here and not
|
|
1248
|
+
// only in canUseTool: the rewrite below allows the call, which may skip
|
|
1249
|
+
// the permission callback.
|
|
1250
|
+
if (name === 'WebSearch' || name === 'WebFetch' || (name === 'Bash' && keys.needsWeb(toolInput.command))) {
|
|
1251
|
+
if ((await consent.web()) !== 'allow') return deny(NO_WEB)
|
|
1252
|
+
}
|
|
1253
|
+
// 5. Rewrites.
|
|
1254
|
+
const allow = (updatedInput) => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', updatedInput } })
|
|
1255
|
+
// The main agent's next step needs the helper's answer, and a run whose
|
|
1256
|
+
// input has closed may lose a background helper.
|
|
1257
|
+
if (name === 'Agent') return allow({ ...toolInput, run_in_background: false })
|
|
1258
|
+
if (name === 'WebSearch') {
|
|
1259
|
+
const search = webSearchInput(toolInput)
|
|
1260
|
+
return search.deny ? deny(search.deny) : allow(search.input)
|
|
1261
|
+
}
|
|
1262
|
+
if (name === 'Bash' && typeof toolInput.command === 'string' && fs.existsSync(self.envFile)) {
|
|
1263
|
+
return allow({ ...toolInput, command: `. ${quote(self.envFile)} && ${toolInput.command}` })
|
|
1264
|
+
}
|
|
1265
|
+
return {}
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
const postToolUse = async (input) => {
|
|
1269
|
+
if (input.tool_name === 'mcp__nw__nw_ask') consent.set(webAnswerOf(input.tool_input, resultText(input.tool_response)))
|
|
1270
|
+
if (EDITS.has(input.tool_name)) {
|
|
1271
|
+
pace.noteEdit()
|
|
1272
|
+
flow.noteEdit(input.tool_name, input.tool_input)
|
|
1273
|
+
}
|
|
1274
|
+
// The notes are for the main agent, the one that may ask and that the
|
|
1275
|
+
// creator reads; a helper's call must not use them up.
|
|
1276
|
+
if (input.agent_id || inCleanup) return {}
|
|
1277
|
+
const note = notesNow()
|
|
1278
|
+
return note ? { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: note } } : {}
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
const stopHook = async (input) => {
|
|
1282
|
+
if (input.agent_id) return {}
|
|
1283
|
+
// A message from the creator that came after the last tool: the run
|
|
1284
|
+
// goes on to take it in rather than end without it.
|
|
1285
|
+
const said = inCleanup ? null : self.creatorSaid?.()
|
|
1286
|
+
if (said) return { decision: 'block', reason: said }
|
|
1287
|
+
// The studio's own gate first (a check and a look, no debug code, the
|
|
1288
|
+
// brief), then the reference loop's (loop/gate.mjs).
|
|
1289
|
+
const reason = (await gate.stopReason({ max: 2 })) ?? (await loopGate.stopReason())
|
|
1290
|
+
if (reason) return { decision: 'block', reason }
|
|
1291
|
+
// A last reply in another language than the creator's is sent back once.
|
|
1292
|
+
const again = language.finalReason(input.last_assistant_message)
|
|
1293
|
+
return again ? { decision: 'block', reason: again } : {}
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
const canUseTool = async (toolName, input) => {
|
|
1297
|
+
const fenced = guard.check(toolName, input)
|
|
1298
|
+
if (!fenced.ok) return { behavior: 'deny', message: fenced.reason }
|
|
1299
|
+
if ((toolName === 'WebSearch' || toolName === 'WebFetch') && (await consent.web()) !== 'allow') return { behavior: 'deny', message: NO_WEB }
|
|
1300
|
+
return { behavior: 'allow' }
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
const baseOptions = (toolDefs, builtIns) => ({
|
|
1304
|
+
cwd: projectRoot,
|
|
1305
|
+
model: model.id,
|
|
1306
|
+
tools: builtIns,
|
|
1307
|
+
mcpServers: {
|
|
1308
|
+
nw: createSdkMcpServer({ name: 'nw', version: '0.3.0', instructions: MCP_INSTRUCTIONS, alwaysLoad: true, tools: toolDefs.map((d) => toSdkTool(d, () => ctx)) }),
|
|
1309
|
+
...extra.mcpServers,
|
|
1310
|
+
},
|
|
1311
|
+
// Path checks run in the PreToolUse hook for every tool; Read, Write and
|
|
1312
|
+
// Edit also stay out of allowedTools so canUseTool checks them a second
|
|
1313
|
+
// time. WebSearch and WebFetch stay out too: the hook asks for the web
|
|
1314
|
+
// consent and canUseTool checks it again.
|
|
1315
|
+
allowedTools: ['Glob', 'Grep', 'TodoWrite', 'Skill', 'Agent', ...(HAS_BASH ? ['Bash'] : []), 'mcp__nw__*', ...extra.allowedTools],
|
|
1316
|
+
permissionMode: 'default',
|
|
1317
|
+
env: {
|
|
1318
|
+
...extra.env,
|
|
1319
|
+
...s.env,
|
|
1320
|
+
// TodoWrite, the plain to-do list, rather than the Task tools: in this
|
|
1321
|
+
// CLI it is offered only with both switches (TodoWrite's isEnabled is
|
|
1322
|
+
// "tasks off and todo tools on").
|
|
1323
|
+
CLAUDE_CODE_ENABLE_TODO_TOOLS: '1',
|
|
1324
|
+
CLAUDE_CODE_ENABLE_TASKS: '0',
|
|
1325
|
+
// The helpers are the two below; the CLI's own (general-purpose,
|
|
1326
|
+
// Explore, a guide to another product) are not this studio's.
|
|
1327
|
+
CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS: '1',
|
|
1328
|
+
},
|
|
1329
|
+
systemPrompt: { type: 'custom', prompt: SYSTEM_PROMPT, snapshot: true },
|
|
1330
|
+
// No helper deeper than the model's effort ceiling; for a build at a
|
|
1331
|
+
// quality step the helpers' efforts follow the step (a tweak or a
|
|
1332
|
+
// question keeps them as they are).
|
|
1333
|
+
agents: subagentsFor(withPlugin, model, s.stepBuild ? (s.quality ?? null) : null),
|
|
1334
|
+
// Only the studio's skills: without the plugin, none (the creator's own
|
|
1335
|
+
// ~/.claude skills are not this agent's).
|
|
1336
|
+
...(withPlugin ? { plugins: [{ type: 'local', path: pluginDir, skipMcpDiscovery: true }], skills: SKILL_NAMES } : { skills: [] }),
|
|
1337
|
+
...(model.thinking === 'adaptive' ? { thinking: { type: 'adaptive' } } : {}),
|
|
1338
|
+
includePartialMessages: true,
|
|
1339
|
+
// The user's own ~/.claude settings must not widen what this agent may do.
|
|
1340
|
+
settingSources: [],
|
|
1341
|
+
strictMcpConfig: true,
|
|
1342
|
+
additionalDirectories: [runDir, ...SDK_SOURCES, ...(withPlugin ? [pluginDir] : [])],
|
|
1343
|
+
canUseTool,
|
|
1344
|
+
})
|
|
1345
|
+
|
|
1346
|
+
const seenTools = new Map()
|
|
1347
|
+
const mainMessages = new Set()
|
|
1348
|
+
/** Streams one query into the chat; returns its result message. */
|
|
1349
|
+
async function consume(session, onInit) {
|
|
1350
|
+
let result = null
|
|
1351
|
+
for await (const m of session) {
|
|
1352
|
+
if (m.type === 'system' && m.subtype === 'init') onInit?.(m)
|
|
1353
|
+
else if (m.type === 'system' && m.subtype === 'thinking_tokens') pace.thinking({ estimateDelta: m.estimated_tokens_delta })
|
|
1354
|
+
// The plan's window as the CLI last read it (subscriptions only).
|
|
1355
|
+
else if (m.type === 'rate_limit_event') pace.rateLimit(m.rate_limit_info)
|
|
1356
|
+
else if (m.type === 'stream_event') {
|
|
1357
|
+
// Every call's usage, a helper's included: its prompt at the start,
|
|
1358
|
+
// its whole output at the end.
|
|
1359
|
+
ledger.addStreamEvent(m)
|
|
1360
|
+
// A helper's own words are its report to the main agent, not the chat.
|
|
1361
|
+
if (m.parent_tool_use_id) continue
|
|
1362
|
+
const ev = m.event
|
|
1363
|
+
if (ev?.type === 'message_start') pace.callStarted()
|
|
1364
|
+
else if (ev?.type === 'message_delta') {
|
|
1365
|
+
pace.thinking({ tokens: ev.usage?.output_tokens_details?.thinking_tokens })
|
|
1366
|
+
sendCost(false)
|
|
1367
|
+
} else if (ev?.type === 'message_stop') {
|
|
1368
|
+
// A step that thought past the model's limit lowers the effort for the next ones.
|
|
1369
|
+
const lower = pace.callEnded()
|
|
1370
|
+
if (lower && !inCleanup) applyEffort(self, lower, '(a step thought past the model\'s limit)', log)
|
|
1371
|
+
}
|
|
1372
|
+
if (ev?.type === 'content_block_delta' && ev.delta?.type === 'text_delta') {
|
|
1373
|
+
language.text(ev.delta.text)
|
|
1374
|
+
send({ type: 'text', id, delta: ev.delta.text })
|
|
1375
|
+
}
|
|
1376
|
+
} else if (m.type === 'assistant') {
|
|
1377
|
+
ledger.addUsage(m)
|
|
1378
|
+
sendCost(false)
|
|
1379
|
+
if (!m.parent_tool_use_id && m.message?.id) mainMessages.add(m.message.id)
|
|
1380
|
+
for (const block of m.message?.content ?? []) {
|
|
1381
|
+
if (block.type !== 'tool_use') continue
|
|
1382
|
+
seenTools.set(block.id, block.name)
|
|
1383
|
+
send({ type: 'tool', id, toolId: block.id, name: block.name, input: block.input })
|
|
1384
|
+
}
|
|
1385
|
+
} else if (m.type === 'user') {
|
|
1386
|
+
for (const block of m.message?.content ?? []) {
|
|
1387
|
+
if (block.type !== 'tool_result') continue
|
|
1388
|
+
send({ type: 'tool-result', id, toolId: block.tool_use_id, name: seenTools.get(block.tool_use_id) ?? 'tool', isError: block.is_error === true })
|
|
1389
|
+
}
|
|
1390
|
+
} else if (m.type === 'result') result = m
|
|
1391
|
+
}
|
|
1392
|
+
return result
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
let sessionId = null
|
|
1396
|
+
let started = false
|
|
1397
|
+
const onInit = (m) => {
|
|
1398
|
+
sessionId = m.session_id ?? sessionId
|
|
1399
|
+
tap.follow(sessionId)
|
|
1400
|
+
log(`[agent] init model=${m.model} effort=${depth.effort} (${depth.reason}) tools=${(m.tools ?? []).join(',')}`)
|
|
1401
|
+
if (started) return
|
|
1402
|
+
started = true
|
|
1403
|
+
// locale: the screen language, which the chat draws this request's card in.
|
|
1404
|
+
send({ type: 'started', id, sessionId: m.session_id, model: m.model, promptHash: PROMPT_HASH, effort: depth.effort, depthReason: depth.reason, locale: screenLocale })
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
const session = sdkQuery({
|
|
1408
|
+
prompt: promptFor(context + (resume ? '' : historyPreamble(msg.history)) + describeSelection(msg.attachment) + text, inline),
|
|
1409
|
+
options: {
|
|
1410
|
+
...baseOptions(defs, AGENT_TOOLS),
|
|
1411
|
+
...(resume ? { resume } : {}),
|
|
1412
|
+
effort: depth.effort,
|
|
1413
|
+
maxTurns,
|
|
1414
|
+
hooks: { PreToolUse: [{ hooks: [preToolUse] }], PostToolUse: [{ hooks: [postToolUse] }], Stop: [{ hooks: [stopHook] }] },
|
|
1415
|
+
},
|
|
1416
|
+
})
|
|
1417
|
+
self.session = session
|
|
1418
|
+
self.interrupt = () => session.interrupt()
|
|
1419
|
+
|
|
1420
|
+
let result = null
|
|
1421
|
+
let thrown = null
|
|
1422
|
+
try {
|
|
1423
|
+
result = await consume(session, onInit)
|
|
1424
|
+
} catch (err) {
|
|
1425
|
+
// The SDK also throws after an error result; the result says more.
|
|
1426
|
+
thrown = err
|
|
1427
|
+
}
|
|
1428
|
+
/** The last of the transcripts, then what the SDK's own totals add. */
|
|
1429
|
+
const settle = async (r) => {
|
|
1430
|
+
await tap.poll().catch(() => {})
|
|
1431
|
+
ledger.reconcile(r, !resume)
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
// A refused request comes back as a "success" whose is_error is set and
|
|
1435
|
+
// whose text is Anthropic's reason (2026-10-13: an empty account showed a
|
|
1436
|
+
// green Done and nothing else). That is a failure, said in words the
|
|
1437
|
+
// creator can act on.
|
|
1438
|
+
if (result && !result.is_error && result.subtype === 'success') {
|
|
1439
|
+
self.stopTap()
|
|
1440
|
+
await settle(result)
|
|
1441
|
+
sendCost(true)
|
|
1442
|
+
send({
|
|
1443
|
+
type: 'done',
|
|
1444
|
+
id,
|
|
1445
|
+
subtype: result.subtype,
|
|
1446
|
+
costUsd: ledger.spentUsd(),
|
|
1447
|
+
helperUsd: ledger.breakdown().helperUsd,
|
|
1448
|
+
generationUsd: ledger.breakdown().generationUsd,
|
|
1449
|
+
turns: result.num_turns ?? mainMessages.size,
|
|
1450
|
+
effort: depth.effort,
|
|
1451
|
+
verified: await gate.verified(),
|
|
1452
|
+
stopBlocks: gate.blocks + loopGate.blocks,
|
|
1453
|
+
...self.loopDone(),
|
|
1454
|
+
})
|
|
1455
|
+
await loop.save()
|
|
1456
|
+
return
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
// A failed request is cleaned up when it left changes behind, unless the
|
|
1460
|
+
// creator stopped it or the account, the key or a busy API is to blame.
|
|
1461
|
+
const turns = result?.num_turns ?? mainMessages.size
|
|
1462
|
+
// What the run used before the cleanup turn resumes the same session.
|
|
1463
|
+
await settle(result)
|
|
1464
|
+
const failure = result ?? { result: thrown?.message ?? String(thrown ?? '') }
|
|
1465
|
+
// On the creator's Claude login a refused key is that login's: the same
|
|
1466
|
+
// words as Claude Code's own "Not logged in".
|
|
1467
|
+
const refused = failureKind(failure)
|
|
1468
|
+
const kind = msg.login === true && refused === 'key' ? 'login' : refused
|
|
1469
|
+
const message = self.cancelled ? 'Stopped before it finished.' : kind === 'login' ? readableFailure({ result: 'Not logged in' }) : readableFailure(failure)
|
|
1470
|
+
// What kind of failure, for the chat to say it in the screen language.
|
|
1471
|
+
const failureName = self.cancelled ? 'stopped' : kind
|
|
1472
|
+
let cleanup = 'skipped'
|
|
1473
|
+
if (!self.cancelled && !['credit', 'key', 'login', 'busy'].includes(kind) && (await gate.changed())) {
|
|
1474
|
+
send({ type: 'cleanup', id })
|
|
1475
|
+
const reason = kind === 'turns' ? 'it reached the step limit for one request' : message.replace(/\.$/, '')
|
|
1476
|
+
let cleanupBlocks = 0
|
|
1477
|
+
const cleanupStop = async (input) => {
|
|
1478
|
+
if (input.agent_id || cleanupBlocks >= 1) return {}
|
|
1479
|
+
const r = await gate.check({ markersOnly: true })
|
|
1480
|
+
if (r.ok) return {}
|
|
1481
|
+
cleanupBlocks++
|
|
1482
|
+
return { decision: 'block', reason: r.reason }
|
|
1483
|
+
}
|
|
1484
|
+
inCleanup = true
|
|
1485
|
+
try {
|
|
1486
|
+
const turn = sdkQuery({
|
|
1487
|
+
prompt: promptFor(sessionId ? CLEANUP_PROMPT(reason, replyLanguage) : historyPreamble(msg.history) + text + '\n\n' + CLEANUP_PROMPT(reason, replyLanguage), []),
|
|
1488
|
+
options: {
|
|
1489
|
+
...baseOptions(defs.filter(cleanupDef), AGENT_TOOLS.filter((t) => !CLEANUP_DROPS.has(t))),
|
|
1490
|
+
...(sessionId ? { resume: sessionId } : {}),
|
|
1491
|
+
effort: 'low',
|
|
1492
|
+
maxTurns: test.cleanupMaxTurns ?? 8,
|
|
1493
|
+
hooks: { PreToolUse: [{ hooks: [preToolUse] }], PostToolUse: [{ hooks: [postToolUse] }], Stop: [{ hooks: [cleanupStop] }] },
|
|
1494
|
+
},
|
|
1495
|
+
})
|
|
1496
|
+
self.session = turn
|
|
1497
|
+
self.interrupt = () => turn.interrupt()
|
|
1498
|
+
const r = await consume(turn, (m) => log(`[agent] cleanup turn model=${m.model}`))
|
|
1499
|
+
cleanup = r && !r.is_error && r.subtype === 'success' ? 'ran' : 'failed'
|
|
1500
|
+
} catch (err) {
|
|
1501
|
+
log(`[agent] cleanup turn failed: ${err?.message ?? err}`)
|
|
1502
|
+
cleanup = 'failed'
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
// Whatever probes are still there (the cleanup turn was skipped, as for
|
|
1506
|
+
// credit, a key or a Stop, or did not get to them) are put back here.
|
|
1507
|
+
const probesBack = await putProbesBack(gate)
|
|
1508
|
+
self.stopTap()
|
|
1509
|
+
await tap.poll().catch(() => {})
|
|
1510
|
+
sendCost(true)
|
|
1511
|
+
send({
|
|
1512
|
+
type: 'error',
|
|
1513
|
+
id,
|
|
1514
|
+
message,
|
|
1515
|
+
failure: failureName,
|
|
1516
|
+
vendor: 'Anthropic',
|
|
1517
|
+
unfinished: true,
|
|
1518
|
+
costUsd: ledger.spentUsd(),
|
|
1519
|
+
helperUsd: ledger.breakdown().helperUsd,
|
|
1520
|
+
generationUsd: ledger.breakdown().generationUsd,
|
|
1521
|
+
turns,
|
|
1522
|
+
cleanup,
|
|
1523
|
+
markers: await gate.newMarkers(),
|
|
1524
|
+
...(probesBack.length ? { probesBack } : {}),
|
|
1525
|
+
})
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
// ------------------------------------------------------------ the creator's agent app
|
|
1529
|
+
|
|
1530
|
+
/** A request built through the creator's own agent app (appRun.mjs): its
|
|
1531
|
+
* words and steps are shown as they come; it costs the studio nothing, and
|
|
1532
|
+
* what it changed is checked by the gate as any other run's is. */
|
|
1533
|
+
async function runApp(s) {
|
|
1534
|
+
const { msg, text, images, context, self, gate, loopGate, depth, screenLocale, language, runDir } = s
|
|
1535
|
+
const { id, app } = msg
|
|
1536
|
+
send({ type: 'started', id, sessionId: null, model: app.id, promptHash: PROMPT_HASH, effort: depth.effort, depthReason: `built through ${app.name}`, locale: screenLocale })
|
|
1537
|
+
// The creator's pictures as files the app can open.
|
|
1538
|
+
const files = []
|
|
1539
|
+
for (const [i, image] of images.entries()) {
|
|
1540
|
+
const ext = /png/.test(image?.mime ?? '') ? 'png' : /webp/.test(image?.mime ?? '') ? 'webp' : /gif/.test(image?.mime ?? '') ? 'gif' : 'jpg'
|
|
1541
|
+
const file = path.join(runDir, `picture-${i + 1}.${ext}`)
|
|
1542
|
+
try {
|
|
1543
|
+
await fsp.writeFile(file, Buffer.from(String(image?.data ?? ''), 'base64'))
|
|
1544
|
+
files.push(file)
|
|
1545
|
+
} catch {
|
|
1546
|
+
// The request goes on without that picture.
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
const result = await (test.runAgentApp ?? runAgentApp)({
|
|
1550
|
+
app,
|
|
1551
|
+
prompt: appNote(app, msg.projectRoot) + context + historyPreamble(msg.history) + describeSelection(msg.attachment) + text,
|
|
1552
|
+
images: files,
|
|
1553
|
+
projectRoot: msg.projectRoot,
|
|
1554
|
+
emit: (event) => {
|
|
1555
|
+
if (event?.type === 'text') language.text(event.delta)
|
|
1556
|
+
send({ ...event, id })
|
|
1557
|
+
},
|
|
1558
|
+
onChild: (stop) => {
|
|
1559
|
+
self.interrupt = stop
|
|
1560
|
+
if (self.cancelled) stop()
|
|
1561
|
+
},
|
|
1562
|
+
})
|
|
1563
|
+
const summary = { costUsd: 0, helperUsd: 0, generationUsd: 0, effort: depth.effort, verified: await gate.verified(), stopBlocks: gate.blocks + loopGate.blocks, markers: await gate.newMarkers(), ...self.loopDone() }
|
|
1564
|
+
if (result.ok) {
|
|
1565
|
+
send({ type: 'done', id, subtype: 'success', turns: result.turns, ...summary })
|
|
1566
|
+
return
|
|
1567
|
+
}
|
|
1568
|
+
send({ type: 'error', id, message: result.error, failure: result.stopped || self.cancelled ? 'stopped' : 'other', vendor: app.name, turns: result.turns ?? 0, unfinished: true, cleanup: 'skipped', ...summary })
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
// ------------------------------------------------------------ other vendors
|
|
1572
|
+
|
|
1573
|
+
/** A request for a model that is not Claude's: agent-loop.mjs, cancelled
|
|
1574
|
+
* through the same `interrupt` as the SDK's session. */
|
|
1575
|
+
async function runOther(s) {
|
|
1576
|
+
const { msg, text, inline, flow, provider, model, screenLocale, depth, defs, byName, ledger, gate, guard, consent, extra, keys, askable, ctx, readOnlyTool, sendCost, notesNow, context, self, pace, language, maxTurns, loop, loopGate } = s
|
|
1577
|
+
const { id } = msg
|
|
1578
|
+
const controller = new AbortController()
|
|
1579
|
+
self.interrupt = () => controller.abort()
|
|
1580
|
+
// OPENAI_BASE_URL, GEMINI_BASE_URL, XAI_BASE_URL, DEEPSEEK_BASE_URL: a
|
|
1581
|
+
// proxy or gateway in front of the vendor, as their own SDKs allow.
|
|
1582
|
+
const baseUrl = (process.env[`${provider.id.toUpperCase()}_BASE_URL`] ?? '').trim() || provider.baseUrl
|
|
1583
|
+
// The vendors' own names for the file tools, as the guard knows them.
|
|
1584
|
+
const asGuarded = (name, args) =>
|
|
1585
|
+
name === 'read_file' ? ['Read', { file_path: args?.path }] : name === 'write_file' || name === 'edit_file' ? ['Write', { file_path: args?.path }] : [name, args]
|
|
1586
|
+
await runLoop({
|
|
1587
|
+
id,
|
|
1588
|
+
provider: { ...provider, baseUrl },
|
|
1589
|
+
model,
|
|
1590
|
+
apiKey: msg.apiKey,
|
|
1591
|
+
system: `${SYSTEM_PROMPT}\n\n${OTHER_VENDOR_NOTE}`,
|
|
1592
|
+
prompt: context + historyPreamble(msg.history) + describeSelection(msg.attachment) + text,
|
|
1593
|
+
images: inline,
|
|
1594
|
+
projectRoot: msg.projectRoot,
|
|
1595
|
+
inside: isInside,
|
|
1596
|
+
defs,
|
|
1597
|
+
toolCtx: ctx,
|
|
1598
|
+
// The agent's words to the creator, for the watch on their language.
|
|
1599
|
+
send: (event) => {
|
|
1600
|
+
if (event?.type === 'text') language.text(event.delta)
|
|
1601
|
+
send(event)
|
|
1602
|
+
},
|
|
1603
|
+
signal: controller.signal,
|
|
1604
|
+
env: extra.env,
|
|
1605
|
+
effort: depth.effort,
|
|
1606
|
+
maxTurns,
|
|
1607
|
+
started: { promptHash: PROMPT_HASH, effort: depth.effort, depthReason: depth.reason, locale: screenLocale },
|
|
1608
|
+
hooks: {
|
|
1609
|
+
async beforeTool(name, args) {
|
|
1610
|
+
const fenced = guard.check(...asGuarded(name, args))
|
|
1611
|
+
if (!fenced.ok) return { deny: fenced.reason }
|
|
1612
|
+
pace.toolStarted()
|
|
1613
|
+
const hold = pace.holdMs()
|
|
1614
|
+
if (hold > 0) await holdFor(hold, () => self.cancelled)
|
|
1615
|
+
const paid = ledger.gate(name, readOnlyTool(name, args))
|
|
1616
|
+
if (!paid.ok) return { deny: depth.space && !loop.kickoff && byName.has('nw_ask_kickoff') && paid.reason === BIG_REASON ? `${paid.reason}${KICKOFF_IS_THE_ASK}` : paid.reason }
|
|
1617
|
+
if (s.loopOn && depth.space && !loop.kickoff && name === 'nw_ask' && args?.kind === 'cost') return { deny: KICKOFF_NOT_COST }
|
|
1618
|
+
if (loop.active && !loop.targets.settled && writesBrief(msg.projectRoot, name, args)) return { deny: TARGETS_FIRST }
|
|
1619
|
+
// run_command is asked as Bash: a paid call waits for a cost card,
|
|
1620
|
+
// and the web for the creator's consent, as for Claude.
|
|
1621
|
+
if (name === 'Bash') {
|
|
1622
|
+
const paidVar = askable && ledger.approvedUsd() === null ? keys.paidVar(args?.command) : null
|
|
1623
|
+
if (paidVar) return { deny: paidReason(paidVar, false) }
|
|
1624
|
+
if (keys.needsWeb(args?.command) && (await consent.web()) !== 'allow') return { deny: NO_WEB }
|
|
1625
|
+
}
|
|
1626
|
+
return {}
|
|
1627
|
+
},
|
|
1628
|
+
afterTool(name, result, args) {
|
|
1629
|
+
if (name === 'nw_ask') consent.set(webAnswerOf(args, result?.text))
|
|
1630
|
+
if (EDITS.has(name) && !result?.isError) {
|
|
1631
|
+
pace.noteEdit()
|
|
1632
|
+
flow.noteEdit(name, args)
|
|
1633
|
+
}
|
|
1634
|
+
return notesNow()
|
|
1635
|
+
},
|
|
1636
|
+
stopGate: async () => self.creatorSaid?.() ?? (await gate.stopReason({ max: 2 })) ?? (await loopGate.stopReason()) ?? language.finalReason(),
|
|
1637
|
+
usage(u) {
|
|
1638
|
+
ledger.addTokens(u?.input, u?.output)
|
|
1639
|
+
pace.step()
|
|
1640
|
+
sendCost(false)
|
|
1641
|
+
},
|
|
1642
|
+
async summary(how) {
|
|
1643
|
+
sendCost(true)
|
|
1644
|
+
const probesBack = how?.unfinished ? await putProbesBack(gate) : []
|
|
1645
|
+
return {
|
|
1646
|
+
costUsd: ledger.spentUsd(),
|
|
1647
|
+
helperUsd: 0,
|
|
1648
|
+
generationUsd: ledger.breakdown().generationUsd,
|
|
1649
|
+
effort: depth.effort,
|
|
1650
|
+
verified: await gate.verified(),
|
|
1651
|
+
stopBlocks: gate.blocks + loopGate.blocks,
|
|
1652
|
+
markers: await gate.newMarkers(),
|
|
1653
|
+
...self.loopDone(),
|
|
1654
|
+
...(probesBack.length ? { probesBack } : {}),
|
|
1655
|
+
}
|
|
1656
|
+
},
|
|
1657
|
+
},
|
|
1658
|
+
})
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
return {
|
|
1662
|
+
run,
|
|
1663
|
+
cancel() {
|
|
1664
|
+
if (!active) return
|
|
1665
|
+
active.cancelled = true
|
|
1666
|
+
void active.interrupt?.()
|
|
1667
|
+
// A Blender the run started would otherwise model on until its own
|
|
1668
|
+
// timeout, minutes after the creator pressed Stop.
|
|
1669
|
+
void import('./blender/run.mjs')
|
|
1670
|
+
.then((m) => m.stopAll?.())
|
|
1671
|
+
.catch(() => {})
|
|
1672
|
+
},
|
|
1673
|
+
/** A key the creator saved in a key card while this run goes on: for
|
|
1674
|
+
* Bash from its next command (an env file it sources) and for the other
|
|
1675
|
+
* vendors' run_command (their env, updated in place). Never logged. */
|
|
1676
|
+
secretEnv(msg) {
|
|
1677
|
+
const self = active
|
|
1678
|
+
if (!self || self.id !== msg?.runId) return
|
|
1679
|
+
const entries = Object.entries(msg.env ?? {}).filter(([k, v]) => /^[A-Z_][A-Z0-9_]*$/.test(k) && typeof v === 'string')
|
|
1680
|
+
if (entries.length === 0) return
|
|
1681
|
+
try {
|
|
1682
|
+
fs.mkdirSync(HOST_DIR, { recursive: true, mode: 0o700 })
|
|
1683
|
+
fs.chmodSync(HOST_DIR, 0o700)
|
|
1684
|
+
fs.appendFileSync(self.envFile, entries.map(([k, v]) => `export ${k}=${quote(v)}\n`).join(''), { mode: 0o600 })
|
|
1685
|
+
fs.chmodSync(self.envFile, 0o600)
|
|
1686
|
+
} catch (err) {
|
|
1687
|
+
log(`[agent] the saved key could not be handed to Bash: ${err?.code ?? 'error'}`)
|
|
1688
|
+
}
|
|
1689
|
+
if (self.env) Object.assign(self.env, Object.fromEntries(entries))
|
|
1690
|
+
for (const [name] of entries) self.secretNames.add(name)
|
|
1691
|
+
},
|
|
1692
|
+
/** A message the creator sent while this run works (main checked it,
|
|
1693
|
+
* agent/notes.cjs noteFor): kept for the main agent's next tool result.
|
|
1694
|
+
* A production's team, or a run that is over, does not take it: the
|
|
1695
|
+
* chat sends it as the next message. In a space's reference loop it is
|
|
1696
|
+
* also the next round's first gap (REFERENCE_LOOP.md 2.7). Answers
|
|
1697
|
+
* whether the run took it. */
|
|
1698
|
+
note(msg) {
|
|
1699
|
+
const self = active
|
|
1700
|
+
const reply = (state) => send({ type: 'note', id: msg?.runId, noteIds: [String(msg?.noteId ?? '')], state })
|
|
1701
|
+
if (!self || self.id !== msg?.runId || !self.notes || self.director) {
|
|
1702
|
+
reply('refused')
|
|
1703
|
+
return false
|
|
1704
|
+
}
|
|
1705
|
+
const text = typeof msg.text === 'string' ? msg.text : ''
|
|
1706
|
+
const marks = msg.marks ?? null
|
|
1707
|
+
const added = self.notes.add({ noteId: String(msg.noteId ?? ''), text, images: Array.isArray(msg.images) ? msg.images : [], marks })
|
|
1708
|
+
if (!added.ok) log(`[agent] a note was not kept: ${added.error}`)
|
|
1709
|
+
// The gap, in short: the words, the picture kept and where its marks are.
|
|
1710
|
+
if (added.ok && self.loop?.active) {
|
|
1711
|
+
const pictures = added.files.map((f) => `${f}${marks?.hero ? ` at ${marks.hero}` : ''}`)
|
|
1712
|
+
const where = (marks?.marks ?? []).slice(0, 6).map((m) => creatorNotes.markLine(m))
|
|
1713
|
+
const gap = [text.trim(), pictures.length ? `(${pictures.join(', ')}${where.length ? `: ${where.join('; ')}` : ''})` : ''].filter(Boolean).join(' ')
|
|
1714
|
+
// The chat shows the creator their own words back, with the view
|
|
1715
|
+
// they marked; the file and the marks' pixels are for the agent.
|
|
1716
|
+
void self.loop.addNote(gap, { said: text.trim(), hero: marks?.hero })
|
|
1717
|
+
}
|
|
1718
|
+
reply(added.ok ? 'queued' : 'refused')
|
|
1719
|
+
return added.ok
|
|
1720
|
+
},
|
|
1721
|
+
/** The studio itself wrote these project files during the run (the
|
|
1722
|
+
* creator moved an object, changed a knob, dropped in a model): they are
|
|
1723
|
+
* not the agent's change, so the stop gate does not count them. */
|
|
1724
|
+
async studioWrote(msg) {
|
|
1725
|
+
const self = active
|
|
1726
|
+
if (!self?.gate || self.id !== msg?.runId || !Array.isArray(msg.files)) return
|
|
1727
|
+
try {
|
|
1728
|
+
await self.gate.noteStudioWrite(msg.files.filter((f) => typeof f === 'string'))
|
|
1729
|
+
} catch (err) {
|
|
1730
|
+
log(`[agent] the studio's own save could not be noted: ${err?.message ?? err}`)
|
|
1731
|
+
}
|
|
1732
|
+
},
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
export const __test = { createConsent, webAnswerOf, resultText, remoteHosts, keyRules, webSearchInput, writeReferences, isEmptyProject, connectorOptions, fallbackLocale, fallbackScreen, writesBrief, HOST_DIR, HOST_PREFIX, MCP_INSTRUCTIONS, TARGETS_FIRST, KICKOFF_IS_THE_ASK, KICKOFF_NOT_COST }
|