@kingsoftcloud/agentkit-harness-node 0.0.16 → 0.0.18

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.
Files changed (41) hide show
  1. package/dist/engine-view.html +566 -0
  2. package/dist/index.mjs +22 -14
  3. package/dist/rpc-entry.mjs +22 -14
  4. package/package.json +16 -2
  5. package/src/native/child-owner.mjs +8 -4
  6. package/src/native/children.mjs +12 -7
  7. package/src/native/command-shell.mjs +28 -3
  8. package/src/native/engine-client.mjs +83 -0
  9. package/src/native/engine-context.mjs +47 -0
  10. package/src/native/engine-hooks.mjs +53 -0
  11. package/src/native/engine-host-effects.mjs +98 -0
  12. package/src/native/engine-managed-delivery.mjs +65 -0
  13. package/src/native/engine-managed-host.mjs +75 -0
  14. package/src/native/engine-managed-service.mjs +249 -0
  15. package/src/native/engine-runtime.mjs +480 -0
  16. package/src/native/engine-server.mjs +454 -0
  17. package/src/native/engine-service.mjs +281 -0
  18. package/src/native/engine-tool-policy.mjs +29 -0
  19. package/src/native/engine-verification.mjs +111 -0
  20. package/src/native/engine-view-store.mjs +63 -0
  21. package/src/native/instruction-assembly.mjs +67 -3
  22. package/src/native/local-background-supervisor.mjs +1 -1
  23. package/src/native/local-background.mjs +4 -3
  24. package/src/native/local-command-tools.mjs +10 -7
  25. package/src/native/model-provider-compat.mjs +12 -7
  26. package/src/native/native-kernel-events.mjs +103 -0
  27. package/src/native/native-kernel-permit.mjs +95 -0
  28. package/src/native/native-managed-execution-grants.mjs +232 -0
  29. package/src/native/native-managed-injection.mjs +53 -0
  30. package/src/native/native-managed-interaction.mjs +192 -0
  31. package/src/native/native-managed-kernel-http.mjs +122 -0
  32. package/src/native/native-managed-kernel.mjs +922 -0
  33. package/src/native/native-managed-scoped-control.mjs +116 -0
  34. package/src/native/native-managed-session-frames.mjs +43 -0
  35. package/src/native/native-managed-teams-context.mjs +126 -0
  36. package/src/native/native-teams-callback-authority.mjs +73 -0
  37. package/src/native/native-teams-context-contract.mjs +272 -0
  38. package/src/native/native-teams-json.mjs +38 -0
  39. package/src/native/native-terminal-failure.mjs +53 -0
  40. package/src/native/sqlite-store.mjs +1 -0
  41. package/src/native/workspace-tools.mjs +2 -0
package/dist/index.mjs CHANGED
@@ -1293,6 +1293,10 @@ var SqliteRunStore = class extends TransactionalRunStore {
1293
1293
  return scope;
1294
1294
  });
1295
1295
  };
1296
+ this.probe = () => {
1297
+ open();
1298
+ db.prepare("SELECT version FROM native_schema LIMIT 1").get();
1299
+ };
1296
1300
  this.close = () => {
1297
1301
  if (!closed) {
1298
1302
  db.close();
@@ -2009,6 +2013,7 @@ function taggedPrefixProjector(marker) {
2009
2013
  }
2010
2014
 
2011
2015
  // packages/agentkit-harness-node/src/native/model-provider-compat.mjs
2016
+ import { FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL2 } from "@kingsoftcloud/agentkit-harness-core";
2012
2017
  var strict = /* @__PURE__ */ new Set(["openai", "strict-openai", "cerebras", "groq"]);
2013
2018
  var requiredAuto = /* @__PURE__ */ new Set(["claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-1", "claude-mythos-5-1"]);
2014
2019
  var mandatory = /* @__PURE__ */ new Set(["claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5-5"]);
@@ -2039,26 +2044,28 @@ function applyAnthropicThinking(payload, profile, binding) {
2039
2044
  }
2040
2045
  function resolveProviderCompatibility(policy, binding) {
2041
2046
  if (!policy) return null;
2042
- if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
2047
+ const version = ["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4", "provider-compat/v5"].indexOf(policy.contract) + 1;
2048
+ if (!version) throw new ProtocolError("invalid_provider_compatibility_policy");
2043
2049
  const rule = resolveCompatibilityRule(policy.rule, binding);
2044
2050
  const name = String(binding.model ?? "").trim().toLowerCase();
2045
2051
  const kimi = ["kspmas-gateway", "moonshot"].includes(rule) && ["kimi-k2.7-code", "kimi-k2.7-code-highspeed"].includes(name);
2046
- const modern = ["provider-compat/v3", "provider-compat/v4"].includes(policy.contract);
2052
+ const modern = version >= 3;
2047
2053
  const reasoningRequired = modern && rule === "kspmas-gateway" && name === "glm-5.3-flash";
2048
2054
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === "claude-haiku-5-5" ? ["low", "medium", "high"] : null;
2049
2055
  return {
2050
2056
  rule,
2051
2057
  supportsUsage: !strict.has(rule),
2052
2058
  supportsThinking: !strict.has(rule) && !kimi,
2053
- supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2059
+ supportsToolArgumentStreaming: version >= 2 && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2054
2060
  reasoningRequired,
2055
2061
  modern,
2062
+ firstToolLowEffort: version >= 5 && reasoningRequired,
2056
2063
  // This route already uses the supported non-thinking mode for tool work.
2057
2064
  // A bounded summary has no tools: omitting the switch can instead select
2058
2065
  // the provider's default high reasoning and consume its whole output cap.
2059
2066
  // Freeze this purpose-specific default only on new admissions; mandatory
2060
2067
  // thinking models and explicit caller choices remain authoritative.
2061
- compactionThinkingOff: policy.contract === "provider-compat/v4" && rule === "kspmas-gateway" && !kimi,
2068
+ compactionThinkingOff: version >= 4 && rule === "kspmas-gateway" && !kimi,
2062
2069
  // Only the observed provider/model dialects may seal without [DONE].
2063
2070
  finishOnEof: modern && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
2064
2071
  supportsEffort: !kimi,
@@ -2099,7 +2106,9 @@ function applyProviderChatCompatibility(payload, request, binding) {
2099
2106
  }
2100
2107
  const model = binding.model, name = normalized(model);
2101
2108
  const requested = options.reasoningEffort ?? result.reasoning_effort ?? null;
2109
+ const mode = options.thinkingMode ?? result.thinking?.type;
2102
2110
  let effort = requested;
2111
+ if (requested === null && mode === void 0 && compat.firstToolLowEffort && request.beforeFirstTool && !request.finalizationOnly && result.tool_choice !== "none" && result.tools?.some((tool) => tool.type === "function" && tool.function?.name !== FINAL_SUBMISSION_TOOL2)) effort = "low";
2103
2112
  if (requested === null && options.controllerReasoningPolicy === "disclosed-delegate/v1" && ["zai", "kspmas-gateway"].includes(compat.rule) && name.startsWith("glm-5.3") && result.tools?.some((tool) => tool.type === "function" && tool.function?.name === "delegate_task")) effort = "low";
2104
2113
  if (requested === null && request.purpose === "compaction" && compat.rule === "kspmas-gateway" && ["glm-5.2", "deepseek-v4-flash"].includes(name)) effort = "none";
2105
2114
  if (requested === null && request.purpose === "compaction" && compat.reasoningRequired) effort = "low";
@@ -2111,7 +2120,6 @@ function applyProviderChatCompatibility(payload, request, binding) {
2111
2120
  delete result.stream_options.include_usage;
2112
2121
  if (!Object.keys(result.stream_options).length) delete result.stream_options;
2113
2122
  }
2114
- const mode = options.thinkingMode ?? result.thinking?.type;
2115
2123
  if (mode === "disabled" && compat.reasoningRequired) throw new ProtocolError("model_thinking_disable_unsupported");
2116
2124
  const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
2117
2125
  const summaryOff = request.purpose === "compaction" && requested === null && compat.rule === "kspmas-gateway" && name === "glm-5.3-flash";
@@ -2249,7 +2257,7 @@ function mergeChatUsage(previous, reported, policy, finalized = false) {
2249
2257
  }
2250
2258
 
2251
2259
  // packages/agentkit-harness-node/src/native/model-openai-chat.mjs
2252
- import { parseModelJson, stringifyModelJson, modelWireToolCall as modelWireToolCall2, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL2 } from "@kingsoftcloud/agentkit-harness-core";
2260
+ import { parseModelJson, stringifyModelJson, modelWireToolCall as modelWireToolCall2, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL3 } from "@kingsoftcloud/agentkit-harness-core";
2253
2261
  function strictParseJson(text) {
2254
2262
  try {
2255
2263
  return parseModelJson(text);
@@ -2317,13 +2325,13 @@ function buildOpenAIRequest(binding, request) {
2317
2325
  payload.max_tokens = boundOutputTokens(parameters.max_tokens, profile.maxOutputTokens);
2318
2326
  }
2319
2327
  const tools = request.tools || [];
2320
- const advertised = request.finalizationOnly ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL2) : tools;
2328
+ const advertised = request.finalizationOnly ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL3) : tools;
2321
2329
  if (advertised.length) {
2322
2330
  payload.tools = advertised.map((tool) => ({
2323
2331
  type: "function",
2324
2332
  function: { name: tool.name, description: tool.description, parameters: tool.parameters || { type: "object", properties: {} } }
2325
2333
  }));
2326
- payload.tool_choice = request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL2 } } : "auto");
2334
+ payload.tool_choice = request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL3 } } : "auto");
2327
2335
  }
2328
2336
  if (profile.parallelToolCalls !== void 0) payload.parallel_tool_calls = profile.parallelToolCalls;
2329
2337
  if (profile.temperature !== void 0) payload.temperature = profile.temperature;
@@ -2813,7 +2821,7 @@ function usageCounters(usage) {
2813
2821
  }
2814
2822
 
2815
2823
  // packages/agentkit-harness-node/src/native/model-anthropic.mjs
2816
- import { parseModelJson as parseModelJson2, stringifyModelJson as stringifyModelJson2, parseNativeJson as parseNativeJson3, modelWireToolCall as modelWireToolCall3, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL3 } from "@kingsoftcloud/agentkit-harness-core";
2824
+ import { parseModelJson as parseModelJson2, stringifyModelJson as stringifyModelJson2, parseNativeJson as parseNativeJson3, modelWireToolCall as modelWireToolCall3, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL4 } from "@kingsoftcloud/agentkit-harness-core";
2817
2825
 
2818
2826
  // packages/agentkit-harness-node/src/native/model-anthropic-cache.mjs
2819
2827
  var ephemeral = () => ({ type: "ephemeral" });
@@ -2985,7 +2993,7 @@ function buildAnthropicRequest(binding, request) {
2985
2993
  payload[key] = value;
2986
2994
  }
2987
2995
  const tools = request.tools || [];
2988
- const advertised = request.finalizationOnly && profile.toolCatalogPolicy !== "stable-task/v1" && !native ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL3) : tools;
2996
+ const advertised = request.finalizationOnly && profile.toolCatalogPolicy !== "stable-task/v1" && !native ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL4) : tools;
2989
2997
  if (advertised.length) {
2990
2998
  payload.tools = advertised.map((tool) => native ? anthropicToolEntry(tool) : {
2991
2999
  name: tool.name,
@@ -2993,7 +3001,7 @@ function buildAnthropicRequest(binding, request) {
2993
3001
  input_schema: tool.parameters || { type: "object", properties: {} }
2994
3002
  });
2995
3003
  const choice = projectProviderToolChoice(
2996
- request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly && advertised.some((tool) => tool.name === FINAL_SUBMISSION_TOOL3) ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL3 } } : "auto"),
3004
+ request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly && advertised.some((tool) => tool.name === FINAL_SUBMISSION_TOOL4) ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL4 } } : "auto"),
2997
3005
  resolveProviderCompatibility(profile.providerCompatibilityPolicy, binding)
2998
3006
  );
2999
3007
  payload.tool_choice = typeof choice === "string" ? { type: choice === "required" ? "any" : choice } : { type: "tool", name: choice.function.name };
@@ -3593,7 +3601,7 @@ function deepCopy(value) {
3593
3601
  }
3594
3602
 
3595
3603
  // packages/agentkit-harness-node/src/native/model-responses.mjs
3596
- import { parseModelJson as parseModelJson3, stringifyModelJson as stringifyModelJson3, modelWireToolCall as modelWireToolCall4, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL4 } from "@kingsoftcloud/agentkit-harness-core";
3604
+ import { parseModelJson as parseModelJson3, stringifyModelJson as stringifyModelJson3, modelWireToolCall as modelWireToolCall4, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL5 } from "@kingsoftcloud/agentkit-harness-core";
3597
3605
  function strictParseJson3(text) {
3598
3606
  try {
3599
3607
  return parseModelJson3(text);
@@ -3710,7 +3718,7 @@ function buildResponsesRequest(binding, request) {
3710
3718
  payload.max_output_tokens = boundOutputTokens(parameters.max_output_tokens, profile.maxOutputTokens);
3711
3719
  }
3712
3720
  const tools = request.tools || [];
3713
- const advertised = request.finalizationOnly ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL4) : tools;
3721
+ const advertised = request.finalizationOnly ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL5) : tools;
3714
3722
  if (advertised.length) {
3715
3723
  payload.tools = advertised.map((tool) => {
3716
3724
  const flat = {
@@ -3721,7 +3729,7 @@ function buildResponsesRequest(binding, request) {
3721
3729
  };
3722
3730
  return flat;
3723
3731
  });
3724
- const choice = request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL4 } } : "auto");
3732
+ const choice = request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL5 } } : "auto");
3725
3733
  payload.tool_choice = typeof choice === "string" ? choice : { type: "function", name: choice.function.name };
3726
3734
  payload.parallel_tool_calls = profile.parallelToolCalls ?? true;
3727
3735
  }
@@ -1304,6 +1304,10 @@ var SqliteRunStore = class extends TransactionalRunStore {
1304
1304
  return scope;
1305
1305
  });
1306
1306
  };
1307
+ this.probe = () => {
1308
+ open2();
1309
+ db.prepare("SELECT version FROM native_schema LIMIT 1").get();
1310
+ };
1307
1311
  this.close = () => {
1308
1312
  if (!closed) {
1309
1313
  db.close();
@@ -2020,6 +2024,7 @@ function taggedPrefixProjector(marker) {
2020
2024
  }
2021
2025
 
2022
2026
  // packages/agentkit-harness-node/src/native/model-provider-compat.mjs
2027
+ import { FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL2 } from "@kingsoftcloud/agentkit-harness-core";
2023
2028
  var strict = /* @__PURE__ */ new Set(["openai", "strict-openai", "cerebras", "groq"]);
2024
2029
  var requiredAuto = /* @__PURE__ */ new Set(["claude-opus-5-5", "claude-sonnet-5-5", "claude-fable-5-1", "claude-mythos-5-1"]);
2025
2030
  var mandatory = /* @__PURE__ */ new Set(["claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5-5"]);
@@ -2050,26 +2055,28 @@ function applyAnthropicThinking(payload, profile, binding) {
2050
2055
  }
2051
2056
  function resolveProviderCompatibility(policy, binding) {
2052
2057
  if (!policy) return null;
2053
- if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
2058
+ const version = ["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4", "provider-compat/v5"].indexOf(policy.contract) + 1;
2059
+ if (!version) throw new ProtocolError("invalid_provider_compatibility_policy");
2054
2060
  const rule = resolveCompatibilityRule(policy.rule, binding);
2055
2061
  const name = String(binding.model ?? "").trim().toLowerCase();
2056
2062
  const kimi = ["kspmas-gateway", "moonshot"].includes(rule) && ["kimi-k2.7-code", "kimi-k2.7-code-highspeed"].includes(name);
2057
- const modern = ["provider-compat/v3", "provider-compat/v4"].includes(policy.contract);
2063
+ const modern = version >= 3;
2058
2064
  const reasoningRequired = modern && rule === "kspmas-gateway" && name === "glm-5.3-flash";
2059
2065
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === "claude-haiku-5-5" ? ["low", "medium", "high"] : null;
2060
2066
  return {
2061
2067
  rule,
2062
2068
  supportsUsage: !strict.has(rule),
2063
2069
  supportsThinking: !strict.has(rule) && !kimi,
2064
- supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2070
+ supportsToolArgumentStreaming: version >= 2 && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2065
2071
  reasoningRequired,
2066
2072
  modern,
2073
+ firstToolLowEffort: version >= 5 && reasoningRequired,
2067
2074
  // This route already uses the supported non-thinking mode for tool work.
2068
2075
  // A bounded summary has no tools: omitting the switch can instead select
2069
2076
  // the provider's default high reasoning and consume its whole output cap.
2070
2077
  // Freeze this purpose-specific default only on new admissions; mandatory
2071
2078
  // thinking models and explicit caller choices remain authoritative.
2072
- compactionThinkingOff: policy.contract === "provider-compat/v4" && rule === "kspmas-gateway" && !kimi,
2079
+ compactionThinkingOff: version >= 4 && rule === "kspmas-gateway" && !kimi,
2073
2080
  // Only the observed provider/model dialects may seal without [DONE].
2074
2081
  finishOnEof: modern && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
2075
2082
  supportsEffort: !kimi,
@@ -2110,7 +2117,9 @@ function applyProviderChatCompatibility(payload, request, binding) {
2110
2117
  }
2111
2118
  const model = binding.model, name = normalized(model);
2112
2119
  const requested = options.reasoningEffort ?? result.reasoning_effort ?? null;
2120
+ const mode = options.thinkingMode ?? result.thinking?.type;
2113
2121
  let effort = requested;
2122
+ if (requested === null && mode === void 0 && compat.firstToolLowEffort && request.beforeFirstTool && !request.finalizationOnly && result.tool_choice !== "none" && result.tools?.some((tool) => tool.type === "function" && tool.function?.name !== FINAL_SUBMISSION_TOOL2)) effort = "low";
2114
2123
  if (requested === null && options.controllerReasoningPolicy === "disclosed-delegate/v1" && ["zai", "kspmas-gateway"].includes(compat.rule) && name.startsWith("glm-5.3") && result.tools?.some((tool) => tool.type === "function" && tool.function?.name === "delegate_task")) effort = "low";
2115
2124
  if (requested === null && request.purpose === "compaction" && compat.rule === "kspmas-gateway" && ["glm-5.2", "deepseek-v4-flash"].includes(name)) effort = "none";
2116
2125
  if (requested === null && request.purpose === "compaction" && compat.reasoningRequired) effort = "low";
@@ -2122,7 +2131,6 @@ function applyProviderChatCompatibility(payload, request, binding) {
2122
2131
  delete result.stream_options.include_usage;
2123
2132
  if (!Object.keys(result.stream_options).length) delete result.stream_options;
2124
2133
  }
2125
- const mode = options.thinkingMode ?? result.thinking?.type;
2126
2134
  if (mode === "disabled" && compat.reasoningRequired) throw new ProtocolError("model_thinking_disable_unsupported");
2127
2135
  const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
2128
2136
  const summaryOff = request.purpose === "compaction" && requested === null && compat.rule === "kspmas-gateway" && name === "glm-5.3-flash";
@@ -2260,7 +2268,7 @@ function mergeChatUsage(previous, reported, policy, finalized = false) {
2260
2268
  }
2261
2269
 
2262
2270
  // packages/agentkit-harness-node/src/native/model-openai-chat.mjs
2263
- import { parseModelJson, stringifyModelJson, modelWireToolCall as modelWireToolCall2, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL2 } from "@kingsoftcloud/agentkit-harness-core";
2271
+ import { parseModelJson, stringifyModelJson, modelWireToolCall as modelWireToolCall2, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL3 } from "@kingsoftcloud/agentkit-harness-core";
2264
2272
  function strictParseJson(text) {
2265
2273
  try {
2266
2274
  return parseModelJson(text);
@@ -2328,13 +2336,13 @@ function buildOpenAIRequest(binding, request) {
2328
2336
  payload.max_tokens = boundOutputTokens(parameters.max_tokens, profile.maxOutputTokens);
2329
2337
  }
2330
2338
  const tools = request.tools || [];
2331
- const advertised = request.finalizationOnly ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL2) : tools;
2339
+ const advertised = request.finalizationOnly ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL3) : tools;
2332
2340
  if (advertised.length) {
2333
2341
  payload.tools = advertised.map((tool) => ({
2334
2342
  type: "function",
2335
2343
  function: { name: tool.name, description: tool.description, parameters: tool.parameters || { type: "object", properties: {} } }
2336
2344
  }));
2337
- payload.tool_choice = request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL2 } } : "auto");
2345
+ payload.tool_choice = request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL3 } } : "auto");
2338
2346
  }
2339
2347
  if (profile.parallelToolCalls !== void 0) payload.parallel_tool_calls = profile.parallelToolCalls;
2340
2348
  if (profile.temperature !== void 0) payload.temperature = profile.temperature;
@@ -2824,7 +2832,7 @@ function usageCounters(usage) {
2824
2832
  }
2825
2833
 
2826
2834
  // packages/agentkit-harness-node/src/native/model-anthropic.mjs
2827
- import { parseModelJson as parseModelJson2, stringifyModelJson as stringifyModelJson2, parseNativeJson as parseNativeJson3, modelWireToolCall as modelWireToolCall3, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL3 } from "@kingsoftcloud/agentkit-harness-core";
2835
+ import { parseModelJson as parseModelJson2, stringifyModelJson as stringifyModelJson2, parseNativeJson as parseNativeJson3, modelWireToolCall as modelWireToolCall3, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL4 } from "@kingsoftcloud/agentkit-harness-core";
2828
2836
 
2829
2837
  // packages/agentkit-harness-node/src/native/model-anthropic-cache.mjs
2830
2838
  var ephemeral = () => ({ type: "ephemeral" });
@@ -2996,7 +3004,7 @@ function buildAnthropicRequest(binding, request) {
2996
3004
  payload[key] = value;
2997
3005
  }
2998
3006
  const tools = request.tools || [];
2999
- const advertised = request.finalizationOnly && profile.toolCatalogPolicy !== "stable-task/v1" && !native ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL3) : tools;
3007
+ const advertised = request.finalizationOnly && profile.toolCatalogPolicy !== "stable-task/v1" && !native ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL4) : tools;
3000
3008
  if (advertised.length) {
3001
3009
  payload.tools = advertised.map((tool) => native ? anthropicToolEntry(tool) : {
3002
3010
  name: tool.name,
@@ -3004,7 +3012,7 @@ function buildAnthropicRequest(binding, request) {
3004
3012
  input_schema: tool.parameters || { type: "object", properties: {} }
3005
3013
  });
3006
3014
  const choice = projectProviderToolChoice(
3007
- request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly && advertised.some((tool) => tool.name === FINAL_SUBMISSION_TOOL3) ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL3 } } : "auto"),
3015
+ request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly && advertised.some((tool) => tool.name === FINAL_SUBMISSION_TOOL4) ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL4 } } : "auto"),
3008
3016
  resolveProviderCompatibility(profile.providerCompatibilityPolicy, binding)
3009
3017
  );
3010
3018
  payload.tool_choice = typeof choice === "string" ? { type: choice === "required" ? "any" : choice } : { type: "tool", name: choice.function.name };
@@ -3604,7 +3612,7 @@ function deepCopy(value) {
3604
3612
  }
3605
3613
 
3606
3614
  // packages/agentkit-harness-node/src/native/model-responses.mjs
3607
- import { parseModelJson as parseModelJson3, stringifyModelJson as stringifyModelJson3, modelWireToolCall as modelWireToolCall4, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL4 } from "@kingsoftcloud/agentkit-harness-core";
3615
+ import { parseModelJson as parseModelJson3, stringifyModelJson as stringifyModelJson3, modelWireToolCall as modelWireToolCall4, FINAL_SUBMISSION_TOOL as FINAL_SUBMISSION_TOOL5 } from "@kingsoftcloud/agentkit-harness-core";
3608
3616
  function strictParseJson3(text) {
3609
3617
  try {
3610
3618
  return parseModelJson3(text);
@@ -3721,7 +3729,7 @@ function buildResponsesRequest(binding, request) {
3721
3729
  payload.max_output_tokens = boundOutputTokens(parameters.max_output_tokens, profile.maxOutputTokens);
3722
3730
  }
3723
3731
  const tools = request.tools || [];
3724
- const advertised = request.finalizationOnly ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL4) : tools;
3732
+ const advertised = request.finalizationOnly ? tools.filter((tool) => tool.name === FINAL_SUBMISSION_TOOL5) : tools;
3725
3733
  if (advertised.length) {
3726
3734
  payload.tools = advertised.map((tool) => {
3727
3735
  const flat = {
@@ -3732,7 +3740,7 @@ function buildResponsesRequest(binding, request) {
3732
3740
  };
3733
3741
  return flat;
3734
3742
  });
3735
- const choice = request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL4 } } : "auto");
3743
+ const choice = request.toolChoice ?? (profile.providerCompatibilityPolicy && request.finalizationOnly ? { type: "function", function: { name: FINAL_SUBMISSION_TOOL5 } } : "auto");
3736
3744
  payload.tool_choice = typeof choice === "string" ? choice : { type: "function", name: choice.function.name };
3737
3745
  payload.parallel_tool_calls = profile.parallelToolCalls ?? true;
3738
3746
  }
package/package.json CHANGED
@@ -1,12 +1,24 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-node",
3
- "version": "0.0.16",
3
+ "version": "0.0.18",
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.",
7
7
  "exports": {
8
8
  ".": "./dist/index.mjs",
9
9
  "./rpc-entry": "./dist/rpc-entry.mjs",
10
+ "./native/engine-runtime": "./src/native/engine-runtime.mjs",
11
+ "./native/engine-server": "./src/native/engine-server.mjs",
12
+ "./native/engine-client": "./src/native/engine-client.mjs",
13
+ "./native/managed-kernel": "./src/native/native-managed-kernel.mjs",
14
+ "./native/managed-kernel-http": "./src/native/native-managed-kernel-http.mjs",
15
+ "./native/managed-scoped-control": "./src/native/native-managed-scoped-control.mjs",
16
+ "./native/teams-callback-authority": "./src/native/native-teams-callback-authority.mjs",
17
+ "./native/teams-context-contract": "./src/native/native-teams-context-contract.mjs",
18
+ "./native/kernel-events": "./src/native/native-kernel-events.mjs",
19
+ "./native/terminal-failure": "./src/native/native-terminal-failure.mjs",
20
+ "./native/kernel-permit": "./src/native/native-kernel-permit.mjs",
21
+ "./native/teams-json": "./src/native/native-teams-json.mjs",
10
22
  "./native/a2a-tools": "./src/native/a2a-tools.mjs",
11
23
  "./native/artifact-codec": "./src/native/artifact-codec.mjs",
12
24
  "./native/artifact-store": "./src/native/artifact-store.mjs",
@@ -127,6 +139,8 @@
127
139
  "./package-integrity": "./src/package-integrity.mjs"
128
140
  },
129
141
  "bin": {
142
+ "agentkit-engine": "./src/native/engine-server.mjs",
143
+ "agentkit-engine-service": "./src/native/engine-service.mjs",
130
144
  "agentkit-native-rpc": "./dist/rpc-entry.mjs"
131
145
  },
132
146
  "files": [
@@ -140,7 +154,7 @@
140
154
  "src/package-integrity.mjs"
141
155
  ],
142
156
  "dependencies": {
143
- "@kingsoftcloud/agentkit-harness-core": "0.0.16",
157
+ "@kingsoftcloud/agentkit-harness-core": "0.0.18",
144
158
  "@astral-sh/ruff-wasm-nodejs": "0.16.8",
145
159
  "parse5": "7.3.0",
146
160
  "playwright-core": "1.58.2",
@@ -34,7 +34,7 @@ async function observeWhileLive(operation, signal) {
34
34
  * an environment/profile fallback. This service does not advertise model tools.
35
35
  */
36
36
  export function createNativeChildOwner({ scope, childScopes = [scope], store, resolveChild, restoreChild, waitForIdle, canWaitForReceipt, onStream, now = Date.now,
37
- childAllocationPolicy, admitRequirements, owner = `native-children-${randomUUID()}` }) {
37
+ childAllocationPolicy, admitRequirements, detachSignal, owner = `native-children-${randomUUID()}` }) {
38
38
  const parentScope = copy(scope), entries = new Map();
39
39
  scopeKey(parentScope);
40
40
  check(childAllocationPolicy === undefined || childAllocationPolicy === CHILD_ALLOCATION_POLICY, 'invalid_child_owner_allocation_policy');
@@ -120,15 +120,16 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
120
120
  entry.error = null;
121
121
  entry.promise = (async () => {
122
122
  for (;;) {
123
- const snapshot = await entry.kernel.runUntilIdle(entry.scope, entry.runId);
123
+ const snapshot = await entry.kernel.runUntilIdle(entry.scope, entry.runId, { detachSignal });
124
124
  if (terminal(snapshot.phase)) { entry.ports.tools.settleQuestions?.(snapshot); return; }
125
125
  const record = store.load(entry.scope, entry.runId);
126
126
  if (!canWaitForReceipt?.(record) || !entry.admitted()) return;
127
127
  const idle = new AbortController(); entry.idle = idle;
128
128
  try {
129
+ const signal = detachSignal ? AbortSignal.any([idle.signal, detachSignal]) : idle.signal;
129
130
  const command = await observeWhileLive(Promise.resolve().then(() => waitForIdle({
130
- snapshot: copy(snapshot), tools: entry.ports.tools, signal: idle.signal,
131
- })), idle.signal);
131
+ snapshot: copy(snapshot), tools: entry.ports.tools, signal,
132
+ })), signal);
132
133
  idle.signal.throwIfAborted();
133
134
  check(entry.admitted() && same(store.load(entry.scope, entry.runId).snapshot, snapshot), 'child_idle_authority_lost');
134
135
  if (!command) return;
@@ -629,6 +630,9 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
629
630
  }
630
631
  for (const entry of owned) entries.delete(entry.runId);
631
632
  },
633
+ async drain() {
634
+ await Promise.all([...entries.values()].map(entry => entry.promise));
635
+ },
632
636
  async closeRun(request) {
633
637
  check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
634
638
  const parent = store.load(parentScope, request.runId);
@@ -112,7 +112,7 @@ export function nativeChildRoles(spec = {}, { childAllocationPolicy } = {}) {
112
112
 
113
113
  /** Bind every child to a declared role and its own scoped tool state. */
114
114
  export async function createNativeChildren({ roles, scope, sessionId, store, tools, hasSkills, hasMcp, mcpBinding, skillBinding, skillInstructions, workspaceContext, instructionTimeoutRecovery,
115
- resolveModel, bindTools, verificationFactory, fileWorkspaces, commandResource, isClosed, onStream, a2aBinding, waitForChildReceipt, mediaSources = new Map(), artifactPolicy, artifactFactory, sourceReadPolicy, childTaskPolicy, childPlanPolicy, childAllocationPolicy, childCapabilityPolicy, outputRecoveryPolicy, outputRestartPolicy, approvalOutcomePolicy, conversationPresentation, toolExecutionPolicy, toolAdmissionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }) }) {
115
+ resolveModel, bindTools, verificationFactory, fileWorkspaces, commandResource, isClosed, onStream, detachSignal, a2aBinding, waitForChildReceipt, mediaSources = new Map(), artifactPolicy, artifactFactory, sourceReadPolicy, childTaskPolicy, childPlanPolicy, childAllocationPolicy, childCapabilityPolicy, outputRecoveryPolicy, outputRestartPolicy, approvalOutcomePolicy, conversationPresentation, toolExecutionPolicy, toolAdmissionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }), restrictTools }) {
116
116
  if (!roles.length) return null;
117
117
  if (workspaceContext !== undefined) {
118
118
  validateNativeWorkspaceContext(workspaceContext);
@@ -124,9 +124,9 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
124
124
  invariant(toolAdmissionPolicy === undefined || toolAdmissionPolicy === 'discover-before-retry/v1', 'studio_native_child_admission_policy_invalid');
125
125
  invariant(toolExecutionPolicy === undefined || toolExecutionPolicy === 'owner-execution/v1', 'studio_native_child_execution_policy_invalid');
126
126
  invariant(providerRecoveryPolicy === undefined || providerRecoveryPolicy === 'provider-recovery/v2', 'native_child_provider_recovery_policy_invalid');
127
- invariant(outputRecoveryPolicy === undefined || ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'studio_native_child_output_policy_invalid');
127
+ invariant(outputRecoveryPolicy === undefined || ['response-boundary/v2', 'response-boundary/v3', 'response-boundary/v4', 'response-boundary/v5'].includes(outputRecoveryPolicy), 'studio_native_child_output_policy_invalid');
128
128
  invariant(outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(outputRestartPolicy)
129
- && ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'native_child_output_restart_policy_invalid');
129
+ && ['response-boundary/v2', 'response-boundary/v3', 'response-boundary/v4', 'response-boundary/v5'].includes(outputRecoveryPolicy), 'native_child_output_restart_policy_invalid');
130
130
  invariant(approvalOutcomePolicy === undefined || approvalOutcomePolicy === 'owner-outcome/v1', 'native_child_approval_outcome_policy_invalid');
131
131
  if (conversationPresentation !== undefined) validateConversationPresentation(conversationPresentation);
132
132
  invariant(childTaskPolicy === undefined || childTaskPolicy === CHILD_TASK_POLICY, 'studio_native_child_task_policy_invalid');
@@ -187,14 +187,16 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
187
187
  ? createStudioNativeChildMerge({ scope, sessionId, store, roles, fileWorkspaces, isClosed,
188
188
  previousPublication: previousChildPublication, authorize: async () => 'allow' }) : null;
189
189
  const readers = createNativeChildResultTools({ scope, childScopes: roles.map(childScope), store, roles: roles.map(role => role.name) });
190
- const owner = createNativeChildOwner({ scope, onStream, childScopes: roles.map(childScope), store,
190
+ const owner = createNativeChildOwner({ scope, onStream, detachSignal, childScopes: roles.map(childScope), store,
191
191
  ...(childCapabilityPolicy ? { admitRequirements: args => admitChildCapabilities(
192
192
  [...bindings].map(([role, bound]) => ({ role, tools: bound.tools.map(tool => tool.name).sort() })), args.role, args.required_tools) } : {}),
193
193
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
194
194
  ...(waitForChildReceipt ? { canWaitForReceipt: record => !!nativeA2aReceiptWaitSource(record), waitForIdle: waitForChildReceipt } : {}),
195
195
  resolveChild: async request => {
196
- const role = byName.get(request.role), bound = bindings.get(request.role);
197
- invariant(role && bound, 'studio_native_child_role_unbound');
196
+ const role = byName.get(request.role), available = bindings.get(request.role);
197
+ invariant(role && available, 'studio_native_child_role_unbound');
198
+ const bound = restrictTools ? { ...available, tools: restrictTools(available.tools,
199
+ store.authority(request.parent.scope, request.parent.runId).configuration) } : available;
198
200
  const args = request.call.arguments;
199
201
  const refs = args.media ?? [];
200
202
  invariant(Array.isArray(refs) && refs.length <= 20 && refs.every(ref => ref && typeof ref === 'object'
@@ -299,8 +301,10 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
299
301
  input: ports.input, store, scope: child, sessionId: request.childSessionId, tools: bound.tools }), verification } };
300
302
  },
301
303
  restoreChild: async ({ identity, configuration, binding }) => {
302
- const bound = bindings.get(binding.role), role = byName.get(binding.role);
304
+ const available = bindings.get(binding.role), role = byName.get(binding.role);
303
305
  const parent = store.load(binding.parent.scope, binding.parent.runId);
306
+ const bound = available && restrictTools
307
+ ? { ...available, tools: restrictTools(available.tools, parent.configuration) } : available;
304
308
  const call = parent.intents.find(item => item.operationKey === binding.parentOperationKey)?.payload.calls
305
309
  ?.find(item => item.callId === binding.parentToolCallId);
306
310
  invariant(call && role, 'studio_native_child_restore_binding_changed');
@@ -324,6 +328,7 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
324
328
  // Reconstruct the same normalized profile, rather than comparing it to
325
329
  // the Host's deliberately partial input and rejecting every live child.
326
330
  const profile = bound && configure({ profile: bound.model.profile, contract: configuration.contract,
331
+ limits: { effectTimeoutMs: configuration.limits.effectTimeoutMs },
327
332
  hostBindingDigest: configuration.hostBindingDigest }).profile;
328
333
  invariant(bound && role && canonical(configuration.tools) === canonical(bound.tools)
329
334
  && configuration.outputRecoveryPolicy === outputRecoveryPolicy
@@ -1,9 +1,34 @@
1
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
2
+
1
3
  export const LOCAL_COMMAND_SHELL = 'bash-execution/v1';
4
+ export const ISOLATED_COMMAND_SHELL = 'bubblewrap-workspace/v1';
2
5
 
3
6
  /** A missing policy belongs to a persisted legacy request. Never reinterpret
4
7
  * it under a new shell during supervision/recovery. No PATH-based fallback.
5
8
  */
6
- export function shellCommandArgv(command, policy = null) {
7
- if (policy !== null && policy !== LOCAL_COMMAND_SHELL) throw Error('unsupported_command_shell');
8
- return [policy === LOCAL_COMMAND_SHELL ? '/bin/bash' : '/bin/sh', '-c', command];
9
+ export function shellCommandArgv(command, policy = null, { workspaceRoot, cwd } = {}) {
10
+ if (policy === null) return ['/bin/sh', '-c', command];
11
+ if (policy === LOCAL_COMMAND_SHELL) return ['/bin/bash', '-c', command];
12
+ if (policy !== ISOLATED_COMMAND_SHELL) throw Error('unsupported_command_shell');
13
+ if (process.platform !== 'linux' || typeof workspaceRoot !== 'string' || typeof cwd !== 'string'
14
+ || !isAbsolute(workspaceRoot) || !isAbsolute(cwd) || resolve(workspaceRoot) !== workspaceRoot
15
+ || resolve(cwd) !== cwd
16
+ || (workspaceRoot !== '/data/workspace' && !workspaceRoot.startsWith('/data/workspace/')))
17
+ throw Error('isolated_command_workspace_invalid');
18
+ const within = relative(workspaceRoot, cwd);
19
+ if (within === '..' || within.startsWith('..' + sep) || isAbsolute(within))
20
+ throw Error('isolated_command_cwd_outside_workspace');
21
+
22
+ // The managed image supplies Debian's usr-merged filesystem. Only the
23
+ // workspace and disposable tmpfs are writable. Neither the state volume nor
24
+ // the engine's PID namespace or deployment credential mounts are visible.
25
+ return ['/usr/bin/bwrap', '--unshare-user', '--unshare-pid', '--unshare-ipc', '--unshare-uts',
26
+ '--unshare-net', '--die-with-parent', '--new-session', '--cap-drop', 'ALL',
27
+ '--ro-bind', '/usr', '/usr', '--symlink', 'usr/bin', '/bin', '--symlink', 'usr/sbin', '/sbin',
28
+ '--symlink', 'usr/lib', '/lib', '--symlink', 'usr/lib64', '/lib64',
29
+ '--dir', '/proc', '--dev', '/dev', '--tmpfs', '/tmp',
30
+ '--ro-bind', '/etc/passwd', '/etc/passwd', '--ro-bind', '/etc/group', '/etc/group',
31
+ '--bind', workspaceRoot, workspaceRoot, '--chdir', cwd,
32
+ '--clearenv', '--setenv', 'PATH', '/usr/local/bin:/usr/bin:/bin', '--setenv', 'HOME', '/tmp',
33
+ '--setenv', 'LANG', 'C.UTF-8', '--setenv', 'CI', '1', '--', '/bin/bash', '-c', command];
9
34
  }
@@ -0,0 +1,83 @@
1
+ // Thin host-side client for agentkit.engine/v1.
2
+ //
3
+ // This file contains no engine logic and imports none: it frames JSON-RPC over
4
+ // a child process's stdio. A host may vendor it, or reimplement it in another
5
+ // language from the protocol alone. It needs to change only when the protocol
6
+ // major version changes.
7
+ import { spawn } from 'node:child_process';
8
+ import * as readline from 'node:readline';
9
+
10
+ export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
11
+
12
+ /** Connect to an engine over a pair of streams (a spawned process, a socket, or an in-memory pair in tests). */
13
+ export function connectEngine({ input, output, onApproveTool, onCallTool, hostName = 'host' }) {
14
+ let next = 1, closed = false;
15
+ const pending = new Map();
16
+ const send = frame => output.write(`${JSON.stringify(frame)}\n`);
17
+ const frames = readline.createInterface({ input, crlfDelay: Infinity });
18
+ const finished = (async () => {
19
+ for await (const line of frames) {
20
+ if (!line.trim()) continue;
21
+ let frame;
22
+ try { frame = JSON.parse(line); } catch { continue; }
23
+ if (frame.method !== undefined) {
24
+ // Engine -> host request. Unknown methods are refused, never guessed.
25
+ if (frame.method === 'host/approveTool' && typeof onApproveTool === 'function') {
26
+ Promise.resolve().then(() => onApproveTool(frame.params ?? {}))
27
+ .then(decision => send({ jsonrpc: '2.0', id: frame.id, result: { decision: decision === 'allow' ? 'allow' : 'deny' } }),
28
+ () => send({ jsonrpc: '2.0', id: frame.id, result: { decision: 'deny' } }));
29
+ } else if (frame.method === 'host/callTool' && typeof onCallTool === 'function') {
30
+ Promise.resolve().then(() => onCallTool(frame.params ?? {}))
31
+ .then(reply => send({ jsonrpc: '2.0', id: frame.id, result: { status: reply?.status === 'error' ? 'error' : 'ok', content: reply?.content ?? null } }),
32
+ error => send({ jsonrpc: '2.0', id: frame.id, result: { status: 'error', content: { code: 'host_tool_failed', message: String(error?.message ?? error).slice(0, 2000) } } }));
33
+ } else if (frame.id !== undefined) send({ jsonrpc: '2.0', id: frame.id, error: { code: -32601, message: 'Method not found' } });
34
+ continue;
35
+ }
36
+ const waiter = pending.get(frame.id);
37
+ if (!waiter) continue;
38
+ pending.delete(frame.id);
39
+ if (frame.error) waiter.reject(Object.assign(new Error(frame.error.message), { code: frame.error.code, data: frame.error.data }));
40
+ else waiter.resolve(frame.result);
41
+ }
42
+ closed = true;
43
+ for (const waiter of pending.values()) waiter.reject(new Error('engine connection closed'));
44
+ pending.clear();
45
+ })();
46
+ const call = (method, params = {}) => new Promise((resolve, reject) => {
47
+ if (closed) { reject(new Error('engine connection closed')); return; }
48
+ const id = next++;
49
+ pending.set(id, { resolve, reject });
50
+ send({ jsonrpc: '2.0', id, method, params });
51
+ });
52
+ return {
53
+ call, finished,
54
+ initialize: () => call('initialize', { protocolVersions: [ENGINE_PROTOCOL], host: { name: hostName },
55
+ services: { approvals: typeof onApproveTool === 'function', tools: typeof onCallTool === 'function' } }),
56
+ startRun: params => call('run/start', params),
57
+ status: runId => call('run/status', { runId }),
58
+ events: (runId, cursor = 0, waitMs = 0) => call('run/events', { runId, cursor, waitMs }),
59
+ resume: runId => call('run/resume', { runId }),
60
+ cancel: runId => call('run/cancel', { runId }),
61
+ view: () => call('ui/view'),
62
+ shutdown: () => call('shutdown'),
63
+ /** Follow a Run to rest, handing each projected event to `onEvent`. */
64
+ async follow(runId, onEvent = () => {}, { waitMs = 5000 } = {}) {
65
+ for (let cursor = 0; ;) {
66
+ const page = await call('run/events', { runId, cursor, waitMs });
67
+ for (const event of page.events) onEvent(event);
68
+ cursor = page.cursor;
69
+ if (!page.running && page.events.length === 0) return call('run/status', { runId });
70
+ }
71
+ },
72
+ };
73
+ }
74
+
75
+ /** Start an engine executable and connect to it. `command` is host configuration, not host code. */
76
+ export function spawnEngine({ command, args = [], env, onApproveTool, onCallTool, hostName, onLog = () => {} }) {
77
+ const child = spawn(command, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
78
+ child.stderr.setEncoding('utf8').on('data', chunk => onLog(chunk));
79
+ 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; } };
83
+ }
@@ -0,0 +1,47 @@
1
+ import { invariant } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ export const ENGINE_CONTEXT = 'agentkit.engine-context/v1';
4
+ const MAX_SOURCES = 32;
5
+ const MAX_SOURCE_MS = 30000;
6
+ const SOURCE_ID = /^[a-z][a-z0-9._-]{0,127}$/;
7
+ const DIGEST = /^sha256:[a-f0-9]{64}$/;
8
+
9
+ export function admitEngineContextSources(value) {
10
+ if (value === undefined) return [];
11
+ invariant(value?.contract === ENGINE_CONTEXT
12
+ && Object.keys(value).every(key => key === 'contract' || key === 'sources') && Array.isArray(value.sources)
13
+ && value.sources.length <= MAX_SOURCES, 'engine_context_sources_invalid');
14
+ const seen = new Set();
15
+ return value.sources.map(source => {
16
+ invariant(source && typeof source === 'object'
17
+ && Object.keys(source).every(key => ['sourceId', 'bindingDigest', 'timeoutMs', 'maxTokens', 'maxBytes',
18
+ 'failureMode', 'allowInstructions'].includes(key))
19
+ && typeof source.sourceId === 'string' && SOURCE_ID.test(source.sourceId) && !seen.has(source.sourceId)
20
+ && typeof source.bindingDigest === 'string' && DIGEST.test(source.bindingDigest)
21
+ && Number.isSafeInteger(source.timeoutMs) && source.timeoutMs >= 1 && source.timeoutMs <= MAX_SOURCE_MS
22
+ && Number.isSafeInteger(source.maxTokens) && source.maxTokens >= 1 && source.maxTokens <= 1048576
23
+ && Number.isSafeInteger(source.maxBytes) && source.maxBytes >= 1 && source.maxBytes <= 131072
24
+ && ['skip', 'warn', 'fail'].includes(source.failureMode) && typeof source.allowInstructions === 'boolean',
25
+ 'engine_context_source_invalid');
26
+ seen.add(source.sourceId);
27
+ return { contract: 'agentkit.native-context-source/v1', sourceId: source.sourceId,
28
+ bindingDigest: source.bindingDigest, priority: 0, timeoutMs: source.timeoutMs, maxTokens: source.maxTokens,
29
+ maxBytes: source.maxBytes, required: source.failureMode === 'fail',
30
+ hostProjection: source.allowInstructions ? 'instructions-and-data/v1' : 'data/v1',
31
+ ...(source.failureMode === 'warn' ? { warnOnFailure: true } : {}) };
32
+ });
33
+ }
34
+
35
+ export function engineContextPort(port, callHostContext) {
36
+ return { ...port, async readSource({ source, snapshot, operationKey, signal, remainingTokens }) {
37
+ invariant(source.hostProjection && typeof callHostContext === 'function', 'engine_context_unavailable');
38
+ const reply = await callHostContext({
39
+ contract: ENGINE_CONTEXT, runId: snapshot.runId, turnId: snapshot.turnId, operationKey,
40
+ sourceId: source.sourceId, bindingDigest: source.bindingDigest,
41
+ goal: snapshot.goal, goalRevision: snapshot.goalRevision, remainingTokens,
42
+ }, source.timeoutMs, signal);
43
+ invariant(reply?.contract === ENGINE_CONTEXT && reply.sourceId === source.sourceId
44
+ && reply.bindingDigest === source.bindingDigest && Array.isArray(reply.items), 'engine_context_result_invalid');
45
+ return { items: reply.items };
46
+ } };
47
+ }