@seriousgaming/sdk-tools 1.5.0 → 1.6.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/dist/bundling/ui-bundler.d.ts +12 -0
- package/dist/cli-25RWY5BQ.js +41 -0
- package/dist/cli-272KBNJH.js +97 -0
- package/dist/cli-2BH7FX27.js +52 -0
- package/dist/cli-2GOFEW26.js +81 -0
- package/dist/cli-3E3MD5U4.js +21 -0
- package/dist/cli-3HE4AVZG.js +115 -0
- package/dist/cli-4AKVLEC4.js +1387 -0
- package/dist/cli-4BV45LBH.js +126 -0
- package/dist/cli-4LKXZQ2B.js +48 -0
- package/dist/cli-4UWFQNGF.js +54 -0
- package/dist/cli-4YB3ROVR.js +78 -0
- package/dist/cli-57RXC3HQ.js +36 -0
- package/dist/cli-5JEGTVTG.js +96 -0
- package/dist/cli-6AMT3BUO.js +97 -0
- package/dist/cli-6RRVEGFB.js +80 -0
- package/dist/cli-6WXLXJVX.js +36 -0
- package/dist/cli-7OGYADZ3.js +97 -0
- package/dist/cli-AK7OIPWY.js +229 -0
- package/dist/cli-B4TN6PJP.js +124 -0
- package/dist/cli-B6YHEKIJ.js +248 -0
- package/dist/cli-BPYMTOUL.js +89 -0
- package/dist/cli-BWX5E7TQ.js +23 -0
- package/dist/cli-BYJWFFCF.js +37 -0
- package/dist/cli-C3NVCKO6.js +43 -0
- package/dist/cli-C47GJATR.js +42 -0
- package/dist/cli-C5QOJJWX.js +46 -0
- package/dist/cli-C6TH5S7K.js +6417 -0
- package/dist/cli-DL2CVMRF.js +89 -0
- package/dist/cli-DMW2OQIJ.js +76 -0
- package/dist/cli-DZW3XD5F.js +143 -0
- package/dist/cli-E2NLWIFE.js +1331 -0
- package/dist/cli-E33CJRRQ.js +36 -0
- package/dist/cli-E6DJIMYD.js +142 -0
- package/dist/cli-EEFJKIGL.js +151 -0
- package/dist/cli-EVFS55WN.js +185 -0
- package/dist/cli-F2D4GGUA.js +549 -0
- package/dist/cli-FBTRTIZJ.js +226 -0
- package/dist/cli-FWFRKQNE.js +11 -0
- package/dist/cli-FYINNRML.js +760 -0
- package/dist/cli-G522CPRL.js +88 -0
- package/dist/cli-G6KELFSX.js +2847 -0
- package/dist/cli-G6UE5NL4.js +90 -0
- package/dist/cli-GBFM76BF.js +16 -0
- package/dist/cli-GDQ6ILJY.js +101 -0
- package/dist/cli-GFBGYFYD.js +50 -0
- package/dist/cli-GGPDQNM3.js +35 -0
- package/dist/cli-GTSGLN3Z.js +307 -0
- package/dist/cli-GUXKQMJ7.js +13641 -0
- package/dist/cli-GXD36NF2.js +60 -0
- package/dist/cli-HCRTYQQS.js +16 -0
- package/dist/cli-HYY64SUD.js +185 -0
- package/dist/cli-I355WTAF.js +463 -0
- package/dist/cli-IDKYF5XB.js +59 -0
- package/dist/cli-ILKCQNM6.js +8 -0
- package/dist/cli-IRZ5KB7D.js +36 -0
- package/dist/cli-IUS2YCD3.js +31 -0
- package/dist/cli-J4DKUUTK.js +138 -0
- package/dist/cli-JFU22EJ2.js +187 -0
- package/dist/cli-JMZLT65J.js +226 -0
- package/dist/cli-JZM7XTNV.js +89 -0
- package/dist/cli-K2B6WHKA.js +81 -0
- package/dist/cli-KL3756X6.js +126 -0
- package/dist/cli-KNOOKGYW.js +88 -0
- package/dist/cli-LFGRFIEO.js +226 -0
- package/dist/cli-LFM7GJHI.js +0 -0
- package/dist/cli-LMDJCHHD.js +304 -0
- package/dist/cli-LXYPE3L5.js +99 -0
- package/dist/cli-M6BCQRID.js +153 -0
- package/dist/cli-MBNMPVDC.js +367 -0
- package/dist/cli-MJUYJIEP.js +13 -0
- package/dist/cli-MMN4BPO4.js +145 -0
- package/dist/cli-MYJGMA6U.js +40 -0
- package/dist/cli-N6H6T2E2.js +616 -0
- package/dist/cli-O5KP4OVN.js +61 -0
- package/dist/cli-O6PWMJTZ.js +25 -0
- package/dist/cli-ORIG557O.js +141 -0
- package/dist/cli-PFFCNGHI.js +243 -0
- package/dist/cli-PNLYX6R6.js +131 -0
- package/dist/cli-PQBXVLEU.js +649 -0
- package/dist/cli-PTT5RGKO.js +62 -0
- package/dist/cli-Q2XJF5AS.js +127 -0
- package/dist/cli-QEVDDBNO.js +60 -0
- package/dist/cli-QEVE5HUM.js +167 -0
- package/dist/cli-QUIJCBYB.js +391 -0
- package/dist/cli-QUNIRH7A.js +57 -0
- package/dist/cli-QVASWX2A.js +187 -0
- package/dist/cli-QWQMPCL6.js +253 -0
- package/dist/cli-R4PCG5YX.js +131 -0
- package/dist/cli-RA673NGF.js +53 -0
- package/dist/cli-RN6IWTL2.js +36 -0
- package/dist/cli-ROT3DRKU.js +145 -0
- package/dist/cli-RZITKPJX.js +367 -0
- package/dist/cli-S5IVGDDD.js +32 -0
- package/dist/cli-S5QDONIQ.js +218 -0
- package/dist/cli-SIPDUBFL.js +36 -0
- package/dist/cli-SMFSZF2G.js +4009 -0
- package/dist/cli-SRHBXZCN.js +159 -0
- package/dist/cli-TCY5LJ7E.js +88 -0
- package/dist/cli-TDSQSCX4.js +131 -0
- package/dist/cli-TIDQ4WUE.js +257 -0
- package/dist/cli-TLLA6KAP.js +79 -0
- package/dist/cli-TPU4TUR6.js +132 -0
- package/dist/cli-U2UE7I7J.js +30 -0
- package/dist/cli-UELGBQG7.js +101 -0
- package/dist/cli-UHSZBKYO.js +97 -0
- package/dist/cli-UJ4UCL2Z.js +38 -0
- package/dist/cli-UKQYZYFK.js +31 -0
- package/dist/cli-UMFFURZ7.js +81 -0
- package/dist/cli-UNAJ2OTE.js +15 -0
- package/dist/cli-UNJ5X6BU.js +89 -0
- package/dist/cli-UTJU4IYG.js +117 -0
- package/dist/cli-V4GHRWOV.js +1837 -0
- package/dist/cli-VCI3CG36.js +73 -0
- package/dist/cli-VCKOC2EV.js +256 -0
- package/dist/cli-VL2P354N.js +46 -0
- package/dist/cli-WAE26SVW.js +72 -0
- package/dist/cli-WOGIAU2E.js +100 -0
- package/dist/cli-WU43JT4T.js +52 -0
- package/dist/cli-XCO2VQOH.js +122 -0
- package/dist/cli-XSVGKI3R.js +39 -0
- package/dist/cli-YOTGR3NB.js +82 -0
- package/dist/cli-YVVXUD2G.js +197 -0
- package/dist/cli-ZISJ36MM.js +89 -0
- package/dist/cli-ZTWOE3ZT.js +65 -0
- package/dist/cli-ZVSFYDPQ.js +205 -0
- package/dist/cli-ZWPYIXNI.js +68 -0
- package/dist/cli.js +148 -43093
- package/dist/client/build-surfaces.d.ts +33 -0
- package/dist/client/dev-server.d.ts +6 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/playwright.d.ts +62 -0
- package/dist/client.js +228 -48
- package/dist/core/session.d.ts +15 -1
- package/dist/dev/console/assets/{index-BVF8exas.js → index-CuMOOH9m.js} +1 -1
- package/dist/dev/console/index.html +1 -1
- package/dist/dev/shell.d.ts +19 -0
- package/dist/dev/surfaces.d.ts +7 -0
- package/dist/docs/api/index.md +14 -12
- package/dist/docs/api/sdk-tools-client.md +29 -0
- package/dist/docs/api/sdk-tools-playwright.md +104 -0
- package/dist/docs/changelog.md +19 -0
- package/dist/docs/cli-and-dev-server.md +21 -0
- package/dist/docs/cli-reference.md +45 -31
- package/dist/docs/environment-variables.md +6 -0
- package/dist/docs/guides/designing-a-game.md +29 -4
- package/dist/docs/guides/starter-game.md +2 -2
- package/dist/docs/guides/testing.md +33 -18
- package/dist/docs/page-index.md +8 -7
- package/dist/docs/recipes/e2e-testing.md +19 -20
- package/dist/playwright.js +32232 -0
- package/dist/templates/package/claude/rules/workflow-test-engine-or-ui.md +1 -1
- package/dist/templates/package/global-setup.ts.template +7 -18
- package/dist/templates/package/playwright.config.ts.liquid +8 -11
- package/dist/templates/starter-game/playwright.config.ts +8 -11
- package/dist/templates/starter-game/testing/e2e/game.spec.ts +1 -1
- package/dist/templates/starter-game/testing/e2e/global-setup.ts +7 -18
- package/dist/utils/prompt.d.ts +5 -5
- package/dist/utils/resource-scan.d.ts +39 -0
- package/package.json +7 -3
|
@@ -0,0 +1,1331 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_PLATFORM_HOST,
|
|
4
|
+
formatPlatformErrors,
|
|
5
|
+
normalisePlatformHost
|
|
6
|
+
} from "./cli-25RWY5BQ.js";
|
|
7
|
+
import {
|
|
8
|
+
describeAssetByReference,
|
|
9
|
+
readAssetByReference,
|
|
10
|
+
storeBlob
|
|
11
|
+
} from "./cli-QWQMPCL6.js";
|
|
12
|
+
import {
|
|
13
|
+
DeniedError,
|
|
14
|
+
UndeclaredApiUseError,
|
|
15
|
+
realPath,
|
|
16
|
+
settingsSchemas,
|
|
17
|
+
validateSessionOverrides,
|
|
18
|
+
validateSettingsOverrides
|
|
19
|
+
} from "./cli-SMFSZF2G.js";
|
|
20
|
+
|
|
21
|
+
// cli/execution/logic-failure.ts
|
|
22
|
+
import { SourceMap } from "node:module";
|
|
23
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
24
|
+
|
|
25
|
+
// cli/utils/llm-client.ts
|
|
26
|
+
var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
27
|
+
var STOP_REASONS = ["endTurn", "toolUse", "maxTokens", "refusal"];
|
|
28
|
+
var CONTENT_BLOCK_TYPES = ["text", "toolUse", "toolResult"];
|
|
29
|
+
var LLM_NOT_CONFIGURED = "LLM_NOT_CONFIGURED";
|
|
30
|
+
var LLM_NOT_CONFIGURED_HINT = "Set SERIOUSGAMING_API_KEY in the environment or in .env, or run `seriousgaming-sdk config set platform.apiKey <key>`, or pass `sdk dev --api-key <key>`, then restart the dev server. Issue a key from your organisation settings on the platform.";
|
|
31
|
+
var LLMClientError = class extends Error {
|
|
32
|
+
constructor(message, code) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.name = "LLMClientError";
|
|
36
|
+
}
|
|
37
|
+
code;
|
|
38
|
+
};
|
|
39
|
+
var LLMClient = class {
|
|
40
|
+
apiKey;
|
|
41
|
+
apiHost;
|
|
42
|
+
constructor(config) {
|
|
43
|
+
this.apiKey = config.apiKey;
|
|
44
|
+
this.apiHost = normalisePlatformHost(config.apiHost ?? DEFAULT_PLATFORM_HOST);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Generate text through the platform LLM API.
|
|
48
|
+
* Supports both simple string prompts and complex options.
|
|
49
|
+
*/
|
|
50
|
+
async generateText(optionsOrPrompt) {
|
|
51
|
+
if (!this.apiKey) {
|
|
52
|
+
throw new LLMClientError(
|
|
53
|
+
"generateText needs a Serious Gaming platform API key, and none is configured.",
|
|
54
|
+
LLM_NOT_CONFIGURED
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const options = typeof optionsOrPrompt === "string" ? { prompt: optionsOrPrompt } : optionsOrPrompt;
|
|
58
|
+
if (options.tools) {
|
|
59
|
+
for (const tool of options.tools) {
|
|
60
|
+
if (!TOOL_NAME_PATTERN.test(tool.name)) {
|
|
61
|
+
throw new LLMClientError(
|
|
62
|
+
`Invalid tool name "${tool.name}": must match ^[a-zA-Z0-9_-]{1,64}$`
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!options.prompt && (!options.messages || options.messages.length === 0)) {
|
|
68
|
+
throw new LLMClientError("No prompt or messages provided to generateText");
|
|
69
|
+
}
|
|
70
|
+
const endpoint = `${this.apiHost}/api/v0/llm/generate`;
|
|
71
|
+
const body = {};
|
|
72
|
+
if (options.prompt !== void 0) body.prompt = options.prompt;
|
|
73
|
+
if (options.messages !== void 0) body.messages = options.messages;
|
|
74
|
+
if (options.systemPrompt !== void 0) body.systemPrompt = options.systemPrompt;
|
|
75
|
+
if (options.jsonSchema !== void 0) body.jsonSchema = options.jsonSchema;
|
|
76
|
+
if (options.tier !== void 0) body.tier = options.tier;
|
|
77
|
+
if (options.tools !== void 0) body.tools = options.tools;
|
|
78
|
+
let response;
|
|
79
|
+
try {
|
|
80
|
+
response = await fetch(endpoint, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: {
|
|
83
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
84
|
+
"Content-Type": "application/json"
|
|
85
|
+
},
|
|
86
|
+
body: JSON.stringify(body)
|
|
87
|
+
});
|
|
88
|
+
} catch (error) {
|
|
89
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
90
|
+
throw new LLMClientError(`Network error contacting ${endpoint}: ${message}`);
|
|
91
|
+
}
|
|
92
|
+
const rawBody = await response.text();
|
|
93
|
+
let parsedBody = null;
|
|
94
|
+
if (rawBody) {
|
|
95
|
+
try {
|
|
96
|
+
parsedBody = JSON.parse(rawBody);
|
|
97
|
+
} catch {
|
|
98
|
+
parsedBody = null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (!response.ok) {
|
|
102
|
+
throw new LLMClientError(
|
|
103
|
+
this.mapErrorMessage(response.status, parsedBody)
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
return translateResponse(parsedBody);
|
|
107
|
+
}
|
|
108
|
+
mapErrorMessage(status, parsedBody) {
|
|
109
|
+
switch (status) {
|
|
110
|
+
case 400: {
|
|
111
|
+
const detail = parsedBody ? formatPlatformErrors(parsedBody) : "";
|
|
112
|
+
return detail ? `LLM request rejected (400): ${detail}` : "LLM request rejected (400). The server did not return an errors array.";
|
|
113
|
+
}
|
|
114
|
+
case 401:
|
|
115
|
+
return "Invalid API key. Check $SERIOUSGAMING_API_KEY and that it has not been revoked.";
|
|
116
|
+
case 403:
|
|
117
|
+
return "The account that created this API key does not have access to the platform LLM API. Ask Serious Gaming support to grant it.";
|
|
118
|
+
default: {
|
|
119
|
+
const detail = parsedBody ? formatPlatformErrors(parsedBody) : "";
|
|
120
|
+
return detail ? `LLM request failed (${status}): ${detail}` : `LLM request failed with HTTP ${status}.`;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
function translateResponse(parsedBody) {
|
|
126
|
+
if (parsedBody === null || typeof parsedBody !== "object") {
|
|
127
|
+
throw new LLMClientError("Unexpected response format from the platform LLM API");
|
|
128
|
+
}
|
|
129
|
+
const { content, stopReason, usage } = parsedBody;
|
|
130
|
+
if (!Array.isArray(content) || content.length === 0) {
|
|
131
|
+
throw new LLMClientError("Empty response from the platform LLM API");
|
|
132
|
+
}
|
|
133
|
+
if (typeof stopReason !== "string") {
|
|
134
|
+
throw new LLMClientError("Unexpected response format from the platform LLM API");
|
|
135
|
+
}
|
|
136
|
+
const response = {
|
|
137
|
+
content: content.filter(isKnownContentBlock),
|
|
138
|
+
stopReason: STOP_REASONS.includes(stopReason) ? stopReason : "endTurn"
|
|
139
|
+
};
|
|
140
|
+
if (usage && typeof usage === "object") {
|
|
141
|
+
const { inputTokens, outputTokens } = usage;
|
|
142
|
+
if (typeof inputTokens === "number" && typeof outputTokens === "number") {
|
|
143
|
+
response.usage = { inputTokens, outputTokens };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return response;
|
|
147
|
+
}
|
|
148
|
+
function isKnownContentBlock(block) {
|
|
149
|
+
if (block === null || typeof block !== "object") return false;
|
|
150
|
+
const { type } = block;
|
|
151
|
+
return typeof type === "string" && CONTENT_BLOCK_TYPES.includes(type);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// cli/execution/logic-failure.ts
|
|
155
|
+
var failures = /* @__PURE__ */ new WeakMap();
|
|
156
|
+
function markLogicFailure(error, failure) {
|
|
157
|
+
const carrier = typeof error === "object" && error !== null ? error : new Error(String(error));
|
|
158
|
+
if (!failures.has(carrier)) failures.set(carrier, failure);
|
|
159
|
+
return carrier;
|
|
160
|
+
}
|
|
161
|
+
function logicFailureOf(error) {
|
|
162
|
+
return typeof error === "object" && error !== null ? failures.get(error) : void 0;
|
|
163
|
+
}
|
|
164
|
+
function carryLogicFailure(from, to) {
|
|
165
|
+
const failure = logicFailureOf(from);
|
|
166
|
+
if (failure && typeof to === "object" && to !== null) failures.set(to, failure);
|
|
167
|
+
return to;
|
|
168
|
+
}
|
|
169
|
+
function logicErrorOf(result) {
|
|
170
|
+
return typeof result === "object" && result !== null && "logicError" in result ? result.logicError : void 0;
|
|
171
|
+
}
|
|
172
|
+
function thrownMessage(error) {
|
|
173
|
+
if (typeof error === "object" && error !== null && "message" in error) {
|
|
174
|
+
return String(error.message);
|
|
175
|
+
}
|
|
176
|
+
return String(error);
|
|
177
|
+
}
|
|
178
|
+
function thrownStack(error) {
|
|
179
|
+
if (typeof error === "object" && error !== null && "stack" in error) {
|
|
180
|
+
const stack = error.stack;
|
|
181
|
+
return typeof stack === "string" ? stack : void 0;
|
|
182
|
+
}
|
|
183
|
+
return void 0;
|
|
184
|
+
}
|
|
185
|
+
var INLINE_MAP = /\n\/\/# sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+)\s*$/;
|
|
186
|
+
var FRAME = /^\s*at (?:.*? \()?(.+?):(\d+):(\d+)\)?\s*$/;
|
|
187
|
+
var SourceMapRegistry = class {
|
|
188
|
+
maps = /* @__PURE__ */ new Map();
|
|
189
|
+
/**
|
|
190
|
+
* Remember the inline source map at the end of `code`, compiled under
|
|
191
|
+
* `filename`. Its sources are relative to the bundle's directory, which is
|
|
192
|
+
* the directory of the entrypoint (see `Transpile`).
|
|
193
|
+
*/
|
|
194
|
+
register(filename, code) {
|
|
195
|
+
const match = INLINE_MAP.exec(code);
|
|
196
|
+
if (!match?.[1]) {
|
|
197
|
+
this.maps.delete(filename);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
const payload = JSON.parse(Buffer.from(match[1], "base64").toString("utf-8"));
|
|
202
|
+
this.maps.set(filename, { map: new SourceMap(payload), base: dirname(filename) });
|
|
203
|
+
} catch {
|
|
204
|
+
this.maps.delete(filename);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
clear() {
|
|
208
|
+
this.maps.clear();
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Where `error` was thrown in source: the first stack frame inside a
|
|
212
|
+
* registered bundle that maps to the author's own code, or failing that to
|
|
213
|
+
* anything (such as a bundled dependency). Undefined when no frame is in a
|
|
214
|
+
* bundle, or the error carries no stack.
|
|
215
|
+
*/
|
|
216
|
+
locate(error) {
|
|
217
|
+
const stack = thrownStack(error);
|
|
218
|
+
if (!stack) return void 0;
|
|
219
|
+
let fallback;
|
|
220
|
+
for (const line of stack.split("\n")) {
|
|
221
|
+
const frame = FRAME.exec(line);
|
|
222
|
+
if (!frame?.[1] || !frame[2] || !frame[3]) continue;
|
|
223
|
+
const entry = this.maps.get(frame[1]);
|
|
224
|
+
if (!entry) continue;
|
|
225
|
+
const origin = entry.map.findOrigin(Number(frame[2]), Number(frame[3]));
|
|
226
|
+
if (!("fileName" in origin) || !origin.fileName) continue;
|
|
227
|
+
const located = {
|
|
228
|
+
file: isAbsolute(origin.fileName) ? origin.fileName : resolve(entry.base, origin.fileName),
|
|
229
|
+
line: origin.lineNumber,
|
|
230
|
+
column: origin.columnNumber
|
|
231
|
+
};
|
|
232
|
+
if (!located.file.split(sep).includes("node_modules")) return located;
|
|
233
|
+
fallback ??= located;
|
|
234
|
+
}
|
|
235
|
+
return fallback;
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
function describeLogicFailure(error, origin, maps, packagePath) {
|
|
239
|
+
const location = maps.locate(error);
|
|
240
|
+
const code = typeof error === "object" && error !== null ? error.code : void 0;
|
|
241
|
+
return {
|
|
242
|
+
...origin,
|
|
243
|
+
message: thrownMessage(error),
|
|
244
|
+
...code === LLM_NOT_CONFIGURED ? { errorCode: code } : {},
|
|
245
|
+
...location ? {
|
|
246
|
+
file: relative(realPath(packagePath), realPath(location.file)).split(sep).join("/"),
|
|
247
|
+
line: location.line,
|
|
248
|
+
column: location.column
|
|
249
|
+
} : {}
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// cli/execution/logic-loader.ts
|
|
254
|
+
import { isAbsolute as isAbsolute2, join } from "node:path";
|
|
255
|
+
import { compileFunction, createContext } from "node:vm";
|
|
256
|
+
var LogicLoader = class {
|
|
257
|
+
constructor(packagePath, deps) {
|
|
258
|
+
this.packagePath = packagePath;
|
|
259
|
+
this.deps = deps;
|
|
260
|
+
}
|
|
261
|
+
packagePath;
|
|
262
|
+
deps;
|
|
263
|
+
caches = {
|
|
264
|
+
engine: /* @__PURE__ */ new Map(),
|
|
265
|
+
tickController: /* @__PURE__ */ new Map(),
|
|
266
|
+
hook: /* @__PURE__ */ new Map(),
|
|
267
|
+
validator: /* @__PURE__ */ new Map(),
|
|
268
|
+
endpoint: /* @__PURE__ */ new Map()
|
|
269
|
+
};
|
|
270
|
+
logicContext;
|
|
271
|
+
/** Each evaluated bundle's source map, to read a thrown stack back to source. */
|
|
272
|
+
sourceMaps = new SourceMapRegistry();
|
|
273
|
+
/**
|
|
274
|
+
* Load the logic exports for `identifier` of the given `kind`, from cache
|
|
275
|
+
* when present. `resource` is the bundle whose logic to compile; a missing
|
|
276
|
+
* resource throws `notFoundMessage`.
|
|
277
|
+
*/
|
|
278
|
+
async load(kind, identifier, resource, notFoundMessage) {
|
|
279
|
+
const cache = this.caches[kind];
|
|
280
|
+
const cached = cache.get(identifier);
|
|
281
|
+
if (cached) {
|
|
282
|
+
return cached;
|
|
283
|
+
}
|
|
284
|
+
if (!resource) {
|
|
285
|
+
throw new Error(notFoundMessage);
|
|
286
|
+
}
|
|
287
|
+
const logicDirectory = resolveResourceDirectory(
|
|
288
|
+
this.packagePath,
|
|
289
|
+
resource.rootDirectory,
|
|
290
|
+
resource.logic.directory
|
|
291
|
+
);
|
|
292
|
+
const logicPath = join(logicDirectory, resource.logic.entrypoint);
|
|
293
|
+
const bundledCode = isPrecompiled(resource.rootDirectory, resource.logic.entrypoint) ? await this.deps.fs.readFile(logicPath, "utf-8") : await this.deps.transpile({
|
|
294
|
+
entrypoint: logicPath,
|
|
295
|
+
sourcemap: true,
|
|
296
|
+
packageRoot: this.packagePath
|
|
297
|
+
});
|
|
298
|
+
this.sourceMaps.register(logicPath, bundledCode);
|
|
299
|
+
const moduleObj = { exports: {} };
|
|
300
|
+
const func = compileFunction(bundledCode, ["module", "exports"], {
|
|
301
|
+
filename: logicPath,
|
|
302
|
+
parsingContext: this.getLogicContext()
|
|
303
|
+
});
|
|
304
|
+
func(moduleObj, moduleObj.exports);
|
|
305
|
+
const exports = moduleObj.exports;
|
|
306
|
+
cache.set(identifier, exports);
|
|
307
|
+
return exports;
|
|
308
|
+
}
|
|
309
|
+
/** Drop every cached bundle (used when configuration or code reloads). */
|
|
310
|
+
clearAll() {
|
|
311
|
+
for (const cache of Object.values(this.caches)) {
|
|
312
|
+
cache.clear();
|
|
313
|
+
}
|
|
314
|
+
this.sourceMaps.clear();
|
|
315
|
+
}
|
|
316
|
+
/** Drop a single cached bundle so its next load re-transpiles it. */
|
|
317
|
+
invalidate(kind, identifier) {
|
|
318
|
+
this.caches[kind].delete(identifier);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* The shared bare-V8 global scope every logic bundle is evaluated in.
|
|
322
|
+
*
|
|
323
|
+
* A fresh vm context exposes only the ECMAScript intrinsics — the
|
|
324
|
+
* environment the production runtime guarantees (SPECIFICATION.md §3.2).
|
|
325
|
+
* Host globals such as `structuredClone`, `fetch`, `setTimeout`,
|
|
326
|
+
* `TextEncoder`, and `process` are absent, so logic that reaches for one
|
|
327
|
+
* throws a `ReferenceError` here exactly as it would in production, instead
|
|
328
|
+
* of silently working against Node's globals and only failing on deploy.
|
|
329
|
+
* (`console` is provided by a shim the transpiler compiles into each bundle.)
|
|
330
|
+
*/
|
|
331
|
+
getLogicContext() {
|
|
332
|
+
if (!this.logicContext) {
|
|
333
|
+
this.logicContext = createContext({});
|
|
334
|
+
}
|
|
335
|
+
return this.logicContext;
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
function resolveResourceDirectory(packagePath, rootDirectory, logicDirectory) {
|
|
339
|
+
if (isAbsolute2(rootDirectory)) {
|
|
340
|
+
return join(rootDirectory, logicDirectory);
|
|
341
|
+
}
|
|
342
|
+
return join(packagePath, rootDirectory, logicDirectory);
|
|
343
|
+
}
|
|
344
|
+
function isPrecompiled(rootDirectory, entrypoint) {
|
|
345
|
+
return isAbsolute2(rootDirectory) && entrypoint.endsWith(".js");
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// cli/runtime/context-merge.ts
|
|
349
|
+
var UNSAFE_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
350
|
+
function isPlainObject(value) {
|
|
351
|
+
if (value === null || typeof value !== "object") return false;
|
|
352
|
+
if (Array.isArray(value)) return false;
|
|
353
|
+
const proto = Object.getPrototypeOf(value);
|
|
354
|
+
if (proto === null || proto === Object.prototype) return true;
|
|
355
|
+
return Object.getPrototypeOf(proto) === null;
|
|
356
|
+
}
|
|
357
|
+
function deepMergeContext(base, patch) {
|
|
358
|
+
const result = { ...base };
|
|
359
|
+
for (const key of Object.keys(patch)) {
|
|
360
|
+
if (UNSAFE_KEYS.has(key)) continue;
|
|
361
|
+
const baseValue = result[key];
|
|
362
|
+
const patchValue = patch[key];
|
|
363
|
+
result[key] = isPlainObject(baseValue) && isPlainObject(patchValue) ? deepMergeContext(baseValue, patchValue) : patchValue;
|
|
364
|
+
}
|
|
365
|
+
return result;
|
|
366
|
+
}
|
|
367
|
+
function segmentsOf(path) {
|
|
368
|
+
return typeof path === "string" ? path.split(".") : [...path];
|
|
369
|
+
}
|
|
370
|
+
function deletePath(base, path) {
|
|
371
|
+
const segments = segmentsOf(path);
|
|
372
|
+
if (segments.length === 0 || segments.some((segment) => UNSAFE_KEYS.has(segment))) {
|
|
373
|
+
return base;
|
|
374
|
+
}
|
|
375
|
+
const [head, ...rest] = segments;
|
|
376
|
+
if (!Object.prototype.hasOwnProperty.call(base, head)) return base;
|
|
377
|
+
if (rest.length === 0) {
|
|
378
|
+
const result = { ...base };
|
|
379
|
+
delete result[head];
|
|
380
|
+
return result;
|
|
381
|
+
}
|
|
382
|
+
const child = base[head];
|
|
383
|
+
if (!isPlainObject(child)) return base;
|
|
384
|
+
const prunedChild = deletePath(child, rest);
|
|
385
|
+
if (prunedChild === child) return base;
|
|
386
|
+
return { ...base, [head]: prunedChild };
|
|
387
|
+
}
|
|
388
|
+
function applyContextUpdate(base, patch, deletes) {
|
|
389
|
+
const merged = deepMergeContext(base, patch);
|
|
390
|
+
if (!deletes || deletes.length === 0) return merged;
|
|
391
|
+
return deletes.reduce((context, path) => deletePath(context, path), merged);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// cli/execution/config-resolver.ts
|
|
395
|
+
var ConfigResolver = class {
|
|
396
|
+
constructor(ctx) {
|
|
397
|
+
this.ctx = ctx;
|
|
398
|
+
}
|
|
399
|
+
ctx;
|
|
400
|
+
sessionOverrides = null;
|
|
401
|
+
// -- Session-override cache ------------------------------------
|
|
402
|
+
hasSessionOverrides() {
|
|
403
|
+
return this.sessionOverrides !== null;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Directly set the session-override layer in memory. Used by the dev
|
|
407
|
+
* server in in-memory mode so config UI changes are captured without
|
|
408
|
+
* writing to disk.
|
|
409
|
+
*/
|
|
410
|
+
setConfiguration(config) {
|
|
411
|
+
this.sessionOverrides = config;
|
|
412
|
+
}
|
|
413
|
+
/** Return the current in-memory session-override layer, if any. */
|
|
414
|
+
getSessionOverrides() {
|
|
415
|
+
return this.sessionOverrides;
|
|
416
|
+
}
|
|
417
|
+
/** Drop the cached session-override layer so the next load rebuilds it. */
|
|
418
|
+
clearSessionOverrides() {
|
|
419
|
+
this.sessionOverrides = null;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Start the session-override layer for an in-memory session.
|
|
423
|
+
*
|
|
424
|
+
* Empty, because nobody has overridden anything yet (§8.2). The resolved
|
|
425
|
+
* values a surface needs come from {@link resolveConfiguration}, which
|
|
426
|
+
* re-layers on demand; storing them here instead would freeze the layers
|
|
427
|
+
* beneath and make the active scenario unchangeable.
|
|
428
|
+
*/
|
|
429
|
+
regenerateInMemoryConfiguration() {
|
|
430
|
+
this.sessionOverrides = {};
|
|
431
|
+
}
|
|
432
|
+
// -- Scenario resolution -------------------------------------------------
|
|
433
|
+
/**
|
|
434
|
+
* Resolve the active scenario from a provided ID or the game's default.
|
|
435
|
+
* Returns null if the game declares no scenarios, or when null is passed
|
|
436
|
+
* for a game with no default scenario (the settings defaults).
|
|
437
|
+
*
|
|
438
|
+
* A game that declares a default never runs on none (§6.7), so null is
|
|
439
|
+
* refused for it, naming the default.
|
|
440
|
+
*/
|
|
441
|
+
resolveScenario(scenarioId) {
|
|
442
|
+
const game = this.ctx.getGame();
|
|
443
|
+
const config = this.ctx.getConfig();
|
|
444
|
+
if (scenarioId === null) {
|
|
445
|
+
const fallback = config?.scenarios?.find((s) => s.definition.default);
|
|
446
|
+
if (fallback) {
|
|
447
|
+
throw new DeniedError(
|
|
448
|
+
`This game runs on a scenario: its default is "${fallback.definition.identifier}", so it cannot run on none`
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
453
|
+
if (!game || !config) return null;
|
|
454
|
+
const allScenarios = config.scenarios || [];
|
|
455
|
+
if (allScenarios.length === 0) return null;
|
|
456
|
+
if (scenarioId) {
|
|
457
|
+
const scenario = allScenarios.find((s) => s.definition.identifier === scenarioId);
|
|
458
|
+
if (!scenario) {
|
|
459
|
+
throw new Error(`Scenario "${scenarioId}" not found in package`);
|
|
460
|
+
}
|
|
461
|
+
return scenario;
|
|
462
|
+
}
|
|
463
|
+
return allScenarios.find((s) => s.definition.default) ?? null;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Reject undeclared keys in the given scenario's overrides, validating them
|
|
467
|
+
* against each settings resource's `settingsSchema` exactly as
|
|
468
|
+
* `configuration.json` is validated on load.
|
|
469
|
+
*
|
|
470
|
+
* Mutates nothing and reads no disk, so dev-server boundaries (file-watch
|
|
471
|
+
* reload, scenario switch) can call it before committing and keep the
|
|
472
|
+
* last-good session running when it throws. Throws with the offending keys
|
|
473
|
+
* named and remediation guidance when invalid.
|
|
474
|
+
*/
|
|
475
|
+
assertLayeredSettingsValid(scenario) {
|
|
476
|
+
const config = this.ctx.getConfig();
|
|
477
|
+
if (!this.ctx.getGame() || !config || !scenario?.definition.settings) return;
|
|
478
|
+
const result = validateSettingsOverrides(
|
|
479
|
+
scenario.definition.settings,
|
|
480
|
+
settingsSchemas(config),
|
|
481
|
+
`Scenario "${scenario.definition.identifier}"`
|
|
482
|
+
);
|
|
483
|
+
if (!result.valid && result.errors) {
|
|
484
|
+
throw new Error(
|
|
485
|
+
`Scenario settings do not match the settings resources they name:
|
|
486
|
+
${result.errors}
|
|
487
|
+
|
|
488
|
+
Either side can be the stale one, so check both:
|
|
489
|
+
- the scenario's settings, in its scenario.sdk.json
|
|
490
|
+
- the settingsSchema, in the settings.sdk.json it names
|
|
491
|
+
|
|
492
|
+
Both are authored files. Correct whichever has fallen behind.`
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
// -- Settings layering ---------------------------------------------------
|
|
497
|
+
/**
|
|
498
|
+
* Resolve every settings resource through the §8.2 layers, in order: its
|
|
499
|
+
* schema defaults, then the active scenario's overrides, then the session
|
|
500
|
+
* overrides.
|
|
501
|
+
*
|
|
502
|
+
* Every layer contributes and none replaces. The session layer used to
|
|
503
|
+
* short-circuit the others, which worked only because it was a generated
|
|
504
|
+
* snapshot containing them all; the moment it held what a facilitator
|
|
505
|
+
* actually changed, everything they had not touched went missing (§8.2).
|
|
506
|
+
*
|
|
507
|
+
* Without the session layer, it is what a surface shown outside the
|
|
508
|
+
* session reads, such as a presentation with no session (§6.15.1).
|
|
509
|
+
*/
|
|
510
|
+
resolveSettings({ sessionLayer = true } = {}) {
|
|
511
|
+
return this.resolveLayers(
|
|
512
|
+
this.ctx.getActiveScenario(),
|
|
513
|
+
sessionLayer ? this.sessionOverrides : null
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* The same layering over any scenario and any top layer, touching neither
|
|
518
|
+
* the active scenario nor the session's own layer. What the scenario
|
|
519
|
+
* editor's draft resolves through (§6.5): the scenario being edited, then
|
|
520
|
+
* the editor's unsaved edits.
|
|
521
|
+
*/
|
|
522
|
+
resolveLayers(scenario, overrides) {
|
|
523
|
+
const config = this.ctx.getConfig();
|
|
524
|
+
if (!this.ctx.getGame() || !config) return {};
|
|
525
|
+
return resolveSettingsLayers(
|
|
526
|
+
config,
|
|
527
|
+
scenario?.definition.settings ?? null,
|
|
528
|
+
overrides
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* The settings a resource receives: exactly the ones it lists in
|
|
533
|
+
* `settings`, keyed by identifier (§8). A resource that lists none
|
|
534
|
+
* receives none, on the same terms as an undeclared capability (§7.4).
|
|
535
|
+
*/
|
|
536
|
+
settingsFor(declaration) {
|
|
537
|
+
const resolved = this.resolveSettings();
|
|
538
|
+
return Object.fromEntries(
|
|
539
|
+
(declaration.settings ?? []).filter((identifier) => identifier in resolved).map((identifier) => [identifier, resolved[identifier]])
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
// -- Session-override build & persistence ----------------------
|
|
543
|
+
/**
|
|
544
|
+
* Load session-override layer from disk.
|
|
545
|
+
* @param reconfigure - If true, regenerate an invalid configuration rather
|
|
546
|
+
* than throwing. Reserved for a caller that knows the file is disposable.
|
|
547
|
+
*/
|
|
548
|
+
async loadSessionSettingsOverrides(reconfigure = false) {
|
|
549
|
+
const game = this.ctx.getGame();
|
|
550
|
+
const config = this.ctx.getConfig();
|
|
551
|
+
if (!game || !config) {
|
|
552
|
+
throw new Error("Game not initialized");
|
|
553
|
+
}
|
|
554
|
+
if (this.ctx.inMemory) {
|
|
555
|
+
this.sessionOverrides = {};
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
const configPath = this.ctx.deps.configStore.getPath(this.ctx.packagePath);
|
|
559
|
+
if (!this.ctx.deps.fs.existsSync(configPath)) {
|
|
560
|
+
throw new Error(
|
|
561
|
+
`Session settings file not found: ${configPath}. Run 'pnpm run sdk init' first.`
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
let loadedConfig;
|
|
565
|
+
try {
|
|
566
|
+
const content = await this.ctx.deps.fs.readFile(configPath, "utf-8");
|
|
567
|
+
loadedConfig = JSON.parse(content);
|
|
568
|
+
} catch (error) {
|
|
569
|
+
throw new Error(
|
|
570
|
+
`Failed to load the session settings file: ${error.message}`
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
const validationResult = validateSessionOverrides(loadedConfig, settingsSchemas(config));
|
|
574
|
+
if (!validationResult.valid) {
|
|
575
|
+
if (reconfigure) {
|
|
576
|
+
console.warn(
|
|
577
|
+
`Session settings validation failed (schema may have changed). Regenerating them:
|
|
578
|
+
${validationResult.errors}`
|
|
579
|
+
);
|
|
580
|
+
await this.saveGameConfiguration();
|
|
581
|
+
} else {
|
|
582
|
+
throw new Error(
|
|
583
|
+
`Session settings are invalid or incompatible with current schemas:
|
|
584
|
+
${validationResult.errors}
|
|
585
|
+
|
|
586
|
+
It is authored content, so correct it in place:
|
|
587
|
+
${configPath}
|
|
588
|
+
Deleting the file starts again from the schema defaults.`
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
} else {
|
|
592
|
+
this.sessionOverrides = loadedConfig;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* The settings with the session-override layer ignored: defaults and the
|
|
597
|
+
* active scenario alone. Used by the dev server's 'Reset configuration'
|
|
598
|
+
* action so the operator can return to a clean slate without restarting.
|
|
599
|
+
*/
|
|
600
|
+
buildResetConfiguration() {
|
|
601
|
+
const cached = this.sessionOverrides;
|
|
602
|
+
this.sessionOverrides = null;
|
|
603
|
+
try {
|
|
604
|
+
return this.resolveConfiguration();
|
|
605
|
+
} finally {
|
|
606
|
+
this.sessionOverrides = cached;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Every settings resource's resolved values, right now: what a settings
|
|
611
|
+
* editor is seeded with (§8.3), what a save-as-scenario flow
|
|
612
|
+
* bakes in, and what an operator surface displays. Recomputed on demand
|
|
613
|
+
* precisely so a scenario change is reflected in it.
|
|
614
|
+
*/
|
|
615
|
+
resolveConfiguration() {
|
|
616
|
+
return this.resolveSettings();
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Establish the session-override layer for a fresh session (§8.2).
|
|
620
|
+
*
|
|
621
|
+
* It starts empty and stays empty until something session-scoped writes to
|
|
622
|
+
* it, which for a game with no `setup` slot is never (§8.3). This
|
|
623
|
+
* used to persist a resolved snapshot instead, and because the session layer
|
|
624
|
+
* outranks the scenario, every value the snapshot carried down from one
|
|
625
|
+
* scenario then suppressed the next: selecting a different scenario changed
|
|
626
|
+
* the label and nothing else.
|
|
627
|
+
*/
|
|
628
|
+
async saveGameConfiguration() {
|
|
629
|
+
const game = this.ctx.getGame();
|
|
630
|
+
const config = this.ctx.getConfig();
|
|
631
|
+
if (!game || !config) {
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
this.sessionOverrides = {};
|
|
635
|
+
if (this.ctx.inMemory) return;
|
|
636
|
+
await this.ctx.deps.configStore.save(this.ctx.packagePath, {});
|
|
637
|
+
await this.ctx.deps.configStore.saveScenario(
|
|
638
|
+
this.ctx.packagePath,
|
|
639
|
+
this.ctx.getActiveScenario()?.definition.identifier ?? null
|
|
640
|
+
);
|
|
641
|
+
await this.loadSessionSettingsOverrides();
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
function resolveSettingsLayers(config, scenarioSettings, overrides) {
|
|
645
|
+
const resolved = {};
|
|
646
|
+
for (const settings of config.settings ?? []) {
|
|
647
|
+
const identifier = settings.definition.identifier;
|
|
648
|
+
resolved[identifier] = deepMergeContext(
|
|
649
|
+
deepMergeContext(
|
|
650
|
+
applySchemaDefaults(settings.definition.settingsSchema),
|
|
651
|
+
scenarioSettings?.[identifier] ?? {}
|
|
652
|
+
),
|
|
653
|
+
overrides?.[identifier] ?? {}
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
return resolved;
|
|
657
|
+
}
|
|
658
|
+
function applySchemaDefaults(configSchema) {
|
|
659
|
+
const config = {};
|
|
660
|
+
if (configSchema?.properties) {
|
|
661
|
+
for (const [key, propSchema] of Object.entries(configSchema.properties)) {
|
|
662
|
+
if (propSchema && typeof propSchema === "object" && "default" in propSchema) {
|
|
663
|
+
config[key] = propSchema.default;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
return config;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// cli/runtime/guarded-callbacks.ts
|
|
671
|
+
var API_USE_TO_CALLBACK = {
|
|
672
|
+
generateText: "generateText",
|
|
673
|
+
extractText: "extractText",
|
|
674
|
+
generateSpeech: "generateSpeech",
|
|
675
|
+
writeBlob: "writeBlob"
|
|
676
|
+
};
|
|
677
|
+
function createGuardedCallbacks(callbacks, uses, resourceIdentifier) {
|
|
678
|
+
const declared = new Set(uses ?? []);
|
|
679
|
+
const guarded = { ...callbacks };
|
|
680
|
+
for (const [api, key] of Object.entries(API_USE_TO_CALLBACK)) {
|
|
681
|
+
if (declared.has(api)) continue;
|
|
682
|
+
if (callbacks[key] === void 0) continue;
|
|
683
|
+
guarded[key] = async () => {
|
|
684
|
+
throw new UndeclaredApiUseError(resourceIdentifier, api);
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
return guarded;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// cli/services/tts/elevenlabs.ts
|
|
691
|
+
var ELEVENLABS_DEFAULT_MODELS = {
|
|
692
|
+
quick: "eleven_flash_v2_5",
|
|
693
|
+
standard: "eleven_turbo_v2_5",
|
|
694
|
+
expert: "eleven_multilingual_v2"
|
|
695
|
+
};
|
|
696
|
+
var ELEVENLABS_DEFAULT_VOICE_ID = "21m00Tcm4TlvDq8ikWAM";
|
|
697
|
+
var FORMAT_TO_OUTPUT_FORMAT = {
|
|
698
|
+
mp3: "mp3_44100_128",
|
|
699
|
+
opus: "opus_48000_64",
|
|
700
|
+
// WAV is requested as PCM and clients decode the WAV header from the
|
|
701
|
+
// mp3 fallback when 'pcm_16000' is unavailable. ElevenLabs supports
|
|
702
|
+
// 'pcm_16000' on the multilingual model.
|
|
703
|
+
wav: "pcm_16000"
|
|
704
|
+
};
|
|
705
|
+
var FORMAT_TO_MIME = {
|
|
706
|
+
mp3: "audio/mpeg",
|
|
707
|
+
opus: "audio/ogg",
|
|
708
|
+
wav: "audio/wav"
|
|
709
|
+
};
|
|
710
|
+
var ElevenLabsAdapter = class {
|
|
711
|
+
name = "elevenlabs";
|
|
712
|
+
apiKey;
|
|
713
|
+
fetchImpl;
|
|
714
|
+
constructor(config) {
|
|
715
|
+
this.apiKey = config.apiKey;
|
|
716
|
+
this.fetchImpl = config.fetchImpl ?? fetch;
|
|
717
|
+
}
|
|
718
|
+
defaultVoice() {
|
|
719
|
+
return ELEVENLABS_DEFAULT_VOICE_ID;
|
|
720
|
+
}
|
|
721
|
+
clampSpeed(speed) {
|
|
722
|
+
if (!Number.isFinite(speed)) return 1;
|
|
723
|
+
return Math.max(0.7, Math.min(1.2, speed));
|
|
724
|
+
}
|
|
725
|
+
async synthesize(request) {
|
|
726
|
+
const outputFormat = FORMAT_TO_OUTPUT_FORMAT[request.format] ?? "mp3_44100_128";
|
|
727
|
+
const mimeType = FORMAT_TO_MIME[request.format] ?? "audio/mpeg";
|
|
728
|
+
const url = new URL(`https://api.elevenlabs.io/v1/text-to-speech/${request.voice}`);
|
|
729
|
+
url.searchParams.set("output_format", outputFormat);
|
|
730
|
+
const voiceSettings = {};
|
|
731
|
+
if (request.speed !== void 0) {
|
|
732
|
+
voiceSettings.speed = request.speed;
|
|
733
|
+
}
|
|
734
|
+
const body = {
|
|
735
|
+
text: request.text,
|
|
736
|
+
model_id: request.model
|
|
737
|
+
};
|
|
738
|
+
if (request.languageHint) {
|
|
739
|
+
body.language_code = request.languageHint;
|
|
740
|
+
}
|
|
741
|
+
if (Object.keys(voiceSettings).length > 0) {
|
|
742
|
+
body.voice_settings = voiceSettings;
|
|
743
|
+
}
|
|
744
|
+
const response = await this.fetchImpl(url.toString(), {
|
|
745
|
+
method: "POST",
|
|
746
|
+
headers: {
|
|
747
|
+
"xi-api-key": this.apiKey,
|
|
748
|
+
"Content-Type": "application/json",
|
|
749
|
+
Accept: mimeType
|
|
750
|
+
},
|
|
751
|
+
body: JSON.stringify(body)
|
|
752
|
+
});
|
|
753
|
+
if (!response.ok) {
|
|
754
|
+
const message = await safeReadText(response);
|
|
755
|
+
throw new Error(
|
|
756
|
+
`ElevenLabs synthesis failed (${response.status} ${response.statusText}): ${message}`
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
const audioBuffer = await response.arrayBuffer();
|
|
760
|
+
const audio = new Uint8Array(audioBuffer);
|
|
761
|
+
return {
|
|
762
|
+
audio,
|
|
763
|
+
mimeType,
|
|
764
|
+
charactersBilled: charactersFromHeader(response.headers) ?? request.text.length
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
async function safeReadText(response) {
|
|
769
|
+
try {
|
|
770
|
+
return await response.text();
|
|
771
|
+
} catch {
|
|
772
|
+
return "<unreadable response body>";
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
function charactersFromHeader(headers) {
|
|
776
|
+
const raw = headers.get("character-cost");
|
|
777
|
+
if (!raw) return void 0;
|
|
778
|
+
const n = Number.parseInt(raw, 10);
|
|
779
|
+
return Number.isNaN(n) ? void 0 : n;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// cli/services/tts/client.ts
|
|
783
|
+
var TtsClientError = class extends Error {
|
|
784
|
+
constructor(message) {
|
|
785
|
+
super(message);
|
|
786
|
+
this.name = "TtsClientError";
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
var TtsClient = class {
|
|
790
|
+
provider;
|
|
791
|
+
quickModel;
|
|
792
|
+
standardModel;
|
|
793
|
+
expertModel;
|
|
794
|
+
voicePresets;
|
|
795
|
+
constructor(config) {
|
|
796
|
+
this.quickModel = config.quickModel ?? ELEVENLABS_DEFAULT_MODELS.quick;
|
|
797
|
+
this.standardModel = config.standardModel;
|
|
798
|
+
this.expertModel = config.expertModel;
|
|
799
|
+
this.voicePresets = { ...config.voicePresets };
|
|
800
|
+
if (config.provider) {
|
|
801
|
+
this.provider = config.provider;
|
|
802
|
+
} else if (config.elevenLabsApiKey) {
|
|
803
|
+
this.provider = new ElevenLabsAdapter({ apiKey: config.elevenLabsApiKey });
|
|
804
|
+
} else {
|
|
805
|
+
this.provider = null;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
/** Whether the client is configured to make TTS calls. */
|
|
809
|
+
isConfigured() {
|
|
810
|
+
return this.provider !== null;
|
|
811
|
+
}
|
|
812
|
+
async generateSpeech(requestOrText) {
|
|
813
|
+
if (!this.provider) {
|
|
814
|
+
throw new TtsClientError(this.buildConfigurationError());
|
|
815
|
+
}
|
|
816
|
+
const request = typeof requestOrText === "string" ? { text: requestOrText } : requestOrText;
|
|
817
|
+
if (!request.text || request.text.length === 0) {
|
|
818
|
+
throw new TtsClientError("generateSpeech requires a non-empty `text` field");
|
|
819
|
+
}
|
|
820
|
+
const format = request.format ?? "mp3";
|
|
821
|
+
const tier = request.tier ?? "quick";
|
|
822
|
+
const model = this.resolveModel(tier);
|
|
823
|
+
const voice = this.resolveVoice(request.voice);
|
|
824
|
+
const speed = request.speed !== void 0 ? this.provider.clampSpeed(request.speed) : void 0;
|
|
825
|
+
const result = await this.provider.synthesize({
|
|
826
|
+
text: request.text,
|
|
827
|
+
voice,
|
|
828
|
+
model,
|
|
829
|
+
format,
|
|
830
|
+
tier,
|
|
831
|
+
...request.languageHint ? { languageHint: request.languageHint } : {},
|
|
832
|
+
...speed !== void 0 ? { speed } : {}
|
|
833
|
+
});
|
|
834
|
+
const response = {
|
|
835
|
+
reference: "",
|
|
836
|
+
audio: result.audio,
|
|
837
|
+
mimeType: result.mimeType
|
|
838
|
+
};
|
|
839
|
+
if (result.durationMs !== void 0) {
|
|
840
|
+
response.durationMs = result.durationMs;
|
|
841
|
+
}
|
|
842
|
+
if (result.charactersBilled !== void 0) {
|
|
843
|
+
response.charactersBilled = result.charactersBilled;
|
|
844
|
+
}
|
|
845
|
+
return response;
|
|
846
|
+
}
|
|
847
|
+
resolveModel(tier) {
|
|
848
|
+
switch (tier) {
|
|
849
|
+
case "expert":
|
|
850
|
+
return this.expertModel ?? this.standardModel ?? this.quickModel;
|
|
851
|
+
case "standard":
|
|
852
|
+
return this.standardModel ?? this.quickModel;
|
|
853
|
+
case "quick":
|
|
854
|
+
default:
|
|
855
|
+
return this.quickModel;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
resolveVoice(preset) {
|
|
859
|
+
if (!this.provider) {
|
|
860
|
+
throw new TtsClientError("No TTS provider configured");
|
|
861
|
+
}
|
|
862
|
+
if (preset) {
|
|
863
|
+
const configured = this.voicePresets[preset];
|
|
864
|
+
if (configured) return configured;
|
|
865
|
+
}
|
|
866
|
+
const neutral = this.voicePresets.neutral;
|
|
867
|
+
if (neutral) return neutral;
|
|
868
|
+
return this.provider.defaultVoice();
|
|
869
|
+
}
|
|
870
|
+
buildConfigurationError() {
|
|
871
|
+
return `
|
|
872
|
+
Text-to-speech Not Configured
|
|
873
|
+
================================
|
|
874
|
+
|
|
875
|
+
This game uses generateSpeech, but no TTS provider is configured in this
|
|
876
|
+
development environment. The dev server's v1 adapter is ElevenLabs.
|
|
877
|
+
|
|
878
|
+
Set the API key via .env, an environment variable, or a CLI flag:
|
|
879
|
+
|
|
880
|
+
ELEVENLABS_API_KEY=...
|
|
881
|
+
TTS_MODEL_QUICK=eleven_flash_v2_5 # Optional
|
|
882
|
+
TTS_MODEL_STANDARD=eleven_turbo_v2_5 # Optional, falls back to quick
|
|
883
|
+
TTS_MODEL_EXPERT=eleven_multilingual_v2 # Optional, falls back to standard
|
|
884
|
+
TTS_VOICE_NEUTRAL=<voice-id> # Optional, falls back to ElevenLabs default
|
|
885
|
+
TTS_VOICE_NARRATOR=<voice-id> # Optional, falls back to neutral
|
|
886
|
+
TTS_VOICE_ANNOUNCER=<voice-id> # Optional, falls back to neutral
|
|
887
|
+
TTS_VOICE_EXECUTIVE=<voice-id> # Optional, falls back to neutral
|
|
888
|
+
TTS_VOICE_COACH=<voice-id> # Optional, falls back to neutral
|
|
889
|
+
|
|
890
|
+
Browse voices at https://elevenlabs.io/voices.
|
|
891
|
+
`.trim();
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
// cli/utils/document-parser-client.ts
|
|
896
|
+
var DocumentParserError = class extends Error {
|
|
897
|
+
constructor(message) {
|
|
898
|
+
super(message);
|
|
899
|
+
this.name = "DocumentParserError";
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
var SUPPORTED_MIME_TYPES = /* @__PURE__ */ new Set(["application/pdf"]);
|
|
903
|
+
var DocumentParserClient = class {
|
|
904
|
+
/**
|
|
905
|
+
* Extract text content from a document.
|
|
906
|
+
*
|
|
907
|
+
* @param data - Raw binary data of the document
|
|
908
|
+
* @param mimeType - MIME type of the document
|
|
909
|
+
* @returns Extracted text content and source MIME type
|
|
910
|
+
*/
|
|
911
|
+
async extractText(data, mimeType) {
|
|
912
|
+
if (!SUPPORTED_MIME_TYPES.has(mimeType)) {
|
|
913
|
+
throw new DocumentParserError(
|
|
914
|
+
`Unsupported file type: ${mimeType}. Supported types: ${[...SUPPORTED_MIME_TYPES].join(", ")}`
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
return this.extractPdf(data);
|
|
918
|
+
}
|
|
919
|
+
async extractPdf(data) {
|
|
920
|
+
try {
|
|
921
|
+
const { extractText } = await import("unpdf");
|
|
922
|
+
const input = data instanceof Buffer ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : data;
|
|
923
|
+
const result = await extractText(input, { mergePages: true });
|
|
924
|
+
return {
|
|
925
|
+
content: result.text,
|
|
926
|
+
mimeType: "application/pdf"
|
|
927
|
+
};
|
|
928
|
+
} catch (error) {
|
|
929
|
+
if (error instanceof DocumentParserError) throw error;
|
|
930
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
931
|
+
throw new DocumentParserError(`Failed to extract text from PDF: ${message}`);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
|
|
936
|
+
// cli/execution/executor-callbacks.ts
|
|
937
|
+
function createExecutorCallbacks(deps) {
|
|
938
|
+
const requireGame = () => {
|
|
939
|
+
const game = deps.getGame();
|
|
940
|
+
if (!game) throw new Error("No game loaded");
|
|
941
|
+
return game;
|
|
942
|
+
};
|
|
943
|
+
const callbacks = {
|
|
944
|
+
generateText: async (optionsOrPrompt) => {
|
|
945
|
+
return deps.llmClient.generateText(optionsOrPrompt);
|
|
946
|
+
},
|
|
947
|
+
// §12.5, offered to logic on the same terms as to a surface. Not
|
|
948
|
+
// `uses`-gated: it reads state this resource already declared, one tick
|
|
949
|
+
// further back.
|
|
950
|
+
getPastState: async (query) => {
|
|
951
|
+
if (!deps.readPastState) return [];
|
|
952
|
+
const scoped = deps.getScopedTeamIndexes();
|
|
953
|
+
const own = scoped ?? deps.getAllTeamIndexes();
|
|
954
|
+
const teams = query.teams === void 0 || query.teams === "own" ? own : query.teams === "all" ? deps.getAllTeamIndexes() : deps.getAllTeamIndexes().filter((index) => `team-${index + 1}` === query.teams);
|
|
955
|
+
return deps.readPastState(
|
|
956
|
+
{
|
|
957
|
+
fromTick: query.fromTick,
|
|
958
|
+
...query.toTick === void 0 ? {} : { toTick: query.toTick },
|
|
959
|
+
...query.capabilityIds === void 0 ? {} : { capabilityIds: query.capabilityIds }
|
|
960
|
+
},
|
|
961
|
+
teams
|
|
962
|
+
);
|
|
963
|
+
},
|
|
964
|
+
readAsset: async (reference) => {
|
|
965
|
+
requireGame();
|
|
966
|
+
const asset = await readAssetByReference(
|
|
967
|
+
deps.packagePath,
|
|
968
|
+
deps.getActiveScenarioRoot(),
|
|
969
|
+
reference
|
|
970
|
+
);
|
|
971
|
+
return {
|
|
972
|
+
data: new Uint8Array(asset.data),
|
|
973
|
+
mimeType: asset.mimeType,
|
|
974
|
+
name: asset.name
|
|
975
|
+
};
|
|
976
|
+
},
|
|
977
|
+
// Not `uses`-gated, like `readAsset`, and resolved exactly as it is,
|
|
978
|
+
// so a file one finds is one the other reads (§10.3).
|
|
979
|
+
describeAsset: async (reference) => {
|
|
980
|
+
requireGame();
|
|
981
|
+
return describeAssetByReference(
|
|
982
|
+
deps.packagePath,
|
|
983
|
+
deps.getActiveScenarioRoot(),
|
|
984
|
+
reference
|
|
985
|
+
);
|
|
986
|
+
},
|
|
987
|
+
extractText: async (reference) => {
|
|
988
|
+
requireGame();
|
|
989
|
+
const asset = await readAssetByReference(
|
|
990
|
+
deps.packagePath,
|
|
991
|
+
deps.getActiveScenarioRoot(),
|
|
992
|
+
reference
|
|
993
|
+
);
|
|
994
|
+
return deps.documentParserClient.extractText(asset.data, asset.mimeType);
|
|
995
|
+
},
|
|
996
|
+
generateSpeech: async (request) => {
|
|
997
|
+
requireGame();
|
|
998
|
+
const synthesised = await deps.ttsClient.generateSpeech(request);
|
|
999
|
+
const requestedFormat = typeof request === "string" ? "mp3" : request.format ?? "mp3";
|
|
1000
|
+
const blobId = await storeBlob(
|
|
1001
|
+
deps.packagePath,
|
|
1002
|
+
Buffer.from(synthesised.audio),
|
|
1003
|
+
`speech.${requestedFormat}`,
|
|
1004
|
+
synthesised.mimeType,
|
|
1005
|
+
deps.blobRetention ?? "game"
|
|
1006
|
+
);
|
|
1007
|
+
const response = {
|
|
1008
|
+
reference: `blob:${blobId}`,
|
|
1009
|
+
mimeType: synthesised.mimeType
|
|
1010
|
+
};
|
|
1011
|
+
if (synthesised.durationMs !== void 0) {
|
|
1012
|
+
response.durationMs = synthesised.durationMs;
|
|
1013
|
+
}
|
|
1014
|
+
if (synthesised.charactersBilled !== void 0) {
|
|
1015
|
+
response.charactersBilled = synthesised.charactersBilled;
|
|
1016
|
+
}
|
|
1017
|
+
return response;
|
|
1018
|
+
},
|
|
1019
|
+
writeBlob: async (data, options) => {
|
|
1020
|
+
const retention = options.retention ?? "game";
|
|
1021
|
+
if (retention !== "game" && retention !== "settings") {
|
|
1022
|
+
const hint = retention === "config" ? " ('config' was renamed 'settings')" : "";
|
|
1023
|
+
throw new Error(
|
|
1024
|
+
`writeBlob: retention must be 'game' or 'settings', got ${JSON.stringify(retention)}${hint}`
|
|
1025
|
+
);
|
|
1026
|
+
}
|
|
1027
|
+
requireGame();
|
|
1028
|
+
const buffer = Buffer.from(data instanceof Uint8Array ? data : new Uint8Array(data));
|
|
1029
|
+
const blobId = await storeBlob(
|
|
1030
|
+
deps.packagePath,
|
|
1031
|
+
buffer,
|
|
1032
|
+
options.name,
|
|
1033
|
+
options.mimeType,
|
|
1034
|
+
deps.blobRetention ?? retention
|
|
1035
|
+
);
|
|
1036
|
+
return `blob:${blobId}`;
|
|
1037
|
+
},
|
|
1038
|
+
...deps.callbackOverrides
|
|
1039
|
+
};
|
|
1040
|
+
return deps.takePlatformFailure ? withPlatformFailures(callbacks, deps.takePlatformFailure) : callbacks;
|
|
1041
|
+
}
|
|
1042
|
+
function withPlatformFailures(callbacks, take) {
|
|
1043
|
+
const check = (service, failure) => {
|
|
1044
|
+
const fired = take();
|
|
1045
|
+
if (!fired) return;
|
|
1046
|
+
throw new failure(
|
|
1047
|
+
`Injected llm-failure: ${service} failed` + (fired.reason === void 0 ? " (armed deliberately)" : `: ${fired.reason}`)
|
|
1048
|
+
);
|
|
1049
|
+
};
|
|
1050
|
+
const { generateText, extractText, generateSpeech } = callbacks;
|
|
1051
|
+
return {
|
|
1052
|
+
...callbacks,
|
|
1053
|
+
generateText: async (optionsOrPrompt) => {
|
|
1054
|
+
check("generateText", LLMClientError);
|
|
1055
|
+
return generateText(optionsOrPrompt);
|
|
1056
|
+
},
|
|
1057
|
+
...extractText === void 0 ? {} : {
|
|
1058
|
+
extractText: async (reference) => {
|
|
1059
|
+
check("extractText", DocumentParserError);
|
|
1060
|
+
return extractText(reference);
|
|
1061
|
+
}
|
|
1062
|
+
},
|
|
1063
|
+
...generateSpeech === void 0 ? {} : {
|
|
1064
|
+
generateSpeech: async (request) => {
|
|
1065
|
+
check("generateSpeech", TtsClientError);
|
|
1066
|
+
return generateSpeech(request);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
// cli/execution/logic-calls.ts
|
|
1073
|
+
var DEFAULT_LOGIC_EXECUTION_BOUND_MS = 3e4;
|
|
1074
|
+
var DEFAULT_TICK_EXECUTION_BOUND_MS = 12e4;
|
|
1075
|
+
var LogicCalls = class {
|
|
1076
|
+
constructor(options) {
|
|
1077
|
+
this.options = options;
|
|
1078
|
+
}
|
|
1079
|
+
options;
|
|
1080
|
+
/** The session locale, surfaced as `meta.locale`. */
|
|
1081
|
+
locale = "en";
|
|
1082
|
+
/**
|
|
1083
|
+
* The session's random seed, surfaced to logic as `meta.seed`. Fixed rather
|
|
1084
|
+
* than drawn so a CLI run is reproducible by default: a game that wants a
|
|
1085
|
+
* different world each session gets one from the host calling `setSeed`,
|
|
1086
|
+
* which the dev server does and persists.
|
|
1087
|
+
*/
|
|
1088
|
+
seed = "seriousgaming-sdk";
|
|
1089
|
+
/**
|
|
1090
|
+
* Which kind of run this executor is driving, surfaced to logic as
|
|
1091
|
+
* `meta.runKind`. Host-owned like the seed and the locale: the executor
|
|
1092
|
+
* carries it and changes no behaviour on it, because deciding what a
|
|
1093
|
+
* walkthrough should look like is the game's business, not ours.
|
|
1094
|
+
*/
|
|
1095
|
+
runKind = "session";
|
|
1096
|
+
/**
|
|
1097
|
+
* When the operation in progress started, or null between operations.
|
|
1098
|
+
* Held so every logic call in one operation reads the same `meta.now`
|
|
1099
|
+
* (§10.2). Set by {@link inOperation}, which serial callers alone use:
|
|
1100
|
+
* an endpoint runs beside the queue, so it is handed its instant instead.
|
|
1101
|
+
*/
|
|
1102
|
+
operationStartedAt = null;
|
|
1103
|
+
/** The session's participants, every team's, as the host holds them. */
|
|
1104
|
+
rosterSource = () => [];
|
|
1105
|
+
/**
|
|
1106
|
+
* Where `getPastState` reads from (§12.5). Supplied by the host after
|
|
1107
|
+
* construction, because the history lives in the session's team store and
|
|
1108
|
+
* that store is built around the executor.
|
|
1109
|
+
*/
|
|
1110
|
+
pastStateReader = null;
|
|
1111
|
+
teamIndexesForHistory = () => [];
|
|
1112
|
+
/** Team indexes the resource now running is scoped to; null is the session. */
|
|
1113
|
+
scopedTeamIndexes = null;
|
|
1114
|
+
/** See {@link setPlatformFailures}. */
|
|
1115
|
+
platformFailures = null;
|
|
1116
|
+
/**
|
|
1117
|
+
* Run `work` as one operation: every logic call inside it reads the same
|
|
1118
|
+
* `meta.now`, taken from the clock as it starts (§10.2). Nested calls join
|
|
1119
|
+
* the operation already running rather than starting their own, so a
|
|
1120
|
+
* cohort tick that runs each independent team separately, and the tick
|
|
1121
|
+
* controller evaluated after it, all read one instant.
|
|
1122
|
+
*/
|
|
1123
|
+
async inOperation(work) {
|
|
1124
|
+
if (this.operationStartedAt !== null) return work();
|
|
1125
|
+
this.operationStartedAt = this.options.clock.now();
|
|
1126
|
+
try {
|
|
1127
|
+
return await work();
|
|
1128
|
+
} finally {
|
|
1129
|
+
this.operationStartedAt = null;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
/** The instant the current operation started, or now when there is none. */
|
|
1133
|
+
operationNow() {
|
|
1134
|
+
return this.operationStartedAt ?? this.options.clock.now();
|
|
1135
|
+
}
|
|
1136
|
+
/** The clock's reading, outside any operation. */
|
|
1137
|
+
now() {
|
|
1138
|
+
return this.options.clock.now();
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* The session-wide half of `meta`, which every logic call receives.
|
|
1142
|
+
*
|
|
1143
|
+
* One builder rather than a literal per call site: `runKind` has to read
|
|
1144
|
+
* the same everywhere within a run (§5.7), and five hand-written copies is
|
|
1145
|
+
* five chances for a surface to disagree with the engine beside it.
|
|
1146
|
+
*/
|
|
1147
|
+
sessionMeta(tick) {
|
|
1148
|
+
return { ...this.meta(), tick };
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* The `meta` given to logic that runs outside the tick loop: hooks,
|
|
1152
|
+
* endpoints and validators. No `tick`, because none of them runs as
|
|
1153
|
+
* part of a tick.
|
|
1154
|
+
*/
|
|
1155
|
+
meta(now = this.operationNow()) {
|
|
1156
|
+
return {
|
|
1157
|
+
locale: this.locale,
|
|
1158
|
+
seed: this.seed,
|
|
1159
|
+
runKind: this.runKind,
|
|
1160
|
+
now,
|
|
1161
|
+
scenarioName: this.options.scenarioName()
|
|
1162
|
+
};
|
|
1163
|
+
}
|
|
1164
|
+
/** See {@link GameExecutor.setRosterSource}. */
|
|
1165
|
+
setRosterSource(source) {
|
|
1166
|
+
this.rosterSource = source;
|
|
1167
|
+
}
|
|
1168
|
+
/** Every participant in the session, as the host holds them. */
|
|
1169
|
+
roster() {
|
|
1170
|
+
return this.rosterSource();
|
|
1171
|
+
}
|
|
1172
|
+
/**
|
|
1173
|
+
* The participants on `teamIds`, in team order and then join order, as a
|
|
1174
|
+
* fresh copy: a call that changes its copy changes no other call's, and
|
|
1175
|
+
* not the roster (§10.2).
|
|
1176
|
+
*/
|
|
1177
|
+
participantsOn(teamIds) {
|
|
1178
|
+
const wanted = new Set(teamIds);
|
|
1179
|
+
return structuredClone(this.rosterSource().filter((p) => wanted.has(p.teamId)));
|
|
1180
|
+
}
|
|
1181
|
+
/** See {@link GameExecutor.setHistoryAccess}. */
|
|
1182
|
+
setHistoryAccess(access) {
|
|
1183
|
+
this.pastStateReader = access.read;
|
|
1184
|
+
this.teamIndexesForHistory = access.allTeamIndexes;
|
|
1185
|
+
}
|
|
1186
|
+
/** See {@link GameExecutor.setPlatformFailures}. */
|
|
1187
|
+
setPlatformFailures(take) {
|
|
1188
|
+
this.platformFailures = take;
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Run something with `getPastState`'s notion of 'own team' pinned to
|
|
1192
|
+
* `indexes`, restoring whatever was in force afterwards.
|
|
1193
|
+
*
|
|
1194
|
+
* Per-team work nests inside session-wide work (a tick loops over teams),
|
|
1195
|
+
* so this saves and restores rather than clearing: leaving it null after a
|
|
1196
|
+
* team's turn would silently widen the next read to the whole session.
|
|
1197
|
+
*/
|
|
1198
|
+
async withScopedTeams(indexes, run) {
|
|
1199
|
+
const previous = this.scopedTeamIndexes;
|
|
1200
|
+
this.scopedTeamIndexes = indexes;
|
|
1201
|
+
try {
|
|
1202
|
+
return await run();
|
|
1203
|
+
} finally {
|
|
1204
|
+
this.scopedTeamIndexes = previous;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* The callbacks a resource receives: the raw runtime callbacks, built
|
|
1209
|
+
* fresh so they read the live game, with every one its `uses` does not
|
|
1210
|
+
* declare replaced by a throwing stub.
|
|
1211
|
+
*
|
|
1212
|
+
* `onDraft` is a scenario-scoped call's: its files are the draft's, and
|
|
1213
|
+
* `asset:` resolves against the scenario being written, not the session's
|
|
1214
|
+
* (§6.5, §6.12, §16.2).
|
|
1215
|
+
*/
|
|
1216
|
+
callbacksFor(resourceIdentifier, uses, onDraft) {
|
|
1217
|
+
const raw = createExecutorCallbacks({
|
|
1218
|
+
...this.options.callbacks,
|
|
1219
|
+
...onDraft === void 0 ? {} : {
|
|
1220
|
+
blobRetention: "scenario",
|
|
1221
|
+
getActiveScenarioRoot: () => onDraft.scenarioRoot
|
|
1222
|
+
},
|
|
1223
|
+
readPastState: this.pastStateReader,
|
|
1224
|
+
getScopedTeamIndexes: () => this.scopedTeamIndexes,
|
|
1225
|
+
getAllTeamIndexes: () => this.teamIndexesForHistory(),
|
|
1226
|
+
takePlatformFailure: this.platformFailures
|
|
1227
|
+
});
|
|
1228
|
+
return createGuardedCallbacks(raw, uses, resourceIdentifier);
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Bound one call into author logic that runs as part of a tick, or of the
|
|
1232
|
+
* initialisation a tick starts from (§11.10).
|
|
1233
|
+
*
|
|
1234
|
+
* Each call is bounded rather than the tick as a whole, because a result
|
|
1235
|
+
* arriving after the bound must go nowhere: a race over one call discards
|
|
1236
|
+
* it, where a race over the whole tick would let the executor carry on and
|
|
1237
|
+
* commit the late result. The bound is longer than the per-call one,
|
|
1238
|
+
* because an engine may make several LLM calls in one run.
|
|
1239
|
+
*/
|
|
1240
|
+
tickBound(what, run, origin) {
|
|
1241
|
+
return this.bound(
|
|
1242
|
+
what,
|
|
1243
|
+
run,
|
|
1244
|
+
this.options.deps.tickExecutionBoundMs ?? DEFAULT_TICK_EXECUTION_BOUND_MS,
|
|
1245
|
+
origin
|
|
1246
|
+
);
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Bound one call into author logic.
|
|
1250
|
+
*
|
|
1251
|
+
* §11.10 bounds the tick. Nothing bounded a validator, a hook or an
|
|
1252
|
+
* endpoint, and each sits on a path something is waiting on: a validator
|
|
1253
|
+
* holds a participant's write, an endpoint holds a UI's promise, and a
|
|
1254
|
+
* hook chain — serialised per team (§14.4) — holds every later signal for
|
|
1255
|
+
* that team.
|
|
1256
|
+
*
|
|
1257
|
+
* **This bounds the wait, not the execution.** A promise race cannot
|
|
1258
|
+
* interrupt a bare loop inside the logic realm; terminating that needs
|
|
1259
|
+
* isolation the runtime may not have (§3.2). Failing the waiting path is
|
|
1260
|
+
* the half that is always achievable, and it is the half that keeps the
|
|
1261
|
+
* session moving.
|
|
1262
|
+
*/
|
|
1263
|
+
async bound(what, run, boundMs = this.options.deps.logicExecutionBoundMs ?? DEFAULT_LOGIC_EXECUTION_BOUND_MS, origin) {
|
|
1264
|
+
if (!Number.isFinite(boundMs) || boundMs <= 0) return this.call(run, origin);
|
|
1265
|
+
let timer;
|
|
1266
|
+
try {
|
|
1267
|
+
return await Promise.race([
|
|
1268
|
+
this.call(run, origin),
|
|
1269
|
+
new Promise((_, reject) => {
|
|
1270
|
+
timer = setTimeout(
|
|
1271
|
+
() => reject(
|
|
1272
|
+
new Error(
|
|
1273
|
+
`${what} exceeded the ${boundMs}ms execution bound and was abandoned.`
|
|
1274
|
+
)
|
|
1275
|
+
),
|
|
1276
|
+
boundMs
|
|
1277
|
+
);
|
|
1278
|
+
})
|
|
1279
|
+
]);
|
|
1280
|
+
} finally {
|
|
1281
|
+
if (timer) clearTimeout(timer);
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Run a call into author logic, marking anything it throws with where it
|
|
1286
|
+
* came from (#639): the resource, the tick and team when there are ones,
|
|
1287
|
+
* and the source line the bundle's map reads the stack back to.
|
|
1288
|
+
*/
|
|
1289
|
+
call(run, origin) {
|
|
1290
|
+
const running = (async () => run())();
|
|
1291
|
+
if (!origin) return running;
|
|
1292
|
+
return running.catch((error) => {
|
|
1293
|
+
if (logicFailureOf(error)) throw error;
|
|
1294
|
+
throw markLogicFailure(
|
|
1295
|
+
error,
|
|
1296
|
+
describeLogicFailure(
|
|
1297
|
+
error,
|
|
1298
|
+
origin,
|
|
1299
|
+
this.options.sourceMaps,
|
|
1300
|
+
this.options.callbacks.packagePath
|
|
1301
|
+
)
|
|
1302
|
+
);
|
|
1303
|
+
});
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
|
|
1307
|
+
// cli/runtime/capability-scope.ts
|
|
1308
|
+
function resolveCapabilityScope(definition) {
|
|
1309
|
+
return definition.scope ?? "team";
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
export {
|
|
1313
|
+
deepMergeContext,
|
|
1314
|
+
applyContextUpdate,
|
|
1315
|
+
ConfigResolver,
|
|
1316
|
+
resolveSettingsLayers,
|
|
1317
|
+
applySchemaDefaults,
|
|
1318
|
+
TtsClient,
|
|
1319
|
+
DocumentParserClient,
|
|
1320
|
+
LLM_NOT_CONFIGURED_HINT,
|
|
1321
|
+
LLMClient,
|
|
1322
|
+
markLogicFailure,
|
|
1323
|
+
logicFailureOf,
|
|
1324
|
+
carryLogicFailure,
|
|
1325
|
+
logicErrorOf,
|
|
1326
|
+
DEFAULT_LOGIC_EXECUTION_BOUND_MS,
|
|
1327
|
+
DEFAULT_TICK_EXECUTION_BOUND_MS,
|
|
1328
|
+
LogicCalls,
|
|
1329
|
+
LogicLoader,
|
|
1330
|
+
resolveCapabilityScope
|
|
1331
|
+
};
|