@memberjunction/realtime-widget 6.3.0-edge.1 → 6.3.0-edge.3
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/dist/embed/chunks/UserViewEngine-AQ4HVXDY.js +7 -0
- package/dist/embed/chunks/{chunk-KHEWGJIZ.js → chunk-CUZ32HGY.js} +4 -0
- package/dist/embed/chunks/{chunk-CIZSPKQR.js → chunk-IHM3SRNY.js} +777 -152
- package/dist/embed/chunks/{chunk-SXFIY47F.js → chunk-P3UR75T6.js} +81327 -52820
- package/dist/embed/chunks/{chunk-6RWWXOZB.js → chunk-VCGHPATD.js} +3179 -199
- package/dist/embed/chunks/{chunk-AJBMDBQR.js → chunk-YDXL5TNM.js} +3173 -303
- package/dist/embed/chunks/{dist-L2XMFU32.js → dist-JBQFIDL4.js} +5 -5
- package/dist/embed/chunks/{guest-tool-relay-JGHE3J5R.js → guest-tool-relay-INT64GMC.js} +4 -4
- package/dist/embed/chunks/{guest-voice-mint-I6KQRNKA.js → guest-voice-mint-G7TM5WCO.js} +4 -4
- package/dist/embed/chunks/{realtime-voice-controller-Z75RH5BM.js → realtime-voice-controller-ZWPWPCU6.js} +320 -28
- package/dist/embed/chunks/{runtime-widget-transport-UXJAHD5F.js → runtime-widget-transport-HC7OF453.js} +10 -10
- package/dist/embed/mj-widget.js +6 -6
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +9 -9
- package/dist/embed/chunks/UserViewEngine-EEVXGC4A.js +0 -7
|
@@ -1,9 +1,332 @@
|
|
|
1
1
|
import {
|
|
2
|
+
BaseSingleton,
|
|
2
3
|
IsPlainObject,
|
|
3
4
|
SafeDeepMerge
|
|
4
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-CUZ32HGY.js";
|
|
5
6
|
|
|
6
|
-
// ../../AI/Core/dist/generic/
|
|
7
|
+
// ../../AI/Core/dist/generic/aiTransportManager.js
|
|
8
|
+
var DEFAULT_LONG_RUNNING_HEADERS_TIMEOUT_MS = 18e5;
|
|
9
|
+
var DEFAULT_LONG_RUNNING_BODY_TIMEOUT_MS = 18e5;
|
|
10
|
+
var DEFAULT_LONG_RUNNING_CONNECT_TIMEOUT_MS = 3e4;
|
|
11
|
+
var DEFAULT_LONG_RUNNING_KEEP_ALIVE_TIMEOUT_MS = 6e4;
|
|
12
|
+
var DEFAULT_LONG_RUNNING_KEEP_ALIVE_MAX_TIMEOUT_MS = 6e5;
|
|
13
|
+
var UNDICI_GLOBAL_DISPATCHER_SYMBOL = Symbol.for("undici.globalDispatcher.1");
|
|
14
|
+
function IsPlainUndiciAgentDispatcher(dispatcher) {
|
|
15
|
+
if (!dispatcher || typeof dispatcher !== "object") {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
const ctor = dispatcher.constructor;
|
|
19
|
+
if (typeof ctor !== "function") {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
const ctorName = ctor.name ?? "";
|
|
23
|
+
return ctorName === "Agent";
|
|
24
|
+
}
|
|
25
|
+
function ResolveNodeBuiltinUndiciModule() {
|
|
26
|
+
const slotHolder = globalThis;
|
|
27
|
+
const current = slotHolder[UNDICI_GLOBAL_DISPATCHER_SYMBOL];
|
|
28
|
+
if (!IsPlainUndiciAgentDispatcher(current)) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
const ctor = current.constructor;
|
|
32
|
+
return {
|
|
33
|
+
Agent: ctor,
|
|
34
|
+
getGlobalDispatcher: () => slotHolder[UNDICI_GLOBAL_DISPATCHER_SYMBOL],
|
|
35
|
+
setGlobalDispatcher: (dispatcher) => {
|
|
36
|
+
slotHolder[UNDICI_GLOBAL_DISPATCHER_SYMBOL] = dispatcher;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function normalizeNonNegativeMs(value, fallback) {
|
|
41
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
|
42
|
+
return fallback;
|
|
43
|
+
}
|
|
44
|
+
return Math.trunc(value);
|
|
45
|
+
}
|
|
46
|
+
function ResolveLongRunningFetchDispatcherOptions(options) {
|
|
47
|
+
return {
|
|
48
|
+
headersTimeout: normalizeNonNegativeMs(options?.headersTimeoutMs, DEFAULT_LONG_RUNNING_HEADERS_TIMEOUT_MS),
|
|
49
|
+
bodyTimeout: normalizeNonNegativeMs(options?.bodyTimeoutMs, DEFAULT_LONG_RUNNING_BODY_TIMEOUT_MS),
|
|
50
|
+
connectTimeout: normalizeNonNegativeMs(options?.connectTimeoutMs, DEFAULT_LONG_RUNNING_CONNECT_TIMEOUT_MS),
|
|
51
|
+
keepAliveTimeout: normalizeNonNegativeMs(options?.keepAliveTimeoutMs, DEFAULT_LONG_RUNNING_KEEP_ALIVE_TIMEOUT_MS),
|
|
52
|
+
keepAliveMaxTimeout: normalizeNonNegativeMs(options?.keepAliveMaxTimeoutMs, DEFAULT_LONG_RUNNING_KEEP_ALIVE_MAX_TIMEOUT_MS)
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function CreateLongRunningFetchDispatcher(options, undiciModule) {
|
|
56
|
+
if (!undiciModule || typeof undiciModule.Agent !== "function") {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const resolved = ResolveLongRunningFetchDispatcherOptions(options);
|
|
60
|
+
try {
|
|
61
|
+
return new undiciModule.Agent(resolved);
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function CreateLongRunningFetch(options, baseFetch, undiciModule, existingDispatcher) {
|
|
67
|
+
const targetFetch = baseFetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
68
|
+
const dispatcher = existingDispatcher ?? CreateLongRunningFetchDispatcher(options, undiciModule);
|
|
69
|
+
if (!dispatcher) {
|
|
70
|
+
return (input, init) => targetFetch(input, init);
|
|
71
|
+
}
|
|
72
|
+
return (input, init) => {
|
|
73
|
+
const mergedInit = init ? { ...init, dispatcher: init.dispatcher ?? dispatcher } : { dispatcher };
|
|
74
|
+
return targetFetch(input, mergedInit);
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
var AITransportManager = class extends BaseSingleton {
|
|
78
|
+
constructor() {
|
|
79
|
+
super();
|
|
80
|
+
this._slot = void 0;
|
|
81
|
+
this._overrideCache = /* @__PURE__ */ new Map();
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Global singleton instance backed by `@memberjunction/global`'s Global Object Store.
|
|
85
|
+
*/
|
|
86
|
+
static get Instance() {
|
|
87
|
+
return super.getInstance();
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Primes Node's lazy built-in `undici` global dispatcher with zero network traffic (using a
|
|
91
|
+
* pre-aborted `AbortSignal`) so {@link Configure} can access the built-in `Agent` constructor
|
|
92
|
+
* during server startup. Safe no-op in browsers or when already primed.
|
|
93
|
+
*/
|
|
94
|
+
async PrimeNodeBuiltinUndici() {
|
|
95
|
+
const slotHolder = globalThis;
|
|
96
|
+
if (slotHolder[UNDICI_GLOBAL_DISPATCHER_SYMBOL]) {
|
|
97
|
+
return ResolveNodeBuiltinUndiciModule() !== null;
|
|
98
|
+
}
|
|
99
|
+
if (typeof globalThis.fetch !== "function" || typeof AbortController !== "function") {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
const ac = new AbortController();
|
|
104
|
+
ac.abort();
|
|
105
|
+
await globalThis.fetch("http://127.0.0.1:1", { signal: ac.signal }).catch(() => void 0);
|
|
106
|
+
} catch {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
return ResolveNodeBuiltinUndiciModule() !== null;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Alias for {@link PrimeNodeBuiltinUndici} matching the standalone helper name.
|
|
113
|
+
*/
|
|
114
|
+
async PrimeNodeBuiltinUndiciDispatcher() {
|
|
115
|
+
return this.PrimeNodeBuiltinUndici();
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Configures the AI-scoped long-running `fetch` wrapper for AI provider SDK calls ONLY —
|
|
119
|
+
* leaving Node's process-global `undici` dispatcher completely untouched so unrelated outbound
|
|
120
|
+
* traffic (OAuth, webhooks, email/SMS, CRM connectors) retains Node's standard timeouts and
|
|
121
|
+
* any host `ProxyAgent` / mTLS configuration stays intact.
|
|
122
|
+
*/
|
|
123
|
+
Configure(options, undiciModule, baseFetch) {
|
|
124
|
+
const resolved = ResolveLongRunningFetchDispatcherOptions(options);
|
|
125
|
+
if (options?.disabled === true) {
|
|
126
|
+
const previousSlot2 = this._slot;
|
|
127
|
+
const disabledSlot = {
|
|
128
|
+
Fetch: void 0,
|
|
129
|
+
Dispatcher: null,
|
|
130
|
+
Options: resolved,
|
|
131
|
+
OwnsDispatcher: false,
|
|
132
|
+
Disabled: true,
|
|
133
|
+
UndiciModule: undiciModule,
|
|
134
|
+
BaseFetch: baseFetch
|
|
135
|
+
};
|
|
136
|
+
this._slot = disabledSlot;
|
|
137
|
+
let restored2 = false;
|
|
138
|
+
return {
|
|
139
|
+
Installed: false,
|
|
140
|
+
Options: resolved,
|
|
141
|
+
Dispatcher: null,
|
|
142
|
+
SkippedReason: "Disabled via options.disabled",
|
|
143
|
+
Restore: async () => {
|
|
144
|
+
if (restored2) {
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
restored2 = true;
|
|
148
|
+
if (this._slot === disabledSlot) {
|
|
149
|
+
this._slot = previousSlot2;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
let dispatcher = options?.dispatcher ?? null;
|
|
155
|
+
const ownsDispatcher = !dispatcher;
|
|
156
|
+
if (!dispatcher) {
|
|
157
|
+
const slotHolder = globalThis;
|
|
158
|
+
const existingGlobal = slotHolder[UNDICI_GLOBAL_DISPATCHER_SYMBOL];
|
|
159
|
+
if (undiciModule === void 0 && existingGlobal && !IsPlainUndiciAgentDispatcher(existingGlobal)) {
|
|
160
|
+
const ctorName = existingGlobal.constructor?.name ?? "unknown";
|
|
161
|
+
return {
|
|
162
|
+
Installed: false,
|
|
163
|
+
Options: resolved,
|
|
164
|
+
Dispatcher: null,
|
|
165
|
+
SkippedReason: `Host installed custom global dispatcher '${ctorName}'; preserving host transport configuration`,
|
|
166
|
+
Restore: async () => void 0
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
const targetUndici = undiciModule === void 0 ? ResolveNodeBuiltinUndiciModule() : undiciModule;
|
|
170
|
+
if (!targetUndici || typeof targetUndici.Agent !== "function") {
|
|
171
|
+
return {
|
|
172
|
+
Installed: false,
|
|
173
|
+
Options: resolved,
|
|
174
|
+
Dispatcher: null,
|
|
175
|
+
SkippedReason: "Built-in undici Agent dispatcher unavailable in this runtime",
|
|
176
|
+
Restore: async () => void 0
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
dispatcher = new targetUndici.Agent(resolved);
|
|
181
|
+
} catch (err) {
|
|
182
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
183
|
+
return {
|
|
184
|
+
Installed: false,
|
|
185
|
+
Options: resolved,
|
|
186
|
+
Dispatcher: null,
|
|
187
|
+
SkippedReason: `Failed to construct undici Agent dispatcher: ${errMsg}`,
|
|
188
|
+
Restore: async () => void 0
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const scopedFetch = CreateLongRunningFetch(options, baseFetch, null, dispatcher);
|
|
193
|
+
const previousSlot = this._slot;
|
|
194
|
+
const nextSlot = {
|
|
195
|
+
Fetch: scopedFetch,
|
|
196
|
+
Dispatcher: dispatcher,
|
|
197
|
+
Options: resolved,
|
|
198
|
+
OwnsDispatcher: ownsDispatcher,
|
|
199
|
+
UndiciModule: undiciModule,
|
|
200
|
+
BaseFetch: baseFetch
|
|
201
|
+
};
|
|
202
|
+
this._slot = nextSlot;
|
|
203
|
+
let restored = false;
|
|
204
|
+
return {
|
|
205
|
+
Installed: true,
|
|
206
|
+
Options: resolved,
|
|
207
|
+
Dispatcher: dispatcher,
|
|
208
|
+
Restore: async () => {
|
|
209
|
+
if (restored) {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
restored = true;
|
|
213
|
+
if (this._slot === nextSlot) {
|
|
214
|
+
this._slot = previousSlot;
|
|
215
|
+
}
|
|
216
|
+
if (ownsDispatcher && dispatcher?.close) {
|
|
217
|
+
await dispatcher.close();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Returns `true` when {@link Configure} has already been called (either with a custom
|
|
224
|
+
* dispatcher/wrapper or with `{ disabled: true }`), allowing server startup to respect a
|
|
225
|
+
* host's pre-startup configuration rather than overwriting it.
|
|
226
|
+
*/
|
|
227
|
+
IsConfigured() {
|
|
228
|
+
return this._slot !== void 0;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Returns the AI-scoped long-running `fetch` wrapper configured via {@link Configure},
|
|
232
|
+
* optionally customized with per-model `overrides` (e.g., tighter or longer per-model
|
|
233
|
+
* timeouts or a per-model dispatcher), or `undefined` when unconfigured, explicitly disabled,
|
|
234
|
+
* running in a browser, or when a host `ProxyAgent` is active.
|
|
235
|
+
*/
|
|
236
|
+
ResolveFetch(overrides) {
|
|
237
|
+
const slot = this._slot;
|
|
238
|
+
if (!overrides || !this.hasAnyOverride(overrides)) {
|
|
239
|
+
return slot?.Disabled ? void 0 : slot?.Fetch;
|
|
240
|
+
}
|
|
241
|
+
if (overrides.disabled === true) {
|
|
242
|
+
return void 0;
|
|
243
|
+
}
|
|
244
|
+
if (slot?.Disabled && overrides.disabled !== false) {
|
|
245
|
+
return void 0;
|
|
246
|
+
}
|
|
247
|
+
if (overrides.dispatcher) {
|
|
248
|
+
return CreateLongRunningFetch(overrides, slot?.BaseFetch, null, overrides.dispatcher);
|
|
249
|
+
}
|
|
250
|
+
const mergedOptions = this.mergeOverrideOptions(slot?.Options, overrides);
|
|
251
|
+
const cacheKey = this.overrideCacheKey(mergedOptions);
|
|
252
|
+
const cached = this._overrideCache.get(cacheKey);
|
|
253
|
+
if (cached) {
|
|
254
|
+
return cached.Fetch;
|
|
255
|
+
}
|
|
256
|
+
const undiciModule = slot?.UndiciModule;
|
|
257
|
+
const slotHolder = globalThis;
|
|
258
|
+
const existingGlobal = slotHolder[UNDICI_GLOBAL_DISPATCHER_SYMBOL];
|
|
259
|
+
if (undiciModule === void 0 && existingGlobal && !IsPlainUndiciAgentDispatcher(existingGlobal)) {
|
|
260
|
+
return void 0;
|
|
261
|
+
}
|
|
262
|
+
const targetUndici = undiciModule === void 0 ? ResolveNodeBuiltinUndiciModule() : undiciModule;
|
|
263
|
+
if (!targetUndici || typeof targetUndici.Agent !== "function") {
|
|
264
|
+
return slot?.Disabled ? void 0 : slot?.Fetch;
|
|
265
|
+
}
|
|
266
|
+
let dispatcher;
|
|
267
|
+
try {
|
|
268
|
+
dispatcher = new targetUndici.Agent(mergedOptions);
|
|
269
|
+
} catch {
|
|
270
|
+
return slot?.Disabled ? void 0 : slot?.Fetch;
|
|
271
|
+
}
|
|
272
|
+
const fetchFn = CreateLongRunningFetch(overrides, slot?.BaseFetch, null, dispatcher);
|
|
273
|
+
this._overrideCache.set(cacheKey, { Fetch: fetchFn, Dispatcher: dispatcher });
|
|
274
|
+
return fetchFn;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Returns a **late-bound** `FetchFunction` that resolves {@link ResolveFetch} at request
|
|
278
|
+
* execution time (falling back to `globalThis.fetch` when unconfigured).
|
|
279
|
+
*
|
|
280
|
+
* Ideal for provider SDKs initialized inside a model `constructor()` before
|
|
281
|
+
* `AITransportManager.Instance.Configure(...)` or `SetAdditionalSettings(...)` is called:
|
|
282
|
+
* requests automatically pick up the active transport configuration when executed.
|
|
283
|
+
*/
|
|
284
|
+
CreateBoundFetch(getOverrides) {
|
|
285
|
+
return (input, init) => {
|
|
286
|
+
const resolved = this.ResolveFetch(getOverrides ? getOverrides() : void 0);
|
|
287
|
+
if (resolved) {
|
|
288
|
+
return resolved(input, init);
|
|
289
|
+
}
|
|
290
|
+
return globalThis.fetch(input, init);
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Clears any configured AI-scoped long-running `fetch` wrapper, closes its dispatcher ONLY
|
|
295
|
+
* when owned by MJ (never closes a host-supplied or global dispatcher), and closes/clears
|
|
296
|
+
* any cached per-model override dispatchers.
|
|
297
|
+
*/
|
|
298
|
+
async Reset() {
|
|
299
|
+
const slot = this._slot;
|
|
300
|
+
this._slot = void 0;
|
|
301
|
+
const overrideEntries = Array.from(this._overrideCache.values());
|
|
302
|
+
this._overrideCache.clear();
|
|
303
|
+
if (slot?.OwnsDispatcher && slot.Dispatcher?.close) {
|
|
304
|
+
await slot.Dispatcher.close();
|
|
305
|
+
}
|
|
306
|
+
for (const entry of overrideEntries) {
|
|
307
|
+
if (entry.Dispatcher.close) {
|
|
308
|
+
await entry.Dispatcher.close();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
hasAnyOverride(overrides) {
|
|
313
|
+
return overrides.disabled !== void 0 || overrides.dispatcher !== void 0 || overrides.headersTimeoutMs !== void 0 || overrides.bodyTimeoutMs !== void 0 || overrides.connectTimeoutMs !== void 0 || overrides.keepAliveTimeoutMs !== void 0 || overrides.keepAliveMaxTimeoutMs !== void 0;
|
|
314
|
+
}
|
|
315
|
+
mergeOverrideOptions(base, overrides) {
|
|
316
|
+
return ResolveLongRunningFetchDispatcherOptions({
|
|
317
|
+
headersTimeoutMs: overrides.headersTimeoutMs ?? base?.headersTimeout,
|
|
318
|
+
bodyTimeoutMs: overrides.bodyTimeoutMs ?? base?.bodyTimeout,
|
|
319
|
+
connectTimeoutMs: overrides.connectTimeoutMs ?? base?.connectTimeout,
|
|
320
|
+
keepAliveTimeoutMs: overrides.keepAliveTimeoutMs ?? base?.keepAliveTimeout,
|
|
321
|
+
keepAliveMaxTimeoutMs: overrides.keepAliveMaxTimeoutMs ?? base?.keepAliveMaxTimeout
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
overrideCacheKey(options) {
|
|
325
|
+
return `${options.headersTimeout}:${options.bodyTimeout}:${options.connectTimeout}:${options.keepAliveTimeout}:${options.keepAliveMaxTimeout}`;
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
// ../../AI/Core/dist/generic/baseModel.types.js
|
|
7
330
|
var BaseResult = class {
|
|
8
331
|
get timeElapsed() {
|
|
9
332
|
return this.endTime.getTime() - this.startTime.getTime();
|
|
@@ -73,6 +396,8 @@ var ModelUsage = class _ModelUsage {
|
|
|
73
396
|
return usage;
|
|
74
397
|
}
|
|
75
398
|
};
|
|
399
|
+
|
|
400
|
+
// ../../AI/Core/dist/generic/baseModel.js
|
|
76
401
|
var BaseModel = class {
|
|
77
402
|
/**
|
|
78
403
|
* Only sub-classes can access the API key
|
|
@@ -81,10 +406,141 @@ var BaseModel = class {
|
|
|
81
406
|
return this._apiKey;
|
|
82
407
|
}
|
|
83
408
|
constructor(apiKey) {
|
|
409
|
+
this._cachedClient = void 0;
|
|
410
|
+
this._hasCachedClient = false;
|
|
411
|
+
this._boundFetch = void 0;
|
|
412
|
+
this._additionalSettings = {};
|
|
84
413
|
if (!apiKey || apiKey.trim().length === 0)
|
|
85
414
|
console.warn("BaseModel: API key is empty, this might cause issues with model execution");
|
|
86
415
|
this._apiKey = apiKey;
|
|
87
416
|
}
|
|
417
|
+
/**
|
|
418
|
+
* Get the current additional settings
|
|
419
|
+
*/
|
|
420
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserves BaseLLM/BaseEmbeddings public signature
|
|
421
|
+
get AdditionalSettings() {
|
|
422
|
+
return this._additionalSettings;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Set additional provider-specific settings and notify {@link OnAdditionalSettingsChanged}
|
|
426
|
+
* (which invalidates any SDK client cached via {@link GetOrCreateClient}).
|
|
427
|
+
* Subclasses may override this method to validate required settings and should call `super.SetAdditionalSettings(settings)`.
|
|
428
|
+
*
|
|
429
|
+
* @param settings Provider-specific settings
|
|
430
|
+
*/
|
|
431
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserves BaseLLM/BaseEmbeddings subclass override compatibility
|
|
432
|
+
SetAdditionalSettings(settings) {
|
|
433
|
+
this._additionalSettings = { ...this._additionalSettings, ...settings };
|
|
434
|
+
this.OnAdditionalSettingsChanged();
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Clear all additional settings and notify {@link OnAdditionalSettingsChanged}.
|
|
438
|
+
* Useful for resetting provider state or switching between configurations.
|
|
439
|
+
*/
|
|
440
|
+
ClearAdditionalSettings() {
|
|
441
|
+
this._additionalSettings = {};
|
|
442
|
+
this.OnAdditionalSettingsChanged();
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Lifecycle hook invoked after {@link SetAdditionalSettings} or {@link ClearAdditionalSettings}.
|
|
446
|
+
* Default implementation invalidates any cached SDK client built through {@link GetOrCreateClient}.
|
|
447
|
+
*/
|
|
448
|
+
OnAdditionalSettingsChanged() {
|
|
449
|
+
this.InvalidateClient();
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Reads optional per-model HTTP transport overrides from {@link _additionalSettings}.
|
|
453
|
+
* Supports either a nested `transport` object ({@link LongRunningFetchDispatcherOptions})
|
|
454
|
+
* or flat timeout keys (`headersTimeoutMs`, `bodyTimeoutMs`, `connectTimeoutMs`,
|
|
455
|
+
* `keepAliveTimeoutMs`, `keepAliveMaxTimeoutMs`, `transportDisabled`).
|
|
456
|
+
*/
|
|
457
|
+
ResolveTransportOverrides() {
|
|
458
|
+
const settings = this._additionalSettings;
|
|
459
|
+
if (!settings || typeof settings !== "object") {
|
|
460
|
+
return void 0;
|
|
461
|
+
}
|
|
462
|
+
const nested = settings["transport"];
|
|
463
|
+
if (nested && typeof nested === "object") {
|
|
464
|
+
return nested;
|
|
465
|
+
}
|
|
466
|
+
const overrides = {};
|
|
467
|
+
let hasAny = false;
|
|
468
|
+
if (typeof settings["headersTimeoutMs"] === "number") {
|
|
469
|
+
overrides.headersTimeoutMs = settings["headersTimeoutMs"];
|
|
470
|
+
hasAny = true;
|
|
471
|
+
}
|
|
472
|
+
if (typeof settings["bodyTimeoutMs"] === "number") {
|
|
473
|
+
overrides.bodyTimeoutMs = settings["bodyTimeoutMs"];
|
|
474
|
+
hasAny = true;
|
|
475
|
+
}
|
|
476
|
+
if (typeof settings["connectTimeoutMs"] === "number") {
|
|
477
|
+
overrides.connectTimeoutMs = settings["connectTimeoutMs"];
|
|
478
|
+
hasAny = true;
|
|
479
|
+
}
|
|
480
|
+
if (typeof settings["keepAliveTimeoutMs"] === "number") {
|
|
481
|
+
overrides.keepAliveTimeoutMs = settings["keepAliveTimeoutMs"];
|
|
482
|
+
hasAny = true;
|
|
483
|
+
}
|
|
484
|
+
if (typeof settings["keepAliveMaxTimeoutMs"] === "number") {
|
|
485
|
+
overrides.keepAliveMaxTimeoutMs = settings["keepAliveMaxTimeoutMs"];
|
|
486
|
+
hasAny = true;
|
|
487
|
+
}
|
|
488
|
+
if (typeof settings["transportDisabled"] === "boolean") {
|
|
489
|
+
overrides.disabled = settings["transportDisabled"];
|
|
490
|
+
hasAny = true;
|
|
491
|
+
}
|
|
492
|
+
return hasAny ? overrides : void 0;
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Returns the AI-scoped long-running `fetch` wrapper from {@link AITransportManager.Instance}
|
|
496
|
+
* (applying any per-model overrides from {@link ResolveTransportOverrides}), or `undefined` when
|
|
497
|
+
* no custom transport is active or configured.
|
|
498
|
+
*/
|
|
499
|
+
get CustomFetch() {
|
|
500
|
+
return AITransportManager.Instance.ResolveFetch(this.ResolveTransportOverrides());
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Memoized per-instance late-bound `fetch` wrapper that resolves {@link CustomFetch} at request
|
|
504
|
+
* execution time (falling back to `globalThis.fetch` when unconfigured).
|
|
505
|
+
*
|
|
506
|
+
* SDK clients initialized in `constructor()` with `fetch: this.BoundFetch` automatically pick up
|
|
507
|
+
* `AITransportManager.Instance.Configure(...)` or `SetAdditionalSettings(...)` changes made
|
|
508
|
+
* after model instantiation.
|
|
509
|
+
*/
|
|
510
|
+
get BoundFetch() {
|
|
511
|
+
if (!this._boundFetch) {
|
|
512
|
+
this._boundFetch = AITransportManager.Instance.CreateBoundFetch(() => this.ResolveTransportOverrides());
|
|
513
|
+
}
|
|
514
|
+
return this._boundFetch;
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Returns `{ fetch: this.CustomFetch }` when a custom AI transport is configured, or `{}`
|
|
518
|
+
* when unconfigured, so SDK constructor options never receive `{ fetch: undefined }`.
|
|
519
|
+
*/
|
|
520
|
+
BuildTransportClientOptions() {
|
|
521
|
+
const customFetch = this.CustomFetch;
|
|
522
|
+
return customFetch ? { fetch: customFetch } : {};
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Lazily creates and caches a provider SDK client instance. Calling {@link InvalidateClient}
|
|
526
|
+
* (automatically invoked by {@link OnAdditionalSettingsChanged}) clears the cached instance so
|
|
527
|
+
* the next call rebuilds it with updated settings.
|
|
528
|
+
*/
|
|
529
|
+
GetOrCreateClient(factory) {
|
|
530
|
+
if (!this._hasCachedClient) {
|
|
531
|
+
this._cachedClient = factory();
|
|
532
|
+
this._hasCachedClient = true;
|
|
533
|
+
}
|
|
534
|
+
return this._cachedClient;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Discards the cached SDK client created by {@link GetOrCreateClient}, forcing lazy
|
|
538
|
+
* reconstruction on the next access.
|
|
539
|
+
*/
|
|
540
|
+
InvalidateClient() {
|
|
541
|
+
this._cachedClient = void 0;
|
|
542
|
+
this._hasCachedClient = false;
|
|
543
|
+
}
|
|
88
544
|
};
|
|
89
545
|
|
|
90
546
|
// ../../AI/Core/dist/generic/realtimeConversationMemory.js
|
|
@@ -2148,38 +2604,222 @@ var ErrorAnalyzer = class {
|
|
|
2148
2604
|
}
|
|
2149
2605
|
};
|
|
2150
2606
|
|
|
2151
|
-
// ../../AI/Core/dist/generic/
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2607
|
+
// ../../AI/Core/dist/generic/openAICompatibleTools.js
|
|
2608
|
+
function BuildOpenAICompatibleTools(tools) {
|
|
2609
|
+
return tools.map((tool) => ({
|
|
2610
|
+
type: "function",
|
|
2611
|
+
function: {
|
|
2612
|
+
name: tool.name,
|
|
2613
|
+
description: tool.description,
|
|
2614
|
+
parameters: tool.inputSchema
|
|
2615
|
+
}
|
|
2616
|
+
}));
|
|
2617
|
+
}
|
|
2618
|
+
function BuildOpenAICompatibleToolChoice(choice) {
|
|
2619
|
+
return typeof choice === "string" ? choice : { type: "function", function: { name: choice.name } };
|
|
2620
|
+
}
|
|
2621
|
+
function BuildOpenAICompatibleToolCalls(toolCalls) {
|
|
2622
|
+
return toolCalls.map((call) => ({
|
|
2623
|
+
id: call.id,
|
|
2624
|
+
type: "function",
|
|
2625
|
+
function: {
|
|
2626
|
+
name: call.name,
|
|
2627
|
+
arguments: JSON.stringify(call.arguments ?? {})
|
|
2628
|
+
}
|
|
2629
|
+
}));
|
|
2630
|
+
}
|
|
2631
|
+
function BuildOpenAICompatibleToolResults(message, providerName) {
|
|
2632
|
+
const blocks = GetToolResultBlocks(message.content);
|
|
2633
|
+
if (blocks.length === 0) {
|
|
2634
|
+
console.warn(`${providerName}: a tool-role message carried no tool_result blocks; skipping it.`);
|
|
2635
|
+
return [];
|
|
2157
2636
|
}
|
|
2158
|
-
|
|
2159
|
-
|
|
2637
|
+
return blocks.map((block) => ({
|
|
2638
|
+
role: "tool",
|
|
2639
|
+
tool_call_id: block.toolCallId,
|
|
2640
|
+
// This wire shape has no error flag on a tool result, so a failure has to be marked in the
|
|
2641
|
+
// text or the model cannot tell a failure from a result.
|
|
2642
|
+
content: block.isError ? `ERROR: ${block.content}` : block.content
|
|
2643
|
+
}));
|
|
2644
|
+
}
|
|
2645
|
+
var MALFORMED_ARGUMENT_PREVIEW = 200;
|
|
2646
|
+
function parseArgumentObject(raw) {
|
|
2647
|
+
try {
|
|
2648
|
+
const parsed = JSON.parse(raw || "{}");
|
|
2649
|
+
if (parsed === null) {
|
|
2650
|
+
return {};
|
|
2651
|
+
}
|
|
2652
|
+
return typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
2653
|
+
} catch {
|
|
2654
|
+
return void 0;
|
|
2655
|
+
}
|
|
2656
|
+
}
|
|
2657
|
+
function ReadOpenAICompatibleToolCalls(toolCalls, providerName) {
|
|
2658
|
+
const calls = [];
|
|
2659
|
+
for (const call of toolCalls ?? []) {
|
|
2660
|
+
const name = call.function?.name;
|
|
2661
|
+
if (call.type !== void 0 && call.type !== "function" || !name) {
|
|
2662
|
+
continue;
|
|
2663
|
+
}
|
|
2664
|
+
const args = parseArgumentObject(call.function?.arguments);
|
|
2665
|
+
if (!args) {
|
|
2666
|
+
const raw = call.function?.arguments ?? "";
|
|
2667
|
+
console.warn(`${providerName}: the arguments of tool call '${name}' are not a JSON object; reporting a malformed tool call.`);
|
|
2668
|
+
const preview = raw.length > MALFORMED_ARGUMENT_PREVIEW ? `${raw.slice(0, MALFORMED_ARGUMENT_PREVIEW)}\u2026` : raw;
|
|
2669
|
+
return { Malformed: `The arguments of ${name} were not a JSON object: ${preview}` };
|
|
2670
|
+
}
|
|
2671
|
+
calls.push({ id: call.id ?? "", name, arguments: args });
|
|
2672
|
+
}
|
|
2673
|
+
return calls.length > 0 ? { Calls: calls } : {};
|
|
2674
|
+
}
|
|
2675
|
+
|
|
2676
|
+
// ../../AI/Core/dist/generic/thinkingStreamExtractor.js
|
|
2677
|
+
var ThinkingStreamExtractor = class {
|
|
2678
|
+
constructor(tags = { open: "<think>", close: "</think>" }) {
|
|
2679
|
+
this._accumulatedThinking = "";
|
|
2680
|
+
this._inThinkingBlock = false;
|
|
2681
|
+
this._pendingContent = "";
|
|
2682
|
+
this._thinkingComplete = false;
|
|
2683
|
+
this._openTag = tags.open;
|
|
2684
|
+
this._closeTag = tags.close;
|
|
2685
|
+
}
|
|
2686
|
+
/** Full thinking/reasoning text accumulated so far during the current stream. */
|
|
2687
|
+
get AccumulatedThinking() {
|
|
2688
|
+
return this._accumulatedThinking;
|
|
2689
|
+
}
|
|
2690
|
+
/** True while currently inside an open thinking block waiting for the closing tag. */
|
|
2691
|
+
get InThinkingBlock() {
|
|
2692
|
+
return this._inThinkingBlock;
|
|
2693
|
+
}
|
|
2694
|
+
/** True once a thinking block has been closed and all subsequent text passes straight through. */
|
|
2695
|
+
get ThinkingComplete() {
|
|
2696
|
+
return this._thinkingComplete;
|
|
2697
|
+
}
|
|
2698
|
+
/** Any buffered trailing fragment currently held back pending the next chunk. */
|
|
2699
|
+
get PendingContent() {
|
|
2700
|
+
return this._pendingContent;
|
|
2160
2701
|
}
|
|
2161
2702
|
/**
|
|
2162
|
-
*
|
|
2703
|
+
* Appends native reasoning text received out-of-band (e.g., OpenAI `delta.reasoning_content`,
|
|
2704
|
+
* Groq `reasoning`, or Anthropic `thinking_delta`) directly into {@link AccumulatedThinking}.
|
|
2163
2705
|
*/
|
|
2164
|
-
|
|
2165
|
-
|
|
2706
|
+
AppendThinking(delta) {
|
|
2707
|
+
if (delta) {
|
|
2708
|
+
this._accumulatedThinking += delta;
|
|
2709
|
+
}
|
|
2166
2710
|
}
|
|
2167
2711
|
/**
|
|
2168
|
-
*
|
|
2169
|
-
*
|
|
2170
|
-
*
|
|
2171
|
-
* @param settings Provider-specific settings
|
|
2712
|
+
* Processes one raw streaming text chunk, returning the user-visible `contentDelta` and any
|
|
2713
|
+
* captured `thinkingDelta`. Handles tags split across arbitrary chunk boundaries and
|
|
2714
|
+
* case-insensitive matching.
|
|
2172
2715
|
*/
|
|
2173
|
-
|
|
2174
|
-
|
|
2716
|
+
ProcessChunk(rawChunk) {
|
|
2717
|
+
if (rawChunk) {
|
|
2718
|
+
this._pendingContent += rawChunk;
|
|
2719
|
+
}
|
|
2720
|
+
let contentDelta = "";
|
|
2721
|
+
let thinkingDelta = "";
|
|
2722
|
+
const openLower = this._openTag.toLowerCase();
|
|
2723
|
+
const closeLower = this._closeTag.toLowerCase();
|
|
2724
|
+
while (this._pendingContent.length > 0) {
|
|
2725
|
+
if (this._thinkingComplete) {
|
|
2726
|
+
contentDelta += this._pendingContent;
|
|
2727
|
+
this._pendingContent = "";
|
|
2728
|
+
break;
|
|
2729
|
+
}
|
|
2730
|
+
if (this._inThinkingBlock) {
|
|
2731
|
+
const pendingLower2 = this._pendingContent.toLowerCase();
|
|
2732
|
+
const endIdx = pendingLower2.indexOf(closeLower);
|
|
2733
|
+
if (endIdx !== -1) {
|
|
2734
|
+
const captured2 = this._pendingContent.substring(0, endIdx);
|
|
2735
|
+
this._accumulatedThinking += captured2;
|
|
2736
|
+
thinkingDelta += captured2;
|
|
2737
|
+
this._pendingContent = this._pendingContent.substring(endIdx + this._closeTag.length);
|
|
2738
|
+
this._inThinkingBlock = false;
|
|
2739
|
+
this._thinkingComplete = true;
|
|
2740
|
+
continue;
|
|
2741
|
+
}
|
|
2742
|
+
const closeHoldBack = this.partialTagSuffixLength(this._pendingContent, this._closeTag);
|
|
2743
|
+
const closeCut = this._pendingContent.length - closeHoldBack;
|
|
2744
|
+
const captured = this._pendingContent.substring(0, closeCut);
|
|
2745
|
+
this._accumulatedThinking += captured;
|
|
2746
|
+
thinkingDelta += captured;
|
|
2747
|
+
this._pendingContent = this._pendingContent.substring(closeCut);
|
|
2748
|
+
break;
|
|
2749
|
+
}
|
|
2750
|
+
const pendingLower = this._pendingContent.toLowerCase();
|
|
2751
|
+
const startIdx = pendingLower.indexOf(openLower);
|
|
2752
|
+
if (startIdx !== -1) {
|
|
2753
|
+
if (startIdx > 0) {
|
|
2754
|
+
contentDelta += this._pendingContent.substring(0, startIdx);
|
|
2755
|
+
}
|
|
2756
|
+
this._inThinkingBlock = true;
|
|
2757
|
+
this._pendingContent = this._pendingContent.substring(startIdx + this._openTag.length);
|
|
2758
|
+
continue;
|
|
2759
|
+
}
|
|
2760
|
+
const openHoldBack = this.partialTagSuffixLength(this._pendingContent, this._openTag);
|
|
2761
|
+
const emitEnd = this.avoidSurrogateSplit(this._pendingContent, this._pendingContent.length - openHoldBack);
|
|
2762
|
+
contentDelta += this._pendingContent.substring(0, emitEnd);
|
|
2763
|
+
this._pendingContent = this._pendingContent.substring(emitEnd);
|
|
2764
|
+
break;
|
|
2765
|
+
}
|
|
2766
|
+
return { contentDelta, thinkingDelta };
|
|
2175
2767
|
}
|
|
2176
2768
|
/**
|
|
2177
|
-
*
|
|
2178
|
-
*
|
|
2179
|
-
*
|
|
2769
|
+
* Flushes any held-back visible text fragment at end-of-stream (e.g. a trailing `"<"` that
|
|
2770
|
+
* never became `<think>`). Never flushes buffered text while inside an unterminated thinking
|
|
2771
|
+
* block so reasoning text cannot leak into user-visible output.
|
|
2180
2772
|
*/
|
|
2181
|
-
|
|
2182
|
-
this.
|
|
2773
|
+
Flush() {
|
|
2774
|
+
if (this._inThinkingBlock) {
|
|
2775
|
+
return "";
|
|
2776
|
+
}
|
|
2777
|
+
const remainder = this._pendingContent;
|
|
2778
|
+
this._pendingContent = "";
|
|
2779
|
+
return remainder;
|
|
2780
|
+
}
|
|
2781
|
+
/**
|
|
2782
|
+
* Resets all accumulated thinking and pending buffer state for reuse or memory release.
|
|
2783
|
+
*/
|
|
2784
|
+
Reset() {
|
|
2785
|
+
this._accumulatedThinking = "";
|
|
2786
|
+
this._inThinkingBlock = false;
|
|
2787
|
+
this._pendingContent = "";
|
|
2788
|
+
this._thinkingComplete = false;
|
|
2789
|
+
}
|
|
2790
|
+
partialTagSuffixLength(text, tag) {
|
|
2791
|
+
if (!text || !tag) {
|
|
2792
|
+
return 0;
|
|
2793
|
+
}
|
|
2794
|
+
const t = text.toLowerCase();
|
|
2795
|
+
const g = tag.toLowerCase();
|
|
2796
|
+
const max = Math.min(t.length, g.length - 1);
|
|
2797
|
+
for (let len = max; len > 0; len--) {
|
|
2798
|
+
if (t.endsWith(g.substring(0, len))) {
|
|
2799
|
+
return len;
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
return 0;
|
|
2803
|
+
}
|
|
2804
|
+
avoidSurrogateSplit(text, cut) {
|
|
2805
|
+
if (cut > 0 && cut < text.length) {
|
|
2806
|
+
const code = text.charCodeAt(cut - 1);
|
|
2807
|
+
if (code >= 55296 && code <= 56319) {
|
|
2808
|
+
return cut - 1;
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
return cut;
|
|
2812
|
+
}
|
|
2813
|
+
};
|
|
2814
|
+
|
|
2815
|
+
// ../../AI/Core/dist/generic/baseLLM.js
|
|
2816
|
+
var BaseLLM = class extends BaseModel {
|
|
2817
|
+
constructor() {
|
|
2818
|
+
super(...arguments);
|
|
2819
|
+
this._thinkingExtractor = null;
|
|
2820
|
+
}
|
|
2821
|
+
static {
|
|
2822
|
+
this.ReplayedReasoningRequiresStablePrefix = false;
|
|
2183
2823
|
}
|
|
2184
2824
|
/**
|
|
2185
2825
|
* Process a chat completion request. If streaming is enabled and supported,
|
|
@@ -2248,22 +2888,11 @@ var BaseLLM = class extends BaseModel {
|
|
|
2248
2888
|
throw error;
|
|
2249
2889
|
}));
|
|
2250
2890
|
const results = await Promise.allSettled(promises);
|
|
2251
|
-
const chatResults = results.map((result
|
|
2891
|
+
const chatResults = results.map((result) => {
|
|
2252
2892
|
if (result.status === "fulfilled") {
|
|
2253
2893
|
return result.value;
|
|
2254
2894
|
} else {
|
|
2255
|
-
|
|
2256
|
-
const endTime = /* @__PURE__ */ new Date();
|
|
2257
|
-
const errorResult = new ChatResult(false, startTime, endTime);
|
|
2258
|
-
errorResult.data = {
|
|
2259
|
-
choices: [],
|
|
2260
|
-
usage: new ModelUsage(0, 0)
|
|
2261
|
-
};
|
|
2262
|
-
errorResult.statusText = "error";
|
|
2263
|
-
errorResult.errorMessage = result.reason?.message || "Unknown error";
|
|
2264
|
-
errorResult.exception = { exception: result.reason };
|
|
2265
|
-
errorResult.errorInfo = ErrorAnalyzer.analyzeError(result.reason, this.constructor.name);
|
|
2266
|
-
return errorResult;
|
|
2895
|
+
return this.BuildErrorChatResult(/* @__PURE__ */ new Date(), result.reason);
|
|
2267
2896
|
}
|
|
2268
2897
|
});
|
|
2269
2898
|
if (callbacks?.OnAllCompleted) {
|
|
@@ -2429,17 +3058,7 @@ var BaseLLM = class extends BaseModel {
|
|
|
2429
3058
|
if (params.streamingCallbacks?.OnError) {
|
|
2430
3059
|
params.streamingCallbacks.OnError(error);
|
|
2431
3060
|
}
|
|
2432
|
-
|
|
2433
|
-
const errorResult = new ChatResult(false, startTime, endTime);
|
|
2434
|
-
errorResult.data = {
|
|
2435
|
-
choices: [],
|
|
2436
|
-
usage: new ModelUsage(0, 0)
|
|
2437
|
-
};
|
|
2438
|
-
errorResult.statusText = "error";
|
|
2439
|
-
errorResult.errorMessage = error?.message || "Unknown error";
|
|
2440
|
-
errorResult.exception = { exception: error };
|
|
2441
|
-
errorResult.errorInfo = ErrorAnalyzer.analyzeError(error, this.constructor.name);
|
|
2442
|
-
reject(errorResult);
|
|
3061
|
+
reject(this.BuildErrorChatResult(startTime, error));
|
|
2443
3062
|
} finally {
|
|
2444
3063
|
try {
|
|
2445
3064
|
this.resetStreamingState();
|
|
@@ -2459,6 +3078,7 @@ var BaseLLM = class extends BaseModel {
|
|
|
2459
3078
|
* lifetime.
|
|
2460
3079
|
*/
|
|
2461
3080
|
resetStreamingState() {
|
|
3081
|
+
this.resetThinkingStreamState();
|
|
2462
3082
|
}
|
|
2463
3083
|
/**
|
|
2464
3084
|
* Settles a cancelled stream: resolves the request first, then tells `OnComplete`. A callback that
|
|
@@ -2508,6 +3128,104 @@ var BaseLLM = class extends BaseModel {
|
|
|
2508
3128
|
result.errorInfo = BuildCancellationErrorInfo({ error: options.error, signal: options.signal, provider: this.constructor.name });
|
|
2509
3129
|
return result;
|
|
2510
3130
|
}
|
|
3131
|
+
/**
|
|
3132
|
+
* Builds a normalized {@link ModelUsage} conforming to MemberJunction's uniform cache contract:
|
|
3133
|
+
* `promptTokens` holds UNCACHED/net-new input tokens only, disjoint from `cacheReadTokens` and
|
|
3134
|
+
* `cacheWriteTokens`. Providers whose raw prompt count includes cached tokens (OpenAI, Groq,
|
|
3135
|
+
* Cerebras, Fireworks, Gemini) pass `promptTokensAlreadyExcludesCache: false` (the default) so
|
|
3136
|
+
* `cacheReadTokens` is subtracted (clamped at 0); providers like Anthropic whose `input_tokens`
|
|
3137
|
+
* already excludes cached tokens pass `promptTokensAlreadyExcludesCache: true`.
|
|
3138
|
+
*/
|
|
3139
|
+
BuildNormalizedModelUsage(params) {
|
|
3140
|
+
const cacheReadTokens = Math.max(0, params.cacheReadTokens ?? 0);
|
|
3141
|
+
const cacheWriteTokens = Math.max(0, params.cacheWriteTokens ?? 0);
|
|
3142
|
+
const rawPrompt = Math.max(0, params.rawPromptTokens ?? 0);
|
|
3143
|
+
const completionTokens = Math.max(0, params.completionTokens ?? 0);
|
|
3144
|
+
const netPromptTokens = params.promptTokensAlreadyExcludesCache ? rawPrompt : Math.max(0, rawPrompt - cacheReadTokens);
|
|
3145
|
+
const usage = new ModelUsage(netPromptTokens, completionTokens, params.cost, params.costCurrency);
|
|
3146
|
+
usage.cacheReadTokens = cacheReadTokens;
|
|
3147
|
+
usage.cacheWriteTokens = cacheWriteTokens;
|
|
3148
|
+
return usage;
|
|
3149
|
+
}
|
|
3150
|
+
/**
|
|
3151
|
+
* Builds a standardized error {@link ChatResult} with zeroed {@link ModelUsage} and structured
|
|
3152
|
+
* {@link ErrorAnalyzer.analyzeError} classification.
|
|
3153
|
+
*/
|
|
3154
|
+
BuildErrorChatResult(startTime, error, statusText = "error", providerName) {
|
|
3155
|
+
const errorResult = new ChatResult(false, startTime, /* @__PURE__ */ new Date());
|
|
3156
|
+
errorResult.data = {
|
|
3157
|
+
choices: [],
|
|
3158
|
+
usage: new ModelUsage(0, 0)
|
|
3159
|
+
};
|
|
3160
|
+
errorResult.statusText = statusText;
|
|
3161
|
+
const message = error instanceof Error ? error.message : typeof error === "object" && error !== null && "message" in error && typeof error.message === "string" ? error.message : "Unknown error";
|
|
3162
|
+
errorResult.errorMessage = message || "Unknown error";
|
|
3163
|
+
errorResult.exception = { exception: error };
|
|
3164
|
+
errorResult.errorInfo = ErrorAnalyzer.analyzeError(error, providerName ?? this.constructor.name);
|
|
3165
|
+
return errorResult;
|
|
3166
|
+
}
|
|
3167
|
+
// ============ OpenAI-Compatible Native Tool Calling Helpers ============
|
|
3168
|
+
/**
|
|
3169
|
+
* Formats {@link ChatParams.tools} into OpenAI-compatible function tool declarations, or
|
|
3170
|
+
* returns `undefined` when no tools were declared on `params`.
|
|
3171
|
+
*/
|
|
3172
|
+
FormatOpenAICompatibleTools(params) {
|
|
3173
|
+
if (!params.tools || params.tools.length === 0) {
|
|
3174
|
+
return void 0;
|
|
3175
|
+
}
|
|
3176
|
+
return BuildOpenAICompatibleTools(params.tools);
|
|
3177
|
+
}
|
|
3178
|
+
/**
|
|
3179
|
+
* Formats {@link ChatParams.toolChoice} into OpenAI-compatible `tool_choice`, or returns
|
|
3180
|
+
* `undefined` when not specified on `params`.
|
|
3181
|
+
*/
|
|
3182
|
+
FormatOpenAICompatibleToolChoice(params) {
|
|
3183
|
+
if (params.toolChoice === void 0) {
|
|
3184
|
+
return void 0;
|
|
3185
|
+
}
|
|
3186
|
+
return BuildOpenAICompatibleToolChoice(params.toolChoice);
|
|
3187
|
+
}
|
|
3188
|
+
/**
|
|
3189
|
+
* Formats normalized prior assistant {@link ChatToolCall}s back onto the OpenAI-compatible wire shape.
|
|
3190
|
+
*/
|
|
3191
|
+
FormatOpenAICompatibleToolCalls(toolCalls) {
|
|
3192
|
+
return BuildOpenAICompatibleToolCalls(toolCalls);
|
|
3193
|
+
}
|
|
3194
|
+
/**
|
|
3195
|
+
* Expands one MJ `tool`-role {@link ChatMessage} into OpenAI-compatible per-result `tool` messages.
|
|
3196
|
+
*/
|
|
3197
|
+
FormatOpenAICompatibleToolResults(message, providerName) {
|
|
3198
|
+
return BuildOpenAICompatibleToolResults(message, providerName ?? this.constructor.name);
|
|
3199
|
+
}
|
|
3200
|
+
/**
|
|
3201
|
+
* Parses raw OpenAI-compatible response `tool_calls`, reporting malformed JSON arguments cleanly
|
|
3202
|
+
* via {@link OpenAICompatibleToolCallReadout.Malformed}.
|
|
3203
|
+
*/
|
|
3204
|
+
ParseOpenAICompatibleToolCalls(rawCalls, providerName) {
|
|
3205
|
+
return ReadOpenAICompatibleToolCalls(rawCalls, providerName ?? this.constructor.name);
|
|
3206
|
+
}
|
|
3207
|
+
/**
|
|
3208
|
+
* Factory creating a fresh {@link ThinkingStreamExtractor} configured with the provider's
|
|
3209
|
+
* thinking tag pair (defaults to {@link getThinkingTagFormat}).
|
|
3210
|
+
*/
|
|
3211
|
+
CreateThinkingStreamExtractor(tags) {
|
|
3212
|
+
return new ThinkingStreamExtractor(tags ?? this.getThinkingTagFormat());
|
|
3213
|
+
}
|
|
3214
|
+
/**
|
|
3215
|
+
* Backwards-compatible state view over {@link _thinkingExtractor} for subclasses reading
|
|
3216
|
+
* `this.thinkingStreamState?.accumulatedThinking`.
|
|
3217
|
+
*/
|
|
3218
|
+
get thinkingStreamState() {
|
|
3219
|
+
if (!this._thinkingExtractor) {
|
|
3220
|
+
return null;
|
|
3221
|
+
}
|
|
3222
|
+
return {
|
|
3223
|
+
accumulatedThinking: this._thinkingExtractor.AccumulatedThinking,
|
|
3224
|
+
inThinkingBlock: this._thinkingExtractor.InThinkingBlock,
|
|
3225
|
+
pendingContent: this._thinkingExtractor.PendingContent,
|
|
3226
|
+
thinkingComplete: this._thinkingExtractor.ThinkingComplete
|
|
3227
|
+
};
|
|
3228
|
+
}
|
|
2511
3229
|
/**
|
|
2512
3230
|
* Check if the provider supports thinking models
|
|
2513
3231
|
* Providers should override this to return true if they support thinking extraction
|
|
@@ -2552,126 +3270,33 @@ var BaseLLM = class extends BaseModel {
|
|
|
2552
3270
|
* Initialize thinking stream state for streaming extraction
|
|
2553
3271
|
*/
|
|
2554
3272
|
initializeThinkingStreamState() {
|
|
2555
|
-
this.
|
|
2556
|
-
accumulatedThinking: "",
|
|
2557
|
-
inThinkingBlock: false,
|
|
2558
|
-
pendingContent: "",
|
|
2559
|
-
thinkingComplete: false
|
|
2560
|
-
};
|
|
3273
|
+
this._thinkingExtractor = this.CreateThinkingStreamExtractor();
|
|
2561
3274
|
}
|
|
2562
3275
|
/**
|
|
2563
3276
|
* Reset thinking stream state
|
|
2564
3277
|
*/
|
|
2565
3278
|
resetThinkingStreamState() {
|
|
2566
|
-
this.
|
|
3279
|
+
if (this._thinkingExtractor) {
|
|
3280
|
+
this._thinkingExtractor.Reset();
|
|
3281
|
+
}
|
|
3282
|
+
this._thinkingExtractor = null;
|
|
2567
3283
|
}
|
|
2568
3284
|
/**
|
|
2569
3285
|
* Returns (and clears) any user-visible content the thinking-tag stripper is still holding back at
|
|
2570
|
-
* the end of a stream.
|
|
2571
|
-
* fragment that could be the start of a `<think>`/`</think>` tag so a split tag never leaks as
|
|
2572
|
-
* partial text; once the stream ends, such a fragment is real content and must be emitted (bug A5).
|
|
2573
|
-
*
|
|
2574
|
-
* Only flushes when NOT inside a thinking block: an unterminated `<think>` block's buffered text is
|
|
2575
|
-
* reasoning, not answer, and is left held back (never surfaced as visible content). Returns `''`
|
|
2576
|
-
* when thinking extraction isn't active (no state) or there's nothing to flush.
|
|
3286
|
+
* the end of a stream. Delegates to {@link ThinkingStreamExtractor.Flush}.
|
|
2577
3287
|
*/
|
|
2578
3288
|
flushThinkingStreamRemainder() {
|
|
2579
|
-
|
|
2580
|
-
if (!state || state.inThinkingBlock) {
|
|
2581
|
-
return "";
|
|
2582
|
-
}
|
|
2583
|
-
const remainder = state.pendingContent;
|
|
2584
|
-
state.pendingContent = "";
|
|
2585
|
-
return remainder;
|
|
3289
|
+
return this._thinkingExtractor ? this._thinkingExtractor.Flush() : "";
|
|
2586
3290
|
}
|
|
2587
3291
|
/**
|
|
2588
|
-
* Process streaming chunk with thinking extraction
|
|
2589
|
-
*
|
|
3292
|
+
* Process streaming chunk with thinking extraction.
|
|
3293
|
+
* Delegates to {@link ThinkingStreamExtractor.ProcessChunk}.
|
|
2590
3294
|
*/
|
|
2591
3295
|
processStreamChunkWithThinking(rawContent) {
|
|
2592
|
-
if (!this.
|
|
3296
|
+
if (!this._thinkingExtractor) {
|
|
2593
3297
|
return rawContent;
|
|
2594
3298
|
}
|
|
2595
|
-
|
|
2596
|
-
this.thinkingStreamState.pendingContent += rawContent;
|
|
2597
|
-
if (this.thinkingStreamState.thinkingComplete) {
|
|
2598
|
-
contentToEmit = this.thinkingStreamState.pendingContent;
|
|
2599
|
-
this.thinkingStreamState.pendingContent = "";
|
|
2600
|
-
return contentToEmit;
|
|
2601
|
-
}
|
|
2602
|
-
const tags = this.getThinkingTagFormat();
|
|
2603
|
-
const pending = this.thinkingStreamState.pendingContent;
|
|
2604
|
-
const pendingLower = pending.toLowerCase();
|
|
2605
|
-
if (!this.thinkingStreamState.inThinkingBlock && pendingLower.includes(tags.open.toLowerCase())) {
|
|
2606
|
-
const thinkStartIndex = pendingLower.indexOf(tags.open.toLowerCase());
|
|
2607
|
-
if (thinkStartIndex > 0) {
|
|
2608
|
-
contentToEmit = pending.substring(0, thinkStartIndex);
|
|
2609
|
-
this.thinkingStreamState.pendingContent = pending.substring(thinkStartIndex);
|
|
2610
|
-
return contentToEmit;
|
|
2611
|
-
}
|
|
2612
|
-
this.thinkingStreamState.inThinkingBlock = true;
|
|
2613
|
-
this.thinkingStreamState.pendingContent = pending.substring(tags.open.length);
|
|
2614
|
-
}
|
|
2615
|
-
if (this.thinkingStreamState.inThinkingBlock) {
|
|
2616
|
-
const pendingInBlockLower = this.thinkingStreamState.pendingContent.toLowerCase();
|
|
2617
|
-
const thinkEndIndex = pendingInBlockLower.indexOf(tags.close.toLowerCase());
|
|
2618
|
-
if (thinkEndIndex !== -1) {
|
|
2619
|
-
this.thinkingStreamState.accumulatedThinking += this.thinkingStreamState.pendingContent.substring(0, thinkEndIndex);
|
|
2620
|
-
this.thinkingStreamState.pendingContent = this.thinkingStreamState.pendingContent.substring(thinkEndIndex + tags.close.length);
|
|
2621
|
-
this.thinkingStreamState.inThinkingBlock = false;
|
|
2622
|
-
this.thinkingStreamState.thinkingComplete = true;
|
|
2623
|
-
return this.processStreamChunkWithThinking("");
|
|
2624
|
-
} else {
|
|
2625
|
-
const closeHoldBack = this.partialTagSuffixLength(this.thinkingStreamState.pendingContent, tags.close);
|
|
2626
|
-
const closeCut = this.thinkingStreamState.pendingContent.length - closeHoldBack;
|
|
2627
|
-
this.thinkingStreamState.accumulatedThinking += this.thinkingStreamState.pendingContent.substring(0, closeCut);
|
|
2628
|
-
this.thinkingStreamState.pendingContent = this.thinkingStreamState.pendingContent.substring(closeCut);
|
|
2629
|
-
return "";
|
|
2630
|
-
}
|
|
2631
|
-
}
|
|
2632
|
-
const openHoldBack = this.partialTagSuffixLength(this.thinkingStreamState.pendingContent, tags.open);
|
|
2633
|
-
let emitEnd = this.avoidSurrogateSplit(this.thinkingStreamState.pendingContent, this.thinkingStreamState.pendingContent.length - openHoldBack);
|
|
2634
|
-
contentToEmit = this.thinkingStreamState.pendingContent.substring(0, emitEnd);
|
|
2635
|
-
this.thinkingStreamState.pendingContent = this.thinkingStreamState.pendingContent.substring(emitEnd);
|
|
2636
|
-
return contentToEmit;
|
|
2637
|
-
}
|
|
2638
|
-
/**
|
|
2639
|
-
* Returns the length of the longest suffix of `text` that is a non-empty prefix of `tag`
|
|
2640
|
-
* (case-insensitive). Used to detect a tag that may be split across streaming chunk
|
|
2641
|
-
* boundaries so the caller can hold that partial fragment back instead of emitting it.
|
|
2642
|
-
* Returns 0 when no suffix of `text` is a prefix of `tag`.
|
|
2643
|
-
*/
|
|
2644
|
-
partialTagSuffixLength(text, tag) {
|
|
2645
|
-
if (!text || !tag) {
|
|
2646
|
-
return 0;
|
|
2647
|
-
}
|
|
2648
|
-
const t = text.toLowerCase();
|
|
2649
|
-
const g = tag.toLowerCase();
|
|
2650
|
-
const max = Math.min(t.length, g.length - 1);
|
|
2651
|
-
for (let len = max; len > 0; len--) {
|
|
2652
|
-
if (t.endsWith(g.substring(0, len))) {
|
|
2653
|
-
return len;
|
|
2654
|
-
}
|
|
2655
|
-
}
|
|
2656
|
-
return 0;
|
|
2657
|
-
}
|
|
2658
|
-
/**
|
|
2659
|
-
* Defensive guard for the tag hold-back: if the emit/hold boundary would fall *between* the two
|
|
2660
|
-
* halves of a UTF-16 surrogate pair (which renders as U+FFFD), move the cut back by one so the
|
|
2661
|
-
* full pair stays together in the held-back remainder. In the common case the held-back fragment
|
|
2662
|
-
* is an ASCII tag prefix (e.g. "<thi"), so `cut` lands on an ASCII boundary and this is a no-op;
|
|
2663
|
-
* it only bites when a hold-back boundary happens to land mid-pair. Note it does NOT hold back a
|
|
2664
|
-
* lone trailing high surrogate when nothing else is being held back (holdBack === 0) — a pair
|
|
2665
|
-
* split exactly at a streaming chunk boundary is left to render and is corrected by the next chunk.
|
|
2666
|
-
*/
|
|
2667
|
-
avoidSurrogateSplit(text, cut) {
|
|
2668
|
-
if (cut > 0 && cut < text.length) {
|
|
2669
|
-
const code = text.charCodeAt(cut - 1);
|
|
2670
|
-
if (code >= 55296 && code <= 56319) {
|
|
2671
|
-
return cut - 1;
|
|
2672
|
-
}
|
|
2673
|
-
}
|
|
2674
|
-
return cut;
|
|
3299
|
+
return this._thinkingExtractor.ProcessChunk(rawContent).contentDelta;
|
|
2675
3300
|
}
|
|
2676
3301
|
/**
|
|
2677
3302
|
* Add thinking content to a chat completion message
|