@kehto/paja 0.28.1 → 0.30.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/README.md CHANGED
@@ -340,6 +340,12 @@ artifact CSP is retained. Set `frame-ancestors` on the host HTTP response, not
340
340
  in a meta policy. See the [shared policy contract](https://github.com/kehto/web/blob/main/docs/policies/NIP-5D-CONFORMANCE.md#shell-csp-enforcement).
341
341
  Local target-URL authoring mode retains its separate development policy and HMR.
342
342
 
343
+ The Paja host page carries `Content-Security-Policy: frame-src 'none'` in its
344
+ `<head>` (`renderNappletFramePolicyMeta()` from `@kehto/shell`), so a napplet
345
+ cannot navigate its frame away from the verified `srcdoc` at any time,
346
+ including before its first `load`, which NIP-5D's replacement evidence cannot
347
+ observe. Paja refuses to load a napplet into a frame whose host page lacks it.
348
+
343
349
  Environment simulation can be supplied through CLI flags or a JSON config file:
344
350
 
345
351
  ```bash
@@ -602,6 +608,21 @@ This non-normative guidance defers to the living [NAP-LLM](https://github.com/na
602
608
 
603
609
  Paja MUST load all three NIP-5D manifest kinds: root `15129`, named `35129`, and snapshot `5129`. Use an `naddr` with an empty identifier for the latest root, an `naddr` with the literal `d` identifier for the latest named napplet, or a `nevent` to pin a signed event of any of the three kinds. Snapshots require `nevent` because they are immutable events without replaceable coordinates. All paths verify the signed manifest and artifact hash before injecting `srcdoc`. Distinct snapshots retain separate tabs and catalog identities even when their artifact bytes match.
604
610
 
611
+
612
+ ### Relay unreachable
613
+
614
+ Pointer resolution tracks each relay's connection outcome, not just whether
615
+ events arrived. When **zero** relays open a WebSocket, the resolver throws
616
+ `PajaRelayUnreachableError` (`code: 'relay-unreachable'`, with a
617
+ `PajaRelayConnectionSummary` of connected/failed/pending relays) instead of the
618
+ generic timeout, and the pointer status reads `No relay connection could be
619
+ opened … 0 of N relays connected …` with the likely causes: the browser is
620
+ offline, the relays are blocked, or the browser reached its WebSocket connection
621
+ limit (for example many open tabs each holding relay connections). Paja logs a
622
+ `paja.relay.unreachable` entry with the per-relay detail. A deadline expiry with
623
+ at least one live relay keeps the timeout message and now states how many relays
624
+ connected. Pools without `ensureRelay` keep the previous messages.
625
+
605
626
  ## Controller diagnostics
606
627
 
607
628
  Paja shows a numbered controller icon directly beside the console arrow for each controller the browser detects. Each slot has its own color and input animation; hover for the controller model and activity state. Buttons and stick movement light up only that controller (stick movement below 0.12 is ignored). Quick taps retain the highlight briefly so they are easy to spot. Reduced-motion settings keep the activity highlight without animation. Disconnecting removes the icon. Browsers may require a button press before exposing a newly connected controller. These host diagnostics work without a napplet gamepad subscription and do not change focus-scoped input delivery.
@@ -14138,8 +14138,9 @@ async function* readLlmSseData(body, signal) {
14138
14138
  var PRESET_ROWS = [
14139
14139
  { id: "openai", label: "OpenAI", protocol: "openai-chat", baseUrl: "https://api.openai.com/v1", requiresCredential: true, local: false, docsUrl: "https://platform.openai.com/docs/api-reference/chat", exampleModels: ["gpt-4.1-mini", "gpt-4o-mini"] },
14140
14140
  { id: "anthropic", label: "Anthropic", protocol: "anthropic-messages", baseUrl: "https://api.anthropic.com/v1", requiresCredential: true, local: false, docsUrl: "https://docs.anthropic.com/en/api/messages", exampleModels: ["claude-sonnet-4-5", "claude-haiku-4-5"] },
14141
- { id: "gemini", label: "Google Gemini", protocol: "gemini", baseUrl: "https://generativelanguage.googleapis.com/v1beta", requiresCredential: true, local: false, docsUrl: "https://ai.google.dev/api/generate-content", exampleModels: ["gemini-2.5-flash", "gemini-2.5-pro"] },
14142
14141
  { id: "openrouter", label: "OpenRouter", protocol: "openai-chat", baseUrl: "https://openrouter.ai/api/v1", requiresCredential: true, local: false, docsUrl: "https://openrouter.ai/docs/api-reference/overview", exampleModels: ["openai/gpt-4.1-mini", "anthropic/claude-sonnet-4.5"] },
14142
+ { id: "routstr", label: "Routstr", protocol: "openai-chat", baseUrl: "http://127.0.0.1:8008/v1", requiresCredential: false, local: true, docsUrl: "https://routstr.com", exampleModels: [], modelsPath: "/models" },
14143
+ { id: "gemini", label: "Google Gemini", protocol: "gemini", baseUrl: "https://generativelanguage.googleapis.com/v1beta", requiresCredential: true, local: false, docsUrl: "https://ai.google.dev/api/generate-content", exampleModels: ["gemini-2.5-flash", "gemini-2.5-pro"] },
14143
14144
  { id: "groq", label: "Groq", protocol: "openai-chat", baseUrl: "https://api.groq.com/openai/v1", requiresCredential: true, local: false, docsUrl: "https://console.groq.com/docs/openai", exampleModels: ["llama-3.3-70b-versatile"] },
14144
14145
  { id: "mistral", label: "Mistral", protocol: "openai-chat", baseUrl: "https://api.mistral.ai/v1", requiresCredential: true, local: false, docsUrl: "https://docs.mistral.ai/api/", exampleModels: ["mistral-small-latest"] },
14145
14146
  { id: "deepseek", label: "DeepSeek", protocol: "openai-chat", baseUrl: "https://api.deepseek.com/v1", requiresCredential: true, local: false, docsUrl: "https://api-docs.deepseek.com/", exampleModels: ["deepseek-chat"] },
@@ -14786,6 +14787,76 @@ function installPajaResourceSettings() {
14786
14787
  return { getServers: settings.getServers, dispose: () => form?.removeEventListener("submit", submit) };
14787
14788
  }
14788
14789
 
14790
+ // src/browser-llm-models.ts
14791
+ var PajaLlmModelsError = class extends Error {
14792
+ constructor(failure4, message3) {
14793
+ super(message3);
14794
+ this.failure = failure4;
14795
+ this.name = "PajaLlmModelsError";
14796
+ }
14797
+ failure;
14798
+ };
14799
+ var PAJA_LLM_MODELS_TIMEOUT_MS = 8e3;
14800
+ function llmModelsUrl(baseUrl, modelsPath) {
14801
+ return `${baseUrl.trim().replace(/\/+$/, "")}/${modelsPath.trim().replace(/^\/+/, "")}`;
14802
+ }
14803
+ function readModelIds(body) {
14804
+ const rows = Array.isArray(body) ? body : body && typeof body === "object" ? body.data ?? body.models : void 0;
14805
+ if (!Array.isArray(rows)) throw new PajaLlmModelsError("shape", "The server did not return a model list.");
14806
+ const ids = [];
14807
+ const seen = /* @__PURE__ */ new Set();
14808
+ for (const row of rows) {
14809
+ const id = typeof row === "string" ? row : row && typeof row === "object" && typeof row.id === "string" ? row.id : void 0;
14810
+ const trimmed = id?.trim();
14811
+ if (!trimmed || seen.has(trimmed)) continue;
14812
+ seen.add(trimmed);
14813
+ ids.push(trimmed);
14814
+ }
14815
+ if (ids.length === 0) throw new PajaLlmModelsError("shape", "The server reported no models.");
14816
+ return ids.sort((a, b) => a.localeCompare(b));
14817
+ }
14818
+ async function fetchPajaLlmModels(options) {
14819
+ const fetchImpl = options.fetch ?? globalThis.fetch;
14820
+ const controller = new AbortController();
14821
+ const timeoutMs = options.timeoutMs ?? PAJA_LLM_MODELS_TIMEOUT_MS;
14822
+ let timedOut = false;
14823
+ const timer = setTimeout(() => {
14824
+ timedOut = true;
14825
+ controller.abort();
14826
+ }, timeoutMs);
14827
+ const abortFromCaller = () => controller.abort();
14828
+ options.signal?.addEventListener("abort", abortFromCaller, { once: true });
14829
+ const reason = () => timedOut ? "timeout" : options.signal?.aborted ? "aborted" : "network";
14830
+ try {
14831
+ const headers = { accept: "application/json" };
14832
+ if (options.credential) headers.authorization = `Bearer ${options.credential}`;
14833
+ const response = await fetchImpl(llmModelsUrl(options.baseUrl, options.modelsPath), {
14834
+ method: "GET",
14835
+ headers,
14836
+ signal: controller.signal
14837
+ });
14838
+ if (!response.ok) {
14839
+ throw new PajaLlmModelsError("http", `The server answered ${String(response.status)} for ${options.modelsPath}.`);
14840
+ }
14841
+ let body;
14842
+ try {
14843
+ body = await response.json();
14844
+ } catch {
14845
+ throw new PajaLlmModelsError("shape", "The server did not return JSON for the model list.");
14846
+ }
14847
+ return readModelIds(body);
14848
+ } catch (error) {
14849
+ if (error instanceof PajaLlmModelsError) throw error;
14850
+ if (timedOut || options.signal?.aborted) {
14851
+ throw new PajaLlmModelsError(reason(), timedOut ? `No answer from the server within ${String(Math.round(timeoutMs / 1e3))}s.` : "The model listing was cancelled.");
14852
+ }
14853
+ throw new PajaLlmModelsError("network", "Could not read the model list \u2014 the server is down, or it does not allow this page cross-origin (CORS).");
14854
+ } finally {
14855
+ clearTimeout(timer);
14856
+ options.signal?.removeEventListener("abort", abortFromCaller);
14857
+ }
14858
+ }
14859
+
14789
14860
  // src/browser-llm-connections.ts
14790
14861
  var PAJA_LLM_CONNECTIONS_STORAGE_KEY = "kehto:paja:llm-connections:v1";
14791
14862
  var MAX_CONNECTIONS = 32;
@@ -15308,6 +15379,10 @@ function readForm() {
15308
15379
  const name = byId("paja-llm-name", HTMLInputElement);
15309
15380
  const baseUrl = byId("paja-llm-base-url", HTMLInputElement);
15310
15381
  const model = byId("paja-llm-model", HTMLInputElement);
15382
+ const modelField = byId("paja-llm-model-field", HTMLElement);
15383
+ const modelSelect = byId("paja-llm-model-select", HTMLSelectElement);
15384
+ const modelSelectField = byId("paja-llm-model-select-field", HTMLElement);
15385
+ const modelStatus = byId("paja-llm-model-status", HTMLElement);
15311
15386
  const examples = byId("paja-llm-model-examples", HTMLDataListElement);
15312
15387
  const credential = byId("paja-llm-credential", HTMLInputElement);
15313
15388
  const remember = byId("paja-llm-remember", HTMLInputElement);
@@ -15316,8 +15391,27 @@ function readForm() {
15316
15391
  const list = byId("paja-llm-connections", HTMLElement);
15317
15392
  const status = byId("paja-llm-status", HTMLElement);
15318
15393
  const lock = byId("paja-llm-vault-lock", HTMLButtonElement);
15319
- if (!form || !preset || !name || !baseUrl || !model || !examples || !credential || !remember || !images || !json || !list || !status || !lock) return null;
15320
- return { form, preset, name, baseUrl, model, examples, credential, remember, images, json, list, status, lock, section: byId("paja-section-llm", HTMLDetailsElement) };
15394
+ if (!form || !preset || !name || !baseUrl || !model || !modelField || !modelSelect || !modelSelectField || !modelStatus || !examples || !credential || !remember || !images || !json || !list || !status || !lock) return null;
15395
+ return {
15396
+ form,
15397
+ preset,
15398
+ name,
15399
+ baseUrl,
15400
+ model,
15401
+ modelField,
15402
+ modelSelect,
15403
+ modelSelectField,
15404
+ modelStatus,
15405
+ examples,
15406
+ credential,
15407
+ remember,
15408
+ images,
15409
+ json,
15410
+ list,
15411
+ status,
15412
+ lock,
15413
+ section: byId("paja-section-llm", HTMLDetailsElement)
15414
+ };
15321
15415
  }
15322
15416
  function installPajaLlmPanel(options) {
15323
15417
  const { store: store2, vault } = options;
@@ -15350,14 +15444,89 @@ function installPajaLlmPanel(options) {
15350
15444
  setStatus2("Wrong vault password. Try again or clear the vault to start over.", true);
15351
15445
  }
15352
15446
  }
15447
+ let modelListing = null;
15448
+ function setModelStatus(text2, state = "idle") {
15449
+ if (!elements) return;
15450
+ elements.modelStatus.textContent = text2;
15451
+ if (state === "idle") delete elements.modelStatus.dataset.state;
15452
+ else elements.modelStatus.dataset.state = state;
15453
+ }
15454
+ function setModelMode(mode) {
15455
+ if (!elements) return;
15456
+ const listing = mode === "select";
15457
+ elements.modelField.hidden = listing;
15458
+ elements.modelSelectField.hidden = !listing;
15459
+ elements.model.disabled = listing;
15460
+ elements.modelSelect.disabled = !listing;
15461
+ }
15462
+ function currentModel() {
15463
+ if (!elements) return "";
15464
+ return (elements.modelSelectField.hidden ? elements.model.value : elements.modelSelect.value).trim();
15465
+ }
15466
+ async function refreshModels() {
15467
+ if (!elements) return;
15468
+ modelListing?.abort();
15469
+ modelListing = null;
15470
+ const preset = presetById(elements.preset.value);
15471
+ const modelsPath = preset?.modelsPath;
15472
+ if (!modelsPath) {
15473
+ setModelMode("text");
15474
+ setModelStatus("");
15475
+ return;
15476
+ }
15477
+ setModelMode("select");
15478
+ elements.modelSelect.replaceChildren();
15479
+ let baseUrl;
15480
+ try {
15481
+ baseUrl = normalizePajaLlmBaseUrl(elements.baseUrl.value);
15482
+ } catch (error) {
15483
+ setModelMode("text");
15484
+ setModelStatus(error instanceof Error ? error.message : "Enter an absolute API base URL.", "error");
15485
+ return;
15486
+ }
15487
+ const controller = new AbortController();
15488
+ modelListing = controller;
15489
+ setModelStatus("Connecting\u2026", "busy");
15490
+ try {
15491
+ const models = await fetchPajaLlmModels({
15492
+ baseUrl,
15493
+ modelsPath,
15494
+ ...elements.credential.value.trim() ? { credential: elements.credential.value.trim() } : {},
15495
+ signal: controller.signal
15496
+ });
15497
+ if (modelListing !== controller || !elements) return;
15498
+ elements.modelSelect.replaceChildren(...models.map((id) => Object.assign(document.createElement("option"), { value: id, textContent: id })));
15499
+ setModelStatus(`Connected \u2713 \u2014 ${String(models.length)} model${models.length === 1 ? "" : "s"}`, "ready");
15500
+ } catch (error) {
15501
+ if (modelListing !== controller || !elements) return;
15502
+ if (error instanceof PajaLlmModelsError && error.failure === "aborted") return;
15503
+ setModelMode("text");
15504
+ setModelStatus(`${error instanceof Error ? error.message : "Could not list models."} Type the model id instead.`, "error");
15505
+ if (preset.id === "routstr") {
15506
+ const install = Object.assign(document.createElement("a"), {
15507
+ href: "https://routstr.com/routstrd",
15508
+ textContent: "Install routstrd",
15509
+ target: "_blank",
15510
+ rel: "noopener noreferrer"
15511
+ });
15512
+ elements.modelStatus.append(document.createElement("br"), install);
15513
+ }
15514
+ } finally {
15515
+ if (modelListing === controller) modelListing = null;
15516
+ }
15517
+ }
15518
+ let appliedPreset;
15353
15519
  function applyPreset() {
15354
15520
  if (!elements) return;
15355
15521
  const preset = presetById(elements.preset.value);
15356
15522
  if (!preset) return;
15523
+ if (appliedPreset && appliedPreset.id !== preset.id) elements.credential.value = "";
15524
+ if (!elements.name.value || elements.name.value === appliedPreset?.label) elements.name.value = preset.label;
15525
+ appliedPreset = preset;
15357
15526
  if (preset.baseUrl) elements.baseUrl.value = preset.baseUrl;
15358
15527
  elements.examples.replaceChildren(...preset.exampleModels.map((value) => Object.assign(document.createElement("option"), { value })));
15359
- if (!elements.name.value) elements.name.value = preset.label;
15360
15528
  elements.credential.placeholder = preset.requiresCredential ? "API key (sent only to this base URL)" : "Optional for local servers";
15529
+ void refreshModels();
15361
15530
  }
15362
15531
  function renderList() {
15363
15532
  if (!elements) return;
@@ -15403,6 +15572,11 @@ function installPajaLlmPanel(options) {
15403
15572
  const credential = elements.credential.value;
15404
15573
  const storage = credential ? elements.remember.checked ? "vault" : "session" : "none";
15405
15574
  const preset = presetById(elements.preset.value);
15575
+ const model = currentModel();
15576
+ if (!model) {
15577
+ setModelStatus("Choose or type a model id.", "error");
15578
+ return;
15579
+ }
15406
15580
  let record3;
15407
15581
  try {
15408
15582
  record3 = {
@@ -15411,7 +15585,7 @@ function installPajaLlmPanel(options) {
15411
15585
  presetId: preset?.id ?? "custom",
15412
15586
  protocol: preset?.protocol ?? "openai-chat",
15413
15587
  baseUrl: normalizePajaLlmBaseUrl(elements.baseUrl.value),
15414
- model: elements.model.value,
15588
+ model,
15415
15589
  images: elements.images.checked,
15416
15590
  json: elements.json.checked,
15417
15591
  credentialStorage: storage,
@@ -15438,6 +15612,10 @@ function installPajaLlmPanel(options) {
15438
15612
  elements.preset.replaceChildren(...LLM_PROVIDER_PRESETS.map((preset) => Object.assign(document.createElement("option"), { value: preset.id, textContent: preset.label })));
15439
15613
  applyPreset();
15440
15614
  const onPreset = () => applyPreset();
15615
+ const onBaseUrl = () => {
15616
+ if (!presetById(elements.preset.value)?.modelsPath) return;
15617
+ void refreshModels();
15618
+ };
15441
15619
  const onSubmit = (event) => {
15442
15620
  void submit(event);
15443
15621
  };
@@ -15448,10 +15626,13 @@ function installPajaLlmPanel(options) {
15448
15626
  options.onChange?.();
15449
15627
  };
15450
15628
  elements.preset.addEventListener("change", onPreset);
15629
+ elements.baseUrl.addEventListener("change", onBaseUrl);
15451
15630
  elements.form.addEventListener("submit", onSubmit);
15452
15631
  elements.lock.addEventListener("click", onLock);
15453
15632
  disposers.push(() => {
15633
+ modelListing?.abort();
15454
15634
  elements.preset.removeEventListener("change", onPreset);
15635
+ elements.baseUrl.removeEventListener("change", onBaseUrl);
15455
15636
  elements.form.removeEventListener("submit", onSubmit);
15456
15637
  elements.lock.removeEventListener("click", onLock);
15457
15638
  });
@@ -16749,6 +16930,10 @@ function postShellInit(windowId, environment) {
16749
16930
  };
16750
16931
  originRegistry.postToNapplet(windowId, initMsg);
16751
16932
  }
16933
+ var NAPPLET_FRAME_POLICY = "frame-src 'none'";
16934
+ function hasNappletFramePolicy(doc) {
16935
+ return [...doc.querySelectorAll('meta[http-equiv="Content-Security-Policy" i]')].some((meta) => meta.content.split(";").some((directive) => directive.trim() === NAPPLET_FRAME_POLICY));
16936
+ }
16752
16937
  var NAPPLET_HELLO = "napplet.hello";
16753
16938
  function reportUnrouted(hooks, event, reason) {
16754
16939
  if (!hooks.onUnroutedMessage) return;
@@ -16770,6 +16955,15 @@ var REVOCATION_DETAIL = {
16770
16955
  function isHello(data) {
16771
16956
  return typeof data === "object" && data !== null && data.type === NAPPLET_HELLO;
16772
16957
  }
16958
+ var framePolicyWarned = false;
16959
+ function warnWithoutFramePolicy(frame) {
16960
+ const doc = frame.ownerDocument;
16961
+ if (framePolicyWarned || !doc || hasNappletFramePolicy(doc)) return;
16962
+ framePolicyWarned = true;
16963
+ console.warn(
16964
+ `[kehto] The host page has no "${NAPPLET_FRAME_POLICY}" CSP. A napplet that navigates its frame before its first load is invisible to NIP-5D's replacement evidence; add renderNappletFramePolicyMeta() to the host page <head>.`
16965
+ );
16966
+ }
16773
16967
  function createNip5dTransport({ hooks, runtime, state: shellReadyState }) {
16774
16968
  const bindings = /* @__PURE__ */ new Map();
16775
16969
  function currentBinding(windowId) {
@@ -16872,6 +17066,7 @@ function createNip5dTransport({ hooks, runtime, state: shellReadyState }) {
16872
17066
  bindPort(windowId, sourceWindow, event.origin, ports[0]);
16873
17067
  }
16874
17068
  function observeFrame(frame, windowId) {
17069
+ warnWithoutFramePolicy(frame);
16875
17070
  let loads = 0;
16876
17071
  const onLoad = () => {
16877
17072
  loads += 1;
@@ -17155,9 +17350,20 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
17155
17350
  const target = window;
17156
17351
  const allowed2 = new Set(domains);
17157
17352
  const requestTimeoutMs = 3e4;
17158
- for (const rtcCtor of ["RTCPeerConnection", "webkitRTCPeerConnection"]) {
17353
+ const rtcGlobals = /* @__PURE__ */ new Set([
17354
+ "webkitRTCPeerConnection",
17355
+ "mozRTCPeerConnection",
17356
+ "webkitRTCSessionDescription",
17357
+ "mozRTCSessionDescription",
17358
+ "webkitRTCIceCandidate",
17359
+ "mozRTCIceCandidate"
17360
+ ]);
17361
+ for (const key of Object.getOwnPropertyNames(target)) {
17362
+ if (key.startsWith("RTC")) rtcGlobals.add(key);
17363
+ }
17364
+ for (const rtcName of rtcGlobals) {
17159
17365
  try {
17160
- Object.defineProperty(target, rtcCtor, {
17366
+ Object.defineProperty(target, rtcName, {
17161
17367
  value: void 0,
17162
17368
  writable: false,
17163
17369
  configurable: false,
@@ -25115,6 +25321,9 @@ function ensureFreshNappletFrame(frame) {
25115
25321
  }
25116
25322
  async function navigateFrame(frame, config, generation2, adapter, resolvedTarget, windowId, isCurrent, onRegistered) {
25117
25323
  denyNappletControllerAccess(frame);
25324
+ if (!hasNappletFramePolicy(frame.ownerDocument)) {
25325
+ throw new Error("[paja] The host page has no frame-src lock; refusing to load a napplet whose frame could navigate away from its verified document.");
25326
+ }
25118
25327
  const identity = getTargetOriginIdentity(config, resolvedTarget);
25119
25328
  const environment = resolvePajaFrameEnvironment(adapter, identity);
25120
25329
  const domains = environment.capabilities.domains;
@@ -27097,6 +27306,16 @@ function freezeRecord(record3) {
27097
27306
 
27098
27307
  // src/runtime-resolver.ts
27099
27308
  var PAJA_NAPPLET_MANIFEST_KINDS = NAPPLET_KINDS;
27309
+ var PajaRelayUnreachableError = class extends Error {
27310
+ constructor(message3, connections) {
27311
+ super(message3);
27312
+ this.connections = connections;
27313
+ this.name = "PajaRelayUnreachableError";
27314
+ }
27315
+ connections;
27316
+ /** Stable discriminator for hosts that cannot rely on `instanceof` across bundles. */
27317
+ code = "relay-unreachable";
27318
+ };
27100
27319
  function decodePajaPointer(value) {
27101
27320
  const trimmed = value.trim();
27102
27321
  const decoded = decode(trimmed);
@@ -27178,9 +27397,17 @@ async function resolvePointerEvent(pointer, pool, relays, maxWaitMs) {
27178
27397
  const result2 = await queryPointerRelays(pool, relays, filter, maxWaitMs);
27179
27398
  const event = result2.events.filter((candidate) => matchesPointer(pointer, candidate)).sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id))[0];
27180
27399
  if (!event) {
27400
+ const connections = result2.connections;
27401
+ if (connections && connections.total > 0 && connections.connected.length === 0) {
27402
+ throw new PajaRelayUnreachableError(
27403
+ describeRelayUnreachable(pointer.type, connections, maxWaitMs),
27404
+ connections
27405
+ );
27406
+ }
27181
27407
  if (result2.timedOut) {
27408
+ const connectedNote = connections ? ` (${connections.connected.length} of ${connections.total} relays connected)` : "";
27182
27409
  throw new Error(
27183
- `Relay resolution timed out after ${maxWaitMs}ms for ${pointer.type} pointer across ${relays.length} relays before complete EOSE.`
27410
+ `Relay resolution timed out after ${maxWaitMs}ms for ${pointer.type} pointer across ${relays.length} relays before complete EOSE${connectedNote}.`
27184
27411
  );
27185
27412
  }
27186
27413
  const failures = relayFailureReasons(result2.reasons);
@@ -27197,11 +27424,55 @@ async function resolvePointerEvent(pointer, pool, relays, maxWaitMs) {
27197
27424
  }
27198
27425
  return event;
27199
27426
  }
27200
- function queryPointerRelays(pool, relays, filter, maxWaitMs) {
27201
- if (pool.subscribeManyEose) {
27202
- return queryPointerRelaySubscription(pool, relays, filter, maxWaitMs);
27427
+ async function queryPointerRelays(pool, relays, filter, maxWaitMs) {
27428
+ const tracker = trackRelayConnections(pool, relays, maxWaitMs);
27429
+ const result2 = pool.subscribeManyEose ? await queryPointerRelaySubscription(pool, relays, filter, maxWaitMs) : await queryPointerRelaySync(pool, relays, filter, maxWaitMs);
27430
+ return tracker ? { ...result2, connections: tracker.snapshot() } : result2;
27431
+ }
27432
+ function trackRelayConnections(pool, relays, maxWaitMs) {
27433
+ const ensureRelay = pool.ensureRelay?.bind(pool);
27434
+ if (!ensureRelay) return null;
27435
+ const urls = [...new Set(relays)];
27436
+ const connected = [];
27437
+ const failed2 = [];
27438
+ const pending = new Set(urls);
27439
+ for (const url of urls) {
27440
+ const settle7 = (outcome, reason) => {
27441
+ if (!pending.delete(url)) return;
27442
+ if (outcome === "connected") connected.push(url);
27443
+ else failed2.push({ url, reason: reason ?? "connection failed" });
27444
+ };
27445
+ try {
27446
+ ensureRelay(url, { connectionTimeout: maxWaitMs }).then(
27447
+ () => settle7("connected"),
27448
+ (error) => settle7("failed", describeRelayFailure(error))
27449
+ );
27450
+ } catch (error) {
27451
+ settle7("failed", describeRelayFailure(error));
27452
+ }
27203
27453
  }
27204
- return queryPointerRelaySync(pool, relays, filter, maxWaitMs);
27454
+ return {
27455
+ snapshot: () => ({
27456
+ total: urls.length,
27457
+ connected: [...connected],
27458
+ failed: [...failed2],
27459
+ pending: [...pending]
27460
+ })
27461
+ };
27462
+ }
27463
+ function describeRelayFailure(error) {
27464
+ const text2 = error instanceof Error ? error.message : String(error ?? "");
27465
+ const trimmed = text2.trim();
27466
+ return (trimmed.length > 0 ? trimmed : "connection failed").slice(0, 160);
27467
+ }
27468
+ function describeRelayUnreachable(pointerType, connections, maxWaitMs) {
27469
+ const reasons = relayFailureReasons(connections.failed.map((entry) => entry.reason));
27470
+ const parts = [
27471
+ `No relay connection could be opened for the ${pointerType} pointer: 0 of ${connections.total} relays connected within ${maxWaitMs}ms (${connections.failed.length} failed, ${connections.pending.length} still connecting).`,
27472
+ "The browser is offline, the relays are blocked, or the browser reached its WebSocket connection limit (for example many open tabs each holding relay connections) \u2014 close some tabs and retry."
27473
+ ];
27474
+ if (reasons.length > 0) parts.push(`Relay errors: ${reasons.join("; ")}.`);
27475
+ return parts.join(" ");
27205
27476
  }
27206
27477
  function queryPointerRelaySubscription(pool, relays, filter, maxWaitMs) {
27207
27478
  return new Promise((resolve) => {
@@ -29338,6 +29609,17 @@ async function loadRuntimePointer(state, context, value, options = {}) {
29338
29609
  state.resolvedTarget = null;
29339
29610
  setPointerStatus(state, message3);
29340
29611
  setStatus(state, "error");
29612
+ if (error instanceof PajaRelayUnreachableError) {
29613
+ const { total, connected, failed: failed2, pending } = error.connections;
29614
+ appendPajaMessageLog(state, "paja", {
29615
+ type: "paja.relay.unreachable",
29616
+ relays: total,
29617
+ connected: connected.length,
29618
+ failed: failed2.map((entry) => `${entry.url}: ${entry.reason}`),
29619
+ pending: [...pending],
29620
+ hint: "browser offline, relays blocked, or WebSocket connection limit reached \u2014 close other tabs holding relay connections and retry"
29621
+ });
29622
+ }
29341
29623
  appendPajaMessageLog(state, "paja", { type: "paja.pointer.error", error: message3 });
29342
29624
  }
29343
29625
  }