paracosm 0.9.1113 → 0.9.1115

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/verdict-scores.d.ts +2 -1
  3. package/dist/cli/verdict-scores.d.ts.map +1 -1
  4. package/dist/cli/verdict-scores.js +2 -1
  5. package/dist/cli/verdict-scores.js.map +1 -1
  6. package/dist/dashboard/dist/assets/{index-G-Q1siQW.js → index-DZKYPCBt.js} +27 -27
  7. package/dist/dashboard/dist/assets/index-DrZBEElm.css +1 -0
  8. package/dist/dashboard/dist/index.html +2 -2
  9. package/dist/engine/compiler/compile-from-seed.d.ts +32 -8
  10. package/dist/engine/compiler/compile-from-seed.d.ts.map +1 -1
  11. package/dist/engine/compiler/compile-from-seed.js +98 -14
  12. package/dist/engine/compiler/compile-from-seed.js.map +1 -1
  13. package/dist/engine/compiler/seed-draft-world.d.ts +127 -0
  14. package/dist/engine/compiler/seed-draft-world.d.ts.map +1 -0
  15. package/dist/engine/compiler/seed-draft-world.js +479 -0
  16. package/dist/engine/compiler/seed-draft-world.js.map +1 -0
  17. package/dist/engine/compiler/state-shape-block.d.ts.map +1 -1
  18. package/dist/engine/compiler/state-shape-block.js +25 -1
  19. package/dist/engine/compiler/state-shape-block.js.map +1 -1
  20. package/dist/engine/compiler/validate.d.ts +27 -2
  21. package/dist/engine/compiler/validate.d.ts.map +1 -1
  22. package/dist/engine/compiler/validate.js +121 -2
  23. package/dist/engine/compiler/validate.js.map +1 -1
  24. package/dist/engine/types.d.ts +3 -3
  25. package/dist/server/routes/quickstart.d.ts +14 -2
  26. package/dist/server/routes/quickstart.d.ts.map +1 -1
  27. package/dist/server/routes/quickstart.js +13 -5
  28. package/dist/server/routes/quickstart.js.map +1 -1
  29. package/dist/server/server-app.d.ts +35 -0
  30. package/dist/server/server-app.d.ts.map +1 -1
  31. package/dist/server/server-app.js +295 -54
  32. package/dist/server/server-app.js.map +1 -1
  33. package/package.json +1 -1
  34. package/dist/dashboard/dist/assets/index-DwkQQHCH.css +0 -1
@@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url';
6
6
  import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
7
7
  import { normalizeSimulationConfig, applyDemoCaps } from '../cli/sim-config.js';
8
8
  import { runPairSimulations, runForkSimulation, runBatchSimulations } from '../cli/pair-runner.js';
9
- import { handleFetchSeed, handleCompileFromSeed, handleCompileFromSeedStatus, handleGenerateActors, handleGroundScenario, handleSimulateIntervention, } from './routes/quickstart.js';
9
+ import { handleFetchSeed, handleCompileFromSeed, handleCompileFromSeedStatus, handleGenerateActors, handleGroundScenario, handleSimulateIntervention, QUICKSTART_SCENARIO_ID_MAX, } from './routes/quickstart.js';
10
10
  import { WorldModel } from '../runtime/world-model/index.js';
11
11
  import { handleSimulate } from './routes/simulate.js';
12
12
  import { compileScenario as compileScenarioReal } from '../engine/compiler/index.js';
@@ -82,6 +82,32 @@ const SCENARIO_PICK_MAX_AGE_SECONDS = 2_592_000;
82
82
  * included; 1024 leaves them room.
83
83
  */
84
84
  const SCENARIO_PICK_MAX_BYTES = 1024;
85
+ /**
86
+ * The largest scenario POST /scenario/store holds in memory, as JSON
87
+ * (256 KiB). The largest scenario under scenarios/ is about 33 KB.
88
+ */
89
+ export const MEMORY_SCENARIO_MAX_BYTES = 256 * 1024;
90
+ /** The most scenarios one visitor holds in memory. */
91
+ export const MEMORY_SCENARIOS_PER_VISITOR = 10;
92
+ /** The most scenarios the memory store holds, every visitor's together. */
93
+ export const MEMORY_SCENARIOS_CAP = 100;
94
+ /**
95
+ * The most scenarios the memory store holds for one address, every visitor
96
+ * id that address sends together. The address is the one the rate limiter
97
+ * keys on (IpRateLimiter.getIp), so one client that sends many visitor ids
98
+ * holds a fifth of the store at most.
99
+ */
100
+ export const MEMORY_SCENARIOS_PER_ADDRESS = 20;
101
+ /**
102
+ * How long the memory store holds a scenario after it was last stored, read
103
+ * by its id or run: 24 hours. A scenario idle for longer is dropped, so a
104
+ * full store empties by itself and never stays full until a restart.
105
+ */
106
+ export const MEMORY_SCENARIO_IDLE_MS = 24 * 60 * 60 * 1000;
107
+ /** What POST /compile answers for an id it may not take. */
108
+ function scenarioIdTakenMessage(id) {
109
+ return `"${id}" is taken on this server. Give your scenario an id of its own.`;
110
+ }
85
111
  /**
86
112
  * The scenario id in the request's `paracosm_scenario` cookie: the first
87
113
  * such pair of the Cookie header, percent-decoded. Null when there is
@@ -585,8 +611,42 @@ export function createMarsServer(options = {}) {
585
611
  import('../runtime/agents/chat-agents.js').then(m => m.clearPool(run.key)).catch(() => { });
586
612
  },
587
613
  });
588
- // Raw custom scenario JSON payloads authored during this session.
589
614
  const memoryScenarios = new Map();
615
+ let memoryScenarioCount = 0;
616
+ const memoryScenarioIdleMs = options.memoryScenarioIdleMs ?? MEMORY_SCENARIO_IDLE_MS;
617
+ /** Drops `id` from one visitor's store. */
618
+ const dropMemoryScenario = (visitorId, id) => {
619
+ const own = memoryScenarios.get(visitorId);
620
+ if (!own?.delete(id))
621
+ return false;
622
+ memoryScenarioCount -= 1;
623
+ if (own.size === 0)
624
+ memoryScenarios.delete(visitorId);
625
+ return true;
626
+ };
627
+ /** Drops `id` from every visitor's store and returns how many held it. */
628
+ const dropFromEveryMemoryStore = (id) => {
629
+ let dropped = 0;
630
+ for (const visitorId of [...memoryScenarios.keys()]) {
631
+ if (dropMemoryScenario(visitorId, id))
632
+ dropped += 1;
633
+ }
634
+ return dropped;
635
+ };
636
+ /** Drops every stored scenario past the idle time. The store holds 100 at most, so each read of it runs this. */
637
+ const dropIdleMemoryScenarios = () => {
638
+ const cutoff = Date.now() - memoryScenarioIdleMs;
639
+ for (const [visitorId, own] of [...memoryScenarios]) {
640
+ for (const [id, held] of [...own]) {
641
+ if (held.usedAt < cutoff)
642
+ dropMemoryScenario(visitorId, id);
643
+ }
644
+ }
645
+ };
646
+ const ownMemoryScenarios = (req) => {
647
+ dropIdleMemoryScenarios();
648
+ return memoryScenarios.get(readVisitorId(req));
649
+ };
590
650
  // Runnable scenarios that can appear in the catalog and be switched to.
591
651
  // Disk-loaded + builtins register into the SAME map so the switch /
592
652
  // list / active-derivation code is universal — no hardcoded branches
@@ -624,6 +684,34 @@ export function createMarsServer(options = {}) {
624
684
  // Genesis: the first reload after a deploy would otherwise answer Mars,
625
685
  // and the page would stop retrying and run Mars against a valid pick.
626
686
  const hydratingScenarioIds = new Set();
687
+ /**
688
+ * Puts a scenario in the catalog every visitor reads. Its id leaves every
689
+ * visitor's memory store: from here on the id names the catalog's entry
690
+ * (lookupScenario reads the catalog first), so a stored copy would be
691
+ * hidden and would still count toward its visitor's and the store's caps.
692
+ */
693
+ const enterCatalog = (id, entry) => {
694
+ customScenarioCatalog.set(id, entry);
695
+ dropFromEveryMemoryStore(id);
696
+ };
697
+ /**
698
+ * Whether `id` already names a scenario for someone other than
699
+ * `visitorId` alone: the catalog holds it (a built-in, a curated or a
700
+ * compiled scenario, which any visitor may have picked), boot is still
701
+ * re-compiling it, or another visitor holds it in memory. A compile never
702
+ * lands under such an id, so it never changes what an id already names
703
+ * for another visitor.
704
+ */
705
+ const scenarioIdTaken = (visitorId, id) => {
706
+ if (customScenarioCatalog.has(id) || hydratingScenarioIds.has(id))
707
+ return true;
708
+ dropIdleMemoryScenarios();
709
+ for (const [holder, own] of memoryScenarios) {
710
+ if (holder !== visitorId && own.has(id))
711
+ return true;
712
+ }
713
+ return false;
714
+ };
627
715
  // Boot-time hydration of persisted compile-from-seed scenarios.
628
716
  // Drafts on disk get lazy-compiled in the background — server boot
629
717
  // doesn't await this so a cold cache (50 drafts × 30s LLM each)
@@ -632,14 +720,23 @@ export function createMarsServer(options = {}) {
632
720
  // /scenarios responses; the picker is eventually-consistent within
633
721
  // a few seconds on warm cache, a few minutes on cold.
634
722
  void (async () => {
635
- let drafts;
723
+ let saved;
636
724
  try {
637
- drafts = loadPersistedCompiledDrafts(scenarioDir);
725
+ saved = loadPersistedCompiledDrafts(scenarioDir);
638
726
  }
639
727
  catch (err) {
640
728
  console.warn('[scenarios] loadPersistedCompiledDrafts failed:', err);
641
729
  return;
642
730
  }
731
+ // A saved draft never takes the place of a scenario the catalog already
732
+ // holds (a built-in or one from the scenarios folder): it is left out,
733
+ // uncompiled, and the catalog's scenario stays.
734
+ const drafts = saved.filter(({ id }) => {
735
+ if (!customScenarioCatalog.has(id))
736
+ return true;
737
+ console.warn(`[scenarios] left out the persisted compiled draft ${id}: the catalog already holds a scenario under that id`);
738
+ return false;
739
+ });
643
740
  if (drafts.length === 0)
644
741
  return;
645
742
  for (const { id } of drafts)
@@ -665,7 +762,13 @@ export function createMarsServer(options = {}) {
665
762
  // a warm cache this is ~10ms per draft; with a cold cache the
666
763
  // hooks regenerate via LLM at the going rate.
667
764
  const compiled = await compileScenario(draft, { cache: true });
668
- customScenarioCatalog.set(compiled.id, { scenario: compiled, source: 'compiled' });
765
+ // Checked again under the compiled id: an earlier draft of this
766
+ // loop, or a scenario saved while this one compiled, may hold it.
767
+ if (customScenarioCatalog.has(compiled.id)) {
768
+ console.warn(`[scenarios] left out the persisted compiled draft ${id}: the catalog already holds a scenario under that id`);
769
+ continue;
770
+ }
771
+ enterCatalog(compiled.id, { scenario: compiled, source: 'compiled' });
669
772
  compiledScenarioMeta.set(compiled.id, meta);
670
773
  console.log(`[scenarios] hydrated ${compiled.id} (${meta.compiledAt})`);
671
774
  }
@@ -700,25 +803,40 @@ export function createMarsServer(options = {}) {
700
803
  const resolveRequestScenario = (req, explicitId, parentId) => {
701
804
  const named = typeof explicitId === 'string' ? explicitId : typeof parentId === 'string' ? parentId : null;
702
805
  if (named !== null) {
703
- const entry = customScenarioCatalog.get(named);
704
- if (entry)
705
- return { scenario: entry.scenario };
806
+ const scenario = lookupScenario(req, named);
807
+ if (scenario)
808
+ return { scenario };
706
809
  if (hydratingScenarioIds.has(named))
707
810
  return { loading: named };
708
- if (memoryScenarios.has(named))
811
+ if (ownMemoryScenarios(req)?.has(named))
709
812
  return { notRunnable: named };
710
813
  return { unknown: named };
711
814
  }
712
815
  const picked = readVisitorScenarioId(req);
713
816
  if (picked !== null) {
714
- const entry = customScenarioCatalog.get(picked);
715
- if (entry)
716
- return { scenario: entry.scenario };
817
+ const scenario = lookupScenario(req, picked);
818
+ if (scenario)
819
+ return { scenario };
717
820
  if (hydratingScenarioIds.has(picked))
718
821
  return { loading: picked };
719
822
  }
720
823
  return { scenario: marsScenario };
721
824
  };
825
+ /**
826
+ * The runnable scenario `id` names for this request: the catalog's, which
827
+ * every visitor shares, else one this visitor stored in memory. A
828
+ * visitor's stored scenario never shadows a catalog entry.
829
+ */
830
+ function lookupScenario(req, id) {
831
+ const entry = customScenarioCatalog.get(id);
832
+ if (entry)
833
+ return entry.scenario;
834
+ const held = ownMemoryScenarios(req)?.get(id);
835
+ if (!held || !isRunnableScenarioPackage(held.scenario))
836
+ return undefined;
837
+ held.usedAt = Date.now();
838
+ return held.scenario;
839
+ }
722
840
  /** Answers a request whose scenario did not resolve: 503 while it loads, 400 otherwise. */
723
841
  const writeScenarioRefusal = (res, refusal, headers = {}) => {
724
842
  if ('loading' in refusal) {
@@ -1259,7 +1377,7 @@ export function createMarsServer(options = {}) {
1259
1377
  corsHeaders,
1260
1378
  paracosmRoutesEnabled,
1261
1379
  runsDir,
1262
- scenarioLookup: (id) => customScenarioCatalog.get(id)?.scenario,
1380
+ scenarioLookup: (id) => lookupScenario(req, id),
1263
1381
  })) {
1264
1382
  return;
1265
1383
  }
@@ -1358,11 +1476,12 @@ export function createMarsServer(options = {}) {
1358
1476
  }
1359
1477
  return;
1360
1478
  }
1361
- // List scenarios that can be switched to. Builtins, disk-loaded,
1362
- // in-memory runnable customs and compiled scenarios all live in the
1363
- // same catalog, and this endpoint is a uniform iteration over it. No
1364
- // hardcoded IDs. `active` is this visitor's pick (or the default),
1365
- // so the answer varies by cookie.
1479
+ // List scenarios that can be switched to. Builtins, disk-loaded and
1480
+ // compiled scenarios all live in the same catalog, and this endpoint is
1481
+ // a uniform iteration over it, followed by the runnable scenarios this
1482
+ // visitor stored in memory, which no other visitor sees. No hardcoded
1483
+ // IDs. `active` is this visitor's pick (or the default), so the answer
1484
+ // varies by cookie.
1366
1485
  //
1367
1486
  // Each entry now carries persistence metadata + a run-count from
1368
1487
  // the run-history store so the dashboard's scenario picker can
@@ -1385,6 +1504,18 @@ export function createMarsServer(options = {}) {
1385
1504
  seedText: meta?.seedText,
1386
1505
  });
1387
1506
  }
1507
+ // The runnable scenarios this visitor stored in memory, theirs alone.
1508
+ for (const [id, { scenario: stored }] of ownMemoryScenarios(req) ?? new Map()) {
1509
+ if (customScenarioCatalog.has(id) || !isRunnableScenarioPackage(stored))
1510
+ continue;
1511
+ entries.push({
1512
+ id,
1513
+ name: stored.labels?.name || id,
1514
+ description: describeCustomScenarioSource('memory'),
1515
+ departments: stored.departments?.length || 0,
1516
+ source: 'memory',
1517
+ });
1518
+ }
1388
1519
  // While the pick re-compiles after a restart, `active` is its id, so
1389
1520
  // the selector shows it once the list holds it.
1390
1521
  const pick = resolveRequestScenario(req);
@@ -1498,14 +1629,18 @@ export function createMarsServer(options = {}) {
1498
1629
  : null;
1499
1630
  if (scenarioDetailMatch && req.method === 'GET') {
1500
1631
  const id = decodeURIComponent(scenarioDetailMatch[1]);
1632
+ // The catalog's scenario, else one this visitor stored in memory, as
1633
+ // GET /scenarios lists them: the answer varies by visitor.
1501
1634
  const entry = customScenarioCatalog.get(id);
1502
- if (!entry) {
1503
- res.writeHead(404, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
1635
+ const sc = lookupScenario(req, id);
1636
+ const detailHeaders = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', ...PER_VISITOR_HEADERS };
1637
+ if (!sc) {
1638
+ res.writeHead(404, detailHeaders);
1504
1639
  res.end(JSON.stringify({ error: 'scenario_not_found', id }));
1505
1640
  return;
1506
1641
  }
1507
- const sc = entry.scenario;
1508
- const meta = compiledScenarioMeta.get(id);
1642
+ const source = entry?.source ?? 'memory';
1643
+ const meta = entry ? compiledScenarioMeta.get(id) : undefined;
1509
1644
  const runCount = await (async () => {
1510
1645
  if (!runHistoryStore?.aggregateStats)
1511
1646
  return 0;
@@ -1548,13 +1683,13 @@ export function createMarsServer(options = {}) {
1548
1683
  role: d.role,
1549
1684
  icon: d.icon,
1550
1685
  }));
1551
- res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
1686
+ res.writeHead(200, detailHeaders);
1552
1687
  res.end(JSON.stringify({
1553
1688
  id,
1554
1689
  name: sc.labels?.name ?? id,
1555
1690
  shortName: sc.labels?.shortName,
1556
- description: describeCustomScenarioSource(entry.source),
1557
- source: entry.source,
1691
+ description: describeCustomScenarioSource(source),
1692
+ source,
1558
1693
  compiledAt: meta?.compiledAt,
1559
1694
  seedText: meta?.seedText,
1560
1695
  runCount,
@@ -1578,7 +1713,8 @@ export function createMarsServer(options = {}) {
1578
1713
  // in the client. Lets operators flip the env var + pm2 restart
1579
1714
  // and the UI updates on the next page load without a redeploy.
1580
1715
  const { DEMO_EXECUTION } = await import('../cli/sim-config.js');
1581
- res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
1716
+ // `memoryScenarios` is this visitor's own, so the answer varies by cookie.
1717
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', ...PER_VISITOR_HEADERS });
1582
1718
  res.end(JSON.stringify({
1583
1719
  adminWrite,
1584
1720
  hostedDemo,
@@ -1588,7 +1724,7 @@ export function createMarsServer(options = {}) {
1588
1724
  maxPopulation: DEMO_EXECUTION.maxPopulation,
1589
1725
  maxActiveDepartments: DEMO_EXECUTION.maxActiveDepartments,
1590
1726
  },
1591
- memoryScenarios: [...memoryScenarios.keys()],
1727
+ memoryScenarios: [...(ownMemoryScenarios(req)?.keys() ?? [])],
1592
1728
  keys: {
1593
1729
  openai: !!env.OPENAI_API_KEY,
1594
1730
  anthropic: !!env.ANTHROPIC_API_KEY,
@@ -1600,11 +1736,15 @@ export function createMarsServer(options = {}) {
1600
1736
  }));
1601
1737
  return;
1602
1738
  }
1603
- // Store a scenario in memory (any visitor) and, with saveToDisk, also
1604
- // write it to <scenarioDir>/<id>.json. The disk write takes the admin
1605
- // credential the /admin/* routes take (requireAdminToken) and an id
1606
- // that names one file directly in the scenarios folder
1607
- // (scenarioJsonPath). A refused disk write stores nothing.
1739
+ // Store a scenario in this visitor's memory (any visitor) or, with
1740
+ // saveToDisk, write it to <scenarioDir>/<id>.json and the catalog every
1741
+ // visitor reads. The disk write takes the admin credential the /admin/*
1742
+ // routes take (requireAdminToken) and an id that names one file directly
1743
+ // in the scenarios folder (scenarioJsonPath). A memory store is the
1744
+ // storing visitor's alone (memoryScenarios), so it never takes an id the
1745
+ // catalog holds, and it is held to MEMORY_SCENARIO_MAX_BYTES,
1746
+ // MEMORY_SCENARIOS_PER_VISITOR, MEMORY_SCENARIOS_PER_ADDRESS and
1747
+ // MEMORY_SCENARIOS_CAP. A refused request stores nothing.
1608
1748
  if (req.url === '/scenario/store' && req.method === 'POST') {
1609
1749
  try {
1610
1750
  const { scenario: scenarioJson, saveToDisk } = JSON.parse(await readBody(req, maxRequestBodyBytes));
@@ -1613,42 +1753,88 @@ export function createMarsServer(options = {}) {
1613
1753
  res.end(JSON.stringify({ error: 'scenario with id required' }));
1614
1754
  return;
1615
1755
  }
1616
- let diskPath = null;
1756
+ const refuse = (status, error, log) => {
1757
+ console.warn(`[scenarios] scenario store refused: ${log}`);
1758
+ res.writeHead(status, { 'Content-Type': 'application/json' });
1759
+ res.end(JSON.stringify({ error }));
1760
+ };
1761
+ const switchable = isRunnableScenarioPackage(scenarioJson);
1762
+ let savedToDisk = false;
1617
1763
  if (saveToDisk) {
1618
1764
  if (!requireAdminToken(req, res)) {
1619
1765
  console.warn('[scenarios] scenario disk write refused: admin credential missing, wrong or not configured');
1620
1766
  return;
1621
1767
  }
1622
- diskPath = scenarioJsonPath(scenarioDir, scenarioJson.id);
1768
+ const diskPath = scenarioJsonPath(scenarioDir, scenarioJson.id);
1623
1769
  if (!diskPath) {
1624
1770
  console.warn('[scenarios] scenario disk write refused: the id is not a plain scenario id');
1625
1771
  res.writeHead(400, { 'Content-Type': 'application/json' });
1626
1772
  res.end(JSON.stringify({ error: `Invalid scenario id for a disk write: ${SCENARIO_ID_RULE}.` }));
1627
1773
  return;
1628
1774
  }
1629
- }
1630
- // Store raw JSON in memory for this authoring session.
1631
- memoryScenarios.set(scenarioJson.id, scenarioJson);
1632
- const switchable = isRunnableScenarioPackage(scenarioJson);
1633
- if (switchable) {
1634
- customScenarioCatalog.set(scenarioJson.id, {
1635
- scenario: scenarioJson,
1636
- source: diskPath ? 'disk' : 'memory',
1637
- });
1638
- }
1639
- let savedToDisk = false;
1640
- if (diskPath) {
1641
1775
  const { writeFileSync, mkdirSync } = await import('node:fs');
1642
1776
  mkdirSync(scenarioDir, { recursive: true });
1643
1777
  writeFileSync(diskPath, JSON.stringify(scenarioJson, null, 2));
1644
1778
  savedToDisk = true;
1645
1779
  if (switchable) {
1646
- customScenarioCatalog.set(scenarioJson.id, {
1780
+ enterCatalog(scenarioJson.id, {
1647
1781
  scenario: scenarioJson,
1648
1782
  source: 'disk',
1649
1783
  });
1650
1784
  }
1651
1785
  }
1786
+ else {
1787
+ const id = scenarioJson.id;
1788
+ if (typeof id !== 'string') {
1789
+ refuse(400, 'The scenario id must be a string.', 'an id that is not a string');
1790
+ return;
1791
+ }
1792
+ if (customScenarioCatalog.has(id) || hydratingScenarioIds.has(id)) {
1793
+ refuse(409, `"${id}" is the id of a scenario every visitor sees. Give your copy an id of its own.`, 'an id the shared catalog holds');
1794
+ return;
1795
+ }
1796
+ if (Buffer.byteLength(JSON.stringify(scenarioJson)) > MEMORY_SCENARIO_MAX_BYTES) {
1797
+ refuse(413, `A scenario held in memory is at most ${MEMORY_SCENARIO_MAX_BYTES / 1024} KiB of JSON.`, 'over the size held in memory');
1798
+ return;
1799
+ }
1800
+ // The counts below are of what is still held: a scenario past the idle time goes first.
1801
+ dropIdleMemoryScenarios();
1802
+ const visitorId = readVisitorId(req);
1803
+ const own = memoryScenarios.get(visitorId) ?? new Map();
1804
+ const held = own.get(id);
1805
+ if (held) {
1806
+ held.scenario = scenarioJson;
1807
+ held.usedAt = Date.now();
1808
+ }
1809
+ else {
1810
+ if (own.size >= MEMORY_SCENARIOS_PER_VISITOR) {
1811
+ refuse(507, `This server holds at most ${MEMORY_SCENARIOS_PER_VISITOR} scenarios in memory for one visitor. Store over one of yours.`, 'the visitor holds the most scenarios in memory');
1812
+ return;
1813
+ }
1814
+ const address = IpRateLimiter.getIp(req);
1815
+ let atAddress = 0;
1816
+ for (const stored of memoryScenarios.values()) {
1817
+ for (const other of stored.values()) {
1818
+ if (other.address === address)
1819
+ atAddress += 1;
1820
+ }
1821
+ }
1822
+ if (atAddress >= MEMORY_SCENARIOS_PER_ADDRESS) {
1823
+ refuse(507, `This server holds at most ${MEMORY_SCENARIOS_PER_ADDRESS} scenarios in memory for one address. Store over one of yours.`, 'the address holds the most scenarios in memory');
1824
+ return;
1825
+ }
1826
+ if (memoryScenarioCount >= MEMORY_SCENARIOS_CAP) {
1827
+ const idle = memoryScenarioIdleMs >= 3_600_000
1828
+ ? `${Math.round(memoryScenarioIdleMs / 3_600_000)} hours`
1829
+ : `${Math.round(memoryScenarioIdleMs / 1000)} seconds`;
1830
+ refuse(507, `This server holds at most ${MEMORY_SCENARIOS_CAP} scenarios in memory, every visitor's together, and it is full. It drops a stored scenario that goes unused for ${idle}, so try again later.`, 'the memory store is full');
1831
+ return;
1832
+ }
1833
+ memoryScenarios.set(visitorId, own);
1834
+ memoryScenarioCount += 1;
1835
+ own.set(id, { scenario: scenarioJson, address, usedAt: Date.now() });
1836
+ }
1837
+ }
1652
1838
  res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
1653
1839
  res.end(JSON.stringify({ stored: true, id: scenarioJson.id, savedToDisk, adminWrite, switchable }));
1654
1840
  }
@@ -1699,17 +1885,38 @@ export function createMarsServer(options = {}) {
1699
1885
  if (req.url?.startsWith('/api/quickstart/') && req.method === 'POST') {
1700
1886
  try {
1701
1887
  const body = JSON.parse(await readBody(req, maxRequestBodyBytes));
1888
+ const quickstartVisitor = readVisitorId(req);
1702
1889
  const quickstartDeps = {
1703
- installCompiledScenario: (sc, seedText) => {
1890
+ installCompiledScenario: (compiledFromSeed, seedText) => {
1704
1891
  const seed = typeof seedText === 'string' && seedText.trim().length > 0
1705
1892
  ? seedText.slice(0, 1000)
1706
1893
  : null;
1894
+ // The compile picks the id, and it never replaces a scenario
1895
+ // that id already names (scenarioIdTaken): the compiled scenario
1896
+ // lands under the next free id instead, `<id>-2`, `<id>-3`, with
1897
+ // the id cut short where it must be so the whole stays within
1898
+ // QUICKSTART_SCENARIO_ID_MAX, the longest id the page's next
1899
+ // Quickstart calls take. The catalog's own entry for this very
1900
+ // scenario (a second request for a compile that already landed)
1901
+ // keeps its id.
1902
+ let sc = compiledFromSeed;
1903
+ if (customScenarioCatalog.get(sc.id)?.scenario !== sc && scenarioIdTaken(quickstartVisitor, sc.id)) {
1904
+ const takenId = sc.id;
1905
+ const withSuffix = (n) => {
1906
+ const tail = `-${n}`;
1907
+ return `${takenId.slice(0, Math.max(0, QUICKSTART_SCENARIO_ID_MAX - tail.length))}${tail}`;
1908
+ };
1909
+ let suffix = 2;
1910
+ while (scenarioIdTaken(quickstartVisitor, withSuffix(suffix)))
1911
+ suffix += 1;
1912
+ sc = { ...sc, id: withSuffix(suffix) };
1913
+ }
1707
1914
  // Quickstart-compiled scenarios reuse the 'compiled' source
1708
1915
  // tag; same post-compile semantics, no new source state
1709
1916
  // required. Nothing becomes active for anyone: the visitor who
1710
1917
  // compiled it gets it as their pick through pickHeaders on the
1711
1918
  // answers they receive.
1712
- customScenarioCatalog.set(sc.id, { scenario: sc, source: 'compiled' });
1919
+ enterCatalog(sc.id, { scenario: sc, source: 'compiled' });
1713
1920
  // Auto-persist to disk so the catalog survives server
1714
1921
  // restarts. The hooks themselves are excluded (functions
1715
1922
  // don't serialize) but compileScenario regenerates them
@@ -1727,8 +1934,9 @@ export function createMarsServer(options = {}) {
1727
1934
  // memory, so /setup carries the brief into the run either way.
1728
1935
  const persistResult = persistCompiledScenario(scenarioDir, sc, seed);
1729
1936
  compiledScenarioMeta.set(sc.id, persistResult?.meta ?? { compiledAt: new Date().toISOString(), seedText: seed });
1937
+ return sc;
1730
1938
  },
1731
- getScenarioById: (id) => customScenarioCatalog.get(id)?.scenario,
1939
+ getScenarioById: (id) => lookupScenario(req, id),
1732
1940
  pickHeaders: (id) => {
1733
1941
  const cookie = pickCookie(id, pickCookieSecure);
1734
1942
  return cookie ? { 'Set-Cookie': cookie } : {};
@@ -1749,6 +1957,7 @@ export function createMarsServer(options = {}) {
1749
1957
  groundingCitationsByScenarioId.set(scenarioId, citations);
1750
1958
  },
1751
1959
  getDigitalTwinWorld,
1960
+ ...(options.compileFromSeed ? { compileFn: options.compileFromSeed } : {}),
1752
1961
  outputDir: runsDir,
1753
1962
  // A digital-twin run is its caller's run, as a /setup run is: it
1754
1963
  // replaces their current run and leaves every other visitor's
@@ -1894,6 +2103,18 @@ export function createMarsServer(options = {}) {
1894
2103
  apiKey: normalizeCredential(apiKey),
1895
2104
  anthropicKey: normalizeCredential(anthropicKey),
1896
2105
  };
2106
+ // A compile lands in the catalog every visitor reads, under the id
2107
+ // its JSON carries, so it takes only an id that names nothing yet
2108
+ // for anyone else (scenarioIdTaken). Refused here, before the stream
2109
+ // opens, the compiler runs or the day's compile count moves.
2110
+ const compileVisitor = readVisitorId(req);
2111
+ const sourceId = scenarioJson.id;
2112
+ if (typeof sourceId === 'string' && scenarioIdTaken(compileVisitor, sourceId)) {
2113
+ console.warn('[scenarios] compile refused: its id is taken');
2114
+ res.writeHead(409, { 'Content-Type': 'application/json' });
2115
+ res.end(JSON.stringify({ error: scenarioIdTakenMessage(sourceId) }));
2116
+ return;
2117
+ }
1897
2118
  // Rate-limit compile against its own daily bucket. Each compile
1898
2119
  // costs ~$0.10 against the host's API key, so even 10 uncontrolled
1899
2120
  // hits is a real line item. Bypassed when the caller is not
@@ -1968,12 +2189,20 @@ export function createMarsServer(options = {}) {
1968
2189
  res.write(`event: progress\ndata: ${JSON.stringify({ hook: hookName, status })}\n\n`);
1969
2190
  },
1970
2191
  });
1971
- // Into the catalog only. The response is a stream whose headers went
2192
+ // Checked again under the compiled id: the compile took a while, and
2193
+ // another compile or a store may have taken the id since.
2194
+ if (scenarioIdTaken(compileVisitor, compiled.id)) {
2195
+ console.warn('[scenarios] compile not kept: its id was taken while it ran');
2196
+ res.write(`event: error\ndata: ${JSON.stringify({ error: scenarioIdTakenMessage(compiled.id) })}\n\n`);
2197
+ res.end();
2198
+ return;
2199
+ }
2200
+ // Into the catalog only, where it leaves its visitor's memory store
2201
+ // if they had stored it. The response is a stream whose headers went
1972
2202
  // out before the compile, so it cannot carry a cookie; the editor
1973
2203
  // that compiled it posts /scenario/switch with the id from
1974
2204
  // `complete`, which makes it that visitor's pick.
1975
- memoryScenarios.set(compiled.id, compiled);
1976
- customScenarioCatalog.set(compiled.id, { scenario: compiled, source: 'compiled' });
2205
+ enterCatalog(compiled.id, { scenario: compiled, source: 'compiled' });
1977
2206
  // Snapshot compile telemetry into the ring buffer so /retry-stats
1978
2207
  // aggregates compile:* schemas alongside runtime schemas, and emit
1979
2208
  // the rollup as SSE so the dashboard can render per-hook attempts
@@ -2431,7 +2660,17 @@ export function createMarsServer(options = {}) {
2431
2660
  return;
2432
2661
  const id = decodeURIComponent(adminScenarioMatch[1]);
2433
2662
  const entry = customScenarioCatalog.get(id);
2663
+ // A scenario visitors stored in memory under this id goes from every
2664
+ // visitor's store; the catalog's entry, if any, is handled below.
2665
+ const dropFromMemory = () => dropFromEveryMemoryStore(id);
2434
2666
  if (!entry) {
2667
+ const memoryDeleted = dropFromMemory();
2668
+ if (memoryDeleted > 0) {
2669
+ console.log(`[scenarios] admin deleted ${id} from ${memoryDeleted} visitor memory store(s)`);
2670
+ res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders });
2671
+ res.end(JSON.stringify({ deleted: true, id, fileDeleted: false, catalogDeleted: false, metaDeleted: false, memoryDeleted }));
2672
+ return;
2673
+ }
2435
2674
  res.writeHead(404, { 'Content-Type': 'application/json', ...corsHeaders });
2436
2675
  res.end(JSON.stringify({ error: 'scenario_not_found', id }));
2437
2676
  return;
@@ -2460,7 +2699,8 @@ export function createMarsServer(options = {}) {
2460
2699
  const fileDeleted = deletePersistedCompiledScenario(scenarioDir, id);
2461
2700
  const catalogDeleted = customScenarioCatalog.delete(id);
2462
2701
  const metaDeleted = compiledScenarioMeta.delete(id);
2463
- console.log(`[scenarios] admin deleted ${id} (file=${fileDeleted} catalog=${catalogDeleted} meta=${metaDeleted})`);
2702
+ const memoryDeleted = dropFromMemory();
2703
+ console.log(`[scenarios] admin deleted ${id} (file=${fileDeleted} catalog=${catalogDeleted} meta=${metaDeleted} memory=${memoryDeleted})`);
2464
2704
  res.writeHead(200, { 'Content-Type': 'application/json', ...corsHeaders });
2465
2705
  res.end(JSON.stringify({
2466
2706
  deleted: true,
@@ -2468,6 +2708,7 @@ export function createMarsServer(options = {}) {
2468
2708
  fileDeleted,
2469
2709
  catalogDeleted,
2470
2710
  metaDeleted,
2711
+ memoryDeleted,
2471
2712
  }));
2472
2713
  return;
2473
2714
  }