oda-engine 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +131 -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-CptQkDVX.js +1 -0
- package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
- package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
- package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
- package/web-dist/assets/index-Baka-ZO7.js +693 -0
- package/web-dist/assets/index-CcjyyQco.css +1 -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,58 @@
|
|
|
1
|
+
// The creator's language in the agent's chat replies to them, held to by the
|
|
2
|
+
// host as well as asked for in the prompt: in a QA run for a Korean creator
|
|
3
|
+
// (2026-10-20) eleven of twelve notes between steps came out in English and
|
|
4
|
+
// only the last reply in Korean. What the main agent writes is read as it
|
|
5
|
+
// streams; a note in another script gets the agent a short correction in its
|
|
6
|
+
// next tool result (three at most), and a final reply in another script is
|
|
7
|
+
// sent back once to be written again. Only where the script tells
|
|
8
|
+
// (locale.cjs writtenIn: Korean, Japanese, Chinese, Russian, Arabic, Thai,
|
|
9
|
+
// Greek, Hebrew, Hindi, or any reply that is mostly a script that is not
|
|
10
|
+
// its language's, Korean for a Japanese creator as English for a Korean
|
|
11
|
+
// one); between two Latin-script languages nothing is said.
|
|
12
|
+
// Cards are not watched here: their words are in the screen language
|
|
13
|
+
// (locale.cjs screenLocale), which the card tools hold them to.
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {{ locale: string, languageName?: string, writtenIn?: (text: string, locale: string) => boolean | null, maxNotes?: number }} options
|
|
17
|
+
*/
|
|
18
|
+
export function createLanguageWatch({ locale, languageName, writtenIn, maxNotes = 3 }) {
|
|
19
|
+
const name = languageName || locale
|
|
20
|
+
let pending = ''
|
|
21
|
+
let notes = 0
|
|
22
|
+
let sentBack = false
|
|
23
|
+
const wrong = (text) => {
|
|
24
|
+
try {
|
|
25
|
+
return writtenIn?.(text, locale) === false
|
|
26
|
+
} catch {
|
|
27
|
+
return false
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const quoteOf = (text) => {
|
|
31
|
+
const s = text.replace(/\s+/g, ' ').trim()
|
|
32
|
+
return s.length > 60 ? `${s.slice(0, 57)}...` : s
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
/** Text the main agent wrote to the creator (a stream delta). */
|
|
36
|
+
text(delta) {
|
|
37
|
+
if (typeof delta === 'string') pending += delta
|
|
38
|
+
},
|
|
39
|
+
/** At a tool result: a correction when what it wrote since the last one
|
|
40
|
+
* was not in the creator's language; null otherwise. */
|
|
41
|
+
note() {
|
|
42
|
+
const text = pending
|
|
43
|
+
pending = ''
|
|
44
|
+
if (notes >= maxNotes || !text.trim() || !wrong(text)) return null
|
|
45
|
+
notes++
|
|
46
|
+
return `Your note to the creator ("${quoteOf(text)}") was not in ${name}. The creator writes in ${name}: write every note between steps, and your final reply, in ${name}. Cards and the brief are in the screen language the studio context names; code, file names, helper briefs, search words and generation prompts stay in English.`
|
|
47
|
+
},
|
|
48
|
+
/** At the end: a reason to write the final reply again, once; null when
|
|
49
|
+
* it is in the creator's language or cannot be told. */
|
|
50
|
+
finalReason(text) {
|
|
51
|
+
const reply = typeof text === 'string' && text.trim() ? text : pending
|
|
52
|
+
pending = ''
|
|
53
|
+
if (sentBack || !reply.trim() || !wrong(reply)) return null
|
|
54
|
+
sentBack = true
|
|
55
|
+
return `Your reply is not in ${name}, the language the creator writes in. Write the same reply again in ${name}, and nothing else.`
|
|
56
|
+
},
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
// What a request costs, kept by the host while it runs: the model's tokens
|
|
2
|
+
// priced from models.json, plus what the agent says each paid generation call
|
|
3
|
+
// cost (nw_spend). There is no cap. A big job waits for the creator to approve
|
|
4
|
+
// an estimate (an nw_ask "cost" card) before it may change anything, and a
|
|
5
|
+
// job that clearly outgrows what was approved is told to ask again; any
|
|
6
|
+
// amount the creator approves goes.
|
|
7
|
+
//
|
|
8
|
+
// One price source for every figure (models.json, through shared.mjs
|
|
9
|
+
// PRICING): the estimate in the studio context, the running total and the
|
|
10
|
+
// final line. A QA run on Claude Haiku 5.5 (2026-10-20) showed both ways it
|
|
11
|
+
// went wrong before. The running total read the usage on the SDK's streamed
|
|
12
|
+
// assistant messages, which is not final (most of a call's output, its
|
|
13
|
+
// thinking above all, arrives later), never saw the helpers, and priced every
|
|
14
|
+
// call at the short-prompt rate; it said $0.09 for about $0.94. The final line
|
|
15
|
+
// took the SDK's total_cost_usd, which priced a model the CLI has no table for
|
|
16
|
+
// at another model's rate; it said $6.33 for about $0.51. Now each call is
|
|
17
|
+
// counted once, at the largest usage any source reported for it (the stream's
|
|
18
|
+
// message_start and message_delta, the assistant messages, and the session's
|
|
19
|
+
// own transcripts, the helpers' included, which host.mjs reads as they grow),
|
|
20
|
+
// priced at the rate its own prompt length bills at; the SDK's per-model
|
|
21
|
+
// totals only add what no source showed, priced the same way.
|
|
22
|
+
//
|
|
23
|
+
// The figure is this request's alone: a resumed session's totals also count
|
|
24
|
+
// the turns before it, so they are used only on a fresh session.
|
|
25
|
+
|
|
26
|
+
// Approval triggers, in US dollars. With an approval A: a reminder once the
|
|
27
|
+
// spend since that approval passes A * 1.25 + 0.5, and no more changes past
|
|
28
|
+
// A * 1.5 + 1 until a new approval. An approval is for what is left (the
|
|
29
|
+
// card shows it beside what was spent so far), so each one adds to what was
|
|
30
|
+
// already spent rather than replacing it. Without one (a request that was not
|
|
31
|
+
// big): the same at $2.50 and $4.00 of the whole spend.
|
|
32
|
+
export const REMIND_FACTOR = 1.25
|
|
33
|
+
export const REMIND_PLUS = 0.5
|
|
34
|
+
export const STOP_FACTOR = 1.5
|
|
35
|
+
export const STOP_PLUS = 1
|
|
36
|
+
export const UNAPPROVED_REMIND = 2.5
|
|
37
|
+
export const UNAPPROVED_STOP = 4
|
|
38
|
+
|
|
39
|
+
/** Cache writes cost a quarter more than input (an hour-long one twice),
|
|
40
|
+
* cache reads a tenth of it unless the model's card says otherwise
|
|
41
|
+
* (Anthropic's list prices); a web search is $10 per thousand. */
|
|
42
|
+
const CACHE_WRITE = 1.25
|
|
43
|
+
const CACHE_WRITE_HOUR = 2
|
|
44
|
+
const CACHE_READ = 0.1
|
|
45
|
+
const WEB_SEARCH_USD = 0.01
|
|
46
|
+
|
|
47
|
+
/** Tools that change nothing in the project: always allowed, approved or not.
|
|
48
|
+
* Bash is read-only when its command is (guard.mjs readOnlyCommand). */
|
|
49
|
+
export const READ_ONLY_TOOLS = new Set([
|
|
50
|
+
'Read', 'Glob', 'Grep', 'TodoWrite', 'TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet', 'Skill', 'WebSearch', 'WebFetch', 'Agent',
|
|
51
|
+
'nw_ask', 'nw_spend', 'nw_check', 'nw_play', 'nw_docs', 'nw_schema', 'nw_capture_screen', 'nw_guide',
|
|
52
|
+
// measuring the reference and a view against it; a team task's own checks
|
|
53
|
+
'nw_reference', 'nw_compare', 'task_check',
|
|
54
|
+
// looking up looks, libraries, licences and jobs; asset_fetch and the jobs write only the quarantine
|
|
55
|
+
'look_compare', 'asset_search', 'asset_fetch', 'asset_inspect', 'asset_ledger', 'asset_job', 'environment_job',
|
|
56
|
+
'browser_navigate', 'browser_read_page', 'browser_find', 'browser_get_text', 'browser_tabs', 'browser_console',
|
|
57
|
+
// the other vendors' names for reading
|
|
58
|
+
'read_file', 'list_files', 'search',
|
|
59
|
+
])
|
|
60
|
+
|
|
61
|
+
export const BIG_REASON =
|
|
62
|
+
'This is a big job. Before you change anything, estimate its cost (the LLM work and any paid generation) and ask with nw_ask kind "cost". Reading, looking and planning are fine until then, read-only commands (ls, cat, grep, git log) included.'
|
|
63
|
+
|
|
64
|
+
const usd = (n) => `$${n.toFixed(2)}`
|
|
65
|
+
const num = (v) => (Number.isFinite(v) ? v : 0)
|
|
66
|
+
|
|
67
|
+
/** A price card from models.json (shared.mjs pricingFor), or a plain
|
|
68
|
+
* [in, out] pair; null for none. */
|
|
69
|
+
export function pricingOf(p) {
|
|
70
|
+
if (Array.isArray(p)) return p.length === 2 ? { price: p } : null
|
|
71
|
+
if (p && Array.isArray(p.price)) return p
|
|
72
|
+
return null
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A call's whole prompt in tokens: input, cache writes and cache reads. The
|
|
76
|
+
* long-prompt tier is chosen by it. */
|
|
77
|
+
export const promptTokens = (u) => num(u?.input_tokens) + num(u?.cache_creation_input_tokens) + num(u?.cache_read_input_tokens)
|
|
78
|
+
|
|
79
|
+
/** The [in, out] rate one call bills at, by the length of its own prompt. */
|
|
80
|
+
export function rateFor(usage, pricing) {
|
|
81
|
+
const p = pricingOf(pricing)
|
|
82
|
+
if (!p) return null
|
|
83
|
+
return p.longPrompt && promptTokens(usage) > p.longPrompt.over ? p.longPrompt.price : p.price
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** One call's usage in dollars, at its model's card (or [in, out] per million). */
|
|
87
|
+
export function priceOf(usage, pricing) {
|
|
88
|
+
if (!usage) return 0
|
|
89
|
+
const p = pricingOf(pricing)
|
|
90
|
+
if (!p) return 0
|
|
91
|
+
const [inUsd, outUsd] = rateFor(usage, p)
|
|
92
|
+
const created = num(usage.cache_creation_input_tokens)
|
|
93
|
+
const hour = Math.min(created, num(usage.cache_creation?.ephemeral_1h_input_tokens))
|
|
94
|
+
const tokens =
|
|
95
|
+
num(usage.input_tokens) * inUsd +
|
|
96
|
+
(created - hour) * inUsd * (p.cacheWrite ?? CACHE_WRITE) +
|
|
97
|
+
hour * inUsd * CACHE_WRITE_HOUR +
|
|
98
|
+
num(usage.cache_read_input_tokens) * inUsd * (p.cacheRead ?? CACHE_READ) +
|
|
99
|
+
num(usage.output_tokens) * outUsd
|
|
100
|
+
return tokens / 1e6 + num(usage.server_tool_use?.web_search_requests) * WEB_SEARCH_USD
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Two reports of one call's usage as one: each count at the larger. The
|
|
104
|
+
* stream's first frame has the prompt and almost no output, its last the
|
|
105
|
+
* output; a transcript line may have either. */
|
|
106
|
+
export function mergeUsage(a, b) {
|
|
107
|
+
if (!b || typeof b !== 'object') return a ?? null
|
|
108
|
+
const out = { ...(a ?? {}) }
|
|
109
|
+
for (const k of ['input_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens', 'output_tokens']) {
|
|
110
|
+
const v = Math.max(num(a?.[k]), num(b[k]))
|
|
111
|
+
if (v > 0 || k in out || k in b) out[k] = v
|
|
112
|
+
}
|
|
113
|
+
const searches = Math.max(num(a?.server_tool_use?.web_search_requests), num(b.server_tool_use?.web_search_requests))
|
|
114
|
+
if (searches > 0) out.server_tool_use = { ...(a?.server_tool_use ?? {}), web_search_requests: searches }
|
|
115
|
+
const hour = Math.max(num(a?.cache_creation?.ephemeral_1h_input_tokens), num(b.cache_creation?.ephemeral_1h_input_tokens))
|
|
116
|
+
if (hour > 0) out.cache_creation = { ...(a?.cache_creation ?? {}), ephemeral_1h_input_tokens: hour }
|
|
117
|
+
const thinking = Math.max(num(a?.output_tokens_details?.thinking_tokens), num(b.output_tokens_details?.thinking_tokens))
|
|
118
|
+
if (thinking > 0) out.output_tokens_details = { thinking_tokens: thinking }
|
|
119
|
+
return out
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A model id as both the API and the SDK's totals spell it: no [1m], no date. */
|
|
123
|
+
const bareModel = (id) =>
|
|
124
|
+
String(id ?? '')
|
|
125
|
+
.replace(/\[[^\]]*\]$/, '')
|
|
126
|
+
.replace(/-\d{8}$/, '')
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* @param {{ price: object | [number, number] | null, prices?: Record<string, object | [number, number]>, big?: boolean,
|
|
130
|
+
* askable?: boolean, onApprove?: (usd: number) => void, model?: string }} options
|
|
131
|
+
* price: the run's model's card; prices: every model's, for a helper on
|
|
132
|
+
* another model; model: the run's model id, for the SDK's per-model totals.
|
|
133
|
+
* askable: false when no nw_ask is loaded (a half-built tree): then nothing
|
|
134
|
+
* waits for an approval that could never come.
|
|
135
|
+
*/
|
|
136
|
+
export function createLedger({ price, prices = {}, big = false, askable = true, onApprove, model = null } = {}) {
|
|
137
|
+
const main = pricingOf(price)
|
|
138
|
+
const cards = new Map(Object.entries(prices).map(([id, p]) => [bareModel(id), pricingOf(p)]))
|
|
139
|
+
/** A call's card: its own model's, else the run's (a call that names no model is the run's). */
|
|
140
|
+
const cardFor = (id) => (id && cards.get(bareModel(id))) || main
|
|
141
|
+
/** message id -> { usage, model, helper, usd } */
|
|
142
|
+
const calls = new Map()
|
|
143
|
+
/** The message each stream (the main agent's, each helper's) is on. */
|
|
144
|
+
const streaming = new Map()
|
|
145
|
+
let vendorUsd = 0
|
|
146
|
+
let extraUsd = 0
|
|
147
|
+
let generationUsd = 0
|
|
148
|
+
const generation = []
|
|
149
|
+
let approved = null // the latest approval: what the creator allowed for what was left
|
|
150
|
+
let base = 0 // the spend when it was given
|
|
151
|
+
let reminded = false
|
|
152
|
+
|
|
153
|
+
/** One report of one call; returns its record. */
|
|
154
|
+
function add(id, usage, modelId, helper) {
|
|
155
|
+
if (!id || !usage) return null
|
|
156
|
+
const was = calls.get(id)
|
|
157
|
+
const rec = was ?? { usage: null, model: null, helper: false, usd: 0 }
|
|
158
|
+
rec.usage = mergeUsage(rec.usage, usage)
|
|
159
|
+
rec.model = rec.model ?? (typeof modelId === 'string' && modelId ? modelId : null)
|
|
160
|
+
rec.helper = rec.helper || helper === true
|
|
161
|
+
rec.usd = priceOf(rec.usage, cardFor(rec.model))
|
|
162
|
+
if (!was) calls.set(id, rec)
|
|
163
|
+
return rec
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const llm = () => {
|
|
167
|
+
let sum = vendorUsd + extraUsd
|
|
168
|
+
for (const rec of calls.values()) sum += rec.usd
|
|
169
|
+
return sum
|
|
170
|
+
}
|
|
171
|
+
const spentUsd = () => llm() + generationUsd
|
|
172
|
+
|
|
173
|
+
const ledger = {
|
|
174
|
+
spentUsd,
|
|
175
|
+
/** What this request may cost in all: the spend at the latest approval plus that approval. */
|
|
176
|
+
approvedUsd: () => (approved === null ? null : base + approved),
|
|
177
|
+
/** The creator approved an estimate for what is left of this request. */
|
|
178
|
+
approve(totalUsd) {
|
|
179
|
+
const n = Number(totalUsd)
|
|
180
|
+
if (!Number.isFinite(n) || n < 0) return
|
|
181
|
+
approved = n
|
|
182
|
+
base = spentUsd()
|
|
183
|
+
reminded = false
|
|
184
|
+
try {
|
|
185
|
+
onApprove?.(n)
|
|
186
|
+
} catch {
|
|
187
|
+
// an escalation that fails never breaks the run
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
addGeneration(amount, what) {
|
|
191
|
+
const n = Number(amount)
|
|
192
|
+
if (!Number.isFinite(n) || n < 0) return
|
|
193
|
+
generationUsd += n
|
|
194
|
+
generation.push({ usd: n, what: String(what ?? '') })
|
|
195
|
+
},
|
|
196
|
+
/** Whether this request still needs a cost approval before it changes anything. */
|
|
197
|
+
big: () => big && askable && approved === null,
|
|
198
|
+
|
|
199
|
+
/** An SDK assistant message, or a transcript line of the session (a
|
|
200
|
+
* helper's lines are sidechain ones). The stream repeats a message as
|
|
201
|
+
* it grows, so each id counts once, each count at its largest. */
|
|
202
|
+
addUsage(msg) {
|
|
203
|
+
const m = msg?.message
|
|
204
|
+
if (!m?.usage) return null
|
|
205
|
+
const id = m.id ?? `anon-${calls.size}`
|
|
206
|
+
return add(id, m.usage, m.model, !!msg.parent_tool_use_id || msg.isSidechain === true || msg.helper === true)
|
|
207
|
+
},
|
|
208
|
+
/** An SDK stream event: message_start carries the call's id, model and
|
|
209
|
+
* prompt, message_delta its final output. Keyed by the stream it is on
|
|
210
|
+
* (the main agent's or a helper's), since a delta names no message. */
|
|
211
|
+
addStreamEvent(msg) {
|
|
212
|
+
const ev = msg?.event
|
|
213
|
+
const stream = msg?.parent_tool_use_id ?? 'main'
|
|
214
|
+
if (ev?.type === 'message_start' && ev.message?.id) {
|
|
215
|
+
streaming.set(stream, ev.message.id)
|
|
216
|
+
return add(ev.message.id, ev.message.usage ?? {}, ev.message.model, stream !== 'main')
|
|
217
|
+
}
|
|
218
|
+
if (ev?.type === 'message_delta' && ev.usage && streaming.has(stream)) return add(streaming.get(stream), ev.usage, null, stream !== 'main')
|
|
219
|
+
return null
|
|
220
|
+
},
|
|
221
|
+
/** The other vendors' loop: plain token counts for one step, its input
|
|
222
|
+
* being that step's whole prompt. */
|
|
223
|
+
addTokens(input, output) {
|
|
224
|
+
if (!main) return
|
|
225
|
+
vendorUsd += priceOf({ input_tokens: num(input), output_tokens: num(output) }, main)
|
|
226
|
+
},
|
|
227
|
+
/**
|
|
228
|
+
* At the end of a fresh session: the SDK's own per-model totals
|
|
229
|
+
* (modelUsage, every call of the query, helpers included), for what no
|
|
230
|
+
* source showed: each count beyond what was seen, priced at the model's
|
|
231
|
+
* card, at the tier the seen calls of that model mostly billed at.
|
|
232
|
+
* total_cost_usd is used only for a model that has no price here, never
|
|
233
|
+
* for one that has: for a model the CLI has no table for it is another
|
|
234
|
+
* model's rate (Haiku 5.5 at 12 to 37 times its own, 2026-10-20).
|
|
235
|
+
*/
|
|
236
|
+
reconcile(result, fresh) {
|
|
237
|
+
if (!fresh || !result) return
|
|
238
|
+
const totals = result.modelUsage && typeof result.modelUsage === 'object' ? result.modelUsage : null
|
|
239
|
+
if (!totals) {
|
|
240
|
+
const total = Number(result.total_cost_usd)
|
|
241
|
+
if (!main && Number.isFinite(total) && total > llm()) extraUsd += total - llm()
|
|
242
|
+
return
|
|
243
|
+
}
|
|
244
|
+
for (const [id, mu] of Object.entries(totals)) {
|
|
245
|
+
const card = cards.get(bareModel(id)) ?? cards.get(bareModel(mu?.canonicalModel)) ?? (model && bareModel(id) === bareModel(model) ? main : null)
|
|
246
|
+
const mine = [...calls.values()].filter((rec) => bareModel(rec.model ?? model) === bareModel(id) || (mu?.canonicalModel && bareModel(rec.model ?? model) === bareModel(mu.canonicalModel)))
|
|
247
|
+
if (!card) {
|
|
248
|
+
const cost = Number(mu?.costUSD)
|
|
249
|
+
if (mine.length === 0 && Number.isFinite(cost) && cost > 0) extraUsd += cost
|
|
250
|
+
continue
|
|
251
|
+
}
|
|
252
|
+
const seen = { input: 0, write: 0, read: 0, output: 0, prompt: 0, long: 0 }
|
|
253
|
+
for (const rec of mine) {
|
|
254
|
+
const u = rec.usage ?? {}
|
|
255
|
+
seen.input += num(u.input_tokens)
|
|
256
|
+
seen.write += num(u.cache_creation_input_tokens)
|
|
257
|
+
seen.read += num(u.cache_read_input_tokens)
|
|
258
|
+
seen.output += num(u.output_tokens)
|
|
259
|
+
const prompt = promptTokens(u)
|
|
260
|
+
seen.prompt += prompt
|
|
261
|
+
if (card.longPrompt && prompt > card.longPrompt.over) seen.long += prompt
|
|
262
|
+
}
|
|
263
|
+
const missing = {
|
|
264
|
+
input_tokens: Math.max(0, num(mu?.inputTokens) - seen.input),
|
|
265
|
+
cache_creation_input_tokens: Math.max(0, num(mu?.cacheCreationInputTokens) - seen.write),
|
|
266
|
+
cache_read_input_tokens: Math.max(0, num(mu?.cacheReadInputTokens) - seen.read),
|
|
267
|
+
output_tokens: Math.max(0, num(mu?.outputTokens) - seen.output),
|
|
268
|
+
}
|
|
269
|
+
if (Object.values(missing).every((v) => v === 0)) continue
|
|
270
|
+
// Priced flat at each tier (the missing tokens are not one call), mixed
|
|
271
|
+
// by how much of the seen prompt was long.
|
|
272
|
+
const share = card.longPrompt && seen.prompt > 0 ? seen.long / seen.prompt : 0
|
|
273
|
+
const flat = (rate) => priceOf(missing, { ...card, price: rate, longPrompt: undefined })
|
|
274
|
+
extraUsd += (1 - share) * flat(card.price) + share * (card.longPrompt ? flat(card.longPrompt.price) : 0)
|
|
275
|
+
}
|
|
276
|
+
},
|
|
277
|
+
/** Where the money went: the main agent's calls, its helpers', paid generation. */
|
|
278
|
+
breakdown() {
|
|
279
|
+
let agentUsd = vendorUsd + extraUsd
|
|
280
|
+
let helperUsd = 0
|
|
281
|
+
let thinking = 0
|
|
282
|
+
for (const rec of calls.values()) {
|
|
283
|
+
if (rec.helper) helperUsd += rec.usd
|
|
284
|
+
else {
|
|
285
|
+
agentUsd += rec.usd
|
|
286
|
+
thinking += num(rec.usage?.output_tokens_details?.thinking_tokens)
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return { agentUsd, helperUsd, generationUsd, calls: calls.size, thinkingTokens: thinking }
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
/** Whether a tool may run now. */
|
|
293
|
+
gate(_toolName, isReadOnly) {
|
|
294
|
+
if (isReadOnly || !askable) return { ok: true }
|
|
295
|
+
if (big && approved === null) return { ok: false, reason: BIG_REASON }
|
|
296
|
+
const spent = spentUsd()
|
|
297
|
+
const over = approved === null ? spent > UNAPPROVED_STOP : spent - base > approved * STOP_FACTOR + STOP_PLUS
|
|
298
|
+
if (over) {
|
|
299
|
+
return {
|
|
300
|
+
ok: false,
|
|
301
|
+
reason:
|
|
302
|
+
approved === null
|
|
303
|
+
? `Spend so far is ${usd(spent)} and no cost was approved for this request. Estimate what is left and ask with nw_ask kind "cost" before you change anything else.`
|
|
304
|
+
: `Spend so far is ${usd(spent)} against the approved ${usd(base + approved)}. Ask again with nw_ask kind "cost" (a new estimate for what is left) before you change anything else.`,
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return { ok: true }
|
|
308
|
+
},
|
|
309
|
+
/** A note for the model, once each time spend passes the reminder line. */
|
|
310
|
+
reminder() {
|
|
311
|
+
if (!askable || reminded) return null
|
|
312
|
+
const spent = spentUsd()
|
|
313
|
+
const passed = approved === null ? spent > UNAPPROVED_REMIND : spent - base > approved * REMIND_FACTOR + REMIND_PLUS
|
|
314
|
+
if (!passed) return null
|
|
315
|
+
reminded = true
|
|
316
|
+
return approved === null
|
|
317
|
+
? `Spend so far is ${usd(spent)}, and no cost was approved for this request. Finish the step you are on, then ask with nw_ask kind "cost" (an estimate for what is left) before you go on.`
|
|
318
|
+
: `Spend so far is ${usd(spent)} against the approved ${usd(base + approved)}. Finish the step you are on, then ask again with nw_ask kind "cost" (a new estimate for what is left) before you go on.`
|
|
319
|
+
},
|
|
320
|
+
generation: () => generation.slice(),
|
|
321
|
+
}
|
|
322
|
+
return ledger
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ---------------------------------------------------------------- the estimate
|
|
326
|
+
// What a request of each kind typically costs on a model, from token counts
|
|
327
|
+
// rather than one model's dollars scaled by the output price, so the long
|
|
328
|
+
// prompt tier and the cache prices count: priced with the same priceOf as the
|
|
329
|
+
// running total. Each profile is a number of calls (the helpers' included)
|
|
330
|
+
// with an average prompt, the part of it that is new (cache writes) and the
|
|
331
|
+
// output. Opus 5.5 at these profiles costs what its studio requests have cost
|
|
332
|
+
// (a tweak $0.05 to $0.30, a big build $3 to $15); a QA build on Haiku 5.5
|
|
333
|
+
// (63 calls of about 103K tokens of prompt, 2026-10-20) falls inside its range.
|
|
334
|
+
|
|
335
|
+
export const TYPICAL = {
|
|
336
|
+
tweak: [
|
|
337
|
+
{ calls: 3, prompt: 30_000, fresh: 2_000, output: 500 },
|
|
338
|
+
{ calls: 8, prompt: 40_000, fresh: 3_000, output: 1_200 },
|
|
339
|
+
],
|
|
340
|
+
feature: [
|
|
341
|
+
{ calls: 10, prompt: 50_000, fresh: 4_000, output: 2_000 },
|
|
342
|
+
{ calls: 24, prompt: 70_000, fresh: 4_000, output: 2_500 },
|
|
343
|
+
],
|
|
344
|
+
build: [
|
|
345
|
+
{ calls: 40, prompt: 80_000, fresh: 4_000, output: 2_000 },
|
|
346
|
+
{ calls: 120, prompt: 140_000, fresh: 6_000, output: 4_000 },
|
|
347
|
+
],
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** What one profile costs on a model's card. */
|
|
351
|
+
export function profileUsd({ calls, prompt, fresh, output }, pricing) {
|
|
352
|
+
const usage = { input_tokens: 0, cache_creation_input_tokens: fresh, cache_read_input_tokens: Math.max(0, prompt - fresh), output_tokens: output }
|
|
353
|
+
return calls * priceOf(usage, pricing)
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** The typical range of each kind of request on a model: { tweak: [lo, hi], ... }. */
|
|
357
|
+
export function typicalUsd(pricing) {
|
|
358
|
+
if (!pricingOf(pricing)) return null
|
|
359
|
+
return Object.fromEntries(Object.entries(TYPICAL).map(([kind, [lo, hi]]) => [kind, [profileUsd(lo, pricing), profileUsd(hi, pricing)]]))
|
|
360
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// The two languages the studio keeps apart (the creator's decision of
|
|
2
|
+
// 2026-11-02: English by default, and the engine's own words in the language
|
|
3
|
+
// the computer is set to, never in one read from a message):
|
|
4
|
+
//
|
|
5
|
+
// - The screen language, for everything fixed on screen (every card's
|
|
6
|
+
// labels, the host's own cards, the panels, the mood board, the level and
|
|
7
|
+
// environment words) and for every word the agent writes onto a card or
|
|
8
|
+
// into a brief, so a card never mixes two languages. It is the computer's
|
|
9
|
+
// own language when the studio has a label table for it
|
|
10
|
+
// (src/cards/labels.ts: en, ko, ja, zh, es, fr, de), else English, and
|
|
11
|
+
// never comes from what the creator types: a Korean message on an English
|
|
12
|
+
// system still gets English cards. screenLocale reads it.
|
|
13
|
+
// - The creator's language, for the agent's chat replies only. It is read
|
|
14
|
+
// from the script of their own message, because that is what they chose
|
|
15
|
+
// to type in; the OS locale only decides between languages that share a
|
|
16
|
+
// script (Latin) or when the message has no letters at all. detectLocale
|
|
17
|
+
// reads it.
|
|
18
|
+
//
|
|
19
|
+
// CommonJS so main can require it; the agent host imports it through Node's
|
|
20
|
+
// CJS interop (`import locale from './locale.cjs'`).
|
|
21
|
+
|
|
22
|
+
/** Languages written in Latin script that the OS locale may name. A Latin
|
|
23
|
+
* message on a French system is French; on a Korean one it is English. */
|
|
24
|
+
const LATIN_LANGUAGES = new Set(['en', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'sv', 'da', 'nb', 'fi', 'pl', 'cs', 'tr', 'id', 'vi'])
|
|
25
|
+
|
|
26
|
+
/** The card label tables that exist (src/cards/labels.ts); anything else shows English. */
|
|
27
|
+
const LABEL_LOCALES = new Set(['en', 'ko', 'ja', 'zh', 'es', 'fr', 'de'])
|
|
28
|
+
|
|
29
|
+
/** For the agent's studio context line ("creator's language: Korean (ko)",
|
|
30
|
+
* "screen language: English (en)"). */
|
|
31
|
+
const LANGUAGE_NAMES = Object.freeze({
|
|
32
|
+
en: 'English',
|
|
33
|
+
ko: 'Korean',
|
|
34
|
+
ja: 'Japanese',
|
|
35
|
+
zh: 'Chinese',
|
|
36
|
+
ru: 'Russian',
|
|
37
|
+
ar: 'Arabic',
|
|
38
|
+
th: 'Thai',
|
|
39
|
+
el: 'Greek',
|
|
40
|
+
he: 'Hebrew',
|
|
41
|
+
hi: 'Hindi',
|
|
42
|
+
es: 'Spanish',
|
|
43
|
+
fr: 'French',
|
|
44
|
+
de: 'German',
|
|
45
|
+
it: 'Italian',
|
|
46
|
+
pt: 'Portuguese',
|
|
47
|
+
nl: 'Dutch',
|
|
48
|
+
sv: 'Swedish',
|
|
49
|
+
da: 'Danish',
|
|
50
|
+
nb: 'Norwegian',
|
|
51
|
+
fi: 'Finnish',
|
|
52
|
+
pl: 'Polish',
|
|
53
|
+
cs: 'Czech',
|
|
54
|
+
tr: 'Turkish',
|
|
55
|
+
id: 'Indonesian',
|
|
56
|
+
vi: 'Vietnamese',
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
// In the order the rules apply: any Hangul at all makes a message Korean even
|
|
60
|
+
// with English words in it, and kana is what tells Japanese from Chinese,
|
|
61
|
+
// since both use Han characters.
|
|
62
|
+
const SCRIPTS = [
|
|
63
|
+
{ locale: 'ko', test: /[ᄀ-ᇿ-ꥠ-가-ힰ-ᅠ-ᅵ]/ },
|
|
64
|
+
{ locale: 'ja', test: /[-ゟ゠-ヿㇰ-ㇿヲ-゚]/ },
|
|
65
|
+
{ locale: 'zh', test: /\p{Script=Han}/u },
|
|
66
|
+
{ locale: 'ru', test: /\p{Script=Cyrillic}/u },
|
|
67
|
+
{ locale: 'ar', test: /\p{Script=Arabic}/u },
|
|
68
|
+
{ locale: 'th', test: /\p{Script=Thai}/u },
|
|
69
|
+
// Unambiguous scripts outside the spec's list: without them a Greek, Hebrew
|
|
70
|
+
// or Hindi message on an English system would get English cards.
|
|
71
|
+
{ locale: 'el', test: /\p{Script=Greek}/u },
|
|
72
|
+
{ locale: 'he', test: /\p{Script=Hebrew}/u },
|
|
73
|
+
{ locale: 'hi', test: /\p{Script=Devanagari}/u },
|
|
74
|
+
]
|
|
75
|
+
const LATIN = /\p{Script=Latin}/u
|
|
76
|
+
|
|
77
|
+
/** 'ko-KR' -> 'ko', 'zh_Hant_TW' -> 'zh', 'no' -> 'nb'; null for nothing usable. */
|
|
78
|
+
function languageOf(tag) {
|
|
79
|
+
const m = /^([A-Za-z]{2,3})(?:[-_]|$)/.exec(String(tag ?? '').trim())
|
|
80
|
+
if (!m) return null
|
|
81
|
+
const lang = m[1].toLowerCase()
|
|
82
|
+
// Norwegian Bokmal is written 'nb' by some systems and 'no' by others.
|
|
83
|
+
return lang === 'no' ? 'nb' : lang
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The language of `text`: 'ko', 'ja', 'zh', 'ru', 'ar', 'th', ... or 'en'.
|
|
88
|
+
* `fallback` is the OS locale ('ko-KR'), used for Latin-script and
|
|
89
|
+
* letterless messages only.
|
|
90
|
+
*/
|
|
91
|
+
function detectLocale(text, fallback) {
|
|
92
|
+
const s = String(text ?? '')
|
|
93
|
+
for (const { locale, test } of SCRIPTS) if (test.test(s)) return locale
|
|
94
|
+
const os = languageOf(fallback)
|
|
95
|
+
if (LATIN.test(s)) return os && LATIN_LANGUAGES.has(os) ? os : 'en'
|
|
96
|
+
return os ?? 'en'
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The label table a card in `locale` is drawn from. */
|
|
100
|
+
function labelLocale(locale) {
|
|
101
|
+
const lang = languageOf(locale)
|
|
102
|
+
return lang && LABEL_LOCALES.has(lang) ? lang : 'en'
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The studio's screen language: the computer's language when a label table
|
|
107
|
+
* exists for it, else English. `system` is the OS's language tag ('en-KR',
|
|
108
|
+
* Electron's app.getPreferredSystemLanguages()[0], the CLI's Intl locale or
|
|
109
|
+
* LANG), or the list of them, whose first is the one the OS shows. What the
|
|
110
|
+
* creator writes plays no part.
|
|
111
|
+
*/
|
|
112
|
+
function screenLocale(system) {
|
|
113
|
+
return labelLocale(Array.isArray(system) ? system[0] : system)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** What a language's own writing looks like, for the languages a script
|
|
117
|
+
* tells apart. Japanese is kana or kanji, since a short note may be all
|
|
118
|
+
* kanji. */
|
|
119
|
+
const WRITTEN = {
|
|
120
|
+
ko: SCRIPTS[0].test,
|
|
121
|
+
ja: /[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]|\p{Script=Han}/u,
|
|
122
|
+
zh: /\p{Script=Han}/u,
|
|
123
|
+
ru: /\p{Script=Cyrillic}/u,
|
|
124
|
+
ar: /\p{Script=Arabic}/u,
|
|
125
|
+
th: /\p{Script=Thai}/u,
|
|
126
|
+
el: /\p{Script=Greek}/u,
|
|
127
|
+
he: /\p{Script=Hebrew}/u,
|
|
128
|
+
hi: /\p{Script=Devanagari}/u,
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Prose only: code blocks, inline code, URLs and paths say nothing about
|
|
132
|
+
* the language a note is written in. */
|
|
133
|
+
const prose = (text) =>
|
|
134
|
+
String(text ?? '')
|
|
135
|
+
.replace(/```[\s\S]*?(```|$)/g, ' ')
|
|
136
|
+
.replace(/`[^`\n]*`/g, ' ')
|
|
137
|
+
.replace(/\b[a-z][a-z0-9+.-]*:\/\/\S+/gi, ' ')
|
|
138
|
+
.replace(/(^|\s)[\w.-]*[/\\][\w./\\-]*/g, ' ')
|
|
139
|
+
|
|
140
|
+
const KANA = /[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f]/gu
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Whether `text` is written in `locale`'s language: true when it has that
|
|
144
|
+
* language's script, false when it has none of it but a sentence's worth of
|
|
145
|
+
* Latin letters, or is mostly another script, null when the script cannot
|
|
146
|
+
* tell (too little text).
|
|
147
|
+
*
|
|
148
|
+
* A card or a reply can miss its language in two ways, and both are caught
|
|
149
|
+
* now that the screen and the creator may differ: Latin words where another
|
|
150
|
+
* script belongs (an English card on a Korean screen), and another script
|
|
151
|
+
* where neither Latin nor the language's own belongs (a Korean card on a
|
|
152
|
+
* Japanese or Chinese screen, a Japanese one on a Korean screen). Japanese
|
|
153
|
+
* on a Chinese screen shares its Han characters, so kana tells it: a text
|
|
154
|
+
* with as much kana as half its Han is Japanese. Chinese on a Japanese
|
|
155
|
+
* screen cannot be told, since a short Japanese title may be all kanji.
|
|
156
|
+
*
|
|
157
|
+
* A Latin-script language (English, French...) cannot be told from another
|
|
158
|
+
* one, so it is null there too, unless the text is mostly another script:
|
|
159
|
+
* a card on an English screen written in Hangul, kana, Han or Cyrillic is
|
|
160
|
+
* not in English. A name or a word of another script inside a Latin
|
|
161
|
+
* sentence still passes.
|
|
162
|
+
*/
|
|
163
|
+
function writtenIn(text, locale) {
|
|
164
|
+
const lang = languageOf(locale)
|
|
165
|
+
const s = prose(text)
|
|
166
|
+
const letters = (s.match(/\p{L}/gu) ?? []).length
|
|
167
|
+
const latin = (s.match(/\p{Script=Latin}/gu) ?? []).length
|
|
168
|
+
// Letters of a script that is neither Latin nor this language's own, as
|
|
169
|
+
// many as half the Latin ones at least: a sentence of it, not a name.
|
|
170
|
+
const mostlyOther = (other) => other >= 2 && other * 2 >= latin
|
|
171
|
+
const test = WRITTEN[lang]
|
|
172
|
+
if (!test) {
|
|
173
|
+
if (!LATIN_LANGUAGES.has(lang)) return null
|
|
174
|
+
return mostlyOther(letters - latin) ? false : null
|
|
175
|
+
}
|
|
176
|
+
if (lang === 'zh') {
|
|
177
|
+
const kana = (s.match(KANA) ?? []).length
|
|
178
|
+
const han = (s.match(/\p{Script=Han}/gu) ?? []).length
|
|
179
|
+
if (kana >= 2 && kana * 2 >= han) return false
|
|
180
|
+
}
|
|
181
|
+
if (test.test(s)) return true
|
|
182
|
+
if (latin >= 20) return false
|
|
183
|
+
return mostlyOther(letters - latin) ? false : null
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
module.exports = { detectLocale, labelLocale, screenLocale, languageOf, writtenIn, LANGUAGE_NAMES }
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// What a space weighs against what a planet carries (REFERENCE_LOOP.md 2.6,
|
|
2
|
+
// 2.8): the files under assets/ against the schema's own size rules
|
|
3
|
+
// (assetSizeProblems: each file's kind ceiling, the sounds, the 100 MB in
|
|
4
|
+
// all) and the bundle esbuild makes of src/ against the 1 MB the publish
|
|
5
|
+
// contract allows (LIMITS.bundleKb). The stop gate holds a loop to it and
|
|
6
|
+
// the approval card shows it; the limits themselves are the schema's and
|
|
7
|
+
// are only read here.
|
|
8
|
+
//
|
|
9
|
+
// The publish pre-flight (publish.cjs preflight) is still the one that
|
|
10
|
+
// counts: it also leaves out what will not travel. Counting every file in
|
|
11
|
+
// assets/ is the cautious side of it.
|
|
12
|
+
|
|
13
|
+
import fsp from 'node:fs/promises'
|
|
14
|
+
import { createRequire } from 'node:module'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
import { LIMITS, assetSizeProblems } from '../../schema/dist/index.js'
|
|
17
|
+
|
|
18
|
+
const require = createRequire(import.meta.url)
|
|
19
|
+
const MB = 1024 * 1024
|
|
20
|
+
|
|
21
|
+
/** Every file under assets/, project-relative, as publish.cjs lists them. */
|
|
22
|
+
async function assetFiles(root) {
|
|
23
|
+
const out = []
|
|
24
|
+
const walk = async (dir, rel) => {
|
|
25
|
+
let entries
|
|
26
|
+
try {
|
|
27
|
+
entries = await fsp.readdir(dir, { withFileTypes: true })
|
|
28
|
+
} catch {
|
|
29
|
+
return
|
|
30
|
+
}
|
|
31
|
+
for (const e of entries) {
|
|
32
|
+
if (e.name.startsWith('.')) continue
|
|
33
|
+
const child = `${rel}/${e.name}`
|
|
34
|
+
if (e.isDirectory()) await walk(path.join(dir, e.name), child)
|
|
35
|
+
else if (e.isFile()) {
|
|
36
|
+
try {
|
|
37
|
+
out.push({ path: child, bytes: (await fsp.stat(path.join(dir, e.name))).size })
|
|
38
|
+
} catch {
|
|
39
|
+
// gone between the listing and the stat
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
await walk(path.join(root, 'assets'), 'assets')
|
|
45
|
+
return out
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* { assetsMb, bundleKb, problems: string[], limits: { assetsMb, bundleKb } }.
|
|
50
|
+
* bundleKb is null when the bundle does not build (nw_check says why).
|
|
51
|
+
* `build` is build.cjs's buildGame, replaceable for the checks.
|
|
52
|
+
*/
|
|
53
|
+
export async function capacityOf(root, { build = null } = {}) {
|
|
54
|
+
const files = await assetFiles(root)
|
|
55
|
+
const bytes = files.reduce((n, f) => n + f.bytes, 0)
|
|
56
|
+
const problems = assetSizeProblems(files).map((f) => f.message)
|
|
57
|
+
let bundleKb = null
|
|
58
|
+
try {
|
|
59
|
+
const buildGame = build ?? require('../../build.cjs').buildGame
|
|
60
|
+
const built = await buildGame(root)
|
|
61
|
+
if (built?.ok && typeof built.code === 'string') {
|
|
62
|
+
bundleKb = Buffer.byteLength(built.code, 'utf8') / 1024
|
|
63
|
+
if (bundleKb > LIMITS.bundleKb) problems.push(`main.js is ${Math.round(bundleKb)} KB; a planet's code is at most ${LIMITS.bundleKb} KB.`)
|
|
64
|
+
}
|
|
65
|
+
} catch {
|
|
66
|
+
// no esbuild here: the bundle is said as unknown
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
assetsMb: Math.round((bytes / MB) * 10) / 10,
|
|
70
|
+
bundleKb: bundleKb === null ? null : Math.round(bundleKb),
|
|
71
|
+
problems,
|
|
72
|
+
limits: { assetsMb: LIMITS.assetsMb, bundleKb: LIMITS.bundleKb },
|
|
73
|
+
}
|
|
74
|
+
}
|