@kingsoftcloud/agentkit-harness-node 0.0.27 → 0.0.28
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/engine-view.html +1 -1
- package/dist/index.mjs +155 -52
- package/dist/rpc-entry.mjs +155 -52
- package/package.json +2 -2
- package/src/native/e2b-command-tools.mjs +27 -10
- package/src/native/model-anthropic.mjs +10 -1
- package/src/native/model-openai-chat.mjs +14 -4
- package/src/native/model-port.mjs +42 -11
- package/src/native/model-responses.mjs +26 -9
- package/src/native/model-sse.mjs +44 -24
- package/src/native/model-stream-budget.mjs +31 -0
- package/src/native/native-terminal-failure.mjs +5 -0
|
@@ -400,7 +400,7 @@ export function classifyAnthropicStreamError(errorObj) {
|
|
|
400
400
|
// Streaming state for the Anthropic Messages SSE protocol. Accumulates text,
|
|
401
401
|
// thinking (with signatures), an assembled tool batch and usage across
|
|
402
402
|
// content_block_* and message_* events. Frame errors throw ProtocolError.
|
|
403
|
-
export function createAnthropicStreamState(profile) {
|
|
403
|
+
export function createAnthropicStreamState(profile, budget) {
|
|
404
404
|
const captureReplay = profile.providerReplayMode !== 'none';
|
|
405
405
|
const emitThinking = profile.providerThinkingDisplay ?? profile.providerReplayMode !== 'none';
|
|
406
406
|
return {
|
|
@@ -510,6 +510,9 @@ export function createAnthropicStreamState(profile) {
|
|
|
510
510
|
if (this.blockTypes.has(index) || this.closed.has(index)) {
|
|
511
511
|
throw new ProtocolError('duplicate content block index');
|
|
512
512
|
}
|
|
513
|
+
budget?.slot();
|
|
514
|
+
const { input: _input, ...replayMetadata } = block;
|
|
515
|
+
budget?.output(stringifyModelJson(replayMetadata));
|
|
513
516
|
this.blockTypes.set(index, blockType);
|
|
514
517
|
this.originals.set(index, deepCopy(block));
|
|
515
518
|
for (const field of ['text', 'thinking', 'signature']) {
|
|
@@ -540,6 +543,7 @@ export function createAnthropicStreamState(profile) {
|
|
|
540
543
|
// is the usual placeholder and still allows input_json_delta fragments.
|
|
541
544
|
if (Object.keys(block.input).length > 0) {
|
|
542
545
|
tool.arguments = stringifyModelJson(block.input);
|
|
546
|
+
budget?.tool(tool, tool.arguments);
|
|
543
547
|
tool.initialInput = true;
|
|
544
548
|
this.initialInputs.add(index);
|
|
545
549
|
}
|
|
@@ -569,6 +573,7 @@ export function createAnthropicStreamState(profile) {
|
|
|
569
573
|
}
|
|
570
574
|
if (expected != null && previous == null && (expected === 'text' || expected === 'thinking')) {
|
|
571
575
|
// Legacy proxy omitting block_start: pin the slot from the first delta.
|
|
576
|
+
budget?.slot();
|
|
572
577
|
this.blockTypes.set(index, expected);
|
|
573
578
|
this.implicitIndexes.add(index);
|
|
574
579
|
this.originals.set(index, { type: expected });
|
|
@@ -576,19 +581,23 @@ export function createAnthropicStreamState(profile) {
|
|
|
576
581
|
}
|
|
577
582
|
if (deltaType === 'text_delta') {
|
|
578
583
|
if (typeof delta.text !== 'string') throw new ProtocolError('invalid text delta');
|
|
584
|
+
budget?.output(delta.text);
|
|
579
585
|
this.values.set(index, (this.values.get(index) || '') + delta.text);
|
|
580
586
|
} else if (deltaType === 'thinking_delta') {
|
|
581
587
|
if (typeof delta.thinking !== 'string') throw new ProtocolError('invalid thinking delta');
|
|
588
|
+
budget?.output(delta.thinking);
|
|
582
589
|
this.values.set(index, (this.values.get(index) || '') + delta.thinking);
|
|
583
590
|
} else if (deltaType === 'signature_delta') {
|
|
584
591
|
if (typeof delta.signature !== 'string') throw new ProtocolError('invalid signature delta');
|
|
585
592
|
const original = this.originals.get(index) || { type: 'thinking' };
|
|
593
|
+
budget?.output(delta.signature);
|
|
586
594
|
original.signature = (original.signature || '') + delta.signature;
|
|
587
595
|
this.originals.set(index, original);
|
|
588
596
|
} else if (deltaType === 'input_json_delta') {
|
|
589
597
|
if (typeof delta.partial_json !== 'string') throw new ProtocolError('invalid input_json delta');
|
|
590
598
|
const tool = this.tools.get(index);
|
|
591
599
|
if (!tool || this.initialInputs.has(index)) throw new ProtocolError('tool delta without an open block');
|
|
600
|
+
budget?.tool(tool, delta.partial_json);
|
|
592
601
|
tool.arguments += delta.partial_json;
|
|
593
602
|
if (delta.partial_json) {
|
|
594
603
|
emit({ kind: 'tool_delta', text: delta.partial_json, metadata: { index,
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
//
|
|
9
9
|
// Profiled inline reasoning is projected under the Run's frozen policy.
|
|
10
10
|
|
|
11
|
+
import { ModelStreamLimitError } from './model-stream-budget.mjs';
|
|
11
12
|
import {
|
|
12
13
|
normalizeResponse, parseOpenAIUsage, sealUsage, ProtocolError, resolveUrl, boundOutputTokens,
|
|
13
14
|
} from './model-normalize.mjs';
|
|
@@ -349,7 +350,7 @@ function chatReasoning(message) {
|
|
|
349
350
|
// assembled tool batch and reported usage across SSE frames. Mirrors
|
|
350
351
|
// ksadk._StreamTurn. Frame errors throw ProtocolError; finalize preserves the
|
|
351
352
|
// accumulated text/usage and classifies the attempt.
|
|
352
|
-
export function createOpenAIStreamTurn(profile, binding) {
|
|
353
|
+
export function createOpenAIStreamTurn(profile, binding, budget) {
|
|
353
354
|
const compatibility = resolveProviderCompatibility(profile.providerCompatibilityPolicy, binding);
|
|
354
355
|
const modern = compatibility?.modern === true;
|
|
355
356
|
const finishOnEof = compatibility?.finishOnEof === true;
|
|
@@ -436,6 +437,8 @@ export function createOpenAIStreamTurn(profile, binding) {
|
|
|
436
437
|
if (typeof content !== 'string') throw new ProtocolError('invalid visible content delta', 'delta_invalid');
|
|
437
438
|
const reasoning = chatReasoning(delta);
|
|
438
439
|
if (this.finish != null && reasoning) throw new ProtocolError('private reasoning continued after finish', 'termination_conflict');
|
|
440
|
+
budget?.output(content);
|
|
441
|
+
budget?.output(reasoning);
|
|
439
442
|
if (captureReplay) this.reasoning += reasoning;
|
|
440
443
|
if (this.finish != null && (content || delta.tool_calls)) {
|
|
441
444
|
throw new ProtocolError('content continued after finish', 'termination_conflict');
|
|
@@ -456,7 +459,8 @@ export function createOpenAIStreamTurn(profile, binding) {
|
|
|
456
459
|
try {
|
|
457
460
|
if ('function_call' in delta) throw new ProtocolError('legacy function calls are unsupported');
|
|
458
461
|
this.addToolFragments(delta.tool_calls, emit);
|
|
459
|
-
} catch {
|
|
462
|
+
} catch (error) {
|
|
463
|
+
if (error instanceof ModelStreamLimitError) throw error;
|
|
460
464
|
this.malformedTools = true;
|
|
461
465
|
}
|
|
462
466
|
},
|
|
@@ -479,6 +483,7 @@ export function createOpenAIStreamTurn(profile, binding) {
|
|
|
479
483
|
if (typeof value !== 'string' || !value || (call[field] != null && call[field] !== value)) {
|
|
480
484
|
throw new ProtocolError('conflicting tool identity', 'identity_conflict');
|
|
481
485
|
}
|
|
486
|
+
if (call[field] == null) budget?.output(value);
|
|
482
487
|
call[field] = value;
|
|
483
488
|
}
|
|
484
489
|
}
|
|
@@ -489,11 +494,16 @@ export function createOpenAIStreamTurn(profile, binding) {
|
|
|
489
494
|
if (field in fn) {
|
|
490
495
|
if (fn[field] == null) continue;
|
|
491
496
|
if (typeof fn[field] !== 'string') throw new ProtocolError('function fragment must be text');
|
|
492
|
-
|
|
497
|
+
if (field === 'arguments') budget?.tool(call, fn[field]);
|
|
498
|
+
else budget?.output(fn[field]);
|
|
499
|
+
call.function[field] += fn[field];
|
|
493
500
|
}
|
|
494
501
|
}
|
|
495
502
|
}
|
|
496
|
-
if (!this.tools.has(fragment.index))
|
|
503
|
+
if (!this.tools.has(fragment.index)) {
|
|
504
|
+
budget?.slot();
|
|
505
|
+
this.tools.set(fragment.index, call);
|
|
506
|
+
}
|
|
497
507
|
// Emit a display-only tool_delta for the argument fragment. The sealed
|
|
498
508
|
// batch in ModelResult is authoritative; this never executes a tool.
|
|
499
509
|
if (fn && 'arguments' in fn && typeof fn.arguments === 'string' && fn.arguments) {
|
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
import {
|
|
29
29
|
parseResponsesBuffered, createResponsesStreamState,
|
|
30
30
|
} from './model-responses.mjs';
|
|
31
|
+
import { createModelStreamBudget, ModelStreamLimitError } from './model-stream-budget.mjs';
|
|
31
32
|
import { MediaError } from './model-media.mjs';
|
|
32
33
|
import { buildNativeModelRequest } from './model-request.mjs';
|
|
33
34
|
// parseModelJson is the kernel's strict finite JSON parser; used here for the
|
|
@@ -38,6 +39,11 @@ import { parseModelJson, MODEL_FAILURE_CODES, MODEL_GATEWAY_ERROR_CODES, MODEL_G
|
|
|
38
39
|
import { observeModelTransportPort } from './model-transport-observation.mjs';
|
|
39
40
|
|
|
40
41
|
const DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
|
|
42
|
+
// A full terminal snapshot can JSON-escape each retained byte as six ASCII
|
|
43
|
+
// bytes. Allow that expansion plus protocol fields without growing the
|
|
44
|
+
// independent budget for assembled content.
|
|
45
|
+
const DEFAULT_MAX_FRAME_BYTES = 6 * DEFAULT_MAX_BYTES + 64 * 1024;
|
|
46
|
+
const MAX_TOOL_ARGUMENT_BYTES = 8 * 1024 * 1024;
|
|
41
47
|
const DEFAULT_IDLE_MS = 180000;
|
|
42
48
|
|
|
43
49
|
/** Only the adapter's plain inference request is admitted for cold replay.
|
|
@@ -58,7 +64,7 @@ class OverflowError extends Error {
|
|
|
58
64
|
export function createNativeModelPort({
|
|
59
65
|
resolveProfile,
|
|
60
66
|
fetchImpl = fetch,
|
|
61
|
-
maxResponseBytes
|
|
67
|
+
maxResponseBytes,
|
|
62
68
|
idleTimeoutMs = DEFAULT_IDLE_MS,
|
|
63
69
|
} = {}) {
|
|
64
70
|
if (typeof resolveProfile !== 'function') {
|
|
@@ -67,9 +73,12 @@ export function createNativeModelPort({
|
|
|
67
73
|
if (typeof fetchImpl !== 'function') {
|
|
68
74
|
throw new TypeError('createNativeModelPort requires a fetchImpl function');
|
|
69
75
|
}
|
|
70
|
-
|
|
76
|
+
const maxBytes = maxResponseBytes === undefined ? DEFAULT_MAX_BYTES : maxResponseBytes;
|
|
77
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError('maxResponseBytes must be a positive safe integer');
|
|
71
78
|
if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs <= 0) throw new RangeError('idleTimeoutMs must be positive and finite');
|
|
72
|
-
|
|
79
|
+
// An explicit ceiling retains its original whole-response semantics.
|
|
80
|
+
const streamBounds = { maxFrameBytes: maxResponseBytes ?? DEFAULT_MAX_FRAME_BYTES,
|
|
81
|
+
maxOutputBytes: maxBytes, maxBytes: maxResponseBytes };
|
|
73
82
|
const idleTimeout = idleTimeoutMs;
|
|
74
83
|
|
|
75
84
|
return observeModelTransportPort(async (request, emitEvent, observation) => {
|
|
@@ -151,8 +160,9 @@ export function createNativeModelPort({
|
|
|
151
160
|
observation.phase('stream');
|
|
152
161
|
const idlePolicy = request.profile.streaming !== false && request.profile.streamTimeoutPolicy === 'idle/v1';
|
|
153
162
|
if (idlePolicy) { clearTimer(overallTimer); overallTimer = null; }
|
|
154
|
-
return await streamResponse(response, request, binding, emitEvent, internal,
|
|
155
|
-
idlePolicy && overallMs > 0 ? Math.min(idleTimeout, overallMs) : idleTimeout,
|
|
163
|
+
return await streamResponse(response, request, binding, emitEvent, internal, {
|
|
164
|
+
...streamBounds, idleTimeoutMs: idlePolicy && overallMs > 0 ? Math.min(idleTimeout, overallMs) : idleTimeout,
|
|
165
|
+
}, observation);
|
|
156
166
|
}
|
|
157
167
|
observation.phase('buffered');
|
|
158
168
|
return await bufferedResponse(response, request, binding, maxBytes, emitEvent, observation);
|
|
@@ -173,14 +183,15 @@ export function createNativeModelPort({
|
|
|
173
183
|
});
|
|
174
184
|
}
|
|
175
185
|
|
|
176
|
-
async function streamResponse(response, request, binding, emit, internal,
|
|
186
|
+
async function streamResponse(response, request, binding, emit, internal, streamBounds, observation) {
|
|
177
187
|
const profile = request.profile;
|
|
178
188
|
const idlePolicy = profile.streaming !== false && profile.streamTimeoutPolicy === 'idle/v1';
|
|
189
|
+
const budget = createModelStreamBudget(streamBounds.maxOutputBytes, streamBounds.maxBytes ?? MAX_TOOL_ARGUMENT_BYTES);
|
|
179
190
|
const state = binding.protocol === 'anthropic-messages'
|
|
180
|
-
? createAnthropicStreamState(profile)
|
|
191
|
+
? createAnthropicStreamState(profile, budget)
|
|
181
192
|
: binding.protocol === 'openai-responses'
|
|
182
|
-
? createResponsesStreamState(profile)
|
|
183
|
-
: createOpenAIStreamTurn(profile, binding);
|
|
193
|
+
? createResponsesStreamState(profile, budget)
|
|
194
|
+
: createOpenAIStreamTurn(profile, binding, budget);
|
|
184
195
|
// Idle silence aborts the fetch via the internal controller so the pending
|
|
185
196
|
// body read rejects cleanly instead of leaving an orphaned read to cancel.
|
|
186
197
|
const abort = (reason) => internal.abort(reason);
|
|
@@ -210,7 +221,7 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
210
221
|
{ ...(frameIndex < 0 ? {} : { frameIndex }),
|
|
211
222
|
...(code === 'usage_conflict' && state.usageConflict ? { usageConflict: state.usageConflict } : {}), ...fields });
|
|
212
223
|
try {
|
|
213
|
-
for await (const frame of readModelSse(response.body, {
|
|
224
|
+
for await (const frame of readModelSse(response.body, { ...streamBounds, abort, observeBytes: observation.bytes })) {
|
|
214
225
|
if (idlePolicy && !frame.data.trim()) continue;
|
|
215
226
|
frameIndex++;
|
|
216
227
|
observation.frame();
|
|
@@ -228,9 +239,29 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
228
239
|
if (error instanceof IdleTimeout) {
|
|
229
240
|
return failed(state.finalize({ errorKind: 'provider_retryable_error', failureKind: 'request_timeout' }), 'stream_timeout');
|
|
230
241
|
}
|
|
242
|
+
if ((error instanceof SseFramingError || error instanceof ModelStreamLimitError)
|
|
243
|
+
&& streamBounds.maxBytes === undefined && ['stream_frame_limit', 'stream_output_limit'].includes(error.code)
|
|
244
|
+
&& (request.purpose == null || request.purpose === 'task') && !state.refused
|
|
245
|
+
&& nativeModelRecoveryPolicy(binding) === 'pure-inference/v1') {
|
|
246
|
+
// Complete tool calls have not been committed. Use the existing output
|
|
247
|
+
// continuation budget, keeping only text the adapter already admitted.
|
|
248
|
+
const partial = state.finalize({ errorKind: 'output_limit' });
|
|
249
|
+
return failed({ ...partial, toolCalls: [], textCommitVersion: 'provider-finished-text/v1',
|
|
250
|
+
outputBoundary: partial.text.trim() ? 'assistant-text/v1' : 'no-visible-output/v1' }, error.code);
|
|
251
|
+
}
|
|
231
252
|
if (error instanceof SseFramingError) {
|
|
232
253
|
return failed(state.finalize({ errorKind: 'provider_terminal_error', failureKind: 'invalid_response' }), protocolCode(error));
|
|
233
254
|
}
|
|
255
|
+
if (error instanceof ModelStreamLimitError) {
|
|
256
|
+
// The adapter has not committed or dispatched any tool in this batch.
|
|
257
|
+
// Only plain inference is eligible for a corrected generation.
|
|
258
|
+
const task = request.purpose == null || request.purpose === 'task';
|
|
259
|
+
const retryable = error.code === 'tool_argument_limit' && task
|
|
260
|
+
&& !state.refused && nativeModelRecoveryPolicy(binding) === 'pure-inference/v1';
|
|
261
|
+
const result = state.finalize({ errorKind: retryable ? 'malformed_tool_call' : 'provider_terminal_error',
|
|
262
|
+
failureKind: 'invalid_response' });
|
|
263
|
+
return failed({ ...result, toolCalls: [] }, error.code);
|
|
264
|
+
}
|
|
234
265
|
if (error instanceof ProtocolError) {
|
|
235
266
|
// Typed provider error envelopes carry a closed, credential-free classification.
|
|
236
267
|
if (error.streamError) {
|
|
@@ -330,7 +361,7 @@ function protocolCode(error) {
|
|
|
330
361
|
}
|
|
331
362
|
function withFailure(result, binding, phase, code, fields = {}) {
|
|
332
363
|
if (!['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)
|
|
333
|
-
&& !(result.kind === 'output_limit' &&
|
|
364
|
+
&& !(result.kind === 'output_limit' && ['reasoning_repetition', 'stream_frame_limit', 'stream_output_limit'].includes(code))
|
|
334
365
|
&& !(result.kind === 'context_overflow' && fields.gateway)) return result;
|
|
335
366
|
const protocol = ['openai-chat', 'openai-responses', 'anthropic-messages'].includes(binding?.protocol) ? binding.protocol : 'unknown';
|
|
336
367
|
return { ...result, failureDiagnostic: { contract: fields.gateway ? 'model-failure-diagnostic/v4'
|
|
@@ -490,7 +490,7 @@ function validateBufferedIdentity(payload) {
|
|
|
490
490
|
|
|
491
491
|
// --- streaming: shared item slot namespace (ports ResponsesItems) ---
|
|
492
492
|
|
|
493
|
-
function createResponsesItems() {
|
|
493
|
+
function createResponsesItems(budget) {
|
|
494
494
|
// One shared slot namespace for message, reasoning and function_call items.
|
|
495
495
|
return {
|
|
496
496
|
indexes: new Map(), // output_index -> item_id
|
|
@@ -501,6 +501,10 @@ function createResponsesItems() {
|
|
|
501
501
|
const itemId = item != null ? identityOf(item.id) : identityOf(event.item_id);
|
|
502
502
|
if ('item_id' in event && identityOf(event.item_id) !== itemId) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
503
503
|
const index = indexOf(event, 'output_index');
|
|
504
|
+
if ((index != null || item != null || kind) && !this.itemIndexes.has(itemId) && !this.kinds.has(itemId)) {
|
|
505
|
+
budget?.slot();
|
|
506
|
+
budget?.output(itemId);
|
|
507
|
+
}
|
|
504
508
|
if (index != null) {
|
|
505
509
|
if (this.indexes.get(index) != null && this.indexes.get(index) !== itemId) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
506
510
|
if (this.itemIndexes.get(itemId) != null && this.itemIndexes.get(itemId) !== index) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
@@ -533,7 +537,7 @@ function createContentPart(kind) {
|
|
|
533
537
|
|
|
534
538
|
// A content item (message or reasoning) holds indexed parts grouped by
|
|
535
539
|
// (group, index). Parts snapshot or accumulate text; closure is validated.
|
|
536
|
-
function createResponsesContent(items) {
|
|
540
|
+
function createResponsesContent(items, budget) {
|
|
537
541
|
const state = {
|
|
538
542
|
items, // shared ResponsesItems
|
|
539
543
|
itemState: new Map(), // key -> { kind, parts, closed }
|
|
@@ -558,6 +562,7 @@ function createResponsesContent(items) {
|
|
|
558
562
|
return previous;
|
|
559
563
|
}
|
|
560
564
|
if (item.closed) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
565
|
+
budget?.slot();
|
|
561
566
|
const part = createContentPart(kind);
|
|
562
567
|
item.parts.set(partKey, part);
|
|
563
568
|
return part;
|
|
@@ -572,6 +577,7 @@ function createResponsesContent(items) {
|
|
|
572
577
|
const part = this.getPart(item, group, index, kind);
|
|
573
578
|
if (delta) {
|
|
574
579
|
if (part.closed) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
580
|
+
budget?.output(text);
|
|
575
581
|
part.text += text;
|
|
576
582
|
} else {
|
|
577
583
|
this.snapshotPart(part, text, closed);
|
|
@@ -583,6 +589,7 @@ function createResponsesContent(items) {
|
|
|
583
589
|
if ((part.closed && text !== part.text) || !text.startsWith(part.text)) {
|
|
584
590
|
throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
585
591
|
}
|
|
592
|
+
budget?.output(text.slice(part.text.length));
|
|
586
593
|
part.text = text;
|
|
587
594
|
part.closed = part.closed || closed;
|
|
588
595
|
},
|
|
@@ -711,11 +718,13 @@ function createResponsesContent(items) {
|
|
|
711
718
|
throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
712
719
|
}
|
|
713
720
|
tail = text.slice(previous.length);
|
|
721
|
+
budget?.output(tail);
|
|
714
722
|
this[attr] = text;
|
|
715
723
|
this.legacyClosed.add(attr);
|
|
716
724
|
} else {
|
|
717
725
|
if (this.legacyClosed.has(attr)) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
718
726
|
tail = text;
|
|
727
|
+
budget?.output(tail);
|
|
719
728
|
this[attr] = previous + text;
|
|
720
729
|
}
|
|
721
730
|
const indexed = attr === 'legacyText' ? this.emittedText : this.emittedReasoning;
|
|
@@ -812,8 +821,8 @@ function sealTool(tool) {
|
|
|
812
821
|
tool.closed = true;
|
|
813
822
|
}
|
|
814
823
|
|
|
815
|
-
function createResponsesToolCalls() {
|
|
816
|
-
const items = createResponsesItems();
|
|
824
|
+
function createResponsesToolCalls(budget) {
|
|
825
|
+
const items = createResponsesItems(budget);
|
|
817
826
|
return {
|
|
818
827
|
items,
|
|
819
828
|
calls: new Map(), // item_id -> WireTool
|
|
@@ -836,7 +845,11 @@ function createResponsesToolCalls() {
|
|
|
836
845
|
if (current != null) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
837
846
|
current = createWireTool();
|
|
838
847
|
pinToolIdentity(current, item, 'call_id');
|
|
839
|
-
if ('arguments' in item)
|
|
848
|
+
if ('arguments' in item) {
|
|
849
|
+
const arguments_ = optionalText(item.arguments);
|
|
850
|
+
budget?.tool(current, arguments_);
|
|
851
|
+
current.arguments = arguments_;
|
|
852
|
+
}
|
|
840
853
|
this.calls.set(key, current);
|
|
841
854
|
return null;
|
|
842
855
|
}
|
|
@@ -853,6 +866,7 @@ function createResponsesToolCalls() {
|
|
|
853
866
|
|| (current.closed || current.argumentsDone) && arguments_ !== current.arguments) {
|
|
854
867
|
throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
855
868
|
}
|
|
869
|
+
budget?.tool(current, arguments_.slice(current.arguments.length));
|
|
856
870
|
current.arguments = arguments_;
|
|
857
871
|
}
|
|
858
872
|
if (current.closed) return null;
|
|
@@ -864,10 +878,13 @@ function createResponsesToolCalls() {
|
|
|
864
878
|
const current = this.calls.get(key);
|
|
865
879
|
if (current == null || current.closed || current.argumentsDone) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
866
880
|
if (type.endsWith('.delta')) {
|
|
867
|
-
|
|
881
|
+
const delta = optionalText(event.delta);
|
|
882
|
+
budget?.tool(current, delta);
|
|
883
|
+
current.arguments += delta;
|
|
868
884
|
} else {
|
|
869
885
|
const arguments_ = optionalText(event.arguments);
|
|
870
886
|
if (!arguments_.startsWith(current.arguments)) throw new ProtocolError('invalid model frame', 'envelope_invalid');
|
|
887
|
+
budget?.tool(current, arguments_.slice(current.arguments.length));
|
|
871
888
|
current.arguments = arguments_;
|
|
872
889
|
current.argumentsDone = true;
|
|
873
890
|
}
|
|
@@ -941,11 +958,11 @@ function createWireIdentity() {
|
|
|
941
958
|
// throw ProtocolError; finalize preserves the accumulated text/usage and
|
|
942
959
|
// classifies the attempt. One terminal event (response.completed/incomplete/
|
|
943
960
|
// failed/error/cancelled) seals the attempt.
|
|
944
|
-
export function createResponsesStreamState(profile) {
|
|
961
|
+
export function createResponsesStreamState(profile, budget) {
|
|
945
962
|
const captureReplay = profile.providerReplayMode !== 'none';
|
|
946
963
|
const emitThinking = profile.providerThinkingDisplay ?? profile.providerReplayMode !== 'none';
|
|
947
|
-
const toolItems = createResponsesToolCalls();
|
|
948
|
-
const contentItems = createResponsesContent(toolItems.items);
|
|
964
|
+
const toolItems = createResponsesToolCalls(budget);
|
|
965
|
+
const contentItems = createResponsesContent(toolItems.items, budget);
|
|
949
966
|
const identity = createWireIdentity();
|
|
950
967
|
return {
|
|
951
968
|
text: '',
|
package/src/native/model-sse.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Strict SSE byte framing for the native model transport.
|
|
2
2
|
//
|
|
3
3
|
// Ports ksadk._model_sse: UTF-8 is deliberately strict (replacing corrupt bytes
|
|
4
|
-
// inside JSON changes model facts),
|
|
4
|
+
// inside JSON changes model facts), byte budgets bound partial lines and frames, and a
|
|
5
5
|
// blank line is the only frame dispatch. A discarded terminal fragment at EOF
|
|
6
6
|
// is an unfinished frame, never a complete response. Idle silence is bounded.
|
|
7
7
|
//
|
|
@@ -38,14 +38,17 @@ function toAsyncIterator(body) {
|
|
|
38
38
|
// Stateful line framer mirroring ksadk._model_sse._Framer. CRLF/CR/LF all
|
|
39
39
|
// terminate lines; a blank line dispatches a frame from accumulated data lines.
|
|
40
40
|
class SseFramer {
|
|
41
|
-
constructor() {
|
|
41
|
+
constructor(maxFrameBytes) {
|
|
42
|
+
this.maxFrameBytes = maxFrameBytes;
|
|
43
|
+
this.lineBytes = 0;
|
|
44
|
+
this.dataBytes = 0;
|
|
42
45
|
this.lineParts = [];
|
|
43
46
|
this.dataLines = [];
|
|
44
47
|
this.eventName = '';
|
|
45
48
|
this.afterCr = false;
|
|
46
49
|
}
|
|
47
50
|
|
|
48
|
-
feed(text
|
|
51
|
+
*feed(text) {
|
|
49
52
|
if (!text) return;
|
|
50
53
|
if (this.afterCr) {
|
|
51
54
|
if (text.startsWith('\n')) text = text.slice(1);
|
|
@@ -53,15 +56,28 @@ class SseFramer {
|
|
|
53
56
|
}
|
|
54
57
|
let start = 0;
|
|
55
58
|
for (const m of text.matchAll(/\r\n|\r|\n/g)) {
|
|
56
|
-
this.
|
|
59
|
+
this.appendLine(text.slice(start, m.index));
|
|
57
60
|
const line = this.lineParts.join('');
|
|
58
61
|
this.lineParts = [];
|
|
62
|
+
this.lineBytes = 0;
|
|
59
63
|
start = m.index + m[0].length;
|
|
60
64
|
this.afterCr = m[0] === '\r' && start === text.length;
|
|
61
65
|
const frame = this.handleLine(line);
|
|
62
|
-
if (frame)
|
|
66
|
+
if (frame) yield frame;
|
|
67
|
+
}
|
|
68
|
+
if (start < text.length) this.appendLine(text.slice(start));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
appendLine(part) {
|
|
72
|
+
this.lineBytes += Buffer.byteLength(part);
|
|
73
|
+
this.checkFrameBytes(this.lineBytes);
|
|
74
|
+
this.lineParts.push(part);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
checkFrameBytes(bytes) {
|
|
78
|
+
if (bytes > this.maxFrameBytes) {
|
|
79
|
+
throw new SseFramingError('model SSE line or event exceeded the byte limit', 'stream_frame_limit');
|
|
63
80
|
}
|
|
64
|
-
if (start < text.length) this.lineParts.push(text.slice(start));
|
|
65
81
|
}
|
|
66
82
|
|
|
67
83
|
handleLine(line) {
|
|
@@ -69,6 +85,7 @@ class SseFramer {
|
|
|
69
85
|
if (this.dataLines.length === 0) { this.eventName = ''; return null; }
|
|
70
86
|
const frame = { data: this.dataLines.join('\n'), event: this.eventName || '' };
|
|
71
87
|
this.dataLines = [];
|
|
88
|
+
this.dataBytes = 0;
|
|
72
89
|
this.eventName = '';
|
|
73
90
|
return frame;
|
|
74
91
|
}
|
|
@@ -77,8 +94,14 @@ class SseFramer {
|
|
|
77
94
|
const name = sep === -1 ? line : line.slice(0, sep);
|
|
78
95
|
let value = sep === -1 ? '' : line.slice(sep + 1);
|
|
79
96
|
if (value.startsWith(' ')) value = value.slice(1);
|
|
80
|
-
if (name === 'data')
|
|
81
|
-
|
|
97
|
+
if (name === 'data') {
|
|
98
|
+
this.dataBytes += Buffer.byteLength(value) + Number(this.dataLines.length > 0);
|
|
99
|
+
this.checkFrameBytes(this.dataBytes + Buffer.byteLength(this.eventName));
|
|
100
|
+
this.dataLines.push(value);
|
|
101
|
+
} else if (name === 'event') {
|
|
102
|
+
this.checkFrameBytes(this.dataBytes + Buffer.byteLength(value));
|
|
103
|
+
this.eventName = value;
|
|
104
|
+
}
|
|
82
105
|
// `id` and `retry` are transport controls, not model payloads; ignore them.
|
|
83
106
|
return null;
|
|
84
107
|
}
|
|
@@ -96,20 +119,22 @@ class SseFramer {
|
|
|
96
119
|
* Yield { data, event } SSE frames from a byte stream with strict framing.
|
|
97
120
|
*
|
|
98
121
|
* @param body fetch response body (ReadableStream or async iterable of bytes)
|
|
99
|
-
* @param {maxBytes, idleTimeoutMs, abort} bounds.
|
|
122
|
+
* @param {maxFrameBytes, maxBytes, idleTimeoutMs, abort} bounds. maxFrameBytes bounds a line or event;
|
|
123
|
+
* maxBytes is an optional explicit whole-response ceiling for callers.
|
|
100
124
|
* idleTimeoutMs bounds silence between nonempty frames: when it fires, abort
|
|
101
125
|
* is called with an IdleTimeout so the underlying fetch aborts and the
|
|
102
126
|
* pending read rejects cleanly (no orphaned read to cancel). Throws
|
|
103
127
|
* SseFramingError (terminal) or propagates transport/abort errors.
|
|
104
128
|
*/
|
|
105
|
-
export async function* readModelSse(body, {
|
|
106
|
-
if (!Number.isSafeInteger(
|
|
129
|
+
export async function* readModelSse(body, { maxFrameBytes = 8 * 1024 * 1024, maxBytes, idleTimeoutMs, abort, observeBytes } = {}) {
|
|
130
|
+
if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0
|
|
131
|
+
|| maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
|
|
107
132
|
throw new SseFramingError('model SSE needs a positive byte budget');
|
|
108
133
|
}
|
|
109
134
|
const iter = toAsyncIterator(body);
|
|
110
135
|
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
111
|
-
const framer = new SseFramer();
|
|
112
|
-
let
|
|
136
|
+
const framer = new SseFramer(maxFrameBytes);
|
|
137
|
+
let wireBytes = 0;
|
|
113
138
|
const idleEnabled = typeof idleTimeoutMs === 'number' && idleTimeoutMs > 0 && typeof abort === 'function';
|
|
114
139
|
let idleTimer = null;
|
|
115
140
|
const armIdle = () => {
|
|
@@ -120,7 +145,6 @@ export async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTime
|
|
|
120
145
|
};
|
|
121
146
|
const disarmIdle = () => { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } };
|
|
122
147
|
armIdle();
|
|
123
|
-
const frames = [];
|
|
124
148
|
try {
|
|
125
149
|
while (true) {
|
|
126
150
|
let result;
|
|
@@ -130,18 +154,18 @@ export async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTime
|
|
|
130
154
|
if (!(chunk instanceof Uint8Array) && !(chunk instanceof ArrayBuffer)) {
|
|
131
155
|
throw new SseFramingError('model SSE requires byte chunks');
|
|
132
156
|
}
|
|
133
|
-
total += chunk.byteLength;
|
|
134
157
|
observeBytes?.(chunk.byteLength);
|
|
135
|
-
if (
|
|
158
|
+
if (maxBytes !== undefined) {
|
|
159
|
+
wireBytes += chunk.byteLength;
|
|
160
|
+
if (wireBytes > maxBytes) throw new SseFramingError('model SSE byte budget exceeded', 'body_limit');
|
|
161
|
+
}
|
|
136
162
|
let text;
|
|
137
163
|
try {
|
|
138
164
|
text = decoder.decode(chunk, { stream: true });
|
|
139
165
|
} catch {
|
|
140
166
|
throw new SseFramingError('invalid utf-8 in model stream', 'body_encoding');
|
|
141
167
|
}
|
|
142
|
-
|
|
143
|
-
framer.feed(text, frames);
|
|
144
|
-
for (const frame of frames) {
|
|
168
|
+
for (const frame of framer.feed(text)) {
|
|
145
169
|
yield frame;
|
|
146
170
|
// Time spent by the consumer is not provider idle time. Comments and
|
|
147
171
|
// blank data do not reset the deadline; only nonempty data does.
|
|
@@ -154,11 +178,7 @@ export async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTime
|
|
|
154
178
|
} catch {
|
|
155
179
|
throw new SseFramingError('invalid utf-8 in model stream', 'body_encoding');
|
|
156
180
|
}
|
|
157
|
-
|
|
158
|
-
frames.length = 0;
|
|
159
|
-
framer.feed(tail, frames);
|
|
160
|
-
for (const frame of frames) yield frame;
|
|
161
|
-
}
|
|
181
|
+
yield* framer.feed(tail);
|
|
162
182
|
framer.finish();
|
|
163
183
|
} finally {
|
|
164
184
|
disarmIdle();
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ProtocolError } from './model-normalize.mjs';
|
|
2
|
+
|
|
3
|
+
export class ModelStreamLimitError extends ProtocolError {}
|
|
4
|
+
|
|
5
|
+
// Count assembled payload bytes only. Provider envelopes, keepalives and
|
|
6
|
+
// repeated terminal snapshots do not add to the retained content.
|
|
7
|
+
export function createModelStreamBudget(maxOutputBytes, maxToolBytes) {
|
|
8
|
+
let outputBytes = 0;
|
|
9
|
+
const toolBytes = new WeakMap();
|
|
10
|
+
const retain = (bytes, code = 'stream_output_limit') => {
|
|
11
|
+
if (outputBytes + bytes > maxOutputBytes) {
|
|
12
|
+
throw new ModelStreamLimitError('assembled model output exceeded the byte limit', code);
|
|
13
|
+
}
|
|
14
|
+
outputBytes += bytes;
|
|
15
|
+
};
|
|
16
|
+
return {
|
|
17
|
+
output(text) { retain(Buffer.byteLength(text)); },
|
|
18
|
+
// Indexed items also retain state when their payload is empty.
|
|
19
|
+
slot() { retain(128); },
|
|
20
|
+
tool(call, fragment) {
|
|
21
|
+
const bytes = Buffer.byteLength(fragment);
|
|
22
|
+
const total = (toolBytes.get(call) ?? 0) + bytes;
|
|
23
|
+
if (total > maxToolBytes) {
|
|
24
|
+
throw new ModelStreamLimitError('assembled tool input exceeded the byte limit', 'tool_argument_limit');
|
|
25
|
+
}
|
|
26
|
+
// A tool fragment exhausting the shared budget also needs smaller calls.
|
|
27
|
+
retain(bytes, 'tool_argument_limit');
|
|
28
|
+
toolBytes.set(call, total);
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -39,6 +39,11 @@ function modelFailureMessage(value, retriesExhausted = false) {
|
|
|
39
39
|
if (value.code === 'host_binding') return '模型连接配置未能加载,请检查运行配置。';
|
|
40
40
|
if (value.phase === 'request') return '模型请求在发送前未通过校验,请查看运行诊断。';
|
|
41
41
|
if (value.code === 'stream_timeout' || value.code === 'http_timeout') return '等待模型服务响应超时,本次运行未能完成。';
|
|
42
|
+
if (value.code === 'body_limit') return '模型响应超过大小上限,本次运行已停止。';
|
|
43
|
+
if (value.code === 'stream_frame_limit') return '模型响应中的单个流式事件超过大小上限。';
|
|
44
|
+
if (value.code === 'stream_output_limit') return '模型本次输出的内容超过大小上限。';
|
|
45
|
+
if (value.code === 'tool_argument_limit') return '模型生成的工具参数超过大小上限,本批工具未执行。';
|
|
46
|
+
if (value.code === 'stream_incomplete') return '模型响应中途结束,未收到完整结果。';
|
|
42
47
|
if (value.code === 'transport_error') return '与模型服务的连接中断,本次运行未能完成。';
|
|
43
48
|
if (value.code === 'provider_error' || value.code === 'http_server') return '模型服务返回执行错误,本次运行未能完成。';
|
|
44
49
|
if (value.phase === 'stream' || value.phase === 'buffered') return '模型响应未通过协议校验,本次运行已停止,请查看运行诊断。';
|