@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.
- package/README.md +1 -0
- package/dist/cjs/harness/index.cjs +2 -0
- package/dist/cjs/harness/index.cjs.map +1 -1
- package/dist/cjs/harness/model.cjs +244 -0
- package/dist/cjs/harness/model.cjs.map +1 -0
- package/dist/cjs/harness/modelService.cjs +335 -0
- package/dist/cjs/harness/modelService.cjs.map +1 -0
- package/dist/cjs/harness/modelStreamCallbacks.cjs +102 -0
- package/dist/cjs/harness/modelStreamCallbacks.cjs.map +1 -0
- package/dist/cjs/harness/providerText.cjs +6 -1
- package/dist/cjs/harness/providerText.cjs.map +1 -1
- package/dist/cjs/llm/google/completion.cjs +49 -0
- package/dist/cjs/llm/google/completion.cjs.map +1 -0
- package/dist/cjs/llm/google/index.cjs +45 -20
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/google/transport.cjs +133 -0
- package/dist/cjs/llm/google/transport.cjs.map +1 -0
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +3 -18
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/modelCallbackRun.cjs +26 -0
- package/dist/cjs/llm/modelCallbackRun.cjs.map +1 -0
- package/dist/cjs/llm/stream/chunkAdapters.cjs +3 -2
- package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
- package/dist/cjs/main.cjs +12 -0
- package/dist/cjs/messages/index.cjs +1 -0
- package/dist/cjs/messages/stored.cjs +34 -0
- package/dist/cjs/messages/stored.cjs.map +1 -0
- package/dist/cjs/protection/providerText.cjs +68 -14
- package/dist/cjs/protection/providerText.cjs.map +1 -1
- package/dist/cjs/protection/providerTextAdmission.cjs +56 -0
- package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -0
- package/dist/esm/harness/index.mjs +2 -0
- package/dist/esm/harness/index.mjs.map +1 -1
- package/dist/esm/harness/model.mjs +241 -0
- package/dist/esm/harness/model.mjs.map +1 -0
- package/dist/esm/harness/modelService.mjs +334 -0
- package/dist/esm/harness/modelService.mjs.map +1 -0
- package/dist/esm/harness/modelStreamCallbacks.mjs +102 -0
- package/dist/esm/harness/modelStreamCallbacks.mjs.map +1 -0
- package/dist/esm/harness/providerText.mjs +7 -2
- package/dist/esm/harness/providerText.mjs.map +1 -1
- package/dist/esm/llm/google/completion.mjs +48 -0
- package/dist/esm/llm/google/completion.mjs.map +1 -0
- package/dist/esm/llm/google/index.mjs +46 -21
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/google/transport.mjs +133 -0
- package/dist/esm/llm/google/transport.mjs.map +1 -0
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +3 -18
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/modelCallbackRun.mjs +26 -0
- package/dist/esm/llm/modelCallbackRun.mjs.map +1 -0
- package/dist/esm/llm/stream/chunkAdapters.mjs +3 -2
- package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
- package/dist/esm/main.mjs +6 -2
- package/dist/esm/messages/index.mjs +1 -0
- package/dist/esm/messages/stored.mjs +34 -0
- package/dist/esm/messages/stored.mjs.map +1 -0
- package/dist/esm/protection/providerText.mjs +66 -15
- package/dist/esm/protection/providerText.mjs.map +1 -1
- package/dist/esm/protection/providerTextAdmission.mjs +56 -0
- package/dist/esm/protection/providerTextAdmission.mjs.map +1 -0
- package/dist/types/harness/index.d.ts +4 -0
- package/dist/types/harness/model.d.ts +104 -0
- package/dist/types/harness/modelService.d.ts +50 -0
- package/dist/types/harness/modelStreamCallbacks.d.ts +11 -0
- package/dist/types/harness/providerText.d.ts +5 -0
- package/dist/types/index.d.ts +4 -2
- package/dist/types/llm/google/completion.d.ts +4 -0
- package/dist/types/llm/google/index.d.ts +3 -1
- package/dist/types/llm/google/transport.d.ts +15 -0
- package/dist/types/llm/google/utils/common.d.ts +5 -3
- package/dist/types/llm/modelCallbackRun.d.ts +9 -0
- package/dist/types/llm/stream/chunkAdapters.d.ts +2 -1
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/stored.d.ts +7 -0
- package/dist/types/protection/providerText.d.ts +15 -1
- package/dist/types/protection/providerTextAdmission.d.ts +29 -0
- package/package.json +2 -1
- package/src/harness/index.ts +12 -0
- package/src/harness/model.ts +392 -0
- package/src/harness/modelService.ts +525 -0
- package/src/harness/modelStreamCallbacks.ts +137 -0
- package/src/harness/providerText.ts +13 -1
- package/src/index.ts +9 -0
- package/src/llm/google/completion.ts +91 -0
- package/src/llm/google/index.ts +95 -34
- package/src/llm/google/transport.ts +202 -0
- package/src/llm/google/utils/common.ts +6 -2
- package/src/llm/invoke.ts +3 -72
- package/src/llm/modelCallbackRun.ts +77 -0
- package/src/llm/stream/chunkAdapters.ts +3 -1
- package/src/messages/index.ts +1 -0
- package/src/messages/stored.ts +48 -0
- package/src/protection/providerText.ts +93 -14
- package/src/protection/providerTextAdmission.ts +86 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { getCallbackManagerForConfig } from '@langchain/core/runnables';
|
|
2
|
+
import {
|
|
3
|
+
CallbackManager,
|
|
4
|
+
CallbackManagerForLLMRun,
|
|
5
|
+
} from '@langchain/core/callbacks/manager';
|
|
6
|
+
import type { Callbacks } from '@langchain/core/callbacks/manager';
|
|
7
|
+
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Every callbacks source the real model run would compose beyond the per-call
|
|
11
|
+
* config. `model` here is whatever `createCallModel` produced — with tools
|
|
12
|
+
* that is `bindTools(...)`'s `RunnableBinding`, and a system runnable pipes a
|
|
13
|
+
* `RunnableSequence` on top — while `clientOptions.callbacks` lives on the
|
|
14
|
+
* chat model at the BOTTOM of that stack. Walks `bound` (bindings) and
|
|
15
|
+
* `last`/`steps` (sequences), collecting each wrapper's own `callbacks` and
|
|
16
|
+
* any binding-config callbacks along the way, since the binding merges its
|
|
17
|
+
* config into the call before the chat model composes.
|
|
18
|
+
*/
|
|
19
|
+
function collectModelCallbackSources(model: unknown): Callbacks[] {
|
|
20
|
+
const sources: Callbacks[] = [];
|
|
21
|
+
const seen = new Set<unknown>();
|
|
22
|
+
let current: unknown = model;
|
|
23
|
+
while (current != null && typeof current === 'object' && !seen.has(current)) {
|
|
24
|
+
seen.add(current);
|
|
25
|
+
const wrapper = current as {
|
|
26
|
+
callbacks?: Callbacks;
|
|
27
|
+
config?: { callbacks?: Callbacks };
|
|
28
|
+
bound?: unknown;
|
|
29
|
+
last?: unknown;
|
|
30
|
+
steps?: unknown[];
|
|
31
|
+
};
|
|
32
|
+
if (wrapper.callbacks != null) {
|
|
33
|
+
sources.push(wrapper.callbacks);
|
|
34
|
+
}
|
|
35
|
+
if (wrapper.config?.callbacks != null) {
|
|
36
|
+
sources.push(wrapper.config.callbacks);
|
|
37
|
+
}
|
|
38
|
+
current =
|
|
39
|
+
wrapper.bound ??
|
|
40
|
+
wrapper.last ??
|
|
41
|
+
(Array.isArray(wrapper.steps)
|
|
42
|
+
? wrapper.steps[wrapper.steps.length - 1]
|
|
43
|
+
: undefined);
|
|
44
|
+
}
|
|
45
|
+
return sources;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface ModelCallbackRunContext {
|
|
49
|
+
parentRunId?: string;
|
|
50
|
+
tags?: string[];
|
|
51
|
+
metadata?: RunnableConfig['metadata'];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Reconstructs the actual native run for early closes, including model-level callback sources. */
|
|
55
|
+
export async function getModelCallbackRunManager(
|
|
56
|
+
runId: string,
|
|
57
|
+
config?: RunnableConfig,
|
|
58
|
+
model?: unknown,
|
|
59
|
+
observed?: ModelCallbackRunContext
|
|
60
|
+
): Promise<CallbackManagerForLLMRun | undefined> {
|
|
61
|
+
let manager = await getCallbackManagerForConfig(config);
|
|
62
|
+
for (const source of collectModelCallbackSources(model)) {
|
|
63
|
+
manager =
|
|
64
|
+
CallbackManager.configure(manager ?? undefined, source) ?? manager;
|
|
65
|
+
}
|
|
66
|
+
if (manager == null) return undefined;
|
|
67
|
+
return new CallbackManagerForLLMRun(
|
|
68
|
+
runId,
|
|
69
|
+
manager.handlers,
|
|
70
|
+
manager.inheritableHandlers,
|
|
71
|
+
observed?.tags ?? manager.tags,
|
|
72
|
+
manager.inheritableTags,
|
|
73
|
+
observed?.metadata ?? manager.metadata,
|
|
74
|
+
manager.inheritableMetadata,
|
|
75
|
+
observed ? observed.parentRunId : manager.getParentRunId()
|
|
76
|
+
);
|
|
77
|
+
}
|
|
@@ -285,11 +285,13 @@ export async function* smoothGenerationChunks({
|
|
|
285
285
|
delayMs,
|
|
286
286
|
signal,
|
|
287
287
|
runManager,
|
|
288
|
+
abortUpstream,
|
|
288
289
|
}: {
|
|
289
290
|
chunks: AsyncGenerator<ChatGenerationChunk>;
|
|
290
291
|
delayMs: number;
|
|
291
292
|
signal?: AbortSignal;
|
|
292
293
|
runManager?: CallbackManagerForLLMRun;
|
|
294
|
+
abortUpstream?: () => void;
|
|
293
295
|
}): AsyncGenerator<ChatGenerationChunk> {
|
|
294
296
|
const source = (async function* (): AsyncGenerator<
|
|
295
297
|
SmoothItem<ChatGenerationChunk>
|
|
@@ -299,7 +301,7 @@ export async function* smoothGenerationChunks({
|
|
|
299
301
|
}
|
|
300
302
|
})();
|
|
301
303
|
|
|
302
|
-
for await (const outputChunk of smoothStream({ source, delayMs, signal })) {
|
|
304
|
+
for await (const outputChunk of smoothStream({ source, delayMs, signal, abortUpstream })) {
|
|
303
305
|
yield outputChunk;
|
|
304
306
|
await runManager?.handleLLMNewToken(
|
|
305
307
|
outputChunk.text || '',
|
package/src/messages/index.ts
CHANGED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isAIMessage,
|
|
3
|
+
isAIMessageChunk,
|
|
4
|
+
isToolMessage,
|
|
5
|
+
isChatMessage,
|
|
6
|
+
isBaseMessageChunk,
|
|
7
|
+
} from '@langchain/core/messages';
|
|
8
|
+
import type { BaseMessage, StoredMessage } from '@langchain/core/messages';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Native stored-message data without LangChain's JSON-oriented object escaping.
|
|
12
|
+
* Values retain their native types and references: callers must snapshot/encode
|
|
13
|
+
* with their own bounded codec before retaining or transmitting the result.
|
|
14
|
+
*/
|
|
15
|
+
export function toStoredMessage(message: BaseMessage): StoredMessage {
|
|
16
|
+
if (Object.keys(message.lc_secrets ?? {}).length > 0) {
|
|
17
|
+
throw new Error('SDK native message secrets require an explicit codec');
|
|
18
|
+
}
|
|
19
|
+
const data = {
|
|
20
|
+
...message.lc_kwargs,
|
|
21
|
+
content: message.content,
|
|
22
|
+
additional_kwargs: message.additional_kwargs,
|
|
23
|
+
response_metadata: message.response_metadata,
|
|
24
|
+
id: message.id,
|
|
25
|
+
name: message.name,
|
|
26
|
+
role: isChatMessage(message) ? message.role : undefined,
|
|
27
|
+
tool_call_id: undefined,
|
|
28
|
+
...(isAIMessage(message)
|
|
29
|
+
? {
|
|
30
|
+
tool_calls: message.tool_calls,
|
|
31
|
+
invalid_tool_calls: message.invalid_tool_calls,
|
|
32
|
+
usage_metadata: message.usage_metadata,
|
|
33
|
+
}
|
|
34
|
+
: {}),
|
|
35
|
+
...(isBaseMessageChunk(message) && isAIMessageChunk(message)
|
|
36
|
+
? { tool_call_chunks: message.tool_call_chunks }
|
|
37
|
+
: {}),
|
|
38
|
+
...(isToolMessage(message)
|
|
39
|
+
? {
|
|
40
|
+
tool_call_id: message.tool_call_id,
|
|
41
|
+
artifact: message.artifact,
|
|
42
|
+
status: message.status,
|
|
43
|
+
}
|
|
44
|
+
: {}),
|
|
45
|
+
};
|
|
46
|
+
// LangChain's StoredMessageData types content as string, but its codec supports native blocks.
|
|
47
|
+
return { type: message.getType(), data } as StoredMessage;
|
|
48
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { performance } from 'node:perf_hooks';
|
|
2
|
+
import type { ProviderTextAdmission, ProviderTextAdmissionLease } from './providerTextAdmission';
|
|
2
3
|
import { PreparedSubagentError } from '@/tools/preparedSubagents';
|
|
3
4
|
import { StreamLimitExceededError } from '@/llm/streamLimits';
|
|
4
5
|
|
|
@@ -101,6 +102,46 @@ const errorCodes = new Set<ProviderTextProtectionErrorCode>([
|
|
|
101
102
|
'incompatible',
|
|
102
103
|
]);
|
|
103
104
|
|
|
105
|
+
export type ProviderTextProtectionFailure = Extract<ProviderTextProtectionResult, { ok: false }>;
|
|
106
|
+
|
|
107
|
+
function isProtectionErrorCode(code: unknown): code is ProviderTextProtectionErrorCode {
|
|
108
|
+
return typeof code === 'string' && (errorCodes as ReadonlySet<string>).has(code);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Safe wire failure, including errors raised by a separate CJS/ESM copy of the SDK. */
|
|
112
|
+
export function serializeProviderTextProtectionError(error: unknown): ProviderTextProtectionFailure {
|
|
113
|
+
let code: ProviderTextProtectionErrorCode = 'unavailable';
|
|
114
|
+
try {
|
|
115
|
+
if (error != null && typeof error === 'object' &&
|
|
116
|
+
'name' in error && error.name === 'ProviderTextProtectionError' &&
|
|
117
|
+
'code' in error && isProtectionErrorCode(error.code)) code = error.code;
|
|
118
|
+
} catch {
|
|
119
|
+
// Never serialize arbitrary exception messages, stacks, causes, or getters.
|
|
120
|
+
}
|
|
121
|
+
return { version: 1, ok: false, error: { code } };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Decode only an authenticated host's failure envelope; unknown versions/codes fail closed. */
|
|
125
|
+
export function deserializeProviderTextProtectionError(failure: unknown): ProviderTextProtectionError {
|
|
126
|
+
try {
|
|
127
|
+
if (failure != null && typeof failure === 'object' &&
|
|
128
|
+
'version' in failure && failure.version === 1 &&
|
|
129
|
+
'ok' in failure && failure.ok === false &&
|
|
130
|
+
'error' in failure && failure.error != null && typeof failure.error === 'object' &&
|
|
131
|
+
'code' in failure.error && isProtectionErrorCode(failure.error.code)) {
|
|
132
|
+
return new ProviderTextProtectionError(failure.error.code);
|
|
133
|
+
}
|
|
134
|
+
} catch {
|
|
135
|
+
// Malformed failures cannot become host policy decisions.
|
|
136
|
+
}
|
|
137
|
+
return new ProviderTextProtectionError('incompatible');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function validateProviderTextTimeout(timeoutMs: number): void {
|
|
141
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647)
|
|
142
|
+
throw new ProviderTextProtectionError('incompatible');
|
|
143
|
+
}
|
|
144
|
+
|
|
104
145
|
export function validateProviderTextProtection(
|
|
105
146
|
policy: ProviderTextProtection
|
|
106
147
|
): void {
|
|
@@ -130,6 +171,11 @@ export function validateProviderTextProtection(
|
|
|
130
171
|
}
|
|
131
172
|
}
|
|
132
173
|
|
|
174
|
+
export interface ProviderTextAttemptOptions {
|
|
175
|
+
readonly timeoutMs?: number;
|
|
176
|
+
readonly admission?: ProviderTextAdmission;
|
|
177
|
+
}
|
|
178
|
+
|
|
133
179
|
/** A lease stays charged while a cancellation-ignoring producer/handler still owns raw text. */
|
|
134
180
|
export class ProviderTextAttempt {
|
|
135
181
|
private readonly controller = new AbortController();
|
|
@@ -142,25 +188,44 @@ export class ProviderTextAttempt {
|
|
|
142
188
|
private readonly timer: ReturnType<typeof setTimeout>;
|
|
143
189
|
private readonly abort: () => void;
|
|
144
190
|
private finished = false;
|
|
191
|
+
private readonly admission?: ProviderTextAdmissionLease;
|
|
145
192
|
|
|
146
193
|
constructor(
|
|
147
194
|
private readonly policy: ProviderTextProtection,
|
|
148
|
-
private readonly parent?: AbortSignal
|
|
195
|
+
private readonly parent?: AbortSignal,
|
|
196
|
+
options: ProviderTextAttemptOptions = {}
|
|
149
197
|
) {
|
|
150
198
|
validateProviderTextProtection(policy);
|
|
151
|
-
|
|
199
|
+
const timeoutMs = options.timeoutMs ?? policy.timeoutMs;
|
|
200
|
+
validateProviderTextTimeout(timeoutMs);
|
|
201
|
+
this.deadline = performance.now() + Math.min(timeoutMs, policy.timeoutMs);
|
|
152
202
|
this.budget = budgets.get(policy) ?? { bytes: 0 };
|
|
153
203
|
budgets.set(policy, this.budget);
|
|
154
|
-
if (parent?.aborted === true) throw protectionAbortError(parent);
|
|
155
|
-
this.charge(512);
|
|
156
|
-
protectedSignals.add(this.signal);
|
|
157
204
|
this.abort = (): void =>
|
|
158
205
|
this.controller.abort(protectionAbortError(this.parent));
|
|
159
|
-
parent?.
|
|
160
|
-
this.
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
206
|
+
if (parent?.aborted === true) throw protectionAbortError(parent);
|
|
207
|
+
this.admission = options.admission?.acquire();
|
|
208
|
+
try {
|
|
209
|
+
this.charge(512);
|
|
210
|
+
parent?.addEventListener('abort', this.abort, { once: true });
|
|
211
|
+
this.check();
|
|
212
|
+
this.timer = setTimeout(() => {
|
|
213
|
+
this.controller.abort(new ProviderTextProtectionError('timeout'));
|
|
214
|
+
}, Math.min(timeoutMs, policy.timeoutMs));
|
|
215
|
+
this.timer.unref();
|
|
216
|
+
protectedSignals.add(this.signal);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
this.budget.bytes -= this.bytes;
|
|
219
|
+
this.bytes = 0;
|
|
220
|
+
this.admission?.release();
|
|
221
|
+
try {
|
|
222
|
+
parent?.removeEventListener('abort', this.abort);
|
|
223
|
+
} catch {
|
|
224
|
+
// Malformed transport signals must not prevent admission rollback.
|
|
225
|
+
}
|
|
226
|
+
if (error instanceof ProviderTextProtectionError || error instanceof StreamLimitExceededError || error instanceof PreparedSubagentError) throw error;
|
|
227
|
+
throw new ProviderTextProtectionError('incompatible');
|
|
228
|
+
}
|
|
164
229
|
}
|
|
165
230
|
|
|
166
231
|
get signal(): AbortSignal {
|
|
@@ -168,6 +233,7 @@ export class ProviderTextAttempt {
|
|
|
168
233
|
}
|
|
169
234
|
|
|
170
235
|
check(): void {
|
|
236
|
+
if (this.finished) throw new ProviderTextProtectionError('incompatible');
|
|
171
237
|
if (this.signal.aborted) throw this.signal.reason;
|
|
172
238
|
if (this.parent?.aborted === true)
|
|
173
239
|
throw protectionAbortError(this.parent);
|
|
@@ -185,6 +251,12 @@ export class ProviderTextAttempt {
|
|
|
185
251
|
this.controller.abort(new ProviderTextProtectionError('overflow'));
|
|
186
252
|
throw this.signal.reason;
|
|
187
253
|
}
|
|
254
|
+
try {
|
|
255
|
+
this.admission?.charge(bytes);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
this.controller.abort(error);
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
188
260
|
this.bytes += bytes;
|
|
189
261
|
this.budget.bytes += bytes;
|
|
190
262
|
}
|
|
@@ -268,8 +340,7 @@ export class ProviderTextAttempt {
|
|
|
268
340
|
} catch (error) {
|
|
269
341
|
this.check();
|
|
270
342
|
if (isProviderTextRestartCancellation(error)) throw error;
|
|
271
|
-
|
|
272
|
-
throw new ProviderTextProtectionError('unavailable');
|
|
343
|
+
throw deserializeProviderTextProtectionError(serializeProviderTextProtectionError(error));
|
|
273
344
|
}
|
|
274
345
|
this.check();
|
|
275
346
|
const canonical = validateResult(result);
|
|
@@ -282,14 +353,22 @@ export class ProviderTextAttempt {
|
|
|
282
353
|
if (this.finished) return;
|
|
283
354
|
this.finished = true;
|
|
284
355
|
clearTimeout(this.timer);
|
|
285
|
-
|
|
356
|
+
try {
|
|
357
|
+
this.parent?.removeEventListener('abort', this.abort);
|
|
358
|
+
} catch {
|
|
359
|
+
// Cleanup must still drain leases if a malformed transport signal throws.
|
|
360
|
+
}
|
|
286
361
|
const dispose = (): void => {
|
|
287
362
|
this.fragments.length = 0;
|
|
288
363
|
this.budget.bytes -= this.bytes;
|
|
289
364
|
this.bytes = 0;
|
|
365
|
+
this.admission?.release();
|
|
290
366
|
};
|
|
291
367
|
if (this.pending.size === 0) dispose();
|
|
292
|
-
else
|
|
368
|
+
else {
|
|
369
|
+
this.admission?.retain();
|
|
370
|
+
void Promise.allSettled([...this.pending]).then(dispose);
|
|
371
|
+
}
|
|
293
372
|
}
|
|
294
373
|
}
|
|
295
374
|
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { ProviderTextProtectionError } from './providerText';
|
|
2
|
+
|
|
3
|
+
export interface ProviderTextAdmissionLimits {
|
|
4
|
+
readonly maxConcurrentInspections: number;
|
|
5
|
+
readonly maxBufferedBytes: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface ProviderTextAdmissionSnapshot {
|
|
9
|
+
readonly inspections: number;
|
|
10
|
+
readonly bufferedBytes: number;
|
|
11
|
+
/** Finished callers whose inspectors have not settled. Included in the totals above. */
|
|
12
|
+
readonly retainedInspections: number;
|
|
13
|
+
readonly retainedBytes: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Internal ownership lease; only the attempt that acquires it may release it. */
|
|
17
|
+
export interface ProviderTextAdmissionLease {
|
|
18
|
+
charge(bytes: number): void;
|
|
19
|
+
retain(): void;
|
|
20
|
+
release(): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Host-owned admission scope. Reuse across bindings/reconnects belonging to the same quota. */
|
|
24
|
+
export class ProviderTextAdmission {
|
|
25
|
+
private readonly limits: ProviderTextAdmissionLimits;
|
|
26
|
+
private inspections = 0;
|
|
27
|
+
private bufferedBytes = 0;
|
|
28
|
+
private retainedInspections = 0;
|
|
29
|
+
private retainedBytes = 0;
|
|
30
|
+
|
|
31
|
+
constructor(limits: ProviderTextAdmissionLimits) {
|
|
32
|
+
for (const value of [
|
|
33
|
+
limits.maxConcurrentInspections,
|
|
34
|
+
limits.maxBufferedBytes,
|
|
35
|
+
]) {
|
|
36
|
+
if (!Number.isSafeInteger(value) || value <= 0)
|
|
37
|
+
throw new ProviderTextProtectionError('incompatible');
|
|
38
|
+
}
|
|
39
|
+
this.limits = Object.freeze({ ...limits });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
snapshot(): Readonly<ProviderTextAdmissionSnapshot> {
|
|
43
|
+
return Object.freeze({
|
|
44
|
+
inspections: this.inspections,
|
|
45
|
+
bufferedBytes: this.bufferedBytes,
|
|
46
|
+
retainedInspections: this.retainedInspections,
|
|
47
|
+
retainedBytes: this.retainedBytes,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** @internal Acquired by ProviderTextAttempt, never by a transport caller. */
|
|
52
|
+
acquire(): ProviderTextAdmissionLease {
|
|
53
|
+
if (this.inspections >= this.limits.maxConcurrentInspections)
|
|
54
|
+
throw new ProviderTextProtectionError('overflow');
|
|
55
|
+
this.inspections++;
|
|
56
|
+
let bytes = 0;
|
|
57
|
+
let retained = false;
|
|
58
|
+
let released = false;
|
|
59
|
+
return {
|
|
60
|
+
charge: (amount): void => {
|
|
61
|
+
if (released || !Number.isSafeInteger(amount) || amount < 0)
|
|
62
|
+
throw new ProviderTextProtectionError('incompatible');
|
|
63
|
+
if (amount > this.limits.maxBufferedBytes - this.bufferedBytes)
|
|
64
|
+
throw new ProviderTextProtectionError('overflow');
|
|
65
|
+
this.bufferedBytes += amount;
|
|
66
|
+
bytes += amount;
|
|
67
|
+
if (retained) this.retainedBytes += amount;
|
|
68
|
+
},
|
|
69
|
+
retain: (): void => {
|
|
70
|
+
if (retained || released) return;
|
|
71
|
+
retained = true;
|
|
72
|
+
this.retainedInspections++;
|
|
73
|
+
this.retainedBytes += bytes;
|
|
74
|
+
},
|
|
75
|
+
release: (): void => {
|
|
76
|
+
if (released) return;
|
|
77
|
+
released = true;
|
|
78
|
+
this.inspections--;
|
|
79
|
+
this.bufferedBytes -= bytes;
|
|
80
|
+
if (!retained) return;
|
|
81
|
+
this.retainedInspections--;
|
|
82
|
+
this.retainedBytes -= bytes;
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
}
|