@kingsoftcloud/agentkit-harness-node 0.0.26 → 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
package/dist/rpc-entry.mjs
CHANGED
|
@@ -1533,13 +1533,16 @@ function toAsyncIterator(body) {
|
|
|
1533
1533
|
throw new SseFramingError("model SSE requires a byte stream");
|
|
1534
1534
|
}
|
|
1535
1535
|
var SseFramer = class {
|
|
1536
|
-
constructor() {
|
|
1536
|
+
constructor(maxFrameBytes) {
|
|
1537
|
+
this.maxFrameBytes = maxFrameBytes;
|
|
1538
|
+
this.lineBytes = 0;
|
|
1539
|
+
this.dataBytes = 0;
|
|
1537
1540
|
this.lineParts = [];
|
|
1538
1541
|
this.dataLines = [];
|
|
1539
1542
|
this.eventName = "";
|
|
1540
1543
|
this.afterCr = false;
|
|
1541
1544
|
}
|
|
1542
|
-
feed(text
|
|
1545
|
+
*feed(text) {
|
|
1543
1546
|
if (!text) return;
|
|
1544
1547
|
if (this.afterCr) {
|
|
1545
1548
|
if (text.startsWith("\n")) text = text.slice(1);
|
|
@@ -1547,15 +1550,26 @@ var SseFramer = class {
|
|
|
1547
1550
|
}
|
|
1548
1551
|
let start = 0;
|
|
1549
1552
|
for (const m of text.matchAll(/\r\n|\r|\n/g)) {
|
|
1550
|
-
this.
|
|
1553
|
+
this.appendLine(text.slice(start, m.index));
|
|
1551
1554
|
const line = this.lineParts.join("");
|
|
1552
1555
|
this.lineParts = [];
|
|
1556
|
+
this.lineBytes = 0;
|
|
1553
1557
|
start = m.index + m[0].length;
|
|
1554
1558
|
this.afterCr = m[0] === "\r" && start === text.length;
|
|
1555
1559
|
const frame = this.handleLine(line);
|
|
1556
|
-
if (frame)
|
|
1560
|
+
if (frame) yield frame;
|
|
1561
|
+
}
|
|
1562
|
+
if (start < text.length) this.appendLine(text.slice(start));
|
|
1563
|
+
}
|
|
1564
|
+
appendLine(part) {
|
|
1565
|
+
this.lineBytes += Buffer.byteLength(part);
|
|
1566
|
+
this.checkFrameBytes(this.lineBytes);
|
|
1567
|
+
this.lineParts.push(part);
|
|
1568
|
+
}
|
|
1569
|
+
checkFrameBytes(bytes) {
|
|
1570
|
+
if (bytes > this.maxFrameBytes) {
|
|
1571
|
+
throw new SseFramingError("model SSE line or event exceeded the byte limit", "stream_frame_limit");
|
|
1557
1572
|
}
|
|
1558
|
-
if (start < text.length) this.lineParts.push(text.slice(start));
|
|
1559
1573
|
}
|
|
1560
1574
|
handleLine(line) {
|
|
1561
1575
|
if (line === "") {
|
|
@@ -1565,6 +1579,7 @@ var SseFramer = class {
|
|
|
1565
1579
|
}
|
|
1566
1580
|
const frame = { data: this.dataLines.join("\n"), event: this.eventName || "" };
|
|
1567
1581
|
this.dataLines = [];
|
|
1582
|
+
this.dataBytes = 0;
|
|
1568
1583
|
this.eventName = "";
|
|
1569
1584
|
return frame;
|
|
1570
1585
|
}
|
|
@@ -1573,8 +1588,14 @@ var SseFramer = class {
|
|
|
1573
1588
|
const name = sep2 === -1 ? line : line.slice(0, sep2);
|
|
1574
1589
|
let value = sep2 === -1 ? "" : line.slice(sep2 + 1);
|
|
1575
1590
|
if (value.startsWith(" ")) value = value.slice(1);
|
|
1576
|
-
if (name === "data")
|
|
1577
|
-
|
|
1591
|
+
if (name === "data") {
|
|
1592
|
+
this.dataBytes += Buffer.byteLength(value) + Number(this.dataLines.length > 0);
|
|
1593
|
+
this.checkFrameBytes(this.dataBytes + Buffer.byteLength(this.eventName));
|
|
1594
|
+
this.dataLines.push(value);
|
|
1595
|
+
} else if (name === "event") {
|
|
1596
|
+
this.checkFrameBytes(this.dataBytes + Buffer.byteLength(value));
|
|
1597
|
+
this.eventName = value;
|
|
1598
|
+
}
|
|
1578
1599
|
return null;
|
|
1579
1600
|
}
|
|
1580
1601
|
finish() {
|
|
@@ -1584,14 +1605,14 @@ var SseFramer = class {
|
|
|
1584
1605
|
}
|
|
1585
1606
|
}
|
|
1586
1607
|
};
|
|
1587
|
-
async function* readModelSse(body, {
|
|
1588
|
-
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
|
|
1608
|
+
async function* readModelSse(body, { maxFrameBytes = 8 * 1024 * 1024, maxBytes, idleTimeoutMs, abort, observeBytes } = {}) {
|
|
1609
|
+
if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0 || maxBytes !== void 0 && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
|
|
1589
1610
|
throw new SseFramingError("model SSE needs a positive byte budget");
|
|
1590
1611
|
}
|
|
1591
1612
|
const iter = toAsyncIterator(body);
|
|
1592
1613
|
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1593
|
-
const framer = new SseFramer();
|
|
1594
|
-
let
|
|
1614
|
+
const framer = new SseFramer(maxFrameBytes);
|
|
1615
|
+
let wireBytes = 0;
|
|
1595
1616
|
const idleEnabled = typeof idleTimeoutMs === "number" && idleTimeoutMs > 0 && typeof abort === "function";
|
|
1596
1617
|
let idleTimer = null;
|
|
1597
1618
|
const armIdle = () => {
|
|
@@ -1607,7 +1628,6 @@ async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTimeoutMs,
|
|
|
1607
1628
|
}
|
|
1608
1629
|
};
|
|
1609
1630
|
armIdle();
|
|
1610
|
-
const frames = [];
|
|
1611
1631
|
try {
|
|
1612
1632
|
while (true) {
|
|
1613
1633
|
let result;
|
|
@@ -1617,18 +1637,18 @@ async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTimeoutMs,
|
|
|
1617
1637
|
if (!(chunk instanceof Uint8Array) && !(chunk instanceof ArrayBuffer)) {
|
|
1618
1638
|
throw new SseFramingError("model SSE requires byte chunks");
|
|
1619
1639
|
}
|
|
1620
|
-
total += chunk.byteLength;
|
|
1621
1640
|
observeBytes?.(chunk.byteLength);
|
|
1622
|
-
if (
|
|
1641
|
+
if (maxBytes !== void 0) {
|
|
1642
|
+
wireBytes += chunk.byteLength;
|
|
1643
|
+
if (wireBytes > maxBytes) throw new SseFramingError("model SSE byte budget exceeded", "body_limit");
|
|
1644
|
+
}
|
|
1623
1645
|
let text;
|
|
1624
1646
|
try {
|
|
1625
1647
|
text = decoder.decode(chunk, { stream: true });
|
|
1626
1648
|
} catch {
|
|
1627
1649
|
throw new SseFramingError("invalid utf-8 in model stream", "body_encoding");
|
|
1628
1650
|
}
|
|
1629
|
-
|
|
1630
|
-
framer.feed(text, frames);
|
|
1631
|
-
for (const frame of frames) {
|
|
1651
|
+
for (const frame of framer.feed(text)) {
|
|
1632
1652
|
yield frame;
|
|
1633
1653
|
if (frame.data && frame.data.trim()) armIdle();
|
|
1634
1654
|
}
|
|
@@ -1639,11 +1659,7 @@ async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTimeoutMs,
|
|
|
1639
1659
|
} catch {
|
|
1640
1660
|
throw new SseFramingError("invalid utf-8 in model stream", "body_encoding");
|
|
1641
1661
|
}
|
|
1642
|
-
|
|
1643
|
-
frames.length = 0;
|
|
1644
|
-
framer.feed(tail, frames);
|
|
1645
|
-
for (const frame of frames) yield frame;
|
|
1646
|
-
}
|
|
1662
|
+
yield* framer.feed(tail);
|
|
1647
1663
|
framer.finish();
|
|
1648
1664
|
} finally {
|
|
1649
1665
|
disarmIdle();
|
|
@@ -1657,6 +1673,38 @@ async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTimeoutMs,
|
|
|
1657
1673
|
}
|
|
1658
1674
|
}
|
|
1659
1675
|
|
|
1676
|
+
// packages/agentkit-harness-node/src/native/model-stream-budget.mjs
|
|
1677
|
+
var ModelStreamLimitError = class extends ProtocolError {
|
|
1678
|
+
};
|
|
1679
|
+
function createModelStreamBudget(maxOutputBytes, maxToolBytes) {
|
|
1680
|
+
let outputBytes = 0;
|
|
1681
|
+
const toolBytes = /* @__PURE__ */ new WeakMap();
|
|
1682
|
+
const retain = (bytes, code = "stream_output_limit") => {
|
|
1683
|
+
if (outputBytes + bytes > maxOutputBytes) {
|
|
1684
|
+
throw new ModelStreamLimitError("assembled model output exceeded the byte limit", code);
|
|
1685
|
+
}
|
|
1686
|
+
outputBytes += bytes;
|
|
1687
|
+
};
|
|
1688
|
+
return {
|
|
1689
|
+
output(text) {
|
|
1690
|
+
retain(Buffer.byteLength(text));
|
|
1691
|
+
},
|
|
1692
|
+
// Indexed items also retain state when their payload is empty.
|
|
1693
|
+
slot() {
|
|
1694
|
+
retain(128);
|
|
1695
|
+
},
|
|
1696
|
+
tool(call, fragment) {
|
|
1697
|
+
const bytes = Buffer.byteLength(fragment);
|
|
1698
|
+
const total = (toolBytes.get(call) ?? 0) + bytes;
|
|
1699
|
+
if (total > maxToolBytes) {
|
|
1700
|
+
throw new ModelStreamLimitError("assembled tool input exceeded the byte limit", "tool_argument_limit");
|
|
1701
|
+
}
|
|
1702
|
+
retain(bytes, "tool_argument_limit");
|
|
1703
|
+
toolBytes.set(call, total);
|
|
1704
|
+
}
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1660
1708
|
// packages/agentkit-harness-node/src/native/model-replay.mjs
|
|
1661
1709
|
import { createHash as createHash4 } from "node:crypto";
|
|
1662
1710
|
import { canonical as canonical7, modelWireToolCall } from "@kingsoftcloud/agentkit-harness-core";
|
|
@@ -2668,7 +2716,7 @@ function chatReasoning(message) {
|
|
|
2668
2716
|
if (native && alias && native !== alias) throw new ProtocolError("conflicting private reasoning fields", "delta_invalid");
|
|
2669
2717
|
return native || alias || "";
|
|
2670
2718
|
}
|
|
2671
|
-
function createOpenAIStreamTurn(profile, binding) {
|
|
2719
|
+
function createOpenAIStreamTurn(profile, binding, budget) {
|
|
2672
2720
|
const compatibility = resolveProviderCompatibility(profile.providerCompatibilityPolicy, binding);
|
|
2673
2721
|
const modern = compatibility?.modern === true;
|
|
2674
2722
|
const finishOnEof = compatibility?.finishOnEof === true;
|
|
@@ -2768,6 +2816,8 @@ function createOpenAIStreamTurn(profile, binding) {
|
|
|
2768
2816
|
if (typeof content !== "string") throw new ProtocolError("invalid visible content delta", "delta_invalid");
|
|
2769
2817
|
const reasoning = chatReasoning(delta);
|
|
2770
2818
|
if (this.finish != null && reasoning) throw new ProtocolError("private reasoning continued after finish", "termination_conflict");
|
|
2819
|
+
budget?.output(content);
|
|
2820
|
+
budget?.output(reasoning);
|
|
2771
2821
|
if (captureReplay) this.reasoning += reasoning;
|
|
2772
2822
|
if (this.finish != null && (content || delta.tool_calls)) {
|
|
2773
2823
|
throw new ProtocolError("content continued after finish", "termination_conflict");
|
|
@@ -2788,7 +2838,8 @@ function createOpenAIStreamTurn(profile, binding) {
|
|
|
2788
2838
|
try {
|
|
2789
2839
|
if ("function_call" in delta) throw new ProtocolError("legacy function calls are unsupported");
|
|
2790
2840
|
this.addToolFragments(delta.tool_calls, emit);
|
|
2791
|
-
} catch {
|
|
2841
|
+
} catch (error) {
|
|
2842
|
+
if (error instanceof ModelStreamLimitError) throw error;
|
|
2792
2843
|
this.malformedTools = true;
|
|
2793
2844
|
}
|
|
2794
2845
|
},
|
|
@@ -2807,6 +2858,7 @@ function createOpenAIStreamTurn(profile, binding) {
|
|
|
2807
2858
|
if (typeof value !== "string" || !value || call[field] != null && call[field] !== value) {
|
|
2808
2859
|
throw new ProtocolError("conflicting tool identity", "identity_conflict");
|
|
2809
2860
|
}
|
|
2861
|
+
if (call[field] == null) budget?.output(value);
|
|
2810
2862
|
call[field] = value;
|
|
2811
2863
|
}
|
|
2812
2864
|
}
|
|
@@ -2817,11 +2869,16 @@ function createOpenAIStreamTurn(profile, binding) {
|
|
|
2817
2869
|
if (field in fn) {
|
|
2818
2870
|
if (fn[field] == null) continue;
|
|
2819
2871
|
if (typeof fn[field] !== "string") throw new ProtocolError("function fragment must be text");
|
|
2872
|
+
if (field === "arguments") budget?.tool(call, fn[field]);
|
|
2873
|
+
else budget?.output(fn[field]);
|
|
2820
2874
|
call.function[field] += fn[field];
|
|
2821
2875
|
}
|
|
2822
2876
|
}
|
|
2823
2877
|
}
|
|
2824
|
-
if (!this.tools.has(fragment.index))
|
|
2878
|
+
if (!this.tools.has(fragment.index)) {
|
|
2879
|
+
budget?.slot();
|
|
2880
|
+
this.tools.set(fragment.index, call);
|
|
2881
|
+
}
|
|
2825
2882
|
if (fn && "arguments" in fn && typeof fn.arguments === "string" && fn.arguments) {
|
|
2826
2883
|
emit({ kind: "tool_delta", text: fn.arguments, metadata: {
|
|
2827
2884
|
index: fragment.index,
|
|
@@ -3345,7 +3402,7 @@ function classifyAnthropicStreamError(errorObj) {
|
|
|
3345
3402
|
}
|
|
3346
3403
|
return { kind: "provider_terminal_error", failureKind: "invalid_response" };
|
|
3347
3404
|
}
|
|
3348
|
-
function createAnthropicStreamState(profile) {
|
|
3405
|
+
function createAnthropicStreamState(profile, budget) {
|
|
3349
3406
|
const captureReplay = profile.providerReplayMode !== "none";
|
|
3350
3407
|
const emitThinking = profile.providerThinkingDisplay ?? profile.providerReplayMode !== "none";
|
|
3351
3408
|
return {
|
|
@@ -3459,6 +3516,9 @@ function createAnthropicStreamState(profile) {
|
|
|
3459
3516
|
if (this.blockTypes.has(index) || this.closed.has(index)) {
|
|
3460
3517
|
throw new ProtocolError("duplicate content block index");
|
|
3461
3518
|
}
|
|
3519
|
+
budget?.slot();
|
|
3520
|
+
const { input: _input, ...replayMetadata } = block;
|
|
3521
|
+
budget?.output(stringifyModelJson2(replayMetadata));
|
|
3462
3522
|
this.blockTypes.set(index, blockType);
|
|
3463
3523
|
this.originals.set(index, deepCopy(block));
|
|
3464
3524
|
for (const field of ["text", "thinking", "signature"]) {
|
|
@@ -3487,6 +3547,7 @@ function createAnthropicStreamState(profile) {
|
|
|
3487
3547
|
}
|
|
3488
3548
|
if (Object.keys(block.input).length > 0) {
|
|
3489
3549
|
tool.arguments = stringifyModelJson2(block.input);
|
|
3550
|
+
budget?.tool(tool, tool.arguments);
|
|
3490
3551
|
tool.initialInput = true;
|
|
3491
3552
|
this.initialInputs.add(index);
|
|
3492
3553
|
}
|
|
@@ -3517,6 +3578,7 @@ function createAnthropicStreamState(profile) {
|
|
|
3517
3578
|
throw new ProtocolError("delta type does not match block type");
|
|
3518
3579
|
}
|
|
3519
3580
|
if (expected != null && previous == null && (expected === "text" || expected === "thinking")) {
|
|
3581
|
+
budget?.slot();
|
|
3520
3582
|
this.blockTypes.set(index, expected);
|
|
3521
3583
|
this.implicitIndexes.add(index);
|
|
3522
3584
|
this.originals.set(index, { type: expected });
|
|
@@ -3524,19 +3586,23 @@ function createAnthropicStreamState(profile) {
|
|
|
3524
3586
|
}
|
|
3525
3587
|
if (deltaType === "text_delta") {
|
|
3526
3588
|
if (typeof delta.text !== "string") throw new ProtocolError("invalid text delta");
|
|
3589
|
+
budget?.output(delta.text);
|
|
3527
3590
|
this.values.set(index, (this.values.get(index) || "") + delta.text);
|
|
3528
3591
|
} else if (deltaType === "thinking_delta") {
|
|
3529
3592
|
if (typeof delta.thinking !== "string") throw new ProtocolError("invalid thinking delta");
|
|
3593
|
+
budget?.output(delta.thinking);
|
|
3530
3594
|
this.values.set(index, (this.values.get(index) || "") + delta.thinking);
|
|
3531
3595
|
} else if (deltaType === "signature_delta") {
|
|
3532
3596
|
if (typeof delta.signature !== "string") throw new ProtocolError("invalid signature delta");
|
|
3533
3597
|
const original = this.originals.get(index) || { type: "thinking" };
|
|
3598
|
+
budget?.output(delta.signature);
|
|
3534
3599
|
original.signature = (original.signature || "") + delta.signature;
|
|
3535
3600
|
this.originals.set(index, original);
|
|
3536
3601
|
} else if (deltaType === "input_json_delta") {
|
|
3537
3602
|
if (typeof delta.partial_json !== "string") throw new ProtocolError("invalid input_json delta");
|
|
3538
3603
|
const tool = this.tools.get(index);
|
|
3539
3604
|
if (!tool || this.initialInputs.has(index)) throw new ProtocolError("tool delta without an open block");
|
|
3605
|
+
budget?.tool(tool, delta.partial_json);
|
|
3540
3606
|
tool.arguments += delta.partial_json;
|
|
3541
3607
|
if (delta.partial_json) {
|
|
3542
3608
|
emit({ kind: "tool_delta", text: delta.partial_json, metadata: {
|
|
@@ -4105,7 +4171,7 @@ function validateBufferedIdentity(payload) {
|
|
|
4105
4171
|
const identity = createWireIdentity();
|
|
4106
4172
|
identity.accept({ type: "response.created", response: payload });
|
|
4107
4173
|
}
|
|
4108
|
-
function createResponsesItems() {
|
|
4174
|
+
function createResponsesItems(budget) {
|
|
4109
4175
|
return {
|
|
4110
4176
|
indexes: /* @__PURE__ */ new Map(),
|
|
4111
4177
|
// output_index -> item_id
|
|
@@ -4117,6 +4183,10 @@ function createResponsesItems() {
|
|
|
4117
4183
|
const itemId = item != null ? identityOf(item.id) : identityOf(event.item_id);
|
|
4118
4184
|
if ("item_id" in event && identityOf(event.item_id) !== itemId) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4119
4185
|
const index = indexOf(event, "output_index");
|
|
4186
|
+
if ((index != null || item != null || kind) && !this.itemIndexes.has(itemId) && !this.kinds.has(itemId)) {
|
|
4187
|
+
budget?.slot();
|
|
4188
|
+
budget?.output(itemId);
|
|
4189
|
+
}
|
|
4120
4190
|
if (index != null) {
|
|
4121
4191
|
if (this.indexes.get(index) != null && this.indexes.get(index) !== itemId) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4122
4192
|
if (this.itemIndexes.get(itemId) != null && this.itemIndexes.get(itemId) !== index) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
@@ -4142,7 +4212,7 @@ var DELTA_KINDS = {
|
|
|
4142
4212
|
function createContentPart(kind) {
|
|
4143
4213
|
return { kind, text: "", closed: false };
|
|
4144
4214
|
}
|
|
4145
|
-
function createResponsesContent(items) {
|
|
4215
|
+
function createResponsesContent(items, budget) {
|
|
4146
4216
|
const state = {
|
|
4147
4217
|
items,
|
|
4148
4218
|
// shared ResponsesItems
|
|
@@ -4167,6 +4237,7 @@ function createResponsesContent(items) {
|
|
|
4167
4237
|
return previous;
|
|
4168
4238
|
}
|
|
4169
4239
|
if (item.closed) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4240
|
+
budget?.slot();
|
|
4170
4241
|
const part = createContentPart(kind);
|
|
4171
4242
|
item.parts.set(partKey, part);
|
|
4172
4243
|
return part;
|
|
@@ -4179,6 +4250,7 @@ function createResponsesContent(items) {
|
|
|
4179
4250
|
const part = this.getPart(item, group, index, kind);
|
|
4180
4251
|
if (delta) {
|
|
4181
4252
|
if (part.closed) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4253
|
+
budget?.output(text);
|
|
4182
4254
|
part.text += text;
|
|
4183
4255
|
} else {
|
|
4184
4256
|
this.snapshotPart(part, text, closed);
|
|
@@ -4189,6 +4261,7 @@ function createResponsesContent(items) {
|
|
|
4189
4261
|
if (part.closed && text !== part.text || !text.startsWith(part.text)) {
|
|
4190
4262
|
throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4191
4263
|
}
|
|
4264
|
+
budget?.output(text.slice(part.text.length));
|
|
4192
4265
|
part.text = text;
|
|
4193
4266
|
part.closed = part.closed || closed;
|
|
4194
4267
|
},
|
|
@@ -4307,11 +4380,13 @@ function createResponsesContent(items) {
|
|
|
4307
4380
|
throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4308
4381
|
}
|
|
4309
4382
|
tail = text.slice(previous.length);
|
|
4383
|
+
budget?.output(tail);
|
|
4310
4384
|
this[attr] = text;
|
|
4311
4385
|
this.legacyClosed.add(attr);
|
|
4312
4386
|
} else {
|
|
4313
4387
|
if (this.legacyClosed.has(attr)) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4314
4388
|
tail = text;
|
|
4389
|
+
budget?.output(tail);
|
|
4315
4390
|
this[attr] = previous + text;
|
|
4316
4391
|
}
|
|
4317
4392
|
const indexed = attr === "legacyText" ? this.emittedText : this.emittedReasoning;
|
|
@@ -4401,8 +4476,8 @@ function sealTool(tool) {
|
|
|
4401
4476
|
identityOf(tool.name);
|
|
4402
4477
|
tool.closed = true;
|
|
4403
4478
|
}
|
|
4404
|
-
function createResponsesToolCalls() {
|
|
4405
|
-
const items = createResponsesItems();
|
|
4479
|
+
function createResponsesToolCalls(budget) {
|
|
4480
|
+
const items = createResponsesItems(budget);
|
|
4406
4481
|
return {
|
|
4407
4482
|
items,
|
|
4408
4483
|
calls: /* @__PURE__ */ new Map(),
|
|
@@ -4424,7 +4499,11 @@ function createResponsesToolCalls() {
|
|
|
4424
4499
|
if (current != null) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4425
4500
|
current = createWireTool();
|
|
4426
4501
|
pinToolIdentity(current, item, "call_id");
|
|
4427
|
-
if ("arguments" in item)
|
|
4502
|
+
if ("arguments" in item) {
|
|
4503
|
+
const arguments_ = optionalText(item.arguments);
|
|
4504
|
+
budget?.tool(current, arguments_);
|
|
4505
|
+
current.arguments = arguments_;
|
|
4506
|
+
}
|
|
4428
4507
|
this.calls.set(key, current);
|
|
4429
4508
|
return null;
|
|
4430
4509
|
}
|
|
@@ -4438,6 +4517,7 @@ function createResponsesToolCalls() {
|
|
|
4438
4517
|
if (!arguments_.startsWith(current.arguments) || (current.closed || current.argumentsDone) && arguments_ !== current.arguments) {
|
|
4439
4518
|
throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4440
4519
|
}
|
|
4520
|
+
budget?.tool(current, arguments_.slice(current.arguments.length));
|
|
4441
4521
|
current.arguments = arguments_;
|
|
4442
4522
|
}
|
|
4443
4523
|
if (current.closed) return null;
|
|
@@ -4449,10 +4529,13 @@ function createResponsesToolCalls() {
|
|
|
4449
4529
|
const current = this.calls.get(key);
|
|
4450
4530
|
if (current == null || current.closed || current.argumentsDone) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4451
4531
|
if (type.endsWith(".delta")) {
|
|
4452
|
-
|
|
4532
|
+
const delta = optionalText(event.delta);
|
|
4533
|
+
budget?.tool(current, delta);
|
|
4534
|
+
current.arguments += delta;
|
|
4453
4535
|
} else {
|
|
4454
4536
|
const arguments_ = optionalText(event.arguments);
|
|
4455
4537
|
if (!arguments_.startsWith(current.arguments)) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
4538
|
+
budget?.tool(current, arguments_.slice(current.arguments.length));
|
|
4456
4539
|
current.arguments = arguments_;
|
|
4457
4540
|
current.argumentsDone = true;
|
|
4458
4541
|
}
|
|
@@ -4512,11 +4595,11 @@ function createWireIdentity() {
|
|
|
4512
4595
|
}
|
|
4513
4596
|
};
|
|
4514
4597
|
}
|
|
4515
|
-
function createResponsesStreamState(profile) {
|
|
4598
|
+
function createResponsesStreamState(profile, budget) {
|
|
4516
4599
|
const captureReplay = profile.providerReplayMode !== "none";
|
|
4517
4600
|
const emitThinking = profile.providerThinkingDisplay ?? profile.providerReplayMode !== "none";
|
|
4518
|
-
const toolItems = createResponsesToolCalls();
|
|
4519
|
-
const contentItems = createResponsesContent(toolItems.items);
|
|
4601
|
+
const toolItems = createResponsesToolCalls(budget);
|
|
4602
|
+
const contentItems = createResponsesContent(toolItems.items, budget);
|
|
4520
4603
|
const identity = createWireIdentity();
|
|
4521
4604
|
return {
|
|
4522
4605
|
text: "",
|
|
@@ -4843,6 +4926,8 @@ function observeModelTransportPort(generate) {
|
|
|
4843
4926
|
|
|
4844
4927
|
// packages/agentkit-harness-node/src/native/model-port.mjs
|
|
4845
4928
|
var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
|
|
4929
|
+
var DEFAULT_MAX_FRAME_BYTES = 6 * DEFAULT_MAX_BYTES + 64 * 1024;
|
|
4930
|
+
var MAX_TOOL_ARGUMENT_BYTES = 8 * 1024 * 1024;
|
|
4846
4931
|
var DEFAULT_IDLE_MS = 18e4;
|
|
4847
4932
|
function nativeModelRecoveryPolicy({ protocol, parameters = {} } = {}) {
|
|
4848
4933
|
return ["openai-chat", "openai-responses", "anthropic-messages"].includes(protocol) && parameters !== null && typeof parameters === "object" && !Array.isArray(parameters) && Object.keys(parameters).length === 0 ? "pure-inference/v1" : "manual";
|
|
@@ -4856,7 +4941,7 @@ var OverflowError = class extends Error {
|
|
|
4856
4941
|
function createNativeModelPort({
|
|
4857
4942
|
resolveProfile,
|
|
4858
4943
|
fetchImpl = fetch,
|
|
4859
|
-
maxResponseBytes
|
|
4944
|
+
maxResponseBytes,
|
|
4860
4945
|
idleTimeoutMs = DEFAULT_IDLE_MS
|
|
4861
4946
|
} = {}) {
|
|
4862
4947
|
if (typeof resolveProfile !== "function") {
|
|
@@ -4865,9 +4950,14 @@ function createNativeModelPort({
|
|
|
4865
4950
|
if (typeof fetchImpl !== "function") {
|
|
4866
4951
|
throw new TypeError("createNativeModelPort requires a fetchImpl function");
|
|
4867
4952
|
}
|
|
4868
|
-
|
|
4953
|
+
const maxBytes = maxResponseBytes === void 0 ? DEFAULT_MAX_BYTES : maxResponseBytes;
|
|
4954
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new RangeError("maxResponseBytes must be a positive safe integer");
|
|
4869
4955
|
if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs <= 0) throw new RangeError("idleTimeoutMs must be positive and finite");
|
|
4870
|
-
const
|
|
4956
|
+
const streamBounds = {
|
|
4957
|
+
maxFrameBytes: maxResponseBytes ?? DEFAULT_MAX_FRAME_BYTES,
|
|
4958
|
+
maxOutputBytes: maxBytes,
|
|
4959
|
+
maxBytes: maxResponseBytes
|
|
4960
|
+
};
|
|
4871
4961
|
const idleTimeout = idleTimeoutMs;
|
|
4872
4962
|
return observeModelTransportPort(async (request, emitEvent, observation) => {
|
|
4873
4963
|
if (!request || typeof request !== "object" || !request.profile) {
|
|
@@ -4931,16 +5021,10 @@ function createNativeModelPort({
|
|
|
4931
5021
|
clearTimer(overallTimer);
|
|
4932
5022
|
overallTimer = null;
|
|
4933
5023
|
}
|
|
4934
|
-
return await streamResponse(
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
|
|
4938
|
-
emitEvent,
|
|
4939
|
-
internal,
|
|
4940
|
-
maxBytes,
|
|
4941
|
-
idlePolicy && overallMs > 0 ? Math.min(idleTimeout, overallMs) : idleTimeout,
|
|
4942
|
-
observation
|
|
4943
|
-
);
|
|
5024
|
+
return await streamResponse(response, request, binding, emitEvent, internal, {
|
|
5025
|
+
...streamBounds,
|
|
5026
|
+
idleTimeoutMs: idlePolicy && overallMs > 0 ? Math.min(idleTimeout, overallMs) : idleTimeout
|
|
5027
|
+
}, observation);
|
|
4944
5028
|
}
|
|
4945
5029
|
observation.phase("buffered");
|
|
4946
5030
|
return await bufferedResponse(response, request, binding, maxBytes, emitEvent, observation);
|
|
@@ -4956,10 +5040,11 @@ function createNativeModelPort({
|
|
|
4956
5040
|
}
|
|
4957
5041
|
});
|
|
4958
5042
|
}
|
|
4959
|
-
async function streamResponse(response, request, binding, emit, internal,
|
|
5043
|
+
async function streamResponse(response, request, binding, emit, internal, streamBounds, observation) {
|
|
4960
5044
|
const profile = request.profile;
|
|
4961
5045
|
const idlePolicy = profile.streaming !== false && profile.streamTimeoutPolicy === "idle/v1";
|
|
4962
|
-
const
|
|
5046
|
+
const budget = createModelStreamBudget(streamBounds.maxOutputBytes, streamBounds.maxBytes ?? MAX_TOOL_ARGUMENT_BYTES);
|
|
5047
|
+
const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile, budget) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile, budget) : createOpenAIStreamTurn(profile, binding, budget);
|
|
4963
5048
|
const abort = (reason) => internal.abort(reason);
|
|
4964
5049
|
let frameIndex = -1;
|
|
4965
5050
|
let reasoning = request.purpose == null || request.purpose === "task" ? "" : null;
|
|
@@ -4993,7 +5078,7 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4993
5078
|
}
|
|
4994
5079
|
);
|
|
4995
5080
|
try {
|
|
4996
|
-
for await (const frame of readModelSse(response.body, {
|
|
5081
|
+
for await (const frame of readModelSse(response.body, { ...streamBounds, abort, observeBytes: observation.bytes })) {
|
|
4997
5082
|
if (idlePolicy && !frame.data.trim()) continue;
|
|
4998
5083
|
frameIndex++;
|
|
4999
5084
|
observation.frame();
|
|
@@ -5018,9 +5103,27 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
5018
5103
|
if (error instanceof IdleTimeout) {
|
|
5019
5104
|
return failed(state.finalize({ errorKind: "provider_retryable_error", failureKind: "request_timeout" }), "stream_timeout");
|
|
5020
5105
|
}
|
|
5106
|
+
if ((error instanceof SseFramingError || error instanceof ModelStreamLimitError) && streamBounds.maxBytes === void 0 && ["stream_frame_limit", "stream_output_limit"].includes(error.code) && (request.purpose == null || request.purpose === "task") && !state.refused && nativeModelRecoveryPolicy(binding) === "pure-inference/v1") {
|
|
5107
|
+
const partial = state.finalize({ errorKind: "output_limit" });
|
|
5108
|
+
return failed({
|
|
5109
|
+
...partial,
|
|
5110
|
+
toolCalls: [],
|
|
5111
|
+
textCommitVersion: "provider-finished-text/v1",
|
|
5112
|
+
outputBoundary: partial.text.trim() ? "assistant-text/v1" : "no-visible-output/v1"
|
|
5113
|
+
}, error.code);
|
|
5114
|
+
}
|
|
5021
5115
|
if (error instanceof SseFramingError) {
|
|
5022
5116
|
return failed(state.finalize({ errorKind: "provider_terminal_error", failureKind: "invalid_response" }), protocolCode(error));
|
|
5023
5117
|
}
|
|
5118
|
+
if (error instanceof ModelStreamLimitError) {
|
|
5119
|
+
const task = request.purpose == null || request.purpose === "task";
|
|
5120
|
+
const retryable = error.code === "tool_argument_limit" && task && !state.refused && nativeModelRecoveryPolicy(binding) === "pure-inference/v1";
|
|
5121
|
+
const result2 = state.finalize({
|
|
5122
|
+
errorKind: retryable ? "malformed_tool_call" : "provider_terminal_error",
|
|
5123
|
+
failureKind: "invalid_response"
|
|
5124
|
+
});
|
|
5125
|
+
return failed({ ...result2, toolCalls: [] }, error.code);
|
|
5126
|
+
}
|
|
5024
5127
|
if (error instanceof ProtocolError) {
|
|
5025
5128
|
if (error.streamError) {
|
|
5026
5129
|
return failed(
|
|
@@ -5114,7 +5217,7 @@ function protocolCode(error) {
|
|
|
5114
5217
|
return (error instanceof ProtocolError || error instanceof SseFramingError) && MODEL_FAILURE_CODES.includes(error.code) ? error.code : "protocol_invalid";
|
|
5115
5218
|
}
|
|
5116
5219
|
function withFailure(result, binding, phase, code, fields2 = {}) {
|
|
5117
|
-
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind) && !(result.kind === "output_limit" &&
|
|
5220
|
+
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind) && !(result.kind === "output_limit" && ["reasoning_repetition", "stream_frame_limit", "stream_output_limit"].includes(code)) && !(result.kind === "context_overflow" && fields2.gateway)) return result;
|
|
5118
5221
|
const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
|
|
5119
5222
|
return { ...result, failureDiagnostic: { contract: fields2.gateway ? "model-failure-diagnostic/v4" : fields2.providerError ? "model-failure-diagnostic/v3" : fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
|
|
5120
5223
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kingsoftcloud/agentkit-harness-node",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.28",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Standalone Native Harness Node adapters: a durable SQLite run store, a one-request model HTTP port, and a minimal versioned JSON-RPC 2.0 over NDJSON process entry. Reuses the shared Native adapter implementations and externalizes @kingsoftcloud/agentkit-harness-core; depends on no Studio/DSH code at runtime.",
|
|
@@ -154,7 +154,7 @@
|
|
|
154
154
|
"src/package-integrity.mjs"
|
|
155
155
|
],
|
|
156
156
|
"dependencies": {
|
|
157
|
-
"@kingsoftcloud/agentkit-harness-core": "0.0.
|
|
157
|
+
"@kingsoftcloud/agentkit-harness-core": "0.0.28",
|
|
158
158
|
"@astral-sh/ruff-wasm-nodejs": "0.16.8",
|
|
159
159
|
"parse5": "7.3.0",
|
|
160
160
|
"playwright-core": "1.58.2",
|
|
@@ -34,7 +34,7 @@ export function e2bCommandToolDefinitions(foregroundTimeoutSeconds = 300) {
|
|
|
34
34
|
&& foregroundTimeoutSeconds <= 86400, 'e2b_command_foreground_limit_invalid');
|
|
35
35
|
return [
|
|
36
36
|
base('sandbox_status', 'Report the bound E2B remote sandbox backend and its execution boundary.', {}, [], false, 10000),
|
|
37
|
-
{ ...base('run_command', 'Run a command inside the bound E2B remote sandbox.
|
|
37
|
+
{ ...base('run_command', 'Run a command inside the bound E2B remote sandbox. Background commands and foreground commands with large output return an owned task_id for read_command_output; stop_command requests cancellation. The sandbox is remote — cwd is a remote path, not a host-local one. An unknown outcome is never re-launched.',
|
|
38
38
|
{ command: { type: 'string', minLength: 1 }, cwd: { anyOf: [{ type: 'string' }, { type: 'null' }] },
|
|
39
39
|
timeout: schemas.nullableSeconds, env: { anyOf: [{ type: 'object', additionalProperties: { type: 'string' } }, { type: 'null' }] },
|
|
40
40
|
background: { type: 'boolean' }, background_timeout: schemas.nullableSeconds },
|
|
@@ -353,11 +353,19 @@ function createCommandTools({ sessionId, owner, storeFactory,
|
|
|
353
353
|
}
|
|
354
354
|
const guardResult = guard(request, before, false, known);
|
|
355
355
|
if (guardResult) return guardResult;
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
356
|
+
let pageBytes = args.max_bytes ?? 65536;
|
|
357
|
+
for (;;) {
|
|
358
|
+
const output = handle.readOutput({ stdoutCursor: args.stdout_cursor ?? 0,
|
|
359
|
+
stderrCursor: args.stderr_cursor ?? 0, maxBytes: pageBytes });
|
|
360
|
+
const uncertain = output.status === 'unknown' || output.evidenceIncomplete;
|
|
361
|
+
known = { status: uncertain ? 'uncertain' : 'ok', content: { ok: !uncertain, task_id: args.task_id,
|
|
362
|
+
...commandOutput(output), ...originLocator(before, undefined, taskId) } };
|
|
363
|
+
if (Buffer.byteLength(canonical(known.content)) <= maxOutputBytes) break;
|
|
364
|
+
// Shrink the actual read window, so the cursor never skips bytes
|
|
365
|
+
// discarded while fitting the tool-result budget.
|
|
366
|
+
if (pageBytes === 4) return errorResult('e2b_command_output_window_budget_exceeded', { task_id: taskId });
|
|
367
|
+
pageBytes = Math.max(4, Math.floor(pageBytes / 2));
|
|
368
|
+
}
|
|
361
369
|
}
|
|
362
370
|
const afterRead = guard(request, before, dispatched, known); if (afterRead) return afterRead;
|
|
363
371
|
return await budget(known, request, before, undefined, taskId);
|
|
@@ -440,14 +448,16 @@ function createCommandTools({ sessionId, owner, storeFactory,
|
|
|
440
448
|
const guardResult3 = guard(request, before, dispatched, known);
|
|
441
449
|
if (guardResult3) return guardResult3;
|
|
442
450
|
// The model sees a bounded preview, but its artifact must contain all
|
|
443
|
-
// retained foreground output
|
|
451
|
+
// retained foreground output while it fits the attachment budget.
|
|
452
|
+
// Larger output stays available in the existing command spool.
|
|
444
453
|
const stdout = [], stderr = []; let stdoutCursor = 0, stderrCursor = 0, bytes = 0;
|
|
454
|
+
let pagedOutput = false;
|
|
445
455
|
for (;;) {
|
|
446
456
|
const rejected = guard(request, before, dispatched, known); if (rejected) return rejected;
|
|
447
457
|
output = syncValue(handle.readOutput({ stdoutCursor, stderrCursor, maxBytes: 65536 }));
|
|
448
458
|
invariant(typeof output.stdout === 'string' && typeof output.stderr === 'string', 'e2b_command_output_invalid');
|
|
449
459
|
bytes += Buffer.byteLength(output.stdout) + Buffer.byteLength(output.stderr);
|
|
450
|
-
|
|
460
|
+
if (bytes > 16 * 1024 * 1024) { pagedOutput = true; break; }
|
|
451
461
|
stdout.push(output.stdout); stderr.push(output.stderr);
|
|
452
462
|
if (!output.outputMayBeTruncated) break;
|
|
453
463
|
invariant(Number.isSafeInteger(output.stdoutCursor) && output.stdoutCursor >= stdoutCursor
|
|
@@ -455,7 +465,8 @@ function createCommandTools({ sessionId, owner, storeFactory,
|
|
|
455
465
|
&& (output.stdoutCursor > stdoutCursor || output.stderrCursor > stderrCursor), 'e2b_command_output_cursor_stalled');
|
|
456
466
|
stdoutCursor = output.stdoutCursor; stderrCursor = output.stderrCursor;
|
|
457
467
|
}
|
|
458
|
-
output = { ...output, stdout: stdout
|
|
468
|
+
output = { ...output, stdout: pagedOutput ? utf8Preview(stdout[0], 512) : stdout.join(''),
|
|
469
|
+
stderr: pagedOutput ? utf8Preview(stderr[0], 512) : stderr.join('') };
|
|
459
470
|
const uncertain = output.status === 'unknown' || output.evidenceIncomplete
|
|
460
471
|
|| !TERMINAL.has(output.status)
|
|
461
472
|
|| (['timed_out', 'canceled'].includes(output.status) && output.exitCode === null);
|
|
@@ -467,7 +478,13 @@ function createCommandTools({ sessionId, owner, storeFactory,
|
|
|
467
478
|
exit_code: uncertain ? null : output.exitCode,
|
|
468
479
|
observed_exit_code: uncertain ? output.exitCode : null,
|
|
469
480
|
evidence_incomplete: uncertain,
|
|
470
|
-
...(
|
|
481
|
+
...(pagedOutput ? { output_may_be_truncated: true, stdout_cursor: 0, stderr_cursor: 0,
|
|
482
|
+
...(!ownership.codeOnly ? { instruction: 'Read remaining output with read_command_output. Do not rerun the command.' } : {}) } : {}),
|
|
483
|
+
...(output.outcomeReason ? { outcome_reason: output.outcomeReason } : {}) },
|
|
484
|
+
...(pagedOutput && !uncertain && !ownership.codeOnly ? {
|
|
485
|
+
backgroundCommandRef: ownership.backgroundRef(before, taskId), backgroundCommandFinished: true,
|
|
486
|
+
} : {}) };
|
|
487
|
+
if (pagedOutput) return guard(request, before, dispatched, known) ?? boundResult(known);
|
|
471
488
|
}
|
|
472
489
|
const afterOutput = guard(request, before, dispatched, known); if (afterOutput) return afterOutput;
|
|
473
490
|
return await budget(known, request, before, sandboxId, taskId);
|