@kingsoftcloud/agentkit-harness-node 0.0.19 → 0.0.20
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 +31 -23
- package/dist/index.mjs +77 -26
- package/dist/rpc-entry.mjs +77 -26
- package/package.json +2 -2
- package/src/native/engine-client.mjs +13 -3
- package/src/native/engine-delivery-evidence.mjs +70 -3
- package/src/native/engine-runtime.mjs +33 -9
- package/src/native/engine-server.mjs +92 -11
- package/src/native/engine-service.mjs +17 -10
- package/src/native/model-port.mjs +72 -31
- package/src/native/native-terminal-failure.mjs +15 -4
- package/src/native/workspace-tools.mjs +32 -8
package/dist/index.mjs
CHANGED
|
@@ -4688,7 +4688,13 @@ function buildNativeModelRequest(binding, request) {
|
|
|
4688
4688
|
}
|
|
4689
4689
|
|
|
4690
4690
|
// packages/agentkit-harness-node/src/native/model-port.mjs
|
|
4691
|
-
import {
|
|
4691
|
+
import {
|
|
4692
|
+
parseModelJson as parseModelJson4,
|
|
4693
|
+
MODEL_FAILURE_CODES,
|
|
4694
|
+
MODEL_GATEWAY_ERROR_CODES,
|
|
4695
|
+
MODEL_GATEWAY_ERROR_TYPES,
|
|
4696
|
+
isModelGatewayRequestId
|
|
4697
|
+
} from "@kingsoftcloud/agentkit-harness-core";
|
|
4692
4698
|
|
|
4693
4699
|
// packages/agentkit-harness-node/src/native/model-transport-observation.mjs
|
|
4694
4700
|
function modelTransportObservation(now = () => performance.now()) {
|
|
@@ -4815,10 +4821,12 @@ function createNativeModelPort({
|
|
|
4815
4821
|
try {
|
|
4816
4822
|
if (!response.ok) {
|
|
4817
4823
|
observation.phase("http-error");
|
|
4818
|
-
const
|
|
4824
|
+
const body = await readHttpError(response, maxBytes);
|
|
4825
|
+
const result = classifyHttpError(response, body);
|
|
4826
|
+
const gateway = httpGatewayDiagnostic(response, body);
|
|
4819
4827
|
request.signal?.throwIfAborted();
|
|
4820
4828
|
const code = response.status === 401 ? "http_authentication" : response.status === 403 ? "http_permission" : response.status === 429 ? "http_rate_limit" : response.status === 408 ? "http_timeout" : response.status >= 500 ? "http_server" : "http_client";
|
|
4821
|
-
return withFailure(result, binding, "http-error", code, { httpStatus: response.status });
|
|
4829
|
+
return withFailure(result, binding, "http-error", code, { httpStatus: response.status, ...gateway ? { gateway } : {} });
|
|
4822
4830
|
}
|
|
4823
4831
|
const contentType = response.headers.get("content-type") || "";
|
|
4824
4832
|
if (contentType.includes("text/event-stream")) {
|
|
@@ -4859,6 +4867,25 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4859
4867
|
const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
|
|
4860
4868
|
const abort = (reason) => internal.abort(reason);
|
|
4861
4869
|
let frameIndex = -1;
|
|
4870
|
+
let reasoning = request.purpose == null || request.purpose === "task" ? "" : null;
|
|
4871
|
+
let sinceCheck = 0;
|
|
4872
|
+
let repetition = false;
|
|
4873
|
+
const observe = (event) => {
|
|
4874
|
+
if (event.kind === "text" && event.text.trim() || event.kind === "tool_delta") reasoning = null;
|
|
4875
|
+
if (reasoning !== null && event.kind === "thinking" && event.text) {
|
|
4876
|
+
reasoning = (reasoning + event.text).slice(-1024);
|
|
4877
|
+
sinceCheck += event.text.length;
|
|
4878
|
+
if (reasoning.length === 1024 && sinceCheck >= 128) {
|
|
4879
|
+
sinceCheck = 0;
|
|
4880
|
+
for (let size = 1; size <= 64; size++) {
|
|
4881
|
+
if (reasoning.slice(size) !== reasoning.slice(0, -size)) continue;
|
|
4882
|
+
repetition = true;
|
|
4883
|
+
break;
|
|
4884
|
+
}
|
|
4885
|
+
}
|
|
4886
|
+
}
|
|
4887
|
+
emit(event);
|
|
4888
|
+
};
|
|
4862
4889
|
const failed = (result2, code, fields2 = {}) => withFailure(
|
|
4863
4890
|
result2,
|
|
4864
4891
|
binding,
|
|
@@ -4875,7 +4902,19 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4875
4902
|
if (idlePolicy && !frame.data.trim()) continue;
|
|
4876
4903
|
frameIndex++;
|
|
4877
4904
|
observation.frame();
|
|
4878
|
-
state.consume(frame,
|
|
4905
|
+
state.consume(frame, observe);
|
|
4906
|
+
if (repetition && reasoning !== null && !state.done) {
|
|
4907
|
+
abort(new Error("reasoning_repetition"));
|
|
4908
|
+
return failed({
|
|
4909
|
+
kind: "output_limit",
|
|
4910
|
+
text: "",
|
|
4911
|
+
toolCalls: [],
|
|
4912
|
+
usage: emptyUsage(),
|
|
4913
|
+
usageReported: false,
|
|
4914
|
+
textCommitVersion: "provider-finished-text/v1",
|
|
4915
|
+
outputBoundary: "no-visible-output/v1"
|
|
4916
|
+
}, "reasoning_repetition");
|
|
4917
|
+
}
|
|
4879
4918
|
if (idlePolicy) emit({ kind: "activity", text: "" });
|
|
4880
4919
|
if (state.done) break;
|
|
4881
4920
|
}
|
|
@@ -4937,37 +4976,41 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
|
|
|
4937
4976
|
return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
|
|
4938
4977
|
}
|
|
4939
4978
|
}
|
|
4940
|
-
|
|
4979
|
+
function classifyHttpError(response, body) {
|
|
4941
4980
|
const status = response.status;
|
|
4942
4981
|
const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
|
|
4943
4982
|
if (status === 408) return retryableResult("request_timeout", retryAfterMs);
|
|
4944
4983
|
if (status === 429) return retryableResult("rate_limit", retryAfterMs);
|
|
4945
4984
|
if (status >= 500 && status <= 599) return retryableResult("server_error", retryAfterMs);
|
|
4946
4985
|
if (status === 403) return { kind: "policy_abort", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
4947
|
-
if (status === 400) {
|
|
4948
|
-
|
|
4949
|
-
const bodyText = await readBoundedText(response, maxBytes);
|
|
4950
|
-
if (hasContextLengthExceeded(bodyText)) {
|
|
4951
|
-
return { kind: "context_overflow", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
4952
|
-
}
|
|
4953
|
-
} catch {
|
|
4954
|
-
}
|
|
4955
|
-
return terminalResult("client_error");
|
|
4986
|
+
if (status === 400 && (body?.error?.code === "context_length_exceeded" || body?.error?.type === "context_length_exceeded")) {
|
|
4987
|
+
return { kind: "context_overflow", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
4956
4988
|
}
|
|
4957
4989
|
return terminalResult("client_error");
|
|
4958
4990
|
}
|
|
4959
|
-
function
|
|
4991
|
+
async function readHttpError(response, maxBytes) {
|
|
4992
|
+
if (response.status === 429) return null;
|
|
4993
|
+
const contextCheck = response.status === 400;
|
|
4994
|
+
if (!contextCheck && !response.body?.getReader) return null;
|
|
4960
4995
|
try {
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
}
|
|
4996
|
+
return parseModelJson4(await readBoundedText(
|
|
4997
|
+
response,
|
|
4998
|
+
contextCheck ? maxBytes : Math.min(maxBytes, 8192),
|
|
4999
|
+
void 0,
|
|
5000
|
+
contextCheck ? void 0 : AbortSignal.timeout(200)
|
|
5001
|
+
));
|
|
4968
5002
|
} catch {
|
|
5003
|
+
return null;
|
|
4969
5004
|
}
|
|
4970
|
-
|
|
5005
|
+
}
|
|
5006
|
+
function httpGatewayDiagnostic(response, body) {
|
|
5007
|
+
const diagnostic = {};
|
|
5008
|
+
const error = body?.error && typeof body.error === "object" ? body.error : body;
|
|
5009
|
+
if (MODEL_GATEWAY_ERROR_CODES.includes(error?.code) || Number.isInteger(error?.code) && error.code >= 400 && error.code <= 599) diagnostic.code = error.code;
|
|
5010
|
+
if (MODEL_GATEWAY_ERROR_TYPES.includes(error?.type)) diagnostic.type = error.type;
|
|
5011
|
+
const requestId = ["x-request-id", "request-id", "x-ksc-request-id"].map((header) => response.headers.get(header)).find(isModelGatewayRequestId);
|
|
5012
|
+
if (requestId) diagnostic.requestId = requestId;
|
|
5013
|
+
return Object.keys(diagnostic).length ? diagnostic : null;
|
|
4971
5014
|
}
|
|
4972
5015
|
function terminalResult(failureKind) {
|
|
4973
5016
|
return { kind: "provider_terminal_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
|
|
@@ -4976,9 +5019,9 @@ function protocolCode(error) {
|
|
|
4976
5019
|
return (error instanceof ProtocolError || error instanceof SseFramingError) && MODEL_FAILURE_CODES.includes(error.code) ? error.code : "protocol_invalid";
|
|
4977
5020
|
}
|
|
4978
5021
|
function withFailure(result, binding, phase, code, fields2 = {}) {
|
|
4979
|
-
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind)) return result;
|
|
5022
|
+
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind) && !(result.kind === "output_limit" && code === "reasoning_repetition") && !(result.kind === "context_overflow" && fields2.gateway)) return result;
|
|
4980
5023
|
const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
|
|
4981
|
-
return { ...result, failureDiagnostic: { contract: fields2.providerError ? "model-failure-diagnostic/v3" : fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
|
|
5024
|
+
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 } };
|
|
4982
5025
|
}
|
|
4983
5026
|
function retryableResult(failureKind, retryAfterMs = null) {
|
|
4984
5027
|
const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
|
|
@@ -4998,7 +5041,7 @@ function cancelBody(response) {
|
|
|
4998
5041
|
} catch {
|
|
4999
5042
|
}
|
|
5000
5043
|
}
|
|
5001
|
-
async function readBoundedText(response, maxBytes, observeBytes) {
|
|
5044
|
+
async function readBoundedText(response, maxBytes, observeBytes, signal) {
|
|
5002
5045
|
const body = response.body;
|
|
5003
5046
|
if (body == null) return "";
|
|
5004
5047
|
const reader = body.getReader ? body.getReader() : null;
|
|
@@ -5006,9 +5049,16 @@ async function readBoundedText(response, maxBytes, observeBytes) {
|
|
|
5006
5049
|
let total = 0;
|
|
5007
5050
|
const chunks = [];
|
|
5008
5051
|
if (reader) {
|
|
5052
|
+
const abort = () => {
|
|
5053
|
+
void reader.cancel().catch(() => {
|
|
5054
|
+
});
|
|
5055
|
+
};
|
|
5009
5056
|
try {
|
|
5057
|
+
signal?.throwIfAborted();
|
|
5058
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
5010
5059
|
while (true) {
|
|
5011
5060
|
const { value, done } = await reader.read();
|
|
5061
|
+
signal?.throwIfAborted();
|
|
5012
5062
|
if (done) break;
|
|
5013
5063
|
if (!value) continue;
|
|
5014
5064
|
if (!(value instanceof Uint8Array) && !(value instanceof ArrayBuffer)) throw new ProtocolError("body requires bytes");
|
|
@@ -5020,6 +5070,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
|
|
|
5020
5070
|
chunks.push(decoder.decode());
|
|
5021
5071
|
return chunks.join("");
|
|
5022
5072
|
} finally {
|
|
5073
|
+
signal?.removeEventListener("abort", abort);
|
|
5023
5074
|
reader.releaseLock?.();
|
|
5024
5075
|
}
|
|
5025
5076
|
}
|
package/dist/rpc-entry.mjs
CHANGED
|
@@ -4699,7 +4699,13 @@ function buildNativeModelRequest(binding, request) {
|
|
|
4699
4699
|
}
|
|
4700
4700
|
|
|
4701
4701
|
// packages/agentkit-harness-node/src/native/model-port.mjs
|
|
4702
|
-
import {
|
|
4702
|
+
import {
|
|
4703
|
+
parseModelJson as parseModelJson4,
|
|
4704
|
+
MODEL_FAILURE_CODES,
|
|
4705
|
+
MODEL_GATEWAY_ERROR_CODES,
|
|
4706
|
+
MODEL_GATEWAY_ERROR_TYPES,
|
|
4707
|
+
isModelGatewayRequestId
|
|
4708
|
+
} from "@kingsoftcloud/agentkit-harness-core";
|
|
4703
4709
|
|
|
4704
4710
|
// packages/agentkit-harness-node/src/native/model-transport-observation.mjs
|
|
4705
4711
|
function modelTransportObservation(now = () => performance.now()) {
|
|
@@ -4826,10 +4832,12 @@ function createNativeModelPort({
|
|
|
4826
4832
|
try {
|
|
4827
4833
|
if (!response.ok) {
|
|
4828
4834
|
observation.phase("http-error");
|
|
4829
|
-
const
|
|
4835
|
+
const body = await readHttpError(response, maxBytes);
|
|
4836
|
+
const result = classifyHttpError(response, body);
|
|
4837
|
+
const gateway = httpGatewayDiagnostic(response, body);
|
|
4830
4838
|
request.signal?.throwIfAborted();
|
|
4831
4839
|
const code = response.status === 401 ? "http_authentication" : response.status === 403 ? "http_permission" : response.status === 429 ? "http_rate_limit" : response.status === 408 ? "http_timeout" : response.status >= 500 ? "http_server" : "http_client";
|
|
4832
|
-
return withFailure(result, binding, "http-error", code, { httpStatus: response.status });
|
|
4840
|
+
return withFailure(result, binding, "http-error", code, { httpStatus: response.status, ...gateway ? { gateway } : {} });
|
|
4833
4841
|
}
|
|
4834
4842
|
const contentType = response.headers.get("content-type") || "";
|
|
4835
4843
|
if (contentType.includes("text/event-stream")) {
|
|
@@ -4870,6 +4878,25 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4870
4878
|
const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
|
|
4871
4879
|
const abort = (reason) => internal.abort(reason);
|
|
4872
4880
|
let frameIndex = -1;
|
|
4881
|
+
let reasoning = request.purpose == null || request.purpose === "task" ? "" : null;
|
|
4882
|
+
let sinceCheck = 0;
|
|
4883
|
+
let repetition = false;
|
|
4884
|
+
const observe = (event) => {
|
|
4885
|
+
if (event.kind === "text" && event.text.trim() || event.kind === "tool_delta") reasoning = null;
|
|
4886
|
+
if (reasoning !== null && event.kind === "thinking" && event.text) {
|
|
4887
|
+
reasoning = (reasoning + event.text).slice(-1024);
|
|
4888
|
+
sinceCheck += event.text.length;
|
|
4889
|
+
if (reasoning.length === 1024 && sinceCheck >= 128) {
|
|
4890
|
+
sinceCheck = 0;
|
|
4891
|
+
for (let size = 1; size <= 64; size++) {
|
|
4892
|
+
if (reasoning.slice(size) !== reasoning.slice(0, -size)) continue;
|
|
4893
|
+
repetition = true;
|
|
4894
|
+
break;
|
|
4895
|
+
}
|
|
4896
|
+
}
|
|
4897
|
+
}
|
|
4898
|
+
emit(event);
|
|
4899
|
+
};
|
|
4873
4900
|
const failed = (result2, code, fields2 = {}) => withFailure(
|
|
4874
4901
|
result2,
|
|
4875
4902
|
binding,
|
|
@@ -4886,7 +4913,19 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4886
4913
|
if (idlePolicy && !frame.data.trim()) continue;
|
|
4887
4914
|
frameIndex++;
|
|
4888
4915
|
observation.frame();
|
|
4889
|
-
state.consume(frame,
|
|
4916
|
+
state.consume(frame, observe);
|
|
4917
|
+
if (repetition && reasoning !== null && !state.done) {
|
|
4918
|
+
abort(new Error("reasoning_repetition"));
|
|
4919
|
+
return failed({
|
|
4920
|
+
kind: "output_limit",
|
|
4921
|
+
text: "",
|
|
4922
|
+
toolCalls: [],
|
|
4923
|
+
usage: emptyUsage(),
|
|
4924
|
+
usageReported: false,
|
|
4925
|
+
textCommitVersion: "provider-finished-text/v1",
|
|
4926
|
+
outputBoundary: "no-visible-output/v1"
|
|
4927
|
+
}, "reasoning_repetition");
|
|
4928
|
+
}
|
|
4890
4929
|
if (idlePolicy) emit({ kind: "activity", text: "" });
|
|
4891
4930
|
if (state.done) break;
|
|
4892
4931
|
}
|
|
@@ -4948,37 +4987,41 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
|
|
|
4948
4987
|
return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
|
|
4949
4988
|
}
|
|
4950
4989
|
}
|
|
4951
|
-
|
|
4990
|
+
function classifyHttpError(response, body) {
|
|
4952
4991
|
const status = response.status;
|
|
4953
4992
|
const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
|
|
4954
4993
|
if (status === 408) return retryableResult("request_timeout", retryAfterMs);
|
|
4955
4994
|
if (status === 429) return retryableResult("rate_limit", retryAfterMs);
|
|
4956
4995
|
if (status >= 500 && status <= 599) return retryableResult("server_error", retryAfterMs);
|
|
4957
4996
|
if (status === 403) return { kind: "policy_abort", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
4958
|
-
if (status === 400) {
|
|
4959
|
-
|
|
4960
|
-
const bodyText = await readBoundedText(response, maxBytes);
|
|
4961
|
-
if (hasContextLengthExceeded(bodyText)) {
|
|
4962
|
-
return { kind: "context_overflow", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
4963
|
-
}
|
|
4964
|
-
} catch {
|
|
4965
|
-
}
|
|
4966
|
-
return terminalResult("client_error");
|
|
4997
|
+
if (status === 400 && (body?.error?.code === "context_length_exceeded" || body?.error?.type === "context_length_exceeded")) {
|
|
4998
|
+
return { kind: "context_overflow", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
4967
4999
|
}
|
|
4968
5000
|
return terminalResult("client_error");
|
|
4969
5001
|
}
|
|
4970
|
-
function
|
|
5002
|
+
async function readHttpError(response, maxBytes) {
|
|
5003
|
+
if (response.status === 429) return null;
|
|
5004
|
+
const contextCheck = response.status === 400;
|
|
5005
|
+
if (!contextCheck && !response.body?.getReader) return null;
|
|
4971
5006
|
try {
|
|
4972
|
-
|
|
4973
|
-
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
|
|
4978
|
-
}
|
|
5007
|
+
return parseModelJson4(await readBoundedText(
|
|
5008
|
+
response,
|
|
5009
|
+
contextCheck ? maxBytes : Math.min(maxBytes, 8192),
|
|
5010
|
+
void 0,
|
|
5011
|
+
contextCheck ? void 0 : AbortSignal.timeout(200)
|
|
5012
|
+
));
|
|
4979
5013
|
} catch {
|
|
5014
|
+
return null;
|
|
4980
5015
|
}
|
|
4981
|
-
|
|
5016
|
+
}
|
|
5017
|
+
function httpGatewayDiagnostic(response, body) {
|
|
5018
|
+
const diagnostic = {};
|
|
5019
|
+
const error = body?.error && typeof body.error === "object" ? body.error : body;
|
|
5020
|
+
if (MODEL_GATEWAY_ERROR_CODES.includes(error?.code) || Number.isInteger(error?.code) && error.code >= 400 && error.code <= 599) diagnostic.code = error.code;
|
|
5021
|
+
if (MODEL_GATEWAY_ERROR_TYPES.includes(error?.type)) diagnostic.type = error.type;
|
|
5022
|
+
const requestId = ["x-request-id", "request-id", "x-ksc-request-id"].map((header) => response.headers.get(header)).find(isModelGatewayRequestId);
|
|
5023
|
+
if (requestId) diagnostic.requestId = requestId;
|
|
5024
|
+
return Object.keys(diagnostic).length ? diagnostic : null;
|
|
4982
5025
|
}
|
|
4983
5026
|
function terminalResult(failureKind) {
|
|
4984
5027
|
return { kind: "provider_terminal_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
|
|
@@ -4987,9 +5030,9 @@ function protocolCode(error) {
|
|
|
4987
5030
|
return (error instanceof ProtocolError || error instanceof SseFramingError) && MODEL_FAILURE_CODES.includes(error.code) ? error.code : "protocol_invalid";
|
|
4988
5031
|
}
|
|
4989
5032
|
function withFailure(result, binding, phase, code, fields2 = {}) {
|
|
4990
|
-
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind)) return result;
|
|
5033
|
+
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind) && !(result.kind === "output_limit" && code === "reasoning_repetition") && !(result.kind === "context_overflow" && fields2.gateway)) return result;
|
|
4991
5034
|
const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
|
|
4992
|
-
return { ...result, failureDiagnostic: { contract: fields2.providerError ? "model-failure-diagnostic/v3" : fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
|
|
5035
|
+
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 } };
|
|
4993
5036
|
}
|
|
4994
5037
|
function retryableResult(failureKind, retryAfterMs = null) {
|
|
4995
5038
|
const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
|
|
@@ -5009,7 +5052,7 @@ function cancelBody(response) {
|
|
|
5009
5052
|
} catch {
|
|
5010
5053
|
}
|
|
5011
5054
|
}
|
|
5012
|
-
async function readBoundedText(response, maxBytes, observeBytes) {
|
|
5055
|
+
async function readBoundedText(response, maxBytes, observeBytes, signal) {
|
|
5013
5056
|
const body = response.body;
|
|
5014
5057
|
if (body == null) return "";
|
|
5015
5058
|
const reader = body.getReader ? body.getReader() : null;
|
|
@@ -5017,9 +5060,16 @@ async function readBoundedText(response, maxBytes, observeBytes) {
|
|
|
5017
5060
|
let total = 0;
|
|
5018
5061
|
const chunks = [];
|
|
5019
5062
|
if (reader) {
|
|
5063
|
+
const abort = () => {
|
|
5064
|
+
void reader.cancel().catch(() => {
|
|
5065
|
+
});
|
|
5066
|
+
};
|
|
5020
5067
|
try {
|
|
5068
|
+
signal?.throwIfAborted();
|
|
5069
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
5021
5070
|
while (true) {
|
|
5022
5071
|
const { value, done } = await reader.read();
|
|
5072
|
+
signal?.throwIfAborted();
|
|
5023
5073
|
if (done) break;
|
|
5024
5074
|
if (!value) continue;
|
|
5025
5075
|
if (!(value instanceof Uint8Array) && !(value instanceof ArrayBuffer)) throw new ProtocolError("body requires bytes");
|
|
@@ -5031,6 +5081,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
|
|
|
5031
5081
|
chunks.push(decoder.decode());
|
|
5032
5082
|
return chunks.join("");
|
|
5033
5083
|
} finally {
|
|
5084
|
+
signal?.removeEventListener("abort", abort);
|
|
5034
5085
|
reader.releaseLock?.();
|
|
5035
5086
|
}
|
|
5036
5087
|
}
|
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.20",
|
|
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.20",
|
|
158
158
|
"@astral-sh/ruff-wasm-nodejs": "0.16.8",
|
|
159
159
|
"parse5": "7.3.0",
|
|
160
160
|
"playwright-core": "1.58.2",
|
|
@@ -57,6 +57,7 @@ export function connectEngine({ input, output, onApproveTool, onCallTool, hostNa
|
|
|
57
57
|
status: runId => call('run/status', { runId }),
|
|
58
58
|
events: (runId, cursor = 0, waitMs = 0) => call('run/events', { runId, cursor, waitMs }),
|
|
59
59
|
resume: runId => call('run/resume', { runId }),
|
|
60
|
+
guide: (runId, inputId, text) => call('run/guide', { runId, inputId, text }),
|
|
60
61
|
cancel: runId => call('run/cancel', { runId }),
|
|
61
62
|
view: () => call('ui/view'),
|
|
62
63
|
shutdown: () => call('shutdown'),
|
|
@@ -77,7 +78,16 @@ export function spawnEngine({ command, args = [], env, onApproveTool, onCallTool
|
|
|
77
78
|
const child = spawn(command, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
78
79
|
child.stderr.setEncoding('utf8').on('data', chunk => onLog(chunk));
|
|
79
80
|
const client = connectEngine({ input: child.stdout, output: child.stdin, onApproveTool, onCallTool, hostName });
|
|
80
|
-
const exited = new Promise(resolve =>
|
|
81
|
-
|
|
82
|
-
|
|
81
|
+
const exited = new Promise(resolve => {
|
|
82
|
+
child.once('exit', code => resolve({ code }));
|
|
83
|
+
child.once('error', error => resolve({ error }));
|
|
84
|
+
});
|
|
85
|
+
// A spawn error is asynchronous. Race RPCs against exit so a missing
|
|
86
|
+
// executable is reported through initialize instead of crashing the host.
|
|
87
|
+
child.stdin.on('error', () => {});
|
|
88
|
+
const call = invoke => (...values) => Promise.race([invoke(...values), exited.then(({ error }) => {
|
|
89
|
+
throw error ?? new Error('engine process exited');
|
|
90
|
+
})]);
|
|
91
|
+
return { ...client, child, exited: exited.then(({ code }) => code ?? null), initialize: call(client.initialize),
|
|
92
|
+
async close() { try { await client.shutdown(); } catch { /* already gone */ } child.stdin.end(); return (await exited).code ?? null; } };
|
|
83
93
|
}
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants, closeSync, existsSync, readFileSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { diffLines } from 'diff';
|
|
5
|
+
import { atomicPrivate, openPrivate, privateDirectory } from './local-command-state.mjs';
|
|
1
6
|
import { currentDeliveryManifest } from '@kingsoftcloud/agentkit-harness-core';
|
|
2
7
|
|
|
3
8
|
const safePath = path => typeof path === 'string' && path.length <= 2048
|
|
@@ -6,7 +11,7 @@ const screenshotPath = path => safePath(path) && /\.(?:png|jpe?g|webp)$/i.test(p
|
|
|
6
11
|
|
|
7
12
|
/** Committed effects for this Run only. The snapshot's workspaceModifiedPaths
|
|
8
13
|
* also contains paths inherited from earlier Turns. */
|
|
9
|
-
export function engineDeliveryEvidence(record) {
|
|
14
|
+
export function engineDeliveryEvidence(record, netChanges) {
|
|
10
15
|
const changes = new Map();
|
|
11
16
|
const screenshots = new Set();
|
|
12
17
|
for (const artifact of currentDeliveryManifest(record.snapshot)?.artifacts ?? []) {
|
|
@@ -32,6 +37,68 @@ export function engineDeliveryEvidence(record) {
|
|
|
32
37
|
}
|
|
33
38
|
}
|
|
34
39
|
}
|
|
35
|
-
const files = [...changes.values()].filter(file => !screenshots.has(file.path))
|
|
36
|
-
|
|
40
|
+
const files = [...changes.values()].filter(file => !screenshots.has(file.path)).flatMap(file => {
|
|
41
|
+
if (!netChanges) return [file];
|
|
42
|
+
const change = netChanges(file.path);
|
|
43
|
+
return change ? [change] : [];
|
|
44
|
+
});
|
|
45
|
+
return { files: files.slice(0, 96), screenshots: [...screenshots].slice(-8), truncated: files.length > 96,
|
|
46
|
+
...(netChanges ? { basis: 'run-net-diff/v1' } : {}) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Compare the two workspace observations, and only show paths evidenced by
|
|
50
|
+
* this Run's receipts. Never total individual edit deltas. */
|
|
51
|
+
export function deliveryNetChanges(before, after) {
|
|
52
|
+
return path => {
|
|
53
|
+
const old = Object.hasOwn(before, path) ? before[path] : null;
|
|
54
|
+
const next = Object.hasOwn(after, path) ? after[path] : null;
|
|
55
|
+
if (old?.digest === next?.digest) return null;
|
|
56
|
+
const file = { path, ...(!next ? { deleted: true } : {}) };
|
|
57
|
+
if (old && typeof old.text !== 'string' || next && typeof next.text !== 'string') return file;
|
|
58
|
+
const delta = diffLines(old?.text ?? '', next?.text ?? '', { timeout: 25, maxEditLength: 10000 });
|
|
59
|
+
if (!delta) return file;
|
|
60
|
+
let added = 0, removed = 0;
|
|
61
|
+
for (const part of delta) {
|
|
62
|
+
if (part.added) added += part.count;
|
|
63
|
+
if (part.removed) removed += part.count;
|
|
64
|
+
}
|
|
65
|
+
return { ...file, added, removed };
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Private snapshots survive engine restart. Only the sealed summary is
|
|
70
|
+
* returned to the host. Runs without a baseline retain their legacy evidence. */
|
|
71
|
+
export function createEngineDeliveryJournal(directory, capture) {
|
|
72
|
+
const paths = runId => {
|
|
73
|
+
const key = createHash('sha256').update(runId).digest('hex');
|
|
74
|
+
return { baseline: join(directory, key + '.baseline'), summary: join(directory, key + '.json') };
|
|
75
|
+
};
|
|
76
|
+
const read = path => {
|
|
77
|
+
const fd = openPrivate(path, constants.O_RDONLY);
|
|
78
|
+
try { return JSON.parse(readFileSync(fd, 'utf8')); }
|
|
79
|
+
finally { closeSync(fd); }
|
|
80
|
+
};
|
|
81
|
+
return {
|
|
82
|
+
begin(runId) {
|
|
83
|
+
const { baseline } = paths(runId);
|
|
84
|
+
if (!existsSync(baseline)) {
|
|
85
|
+
privateDirectory(directory, true);
|
|
86
|
+
atomicPrivate(baseline, JSON.stringify(capture()));
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
seal(record) {
|
|
90
|
+
const { baseline, summary } = paths(record.snapshot.runId);
|
|
91
|
+
if (!existsSync(baseline)) return;
|
|
92
|
+
try {
|
|
93
|
+
if (record.snapshot.phase === 'completed' && !existsSync(summary)) {
|
|
94
|
+
const evidence = engineDeliveryEvidence(record, deliveryNetChanges(read(baseline), capture()));
|
|
95
|
+
atomicPrivate(summary, JSON.stringify(evidence));
|
|
96
|
+
}
|
|
97
|
+
} finally { unlinkSync(baseline); }
|
|
98
|
+
},
|
|
99
|
+
read(record) {
|
|
100
|
+
const { summary } = paths(record.snapshot.runId);
|
|
101
|
+
return existsSync(summary) ? read(summary) : engineDeliveryEvidence(record);
|
|
102
|
+
},
|
|
103
|
+
};
|
|
37
104
|
}
|
|
@@ -18,6 +18,7 @@ import { admitChatUsagePolicy } from './model-chat-usage.mjs';
|
|
|
18
18
|
import { validateMediaBlock } from './model-media.mjs';
|
|
19
19
|
import { admitProviderCompatibilityPolicy } from './model-provider-compat.mjs';
|
|
20
20
|
import { bindNativeContext, nativeContextDefaults } from './context-profile.mjs';
|
|
21
|
+
import { createEngineDeliveryJournal, engineDeliveryEvidence } from './engine-delivery-evidence.mjs';
|
|
21
22
|
import { createNativeWorkspaceTools } from './workspace-tools.mjs';
|
|
22
23
|
import { createNativeLocalCommandTools } from './local-command-tools.mjs';
|
|
23
24
|
import { createOwnedCommandResolver } from './owned-command.mjs';
|
|
@@ -52,7 +53,14 @@ export const engineApprovalSubject = ({ arguments: args = {} }) => {
|
|
|
52
53
|
return subject ? redactDiagnosticText(subject, 500) : null;
|
|
53
54
|
};
|
|
54
55
|
|
|
55
|
-
|
|
56
|
+
const approvalDenialMessages = {
|
|
57
|
+
approval_prompts_disabled: 'This action requires one-time authorization, but approval prompts are disabled in this session. Changing the arguments cannot grant permission. Do not retry the denied action or try to bypass approval; continue with permitted work, or tell the user to enable approval prompts before trying again.',
|
|
58
|
+
approval_rejected: 'The user declined this action. Do not retry it with different arguments or use another tool to bypass the decision.',
|
|
59
|
+
approval_unavailable: 'No approval responder is available for this action. Changing the arguments cannot grant permission. Continue with permitted work and report the limitation.',
|
|
60
|
+
approval_cancelled: 'This approval was cancelled. The action did not run. Do not request it again unless the user asks to continue.',
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
function durableDecision(record, request, explainDenial = false) {
|
|
56
64
|
const { call, operationKey } = request;
|
|
57
65
|
const interactionId = `engine-permission-${digest({ runId: request.runId, call, definition: request.definition })}`;
|
|
58
66
|
// Walk backward only within the lifetime of this call. A reused provider
|
|
@@ -65,8 +73,13 @@ function durableDecision(record, request) {
|
|
|
65
73
|
const intentKey = payload.interactionId?.slice(0, -':approval'.length);
|
|
66
74
|
if (!intentKey || intentKey === operationKey) continue;
|
|
67
75
|
const receipt = record.receipts.find(row => row.operationKey === intentKey && row.status === 'committed');
|
|
68
|
-
if (receipt?.result.results?.some(result => result.status === 'approval_required' && result.interactionId === interactionId))
|
|
69
|
-
|
|
76
|
+
if (receipt?.result.results?.some(result => result.status === 'approval_required' && result.interactionId === interactionId)) {
|
|
77
|
+
if (payload.decision === 'allow') return 'allow';
|
|
78
|
+
if (explainDenial && Object.hasOwn(approvalDenialMessages, payload.denialReason))
|
|
79
|
+
return { status: 'error', content: { code: payload.denialReason, executed: false, retryable: false,
|
|
80
|
+
message: approvalDenialMessages[payload.denialReason] } };
|
|
81
|
+
return 'deny';
|
|
82
|
+
}
|
|
70
83
|
}
|
|
71
84
|
return { status: 'approval_required', approvalPolicy: DURABLE_APPROVAL, interactionId,
|
|
72
85
|
content: { contract: ENGINE_APPROVAL_CONTRACT, code: 'approval_required', argumentDigest: digest(call.arguments),
|
|
@@ -193,8 +206,8 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
193
206
|
const roles = nativeChildRoles({ subAgents });
|
|
194
207
|
const supportsImages = description.input.includes('image');
|
|
195
208
|
const store = runStore ?? new SqliteRunStore(join(stateDir, 'runs.sqlite'));
|
|
196
|
-
const decide = async request => {
|
|
197
|
-
if (request.definition?.approvalPolicy === DURABLE_APPROVAL) return durableDecision(store.load(request.scope, request.runId), request);
|
|
209
|
+
const decide = async (request, explainDenial = false) => {
|
|
210
|
+
if (request.definition?.approvalPolicy === DURABLE_APPROVAL) return durableDecision(store.load(request.scope, request.runId), request, explainDenial);
|
|
198
211
|
return await authorize(request) === 'allow' ? 'allow' : 'deny';
|
|
199
212
|
};
|
|
200
213
|
const artifacts = await createNativeArtifactStore({ directory: join(stateDir, 'artifacts'), scope });
|
|
@@ -202,6 +215,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
202
215
|
const executionOptions = { modern: true, resourceProfile: 'local-development/v2' };
|
|
203
216
|
const local = execution.localExecution(executionOptions);
|
|
204
217
|
const workspace = createNativeWorkspaceTools({ workspaceRoot: root, stateDir: join(stateDir, 'workspace'), sessionId, authorize: decide });
|
|
218
|
+
const deliveries = createEngineDeliveryJournal(join(stateDir, 'delivery'), () => workspace.captureDelivery());
|
|
205
219
|
const commands = createNativeLocalCommandTools({ workspaceRoot: root, stateRoot: join(stateDir, 'commands'), sessionId,
|
|
206
220
|
settings: local.settings, sourceEnv: local.environment, outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy,
|
|
207
221
|
shellPolicy: commandSandbox,
|
|
@@ -218,19 +232,20 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
218
232
|
const effectBound = request.definition?.hostEffectProtocol === ENGINE_HOST_EFFECT;
|
|
219
233
|
const record = effectBound ? store.load(request.scope, request.runId) : null;
|
|
220
234
|
const decision = record && request.definition.approvalPolicy === DURABLE_APPROVAL
|
|
221
|
-
? durableDecision(record, request) : null;
|
|
235
|
+
? durableDecision(record, request, true) : null;
|
|
222
236
|
if (decision === 'deny') return { status: 'error', content: { code: 'policy_denied', executed: false } };
|
|
237
|
+
if (decision?.status === 'error') return decision;
|
|
223
238
|
const effect = record ? {
|
|
224
239
|
contract: ENGINE_HOST_EFFECT, operationKey: request.operationKey,
|
|
225
240
|
sourceEventId: record.events.at(-1)?.eventId ?? null,
|
|
226
241
|
goal: record.snapshot.goal, goalRevision: record.snapshot.goalRevision,
|
|
227
242
|
observations: engineUserObservations(store, request.scope, record.snapshot),
|
|
228
|
-
approved: decision === 'allow', canRequestApproval:
|
|
243
|
+
approved: decision === 'allow', canRequestApproval: decision?.status === 'approval_required',
|
|
229
244
|
} : undefined;
|
|
230
245
|
const reply = await callHostTool({ runId: request.runId, callId: request.call.callId, name: request.call.name,
|
|
231
246
|
arguments: request.call.arguments ?? {}, signal: request.signal, timeoutMs: request.definition?.timeoutMs ?? 120000, effect });
|
|
232
247
|
if (effectBound && reply?.status === 'approval_required') {
|
|
233
|
-
return decision
|
|
248
|
+
return decision?.status === 'approval_required' ? decision
|
|
234
249
|
: { status: 'error', content: { code: 'host_tool_approval_unavailable', executed: false } };
|
|
235
250
|
}
|
|
236
251
|
if (effectBound && reply?.status === 'uncertain')
|
|
@@ -260,7 +275,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
260
275
|
const preflight = async (request, dispatch) => {
|
|
261
276
|
if (request.definition.approvalPolicy === DURABLE_APPROVAL
|
|
262
277
|
&& (!request.definition.hostEffectProtocol || request.definition.hostApprovalRequired)) {
|
|
263
|
-
const decision = await decide(request);
|
|
278
|
+
const decision = await decide(request, true);
|
|
264
279
|
if (decision === 'deny') return { status: 'error', content: { code: 'policy_denied', executed: false } };
|
|
265
280
|
if (decision !== 'allow') return decision;
|
|
266
281
|
}
|
|
@@ -401,6 +416,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
401
416
|
] : [{ role: 'user', content: task, ...(media.length ? { media } : {}) }];
|
|
402
417
|
const configuration = configure({ profile, tools: runtimeTools, contextSources, hooks: hooks.definitions,
|
|
403
418
|
...hooks.configuration,
|
|
419
|
+
guidancePolicy: 'boundary-guide/v1',
|
|
404
420
|
...(verification ? { hostVerification: verification } : {}),
|
|
405
421
|
...(executionPolicy?.strategy === 'plan-act-observe' ? { initialPlanPolicy: 'plan-act-observe/v1' } : {}),
|
|
406
422
|
contract: { objective: scopedCallbacks ? objective : task,
|
|
@@ -432,6 +448,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
432
448
|
/** Admit a new Run. The Run freezes the preset and instructions it starts with. */
|
|
433
449
|
function start(input) {
|
|
434
450
|
const { identity, configuration, preset, hostTools } = prepareRun(input);
|
|
451
|
+
try { deliveries.begin(input.runId); } catch { /* Optional presentation evidence. */ }
|
|
435
452
|
kernel.start(initialSnapshot(identity, configuration, digest(configuration)), configuration);
|
|
436
453
|
return { runId: input.runId, preset, hostTools };
|
|
437
454
|
}
|
|
@@ -450,6 +467,9 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
450
467
|
start, prepareRun, ports,
|
|
451
468
|
async run(runId, options) {
|
|
452
469
|
const snapshot = await kernel.runUntilIdle(scope, runId, options);
|
|
470
|
+
if (terminal(snapshot.phase)) {
|
|
471
|
+
try { deliveries.seal(store.load(scope, runId)); } catch { /* Preserve the completed Run. */ }
|
|
472
|
+
}
|
|
453
473
|
if (children && terminal(snapshot.phase)) await children.owner.releaseRun({ scope, runId });
|
|
454
474
|
return snapshot;
|
|
455
475
|
},
|
|
@@ -469,6 +489,10 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
469
489
|
...(snapshot.childApproval ? { childRunId: snapshot.childApproval.childRunId } : {}),
|
|
470
490
|
...(subject ? { subject } : {}) };
|
|
471
491
|
},
|
|
492
|
+
deliveryEvidence(runId) {
|
|
493
|
+
const record = store.load(scope, runId);
|
|
494
|
+
try { return deliveries.read(record); } catch { return engineDeliveryEvidence(record); }
|
|
495
|
+
},
|
|
472
496
|
load: runId => store.load(scope, runId),
|
|
473
497
|
completedHostObservations: record => completedHostObservations(store, scope, record),
|
|
474
498
|
authority: runId => store.authority(scope, runId),
|