@kehto/paja 0.30.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/browser-host.js +1395 -271
- package/dist/browser-host.js.map +1 -1
- package/dist/{chunk-4GUFJFK7.js → chunk-DDYBKY5L.js} +76 -12
- package/dist/chunk-DDYBKY5L.js.map +1 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +8 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +11 -3
- package/dist/index.js +1 -1
- package/dist/{server-CRv7mQBf.d.ts → server-bAe1oDUG.d.ts} +20 -7
- package/package.json +10 -10
- package/dist/chunk-4GUFJFK7.js.map +0 -1
package/dist/browser-host.js
CHANGED
|
@@ -3831,7 +3831,176 @@ function deserialize2(json) {
|
|
|
3831
3831
|
return defaultConfig();
|
|
3832
3832
|
}
|
|
3833
3833
|
|
|
3834
|
-
// ../../node_modules/.pnpm/@napplet+core@0.
|
|
3834
|
+
// ../../node_modules/.pnpm/@napplet+core@0.38.0/node_modules/@napplet/core/dist/index.js
|
|
3835
|
+
var NAP_IMPLEMENTATIONS = {
|
|
3836
|
+
shell: {
|
|
3837
|
+
proposal: { url: "https://github.com/napplet/naps/pull/101", status: "merged", checkedAt: "2026-10-31" },
|
|
3838
|
+
maturity: "supported",
|
|
3839
|
+
rationale: "Optional readiness and environment binding has focused shim and reference-runtime coverage.",
|
|
3840
|
+
evidence: ["packages/nap/src/shell/shim.test.ts"]
|
|
3841
|
+
},
|
|
3842
|
+
relay: {
|
|
3843
|
+
proposal: { url: "https://github.com/napplet/naps/pull/2", status: "in-review", checkedAt: "2026-10-31" },
|
|
3844
|
+
maturity: "supported",
|
|
3845
|
+
rationale: "Relay reads, publishing, and subscription lifecycle have maintained shim and integration tests; upstream naming remains under review.",
|
|
3846
|
+
evidence: ["packages/nap/src/relay/shim.test.ts"],
|
|
3847
|
+
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." }
|
|
3848
|
+
},
|
|
3849
|
+
identity: {
|
|
3850
|
+
proposal: { url: "https://github.com/napplet/naps/pull/102", status: "merged", checkedAt: "2026-10-31" },
|
|
3851
|
+
maturity: "supported",
|
|
3852
|
+
rationale: "Read-only identity queries and updates have focused binding and reference-runtime coverage.",
|
|
3853
|
+
evidence: ["packages/nap/src/identity/shim.test.ts"]
|
|
3854
|
+
},
|
|
3855
|
+
storage: {
|
|
3856
|
+
proposal: { url: "https://github.com/napplet/naps/pull/3", status: "in-review", checkedAt: "2026-10-31" },
|
|
3857
|
+
maturity: "supported",
|
|
3858
|
+
rationale: "Key-value binding has focused request/result tests and tutorial usage; host storage isolation remains the host responsibility.",
|
|
3859
|
+
evidence: ["packages/nap/src/storage/shim.test.ts"]
|
|
3860
|
+
},
|
|
3861
|
+
inc: {
|
|
3862
|
+
proposal: { url: "https://github.com/napplet/naps/pull/104", status: "merged", checkedAt: "2026-10-31" },
|
|
3863
|
+
maturity: "supported",
|
|
3864
|
+
rationale: "Topic and channel bindings have compatibility tests and authenticated-endpoint reference-runtime coverage.",
|
|
3865
|
+
evidence: ["packages/nap/src/inc/shim.ts", "packages/conformance-cli/src/browser.test.ts"]
|
|
3866
|
+
},
|
|
3867
|
+
theme: {
|
|
3868
|
+
proposal: { url: "https://github.com/napplet/naps/pull/103", status: "merged", checkedAt: "2026-10-31" },
|
|
3869
|
+
maturity: "supported",
|
|
3870
|
+
rationale: "Theme queries and pushed updates have focused binding and opaque-iframe integration coverage.",
|
|
3871
|
+
evidence: ["packages/nap/src/theme/shim.test.ts", "packages/conformance-cli/src/browser.test.ts"]
|
|
3872
|
+
},
|
|
3873
|
+
keys: {
|
|
3874
|
+
proposal: { url: "https://github.com/napplet/naps/pull/9", status: "in-review", checkedAt: "2026-10-31" },
|
|
3875
|
+
maturity: "experimental",
|
|
3876
|
+
rationale: "Keyboard binding ships, but dedicated domain regression coverage is limited; retain explicit evaluation opt-in.",
|
|
3877
|
+
evidence: ["packages/nap/src/keys/shim.ts"]
|
|
3878
|
+
},
|
|
3879
|
+
media: {
|
|
3880
|
+
proposal: { url: "https://github.com/napplet/naps/pull/10", status: "in-review", checkedAt: "2026-10-31" },
|
|
3881
|
+
maturity: "supported",
|
|
3882
|
+
rationale: "Session creation and playback binding have focused regression coverage; proposed torrent playback amendments are not implied.",
|
|
3883
|
+
evidence: ["packages/nap/src/media/shim.test.ts"]
|
|
3884
|
+
},
|
|
3885
|
+
notify: {
|
|
3886
|
+
proposal: { url: "https://github.com/napplet/naps/pull/11", status: "in-review", checkedAt: "2026-10-31" },
|
|
3887
|
+
maturity: "experimental",
|
|
3888
|
+
rationale: "Notification binding ships with limited dedicated domain regression evidence; broader host integration confidence is unverified.",
|
|
3889
|
+
evidence: ["packages/nap/src/notify/shim.ts"]
|
|
3890
|
+
},
|
|
3891
|
+
config: {
|
|
3892
|
+
proposal: { url: "https://github.com/napplet/naps/pull/14", status: "draft", checkedAt: "2026-10-31" },
|
|
3893
|
+
maturity: "exploratory",
|
|
3894
|
+
rationale: "Configuration binding is tested, but the upstream draft is marked MAY DEFER; use for design exploration.",
|
|
3895
|
+
evidence: ["packages/nap/src/config/shim.test.ts"]
|
|
3896
|
+
},
|
|
3897
|
+
resource: {
|
|
3898
|
+
proposal: { url: "https://github.com/napplet/naps/pull/80", status: "in-review", checkedAt: "2026-10-31" },
|
|
3899
|
+
maturity: "supported",
|
|
3900
|
+
rationale: "Resource fetching has focused shim and type tests; the reverted merge and reopened proposal do not change that implementation assessment.",
|
|
3901
|
+
evidence: ["packages/nap/src/resource/shim.test.ts"],
|
|
3902
|
+
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." }
|
|
3903
|
+
},
|
|
3904
|
+
cvm: {
|
|
3905
|
+
proposal: { url: "https://github.com/napplet/naps/pull/31", status: "in-review", checkedAt: "2026-10-31" },
|
|
3906
|
+
maturity: "experimental",
|
|
3907
|
+
rationale: "Session and registry bindings are tested; upstream explicitly marks the contract NEEDS WORK.",
|
|
3908
|
+
evidence: ["packages/nap/src/cvm/shim.test.ts"]
|
|
3909
|
+
},
|
|
3910
|
+
outbox: {
|
|
3911
|
+
proposal: { url: "https://github.com/napplet/naps/pull/32", status: "in-review", checkedAt: "2026-10-31" },
|
|
3912
|
+
maturity: "supported",
|
|
3913
|
+
rationale: "Routing and subscription bindings have focused tests and an integration regression for structured-clone boundaries.",
|
|
3914
|
+
evidence: ["packages/nap/src/outbox/shim.test.ts", "packages/nap/src/boundary-integration.test.ts"],
|
|
3915
|
+
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." }
|
|
3916
|
+
},
|
|
3917
|
+
upload: {
|
|
3918
|
+
proposal: { url: "https://github.com/napplet/naps/pull/33", status: "in-review", checkedAt: "2026-10-31" },
|
|
3919
|
+
maturity: "supported",
|
|
3920
|
+
rationale: "Upload binding has focused tests for request/result behavior; host rail support remains runtime-specific.",
|
|
3921
|
+
evidence: ["packages/nap/src/upload/shim.test.ts"]
|
|
3922
|
+
},
|
|
3923
|
+
intent: {
|
|
3924
|
+
proposal: { url: "https://github.com/napplet/naps/pull/91", status: "merged", checkedAt: "2026-10-31" },
|
|
3925
|
+
maturity: "supported",
|
|
3926
|
+
rationale: "Convention normalization and dispatch have focused binding and reference-runtime integration tests.",
|
|
3927
|
+
evidence: ["packages/nap/src/intent/shim.test.ts"]
|
|
3928
|
+
},
|
|
3929
|
+
ble: {
|
|
3930
|
+
proposal: { url: "https://github.com/napplet/naps/pull/62", status: "in-review", checkedAt: "2026-10-31" },
|
|
3931
|
+
maturity: "experimental",
|
|
3932
|
+
rationale: "GATT binding has unit coverage; real-device behavior across host backends is not established by these tests.",
|
|
3933
|
+
evidence: ["packages/nap/src/ble/shim.test.ts"]
|
|
3934
|
+
},
|
|
3935
|
+
webrtc: {
|
|
3936
|
+
proposal: { url: "https://github.com/napplet/naps/pull/59", status: "in-review", checkedAt: "2026-10-31" },
|
|
3937
|
+
maturity: "experimental",
|
|
3938
|
+
rationale: "Signaling and session binding have unit coverage; interoperable live peer sessions remain unverified here.",
|
|
3939
|
+
evidence: ["packages/nap/src/webrtc/shim.test.ts"]
|
|
3940
|
+
},
|
|
3941
|
+
link: {
|
|
3942
|
+
proposal: { url: "https://github.com/napplet/naps/pull/53", status: "in-review", checkedAt: "2026-10-31" },
|
|
3943
|
+
maturity: "supported",
|
|
3944
|
+
rationale: "The small link-opening binding has focused regression coverage; navigation authorization stays with the host.",
|
|
3945
|
+
evidence: ["packages/nap/src/link/shim.test.ts"]
|
|
3946
|
+
},
|
|
3947
|
+
count: {
|
|
3948
|
+
proposal: { url: "https://github.com/napplet/naps/pull/69", status: "in-review", checkedAt: "2026-10-31" },
|
|
3949
|
+
maturity: "experimental",
|
|
3950
|
+
rationale: "Count binding is tested, but accuracy and aggregation across real relay backends remain outside that evidence.",
|
|
3951
|
+
evidence: ["packages/nap/src/count/shim.test.ts"]
|
|
3952
|
+
},
|
|
3953
|
+
lists: {
|
|
3954
|
+
proposal: { url: "https://github.com/napplet/naps/pull/68", status: "in-review", checkedAt: "2026-10-31" },
|
|
3955
|
+
maturity: "experimental",
|
|
3956
|
+
rationale: "List mutation binding is tested; concurrent real-host mutation behavior is not established by binding tests.",
|
|
3957
|
+
evidence: ["packages/nap/src/lists/shim.test.ts"]
|
|
3958
|
+
},
|
|
3959
|
+
serial: {
|
|
3960
|
+
proposal: { url: "https://github.com/napplet/naps/pull/61", status: "in-review", checkedAt: "2026-10-31" },
|
|
3961
|
+
maturity: "experimental",
|
|
3962
|
+
rationale: "Serial binding has unit coverage; device and native-host integration evidence is limited.",
|
|
3963
|
+
evidence: ["packages/nap/src/serial/shim.test.ts"]
|
|
3964
|
+
},
|
|
3965
|
+
fs: {
|
|
3966
|
+
proposal: { url: "https://github.com/napplet/naps/pull/88", status: "in-review", checkedAt: "2026-10-31" },
|
|
3967
|
+
maturity: "experimental",
|
|
3968
|
+
rationale: "Filesystem binding has MVP coverage; portability and authorization across storage backends remain under evaluation.",
|
|
3969
|
+
evidence: ["packages/nap/src/fs/shim.test.ts"]
|
|
3970
|
+
},
|
|
3971
|
+
common: {
|
|
3972
|
+
proposal: { url: "https://github.com/napplet/naps/pull/67", status: "in-review", checkedAt: "2026-10-31" },
|
|
3973
|
+
maturity: "experimental",
|
|
3974
|
+
rationale: "Social action binding is tested; broader host integration and evolving action semantics warrant explicit opt-in.",
|
|
3975
|
+
evidence: ["packages/nap/src/common/shim.test.ts"]
|
|
3976
|
+
},
|
|
3977
|
+
dm: {
|
|
3978
|
+
proposal: { url: "https://github.com/napplet/naps/pull/74", status: "draft", checkedAt: "2026-10-31" },
|
|
3979
|
+
maturity: "experimental",
|
|
3980
|
+
rationale: "Direct-message binding has shim and type coverage; transport interoperability is not established by those tests.",
|
|
3981
|
+
evidence: ["packages/nap/src/dm/shim.test.ts"]
|
|
3982
|
+
},
|
|
3983
|
+
gamepad: {
|
|
3984
|
+
proposal: { url: "https://github.com/napplet/naps/pull/130", status: "in-review", checkedAt: "2026-10-31" },
|
|
3985
|
+
maturity: "supported",
|
|
3986
|
+
rationale: "Cross-repository delivery includes binding, security, runtime, and conformance verification; the reopened proposal is still subject to change.",
|
|
3987
|
+
evidence: ["packages/nap/src/gamepad/shim.test.ts", ".planning/phases/163-nap-gamepad-across-repositories/163-VERIFICATION.md"],
|
|
3988
|
+
implementationReference: { revision: "0b28f77e3dfa0f07dd7c0f9d61a7090ee99f3a5e", evidence: ".planning/phases/163-nap-gamepad-across-repositories/163-SECURITY.md", scope: "Phase 163 binding, runtime isolation, and conformance verification." }
|
|
3989
|
+
},
|
|
3990
|
+
llm: {
|
|
3991
|
+
proposal: { url: "https://github.com/napplet/naps/pull/134", status: "draft", checkedAt: "2026-10-31" },
|
|
3992
|
+
maturity: "exploratory",
|
|
3993
|
+
rationale: "Early published draft has binding and mock-runtime tests; provider behavior and API design remain exploratory.",
|
|
3994
|
+
evidence: ["packages/nap/src/llm/shim.test.ts", "packages/conformance-cli/src/browser.test.ts"]
|
|
3995
|
+
}
|
|
3996
|
+
};
|
|
3997
|
+
for (const entry of Object.values(NAP_IMPLEMENTATIONS)) {
|
|
3998
|
+
Object.freeze(entry.proposal);
|
|
3999
|
+
Object.freeze(entry.evidence);
|
|
4000
|
+
if (entry.implementationReference) Object.freeze(entry.implementationReference);
|
|
4001
|
+
Object.freeze(entry);
|
|
4002
|
+
}
|
|
4003
|
+
Object.freeze(NAP_IMPLEMENTATIONS);
|
|
3835
4004
|
function createDispatch() {
|
|
3836
4005
|
const handlers = /* @__PURE__ */ new Map();
|
|
3837
4006
|
function registerNap2(domain, handler) {
|
|
@@ -7988,10 +8157,10 @@ function normalizeCountResult2(value) {
|
|
|
7988
8157
|
if (typeof value === "number") {
|
|
7989
8158
|
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
8159
|
}
|
|
7991
|
-
const
|
|
8160
|
+
const count2 = typeof value.count === "number" && Number.isFinite(value.count) && value.count >= 0 ? Math.floor(value.count) : void 0;
|
|
7992
8161
|
return {
|
|
7993
8162
|
ok: value.ok === true,
|
|
7994
|
-
...
|
|
8163
|
+
...count2 !== void 0 ? { count: count2 } : {},
|
|
7995
8164
|
...typeof value.approximate === "boolean" ? { approximate: value.approximate } : {},
|
|
7996
8165
|
...typeof value.hll === "string" ? { hll: value.hll } : {},
|
|
7997
8166
|
...Array.isArray(value.relays) ? { relays: value.relays } : {},
|
|
@@ -8646,8 +8815,8 @@ var MediaRegistry = class {
|
|
|
8646
8815
|
const fail2 = (error) => send({ type: "media.session.create.result", id: msg.id ?? "", ...msg.owner === "shell" || msg.owner === "napplet" ? { owner: msg.owner } : {}, error });
|
|
8647
8816
|
if (this.destroyed) return;
|
|
8648
8817
|
if (msg.owner !== "napplet" && msg.owner !== "shell") return fail2("missing owner");
|
|
8649
|
-
const
|
|
8650
|
-
if (
|
|
8818
|
+
const count2 = [...this.sessions.values()].filter((entry2) => entry2.windowId === windowId).length + [...this.pending.values()].filter((pending) => pending.windowId === windowId).length;
|
|
8819
|
+
if (count2 >= (this.options.maxSessionsPerWindow ?? 16)) return fail2("session limit exceeded");
|
|
8651
8820
|
if (msg.owner === "shell" && !msg.source) return fail2("missing source");
|
|
8652
8821
|
if (msg.owner === "shell" && !this.options.playback) return fail2("unsupported owner mode");
|
|
8653
8822
|
const entry = {
|
|
@@ -8887,8 +9056,8 @@ function createNotifyService(options = {}) {
|
|
|
8887
9056
|
}
|
|
8888
9057
|
case "notify.badge": {
|
|
8889
9058
|
if (options.setBadge) {
|
|
8890
|
-
const
|
|
8891
|
-
forget(options.setBadge(windowId,
|
|
9059
|
+
const count2 = Math.max(0, Math.floor(message22.count));
|
|
9060
|
+
forget(options.setBadge(windowId, count2), options.onError);
|
|
8892
9061
|
}
|
|
8893
9062
|
return;
|
|
8894
9063
|
}
|
|
@@ -13368,33 +13537,161 @@ var boolean = (value) => typeof value === "boolean";
|
|
|
13368
13537
|
var oneOf = (...allowed2) => (value) => typeof value === "string" && allowed2.includes(value);
|
|
13369
13538
|
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
13539
|
var nonNegativeInteger = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
13540
|
+
var positiveInteger = (value) => typeof value === "number" && Number.isInteger(value) && value > 0;
|
|
13541
|
+
var finiteNumber = (value) => typeof value === "number" && Number.isFinite(value);
|
|
13542
|
+
var MAX_JSON_DEPTH = 64;
|
|
13543
|
+
var MAX_JSON_NODES = 5e4;
|
|
13544
|
+
function isPlainObject22(value) {
|
|
13545
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
13546
|
+
const prototype = Object.getPrototypeOf(value);
|
|
13547
|
+
return prototype === Object.prototype || prototype === null;
|
|
13548
|
+
}
|
|
13549
|
+
function isJsonValue(value) {
|
|
13550
|
+
let budget = MAX_JSON_NODES;
|
|
13551
|
+
const visit = (current, depth) => {
|
|
13552
|
+
if ((budget -= 1) < 0 || depth > MAX_JSON_DEPTH) return false;
|
|
13553
|
+
if (current === null || typeof current === "string" || typeof current === "boolean") return true;
|
|
13554
|
+
if (typeof current === "number") return Number.isFinite(current);
|
|
13555
|
+
if (Array.isArray(current)) return current.every((entry) => visit(entry, depth + 1));
|
|
13556
|
+
return isPlainObject22(current) && Object.values(current).every((entry) => visit(entry, depth + 1));
|
|
13557
|
+
};
|
|
13558
|
+
return visit(value, 0);
|
|
13559
|
+
}
|
|
13560
|
+
var jsonObject = (value) => isPlainObject22(value) && isJsonValue(value);
|
|
13561
|
+
function hasKey(record3, key) {
|
|
13562
|
+
return Object.prototype.hasOwnProperty.call(record3, key);
|
|
13563
|
+
}
|
|
13371
13564
|
function exactRecord(required, optional = {}) {
|
|
13372
13565
|
return (value) => {
|
|
13373
13566
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
13374
13567
|
const data = value;
|
|
13375
|
-
if (Object.keys(data).some((key) => !(key
|
|
13568
|
+
if (Object.keys(data).some((key) => !hasKey(required, key) && !hasKey(optional, key))) return false;
|
|
13376
13569
|
return Object.entries(required).every(([key, check2]) => check2(data[key])) && Object.entries(optional).every(([key, check2]) => data[key] === void 0 || check2(data[key]));
|
|
13377
13570
|
};
|
|
13378
13571
|
}
|
|
13379
13572
|
var nonemptyList = (item) => (value) => Array.isArray(value) && value.length > 0 && value.every(item);
|
|
13380
13573
|
var textPart = exactRecord({ type: oneOf("text"), text });
|
|
13381
13574
|
var imagePart = exactRecord({ type: oneOf("image"), mimeType: oneOf("image/png", "image/jpeg", "image/webp"), data: base642 });
|
|
13382
|
-
var
|
|
13383
|
-
var
|
|
13384
|
-
var
|
|
13385
|
-
var
|
|
13386
|
-
var
|
|
13387
|
-
var
|
|
13575
|
+
var thinkingPart = exactRecord({ type: oneOf("thinking"), text });
|
|
13576
|
+
var toolCallPart = exactRecord({ type: oneOf("toolCall"), toolCallId: nonemptyText, name: nonemptyText, arguments: jsonObject });
|
|
13577
|
+
var inputPart = (value) => textPart(value) || imagePart(value);
|
|
13578
|
+
var assistantPart = (value) => inputPart(value) || thinkingPart(value) || toolCallPart(value);
|
|
13579
|
+
var resultPart = inputPart;
|
|
13580
|
+
var plainMessage = exactRecord({ role: oneOf("system", "user"), content: nonemptyList(inputPart) });
|
|
13581
|
+
var assistantMessage = exactRecord({ role: oneOf("assistant"), content: nonemptyList(assistantPart) });
|
|
13582
|
+
var toolResultMessage = exactRecord(
|
|
13583
|
+
{ role: oneOf("toolResult"), content: nonemptyList(resultPart), toolCallId: nonemptyText, toolName: nonemptyText },
|
|
13584
|
+
{ isError: boolean }
|
|
13585
|
+
);
|
|
13586
|
+
var message = (value) => plainMessage(value) || assistantMessage(value) || toolResultMessage(value);
|
|
13587
|
+
var requirements = exactRecord({}, { model: nonemptyText, images: boolean, json: boolean, tools: boolean });
|
|
13588
|
+
var SCHEMA_TYPES = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "object", "array", "null"]);
|
|
13589
|
+
var MAX_SCHEMA_DEPTH = 32;
|
|
13590
|
+
var SCHEMA_MAPS = ["properties", "patternProperties", "$defs"];
|
|
13591
|
+
var SCHEMA_SINGLES = ["items", "additionalProperties", "not", "contains", "propertyNames", "if", "then", "else"];
|
|
13592
|
+
var SCHEMA_LISTS = ["allOf", "anyOf", "oneOf", "prefixItems"];
|
|
13593
|
+
function validSchemaType(type) {
|
|
13594
|
+
if (typeof type === "string") return SCHEMA_TYPES.has(type);
|
|
13595
|
+
return Array.isArray(type) && type.length > 0 && type.every((entry) => typeof entry === "string" && SCHEMA_TYPES.has(entry));
|
|
13596
|
+
}
|
|
13597
|
+
function isSchema(value, depth) {
|
|
13598
|
+
if (typeof value === "boolean") return true;
|
|
13599
|
+
if (depth > MAX_SCHEMA_DEPTH || !isPlainObject22(value)) return false;
|
|
13600
|
+
const sub = (entry) => isSchema(entry, depth + 1);
|
|
13601
|
+
if (value.type !== void 0 && !validSchemaType(value.type)) return false;
|
|
13602
|
+
for (const key of SCHEMA_MAPS) {
|
|
13603
|
+
const entry = value[key];
|
|
13604
|
+
if (entry !== void 0 && !(isPlainObject22(entry) && Object.values(entry).every(sub))) return false;
|
|
13605
|
+
}
|
|
13606
|
+
for (const key of SCHEMA_SINGLES) if (value[key] !== void 0 && !sub(value[key])) return false;
|
|
13607
|
+
for (const key of SCHEMA_LISTS) {
|
|
13608
|
+
const entry = value[key];
|
|
13609
|
+
if (entry !== void 0 && !(Array.isArray(entry) && entry.length > 0 && entry.every(sub))) return false;
|
|
13610
|
+
}
|
|
13611
|
+
if (value.required !== void 0 && !(Array.isArray(value.required) && value.required.every((name) => typeof name === "string"))) return false;
|
|
13612
|
+
return value.enum === void 0 || Array.isArray(value.enum);
|
|
13613
|
+
}
|
|
13614
|
+
var toolParameters = (value) => isPlainObject22(value) && isJsonValue(value) && value.type === "object" && isSchema(value, 0);
|
|
13615
|
+
var toolName = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value);
|
|
13616
|
+
var tool = exactRecord({ name: toolName }, { description: text, parameters: toolParameters });
|
|
13617
|
+
var namedToolChoice = exactRecord({ type: oneOf("tool"), name: nonemptyText });
|
|
13618
|
+
var toolChoice = (value) => oneOf("auto", "none", "required")(value) || namedToolChoice(value);
|
|
13619
|
+
var generationFields = exactRecord(
|
|
13620
|
+
{ handle: nonemptyText, messages: nonemptyList(message) },
|
|
13621
|
+
{
|
|
13622
|
+
format: oneOf("text", "json"),
|
|
13623
|
+
maxTokens: positiveInteger,
|
|
13624
|
+
temperature: finiteNumber,
|
|
13625
|
+
tools: (value) => Array.isArray(value) && value.every(tool),
|
|
13626
|
+
toolChoice
|
|
13627
|
+
}
|
|
13628
|
+
);
|
|
13629
|
+
function callsOf(turn) {
|
|
13630
|
+
return turn.role === "assistant" ? turn.content.filter((entry) => entry.type === "toolCall") : [];
|
|
13631
|
+
}
|
|
13632
|
+
function validToolHistory(messages) {
|
|
13633
|
+
const seen = /* @__PURE__ */ new Set();
|
|
13634
|
+
let index = 0;
|
|
13635
|
+
while (index < messages.length) {
|
|
13636
|
+
const turn = messages[index];
|
|
13637
|
+
index += 1;
|
|
13638
|
+
if (turn.role === "toolResult") return false;
|
|
13639
|
+
const calls = callsOf(turn);
|
|
13640
|
+
for (const call of calls) {
|
|
13641
|
+
if (seen.has(call.toolCallId)) return false;
|
|
13642
|
+
seen.add(call.toolCallId);
|
|
13643
|
+
}
|
|
13644
|
+
const pending = new Map(calls.map((call) => [call.toolCallId, call.name]));
|
|
13645
|
+
for (let answered = 0; answered < calls.length; answered += 1) {
|
|
13646
|
+
const result2 = messages[index + answered];
|
|
13647
|
+
if (result2?.role !== "toolResult" || result2.toolCallId === void 0 || pending.get(result2.toolCallId) !== result2.toolName) return false;
|
|
13648
|
+
pending.delete(result2.toolCallId);
|
|
13649
|
+
}
|
|
13650
|
+
index += calls.length;
|
|
13651
|
+
}
|
|
13652
|
+
return true;
|
|
13653
|
+
}
|
|
13654
|
+
function validRequestRelations(request) {
|
|
13655
|
+
const names = (request.tools ?? []).map((entry) => entry.name);
|
|
13656
|
+
if (new Set(names).size !== names.length) return false;
|
|
13657
|
+
if (request.toolChoice !== void 0) {
|
|
13658
|
+
if (names.length === 0) return false;
|
|
13659
|
+
if (typeof request.toolChoice === "object" && !names.includes(request.toolChoice.name)) return false;
|
|
13660
|
+
}
|
|
13661
|
+
return validToolHistory(request.messages);
|
|
13662
|
+
}
|
|
13663
|
+
var usage = exactRecord(
|
|
13664
|
+
{ inputTokens: nonNegativeInteger, outputTokens: nonNegativeInteger },
|
|
13665
|
+
{ cacheReadTokens: nonNegativeInteger, cacheWriteTokens: nonNegativeInteger, reasoningTokens: nonNegativeInteger }
|
|
13666
|
+
);
|
|
13667
|
+
var outputPart = (value) => textPart(value) || thinkingPart(value) || toolCallPart(value);
|
|
13668
|
+
var generation = exactRecord(
|
|
13669
|
+
{ content: (value) => Array.isArray(value) && value.every(outputPart), finish: oneOf("stop", "length", "refusal", "toolUse") },
|
|
13670
|
+
{ usage }
|
|
13671
|
+
);
|
|
13388
13672
|
function isLlmRequirements(value) {
|
|
13389
13673
|
return value === void 0 || requirements(value);
|
|
13390
13674
|
}
|
|
13391
|
-
|
|
13675
|
+
function isLlmGenerationRequest(value) {
|
|
13676
|
+
return generationFields(value) && validRequestRelations(value);
|
|
13677
|
+
}
|
|
13392
13678
|
var isLlmGeneration = generation;
|
|
13679
|
+
function llmTextOf(content) {
|
|
13680
|
+
return content.map((part) => part.type === "text" ? part.text : "").join("");
|
|
13681
|
+
}
|
|
13393
13682
|
var isNonemptyText = nonemptyText;
|
|
13394
13683
|
function countLlmImages(messages) {
|
|
13395
|
-
let
|
|
13396
|
-
for (const entry of messages) for (const item of entry.content) if (item.type === "image")
|
|
13397
|
-
return
|
|
13684
|
+
let count2 = 0;
|
|
13685
|
+
for (const entry of messages) for (const item of entry.content) if (item.type === "image") count2 += 1;
|
|
13686
|
+
return count2;
|
|
13687
|
+
}
|
|
13688
|
+
function hasLlmToolHistory(messages) {
|
|
13689
|
+
return messages.some((entry) => entry.role === "toolResult" || entry.content.some((item) => item.type === "toolCall"));
|
|
13690
|
+
}
|
|
13691
|
+
function llmToolChoiceMode(request) {
|
|
13692
|
+
if ((request.tools ?? []).length === 0) return null;
|
|
13693
|
+
if (request.toolChoice === void 0) return "auto";
|
|
13694
|
+
return typeof request.toolChoice === "string" ? request.toolChoice : "tool";
|
|
13398
13695
|
}
|
|
13399
13696
|
function isJsonObjectText(value) {
|
|
13400
13697
|
try {
|
|
@@ -13404,6 +13701,136 @@ function isJsonObjectText(value) {
|
|
|
13404
13701
|
return false;
|
|
13405
13702
|
}
|
|
13406
13703
|
}
|
|
13704
|
+
var MALFORMED = { code: "provider-error", message: "The provider returned an incomplete or malformed completion." };
|
|
13705
|
+
var LIFECYCLE = { code: "provider-error", message: "The provider streamed output that breaks the block lifecycle." };
|
|
13706
|
+
var MISMATCH = { code: "provider-error", message: "The provider result does not match its streamed blocks." };
|
|
13707
|
+
var BAD_CALL = { code: "provider-error", message: "The provider returned an invalid tool call." };
|
|
13708
|
+
var BAD_MODE = { code: "provider-error", message: "The provider result does not honour the requested tool choice." };
|
|
13709
|
+
var NO_JSON = { code: "provider-error", message: "The provider completed without a JSON object." };
|
|
13710
|
+
function unsupported4(message22) {
|
|
13711
|
+
return { code: "unsupported", message: message22 };
|
|
13712
|
+
}
|
|
13713
|
+
function unsupportedInput(connection, request) {
|
|
13714
|
+
const mode = llmToolChoiceMode(request);
|
|
13715
|
+
if (mode !== null && !connection.tools) return unsupported4("This connection does not support tool calling.");
|
|
13716
|
+
if (mode !== null && !connection.toolChoiceModes.includes(mode)) return unsupported4(`This connection does not support the "${mode}" tool choice.`);
|
|
13717
|
+
if (hasLlmToolHistory(request.messages) && !connection.tools) return unsupported4("This connection does not accept tool calls or tool results.");
|
|
13718
|
+
if (countLlmImages(request.messages) > 0 && !connection.images) return unsupported4("This connection does not accept image input.");
|
|
13719
|
+
if (request.format === "json" && !connection.json) return unsupported4("This connection does not support JSON-object output.");
|
|
13720
|
+
return null;
|
|
13721
|
+
}
|
|
13722
|
+
var EVENTS = /* @__PURE__ */ new Set(["start", "delta", "end"]);
|
|
13723
|
+
var BLOCKS = /* @__PURE__ */ new Set(["text", "thinking", "toolCall"]);
|
|
13724
|
+
var nonEmpty = (value) => typeof value === "string" && value.length > 0;
|
|
13725
|
+
function jsonEqual(a, b) {
|
|
13726
|
+
if (a === b) return true;
|
|
13727
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
|
|
13728
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
13729
|
+
return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((entry, index) => jsonEqual(entry, b[index]));
|
|
13730
|
+
}
|
|
13731
|
+
const left = a;
|
|
13732
|
+
const right = b;
|
|
13733
|
+
const keys = Object.keys(left);
|
|
13734
|
+
return keys.length === Object.keys(right).length && keys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && jsonEqual(left[key], right[key]));
|
|
13735
|
+
}
|
|
13736
|
+
function validStart(event) {
|
|
13737
|
+
if (event.text !== void 0) return false;
|
|
13738
|
+
if (event.block === "toolCall") return nonEmpty(event.toolCallId) && nonEmpty(event.name);
|
|
13739
|
+
return event.toolCallId === void 0 && event.name === void 0;
|
|
13740
|
+
}
|
|
13741
|
+
function createLlmDeltaTracker() {
|
|
13742
|
+
const blocks = /* @__PURE__ */ new Map();
|
|
13743
|
+
return {
|
|
13744
|
+
accept(event) {
|
|
13745
|
+
if (!EVENTS.has(event.event) || !BLOCKS.has(event.block)) return false;
|
|
13746
|
+
if (!Number.isInteger(event.blockIndex) || event.blockIndex < 0) return false;
|
|
13747
|
+
const known = blocks.get(event.blockIndex);
|
|
13748
|
+
if (event.event === "start") {
|
|
13749
|
+
if (known || !validStart(event)) return false;
|
|
13750
|
+
blocks.set(event.blockIndex, {
|
|
13751
|
+
kind: event.block,
|
|
13752
|
+
open: true,
|
|
13753
|
+
text: "",
|
|
13754
|
+
...event.block === "toolCall" ? { toolCallId: event.toolCallId, name: event.name } : {}
|
|
13755
|
+
});
|
|
13756
|
+
return true;
|
|
13757
|
+
}
|
|
13758
|
+
if (!known?.open || known.kind !== event.block) return false;
|
|
13759
|
+
if (event.toolCallId !== void 0 || event.name !== void 0) return false;
|
|
13760
|
+
if (event.event === "end") {
|
|
13761
|
+
known.open = false;
|
|
13762
|
+
return event.text === void 0;
|
|
13763
|
+
}
|
|
13764
|
+
if (typeof event.text !== "string") return false;
|
|
13765
|
+
known.text += event.text;
|
|
13766
|
+
return true;
|
|
13767
|
+
},
|
|
13768
|
+
matches(content) {
|
|
13769
|
+
for (const [index, block2] of blocks) {
|
|
13770
|
+
if (block2.open) return false;
|
|
13771
|
+
const part = content[index];
|
|
13772
|
+
if (!part || part.type !== block2.kind) return false;
|
|
13773
|
+
if (part.type === "toolCall") {
|
|
13774
|
+
if (part.toolCallId !== block2.toolCallId || part.name !== block2.name) return false;
|
|
13775
|
+
try {
|
|
13776
|
+
if (!jsonEqual(JSON.parse(block2.text), part.arguments)) return false;
|
|
13777
|
+
} catch {
|
|
13778
|
+
return false;
|
|
13779
|
+
}
|
|
13780
|
+
} else if (part.text !== block2.text) {
|
|
13781
|
+
return false;
|
|
13782
|
+
}
|
|
13783
|
+
}
|
|
13784
|
+
return true;
|
|
13785
|
+
}
|
|
13786
|
+
};
|
|
13787
|
+
}
|
|
13788
|
+
function callsOf2(content) {
|
|
13789
|
+
return content.filter((part) => part.type === "toolCall");
|
|
13790
|
+
}
|
|
13791
|
+
function historyIds(request) {
|
|
13792
|
+
const ids = /* @__PURE__ */ new Set();
|
|
13793
|
+
for (const message22 of request.messages) {
|
|
13794
|
+
for (const part of message22.content) if (part.type === "toolCall") ids.add(part.toolCallId);
|
|
13795
|
+
}
|
|
13796
|
+
return ids;
|
|
13797
|
+
}
|
|
13798
|
+
function validCalls(request, calls) {
|
|
13799
|
+
const names = new Set((request.tools ?? []).map((entry) => entry.name));
|
|
13800
|
+
const used = historyIds(request);
|
|
13801
|
+
for (const call of calls) {
|
|
13802
|
+
if (!names.has(call.name) || used.has(call.toolCallId)) return false;
|
|
13803
|
+
used.add(call.toolCallId);
|
|
13804
|
+
}
|
|
13805
|
+
return true;
|
|
13806
|
+
}
|
|
13807
|
+
function honoursChoice(request, calls) {
|
|
13808
|
+
const mode = llmToolChoiceMode(request);
|
|
13809
|
+
if (mode === "none") return calls.length === 0;
|
|
13810
|
+
if (mode === "required") return calls.length > 0;
|
|
13811
|
+
if (mode !== "tool") return true;
|
|
13812
|
+
const forced = typeof request.toolChoice === "object" ? request.toolChoice.name : "";
|
|
13813
|
+
return calls.length > 0 && calls.every((call) => call.name === forced);
|
|
13814
|
+
}
|
|
13815
|
+
function stripPartialCalls(result2) {
|
|
13816
|
+
if (typeof result2 !== "object" || result2 === null) return result2;
|
|
13817
|
+
const generation2 = result2;
|
|
13818
|
+
if (generation2.finish !== "length" && generation2.finish !== "refusal" || !Array.isArray(generation2.content)) return result2;
|
|
13819
|
+
return { ...generation2, content: generation2.content.filter((part) => part?.type !== "toolCall") };
|
|
13820
|
+
}
|
|
13821
|
+
function checkTerminal(request, raw, tracker) {
|
|
13822
|
+
const result2 = stripPartialCalls(raw);
|
|
13823
|
+
if (!isLlmGeneration(result2)) return MALFORMED;
|
|
13824
|
+
if (result2.finish === "length" || result2.finish === "refusal") return result2;
|
|
13825
|
+
const calls = callsOf2(result2.content);
|
|
13826
|
+
if (result2.finish === "toolUse" && calls.length === 0) return MALFORMED;
|
|
13827
|
+
if (!validCalls(request, calls)) return BAD_CALL;
|
|
13828
|
+
if (!honoursChoice(request, calls)) return BAD_MODE;
|
|
13829
|
+
const normalised = calls.length > 0 && result2.finish === "stop" ? { ...result2, finish: "toolUse" } : result2;
|
|
13830
|
+
if (request.format === "json" && normalised.finish === "stop" && !isJsonObjectText(llmTextOf(normalised.content))) return NO_JSON;
|
|
13831
|
+
return tracker.matches(normalised.content) ? normalised : MISMATCH;
|
|
13832
|
+
}
|
|
13833
|
+
var LLM_LIFECYCLE_FAILURE = LIFECYCLE;
|
|
13407
13834
|
var DESCRIPTOR = {
|
|
13408
13835
|
name: "llm",
|
|
13409
13836
|
version: "1.0.0",
|
|
@@ -13421,16 +13848,35 @@ function failure(error) {
|
|
|
13421
13848
|
if (error instanceof LlmServiceError) return { code: error.code, message: error.message };
|
|
13422
13849
|
return { code: "provider-error", message: "The provider request failed." };
|
|
13423
13850
|
}
|
|
13851
|
+
function sameModes(a, b) {
|
|
13852
|
+
return a.length === b.length && a.every((mode, index) => mode === b[index]);
|
|
13853
|
+
}
|
|
13424
13854
|
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;
|
|
13855
|
+
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);
|
|
13856
|
+
}
|
|
13857
|
+
function declaresValidModes(connection) {
|
|
13858
|
+
if (!connection.tools) return true;
|
|
13859
|
+
const modes = connection.toolChoiceModes;
|
|
13860
|
+
return new Set(modes).size === modes.length && modes.includes("auto") && modes.includes("none");
|
|
13426
13861
|
}
|
|
13427
13862
|
function meetsRequirements(connection, requirements2) {
|
|
13863
|
+
if (!declaresValidModes(connection)) return false;
|
|
13428
13864
|
if (requirements2.model !== void 0 && requirements2.model !== connection.model) return false;
|
|
13429
13865
|
if (requirements2.images === true && !connection.images) return false;
|
|
13866
|
+
if (requirements2.tools === true && !connection.tools) return false;
|
|
13430
13867
|
return !(requirements2.json === true && !connection.json);
|
|
13431
13868
|
}
|
|
13432
13869
|
function toModel(handle, connection) {
|
|
13433
|
-
return {
|
|
13870
|
+
return {
|
|
13871
|
+
handle,
|
|
13872
|
+
name: connection.name,
|
|
13873
|
+
model: connection.model,
|
|
13874
|
+
route: connection.route,
|
|
13875
|
+
images: connection.images,
|
|
13876
|
+
json: connection.json,
|
|
13877
|
+
tools: connection.tools,
|
|
13878
|
+
toolChoiceModes: connection.tools ? [...connection.toolChoiceModes] : []
|
|
13879
|
+
};
|
|
13434
13880
|
}
|
|
13435
13881
|
function defaultHandleFactory() {
|
|
13436
13882
|
let counter = 0;
|
|
@@ -13591,17 +14037,12 @@ function admitGeneration(state, windowId, message22) {
|
|
|
13591
14037
|
if (JSON.stringify(message22.request).length > state.maxRequestChars) return { code: "quota-exceeded", message: "The request exceeds the runtime size limit." };
|
|
13592
14038
|
return null;
|
|
13593
14039
|
}
|
|
13594
|
-
function
|
|
13595
|
-
|
|
13596
|
-
if (
|
|
13597
|
-
|
|
13598
|
-
|
|
13599
|
-
|
|
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;
|
|
14040
|
+
function deltaMessage(requestId, sequence, event) {
|
|
14041
|
+
const delta = { requestId, sequence, event: event.event, block: event.block, blockIndex: event.blockIndex };
|
|
14042
|
+
if (event.text !== void 0) delta.text = event.text;
|
|
14043
|
+
if (event.toolCallId !== void 0) delta.toolCallId = event.toolCallId;
|
|
14044
|
+
if (event.name !== void 0) delta.name = event.name;
|
|
14045
|
+
return { type: "llm.delta", ...delta };
|
|
13605
14046
|
}
|
|
13606
14047
|
async function awaitConsent(state, context, connection, request, generation2) {
|
|
13607
14048
|
const prompt = new AbortController();
|
|
@@ -13643,13 +14084,17 @@ async function runGeneration(state, windowId, requestId, request, generation2, s
|
|
|
13643
14084
|
}
|
|
13644
14085
|
const result2 = await state.host.generate(context, entry.snapshot, request, {
|
|
13645
14086
|
signal: generation2.controller.signal,
|
|
13646
|
-
onDelta: (
|
|
13647
|
-
if (generation2.settled
|
|
13648
|
-
|
|
14087
|
+
onDelta: (event) => {
|
|
14088
|
+
if (generation2.settled) return;
|
|
14089
|
+
if (!generation2.tracker.accept(event)) {
|
|
14090
|
+
fail2(LLM_LIFECYCLE_FAILURE);
|
|
14091
|
+
return;
|
|
14092
|
+
}
|
|
14093
|
+
send(deltaMessage(requestId, generation2.sequence++, event));
|
|
13649
14094
|
}
|
|
13650
14095
|
});
|
|
13651
14096
|
if (generation2.settled) return;
|
|
13652
|
-
const checked =
|
|
14097
|
+
const checked = checkTerminal(request, result2, generation2.tracker);
|
|
13653
14098
|
if ("code" in checked) fail2(checked);
|
|
13654
14099
|
else settle6(state, windowId, requestId, generation2, { type: "llm.generate.result", id: requestId, result: checked });
|
|
13655
14100
|
} catch (error) {
|
|
@@ -13669,7 +14114,8 @@ function handleGenerate(state, windowId, message22, send) {
|
|
|
13669
14114
|
handle: request.handle,
|
|
13670
14115
|
awaitingConsent: false,
|
|
13671
14116
|
send,
|
|
13672
|
-
|
|
14117
|
+
request,
|
|
14118
|
+
tracker: createLlmDeltaTracker(),
|
|
13673
14119
|
epoch: state.epoch,
|
|
13674
14120
|
sequence: 0,
|
|
13675
14121
|
settled: false,
|
|
@@ -13770,10 +14216,143 @@ function createLlmService(options) {
|
|
|
13770
14216
|
}
|
|
13771
14217
|
};
|
|
13772
14218
|
}
|
|
14219
|
+
var BAD_CALL2 = "The provider returned an invalid tool call.";
|
|
14220
|
+
var fallbackCounter = 0;
|
|
14221
|
+
function synthesizeLlmToolCallId() {
|
|
14222
|
+
fallbackCounter += 1;
|
|
14223
|
+
const random = typeof globalThis.crypto?.randomUUID === "function" ? globalThis.crypto.randomUUID() : `${Date.now().toString(36)}-${fallbackCounter}`;
|
|
14224
|
+
return `call_${random}`;
|
|
14225
|
+
}
|
|
14226
|
+
function parseToolArguments(raw) {
|
|
14227
|
+
if (raw === void 0 || raw === "") return {};
|
|
14228
|
+
let value = raw;
|
|
14229
|
+
if (typeof raw === "string") {
|
|
14230
|
+
try {
|
|
14231
|
+
value = JSON.parse(raw);
|
|
14232
|
+
} catch {
|
|
14233
|
+
throw new LlmServiceError("provider-error", BAD_CALL2);
|
|
14234
|
+
}
|
|
14235
|
+
}
|
|
14236
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new LlmServiceError("provider-error", BAD_CALL2);
|
|
14237
|
+
return value;
|
|
14238
|
+
}
|
|
14239
|
+
function toolCallParts(partial, calls) {
|
|
14240
|
+
if (partial) return [];
|
|
14241
|
+
return calls.map((call) => {
|
|
14242
|
+
if (typeof call.name !== "string" || call.name === "") throw new LlmServiceError("provider-error", BAD_CALL2);
|
|
14243
|
+
const toolCallId = typeof call.id === "string" && call.id !== "" ? call.id : synthesizeLlmToolCallId();
|
|
14244
|
+
return { type: "toolCall", toolCallId, name: call.name, arguments: parseToolArguments(call.args) };
|
|
14245
|
+
});
|
|
14246
|
+
}
|
|
14247
|
+
function createLlmBlockBuilder() {
|
|
14248
|
+
const texts = /* @__PURE__ */ new Map();
|
|
14249
|
+
const calls = /* @__PURE__ */ new Map();
|
|
14250
|
+
let next = 0;
|
|
14251
|
+
function startCall(call) {
|
|
14252
|
+
call.index = next++;
|
|
14253
|
+
const events = [
|
|
14254
|
+
{ event: "start", block: "toolCall", blockIndex: call.index, toolCallId: call.id, name: call.name }
|
|
14255
|
+
];
|
|
14256
|
+
for (const fragment of call.held) events.push(deltaOf(call, fragment));
|
|
14257
|
+
call.held = [];
|
|
14258
|
+
return events;
|
|
14259
|
+
}
|
|
14260
|
+
function deltaOf(call, fragment) {
|
|
14261
|
+
call.sent.push(fragment);
|
|
14262
|
+
return { event: "delta", block: "toolCall", blockIndex: call.index, text: fragment };
|
|
14263
|
+
}
|
|
14264
|
+
function endCall(call) {
|
|
14265
|
+
if (!call.open || call.index === void 0) return [];
|
|
14266
|
+
call.open = false;
|
|
14267
|
+
const events = [];
|
|
14268
|
+
if (call.sent.length === 0) events.push(deltaOf(call, "{}"));
|
|
14269
|
+
events.push({ event: "end", block: "toolCall", blockIndex: call.index });
|
|
14270
|
+
return events;
|
|
14271
|
+
}
|
|
14272
|
+
function callFor(key) {
|
|
14273
|
+
let call = calls.get(key);
|
|
14274
|
+
if (!call) {
|
|
14275
|
+
call = { index: void 0, id: void 0, name: void 0, held: [], sent: [], open: true };
|
|
14276
|
+
calls.set(key, call);
|
|
14277
|
+
}
|
|
14278
|
+
return call;
|
|
14279
|
+
}
|
|
14280
|
+
function endKey(key) {
|
|
14281
|
+
const text2 = texts.get(key);
|
|
14282
|
+
if (text2) {
|
|
14283
|
+
if (!text2.open) return [];
|
|
14284
|
+
text2.open = false;
|
|
14285
|
+
return [{ event: "end", block: text2.kind, blockIndex: text2.index }];
|
|
14286
|
+
}
|
|
14287
|
+
const call = calls.get(key);
|
|
14288
|
+
return call ? endCall(call) : [];
|
|
14289
|
+
}
|
|
14290
|
+
return {
|
|
14291
|
+
append(kind, key, fragment) {
|
|
14292
|
+
if (fragment === "") return [];
|
|
14293
|
+
const events = [];
|
|
14294
|
+
let block2 = texts.get(key);
|
|
14295
|
+
if (!block2) {
|
|
14296
|
+
block2 = { kind, index: next++, text: "", open: true };
|
|
14297
|
+
texts.set(key, block2);
|
|
14298
|
+
events.push({ event: "start", block: kind, blockIndex: block2.index });
|
|
14299
|
+
}
|
|
14300
|
+
if (!block2.open) return [];
|
|
14301
|
+
block2.text += fragment;
|
|
14302
|
+
events.push({ event: "delta", block: kind, blockIndex: block2.index, text: fragment });
|
|
14303
|
+
return events;
|
|
14304
|
+
},
|
|
14305
|
+
toolDelta(key, update) {
|
|
14306
|
+
const call = callFor(key);
|
|
14307
|
+
if (!call.open) return [];
|
|
14308
|
+
const events = [];
|
|
14309
|
+
if (call.index === void 0) {
|
|
14310
|
+
if (typeof update.id === "string" && update.id !== "" && call.id === void 0) call.id = update.id;
|
|
14311
|
+
if (typeof update.name === "string" && update.name !== "" && call.name === void 0) {
|
|
14312
|
+
call.name = update.name;
|
|
14313
|
+
call.id ??= synthesizeLlmToolCallId();
|
|
14314
|
+
}
|
|
14315
|
+
if (call.id !== void 0 && call.name !== void 0) events.push(...startCall(call));
|
|
14316
|
+
}
|
|
14317
|
+
if (typeof update.fragment === "string" && update.fragment !== "") {
|
|
14318
|
+
if (call.index === void 0) call.held.push(update.fragment);
|
|
14319
|
+
else events.push(deltaOf(call, update.fragment));
|
|
14320
|
+
}
|
|
14321
|
+
return events;
|
|
14322
|
+
},
|
|
14323
|
+
toolWhole(key, update) {
|
|
14324
|
+
const call = callFor(key);
|
|
14325
|
+
if (typeof update.name !== "string" || update.name === "") throw new LlmServiceError("provider-error", BAD_CALL2);
|
|
14326
|
+
call.name = update.name;
|
|
14327
|
+
call.id = typeof update.id === "string" && update.id !== "" ? update.id : synthesizeLlmToolCallId();
|
|
14328
|
+
const args = parseToolArguments(update.args);
|
|
14329
|
+
return [...startCall(call), deltaOf(call, JSON.stringify(args)), ...endCall(call)];
|
|
14330
|
+
},
|
|
14331
|
+
end: endKey,
|
|
14332
|
+
closeAll() {
|
|
14333
|
+
const open = [];
|
|
14334
|
+
for (const [key, block2] of texts) if (block2.open) open.push({ index: block2.index, key });
|
|
14335
|
+
for (const [key, call] of calls) if (call.open && call.index !== void 0) open.push({ index: call.index, key });
|
|
14336
|
+
return open.sort((a, b) => a.index - b.index).flatMap((entry) => endKey(entry.key));
|
|
14337
|
+
},
|
|
14338
|
+
content(completedTurn) {
|
|
14339
|
+
const parts = [];
|
|
14340
|
+
for (const block2 of texts.values()) parts.push({ index: block2.index, part: { type: block2.kind, text: block2.text } });
|
|
14341
|
+
for (const call of calls.values()) {
|
|
14342
|
+
if (!completedTurn) continue;
|
|
14343
|
+
if (call.index === void 0) throw new LlmServiceError("provider-error", BAD_CALL2);
|
|
14344
|
+
const toolCallId = call.id;
|
|
14345
|
+
const name = call.name;
|
|
14346
|
+
parts.push({ index: call.index, part: { type: "toolCall", toolCallId, name, arguments: parseToolArguments(call.sent.join("")) } });
|
|
14347
|
+
}
|
|
14348
|
+
return parts.sort((a, b) => a.index - b.index).map((entry) => entry.part);
|
|
14349
|
+
}
|
|
14350
|
+
};
|
|
14351
|
+
}
|
|
13773
14352
|
var DEFAULT_MAX_OUTPUT_TOKENS = 4096;
|
|
13774
14353
|
var ANTHROPIC_VERSION = "2023-06-01";
|
|
13775
14354
|
var JSON_INSTRUCTION = "Respond with a single JSON object and no other text.";
|
|
13776
|
-
function
|
|
14355
|
+
function unsupported5(message22) {
|
|
13777
14356
|
return new LlmServiceError("unsupported", message22);
|
|
13778
14357
|
}
|
|
13779
14358
|
function providerError(message22) {
|
|
@@ -13793,69 +14372,84 @@ function credentialHeaders(endpoint) {
|
|
|
13793
14372
|
if (header === "authorization-bearer") return { authorization: `Bearer ${endpoint.credential}` };
|
|
13794
14373
|
return { [header]: endpoint.credential };
|
|
13795
14374
|
}
|
|
14375
|
+
function plainParts(parts) {
|
|
14376
|
+
return parts.map((part) => {
|
|
14377
|
+
if (part.type === "text" || part.type === "image") return part;
|
|
14378
|
+
throw unsupported5("This provider mapping does not accept this content part.");
|
|
14379
|
+
});
|
|
14380
|
+
}
|
|
13796
14381
|
function textOf(parts) {
|
|
13797
|
-
return parts.map((
|
|
14382
|
+
return plainParts(parts).map((part) => part.type === "text" ? part.text : "").join("");
|
|
13798
14383
|
}
|
|
13799
14384
|
function hasImage(parts) {
|
|
13800
|
-
return parts.some((
|
|
14385
|
+
return parts.some((part) => part.type === "image");
|
|
13801
14386
|
}
|
|
13802
14387
|
function record2(value) {
|
|
13803
14388
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
|
|
13804
14389
|
}
|
|
13805
|
-
|
|
13806
|
-
|
|
13807
|
-
|
|
14390
|
+
var count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
14391
|
+
function usageFrom(input, output, extras = {}) {
|
|
14392
|
+
if (!count(input) || !count(output)) return void 0;
|
|
14393
|
+
const usage2 = { inputTokens: input, outputTokens: output };
|
|
14394
|
+
if (count(extras.cacheReadTokens)) usage2.cacheReadTokens = extras.cacheReadTokens;
|
|
14395
|
+
if (count(extras.cacheWriteTokens)) usage2.cacheWriteTokens = extras.cacheWriteTokens;
|
|
14396
|
+
if (count(extras.reasoningTokens)) usage2.reasoningTokens = extras.reasoningTokens;
|
|
14397
|
+
return usage2;
|
|
13808
14398
|
}
|
|
13809
|
-
function finished(
|
|
13810
|
-
return usage2 ? {
|
|
14399
|
+
function finished(content, finish, usage2) {
|
|
14400
|
+
return usage2 ? { content, finish, usage: usage2 } : { content, finish };
|
|
13811
14401
|
}
|
|
13812
|
-
function
|
|
13813
|
-
|
|
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}` } });
|
|
14402
|
+
function textContent(text2) {
|
|
14403
|
+
return text2 === "" ? [] : [{ type: "text", text: text2 }];
|
|
13815
14404
|
}
|
|
13816
|
-
function
|
|
13817
|
-
|
|
13818
|
-
|
|
13819
|
-
|
|
13820
|
-
|
|
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
|
-
};
|
|
14405
|
+
function completed(content, finish, usage2) {
|
|
14406
|
+
if (finish === null) throw providerError("The provider response had no recognised completion marker.");
|
|
14407
|
+
if (finish === "length" || finish === "refusal") return finished(content.filter((part) => part.type !== "toolCall"), finish, usage2);
|
|
14408
|
+
const calls = content.some((part) => part.type === "toolCall");
|
|
14409
|
+
return finished(content, finish === "stop" && calls ? "toolUse" : finish, usage2);
|
|
13831
14410
|
}
|
|
13832
|
-
function
|
|
13833
|
-
|
|
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);
|
|
14411
|
+
function isCompletedFinish(finish) {
|
|
14412
|
+
return finish === "stop" || finish === "toolUse";
|
|
13842
14413
|
}
|
|
13843
|
-
|
|
13844
|
-
|
|
13845
|
-
|
|
13846
|
-
return reason === "content_filter" ? "refusal" : null;
|
|
14414
|
+
var DEFAULT_TOOL_PARAMETERS = { type: "object", properties: {}, additionalProperties: false };
|
|
14415
|
+
function toolsOf(request) {
|
|
14416
|
+
return request.tools ?? [];
|
|
13847
14417
|
}
|
|
13848
|
-
function
|
|
13849
|
-
|
|
13850
|
-
if (reason === "max_tokens") return "length";
|
|
13851
|
-
return reason === "refusal" ? "refusal" : null;
|
|
14418
|
+
function parametersOf(tool2) {
|
|
14419
|
+
return tool2.parameters ?? DEFAULT_TOOL_PARAMETERS;
|
|
13852
14420
|
}
|
|
13853
|
-
function
|
|
13854
|
-
|
|
13855
|
-
return finished(text2, finish, usage2);
|
|
14421
|
+
function callsOf3(message22) {
|
|
14422
|
+
return message22.content.filter((part) => part.type === "toolCall");
|
|
13856
14423
|
}
|
|
13857
|
-
function
|
|
13858
|
-
return
|
|
14424
|
+
function nonCallParts(message22) {
|
|
14425
|
+
return plainParts(message22.content.filter((part) => part.type !== "toolCall"));
|
|
14426
|
+
}
|
|
14427
|
+
function outputLimit(endpoint, request) {
|
|
14428
|
+
const limits = [request.maxTokens, endpoint.maxOutputTokens].filter((limit) => limit !== void 0);
|
|
14429
|
+
return limits.length === 0 ? void 0 : Math.min(...limits);
|
|
14430
|
+
}
|
|
14431
|
+
var TOOL_FAILED = "Tool execution failed.";
|
|
14432
|
+
function toolResultText(message22) {
|
|
14433
|
+
if (hasImage(message22.content)) throw unsupported5("This provider does not accept images in tool results.");
|
|
14434
|
+
const texts = plainParts(message22.content).map((part) => part.type === "text" ? part.text : "");
|
|
14435
|
+
return (message22.isError === true ? [TOOL_FAILED, ...texts] : texts).join("\n");
|
|
14436
|
+
}
|
|
14437
|
+
var OPAQUE_REASONING_MODEL = /^(models\/)?gemini-([3-9]|\d{2,})/;
|
|
14438
|
+
var TEMPERATURE_CEILING = { "openai-chat": 2, "anthropic-messages": 1, gemini: 2 };
|
|
14439
|
+
function needsOpaqueReasoning(endpoint) {
|
|
14440
|
+
return endpoint.requiresOpaqueReasoning ?? (endpoint.protocol === "gemini" && OPAQUE_REASONING_MODEL.test(endpoint.model));
|
|
14441
|
+
}
|
|
14442
|
+
function prepareRequest(endpoint, request) {
|
|
14443
|
+
if (needsOpaqueReasoning(endpoint) && request.messages.some((message22) => callsOf3(message22).length > 0)) {
|
|
14444
|
+
throw unsupported5("This model needs reasoning state that NAP-LLM cannot carry, so a conversation containing tool calls cannot continue on it.");
|
|
14445
|
+
}
|
|
14446
|
+
const ceiling = TEMPERATURE_CEILING[endpoint.protocol];
|
|
14447
|
+
if (request.temperature !== void 0 && (request.temperature < 0 || request.temperature > ceiling)) {
|
|
14448
|
+
throw unsupported5(`This provider accepts a temperature between 0 and ${ceiling}.`);
|
|
14449
|
+
}
|
|
14450
|
+
const messages = request.messages.map((message22) => ({ ...message22, content: message22.content.filter((part) => part.type !== "thinking") })).filter((message22) => message22.content.length > 0);
|
|
14451
|
+
if (messages.length === 0) throw unsupported5("Nothing remains to send once display-only thinking is omitted.");
|
|
14452
|
+
return { ...request, messages };
|
|
13859
14453
|
}
|
|
13860
14454
|
function splitSystem(messages) {
|
|
13861
14455
|
const systemParts = [];
|
|
@@ -13865,29 +14459,83 @@ function splitSystem(messages) {
|
|
|
13865
14459
|
turns.push(message22);
|
|
13866
14460
|
continue;
|
|
13867
14461
|
}
|
|
13868
|
-
if (hasImage(message22.content)) throw
|
|
14462
|
+
if (hasImage(message22.content)) throw unsupported5("This provider does not accept images in system messages.");
|
|
13869
14463
|
systemParts.push(textOf(message22.content));
|
|
13870
14464
|
}
|
|
13871
14465
|
return { system: systemParts.join("\n"), turns };
|
|
13872
14466
|
}
|
|
14467
|
+
var STREAM_ERROR = "The provider reported an error while streaming.";
|
|
14468
|
+
function textField(value) {
|
|
14469
|
+
return typeof value === "string" ? value : "";
|
|
14470
|
+
}
|
|
14471
|
+
function anthropicFinish(reason) {
|
|
14472
|
+
if (reason === "end_turn" || reason === "stop_sequence") return "stop";
|
|
14473
|
+
if (reason === "max_tokens") return "length";
|
|
14474
|
+
if (reason === "tool_use") return "toolUse";
|
|
14475
|
+
return reason === "refusal" ? "refusal" : null;
|
|
14476
|
+
}
|
|
14477
|
+
function anthropicBlocks(parts) {
|
|
14478
|
+
return parts.map((part) => {
|
|
14479
|
+
switch (part.type) {
|
|
14480
|
+
case "text":
|
|
14481
|
+
return { type: "text", text: part.text };
|
|
14482
|
+
case "toolCall":
|
|
14483
|
+
return { type: "tool_use", id: part.toolCallId, name: part.name, input: part.arguments };
|
|
14484
|
+
case "image":
|
|
14485
|
+
return { type: "image", source: { type: "base64", media_type: part.mimeType, data: part.data } };
|
|
14486
|
+
default:
|
|
14487
|
+
throw unsupported5("This provider mapping does not accept this content part.");
|
|
14488
|
+
}
|
|
14489
|
+
});
|
|
14490
|
+
}
|
|
14491
|
+
function anthropicTurn(message22) {
|
|
14492
|
+
if (message22.role === "assistant") return { role: "assistant", content: anthropicBlocks(message22.content) };
|
|
14493
|
+
if (message22.role !== "toolResult") return { role: "user", content: anthropicBlocks(message22.content) };
|
|
14494
|
+
const result2 = {
|
|
14495
|
+
type: "tool_result",
|
|
14496
|
+
tool_use_id: message22.toolCallId,
|
|
14497
|
+
content: anthropicBlocks(plainParts(message22.content)),
|
|
14498
|
+
...message22.isError === true ? { is_error: true } : {}
|
|
14499
|
+
};
|
|
14500
|
+
return { role: "user", content: [result2] };
|
|
14501
|
+
}
|
|
14502
|
+
function anthropicToolChoice(choice) {
|
|
14503
|
+
if (choice === "required") return { type: "any" };
|
|
14504
|
+
return typeof choice === "string" ? { type: choice } : { type: "tool", name: choice.name };
|
|
14505
|
+
}
|
|
13873
14506
|
function buildAnthropicMessages(endpoint, request, stream) {
|
|
14507
|
+
const tools = toolsOf(request);
|
|
14508
|
+
if (tools.length === 0 && hasLlmToolHistory(request.messages)) {
|
|
14509
|
+
throw unsupported5("This provider needs tool definitions to continue a conversation that contains tool calls.");
|
|
14510
|
+
}
|
|
13874
14511
|
const { system, turns } = splitSystem(request.messages);
|
|
13875
|
-
if (turns.length === 0 || turns[0].role
|
|
14512
|
+
if (turns.length === 0 || turns[0].role === "assistant" || turns[0].role === "toolResult") {
|
|
14513
|
+
throw unsupported5("This provider requires the first non-system message to come from the user.");
|
|
14514
|
+
}
|
|
13876
14515
|
const merged = [];
|
|
13877
14516
|
for (const turn of turns) {
|
|
14517
|
+
const next = anthropicTurn(turn);
|
|
13878
14518
|
const previous = merged.at(-1);
|
|
13879
|
-
|
|
13880
|
-
|
|
13881
|
-
else merged.push({ role: turn.role, content: blocks });
|
|
14519
|
+
if (previous && previous.role === next.role) previous.content.push(...next.content);
|
|
14520
|
+
else merged.push(next);
|
|
13882
14521
|
}
|
|
13883
14522
|
const systemText = request.format === "json" ? [system, JSON_INSTRUCTION].filter(Boolean).join("\n") : system;
|
|
13884
14523
|
const body = {
|
|
13885
14524
|
model: endpoint.model,
|
|
13886
|
-
max_tokens: endpoint
|
|
14525
|
+
max_tokens: outputLimit(endpoint, request) ?? DEFAULT_MAX_OUTPUT_TOKENS,
|
|
13887
14526
|
messages: merged,
|
|
13888
14527
|
stream
|
|
13889
14528
|
};
|
|
13890
14529
|
if (systemText) body.system = systemText;
|
|
14530
|
+
if (request.temperature !== void 0) body.temperature = request.temperature;
|
|
14531
|
+
if (tools.length > 0) {
|
|
14532
|
+
body.tools = tools.map((tool2) => ({
|
|
14533
|
+
name: tool2.name,
|
|
14534
|
+
...tool2.description === void 0 ? {} : { description: tool2.description },
|
|
14535
|
+
input_schema: parametersOf(tool2)
|
|
14536
|
+
}));
|
|
14537
|
+
if (request.toolChoice !== void 0) body.tool_choice = anthropicToolChoice(request.toolChoice);
|
|
14538
|
+
}
|
|
13891
14539
|
return {
|
|
13892
14540
|
url: `${trimBase(endpoint.baseUrl)}/messages`,
|
|
13893
14541
|
method: "POST",
|
|
@@ -13901,31 +14549,148 @@ function buildAnthropicMessages(endpoint, request, stream) {
|
|
|
13901
14549
|
body: JSON.stringify(body)
|
|
13902
14550
|
};
|
|
13903
14551
|
}
|
|
14552
|
+
function anthropicUsage(usage2) {
|
|
14553
|
+
return usageFrom(usage2?.input_tokens, usage2?.output_tokens, {
|
|
14554
|
+
cacheReadTokens: usage2?.cache_read_input_tokens,
|
|
14555
|
+
cacheWriteTokens: usage2?.cache_creation_input_tokens
|
|
14556
|
+
});
|
|
14557
|
+
}
|
|
13904
14558
|
function parseAnthropicMessages(json) {
|
|
13905
14559
|
const root = record2(json);
|
|
13906
14560
|
if (!root || !Array.isArray(root.content)) throw providerError("The provider response had no content blocks.");
|
|
13907
|
-
const
|
|
14561
|
+
const finish = anthropicFinish(root.stop_reason);
|
|
14562
|
+
const partial = finish === "length" || finish === "refusal";
|
|
14563
|
+
const content = [];
|
|
14564
|
+
for (const block2 of root.content) {
|
|
13908
14565
|
const entry = record2(block2);
|
|
13909
|
-
|
|
13910
|
-
|
|
13911
|
-
|
|
13912
|
-
|
|
13913
|
-
|
|
14566
|
+
const previous = content.at(-1);
|
|
14567
|
+
if (entry?.type === "text" && typeof entry.text === "string") {
|
|
14568
|
+
if (previous?.type === "text") previous.text += entry.text;
|
|
14569
|
+
else content.push(...textContent(entry.text));
|
|
14570
|
+
} else if (entry?.type === "thinking" && typeof entry.thinking === "string" && entry.thinking !== "") {
|
|
14571
|
+
content.push({ type: "thinking", text: entry.thinking });
|
|
14572
|
+
} else if (entry?.type === "tool_use") {
|
|
14573
|
+
const raw = { id: entry.id, name: entry.name, args: entry.input };
|
|
14574
|
+
content.push(...toolCallParts(partial, [raw]));
|
|
14575
|
+
}
|
|
14576
|
+
}
|
|
14577
|
+
return completed(content, finish, anthropicUsage(record2(root.usage)));
|
|
14578
|
+
}
|
|
14579
|
+
function anthropicAccumulator() {
|
|
14580
|
+
const blocks = createLlmBlockBuilder();
|
|
14581
|
+
let finish = null;
|
|
14582
|
+
let start = null;
|
|
14583
|
+
let delta = null;
|
|
14584
|
+
return {
|
|
14585
|
+
push(event) {
|
|
14586
|
+
const root = record2(event);
|
|
14587
|
+
const key = String(root?.index);
|
|
14588
|
+
switch (root?.type) {
|
|
14589
|
+
case "error":
|
|
14590
|
+
throw providerError(STREAM_ERROR);
|
|
14591
|
+
case "message_start":
|
|
14592
|
+
start = record2(record2(root.message)?.usage);
|
|
14593
|
+
return [];
|
|
14594
|
+
case "message_delta":
|
|
14595
|
+
finish = anthropicFinish(record2(root.delta)?.stop_reason) ?? finish;
|
|
14596
|
+
delta = { ...delta, ...record2(root.usage) };
|
|
14597
|
+
return [];
|
|
14598
|
+
case "content_block_start": {
|
|
14599
|
+
const block2 = record2(root.content_block);
|
|
14600
|
+
if (block2?.type !== "tool_use") return [];
|
|
14601
|
+
return blocks.toolDelta(key, { id: block2.id, name: block2.name });
|
|
14602
|
+
}
|
|
14603
|
+
case "content_block_delta": {
|
|
14604
|
+
const part = record2(root.delta);
|
|
14605
|
+
if (part?.type === "text_delta") return blocks.append("text", key, textField(part.text));
|
|
14606
|
+
if (part?.type === "thinking_delta") return blocks.append("thinking", key, textField(part.thinking));
|
|
14607
|
+
return part?.type === "input_json_delta" ? blocks.toolDelta(key, { fragment: part.partial_json }) : [];
|
|
14608
|
+
}
|
|
14609
|
+
case "content_block_stop":
|
|
14610
|
+
return blocks.end(key);
|
|
14611
|
+
case "message_stop":
|
|
14612
|
+
return blocks.closeAll();
|
|
14613
|
+
default:
|
|
14614
|
+
return [];
|
|
14615
|
+
}
|
|
14616
|
+
},
|
|
14617
|
+
finish: () => completed(blocks.content(isCompletedFinish(finish)), finish, anthropicUsage({ ...start, ...delta }))
|
|
14618
|
+
};
|
|
14619
|
+
}
|
|
14620
|
+
var STREAM_ERROR2 = "The provider reported an error while streaming.";
|
|
14621
|
+
var GEMINI_REFUSALS = /* @__PURE__ */ new Set(["SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "IMAGE_SAFETY"]);
|
|
14622
|
+
function textField2(value) {
|
|
14623
|
+
return typeof value === "string" ? value : "";
|
|
13914
14624
|
}
|
|
13915
14625
|
function geminiParts(parts) {
|
|
13916
|
-
return parts.map((
|
|
14626
|
+
return parts.map((part) => {
|
|
14627
|
+
switch (part.type) {
|
|
14628
|
+
case "text":
|
|
14629
|
+
return { text: part.text };
|
|
14630
|
+
case "toolCall":
|
|
14631
|
+
return { functionCall: { name: part.name, args: part.arguments } };
|
|
14632
|
+
case "image":
|
|
14633
|
+
return { inlineData: { mimeType: part.mimeType, data: part.data } };
|
|
14634
|
+
default:
|
|
14635
|
+
throw unsupported5("This provider mapping does not accept this content part.");
|
|
14636
|
+
}
|
|
14637
|
+
});
|
|
14638
|
+
}
|
|
14639
|
+
function geminiResults(results, callOrder) {
|
|
14640
|
+
const ordered = [...results].sort((a, b) => callOrder.indexOf(a.toolCallId ?? "") - callOrder.indexOf(b.toolCallId ?? ""));
|
|
14641
|
+
return {
|
|
14642
|
+
role: "user",
|
|
14643
|
+
parts: ordered.map((result2) => ({ functionResponse: { name: result2.toolName, response: { output: toolResultText(result2) } } }))
|
|
14644
|
+
};
|
|
14645
|
+
}
|
|
14646
|
+
function geminiContents(turns) {
|
|
14647
|
+
const contents = [];
|
|
14648
|
+
let callOrder = [];
|
|
14649
|
+
for (let index = 0; index < turns.length; index += 1) {
|
|
14650
|
+
const turn = turns[index];
|
|
14651
|
+
if (turn.role === "toolResult") {
|
|
14652
|
+
const group = [turn];
|
|
14653
|
+
while (turns[index + 1]?.role === "toolResult") {
|
|
14654
|
+
index += 1;
|
|
14655
|
+
group.push(turns[index]);
|
|
14656
|
+
}
|
|
14657
|
+
contents.push(geminiResults(group, callOrder));
|
|
14658
|
+
continue;
|
|
14659
|
+
}
|
|
14660
|
+
if (turn.role === "assistant") callOrder = callsOf3(turn).map((call) => call.toolCallId);
|
|
14661
|
+
contents.push({ role: turn.role === "assistant" ? "model" : "user", parts: geminiParts(turn.role === "assistant" ? turn.content : plainParts(turn.content)) });
|
|
14662
|
+
}
|
|
14663
|
+
return contents;
|
|
14664
|
+
}
|
|
14665
|
+
function geminiToolConfig(choice) {
|
|
14666
|
+
if (choice === "auto") return { functionCallingConfig: { mode: "AUTO" } };
|
|
14667
|
+
if (choice === "none") return { functionCallingConfig: { mode: "NONE" } };
|
|
14668
|
+
if (choice === "required") return { functionCallingConfig: { mode: "ANY" } };
|
|
14669
|
+
return { functionCallingConfig: { mode: "ANY", allowedFunctionNames: [choice.name] } };
|
|
13917
14670
|
}
|
|
13918
14671
|
function buildGemini(endpoint, request, stream) {
|
|
13919
14672
|
const { system, turns } = splitSystem(request.messages);
|
|
13920
|
-
if (turns.length === 0) throw
|
|
14673
|
+
if (turns.length === 0) throw unsupported5("This provider requires at least one user or assistant message.");
|
|
14674
|
+
const tools = toolsOf(request);
|
|
14675
|
+
if (request.format === "json" && tools.length > 0) throw unsupported5("This provider cannot combine JSON-object output with tool calling.");
|
|
13921
14676
|
const generationConfig = {};
|
|
13922
14677
|
if (request.format === "json") generationConfig.responseMimeType = "application/json";
|
|
13923
|
-
|
|
13924
|
-
|
|
13925
|
-
|
|
13926
|
-
};
|
|
14678
|
+
const limit = outputLimit(endpoint, request);
|
|
14679
|
+
if (limit !== void 0) generationConfig.maxOutputTokens = limit;
|
|
14680
|
+
if (request.temperature !== void 0) generationConfig.temperature = request.temperature;
|
|
14681
|
+
const body = { contents: geminiContents(turns) };
|
|
13927
14682
|
if (system) body.systemInstruction = { parts: [{ text: system }] };
|
|
13928
14683
|
if (Object.keys(generationConfig).length > 0) body.generationConfig = generationConfig;
|
|
14684
|
+
if (tools.length > 0) {
|
|
14685
|
+
body.tools = [{
|
|
14686
|
+
functionDeclarations: tools.map((tool2) => ({
|
|
14687
|
+
name: tool2.name,
|
|
14688
|
+
...tool2.description === void 0 ? {} : { description: tool2.description },
|
|
14689
|
+
parametersJsonSchema: parametersOf(tool2)
|
|
14690
|
+
}))
|
|
14691
|
+
}];
|
|
14692
|
+
if (request.toolChoice !== void 0) body.toolConfig = geminiToolConfig(request.toolChoice);
|
|
14693
|
+
}
|
|
13929
14694
|
return {
|
|
13930
14695
|
url: `${trimBase(endpoint.baseUrl)}/models/${encodeURIComponent(endpoint.model)}:${stream ? "streamGenerateContent?alt=sse" : "generateContent"}`,
|
|
13931
14696
|
method: "POST",
|
|
@@ -13933,38 +14698,214 @@ function buildGemini(endpoint, request, stream) {
|
|
|
13933
14698
|
body: JSON.stringify(body)
|
|
13934
14699
|
};
|
|
13935
14700
|
}
|
|
13936
|
-
|
|
14701
|
+
function geminiUsage(value) {
|
|
14702
|
+
const usage2 = record2(value);
|
|
14703
|
+
return usageFrom(usage2?.promptTokenCount, usage2?.candidatesTokenCount, {
|
|
14704
|
+
cacheReadTokens: usage2?.cachedContentTokenCount,
|
|
14705
|
+
reasoningTokens: usage2?.thoughtsTokenCount
|
|
14706
|
+
});
|
|
14707
|
+
}
|
|
14708
|
+
function partsOf(candidate) {
|
|
14709
|
+
const parts = record2(candidate.content)?.parts;
|
|
14710
|
+
return Array.isArray(parts) ? parts.flatMap((part) => {
|
|
14711
|
+
const entry = record2(part);
|
|
14712
|
+
return entry ? [entry] : [];
|
|
14713
|
+
}) : [];
|
|
14714
|
+
}
|
|
13937
14715
|
function parseGemini(json) {
|
|
13938
14716
|
const root = record2(json);
|
|
13939
|
-
const
|
|
13940
|
-
|
|
13941
|
-
const feedback = record2(root?.promptFeedback);
|
|
13942
|
-
if (typeof feedback?.blockReason === "string") return finished("", "refusal", tokens);
|
|
14717
|
+
const tokens = geminiUsage(root?.usageMetadata);
|
|
14718
|
+
if (typeof record2(root?.promptFeedback)?.blockReason === "string") return finished([], "refusal", tokens);
|
|
13943
14719
|
const candidate = record2(Array.isArray(root?.candidates) ? root?.candidates[0] : void 0);
|
|
13944
14720
|
if (!candidate) throw providerError("The provider response had no candidate.");
|
|
13945
|
-
const
|
|
13946
|
-
const
|
|
13947
|
-
|
|
13948
|
-
|
|
13949
|
-
|
|
13950
|
-
|
|
14721
|
+
const finish = geminiFinish(candidate.finishReason);
|
|
14722
|
+
const partial = finish === "length" || finish === "refusal";
|
|
14723
|
+
const content = [];
|
|
14724
|
+
for (const part of partsOf(candidate)) {
|
|
14725
|
+
const call = record2(part.functionCall);
|
|
14726
|
+
if (call) {
|
|
14727
|
+
const raw = { id: call.id, name: call.name, args: call.args };
|
|
14728
|
+
content.push(...toolCallParts(partial, [raw]));
|
|
14729
|
+
continue;
|
|
14730
|
+
}
|
|
14731
|
+
const kind = part.thought === true ? "thinking" : "text";
|
|
14732
|
+
const text2 = textField2(part.text);
|
|
14733
|
+
const previous = content.at(-1);
|
|
14734
|
+
if (text2 === "") continue;
|
|
14735
|
+
if (previous?.type === kind) previous.text += text2;
|
|
14736
|
+
else content.push(...kind === "text" ? textContent(text2) : [{ type: "thinking", text: text2 }]);
|
|
14737
|
+
}
|
|
14738
|
+
return completed(content, finish, tokens);
|
|
13951
14739
|
}
|
|
13952
14740
|
function geminiFinish(reason) {
|
|
13953
14741
|
if (reason === "STOP") return "stop";
|
|
13954
14742
|
if (reason === "MAX_TOKENS") return "length";
|
|
13955
14743
|
return typeof reason === "string" && GEMINI_REFUSALS.has(reason) ? "refusal" : null;
|
|
13956
14744
|
}
|
|
14745
|
+
function geminiAccumulator() {
|
|
14746
|
+
const blocks = createLlmBlockBuilder();
|
|
14747
|
+
let blocked = false;
|
|
14748
|
+
let finish = null;
|
|
14749
|
+
let usage2;
|
|
14750
|
+
let calls = 0;
|
|
14751
|
+
return {
|
|
14752
|
+
push(event) {
|
|
14753
|
+
const root = record2(event);
|
|
14754
|
+
if (root?.error !== void 0) throw providerError(STREAM_ERROR2);
|
|
14755
|
+
usage2 = geminiUsage(root?.usageMetadata) ?? usage2;
|
|
14756
|
+
if (typeof record2(root?.promptFeedback)?.blockReason === "string") blocked = true;
|
|
14757
|
+
const candidate = record2(Array.isArray(root?.candidates) ? root?.candidates[0] : void 0);
|
|
14758
|
+
if (!candidate) return [];
|
|
14759
|
+
const events = [];
|
|
14760
|
+
for (const part of partsOf(candidate)) {
|
|
14761
|
+
const call = record2(part.functionCall);
|
|
14762
|
+
if (call) {
|
|
14763
|
+
calls += 1;
|
|
14764
|
+
events.push(...blocks.toolWhole(`call-${calls}`, { id: call.id, name: call.name, args: call.args }));
|
|
14765
|
+
} else if (part.thought === true) {
|
|
14766
|
+
events.push(...blocks.append("thinking", "thinking", textField2(part.text)));
|
|
14767
|
+
} else {
|
|
14768
|
+
events.push(...blocks.append("text", "text", textField2(part.text)));
|
|
14769
|
+
}
|
|
14770
|
+
}
|
|
14771
|
+
finish = geminiFinish(candidate.finishReason) ?? finish;
|
|
14772
|
+
if (finish !== null) events.push(...blocks.closeAll());
|
|
14773
|
+
return events;
|
|
14774
|
+
},
|
|
14775
|
+
finish: () => blocked ? completed([], "refusal", usage2) : completed(blocks.content(isCompletedFinish(finish)), finish, usage2)
|
|
14776
|
+
};
|
|
14777
|
+
}
|
|
14778
|
+
var STREAM_ERROR3 = "The provider reported an error while streaming.";
|
|
14779
|
+
function textField3(value) {
|
|
14780
|
+
return typeof value === "string" ? value : "";
|
|
14781
|
+
}
|
|
14782
|
+
function openAiContent(parts) {
|
|
14783
|
+
const plain = plainParts(parts);
|
|
14784
|
+
if (!hasImage(plain)) return plain.map((part) => part.type === "text" ? part.text : "").join("");
|
|
14785
|
+
return plain.map((part) => part.type === "text" ? { type: "text", text: part.text } : { type: "image_url", image_url: { url: `data:${part.mimeType};base64,${part.data}` } });
|
|
14786
|
+
}
|
|
14787
|
+
function openAiMessage(message22) {
|
|
14788
|
+
if (message22.role === "toolResult") return { role: "tool", tool_call_id: message22.toolCallId, content: toolResultText(message22) };
|
|
14789
|
+
if (message22.role !== "assistant") return { role: message22.role, content: openAiContent(message22.content) };
|
|
14790
|
+
const calls = callsOf3(message22);
|
|
14791
|
+
const parts = nonCallParts(message22);
|
|
14792
|
+
const entry = { role: "assistant", content: parts.length === 0 && calls.length > 0 ? null : openAiContent(parts) };
|
|
14793
|
+
if (calls.length > 0) {
|
|
14794
|
+
entry.tool_calls = calls.map((call) => ({ id: call.toolCallId, type: "function", function: { name: call.name, arguments: JSON.stringify(call.arguments) } }));
|
|
14795
|
+
}
|
|
14796
|
+
return entry;
|
|
14797
|
+
}
|
|
14798
|
+
function openAiToolChoice(choice) {
|
|
14799
|
+
return typeof choice === "string" ? choice : { type: "function", function: { name: choice.name } };
|
|
14800
|
+
}
|
|
14801
|
+
function buildOpenAiChat(endpoint, request, stream) {
|
|
14802
|
+
const body = {
|
|
14803
|
+
model: endpoint.model,
|
|
14804
|
+
messages: request.messages.map(openAiMessage),
|
|
14805
|
+
stream
|
|
14806
|
+
};
|
|
14807
|
+
if (stream) body.stream_options = { include_usage: true };
|
|
14808
|
+
if (request.format === "json") body.response_format = { type: "json_object" };
|
|
14809
|
+
const limit = outputLimit(endpoint, request);
|
|
14810
|
+
if (limit !== void 0) body.max_tokens = limit;
|
|
14811
|
+
if (request.temperature !== void 0) body.temperature = request.temperature;
|
|
14812
|
+
const tools = toolsOf(request);
|
|
14813
|
+
if (tools.length > 0) {
|
|
14814
|
+
body.tools = tools.map((tool2) => ({
|
|
14815
|
+
type: "function",
|
|
14816
|
+
function: { name: tool2.name, ...tool2.description === void 0 ? {} : { description: tool2.description }, parameters: parametersOf(tool2) }
|
|
14817
|
+
}));
|
|
14818
|
+
if (request.toolChoice !== void 0) body.tool_choice = openAiToolChoice(request.toolChoice);
|
|
14819
|
+
}
|
|
14820
|
+
return {
|
|
14821
|
+
url: `${trimBase(endpoint.baseUrl)}/chat/completions`,
|
|
14822
|
+
method: "POST",
|
|
14823
|
+
headers: { "content-type": "application/json", ...endpoint.headers, ...credentialHeaders(endpoint) },
|
|
14824
|
+
body: JSON.stringify(body)
|
|
14825
|
+
};
|
|
14826
|
+
}
|
|
14827
|
+
function openAiUsage(value) {
|
|
14828
|
+
const usage2 = record2(value);
|
|
14829
|
+
return usageFrom(usage2?.prompt_tokens, usage2?.completion_tokens, {
|
|
14830
|
+
cacheReadTokens: record2(usage2?.prompt_tokens_details)?.cached_tokens,
|
|
14831
|
+
reasoningTokens: record2(usage2?.completion_tokens_details)?.reasoning_tokens
|
|
14832
|
+
});
|
|
14833
|
+
}
|
|
14834
|
+
function reasoningOf(source) {
|
|
14835
|
+
return textField3(source?.reasoning_content) || textField3(source?.reasoning);
|
|
14836
|
+
}
|
|
14837
|
+
function rawCallsOf(message22) {
|
|
14838
|
+
const calls = Array.isArray(message22.tool_calls) ? message22.tool_calls : [];
|
|
14839
|
+
return calls.map((call) => {
|
|
14840
|
+
const entry = record2(call);
|
|
14841
|
+
const fn = record2(entry?.function);
|
|
14842
|
+
return { id: entry?.id, name: fn?.name, args: fn?.arguments };
|
|
14843
|
+
});
|
|
14844
|
+
}
|
|
14845
|
+
function parseOpenAiChat(json) {
|
|
14846
|
+
const root = record2(json);
|
|
14847
|
+
const choice = record2(Array.isArray(root?.choices) ? root?.choices[0] : void 0);
|
|
14848
|
+
const message22 = record2(choice?.message);
|
|
14849
|
+
if (!choice || !message22) throw providerError("The provider response had no completion choice.");
|
|
14850
|
+
const tokens = openAiUsage(root?.usage);
|
|
14851
|
+
if (typeof message22.refusal === "string" && message22.refusal.length > 0) return finished([], "refusal", tokens);
|
|
14852
|
+
const finish = openAiFinish(choice.finish_reason);
|
|
14853
|
+
const content = [];
|
|
14854
|
+
const thinking = reasoningOf(message22);
|
|
14855
|
+
if (thinking !== "") content.push({ type: "thinking", text: thinking });
|
|
14856
|
+
content.push(...textContent(typeof message22.content === "string" ? message22.content : ""));
|
|
14857
|
+
content.push(...toolCallParts(finish === "length" || finish === "refusal", rawCallsOf(message22)));
|
|
14858
|
+
return completed(content, finish, tokens);
|
|
14859
|
+
}
|
|
14860
|
+
function openAiFinish(reason) {
|
|
14861
|
+
if (reason === "stop") return "stop";
|
|
14862
|
+
if (reason === "length") return "length";
|
|
14863
|
+
if (reason === "tool_calls" || reason === "function_call") return "toolUse";
|
|
14864
|
+
return reason === "content_filter" ? "refusal" : null;
|
|
14865
|
+
}
|
|
14866
|
+
function openAiAccumulator() {
|
|
14867
|
+
const blocks = createLlmBlockBuilder();
|
|
14868
|
+
let refused = false;
|
|
14869
|
+
let finish = null;
|
|
14870
|
+
let usage2;
|
|
14871
|
+
return {
|
|
14872
|
+
push(event) {
|
|
14873
|
+
const root = record2(event);
|
|
14874
|
+
if (root?.error !== void 0) throw providerError(STREAM_ERROR3);
|
|
14875
|
+
usage2 = openAiUsage(root?.usage) ?? usage2;
|
|
14876
|
+
const choice = record2(Array.isArray(root?.choices) ? root?.choices[0] : void 0);
|
|
14877
|
+
if (!choice) return [];
|
|
14878
|
+
const delta = record2(choice.delta);
|
|
14879
|
+
if (textField3(delta?.refusal).length > 0) refused = true;
|
|
14880
|
+
const events = [
|
|
14881
|
+
...blocks.append("thinking", "thinking", reasoningOf(delta)),
|
|
14882
|
+
...blocks.append("text", "text", textField3(delta?.content))
|
|
14883
|
+
];
|
|
14884
|
+
const calls = Array.isArray(delta?.tool_calls) ? delta.tool_calls : [];
|
|
14885
|
+
calls.forEach((call, position) => {
|
|
14886
|
+
const entry = record2(call);
|
|
14887
|
+
const fn = record2(entry?.function);
|
|
14888
|
+
events.push(...blocks.toolDelta(String(entry?.index ?? position), { id: entry?.id, name: fn?.name, fragment: fn?.arguments }));
|
|
14889
|
+
});
|
|
14890
|
+
finish = openAiFinish(choice.finish_reason) ?? finish;
|
|
14891
|
+
if (finish !== null) events.push(...blocks.closeAll());
|
|
14892
|
+
return events;
|
|
14893
|
+
},
|
|
14894
|
+
finish: () => refused ? completed([], "refusal", usage2) : completed(blocks.content(isCompletedFinish(finish)), finish, usage2)
|
|
14895
|
+
};
|
|
14896
|
+
}
|
|
13957
14897
|
function buildLlmProviderRequest(endpoint, request, options = {}) {
|
|
13958
14898
|
const stream = options.stream === true;
|
|
14899
|
+
const prepared = prepareRequest(endpoint, request);
|
|
13959
14900
|
switch (endpoint.protocol) {
|
|
13960
14901
|
case "openai-chat":
|
|
13961
|
-
return buildOpenAiChat(endpoint,
|
|
14902
|
+
return buildOpenAiChat(endpoint, prepared, stream);
|
|
13962
14903
|
case "anthropic-messages":
|
|
13963
|
-
return buildAnthropicMessages(endpoint,
|
|
14904
|
+
return buildAnthropicMessages(endpoint, prepared, stream);
|
|
13964
14905
|
case "gemini":
|
|
13965
|
-
return buildGemini(endpoint,
|
|
14906
|
+
return buildGemini(endpoint, prepared, stream);
|
|
13966
14907
|
default:
|
|
13967
|
-
throw
|
|
14908
|
+
throw unsupported5("Unknown provider protocol.");
|
|
13968
14909
|
}
|
|
13969
14910
|
}
|
|
13970
14911
|
function parseLlmProviderResponse(protocol, json) {
|
|
@@ -13979,90 +14920,6 @@ function parseLlmProviderResponse(protocol, json) {
|
|
|
13979
14920
|
throw providerError("Unknown provider protocol.");
|
|
13980
14921
|
}
|
|
13981
14922
|
}
|
|
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
14923
|
function createLlmStreamAccumulator(protocol) {
|
|
14067
14924
|
switch (protocol) {
|
|
14068
14925
|
case "openai-chat":
|
|
@@ -14177,8 +15034,9 @@ async function readStream(protocol, body, signal, onDelta) {
|
|
|
14177
15034
|
try {
|
|
14178
15035
|
for await (const data of readLlmSseData(body, signal)) {
|
|
14179
15036
|
if (data === "[DONE]") continue;
|
|
14180
|
-
const
|
|
14181
|
-
if (
|
|
15037
|
+
const events = accumulator.push(parseStreamEvent(data));
|
|
15038
|
+
if (signal.aborted) continue;
|
|
15039
|
+
for (const event of events) onDelta?.(event);
|
|
14182
15040
|
}
|
|
14183
15041
|
} catch (error) {
|
|
14184
15042
|
if (signal.aborted) throw abortReason(signal);
|
|
@@ -14787,6 +15645,66 @@ function installPajaResourceSettings() {
|
|
|
14787
15645
|
return { getServers: settings.getServers, dispose: () => form?.removeEventListener("submit", submit) };
|
|
14788
15646
|
}
|
|
14789
15647
|
|
|
15648
|
+
// src/browser-security-settings.ts
|
|
15649
|
+
var STORAGE_KEY2 = "kehto:paja:nested-context-lock";
|
|
15650
|
+
function isSetting(value) {
|
|
15651
|
+
return value === "auto" || value === "on" || value === "off";
|
|
15652
|
+
}
|
|
15653
|
+
function readStoredNestedContextLockSetting(getStorage = () => localStorage) {
|
|
15654
|
+
try {
|
|
15655
|
+
const stored = getStorage().getItem(STORAGE_KEY2);
|
|
15656
|
+
return isSetting(stored) ? stored : null;
|
|
15657
|
+
} catch {
|
|
15658
|
+
return null;
|
|
15659
|
+
}
|
|
15660
|
+
}
|
|
15661
|
+
function createPajaSecuritySettings(getStorage = () => localStorage) {
|
|
15662
|
+
let setting = readStoredNestedContextLockSetting(getStorage);
|
|
15663
|
+
let status = setting ? `Frame-creation lock forced ${setting} for this host.` : "Frame-creation lock follows the host default.";
|
|
15664
|
+
return {
|
|
15665
|
+
getSetting: () => setting,
|
|
15666
|
+
getStatus: () => status,
|
|
15667
|
+
save(next) {
|
|
15668
|
+
if (next !== "" && !isSetting(next)) {
|
|
15669
|
+
return { ok: false, message: "Choose host default, auto, on, or off." };
|
|
15670
|
+
}
|
|
15671
|
+
try {
|
|
15672
|
+
const storage = getStorage();
|
|
15673
|
+
if (next === "") {
|
|
15674
|
+
storage.removeItem(STORAGE_KEY2);
|
|
15675
|
+
setting = null;
|
|
15676
|
+
status = "Frame-creation lock follows the host default.";
|
|
15677
|
+
} else {
|
|
15678
|
+
storage.setItem(STORAGE_KEY2, next);
|
|
15679
|
+
setting = next;
|
|
15680
|
+
status = `Frame-creation lock forced ${next}; applies on the next napplet load.`;
|
|
15681
|
+
}
|
|
15682
|
+
} catch {
|
|
15683
|
+
setting = next === "" ? null : next;
|
|
15684
|
+
status = "Applied for this session only; storage is unavailable, so the choice will not persist.";
|
|
15685
|
+
}
|
|
15686
|
+
return { ok: true, message: status };
|
|
15687
|
+
}
|
|
15688
|
+
};
|
|
15689
|
+
}
|
|
15690
|
+
function installPajaSecuritySettings() {
|
|
15691
|
+
const settings = createPajaSecuritySettings();
|
|
15692
|
+
const select2 = document.getElementById("paja-nested-context-lock");
|
|
15693
|
+
const status = document.getElementById("paja-nested-context-lock-status");
|
|
15694
|
+
if (!select2 || !status) return { getSetting: settings.getSetting, dispose: () => {
|
|
15695
|
+
} };
|
|
15696
|
+
select2.value = settings.getSetting() ?? "";
|
|
15697
|
+
status.textContent = settings.getStatus();
|
|
15698
|
+
const onChange = () => {
|
|
15699
|
+
const result2 = settings.save(select2.value);
|
|
15700
|
+
select2.setAttribute("aria-invalid", String(!result2.ok));
|
|
15701
|
+
status.textContent = result2.message;
|
|
15702
|
+
if (!result2.ok) select2.value = settings.getSetting() ?? "";
|
|
15703
|
+
};
|
|
15704
|
+
select2.addEventListener("change", onChange);
|
|
15705
|
+
return { getSetting: settings.getSetting, dispose: () => select2.removeEventListener("change", onChange) };
|
|
15706
|
+
}
|
|
15707
|
+
|
|
14790
15708
|
// src/browser-llm-models.ts
|
|
14791
15709
|
var PajaLlmModelsError = class extends Error {
|
|
14792
15710
|
constructor(failure4, message3) {
|
|
@@ -14862,6 +15780,7 @@ var PAJA_LLM_CONNECTIONS_STORAGE_KEY = "kehto:paja:llm-connections:v1";
|
|
|
14862
15780
|
var MAX_CONNECTIONS = 32;
|
|
14863
15781
|
var PROTOCOLS = /* @__PURE__ */ new Set(["openai-chat", "anthropic-messages", "gemini"]);
|
|
14864
15782
|
var CREDENTIAL_HEADERS = /* @__PURE__ */ new Set(["authorization-bearer", "api-key", "x-api-key", "x-goog-api-key"]);
|
|
15783
|
+
var TOOL_CHOICE_ORDER = ["auto", "none", "required", "tool"];
|
|
14865
15784
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
14866
15785
|
function normalizePajaLlmBaseUrl(value) {
|
|
14867
15786
|
let url;
|
|
@@ -14881,6 +15800,11 @@ function normalizePajaLlmBaseUrl(value) {
|
|
|
14881
15800
|
function isRecord4(value) {
|
|
14882
15801
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
14883
15802
|
}
|
|
15803
|
+
function canonicalToolChoiceModes(tools, requested) {
|
|
15804
|
+
if (!tools) return [];
|
|
15805
|
+
const wanted = new Set(Array.isArray(requested) ? requested : []);
|
|
15806
|
+
return TOOL_CHOICE_ORDER.filter((mode) => mode === "auto" || mode === "none" || wanted.has(mode));
|
|
15807
|
+
}
|
|
14884
15808
|
function normalizeRecord(input) {
|
|
14885
15809
|
const text2 = (value) => typeof value === "string" ? value : "";
|
|
14886
15810
|
const name = text2(input.name).trim();
|
|
@@ -14895,6 +15819,7 @@ function normalizeRecord(input) {
|
|
|
14895
15819
|
if (!PROTOCOLS.has(protocol)) throw new Error("Unknown provider protocol.");
|
|
14896
15820
|
if (credentialHeader !== void 0 && !CREDENTIAL_HEADERS.has(credentialHeader)) throw new Error("Unknown credential header.");
|
|
14897
15821
|
if (!["vault", "session", "none"].includes(credentialStorage)) throw new Error("Unknown credential storage.");
|
|
15822
|
+
const tools = input.tools === true;
|
|
14898
15823
|
const record3 = {
|
|
14899
15824
|
id,
|
|
14900
15825
|
name,
|
|
@@ -14904,6 +15829,8 @@ function normalizeRecord(input) {
|
|
|
14904
15829
|
model,
|
|
14905
15830
|
images: input.images === true,
|
|
14906
15831
|
json: input.json === true,
|
|
15832
|
+
tools,
|
|
15833
|
+
toolChoiceModes: Object.freeze(canonicalToolChoiceModes(tools, input.toolChoiceModes)),
|
|
14907
15834
|
credentialStorage,
|
|
14908
15835
|
...credentialHeader ? { credentialHeader } : {}
|
|
14909
15836
|
};
|
|
@@ -14975,29 +15902,59 @@ function describePajaLlmRoute(record3) {
|
|
|
14975
15902
|
return `Paja (this browser) \u2192 ${label}`;
|
|
14976
15903
|
}
|
|
14977
15904
|
function toConnection(record3) {
|
|
14978
|
-
|
|
15905
|
+
const tools = record3.tools === true;
|
|
15906
|
+
return {
|
|
15907
|
+
id: record3.id,
|
|
15908
|
+
name: record3.name,
|
|
15909
|
+
model: record3.model,
|
|
15910
|
+
route: describePajaLlmRoute(record3),
|
|
15911
|
+
images: record3.images,
|
|
15912
|
+
json: record3.json,
|
|
15913
|
+
tools,
|
|
15914
|
+
toolChoiceModes: tools ? canonicalToolChoiceModes(true, record3.toolChoiceModes) : []
|
|
15915
|
+
};
|
|
14979
15916
|
}
|
|
14980
15917
|
function meets(record3, requirements2) {
|
|
14981
15918
|
if (requirements2.model !== void 0 && requirements2.model !== record3.model) return false;
|
|
14982
15919
|
if (requirements2.images === true && !record3.images) return false;
|
|
15920
|
+
if (requirements2.tools === true && record3.tools !== true) return false;
|
|
14983
15921
|
return !(requirements2.json === true && !record3.json);
|
|
14984
15922
|
}
|
|
14985
15923
|
function describeRequirements(requirements2) {
|
|
14986
15924
|
const parts = [
|
|
14987
15925
|
requirements2.model ? `model ${requirements2.model}` : "any model",
|
|
14988
15926
|
requirements2.images ? "image input" : null,
|
|
14989
|
-
requirements2.json ? "JSON output" : null
|
|
14990
|
-
|
|
15927
|
+
requirements2.json ? "JSON output" : null,
|
|
15928
|
+
requirements2.tools ? "tool calling" : null
|
|
15929
|
+
].filter((part) => part !== null);
|
|
14991
15930
|
return parts.join(", ");
|
|
14992
15931
|
}
|
|
14993
15932
|
function countCharacters(request) {
|
|
14994
15933
|
let total = 0;
|
|
14995
|
-
for (const message3 of request.messages)
|
|
15934
|
+
for (const message3 of request.messages) {
|
|
15935
|
+
for (const part of message3.content) {
|
|
15936
|
+
if (part.type === "text") total += part.text.length;
|
|
15937
|
+
else if (part.type === "toolCall") total += JSON.stringify(part.arguments).length;
|
|
15938
|
+
}
|
|
15939
|
+
}
|
|
15940
|
+
for (const tool2 of request.tools ?? []) total += JSON.stringify(tool2).length;
|
|
14996
15941
|
return total;
|
|
14997
15942
|
}
|
|
15943
|
+
function countToolResults(request) {
|
|
15944
|
+
return request.messages.filter((message3) => message3.role === "toolResult").length;
|
|
15945
|
+
}
|
|
14998
15946
|
function createPajaLlmHost(options) {
|
|
14999
15947
|
const { store: store2, vault, confirm, getIdentity } = options;
|
|
15000
15948
|
const provider = options.provider ?? createHttpLlmProvider({ stream: true });
|
|
15949
|
+
function endpointFor(record3, credential) {
|
|
15950
|
+
return {
|
|
15951
|
+
protocol: record3.protocol,
|
|
15952
|
+
baseUrl: record3.baseUrl,
|
|
15953
|
+
model: record3.model,
|
|
15954
|
+
...credential === void 0 ? {} : { credential },
|
|
15955
|
+
...record3.credentialHeader ? { credentialHeader: record3.credentialHeader } : {}
|
|
15956
|
+
};
|
|
15957
|
+
}
|
|
15001
15958
|
async function ensureCredential(record3, signal) {
|
|
15002
15959
|
if (record3.credentialStorage === "none") return void 0;
|
|
15003
15960
|
const existing = vault.getCredential(record3.id);
|
|
@@ -15043,6 +16000,7 @@ function createPajaLlmHost(options) {
|
|
|
15043
16000
|
const signal = prompt?.signal;
|
|
15044
16001
|
const record3 = store2.get(connection.id);
|
|
15045
16002
|
if (!record3) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
|
|
16003
|
+
buildLlmProviderRequest(endpointFor(record3), request, { stream: true });
|
|
15046
16004
|
await ensureCredential(record3, signal);
|
|
15047
16005
|
if (signal?.aborted) return false;
|
|
15048
16006
|
return confirm({
|
|
@@ -15056,21 +16014,17 @@ function createPajaLlmHost(options) {
|
|
|
15056
16014
|
messages: request.messages.length,
|
|
15057
16015
|
characters: countCharacters(request),
|
|
15058
16016
|
images: countLlmImages(request.messages),
|
|
16017
|
+
tools: (request.tools ?? []).map((tool2) => tool2.name),
|
|
16018
|
+
toolResults: countToolResults(request),
|
|
15059
16019
|
format: request.format ?? "text",
|
|
15060
|
-
warning: "The prompt text and
|
|
16020
|
+
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."
|
|
15061
16021
|
});
|
|
15062
16022
|
},
|
|
15063
16023
|
async generate(_context, connection, request, hooks) {
|
|
15064
16024
|
const record3 = store2.get(connection.id);
|
|
15065
16025
|
if (!record3) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
|
|
15066
16026
|
const credential = await ensureCredential(record3);
|
|
15067
|
-
return provider(
|
|
15068
|
-
protocol: record3.protocol,
|
|
15069
|
-
baseUrl: record3.baseUrl,
|
|
15070
|
-
model: record3.model,
|
|
15071
|
-
...credential === void 0 ? {} : { credential },
|
|
15072
|
-
...record3.credentialHeader ? { credentialHeader: record3.credentialHeader } : {}
|
|
15073
|
-
}, request, hooks.signal, (text2) => hooks.onDelta(text2));
|
|
16027
|
+
return provider(endpointFor(record3, credential), request, hooks.signal, (event) => hooks.onDelta(event));
|
|
15074
16028
|
},
|
|
15075
16029
|
subscribe(listener) {
|
|
15076
16030
|
const stopStore = store2.subscribe(listener);
|
|
@@ -15343,7 +16297,7 @@ function createChooserDialog() {
|
|
|
15343
16297
|
choose(candidates, context) {
|
|
15344
16298
|
if (settle7) finish(null);
|
|
15345
16299
|
if (context.signal?.aborted) return Promise.resolve(null);
|
|
15346
|
-
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(", ");
|
|
16300
|
+
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(", ");
|
|
15347
16301
|
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.`;
|
|
15348
16302
|
select2.replaceChildren(...candidates.map((record3) => {
|
|
15349
16303
|
const option = document.createElement("option");
|
|
@@ -15388,10 +16342,13 @@ function readForm() {
|
|
|
15388
16342
|
const remember = byId("paja-llm-remember", HTMLInputElement);
|
|
15389
16343
|
const images = byId("paja-llm-images", HTMLInputElement);
|
|
15390
16344
|
const json = byId("paja-llm-json", HTMLInputElement);
|
|
16345
|
+
const tools = byId("paja-llm-tools", HTMLInputElement);
|
|
16346
|
+
const toolRequired = byId("paja-llm-tool-required", HTMLInputElement);
|
|
16347
|
+
const toolNamed = byId("paja-llm-tool-named", HTMLInputElement);
|
|
15391
16348
|
const list = byId("paja-llm-connections", HTMLElement);
|
|
15392
16349
|
const status = byId("paja-llm-status", HTMLElement);
|
|
15393
16350
|
const lock = byId("paja-llm-vault-lock", HTMLButtonElement);
|
|
15394
|
-
if (!form || !preset || !name || !baseUrl || !model || !modelField || !modelSelect || !modelSelectField || !modelStatus || !examples || !credential || !remember || !images || !json || !list || !status || !lock) return null;
|
|
16351
|
+
if (!form || !preset || !name || !baseUrl || !model || !modelField || !modelSelect || !modelSelectField || !modelStatus || !examples || !credential || !remember || !images || !json || !tools || !toolRequired || !toolNamed || !list || !status || !lock) return null;
|
|
15395
16352
|
return {
|
|
15396
16353
|
form,
|
|
15397
16354
|
preset,
|
|
@@ -15407,6 +16364,9 @@ function readForm() {
|
|
|
15407
16364
|
remember,
|
|
15408
16365
|
images,
|
|
15409
16366
|
json,
|
|
16367
|
+
tools,
|
|
16368
|
+
toolRequired,
|
|
16369
|
+
toolNamed,
|
|
15410
16370
|
list,
|
|
15411
16371
|
status,
|
|
15412
16372
|
lock,
|
|
@@ -15538,7 +16498,7 @@ function installPajaLlmPanel(options) {
|
|
|
15538
16498
|
label.className = "llm-connection-label";
|
|
15539
16499
|
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";
|
|
15540
16500
|
label.textContent = `${record3.name} \xB7 ${record3.model} \xB7 ${new URL(record3.baseUrl).origin} \xB7 ${tier}`;
|
|
15541
|
-
label.title = `${record3.protocol}${record3.images ? " \xB7 images" : ""}${record3.json ? " \xB7 json" : ""}`;
|
|
16501
|
+
label.title = `${record3.protocol}${record3.images ? " \xB7 images" : ""}${record3.json ? " \xB7 json" : ""}${record3.tools ? " \xB7 tools" : ""}`;
|
|
15542
16502
|
const remove = document.createElement("button");
|
|
15543
16503
|
remove.type = "button";
|
|
15544
16504
|
remove.textContent = "Remove";
|
|
@@ -15566,6 +16526,10 @@ function installPajaLlmPanel(options) {
|
|
|
15566
16526
|
renderList();
|
|
15567
16527
|
options.onChange?.();
|
|
15568
16528
|
}
|
|
16529
|
+
function toolChoiceModes(form) {
|
|
16530
|
+
if (!form.tools.checked) return [];
|
|
16531
|
+
return [...form.toolRequired.checked ? ["required"] : [], ...form.toolNamed.checked ? ["tool"] : []];
|
|
16532
|
+
}
|
|
15569
16533
|
async function submit(event) {
|
|
15570
16534
|
event.preventDefault();
|
|
15571
16535
|
if (!elements) return;
|
|
@@ -15588,6 +16552,8 @@ function installPajaLlmPanel(options) {
|
|
|
15588
16552
|
model,
|
|
15589
16553
|
images: elements.images.checked,
|
|
15590
16554
|
json: elements.json.checked,
|
|
16555
|
+
tools: elements.tools.checked,
|
|
16556
|
+
toolChoiceModes: toolChoiceModes(elements),
|
|
15591
16557
|
credentialStorage: storage,
|
|
15592
16558
|
...preset?.credentialHeader ? { credentialHeader: preset.credentialHeader } : {}
|
|
15593
16559
|
};
|
|
@@ -15619,6 +16585,12 @@ function installPajaLlmPanel(options) {
|
|
|
15619
16585
|
const onSubmit = (event) => {
|
|
15620
16586
|
void submit(event);
|
|
15621
16587
|
};
|
|
16588
|
+
const onTools = () => {
|
|
16589
|
+
for (const option of [elements.toolRequired, elements.toolNamed]) {
|
|
16590
|
+
option.disabled = !elements.tools.checked;
|
|
16591
|
+
if (!elements.tools.checked) option.checked = false;
|
|
16592
|
+
}
|
|
16593
|
+
};
|
|
15622
16594
|
const onLock = () => {
|
|
15623
16595
|
vault.lock();
|
|
15624
16596
|
renderList();
|
|
@@ -15628,12 +16600,15 @@ function installPajaLlmPanel(options) {
|
|
|
15628
16600
|
elements.preset.addEventListener("change", onPreset);
|
|
15629
16601
|
elements.baseUrl.addEventListener("change", onBaseUrl);
|
|
15630
16602
|
elements.form.addEventListener("submit", onSubmit);
|
|
16603
|
+
elements.tools.addEventListener("change", onTools);
|
|
15631
16604
|
elements.lock.addEventListener("click", onLock);
|
|
16605
|
+
onTools();
|
|
15632
16606
|
disposers.push(() => {
|
|
15633
16607
|
modelListing?.abort();
|
|
15634
16608
|
elements.preset.removeEventListener("change", onPreset);
|
|
15635
16609
|
elements.baseUrl.removeEventListener("change", onBaseUrl);
|
|
15636
16610
|
elements.form.removeEventListener("submit", onSubmit);
|
|
16611
|
+
elements.tools.removeEventListener("change", onTools);
|
|
15637
16612
|
elements.lock.removeEventListener("click", onLock);
|
|
15638
16613
|
});
|
|
15639
16614
|
renderList();
|
|
@@ -16294,7 +17269,7 @@ var sessionRegistry = {
|
|
|
16294
17269
|
}
|
|
16295
17270
|
};
|
|
16296
17271
|
var nappKeyRegistry = sessionRegistry;
|
|
16297
|
-
var
|
|
17272
|
+
var STORAGE_KEY3 = "napplet:acl";
|
|
16298
17273
|
var DEFAULT_STATE_QUOTA = 512 * 1024;
|
|
16299
17274
|
function aclKey(_pubkey, dTag, aggregateHash) {
|
|
16300
17275
|
return `${dTag}:${aggregateHash}`;
|
|
@@ -16461,14 +17436,14 @@ var aclStore = {
|
|
|
16461
17436
|
stateQuota: val.stateQuota
|
|
16462
17437
|
}
|
|
16463
17438
|
]);
|
|
16464
|
-
localStorage.setItem(
|
|
17439
|
+
localStorage.setItem(STORAGE_KEY3, JSON.stringify(entries));
|
|
16465
17440
|
} catch {
|
|
16466
17441
|
}
|
|
16467
17442
|
},
|
|
16468
17443
|
/** Load the ACL store from localStorage. Migrates old 3-segment keys to 2-segment format. */
|
|
16469
17444
|
load() {
|
|
16470
17445
|
try {
|
|
16471
|
-
const raw = localStorage.getItem(
|
|
17446
|
+
const raw = localStorage.getItem(STORAGE_KEY3);
|
|
16472
17447
|
if (!raw) return;
|
|
16473
17448
|
let entries = JSON.parse(raw);
|
|
16474
17449
|
const hasOldKeys = entries.some(([key]) => key.split(":").length === 3);
|
|
@@ -16496,7 +17471,7 @@ var aclStore = {
|
|
|
16496
17471
|
stateQuota: entry.quota
|
|
16497
17472
|
}];
|
|
16498
17473
|
});
|
|
16499
|
-
localStorage.setItem(
|
|
17474
|
+
localStorage.setItem(STORAGE_KEY3, JSON.stringify(entries));
|
|
16500
17475
|
}
|
|
16501
17476
|
}
|
|
16502
17477
|
store.clear();
|
|
@@ -16532,7 +17507,7 @@ var aclStore = {
|
|
|
16532
17507
|
clear() {
|
|
16533
17508
|
store.clear();
|
|
16534
17509
|
try {
|
|
16535
|
-
localStorage.removeItem(
|
|
17510
|
+
localStorage.removeItem(STORAGE_KEY3);
|
|
16536
17511
|
} catch {
|
|
16537
17512
|
}
|
|
16538
17513
|
}
|
|
@@ -17221,7 +18196,7 @@ function createIntentUriNormalizer() {
|
|
|
17221
18196
|
relays.push(relay);
|
|
17222
18197
|
} else if (type === 2) {
|
|
17223
18198
|
if (pubkey2 !== void 0 || value.length !== 32) fail2("Intent URI fragment has an invalid pubkey");
|
|
17224
|
-
pubkey2 = value.map((
|
|
18199
|
+
pubkey2 = value.map((part) => part.toString(16).padStart(2, "0")).join("");
|
|
17225
18200
|
} else if (type === 3) {
|
|
17226
18201
|
if (kind !== void 0 || value.length !== 4) fail2("Intent URI fragment has an invalid kind");
|
|
17227
18202
|
kind = (value[0] << 24 >>> 0 | value[1] << 16 | value[2] << 8 | value[3]) >>> 0;
|
|
@@ -17330,7 +18305,76 @@ function scriptJson(value) {
|
|
|
17330
18305
|
}
|
|
17331
18306
|
function renderNappletNamespacePrelude(options) {
|
|
17332
18307
|
const domains = uniqueBareDomains(options.domains);
|
|
17333
|
-
|
|
18308
|
+
const frameLock = options.experimental?.nestedContextLock ? nappletFrameLock.toString() : "(function(){})";
|
|
18309
|
+
return `<script data-kehto-nip5d-injection>(${nappletNamespacePrelude.toString()})(${scriptJson(domains)}, (${createIntentUriNormalizer.toString()})(), ${frameLock});<\/script>`;
|
|
18310
|
+
}
|
|
18311
|
+
function nappletFrameLock(win) {
|
|
18312
|
+
const FRAME_ELEMENTS2 = /* @__PURE__ */ new Set([
|
|
18313
|
+
"iframe",
|
|
18314
|
+
"frame",
|
|
18315
|
+
"frameset",
|
|
18316
|
+
"object",
|
|
18317
|
+
"embed",
|
|
18318
|
+
"portal",
|
|
18319
|
+
"fencedframe"
|
|
18320
|
+
]);
|
|
18321
|
+
const isFrameTag = (value) => FRAME_ELEMENTS2.has(String(value).toLowerCase());
|
|
18322
|
+
const FRAME_TAG2 = /<\/?(?:iframe|frame|frameset|object|embed|portal|fencedframe)(?=[\s/>]|$)/i;
|
|
18323
|
+
const FRAME_TAG_PREFIX = /<[a-zA-Z]*$/;
|
|
18324
|
+
const { trustedTypes } = win;
|
|
18325
|
+
if (trustedTypes) {
|
|
18326
|
+
try {
|
|
18327
|
+
trustedTypes.createPolicy("default", {
|
|
18328
|
+
createHTML: (input, ...rest) => {
|
|
18329
|
+
const sink = rest.length >= 2 ? String(rest[1]) : "";
|
|
18330
|
+
const blocked = /write/i.test(sink) ? FRAME_TAG2.test(input) || FRAME_TAG_PREFIX.test(input) : FRAME_TAG2.test(input);
|
|
18331
|
+
if (blocked) throw new TypeError("kehto: napplets may not create nested browsing contexts");
|
|
18332
|
+
return input;
|
|
18333
|
+
},
|
|
18334
|
+
createScript: (input) => input,
|
|
18335
|
+
createScriptURL: (input) => input
|
|
18336
|
+
});
|
|
18337
|
+
} catch {
|
|
18338
|
+
}
|
|
18339
|
+
}
|
|
18340
|
+
const pin = (object, name, value) => {
|
|
18341
|
+
try {
|
|
18342
|
+
Object.defineProperty(object, name, {
|
|
18343
|
+
value,
|
|
18344
|
+
writable: false,
|
|
18345
|
+
configurable: false,
|
|
18346
|
+
enumerable: false
|
|
18347
|
+
});
|
|
18348
|
+
} catch {
|
|
18349
|
+
}
|
|
18350
|
+
};
|
|
18351
|
+
const localName = (qualified) => String(qualified ?? "").split(":").pop().toLowerCase();
|
|
18352
|
+
const HTML_NS = "http://www.w3.org/1999/xhtml";
|
|
18353
|
+
const docProto = win.Document?.prototype;
|
|
18354
|
+
if (docProto) {
|
|
18355
|
+
const createElement = docProto.createElement;
|
|
18356
|
+
pin(docProto, "createElement", function(tagName, ...rest) {
|
|
18357
|
+
if (isFrameTag(tagName)) throw new TypeError("kehto: napplets may not create nested browsing contexts");
|
|
18358
|
+
return createElement.call(this, tagName, ...rest);
|
|
18359
|
+
});
|
|
18360
|
+
const createElementNS = docProto.createElementNS;
|
|
18361
|
+
pin(docProto, "createElementNS", function(namespace, qualifiedName, ...rest) {
|
|
18362
|
+
if (namespace === HTML_NS && FRAME_ELEMENTS2.has(localName(qualifiedName))) {
|
|
18363
|
+
throw new TypeError("kehto: napplets may not create nested browsing contexts");
|
|
18364
|
+
}
|
|
18365
|
+
return createElementNS.call(this, namespace, qualifiedName, ...rest);
|
|
18366
|
+
});
|
|
18367
|
+
}
|
|
18368
|
+
const domImpl = win.DOMImplementation?.prototype;
|
|
18369
|
+
if (domImpl) {
|
|
18370
|
+
const createDocument = domImpl.createDocument;
|
|
18371
|
+
pin(domImpl, "createDocument", function(namespace, qualifiedName, ...rest) {
|
|
18372
|
+
if (namespace === HTML_NS && FRAME_ELEMENTS2.has(localName(qualifiedName))) {
|
|
18373
|
+
throw new TypeError("kehto: napplets may not create nested browsing contexts");
|
|
18374
|
+
}
|
|
18375
|
+
return createDocument.call(this, namespace, qualifiedName, ...rest);
|
|
18376
|
+
});
|
|
18377
|
+
}
|
|
17334
18378
|
}
|
|
17335
18379
|
function injectNappletNamespacePrelude(html, options) {
|
|
17336
18380
|
const prelude = renderNappletNamespacePrelude(options);
|
|
@@ -17346,7 +18390,7 @@ function injectNappletNamespacePrelude(html, options) {
|
|
|
17346
18390
|
}
|
|
17347
18391
|
return `${prelude}${html}`;
|
|
17348
18392
|
}
|
|
17349
|
-
function nappletNamespacePrelude(domains, normalizeIntentUri2) {
|
|
18393
|
+
function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
|
|
17350
18394
|
const target = window;
|
|
17351
18395
|
const allowed2 = new Set(domains);
|
|
17352
18396
|
const requestTimeoutMs = 3e4;
|
|
@@ -17372,6 +18416,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
|
|
|
17372
18416
|
} catch {
|
|
17373
18417
|
}
|
|
17374
18418
|
}
|
|
18419
|
+
frameLock(target);
|
|
17375
18420
|
function id() {
|
|
17376
18421
|
if (target.crypto?.randomUUID) return target.crypto.randomUUID();
|
|
17377
18422
|
return `napplet-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
@@ -18185,7 +19230,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
|
|
|
18185
19230
|
(msg) => ({ notificationId: fieldOrThrow(msg, "notificationId", "notify.send.result missing notificationId") })
|
|
18186
19231
|
),
|
|
18187
19232
|
dismiss: (notificationId) => fire({ type: "notify.dismiss", notificationId }),
|
|
18188
|
-
badge: (
|
|
19233
|
+
badge: (count2) => fire({ type: "notify.badge", count: count2 }),
|
|
18189
19234
|
registerChannel: (channel2) => fire({ type: "notify.channel.register", ...channel2 }),
|
|
18190
19235
|
requestPermission: (channel2) => request(
|
|
18191
19236
|
{ type: "notify.permission.request", ...channel2 ? { channel: channel2 } : {} },
|
|
@@ -18782,6 +19827,25 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
|
|
|
18782
19827
|
};
|
|
18783
19828
|
}
|
|
18784
19829
|
function makeLlm() {
|
|
19830
|
+
const asDelta = (msg, requestId, expected) => {
|
|
19831
|
+
const { sequence, event, block: block2, blockIndex, text: text2, toolCallId, name } = msg;
|
|
19832
|
+
if (sequence !== expected) return null;
|
|
19833
|
+
if (event !== "start" && event !== "delta" && event !== "end") return null;
|
|
19834
|
+
if (block2 !== "text" && block2 !== "thinking" && block2 !== "toolCall") return null;
|
|
19835
|
+
if (typeof blockIndex !== "number" || !Number.isInteger(blockIndex) || blockIndex < 0) return null;
|
|
19836
|
+
if (event === "delta" ? typeof text2 !== "string" : text2 !== void 0) return null;
|
|
19837
|
+
const identified = event === "start" && block2 === "toolCall";
|
|
19838
|
+
const validId = typeof toolCallId === "string" && toolCallId.length > 0;
|
|
19839
|
+
const validName = typeof name === "string" && name.length > 0;
|
|
19840
|
+
if (identified ? !validId || !validName : toolCallId !== void 0 || name !== void 0) return null;
|
|
19841
|
+
const delta = { requestId, sequence: expected, event, block: block2, blockIndex };
|
|
19842
|
+
if (text2 !== void 0) delta.text = text2;
|
|
19843
|
+
if (identified) {
|
|
19844
|
+
delta.toolCallId = toolCallId;
|
|
19845
|
+
delta.name = name;
|
|
19846
|
+
}
|
|
19847
|
+
return delta;
|
|
19848
|
+
};
|
|
18785
19849
|
const asFailure = (value) => {
|
|
18786
19850
|
if (!value || typeof value !== "object") return null;
|
|
18787
19851
|
const { code, message: message3 } = value;
|
|
@@ -18800,9 +19864,10 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2) {
|
|
|
18800
19864
|
const msg = event.data;
|
|
18801
19865
|
if (typeof msg !== "object" || msg === null) return;
|
|
18802
19866
|
if (type === "llm.generate" && msg.type === "llm.delta" && msg.requestId === requestId) {
|
|
18803
|
-
|
|
19867
|
+
const delta = asDelta(msg, requestId, nextSequence);
|
|
19868
|
+
if (!delta) return;
|
|
18804
19869
|
nextSequence += 1;
|
|
18805
|
-
options.onDelta?.(
|
|
19870
|
+
options.onDelta?.(delta);
|
|
18806
19871
|
return;
|
|
18807
19872
|
}
|
|
18808
19873
|
if (msg.type !== `${type}.result` || msg.id !== requestId) return;
|
|
@@ -19046,7 +20111,7 @@ function requireBootstrapScripts(directive, sources2) {
|
|
|
19046
20111
|
throw new Error(`CSP ${directive} must allow the shell's inline namespace bootstrap`);
|
|
19047
20112
|
}
|
|
19048
20113
|
}
|
|
19049
|
-
function buildNappletCsp(options = {}) {
|
|
20114
|
+
function buildNappletCsp(options = {}, lockTrustedTypes = false) {
|
|
19050
20115
|
const grants = [...new Set((options.connectOrigins ?? []).map(connectionOrigin))].sort();
|
|
19051
20116
|
const policy = {
|
|
19052
20117
|
...DEFAULT_DIRECTIVES,
|
|
@@ -19068,16 +20133,60 @@ function buildNappletCsp(options = {}) {
|
|
|
19068
20133
|
}
|
|
19069
20134
|
requireBootstrapScripts("script-src", policy["script-src"]);
|
|
19070
20135
|
if (policy["script-src-elem"]) requireBootstrapScripts("script-src-elem", policy["script-src-elem"]);
|
|
19071
|
-
|
|
20136
|
+
const sourceLists = Object.entries(policy).map(([name, sources2]) => `${name} ${sources2.join(" ")}`);
|
|
20137
|
+
if (lockTrustedTypes) sourceLists.push(TRUSTED_TYPES_DIRECTIVES);
|
|
20138
|
+
return sourceLists.join("; ");
|
|
19072
20139
|
}
|
|
19073
|
-
|
|
19074
|
-
|
|
20140
|
+
var TRUSTED_TYPES_DIRECTIVES = "require-trusted-types-for 'script'; trusted-types default";
|
|
20141
|
+
function renderNappletCspMeta(options = {}, lockTrustedTypes = false) {
|
|
20142
|
+
const policy = buildNappletCsp(options, lockTrustedTypes).replace(/&/g, "&").replace(/"/g, """);
|
|
19075
20143
|
return `<meta http-equiv="Content-Security-Policy" content="${policy}">`;
|
|
19076
20144
|
}
|
|
19077
20145
|
function prepareNappletSrcdoc(html, options) {
|
|
19078
|
-
const
|
|
20146
|
+
const lockNestedContexts = options.experimental?.nestedContextLock === true;
|
|
20147
|
+
const meta = renderNappletCspMeta(options.csp, lockNestedContexts);
|
|
19079
20148
|
return insertNappletHead(html, meta + renderNappletNamespacePrelude(options));
|
|
19080
20149
|
}
|
|
20150
|
+
var FRAME_ELEMENTS = /* @__PURE__ */ new Set([
|
|
20151
|
+
"iframe",
|
|
20152
|
+
"frame",
|
|
20153
|
+
"frameset",
|
|
20154
|
+
"object",
|
|
20155
|
+
"embed",
|
|
20156
|
+
"portal",
|
|
20157
|
+
"fencedframe"
|
|
20158
|
+
]);
|
|
20159
|
+
var FRAME_TAG = /<\/?(?:iframe|frame|frameset|object|embed|portal|fencedframe)(?=[\s/>]|$)/i;
|
|
20160
|
+
function subtreeHasFrame(root) {
|
|
20161
|
+
for (const element2 of Array.from(root.querySelectorAll("*"))) {
|
|
20162
|
+
const local = (element2.localName || "").toLowerCase();
|
|
20163
|
+
if (element2.namespaceURI === "http://www.w3.org/1999/xhtml" && FRAME_ELEMENTS.has(local)) {
|
|
20164
|
+
return true;
|
|
20165
|
+
}
|
|
20166
|
+
const template = element2;
|
|
20167
|
+
if (local === "template" && template.content && subtreeHasFrame(template.content)) return true;
|
|
20168
|
+
if (element2.shadowRoot && subtreeHasFrame(element2.shadowRoot)) return true;
|
|
20169
|
+
}
|
|
20170
|
+
return false;
|
|
20171
|
+
}
|
|
20172
|
+
function nappletMarkupHasFrame(html) {
|
|
20173
|
+
if (typeof html !== "string") return false;
|
|
20174
|
+
const DOMParser = globalThis.DOMParser;
|
|
20175
|
+
if (DOMParser) {
|
|
20176
|
+
try {
|
|
20177
|
+
return subtreeHasFrame(new DOMParser().parseFromString(html, "text/html"));
|
|
20178
|
+
} catch {
|
|
20179
|
+
}
|
|
20180
|
+
}
|
|
20181
|
+
return FRAME_TAG.test(html);
|
|
20182
|
+
}
|
|
20183
|
+
function assertNappletHasNoFrame(html) {
|
|
20184
|
+
if (nappletMarkupHasFrame(html)) {
|
|
20185
|
+
throw new Error(
|
|
20186
|
+
"kehto: napplet markup declares a nested browsing context (iframe/frame/object/embed); rejected before load"
|
|
20187
|
+
);
|
|
20188
|
+
}
|
|
20189
|
+
}
|
|
19081
20190
|
|
|
19082
20191
|
// src/browser-console-panel.ts
|
|
19083
20192
|
var PAJA_CONSOLE_PANEL_STORAGE_KEY = "kehto:paja:console:v1";
|
|
@@ -20273,9 +21382,9 @@ function createNostrCvmTransport(options = {}) {
|
|
|
20273
21382
|
}
|
|
20274
21383
|
function releaseRelays(relays) {
|
|
20275
21384
|
for (const url of relays) {
|
|
20276
|
-
const
|
|
20277
|
-
if (
|
|
20278
|
-
else relayRefcount.set(url,
|
|
21385
|
+
const count2 = (relayRefcount.get(url) ?? 0) - 1;
|
|
21386
|
+
if (count2 <= 0) relayRefcount.delete(url);
|
|
21387
|
+
else relayRefcount.set(url, count2);
|
|
20279
21388
|
}
|
|
20280
21389
|
refreshSubscription();
|
|
20281
21390
|
}
|
|
@@ -22005,12 +23114,12 @@ async function countLive(pool, relayUrls2, filters) {
|
|
|
22005
23114
|
}),
|
|
22006
23115
|
timedOut
|
|
22007
23116
|
]);
|
|
22008
|
-
const
|
|
23117
|
+
const count2 = await Promise.race([
|
|
22009
23118
|
relay.count(filters, { id: null }),
|
|
22010
23119
|
timedOut
|
|
22011
23120
|
]);
|
|
22012
|
-
if (!Number.isSafeInteger(
|
|
22013
|
-
return { count, relay: relayUrl2 };
|
|
23121
|
+
if (!Number.isSafeInteger(count2) || count2 < 0) throw new Error("invalid count");
|
|
23122
|
+
return { count: count2, relay: relayUrl2 };
|
|
22014
23123
|
} catch (error) {
|
|
22015
23124
|
failure4 = error;
|
|
22016
23125
|
} finally {
|
|
@@ -22477,11 +23586,11 @@ function matchingCachedProfiles(profiles, filters) {
|
|
|
22477
23586
|
const matched = /* @__PURE__ */ new Map();
|
|
22478
23587
|
for (const filter of filters) {
|
|
22479
23588
|
const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
|
|
22480
|
-
let
|
|
23589
|
+
let count2 = 0;
|
|
22481
23590
|
for (const entry of readyProfiles) {
|
|
22482
23591
|
if (!matchesAnyFilter2(entry.event, [filter])) continue;
|
|
22483
|
-
if (limit !== void 0 &&
|
|
22484
|
-
|
|
23592
|
+
if (limit !== void 0 && count2 >= limit) continue;
|
|
23593
|
+
count2 += 1;
|
|
22485
23594
|
if (!matched.has(entry.event.id)) matched.set(entry.event.id, entry);
|
|
22486
23595
|
}
|
|
22487
23596
|
}
|
|
@@ -23535,9 +24644,9 @@ var BrowserWebrtcController = class {
|
|
|
23535
24644
|
if (session.state !== "closed" || event.type === "closed" || event.type === "state") session.context.emit(event);
|
|
23536
24645
|
}
|
|
23537
24646
|
windowSessionCount(windowId) {
|
|
23538
|
-
let
|
|
23539
|
-
for (const session of this.sessions.values()) if (session.windowId === windowId)
|
|
23540
|
-
return
|
|
24647
|
+
let count2 = 0;
|
|
24648
|
+
for (const session of this.sessions.values()) if (session.windowId === windowId) count2 += 1;
|
|
24649
|
+
return count2;
|
|
23541
24650
|
}
|
|
23542
24651
|
};
|
|
23543
24652
|
function validateOpenRequest(request) {
|
|
@@ -24178,8 +25287,8 @@ async function createPajaBrowserFsBackend(options) {
|
|
|
24178
25287
|
});
|
|
24179
25288
|
},
|
|
24180
25289
|
async watch(windowId, path, watchOptions, onChange) {
|
|
24181
|
-
const
|
|
24182
|
-
if (
|
|
25290
|
+
const count2 = [...backendWatches].filter((watch) => watch.windowId === windowId && !watch.closed).length + [...pendingBackendWatches].filter((watch) => watch.windowId === windowId && !watch.closed).length;
|
|
25291
|
+
if (count2 >= MAX_WATCH_COUNT) throw new FsServiceError("policy-denied");
|
|
24183
25292
|
const pending = { windowId, closed: false };
|
|
24184
25293
|
pendingBackendWatches.add(pending);
|
|
24185
25294
|
try {
|
|
@@ -25029,7 +26138,7 @@ function createPajaRelayEventCounter(onChange) {
|
|
|
25029
26138
|
count: relay?.count ?? 0,
|
|
25030
26139
|
readCount: box?.reads.get(key) ?? 0,
|
|
25031
26140
|
configured: isConfigured,
|
|
25032
|
-
kinds: [...relay?.kinds.entries() ?? []].sort(([left], [right]) => left - right).map(([kind,
|
|
26141
|
+
kinds: [...relay?.kinds.entries() ?? []].sort(([left], [right]) => left - right).map(([kind, count2]) => ({ kind, count: count2 }))
|
|
25033
26142
|
});
|
|
25034
26143
|
};
|
|
25035
26144
|
for (const url of configured) push(url, true);
|
|
@@ -25042,7 +26151,7 @@ function createPajaRelayEventCounter(onChange) {
|
|
|
25042
26151
|
reason: spec.reason,
|
|
25043
26152
|
...spec.origin ? { origin: spec.origin } : {},
|
|
25044
26153
|
count: box?.count ?? 0,
|
|
25045
|
-
authors: [...box?.authors.entries() ?? []].sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey)).map(([pubkey2,
|
|
26154
|
+
authors: [...box?.authors.entries() ?? []].sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey)).map(([pubkey2, count2]) => ({ pubkey: pubkey2, count: count2 })),
|
|
25046
26155
|
relays,
|
|
25047
26156
|
...relays.length === 0 && spec.emptyNote ? { emptyNote: spec.emptyNote } : {}
|
|
25048
26157
|
});
|
|
@@ -25102,13 +26211,13 @@ function installPajaEventCounterReset(counter) {
|
|
|
25102
26211
|
function renderBoxAuthors(authors) {
|
|
25103
26212
|
const row = document.createElement("div");
|
|
25104
26213
|
row.className = "event-box-authors";
|
|
25105
|
-
row.replaceChildren(...authors.map(({ pubkey: pubkey2, count }) => {
|
|
26214
|
+
row.replaceChildren(...authors.map(({ pubkey: pubkey2, count: count2 }) => {
|
|
25106
26215
|
const chip = document.createElement("span");
|
|
25107
26216
|
chip.className = "event-author";
|
|
25108
26217
|
chip.dataset.authorPubkey = pubkey2;
|
|
25109
|
-
chip.dataset.authorReads = String(
|
|
25110
|
-
chip.textContent =
|
|
25111
|
-
chip.title =
|
|
26218
|
+
chip.dataset.authorReads = String(count2);
|
|
26219
|
+
chip.textContent = count2 > 1 ? `${shortPubkey(pubkey2)} \xB7 ${count2}` : shortPubkey(pubkey2);
|
|
26220
|
+
chip.title = count2 > 1 ? `${pubkey2} \xB7 routed ${count2} reads into this box` : `${pubkey2} \xB7 routed 1 read into this box`;
|
|
25112
26221
|
return chip;
|
|
25113
26222
|
}));
|
|
25114
26223
|
return row;
|
|
@@ -25183,7 +26292,7 @@ function renderPajaEventKindCounts(counter, inventory) {
|
|
|
25183
26292
|
if (relay.kinds.length > 0) {
|
|
25184
26293
|
const kinds = document.createElement("div");
|
|
25185
26294
|
kinds.className = "event-kinds";
|
|
25186
|
-
kinds.replaceChildren(...relay.kinds.map(({ kind, count }) => {
|
|
26295
|
+
kinds.replaceChildren(...relay.kinds.map(({ kind, count: count2 }) => {
|
|
25187
26296
|
const kindRow = document.createElement("div");
|
|
25188
26297
|
kindRow.className = "event-row";
|
|
25189
26298
|
kindRow.dataset.eventKind = String(kind);
|
|
@@ -25195,7 +26304,7 @@ function renderPajaEventKindCounts(counter, inventory) {
|
|
|
25195
26304
|
separator.textContent = "-";
|
|
25196
26305
|
const countCell = document.createElement("span");
|
|
25197
26306
|
countCell.className = "event-count";
|
|
25198
|
-
countCell.textContent = String(
|
|
26307
|
+
countCell.textContent = String(count2);
|
|
25199
26308
|
kindRow.append(kindCell, separator, countCell);
|
|
25200
26309
|
return kindRow;
|
|
25201
26310
|
}));
|
|
@@ -25340,8 +26449,14 @@ async function navigateFrame(frame, config, generation2, adapter, resolvedTarget
|
|
|
25340
26449
|
console.warn(`[paja] Napplet requires unsupported NAP capabilities: ${missing.join(", ")}; full functionality may be unavailable.`);
|
|
25341
26450
|
}
|
|
25342
26451
|
}
|
|
26452
|
+
const lockSetting = readStoredNestedContextLockSetting() ?? config.experimental?.nestedContextLock ?? "auto";
|
|
26453
|
+
const nestedContextLock = resolveNestedContextLock(lockSetting, domains);
|
|
26454
|
+
if (nestedContextLock) {
|
|
26455
|
+
assertNappletHasNoFrame(resolvedTarget.indexHtml);
|
|
26456
|
+
}
|
|
25343
26457
|
const srcdoc = prepareNappletSrcdoc(resolvedTarget.indexHtml, {
|
|
25344
26458
|
domains,
|
|
26459
|
+
...nestedContextLock ? { experimental: { nestedContextLock: true } } : {},
|
|
25345
26460
|
csp: {
|
|
25346
26461
|
...config.csp,
|
|
25347
26462
|
connectOrigins: [
|
|
@@ -25367,6 +26482,12 @@ async function navigateFrame(frame, config, generation2, adapter, resolvedTarget
|
|
|
25367
26482
|
);
|
|
25368
26483
|
return registeredWindowId;
|
|
25369
26484
|
}
|
|
26485
|
+
var PRIVACY_SENSITIVE_DOMAINS = /* @__PURE__ */ new Set(["dm"]);
|
|
26486
|
+
function resolveNestedContextLock(setting, grantedDomains) {
|
|
26487
|
+
if (setting === "on") return true;
|
|
26488
|
+
if (setting === "off") return false;
|
|
26489
|
+
return grantedDomains.some((domain) => PRIVACY_SENSITIVE_DOMAINS.has(domain));
|
|
26490
|
+
}
|
|
25370
26491
|
function renderTargetErrorHtml(error) {
|
|
25371
26492
|
const message3 = error instanceof Error ? error.message : String(error);
|
|
25372
26493
|
return `<!doctype html><html><body><pre>${escapeHtml(message3)}</pre></body></html>`;
|
|
@@ -26483,7 +27604,8 @@ function describeConfirmation(request) {
|
|
|
26483
27604
|
`Version: ${request.napplet.aggregateHash}`,
|
|
26484
27605
|
`Route: ${request.route}`,
|
|
26485
27606
|
`Model: ${request.model}`,
|
|
26486
|
-
`Disclosed: ${request.messages} message(s), ${request.characters} characters, ${request.images} image(s); ${request.format} output`,
|
|
27607
|
+
`Disclosed: ${request.messages} message(s), ${request.characters} characters, ${request.images} image(s), ${request.toolResults} tool result(s); ${request.format} output`,
|
|
27608
|
+
`Tools offered: ${request.tools.length === 0 ? "none" : `${request.tools.length} (${request.tools.join(", ")})`}`,
|
|
26487
27609
|
request.warning
|
|
26488
27610
|
);
|
|
26489
27611
|
}
|
|
@@ -26594,7 +27716,7 @@ function recordPajaConfirmation(state, request, allowed2, signerApprovalMode) {
|
|
|
26594
27716
|
windowId: request.windowId,
|
|
26595
27717
|
dTag: request.napplet.dTag,
|
|
26596
27718
|
aggregateHash: request.napplet.aggregateHash,
|
|
26597
|
-
...request.action === "llm" ? { connection: request.connection, model: request.model, route: request.route, messages: request.messages, images: request.images, format: request.format } : { requirements: request.requirements }
|
|
27719
|
+
...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 }
|
|
26598
27720
|
});
|
|
26599
27721
|
return;
|
|
26600
27722
|
}
|
|
@@ -28098,11 +29220,11 @@ function strictDecode(value, label) {
|
|
|
28098
29220
|
function parseOuterQuery(search) {
|
|
28099
29221
|
const fields = /* @__PURE__ */ Object.create(null);
|
|
28100
29222
|
if (!search) return fields;
|
|
28101
|
-
for (const
|
|
28102
|
-
const equal =
|
|
29223
|
+
for (const part of search.slice(1).split("&")) {
|
|
29224
|
+
const equal = part.indexOf("=");
|
|
28103
29225
|
if (equal <= 0) fail("Paja intent link fields must be name=value");
|
|
28104
|
-
const name = strictDecode(
|
|
28105
|
-
const value = strictDecode(
|
|
29226
|
+
const name = strictDecode(part.slice(0, equal), "a field name");
|
|
29227
|
+
const value = strictDecode(part.slice(equal + 1), `the ${name || "unnamed"} field`);
|
|
28106
29228
|
if (!name || hasOwn(fields, name)) fail("Paja intent link field names must be unique after decoding");
|
|
28107
29229
|
Object.defineProperty(fields, name, { value, enumerable: true, configurable: true });
|
|
28108
29230
|
}
|
|
@@ -28110,11 +29232,11 @@ function parseOuterQuery(search) {
|
|
|
28110
29232
|
}
|
|
28111
29233
|
function rawOuterValue(search, expectedName) {
|
|
28112
29234
|
if (!search) return void 0;
|
|
28113
|
-
for (const
|
|
28114
|
-
const equal =
|
|
29235
|
+
for (const part of search.slice(1).split("&")) {
|
|
29236
|
+
const equal = part.indexOf("=");
|
|
28115
29237
|
if (equal <= 0) continue;
|
|
28116
29238
|
try {
|
|
28117
|
-
if (decodeURIComponent(
|
|
29239
|
+
if (decodeURIComponent(part.slice(0, equal)) === expectedName) return part.slice(equal + 1);
|
|
28118
29240
|
} catch {
|
|
28119
29241
|
}
|
|
28120
29242
|
}
|
|
@@ -29100,9 +30222,9 @@ function createPajaNotifyController(options) {
|
|
|
29100
30222
|
active.set(key, { element: article, emit });
|
|
29101
30223
|
center.prepend(article);
|
|
29102
30224
|
};
|
|
29103
|
-
const setBadge = (windowId,
|
|
30225
|
+
const setBadge = (windowId, count2) => {
|
|
29104
30226
|
const current = badges.get(windowId);
|
|
29105
|
-
if (
|
|
30227
|
+
if (count2 === 0) {
|
|
29106
30228
|
current?.remove();
|
|
29107
30229
|
badges.delete(windowId);
|
|
29108
30230
|
return;
|
|
@@ -29110,7 +30232,7 @@ function createPajaNotifyController(options) {
|
|
|
29110
30232
|
const badge = current ?? document2.createElement("span");
|
|
29111
30233
|
badge.className = "paja-notification-badge";
|
|
29112
30234
|
badge.dataset.windowId = windowId;
|
|
29113
|
-
badge.textContent = `${originLabel(options.getIdentity, windowId)}: ${Math.min(
|
|
30235
|
+
badge.textContent = `${originLabel(options.getIdentity, windowId)}: ${Math.min(count2, 9999)}`;
|
|
29114
30236
|
if (!current) badgeCenter.append(badge);
|
|
29115
30237
|
badges.set(windowId, badge);
|
|
29116
30238
|
};
|
|
@@ -29777,6 +30899,8 @@ async function installPajaHost() {
|
|
|
29777
30899
|
const disposeSidebarSections = installPajaSidebarSections();
|
|
29778
30900
|
window.addEventListener("pagehide", disposeSidebarSections, { once: true });
|
|
29779
30901
|
const resourceSettings = installPajaResourceSettings();
|
|
30902
|
+
const securitySettings = installPajaSecuritySettings();
|
|
30903
|
+
window.addEventListener("pagehide", securitySettings.dispose, { once: true });
|
|
29780
30904
|
const config = await readLatestPajaHostConfig(readPajaHostConfig());
|
|
29781
30905
|
const stage = getStage();
|
|
29782
30906
|
const frame = config.target.mode === "runtime-pointer" ? null : getFrame();
|
|
@@ -29820,9 +30944,9 @@ async function installPajaHost() {
|
|
|
29820
30944
|
const confirmationController = createPajaConfirmationController(
|
|
29821
30945
|
() => stateRef,
|
|
29822
30946
|
{
|
|
29823
|
-
onSignerConsentChange(
|
|
30947
|
+
onSignerConsentChange(count2) {
|
|
29824
30948
|
if (!stateRef) return;
|
|
29825
|
-
stateRef.signerConsentCount =
|
|
30949
|
+
stateRef.signerConsentCount = count2;
|
|
29826
30950
|
setSimulationStatus(stateRef);
|
|
29827
30951
|
}
|
|
29828
30952
|
}
|