@kingsoftcloud/agentkit-harness-node 0.0.19 → 0.0.21

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/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 { parseModelJson as parseModelJson4, MODEL_FAILURE_CODES } from "@kingsoftcloud/agentkit-harness-core";
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 result = await classifyHttpError(response, { maxBytes });
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, emit);
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
- async function classifyHttpError(response, { maxBytes }) {
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
- try {
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 hasContextLengthExceeded(bodyText) {
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
- const payload = parseModelJson4(bodyText);
4962
- const error = payload && typeof payload === "object" ? payload.error : null;
4963
- if (error && typeof error === "object") {
4964
- const code = String(error.code || "");
4965
- const type = String(error.type || "");
4966
- if (code === "context_length_exceeded" || type === "context_length_exceeded") return true;
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
- return false;
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
  }
@@ -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 { parseModelJson as parseModelJson4, MODEL_FAILURE_CODES } from "@kingsoftcloud/agentkit-harness-core";
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 result = await classifyHttpError(response, { maxBytes });
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, emit);
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
- async function classifyHttpError(response, { maxBytes }) {
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
- try {
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 hasContextLengthExceeded(bodyText) {
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
- const payload = parseModelJson4(bodyText);
4973
- const error = payload && typeof payload === "object" ? payload.error : null;
4974
- if (error && typeof error === "object") {
4975
- const code = String(error.code || "");
4976
- const type = String(error.type || "");
4977
- if (code === "context_length_exceeded" || type === "context_length_exceeded") return true;
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
- return false;
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.19",
3
+ "version": "0.0.21",
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.19",
157
+ "@kingsoftcloud/agentkit-harness-core": "0.0.21",
158
158
  "@astral-sh/ruff-wasm-nodejs": "0.16.8",
159
159
  "parse5": "7.3.0",
160
160
  "playwright-core": "1.58.2",
@@ -55,8 +55,10 @@ export function connectEngine({ input, output, onApproveTool, onCallTool, hostNa
55
55
  services: { approvals: typeof onApproveTool === 'function', tools: typeof onCallTool === 'function' } }),
56
56
  startRun: params => call('run/start', params),
57
57
  status: runId => call('run/status', { runId }),
58
- events: (runId, cursor = 0, waitMs = 0) => call('run/events', { runId, cursor, waitMs }),
58
+ events: (runId, cursor = 0, waitMs = 0, thinkingCursor, toolDraftCursor, textCursor) =>
59
+ call('run/events', { runId, cursor, waitMs, thinkingCursor, toolDraftCursor, textCursor }),
59
60
  resume: runId => call('run/resume', { runId }),
61
+ guide: (runId, inputId, text) => call('run/guide', { runId, inputId, text }),
60
62
  cancel: runId => call('run/cancel', { runId }),
61
63
  view: () => call('ui/view'),
62
64
  shutdown: () => call('shutdown'),
@@ -77,7 +79,16 @@ export function spawnEngine({ command, args = [], env, onApproveTool, onCallTool
77
79
  const child = spawn(command, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
78
80
  child.stderr.setEncoding('utf8').on('data', chunk => onLog(chunk));
79
81
  const client = connectEngine({ input: child.stdout, output: child.stdin, onApproveTool, onCallTool, hostName });
80
- const exited = new Promise(resolve => child.once('exit', code => resolve(code)));
81
- return { ...client, child, exited,
82
- async close() { try { await client.shutdown(); } catch { /* already gone */ } child.stdin.end(); return exited; } };
82
+ const exited = new Promise(resolve => {
83
+ child.once('exit', code => resolve({ code }));
84
+ child.once('error', error => resolve({ error }));
85
+ });
86
+ // A spawn error is asynchronous. Race RPCs against exit so a missing
87
+ // executable is reported through initialize instead of crashing the host.
88
+ child.stdin.on('error', () => {});
89
+ const call = invoke => (...values) => Promise.race([invoke(...values), exited.then(({ error }) => {
90
+ throw error ?? new Error('engine process exited');
91
+ })]);
92
+ return { ...client, child, exited: exited.then(({ code }) => code ?? null), initialize: call(client.initialize),
93
+ async close() { try { await client.shutdown(); } catch { /* already gone */ } child.stdin.end(); return (await exited).code ?? null; } };
83
94
  }
@@ -1,12 +1,18 @@
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
4
9
  && !/[\\:\u0000-\u001f\u007f?#]/u.test(path) && path.split('/').every(part => part && part !== '.' && part !== '..');
5
10
  const screenshotPath = path => safePath(path) && /\.(?:png|jpe?g|webp)$/i.test(path);
11
+ const generatedPythonCache = path => path.split('/').includes('__pycache__') && /\.py[co]$/i.test(path);
6
12
 
7
13
  /** Committed effects for this Run only. The snapshot's workspaceModifiedPaths
8
14
  * also contains paths inherited from earlier Turns. */
9
- export function engineDeliveryEvidence(record) {
15
+ export function engineDeliveryEvidence(record, netChanges) {
10
16
  const changes = new Map();
11
17
  const screenshots = new Set();
12
18
  for (const artifact of currentDeliveryManifest(record.snapshot)?.artifacts ?? []) {
@@ -22,7 +28,7 @@ export function engineDeliveryEvidence(record) {
22
28
  if (tool === 'browser_inspect_workspace' && ['ok', 'error'].includes(result.status) && screenshotPath(screenshot)) screenshots.add(screenshot);
23
29
  if (result.status !== 'ok') continue;
24
30
  for (const changed of result.workspaceChangedPaths ?? []) {
25
- if (!safePath(changed)) continue;
31
+ if (!safePath(changed) || tool === 'run_command' && generatedPythonCache(changed)) continue;
26
32
  const counts = changed === path && [added, removed].every(value => Number.isSafeInteger(value) && value >= 0)
27
33
  ? { added, removed } : {};
28
34
  // Overlapping edits cannot be counted as a net diff from their tool deltas.
@@ -32,6 +38,68 @@ export function engineDeliveryEvidence(record) {
32
38
  }
33
39
  }
34
40
  }
35
- const files = [...changes.values()].filter(file => !screenshots.has(file.path));
36
- return { files: files.slice(0, 96), screenshots: [...screenshots].slice(-8), truncated: files.length > 96 };
41
+ const files = [...changes.values()].filter(file => !screenshots.has(file.path)).flatMap(file => {
42
+ if (!netChanges) return [file];
43
+ const change = netChanges(file.path);
44
+ return change ? [change] : [];
45
+ });
46
+ return { files: files.slice(0, 96), screenshots: [...screenshots].slice(-8), truncated: files.length > 96,
47
+ ...(netChanges ? { basis: 'run-net-diff/v1' } : {}) };
48
+ }
49
+
50
+ /** Compare the two workspace observations, and only show paths evidenced by
51
+ * this Run's receipts. Never total individual edit deltas. */
52
+ export function deliveryNetChanges(before, after) {
53
+ return path => {
54
+ const old = Object.hasOwn(before, path) ? before[path] : null;
55
+ const next = Object.hasOwn(after, path) ? after[path] : null;
56
+ if (old?.digest === next?.digest) return null;
57
+ const file = { path, ...(!next ? { deleted: true } : {}) };
58
+ if (old && typeof old.text !== 'string' || next && typeof next.text !== 'string') return file;
59
+ const delta = diffLines(old?.text ?? '', next?.text ?? '', { timeout: 25, maxEditLength: 10000 });
60
+ if (!delta) return file;
61
+ let added = 0, removed = 0;
62
+ for (const part of delta) {
63
+ if (part.added) added += part.count;
64
+ if (part.removed) removed += part.count;
65
+ }
66
+ return { ...file, added, removed };
67
+ };
68
+ }
69
+
70
+ /** Private snapshots survive engine restart. Only the sealed summary is
71
+ * returned to the host. Runs without a baseline retain their legacy evidence. */
72
+ export function createEngineDeliveryJournal(directory, capture) {
73
+ const paths = runId => {
74
+ const key = createHash('sha256').update(runId).digest('hex');
75
+ return { baseline: join(directory, key + '.baseline'), summary: join(directory, key + '.json') };
76
+ };
77
+ const read = path => {
78
+ const fd = openPrivate(path, constants.O_RDONLY);
79
+ try { return JSON.parse(readFileSync(fd, 'utf8')); }
80
+ finally { closeSync(fd); }
81
+ };
82
+ return {
83
+ begin(runId) {
84
+ const { baseline } = paths(runId);
85
+ if (!existsSync(baseline)) {
86
+ privateDirectory(directory, true);
87
+ atomicPrivate(baseline, JSON.stringify(capture()));
88
+ }
89
+ },
90
+ seal(record) {
91
+ const { baseline, summary } = paths(record.snapshot.runId);
92
+ if (!existsSync(baseline)) return;
93
+ try {
94
+ if (record.snapshot.phase === 'completed' && !existsSync(summary)) {
95
+ const evidence = engineDeliveryEvidence(record, deliveryNetChanges(read(baseline), capture()));
96
+ atomicPrivate(summary, JSON.stringify(evidence));
97
+ }
98
+ } finally { unlinkSync(baseline); }
99
+ },
100
+ read(record) {
101
+ const { summary } = paths(record.snapshot.runId);
102
+ return existsSync(summary) ? read(summary) : engineDeliveryEvidence(record);
103
+ },
104
+ };
37
105
  }
@@ -5,6 +5,7 @@ import { canonical, invariant, isNativeError, toolReceiptSource } from '@kingsof
5
5
  export const ENGINE_HOST_EFFECT = 'agentkit.engine-host-tool-effect/v1';
6
6
  const MAX_INPUT_BYTES = 128 * 1024;
7
7
  const MAX_INPUTS = 64;
8
+ export const RECEIPT_WAIT_MS = 30_000;
8
9
 
9
10
  export function hostReceiptSource(record) {
10
11
  const originalOperationKey = record.snapshot.toolReconciliation?.operationKey;
@@ -27,28 +28,37 @@ export function hostReceiptReply(reply, observationId) {
27
28
 
28
29
  /** Idle reads inspect a durable checkpoint. The Kernel claims the original
29
30
  * remote receipt query separately from the initial mutation. */
30
- export async function waitForHostReceipt(record, { read, signal, assertCurrent }) {
31
+ export async function waitForHostReceipt(record, { read, signal, assertCurrent, waitMs = RECEIPT_WAIT_MS }) {
31
32
  const source = hostReceiptSource(record);
32
33
  if (!source) return null;
33
34
  const { call, originalOperationKey } = source, { runId } = record.snapshot;
34
- for (;;) {
35
- assertCurrent();
36
- const ready = await read(call, originalOperationKey, signal).catch(() => null);
37
- assertCurrent();
38
- if (ready) {
39
- const digest = createHash('sha256').update(canonical({ runId, originalOperationKey, token: ready.token })).digest('hex');
40
- const prefix = 'host-receipt-' + digest;
41
- const attempts = record.commands.filter(row => row.consumed && row.command.commandId.startsWith(prefix + '-')).length;
42
- // One initial read may find the original Task finished even after its
43
- // deadline. Later terminal facts have a different checkpoint token.
44
- if (ready.settled ? attempts < 3 : attempts === 0 || Date.now() < ready.retryUntil) {
45
- if (attempts) await delay(Math.min(1500 * attempts, 5000), undefined, { signal });
46
- assertCurrent();
47
- return { commandId: prefix + '-' + attempts, kind: 'reconcile_tool', payload: { originalOperationKey } };
35
+ const deadline = AbortSignal.timeout(waitMs);
36
+ const polling = AbortSignal.any([signal, deadline]);
37
+ try {
38
+ while (!polling.aborted) {
39
+ assertCurrent();
40
+ const ready = await read(call, originalOperationKey, polling).catch(() => null);
41
+ polling.throwIfAborted();
42
+ assertCurrent();
43
+ if (ready) {
44
+ const digest = createHash('sha256').update(canonical({ runId, originalOperationKey, token: ready.token })).digest('hex');
45
+ const prefix = 'host-receipt-' + digest;
46
+ const attempts = record.commands.filter(row => row.consumed && row.command.commandId.startsWith(prefix + '-')).length;
47
+ // A terminal fact has a different checkpoint token. Give the host a
48
+ // bounded window to publish it before leaving the durable Run idle.
49
+ if (ready.settled ? attempts < 3 : attempts === 0 || Date.now() < ready.retryUntil) {
50
+ if (attempts) await delay(Math.min(1500 * attempts, 5000), undefined, { signal: polling });
51
+ assertCurrent();
52
+ return { commandId: prefix + '-' + attempts, kind: 'reconcile_tool', payload: { originalOperationKey } };
53
+ }
48
54
  }
55
+ await delay(1000, undefined, { signal: polling });
49
56
  }
50
- await delay(1000, undefined, { signal });
57
+ } catch (error) {
58
+ if (!deadline.aborted || signal.aborted) throw error;
51
59
  }
60
+ assertCurrent();
61
+ return null;
52
62
  }
53
63
 
54
64
  /** The host receives original user text and stable identities, never imported prose or media. */
@@ -2,7 +2,7 @@ import { createHash, createPublicKey, timingSafeEqual } from 'node:crypto';
2
2
  import { join } from 'node:path';
3
3
  import { canonical, configure, invariant, parseNativeJson, TOOL_RECEIPT_OBSERVATION_CONTRACT } from '@kingsoftcloud/agentkit-harness-core';
4
4
  import { createEngineRuntime } from './engine-runtime.mjs';
5
- import { ENGINE_HOST_EFFECT, waitForHostReceipt } from './engine-host-effects.mjs';
5
+ import { ENGINE_HOST_EFFECT, RECEIPT_WAIT_MS, waitForHostReceipt } from './engine-host-effects.mjs';
6
6
  import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
7
7
  import { createManagedSessionDelivery, MANAGED_SESSION_DELIVERY, projectManagedSessionEvent } from './engine-managed-delivery.mjs';
8
8
  import { createManagedEngineHost, MANAGED_HOST_RESOURCES } from './engine-managed-host.mjs';
@@ -150,12 +150,19 @@ export function createEngineManagedService({ startup, stateDir, workspace, confi
150
150
  }) : {};
151
151
  const hasHostReceipts = configuration.tools.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT
152
152
  && tool.recoveryPolicy === 'receipt-observation/v1');
153
- function waitForReceipt(_snapshot, { signal: idleSignal, assertCurrent }) {
154
- assertCurrent();
155
- return waitForHostReceipt(store.load(scope, runId), { read: readReceipt, signal: idleSignal, assertCurrent });
153
+ function executeWithReceipts({ execute }) {
154
+ let deadline;
155
+ return execute({ onIdle(_snapshot, { signal: idleSignal, assertCurrent }) {
156
+ assertCurrent();
157
+ deadline ??= Date.now() + RECEIPT_WAIT_MS;
158
+ const waitMs = deadline - Date.now();
159
+ return waitMs <= 0 ? null : waitForHostReceipt(store.load(scope, runId), {
160
+ read: readReceipt, signal: idleSignal, assertCurrent, waitMs,
161
+ });
162
+ } });
156
163
  }
157
164
  return { scope, buildId, configuration, ports: engine.ports, ...delivery,
158
- ...(hasHostReceipts ? { withExecution: ({ execute }) => execute({ onIdle: waitForReceipt }) } : {}),
165
+ ...(hasHostReceipts ? { withExecution: executeWithReceipts } : {}),
159
166
  release: () => engine.close() };
160
167
  } catch (error) {
161
168
  await engine.close();