@polycode-projects/the-mechanical-code-talker 6.0.1 → 6.0.3

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.
@@ -366,6 +366,35 @@ export function inviteParamsFrom(search) {
366
366
  return { offer: offer, world: params.get("world") || "", worldName: params.get("name") || "" };
367
367
  }
368
368
 
369
+ /**
370
+ * The page's backend mode from its own query string: "aws" when
371
+ * `backend=aws` is present, "local" for anything else — absent, empty, or
372
+ * any other value, silently. Mode is a boot choice (the slider rewrites the
373
+ * URL and reloads rather than switching a live session), so this is the one
374
+ * place either mode is ever decided.
375
+ *
376
+ * Self-contained (no outer refs), `.toString()`-splice safe.
377
+ */
378
+ export function resolveBackendMode(search) {
379
+ return new URLSearchParams(String(search || "")).get("backend") === "aws" ? "aws" : "local";
380
+ }
381
+
382
+ /**
383
+ * The current page address with its `backend` query parameter rewritten to
384
+ * match `mode` — "aws" written explicitly, anything else removed rather than
385
+ * written out as "local", so a plain reload never carries a redundant param.
386
+ * Every other query parameter and the hash survive untouched, so a slider
387
+ * flip never drops an invite the address was already carrying.
388
+ *
389
+ * Self-contained (no outer refs), `.toString()`-splice safe.
390
+ */
391
+ export function backendModeUrl(pageUrl, mode) {
392
+ const url = new URL(String(pageUrl));
393
+ if (mode === "aws") url.searchParams.set("backend", "aws");
394
+ else url.searchParams.delete("backend");
395
+ return url.toString();
396
+ }
397
+
369
398
  /**
370
399
  * The boot statusline while the big assets stream in — "loading the engine…
371
400
  * X MB / Y MB", aggregated across every asset currently downloading. `parts`
@@ -561,13 +590,18 @@ ${THEME_TOKENS_CSS}
561
590
  only) has no radio of its own — every radio clears when that mode is
562
591
  active, and the statusline names it instead. */
563
592
  .composer-wiki { max-width: 720px; margin: 0 auto; padding: 0 1.1rem .4rem; display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); }
564
- fieldset.wikiMode { border: none; margin: 0; padding: 0; display: inline-flex; align-items: center; gap: .7rem; }
565
- fieldset.wikiMode legend { padding: 0; margin-right: .15rem; font: inherit; color: inherit; }
566
- fieldset.wikiMode label { display: inline-flex; align-items: center; gap: .28rem; cursor: pointer; white-space: nowrap; }
567
- fieldset.wikiMode input[type="radio"] { margin: 0; accent-color: var(--corpus); }
593
+ fieldset.wikiMode, fieldset.backendMode { border: none; margin: 0; padding: 0; display: inline-flex; align-items: center; gap: .7rem; }
594
+ fieldset.wikiMode legend, fieldset.backendMode legend { padding: 0; margin-right: .15rem; font: inherit; color: inherit; }
595
+ fieldset.wikiMode label, fieldset.backendMode label { display: inline-flex; align-items: center; gap: .28rem; cursor: pointer; white-space: nowrap; }
596
+ fieldset.wikiMode input[type="radio"], fieldset.backendMode input[type="radio"] { margin: 0; accent-color: var(--corpus); }
568
597
  .synthRow { display: inline-flex; align-items: center; gap: .5rem; white-space: nowrap; }
569
598
  .synthRow input[type="range"] { width: 88px; accent-color: var(--corpus); }
570
599
 
600
+ /* the backend row, above the wiki row: local (this browser, IndexedDB) or
601
+ AWS (an anonymous server-side session) — a boot choice, so picking one
602
+ reloads the page rather than switching a live session. */
603
+ .composer-backend { max-width: 720px; margin: 0 auto; padding: .5rem 1.1rem 0; display: flex; align-items: center; gap: .6rem; flex-wrap: wrap; font-family: ${MONO_STACK}; font-size: .68rem; color: var(--muted); }
604
+
571
605
  /* the research row: type a topic, and the page asks "research <topic>"
572
606
  then ticks "research next" turns through the queue — play/pause rides
573
607
  the shared viz-ticker verbs. Same quiet mono idiom as the wiki row. */
@@ -751,6 +785,13 @@ ${shareOverlayHtml({ withTape: true })}
751
785
  placeholder="loading the engine…" aria-label="Ask tmct something" disabled>
752
786
  <button type="submit" id="composerSend" aria-label="Send" disabled>&#8594;</button>
753
787
  </div>
788
+ <div class="composer-backend">
789
+ <fieldset class="backendMode" id="backendMode" title="local: everything you teach stays in this browser only (IndexedDB), never sent anywhere. AWS: the same engine, but taught facts save to an anonymous server-side session that expires after seven days, restored on reload. Switching reloads the page — a session is never moved between modes.">
790
+ <legend>backend</legend>
791
+ <label><input type="radio" name="backendMode" id="backendLocal" value="local" checked> local</label>
792
+ <label><input type="radio" name="backendMode" id="backendAws" value="aws"> AWS</label>
793
+ </fieldset>
794
+ </div>
754
795
  <div class="composer-wiki">
755
796
  <fieldset class="wikiMode" id="wikiMode" title="Off by default. &quot;when I don't know&quot;: a question nothing local can answer also asks en.wikipedia.org — two small requests per lookup, cited (CC BY-SA). &quot;always&quot;: every grounded answer also gets a cited Wikipedia read-out. Type /wiki supplement for that same read-out on grounded answers only, without switching this to always.">
756
797
  <legend>ask wikipedia</legend>
@@ -812,6 +853,8 @@ ${shareOverlayHtml({ withTape: true })}
812
853
  const nodeInitials = ${nodeInitials.toString()};
813
854
  const inviteLinkFor = ${inviteLinkFor.toString()};
814
855
  const inviteParamsFrom = ${inviteParamsFrom.toString()};
856
+ const resolveBackendMode = ${resolveBackendMode.toString()};
857
+ const backendModeUrl = ${backendModeUrl.toString()};
815
858
  const tapeClock = ${tapeClock.toString()};
816
859
  const relativeWhen = ${relativeWhen.toString()};
817
860
  const shareStepStates = ${shareStepStates.toString()};
@@ -844,6 +887,19 @@ ${shareOverlayHtml({ withTape: true })}
844
887
  const synthSliderEl = el("synthSlider");
845
888
  const synthValueEl = el("synthValue");
846
889
 
890
+ // The backend mode is a boot choice, decided once from the URL this page
891
+ // was loaded with — never switched under a live session. The radios only
892
+ // ever reflect that choice and, on a change, rewrite the URL and reload;
893
+ // they never flip the running session's own store.
894
+ const backendModeFieldset = el("backendMode");
895
+ const backendModeRadios = Array.prototype.slice.call(backendModeFieldset.querySelectorAll('input[type="radio"]'));
896
+ const backendMode = resolveBackendMode(location.search);
897
+ for (const radio of backendModeRadios) radio.checked = radio.value === backendMode;
898
+ backendModeFieldset.addEventListener("change", function () {
899
+ const chosen = backendModeRadios.find((r) => r.checked);
900
+ location.href = backendModeUrl(location.href, chosen ? chosen.value : "local");
901
+ });
902
+
847
903
  // The wikipedia mode: "off" | "miss" (the radio's own value for what the
848
904
  // session calls plain true, a rescue on a clean miss) | "always". "supplement"
849
905
  // (typed /wiki supplement only) never lands here — a turn that sets it
@@ -889,6 +945,25 @@ ${shareOverlayHtml({ withTape: true })}
889
945
  try { localStorage.setItem(SYNTH_BUDGET_KEY, String(n)); } catch { /* private mode — this visit still works */ }
890
946
  }
891
947
 
948
+ // AWS mode's one local item: a session pointer, never facts (§2's own
949
+ // wording — the copy the stats panel shows repeats it). Read once at boot;
950
+ // minted fresh whenever none is stored yet, or after a purge discards one.
951
+ const AWS_SESSION_KEY = "tmct.chat.sessionKey";
952
+ function readAwsSessionKey() {
953
+ try { return localStorage.getItem(AWS_SESSION_KEY) || null; } catch { return null; }
954
+ }
955
+ function writeAwsSessionKey(key) {
956
+ try { localStorage.setItem(AWS_SESSION_KEY, key); } catch { /* private mode — this visit still works, just not restorable */ }
957
+ }
958
+ function discardAwsSessionKey() {
959
+ try { localStorage.removeItem(AWS_SESSION_KEY); } catch { /* already effectively gone this visit */ }
960
+ }
961
+ function mintAwsSessionKey() {
962
+ const key = crypto.randomUUID();
963
+ writeAwsSessionKey(key);
964
+ return key;
965
+ }
966
+
892
967
  function scrollToEnd() {
893
968
  messagesEl.parentElement.scrollTop = messagesEl.parentElement.scrollHeight;
894
969
  }
@@ -1126,6 +1201,7 @@ ${shareOverlayHtml({ withTape: true })}
1126
1201
  synthesisBudget: readSynthBudget(),
1127
1202
  onLiveLookup: function () { statusEl.textContent = "searching wikipedia\\u2026"; },
1128
1203
  digestStructures: DIGEST_STRUCTURES,
1204
+ awsSessionKey: (backendMode === "aws" && !persistenceUnavailable) ? awsSessionKey : undefined,
1129
1205
  });
1130
1206
  }
1131
1207
 
@@ -1164,6 +1240,11 @@ ${shareOverlayHtml({ withTape: true })}
1164
1240
  let restoredCount = 0;
1165
1241
  let siteVersion = "dev";
1166
1242
  let lastStatsTotal = null;
1243
+ // AWS mode's own state: the minted/restored session pointer, and whether
1244
+ // the row service ever answered this visit. Local mode never touches
1245
+ // either — persist (IndexedDB) stays that mode's own persistence.
1246
+ let awsSessionKey = null;
1247
+ let persistenceUnavailable = false;
1167
1248
  window.tmctChatLastSave = null;
1168
1249
  window.tmct.lastSave = null;
1169
1250
 
@@ -1193,7 +1274,15 @@ ${shareOverlayHtml({ withTape: true })}
1193
1274
  async function forgetEverything() {
1194
1275
  clearTimeout(saveTimer);
1195
1276
  saveTimer = null;
1196
- if (persist) await persist.clear();
1277
+ if (backendMode === "aws" && !persistenceUnavailable) {
1278
+ if (window.tmct.session && window.tmct.page.discardAwsSession) {
1279
+ try { await window.tmct.page.discardAwsSession(window.tmct.session.memoryDir); }
1280
+ catch { /* best effort — the old session still expires on its own within seven days */ }
1281
+ }
1282
+ awsSessionKey = mintAwsSessionKey();
1283
+ } else if (persist) {
1284
+ await persist.clear();
1285
+ }
1197
1286
  restoredCount = 0;
1198
1287
  // The room holds the OLD session's store, so it can't outlive the swap —
1199
1288
  // it would keep merging peers' facts into a store nothing reads any more.
@@ -1201,7 +1290,10 @@ ${shareOverlayHtml({ withTape: true })}
1201
1290
  dropRoom();
1202
1291
  await newSession();
1203
1292
  const stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
1204
- addSystemLine("forgot everything taught on this device \\u2014 back to the fresh seed (" + statsSummaryLine(stats, bandLabelFor) + ").");
1293
+ const note = backendMode === "aws" && !persistenceUnavailable
1294
+ ? "forgot everything taught this session \\u2014 back to the fresh seed under a new anonymous session ("
1295
+ : "forgot everything taught on this device \\u2014 back to the fresh seed (";
1296
+ addSystemLine(note + statsSummaryLine(stats, bandLabelFor) + ").");
1205
1297
  await renderStatsPanel(stats);
1206
1298
  }
1207
1299
 
@@ -1225,10 +1317,15 @@ ${shareOverlayHtml({ withTape: true })}
1225
1317
  }
1226
1318
  lastStatsTotal = Number(stats.total || 0);
1227
1319
  renderFactPill();
1320
+ const awsPersisting = backendMode === "aws" && !persistenceUnavailable;
1228
1321
  renderStatsPanelInto(statsPanelEl, stats, {
1229
1322
  bandLabel: bandLabelFor,
1230
- onForget: persist ? forgetEverything : null,
1231
- persistNote: "taught facts are kept best-effort on this device (IndexedDB), never sent anywhere.",
1323
+ onForget: (awsPersisting || persist) ? forgetEverything : null,
1324
+ persistNote: backendMode === "aws"
1325
+ ? (persistenceUnavailable
1326
+ ? "the row service wasn't reachable this visit \\u2014 taught facts are not being saved anywhere."
1327
+ : "taught facts are stored server-side against an anonymous session that expires after seven days.")
1328
+ : "taught facts are kept best-effort on this device (IndexedDB), never sent anywhere.",
1232
1329
  });
1233
1330
  }
1234
1331
 
@@ -1649,14 +1746,23 @@ ${shareOverlayHtml({ withTape: true })}
1649
1746
  // first visit. Harder than "forget everything", which only swaps the live
1650
1747
  // session — this trusts nothing in memory and re-fetches the seed asset.
1651
1748
  //
1652
- // Both stores go, not just the payload: what you taught lives in IndexedDB,
1653
- // and the seed asset itself lives in the service worker's Cache Storage. A
1654
- // reset that cleared only the first would re-seed straight back out of a
1655
- // cached copy of an older seed, which is exactly what it promises not to do.
1749
+ // Both stores go, not just the payload: what you taught lives in IndexedDB
1750
+ // (local mode) or the row service (AWS mode), and the seed asset itself
1751
+ // lives in the service worker's Cache Storage. A reset that cleared only
1752
+ // the first would re-seed straight back out of a cached copy of an older
1753
+ // seed, which is exactly what it promises not to do. In AWS mode the reset
1754
+ // also discards the stored session pointer, so the reload it triggers
1755
+ // mints a fresh one — the same "back to a first visit" promise, kept on
1756
+ // the server side too.
1656
1757
  el("reinitStore").addEventListener("click", async () => {
1657
1758
  clearTimeout(saveTimer);
1658
1759
  saveTimer = null;
1659
1760
  if (persist) await persist.clear();
1761
+ if (backendMode === "aws" && !persistenceUnavailable && window.tmct.session && window.tmct.page.discardAwsSession) {
1762
+ try { await window.tmct.page.discardAwsSession(window.tmct.session.memoryDir); }
1763
+ catch { /* best effort — TTL still reclaims it within seven days */ }
1764
+ discardAwsSessionKey();
1765
+ }
1660
1766
  await clearSiteAssetCaches();
1661
1767
  window.location.reload();
1662
1768
  });
@@ -2410,36 +2516,93 @@ ${shareOverlayHtml({ withTape: true })}
2410
2516
  await Promise.all([fetchSeed(), tryLoadWink(), fetchSiteVersion().then((v) => { siteVersion = v; })]);
2411
2517
  progressActive = false;
2412
2518
  window.tmct.page.registerReferencePackProvider(fetchPackProvider);
2413
- if (window.tmct.page.openPersistedStore) {
2414
- persist = window.tmct.page.openPersistedStore({ storeKey: "chat", stamp: siteVersion + ":" + seedFacts + ":" + SEED_STAMP });
2415
- }
2416
- const savedRecord = persist ? await persist.load() : null;
2417
2519
  const initialMode = readWikiMode();
2418
2520
  setWikiModeRadios(initialMode);
2419
2521
  writeWikiMode(initialMode); // settles a legacy-key migration under the new key immediately, not only on the next radio change
2420
2522
  synthSliderEl.value = String(readSynthBudget());
2421
2523
  synthValueEl.textContent = synthSliderEl.value;
2422
- if (savedRecord && savedRecord.payload) {
2524
+
2525
+ // AWS mode boots straight into the row service under the stored (or
2526
+ // freshly minted) session pointer — no separate consent step, unlike
2527
+ // news.html's start press, since this page's engine is in-page either
2528
+ // way and the mode was already chosen before this script ran. Local
2529
+ // mode keeps its own IndexedDB restore path, byte-identical to before.
2530
+ let savedRecord = null;
2531
+ if (backendMode === "aws") {
2532
+ awsSessionKey = readAwsSessionKey() || mintAwsSessionKey();
2423
2533
  await window.tmct.open({
2424
- seedPayload: savedRecord.payload,
2425
- vocabSeeded: true,
2534
+ seedPayload: cloneSeed(),
2535
+ vocabSeeded: Boolean(seedPayload),
2426
2536
  liveReference: liveReferenceForMode(initialMode),
2427
2537
  synthesisBudget: readSynthBudget(),
2428
2538
  onLiveLookup: function () { statusEl.textContent = "searching wikipedia\\u2026"; },
2429
2539
  digestStructures: DIGEST_STRUCTURES,
2540
+ awsSessionKey: awsSessionKey,
2430
2541
  });
2431
2542
  } else {
2432
- await newSession();
2543
+ if (window.tmct.page.openPersistedStore) {
2544
+ persist = window.tmct.page.openPersistedStore({ storeKey: "chat", stamp: siteVersion + ":" + seedFacts + ":" + SEED_STAMP });
2545
+ }
2546
+ savedRecord = persist ? await persist.load() : null;
2547
+ if (savedRecord && savedRecord.payload) {
2548
+ await window.tmct.open({
2549
+ seedPayload: savedRecord.payload,
2550
+ vocabSeeded: true,
2551
+ liveReference: liveReferenceForMode(initialMode),
2552
+ synthesisBudget: readSynthBudget(),
2553
+ onLiveLookup: function () { statusEl.textContent = "searching wikipedia\\u2026"; },
2554
+ digestStructures: DIGEST_STRUCTURES,
2555
+ });
2556
+ } else {
2557
+ await newSession();
2558
+ }
2433
2559
  }
2434
2560
  // The session now holds whatever the seed brought, so the phase settles
2435
2561
  // here rather than when the bytes landed: "ready" means queryable.
2436
2562
  if (window.tmct.seed.state !== "failed") setSeedPhase("ready");
2437
- const stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
2438
- if (savedRecord) restoredCount = stats.taught.length;
2439
- const restoredNote = savedRecord
2440
- ? " Restored " + restoredCount + " taught fact" + (restoredCount === 1 ? "" : "s")
2441
- + " from your last visit \\u2014 state kept best-effort on this device."
2442
- : "";
2563
+
2564
+ // AWS mode's first real read: an unreachable row service surfaces here,
2565
+ // before "ready" is ever said, and the page falls through to running
2566
+ // this visit unpersisted rather than failing to boot — the best-effort
2567
+ // row every page keeps (§2's own wording): the engine is in-page, so a
2568
+ // service outage never blocks the page, it only costs this visit's save.
2569
+ let stats;
2570
+ if (backendMode === "aws") {
2571
+ try {
2572
+ stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
2573
+ } catch {
2574
+ persistenceUnavailable = true;
2575
+ await window.tmct.open({
2576
+ seedPayload: cloneSeed(),
2577
+ vocabSeeded: Boolean(seedPayload),
2578
+ liveReference: liveReferenceForMode(initialMode),
2579
+ synthesisBudget: readSynthBudget(),
2580
+ onLiveLookup: function () { statusEl.textContent = "searching wikipedia\\u2026"; },
2581
+ digestStructures: DIGEST_STRUCTURES,
2582
+ });
2583
+ stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
2584
+ }
2585
+ } else {
2586
+ stats = await window.tmct.page.memoryStats(window.tmct.session.memoryDir);
2587
+ }
2588
+
2589
+ if (backendMode === "aws" && !persistenceUnavailable) restoredCount = stats.taught.length;
2590
+ else if (savedRecord) restoredCount = stats.taught.length;
2591
+
2592
+ let restoredNote;
2593
+ if (backendMode === "aws") {
2594
+ restoredNote = persistenceUnavailable
2595
+ ? " This visit couldn't reach the row service \\u2014 running unpersisted; nothing taught will be saved."
2596
+ : (restoredCount
2597
+ ? " Restored " + restoredCount + " taught fact" + (restoredCount === 1 ? "" : "s")
2598
+ + " from your last visit \\u2014 kept server-side against this anonymous session."
2599
+ : "");
2600
+ } else {
2601
+ restoredNote = savedRecord
2602
+ ? " Restored " + restoredCount + " taught fact" + (restoredCount === 1 ? "" : "s")
2603
+ + " from your last visit \\u2014 state kept best-effort on this device."
2604
+ : "";
2605
+ }
2443
2606
  addSystemLine("tmct \\u2014 the real engine, running in this page \\u2014 " + statsSummaryLine(stats, bandLabelFor)
2444
2607
  + "." + restoredNote + " Ask it something, or teach it a fact of your own.");
2445
2608
  await renderStatsPanel(stats);