@kingsoftcloud/agentkit-harness-node 0.0.27 → 0.0.29
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/engine-runtime.mjs +10 -7
- package/src/native/engine-service.mjs +4 -1
- package/src/native/local-command-state.mjs +10 -2
- 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
- package/src/native/windows-private-state.mjs +41 -0
- package/src/native/workspace-state.mjs +3 -3
- package/src/native/workspace-tools.mjs +3 -3
|
@@ -19,6 +19,7 @@ import { validateMediaBlock } from './model-media.mjs';
|
|
|
19
19
|
import { admitProviderCompatibilityPolicy } from './model-provider-compat.mjs';
|
|
20
20
|
import { isProviderCompatibilityRule } from './model-inline-reasoning.mjs';
|
|
21
21
|
import { bindNativeContext, nativeContextDefaults } from './context-profile.mjs';
|
|
22
|
+
import { privateDirectory } from './local-command-state.mjs';
|
|
22
23
|
import { createEngineDeliveryJournal, engineDeliveryEvidence } from './engine-delivery-evidence.mjs';
|
|
23
24
|
import { createNativeWorkspaceTools } from './workspace-tools.mjs';
|
|
24
25
|
import { createNativeLocalCommandTools } from './local-command-tools.mjs';
|
|
@@ -215,6 +216,8 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
215
216
|
&& scope && ['tenantId', 'workspaceId', 'userId', 'agentId'].every(key => text(scope[key])), 'engine_runtime_invalid');
|
|
216
217
|
const root = realpathSync(resolve(workspaceRoot));
|
|
217
218
|
mkdirSync(stateDir, { recursive: true });
|
|
219
|
+
const windows = process.platform === 'win32';
|
|
220
|
+
if (windows) privateDirectory(realpathSync(stateDir));
|
|
218
221
|
const description = admitEngineModel(model);
|
|
219
222
|
const roles = nativeChildRoles({ subAgents });
|
|
220
223
|
const supportsImages = description.input.includes('image');
|
|
@@ -230,7 +233,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
230
233
|
const local = execution.localExecution(executionOptions);
|
|
231
234
|
const workspace = createNativeWorkspaceTools({ workspaceRoot: root, stateDir: join(stateDir, 'workspace'), sessionId, authorize: decide });
|
|
232
235
|
const deliveries = createEngineDeliveryJournal(join(stateDir, 'delivery'), () => workspace.captureDelivery());
|
|
233
|
-
const commands = createNativeLocalCommandTools({ workspaceRoot: root, stateRoot: join(stateDir, 'commands'), sessionId,
|
|
236
|
+
const commands = windows ? null : createNativeLocalCommandTools({ workspaceRoot: root, stateRoot: join(stateDir, 'commands'), sessionId,
|
|
234
237
|
settings: local.settings, sourceEnv: local.environment, outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy,
|
|
235
238
|
shellPolicy: commandSandbox,
|
|
236
239
|
artifacts, authorize: (request, info) => decide(request, true, info?.readOnlyCommand),
|
|
@@ -241,7 +244,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
241
244
|
// Do not advertise a search which can only return provider_not_configured.
|
|
242
245
|
// Public page fetching remains available independently of search credentials.
|
|
243
246
|
if (!search.configured) web.definitions = web.definitions.filter(tool => tool.name !== 'web_search');
|
|
244
|
-
const owners = [workspace, commands, web];
|
|
247
|
+
const owners = [workspace, ...(commands ? [commands] : []), web];
|
|
245
248
|
const route = new Map(owners.flatMap(port => port.definitions.map(definition => [definition.name, port])));
|
|
246
249
|
// Anything a Run advertises that the engine does not own was admitted as a host tool.
|
|
247
250
|
const hostPort = {
|
|
@@ -330,17 +333,17 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
330
333
|
const modelSurface = bindNativeModelSurface({ environment: execution.executionEnvironment(executionOptions), description });
|
|
331
334
|
const modelPort = createNativeModelPort({ fetchImpl, resolveProfile: async () => ({ protocol: description.protocol, baseUrl: description.baseUrl,
|
|
332
335
|
apiKey: await model.apiKey(), model: description.modelName, parameters: description.parameters }) });
|
|
333
|
-
const background = createBackgroundCommandPort({ scope, store, readers: { local_process: commands.reader } });
|
|
336
|
+
const background = createBackgroundCommandPort({ scope, store, readers: commands ? { local_process: commands.reader } : {} });
|
|
334
337
|
const lifetime = new AbortController();
|
|
335
338
|
const childDefinitions = [];
|
|
336
339
|
let children;
|
|
337
340
|
if (roles.length) {
|
|
338
341
|
try {
|
|
339
|
-
const childTools = [...workspace.definitions, ...commands
|
|
342
|
+
const childTools = [...workspace.definitions, ...(commands?.definitions ?? [])].map(tool => tool.readOnly
|
|
340
343
|
? tool : { ...tool, approvalPolicy: DURABLE_APPROVAL });
|
|
341
344
|
const fileWorkspaces = createStudioNativeChildWorkspaces({ workspaceRoot: root, stateDir });
|
|
342
|
-
const commandResource = childCommandResource({ ...local.binding,
|
|
343
|
-
controls: { ...local.binding.controls, shellPolicy: commandSandbox ?? local.binding.controls.shellPolicy } });
|
|
345
|
+
const commandResource = commands ? childCommandResource({ ...local.binding,
|
|
346
|
+
controls: { ...local.binding.controls, shellPolicy: commandSandbox ?? local.binding.controls.shellPolicy } }) : null;
|
|
344
347
|
children = await createNativeChildren({ roles, scope, sessionId, store, tools: childTools, fileWorkspaces,
|
|
345
348
|
commandResource, isClosed: () => lifetime.signal.aborted, detachSignal: lifetime.signal,
|
|
346
349
|
restrictTools: (tools, parent) => tools.flatMap(tool => {
|
|
@@ -360,7 +363,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
360
363
|
const childState = join(stateDir, 'children', digest({ childScope, childSession }));
|
|
361
364
|
const files = createNativeWorkspaceTools({ workspaceRoot: childRoot, stateDir: join(childState, 'workspace'),
|
|
362
365
|
sessionId: childSession, authorize: decide });
|
|
363
|
-
const command = executionResource ? createNativeLocalCommandTools({ workspaceRoot: childRoot,
|
|
366
|
+
const command = commands && executionResource ? createNativeLocalCommandTools({ workspaceRoot: childRoot,
|
|
364
367
|
stateRoot: join(childState, 'commands'), sessionId: childSession, settings: local.settings, sourceEnv: local.environment,
|
|
365
368
|
outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy, shellPolicy: commandSandbox,
|
|
366
369
|
authorize: decide, captureWorkspace: request => files.capture(request),
|
|
@@ -10,6 +10,8 @@ import { PassThrough } from 'node:stream';
|
|
|
10
10
|
import { fileURLToPath } from 'node:url';
|
|
11
11
|
import { engineStartupFromArgs, engineView, serveEngine } from './engine-server.mjs';
|
|
12
12
|
import { ENGINE_EXECUTION_POLICY } from './engine-runtime.mjs';
|
|
13
|
+
import { privateDirectory } from './local-command-state.mjs';
|
|
14
|
+
import { isInside } from './workspace-paths.mjs';
|
|
13
15
|
import { createEngineViewStore } from './engine-view-store.mjs';
|
|
14
16
|
import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
|
|
15
17
|
import { ENGINE_CONTEXT } from './engine-context.mjs';
|
|
@@ -187,8 +189,9 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
|
|
|
187
189
|
mkdirSync(startup.stateDir, { recursive: true, mode: 0o700 });
|
|
188
190
|
const stateDir = realpathSync(startup.stateDir);
|
|
189
191
|
const workspace = realpathSync(startup.workspace);
|
|
190
|
-
if (workspace
|
|
192
|
+
if (isInside(workspace, stateDir) || isInside(stateDir, workspace))
|
|
191
193
|
throw new Error('engine_service_workspace_state_overlap');
|
|
194
|
+
if (process.platform === 'win32') privateDirectory(stateDir);
|
|
192
195
|
if (startup.commandSandbox !== undefined) {
|
|
193
196
|
if (startup.commandSandbox !== ISOLATED_COMMAND_SHELL) throw new Error('engine_service_sandbox_invalid');
|
|
194
197
|
const [command, ...args] = shellCommandArgv(':', startup.commandSandbox, { workspaceRoot: workspace, cwd: workspace });
|
|
@@ -4,6 +4,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
4
4
|
import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync,
|
|
5
5
|
openSync, readFileSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
6
6
|
import { dirname, join, resolve } from 'node:path';
|
|
7
|
+
import { verifyWindowsPrivateState } from './windows-private-state.mjs';
|
|
7
8
|
import { validCommandEvidence } from './local-command-evidence.mjs';
|
|
8
9
|
|
|
9
10
|
export const LOCAL_BACKGROUND_CONTRACT = 'agentkit.local-background-command/v1';
|
|
@@ -24,6 +25,10 @@ function noSymlinks(path) {
|
|
|
24
25
|
if (dirname(part) === part) break;
|
|
25
26
|
}
|
|
26
27
|
}
|
|
28
|
+
function hasPrivatePermissions(path, stat) {
|
|
29
|
+
return process.platform === 'win32' ? verifyWindowsPrivateState(resolve(path), stat)
|
|
30
|
+
: stat.uid === process.getuid() && (stat.mode & 0o077) === 0;
|
|
31
|
+
}
|
|
27
32
|
export function privateDirectory(path, create = false) {
|
|
28
33
|
noSymlinks(path);
|
|
29
34
|
if (create) {
|
|
@@ -33,12 +38,12 @@ export function privateDirectory(path, create = false) {
|
|
|
33
38
|
for (const part of missing.reverse()) { syncDirectory(part); syncDirectory(dirname(part)); }
|
|
34
39
|
}
|
|
35
40
|
const stat = lstatSync(path);
|
|
36
|
-
check(stat.isDirectory() &&
|
|
41
|
+
check(stat.isDirectory() && hasPrivatePermissions(path, stat), 'background_state_not_private');
|
|
37
42
|
}
|
|
38
43
|
export function privateFile(path, allowMissing = false) {
|
|
39
44
|
try {
|
|
40
45
|
const stat = lstatSync(path);
|
|
41
|
-
check(stat.isFile() &&
|
|
46
|
+
check(stat.isFile() && hasPrivatePermissions(path, stat),
|
|
42
47
|
'background_state_not_private');
|
|
43
48
|
// Atomic publication can unlink the inode while lstat is observing it.
|
|
44
49
|
// It is never usable evidence; read-only callers may retry the new inode.
|
|
@@ -66,6 +71,9 @@ export function openPrivate(path, flags) {
|
|
|
66
71
|
}
|
|
67
72
|
}
|
|
68
73
|
export function syncDirectory(directory) {
|
|
74
|
+
// Node opens directory handles read-only on Windows. File data is still
|
|
75
|
+
// flushed before rename, and SQLite journals use their native Windows VFS.
|
|
76
|
+
if (process.platform === 'win32') return;
|
|
69
77
|
const fd = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
|
70
78
|
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
71
79
|
}
|
|
@@ -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: '',
|