@kingsoftcloud/agentkit-harness-node 0.0.18 → 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/index.mjs CHANGED
@@ -385,16 +385,25 @@ function foregroundReceiptState(record, ref, intent) {
385
385
  if (receipt?.status !== "committed" || result?.status !== "ok" || result.backgroundCommandFinished !== true || !result.backgroundCommandRef || canonical4(result.backgroundCommandRef) !== canonical4(ref) || result.content?.task_id !== ref.taskId || result.content.evidence_incomplete === true || !settledCommandStates.has(result.content.status)) return null;
386
386
  return result.content.status;
387
387
  }
388
- function nativeActivityStatus(record, { driving = false } = {}) {
389
- if (!record) return null;
390
- const { snapshot } = record;
391
- const todos = snapshot.todos?.items ?? [], occurrences = /* @__PURE__ */ new Map();
388
+ function nativeTodoPlan(todos) {
389
+ if (!todos.length) return null;
390
+ const occurrences = /* @__PURE__ */ new Map();
392
391
  const items = todos.slice(0, 512).map((todo) => {
393
392
  const digest = createHash2("sha256").update(todo.content).digest("hex");
394
393
  const occurrence = occurrences.get(digest) ?? 0;
395
394
  occurrences.set(digest, occurrence + 1);
396
395
  return { id: `todo:${digest}:${occurrence}`, content: todo.content, status: todo.status };
397
396
  });
397
+ return {
398
+ items,
399
+ completedCount: todos.filter((todo) => todo.status === "completed").length,
400
+ totalCount: todos.length,
401
+ omittedItems: Math.max(0, todos.length - items.length)
402
+ };
403
+ }
404
+ function nativeActivityStatus(record, { driving = false } = {}) {
405
+ if (!record) return null;
406
+ const { snapshot } = record;
398
407
  const observations = /* @__PURE__ */ new Map();
399
408
  for (const event of record.events ?? []) if (event.kind === "background.commands_observed")
400
409
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
@@ -418,12 +427,7 @@ function nativeActivityStatus(record, { driving = false } = {}) {
418
427
  runId: snapshot.runId,
419
428
  snapshotRevision: snapshot.revision,
420
429
  isRunning: driving,
421
- plan: todos.length ? {
422
- items,
423
- completedCount: todos.filter((todo) => todo.status === "completed").length,
424
- totalCount: todos.length,
425
- omittedItems: Math.max(0, todos.length - items.length)
426
- } : null,
430
+ plan: nativeTodoPlan(snapshot.todos?.items ?? []),
427
431
  terminals,
428
432
  omittedTerminals: commands.length - terminals.length
429
433
  };
@@ -4684,7 +4688,13 @@ function buildNativeModelRequest(binding, request) {
4684
4688
  }
4685
4689
 
4686
4690
  // packages/agentkit-harness-node/src/native/model-port.mjs
4687
- 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";
4688
4698
 
4689
4699
  // packages/agentkit-harness-node/src/native/model-transport-observation.mjs
4690
4700
  function modelTransportObservation(now = () => performance.now()) {
@@ -4811,10 +4821,12 @@ function createNativeModelPort({
4811
4821
  try {
4812
4822
  if (!response.ok) {
4813
4823
  observation.phase("http-error");
4814
- 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);
4815
4827
  request.signal?.throwIfAborted();
4816
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";
4817
- return withFailure(result, binding, "http-error", code, { httpStatus: response.status });
4829
+ return withFailure(result, binding, "http-error", code, { httpStatus: response.status, ...gateway ? { gateway } : {} });
4818
4830
  }
4819
4831
  const contentType = response.headers.get("content-type") || "";
4820
4832
  if (contentType.includes("text/event-stream")) {
@@ -4855,6 +4867,25 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4855
4867
  const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
4856
4868
  const abort = (reason) => internal.abort(reason);
4857
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
+ };
4858
4889
  const failed = (result2, code, fields2 = {}) => withFailure(
4859
4890
  result2,
4860
4891
  binding,
@@ -4871,7 +4902,19 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4871
4902
  if (idlePolicy && !frame.data.trim()) continue;
4872
4903
  frameIndex++;
4873
4904
  observation.frame();
4874
- 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
+ }
4875
4918
  if (idlePolicy) emit({ kind: "activity", text: "" });
4876
4919
  if (state.done) break;
4877
4920
  }
@@ -4933,37 +4976,41 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
4933
4976
  return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
4934
4977
  }
4935
4978
  }
4936
- async function classifyHttpError(response, { maxBytes }) {
4979
+ function classifyHttpError(response, body) {
4937
4980
  const status = response.status;
4938
4981
  const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
4939
4982
  if (status === 408) return retryableResult("request_timeout", retryAfterMs);
4940
4983
  if (status === 429) return retryableResult("rate_limit", retryAfterMs);
4941
4984
  if (status >= 500 && status <= 599) return retryableResult("server_error", retryAfterMs);
4942
4985
  if (status === 403) return { kind: "policy_abort", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
4943
- if (status === 400) {
4944
- try {
4945
- const bodyText = await readBoundedText(response, maxBytes);
4946
- if (hasContextLengthExceeded(bodyText)) {
4947
- return { kind: "context_overflow", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
4948
- }
4949
- } catch {
4950
- }
4951
- 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 };
4952
4988
  }
4953
4989
  return terminalResult("client_error");
4954
4990
  }
4955
- 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;
4956
4995
  try {
4957
- const payload = parseModelJson4(bodyText);
4958
- const error = payload && typeof payload === "object" ? payload.error : null;
4959
- if (error && typeof error === "object") {
4960
- const code = String(error.code || "");
4961
- const type = String(error.type || "");
4962
- if (code === "context_length_exceeded" || type === "context_length_exceeded") return true;
4963
- }
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
+ ));
4964
5002
  } catch {
5003
+ return null;
4965
5004
  }
4966
- 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;
4967
5014
  }
4968
5015
  function terminalResult(failureKind) {
4969
5016
  return { kind: "provider_terminal_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
@@ -4972,9 +5019,9 @@ function protocolCode(error) {
4972
5019
  return (error instanceof ProtocolError || error instanceof SseFramingError) && MODEL_FAILURE_CODES.includes(error.code) ? error.code : "protocol_invalid";
4973
5020
  }
4974
5021
  function withFailure(result, binding, phase, code, fields2 = {}) {
4975
- 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;
4976
5023
  const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
4977
- 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 } };
4978
5025
  }
4979
5026
  function retryableResult(failureKind, retryAfterMs = null) {
4980
5027
  const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
@@ -4994,7 +5041,7 @@ function cancelBody(response) {
4994
5041
  } catch {
4995
5042
  }
4996
5043
  }
4997
- async function readBoundedText(response, maxBytes, observeBytes) {
5044
+ async function readBoundedText(response, maxBytes, observeBytes, signal) {
4998
5045
  const body = response.body;
4999
5046
  if (body == null) return "";
5000
5047
  const reader = body.getReader ? body.getReader() : null;
@@ -5002,9 +5049,16 @@ async function readBoundedText(response, maxBytes, observeBytes) {
5002
5049
  let total = 0;
5003
5050
  const chunks = [];
5004
5051
  if (reader) {
5052
+ const abort = () => {
5053
+ void reader.cancel().catch(() => {
5054
+ });
5055
+ };
5005
5056
  try {
5057
+ signal?.throwIfAborted();
5058
+ signal?.addEventListener("abort", abort, { once: true });
5006
5059
  while (true) {
5007
5060
  const { value, done } = await reader.read();
5061
+ signal?.throwIfAborted();
5008
5062
  if (done) break;
5009
5063
  if (!value) continue;
5010
5064
  if (!(value instanceof Uint8Array) && !(value instanceof ArrayBuffer)) throw new ProtocolError("body requires bytes");
@@ -5016,6 +5070,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
5016
5070
  chunks.push(decoder.decode());
5017
5071
  return chunks.join("");
5018
5072
  } finally {
5073
+ signal?.removeEventListener("abort", abort);
5019
5074
  reader.releaseLock?.();
5020
5075
  }
5021
5076
  }
@@ -396,16 +396,25 @@ function foregroundReceiptState(record, ref, intent) {
396
396
  if (receipt?.status !== "committed" || result?.status !== "ok" || result.backgroundCommandFinished !== true || !result.backgroundCommandRef || canonical4(result.backgroundCommandRef) !== canonical4(ref) || result.content?.task_id !== ref.taskId || result.content.evidence_incomplete === true || !settledCommandStates.has(result.content.status)) return null;
397
397
  return result.content.status;
398
398
  }
399
- function nativeActivityStatus(record, { driving = false } = {}) {
400
- if (!record) return null;
401
- const { snapshot } = record;
402
- const todos = snapshot.todos?.items ?? [], occurrences = /* @__PURE__ */ new Map();
399
+ function nativeTodoPlan(todos) {
400
+ if (!todos.length) return null;
401
+ const occurrences = /* @__PURE__ */ new Map();
403
402
  const items = todos.slice(0, 512).map((todo) => {
404
403
  const digest2 = createHash2("sha256").update(todo.content).digest("hex");
405
404
  const occurrence = occurrences.get(digest2) ?? 0;
406
405
  occurrences.set(digest2, occurrence + 1);
407
406
  return { id: `todo:${digest2}:${occurrence}`, content: todo.content, status: todo.status };
408
407
  });
408
+ return {
409
+ items,
410
+ completedCount: todos.filter((todo) => todo.status === "completed").length,
411
+ totalCount: todos.length,
412
+ omittedItems: Math.max(0, todos.length - items.length)
413
+ };
414
+ }
415
+ function nativeActivityStatus(record, { driving = false } = {}) {
416
+ if (!record) return null;
417
+ const { snapshot } = record;
409
418
  const observations = /* @__PURE__ */ new Map();
410
419
  for (const event of record.events ?? []) if (event.kind === "background.commands_observed")
411
420
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
@@ -429,12 +438,7 @@ function nativeActivityStatus(record, { driving = false } = {}) {
429
438
  runId: snapshot.runId,
430
439
  snapshotRevision: snapshot.revision,
431
440
  isRunning: driving,
432
- plan: todos.length ? {
433
- items,
434
- completedCount: todos.filter((todo) => todo.status === "completed").length,
435
- totalCount: todos.length,
436
- omittedItems: Math.max(0, todos.length - items.length)
437
- } : null,
441
+ plan: nativeTodoPlan(snapshot.todos?.items ?? []),
438
442
  terminals,
439
443
  omittedTerminals: commands.length - terminals.length
440
444
  };
@@ -4695,7 +4699,13 @@ function buildNativeModelRequest(binding, request) {
4695
4699
  }
4696
4700
 
4697
4701
  // packages/agentkit-harness-node/src/native/model-port.mjs
4698
- 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";
4699
4709
 
4700
4710
  // packages/agentkit-harness-node/src/native/model-transport-observation.mjs
4701
4711
  function modelTransportObservation(now = () => performance.now()) {
@@ -4822,10 +4832,12 @@ function createNativeModelPort({
4822
4832
  try {
4823
4833
  if (!response.ok) {
4824
4834
  observation.phase("http-error");
4825
- 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);
4826
4838
  request.signal?.throwIfAborted();
4827
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";
4828
- return withFailure(result, binding, "http-error", code, { httpStatus: response.status });
4840
+ return withFailure(result, binding, "http-error", code, { httpStatus: response.status, ...gateway ? { gateway } : {} });
4829
4841
  }
4830
4842
  const contentType = response.headers.get("content-type") || "";
4831
4843
  if (contentType.includes("text/event-stream")) {
@@ -4866,6 +4878,25 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4866
4878
  const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
4867
4879
  const abort = (reason) => internal.abort(reason);
4868
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
+ };
4869
4900
  const failed = (result2, code, fields2 = {}) => withFailure(
4870
4901
  result2,
4871
4902
  binding,
@@ -4882,7 +4913,19 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4882
4913
  if (idlePolicy && !frame.data.trim()) continue;
4883
4914
  frameIndex++;
4884
4915
  observation.frame();
4885
- 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
+ }
4886
4929
  if (idlePolicy) emit({ kind: "activity", text: "" });
4887
4930
  if (state.done) break;
4888
4931
  }
@@ -4944,37 +4987,41 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
4944
4987
  return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
4945
4988
  }
4946
4989
  }
4947
- async function classifyHttpError(response, { maxBytes }) {
4990
+ function classifyHttpError(response, body) {
4948
4991
  const status = response.status;
4949
4992
  const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
4950
4993
  if (status === 408) return retryableResult("request_timeout", retryAfterMs);
4951
4994
  if (status === 429) return retryableResult("rate_limit", retryAfterMs);
4952
4995
  if (status >= 500 && status <= 599) return retryableResult("server_error", retryAfterMs);
4953
4996
  if (status === 403) return { kind: "policy_abort", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
4954
- if (status === 400) {
4955
- try {
4956
- const bodyText = await readBoundedText(response, maxBytes);
4957
- if (hasContextLengthExceeded(bodyText)) {
4958
- return { kind: "context_overflow", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false };
4959
- }
4960
- } catch {
4961
- }
4962
- 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 };
4963
4999
  }
4964
5000
  return terminalResult("client_error");
4965
5001
  }
4966
- 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;
4967
5006
  try {
4968
- const payload = parseModelJson4(bodyText);
4969
- const error = payload && typeof payload === "object" ? payload.error : null;
4970
- if (error && typeof error === "object") {
4971
- const code = String(error.code || "");
4972
- const type = String(error.type || "");
4973
- if (code === "context_length_exceeded" || type === "context_length_exceeded") return true;
4974
- }
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
+ ));
4975
5013
  } catch {
5014
+ return null;
4976
5015
  }
4977
- 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;
4978
5025
  }
4979
5026
  function terminalResult(failureKind) {
4980
5027
  return { kind: "provider_terminal_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
@@ -4983,9 +5030,9 @@ function protocolCode(error) {
4983
5030
  return (error instanceof ProtocolError || error instanceof SseFramingError) && MODEL_FAILURE_CODES.includes(error.code) ? error.code : "protocol_invalid";
4984
5031
  }
4985
5032
  function withFailure(result, binding, phase, code, fields2 = {}) {
4986
- 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;
4987
5034
  const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
4988
- 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 } };
4989
5036
  }
4990
5037
  function retryableResult(failureKind, retryAfterMs = null) {
4991
5038
  const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
@@ -5005,7 +5052,7 @@ function cancelBody(response) {
5005
5052
  } catch {
5006
5053
  }
5007
5054
  }
5008
- async function readBoundedText(response, maxBytes, observeBytes) {
5055
+ async function readBoundedText(response, maxBytes, observeBytes, signal) {
5009
5056
  const body = response.body;
5010
5057
  if (body == null) return "";
5011
5058
  const reader = body.getReader ? body.getReader() : null;
@@ -5013,9 +5060,16 @@ async function readBoundedText(response, maxBytes, observeBytes) {
5013
5060
  let total = 0;
5014
5061
  const chunks = [];
5015
5062
  if (reader) {
5063
+ const abort = () => {
5064
+ void reader.cancel().catch(() => {
5065
+ });
5066
+ };
5016
5067
  try {
5068
+ signal?.throwIfAborted();
5069
+ signal?.addEventListener("abort", abort, { once: true });
5017
5070
  while (true) {
5018
5071
  const { value, done } = await reader.read();
5072
+ signal?.throwIfAborted();
5019
5073
  if (done) break;
5020
5074
  if (!value) continue;
5021
5075
  if (!(value instanceof Uint8Array) && !(value instanceof ArrayBuffer)) throw new ProtocolError("body requires bytes");
@@ -5027,6 +5081,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
5027
5081
  chunks.push(decoder.decode());
5028
5082
  return chunks.join("");
5029
5083
  } finally {
5084
+ signal?.removeEventListener("abort", abort);
5030
5085
  reader.releaseLock?.();
5031
5086
  }
5032
5087
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-node",
3
- "version": "0.0.18",
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.18",
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",
@@ -31,16 +31,23 @@ function foregroundReceiptState(record, ref, intent) {
31
31
  return result.content.status;
32
32
  }
33
33
 
34
- /** Content and lifecycle facts from committed task state; no control authority. */
35
- export function nativeActivityStatus(record, { driving = false } = {}) {
36
- if (!record) return null;
37
- const { snapshot } = record;
38
- const todos = snapshot.todos?.items ?? [], occurrences = new Map();
34
+ /** A bounded presentation of the committed task checklist. */
35
+ export function nativeTodoPlan(todos) {
36
+ if (!todos.length) return null;
37
+ const occurrences = new Map();
39
38
  const items = todos.slice(0, 512).map(todo => {
40
39
  const digest = createHash('sha256').update(todo.content).digest('hex');
41
40
  const occurrence = occurrences.get(digest) ?? 0; occurrences.set(digest, occurrence + 1);
42
41
  return { id: `todo:${digest}:${occurrence}`, content: todo.content, status: todo.status };
43
42
  });
43
+ return { items, completedCount: todos.filter(todo => todo.status === 'completed').length,
44
+ totalCount: todos.length, omittedItems: Math.max(0, todos.length - items.length) };
45
+ }
46
+
47
+ /** Content and lifecycle facts from committed task state; no control authority. */
48
+ export function nativeActivityStatus(record, { driving = false } = {}) {
49
+ if (!record) return null;
50
+ const { snapshot } = record;
44
51
  const observations = new Map();
45
52
  for (const event of record.events ?? []) if (event.kind === 'background.commands_observed')
46
53
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
@@ -56,8 +63,6 @@ export function nativeActivityStatus(record, { driving = false } = {}) {
56
63
  state: observed?.status ?? foregroundReceiptState(record, ref, intent) ?? 'unknown', canCancel: false };
57
64
  });
58
65
  return { contract: 'agentkit.native-activity-status/v1', runId: snapshot.runId, snapshotRevision: snapshot.revision,
59
- isRunning: driving, plan: todos.length ? { items,
60
- completedCount: todos.filter(todo => todo.status === 'completed').length, totalCount: todos.length,
61
- omittedItems: Math.max(0, todos.length - items.length) } : null,
66
+ isRunning: driving, plan: nativeTodoPlan(snapshot.todos?.items ?? []),
62
67
  terminals, omittedTerminals: commands.length - terminals.length };
63
68
  }
@@ -2,7 +2,7 @@
2
2
  import { createHash, randomBytes } from 'node:crypto';
3
3
  import { createServer } from 'node:http';
4
4
  import { constants, closeSync, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
5
- import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
6
  import { allowsWorkspaceBrowserUrl } from './browser-workspace-policy.mjs';
7
7
 
8
8
  const within = (root, path) => path === root || path.startsWith(root + sep);
@@ -65,11 +65,18 @@ export function resolveBrowserWorkspaceEntry(root, path) {
65
65
  }
66
66
 
67
67
  export async function createBrowserWorkspaceServer({ root, path, maxFileBytes = 32 * 1024 * 1024,
68
- maxFiles = 4096, signal } = {}) {
68
+ maxFiles = 4096, signal, interactivePreview = false, projectRoot, previewHost } = {}) {
69
69
  signal?.throwIfAborted();
70
70
  if (!Number.isSafeInteger(maxFileBytes) || maxFileBytes < 1 || maxFileBytes > 2 ** 30
71
71
  || !Number.isSafeInteger(maxFiles) || maxFiles < 1 || maxFiles > 65536) fail('browser_server_limits_invalid');
72
- const { workspace, entry, servedRoot } = resolveBrowserWorkspaceEntry(root, path);
72
+ const { workspace, entry, servedRoot: entryDirectory } = resolveBrowserWorkspaceEntry(root, path);
73
+ const servedRoot = projectRoot === undefined ? entryDirectory : bound(workspace, resolve(workspace, safeRelative(projectRoot)));
74
+ if (!within(servedRoot, entry) || !statSync(servedRoot).isDirectory()) fail('workspace_path_outside_scope');
75
+ const entryPath = relative(servedRoot, entry).split(sep);
76
+ const visible = path => path.split('/').every(part => !part.startsWith('.') && !ignored.has(part));
77
+ if (interactivePreview && (!visible(path) || !visible(relative(workspace, entry).split(sep).join('/')))) fail('workspace_path_invalid');
78
+ if (previewHost !== undefined && !/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/i.test(previewHost))
79
+ fail('browser_preview_host_invalid');
73
80
  const prefix = `/${randomBytes(24).toString('hex')}/`, generated = new Map();
74
81
  let origin, closed = false, closing;
75
82
 
@@ -91,7 +98,12 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
91
98
  walk(servedRoot); return digest.digest('hex');
92
99
  }
93
100
 
94
- const initialRevision = revision();
101
+ const initialRevision = interactivePreview ? null : revision();
102
+ const frameAncestors = previewHost ? `http://${previewHost} https://${previewHost}` : "'none'";
103
+ const previewHeaders = interactivePreview ? {
104
+ 'content-security-policy': `default-src 'none'; script-src 'self' 'unsafe-inline' https:; style-src 'self' 'unsafe-inline' https:; img-src 'self' https: data: blob:; font-src 'self' https: data:; media-src 'self' https: data: blob:; connect-src 'self'; worker-src 'self' blob:; frame-ancestors ${frameAncestors}; base-uri 'self'; form-action 'none'`,
105
+ 'cross-origin-opener-policy': 'same-origin', 'cross-origin-resource-policy': 'same-origin', 'referrer-policy': 'no-referrer',
106
+ } : {};
95
107
  const server = createServer((request, response) => {
96
108
  const reply = (status, text) => { response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8',
97
109
  'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); response.end(text); };
@@ -102,6 +114,7 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
102
114
  const raw = request.url;
103
115
  if (!raw?.startsWith(prefix)) return reply(403, 'Outside browser page');
104
116
  const rawPath = raw.split('?')[0], pathname = decodeURIComponent(rawPath.slice(prefix.length));
117
+ if (interactivePreview && !visible(pathname)) return reply(403, 'Outside browser page');
105
118
  const lexical = resolve(servedRoot, pathname ? safeRelative(pathname) : '.');
106
119
  if (!within(servedRoot, lexical)) return reply(403, 'Outside browser page');
107
120
  let target = bound(servedRoot, lexical);
@@ -116,8 +129,9 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
116
129
  }
117
130
  }
118
131
  const { bytes, target: actual } = readBoundFile(servedRoot, target, maxFileBytes);
132
+ if (interactivePreview && !visible(relative(servedRoot, actual).split(sep).join('/'))) return reply(403, 'Outside browser page');
119
133
  response.writeHead(200, { 'content-type': types[extname(actual).toLowerCase()] ?? 'application/octet-stream',
120
- 'content-length': bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
134
+ 'content-length': bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...previewHeaders });
121
135
  response.end(request.method === 'HEAD' ? undefined : bytes);
122
136
  } catch (error) {
123
137
  const status = error.code === 'browser_file_too_large' ? 413
@@ -135,7 +149,8 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
135
149
  const ready = () => { server.off('error', error); resolve(); };
136
150
  server.once('error', error); server.once('listening', ready); server.listen(0, '127.0.0.1');
137
151
  });
138
- origin = `http://127.0.0.1:${server.address().port}`;
152
+ const hostname = interactivePreview ? `preview-${randomBytes(12).toString('hex')}.localhost` : '127.0.0.1';
153
+ origin = `http://${hostname}:${server.address().port}`;
139
154
  signal?.throwIfAborted();
140
155
  } catch (error) { server.close(); server.closeAllConnections(); throw error; }
141
156
 
@@ -149,7 +164,7 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
149
164
  };
150
165
  const abort = () => { void close().catch(() => {}); };
151
166
  signal?.addEventListener('abort', abort, { once: true });
152
- return { workspace, servedRoot, entry, origin, url: `${origin}${prefix}${encodeURIComponent(basename(entry))}`, initialRevision,
167
+ return { workspace, servedRoot, entry, origin, url: `${origin}${prefix}${entryPath.map(encodeURIComponent).join('/')}`, initialRevision,
153
168
  revision, close,
154
169
  allows(value) {
155
170
  return allowsWorkspaceBrowserUrl(value, { origin, prefix, closed });
@@ -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 => 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; } };
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
  }