paracosm 0.9.1127 → 0.9.1130

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.
@@ -47,14 +47,7 @@ export declare function readVisitorScenarioId(req: IncomingMessage): string | nu
47
47
  */
48
48
  export declare function pickCookie(id: string, secure?: boolean): string | null;
49
49
  /**
50
- * Whether a local server answers this request.
51
- *
52
- * The name the request was sent to (its `Host`) must be one the server is
53
- * served under: a loopback name, an address literal, or the name `HOST`
54
- * gives. A site that points a name of its own at this machine (DNS
55
- * rebinding) sends that name in `Host`, and in `Origin` when it sends one,
56
- * so a name is never taken because the two agree. An address literal names
57
- * this machine itself, and no other site's page can be served from it.
50
+ * Whether a local server answers this request: first its Host is known.
58
51
  *
59
52
  * Then the request carries no Origin (a same-origin GET, curl, a script),
60
53
  * or its Origin is a loopback address on any port (the dashboard itself,
@@ -62,7 +55,7 @@ export declare function pickCookie(id: string, secure?: boolean): string | null;
62
55
  * (the dashboard served under its address or its `HOST` name).
63
56
  * `Origin: null` and any other site are refused.
64
57
  */
65
- export declare function localOriginAllowed(req: IncomingMessage, servedHost?: string): boolean;
58
+ export declare function localOriginAllowed(req: IncomingMessage, servedHost?: string, allowedHosts?: ReadonlySet<string>): boolean;
66
59
  export interface CreateMarsServerOptions {
67
60
  env?: NodeJS.ProcessEnv;
68
61
  runPairSimulations?: (config: NormalizedSimulationConfig, broadcast: BroadcastFn, signal?: AbortSignal, scenario?: ScenarioPackage, onArtifact?: (artifact: import('../engine/schema/index.js').RunArtifact, leader: import('../runtime/orchestrator/index.js').ActorConfig) => void | Promise<void>,
@@ -1 +1 @@
1
- {"version":3,"file":"server-app.d.ts","sourceRoot":"","sources":["../../src/server/server-app.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,eAAe,EAAE,KAAK,MAAM,EAAuB,MAAM,WAAW,CAAC;AAOjG,OAAO,EAA4D,KAAK,0BAA0B,EAA+B,MAAM,sBAAsB,CAAC;AAC9J,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AC,UAAU,CAAC,EAAE,MAAM,CAAC;YAAC,OAAO,CAAC,EAAE,MAAM,CAAC;YAAC,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC;YAAC,kBAAkB,CAAC,EAAE,OAAO,EAAE,CAAC;YAAC,SAAS,CAAC,EAAE,MAAM,CAAC;YAAC,SAAS,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;wBAC3L,KAAK,CAAC;YAAE,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAC;YAAC,SAAS,CAAC,EAAE,OAAO,EAAE,CAAC;YAAC,cAAc,CAAC,EAAE,MAAM,CAAA;SAAE,CAAC;oBAC3F,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;0BACxB,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;;;EAoEnD;AAED,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CA87HlF"}
@@ -7,7 +7,7 @@ import { fileURLToPath } from 'node:url';
7
7
  import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
8
8
  import { normalizeSimulationConfig, applyDemoCaps, DEMO_EXECUTION } from '../cli/sim-config.js';
9
9
  import { runPairSimulations, runForkSimulation, runBatchSimulations } from '../cli/pair-runner.js';
10
- import { handleFetchSeed, handleCompileFromSeed, handleCompileFromSeedStatus, handleGenerateActors, handleGroundScenario, handleSimulateIntervention, QUICKSTART_SCENARIO_ID_MAX, } from './routes/quickstart.js';
10
+ import { handleFetchSeed, handleCompileFromSeed, handleCompileFromSeedStatus, handleGenerateActors, handleGroundScenario, handleSimulateIntervention, QUICKSTART_SCENARIO_ID_MAX, endFinishedJobsOf, } from './routes/quickstart.js';
11
11
  import { WorldModel } from '../runtime/world-model/index.js';
12
12
  import { handleSimulate } from './routes/simulate.js';
13
13
  import { compileScenario as compileScenarioReal } from '../engine/compiler/index.js';
@@ -15,7 +15,7 @@ import { marsScenario } from '../engine/scenarios/index.js';
15
15
  import { lunarScenario } from '../engine/scenarios/index.js';
16
16
  import { hasProviderCredentials, normalizeCredential, resolveProviderFromCredentials, } from '../engine/provider/credentials.js';
17
17
  import { describeCustomScenarioSource, isRunnableScenarioPackage, loadDiskCustomScenarios, } from '../cli/custom-scenarios.js';
18
- import { deletePersistedCompiledScenario, loadPersistedCompiledDrafts, persistCompiledScenario, scenarioJsonPath, SCENARIO_ID_RULE, } from '../cli/persisted-compiled-scenarios.js';
18
+ import { COMPILED_SCENARIOS_CAP, deletePersistedCompiledScenario, loadPersistedCompiledDrafts, persistCompiledScenario, scenarioJsonPath, SCENARIO_ID_RULE, } from '../cli/persisted-compiled-scenarios.js';
19
19
  import { IpRateLimiter, readLimitFromEnv, readClientIpHeader } from './rate-limiter.js';
20
20
  import { aggregateSchemaRetries, aggregateForgeStats, aggregateCacheStats, aggregateProviderErrors, } from './retry-stats.js';
21
21
  import { createCompilerTelemetry } from '../engine/compiler/telemetry.js';
@@ -77,6 +77,9 @@ function projectScenarioForClient(sc) {
77
77
  export const SCENARIO_PICK_COOKIE = 'paracosm_scenario';
78
78
  /** Thirty days, in seconds: a returning visitor finds the scenario they picked. */
79
79
  const SCENARIO_PICK_MAX_AGE_SECONDS = 2_592_000;
80
+ // A pick cookie lives 30 days. The extra day covers a cookie set by a
81
+ // request that resolved the scenario before it left the catalog.
82
+ const RETIRED_SCENARIO_ID_MS = (SCENARIO_PICK_MAX_AGE_SECONDS + 86_400) * 1000;
80
83
  /**
81
84
  * The longest cookie value held as a pick. RFC 6265 section 6.1 asks a
82
85
  * browser for at least 4096 bytes per cookie, name and attributes
@@ -178,15 +181,104 @@ function hostHeaderName(value) {
178
181
  return '';
179
182
  }
180
183
  }
184
+ /** The additional origins whose pages the hosted demo answers on its own keys. */
185
+ function readAllowedOrigins(env) {
186
+ const origins = new Set();
187
+ let dropped = 0;
188
+ for (const entry of (env.PARACOSM_ALLOWED_ORIGINS ?? '').split(',')) {
189
+ const piece = entry.trim();
190
+ if (!piece)
191
+ continue;
192
+ try {
193
+ const parsed = new URL(piece);
194
+ if ((parsed.protocol === 'http:' || parsed.protocol === 'https:') && parsed.origin === piece.toLowerCase()) {
195
+ origins.add(piece.toLowerCase());
196
+ continue;
197
+ }
198
+ }
199
+ catch {
200
+ // Count an entry that does not parse with the other invalid entries.
201
+ }
202
+ dropped++;
203
+ }
204
+ if (dropped > 0)
205
+ console.warn(`[origin] PARACOSM_ALLOWED_ORIGINS: dropped ${dropped} entries that are not origins (https://host or https://host:port)`);
206
+ return origins;
207
+ }
208
+ /** The additional host names a local server answers, on any port. */
209
+ function readAllowedHosts(env) {
210
+ const hosts = new Set();
211
+ let dropped = 0;
212
+ for (const entry of (env.PARACOSM_ALLOWED_HOSTS ?? '').split(',')) {
213
+ const piece = entry.trim();
214
+ if (!piece)
215
+ continue;
216
+ if (hostHeaderName(piece) === piece.toLowerCase())
217
+ hosts.add(piece.toLowerCase());
218
+ else
219
+ dropped++;
220
+ }
221
+ if (dropped > 0)
222
+ console.warn(`[host] PARACOSM_ALLOWED_HOSTS: dropped ${dropped} entries that are not host names (a name with no port)`);
223
+ return hosts;
224
+ }
181
225
  /**
182
- * Whether a local server answers this request.
226
+ * Listed origins take precedence over fetch metadata, with Origin as the fallback.
227
+ * With origins listed, a request whose Origin is any other origin (not `null`)
228
+ * is another site's, whatever Sec-Fetch-Site says.
229
+ */
230
+ function fromAnotherSite(req, allowedOrigins) {
231
+ const origin = req.headers.origin;
232
+ if (origin !== undefined && allowedOrigins.has(origin.toLowerCase()))
233
+ return false;
234
+ if (origin !== undefined && allowedOrigins.size > 0 && origin.trim().toLowerCase() !== 'null')
235
+ return true;
236
+ const site = req.headers['sec-fetch-site'];
237
+ switch (typeof site === 'string' ? site.trim().toLowerCase() : '') {
238
+ case 'cross-site':
239
+ case 'same-site':
240
+ return true;
241
+ case 'same-origin':
242
+ case 'none':
243
+ return false;
244
+ }
245
+ if (origin === undefined)
246
+ return false;
247
+ try {
248
+ const parsed = new URL(origin);
249
+ return (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') ||
250
+ parsed.host !== (req.headers.host ?? '').toLowerCase();
251
+ }
252
+ catch {
253
+ return true;
254
+ }
255
+ }
256
+ /** Uses the compiler's seed test, including truthy values that are not strings. */
257
+ function compileUsesHostSearch(body, env) {
258
+ const seeded = Boolean(body.seedText || body.seedUrl);
259
+ const scrapes = Boolean(body.seedUrl) && normalizeCredential(env.FIRECRAWL_API_KEY) !== undefined;
260
+ return seeded && ((body.webSearch ?? true) !== false || scrapes);
261
+ }
262
+ /**
263
+ * Whether a local server answers the name this request was sent to.
183
264
  *
184
265
  * The name the request was sent to (its `Host`) must be one the server is
185
- * served under: a loopback name, an address literal, or the name `HOST`
266
+ * served under: a loopback name, an address literal, a listed name, or the name `HOST`
186
267
  * gives. A site that points a name of its own at this machine (DNS
187
268
  * rebinding) sends that name in `Host`, and in `Origin` when it sends one,
188
269
  * so a name is never taken because the two agree. An address literal names
189
270
  * this machine itself, and no other site's page can be served from it.
271
+ */
272
+ function localHostKnown(hostHeader, servedHost, allowedHosts) {
273
+ const name = hostHeaderName(hostHeader);
274
+ if (!name)
275
+ return false;
276
+ const served = hostHeaderName(servedHost.trim());
277
+ return LOOPBACK_HOSTNAMES.has(name) || isIP(name.replace(/^\[|\]$/g, '')) !== 0 ||
278
+ (served.length > 0 && name === served) || allowedHosts.has(name);
279
+ }
280
+ /**
281
+ * Whether a local server answers this request: first its Host is known.
190
282
  *
191
283
  * Then the request carries no Origin (a same-origin GET, curl, a script),
192
284
  * or its Origin is a loopback address on any port (the dashboard itself,
@@ -194,11 +286,8 @@ function hostHeaderName(value) {
194
286
  * (the dashboard served under its address or its `HOST` name).
195
287
  * `Origin: null` and any other site are refused.
196
288
  */
197
- export function localOriginAllowed(req, servedHost = '') {
198
- const name = hostHeaderName(req.headers.host);
199
- const served = hostHeaderName(servedHost.trim());
200
- const knownName = LOOPBACK_HOSTNAMES.has(name) || isIP(name.replace(/^\[|\]$/g, '')) !== 0 || (served.length > 0 && name === served);
201
- if (!knownName)
289
+ export function localOriginAllowed(req, servedHost = '', allowedHosts = new Set()) {
290
+ if (!localHostKnown(req.headers.host, servedHost, allowedHosts))
202
291
  return false;
203
292
  const origin = req.headers.origin;
204
293
  if (origin === undefined)
@@ -493,6 +582,8 @@ export function buildResultsPayloadFromEventBuffer(eventBuffer) {
493
582
  export function createMarsServer(options = {}) {
494
583
  const env = options.env ?? process.env;
495
584
  const serverMode = resolveServerMode(env);
585
+ const allowedOrigins = serverMode === 'hosted_demo' ? readAllowedOrigins(env) : new Set();
586
+ const allowedHosts = serverMode === 'local_demo' ? readAllowedHosts(env) : new Set();
496
587
  // The one directory run output, imported artifacts, run reads, the
497
588
  // retention sweep and the output wipe all use.
498
589
  const runsDir = resolveRunsDir(env);
@@ -990,6 +1081,17 @@ export function createMarsServer(options = {}) {
990
1081
  // than a CustomScenarioEntry extension so the existing entry shape
991
1082
  // and every consumer of `customScenarioCatalog` stays unchanged.
992
1083
  const compiledScenarioMeta = new Map();
1084
+ const compiledEntryInfo = new Map();
1085
+ // Digests keep each retired id the same size, regardless of its length.
1086
+ const retiredScenarioIds = new Map();
1087
+ const pruneRetiredScenarioIds = () => {
1088
+ const now = Date.now();
1089
+ for (const [digest, retiredAt] of retiredScenarioIds) {
1090
+ if (now - retiredAt < RETIRED_SCENARIO_ID_MS)
1091
+ break;
1092
+ retiredScenarioIds.delete(digest);
1093
+ }
1094
+ };
993
1095
  // Ids of the persisted compiled drafts boot is still re-compiling. Filled
994
1096
  // before the first compile starts and emptied one id at a time as each
995
1097
  // lands in the catalog or fails. A visitor whose pick is one of them is
@@ -1007,17 +1109,78 @@ export function createMarsServer(options = {}) {
1007
1109
  customScenarioCatalog.set(id, entry);
1008
1110
  dropFromEveryMemoryStore(id);
1009
1111
  };
1112
+ /** The saved drafts that folder clean-up must keep. */
1113
+ const keep = (id) => customScenarioCatalog.get(id)?.source === 'compiled' || hydratingScenarioIds.has(id);
1114
+ /** Removes one compiled entry or waiting draft and retires its id. */
1115
+ const evictCompiled = (id) => {
1116
+ const entry = customScenarioCatalog.get(id);
1117
+ if (entry?.source === 'compiled')
1118
+ customScenarioCatalog.delete(id);
1119
+ hydratingScenarioIds.delete(id);
1120
+ compiledScenarioMeta.delete(id);
1121
+ compiledBriefOwners.delete(id);
1122
+ groundingCitationsByScenarioId.delete(id);
1123
+ compiledEntryInfo.delete(id);
1124
+ deletePersistedCompiledScenario(scenarioDir, id);
1125
+ pruneRetiredScenarioIds();
1126
+ const digest = createHash('sha256').update(id).digest('hex');
1127
+ retiredScenarioIds.delete(digest);
1128
+ retiredScenarioIds.set(digest, Date.now());
1129
+ if (entry?.source === 'compiled')
1130
+ endFinishedJobsOf(entry.scenario);
1131
+ console.log(`[scenarios] ${JSON.stringify(id)} left the catalog to keep it at ${COMPILED_SCENARIOS_CAP} compiled scenarios`);
1132
+ };
1133
+ /** Makes room after a compile, preserving the new entry and every run's scenario. */
1134
+ const makeRoomAfter = (enteredId) => {
1135
+ const compiledIds = new Set([
1136
+ ...[...customScenarioCatalog].filter(([, entry]) => entry.source === 'compiled').map(([id]) => id),
1137
+ ...[...hydratingScenarioIds].filter(id => !customScenarioCatalog.has(id)),
1138
+ ]);
1139
+ const protectedIds = liveRuns.scenarioIdsInRuns();
1140
+ while (compiledIds.size > COMPILED_SCENARIOS_CAP) {
1141
+ const addressCounts = new Map();
1142
+ if (serverMode === 'hosted_demo') {
1143
+ for (const id of compiledIds) {
1144
+ const address = compiledEntryInfo.get(id)?.address;
1145
+ if (address != null)
1146
+ addressCounts.set(address, (addressCounts.get(address) ?? 0) + 1);
1147
+ }
1148
+ }
1149
+ // Map order breaks equal timestamps. Null addresses each hold one.
1150
+ let oldest;
1151
+ for (const [id, info] of compiledEntryInfo) {
1152
+ if (!compiledIds.has(id) || id === enteredId || protectedIds.has(id))
1153
+ continue;
1154
+ const count = serverMode === 'hosted_demo' && info.address !== null
1155
+ ? addressCounts.get(info.address) ?? 1 : 1;
1156
+ if (!oldest || count > oldest.count || (count === oldest.count && info.enteredAt < oldest.enteredAt)) {
1157
+ oldest = { id, enteredAt: info.enteredAt, count };
1158
+ }
1159
+ }
1160
+ if (!oldest) {
1161
+ console.log(`[scenarios] kept ${compiledIds.size} compiled scenarios, over the cap of ${COMPILED_SCENARIOS_CAP}: every other one is in a run the server holds`);
1162
+ break;
1163
+ }
1164
+ evictCompiled(oldest.id);
1165
+ compiledIds.delete(oldest.id);
1166
+ }
1167
+ };
1010
1168
  /**
1011
1169
  * Whether `id` already names a scenario for someone other than
1012
1170
  * `visitorId` alone: the catalog holds it (a built-in, a curated or a
1013
1171
  * compiled scenario, which any visitor may have picked), boot is still
1014
- * re-compiling it, or another visitor holds it in memory. A compile never
1172
+ * re-compiling it, its retired digest is held for a recent eviction, or
1173
+ * another visitor holds it in memory. A compile never
1015
1174
  * lands under such an id, so it never changes what an id already names
1016
1175
  * for another visitor.
1017
1176
  */
1018
1177
  const scenarioIdTaken = (visitorId, id) => {
1019
1178
  if (customScenarioCatalog.has(id) || hydratingScenarioIds.has(id))
1020
1179
  return true;
1180
+ pruneRetiredScenarioIds();
1181
+ const retiredAt = retiredScenarioIds.get(createHash('sha256').update(id).digest('hex'));
1182
+ if (retiredAt !== undefined && Date.now() - retiredAt < RETIRED_SCENARIO_ID_MS)
1183
+ return true;
1021
1184
  dropIdleMemoryScenarios();
1022
1185
  for (const [holder, own] of memoryScenarios) {
1023
1186
  if (holder !== visitorId && own.has(id))
@@ -1052,8 +1215,10 @@ export function createMarsServer(options = {}) {
1052
1215
  });
1053
1216
  if (drafts.length === 0)
1054
1217
  return;
1055
- for (const { id } of drafts)
1218
+ for (const { id, meta } of drafts) {
1056
1219
  hydratingScenarioIds.add(id);
1220
+ compiledEntryInfo.set(id, { enteredAt: Date.parse(meta.compiledAt) || 0, address: null });
1221
+ }
1057
1222
  console.log(`[scenarios] re-compiling ${drafts.length} persisted compiled draft(s) from disk…`);
1058
1223
  // Wrap the dynamic import + per-draft loop in its own try-catch
1059
1224
  // so a module-resolution failure (deploy with broken compiler
@@ -1071,10 +1236,18 @@ export function createMarsServer(options = {}) {
1071
1236
  ?? (await import('../engine/compiler/index.js')).compileScenario;
1072
1237
  for (const { id, draft, meta } of drafts) {
1073
1238
  try {
1239
+ if (!hydratingScenarioIds.has(id)) {
1240
+ console.log(`[scenarios] left out the persisted compiled draft ${id}: it left the catalog while boot re-compiled it`);
1241
+ continue;
1242
+ }
1074
1243
  // Cache: true means we hit the local hook-source cache. With
1075
1244
  // a warm cache this is ~10ms per draft; with a cold cache the
1076
1245
  // hooks regenerate via LLM at the going rate.
1077
1246
  const compiled = await compileScenario(draft, { cache: true });
1247
+ if (!hydratingScenarioIds.has(id)) {
1248
+ console.log(`[scenarios] left out the persisted compiled draft ${id}: it left the catalog while boot re-compiled it`);
1249
+ continue;
1250
+ }
1078
1251
  // Checked again under the compiled id: an earlier draft of this
1079
1252
  // loop, or a scenario saved while this one compiled, may hold it.
1080
1253
  if (customScenarioCatalog.has(compiled.id)) {
@@ -1082,7 +1255,12 @@ export function createMarsServer(options = {}) {
1082
1255
  continue;
1083
1256
  }
1084
1257
  enterCatalog(compiled.id, { scenario: compiled, source: 'compiled' });
1258
+ if (compiled.id !== id) {
1259
+ compiledEntryInfo.set(compiled.id, compiledEntryInfo.get(id));
1260
+ hydratingScenarioIds.delete(id);
1261
+ }
1085
1262
  compiledScenarioMeta.set(compiled.id, meta);
1263
+ makeRoomAfter(compiled.id);
1086
1264
  console.log(`[scenarios] hydrated ${compiled.id} (${meta.compiledAt})`);
1087
1265
  }
1088
1266
  catch (err) {
@@ -1090,6 +1268,8 @@ export function createMarsServer(options = {}) {
1090
1268
  }
1091
1269
  finally {
1092
1270
  hydratingScenarioIds.delete(id);
1271
+ if (customScenarioCatalog.get(id)?.source !== 'compiled')
1272
+ compiledEntryInfo.delete(id);
1093
1273
  }
1094
1274
  }
1095
1275
  }
@@ -1099,6 +1279,10 @@ export function createMarsServer(options = {}) {
1099
1279
  finally {
1100
1280
  // Nothing is loading any more: a pick that never landed reads as
1101
1281
  // unknown, so its visitor gets the default.
1282
+ for (const id of hydratingScenarioIds) {
1283
+ if (customScenarioCatalog.get(id)?.source !== 'compiled')
1284
+ compiledEntryInfo.delete(id);
1285
+ }
1102
1286
  hydratingScenarioIds.clear();
1103
1287
  }
1104
1288
  })();
@@ -1588,6 +1772,22 @@ export function createMarsServer(options = {}) {
1588
1772
  const corsHeaders = {
1589
1773
  'Access-Control-Allow-Origin': '*',
1590
1774
  };
1775
+ const writeCrossSiteRefusal = (res) => {
1776
+ console.warn("[origin] refused a request from another site on the host's keys");
1777
+ res.writeHead(403, { 'Content-Type': 'application/json', ...corsHeaders });
1778
+ res.end(JSON.stringify({
1779
+ error: 'cross_site_refused',
1780
+ message: "This request came from a page on another site. The hosted demo takes it from its own pages, or on /setup, /compile and /chat with the caller's own provider key (on /compile, and no seed the host's search or scraping keys would read).",
1781
+ }));
1782
+ };
1783
+ const writeLocalRefusal = (res, logLine) => {
1784
+ console.warn(logLine);
1785
+ res.writeHead(403, { 'Content-Type': 'application/json' });
1786
+ res.end(JSON.stringify({
1787
+ error: 'cross_site_refused',
1788
+ message: 'This local server answers requests from its own pages and from localhost only, sent to a loopback name, its address, the name HOST gives or a name PARACOSM_ALLOWED_HOSTS lists.',
1789
+ }));
1790
+ };
1591
1791
  /** Answers a run the server has no room for: 503 with the run cap. Nothing has been charged to the caller. */
1592
1792
  const writeRunCapacityRefusal = (res, err) => {
1593
1793
  res.writeHead(503, {
@@ -1626,6 +1826,10 @@ export function createMarsServer(options = {}) {
1626
1826
  res.end(JSON.stringify({ error: `Unknown run: ${key}` }));
1627
1827
  };
1628
1828
  const handleRequest = async (req, res) => {
1829
+ if (serverMode === 'local_demo' && !localHostKnown(req.headers.host, env.HOST ?? '', allowedHosts)) {
1830
+ writeLocalRefusal(res, '[host] refused a request sent to a name this local server does not answer');
1831
+ return;
1832
+ }
1629
1833
  // CORS preflight for browser-based requests across the public API.
1630
1834
  // DELETE is in the allow-list because /admin/scenarios/:id is a
1631
1835
  // cross-origin candidate for the embedded landing-page demos;
@@ -1645,10 +1849,14 @@ export function createMarsServer(options = {}) {
1645
1849
  // A local server answers its own pages and other local ports alone: a
1646
1850
  // request a browser sends from a page on another site carries that
1647
1851
  // site's Origin, and is refused before any route reads or spends.
1648
- if (serverMode === 'local_demo' && !localOriginAllowed(req, env.HOST ?? '')) {
1649
- console.warn('[origin] refused a request from another site on a local server');
1650
- res.writeHead(403, { 'Content-Type': 'application/json' });
1651
- res.end(JSON.stringify({ error: 'cross_site_refused', message: 'This local server answers requests from its own pages and from localhost only, sent to a loopback name, its address or the name HOST gives.' }));
1852
+ if (serverMode === 'local_demo' && !localOriginAllowed(req, env.HOST ?? '', allowedHosts)) {
1853
+ writeLocalRefusal(res, '[origin] refused a request from another site on a local server');
1854
+ return;
1855
+ }
1856
+ if (serverMode === 'hosted_demo' && req.method === 'POST' &&
1857
+ (req.url?.startsWith('/api/quickstart/') || req.url === '/scenario/switch') &&
1858
+ fromAnotherSite(req, allowedOrigins)) {
1859
+ writeCrossSiteRefusal(res);
1652
1860
  return;
1653
1861
  }
1654
1862
  // A path whose percent escapes do not decode names no route.
@@ -1895,9 +2103,10 @@ export function createMarsServer(options = {}) {
1895
2103
  const active = 'scenario' in pick ? pick.scenario.id : 'loading' in pick ? pick.loading : marsScenario.id;
1896
2104
  // Best-effort run-count enrichment. Aggregate one query per
1897
2105
  // scenario id rather than one bulk because aggregateStats
1898
- // already accepts a scenarioId filter; the cost is bounded by
1899
- // catalog size (≤50 + a couple builtins) so the fan-out stays
1900
- // reasonable.
2106
+ // already accepts a scenarioId filter. The catalog holds at most 50
2107
+ // compiled entries, or one more than the compiled scenarios the
2108
+ // server's runs have held, beside the built-ins, the scenarios folder
2109
+ // and this visitor's own memory scenarios.
1901
2110
  if (runHistoryStore?.aggregateStats) {
1902
2111
  await Promise.all(entries.map(async (entry) => {
1903
2112
  try {
@@ -1959,6 +2168,11 @@ export function createMarsServer(options = {}) {
1959
2168
  res.end(JSON.stringify({ error: 'invalid_json_body' }));
1960
2169
  return;
1961
2170
  }
2171
+ if (customScenarioCatalog.get(id) !== entry) {
2172
+ res.writeHead(404, { 'Content-Type': 'application/json', ...corsHeaders });
2173
+ res.end(JSON.stringify({ error: 'scenario_not_found', id }));
2174
+ return;
2175
+ }
1962
2176
  const rawName = typeof body.name === 'string' ? body.name : '';
1963
2177
  // Sanitize: strip control chars (0x00-0x1F + DEL) + HTML
1964
2178
  // angle-brackets so a crafted name never sneaks markup into
@@ -1988,7 +2202,7 @@ export function createMarsServer(options = {}) {
1988
2202
  // we re-read the meta map so the on-disk file never loses the
1989
2203
  // original seed prompt the user submitted.
1990
2204
  const existingMeta = compiledScenarioMeta.get(id);
1991
- const persistResult = persistCompiledScenario(scenarioDir, sc, existingMeta?.seedText ?? null);
2205
+ const persistResult = persistCompiledScenario(scenarioDir, sc, existingMeta?.seedText ?? null, keep);
1992
2206
  if (persistResult) {
1993
2207
  compiledScenarioMeta.set(id, persistResult.meta);
1994
2208
  }
@@ -2155,6 +2369,24 @@ export function createMarsServer(options = {}) {
2155
2369
  mkdirSync(scenarioDir, { recursive: true });
2156
2370
  writeFileSync(diskPath, JSON.stringify(scenarioJson, null, 2));
2157
2371
  savedToDisk = true;
2372
+ // The saved file takes the id from a compiled scenario or a draft
2373
+ // boot is re-compiling, runnable or not: its saved draft goes, so
2374
+ // a restart never brings the compiled scenario back. A save that
2375
+ // is not runnable also takes the compiled scenario out of the
2376
+ // catalog and ends boot's re-compile of it; the file loads at the
2377
+ // next restart when the boot loader can read it.
2378
+ if (customScenarioCatalog.get(scenarioJson.id)?.source === 'compiled' || hydratingScenarioIds.has(scenarioJson.id)) {
2379
+ deletePersistedCompiledScenario(scenarioDir, scenarioJson.id);
2380
+ compiledScenarioMeta.delete(scenarioJson.id);
2381
+ compiledBriefOwners.delete(scenarioJson.id);
2382
+ compiledEntryInfo.delete(scenarioJson.id);
2383
+ if (!switchable) {
2384
+ if (customScenarioCatalog.get(scenarioJson.id)?.source === 'compiled')
2385
+ customScenarioCatalog.delete(scenarioJson.id);
2386
+ groundingCitationsByScenarioId.delete(scenarioJson.id);
2387
+ hydratingScenarioIds.delete(scenarioJson.id);
2388
+ }
2389
+ }
2158
2390
  if (switchable) {
2159
2391
  enterCatalog(scenarioJson.id, {
2160
2392
  scenario: scenarioJson,
@@ -2279,7 +2511,9 @@ export function createMarsServer(options = {}) {
2279
2511
  // scenario (a second request for a compile that already landed)
2280
2512
  // keeps its id.
2281
2513
  let sc = compiledFromSeed;
2282
- if (customScenarioCatalog.get(sc.id)?.scenario !== sc && scenarioIdTaken(quickstartVisitor, sc.id)) {
2514
+ if (customScenarioCatalog.get(sc.id)?.scenario === sc)
2515
+ return sc;
2516
+ if (scenarioIdTaken(quickstartVisitor, sc.id)) {
2283
2517
  const takenId = sc.id;
2284
2518
  const withSuffix = (n) => {
2285
2519
  const tail = `-${n}`;
@@ -2296,6 +2530,11 @@ export function createMarsServer(options = {}) {
2296
2530
  // compiled it gets it as their pick through pickHeaders on the
2297
2531
  // answers they receive.
2298
2532
  enterCatalog(sc.id, { scenario: sc, source: 'compiled' });
2533
+ compiledEntryInfo.set(sc.id, {
2534
+ enteredAt: Date.now(),
2535
+ address: serverMode === 'hosted_demo' ? IpRateLimiter.getIp(req, clientIpHeader) : null,
2536
+ });
2537
+ makeRoomAfter(sc.id);
2299
2538
  // Auto-persist to disk so the catalog survives server
2300
2539
  // restarts. The hooks themselves are excluded (functions
2301
2540
  // don't serialize) but compileScenario regenerates them
@@ -2311,7 +2550,7 @@ export function createMarsServer(options = {}) {
2311
2550
  // timestamp here would drift by however long writeFileSync
2312
2551
  // took to flush. A failed write still records the meta in
2313
2552
  // memory, so /setup carries the brief into the run either way.
2314
- const persistResult = persistCompiledScenario(scenarioDir, sc, seed);
2553
+ const persistResult = persistCompiledScenario(scenarioDir, sc, seed, keep);
2315
2554
  compiledScenarioMeta.set(sc.id, persistResult?.meta ?? { compiledAt: new Date().toISOString(), seedText: seed });
2316
2555
  return sc;
2317
2556
  },
@@ -2434,6 +2673,10 @@ export function createMarsServer(options = {}) {
2434
2673
  anthropicKey: normalizeCredential(userAnthropicKey),
2435
2674
  };
2436
2675
  const hasUserKeys = hasProviderCredentials(simulateCredentials);
2676
+ if (serverMode === 'hosted_demo' && !hasUserKeys && fromAnotherSite(req, allowedOrigins)) {
2677
+ writeCrossSiteRefusal(res);
2678
+ return;
2679
+ }
2437
2680
  // Rate limit with BYO-key bypass, matching the /setup pattern.
2438
2681
  // `.check()` alone is advisory; `.record()` consumes the slot.
2439
2682
  if (rateLimiter && !hasUserKeys) {
@@ -2489,10 +2732,22 @@ export function createMarsServer(options = {}) {
2489
2732
  res.end(JSON.stringify({ error: 'scenario JSON object required' }));
2490
2733
  return;
2491
2734
  }
2735
+ if (Buffer.byteLength(JSON.stringify(scenarioJson)) > MEMORY_SCENARIO_MAX_BYTES) {
2736
+ console.warn('[scenarios] compile refused: over the size a compile takes');
2737
+ res.writeHead(413, { 'Content-Type': 'application/json' });
2738
+ res.end(JSON.stringify({ error: `A scenario sent to /compile is at most ${MEMORY_SCENARIO_MAX_BYTES / 1024} KiB of JSON.` }));
2739
+ return;
2740
+ }
2492
2741
  const compileCredentials = {
2493
2742
  apiKey: normalizeCredential(apiKey),
2494
2743
  anthropicKey: normalizeCredential(anthropicKey),
2495
2744
  };
2745
+ if (serverMode === 'hosted_demo' &&
2746
+ (!hasProviderCredentials(compileCredentials) || compileUsesHostSearch(body, env)) &&
2747
+ fromAnotherSite(req, allowedOrigins)) {
2748
+ writeCrossSiteRefusal(res);
2749
+ return;
2750
+ }
2496
2751
  // A compile lands in the catalog every visitor reads, under the id
2497
2752
  // its JSON carries, so it takes only an id that names nothing yet
2498
2753
  // for anyone else (scenarioIdTaken). Refused here, before the stream
@@ -2637,6 +2892,11 @@ export function createMarsServer(options = {}) {
2637
2892
  // that compiled it posts /scenario/switch with the id from
2638
2893
  // `complete`, which makes it that visitor's pick.
2639
2894
  enterCatalog(compiled.id, { scenario: compiled, source: 'compiled' });
2895
+ compiledEntryInfo.set(compiled.id, {
2896
+ enteredAt: Date.now(),
2897
+ address: serverMode === 'hosted_demo' ? IpRateLimiter.getIp(req, clientIpHeader) : null,
2898
+ });
2899
+ makeRoomAfter(compiled.id);
2640
2900
  // Snapshot compile telemetry into the ring buffer so /retry-stats
2641
2901
  // aggregates compile:* schemas alongside runtime schemas, and emit
2642
2902
  // the rollup as SSE so the dashboard can render per-hook attempts
@@ -2790,6 +3050,10 @@ export function createMarsServer(options = {}) {
2790
3050
  anthropicKey: normalizeCredential(anthropicKey),
2791
3051
  };
2792
3052
  const chatUserKey = hasProviderCredentials(chatCredentials);
3053
+ if (serverMode === 'hosted_demo' && !chatUserKey && fromAnotherSite(req, allowedOrigins)) {
3054
+ writeCrossSiteRefusal(res);
3055
+ return;
3056
+ }
2793
3057
  // Rate-limit chat per IP per hour. Runs against the host's
2794
3058
  // key unless a session key was provided in the request body,
2795
3059
  // in which case the caller is paying and the cap is bypassed
@@ -3143,6 +3407,9 @@ export function createMarsServer(options = {}) {
3143
3407
  const fileDeleted = deletePersistedCompiledScenario(scenarioDir, id);
3144
3408
  const catalogDeleted = customScenarioCatalog.delete(id);
3145
3409
  const metaDeleted = compiledScenarioMeta.delete(id);
3410
+ compiledEntryInfo.delete(id);
3411
+ compiledBriefOwners.delete(id);
3412
+ groundingCitationsByScenarioId.delete(id);
3146
3413
  const memoryDeleted = dropFromMemory();
3147
3414
  console.log(`[scenarios] admin deleted ${id} (file=${fileDeleted} catalog=${catalogDeleted} meta=${metaDeleted} memory=${memoryDeleted})`);
3148
3415
  res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders });
@@ -3405,6 +3672,10 @@ export function createMarsServer(options = {}) {
3405
3672
  anthropicKey: normalizeCredential(config.anthropicKey),
3406
3673
  };
3407
3674
  const hasUserKeys = hasProviderCredentials(requestCredentials);
3675
+ if (serverMode === 'hosted_demo' && !hasUserKeys && fromAnotherSite(req, allowedOrigins)) {
3676
+ writeCrossSiteRefusal(res);
3677
+ return;
3678
+ }
3408
3679
  const rateIp = rateLimiter && !hasUserKeys ? IpRateLimiter.getIp(req, clientIpHeader) : null;
3409
3680
  /** Answers 429 and returns true when the caller's IP has used its runs of the day. */
3410
3681
  const overTheDay = () => {