@librechat/agents 4.2.6 → 4.2.8

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.
Files changed (97) hide show
  1. package/README.md +1 -0
  2. package/dist/cjs/harness/index.cjs +2 -0
  3. package/dist/cjs/harness/index.cjs.map +1 -1
  4. package/dist/cjs/harness/model.cjs +244 -0
  5. package/dist/cjs/harness/model.cjs.map +1 -0
  6. package/dist/cjs/harness/modelService.cjs +335 -0
  7. package/dist/cjs/harness/modelService.cjs.map +1 -0
  8. package/dist/cjs/harness/modelStreamCallbacks.cjs +102 -0
  9. package/dist/cjs/harness/modelStreamCallbacks.cjs.map +1 -0
  10. package/dist/cjs/harness/providerText.cjs +6 -1
  11. package/dist/cjs/harness/providerText.cjs.map +1 -1
  12. package/dist/cjs/llm/google/completion.cjs +49 -0
  13. package/dist/cjs/llm/google/completion.cjs.map +1 -0
  14. package/dist/cjs/llm/google/index.cjs +45 -20
  15. package/dist/cjs/llm/google/index.cjs.map +1 -1
  16. package/dist/cjs/llm/google/transport.cjs +133 -0
  17. package/dist/cjs/llm/google/transport.cjs.map +1 -0
  18. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  19. package/dist/cjs/llm/invoke.cjs +3 -18
  20. package/dist/cjs/llm/invoke.cjs.map +1 -1
  21. package/dist/cjs/llm/modelCallbackRun.cjs +26 -0
  22. package/dist/cjs/llm/modelCallbackRun.cjs.map +1 -0
  23. package/dist/cjs/llm/stream/chunkAdapters.cjs +3 -2
  24. package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
  25. package/dist/cjs/main.cjs +12 -0
  26. package/dist/cjs/messages/index.cjs +1 -0
  27. package/dist/cjs/messages/stored.cjs +34 -0
  28. package/dist/cjs/messages/stored.cjs.map +1 -0
  29. package/dist/cjs/protection/providerText.cjs +68 -14
  30. package/dist/cjs/protection/providerText.cjs.map +1 -1
  31. package/dist/cjs/protection/providerTextAdmission.cjs +56 -0
  32. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -0
  33. package/dist/esm/harness/index.mjs +2 -0
  34. package/dist/esm/harness/index.mjs.map +1 -1
  35. package/dist/esm/harness/model.mjs +241 -0
  36. package/dist/esm/harness/model.mjs.map +1 -0
  37. package/dist/esm/harness/modelService.mjs +334 -0
  38. package/dist/esm/harness/modelService.mjs.map +1 -0
  39. package/dist/esm/harness/modelStreamCallbacks.mjs +102 -0
  40. package/dist/esm/harness/modelStreamCallbacks.mjs.map +1 -0
  41. package/dist/esm/harness/providerText.mjs +7 -2
  42. package/dist/esm/harness/providerText.mjs.map +1 -1
  43. package/dist/esm/llm/google/completion.mjs +48 -0
  44. package/dist/esm/llm/google/completion.mjs.map +1 -0
  45. package/dist/esm/llm/google/index.mjs +46 -21
  46. package/dist/esm/llm/google/index.mjs.map +1 -1
  47. package/dist/esm/llm/google/transport.mjs +133 -0
  48. package/dist/esm/llm/google/transport.mjs.map +1 -0
  49. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  50. package/dist/esm/llm/invoke.mjs +3 -18
  51. package/dist/esm/llm/invoke.mjs.map +1 -1
  52. package/dist/esm/llm/modelCallbackRun.mjs +26 -0
  53. package/dist/esm/llm/modelCallbackRun.mjs.map +1 -0
  54. package/dist/esm/llm/stream/chunkAdapters.mjs +3 -2
  55. package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
  56. package/dist/esm/main.mjs +6 -2
  57. package/dist/esm/messages/index.mjs +1 -0
  58. package/dist/esm/messages/stored.mjs +34 -0
  59. package/dist/esm/messages/stored.mjs.map +1 -0
  60. package/dist/esm/protection/providerText.mjs +66 -15
  61. package/dist/esm/protection/providerText.mjs.map +1 -1
  62. package/dist/esm/protection/providerTextAdmission.mjs +56 -0
  63. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -0
  64. package/dist/types/harness/index.d.ts +4 -0
  65. package/dist/types/harness/model.d.ts +104 -0
  66. package/dist/types/harness/modelService.d.ts +50 -0
  67. package/dist/types/harness/modelStreamCallbacks.d.ts +11 -0
  68. package/dist/types/harness/providerText.d.ts +5 -0
  69. package/dist/types/index.d.ts +4 -2
  70. package/dist/types/llm/google/completion.d.ts +4 -0
  71. package/dist/types/llm/google/index.d.ts +3 -1
  72. package/dist/types/llm/google/transport.d.ts +15 -0
  73. package/dist/types/llm/google/utils/common.d.ts +5 -3
  74. package/dist/types/llm/modelCallbackRun.d.ts +9 -0
  75. package/dist/types/llm/stream/chunkAdapters.d.ts +2 -1
  76. package/dist/types/messages/index.d.ts +1 -0
  77. package/dist/types/messages/stored.d.ts +7 -0
  78. package/dist/types/protection/providerText.d.ts +15 -1
  79. package/dist/types/protection/providerTextAdmission.d.ts +29 -0
  80. package/package.json +2 -1
  81. package/src/harness/index.ts +12 -0
  82. package/src/harness/model.ts +392 -0
  83. package/src/harness/modelService.ts +525 -0
  84. package/src/harness/modelStreamCallbacks.ts +137 -0
  85. package/src/harness/providerText.ts +13 -1
  86. package/src/index.ts +9 -0
  87. package/src/llm/google/completion.ts +91 -0
  88. package/src/llm/google/index.ts +95 -34
  89. package/src/llm/google/transport.ts +202 -0
  90. package/src/llm/google/utils/common.ts +6 -2
  91. package/src/llm/invoke.ts +3 -72
  92. package/src/llm/modelCallbackRun.ts +77 -0
  93. package/src/llm/stream/chunkAdapters.ts +3 -1
  94. package/src/messages/index.ts +1 -0
  95. package/src/messages/stored.ts +48 -0
  96. package/src/protection/providerText.ts +93 -14
  97. package/src/protection/providerTextAdmission.ts +86 -0
@@ -0,0 +1,525 @@
1
+ import { z } from 'zod';
2
+ import { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';
3
+ import {
4
+ serialize as serializeNativeValue,
5
+ deserialize as deserializeNativeValue,
6
+ } from 'node:v8';
7
+ import {
8
+ isAIMessage,
9
+ isAIMessageChunk,
10
+ isBaseMessage,
11
+ mapStoredMessagesToChatMessages,
12
+ } from '@langchain/core/messages';
13
+ import type {
14
+ AIMessage,
15
+ AIMessageChunk,
16
+ BaseMessage,
17
+ StoredMessage,
18
+ } from '@langchain/core/messages';
19
+ import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
20
+ import type { RunnableConfig } from '@langchain/core/runnables';
21
+ import type {
22
+ HostModelDescriptor,
23
+ HostModelRequest,
24
+ HostModelService,
25
+ HostModelErrorCode,
26
+ } from './model';
27
+ import type { ExecutionIdentity } from './identity';
28
+ import {
29
+ executionIdentitySchema,
30
+ snapshotExecutionIdentity,
31
+ matchesExecutionIdentity,
32
+ } from './identity';
33
+ import {
34
+ hostModelDescriptorSchema,
35
+ HostModelServiceError,
36
+ normalizeHostModelError,
37
+ } from './model';
38
+ import { modelStreamCallbacks } from './modelStreamCallbacks';
39
+ import { getProviderFamily } from '@/llm/providers';
40
+ import { toStoredMessage } from '@/messages/stored';
41
+
42
+ interface ModelLease {
43
+ charge(bytes: number): void;
44
+ retain(): void;
45
+ release(): void;
46
+ }
47
+
48
+ /** Shared host scope; admission remains charged until provider work and iterator cleanup settle. */
49
+ export class HostModelAdmission {
50
+ private calls = 0;
51
+ private bytes = 0;
52
+ private retainedCalls = 0;
53
+ private retainedBytes = 0;
54
+ private readonly maxConcurrentCalls: number;
55
+ private readonly maxRequestBytes: number;
56
+
57
+ constructor(limits: { maxConcurrentCalls: number; maxRequestBytes: number }) {
58
+ positive(limits.maxConcurrentCalls);
59
+ positive(limits.maxRequestBytes);
60
+ this.maxConcurrentCalls = limits.maxConcurrentCalls;
61
+ this.maxRequestBytes = limits.maxRequestBytes;
62
+ }
63
+
64
+ snapshot(): Readonly<{
65
+ calls: number;
66
+ requestBytes: number;
67
+ retainedCalls: number;
68
+ retainedRequestBytes: number;
69
+ }> {
70
+ return Object.freeze({
71
+ calls: this.calls,
72
+ requestBytes: this.bytes,
73
+ retainedCalls: this.retainedCalls,
74
+ retainedRequestBytes: this.retainedBytes,
75
+ });
76
+ }
77
+
78
+ /** @internal The binding owns this lease; transports cannot release outstanding provider work. */
79
+ acquire(bytes: number): ModelLease {
80
+ positive(bytes);
81
+ if (
82
+ this.calls >= this.maxConcurrentCalls ||
83
+ bytes > this.maxRequestBytes - this.bytes
84
+ )
85
+ throw new HostModelServiceError('overflow');
86
+ this.calls++;
87
+ this.bytes += bytes;
88
+ let released = false;
89
+ let retained = false;
90
+ return {
91
+ charge: (amount): void => {
92
+ positive(amount);
93
+ if (released) throw new HostModelServiceError('incompatible');
94
+ if (amount > this.maxRequestBytes - this.bytes)
95
+ throw new HostModelServiceError('overflow');
96
+ bytes += amount;
97
+ this.bytes += amount;
98
+ if (retained) this.retainedBytes += amount;
99
+ },
100
+ retain: (): void => {
101
+ if (released || retained) return;
102
+ retained = true;
103
+ this.retainedCalls++;
104
+ this.retainedBytes += bytes;
105
+ },
106
+ release: (): void => {
107
+ if (released) return;
108
+ released = true;
109
+ this.calls--;
110
+ this.bytes -= bytes;
111
+ if (!retained) return;
112
+ this.retainedCalls--;
113
+ this.retainedBytes -= bytes;
114
+ },
115
+ };
116
+ }
117
+ }
118
+
119
+ function positive(value: number): void {
120
+ if (!Number.isSafeInteger(value) || value <= 0)
121
+ throw new HostModelServiceError('incompatible');
122
+ }
123
+
124
+ export interface HostModelLimits {
125
+ readonly timeoutMs: number;
126
+ readonly maxRequestBytes: number;
127
+ /** Cumulative serialized native-message bytes, including metadata and tool chunks. */
128
+ readonly maxResponseBytes: number;
129
+ }
130
+
131
+ const requestSchema = z.object({
132
+ version: z.literal(1),
133
+ identity: executionIdentitySchema,
134
+ reference: z.string(),
135
+ messages: z.array(z.custom<BaseMessage>(isBaseMessage)),
136
+ toolNames: z.array(z.string()),
137
+ toolChoice: z
138
+ .union([
139
+ z.object({ mode: z.enum(['auto', 'none', 'required']) }),
140
+ z.object({ mode: z.literal('tool'), name: z.string() }),
141
+ ])
142
+ .optional(),
143
+ });
144
+
145
+ function messageBytes(
146
+ messages: readonly BaseMessage[],
147
+ maxBytes: number
148
+ ): number {
149
+ let bytes = 2;
150
+ try {
151
+ for (const message of messages) {
152
+ bytes += serializeNativeValue(toStoredMessage(message)).byteLength + 1;
153
+ if (bytes > maxBytes) throw new HostModelServiceError('overflow');
154
+ }
155
+ return bytes;
156
+ } catch (error) {
157
+ if (error instanceof HostModelServiceError) throw error;
158
+ throw new HostModelServiceError('incompatible');
159
+ }
160
+ }
161
+
162
+ /** Tracks actual settlement separately from a caller's cancelled/timed-out wait. */
163
+ class ModelAttempt {
164
+ readonly signal: AbortSignal;
165
+ private readonly controller = new AbortController();
166
+ private readonly timer: ReturnType<typeof setTimeout>;
167
+ private pending = 0;
168
+ private finished = false;
169
+ private stopCleanup = (): void => {};
170
+ private readonly onAbort = (): void => {
171
+ this.finish();
172
+ };
173
+
174
+ constructor(
175
+ private readonly lease: ModelLease,
176
+ timeoutMs: number,
177
+ signal?: AbortSignal
178
+ ) {
179
+ this.signal = signal
180
+ ? AbortSignal.any([signal, this.controller.signal])
181
+ : this.controller.signal;
182
+ this.timer = setTimeout(
183
+ () => this.controller.abort(new HostModelServiceError('timeout')),
184
+ timeoutMs
185
+ );
186
+ this.timer.unref();
187
+ this.signal.addEventListener('abort', this.onAbort, { once: true });
188
+ }
189
+
190
+ setCleanup(cleanup: () => void): void {
191
+ this.stopCleanup = cleanup;
192
+ }
193
+
194
+ track<T>(promise: Promise<T>): Promise<T> {
195
+ this.pending++;
196
+ const tracked = promise.finally(() => {
197
+ this.pending--;
198
+ if (this.finished && this.pending === 0) this.lease.release();
199
+ });
200
+ void tracked.catch(() => undefined);
201
+ return tracked;
202
+ }
203
+
204
+ async wait<T>(promise: Promise<T>): Promise<T> {
205
+ this.signal.throwIfAborted();
206
+ return new Promise<T>((resolve, reject) => {
207
+ const abort = (): void => {
208
+ this.signal.removeEventListener('abort', abort);
209
+ reject(this.signal.reason);
210
+ };
211
+ this.signal.addEventListener('abort', abort, { once: true });
212
+ promise.then(
213
+ (value) => {
214
+ this.signal.removeEventListener('abort', abort);
215
+ if (this.signal.aborted) reject(this.signal.reason);
216
+ else resolve(value);
217
+ },
218
+ (error: Error) => {
219
+ this.signal.removeEventListener('abort', abort);
220
+ reject(error);
221
+ }
222
+ );
223
+ if (this.signal.aborted) abort();
224
+ });
225
+ }
226
+
227
+ error(error: unknown): Error {
228
+ if (
229
+ this.signal.reason instanceof HostModelServiceError &&
230
+ this.signal.reason.code === 'timeout'
231
+ )
232
+ return new HostModelServiceError('timeout');
233
+ return normalizeHostModelError(error, this.signal);
234
+ }
235
+
236
+ finish(): void {
237
+ if (this.finished) return;
238
+ this.finished = true;
239
+ clearTimeout(this.timer);
240
+ this.signal.removeEventListener('abort', this.onAbort);
241
+ this.controller.abort();
242
+ this.stopCleanup();
243
+ if (this.pending > 0) this.lease.retain();
244
+ else this.lease.release();
245
+ }
246
+ }
247
+
248
+ /** Binds native model execution to one authenticated execution; transport authentication remains external. */
249
+ export function createHostModelService(options: {
250
+ identity: Readonly<ExecutionIdentity>;
251
+ descriptor: HostModelDescriptor;
252
+ model: BaseChatModel;
253
+ admission: HostModelAdmission;
254
+ limits: HostModelLimits;
255
+ /** Trusted host configuration only. Worker config is never merged into it. */
256
+ config?: RunnableConfig;
257
+ }): { descriptor: HostModelDescriptor; service: HostModelService } {
258
+ const identity = snapshotExecutionIdentity(options.identity);
259
+ const parsed = hostModelDescriptorSchema.safeParse(options.descriptor);
260
+ if (!parsed.success) throw new HostModelServiceError('incompatible');
261
+ const descriptor = structuredClone(parsed.data);
262
+ const limits = Object.freeze({ ...options.limits });
263
+ positive(limits.timeoutMs);
264
+ positive(limits.maxRequestBytes);
265
+ positive(limits.maxResponseBytes);
266
+ if (limits.timeoutMs > 2147483647)
267
+ throw new HostModelServiceError('incompatible');
268
+ const tools = new Map(
269
+ descriptor.tools.map((tool) => [tool.function.name, tool])
270
+ );
271
+ if (tools.size !== descriptor.tools.length)
272
+ throw new HostModelServiceError('incompatible');
273
+ const config = { ...options.config };
274
+ const hostStorage = AsyncLocalStorageProviderSingleton.getInstance();
275
+ const hostStore: unknown = hostStorage.run(undefined, () =>
276
+ AsyncLocalStorageProviderSingleton.runWithConfig(
277
+ config,
278
+ () => hostStorage.getStore(),
279
+ true
280
+ )
281
+ );
282
+ function runOnHost<T>(operation: () => T): T {
283
+ return hostStorage.run(hostStore, operation);
284
+ }
285
+ const model = options.model;
286
+ const admission = options.admission;
287
+
288
+ function prepare(
289
+ request: HostModelRequest,
290
+ signal?: AbortSignal
291
+ ): { request: HostModelRequest; attempt: ModelAttempt } {
292
+ const checked = requestSchema.safeParse(request);
293
+ if (!checked.success) throw new HostModelServiceError('incompatible');
294
+ const value = checked.data;
295
+ if (
296
+ !matchesExecutionIdentity(identity, value.identity) ||
297
+ value.reference !== descriptor.reference
298
+ )
299
+ throw new HostModelServiceError('forbidden');
300
+ const names = new Set(value.toolNames);
301
+ const choice = value.toolChoice;
302
+ if (
303
+ names.size !== value.toolNames.length ||
304
+ value.toolNames.some((name) => !tools.has(name)) ||
305
+ (choice?.mode === 'tool' && !names.has(choice.name)) ||
306
+ (choice?.mode === 'required' && names.size === 0)
307
+ )
308
+ throw new HostModelServiceError('forbidden');
309
+ let boundSignal = signal;
310
+ if (config.signal)
311
+ boundSignal = signal
312
+ ? AbortSignal.any([config.signal, signal])
313
+ : config.signal;
314
+ if (boundSignal?.aborted === true)
315
+ throw new HostModelServiceError('cancelled');
316
+ const lease = admission.acquire(2);
317
+ try {
318
+ const stored: StoredMessage[] = [];
319
+ let bytes = 2;
320
+ if (bytes > limits.maxRequestBytes)
321
+ throw new HostModelServiceError('overflow');
322
+ for (const message of value.messages) {
323
+ const serialized = serializeNativeValue(toStoredMessage(message));
324
+ const added = serialized.byteLength + 1;
325
+ bytes += added;
326
+ if (bytes > limits.maxRequestBytes)
327
+ throw new HostModelServiceError('overflow');
328
+ lease.charge(added);
329
+ stored.push(deserializeNativeValue(serialized) as StoredMessage);
330
+ }
331
+ value.messages = mapStoredMessagesToChatMessages(stored);
332
+ return {
333
+ request: value,
334
+ attempt: new ModelAttempt(lease, limits.timeoutMs, boundSignal),
335
+ };
336
+ } catch (error) {
337
+ lease.release();
338
+ if (error instanceof HostModelServiceError) throw error;
339
+ throw new HostModelServiceError('incompatible');
340
+ }
341
+ }
342
+
343
+ function selected(
344
+ request: HostModelRequest
345
+ ): ReturnType<BaseChatModel['withConfig']> {
346
+ if (descriptor.tools.length === 0) return model.withConfig(config);
347
+ if (!model.bindTools) throw new HostModelServiceError('incompatible');
348
+ const choice = request.toolChoice;
349
+ const family = getProviderFamily(descriptor.provider);
350
+ const definitions = request.toolNames.map((name) =>
351
+ structuredClone(tools.get(name)!)
352
+ );
353
+ if (choice?.mode === 'none' && family === 'bedrock')
354
+ return model.bindTools([]).withConfig(config);
355
+ if (choice?.mode !== 'tool')
356
+ return model
357
+ .bindTools(definitions, {
358
+ ...(choice
359
+ ? { tool_choice: choice.mode === 'required' ? 'any' : choice.mode }
360
+ : {}),
361
+ })
362
+ .withConfig(config);
363
+ if (family === 'openai' || family === 'mistral')
364
+ return model
365
+ .bindTools(definitions, {
366
+ tool_choice: { type: 'function', function: { name: choice.name } },
367
+ })
368
+ .withConfig(config);
369
+ if (family === 'anthropic')
370
+ return model
371
+ .bindTools(definitions, {
372
+ tool_choice: { type: 'tool', name: choice.name },
373
+ })
374
+ .withConfig(config);
375
+ if (family === 'bedrock')
376
+ return model
377
+ .bindTools(definitions, {
378
+ tool_choice: { tool: { name: choice.name } },
379
+ })
380
+ .withConfig(config);
381
+ if (family === 'google') {
382
+ const googleChoice = {
383
+ tool_choice: 'any',
384
+ allowedFunctionNames: [choice.name],
385
+ allowed_function_names: [choice.name],
386
+ };
387
+ return model.bindTools(definitions, googleChoice).withConfig(config);
388
+ }
389
+ // Unregistered custom models may accept names, but reserved words are ambiguous.
390
+ if (['auto', 'none', 'any', 'required'].includes(choice.name))
391
+ throw new HostModelServiceError('incompatible');
392
+ return model
393
+ .bindTools(definitions, { tool_choice: choice.name })
394
+ .withConfig(config);
395
+ }
396
+
397
+ return {
398
+ descriptor: structuredClone(descriptor),
399
+ service: {
400
+ version: 1,
401
+ invoke: async (request, signal): Promise<AIMessage> => {
402
+ const prepared = prepare(request, signal);
403
+ const { attempt } = prepared;
404
+ try {
405
+ const operation = attempt.track(
406
+ Promise.resolve().then(() => {
407
+ attempt.signal.throwIfAborted();
408
+ return runOnHost(() =>
409
+ selected(prepared.request).invoke(
410
+ [...prepared.request.messages],
411
+ { signal: attempt.signal }
412
+ )
413
+ );
414
+ })
415
+ );
416
+ const message = await attempt.wait(operation);
417
+ if (!isAIMessage(message))
418
+ throw new HostModelServiceError('incompatible');
419
+ messageBytes([message], limits.maxResponseBytes);
420
+ return message;
421
+ } catch (error) {
422
+ throw attempt.error(error);
423
+ } finally {
424
+ attempt.finish();
425
+ }
426
+ },
427
+ stream: async function* (
428
+ request,
429
+ signal
430
+ ): AsyncGenerator<AIMessageChunk> {
431
+ if (!descriptor.streaming)
432
+ throw new HostModelServiceError('incompatible');
433
+ const prepared = prepare(request, signal);
434
+ const { attempt } = prepared;
435
+ let iterator: AsyncIterator<AIMessageChunk> | undefined;
436
+ let callbacks: ReturnType<typeof modelStreamCallbacks> | undefined;
437
+ let termination: HostModelErrorCode = 'cancelled';
438
+ let closing = false;
439
+ const close = (): void => {
440
+ if (!iterator || closing) return;
441
+ closing = true;
442
+ const active = iterator;
443
+ void attempt
444
+ .track(
445
+ Promise.resolve().then(() =>
446
+ runOnHost(async () => {
447
+ try {
448
+ await active.return?.();
449
+ } finally {
450
+ const reason = attempt.signal.reason;
451
+ await callbacks?.finish(
452
+ reason instanceof HostModelServiceError
453
+ ? reason.code
454
+ : termination
455
+ );
456
+ }
457
+ })
458
+ )
459
+ )
460
+ .catch(() => undefined);
461
+ };
462
+ attempt.setCleanup(close);
463
+ let responseBytes = 0;
464
+ try {
465
+ await attempt.wait(
466
+ attempt.track(
467
+ Promise.resolve().then(async () => {
468
+ attempt.signal.throwIfAborted();
469
+ // Use the native iterator/callback path: ReadableStream cancellation can
470
+ // settle before the provider generator's asynchronous cleanup drains.
471
+ const boundModel = runOnHost(() => selected(prepared.request));
472
+ callbacks = modelStreamCallbacks(boundModel, {
473
+ signal: attempt.signal,
474
+ });
475
+ const stream = runOnHost(() =>
476
+ boundModel._streamIterator(
477
+ [...prepared.request.messages],
478
+ callbacks!.config
479
+ )
480
+ );
481
+ iterator = stream[Symbol.asyncIterator]();
482
+ if (attempt.signal.aborted) close();
483
+ attempt.signal.throwIfAborted();
484
+ })
485
+ )
486
+ );
487
+ for (;;) {
488
+ const next = await attempt.wait(
489
+ attempt.track(
490
+ Promise.resolve().then(() => {
491
+ attempt.signal.throwIfAborted();
492
+ return runOnHost(() => iterator!.next());
493
+ })
494
+ )
495
+ );
496
+ if (next.done === true) {
497
+ closing = true;
498
+ return;
499
+ }
500
+ if (!isAIMessageChunk(next.value))
501
+ throw new HostModelServiceError('incompatible');
502
+ callbacks?.observeUsage(next.value.usage_metadata);
503
+ responseBytes += messageBytes(
504
+ [next.value],
505
+ limits.maxResponseBytes
506
+ );
507
+ if (responseBytes > limits.maxResponseBytes)
508
+ throw new HostModelServiceError('overflow');
509
+ callbacks?.observe(next.value);
510
+ yield next.value;
511
+ }
512
+ } catch (error) {
513
+ const normalized = attempt.error(error);
514
+ termination =
515
+ normalized instanceof HostModelServiceError
516
+ ? normalized.code
517
+ : 'cancelled';
518
+ throw normalized;
519
+ } finally {
520
+ attempt.finish();
521
+ }
522
+ },
523
+ },
524
+ };
525
+ }
@@ -0,0 +1,137 @@
1
+ import { AIMessageChunk, mergeUsageMetadata } from '@langchain/core/messages';
2
+ import type { UsageMetadata } from '@langchain/core/messages';
3
+ import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
4
+ import type { RunnableConfig } from '@langchain/core/runnables';
5
+ import type { ChatGeneration } from '@langchain/core/outputs';
6
+ import type { ModelCallbackRunContext } from '@/llm/modelCallbackRun';
7
+ import type { HostModelErrorCode } from './model';
8
+ import { getModelCallbackRunManager } from '@/llm/modelCallbackRun';
9
+ import { HostModelServiceError } from './model';
10
+ import { appendCallbacks } from '@/utils/callbacks';
11
+
12
+ /** Observes native completion; only synthesizes an end when iterator return bypasses it. */
13
+ export function modelStreamCallbacks(
14
+ model: object,
15
+ config: RunnableConfig
16
+ ): {
17
+ config: RunnableConfig;
18
+ observe(chunk: AIMessageChunk): void;
19
+ observeUsage(usage: UsageMetadata | undefined): void;
20
+ finish(reason: HostModelErrorCode): Promise<void>;
21
+ } {
22
+ let runId: string | undefined;
23
+ let observed: ModelCallbackRunContext | undefined;
24
+ let terminal = false;
25
+ const isTerminal = (): boolean => terminal;
26
+ let finishing: Promise<void> | undefined;
27
+ let usage: UsageMetadata | undefined;
28
+ const chunks: AIMessageChunk[] = [];
29
+ const capture = BaseCallbackHandler.fromMethods({
30
+ handleChatModelStart: (
31
+ _model,
32
+ _messages,
33
+ id,
34
+ parentRunId,
35
+ _extra,
36
+ tags,
37
+ metadata
38
+ ): void => {
39
+ if (runId !== undefined) return;
40
+ runId = id;
41
+ observed = {
42
+ parentRunId,
43
+ tags: tags?.slice(),
44
+ metadata: { ...metadata },
45
+ };
46
+ },
47
+ handleLLMEnd: (_output, id): void => {
48
+ if (id === runId) {
49
+ terminal = true;
50
+ chunks.length = 0;
51
+ usage = undefined;
52
+ }
53
+ },
54
+ handleLLMError: (_error, id): void => {
55
+ if (id === runId) {
56
+ terminal = true;
57
+ chunks.length = 0;
58
+ usage = undefined;
59
+ }
60
+ },
61
+ });
62
+ capture.name = 'host-model-stream-lifecycle';
63
+ capture.awaitHandlers = true;
64
+ const callConfig = {
65
+ ...config,
66
+ callbacks: appendCallbacks(config.callbacks, [capture]),
67
+ };
68
+ return {
69
+ config: callConfig,
70
+ observeUsage: (reported): void => {
71
+ if (!terminal && reported !== undefined) {
72
+ usage = mergeUsageMetadata(usage, reported);
73
+ }
74
+ },
75
+ observe: (chunk): void => {
76
+ if (!terminal) chunks.push(chunk);
77
+ },
78
+ finish: (reason): Promise<void> => {
79
+ finishing ??= (async (): Promise<void> => {
80
+ if (terminal || runId === undefined) return;
81
+ const manager = await getModelCallbackRunManager(
82
+ runId,
83
+ callConfig,
84
+ model,
85
+ observed
86
+ );
87
+ if (isTerminal() || manager == null) return;
88
+ let aggregate: AIMessageChunk;
89
+ try {
90
+ aggregate = chunks.reduce(
91
+ (current, chunk) => current.concat(chunk),
92
+ new AIMessageChunk('')
93
+ );
94
+ } catch {
95
+ await manager.handleLLMError(
96
+ new HostModelServiceError('incompatible')
97
+ );
98
+ return;
99
+ } finally {
100
+ chunks.length = 0;
101
+ }
102
+ aggregate.usage_metadata = usage;
103
+ aggregate.lc_kwargs.usage_metadata = usage;
104
+ const incomplete = usage === undefined;
105
+ aggregate.response_metadata = {
106
+ ...aggregate.response_metadata,
107
+ host_model_terminated: reason,
108
+ ...(incomplete ? { usage_incomplete: true } : {}),
109
+ };
110
+ aggregate.lc_kwargs.response_metadata = aggregate.response_metadata;
111
+ // No invented token counts: native usage is preserved when the provider supplied it.
112
+ const generation: ChatGeneration = {
113
+ text: aggregate.text,
114
+ message: aggregate,
115
+ };
116
+ await manager.handleLLMEnd({
117
+ generations: [[generation]],
118
+ llmOutput: {
119
+ controlFlow: 'HostModelTerminated',
120
+ reason,
121
+ usage_incomplete: incomplete,
122
+ ...(usage
123
+ ? {
124
+ tokenUsage: {
125
+ promptTokens: usage.input_tokens,
126
+ completionTokens: usage.output_tokens,
127
+ totalTokens: usage.total_tokens,
128
+ },
129
+ }
130
+ : {}),
131
+ },
132
+ });
133
+ })();
134
+ return finishing;
135
+ },
136
+ };
137
+ }
@@ -1,10 +1,12 @@
1
1
  import { z } from 'zod';
2
+ import type { ProviderTextAdmission } from '@/protection/providerTextAdmission';
2
3
  import type { ProviderTextProtection } from '@/protection/providerText';
3
4
  import type { ExecutionIdentity } from './identity';
4
5
  import {
5
6
  ProviderTextAttempt,
6
7
  ProviderTextProtectionError,
7
8
  validateProviderTextProtection,
9
+ validateProviderTextTimeout,
8
10
  } from '@/protection/providerText';
9
11
  import {
10
12
  executionIdentitySchema,
@@ -53,6 +55,10 @@ function boundIdentity(
53
55
  export function createHostProviderTextService(options: {
54
56
  identity: Readonly<ExecutionIdentity>;
55
57
  policy: ProviderTextProtection;
58
+ /** Reuse a host-owned scope for all bindings sharing a tenant or runtime quota. */
59
+ admission?: ProviderTextAdmission;
60
+ /** Host inspection deadline; cannot extend the policy's model-attempt timeout. */
61
+ inspectionTimeoutMs?: number;
56
62
  }): {
57
63
  descriptor: HostProviderTextDescriptor;
58
64
  service: HostProviderTextService;
@@ -60,6 +66,9 @@ export function createHostProviderTextService(options: {
60
66
  const identity = boundIdentity(options.identity);
61
67
  const policy = options.policy;
62
68
  validateProviderTextProtection(policy);
69
+ const { admission, inspectionTimeoutMs } = options;
70
+ if (inspectionTimeoutMs !== undefined)
71
+ validateProviderTextTimeout(inspectionTimeoutMs);
63
72
  return {
64
73
  descriptor: Object.freeze({
65
74
  version: 1,
@@ -76,7 +85,10 @@ export function createHostProviderTextService(options: {
76
85
  !matchesExecutionIdentity(parsed.data.identity, identity)
77
86
  )
78
87
  throw new ProviderTextProtectionError('incompatible');
79
- const attempt = new ProviderTextAttempt(policy, signal);
88
+ const attempt = new ProviderTextAttempt(policy, signal, {
89
+ admission,
90
+ timeoutMs: inspectionTimeoutMs,
91
+ });
80
92
  try {
81
93
  attempt.append(parsed.data.content);
82
94
  return await attempt.release();