@kehto/paja 0.31.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 +1195 -259
- package/dist/browser-host.js.map +1 -1
- package/dist/{chunk-JVTK35QF.js → chunk-DDYBKY5L.js} +52 -12
- package/dist/chunk-DDYBKY5L.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.js +1 -1
- package/package.json +10 -10
- package/dist/chunk-JVTK35QF.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);
|
|
@@ -14922,6 +15780,7 @@ var PAJA_LLM_CONNECTIONS_STORAGE_KEY = "kehto:paja:llm-connections:v1";
|
|
|
14922
15780
|
var MAX_CONNECTIONS = 32;
|
|
14923
15781
|
var PROTOCOLS = /* @__PURE__ */ new Set(["openai-chat", "anthropic-messages", "gemini"]);
|
|
14924
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"];
|
|
14925
15784
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
14926
15785
|
function normalizePajaLlmBaseUrl(value) {
|
|
14927
15786
|
let url;
|
|
@@ -14941,6 +15800,11 @@ function normalizePajaLlmBaseUrl(value) {
|
|
|
14941
15800
|
function isRecord4(value) {
|
|
14942
15801
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
14943
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
|
+
}
|
|
14944
15808
|
function normalizeRecord(input) {
|
|
14945
15809
|
const text2 = (value) => typeof value === "string" ? value : "";
|
|
14946
15810
|
const name = text2(input.name).trim();
|
|
@@ -14955,6 +15819,7 @@ function normalizeRecord(input) {
|
|
|
14955
15819
|
if (!PROTOCOLS.has(protocol)) throw new Error("Unknown provider protocol.");
|
|
14956
15820
|
if (credentialHeader !== void 0 && !CREDENTIAL_HEADERS.has(credentialHeader)) throw new Error("Unknown credential header.");
|
|
14957
15821
|
if (!["vault", "session", "none"].includes(credentialStorage)) throw new Error("Unknown credential storage.");
|
|
15822
|
+
const tools = input.tools === true;
|
|
14958
15823
|
const record3 = {
|
|
14959
15824
|
id,
|
|
14960
15825
|
name,
|
|
@@ -14964,6 +15829,8 @@ function normalizeRecord(input) {
|
|
|
14964
15829
|
model,
|
|
14965
15830
|
images: input.images === true,
|
|
14966
15831
|
json: input.json === true,
|
|
15832
|
+
tools,
|
|
15833
|
+
toolChoiceModes: Object.freeze(canonicalToolChoiceModes(tools, input.toolChoiceModes)),
|
|
14967
15834
|
credentialStorage,
|
|
14968
15835
|
...credentialHeader ? { credentialHeader } : {}
|
|
14969
15836
|
};
|
|
@@ -15035,29 +15902,59 @@ function describePajaLlmRoute(record3) {
|
|
|
15035
15902
|
return `Paja (this browser) \u2192 ${label}`;
|
|
15036
15903
|
}
|
|
15037
15904
|
function toConnection(record3) {
|
|
15038
|
-
|
|
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
|
+
};
|
|
15039
15916
|
}
|
|
15040
15917
|
function meets(record3, requirements2) {
|
|
15041
15918
|
if (requirements2.model !== void 0 && requirements2.model !== record3.model) return false;
|
|
15042
15919
|
if (requirements2.images === true && !record3.images) return false;
|
|
15920
|
+
if (requirements2.tools === true && record3.tools !== true) return false;
|
|
15043
15921
|
return !(requirements2.json === true && !record3.json);
|
|
15044
15922
|
}
|
|
15045
15923
|
function describeRequirements(requirements2) {
|
|
15046
15924
|
const parts = [
|
|
15047
15925
|
requirements2.model ? `model ${requirements2.model}` : "any model",
|
|
15048
15926
|
requirements2.images ? "image input" : null,
|
|
15049
|
-
requirements2.json ? "JSON output" : null
|
|
15050
|
-
|
|
15927
|
+
requirements2.json ? "JSON output" : null,
|
|
15928
|
+
requirements2.tools ? "tool calling" : null
|
|
15929
|
+
].filter((part) => part !== null);
|
|
15051
15930
|
return parts.join(", ");
|
|
15052
15931
|
}
|
|
15053
15932
|
function countCharacters(request) {
|
|
15054
15933
|
let total = 0;
|
|
15055
|
-
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;
|
|
15056
15941
|
return total;
|
|
15057
15942
|
}
|
|
15943
|
+
function countToolResults(request) {
|
|
15944
|
+
return request.messages.filter((message3) => message3.role === "toolResult").length;
|
|
15945
|
+
}
|
|
15058
15946
|
function createPajaLlmHost(options) {
|
|
15059
15947
|
const { store: store2, vault, confirm, getIdentity } = options;
|
|
15060
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
|
+
}
|
|
15061
15958
|
async function ensureCredential(record3, signal) {
|
|
15062
15959
|
if (record3.credentialStorage === "none") return void 0;
|
|
15063
15960
|
const existing = vault.getCredential(record3.id);
|
|
@@ -15103,6 +16000,7 @@ function createPajaLlmHost(options) {
|
|
|
15103
16000
|
const signal = prompt?.signal;
|
|
15104
16001
|
const record3 = store2.get(connection.id);
|
|
15105
16002
|
if (!record3) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
|
|
16003
|
+
buildLlmProviderRequest(endpointFor(record3), request, { stream: true });
|
|
15106
16004
|
await ensureCredential(record3, signal);
|
|
15107
16005
|
if (signal?.aborted) return false;
|
|
15108
16006
|
return confirm({
|
|
@@ -15116,21 +16014,17 @@ function createPajaLlmHost(options) {
|
|
|
15116
16014
|
messages: request.messages.length,
|
|
15117
16015
|
characters: countCharacters(request),
|
|
15118
16016
|
images: countLlmImages(request.messages),
|
|
16017
|
+
tools: (request.tools ?? []).map((tool2) => tool2.name),
|
|
16018
|
+
toolResults: countToolResults(request),
|
|
15119
16019
|
format: request.format ?? "text",
|
|
15120
|
-
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."
|
|
15121
16021
|
});
|
|
15122
16022
|
},
|
|
15123
16023
|
async generate(_context, connection, request, hooks) {
|
|
15124
16024
|
const record3 = store2.get(connection.id);
|
|
15125
16025
|
if (!record3) throw new LlmServiceError("selection-expired", "The selected connection was removed; select again.");
|
|
15126
16026
|
const credential = await ensureCredential(record3);
|
|
15127
|
-
return provider(
|
|
15128
|
-
protocol: record3.protocol,
|
|
15129
|
-
baseUrl: record3.baseUrl,
|
|
15130
|
-
model: record3.model,
|
|
15131
|
-
...credential === void 0 ? {} : { credential },
|
|
15132
|
-
...record3.credentialHeader ? { credentialHeader: record3.credentialHeader } : {}
|
|
15133
|
-
}, request, hooks.signal, (text2) => hooks.onDelta(text2));
|
|
16027
|
+
return provider(endpointFor(record3, credential), request, hooks.signal, (event) => hooks.onDelta(event));
|
|
15134
16028
|
},
|
|
15135
16029
|
subscribe(listener) {
|
|
15136
16030
|
const stopStore = store2.subscribe(listener);
|
|
@@ -15403,7 +16297,7 @@ function createChooserDialog() {
|
|
|
15403
16297
|
choose(candidates, context) {
|
|
15404
16298
|
if (settle7) finish(null);
|
|
15405
16299
|
if (context.signal?.aborted) return Promise.resolve(null);
|
|
15406
|
-
const wanted = [context.requirements.model ? `model ${context.requirements.model}` : null, context.requirements.images ? "image input" : null, context.requirements.json ? "JSON output" : null].filter(Boolean).join(", ");
|
|
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(", ");
|
|
15407
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.`;
|
|
15408
16302
|
select2.replaceChildren(...candidates.map((record3) => {
|
|
15409
16303
|
const option = document.createElement("option");
|
|
@@ -15448,10 +16342,13 @@ function readForm() {
|
|
|
15448
16342
|
const remember = byId("paja-llm-remember", HTMLInputElement);
|
|
15449
16343
|
const images = byId("paja-llm-images", HTMLInputElement);
|
|
15450
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);
|
|
15451
16348
|
const list = byId("paja-llm-connections", HTMLElement);
|
|
15452
16349
|
const status = byId("paja-llm-status", HTMLElement);
|
|
15453
16350
|
const lock = byId("paja-llm-vault-lock", HTMLButtonElement);
|
|
15454
|
-
if (!form || !preset || !name || !baseUrl || !model || !modelField || !modelSelect || !modelSelectField || !modelStatus || !examples || !credential || !remember || !images || !json || !list || !status || !lock) return null;
|
|
16351
|
+
if (!form || !preset || !name || !baseUrl || !model || !modelField || !modelSelect || !modelSelectField || !modelStatus || !examples || !credential || !remember || !images || !json || !tools || !toolRequired || !toolNamed || !list || !status || !lock) return null;
|
|
15455
16352
|
return {
|
|
15456
16353
|
form,
|
|
15457
16354
|
preset,
|
|
@@ -15467,6 +16364,9 @@ function readForm() {
|
|
|
15467
16364
|
remember,
|
|
15468
16365
|
images,
|
|
15469
16366
|
json,
|
|
16367
|
+
tools,
|
|
16368
|
+
toolRequired,
|
|
16369
|
+
toolNamed,
|
|
15470
16370
|
list,
|
|
15471
16371
|
status,
|
|
15472
16372
|
lock,
|
|
@@ -15598,7 +16498,7 @@ function installPajaLlmPanel(options) {
|
|
|
15598
16498
|
label.className = "llm-connection-label";
|
|
15599
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";
|
|
15600
16500
|
label.textContent = `${record3.name} \xB7 ${record3.model} \xB7 ${new URL(record3.baseUrl).origin} \xB7 ${tier}`;
|
|
15601
|
-
label.title = `${record3.protocol}${record3.images ? " \xB7 images" : ""}${record3.json ? " \xB7 json" : ""}`;
|
|
16501
|
+
label.title = `${record3.protocol}${record3.images ? " \xB7 images" : ""}${record3.json ? " \xB7 json" : ""}${record3.tools ? " \xB7 tools" : ""}`;
|
|
15602
16502
|
const remove = document.createElement("button");
|
|
15603
16503
|
remove.type = "button";
|
|
15604
16504
|
remove.textContent = "Remove";
|
|
@@ -15626,6 +16526,10 @@ function installPajaLlmPanel(options) {
|
|
|
15626
16526
|
renderList();
|
|
15627
16527
|
options.onChange?.();
|
|
15628
16528
|
}
|
|
16529
|
+
function toolChoiceModes(form) {
|
|
16530
|
+
if (!form.tools.checked) return [];
|
|
16531
|
+
return [...form.toolRequired.checked ? ["required"] : [], ...form.toolNamed.checked ? ["tool"] : []];
|
|
16532
|
+
}
|
|
15629
16533
|
async function submit(event) {
|
|
15630
16534
|
event.preventDefault();
|
|
15631
16535
|
if (!elements) return;
|
|
@@ -15648,6 +16552,8 @@ function installPajaLlmPanel(options) {
|
|
|
15648
16552
|
model,
|
|
15649
16553
|
images: elements.images.checked,
|
|
15650
16554
|
json: elements.json.checked,
|
|
16555
|
+
tools: elements.tools.checked,
|
|
16556
|
+
toolChoiceModes: toolChoiceModes(elements),
|
|
15651
16557
|
credentialStorage: storage,
|
|
15652
16558
|
...preset?.credentialHeader ? { credentialHeader: preset.credentialHeader } : {}
|
|
15653
16559
|
};
|
|
@@ -15679,6 +16585,12 @@ function installPajaLlmPanel(options) {
|
|
|
15679
16585
|
const onSubmit = (event) => {
|
|
15680
16586
|
void submit(event);
|
|
15681
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
|
+
};
|
|
15682
16594
|
const onLock = () => {
|
|
15683
16595
|
vault.lock();
|
|
15684
16596
|
renderList();
|
|
@@ -15688,12 +16600,15 @@ function installPajaLlmPanel(options) {
|
|
|
15688
16600
|
elements.preset.addEventListener("change", onPreset);
|
|
15689
16601
|
elements.baseUrl.addEventListener("change", onBaseUrl);
|
|
15690
16602
|
elements.form.addEventListener("submit", onSubmit);
|
|
16603
|
+
elements.tools.addEventListener("change", onTools);
|
|
15691
16604
|
elements.lock.addEventListener("click", onLock);
|
|
16605
|
+
onTools();
|
|
15692
16606
|
disposers.push(() => {
|
|
15693
16607
|
modelListing?.abort();
|
|
15694
16608
|
elements.preset.removeEventListener("change", onPreset);
|
|
15695
16609
|
elements.baseUrl.removeEventListener("change", onBaseUrl);
|
|
15696
16610
|
elements.form.removeEventListener("submit", onSubmit);
|
|
16611
|
+
elements.tools.removeEventListener("change", onTools);
|
|
15697
16612
|
elements.lock.removeEventListener("click", onLock);
|
|
15698
16613
|
});
|
|
15699
16614
|
renderList();
|
|
@@ -17281,7 +18196,7 @@ function createIntentUriNormalizer() {
|
|
|
17281
18196
|
relays.push(relay);
|
|
17282
18197
|
} else if (type === 2) {
|
|
17283
18198
|
if (pubkey2 !== void 0 || value.length !== 32) fail2("Intent URI fragment has an invalid pubkey");
|
|
17284
|
-
pubkey2 = value.map((
|
|
18199
|
+
pubkey2 = value.map((part) => part.toString(16).padStart(2, "0")).join("");
|
|
17285
18200
|
} else if (type === 3) {
|
|
17286
18201
|
if (kind !== void 0 || value.length !== 4) fail2("Intent URI fragment has an invalid kind");
|
|
17287
18202
|
kind = (value[0] << 24 >>> 0 | value[1] << 16 | value[2] << 8 | value[3]) >>> 0;
|
|
@@ -18315,7 +19230,7 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
|
|
|
18315
19230
|
(msg) => ({ notificationId: fieldOrThrow(msg, "notificationId", "notify.send.result missing notificationId") })
|
|
18316
19231
|
),
|
|
18317
19232
|
dismiss: (notificationId) => fire({ type: "notify.dismiss", notificationId }),
|
|
18318
|
-
badge: (
|
|
19233
|
+
badge: (count2) => fire({ type: "notify.badge", count: count2 }),
|
|
18319
19234
|
registerChannel: (channel2) => fire({ type: "notify.channel.register", ...channel2 }),
|
|
18320
19235
|
requestPermission: (channel2) => request(
|
|
18321
19236
|
{ type: "notify.permission.request", ...channel2 ? { channel: channel2 } : {} },
|
|
@@ -18912,6 +19827,25 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
|
|
|
18912
19827
|
};
|
|
18913
19828
|
}
|
|
18914
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
|
+
};
|
|
18915
19849
|
const asFailure = (value) => {
|
|
18916
19850
|
if (!value || typeof value !== "object") return null;
|
|
18917
19851
|
const { code, message: message3 } = value;
|
|
@@ -18930,9 +19864,10 @@ function nappletNamespacePrelude(domains, normalizeIntentUri2, frameLock) {
|
|
|
18930
19864
|
const msg = event.data;
|
|
18931
19865
|
if (typeof msg !== "object" || msg === null) return;
|
|
18932
19866
|
if (type === "llm.generate" && msg.type === "llm.delta" && msg.requestId === requestId) {
|
|
18933
|
-
|
|
19867
|
+
const delta = asDelta(msg, requestId, nextSequence);
|
|
19868
|
+
if (!delta) return;
|
|
18934
19869
|
nextSequence += 1;
|
|
18935
|
-
options.onDelta?.(
|
|
19870
|
+
options.onDelta?.(delta);
|
|
18936
19871
|
return;
|
|
18937
19872
|
}
|
|
18938
19873
|
if (msg.type !== `${type}.result` || msg.id !== requestId) return;
|
|
@@ -20447,9 +21382,9 @@ function createNostrCvmTransport(options = {}) {
|
|
|
20447
21382
|
}
|
|
20448
21383
|
function releaseRelays(relays) {
|
|
20449
21384
|
for (const url of relays) {
|
|
20450
|
-
const
|
|
20451
|
-
if (
|
|
20452
|
-
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);
|
|
20453
21388
|
}
|
|
20454
21389
|
refreshSubscription();
|
|
20455
21390
|
}
|
|
@@ -22179,12 +23114,12 @@ async function countLive(pool, relayUrls2, filters) {
|
|
|
22179
23114
|
}),
|
|
22180
23115
|
timedOut
|
|
22181
23116
|
]);
|
|
22182
|
-
const
|
|
23117
|
+
const count2 = await Promise.race([
|
|
22183
23118
|
relay.count(filters, { id: null }),
|
|
22184
23119
|
timedOut
|
|
22185
23120
|
]);
|
|
22186
|
-
if (!Number.isSafeInteger(
|
|
22187
|
-
return { count, relay: relayUrl2 };
|
|
23121
|
+
if (!Number.isSafeInteger(count2) || count2 < 0) throw new Error("invalid count");
|
|
23122
|
+
return { count: count2, relay: relayUrl2 };
|
|
22188
23123
|
} catch (error) {
|
|
22189
23124
|
failure4 = error;
|
|
22190
23125
|
} finally {
|
|
@@ -22651,11 +23586,11 @@ function matchingCachedProfiles(profiles, filters) {
|
|
|
22651
23586
|
const matched = /* @__PURE__ */ new Map();
|
|
22652
23587
|
for (const filter of filters) {
|
|
22653
23588
|
const limit = typeof filter.limit === "number" && filter.limit >= 0 ? filter.limit : void 0;
|
|
22654
|
-
let
|
|
23589
|
+
let count2 = 0;
|
|
22655
23590
|
for (const entry of readyProfiles) {
|
|
22656
23591
|
if (!matchesAnyFilter2(entry.event, [filter])) continue;
|
|
22657
|
-
if (limit !== void 0 &&
|
|
22658
|
-
|
|
23592
|
+
if (limit !== void 0 && count2 >= limit) continue;
|
|
23593
|
+
count2 += 1;
|
|
22659
23594
|
if (!matched.has(entry.event.id)) matched.set(entry.event.id, entry);
|
|
22660
23595
|
}
|
|
22661
23596
|
}
|
|
@@ -23709,9 +24644,9 @@ var BrowserWebrtcController = class {
|
|
|
23709
24644
|
if (session.state !== "closed" || event.type === "closed" || event.type === "state") session.context.emit(event);
|
|
23710
24645
|
}
|
|
23711
24646
|
windowSessionCount(windowId) {
|
|
23712
|
-
let
|
|
23713
|
-
for (const session of this.sessions.values()) if (session.windowId === windowId)
|
|
23714
|
-
return
|
|
24647
|
+
let count2 = 0;
|
|
24648
|
+
for (const session of this.sessions.values()) if (session.windowId === windowId) count2 += 1;
|
|
24649
|
+
return count2;
|
|
23715
24650
|
}
|
|
23716
24651
|
};
|
|
23717
24652
|
function validateOpenRequest(request) {
|
|
@@ -24352,8 +25287,8 @@ async function createPajaBrowserFsBackend(options) {
|
|
|
24352
25287
|
});
|
|
24353
25288
|
},
|
|
24354
25289
|
async watch(windowId, path, watchOptions, onChange) {
|
|
24355
|
-
const
|
|
24356
|
-
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");
|
|
24357
25292
|
const pending = { windowId, closed: false };
|
|
24358
25293
|
pendingBackendWatches.add(pending);
|
|
24359
25294
|
try {
|
|
@@ -25203,7 +26138,7 @@ function createPajaRelayEventCounter(onChange) {
|
|
|
25203
26138
|
count: relay?.count ?? 0,
|
|
25204
26139
|
readCount: box?.reads.get(key) ?? 0,
|
|
25205
26140
|
configured: isConfigured,
|
|
25206
|
-
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 }))
|
|
25207
26142
|
});
|
|
25208
26143
|
};
|
|
25209
26144
|
for (const url of configured) push(url, true);
|
|
@@ -25216,7 +26151,7 @@ function createPajaRelayEventCounter(onChange) {
|
|
|
25216
26151
|
reason: spec.reason,
|
|
25217
26152
|
...spec.origin ? { origin: spec.origin } : {},
|
|
25218
26153
|
count: box?.count ?? 0,
|
|
25219
|
-
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 })),
|
|
25220
26155
|
relays,
|
|
25221
26156
|
...relays.length === 0 && spec.emptyNote ? { emptyNote: spec.emptyNote } : {}
|
|
25222
26157
|
});
|
|
@@ -25276,13 +26211,13 @@ function installPajaEventCounterReset(counter) {
|
|
|
25276
26211
|
function renderBoxAuthors(authors) {
|
|
25277
26212
|
const row = document.createElement("div");
|
|
25278
26213
|
row.className = "event-box-authors";
|
|
25279
|
-
row.replaceChildren(...authors.map(({ pubkey: pubkey2, count }) => {
|
|
26214
|
+
row.replaceChildren(...authors.map(({ pubkey: pubkey2, count: count2 }) => {
|
|
25280
26215
|
const chip = document.createElement("span");
|
|
25281
26216
|
chip.className = "event-author";
|
|
25282
26217
|
chip.dataset.authorPubkey = pubkey2;
|
|
25283
|
-
chip.dataset.authorReads = String(
|
|
25284
|
-
chip.textContent =
|
|
25285
|
-
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`;
|
|
25286
26221
|
return chip;
|
|
25287
26222
|
}));
|
|
25288
26223
|
return row;
|
|
@@ -25357,7 +26292,7 @@ function renderPajaEventKindCounts(counter, inventory) {
|
|
|
25357
26292
|
if (relay.kinds.length > 0) {
|
|
25358
26293
|
const kinds = document.createElement("div");
|
|
25359
26294
|
kinds.className = "event-kinds";
|
|
25360
|
-
kinds.replaceChildren(...relay.kinds.map(({ kind, count }) => {
|
|
26295
|
+
kinds.replaceChildren(...relay.kinds.map(({ kind, count: count2 }) => {
|
|
25361
26296
|
const kindRow = document.createElement("div");
|
|
25362
26297
|
kindRow.className = "event-row";
|
|
25363
26298
|
kindRow.dataset.eventKind = String(kind);
|
|
@@ -25369,7 +26304,7 @@ function renderPajaEventKindCounts(counter, inventory) {
|
|
|
25369
26304
|
separator.textContent = "-";
|
|
25370
26305
|
const countCell = document.createElement("span");
|
|
25371
26306
|
countCell.className = "event-count";
|
|
25372
|
-
countCell.textContent = String(
|
|
26307
|
+
countCell.textContent = String(count2);
|
|
25373
26308
|
kindRow.append(kindCell, separator, countCell);
|
|
25374
26309
|
return kindRow;
|
|
25375
26310
|
}));
|
|
@@ -26669,7 +27604,8 @@ function describeConfirmation(request) {
|
|
|
26669
27604
|
`Version: ${request.napplet.aggregateHash}`,
|
|
26670
27605
|
`Route: ${request.route}`,
|
|
26671
27606
|
`Model: ${request.model}`,
|
|
26672
|
-
`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(", ")})`}`,
|
|
26673
27609
|
request.warning
|
|
26674
27610
|
);
|
|
26675
27611
|
}
|
|
@@ -26780,7 +27716,7 @@ function recordPajaConfirmation(state, request, allowed2, signerApprovalMode) {
|
|
|
26780
27716
|
windowId: request.windowId,
|
|
26781
27717
|
dTag: request.napplet.dTag,
|
|
26782
27718
|
aggregateHash: request.napplet.aggregateHash,
|
|
26783
|
-
...request.action === "llm" ? { connection: request.connection, model: request.model, route: request.route, messages: request.messages, images: request.images, format: request.format } : { requirements: request.requirements }
|
|
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 }
|
|
26784
27720
|
});
|
|
26785
27721
|
return;
|
|
26786
27722
|
}
|
|
@@ -28284,11 +29220,11 @@ function strictDecode(value, label) {
|
|
|
28284
29220
|
function parseOuterQuery(search) {
|
|
28285
29221
|
const fields = /* @__PURE__ */ Object.create(null);
|
|
28286
29222
|
if (!search) return fields;
|
|
28287
|
-
for (const
|
|
28288
|
-
const equal =
|
|
29223
|
+
for (const part of search.slice(1).split("&")) {
|
|
29224
|
+
const equal = part.indexOf("=");
|
|
28289
29225
|
if (equal <= 0) fail("Paja intent link fields must be name=value");
|
|
28290
|
-
const name = strictDecode(
|
|
28291
|
-
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`);
|
|
28292
29228
|
if (!name || hasOwn(fields, name)) fail("Paja intent link field names must be unique after decoding");
|
|
28293
29229
|
Object.defineProperty(fields, name, { value, enumerable: true, configurable: true });
|
|
28294
29230
|
}
|
|
@@ -28296,11 +29232,11 @@ function parseOuterQuery(search) {
|
|
|
28296
29232
|
}
|
|
28297
29233
|
function rawOuterValue(search, expectedName) {
|
|
28298
29234
|
if (!search) return void 0;
|
|
28299
|
-
for (const
|
|
28300
|
-
const equal =
|
|
29235
|
+
for (const part of search.slice(1).split("&")) {
|
|
29236
|
+
const equal = part.indexOf("=");
|
|
28301
29237
|
if (equal <= 0) continue;
|
|
28302
29238
|
try {
|
|
28303
|
-
if (decodeURIComponent(
|
|
29239
|
+
if (decodeURIComponent(part.slice(0, equal)) === expectedName) return part.slice(equal + 1);
|
|
28304
29240
|
} catch {
|
|
28305
29241
|
}
|
|
28306
29242
|
}
|
|
@@ -29286,9 +30222,9 @@ function createPajaNotifyController(options) {
|
|
|
29286
30222
|
active.set(key, { element: article, emit });
|
|
29287
30223
|
center.prepend(article);
|
|
29288
30224
|
};
|
|
29289
|
-
const setBadge = (windowId,
|
|
30225
|
+
const setBadge = (windowId, count2) => {
|
|
29290
30226
|
const current = badges.get(windowId);
|
|
29291
|
-
if (
|
|
30227
|
+
if (count2 === 0) {
|
|
29292
30228
|
current?.remove();
|
|
29293
30229
|
badges.delete(windowId);
|
|
29294
30230
|
return;
|
|
@@ -29296,7 +30232,7 @@ function createPajaNotifyController(options) {
|
|
|
29296
30232
|
const badge = current ?? document2.createElement("span");
|
|
29297
30233
|
badge.className = "paja-notification-badge";
|
|
29298
30234
|
badge.dataset.windowId = windowId;
|
|
29299
|
-
badge.textContent = `${originLabel(options.getIdentity, windowId)}: ${Math.min(
|
|
30235
|
+
badge.textContent = `${originLabel(options.getIdentity, windowId)}: ${Math.min(count2, 9999)}`;
|
|
29300
30236
|
if (!current) badgeCenter.append(badge);
|
|
29301
30237
|
badges.set(windowId, badge);
|
|
29302
30238
|
};
|
|
@@ -30008,9 +30944,9 @@ async function installPajaHost() {
|
|
|
30008
30944
|
const confirmationController = createPajaConfirmationController(
|
|
30009
30945
|
() => stateRef,
|
|
30010
30946
|
{
|
|
30011
|
-
onSignerConsentChange(
|
|
30947
|
+
onSignerConsentChange(count2) {
|
|
30012
30948
|
if (!stateRef) return;
|
|
30013
|
-
stateRef.signerConsentCount =
|
|
30949
|
+
stateRef.signerConsentCount = count2;
|
|
30014
30950
|
setSimulationStatus(stateRef);
|
|
30015
30951
|
}
|
|
30016
30952
|
}
|