@kehto/paja 0.31.0 → 0.32.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.
@@ -3736,6 +3736,25 @@ function setGlobalRate(config, napplet, limit) {
3736
3736
  }
3737
3737
  };
3738
3738
  }
3739
+ function setUnfocusedMultiplier(config, multiplier) {
3740
+ if (!Number.isFinite(multiplier) || multiplier <= 0) {
3741
+ throw new RangeError("unfocusedMultiplier must be a finite number above zero");
3742
+ }
3743
+ return { ...config, unfocusedMultiplier: multiplier };
3744
+ }
3745
+ function setBurstGuard(config, guard) {
3746
+ const { windowMs, maxOps, action } = guard;
3747
+ if (!Number.isFinite(windowMs) || windowMs < 0) {
3748
+ throw new RangeError("burstGuard.windowMs must be a finite number of zero or more");
3749
+ }
3750
+ if (!Number.isSafeInteger(maxOps) || maxOps < 0) {
3751
+ throw new RangeError("burstGuard.maxOps must be a non-negative safe integer");
3752
+ }
3753
+ if (!isValidAction(action)) {
3754
+ throw new RangeError("burstGuard.action must be 'flag', 'block' or 'ignore'");
3755
+ }
3756
+ return { ...config, burstGuard: { windowMs, maxOps, action } };
3757
+ }
3739
3758
  function addMatcher(config, matcher) {
3740
3759
  return { ...config, matchers: [...config.matchers, matcher] };
3741
3760
  }
@@ -3831,7 +3850,176 @@ function deserialize2(json) {
3831
3850
  return defaultConfig();
3832
3851
  }
3833
3852
 
3834
- // ../../node_modules/.pnpm/@napplet+core@0.32.0/node_modules/@napplet/core/dist/index.js
3853
+ // ../../node_modules/.pnpm/@napplet+core@0.38.0/node_modules/@napplet/core/dist/index.js
3854
+ var NAP_IMPLEMENTATIONS = {
3855
+ shell: {
3856
+ proposal: { url: "https://github.com/napplet/naps/pull/101", status: "merged", checkedAt: "2026-10-31" },
3857
+ maturity: "supported",
3858
+ rationale: "Optional readiness and environment binding has focused shim and reference-runtime coverage.",
3859
+ evidence: ["packages/nap/src/shell/shim.test.ts"]
3860
+ },
3861
+ relay: {
3862
+ proposal: { url: "https://github.com/napplet/naps/pull/2", status: "in-review", checkedAt: "2026-10-31" },
3863
+ maturity: "supported",
3864
+ rationale: "Relay reads, publishing, and subscription lifecycle have maintained shim and integration tests; upstream naming remains under review.",
3865
+ evidence: ["packages/nap/src/relay/shim.test.ts"],
3866
+ implementationReference: { revision: "cb8f8eabb2d09439e9d174cb9eb6ef2caad0eca1", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "RelayEventResult sidecar migration; subsequent changes are not covered." }
3867
+ },
3868
+ identity: {
3869
+ proposal: { url: "https://github.com/napplet/naps/pull/102", status: "merged", checkedAt: "2026-10-31" },
3870
+ maturity: "supported",
3871
+ rationale: "Read-only identity queries and updates have focused binding and reference-runtime coverage.",
3872
+ evidence: ["packages/nap/src/identity/shim.test.ts"]
3873
+ },
3874
+ storage: {
3875
+ proposal: { url: "https://github.com/napplet/naps/pull/3", status: "in-review", checkedAt: "2026-10-31" },
3876
+ maturity: "supported",
3877
+ rationale: "Key-value binding has focused request/result tests and tutorial usage; host storage isolation remains the host responsibility.",
3878
+ evidence: ["packages/nap/src/storage/shim.test.ts"]
3879
+ },
3880
+ inc: {
3881
+ proposal: { url: "https://github.com/napplet/naps/pull/104", status: "merged", checkedAt: "2026-10-31" },
3882
+ maturity: "supported",
3883
+ rationale: "Topic and channel bindings have compatibility tests and authenticated-endpoint reference-runtime coverage.",
3884
+ evidence: ["packages/nap/src/inc/shim.ts", "packages/conformance-cli/src/browser.test.ts"]
3885
+ },
3886
+ theme: {
3887
+ proposal: { url: "https://github.com/napplet/naps/pull/103", status: "merged", checkedAt: "2026-10-31" },
3888
+ maturity: "supported",
3889
+ rationale: "Theme queries and pushed updates have focused binding and opaque-iframe integration coverage.",
3890
+ evidence: ["packages/nap/src/theme/shim.test.ts", "packages/conformance-cli/src/browser.test.ts"]
3891
+ },
3892
+ keys: {
3893
+ proposal: { url: "https://github.com/napplet/naps/pull/9", status: "in-review", checkedAt: "2026-10-31" },
3894
+ maturity: "experimental",
3895
+ rationale: "Keyboard binding ships, but dedicated domain regression coverage is limited; retain explicit evaluation opt-in.",
3896
+ evidence: ["packages/nap/src/keys/shim.ts"]
3897
+ },
3898
+ media: {
3899
+ proposal: { url: "https://github.com/napplet/naps/pull/10", status: "in-review", checkedAt: "2026-10-31" },
3900
+ maturity: "supported",
3901
+ rationale: "Session creation and playback binding have focused regression coverage; proposed torrent playback amendments are not implied.",
3902
+ evidence: ["packages/nap/src/media/shim.test.ts"]
3903
+ },
3904
+ notify: {
3905
+ proposal: { url: "https://github.com/napplet/naps/pull/11", status: "in-review", checkedAt: "2026-10-31" },
3906
+ maturity: "experimental",
3907
+ rationale: "Notification binding ships with limited dedicated domain regression evidence; broader host integration confidence is unverified.",
3908
+ evidence: ["packages/nap/src/notify/shim.ts"]
3909
+ },
3910
+ config: {
3911
+ proposal: { url: "https://github.com/napplet/naps/pull/14", status: "draft", checkedAt: "2026-10-31" },
3912
+ maturity: "exploratory",
3913
+ rationale: "Configuration binding is tested, but the upstream draft is marked MAY DEFER; use for design exploration.",
3914
+ evidence: ["packages/nap/src/config/shim.test.ts"]
3915
+ },
3916
+ resource: {
3917
+ proposal: { url: "https://github.com/napplet/naps/pull/80", status: "in-review", checkedAt: "2026-10-31" },
3918
+ maturity: "supported",
3919
+ rationale: "Resource fetching has focused shim and type tests; the reverted merge and reopened proposal do not change that implementation assessment.",
3920
+ evidence: ["packages/nap/src/resource/shim.test.ts"],
3921
+ implementationReference: { revision: "8e75eadf317d7fe809415e4755cd48f63cfb63f3", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "Shared ResourceSidecarEntry types during the sidecar migration; subsequent resource changes are not covered." }
3922
+ },
3923
+ cvm: {
3924
+ proposal: { url: "https://github.com/napplet/naps/pull/31", status: "in-review", checkedAt: "2026-10-31" },
3925
+ maturity: "experimental",
3926
+ rationale: "Session and registry bindings are tested; upstream explicitly marks the contract NEEDS WORK.",
3927
+ evidence: ["packages/nap/src/cvm/shim.test.ts"]
3928
+ },
3929
+ outbox: {
3930
+ proposal: { url: "https://github.com/napplet/naps/pull/32", status: "in-review", checkedAt: "2026-10-31" },
3931
+ maturity: "supported",
3932
+ rationale: "Routing and subscription bindings have focused tests and an integration regression for structured-clone boundaries.",
3933
+ evidence: ["packages/nap/src/outbox/shim.test.ts", "packages/nap/src/boundary-integration.test.ts"],
3934
+ implementationReference: { revision: "57db924bac022cc14c67d9fca1a4d92cf1bd4725", evidence: ".planning/quick/260703-ghg-align-napplet-packages-with-nap-relayeve/260703-ghg-SUMMARY.md", scope: "RelayEventResult and stream lifecycle migration; subsequent changes are not covered." }
3935
+ },
3936
+ upload: {
3937
+ proposal: { url: "https://github.com/napplet/naps/pull/33", status: "in-review", checkedAt: "2026-10-31" },
3938
+ maturity: "supported",
3939
+ rationale: "Upload binding has focused tests for request/result behavior; host rail support remains runtime-specific.",
3940
+ evidence: ["packages/nap/src/upload/shim.test.ts"]
3941
+ },
3942
+ intent: {
3943
+ proposal: { url: "https://github.com/napplet/naps/pull/91", status: "merged", checkedAt: "2026-10-31" },
3944
+ maturity: "supported",
3945
+ rationale: "Convention normalization and dispatch have focused binding and reference-runtime integration tests.",
3946
+ evidence: ["packages/nap/src/intent/shim.test.ts"]
3947
+ },
3948
+ ble: {
3949
+ proposal: { url: "https://github.com/napplet/naps/pull/62", status: "in-review", checkedAt: "2026-10-31" },
3950
+ maturity: "experimental",
3951
+ rationale: "GATT binding has unit coverage; real-device behavior across host backends is not established by these tests.",
3952
+ evidence: ["packages/nap/src/ble/shim.test.ts"]
3953
+ },
3954
+ webrtc: {
3955
+ proposal: { url: "https://github.com/napplet/naps/pull/59", status: "in-review", checkedAt: "2026-10-31" },
3956
+ maturity: "experimental",
3957
+ rationale: "Signaling and session binding have unit coverage; interoperable live peer sessions remain unverified here.",
3958
+ evidence: ["packages/nap/src/webrtc/shim.test.ts"]
3959
+ },
3960
+ link: {
3961
+ proposal: { url: "https://github.com/napplet/naps/pull/53", status: "in-review", checkedAt: "2026-10-31" },
3962
+ maturity: "supported",
3963
+ rationale: "The small link-opening binding has focused regression coverage; navigation authorization stays with the host.",
3964
+ evidence: ["packages/nap/src/link/shim.test.ts"]
3965
+ },
3966
+ count: {
3967
+ proposal: { url: "https://github.com/napplet/naps/pull/69", status: "in-review", checkedAt: "2026-10-31" },
3968
+ maturity: "experimental",
3969
+ rationale: "Count binding is tested, but accuracy and aggregation across real relay backends remain outside that evidence.",
3970
+ evidence: ["packages/nap/src/count/shim.test.ts"]
3971
+ },
3972
+ lists: {
3973
+ proposal: { url: "https://github.com/napplet/naps/pull/68", status: "in-review", checkedAt: "2026-10-31" },
3974
+ maturity: "experimental",
3975
+ rationale: "List mutation binding is tested; concurrent real-host mutation behavior is not established by binding tests.",
3976
+ evidence: ["packages/nap/src/lists/shim.test.ts"]
3977
+ },
3978
+ serial: {
3979
+ proposal: { url: "https://github.com/napplet/naps/pull/61", status: "in-review", checkedAt: "2026-10-31" },
3980
+ maturity: "experimental",
3981
+ rationale: "Serial binding has unit coverage; device and native-host integration evidence is limited.",
3982
+ evidence: ["packages/nap/src/serial/shim.test.ts"]
3983
+ },
3984
+ fs: {
3985
+ proposal: { url: "https://github.com/napplet/naps/pull/88", status: "in-review", checkedAt: "2026-10-31" },
3986
+ maturity: "experimental",
3987
+ rationale: "Filesystem binding has MVP coverage; portability and authorization across storage backends remain under evaluation.",
3988
+ evidence: ["packages/nap/src/fs/shim.test.ts"]
3989
+ },
3990
+ common: {
3991
+ proposal: { url: "https://github.com/napplet/naps/pull/67", status: "in-review", checkedAt: "2026-10-31" },
3992
+ maturity: "experimental",
3993
+ rationale: "Social action binding is tested; broader host integration and evolving action semantics warrant explicit opt-in.",
3994
+ evidence: ["packages/nap/src/common/shim.test.ts"]
3995
+ },
3996
+ dm: {
3997
+ proposal: { url: "https://github.com/napplet/naps/pull/74", status: "draft", checkedAt: "2026-10-31" },
3998
+ maturity: "experimental",
3999
+ rationale: "Direct-message binding has shim and type coverage; transport interoperability is not established by those tests.",
4000
+ evidence: ["packages/nap/src/dm/shim.test.ts"]
4001
+ },
4002
+ gamepad: {
4003
+ proposal: { url: "https://github.com/napplet/naps/pull/130", status: "in-review", checkedAt: "2026-10-31" },
4004
+ maturity: "supported",
4005
+ rationale: "Cross-repository delivery includes binding, security, runtime, and conformance verification; the reopened proposal is still subject to change.",
4006
+ evidence: ["packages/nap/src/gamepad/shim.test.ts", ".planning/phases/163-nap-gamepad-across-repositories/163-VERIFICATION.md"],
4007
+ implementationReference: { revision: "0b28f77e3dfa0f07dd7c0f9d61a7090ee99f3a5e", evidence: ".planning/phases/163-nap-gamepad-across-repositories/163-SECURITY.md", scope: "Phase 163 binding, runtime isolation, and conformance verification." }
4008
+ },
4009
+ llm: {
4010
+ proposal: { url: "https://github.com/napplet/naps/pull/134", status: "draft", checkedAt: "2026-10-31" },
4011
+ maturity: "exploratory",
4012
+ rationale: "Early published draft has binding and mock-runtime tests; provider behavior and API design remain exploratory.",
4013
+ evidence: ["packages/nap/src/llm/shim.test.ts", "packages/conformance-cli/src/browser.test.ts"]
4014
+ }
4015
+ };
4016
+ for (const entry of Object.values(NAP_IMPLEMENTATIONS)) {
4017
+ Object.freeze(entry.proposal);
4018
+ Object.freeze(entry.evidence);
4019
+ if (entry.implementationReference) Object.freeze(entry.implementationReference);
4020
+ Object.freeze(entry);
4021
+ }
4022
+ Object.freeze(NAP_IMPLEMENTATIONS);
3835
4023
  function createDispatch() {
3836
4024
  const handlers = /* @__PURE__ */ new Map();
3837
4025
  function registerNap2(domain, handler) {
@@ -4030,7 +4218,7 @@ function bitsToCapabilities(bits) {
4030
4218
  function toIdentity(pubkey2, dTag, hash) {
4031
4219
  return { pubkey: pubkey2, dTag, hash };
4032
4220
  }
4033
- function createAclState(persistence, defaultPolicy = "permissive", onMutation) {
4221
+ function createAclState(persistence, defaultPolicy = "permissive", onMutation, pinDefaultPolicy = false) {
4034
4222
  let state = createState(defaultPolicy);
4035
4223
  function ensureRuntimeDefaultEntry(id) {
4036
4224
  if (state.defaultPolicy !== "permissive") return;
@@ -4119,7 +4307,8 @@ function createAclState(persistence, defaultPolicy = "permissive", onMutation) {
4119
4307
  try {
4120
4308
  const raw = persistence.load();
4121
4309
  if (!raw) return;
4122
- state = deserialize(raw);
4310
+ const loaded = deserialize(raw);
4311
+ state = pinDefaultPolicy ? { ...loaded, defaultPolicy } : loaded;
4123
4312
  } catch {
4124
4313
  state = createState(defaultPolicy);
4125
4314
  }
@@ -4159,6 +4348,12 @@ function createFirewallState(persistence) {
4159
4348
  setGlobalRate(napplet, limit) {
4160
4349
  config = setGlobalRate(config, napplet, limit);
4161
4350
  },
4351
+ setUnfocusedMultiplier(multiplier) {
4352
+ config = setUnfocusedMultiplier(config, multiplier);
4353
+ },
4354
+ setBurstGuard(guard) {
4355
+ config = setBurstGuard(config, guard);
4356
+ },
4162
4357
  addMatcher(matcher) {
4163
4358
  config = addMatcher(config, matcher);
4164
4359
  },
@@ -5989,7 +6184,7 @@ function createRuntime(hooks) {
5989
6184
  extensions?.destroyWindow(windowId);
5990
6185
  });
5991
6186
  let incRuntime = null;
5992
- const aclState = createAclState(hooks.aclPersistence, "permissive", (mutation) => {
6187
+ const aclState = createAclState(hooks.aclPersistence, hooks.aclDefaultPolicy ?? "permissive", (mutation) => {
5993
6188
  for (const entry of sessionRegistry2.getAllEntries()) {
5994
6189
  if (entry.dTag === mutation.dTag && entry.aggregateHash === mutation.aggregateHash) {
5995
6190
  for (const service of Object.values(serviceRegistry)) {
@@ -6001,7 +6196,7 @@ function createRuntime(hooks) {
6001
6196
  }
6002
6197
  }
6003
6198
  }
6004
- });
6199
+ }, hooks.aclDefaultPolicy !== void 0);
6005
6200
  const manifestCache2 = createManifestCache(hooks.manifestPersistence);
6006
6201
  const replayDetector = createReplayDetector(
6007
6202
  hooks.getConfigOverrides ? () => hooks.getConfigOverrides().replayWindowSeconds : void 0
@@ -7988,10 +8183,10 @@ function normalizeCountResult2(value) {
7988
8183
  if (typeof value === "number") {
7989
8184
  return Number.isFinite(value) && value >= 0 ? { ok: true, count: Math.floor(value), approximate: false } : { ok: false, error: "count-unavailable", reason: "count backend returned an invalid count" };
7990
8185
  }
7991
- const count = typeof value.count === "number" && Number.isFinite(value.count) && value.count >= 0 ? Math.floor(value.count) : void 0;
8186
+ const count2 = typeof value.count === "number" && Number.isFinite(value.count) && value.count >= 0 ? Math.floor(value.count) : void 0;
7992
8187
  return {
7993
8188
  ok: value.ok === true,
7994
- ...count !== void 0 ? { count } : {},
8189
+ ...count2 !== void 0 ? { count: count2 } : {},
7995
8190
  ...typeof value.approximate === "boolean" ? { approximate: value.approximate } : {},
7996
8191
  ...typeof value.hll === "string" ? { hll: value.hll } : {},
7997
8192
  ...Array.isArray(value.relays) ? { relays: value.relays } : {},
@@ -8646,8 +8841,8 @@ var MediaRegistry = class {
8646
8841
  const fail2 = (error) => send({ type: "media.session.create.result", id: msg.id ?? "", ...msg.owner === "shell" || msg.owner === "napplet" ? { owner: msg.owner } : {}, error });
8647
8842
  if (this.destroyed) return;
8648
8843
  if (msg.owner !== "napplet" && msg.owner !== "shell") return fail2("missing owner");
8649
- const count = [...this.sessions.values()].filter((entry2) => entry2.windowId === windowId).length + [...this.pending.values()].filter((pending) => pending.windowId === windowId).length;
8650
- if (count >= (this.options.maxSessionsPerWindow ?? 16)) return fail2("session limit exceeded");
8844
+ const count2 = [...this.sessions.values()].filter((entry2) => entry2.windowId === windowId).length + [...this.pending.values()].filter((pending) => pending.windowId === windowId).length;
8845
+ if (count2 >= (this.options.maxSessionsPerWindow ?? 16)) return fail2("session limit exceeded");
8651
8846
  if (msg.owner === "shell" && !msg.source) return fail2("missing source");
8652
8847
  if (msg.owner === "shell" && !this.options.playback) return fail2("unsupported owner mode");
8653
8848
  const entry = {
@@ -8887,8 +9082,8 @@ function createNotifyService(options = {}) {
8887
9082
  }
8888
9083
  case "notify.badge": {
8889
9084
  if (options.setBadge) {
8890
- const count = Math.max(0, Math.floor(message22.count));
8891
- forget(options.setBadge(windowId, count), options.onError);
9085
+ const count2 = Math.max(0, Math.floor(message22.count));
9086
+ forget(options.setBadge(windowId, count2), options.onError);
8892
9087
  }
8893
9088
  return;
8894
9089
  }
@@ -13368,33 +13563,161 @@ var boolean = (value) => typeof value === "boolean";
13368
13563
  var oneOf = (...allowed2) => (value) => typeof value === "string" && allowed2.includes(value);
13369
13564
  var base642 = (value) => typeof value === "string" && value.length >= 4 && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
13370
13565
  var nonNegativeInteger = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
13566
+ var positiveInteger = (value) => typeof value === "number" && Number.isInteger(value) && value > 0;
13567
+ var finiteNumber = (value) => typeof value === "number" && Number.isFinite(value);
13568
+ var MAX_JSON_DEPTH = 64;
13569
+ var MAX_JSON_NODES = 5e4;
13570
+ function isPlainObject22(value) {
13571
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
13572
+ const prototype = Object.getPrototypeOf(value);
13573
+ return prototype === Object.prototype || prototype === null;
13574
+ }
13575
+ function isJsonValue(value) {
13576
+ let budget = MAX_JSON_NODES;
13577
+ const visit = (current, depth) => {
13578
+ if ((budget -= 1) < 0 || depth > MAX_JSON_DEPTH) return false;
13579
+ if (current === null || typeof current === "string" || typeof current === "boolean") return true;
13580
+ if (typeof current === "number") return Number.isFinite(current);
13581
+ if (Array.isArray(current)) return current.every((entry) => visit(entry, depth + 1));
13582
+ return isPlainObject22(current) && Object.values(current).every((entry) => visit(entry, depth + 1));
13583
+ };
13584
+ return visit(value, 0);
13585
+ }
13586
+ var jsonObject = (value) => isPlainObject22(value) && isJsonValue(value);
13587
+ function hasKey(record3, key) {
13588
+ return Object.prototype.hasOwnProperty.call(record3, key);
13589
+ }
13371
13590
  function exactRecord(required, optional = {}) {
13372
13591
  return (value) => {
13373
13592
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
13374
13593
  const data = value;
13375
- if (Object.keys(data).some((key) => !(key in required) && !(key in optional))) return false;
13594
+ if (Object.keys(data).some((key) => !hasKey(required, key) && !hasKey(optional, key))) return false;
13376
13595
  return Object.entries(required).every(([key, check2]) => check2(data[key])) && Object.entries(optional).every(([key, check2]) => data[key] === void 0 || check2(data[key]));
13377
13596
  };
13378
13597
  }
13379
13598
  var nonemptyList = (item) => (value) => Array.isArray(value) && value.length > 0 && value.every(item);
13380
13599
  var textPart = exactRecord({ type: oneOf("text"), text });
13381
13600
  var imagePart = exactRecord({ type: oneOf("image"), mimeType: oneOf("image/png", "image/jpeg", "image/webp"), data: base642 });
13382
- var part = (value) => textPart(value) || imagePart(value);
13383
- var message = exactRecord({ role: oneOf("system", "user", "assistant"), content: nonemptyList(part) });
13384
- var requirements = exactRecord({}, { model: nonemptyText, images: boolean, json: boolean });
13385
- var generationRequest = exactRecord({ handle: nonemptyText, messages: nonemptyList(message) }, { format: oneOf("text", "json") });
13386
- var usage = exactRecord({ inputTokens: nonNegativeInteger, outputTokens: nonNegativeInteger });
13387
- var generation = exactRecord({ text, finish: oneOf("stop", "length", "refusal") }, { usage });
13601
+ var thinkingPart = exactRecord({ type: oneOf("thinking"), text });
13602
+ var toolCallPart = exactRecord({ type: oneOf("toolCall"), toolCallId: nonemptyText, name: nonemptyText, arguments: jsonObject });
13603
+ var inputPart = (value) => textPart(value) || imagePart(value);
13604
+ var assistantPart = (value) => inputPart(value) || thinkingPart(value) || toolCallPart(value);
13605
+ var resultPart = inputPart;
13606
+ var plainMessage = exactRecord({ role: oneOf("system", "user"), content: nonemptyList(inputPart) });
13607
+ var assistantMessage = exactRecord({ role: oneOf("assistant"), content: nonemptyList(assistantPart) });
13608
+ var toolResultMessage = exactRecord(
13609
+ { role: oneOf("toolResult"), content: nonemptyList(resultPart), toolCallId: nonemptyText, toolName: nonemptyText },
13610
+ { isError: boolean }
13611
+ );
13612
+ var message = (value) => plainMessage(value) || assistantMessage(value) || toolResultMessage(value);
13613
+ var requirements = exactRecord({}, { model: nonemptyText, images: boolean, json: boolean, tools: boolean });
13614
+ var SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "object", "array", "null"]);
13615
+ var MAX_SCHEMA_DEPTH = 32;
13616
+ var SCHEMA_MAPS = ["properties", "patternProperties", "$defs"];
13617
+ var SCHEMA_SINGLES = ["items", "additionalProperties", "not", "contains", "propertyNames", "if", "then", "else"];
13618
+ var SCHEMA_LISTS = ["allOf", "anyOf", "oneOf", "prefixItems"];
13619
+ function validSchemaType(type) {
13620
+ if (typeof type === "string") return SCHEMA_TYPES.has(type);
13621
+ return Array.isArray(type) && type.length > 0 && type.every((entry) => typeof entry === "string" && SCHEMA_TYPES.has(entry));
13622
+ }
13623
+ function isSchema(value, depth) {
13624
+ if (typeof value === "boolean") return true;
13625
+ if (depth > MAX_SCHEMA_DEPTH || !isPlainObject22(value)) return false;
13626
+ const sub = (entry) => isSchema(entry, depth + 1);
13627
+ if (value.type !== void 0 && !validSchemaType(value.type)) return false;
13628
+ for (const key of SCHEMA_MAPS) {
13629
+ const entry = value[key];
13630
+ if (entry !== void 0 && !(isPlainObject22(entry) && Object.values(entry).every(sub))) return false;
13631
+ }
13632
+ for (const key of SCHEMA_SINGLES) if (value[key] !== void 0 && !sub(value[key])) return false;
13633
+ for (const key of SCHEMA_LISTS) {
13634
+ const entry = value[key];
13635
+ if (entry !== void 0 && !(Array.isArray(entry) && entry.length > 0 && entry.every(sub))) return false;
13636
+ }
13637
+ if (value.required !== void 0 && !(Array.isArray(value.required) && value.required.every((name) => typeof name === "string"))) return false;
13638
+ return value.enum === void 0 || Array.isArray(value.enum);
13639
+ }
13640
+ var toolParameters = (value) => isPlainObject22(value) && isJsonValue(value) && value.type === "object" && isSchema(value, 0);
13641
+ var toolName = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value);
13642
+ var tool = exactRecord({ name: toolName }, { description: text, parameters: toolParameters });
13643
+ var namedToolChoice = exactRecord({ type: oneOf("tool"), name: nonemptyText });
13644
+ var toolChoice = (value) => oneOf("auto", "none", "required")(value) || namedToolChoice(value);
13645
+ var generationFields = exactRecord(
13646
+ { handle: nonemptyText, messages: nonemptyList(message) },
13647
+ {
13648
+ format: oneOf("text", "json"),
13649
+ maxTokens: positiveInteger,
13650
+ temperature: finiteNumber,
13651
+ tools: (value) => Array.isArray(value) && value.every(tool),
13652
+ toolChoice
13653
+ }
13654
+ );
13655
+ function callsOf(turn) {
13656
+ return turn.role === "assistant" ? turn.content.filter((entry) => entry.type === "toolCall") : [];
13657
+ }
13658
+ function validToolHistory(messages) {
13659
+ const seen = /* @__PURE__ */ new Set();
13660
+ let index = 0;
13661
+ while (index < messages.length) {
13662
+ const turn = messages[index];
13663
+ index += 1;
13664
+ if (turn.role === "toolResult") return false;
13665
+ const calls = callsOf(turn);
13666
+ for (const call of calls) {
13667
+ if (seen.has(call.toolCallId)) return false;
13668
+ seen.add(call.toolCallId);
13669
+ }
13670
+ const pending = new Map(calls.map((call) => [call.toolCallId, call.name]));
13671
+ for (let answered = 0; answered < calls.length; answered += 1) {
13672
+ const result2 = messages[index + answered];
13673
+ if (result2?.role !== "toolResult" || result2.toolCallId === void 0 || pending.get(result2.toolCallId) !== result2.toolName) return false;
13674
+ pending.delete(result2.toolCallId);
13675
+ }
13676
+ index += calls.length;
13677
+ }
13678
+ return true;
13679
+ }
13680
+ function validRequestRelations(request) {
13681
+ const names = (request.tools ?? []).map((entry) => entry.name);
13682
+ if (new Set(names).size !== names.length) return false;
13683
+ if (request.toolChoice !== void 0) {
13684
+ if (names.length === 0) return false;
13685
+ if (typeof request.toolChoice === "object" && !names.includes(request.toolChoice.name)) return false;
13686
+ }
13687
+ return validToolHistory(request.messages);
13688
+ }
13689
+ var usage = exactRecord(
13690
+ { inputTokens: nonNegativeInteger, outputTokens: nonNegativeInteger },
13691
+ { cacheReadTokens: nonNegativeInteger, cacheWriteTokens: nonNegativeInteger, reasoningTokens: nonNegativeInteger }
13692
+ );
13693
+ var outputPart = (value) => textPart(value) || thinkingPart(value) || toolCallPart(value);
13694
+ var generation = exactRecord(
13695
+ { content: (value) => Array.isArray(value) && value.every(outputPart), finish: oneOf("stop", "length", "refusal", "toolUse") },
13696
+ { usage }
13697
+ );
13388
13698
  function isLlmRequirements(value) {
13389
13699
  return value === void 0 || requirements(value);
13390
13700
  }
13391
- var isLlmGenerationRequest = generationRequest;
13701
+ function isLlmGenerationRequest(value) {
13702
+ return generationFields(value) && validRequestRelations(value);
13703
+ }
13392
13704
  var isLlmGeneration = generation;
13705
+ function llmTextOf(content) {
13706
+ return content.map((part) => part.type === "text" ? part.text : "").join("");
13707
+ }
13393
13708
  var isNonemptyText = nonemptyText;
13394
13709
  function countLlmImages(messages) {
13395
- let count = 0;
13396
- for (const entry of messages) for (const item of entry.content) if (item.type === "image") count += 1;
13397
- return count;
13710
+ let count2 = 0;
13711
+ for (const entry of messages) for (const item of entry.content) if (item.type === "image") count2 += 1;
13712
+ return count2;
13713
+ }
13714
+ function hasLlmToolHistory(messages) {
13715
+ return messages.some((entry) => entry.role === "toolResult" || entry.content.some((item) => item.type === "toolCall"));
13716
+ }
13717
+ function llmToolChoiceMode(request) {
13718
+ if ((request.tools ?? []).length === 0) return null;
13719
+ if (request.toolChoice === void 0) return "auto";
13720
+ return typeof request.toolChoice === "string" ? request.toolChoice : "tool";
13398
13721
  }
13399
13722
  function isJsonObjectText(value) {
13400
13723
  try {
@@ -13404,6 +13727,136 @@ function isJsonObjectText(value) {
13404
13727
  return false;
13405
13728
  }
13406
13729
  }
13730
+ var MALFORMED = { code: "provider-error", message: "The provider returned an incomplete or malformed completion." };
13731
+ var LIFECYCLE = { code: "provider-error", message: "The provider streamed output that breaks the block lifecycle." };
13732
+ var MISMATCH = { code: "provider-error", message: "The provider result does not match its streamed blocks." };
13733
+ var BAD_CALL = { code: "provider-error", message: "The provider returned an invalid tool call." };
13734
+ var BAD_MODE = { code: "provider-error", message: "The provider result does not honour the requested tool choice." };
13735
+ var NO_JSON = { code: "provider-error", message: "The provider completed without a JSON object." };
13736
+ function unsupported4(message22) {
13737
+ return { code: "unsupported", message: message22 };
13738
+ }
13739
+ function unsupportedInput(connection, request) {
13740
+ const mode = llmToolChoiceMode(request);
13741
+ if (mode !== null && !connection.tools) return unsupported4("This connection does not support tool calling.");
13742
+ if (mode !== null && !connection.toolChoiceModes.includes(mode)) return unsupported4(`This connection does not support the "${mode}" tool choice.`);
13743
+ if (hasLlmToolHistory(request.messages) && !connection.tools) return unsupported4("This connection does not accept tool calls or tool results.");
13744
+ if (countLlmImages(request.messages) > 0 && !connection.images) return unsupported4("This connection does not accept image input.");
13745
+ if (request.format === "json" && !connection.json) return unsupported4("This connection does not support JSON-object output.");
13746
+ return null;
13747
+ }
13748
+ var EVENTS = /* @__PURE__ */ new Set(["start", "delta", "end"]);
13749
+ var BLOCKS = /* @__PURE__ */ new Set(["text", "thinking", "toolCall"]);
13750
+ var nonEmpty = (value) => typeof value === "string" && value.length > 0;
13751
+ function jsonEqual(a, b) {
13752
+ if (a === b) return true;
13753
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
13754
+ if (Array.isArray(a) || Array.isArray(b)) {
13755
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((entry, index) => jsonEqual(entry, b[index]));
13756
+ }
13757
+ const left = a;
13758
+ const right = b;
13759
+ const keys = Object.keys(left);
13760
+ return keys.length === Object.keys(right).length && keys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && jsonEqual(left[key], right[key]));
13761
+ }
13762
+ function validStart(event) {
13763
+ if (event.text !== void 0) return false;
13764
+ if (event.block === "toolCall") return nonEmpty(event.toolCallId) && nonEmpty(event.name);
13765
+ return event.toolCallId === void 0 && event.name === void 0;
13766
+ }
13767
+ function createLlmDeltaTracker() {
13768
+ const blocks = /* @__PURE__ */ new Map();
13769
+ return {
13770
+ accept(event) {
13771
+ if (!EVENTS.has(event.event) || !BLOCKS.has(event.block)) return false;
13772
+ if (!Number.isInteger(event.blockIndex) || event.blockIndex < 0) return false;
13773
+ const known = blocks.get(event.blockIndex);
13774
+ if (event.event === "start") {
13775
+ if (known || !validStart(event)) return false;
13776
+ blocks.set(event.blockIndex, {
13777
+ kind: event.block,
13778
+ open: true,
13779
+ text: "",
13780
+ ...event.block === "toolCall" ? { toolCallId: event.toolCallId, name: event.name } : {}
13781
+ });
13782
+ return true;
13783
+ }
13784
+ if (!known?.open || known.kind !== event.block) return false;
13785
+ if (event.toolCallId !== void 0 || event.name !== void 0) return false;
13786
+ if (event.event === "end") {
13787
+ known.open = false;
13788
+ return event.text === void 0;
13789
+ }
13790
+ if (typeof event.text !== "string") return false;
13791
+ known.text += event.text;
13792
+ return true;
13793
+ },
13794
+ matches(content) {
13795
+ for (const [index, block2] of blocks) {
13796
+ if (block2.open) return false;
13797
+ const part = content[index];
13798
+ if (!part || part.type !== block2.kind) return false;
13799
+ if (part.type === "toolCall") {
13800
+ if (part.toolCallId !== block2.toolCallId || part.name !== block2.name) return false;
13801
+ try {
13802
+ if (!jsonEqual(JSON.parse(block2.text), part.arguments)) return false;
13803
+ } catch {
13804
+ return false;
13805
+ }
13806
+ } else if (part.text !== block2.text) {
13807
+ return false;
13808
+ }
13809
+ }
13810
+ return true;
13811
+ }
13812
+ };
13813
+ }
13814
+ function callsOf2(content) {
13815
+ return content.filter((part) => part.type === "toolCall");
13816
+ }
13817
+ function historyIds(request) {
13818
+ const ids = /* @__PURE__ */ new Set();
13819
+ for (const message22 of request.messages) {
13820
+ for (const part of message22.content) if (part.type === "toolCall") ids.add(part.toolCallId);
13821
+ }
13822
+ return ids;
13823
+ }
13824
+ function validCalls(request, calls) {
13825
+ const names = new Set((request.tools ?? []).map((entry) => entry.name));
13826
+ const used = historyIds(request);
13827
+ for (const call of calls) {
13828
+ if (!names.has(call.name) || used.has(call.toolCallId)) return false;
13829
+ used.add(call.toolCallId);
13830
+ }
13831
+ return true;
13832
+ }
13833
+ function honoursChoice(request, calls) {
13834
+ const mode = llmToolChoiceMode(request);
13835
+ if (mode === "none") return calls.length === 0;
13836
+ if (mode === "required") return calls.length > 0;
13837
+ if (mode !== "tool") return true;
13838
+ const forced = typeof request.toolChoice === "object" ? request.toolChoice.name : "";
13839
+ return calls.length > 0 && calls.every((call) => call.name === forced);
13840
+ }
13841
+ function stripPartialCalls(result2) {
13842
+ if (typeof result2 !== "object" || result2 === null) return result2;
13843
+ const generation2 = result2;
13844
+ if (generation2.finish !== "length" && generation2.finish !== "refusal" || !Array.isArray(generation2.content)) return result2;
13845
+ return { ...generation2, content: generation2.content.filter((part) => part?.type !== "toolCall") };
13846
+ }
13847
+ function checkTerminal(request, raw, tracker) {
13848
+ const result2 = stripPartialCalls(raw);
13849
+ if (!isLlmGeneration(result2)) return MALFORMED;
13850
+ if (result2.finish === "length" || result2.finish === "refusal") return result2;
13851
+ const calls = callsOf2(result2.content);
13852
+ if (result2.finish === "toolUse" && calls.length === 0) return MALFORMED;
13853
+ if (!validCalls(request, calls)) return BAD_CALL;
13854
+ if (!honoursChoice(request, calls)) return BAD_MODE;
13855
+ const normalised = calls.length > 0 && result2.finish === "stop" ? { ...result2, finish: "toolUse" } : result2;
13856
+ if (request.format === "json" && normalised.finish === "stop" && !isJsonObjectText(llmTextOf(normalised.content))) return NO_JSON;
13857
+ return tracker.matches(normalised.content) ? normalised : MISMATCH;
13858
+ }
13859
+ var LLM_LIFECYCLE_FAILURE = LIFECYCLE;
13407
13860
  var DESCRIPTOR = {
13408
13861
  name: "llm",
13409
13862
  version: "1.0.0",
@@ -13421,16 +13874,35 @@ function failure(error) {
13421
13874
  if (error instanceof LlmServiceError) return { code: error.code, message: error.message };
13422
13875
  return { code: "provider-error", message: "The provider request failed." };
13423
13876
  }
13877
+ function sameModes(a, b) {
13878
+ return a.length === b.length && a.every((mode, index) => mode === b[index]);
13879
+ }
13424
13880
  function sameConnection(a, b) {
13425
- return a.id === b.id && a.name === b.name && a.model === b.model && a.route === b.route && a.images === b.images && a.json === b.json;
13881
+ return a.id === b.id && a.name === b.name && a.model === b.model && a.route === b.route && a.images === b.images && a.json === b.json && a.tools === b.tools && sameModes(a.toolChoiceModes, b.toolChoiceModes);
13882
+ }
13883
+ function declaresValidModes(connection) {
13884
+ if (!connection.tools) return true;
13885
+ const modes = connection.toolChoiceModes;
13886
+ return new Set(modes).size === modes.length && modes.includes("auto") && modes.includes("none");
13426
13887
  }
13427
13888
  function meetsRequirements(connection, requirements2) {
13889
+ if (!declaresValidModes(connection)) return false;
13428
13890
  if (requirements2.model !== void 0 && requirements2.model !== connection.model) return false;
13429
13891
  if (requirements2.images === true && !connection.images) return false;
13892
+ if (requirements2.tools === true && !connection.tools) return false;
13430
13893
  return !(requirements2.json === true && !connection.json);
13431
13894
  }
13432
13895
  function toModel(handle, connection) {
13433
- return { handle, name: connection.name, model: connection.model, route: connection.route, images: connection.images, json: connection.json };
13896
+ return {
13897
+ handle,
13898
+ name: connection.name,
13899
+ model: connection.model,
13900
+ route: connection.route,
13901
+ images: connection.images,
13902
+ json: connection.json,
13903
+ tools: connection.tools,
13904
+ toolChoiceModes: connection.tools ? [...connection.toolChoiceModes] : []
13905
+ };
13434
13906
  }
13435
13907
  function defaultHandleFactory() {
13436
13908
  let counter = 0;
@@ -13591,17 +14063,12 @@ function admitGeneration(state, windowId, message22) {
13591
14063
  if (JSON.stringify(message22.request).length > state.maxRequestChars) return { code: "quota-exceeded", message: "The request exceeds the runtime size limit." };
13592
14064
  return null;
13593
14065
  }
13594
- function unsupportedInput(connection, request) {
13595
- if (countLlmImages(request.messages) > 0 && !connection.images) return { code: "unsupported", message: "This connection does not accept image input." };
13596
- if (request.format === "json" && !connection.json) return { code: "unsupported", message: "This connection does not support JSON-object output." };
13597
- return null;
13598
- }
13599
- function validateGeneration(generation2, result2) {
13600
- if (!isLlmGeneration(result2)) return { code: "provider-error", message: "The provider returned an incomplete or malformed completion." };
13601
- if (generation2.format === "json" && result2.finish === "stop" && !isJsonObjectText(result2.text)) {
13602
- return { code: "provider-error", message: "The provider completed without a JSON object." };
13603
- }
13604
- return result2;
14066
+ function deltaMessage(requestId, sequence, event) {
14067
+ const delta = { requestId, sequence, event: event.event, block: event.block, blockIndex: event.blockIndex };
14068
+ if (event.text !== void 0) delta.text = event.text;
14069
+ if (event.toolCallId !== void 0) delta.toolCallId = event.toolCallId;
14070
+ if (event.name !== void 0) delta.name = event.name;
14071
+ return { type: "llm.delta", ...delta };
13605
14072
  }
13606
14073
  async function awaitConsent(state, context, connection, request, generation2) {
13607
14074
  const prompt = new AbortController();
@@ -13643,13 +14110,17 @@ async function runGeneration(state, windowId, requestId, request, generation2, s
13643
14110
  }
13644
14111
  const result2 = await state.host.generate(context, entry.snapshot, request, {
13645
14112
  signal: generation2.controller.signal,
13646
- onDelta: (text2) => {
13647
- if (generation2.settled || typeof text2 !== "string") return;
13648
- send({ type: "llm.delta", requestId, sequence: generation2.sequence++, text: text2 });
14113
+ onDelta: (event) => {
14114
+ if (generation2.settled) return;
14115
+ if (!generation2.tracker.accept(event)) {
14116
+ fail2(LLM_LIFECYCLE_FAILURE);
14117
+ return;
14118
+ }
14119
+ send(deltaMessage(requestId, generation2.sequence++, event));
13649
14120
  }
13650
14121
  });
13651
14122
  if (generation2.settled) return;
13652
- const checked = validateGeneration(generation2, result2);
14123
+ const checked = checkTerminal(request, result2, generation2.tracker);
13653
14124
  if ("code" in checked) fail2(checked);
13654
14125
  else settle6(state, windowId, requestId, generation2, { type: "llm.generate.result", id: requestId, result: checked });
13655
14126
  } catch (error) {
@@ -13669,7 +14140,8 @@ function handleGenerate(state, windowId, message22, send) {
13669
14140
  handle: request.handle,
13670
14141
  awaitingConsent: false,
13671
14142
  send,
13672
- format: request.format ?? "text",
14143
+ request,
14144
+ tracker: createLlmDeltaTracker(),
13673
14145
  epoch: state.epoch,
13674
14146
  sequence: 0,
13675
14147
  settled: false,
@@ -13770,10 +14242,143 @@ function createLlmService(options) {
13770
14242
  }
13771
14243
  };
13772
14244
  }
14245
+ var BAD_CALL2 = "The provider returned an invalid tool call.";
14246
+ var fallbackCounter = 0;
14247
+ function synthesizeLlmToolCallId() {
14248
+ fallbackCounter += 1;
14249
+ const random = typeof globalThis.crypto?.randomUUID === "function" ? globalThis.crypto.randomUUID() : `${Date.now().toString(36)}-${fallbackCounter}`;
14250
+ return `call_${random}`;
14251
+ }
14252
+ function parseToolArguments(raw) {
14253
+ if (raw === void 0 || raw === "") return {};
14254
+ let value = raw;
14255
+ if (typeof raw === "string") {
14256
+ try {
14257
+ value = JSON.parse(raw);
14258
+ } catch {
14259
+ throw new LlmServiceError("provider-error", BAD_CALL2);
14260
+ }
14261
+ }
14262
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new LlmServiceError("provider-error", BAD_CALL2);
14263
+ return value;
14264
+ }
14265
+ function toolCallParts(partial, calls) {
14266
+ if (partial) return [];
14267
+ return calls.map((call) => {
14268
+ if (typeof call.name !== "string" || call.name === "") throw new LlmServiceError("provider-error", BAD_CALL2);
14269
+ const toolCallId = typeof call.id === "string" && call.id !== "" ? call.id : synthesizeLlmToolCallId();
14270
+ return { type: "toolCall", toolCallId, name: call.name, arguments: parseToolArguments(call.args) };
14271
+ });
14272
+ }
14273
+ function createLlmBlockBuilder() {
14274
+ const texts = /* @__PURE__ */ new Map();
14275
+ const calls = /* @__PURE__ */ new Map();
14276
+ let next = 0;
14277
+ function startCall(call) {
14278
+ call.index = next++;
14279
+ const events = [
14280
+ { event: "start", block: "toolCall", blockIndex: call.index, toolCallId: call.id, name: call.name }
14281
+ ];
14282
+ for (const fragment of call.held) events.push(deltaOf(call, fragment));
14283
+ call.held = [];
14284
+ return events;
14285
+ }
14286
+ function deltaOf(call, fragment) {
14287
+ call.sent.push(fragment);
14288
+ return { event: "delta", block: "toolCall", blockIndex: call.index, text: fragment };
14289
+ }
14290
+ function endCall(call) {
14291
+ if (!call.open || call.index === void 0) return [];
14292
+ call.open = false;
14293
+ const events = [];
14294
+ if (call.sent.length === 0) events.push(deltaOf(call, "{}"));
14295
+ events.push({ event: "end", block: "toolCall", blockIndex: call.index });
14296
+ return events;
14297
+ }
14298
+ function callFor(key) {
14299
+ let call = calls.get(key);
14300
+ if (!call) {
14301
+ call = { index: void 0, id: void 0, name: void 0, held: [], sent: [], open: true };
14302
+ calls.set(key, call);
14303
+ }
14304
+ return call;
14305
+ }
14306
+ function endKey(key) {
14307
+ const text2 = texts.get(key);
14308
+ if (text2) {
14309
+ if (!text2.open) return [];
14310
+ text2.open = false;
14311
+ return [{ event: "end", block: text2.kind, blockIndex: text2.index }];
14312
+ }
14313
+ const call = calls.get(key);
14314
+ return call ? endCall(call) : [];
14315
+ }
14316
+ return {
14317
+ append(kind, key, fragment) {
14318
+ if (fragment === "") return [];
14319
+ const events = [];
14320
+ let block2 = texts.get(key);
14321
+ if (!block2) {
14322
+ block2 = { kind, index: next++, text: "", open: true };
14323
+ texts.set(key, block2);
14324
+ events.push({ event: "start", block: kind, blockIndex: block2.index });
14325
+ }
14326
+ if (!block2.open) return [];
14327
+ block2.text += fragment;
14328
+ events.push({ event: "delta", block: kind, blockIndex: block2.index, text: fragment });
14329
+ return events;
14330
+ },
14331
+ toolDelta(key, update) {
14332
+ const call = callFor(key);
14333
+ if (!call.open) return [];
14334
+ const events = [];
14335
+ if (call.index === void 0) {
14336
+ if (typeof update.id === "string" && update.id !== "" && call.id === void 0) call.id = update.id;
14337
+ if (typeof update.name === "string" && update.name !== "" && call.name === void 0) {
14338
+ call.name = update.name;
14339
+ call.id ??= synthesizeLlmToolCallId();
14340
+ }
14341
+ if (call.id !== void 0 && call.name !== void 0) events.push(...startCall(call));
14342
+ }
14343
+ if (typeof update.fragment === "string" && update.fragment !== "") {
14344
+ if (call.index === void 0) call.held.push(update.fragment);
14345
+ else events.push(deltaOf(call, update.fragment));
14346
+ }
14347
+ return events;
14348
+ },
14349
+ toolWhole(key, update) {
14350
+ const call = callFor(key);
14351
+ if (typeof update.name !== "string" || update.name === "") throw new LlmServiceError("provider-error", BAD_CALL2);
14352
+ call.name = update.name;
14353
+ call.id = typeof update.id === "string" && update.id !== "" ? update.id : synthesizeLlmToolCallId();
14354
+ const args = parseToolArguments(update.args);
14355
+ return [...startCall(call), deltaOf(call, JSON.stringify(args)), ...endCall(call)];
14356
+ },
14357
+ end: endKey,
14358
+ closeAll() {
14359
+ const open = [];
14360
+ for (const [key, block2] of texts) if (block2.open) open.push({ index: block2.index, key });
14361
+ for (const [key, call] of calls) if (call.open && call.index !== void 0) open.push({ index: call.index, key });
14362
+ return open.sort((a, b) => a.index - b.index).flatMap((entry) => endKey(entry.key));
14363
+ },
14364
+ content(completedTurn) {
14365
+ const parts = [];
14366
+ for (const block2 of texts.values()) parts.push({ index: block2.index, part: { type: block2.kind, text: block2.text } });
14367
+ for (const call of calls.values()) {
14368
+ if (!completedTurn) continue;
14369
+ if (call.index === void 0) throw new LlmServiceError("provider-error", BAD_CALL2);
14370
+ const toolCallId = call.id;
14371
+ const name = call.name;
14372
+ parts.push({ index: call.index, part: { type: "toolCall", toolCallId, name, arguments: parseToolArguments(call.sent.join("")) } });
14373
+ }
14374
+ return parts.sort((a, b) => a.index - b.index).map((entry) => entry.part);
14375
+ }
14376
+ };
14377
+ }
13773
14378
  var DEFAULT_MAX_OUTPUT_TOKENS = 4096;
13774
14379
  var ANTHROPIC_VERSION = "2023-06-01";
13775
14380
  var JSON_INSTRUCTION = "Respond with a single JSON object and no other text.";
13776
- function unsupported4(message22) {
14381
+ function unsupported5(message22) {
13777
14382
  return new LlmServiceError("unsupported", message22);
13778
14383
  }
13779
14384
  function providerError(message22) {
@@ -13793,69 +14398,84 @@ function credentialHeaders(endpoint) {
13793
14398
  if (header === "authorization-bearer") return { authorization: `Bearer ${endpoint.credential}` };
13794
14399
  return { [header]: endpoint.credential };
13795
14400
  }
14401
+ function plainParts(parts) {
14402
+ return parts.map((part) => {
14403
+ if (part.type === "text" || part.type === "image") return part;
14404
+ throw unsupported5("This provider mapping does not accept this content part.");
14405
+ });
14406
+ }
13796
14407
  function textOf(parts) {
13797
- return parts.map((part2) => part2.type === "text" ? part2.text : "").join("");
14408
+ return plainParts(parts).map((part) => part.type === "text" ? part.text : "").join("");
13798
14409
  }
13799
14410
  function hasImage(parts) {
13800
- return parts.some((part2) => part2.type === "image");
14411
+ return parts.some((part) => part.type === "image");
13801
14412
  }
13802
14413
  function record2(value) {
13803
14414
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
13804
14415
  }
13805
- function usageFrom(input, output) {
13806
- if (typeof input !== "number" || typeof output !== "number" || !Number.isInteger(input) || !Number.isInteger(output) || input < 0 || output < 0) return void 0;
13807
- return { inputTokens: input, outputTokens: output };
14416
+ var count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
14417
+ function usageFrom(input, output, extras = {}) {
14418
+ if (!count(input) || !count(output)) return void 0;
14419
+ const usage2 = { inputTokens: input, outputTokens: output };
14420
+ if (count(extras.cacheReadTokens)) usage2.cacheReadTokens = extras.cacheReadTokens;
14421
+ if (count(extras.cacheWriteTokens)) usage2.cacheWriteTokens = extras.cacheWriteTokens;
14422
+ if (count(extras.reasoningTokens)) usage2.reasoningTokens = extras.reasoningTokens;
14423
+ return usage2;
13808
14424
  }
13809
- function finished(text2, finish, usage2) {
13810
- return usage2 ? { text: text2, finish, usage: usage2 } : { text: text2, finish };
14425
+ function finished(content, finish, usage2) {
14426
+ return usage2 ? { content, finish, usage: usage2 } : { content, finish };
13811
14427
  }
13812
- function openAiContent(parts) {
13813
- if (!hasImage(parts)) return textOf(parts);
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}` } });
14428
+ function textContent(text2) {
14429
+ return text2 === "" ? [] : [{ type: "text", text: text2 }];
13815
14430
  }
13816
- function buildOpenAiChat(endpoint, request, stream) {
13817
- const body = {
13818
- model: endpoint.model,
13819
- messages: request.messages.map((message22) => ({ role: message22.role, content: openAiContent(message22.content) })),
13820
- stream
13821
- };
13822
- if (stream) body.stream_options = { include_usage: true };
13823
- if (request.format === "json") body.response_format = { type: "json_object" };
13824
- if (endpoint.maxOutputTokens !== void 0) body.max_tokens = endpoint.maxOutputTokens;
13825
- return {
13826
- url: `${trimBase(endpoint.baseUrl)}/chat/completions`,
13827
- method: "POST",
13828
- headers: { "content-type": "application/json", ...endpoint.headers, ...credentialHeaders(endpoint) },
13829
- body: JSON.stringify(body)
13830
- };
14431
+ function completed(content, finish, usage2) {
14432
+ if (finish === null) throw providerError("The provider response had no recognised completion marker.");
14433
+ if (finish === "length" || finish === "refusal") return finished(content.filter((part) => part.type !== "toolCall"), finish, usage2);
14434
+ const calls = content.some((part) => part.type === "toolCall");
14435
+ return finished(content, finish === "stop" && calls ? "toolUse" : finish, usage2);
13831
14436
  }
13832
- function parseOpenAiChat(json) {
13833
- const root = record2(json);
13834
- const choice = record2(Array.isArray(root?.choices) ? root?.choices[0] : void 0);
13835
- const message22 = record2(choice?.message);
13836
- if (!choice || !message22) throw providerError("The provider response had no completion choice.");
13837
- const usage2 = record2(root?.usage);
13838
- const tokens = usageFrom(usage2?.prompt_tokens, usage2?.completion_tokens);
13839
- if (typeof message22.refusal === "string" && message22.refusal.length > 0) return finished("", "refusal", tokens);
13840
- const text2 = typeof message22.content === "string" ? message22.content : "";
13841
- return completed(text2, openAiFinish(choice.finish_reason), tokens);
14437
+ function isCompletedFinish(finish) {
14438
+ return finish === "stop" || finish === "toolUse";
13842
14439
  }
13843
- function openAiFinish(reason) {
13844
- if (reason === "stop") return "stop";
13845
- if (reason === "length") return "length";
13846
- return reason === "content_filter" ? "refusal" : null;
14440
+ var DEFAULT_TOOL_PARAMETERS = { type: "object", properties: {}, additionalProperties: false };
14441
+ function toolsOf(request) {
14442
+ return request.tools ?? [];
13847
14443
  }
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;
14444
+ function parametersOf(tool2) {
14445
+ return tool2.parameters ?? DEFAULT_TOOL_PARAMETERS;
13852
14446
  }
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);
14447
+ function callsOf3(message22) {
14448
+ return message22.content.filter((part) => part.type === "toolCall");
13856
14449
  }
13857
- function anthropicBlocks(parts) {
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 } });
14450
+ function nonCallParts(message22) {
14451
+ return plainParts(message22.content.filter((part) => part.type !== "toolCall"));
14452
+ }
14453
+ function outputLimit(endpoint, request) {
14454
+ const limits = [request.maxTokens, endpoint.maxOutputTokens].filter((limit) => limit !== void 0);
14455
+ return limits.length === 0 ? void 0 : Math.min(...limits);
14456
+ }
14457
+ var TOOL_FAILED = "Tool execution failed.";
14458
+ function toolResultText(message22) {
14459
+ if (hasImage(message22.content)) throw unsupported5("This provider does not accept images in tool results.");
14460
+ const texts = plainParts(message22.content).map((part) => part.type === "text" ? part.text : "");
14461
+ return (message22.isError === true ? [TOOL_FAILED, ...texts] : texts).join("\n");
14462
+ }
14463
+ var OPAQUE_REASONING_MODEL = /^(models\/)?gemini-([3-9]|\d{2,})/;
14464
+ var TEMPERATURE_CEILING = { "openai-chat": 2, "anthropic-messages": 1, gemini: 2 };
14465
+ function needsOpaqueReasoning(endpoint) {
14466
+ return endpoint.requiresOpaqueReasoning ?? (endpoint.protocol === "gemini" && OPAQUE_REASONING_MODEL.test(endpoint.model));
14467
+ }
14468
+ function prepareRequest(endpoint, request) {
14469
+ if (needsOpaqueReasoning(endpoint) && request.messages.some((message22) => callsOf3(message22).length > 0)) {
14470
+ throw unsupported5("This model needs reasoning state that NAP-LLM cannot carry, so a conversation containing tool calls cannot continue on it.");
14471
+ }
14472
+ const ceiling = TEMPERATURE_CEILING[endpoint.protocol];
14473
+ if (request.temperature !== void 0 && (request.temperature < 0 || request.temperature > ceiling)) {
14474
+ throw unsupported5(`This provider accepts a temperature between 0 and ${ceiling}.`);
14475
+ }
14476
+ const messages = request.messages.map((message22) => ({ ...message22, content: message22.content.filter((part) => part.type !== "thinking") })).filter((message22) => message22.content.length > 0);
14477
+ if (messages.length === 0) throw unsupported5("Nothing remains to send once display-only thinking is omitted.");
14478
+ return { ...request, messages };
13859
14479
  }
13860
14480
  function splitSystem(messages) {
13861
14481
  const systemParts = [];
@@ -13865,29 +14485,83 @@ function splitSystem(messages) {
13865
14485
  turns.push(message22);
13866
14486
  continue;
13867
14487
  }
13868
- if (hasImage(message22.content)) throw unsupported4("This provider does not accept images in system messages.");
14488
+ if (hasImage(message22.content)) throw unsupported5("This provider does not accept images in system messages.");
13869
14489
  systemParts.push(textOf(message22.content));
13870
14490
  }
13871
14491
  return { system: systemParts.join("\n"), turns };
13872
14492
  }
14493
+ var STREAM_ERROR = "The provider reported an error while streaming.";
14494
+ function textField(value) {
14495
+ return typeof value === "string" ? value : "";
14496
+ }
14497
+ function anthropicFinish(reason) {
14498
+ if (reason === "end_turn" || reason === "stop_sequence") return "stop";
14499
+ if (reason === "max_tokens") return "length";
14500
+ if (reason === "tool_use") return "toolUse";
14501
+ return reason === "refusal" ? "refusal" : null;
14502
+ }
14503
+ function anthropicBlocks(parts) {
14504
+ return parts.map((part) => {
14505
+ switch (part.type) {
14506
+ case "text":
14507
+ return { type: "text", text: part.text };
14508
+ case "toolCall":
14509
+ return { type: "tool_use", id: part.toolCallId, name: part.name, input: part.arguments };
14510
+ case "image":
14511
+ return { type: "image", source: { type: "base64", media_type: part.mimeType, data: part.data } };
14512
+ default:
14513
+ throw unsupported5("This provider mapping does not accept this content part.");
14514
+ }
14515
+ });
14516
+ }
14517
+ function anthropicTurn(message22) {
14518
+ if (message22.role === "assistant") return { role: "assistant", content: anthropicBlocks(message22.content) };
14519
+ if (message22.role !== "toolResult") return { role: "user", content: anthropicBlocks(message22.content) };
14520
+ const result2 = {
14521
+ type: "tool_result",
14522
+ tool_use_id: message22.toolCallId,
14523
+ content: anthropicBlocks(plainParts(message22.content)),
14524
+ ...message22.isError === true ? { is_error: true } : {}
14525
+ };
14526
+ return { role: "user", content: [result2] };
14527
+ }
14528
+ function anthropicToolChoice(choice) {
14529
+ if (choice === "required") return { type: "any" };
14530
+ return typeof choice === "string" ? { type: choice } : { type: "tool", name: choice.name };
14531
+ }
13873
14532
  function buildAnthropicMessages(endpoint, request, stream) {
14533
+ const tools = toolsOf(request);
14534
+ if (tools.length === 0 && hasLlmToolHistory(request.messages)) {
14535
+ throw unsupported5("This provider needs tool definitions to continue a conversation that contains tool calls.");
14536
+ }
13874
14537
  const { system, turns } = splitSystem(request.messages);
13875
- if (turns.length === 0 || turns[0].role !== "user") throw unsupported4("This provider requires the first non-system message to come from the user.");
14538
+ if (turns.length === 0 || turns[0].role === "assistant" || turns[0].role === "toolResult") {
14539
+ throw unsupported5("This provider requires the first non-system message to come from the user.");
14540
+ }
13876
14541
  const merged = [];
13877
14542
  for (const turn of turns) {
14543
+ const next = anthropicTurn(turn);
13878
14544
  const previous = merged.at(-1);
13879
- const blocks = anthropicBlocks(turn.content);
13880
- if (previous && previous.role === turn.role) previous.content.push(...blocks);
13881
- else merged.push({ role: turn.role, content: blocks });
14545
+ if (previous && previous.role === next.role) previous.content.push(...next.content);
14546
+ else merged.push(next);
13882
14547
  }
13883
14548
  const systemText = request.format === "json" ? [system, JSON_INSTRUCTION].filter(Boolean).join("\n") : system;
13884
14549
  const body = {
13885
14550
  model: endpoint.model,
13886
- max_tokens: endpoint.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
14551
+ max_tokens: outputLimit(endpoint, request) ?? DEFAULT_MAX_OUTPUT_TOKENS,
13887
14552
  messages: merged,
13888
14553
  stream
13889
14554
  };
13890
14555
  if (systemText) body.system = systemText;
14556
+ if (request.temperature !== void 0) body.temperature = request.temperature;
14557
+ if (tools.length > 0) {
14558
+ body.tools = tools.map((tool2) => ({
14559
+ name: tool2.name,
14560
+ ...tool2.description === void 0 ? {} : { description: tool2.description },
14561
+ input_schema: parametersOf(tool2)
14562
+ }));
14563
+ if (request.toolChoice !== void 0) body.tool_choice = anthropicToolChoice(request.toolChoice);
14564
+ }
13891
14565
  return {
13892
14566
  url: `${trimBase(endpoint.baseUrl)}/messages`,
13893
14567
  method: "POST",
@@ -13901,31 +14575,148 @@ function buildAnthropicMessages(endpoint, request, stream) {
13901
14575
  body: JSON.stringify(body)
13902
14576
  };
13903
14577
  }
14578
+ function anthropicUsage(usage2) {
14579
+ return usageFrom(usage2?.input_tokens, usage2?.output_tokens, {
14580
+ cacheReadTokens: usage2?.cache_read_input_tokens,
14581
+ cacheWriteTokens: usage2?.cache_creation_input_tokens
14582
+ });
14583
+ }
13904
14584
  function parseAnthropicMessages(json) {
13905
14585
  const root = record2(json);
13906
14586
  if (!root || !Array.isArray(root.content)) throw providerError("The provider response had no content blocks.");
13907
- const text2 = root.content.map((block2) => {
14587
+ const finish = anthropicFinish(root.stop_reason);
14588
+ const partial = finish === "length" || finish === "refusal";
14589
+ const content = [];
14590
+ for (const block2 of root.content) {
13908
14591
  const entry = record2(block2);
13909
- return entry?.type === "text" && typeof entry.text === "string" ? entry.text : "";
13910
- }).join("");
13911
- const usage2 = record2(root.usage);
13912
- const tokens = usageFrom(usage2?.input_tokens, usage2?.output_tokens);
13913
- return completed(text2, anthropicFinish(root.stop_reason), tokens);
14592
+ const previous = content.at(-1);
14593
+ if (entry?.type === "text" && typeof entry.text === "string") {
14594
+ if (previous?.type === "text") previous.text += entry.text;
14595
+ else content.push(...textContent(entry.text));
14596
+ } else if (entry?.type === "thinking" && typeof entry.thinking === "string" && entry.thinking !== "") {
14597
+ content.push({ type: "thinking", text: entry.thinking });
14598
+ } else if (entry?.type === "tool_use") {
14599
+ const raw = { id: entry.id, name: entry.name, args: entry.input };
14600
+ content.push(...toolCallParts(partial, [raw]));
14601
+ }
14602
+ }
14603
+ return completed(content, finish, anthropicUsage(record2(root.usage)));
14604
+ }
14605
+ function anthropicAccumulator() {
14606
+ const blocks = createLlmBlockBuilder();
14607
+ let finish = null;
14608
+ let start = null;
14609
+ let delta = null;
14610
+ return {
14611
+ push(event) {
14612
+ const root = record2(event);
14613
+ const key = String(root?.index);
14614
+ switch (root?.type) {
14615
+ case "error":
14616
+ throw providerError(STREAM_ERROR);
14617
+ case "message_start":
14618
+ start = record2(record2(root.message)?.usage);
14619
+ return [];
14620
+ case "message_delta":
14621
+ finish = anthropicFinish(record2(root.delta)?.stop_reason) ?? finish;
14622
+ delta = { ...delta, ...record2(root.usage) };
14623
+ return [];
14624
+ case "content_block_start": {
14625
+ const block2 = record2(root.content_block);
14626
+ if (block2?.type !== "tool_use") return [];
14627
+ return blocks.toolDelta(key, { id: block2.id, name: block2.name });
14628
+ }
14629
+ case "content_block_delta": {
14630
+ const part = record2(root.delta);
14631
+ if (part?.type === "text_delta") return blocks.append("text", key, textField(part.text));
14632
+ if (part?.type === "thinking_delta") return blocks.append("thinking", key, textField(part.thinking));
14633
+ return part?.type === "input_json_delta" ? blocks.toolDelta(key, { fragment: part.partial_json }) : [];
14634
+ }
14635
+ case "content_block_stop":
14636
+ return blocks.end(key);
14637
+ case "message_stop":
14638
+ return blocks.closeAll();
14639
+ default:
14640
+ return [];
14641
+ }
14642
+ },
14643
+ finish: () => completed(blocks.content(isCompletedFinish(finish)), finish, anthropicUsage({ ...start, ...delta }))
14644
+ };
14645
+ }
14646
+ var STREAM_ERROR2 = "The provider reported an error while streaming.";
14647
+ var GEMINI_REFUSALS = /* @__PURE__ */ new Set(["SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY"]);
14648
+ function textField2(value) {
14649
+ return typeof value === "string" ? value : "";
13914
14650
  }
13915
14651
  function geminiParts(parts) {
13916
- return parts.map((part2) => part2.type === "text" ? { text: part2.text } : { inlineData: { mimeType: part2.mimeType, data: part2.data } });
14652
+ return parts.map((part) => {
14653
+ switch (part.type) {
14654
+ case "text":
14655
+ return { text: part.text };
14656
+ case "toolCall":
14657
+ return { functionCall: { name: part.name, args: part.arguments } };
14658
+ case "image":
14659
+ return { inlineData: { mimeType: part.mimeType, data: part.data } };
14660
+ default:
14661
+ throw unsupported5("This provider mapping does not accept this content part.");
14662
+ }
14663
+ });
14664
+ }
14665
+ function geminiResults(results, callOrder) {
14666
+ const ordered = [...results].sort((a, b) => callOrder.indexOf(a.toolCallId ?? "") - callOrder.indexOf(b.toolCallId ?? ""));
14667
+ return {
14668
+ role: "user",
14669
+ parts: ordered.map((result2) => ({ functionResponse: { name: result2.toolName, response: { output: toolResultText(result2) } } }))
14670
+ };
14671
+ }
14672
+ function geminiContents(turns) {
14673
+ const contents = [];
14674
+ let callOrder = [];
14675
+ for (let index = 0; index < turns.length; index += 1) {
14676
+ const turn = turns[index];
14677
+ if (turn.role === "toolResult") {
14678
+ const group = [turn];
14679
+ while (turns[index + 1]?.role === "toolResult") {
14680
+ index += 1;
14681
+ group.push(turns[index]);
14682
+ }
14683
+ contents.push(geminiResults(group, callOrder));
14684
+ continue;
14685
+ }
14686
+ if (turn.role === "assistant") callOrder = callsOf3(turn).map((call) => call.toolCallId);
14687
+ contents.push({ role: turn.role === "assistant" ? "model" : "user", parts: geminiParts(turn.role === "assistant" ? turn.content : plainParts(turn.content)) });
14688
+ }
14689
+ return contents;
14690
+ }
14691
+ function geminiToolConfig(choice) {
14692
+ if (choice === "auto") return { functionCallingConfig: { mode: "AUTO" } };
14693
+ if (choice === "none") return { functionCallingConfig: { mode: "NONE" } };
14694
+ if (choice === "required") return { functionCallingConfig: { mode: "ANY" } };
14695
+ return { functionCallingConfig: { mode: "ANY", allowedFunctionNames: [choice.name] } };
13917
14696
  }
13918
14697
  function buildGemini(endpoint, request, stream) {
13919
14698
  const { system, turns } = splitSystem(request.messages);
13920
- if (turns.length === 0) throw unsupported4("This provider requires at least one user or assistant message.");
14699
+ if (turns.length === 0) throw unsupported5("This provider requires at least one user or assistant message.");
14700
+ const tools = toolsOf(request);
14701
+ if (request.format === "json" && tools.length > 0) throw unsupported5("This provider cannot combine JSON-object output with tool calling.");
13921
14702
  const generationConfig = {};
13922
14703
  if (request.format === "json") generationConfig.responseMimeType = "application/json";
13923
- if (endpoint.maxOutputTokens !== void 0) generationConfig.maxOutputTokens = endpoint.maxOutputTokens;
13924
- const body = {
13925
- contents: turns.map((turn) => ({ role: turn.role === "assistant" ? "model" : "user", parts: geminiParts(turn.content) }))
13926
- };
14704
+ const limit = outputLimit(endpoint, request);
14705
+ if (limit !== void 0) generationConfig.maxOutputTokens = limit;
14706
+ if (request.temperature !== void 0) generationConfig.temperature = request.temperature;
14707
+ const body = { contents: geminiContents(turns) };
13927
14708
  if (system) body.systemInstruction = { parts: [{ text: system }] };
13928
14709
  if (Object.keys(generationConfig).length > 0) body.generationConfig = generationConfig;
14710
+ if (tools.length > 0) {
14711
+ body.tools = [{
14712
+ functionDeclarations: tools.map((tool2) => ({
14713
+ name: tool2.name,
14714
+ ...tool2.description === void 0 ? {} : { description: tool2.description },
14715
+ parametersJsonSchema: parametersOf(tool2)
14716
+ }))
14717
+ }];
14718
+ if (request.toolChoice !== void 0) body.toolConfig = geminiToolConfig(request.toolChoice);
14719
+ }
13929
14720
  return {
13930
14721
  url: `${trimBase(endpoint.baseUrl)}/models/${encodeURIComponent(endpoint.model)}:${stream ? "streamGenerateContent?alt=sse" : "generateContent"}`,
13931
14722
  method: "POST",
@@ -13933,38 +14724,214 @@ function buildGemini(endpoint, request, stream) {
13933
14724
  body: JSON.stringify(body)
13934
14725
  };
13935
14726
  }
13936
- var GEMINI_REFUSALS = /* @__PURE__ */ new Set(["SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY"]);
14727
+ function geminiUsage(value) {
14728
+ const usage2 = record2(value);
14729
+ return usageFrom(usage2?.promptTokenCount, usage2?.candidatesTokenCount, {
14730
+ cacheReadTokens: usage2?.cachedContentTokenCount,
14731
+ reasoningTokens: usage2?.thoughtsTokenCount
14732
+ });
14733
+ }
14734
+ function partsOf(candidate) {
14735
+ const parts = record2(candidate.content)?.parts;
14736
+ return Array.isArray(parts) ? parts.flatMap((part) => {
14737
+ const entry = record2(part);
14738
+ return entry ? [entry] : [];
14739
+ }) : [];
14740
+ }
13937
14741
  function parseGemini(json) {
13938
14742
  const root = record2(json);
13939
- const usage2 = record2(root?.usageMetadata);
13940
- const tokens = usageFrom(usage2?.promptTokenCount, usage2?.candidatesTokenCount);
13941
- const feedback = record2(root?.promptFeedback);
13942
- if (typeof feedback?.blockReason === "string") return finished("", "refusal", tokens);
14743
+ const tokens = geminiUsage(root?.usageMetadata);
14744
+ if (typeof record2(root?.promptFeedback)?.blockReason === "string") return finished([], "refusal", tokens);
13943
14745
  const candidate = record2(Array.isArray(root?.candidates) ? root?.candidates[0] : void 0);
13944
14746
  if (!candidate) throw providerError("The provider response had no candidate.");
13945
- const parts = Array.isArray(record2(candidate.content)?.parts) ? record2(candidate.content).parts : [];
13946
- const text2 = parts.map((part2) => {
13947
- const entry = record2(part2);
13948
- return typeof entry?.text === "string" ? entry.text : "";
13949
- }).join("");
13950
- return completed(text2, geminiFinish(candidate.finishReason), tokens);
14747
+ const finish = geminiFinish(candidate.finishReason);
14748
+ const partial = finish === "length" || finish === "refusal";
14749
+ const content = [];
14750
+ for (const part of partsOf(candidate)) {
14751
+ const call = record2(part.functionCall);
14752
+ if (call) {
14753
+ const raw = { id: call.id, name: call.name, args: call.args };
14754
+ content.push(...toolCallParts(partial, [raw]));
14755
+ continue;
14756
+ }
14757
+ const kind = part.thought === true ? "thinking" : "text";
14758
+ const text2 = textField2(part.text);
14759
+ const previous = content.at(-1);
14760
+ if (text2 === "") continue;
14761
+ if (previous?.type === kind) previous.text += text2;
14762
+ else content.push(...kind === "text" ? textContent(text2) : [{ type: "thinking", text: text2 }]);
14763
+ }
14764
+ return completed(content, finish, tokens);
13951
14765
  }
13952
14766
  function geminiFinish(reason) {
13953
14767
  if (reason === "STOP") return "stop";
13954
14768
  if (reason === "MAX_TOKENS") return "length";
13955
14769
  return typeof reason === "string" && GEMINI_REFUSALS.has(reason) ? "refusal" : null;
13956
14770
  }
14771
+ function geminiAccumulator() {
14772
+ const blocks = createLlmBlockBuilder();
14773
+ let blocked = false;
14774
+ let finish = null;
14775
+ let usage2;
14776
+ let calls = 0;
14777
+ return {
14778
+ push(event) {
14779
+ const root = record2(event);
14780
+ if (root?.error !== void 0) throw providerError(STREAM_ERROR2);
14781
+ usage2 = geminiUsage(root?.usageMetadata) ?? usage2;
14782
+ if (typeof record2(root?.promptFeedback)?.blockReason === "string") blocked = true;
14783
+ const candidate = record2(Array.isArray(root?.candidates) ? root?.candidates[0] : void 0);
14784
+ if (!candidate) return [];
14785
+ const events = [];
14786
+ for (const part of partsOf(candidate)) {
14787
+ const call = record2(part.functionCall);
14788
+ if (call) {
14789
+ calls += 1;
14790
+ events.push(...blocks.toolWhole(`call-${calls}`, { id: call.id, name: call.name, args: call.args }));
14791
+ } else if (part.thought === true) {
14792
+ events.push(...blocks.append("thinking", "thinking", textField2(part.text)));
14793
+ } else {
14794
+ events.push(...blocks.append("text", "text", textField2(part.text)));
14795
+ }
14796
+ }
14797
+ finish = geminiFinish(candidate.finishReason) ?? finish;
14798
+ if (finish !== null) events.push(...blocks.closeAll());
14799
+ return events;
14800
+ },
14801
+ finish: () => blocked ? completed([], "refusal", usage2) : completed(blocks.content(isCompletedFinish(finish)), finish, usage2)
14802
+ };
14803
+ }
14804
+ var STREAM_ERROR3 = "The provider reported an error while streaming.";
14805
+ function textField3(value) {
14806
+ return typeof value === "string" ? value : "";
14807
+ }
14808
+ function openAiContent(parts) {
14809
+ const plain = plainParts(parts);
14810
+ if (!hasImage(plain)) return plain.map((part) => part.type === "text" ? part.text : "").join("");
14811
+ return plain.map((part) => part.type === "text" ? { type: "text", text: part.text } : { type: "image_url", image_url: { url: `data:${part.mimeType};base64,${part.data}` } });
14812
+ }
14813
+ function openAiMessage(message22) {
14814
+ if (message22.role === "toolResult") return { role: "tool", tool_call_id: message22.toolCallId, content: toolResultText(message22) };
14815
+ if (message22.role !== "assistant") return { role: message22.role, content: openAiContent(message22.content) };
14816
+ const calls = callsOf3(message22);
14817
+ const parts = nonCallParts(message22);
14818
+ const entry = { role: "assistant", content: parts.length === 0 && calls.length > 0 ? null : openAiContent(parts) };
14819
+ if (calls.length > 0) {
14820
+ entry.tool_calls = calls.map((call) => ({ id: call.toolCallId, type: "function", function: { name: call.name, arguments: JSON.stringify(call.arguments) } }));
14821
+ }
14822
+ return entry;
14823
+ }
14824
+ function openAiToolChoice(choice) {
14825
+ return typeof choice === "string" ? choice : { type: "function", function: { name: choice.name } };
14826
+ }
14827
+ function buildOpenAiChat(endpoint, request, stream) {
14828
+ const body = {
14829
+ model: endpoint.model,
14830
+ messages: request.messages.map(openAiMessage),
14831
+ stream
14832
+ };
14833
+ if (stream) body.stream_options = { include_usage: true };
14834
+ if (request.format === "json") body.response_format = { type: "json_object" };
14835
+ const limit = outputLimit(endpoint, request);
14836
+ if (limit !== void 0) body.max_tokens = limit;
14837
+ if (request.temperature !== void 0) body.temperature = request.temperature;
14838
+ const tools = toolsOf(request);
14839
+ if (tools.length > 0) {
14840
+ body.tools = tools.map((tool2) => ({
14841
+ type: "function",
14842
+ function: { name: tool2.name, ...tool2.description === void 0 ? {} : { description: tool2.description }, parameters: parametersOf(tool2) }
14843
+ }));
14844
+ if (request.toolChoice !== void 0) body.tool_choice = openAiToolChoice(request.toolChoice);
14845
+ }
14846
+ return {
14847
+ url: `${trimBase(endpoint.baseUrl)}/chat/completions`,
14848
+ method: "POST",
14849
+ headers: { "content-type": "application/json", ...endpoint.headers, ...credentialHeaders(endpoint) },
14850
+ body: JSON.stringify(body)
14851
+ };
14852
+ }
14853
+ function openAiUsage(value) {
14854
+ const usage2 = record2(value);
14855
+ return usageFrom(usage2?.prompt_tokens, usage2?.completion_tokens, {
14856
+ cacheReadTokens: record2(usage2?.prompt_tokens_details)?.cached_tokens,
14857
+ reasoningTokens: record2(usage2?.completion_tokens_details)?.reasoning_tokens
14858
+ });
14859
+ }
14860
+ function reasoningOf(source) {
14861
+ return textField3(source?.reasoning_content) || textField3(source?.reasoning);
14862
+ }
14863
+ function rawCallsOf(message22) {
14864
+ const calls = Array.isArray(message22.tool_calls) ? message22.tool_calls : [];
14865
+ return calls.map((call) => {
14866
+ const entry = record2(call);
14867
+ const fn = record2(entry?.function);
14868
+ return { id: entry?.id, name: fn?.name, args: fn?.arguments };
14869
+ });
14870
+ }
14871
+ function parseOpenAiChat(json) {
14872
+ const root = record2(json);
14873
+ const choice = record2(Array.isArray(root?.choices) ? root?.choices[0] : void 0);
14874
+ const message22 = record2(choice?.message);
14875
+ if (!choice || !message22) throw providerError("The provider response had no completion choice.");
14876
+ const tokens = openAiUsage(root?.usage);
14877
+ if (typeof message22.refusal === "string" && message22.refusal.length > 0) return finished([], "refusal", tokens);
14878
+ const finish = openAiFinish(choice.finish_reason);
14879
+ const content = [];
14880
+ const thinking = reasoningOf(message22);
14881
+ if (thinking !== "") content.push({ type: "thinking", text: thinking });
14882
+ content.push(...textContent(typeof message22.content === "string" ? message22.content : ""));
14883
+ content.push(...toolCallParts(finish === "length" || finish === "refusal", rawCallsOf(message22)));
14884
+ return completed(content, finish, tokens);
14885
+ }
14886
+ function openAiFinish(reason) {
14887
+ if (reason === "stop") return "stop";
14888
+ if (reason === "length") return "length";
14889
+ if (reason === "tool_calls" || reason === "function_call") return "toolUse";
14890
+ return reason === "content_filter" ? "refusal" : null;
14891
+ }
14892
+ function openAiAccumulator() {
14893
+ const blocks = createLlmBlockBuilder();
14894
+ let refused = false;
14895
+ let finish = null;
14896
+ let usage2;
14897
+ return {
14898
+ push(event) {
14899
+ const root = record2(event);
14900
+ if (root?.error !== void 0) throw providerError(STREAM_ERROR3);
14901
+ usage2 = openAiUsage(root?.usage) ?? usage2;
14902
+ const choice = record2(Array.isArray(root?.choices) ? root?.choices[0] : void 0);
14903
+ if (!choice) return [];
14904
+ const delta = record2(choice.delta);
14905
+ if (textField3(delta?.refusal).length > 0) refused = true;
14906
+ const events = [
14907
+ ...blocks.append("thinking", "thinking", reasoningOf(delta)),
14908
+ ...blocks.append("text", "text", textField3(delta?.content))
14909
+ ];
14910
+ const calls = Array.isArray(delta?.tool_calls) ? delta.tool_calls : [];
14911
+ calls.forEach((call, position) => {
14912
+ const entry = record2(call);
14913
+ const fn = record2(entry?.function);
14914
+ events.push(...blocks.toolDelta(String(entry?.index ?? position), { id: entry?.id, name: fn?.name, fragment: fn?.arguments }));
14915
+ });
14916
+ finish = openAiFinish(choice.finish_reason) ?? finish;
14917
+ if (finish !== null) events.push(...blocks.closeAll());
14918
+ return events;
14919
+ },
14920
+ finish: () => refused ? completed([], "refusal", usage2) : completed(blocks.content(isCompletedFinish(finish)), finish, usage2)
14921
+ };
14922
+ }
13957
14923
  function buildLlmProviderRequest(endpoint, request, options = {}) {
13958
14924
  const stream = options.stream === true;
14925
+ const prepared = prepareRequest(endpoint, request);
13959
14926
  switch (endpoint.protocol) {
13960
14927
  case "openai-chat":
13961
- return buildOpenAiChat(endpoint, request, stream);
14928
+ return buildOpenAiChat(endpoint, prepared, stream);
13962
14929
  case "anthropic-messages":
13963
- return buildAnthropicMessages(endpoint, request, stream);
14930
+ return buildAnthropicMessages(endpoint, prepared, stream);
13964
14931
  case "gemini":
13965
- return buildGemini(endpoint, request, stream);
14932
+ return buildGemini(endpoint, prepared, stream);
13966
14933
  default:
13967
- throw unsupported4("Unknown provider protocol.");
14934
+ throw unsupported5("Unknown provider protocol.");
13968
14935
  }
13969
14936
  }
13970
14937
  function parseLlmProviderResponse(protocol, json) {
@@ -13979,90 +14946,6 @@ function parseLlmProviderResponse(protocol, json) {
13979
14946
  throw providerError("Unknown provider protocol.");
13980
14947
  }
13981
14948
  }
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
14949
  function createLlmStreamAccumulator(protocol) {
14067
14950
  switch (protocol) {
14068
14951
  case "openai-chat":
@@ -14177,8 +15060,9 @@ async function readStream(protocol, body, signal, onDelta) {
14177
15060
  try {
14178
15061
  for await (const data of readLlmSseData(body, signal)) {
14179
15062
  if (data === "[DONE]") continue;
14180
- const appended = accumulator.push(parseStreamEvent(data));
14181
- if (appended && !signal.aborted) onDelta?.(appended);
15063
+ const events = accumulator.push(parseStreamEvent(data));
15064
+ if (signal.aborted) continue;
15065
+ for (const event of events) onDelta?.(event);
14182
15066
  }
14183
15067
  } catch (error) {
14184
15068
  if (signal.aborted) throw abortReason(signal);
@@ -14922,6 +15806,7 @@ var PAJA_LLM_CONNECTIONS_STORAGE_KEY = "kehto:paja:llm-connections:v1";
14922
15806
  var MAX_CONNECTIONS = 32;
14923
15807
  var PROTOCOLS = /* @__PURE__ */ new Set(["openai-chat", "anthropic-messages", "gemini"]);
14924
15808
  var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set(["authorization-bearer", "api-key", "x-api-key", "x-goog-api-key"]);
15809
+ var TOOL_CHOICE_ORDER = ["auto", "none", "required", "tool"];
14925
15810
  var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
14926
15811
  function normalizePajaLlmBaseUrl(value) {
14927
15812
  let url;
@@ -14941,6 +15826,11 @@ function normalizePajaLlmBaseUrl(value) {
14941
15826
  function isRecord4(value) {
14942
15827
  return typeof value === "object" && value !== null && !Array.isArray(value);
14943
15828
  }
15829
+ function canonicalToolChoiceModes(tools, requested) {
15830
+ if (!tools) return [];
15831
+ const wanted = new Set(Array.isArray(requested) ? requested : []);
15832
+ return TOOL_CHOICE_ORDER.filter((mode) => mode === "auto" || mode === "none" || wanted.has(mode));
15833
+ }
14944
15834
  function normalizeRecord(input) {
14945
15835
  const text2 = (value) => typeof value === "string" ? value : "";
14946
15836
  const name = text2(input.name).trim();
@@ -14955,6 +15845,7 @@ function normalizeRecord(input) {
14955
15845
  if (!PROTOCOLS.has(protocol)) throw new Error("Unknown provider protocol.");
14956
15846
  if (credentialHeader !== void 0 && !CREDENTIAL_HEADERS.has(credentialHeader)) throw new Error("Unknown credential header.");
14957
15847
  if (!["vault", "session", "none"].includes(credentialStorage)) throw new Error("Unknown credential storage.");
15848
+ const tools = input.tools === true;
14958
15849
  const record3 = {
14959
15850
  id,
14960
15851
  name,
@@ -14964,6 +15855,8 @@ function normalizeRecord(input) {
14964
15855
  model,
14965
15856
  images: input.images === true,
14966
15857
  json: input.json === true,
15858
+ tools,
15859
+ toolChoiceModes: Object.freeze(canonicalToolChoiceModes(tools, input.toolChoiceModes)),
14967
15860
  credentialStorage,
14968
15861
  ...credentialHeader ? { credentialHeader } : {}
14969
15862
  };
@@ -15035,29 +15928,59 @@ function describePajaLlmRoute(record3) {
15035
15928
  return `Paja (this browser) \u2192 ${label}`;
15036
15929
  }
15037
15930
  function toConnection(record3) {
15038
- return { id: record3.id, name: record3.name, model: record3.model, route: describePajaLlmRoute(record3), images: record3.images, json: record3.json };
15931
+ const tools = record3.tools === true;
15932
+ return {
15933
+ id: record3.id,
15934
+ name: record3.name,
15935
+ model: record3.model,
15936
+ route: describePajaLlmRoute(record3),
15937
+ images: record3.images,
15938
+ json: record3.json,
15939
+ tools,
15940
+ toolChoiceModes: tools ? canonicalToolChoiceModes(true, record3.toolChoiceModes) : []
15941
+ };
15039
15942
  }
15040
15943
  function meets(record3, requirements2) {
15041
15944
  if (requirements2.model !== void 0 && requirements2.model !== record3.model) return false;
15042
15945
  if (requirements2.images === true && !record3.images) return false;
15946
+ if (requirements2.tools === true && record3.tools !== true) return false;
15043
15947
  return !(requirements2.json === true && !record3.json);
15044
15948
  }
15045
15949
  function describeRequirements(requirements2) {
15046
15950
  const parts = [
15047
15951
  requirements2.model ? `model ${requirements2.model}` : "any model",
15048
15952
  requirements2.images ? "image input" : null,
15049
- requirements2.json ? "JSON output" : null
15050
- ].filter((part2) => part2 !== null);
15953
+ requirements2.json ? "JSON output" : null,
15954
+ requirements2.tools ? "tool calling" : null
15955
+ ].filter((part) => part !== null);
15051
15956
  return parts.join(", ");
15052
15957
  }
15053
15958
  function countCharacters(request) {
15054
15959
  let total = 0;
15055
- for (const message3 of request.messages) for (const part2 of message3.content) total += part2.type === "text" ? part2.text.length : 0;
15960
+ for (const message3 of request.messages) {
15961
+ for (const part of message3.content) {
15962
+ if (part.type === "text") total += part.text.length;
15963
+ else if (part.type === "toolCall") total += JSON.stringify(part.arguments).length;
15964
+ }
15965
+ }
15966
+ for (const tool2 of request.tools ?? []) total += JSON.stringify(tool2).length;
15056
15967
  return total;
15057
15968
  }
15969
+ function countToolResults(request) {
15970
+ return request.messages.filter((message3) => message3.role === "toolResult").length;
15971
+ }
15058
15972
  function createPajaLlmHost(options) {
15059
15973
  const { store: store2, vault, confirm, getIdentity } = options;
15060
15974
  const provider = options.provider ?? createHttpLlmProvider({ stream: true });
15975
+ function endpointFor(record3, credential) {
15976
+ return {
15977
+ protocol: record3.protocol,
15978
+ baseUrl: record3.baseUrl,
15979
+ model: record3.model,
15980
+ ...credential === void 0 ? {} : { credential },
15981
+ ...record3.credentialHeader ? { credentialHeader: record3.credentialHeader } : {}
15982
+ };
15983
+ }
15061
15984
  async function ensureCredential(record3, signal) {
15062
15985
  if (record3.credentialStorage === "none") return void 0;
15063
15986
  const existing = vault.getCredential(record3.id);
@@ -15103,6 +16026,7 @@ function createPajaLlmHost(options) {
15103
16026
  const signal = prompt?.signal;
15104
16027
  const record3 = store2.get(connection.id);
15105
16028
  if (!record3) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
16029
+ buildLlmProviderRequest(endpointFor(record3), request, { stream: true });
15106
16030
  await ensureCredential(record3, signal);
15107
16031
  if (signal?.aborted) return false;
15108
16032
  return confirm({
@@ -15116,21 +16040,17 @@ function createPajaLlmHost(options) {
15116
16040
  messages: request.messages.length,
15117
16041
  characters: countCharacters(request),
15118
16042
  images: countLlmImages(request.messages),
16043
+ tools: (request.tools ?? []).map((tool2) => tool2.name),
16044
+ toolResults: countToolResults(request),
15119
16045
  format: request.format ?? "text",
15120
- warning: "The prompt text and images below leave this device for the provider named in the route. Provider charges and retention follow that service's terms."
16046
+ warning: "The prompt text, images, tool definitions and tool results disclosed here leave this device for the provider named in the route. Provider charges and retention follow that service's terms."
15121
16047
  });
15122
16048
  },
15123
16049
  async generate(_context, connection, request, hooks) {
15124
16050
  const record3 = store2.get(connection.id);
15125
16051
  if (!record3) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
15126
16052
  const credential = await ensureCredential(record3);
15127
- return provider({
15128
- protocol: record3.protocol,
15129
- baseUrl: record3.baseUrl,
15130
- model: record3.model,
15131
- ...credential === void 0 ? {} : { credential },
15132
- ...record3.credentialHeader ? { credentialHeader: record3.credentialHeader } : {}
15133
- }, request, hooks.signal, (text2) => hooks.onDelta(text2));
16053
+ return provider(endpointFor(record3, credential), request, hooks.signal, (event) => hooks.onDelta(event));
15134
16054
  },
15135
16055
  subscribe(listener) {
15136
16056
  const stopStore = store2.subscribe(listener);
@@ -15403,7 +16323,7 @@ function createChooserDialog() {
15403
16323
  choose(candidates, context) {
15404
16324
  if (settle7) finish(null);
15405
16325
  if (context.signal?.aborted) return Promise.resolve(null);
15406
- 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(", ");
16326
+ const wanted = [context.requirements.model ? `model ${context.requirements.model}` : null, context.requirements.images ? "image input" : null, context.requirements.json ? "JSON output" : null, context.requirements.tools ? "tool calling" : null].filter(Boolean).join(", ");
15407
16327
  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.`;
15408
16328
  select2.replaceChildren(...candidates.map((record3) => {
15409
16329
  const option = document.createElement("option");
@@ -15448,10 +16368,13 @@ function readForm() {
15448
16368
  const remember = byId("paja-llm-remember", HTMLInputElement);
15449
16369
  const images = byId("paja-llm-images", HTMLInputElement);
15450
16370
  const json = byId("paja-llm-json", HTMLInputElement);
16371
+ const tools = byId("paja-llm-tools", HTMLInputElement);
16372
+ const toolRequired = byId("paja-llm-tool-required", HTMLInputElement);
16373
+ const toolNamed = byId("paja-llm-tool-named", HTMLInputElement);
15451
16374
  const list = byId("paja-llm-connections", HTMLElement);
15452
16375
  const status = byId("paja-llm-status", HTMLElement);
15453
16376
  const lock = byId("paja-llm-vault-lock", HTMLButtonElement);
15454
- if (!form || !preset || !name || !baseUrl || !model || !modelField || !modelSelect || !modelSelectField || !modelStatus || !examples || !credential || !remember || !images || !json || !list || !status || !lock) return null;
16377
+ if (!form || !preset || !name || !baseUrl || !model || !modelField || !modelSelect || !modelSelectField || !modelStatus || !examples || !credential || !remember || !images || !json || !tools || !toolRequired || !toolNamed || !list || !status || !lock) return null;
15455
16378
  return {
15456
16379
  form,
15457
16380
  preset,
@@ -15467,6 +16390,9 @@ function readForm() {
15467
16390
  remember,
15468
16391
  images,
15469
16392
  json,
16393
+ tools,
16394
+ toolRequired,
16395
+ toolNamed,
15470
16396
  list,
15471
16397
  status,
15472
16398
  lock,
@@ -15598,7 +16524,7 @@ function installPajaLlmPanel(options) {
15598
16524
  label.className = "llm-connection-label";
15599
16525
  const tier = record3.credentialStorage === "vault" ? vault.isUnlocked() ? "key unlocked" : "key encrypted, locked" : record3.credentialStorage === "session" ? vault.getCredential(record3.id) ? "key for this session" : "key missing" : "no key";
15600
16526
  label.textContent = `${record3.name} \xB7 ${record3.model} \xB7 ${new URL(record3.baseUrl).origin} \xB7 ${tier}`;
15601
- label.title = `${record3.protocol}${record3.images ? " \xB7 images" : ""}${record3.json ? " \xB7 json" : ""}`;
16527
+ label.title = `${record3.protocol}${record3.images ? " \xB7 images" : ""}${record3.json ? " \xB7 json" : ""}${record3.tools ? " \xB7 tools" : ""}`;
15602
16528
  const remove = document.createElement("button");
15603
16529
  remove.type = "button";
15604
16530
  remove.textContent = "Remove";
@@ -15626,6 +16552,10 @@ function installPajaLlmPanel(options) {
15626
16552
  renderList();
15627
16553
  options.onChange?.();
15628
16554
  }
16555
+ function toolChoiceModes(form) {
16556
+ if (!form.tools.checked) return [];
16557
+ return [...form.toolRequired.checked ? ["required"] : [], ...form.toolNamed.checked ? ["tool"] : []];
16558
+ }
15629
16559
  async function submit(event) {
15630
16560
  event.preventDefault();
15631
16561
  if (!elements) return;
@@ -15648,6 +16578,8 @@ function installPajaLlmPanel(options) {
15648
16578
  model,
15649
16579
  images: elements.images.checked,
15650
16580
  json: elements.json.checked,
16581
+ tools: elements.tools.checked,
16582
+ toolChoiceModes: toolChoiceModes(elements),
15651
16583
  credentialStorage: storage,
15652
16584
  ...preset?.credentialHeader ? { credentialHeader: preset.credentialHeader } : {}
15653
16585
  };
@@ -15679,6 +16611,12 @@ function installPajaLlmPanel(options) {
15679
16611
  const onSubmit = (event) => {
15680
16612
  void submit(event);
15681
16613
  };
16614
+ const onTools = () => {
16615
+ for (const option of [elements.toolRequired, elements.toolNamed]) {
16616
+ option.disabled = !elements.tools.checked;
16617
+ if (!elements.tools.checked) option.checked = false;
16618
+ }
16619
+ };
15682
16620
  const onLock = () => {
15683
16621
  vault.lock();
15684
16622
  renderList();
@@ -15688,12 +16626,15 @@ function installPajaLlmPanel(options) {
15688
16626
  elements.preset.addEventListener("change", onPreset);
15689
16627
  elements.baseUrl.addEventListener("change", onBaseUrl);
15690
16628
  elements.form.addEventListener("submit", onSubmit);
16629
+ elements.tools.addEventListener("change", onTools);
15691
16630
  elements.lock.addEventListener("click", onLock);
16631
+ onTools();
15692
16632
  disposers.push(() => {
15693
16633
  modelListing?.abort();
15694
16634
  elements.preset.removeEventListener("change", onPreset);
15695
16635
  elements.baseUrl.removeEventListener("change", onBaseUrl);
15696
16636
  elements.form.removeEventListener("submit", onSubmit);
16637
+ elements.tools.removeEventListener("change", onTools);
15697
16638
  elements.lock.removeEventListener("click", onLock);
15698
16639
  });
15699
16640
  renderList();
@@ -16047,9 +16988,13 @@ function adaptHooks(shellHooks, deps) {
16047
16988
  shellSecretPersistence: createShellSecretPersistence(),
16048
16989
  guidPersistence: createGuidPersistence(),
16049
16990
  onAclCheck: shellHooks.onAclCheck,
16991
+ firewallPersistence: shellHooks.firewallPersistence,
16992
+ onFirewallEvent: shellHooks.onFirewallEvent,
16993
+ getFocusContext: shellHooks.getFocusContext,
16050
16994
  onHashMismatch: shellHooks.onHashMismatch,
16051
16995
  services: shellHooks.services,
16052
- getConfigOverrides: shellHooks.getConfigOverrides
16996
+ getConfigOverrides: shellHooks.getConfigOverrides,
16997
+ aclDefaultPolicy: shellHooks.aclDefaultPolicy
16053
16998
  };
16054
16999
  }
16055
17000
  var registry = /* @__PURE__ */ new Map();
@@ -16995,6 +17940,7 @@ function hasNappletFramePolicy(doc) {
16995
17940
  return [...doc.querySelectorAll('meta[http-equiv="Content-Security-Policy" i]')].some((meta) => meta.content.split(";").some((directive) => directive.trim() === NAPPLET_FRAME_POLICY));
16996
17941
  }
16997
17942
  var NAPPLET_HELLO = "napplet.hello";
17943
+ var MAX_DEFERRED_MESSAGES = 1024;
16998
17944
  function reportUnrouted(hooks, event, reason) {
16999
17945
  if (!hooks.onUnroutedMessage) return;
17000
17946
  const data = event.data;
@@ -17010,8 +17956,18 @@ var REVOCATION_DETAIL = {
17010
17956
  "invalid-hello": "napplet.hello did not carry exactly one MessagePort",
17011
17957
  "second-load": "The frame loaded a second document (navigation or reload)",
17012
17958
  "port-closed": "The bound NIP-5D port closed or failed",
17959
+ "deferred-overflow": `More than ${MAX_DEFERRED_MESSAGES} deferred messages were waiting for this frame`,
17013
17960
  host: "The host revoked the napplet binding"
17014
17961
  };
17962
+ function decideDispatch(hooks, windowId, envelope) {
17963
+ if (!hooks.filterNappletMessage) return "dispatch";
17964
+ try {
17965
+ const decision = hooks.filterNappletMessage(windowId, envelope);
17966
+ return decision === "dispatch" || decision === "defer" ? decision : "drop";
17967
+ } catch {
17968
+ return "drop";
17969
+ }
17970
+ }
17015
17971
  function isHello(data) {
17016
17972
  return typeof data === "object" && data !== null && data.type === NAPPLET_HELLO;
17017
17973
  }
@@ -17024,7 +17980,29 @@ function warnWithoutFramePolicy(frame) {
17024
17980
  `[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>.`
17025
17981
  );
17026
17982
  }
17027
- function createNip5dTransport({ hooks, runtime, state: shellReadyState }) {
17983
+ function observeFrameLoads(frame, onSecondLoad) {
17984
+ warnWithoutFramePolicy(frame);
17985
+ let loads = 0;
17986
+ const onLoad = () => {
17987
+ loads += 1;
17988
+ if (loads > 1) onSecondLoad();
17989
+ };
17990
+ frame.addEventListener("load", onLoad);
17991
+ return () => frame.removeEventListener("load", onLoad);
17992
+ }
17993
+ function sessionContext({ hooks, runtime, state }, windowId, binding) {
17994
+ return {
17995
+ hooks,
17996
+ origin: binding.origin,
17997
+ runtime,
17998
+ state,
17999
+ sourceRegistrationId: binding.registrationId,
18000
+ sourceWindow: binding.sourceWindow,
18001
+ windowId
18002
+ };
18003
+ }
18004
+ function createNip5dTransport(options) {
18005
+ const { hooks, runtime, state: shellReadyState } = options;
17028
18006
  const bindings = /* @__PURE__ */ new Map();
17029
18007
  function currentBinding(windowId) {
17030
18008
  const binding = bindings.get(windowId);
@@ -17058,22 +18036,36 @@ function createNip5dTransport({ hooks, runtime, state: shellReadyState }) {
17058
18036
  hooks.onNappletMessage?.(windowId, envelope);
17059
18037
  } catch {
17060
18038
  }
17061
- const context = {
17062
- hooks,
17063
- origin: binding.origin,
17064
- runtime,
17065
- state: shellReadyState,
17066
- sourceRegistrationId: binding.registrationId,
17067
- sourceWindow: binding.sourceWindow,
17068
- windowId
17069
- };
18039
+ const context = sessionContext(options, windowId, binding);
17070
18040
  if (!registerSourceSession(context)) return;
17071
18041
  if (envelope.type === "shell.ready") {
17072
18042
  handleShellReady(context);
17073
18043
  return;
17074
18044
  }
18045
+ const decision = decideDispatch(hooks, windowId, envelope);
18046
+ if (decision === "drop" || currentBinding(windowId) !== binding) return;
18047
+ if (decision === "defer" || binding.deferred.length > 0) {
18048
+ if (binding.deferred.length >= MAX_DEFERRED_MESSAGES) {
18049
+ revokeNapplet(windowId, "deferred-overflow");
18050
+ return;
18051
+ }
18052
+ binding.deferred.push(envelope);
18053
+ return;
18054
+ }
17075
18055
  runtime.handleMessage(windowId, envelope);
17076
18056
  }
18057
+ function releaseDeferred(windowId) {
18058
+ const binding = currentBinding(windowId);
18059
+ if (!binding) return 0;
18060
+ let released = 0;
18061
+ while (binding.deferred.length > 0 && currentBinding(windowId) === binding) {
18062
+ const envelope = binding.deferred.shift();
18063
+ if (!registerSourceSession(sessionContext(options, windowId, binding))) continue;
18064
+ runtime.handleMessage(windowId, envelope);
18065
+ released += 1;
18066
+ }
18067
+ return released;
18068
+ }
17077
18069
  function bindPort(windowId, sourceWindow, origin, port) {
17078
18070
  if (!originRegistry.bindPort(windowId, port)) {
17079
18071
  port.close();
@@ -17084,7 +18076,8 @@ function createNip5dTransport({ hooks, runtime, state: shellReadyState }) {
17084
18076
  port,
17085
18077
  sourceWindow,
17086
18078
  origin,
17087
- registrationId: originRegistry.getRegistrationId(sourceWindow) ?? 0
18079
+ registrationId: originRegistry.getRegistrationId(sourceWindow) ?? 0,
18080
+ deferred: []
17088
18081
  };
17089
18082
  bindings.set(windowId, binding);
17090
18083
  const isCurrent = () => currentBinding(windowId) === binding;
@@ -17126,14 +18119,7 @@ function createNip5dTransport({ hooks, runtime, state: shellReadyState }) {
17126
18119
  bindPort(windowId, sourceWindow, event.origin, ports[0]);
17127
18120
  }
17128
18121
  function observeFrame(frame, windowId) {
17129
- warnWithoutFramePolicy(frame);
17130
- let loads = 0;
17131
- const onLoad = () => {
17132
- loads += 1;
17133
- if (loads > 1) revokeNapplet(windowId, "second-load");
17134
- };
17135
- frame.addEventListener("load", onLoad);
17136
- return () => frame.removeEventListener("load", onLoad);
18122
+ return observeFrameLoads(frame, () => revokeNapplet(windowId, "second-load"));
17137
18123
  }
17138
18124
  function destroy() {
17139
18125
  for (const [windowId, binding] of bindings) {
@@ -17142,7 +18128,7 @@ function createNip5dTransport({ hooks, runtime, state: shellReadyState }) {
17142
18128
  }
17143
18129
  bindings.clear();
17144
18130
  }
17145
- return { handleMessage, revokeNapplet, observeFrame, destroy };
18131
+ return { handleMessage, revokeNapplet, releaseDeferred, observeFrame, destroy };
17146
18132
  }
17147
18133
  function createShellBridge(hooks) {
17148
18134
  const shellReadyState = createShellReadyState();
@@ -17189,6 +18175,7 @@ function createShellBridge(hooks) {
17189
18175
  },
17190
18176
  observeFrame: transport.observeFrame,
17191
18177
  revokeNapplet: transport.revokeNapplet,
18178
+ releaseDeferred: transport.releaseDeferred,
17192
18179
  get runtime() {
17193
18180
  return runtime;
17194
18181
  }
@@ -17281,7 +18268,7 @@ function createIntentUriNormalizer() {
17281
18268
  relays.push(relay);
17282
18269
  } else if (type === 2) {
17283
18270
  if (pubkey2 !== void 0 || value.length !== 32) fail2("Intent URI fragment has an invalid pubkey");
17284
- pubkey2 = value.map((part2) => part2.toString(16).padStart(2, "0")).join("");
18271
+ pubkey2 = value.map((part) => part.toString(16).padStart(2, "0")).join("");
17285
18272
  } else if (type === 3) {
17286
18273
  if (kind !== void 0 || value.length !== 4) fail2("Intent URI fragment has an invalid kind");
17287
18274
  kind = (value[0] << 24 >>> 0 | value[1] << 16 | value[2] << 8 | value[3]) >>> 0;
@@ -18315,7 +19302,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
18315
19302
  (msg) => ({ notificationId: fieldOrThrow(msg, "notificationId", "notify.send.result missing notificationId") })
18316
19303
  ),
18317
19304
  dismiss: (notificationId) => fire({ type: "notify.dismiss", notificationId }),
18318
- badge: (count) => fire({ type: "notify.badge", count }),
19305
+ badge: (count2) => fire({ type: "notify.badge", count: count2 }),
18319
19306
  registerChannel: (channel2) => fire({ type: "notify.channel.register", ...channel2 }),
18320
19307
  requestPermission: (channel2) => request(
18321
19308
  { type: "notify.permission.request", ...channel2 ? { channel: channel2 } : {} },
@@ -18912,6 +19899,25 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
18912
19899
  };
18913
19900
  }
18914
19901
  function makeLlm() {
19902
+ const asDelta = (msg, requestId, expected) => {
19903
+ const { sequence, event, block: block2, blockIndex, text: text2, toolCallId, name } = msg;
19904
+ if (sequence !== expected) return null;
19905
+ if (event !== "start" && event !== "delta" && event !== "end") return null;
19906
+ if (block2 !== "text" && block2 !== "thinking" && block2 !== "toolCall") return null;
19907
+ if (typeof blockIndex !== "number" || !Number.isInteger(blockIndex) || blockIndex < 0) return null;
19908
+ if (event === "delta" ? typeof text2 !== "string" : text2 !== void 0) return null;
19909
+ const identified = event === "start" && block2 === "toolCall";
19910
+ const validId = typeof toolCallId === "string" && toolCallId.length > 0;
19911
+ const validName = typeof name === "string" && name.length > 0;
19912
+ if (identified ? !validId || !validName : toolCallId !== void 0 || name !== void 0) return null;
19913
+ const delta = { requestId, sequence: expected, event, block: block2, blockIndex };
19914
+ if (text2 !== void 0) delta.text = text2;
19915
+ if (identified) {
19916
+ delta.toolCallId = toolCallId;
19917
+ delta.name = name;
19918
+ }
19919
+ return delta;
19920
+ };
18915
19921
  const asFailure = (value) => {
18916
19922
  if (!value || typeof value !== "object") return null;
18917
19923
  const { code, message: message3 } = value;
@@ -18930,9 +19936,10 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
18930
19936
  const msg = event.data;
18931
19937
  if (typeof msg !== "object" || msg === null) return;
18932
19938
  if (type === "llm.generate" && msg.type === "llm.delta" && msg.requestId === requestId) {
18933
- if (msg.sequence !== nextSequence || typeof msg.text !== "string") return;
19939
+ const delta = asDelta(msg, requestId, nextSequence);
19940
+ if (!delta) return;
18934
19941
  nextSequence += 1;
18935
- options.onDelta?.({ requestId, sequence: msg.sequence, text: msg.text });
19942
+ options.onDelta?.(delta);
18936
19943
  return;
18937
19944
  }
18938
19945
  if (msg.type !== `${type}.result` || msg.id !== requestId) return;
@@ -20447,9 +21454,9 @@ function createNostrCvmTransport(options = {}) {
20447
21454
  }
20448
21455
  function releaseRelays(relays) {
20449
21456
  for (const url of relays) {
20450
- const count = (relayRefcount.get(url) ?? 0) - 1;
20451
- if (count <= 0) relayRefcount.delete(url);
20452
- else relayRefcount.set(url, count);
21457
+ const count2 = (relayRefcount.get(url) ?? 0) - 1;
21458
+ if (count2 <= 0) relayRefcount.delete(url);
21459
+ else relayRefcount.set(url, count2);
20453
21460
  }
20454
21461
  refreshSubscription();
20455
21462
  }
@@ -22179,12 +23186,12 @@ async function countLive(pool, relayUrls2, filters) {
22179
23186
  }),
22180
23187
  timedOut
22181
23188
  ]);
22182
- const count = await Promise.race([
23189
+ const count2 = await Promise.race([
22183
23190
  relay.count(filters, { id: null }),
22184
23191
  timedOut
22185
23192
  ]);
22186
- if (!Number.isSafeInteger(count) || count < 0) throw new Error("invalid count");
22187
- return { count, relay: relayUrl2 };
23193
+ if (!Number.isSafeInteger(count2) || count2 < 0) throw new Error("invalid count");
23194
+ return { count: count2, relay: relayUrl2 };
22188
23195
  } catch (error) {
22189
23196
  failure4 = error;
22190
23197
  } finally {
@@ -22651,11 +23658,11 @@ function matchingCachedProfiles(profiles, filters) {
22651
23658
  const matched = /* @__PURE__ */ new Map();
22652
23659
  for (const filter of filters) {
22653
23660
  const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
22654
- let count = 0;
23661
+ let count2 = 0;
22655
23662
  for (const entry of readyProfiles) {
22656
23663
  if (!matchesAnyFilter2(entry.event, [filter])) continue;
22657
- if (limit !== void 0 && count >= limit) continue;
22658
- count += 1;
23664
+ if (limit !== void 0 && count2 >= limit) continue;
23665
+ count2 += 1;
22659
23666
  if (!matched.has(entry.event.id)) matched.set(entry.event.id, entry);
22660
23667
  }
22661
23668
  }
@@ -23709,9 +24716,9 @@ var BrowserWebrtcController = class {
23709
24716
  if (session.state !== "closed" || event.type === "closed" || event.type === "state") session.context.emit(event);
23710
24717
  }
23711
24718
  windowSessionCount(windowId) {
23712
- let count = 0;
23713
- for (const session of this.sessions.values()) if (session.windowId === windowId) count += 1;
23714
- return count;
24719
+ let count2 = 0;
24720
+ for (const session of this.sessions.values()) if (session.windowId === windowId) count2 += 1;
24721
+ return count2;
23715
24722
  }
23716
24723
  };
23717
24724
  function validateOpenRequest(request) {
@@ -24352,8 +25359,8 @@ async function createPajaBrowserFsBackend(options) {
24352
25359
  });
24353
25360
  },
24354
25361
  async watch(windowId, path, watchOptions, onChange) {
24355
- const count = [...backendWatches].filter((watch) => watch.windowId === windowId && !watch.closed).length + [...pendingBackendWatches].filter((watch) => watch.windowId === windowId && !watch.closed).length;
24356
- if (count >= MAX_WATCH_COUNT) throw new FsServiceError("policy-denied");
25362
+ const count2 = [...backendWatches].filter((watch) => watch.windowId === windowId && !watch.closed).length + [...pendingBackendWatches].filter((watch) => watch.windowId === windowId && !watch.closed).length;
25363
+ if (count2 >= MAX_WATCH_COUNT) throw new FsServiceError("policy-denied");
24357
25364
  const pending = { windowId, closed: false };
24358
25365
  pendingBackendWatches.add(pending);
24359
25366
  try {
@@ -25203,7 +26210,7 @@ function createPajaRelayEventCounter(onChange) {
25203
26210
  count: relay?.count ?? 0,
25204
26211
  readCount: box?.reads.get(key) ?? 0,
25205
26212
  configured: isConfigured,
25206
- kinds: [...relay?.kinds.entries() ?? []].sort(([left], [right]) => left - right).map(([kind, count]) => ({ kind, count }))
26213
+ kinds: [...relay?.kinds.entries() ?? []].sort(([left], [right]) => left - right).map(([kind, count2]) => ({ kind, count: count2 }))
25207
26214
  });
25208
26215
  };
25209
26216
  for (const url of configured) push(url, true);
@@ -25216,7 +26223,7 @@ function createPajaRelayEventCounter(onChange) {
25216
26223
  reason: spec.reason,
25217
26224
  ...spec.origin ? { origin: spec.origin } : {},
25218
26225
  count: box?.count ?? 0,
25219
- authors: [...box?.authors.entries() ?? []].sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey)).map(([pubkey2, count]) => ({ pubkey: pubkey2, count })),
26226
+ authors: [...box?.authors.entries() ?? []].sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey)).map(([pubkey2, count2]) => ({ pubkey: pubkey2, count: count2 })),
25220
26227
  relays,
25221
26228
  ...relays.length === 0 && spec.emptyNote ? { emptyNote: spec.emptyNote } : {}
25222
26229
  });
@@ -25276,13 +26283,13 @@ function installPajaEventCounterReset(counter) {
25276
26283
  function renderBoxAuthors(authors) {
25277
26284
  const row = document.createElement("div");
25278
26285
  row.className = "event-box-authors";
25279
- row.replaceChildren(...authors.map(({ pubkey: pubkey2, count }) => {
26286
+ row.replaceChildren(...authors.map(({ pubkey: pubkey2, count: count2 }) => {
25280
26287
  const chip = document.createElement("span");
25281
26288
  chip.className = "event-author";
25282
26289
  chip.dataset.authorPubkey = pubkey2;
25283
- chip.dataset.authorReads = String(count);
25284
- chip.textContent = count > 1 ? `${shortPubkey(pubkey2)} \xB7 ${count}` : shortPubkey(pubkey2);
25285
- chip.title = count > 1 ? `${pubkey2} \xB7 routed ${count} reads into this box` : `${pubkey2} \xB7 routed 1 read into this box`;
26290
+ chip.dataset.authorReads = String(count2);
26291
+ chip.textContent = count2 > 1 ? `${shortPubkey(pubkey2)} \xB7 ${count2}` : shortPubkey(pubkey2);
26292
+ chip.title = count2 > 1 ? `${pubkey2} \xB7 routed ${count2} reads into this box` : `${pubkey2} \xB7 routed 1 read into this box`;
25286
26293
  return chip;
25287
26294
  }));
25288
26295
  return row;
@@ -25357,7 +26364,7 @@ function renderPajaEventKindCounts(counter, inventory) {
25357
26364
  if (relay.kinds.length > 0) {
25358
26365
  const kinds = document.createElement("div");
25359
26366
  kinds.className = "event-kinds";
25360
- kinds.replaceChildren(...relay.kinds.map(({ kind, count }) => {
26367
+ kinds.replaceChildren(...relay.kinds.map(({ kind, count: count2 }) => {
25361
26368
  const kindRow = document.createElement("div");
25362
26369
  kindRow.className = "event-row";
25363
26370
  kindRow.dataset.eventKind = String(kind);
@@ -25369,7 +26376,7 @@ function renderPajaEventKindCounts(counter, inventory) {
25369
26376
  separator.textContent = "-";
25370
26377
  const countCell = document.createElement("span");
25371
26378
  countCell.className = "event-count";
25372
- countCell.textContent = String(count);
26379
+ countCell.textContent = String(count2);
25373
26380
  kindRow.append(kindCell, separator, countCell);
25374
26381
  return kindRow;
25375
26382
  }));
@@ -26669,7 +27676,8 @@ function describeConfirmation(request) {
26669
27676
  `Version: ${request.napplet.aggregateHash}`,
26670
27677
  `Route: ${request.route}`,
26671
27678
  `Model: ${request.model}`,
26672
- `Disclosed: ${request.messages} message(s), ${request.characters} characters, ${request.images} image(s); ${request.format} output`,
27679
+ `Disclosed: ${request.messages} message(s), ${request.characters} characters, ${request.images} image(s), ${request.toolResults} tool result(s); ${request.format} output`,
27680
+ `Tools offered: ${request.tools.length === 0 ? "none" : `${request.tools.length} (${request.tools.join(", ")})`}`,
26673
27681
  request.warning
26674
27682
  );
26675
27683
  }
@@ -26780,7 +27788,7 @@ function recordPajaConfirmation(state, request, allowed2, signerApprovalMode) {
26780
27788
  windowId: request.windowId,
26781
27789
  dTag: request.napplet.dTag,
26782
27790
  aggregateHash: request.napplet.aggregateHash,
26783
- ...request.action === "llm" ? { connection: request.connection, model: request.model, route: request.route, messages: request.messages, images: request.images, format: request.format } : { requirements: request.requirements }
27791
+ ...request.action === "llm" ? { connection: request.connection, model: request.model, route: request.route, messages: request.messages, images: request.images, tools: request.tools.length, toolResults: request.toolResults, format: request.format } : { requirements: request.requirements }
26784
27792
  });
26785
27793
  return;
26786
27794
  }
@@ -28284,11 +29292,11 @@ function strictDecode(value, label) {
28284
29292
  function parseOuterQuery(search) {
28285
29293
  const fields = /* @__PURE__ */ Object.create(null);
28286
29294
  if (!search) return fields;
28287
- for (const part2 of search.slice(1).split("&")) {
28288
- const equal = part2.indexOf("=");
29295
+ for (const part of search.slice(1).split("&")) {
29296
+ const equal = part.indexOf("=");
28289
29297
  if (equal <= 0) fail("Paja intent link fields must be name=value");
28290
- const name = strictDecode(part2.slice(0, equal), "a field name");
28291
- const value = strictDecode(part2.slice(equal + 1), `the ${name || "unnamed"} field`);
29298
+ const name = strictDecode(part.slice(0, equal), "a field name");
29299
+ const value = strictDecode(part.slice(equal + 1), `the ${name || "unnamed"} field`);
28292
29300
  if (!name || hasOwn(fields, name)) fail("Paja intent link field names must be unique after decoding");
28293
29301
  Object.defineProperty(fields, name, { value, enumerable: true, configurable: true });
28294
29302
  }
@@ -28296,11 +29304,11 @@ function parseOuterQuery(search) {
28296
29304
  }
28297
29305
  function rawOuterValue(search, expectedName) {
28298
29306
  if (!search) return void 0;
28299
- for (const part2 of search.slice(1).split("&")) {
28300
- const equal = part2.indexOf("=");
29307
+ for (const part of search.slice(1).split("&")) {
29308
+ const equal = part.indexOf("=");
28301
29309
  if (equal <= 0) continue;
28302
29310
  try {
28303
- if (decodeURIComponent(part2.slice(0, equal)) === expectedName) return part2.slice(equal + 1);
29311
+ if (decodeURIComponent(part.slice(0, equal)) === expectedName) return part.slice(equal + 1);
28304
29312
  } catch {
28305
29313
  }
28306
29314
  }
@@ -29286,9 +30294,9 @@ function createPajaNotifyController(options) {
29286
30294
  active.set(key, { element: article, emit });
29287
30295
  center.prepend(article);
29288
30296
  };
29289
- const setBadge = (windowId, count) => {
30297
+ const setBadge = (windowId, count2) => {
29290
30298
  const current = badges.get(windowId);
29291
- if (count === 0) {
30299
+ if (count2 === 0) {
29292
30300
  current?.remove();
29293
30301
  badges.delete(windowId);
29294
30302
  return;
@@ -29296,7 +30304,7 @@ function createPajaNotifyController(options) {
29296
30304
  const badge = current ?? document2.createElement("span");
29297
30305
  badge.className = "paja-notification-badge";
29298
30306
  badge.dataset.windowId = windowId;
29299
- badge.textContent = `${originLabel(options.getIdentity, windowId)}: ${Math.min(count, 9999)}`;
30307
+ badge.textContent = `${originLabel(options.getIdentity, windowId)}: ${Math.min(count2, 9999)}`;
29300
30308
  if (!current) badgeCenter.append(badge);
29301
30309
  badges.set(windowId, badge);
29302
30310
  };
@@ -30008,9 +31016,9 @@ async function installPajaHost() {
30008
31016
  const confirmationController = createPajaConfirmationController(
30009
31017
  () => stateRef,
30010
31018
  {
30011
- onSignerConsentChange(count) {
31019
+ onSignerConsentChange(count2) {
30012
31020
  if (!stateRef) return;
30013
- stateRef.signerConsentCount = count;
31021
+ stateRef.signerConsentCount = count2;
30014
31022
  setSimulationStatus(stateRef);
30015
31023
  }
30016
31024
  }