@kehto/paja 0.26.1 → 0.27.1

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.
@@ -10219,6 +10219,7 @@ async function resolvePlan(ctx, pubkeys, direction, relayHints) {
10219
10219
  }
10220
10220
  function discoveredReadRelays(ctx, authors, lists) {
10221
10221
  const relays = /* @__PURE__ */ new Set();
10222
+ const authorsByRelay = /* @__PURE__ */ new Map();
10222
10223
  const missingAuthors = [];
10223
10224
  for (const author of new Set(authors)) {
10224
10225
  const writeRelays = lists.get(author)?.write;
@@ -10226,9 +10227,14 @@ function discoveredReadRelays(ctx, authors, lists) {
10226
10227
  missingAuthors.push(author);
10227
10228
  continue;
10228
10229
  }
10229
- for (const url of allowed(ctx, writeRelays)) relays.add(url);
10230
+ for (const url of allowed(ctx, writeRelays)) {
10231
+ relays.add(url);
10232
+ const owners = authorsByRelay.get(url) ?? [];
10233
+ owners.push(author);
10234
+ authorsByRelay.set(url, owners);
10235
+ }
10230
10236
  }
10231
- return { relays: [...relays], missingAuthors };
10237
+ return { relays: [...relays], authorsByRelay, missingAuthors };
10232
10238
  }
10233
10239
  function immediateReadPlan(ctx, relayHints) {
10234
10240
  const hints = allowed(ctx, relayHints ?? []);
@@ -10276,8 +10282,8 @@ function buildQueryResult(collector, options, incomplete, subscribedAny) {
10276
10282
  if (!subscribedAny) result2.error = "relay list unavailable";
10277
10283
  return result2;
10278
10284
  }
10279
- function relayPoolSubscribe(ctx, filters, relayUrl2, cb, origin) {
10280
- return ctx.relayPool.subscribe(filters, [relayUrl2], cb, origin);
10285
+ function relayPoolSubscribe(ctx, filters, relayUrl2, cb, origin, authors) {
10286
+ return ctx.relayPool.subscribe(filters, [relayUrl2], cb, origin, authors);
10281
10287
  }
10282
10288
  function startQueryImpl(ctx, filters, options, sink) {
10283
10289
  if (!ctx.relayPool.isAvailable()) {
@@ -10327,7 +10333,7 @@ function startQueryImpl(ctx, filters, options, sink) {
10327
10333
  if (finished2 || discoveryPending || collector.pendingVerifications > 0) return;
10328
10334
  if (activeRelays.size === 0 || eoseRelays.size >= activeRelays.size) finalize();
10329
10335
  }
10330
- function attachRelay(relayUrl2, origin) {
10336
+ function attachRelay(relayUrl2, origin, relayAuthors) {
10331
10337
  if (finished2 || activeRelays.has(relayUrl2)) return;
10332
10338
  activeRelays.add(relayUrl2);
10333
10339
  try {
@@ -10340,7 +10346,7 @@ function startQueryImpl(ctx, filters, options, sink) {
10340
10346
  }
10341
10347
  recordRelay(collector, item.id, relayUrl2);
10342
10348
  admitEvent(ctx, collector, item, sink, () => !finished2, maybeFinalize);
10343
- }, origin);
10349
+ }, origin, relayAuthors);
10344
10350
  subscribedAny = true;
10345
10351
  if (finished2) {
10346
10352
  try {
@@ -10355,13 +10361,15 @@ function startQueryImpl(ctx, filters, options, sink) {
10355
10361
  incomplete = true;
10356
10362
  }
10357
10363
  }
10358
- function attachMany(relayUrls2, origin) {
10359
- for (const relayUrl2 of relayUrls2) attachRelay(relayUrl2, origin);
10364
+ function attachMany(relayUrls2, origin, authorsByRelay) {
10365
+ for (const relayUrl2 of relayUrls2) {
10366
+ attachRelay(relayUrl2, origin, origin === "nip65" ? authorsByRelay?.get(relayUrl2) ?? [] : authors);
10367
+ }
10360
10368
  }
10361
- function attachHintedAndDiscovered(hintRelays, discoveredRelays) {
10369
+ function attachHintedAndDiscovered(hintRelays, discovery) {
10362
10370
  attachMany(hintRelays, "hint");
10363
- attachMany(discoveredRelays, "nip65");
10364
- if (hintRelays.length === 0 && discoveredRelays.length === 0) {
10371
+ attachMany(discovery.relays, "nip65", discovery.authorsByRelay);
10372
+ if (hintRelays.length === 0 && discovery.relays.length === 0) {
10365
10373
  attachMany(allowed(ctx, ctx.fallbackRelays), "fallback");
10366
10374
  }
10367
10375
  }
@@ -10387,7 +10395,7 @@ function startQueryImpl(ctx, filters, options, sink) {
10387
10395
  const discovery = discoveredReadRelays(ctx, authors, loaded);
10388
10396
  discoveryPending = false;
10389
10397
  incomplete ||= discovery.missingAuthors.length > 0;
10390
- attachHintedAndDiscovered(allowed(ctx, options?.relays ?? []), discovery.relays);
10398
+ attachHintedAndDiscovered(allowed(ctx, options?.relays ?? []), discovery);
10391
10399
  maybeFinalize();
10392
10400
  } else {
10393
10401
  const immediate = immediateReadPlan(ctx, options?.relays);
@@ -10397,7 +10405,7 @@ function startQueryImpl(ctx, filters, options, sink) {
10397
10405
  const discovery = discoveredReadRelays(ctx, authors, lists);
10398
10406
  discoveryPending = false;
10399
10407
  incomplete ||= discovery.missingAuthors.length > 0;
10400
- attachMany(discovery.relays, "nip65");
10408
+ attachMany(discovery.relays, "nip65", discovery.authorsByRelay);
10401
10409
  maybeFinalize();
10402
10410
  }).catch(() => {
10403
10411
  if (finished2) return;
@@ -10443,7 +10451,7 @@ function closeLiveSub(sub) {
10443
10451
  }
10444
10452
  sub.handles.clear();
10445
10453
  }
10446
- function attachLiveRelay(ctx, sub, filters, relayUrl2, sink, origin) {
10454
+ function attachLiveRelay(ctx, sub, filters, relayUrl2, sink, routing) {
10447
10455
  if (sub.closed || sub.relays.has(relayUrl2)) return false;
10448
10456
  sub.relays.add(relayUrl2);
10449
10457
  try {
@@ -10455,7 +10463,7 @@ function attachLiveRelay(ctx, sub, filters, relayUrl2, sink, origin) {
10455
10463
  sub.seen.add(item.id);
10456
10464
  sink.event(createRelayEventResultWithHints(item, [relayUrl2]));
10457
10465
  });
10458
- }, origin);
10466
+ }, routing.origin, routing.authors);
10459
10467
  if (sub.closed) {
10460
10468
  try {
10461
10469
  handle.unsubscribe();
@@ -10481,13 +10489,18 @@ function startSubscription(ctx, filters, options, sink) {
10481
10489
  };
10482
10490
  let discoveryOpen = authors.length > 0;
10483
10491
  let discoveryTimer;
10484
- function attachMany(relayUrls2, origin) {
10485
- for (const relayUrl2 of relayUrls2) attachLiveRelay(ctx, sub, filters, relayUrl2, sink, origin);
10492
+ function attachMany(relayUrls2, origin, authorsByRelay) {
10493
+ for (const relayUrl2 of relayUrls2) {
10494
+ attachLiveRelay(ctx, sub, filters, relayUrl2, sink, {
10495
+ origin,
10496
+ authors: origin === "nip65" ? authorsByRelay?.get(relayUrl2) ?? [] : authors
10497
+ });
10498
+ }
10486
10499
  }
10487
- function attachHintedAndDiscovered(hintRelays, discoveredRelays) {
10500
+ function attachHintedAndDiscovered(hintRelays, discovery) {
10488
10501
  attachMany(hintRelays, "hint");
10489
- attachMany(discoveredRelays, "nip65");
10490
- if (hintRelays.length === 0 && discoveredRelays.length === 0) {
10502
+ attachMany(discovery.relays, "nip65", discovery.authorsByRelay);
10503
+ if (hintRelays.length === 0 && discovery.relays.length === 0) {
10491
10504
  attachMany(allowed(ctx, ctx.fallbackRelays), "fallback");
10492
10505
  }
10493
10506
  }
@@ -10517,7 +10530,7 @@ function startSubscription(ctx, filters, options, sink) {
10517
10530
  if (discoveryOpen && loaded instanceof Map) {
10518
10531
  const discovery = discoveredReadRelays(ctx, authors, loaded);
10519
10532
  discoveryOpen = false;
10520
- attachHintedAndDiscovered(allowed(ctx, options?.relays ?? []), discovery.relays);
10533
+ attachHintedAndDiscovered(allowed(ctx, options?.relays ?? []), discovery);
10521
10534
  closeUnavailable();
10522
10535
  } else if (discoveryOpen) {
10523
10536
  const immediate = immediateReadPlan(ctx, options?.relays);
@@ -10530,7 +10543,8 @@ function startSubscription(ctx, filters, options, sink) {
10530
10543
  if (!discoveryOpen || sub.closed) return;
10531
10544
  discoveryOpen = false;
10532
10545
  clearTimeout(discoveryTimer);
10533
- attachMany(discoveredReadRelays(ctx, authors, lists).relays, "nip65");
10546
+ const discovery = discoveredReadRelays(ctx, authors, lists);
10547
+ attachMany(discovery.relays, "nip65", discovery.authorsByRelay);
10534
10548
  closeUnavailable();
10535
10549
  }).catch(() => {
10536
10550
  if (!discoveryOpen || sub.closed) return;
@@ -13399,6 +13413,10 @@ var REQUEST_TYPES = /* @__PURE__ */ new Set(["llm.select", "llm.describe", "llm.
13399
13413
  var CANCELLED = { code: "cancelled", message: "Generation cancelled; provider charges may still apply." };
13400
13414
  var TIMEOUT = { code: "timeout", message: "Generation deadline reached; provider charges may still apply." };
13401
13415
  var EXPIRED = { code: "selection-expired", message: "Unknown or expired model handle; select again." };
13416
+ var CHANGED_DURING_SELECT = { code: "selection-expired", message: "Connections changed during selection; select again." };
13417
+ var CHANGED_DURING_CONSENT = { code: "selection-expired", message: "The selected connection changed before submission; select again." };
13418
+ var SELECT_REVOKED = { code: "cancelled", message: "Selection cancelled; authorization was revoked." };
13419
+ var DEFAULT_MAX_HANDLES = 32;
13402
13420
  function failure(error) {
13403
13421
  if (error instanceof LlmServiceError) return { code: error.code, message: error.message };
13404
13422
  return { code: "provider-error", message: "The provider request failed." };
@@ -13453,9 +13471,55 @@ function cancelWindow(state, windowId, error) {
13453
13471
  settle6(state, windowId, requestId, generation2, error ? { type: "llm.generate.result", id: requestId, error } : null);
13454
13472
  }
13455
13473
  }
13474
+ function expireStaleConsent(state) {
13475
+ for (const [windowId, perWindow] of state.active) {
13476
+ for (const [requestId, generation2] of perWindow) {
13477
+ if (!generation2.awaitingConsent) continue;
13478
+ if (generation2.epoch === state.epoch && state.handles.get(windowId)?.has(generation2.handle)) continue;
13479
+ failGeneration(state, windowId, requestId, generation2, CHANGED_DURING_CONSENT);
13480
+ }
13481
+ }
13482
+ }
13483
+ function settleSelects(state, windowId, error) {
13484
+ const windows = windowId === null ? [...state.selects.keys()] : [windowId];
13485
+ for (const id of windows) {
13486
+ for (const pending of state.selects.get(id) ?? []) {
13487
+ pending.done = true;
13488
+ pending.controller.abort();
13489
+ if (error) reply(pending.send, "llm.select", pending.id, { error });
13490
+ }
13491
+ state.selects.delete(id);
13492
+ }
13493
+ }
13456
13494
  function invalidateHandles(state) {
13457
13495
  state.epoch += 1;
13458
13496
  state.handles.clear();
13497
+ settleSelects(state, null, CHANGED_DURING_SELECT);
13498
+ expireStaleConsent(state);
13499
+ }
13500
+ function storeHandle(state, windowId, handle, entry) {
13501
+ const entries = windowHandles(state, windowId);
13502
+ entries.set(handle, entry);
13503
+ let evicted = false;
13504
+ while (entries.size > state.maxHandles) {
13505
+ const oldest = entries.keys().next().value;
13506
+ entries.delete(oldest);
13507
+ evicted = true;
13508
+ }
13509
+ if (evicted) expireStaleConsent(state);
13510
+ }
13511
+ function trackSelect(state, windowId, pending) {
13512
+ let perWindow = state.selects.get(windowId);
13513
+ if (!perWindow) {
13514
+ perWindow = /* @__PURE__ */ new Set();
13515
+ state.selects.set(windowId, perWindow);
13516
+ }
13517
+ perWindow.add(pending);
13518
+ return () => {
13519
+ const current = state.selects.get(windowId);
13520
+ current?.delete(pending);
13521
+ if (current?.size === 0) state.selects.delete(windowId);
13522
+ };
13459
13523
  }
13460
13524
  async function handleSelect(state, windowId, message22, send) {
13461
13525
  const id = message22.id;
@@ -13466,9 +13530,11 @@ async function handleSelect(state, windowId, message22, send) {
13466
13530
  }
13467
13531
  const wanted = requirements2 ?? {};
13468
13532
  const startEpoch = state.epoch;
13533
+ const pending = { controller: new AbortController(), id, send, done: false };
13534
+ const untrack = trackSelect(state, windowId, pending);
13469
13535
  try {
13470
- const connection = await state.host.select({ windowId }, wanted);
13471
- if (state.closed) return;
13536
+ const connection = await state.host.select({ windowId }, wanted, { signal: pending.controller.signal });
13537
+ if (pending.done || state.closed) return;
13472
13538
  if (connection === null) {
13473
13539
  reply(send, "llm.select", id, { error: { code: "user-cancelled", message: "The user declined to select a model connection." } });
13474
13540
  return;
@@ -13478,14 +13544,17 @@ async function handleSelect(state, windowId, message22, send) {
13478
13544
  return;
13479
13545
  }
13480
13546
  if (startEpoch !== state.epoch) {
13481
- reply(send, "llm.select", id, { error: { code: "selection-expired", message: "Connections changed during selection; select again." } });
13547
+ reply(send, "llm.select", id, { error: CHANGED_DURING_SELECT });
13482
13548
  return;
13483
13549
  }
13484
13550
  const handle = state.createHandle();
13485
- windowHandles(state, windowId).set(handle, { connectionId: connection.id, snapshot: connection });
13551
+ storeHandle(state, windowId, handle, { connectionId: connection.id, snapshot: connection });
13486
13552
  reply(send, "llm.select", id, { model: toModel(handle, connection) });
13487
13553
  } catch (error) {
13488
- if (!state.closed) reply(send, "llm.select", id, { error: failure(error) });
13554
+ if (!pending.done && !state.closed) reply(send, "llm.select", id, { error: failure(error) });
13555
+ } finally {
13556
+ pending.done = true;
13557
+ untrack();
13489
13558
  }
13490
13559
  }
13491
13560
  async function revalidate(state, windowId, handle) {
@@ -13493,10 +13562,14 @@ async function revalidate(state, windowId, handle) {
13493
13562
  const entry = windowHandles(state, windowId).get(handle);
13494
13563
  if (!entry) return EXPIRED;
13495
13564
  const current = await state.host.describe({ windowId }, entry.connectionId);
13565
+ const entries = windowHandles(state, windowId);
13566
+ if (entries.get(handle) !== entry) return EXPIRED;
13567
+ entries.delete(handle);
13496
13568
  if (!current || !sameConnection(current, entry.snapshot)) {
13497
- windowHandles(state, windowId).delete(handle);
13569
+ expireStaleConsent(state);
13498
13570
  return EXPIRED;
13499
13571
  }
13572
+ entries.set(handle, entry);
13500
13573
  return toModel(handle, current);
13501
13574
  }
13502
13575
  async function handleDescribe(state, windowId, message22, send) {
@@ -13530,6 +13603,18 @@ function validateGeneration(generation2, result2) {
13530
13603
  }
13531
13604
  return result2;
13532
13605
  }
13606
+ async function awaitConsent(state, context, connection, request, generation2) {
13607
+ const prompt = new AbortController();
13608
+ const withdraw = () => prompt.abort();
13609
+ generation2.controller.signal.addEventListener("abort", withdraw, { once: true });
13610
+ generation2.awaitingConsent = true;
13611
+ try {
13612
+ return await state.host.authorize(context, connection, request, { signal: prompt.signal });
13613
+ } finally {
13614
+ generation2.awaitingConsent = false;
13615
+ generation2.controller.signal.removeEventListener("abort", withdraw);
13616
+ }
13617
+ }
13533
13618
  async function runGeneration(state, windowId, requestId, request, generation2, send) {
13534
13619
  const context = { windowId };
13535
13620
  const fail2 = (error) => failGeneration(state, windowId, requestId, generation2, error);
@@ -13546,14 +13631,14 @@ async function runGeneration(state, windowId, requestId, request, generation2, s
13546
13631
  fail2(rejected2);
13547
13632
  return;
13548
13633
  }
13549
- const authorized = await state.host.authorize(context, entry.snapshot, request);
13634
+ const authorized = await awaitConsent(state, context, entry.snapshot, request, generation2);
13550
13635
  if (generation2.settled) return;
13551
13636
  if (!authorized) {
13552
13637
  fail2({ code: "user-cancelled", message: "The user declined to disclose this request." });
13553
13638
  return;
13554
13639
  }
13555
13640
  if (generation2.epoch !== state.epoch || !windowHandles(state, windowId).has(request.handle)) {
13556
- fail2({ code: "selection-expired", message: "The selected connection changed before submission; select again." });
13641
+ fail2(CHANGED_DURING_CONSENT);
13557
13642
  return;
13558
13643
  }
13559
13644
  const result2 = await state.host.generate(context, entry.snapshot, request, {
@@ -13581,6 +13666,8 @@ function handleGenerate(state, windowId, message22, send) {
13581
13666
  const request = message22.request;
13582
13667
  const generation2 = {
13583
13668
  controller: new AbortController(),
13669
+ handle: request.handle,
13670
+ awaitingConsent: false,
13584
13671
  send,
13585
13672
  format: request.format ?? "text",
13586
13673
  epoch: state.epoch,
@@ -13620,15 +13707,18 @@ function createLlmService(options) {
13620
13707
  deadlineMs: options.deadlineMs ?? 12e4,
13621
13708
  maxConcurrent: options.maxConcurrentPerWindow ?? 4,
13622
13709
  maxRequestChars: options.maxRequestChars ?? 4 * 1024 * 1024,
13710
+ maxHandles: Math.max(1, Math.floor(options.maxHandlesPerWindow ?? DEFAULT_MAX_HANDLES)),
13623
13711
  createHandle: options.createHandle ?? defaultHandleFactory(),
13624
13712
  handles: /* @__PURE__ */ new Map(),
13625
13713
  active: /* @__PURE__ */ new Map(),
13714
+ selects: /* @__PURE__ */ new Map(),
13626
13715
  epoch: 0,
13627
13716
  closed: false
13628
13717
  };
13629
13718
  let unsubscribe;
13630
13719
  function revokeWindow(windowId) {
13631
13720
  cancelWindow(state, windowId, CANCELLED);
13721
+ settleSelects(state, windowId, SELECT_REVOKED);
13632
13722
  state.handles.delete(windowId);
13633
13723
  }
13634
13724
  return {
@@ -13640,8 +13730,8 @@ function createLlmService(options) {
13640
13730
  state.closed = false;
13641
13731
  unsubscribe?.();
13642
13732
  unsubscribe = state.host.subscribe?.(() => {
13643
- invalidateHandles(state);
13644
13733
  for (const windowId of state.active.keys()) cancelWindow(state, windowId, CANCELLED);
13734
+ invalidateHandles(state);
13645
13735
  });
13646
13736
  },
13647
13737
  onUnregistered() {
@@ -13649,6 +13739,7 @@ function createLlmService(options) {
13649
13739
  unsubscribe?.();
13650
13740
  unsubscribe = void 0;
13651
13741
  for (const windowId of state.active.keys()) cancelWindow(state, windowId, null);
13742
+ settleSelects(state, null, null);
13652
13743
  state.handles.clear();
13653
13744
  },
13654
13745
  handleMessage(windowId, message22, send) {
@@ -13671,6 +13762,7 @@ function createLlmService(options) {
13671
13762
  },
13672
13763
  onWindowDestroyed(windowId) {
13673
13764
  cancelWindow(state, windowId, null);
13765
+ settleSelects(state, windowId, null);
13674
13766
  state.handles.delete(windowId);
13675
13767
  },
13676
13768
  onCapabilityRevoked(windowId, capability) {
@@ -13721,12 +13813,13 @@ function openAiContent(parts) {
13721
13813
  if (!hasImage(parts)) return textOf(parts);
13722
13814
  return parts.map((part2) => part2.type === "text" ? { type: "text", text: part2.text } : { type: "image_url", image_url: { url: `data:${part2.mimeType};base64,${part2.data}` } });
13723
13815
  }
13724
- function buildOpenAiChat(endpoint, request) {
13816
+ function buildOpenAiChat(endpoint, request, stream) {
13725
13817
  const body = {
13726
13818
  model: endpoint.model,
13727
13819
  messages: request.messages.map((message22) => ({ role: message22.role, content: openAiContent(message22.content) })),
13728
- stream: false
13820
+ stream
13729
13821
  };
13822
+ if (stream) body.stream_options = { include_usage: true };
13730
13823
  if (request.format === "json") body.response_format = { type: "json_object" };
13731
13824
  if (endpoint.maxOutputTokens !== void 0) body.max_tokens = endpoint.maxOutputTokens;
13732
13825
  return {
@@ -13745,16 +13838,21 @@ function parseOpenAiChat(json) {
13745
13838
  const tokens = usageFrom(usage2?.prompt_tokens, usage2?.completion_tokens);
13746
13839
  if (typeof message22.refusal === "string" && message22.refusal.length > 0) return finished("", "refusal", tokens);
13747
13840
  const text2 = typeof message22.content === "string" ? message22.content : "";
13748
- switch (choice.finish_reason) {
13749
- case "stop":
13750
- return finished(text2, "stop", tokens);
13751
- case "length":
13752
- return finished(text2, "length", tokens);
13753
- case "content_filter":
13754
- return finished(text2, "refusal", tokens);
13755
- default:
13756
- throw providerError("The provider response had no recognised completion marker.");
13757
- }
13841
+ return completed(text2, openAiFinish(choice.finish_reason), tokens);
13842
+ }
13843
+ function openAiFinish(reason) {
13844
+ if (reason === "stop") return "stop";
13845
+ if (reason === "length") return "length";
13846
+ return reason === "content_filter" ? "refusal" : null;
13847
+ }
13848
+ function anthropicFinish(reason) {
13849
+ if (reason === "end_turn" || reason === "stop_sequence") return "stop";
13850
+ if (reason === "max_tokens") return "length";
13851
+ return reason === "refusal" ? "refusal" : null;
13852
+ }
13853
+ function completed(text2, finish, usage2) {
13854
+ if (finish === null) throw providerError("The provider response had no recognised completion marker.");
13855
+ return finished(text2, finish, usage2);
13758
13856
  }
13759
13857
  function anthropicBlocks(parts) {
13760
13858
  return parts.map((part2) => part2.type === "text" ? { type: "text", text: part2.text } : { type: "image", source: { type: "base64", media_type: part2.mimeType, data: part2.data } });
@@ -13772,7 +13870,7 @@ function splitSystem(messages) {
13772
13870
  }
13773
13871
  return { system: systemParts.join("\n"), turns };
13774
13872
  }
13775
- function buildAnthropicMessages(endpoint, request) {
13873
+ function buildAnthropicMessages(endpoint, request, stream) {
13776
13874
  const { system, turns } = splitSystem(request.messages);
13777
13875
  if (turns.length === 0 || turns[0].role !== "user") throw unsupported4("This provider requires the first non-system message to come from the user.");
13778
13876
  const merged = [];
@@ -13787,7 +13885,7 @@ function buildAnthropicMessages(endpoint, request) {
13787
13885
  model: endpoint.model,
13788
13886
  max_tokens: endpoint.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
13789
13887
  messages: merged,
13790
- stream: false
13888
+ stream
13791
13889
  };
13792
13890
  if (systemText) body.system = systemText;
13793
13891
  return {
@@ -13812,22 +13910,12 @@ function parseAnthropicMessages(json) {
13812
13910
  }).join("");
13813
13911
  const usage2 = record2(root.usage);
13814
13912
  const tokens = usageFrom(usage2?.input_tokens, usage2?.output_tokens);
13815
- switch (root.stop_reason) {
13816
- case "end_turn":
13817
- case "stop_sequence":
13818
- return finished(text2, "stop", tokens);
13819
- case "max_tokens":
13820
- return finished(text2, "length", tokens);
13821
- case "refusal":
13822
- return finished(text2, "refusal", tokens);
13823
- default:
13824
- throw providerError("The provider response had no recognised completion marker.");
13825
- }
13913
+ return completed(text2, anthropicFinish(root.stop_reason), tokens);
13826
13914
  }
13827
13915
  function geminiParts(parts) {
13828
13916
  return parts.map((part2) => part2.type === "text" ? { text: part2.text } : { inlineData: { mimeType: part2.mimeType, data: part2.data } });
13829
13917
  }
13830
- function buildGemini(endpoint, request) {
13918
+ function buildGemini(endpoint, request, stream) {
13831
13919
  const { system, turns } = splitSystem(request.messages);
13832
13920
  if (turns.length === 0) throw unsupported4("This provider requires at least one user or assistant message.");
13833
13921
  const generationConfig = {};
@@ -13839,7 +13927,7 @@ function buildGemini(endpoint, request) {
13839
13927
  if (system) body.systemInstruction = { parts: [{ text: system }] };
13840
13928
  if (Object.keys(generationConfig).length > 0) body.generationConfig = generationConfig;
13841
13929
  return {
13842
- url: `${trimBase(endpoint.baseUrl)}/models/${encodeURIComponent(endpoint.model)}:generateContent`,
13930
+ url: `${trimBase(endpoint.baseUrl)}/models/${encodeURIComponent(endpoint.model)}:${stream ? "streamGenerateContent?alt=sse" : "generateContent"}`,
13843
13931
  method: "POST",
13844
13932
  headers: { "content-type": "application/json", ...endpoint.headers, ...credentialHeaders(endpoint) },
13845
13933
  body: JSON.stringify(body)
@@ -13859,20 +13947,22 @@ function parseGemini(json) {
13859
13947
  const entry = record2(part2);
13860
13948
  return typeof entry?.text === "string" ? entry.text : "";
13861
13949
  }).join("");
13862
- const reason = candidate.finishReason;
13863
- if (reason === "STOP") return finished(text2, "stop", tokens);
13864
- if (reason === "MAX_TOKENS") return finished(text2, "length", tokens);
13865
- if (typeof reason === "string" && GEMINI_REFUSALS.has(reason)) return finished(text2, "refusal", tokens);
13866
- throw providerError("The provider response had no recognised completion marker.");
13950
+ return completed(text2, geminiFinish(candidate.finishReason), tokens);
13867
13951
  }
13868
- function buildLlmProviderRequest(endpoint, request) {
13952
+ function geminiFinish(reason) {
13953
+ if (reason === "STOP") return "stop";
13954
+ if (reason === "MAX_TOKENS") return "length";
13955
+ return typeof reason === "string" && GEMINI_REFUSALS.has(reason) ? "refusal" : null;
13956
+ }
13957
+ function buildLlmProviderRequest(endpoint, request, options = {}) {
13958
+ const stream = options.stream === true;
13869
13959
  switch (endpoint.protocol) {
13870
13960
  case "openai-chat":
13871
- return buildOpenAiChat(endpoint, request);
13961
+ return buildOpenAiChat(endpoint, request, stream);
13872
13962
  case "anthropic-messages":
13873
- return buildAnthropicMessages(endpoint, request);
13963
+ return buildAnthropicMessages(endpoint, request, stream);
13874
13964
  case "gemini":
13875
- return buildGemini(endpoint, request);
13965
+ return buildGemini(endpoint, request, stream);
13876
13966
  default:
13877
13967
  throw unsupported4("Unknown provider protocol.");
13878
13968
  }
@@ -13889,6 +13979,162 @@ function parseLlmProviderResponse(protocol, json) {
13889
13979
  throw providerError("Unknown provider protocol.");
13890
13980
  }
13891
13981
  }
13982
+ var STREAM_ERROR = "The provider reported an error while streaming.";
13983
+ function textField(value) {
13984
+ return typeof value === "string" ? value : "";
13985
+ }
13986
+ function openAiAccumulator() {
13987
+ let text2 = "";
13988
+ let refused = false;
13989
+ let finish = null;
13990
+ let usage2;
13991
+ return {
13992
+ push(event) {
13993
+ const root = record2(event);
13994
+ if (root?.error !== void 0) throw providerError(STREAM_ERROR);
13995
+ const reported = record2(root?.usage);
13996
+ if (reported) usage2 = usageFrom(reported.prompt_tokens, reported.completion_tokens) ?? usage2;
13997
+ const choice = record2(Array.isArray(root?.choices) ? root?.choices[0] : void 0);
13998
+ if (!choice) return "";
13999
+ const delta = record2(choice.delta);
14000
+ if (textField(delta?.refusal).length > 0) refused = true;
14001
+ finish = openAiFinish(choice.finish_reason) ?? finish;
14002
+ const appended = textField(delta?.content);
14003
+ text2 += appended;
14004
+ return appended;
14005
+ },
14006
+ finish: () => refused ? completed("", "refusal", usage2) : completed(text2, finish, usage2)
14007
+ };
14008
+ }
14009
+ function anthropicAccumulator() {
14010
+ let text2 = "";
14011
+ let finish = null;
14012
+ let inputTokens;
14013
+ let outputTokens;
14014
+ return {
14015
+ push(event) {
14016
+ const root = record2(event);
14017
+ switch (root?.type) {
14018
+ case "error":
14019
+ throw providerError(STREAM_ERROR);
14020
+ case "message_start":
14021
+ inputTokens = record2(record2(root.message)?.usage)?.input_tokens;
14022
+ return "";
14023
+ case "message_delta": {
14024
+ finish = anthropicFinish(record2(root.delta)?.stop_reason) ?? finish;
14025
+ const usage2 = record2(root.usage);
14026
+ if (usage2?.output_tokens !== void 0) outputTokens = usage2.output_tokens;
14027
+ if (usage2?.input_tokens !== void 0) inputTokens = usage2.input_tokens;
14028
+ return "";
14029
+ }
14030
+ case "content_block_delta": {
14031
+ const delta = record2(root.delta);
14032
+ const appended = delta?.type === "text_delta" ? textField(delta.text) : "";
14033
+ text2 += appended;
14034
+ return appended;
14035
+ }
14036
+ default:
14037
+ return "";
14038
+ }
14039
+ },
14040
+ finish: () => completed(text2, finish, usageFrom(inputTokens, outputTokens))
14041
+ };
14042
+ }
14043
+ function geminiAccumulator() {
14044
+ let text2 = "";
14045
+ let blocked = false;
14046
+ let finish = null;
14047
+ let usage2;
14048
+ return {
14049
+ push(event) {
14050
+ const root = record2(event);
14051
+ if (root?.error !== void 0) throw providerError(STREAM_ERROR);
14052
+ const metadata = record2(root?.usageMetadata);
14053
+ if (metadata) usage2 = usageFrom(metadata.promptTokenCount, metadata.candidatesTokenCount) ?? usage2;
14054
+ if (typeof record2(root?.promptFeedback)?.blockReason === "string") blocked = true;
14055
+ const candidate = record2(Array.isArray(root?.candidates) ? root?.candidates[0] : void 0);
14056
+ if (!candidate) return "";
14057
+ finish = geminiFinish(candidate.finishReason) ?? finish;
14058
+ const parts = record2(candidate.content)?.parts;
14059
+ const appended = Array.isArray(parts) ? parts.map((part2) => textField(record2(part2)?.text)).join("") : "";
14060
+ text2 += appended;
14061
+ return appended;
14062
+ },
14063
+ finish: () => blocked ? completed("", "refusal", usage2) : completed(text2, finish, usage2)
14064
+ };
14065
+ }
14066
+ function createLlmStreamAccumulator(protocol) {
14067
+ switch (protocol) {
14068
+ case "openai-chat":
14069
+ return openAiAccumulator();
14070
+ case "anthropic-messages":
14071
+ return anthropicAccumulator();
14072
+ case "gemini":
14073
+ return geminiAccumulator();
14074
+ default:
14075
+ throw providerError("Unknown provider protocol.");
14076
+ }
14077
+ }
14078
+ function nextLineBreak(buffer, final) {
14079
+ const index = buffer.search(/[\r\n]/);
14080
+ if (index === -1) return null;
14081
+ if (buffer[index] === "\n") return { index, length: 1 };
14082
+ if (index === buffer.length - 1 && !final) return null;
14083
+ return { index, length: buffer[index + 1] === "\n" ? 2 : 1 };
14084
+ }
14085
+ function drainLines(state, final, events) {
14086
+ for (let found = nextLineBreak(state.buffer, final); found; found = nextLineBreak(state.buffer, final)) {
14087
+ const line = state.buffer.slice(0, found.index);
14088
+ state.buffer = state.buffer.slice(found.index + found.length);
14089
+ if (line === "") {
14090
+ if (state.data.length > 0) events.push(state.data.join("\n"));
14091
+ state.data = [];
14092
+ continue;
14093
+ }
14094
+ if (line.startsWith(":")) continue;
14095
+ const colon = line.indexOf(":");
14096
+ const field = colon === -1 ? line : line.slice(0, colon);
14097
+ if (field !== "data") continue;
14098
+ const value = colon === -1 ? "" : line.slice(colon + 1);
14099
+ state.data.push(value.startsWith(" ") ? value.slice(1) : value);
14100
+ }
14101
+ }
14102
+ async function* readLlmSseData(body, signal) {
14103
+ const reader = body.getReader();
14104
+ const decoder = new TextDecoder();
14105
+ const state = { buffer: "", data: [] };
14106
+ const cancel = () => {
14107
+ void reader.cancel().catch(() => void 0);
14108
+ };
14109
+ let complete = false;
14110
+ signal?.addEventListener("abort", cancel, { once: true });
14111
+ try {
14112
+ for (; ; ) {
14113
+ if (signal?.aborted) return;
14114
+ const { done, value } = await reader.read();
14115
+ const events = [];
14116
+ if (done) {
14117
+ complete = true;
14118
+ state.buffer += decoder.decode();
14119
+ drainLines(state, true, events);
14120
+ if (state.buffer !== "") {
14121
+ state.buffer += "\n";
14122
+ drainLines(state, true, events);
14123
+ }
14124
+ if (state.data.length > 0) events.push(state.data.join("\n"));
14125
+ yield* events;
14126
+ return;
14127
+ }
14128
+ state.buffer += decoder.decode(value, { stream: true });
14129
+ drainLines(state, false, events);
14130
+ yield* events;
14131
+ }
14132
+ } finally {
14133
+ signal?.removeEventListener("abort", cancel);
14134
+ if (!complete) cancel();
14135
+ reader.releaseLock();
14136
+ }
14137
+ }
13892
14138
  var PRESET_ROWS = [
13893
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"] },
13894
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"] },
@@ -13911,10 +14157,44 @@ var PRESET_ROWS = [
13911
14157
  var LLM_PROVIDER_PRESETS = Object.freeze(
13912
14158
  PRESET_ROWS.map((preset) => Object.freeze({ ...preset, exampleModels: Object.freeze([...preset.exampleModels]) }))
13913
14159
  );
14160
+ async function readJson(response) {
14161
+ try {
14162
+ return await response.json();
14163
+ } catch {
14164
+ throw new LlmServiceError("provider-error", "The provider response was not valid JSON.");
14165
+ }
14166
+ }
14167
+ function parseStreamEvent(data) {
14168
+ try {
14169
+ return JSON.parse(data);
14170
+ } catch {
14171
+ throw new LlmServiceError("provider-error", "The provider stream carried an invalid event.");
14172
+ }
14173
+ }
14174
+ async function readStream(protocol, body, signal, onDelta) {
14175
+ const accumulator = createLlmStreamAccumulator(protocol);
14176
+ try {
14177
+ for await (const data of readLlmSseData(body, signal)) {
14178
+ if (data === "[DONE]") continue;
14179
+ const appended = accumulator.push(parseStreamEvent(data));
14180
+ if (appended && !signal.aborted) onDelta?.(appended);
14181
+ }
14182
+ } catch (error) {
14183
+ if (signal.aborted) throw abortReason(signal);
14184
+ if (error instanceof LlmServiceError) throw error;
14185
+ throw new LlmServiceError("provider-error", "The provider stream was interrupted.");
14186
+ }
14187
+ if (signal.aborted) throw abortReason(signal);
14188
+ return accumulator.finish();
14189
+ }
14190
+ function abortReason(signal) {
14191
+ return signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
14192
+ }
13914
14193
  function createHttpLlmProvider(options = {}) {
13915
14194
  const fetchImpl = options.fetch ?? ((url, init) => globalThis.fetch(url, init));
13916
- return async (endpoint, request, signal) => {
13917
- const http = buildLlmProviderRequest(endpoint, request);
14195
+ const stream = options.stream === true;
14196
+ return async (endpoint, request, signal, onDelta) => {
14197
+ const http = buildLlmProviderRequest(endpoint, request, { stream });
13918
14198
  let response;
13919
14199
  try {
13920
14200
  response = await fetchImpl(http.url, { method: http.method, headers: { ...http.headers }, body: http.body, signal });
@@ -13923,13 +14203,10 @@ function createHttpLlmProvider(options = {}) {
13923
14203
  throw new LlmServiceError("provider-error", "The provider could not be reached.");
13924
14204
  }
13925
14205
  if (!response.ok) throw new LlmServiceError("provider-error", `The provider responded with HTTP ${response.status}.`);
13926
- let json;
13927
- try {
13928
- json = await response.json();
13929
- } catch {
13930
- throw new LlmServiceError("provider-error", "The provider response was not valid JSON.");
13931
- }
13932
- return parseLlmProviderResponse(endpoint.protocol, json);
14206
+ const buffered = !stream || response.headers?.get("content-type")?.toLowerCase().includes("application/json") === true;
14207
+ if (buffered) return parseLlmProviderResponse(endpoint.protocol, await readJson(response));
14208
+ if (!response.body) throw new LlmServiceError("provider-error", "The provider response had no readable stream.");
14209
+ return readStream(endpoint.protocol, response.body, signal, onDelta);
13933
14210
  };
13934
14211
  }
13935
14212
 
@@ -14649,8 +14926,8 @@ function countCharacters(request) {
14649
14926
  }
14650
14927
  function createPajaLlmHost(options) {
14651
14928
  const { store: store2, vault, confirm, getIdentity } = options;
14652
- const provider = options.provider ?? createHttpLlmProvider();
14653
- async function ensureCredential(record3) {
14929
+ const provider = options.provider ?? createHttpLlmProvider({ stream: true });
14930
+ async function ensureCredential(record3, signal) {
14654
14931
  if (record3.credentialStorage === "none") return void 0;
14655
14932
  const existing = vault.getCredential(record3.id);
14656
14933
  if (existing !== void 0) return existing;
@@ -14659,7 +14936,7 @@ function createPajaLlmHost(options) {
14659
14936
  throw new LlmServiceError("unsupported", "This connection's API key was kept for one session only. Enter it again in Language models.");
14660
14937
  }
14661
14938
  if (!vault.isUnlocked()) {
14662
- const unlocked = await options.requestUnlock();
14939
+ const unlocked = await options.requestUnlock(signal);
14663
14940
  if (!unlocked) throw new LlmServiceError("user-cancelled", "The credential vault stayed locked.");
14664
14941
  }
14665
14942
  const credential = vault.getCredential(record3.id);
@@ -14669,16 +14946,17 @@ function createPajaLlmHost(options) {
14669
14946
  }
14670
14947
  return credential;
14671
14948
  }
14672
- async function select2(context, requirements2) {
14949
+ async function select2(context, requirements2, prompt) {
14950
+ const signal = prompt?.signal;
14673
14951
  const napplet = getIdentity(context.windowId);
14674
14952
  const candidates = store2.list().filter((record3) => meets(record3, requirements2));
14675
14953
  if (candidates.length === 0) {
14676
- const configure = await confirm({ action: "llm-configure", windowId: context.windowId, napplet, requirements: describeRequirements(requirements2), configured: store2.list().length });
14954
+ const configure = await confirm({ action: "llm-configure", windowId: context.windowId, napplet, requirements: describeRequirements(requirements2), configured: store2.list().length, ...signal ? { signal } : {} });
14677
14955
  if (!configure) return null;
14678
14956
  options.openPanel();
14679
14957
  throw new LlmServiceError("unsupported", "No compatible language model connection is configured yet. Add one in Paja's Language models panel, then select again.");
14680
14958
  }
14681
- const chosen = await options.chooseConnection(candidates, { windowId: context.windowId, napplet, requirements: requirements2 });
14959
+ const chosen = await options.chooseConnection(candidates, { windowId: context.windowId, napplet, requirements: requirements2, ...signal ? { signal } : {} });
14682
14960
  if (!chosen) return null;
14683
14961
  const current = store2.get(chosen.id);
14684
14962
  return current && meets(current, requirements2) ? toConnection(current) : null;
@@ -14690,11 +14968,14 @@ function createPajaLlmHost(options) {
14690
14968
  const record3 = store2.get(connectionId);
14691
14969
  return record3 ? toConnection(record3) : null;
14692
14970
  },
14693
- async authorize(context, connection, request) {
14971
+ async authorize(context, connection, request, prompt) {
14972
+ const signal = prompt?.signal;
14694
14973
  const record3 = store2.get(connection.id);
14695
14974
  if (!record3) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
14696
- await ensureCredential(record3);
14975
+ await ensureCredential(record3, signal);
14976
+ if (signal?.aborted) return false;
14697
14977
  return confirm({
14978
+ ...signal ? { signal } : {},
14698
14979
  action: "llm",
14699
14980
  windowId: context.windowId,
14700
14981
  napplet: getIdentity(context.windowId),
@@ -14718,7 +14999,7 @@ function createPajaLlmHost(options) {
14718
14999
  model: record3.model,
14719
15000
  ...credential === void 0 ? {} : { credential },
14720
15001
  ...record3.credentialHeader ? { credentialHeader: record3.credentialHeader } : {}
14721
- }, request, hooks.signal);
15002
+ }, request, hooks.signal, (text2) => hooks.onDelta(text2));
14722
15003
  },
14723
15004
  subscribe(listener) {
14724
15005
  const stopStore = store2.subscribe(listener);
@@ -14895,6 +15176,11 @@ function defaultId() {
14895
15176
  const random = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID().slice(0, 8) : Math.random().toString(16).slice(2, 10);
14896
15177
  return `conn-${random}`;
14897
15178
  }
15179
+ function withdrawOnAbort(signal, withdraw) {
15180
+ if (!signal) return () => void 0;
15181
+ signal.addEventListener("abort", withdraw, { once: true });
15182
+ return () => signal.removeEventListener("abort", withdraw);
15183
+ }
14898
15184
  function createPasswordDialog() {
14899
15185
  const dialog = byId("paja-llm-vault-dialog", HTMLDialogElement);
14900
15186
  const title = byId("paja-llm-vault-title", HTMLElement);
@@ -14932,14 +15218,22 @@ function createPasswordDialog() {
14932
15218
  cancel.addEventListener("click", onCancel);
14933
15219
  dialog.addEventListener("cancel", onCancel);
14934
15220
  return {
14935
- prompt(mode) {
15221
+ prompt(mode, signal) {
14936
15222
  if (settle7) finish(null);
15223
+ if (signal?.aborted) return Promise.resolve(null);
14937
15224
  dialog.dataset.mode = mode;
14938
15225
  title.textContent = mode === "create" ? "Create a credential vault password" : "Unlock the credential vault";
14939
15226
  copy.textContent = mode === "create" ? `Paja encrypts remembered API keys with this password (PBKDF2-SHA-256 and AES-GCM). It is never stored or sent anywhere; use at least ${String(12)} characters.` : "Enter the vault password to use a remembered API key for this session.";
14940
15227
  confirm.textContent = mode === "create" ? "Create vault" : "Unlock";
14941
15228
  return new Promise((resolve) => {
14942
- settle7 = resolve;
15229
+ const mine = (value) => {
15230
+ detach();
15231
+ resolve(value);
15232
+ };
15233
+ const detach = withdrawOnAbort(signal, () => {
15234
+ if (settle7 === mine) finish(null);
15235
+ });
15236
+ settle7 = mine;
14943
15237
  dialog.showModal();
14944
15238
  input.focus();
14945
15239
  });
@@ -14977,6 +15271,7 @@ function createChooserDialog() {
14977
15271
  return {
14978
15272
  choose(candidates, context) {
14979
15273
  if (settle7) finish(null);
15274
+ if (context.signal?.aborted) return Promise.resolve(null);
14980
15275
  const wanted = [context.requirements.model ? `model ${context.requirements.model}` : null, context.requirements.images ? "image input" : null, context.requirements.json ? "JSON output" : null].filter(Boolean).join(", ");
14981
15276
  copy.textContent = `${context.napplet.dTag} (${context.windowId}) asks to use a language model${wanted ? ` with ${wanted}` : ""}. Selecting does not send anything yet; each generation asks for consent.`;
14982
15277
  select2.replaceChildren(...candidates.map((record3) => {
@@ -14987,7 +15282,14 @@ function createChooserDialog() {
14987
15282
  }));
14988
15283
  select2.selectedIndex = candidates.length > 0 ? 0 : -1;
14989
15284
  return new Promise((resolve) => {
14990
- settle7 = (value) => resolve(candidates.find((record3) => record3.id === value) ?? null);
15285
+ const mine = (value) => {
15286
+ detach();
15287
+ resolve(candidates.find((record3) => record3.id === value) ?? null);
15288
+ };
15289
+ const detach = withdrawOnAbort(context.signal, () => {
15290
+ if (settle7 === mine) finish(null);
15291
+ });
15292
+ settle7 = mine;
14991
15293
  dialog.showModal();
14992
15294
  select2.focus();
14993
15295
  });
@@ -15039,10 +15341,10 @@ function installPajaLlmPanel(options) {
15039
15341
  }
15040
15342
  return requestUnlock();
15041
15343
  }
15042
- async function requestUnlock() {
15344
+ async function requestUnlock(signal) {
15043
15345
  for (; ; ) {
15044
15346
  if (vault.isUnlocked()) return true;
15045
- const entered = await password.prompt("unlock");
15347
+ const entered = await password.prompt("unlock", signal);
15046
15348
  if (entered === null) return false;
15047
15349
  if (await vault.unlock(entered)) return true;
15048
15350
  setStatus2("Wrong vault password. Try again or clear the vault to start over.", true);
@@ -21325,6 +21627,10 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
21325
21627
  if (relayUrls2.length === 0) return;
21326
21628
  relayRequestObserver?.({ ...context, relayUrls: [...relayUrls2] });
21327
21629
  };
21630
+ const attributeAuthors = (context, filters) => {
21631
+ const authors = readAuthors(context.authors ?? filters.flatMap((filter) => filter.authors ?? []));
21632
+ return authors.length === 0 && context.authors === void 0 ? context : { ...context, authors };
21633
+ };
21328
21634
  const observeRelayEvent = (context, relayUrls2, event, source) => {
21329
21635
  relayEventObserver?.({
21330
21636
  ...context,
@@ -21338,13 +21644,14 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
21338
21644
  const query = async (relayUrls2, filters, maxWaitMs, context = { reason: "host" }) => {
21339
21645
  const cached = collectMemoryEvents(cachedEvents(), filters);
21340
21646
  if (getSimulation().relay.mode !== "live" || relayUrls2.length === 0) return cached;
21341
- observeRelayRequest(context, relayUrls2);
21647
+ const readContext = attributeAuthors(context, filters);
21648
+ observeRelayRequest(readContext, relayUrls2);
21342
21649
  const liveEvents = await queryPajaLive(
21343
21650
  livePool,
21344
21651
  relayUrls2,
21345
21652
  filters,
21346
21653
  maxWaitMs ?? PAJA_LIVE_QUERY_WAIT_MS,
21347
- (event, source) => observeRelayEvent(context, relayUrls2, event, source)
21654
+ (event, source) => observeRelayEvent(readContext, relayUrls2, event, source)
21348
21655
  );
21349
21656
  const out = /* @__PURE__ */ new Map();
21350
21657
  for (const event of [...cached, ...liveEvents]) out.set(event.id, event);
@@ -21353,13 +21660,14 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
21353
21660
  const queryContactListCandidates = async (relayUrls2, filters, maxWaitMs, signal) => {
21354
21661
  const cached = collectMemoryEvents(cachedEvents(), filters);
21355
21662
  if (signal?.aborted || getSimulation().relay.mode !== "live" || relayUrls2.length === 0) return cached;
21356
- observeRelayRequest({ reason: "host" }, relayUrls2);
21663
+ const readContext = attributeAuthors({ reason: "host" }, filters);
21664
+ observeRelayRequest(readContext, relayUrls2);
21357
21665
  const liveEvents = await queryPajaLive(
21358
21666
  livePool,
21359
21667
  relayUrls2,
21360
21668
  filters,
21361
21669
  maxWaitMs ?? PAJA_LIVE_QUERY_WAIT_MS,
21362
- (event, source) => observeRelayEvent({ reason: "host" }, relayUrls2, event, source),
21670
+ (event, source) => observeRelayEvent(readContext, relayUrls2, event, source),
21363
21671
  true,
21364
21672
  signal
21365
21673
  );
@@ -21401,13 +21709,14 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
21401
21709
  };
21402
21710
  subscribers.add(subscriber);
21403
21711
  for (const event of collectMemoryEvents(cachedEvents(), filters)) next(event);
21404
- if (getSimulation().relay.mode === "live") observeRelayRequest(context, relayUrls2);
21712
+ const readContext = attributeAuthors(context, filters);
21713
+ if (getSimulation().relay.mode === "live") observeRelayRequest(readContext, relayUrls2);
21405
21714
  const liveSub = getSimulation().relay.mode === "live" ? subscribePajaLive(
21406
21715
  livePool,
21407
21716
  relayUrls2,
21408
21717
  filters,
21409
21718
  subscriber.next,
21410
- (event, source) => observeRelayEvent(context, relayUrls2, event, source),
21719
+ (event, source) => observeRelayEvent(readContext, relayUrls2, event, source),
21411
21720
  PAJA_LIVE_QUERY_WAIT_MS
21412
21721
  ) : null;
21413
21722
  queueMicrotask(() => {
@@ -21450,7 +21759,7 @@ function createPajaRelayBackend(getSimulation, confirmRequest, livePool = new Si
21450
21759
  },
21451
21760
  async countWithRelay(relayUrls2, filters) {
21452
21761
  if (getSimulation().relay.mode !== "live") throw new Error("count unavailable");
21453
- observeRelayRequest({ reason: "host" }, relayUrls2);
21762
+ observeRelayRequest(attributeAuthors({ reason: "host" }, filters), relayUrls2);
21454
21763
  return countLive(livePool, relayUrls2, normalizedFilters(filters));
21455
21764
  },
21456
21765
  observedRelayUrls(eventId) {
@@ -21507,6 +21816,13 @@ function dedupeRelayUrls(urls) {
21507
21816
  }
21508
21817
  return [...out];
21509
21818
  }
21819
+ function readAuthors(candidates) {
21820
+ const authors = /* @__PURE__ */ new Set();
21821
+ for (const author of candidates) {
21822
+ if (typeof author === "string" && /^[0-9a-f]{64}$/i.test(author)) authors.add(author.toLowerCase());
21823
+ }
21824
+ return [...authors];
21825
+ }
21510
21826
  async function getSignerRelayUrls(signerProvider, direction) {
21511
21827
  const signer = signerProvider?.getSigner();
21512
21828
  if (!signer?.getRelays) return [];
@@ -21581,8 +21897,8 @@ function createPajaRelayListLoader(backend, getSimulation, signerProvider, getHo
21581
21897
  }
21582
21898
  function createPajaOutboxRelayPool(backend) {
21583
21899
  return {
21584
- subscribe(filters, relayUrls2, callback, origin) {
21585
- return backend.subscription(relayUrls2, filters, { reason: "outbox", origin }).subscribe((item) => callback(item));
21900
+ subscribe(filters, relayUrls2, callback, origin, authors) {
21901
+ return backend.subscription(relayUrls2, filters, { reason: "outbox", origin, authors }).subscribe((item) => callback(item));
21586
21902
  },
21587
21903
  publish(event, relayUrls2) {
21588
21904
  return backend.publishToRelays(relayUrls2, event);
@@ -23789,6 +24105,13 @@ function createDevTheme(mode, values) {
23789
24105
  }
23790
24106
  };
23791
24107
  }
24108
+ var HEX_PUBKEY2 = /^[0-9a-f]{64}$/i;
24109
+ function getConnectedAccountPubkey(signerProvider) {
24110
+ const pubkey2 = signerProvider?.getPubkey();
24111
+ if (typeof pubkey2 === "string" && HEX_PUBKEY2.test(pubkey2)) return pubkey2.toLowerCase();
24112
+ if (signerProvider?.getMethod() === "dev") return PAJA_DEV_SIGNER_PUBKEY;
24113
+ return null;
24114
+ }
23792
24115
  function createDevServices(backend, getSimulation, relayConfig, onThemeService, onThemeBroadcast, confirmRequest, getConfiguredBlossomServers, uploadRuntime, signerProvider, getIdentity, userActivation, notifyOptions, configOptions, getSignerSource) {
23793
24116
  const scopeFor = (windowId, isCurrent) => createPajaWindowScope({
23794
24117
  backend,
@@ -23825,7 +24148,10 @@ function createDevServices(backend, getSimulation, relayConfig, onThemeService,
23825
24148
  baseRouter: baseOutboxRouter,
23826
24149
  loadContactList: createPajaContactListLoader(backend, getSimulation, signerProvider, getReadRelays),
23827
24150
  verifyEvent: (event) => verifyEvent(event),
23828
- getActivePubkey: () => getRuntimePubkey(getSimulation, signerProvider),
24151
+ // Background warming is speculative relay traffic, so it only runs for a
24152
+ // signer account. `getFollows` still answers on demand for any requested
24153
+ // pubkey, including the fixed simulation identity.
24154
+ getActivePubkey: () => getConnectedAccountPubkey(signerProvider),
23829
24155
  subscribeSignerChange: signerProvider?.subscribe?.bind(signerProvider)
23830
24156
  });
23831
24157
  const commonBackend = createPajaCommonBackend({
@@ -24230,7 +24556,7 @@ function boxKindFor(reason, origin) {
24230
24556
  return reason === "hint" ? "scoped" : "host";
24231
24557
  }
24232
24558
  function emptyBox() {
24233
- return { count: 0, reads: /* @__PURE__ */ new Map(), relays: /* @__PURE__ */ new Map() };
24559
+ return { count: 0, reads: /* @__PURE__ */ new Map(), authors: /* @__PURE__ */ new Map(), relays: /* @__PURE__ */ new Map() };
24234
24560
  }
24235
24561
  function distinctRelayUrls(urls) {
24236
24562
  const unique = /* @__PURE__ */ new Map();
@@ -24241,6 +24567,13 @@ function distinctRelayUrls(urls) {
24241
24567
  }
24242
24568
  return [...unique.values()];
24243
24569
  }
24570
+ function distinctAuthors(authors) {
24571
+ const unique = /* @__PURE__ */ new Set();
24572
+ for (const author of authors ?? []) {
24573
+ if (typeof author === "string" && author.length > 0) unique.add(author.toLowerCase());
24574
+ }
24575
+ return [...unique];
24576
+ }
24244
24577
  function createPajaRelayEventCounter(onChange) {
24245
24578
  const boxes = /* @__PURE__ */ new Map();
24246
24579
  const eventIds = /* @__PURE__ */ new Set();
@@ -24253,6 +24586,12 @@ function createPajaRelayEventCounter(onChange) {
24253
24586
  }
24254
24587
  return box;
24255
24588
  };
24589
+ const attributeAuthors = (kind, authors) => {
24590
+ const box = boxFor(kind);
24591
+ for (const author of distinctAuthors(authors)) {
24592
+ box.authors.set(author, (box.authors.get(author) ?? 0) + 1);
24593
+ }
24594
+ };
24256
24595
  const relayFor = (kind, relayUrl2) => {
24257
24596
  const box = boxFor(kind);
24258
24597
  const key = normalizeURL2(relayUrl2);
@@ -24300,13 +24639,14 @@ function createPajaRelayEventCounter(onChange) {
24300
24639
  reason: spec.reason,
24301
24640
  ...spec.origin ? { origin: spec.origin } : {},
24302
24641
  count: box?.count ?? 0,
24642
+ authors: [...box?.authors.entries() ?? []].sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey)).map(([pubkey2, count]) => ({ pubkey: pubkey2, count })),
24303
24643
  relays,
24304
24644
  ...relays.length === 0 && spec.emptyNote ? { emptyNote: spec.emptyNote } : {}
24305
24645
  });
24306
24646
  }
24307
24647
  return out;
24308
24648
  },
24309
- recordRead(reason, relayUrls2, origin) {
24649
+ recordRead(reason, relayUrls2, origin, authors) {
24310
24650
  const kind = boxKindFor(reason, origin);
24311
24651
  const box = boxFor(kind);
24312
24652
  let changed = false;
@@ -24316,7 +24656,10 @@ function createPajaRelayEventCounter(onChange) {
24316
24656
  relayFor(kind, relayUrl2);
24317
24657
  changed = true;
24318
24658
  }
24319
- if (changed) onChange?.();
24659
+ if (changed) {
24660
+ attributeAuthors(kind, authors);
24661
+ onChange?.();
24662
+ }
24320
24663
  },
24321
24664
  recordEvent(reason, event, sightedOn, origin) {
24322
24665
  if (typeof event !== "object" || event === null) return;
@@ -24353,6 +24696,23 @@ function installPajaEventCounterReset(counter) {
24353
24696
  button2?.addEventListener("click", onClick);
24354
24697
  return () => button2?.removeEventListener("click", onClick);
24355
24698
  }
24699
+ function renderBoxAuthors(authors) {
24700
+ const row = document.createElement("div");
24701
+ row.className = "event-box-authors";
24702
+ row.replaceChildren(...authors.map(({ pubkey: pubkey2, count }) => {
24703
+ const chip = document.createElement("span");
24704
+ chip.className = "event-author";
24705
+ chip.dataset.authorPubkey = pubkey2;
24706
+ chip.dataset.authorReads = String(count);
24707
+ chip.textContent = count > 1 ? `${shortPubkey(pubkey2)} \xB7 ${count}` : shortPubkey(pubkey2);
24708
+ chip.title = count > 1 ? `${pubkey2} \xB7 routed ${count} reads into this box` : `${pubkey2} \xB7 routed 1 read into this box`;
24709
+ return chip;
24710
+ }));
24711
+ return row;
24712
+ }
24713
+ function shortPubkey(pubkey2) {
24714
+ return pubkey2.length > 12 ? `${pubkey2.slice(0, 8)}\u2026${pubkey2.slice(-4)}` : pubkey2;
24715
+ }
24356
24716
  function renderPajaEventKindCounts(counter, inventory) {
24357
24717
  const container = document.getElementById("event-kind-counts");
24358
24718
  const total = document.getElementById("event-kind-total");
@@ -24385,6 +24745,7 @@ function renderPajaEventKindCounts(counter, inventory) {
24385
24745
  boxCount.textContent = box.relays.length === 0 ? box.emptyNote ?? "0" : String(box.count);
24386
24746
  head.append(name, boxCount);
24387
24747
  section.append(head);
24748
+ if (box.authors.length > 0) section.append(renderBoxAuthors(box.authors));
24388
24749
  for (const relay of box.relays) {
24389
24750
  const row = document.createElement("div");
24390
24751
  row.className = "event-relay";
@@ -25062,11 +25423,11 @@ function createNipEncryptionMethods(state, prefix) {
25062
25423
  decrypt: async (pubkey2, ciphertext) => sendRequestWithId(state, crypto.randomUUID(), `${prefix}_decrypt`, [pubkey2, ciphertext])
25063
25424
  };
25064
25425
  }
25065
- var HEX_PUBKEY2 = /^[0-9a-f]{64}$/i;
25426
+ var HEX_PUBKEY3 = /^[0-9a-f]{64}$/i;
25066
25427
  function readPubkey(value) {
25067
25428
  if (typeof value === "string") {
25068
25429
  const normalized = value.trim().toLowerCase();
25069
- return HEX_PUBKEY2.test(normalized) ? normalized : null;
25430
+ return HEX_PUBKEY3.test(normalized) ? normalized : null;
25070
25431
  }
25071
25432
  if (value && typeof value === "object" && "pubkey" in value) {
25072
25433
  return readPubkey(value.pubkey);
@@ -25605,12 +25966,22 @@ function createPajaConfirmationController(getState, options = {}) {
25605
25966
  };
25606
25967
  return {
25607
25968
  confirm(request) {
25608
- if (!ready || disposed) {
25969
+ if (!ready || disposed || request.signal?.aborted) {
25609
25970
  recordPajaConfirmation(getState(), request, false);
25610
25971
  return false;
25611
25972
  }
25973
+ const { signal } = request;
25612
25974
  return new Promise((resolve) => {
25613
- queue.push({ request, approve: () => resolve(true), deny: () => resolve(false) });
25975
+ const withdraw = () => cancelMatching((candidate) => candidate === request);
25976
+ const detach = () => signal?.removeEventListener("abort", withdraw);
25977
+ signal?.addEventListener("abort", withdraw, { once: true });
25978
+ queue.push({ request, approve: () => {
25979
+ detach();
25980
+ resolve(true);
25981
+ }, deny: () => {
25982
+ detach();
25983
+ resolve(false);
25984
+ } });
25614
25985
  pump();
25615
25986
  });
25616
25987
  },
@@ -25675,6 +26046,7 @@ function signerConsentCandidate(request) {
25675
26046
  return { context: request.signerContext, kind };
25676
26047
  }
25677
26048
  function isRequestCurrent(request) {
26049
+ if (request.signal?.aborted) return false;
25678
26050
  if (request.isCurrent && !request.isCurrent()) return false;
25679
26051
  return !("signerContext" in request) || !request.signerContext?.isCurrent || request.signerContext.isCurrent();
25680
26052
  }
@@ -28981,7 +29353,7 @@ async function installPajaHost() {
28981
29353
  relayEventCounts.recordEvent(sighting.reason, sighting.event, sighting.sightedOn, sighting.origin);
28982
29354
  });
28983
29355
  relayBackend?.setRelayRequestObserver((request) => {
28984
- relayEventCounts.recordRead(request.reason, request.relayUrls, request.origin);
29356
+ relayEventCounts.recordRead(request.reason, request.relayUrls, request.origin, request.authors);
28985
29357
  });
28986
29358
  await adapter.ready;
28987
29359
  const bridge = createShellBridge(adapter);