@kingsoftcloud/agentkit-harness-node 0.0.14 → 0.0.16

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
@@ -373,7 +373,7 @@ function nativeContextStatus(record, { driving = false } = {}) {
373
373
 
374
374
  // packages/agentkit-harness-node/src/native/activity-status.mjs
375
375
  import { createHash as createHash2 } from "node:crypto";
376
- import { canonical as canonical4 } from "@kingsoftcloud/agentkit-harness-core";
376
+ import { canonical as canonical4, projectBackgroundCommands } from "@kingsoftcloud/agentkit-harness-core";
377
377
  var settledCommandStates = /* @__PURE__ */ new Set(["completed", "failed", "canceled", "timed_out", "output_limit"]);
378
378
  function foregroundReceiptState(record, ref, intent) {
379
379
  if (ref.sourceRunId !== record.snapshot.runId || intent?.kind !== "tool" || intent.payload.calls?.length !== 1) return null;
@@ -398,9 +398,11 @@ function nativeActivityStatus(record, { driving = false } = {}) {
398
398
  const observations = /* @__PURE__ */ new Map();
399
399
  for (const event of record.events ?? []) if (event.kind === "background.commands_observed")
400
400
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
401
- const terminals = (snapshot.backgroundCommands ?? []).slice(-128).map(({ ref }) => {
401
+ const commands = snapshot.backgroundCommands ?? [];
402
+ const intents = new Map(record.intents.map((intent) => [intent.operationKey, intent]));
403
+ const terminals = projectBackgroundCommands(commands, 128).map(({ ref }) => {
402
404
  const observed = observations.get(ref.taskId);
403
- const intent = record.intents.find((row) => row.operationKey === ref.operationKey);
405
+ const intent = intents.get(ref.operationKey);
404
406
  const calls = intent?.payload.calls ?? [];
405
407
  const call = calls.length === 1 ? calls[0] : null;
406
408
  return {
@@ -423,7 +425,7 @@ function nativeActivityStatus(record, { driving = false } = {}) {
423
425
  omittedItems: Math.max(0, todos.length - items.length)
424
426
  } : null,
425
427
  terminals,
426
- omittedTerminals: Math.max(0, (snapshot.backgroundCommands ?? []).length - terminals.length)
428
+ omittedTerminals: commands.length - terminals.length
427
429
  };
428
430
  }
429
431
 
@@ -2037,21 +2039,28 @@ function applyAnthropicThinking(payload, profile, binding) {
2037
2039
  }
2038
2040
  function resolveProviderCompatibility(policy, binding) {
2039
2041
  if (!policy) return null;
2040
- if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
2042
+ if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
2041
2043
  const rule = resolveCompatibilityRule(policy.rule, binding);
2042
2044
  const name = String(binding.model ?? "").trim().toLowerCase();
2043
2045
  const kimi = ["kspmas-gateway", "moonshot"].includes(rule) && ["kimi-k2.7-code", "kimi-k2.7-code-highspeed"].includes(name);
2044
- const reasoningRequired = policy.contract === "provider-compat/v3" && rule === "kspmas-gateway" && name === "glm-5.3-flash";
2046
+ const modern = ["provider-compat/v3", "provider-compat/v4"].includes(policy.contract);
2047
+ const reasoningRequired = modern && rule === "kspmas-gateway" && name === "glm-5.3-flash";
2045
2048
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === "claude-haiku-5-5" ? ["low", "medium", "high"] : null;
2046
2049
  return {
2047
2050
  rule,
2048
2051
  supportsUsage: !strict.has(rule),
2049
2052
  supportsThinking: !strict.has(rule) && !kimi,
2050
- supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2053
+ supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2051
2054
  reasoningRequired,
2052
- modern: policy.contract === "provider-compat/v3",
2055
+ modern,
2056
+ // This route already uses the supported non-thinking mode for tool work.
2057
+ // A bounded summary has no tools: omitting the switch can instead select
2058
+ // the provider's default high reasoning and consume its whole output cap.
2059
+ // Freeze this purpose-specific default only on new admissions; mandatory
2060
+ // thinking models and explicit caller choices remain authoritative.
2061
+ compactionThinkingOff: policy.contract === "provider-compat/v4" && rule === "kspmas-gateway" && !kimi,
2053
2062
  // Only the observed provider/model dialects may seal without [DONE].
2054
- finishOnEof: policy.contract === "provider-compat/v3" && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
2063
+ finishOnEof: modern && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
2055
2064
  supportsEffort: !kimi,
2056
2065
  toolThinkingOff: ["zai", "kspmas-gateway"].includes(rule) && !kimi,
2057
2066
  thinkingBudget: rule === "zai" && !kimi && !disabledEfforts ? 32e3 : null,
@@ -2106,11 +2115,12 @@ function applyProviderChatCompatibility(payload, request, binding) {
2106
2115
  if (mode === "disabled" && compat.reasoningRequired) throw new ProtocolError("model_thinking_disable_unsupported");
2107
2116
  const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
2108
2117
  const summaryOff = request.purpose === "compaction" && requested === null && compat.rule === "kspmas-gateway" && name === "glm-5.3-flash";
2118
+ const boundedSummaryOff = request.purpose === "compaction" && compat.compactionThinkingOff && requested === null && mode === void 0;
2109
2119
  const budget = result.max_completion_tokens ?? result.max_tokens;
2110
2120
  if (mode === "enabled") {
2111
2121
  if (!compat.supportsThinking) throw new ProtocolError("model_thinking_mode_unsupported");
2112
2122
  result.thinking = { type: "enabled" };
2113
- } else if (mayDisable && (mode === "disabled" || summaryOff || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== "none" || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: "disabled" };
2123
+ } else if (mayDisable && (mode === "disabled" || summaryOff || boundedSummaryOff || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== "none" || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: "disabled" };
2114
2124
  if (!compat.supportsThinking) delete result.thinking;
2115
2125
  if (!compat.supportsEffort) delete result.reasoning_effort;
2116
2126
  if (compat.modern && ["moonshot", "kspmas-gateway"].includes(compat.rule) && result.tools) {
@@ -2148,6 +2158,8 @@ function explicitLiteralTypes(schema) {
2148
2158
  }
2149
2159
 
2150
2160
  // packages/agentkit-harness-node/src/native/model-provider-error.mjs
2161
+ import { createHash as createHash6 } from "node:crypto";
2162
+ import { canonical as canonical8, MODEL_PROVIDER_ERROR_CODES, MODEL_PROVIDER_ERROR_TYPES } from "@kingsoftcloud/agentkit-harness-core";
2151
2163
  var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
2152
2164
  "rate_limit_error",
2153
2165
  "rate_limit_exceeded",
@@ -2176,6 +2188,23 @@ var TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
2176
2188
  "MODEL_PROVIDER_QUOTA_EXHAUSTED"
2177
2189
  ]);
2178
2190
  function classifyOpenAIProviderError(error) {
2191
+ const decision = classifyError(error);
2192
+ let fingerprint;
2193
+ try {
2194
+ fingerprint = `sha256:${createHash6("sha256").update(canonical8(error)).digest("hex")}`;
2195
+ } catch {
2196
+ return decision;
2197
+ }
2198
+ const object2 = error && typeof error === "object" && !Array.isArray(error) ? error : {};
2199
+ return { ...decision, diagnostic: {
2200
+ category: decision.failureKind,
2201
+ fingerprint,
2202
+ ...MODEL_PROVIDER_ERROR_CODES.includes(object2.code) ? { code: object2.code } : {},
2203
+ ...MODEL_PROVIDER_ERROR_TYPES.includes(object2.type) ? { type: object2.type } : {},
2204
+ ...Number.isInteger(object2.code) && object2.code >= 400 && object2.code <= 599 ? { status: object2.code } : {}
2205
+ } };
2206
+ }
2207
+ function classifyError(error) {
2179
2208
  const invalid = { kind: "provider_terminal_error", failureKind: "invalid_response" };
2180
2209
  if (!error || typeof error !== "object" || Array.isArray(error)) return invalid;
2181
2210
  if (error.type != null && typeof error.type !== "string") return invalid;
@@ -3038,7 +3067,7 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
3038
3067
  if (profile.providerReplayProjectionPolicy === "anthropic-client-compaction/v1") {
3039
3068
  const originals = message.providerReplay.anthropicContent.filter((block) => block?.type === "tool_use");
3040
3069
  for (const [index, block] of originals.entries()) wireIds.set(message.toolCalls[index].callId, block.id);
3041
- const inverse = new Map([...wireIds].map(([canonical8, original]) => [canonical8, original]));
3070
+ const inverse = new Map([...wireIds].map(([canonical9, original]) => [canonical9, original]));
3042
3071
  blocks = replayContent.map((block) => block?.type === "tool_use" ? { ...block, id: inverse.get(block.id) ?? block.id } : block);
3043
3072
  } else blocks = replayContent;
3044
3073
  } else {
@@ -3859,9 +3888,9 @@ function projectResponsesOutput(payload, { status }) {
3859
3888
  reasoning.push(partsText(item.content, /* @__PURE__ */ new Set(["reasoning_text", "text"])));
3860
3889
  }
3861
3890
  }
3862
- const canonical8 = messages.join("");
3891
+ const canonical9 = messages.join("");
3863
3892
  const convenience = optionalText(payload.output_text);
3864
- if ("output" in payload && payload.output_text != null && canonical8 !== convenience) {
3893
+ if ("output" in payload && payload.output_text != null && canonical9 !== convenience) {
3865
3894
  throw new ProtocolError("invalid model frame", "envelope_invalid");
3866
3895
  }
3867
3896
  let finish;
@@ -3881,7 +3910,7 @@ function projectResponsesOutput(payload, { status }) {
3881
3910
  finish = "content_filter";
3882
3911
  calls.length = 0;
3883
3912
  }
3884
- return { finish, content: canonical8 || convenience, reasoning: reasoning.join(""), calls, refused };
3913
+ return { finish, content: canonical9 || convenience, reasoning: reasoning.join(""), calls, refused };
3885
3914
  }
3886
3915
  function responseMessageContent(value) {
3887
3916
  if (!Array.isArray(value)) throw new ProtocolError("invalid model frame", "envelope_invalid");
@@ -4818,14 +4847,15 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4818
4847
  const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
4819
4848
  const abort = (reason) => internal.abort(reason);
4820
4849
  let frameIndex = -1;
4821
- const failed = (result2, code) => withFailure(
4850
+ const failed = (result2, code, fields2 = {}) => withFailure(
4822
4851
  result2,
4823
4852
  binding,
4824
4853
  "stream",
4825
4854
  code,
4826
4855
  {
4827
4856
  ...frameIndex < 0 ? {} : { frameIndex },
4828
- ...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {}
4857
+ ...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {},
4858
+ ...fields2
4829
4859
  }
4830
4860
  );
4831
4861
  try {
@@ -4847,7 +4877,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4847
4877
  }
4848
4878
  if (error instanceof ProtocolError) {
4849
4879
  if (error.streamError) {
4850
- return failed(state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }), "provider_error");
4880
+ return failed(
4881
+ state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }),
4882
+ "provider_error",
4883
+ error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
4884
+ );
4851
4885
  }
4852
4886
  return failed(state.finalize({ errorKind: "provider_terminal_error", failureKind: "invalid_response" }), protocolCode(error));
4853
4887
  }
@@ -4857,7 +4891,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4857
4891
  return failed(state.finalize({ errorKind: "provider_retryable_error", failureKind: sanitizeFailureKind(error, "network_error") }), "transport_error");
4858
4892
  }
4859
4893
  const result = state.finalize();
4860
- return failed(result, state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid");
4894
+ return failed(
4895
+ result,
4896
+ state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid",
4897
+ state.streamError?.diagnostic ? { providerError: state.streamError.diagnostic } : {}
4898
+ );
4861
4899
  }
4862
4900
  async function bufferedResponse(response, request, binding, maxBytes, emit, observation) {
4863
4901
  const bodyText = await readBoundedText(response, maxBytes, observation.bytes);
@@ -4876,7 +4914,13 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
4876
4914
  } catch (error) {
4877
4915
  if (error instanceof ProtocolError && error.streamError) {
4878
4916
  const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
4879
- return withFailure(result, binding, "buffered", "provider_error");
4917
+ return withFailure(
4918
+ result,
4919
+ binding,
4920
+ "buffered",
4921
+ "provider_error",
4922
+ error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
4923
+ );
4880
4924
  }
4881
4925
  return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
4882
4926
  }
@@ -4922,7 +4966,7 @@ function protocolCode(error) {
4922
4966
  function withFailure(result, binding, phase, code, fields2 = {}) {
4923
4967
  if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind)) return result;
4924
4968
  const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
4925
- return { ...result, failureDiagnostic: { contract: fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
4969
+ return { ...result, failureDiagnostic: { contract: fields2.providerError ? "model-failure-diagnostic/v3" : fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
4926
4970
  }
4927
4971
  function retryableResult(failureKind, retryAfterMs = null) {
4928
4972
  const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
@@ -2,12 +2,12 @@
2
2
 
3
3
  // packages/agentkit-harness-node/src/rpc-entry.mjs
4
4
  import { parseArgs } from "node:util";
5
- import { createHash as createHash7 } from "node:crypto";
5
+ import { createHash as createHash8 } from "node:crypto";
6
6
  import { realpathSync as realpathSync2 } from "node:fs";
7
7
  import { resolve as resolvePath } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import * as readline from "node:readline";
10
- import { NativeKernel, configure, initialSnapshot, canonical as canonical8, terminal as terminal3, runKey as runKey2, NativeError, isNativeError } from "@kingsoftcloud/agentkit-harness-core";
10
+ import { NativeKernel, configure, initialSnapshot, canonical as canonical9, terminal as terminal3, runKey as runKey2, NativeError, isNativeError } from "@kingsoftcloud/agentkit-harness-core";
11
11
 
12
12
  // packages/agentkit-harness-node/src/native/sqlite-session-inbox.mjs
13
13
  import { appendSessionInjection, canonical, invariant, parseNativeJson } from "@kingsoftcloud/agentkit-harness-core";
@@ -384,7 +384,7 @@ function nativeContextStatus(record, { driving = false } = {}) {
384
384
 
385
385
  // packages/agentkit-harness-node/src/native/activity-status.mjs
386
386
  import { createHash as createHash2 } from "node:crypto";
387
- import { canonical as canonical4 } from "@kingsoftcloud/agentkit-harness-core";
387
+ import { canonical as canonical4, projectBackgroundCommands } from "@kingsoftcloud/agentkit-harness-core";
388
388
  var settledCommandStates = /* @__PURE__ */ new Set(["completed", "failed", "canceled", "timed_out", "output_limit"]);
389
389
  function foregroundReceiptState(record, ref, intent) {
390
390
  if (ref.sourceRunId !== record.snapshot.runId || intent?.kind !== "tool" || intent.payload.calls?.length !== 1) return null;
@@ -409,9 +409,11 @@ function nativeActivityStatus(record, { driving = false } = {}) {
409
409
  const observations = /* @__PURE__ */ new Map();
410
410
  for (const event of record.events ?? []) if (event.kind === "background.commands_observed")
411
411
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
412
- const terminals = (snapshot.backgroundCommands ?? []).slice(-128).map(({ ref }) => {
412
+ const commands = snapshot.backgroundCommands ?? [];
413
+ const intents = new Map(record.intents.map((intent) => [intent.operationKey, intent]));
414
+ const terminals = projectBackgroundCommands(commands, 128).map(({ ref }) => {
413
415
  const observed = observations.get(ref.taskId);
414
- const intent = record.intents.find((row) => row.operationKey === ref.operationKey);
416
+ const intent = intents.get(ref.operationKey);
415
417
  const calls = intent?.payload.calls ?? [];
416
418
  const call = calls.length === 1 ? calls[0] : null;
417
419
  return {
@@ -434,7 +436,7 @@ function nativeActivityStatus(record, { driving = false } = {}) {
434
436
  omittedItems: Math.max(0, todos.length - items.length)
435
437
  } : null,
436
438
  terminals,
437
- omittedTerminals: Math.max(0, (snapshot.backgroundCommands ?? []).length - terminals.length)
439
+ omittedTerminals: commands.length - terminals.length
438
440
  };
439
441
  }
440
442
 
@@ -2048,21 +2050,28 @@ function applyAnthropicThinking(payload, profile, binding) {
2048
2050
  }
2049
2051
  function resolveProviderCompatibility(policy, binding) {
2050
2052
  if (!policy) return null;
2051
- if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
2053
+ if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
2052
2054
  const rule = resolveCompatibilityRule(policy.rule, binding);
2053
2055
  const name = String(binding.model ?? "").trim().toLowerCase();
2054
2056
  const kimi = ["kspmas-gateway", "moonshot"].includes(rule) && ["kimi-k2.7-code", "kimi-k2.7-code-highspeed"].includes(name);
2055
- const reasoningRequired = policy.contract === "provider-compat/v3" && rule === "kspmas-gateway" && name === "glm-5.3-flash";
2057
+ const modern = ["provider-compat/v3", "provider-compat/v4"].includes(policy.contract);
2058
+ const reasoningRequired = modern && rule === "kspmas-gateway" && name === "glm-5.3-flash";
2056
2059
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === "claude-haiku-5-5" ? ["low", "medium", "high"] : null;
2057
2060
  return {
2058
2061
  rule,
2059
2062
  supportsUsage: !strict.has(rule),
2060
2063
  supportsThinking: !strict.has(rule) && !kimi,
2061
- supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2064
+ supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
2062
2065
  reasoningRequired,
2063
- modern: policy.contract === "provider-compat/v3",
2066
+ modern,
2067
+ // This route already uses the supported non-thinking mode for tool work.
2068
+ // A bounded summary has no tools: omitting the switch can instead select
2069
+ // the provider's default high reasoning and consume its whole output cap.
2070
+ // Freeze this purpose-specific default only on new admissions; mandatory
2071
+ // thinking models and explicit caller choices remain authoritative.
2072
+ compactionThinkingOff: policy.contract === "provider-compat/v4" && rule === "kspmas-gateway" && !kimi,
2064
2073
  // Only the observed provider/model dialects may seal without [DONE].
2065
- finishOnEof: policy.contract === "provider-compat/v3" && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
2074
+ finishOnEof: modern && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
2066
2075
  supportsEffort: !kimi,
2067
2076
  toolThinkingOff: ["zai", "kspmas-gateway"].includes(rule) && !kimi,
2068
2077
  thinkingBudget: rule === "zai" && !kimi && !disabledEfforts ? 32e3 : null,
@@ -2117,11 +2126,12 @@ function applyProviderChatCompatibility(payload, request, binding) {
2117
2126
  if (mode === "disabled" && compat.reasoningRequired) throw new ProtocolError("model_thinking_disable_unsupported");
2118
2127
  const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
2119
2128
  const summaryOff = request.purpose === "compaction" && requested === null && compat.rule === "kspmas-gateway" && name === "glm-5.3-flash";
2129
+ const boundedSummaryOff = request.purpose === "compaction" && compat.compactionThinkingOff && requested === null && mode === void 0;
2120
2130
  const budget = result.max_completion_tokens ?? result.max_tokens;
2121
2131
  if (mode === "enabled") {
2122
2132
  if (!compat.supportsThinking) throw new ProtocolError("model_thinking_mode_unsupported");
2123
2133
  result.thinking = { type: "enabled" };
2124
- } else if (mayDisable && (mode === "disabled" || summaryOff || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== "none" || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: "disabled" };
2134
+ } else if (mayDisable && (mode === "disabled" || summaryOff || boundedSummaryOff || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== "none" || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: "disabled" };
2125
2135
  if (!compat.supportsThinking) delete result.thinking;
2126
2136
  if (!compat.supportsEffort) delete result.reasoning_effort;
2127
2137
  if (compat.modern && ["moonshot", "kspmas-gateway"].includes(compat.rule) && result.tools) {
@@ -2159,6 +2169,8 @@ function explicitLiteralTypes(schema) {
2159
2169
  }
2160
2170
 
2161
2171
  // packages/agentkit-harness-node/src/native/model-provider-error.mjs
2172
+ import { createHash as createHash6 } from "node:crypto";
2173
+ import { canonical as canonical8, MODEL_PROVIDER_ERROR_CODES, MODEL_PROVIDER_ERROR_TYPES } from "@kingsoftcloud/agentkit-harness-core";
2162
2174
  var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
2163
2175
  "rate_limit_error",
2164
2176
  "rate_limit_exceeded",
@@ -2187,6 +2199,23 @@ var TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
2187
2199
  "MODEL_PROVIDER_QUOTA_EXHAUSTED"
2188
2200
  ]);
2189
2201
  function classifyOpenAIProviderError(error) {
2202
+ const decision = classifyError(error);
2203
+ let fingerprint;
2204
+ try {
2205
+ fingerprint = `sha256:${createHash6("sha256").update(canonical8(error)).digest("hex")}`;
2206
+ } catch {
2207
+ return decision;
2208
+ }
2209
+ const object2 = error && typeof error === "object" && !Array.isArray(error) ? error : {};
2210
+ return { ...decision, diagnostic: {
2211
+ category: decision.failureKind,
2212
+ fingerprint,
2213
+ ...MODEL_PROVIDER_ERROR_CODES.includes(object2.code) ? { code: object2.code } : {},
2214
+ ...MODEL_PROVIDER_ERROR_TYPES.includes(object2.type) ? { type: object2.type } : {},
2215
+ ...Number.isInteger(object2.code) && object2.code >= 400 && object2.code <= 599 ? { status: object2.code } : {}
2216
+ } };
2217
+ }
2218
+ function classifyError(error) {
2190
2219
  const invalid = { kind: "provider_terminal_error", failureKind: "invalid_response" };
2191
2220
  if (!error || typeof error !== "object" || Array.isArray(error)) return invalid;
2192
2221
  if (error.type != null && typeof error.type !== "string") return invalid;
@@ -3049,7 +3078,7 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
3049
3078
  if (profile.providerReplayProjectionPolicy === "anthropic-client-compaction/v1") {
3050
3079
  const originals = message.providerReplay.anthropicContent.filter((block) => block?.type === "tool_use");
3051
3080
  for (const [index, block] of originals.entries()) wireIds.set(message.toolCalls[index].callId, block.id);
3052
- const inverse = new Map([...wireIds].map(([canonical9, original]) => [canonical9, original]));
3081
+ const inverse = new Map([...wireIds].map(([canonical10, original]) => [canonical10, original]));
3053
3082
  blocks = replayContent.map((block) => block?.type === "tool_use" ? { ...block, id: inverse.get(block.id) ?? block.id } : block);
3054
3083
  } else blocks = replayContent;
3055
3084
  } else {
@@ -3870,9 +3899,9 @@ function projectResponsesOutput(payload, { status }) {
3870
3899
  reasoning.push(partsText(item.content, /* @__PURE__ */ new Set(["reasoning_text", "text"])));
3871
3900
  }
3872
3901
  }
3873
- const canonical9 = messages.join("");
3902
+ const canonical10 = messages.join("");
3874
3903
  const convenience = optionalText(payload.output_text);
3875
- if ("output" in payload && payload.output_text != null && canonical9 !== convenience) {
3904
+ if ("output" in payload && payload.output_text != null && canonical10 !== convenience) {
3876
3905
  throw new ProtocolError("invalid model frame", "envelope_invalid");
3877
3906
  }
3878
3907
  let finish;
@@ -3892,7 +3921,7 @@ function projectResponsesOutput(payload, { status }) {
3892
3921
  finish = "content_filter";
3893
3922
  calls.length = 0;
3894
3923
  }
3895
- return { finish, content: canonical9 || convenience, reasoning: reasoning.join(""), calls, refused };
3924
+ return { finish, content: canonical10 || convenience, reasoning: reasoning.join(""), calls, refused };
3896
3925
  }
3897
3926
  function responseMessageContent(value) {
3898
3927
  if (!Array.isArray(value)) throw new ProtocolError("invalid model frame", "envelope_invalid");
@@ -4829,14 +4858,15 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4829
4858
  const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
4830
4859
  const abort = (reason) => internal.abort(reason);
4831
4860
  let frameIndex = -1;
4832
- const failed = (result2, code) => withFailure(
4861
+ const failed = (result2, code, fields2 = {}) => withFailure(
4833
4862
  result2,
4834
4863
  binding,
4835
4864
  "stream",
4836
4865
  code,
4837
4866
  {
4838
4867
  ...frameIndex < 0 ? {} : { frameIndex },
4839
- ...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {}
4868
+ ...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {},
4869
+ ...fields2
4840
4870
  }
4841
4871
  );
4842
4872
  try {
@@ -4858,7 +4888,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4858
4888
  }
4859
4889
  if (error instanceof ProtocolError) {
4860
4890
  if (error.streamError) {
4861
- return failed(state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }), "provider_error");
4891
+ return failed(
4892
+ state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }),
4893
+ "provider_error",
4894
+ error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
4895
+ );
4862
4896
  }
4863
4897
  return failed(state.finalize({ errorKind: "provider_terminal_error", failureKind: "invalid_response" }), protocolCode(error));
4864
4898
  }
@@ -4868,7 +4902,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
4868
4902
  return failed(state.finalize({ errorKind: "provider_retryable_error", failureKind: sanitizeFailureKind(error, "network_error") }), "transport_error");
4869
4903
  }
4870
4904
  const result = state.finalize();
4871
- return failed(result, state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid");
4905
+ return failed(
4906
+ result,
4907
+ state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid",
4908
+ state.streamError?.diagnostic ? { providerError: state.streamError.diagnostic } : {}
4909
+ );
4872
4910
  }
4873
4911
  async function bufferedResponse(response, request, binding, maxBytes, emit, observation) {
4874
4912
  const bodyText = await readBoundedText(response, maxBytes, observation.bytes);
@@ -4887,7 +4925,13 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
4887
4925
  } catch (error) {
4888
4926
  if (error instanceof ProtocolError && error.streamError) {
4889
4927
  const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
4890
- return withFailure(result, binding, "buffered", "provider_error");
4928
+ return withFailure(
4929
+ result,
4930
+ binding,
4931
+ "buffered",
4932
+ "provider_error",
4933
+ error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
4934
+ );
4891
4935
  }
4892
4936
  return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
4893
4937
  }
@@ -4933,7 +4977,7 @@ function protocolCode(error) {
4933
4977
  function withFailure(result, binding, phase, code, fields2 = {}) {
4934
4978
  if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind)) return result;
4935
4979
  const protocol = ["openai-chat", "openai-responses", "anthropic-messages"].includes(binding?.protocol) ? binding.protocol : "unknown";
4936
- return { ...result, failureDiagnostic: { contract: fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
4980
+ return { ...result, failureDiagnostic: { contract: fields2.providerError ? "model-failure-diagnostic/v3" : fields2.usageConflict ? "model-failure-diagnostic/v2" : "model-failure-diagnostic/v1", protocol, phase, code, ...fields2 } };
4937
4981
  }
4938
4982
  function retryableResult(failureKind, retryAfterMs = null) {
4939
4983
  const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
@@ -4994,7 +5038,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
4994
5038
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
4995
5039
  import { mkdirSync as mkdirSync2 } from "node:fs";
4996
5040
  import { dirname as dirname2 } from "node:path";
4997
- import { createHash as createHash6 } from "node:crypto";
5041
+ import { createHash as createHash7 } from "node:crypto";
4998
5042
  function stable(value) {
4999
5043
  if (value === null || typeof value !== "object") return JSON.stringify(value);
5000
5044
  if (Array.isArray(value)) return "[" + value.map(stable).join(",") + "]";
@@ -5002,7 +5046,7 @@ function stable(value) {
5002
5046
  return "{" + keys.map((k) => JSON.stringify(k) + ":" + stable(value[k])).join(",") + "}";
5003
5047
  }
5004
5048
  function digestRequest(method, params) {
5005
- return createHash6("sha256").update(stable({ method, params: params ?? null })).digest("hex");
5049
+ return createHash7("sha256").update(stable({ method, params: params ?? null })).digest("hex");
5006
5050
  }
5007
5051
  var RpcRequestLedger = class {
5008
5052
  constructor(filename, { now = Date.now } = {}) {
@@ -5276,8 +5320,8 @@ var ERR = {
5276
5320
  var success = (id, result) => ({ jsonrpc: "2.0", id, result });
5277
5321
  var errorResponse = (id, e, data) => ({ jsonrpc: "2.0", id, error: publicFailureContent({ code: e.code, message: e.message, ...data ? { data } : {} }) });
5278
5322
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5279
- var digest = (value) => createHash7("sha256").update(canonical8(value)).digest("hex");
5280
- var runIdFor = (requestId) => "rpc:" + createHash7("sha256").update(requestId).digest("hex");
5323
+ var digest = (value) => createHash8("sha256").update(canonical9(value)).digest("hex");
5324
+ var runIdFor = (requestId) => "rpc:" + createHash8("sha256").update(requestId).digest("hex");
5281
5325
  function nativeErrorToRpc(e) {
5282
5326
  if (isNativeError(e)) {
5283
5327
  if (e.code === "run_not_found") return ERR.run_not_found;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-node",
3
- "version": "0.0.14",
3
+ "version": "0.0.16",
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.",
@@ -25,6 +25,8 @@
25
25
  "./native/child-history": "./src/native/child-history.mjs",
26
26
  "./native/child-command-resource": "./src/native/child-command-resource.mjs",
27
27
  "./native/child-owner": "./src/native/child-owner.mjs",
28
+ "./native/session-tool-approval": "./src/native/session-tool-approval.mjs",
29
+ "./native/approval-preflight": "./src/native/approval-preflight.mjs",
28
30
  "./native/child-publication": "./src/native/child-publication.mjs",
29
31
  "./native/child-readers": "./src/native/child-readers.mjs",
30
32
  "./native/child-tools": "./src/native/child-tools.mjs",
@@ -138,7 +140,7 @@
138
140
  "src/package-integrity.mjs"
139
141
  ],
140
142
  "dependencies": {
141
- "@kingsoftcloud/agentkit-harness-core": "0.0.14",
143
+ "@kingsoftcloud/agentkit-harness-core": "0.0.16",
142
144
  "@astral-sh/ruff-wasm-nodejs": "0.16.8",
143
145
  "parse5": "7.3.0",
144
146
  "playwright-core": "1.58.2",
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { canonical } from '@kingsoftcloud/agentkit-harness-core';
2
+ import { canonical, projectBackgroundCommands } from '@kingsoftcloud/agentkit-harness-core';
3
3
 
4
4
  const settledCommandStates = new Set(['completed', 'failed', 'canceled', 'timed_out', 'output_limit']);
5
5
 
@@ -44,9 +44,11 @@ export function nativeActivityStatus(record, { driving = false } = {}) {
44
44
  const observations = new Map();
45
45
  for (const event of record.events ?? []) if (event.kind === 'background.commands_observed')
46
46
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
47
- const terminals = (snapshot.backgroundCommands ?? []).slice(-128).map(({ ref }) => {
47
+ const commands = snapshot.backgroundCommands ?? [];
48
+ const intents = new Map(record.intents.map(intent => [intent.operationKey, intent]));
49
+ const terminals = projectBackgroundCommands(commands, 128).map(({ ref }) => {
48
50
  const observed = observations.get(ref.taskId);
49
- const intent = record.intents.find(row => row.operationKey === ref.operationKey);
51
+ const intent = intents.get(ref.operationKey);
50
52
  const calls = intent?.payload.calls ?? [];
51
53
  const call = calls.length === 1 ? calls[0] : null;
52
54
  return { id: ref.taskId, runId: snapshot.runId,
@@ -57,5 +59,5 @@ export function nativeActivityStatus(record, { driving = false } = {}) {
57
59
  isRunning: driving, plan: todos.length ? { items,
58
60
  completedCount: todos.filter(todo => todo.status === 'completed').length, totalCount: todos.length,
59
61
  omittedItems: Math.max(0, todos.length - items.length) } : null,
60
- terminals, omittedTerminals: Math.max(0, (snapshot.backgroundCommands ?? []).length - terminals.length) };
62
+ terminals, omittedTerminals: commands.length - terminals.length };
61
63
  }
@@ -0,0 +1,35 @@
1
+ import { canonical, invariant, parseNativeJson } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ export const SCHEMA_BOUND_PREFLIGHT = 'dsh.tool-preflight-defer/v1';
4
+ export const CONTROL_PREFLIGHT = 'dsh.tool-preflight-defer/v2';
5
+
6
+ /** Select an explicitly advertised Host seam. Never guess support from a tool
7
+ * name or relax the actual tool's output schema to carry an approval request. */
8
+ export function nativeApprovalPreflightContract(capabilities) {
9
+ const advertised = capabilities?.preflightDeferContracts ?? [capabilities?.preflightDeferContract];
10
+ if (!Array.isArray(advertised)) return null;
11
+ return advertised.includes(CONTROL_PREFLIGHT) ? CONTROL_PREFLIGHT
12
+ : advertised.includes(SCHEMA_BOUND_PREFLIGHT) ? SCHEMA_BOUND_PREFLIGHT : null;
13
+ }
14
+
15
+ /** A pre-dispatch control value is not a successful tool body value. The v1
16
+ * envelope is retained only for historical Hosts whose owned tools declare it.
17
+ * The v2 Host renders marked control data without invoking the body projector. */
18
+ export function nativeApprovalPreflight(content, contract) {
19
+ invariant([SCHEMA_BOUND_PREFLIGHT, CONTROL_PREFLIGHT].includes(contract), 'native_approval_preflight_contract_unavailable');
20
+ const text = canonical(content);
21
+ const value = contract === SCHEMA_BOUND_PREFLIGHT ? { result: text } : parseNativeJson(text);
22
+ return { contract, value, text, decision: { kind: 'defer', value: structuredClone(value) } };
23
+ }
24
+
25
+ /** Post-policy denial remains a denial. A success-shaped replacement cannot
26
+ * turn a deferred request into an execution receipt or change its authority. */
27
+ export function assertNativeApprovalPreflightProjection(expected, result) {
28
+ if (result?.isError === true) return;
29
+ invariant(result?.isError === false && !result.concludesTurn
30
+ && (expected.contract === CONTROL_PREFLIGHT ? result.preflightDeferred === CONTROL_PREFLIGHT
31
+ : result.preflightDeferred === undefined)
32
+ && canonical(result.value) === canonical(expected.value)
33
+ && canonical(result.content) === canonical([{ type: 'text', text: expected.text }]),
34
+ 'native_approval_preflight_projection_changed');
35
+ }
@@ -42,7 +42,8 @@ export function mergeNativeChildHistory(request, inventories) {
42
42
  for (const parent of sourceParents) parents.add(parent);
43
43
  }
44
44
  const selected = tasks.map(task => task.parentRunId === runId ? task
45
- : { ...task, canPromote: false, canCancel: false, canSendInput: false });
45
+ : { ...task, canPromote: false, canCancel: false, canSendInput: false,
46
+ ...(task.canResume === undefined ? {} : { canResume: false }) });
46
47
  return pageInventory(request, { contract: NATIVE_CHILD_HISTORY_CONTRACT, sessionId: request.sessionId, runId,
47
48
  inventoryDigest: hash({ contract: 'agentkit.native-child-inventory-merge/v1', sessionId: request.sessionId,
48
49
  sources: present.map(value => [value.runId, value.inventoryDigest]) }), tasks: selected });
@@ -118,7 +119,7 @@ export function createNativeChildHistory({ scope, store, liveTasks = () => [], l
118
119
  const taskRow = ({ parent, child, control }) => {
119
120
  const snapshot = child.snapshot, binding = child.configuration.childOwnerBinding;
120
121
  const accounted = Boolean(accountedChildDelivery(parent, child));
121
- const command = parent.commands.filter(row => ['message_child', 'cancel_child', 'promote_child'].includes(row.command.kind)
122
+ const command = parent.commands.filter(row => ['message_child', 'cancel_child', 'promote_child', 'resume_child'].includes(row.command.kind)
122
123
  && row.command.payload.childRunId === snapshot.runId).at(-1);
123
124
  const applied = command && parent.events.find(event => event.kind === 'command.applied' && event.payload.commandId === command.command.commandId);
124
125
  const lastControl = command ? { commandId: command.command.commandId, action: command.command.kind,
@@ -135,6 +136,8 @@ export function createNativeChildHistory({ scope, store, liveTasks = () => [], l
135
136
  delivery: control?.delivery ?? (binding.deliveryMode === 'foreground'
136
137
  && !(parent.snapshot.promotedChildRunIds ?? []).includes(snapshot.runId) ? 'foreground' : 'background'),
137
138
  canPromote: control?.canPromote === true, canCancel: control?.canCancel === true, canSendInput: control?.canSendInput === true,
139
+ ...(child.configuration.outputRestartPolicy === 'per-response/v2' || child.configuration.providerRecoveryPolicy === 'provider-recovery/v2'
140
+ || control?.canResume !== undefined ? { canResume: control?.canResume === true } : {}),
138
141
  goalRevision: snapshot.goalRevision,
139
142
  lastControl,
140
143
  goalPreview: [...snapshot.goal].slice(0, 256).join(''), goalComplete: [...snapshot.goal].length <= 256,
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { NativeKernel, NativeError, isNativeError, CHILD_OWNER_CONTRACT, canonical, copy, configure,
3
3
  addUsage, admittedToolBudget, childLifecycleRequest, childReadyProbe, scopeKey, terminal,
4
- CHILD_TASK_POLICY, COORDINATOR_RESPONSE_POLICY, activePlanMode, isPlanChildCall, planModeWriteDenial,
4
+ CHILD_TASK_POLICY, COORDINATOR_RESPONSE_POLICY, activePlanMode, isPlanChildCall, planModeWriteDenial, childResumeAllowed,
5
5
  CHILD_PLAN_POLICY, CHILD_PLAN_MODE_POLICY, defaultPolicyBindings } from '@kingsoftcloud/agentkit-harness-core';
6
6
  import { loadSessionChild, accountedChildDelivery, hasUnsafeChildReceipt, childNeedsApproval } from './owned-child.mjs';
7
7
  import { CHILD_ALLOCATION_POLICY, CHILD_ALLOCATION_DEFAULTS, LEGACY_CALL_DEFAULTS,
@@ -222,23 +222,23 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
222
222
  request.signal.throwIfAborted();
223
223
  toolInvocation(request);
224
224
  if (entry && !terminal(record.snapshot.phase)) drive(entry);
225
- while (!terminal(record.snapshot.phase) && !childNeedsApproval(record)) {
225
+ while (!terminal(record.snapshot.phase) && record.snapshot.phase !== 'paused' && !childNeedsApproval(record)) {
226
226
  request.signal.throwIfAborted(); const parent = toolInvocation(request);
227
- if (parent.commands.some(row => !row.consumed && ['pause', 'promote_child', 'message_child', 'cancel_child'].includes(row.command.kind))
227
+ if (parent.commands.some(row => !row.consumed && ['pause', 'promote_child', 'message_child', 'cancel_child', 'resume_child'].includes(row.command.kind))
228
228
  || entry?.error && entry.error.code !== 'lease_busy') return startup();
229
229
  await observeWhileLive(new Promise(resolve => setTimeout(resolve, 25)), request.signal);
230
230
  record = ownedChild(request, reservation);
231
231
  if (entry?.error?.code === 'lease_busy') drive(entry);
232
232
  }
233
233
  request.signal.throwIfAborted(); toolInvocation(request);
234
- if (childNeedsApproval(record) || record.snapshot.phase === 'interrupted' || unsafeReceipt(record)) return startup();
234
+ if (childNeedsApproval(record) || record.snapshot.phase === 'paused' || record.snapshot.phase === 'interrupted' || unsafeReceipt(record)) return startup();
235
235
  return { ...terminalReceipt(record, reservation), childBudgetReservation: copy(reservation) };
236
236
  } finally { request.signal.removeEventListener('abort', cancel); }
237
237
  };
238
238
  const projection = (record, reservation) => ({ runId: record.snapshot.runId, sessionId: record.snapshot.sessionId,
239
239
  operationKey: reservation.parentOperationKey, callId: reservation.parentToolCallId,
240
240
  state: unsafeReceipt(record) && !canWaitForReceipt?.(record) ? 'interrupted' : record.snapshot.phase === 'created' ? 'prepared' : childNeedsApproval(record) ? 'awaiting_interaction'
241
- : terminal(record.snapshot.phase) ? record.snapshot.phase : 'running',
241
+ : record.snapshot.phase === 'paused' || terminal(record.snapshot.phase) ? record.snapshot.phase : 'running',
242
242
  reservedModelCalls: reservation.maxModelCalls, reservedToolCalls: reservation.maxToolCalls,
243
243
  usage: addUsage(record.snapshot.usage, record.snapshot.descendantUsage), notified: false, metadata: {} });
244
244
 
@@ -283,7 +283,10 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
283
283
  && !terminal(child.phase) && (!unsafeReceipt(record) || canWaitForReceipt?.(record)) && reservation.settledUsageDigest === null;
284
284
  rows.push({ childRunId: child.runId, sessionId: child.sessionId, role: binding.role, phase: child.phase, goalRevision: child.goalRevision, delivery,
285
285
  canPromote: live && delivery === 'foreground' && effective(parent).childPromotionPolicy === 'owned-child-promotion/v1',
286
- canCancel: live, canSendInput: live });
286
+ canCancel: live, canSendInput: live,
287
+ ...(child.phase === 'paused' || record.configuration.outputRestartPolicy === 'per-response/v2'
288
+ || record.configuration.providerRecoveryPolicy === 'provider-recovery/v2'
289
+ ? { canResume: live && childResumeAllowed(record.snapshot) } : {}) });
287
290
  }
288
291
  return rows;
289
292
  },
@@ -476,7 +479,11 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
476
479
  const expected = request.childApproval;
477
480
  check(request.interaction.interactionId === `native-child-${hash(expected)}`
478
481
  && request.interaction.callId === expected.toolCall.callId && ['allow', 'deny'].includes(request.interaction.decision), 'child_approval_identity_conflict');
479
- const commandId = `parent-approval-${hash({ parent: identity(request), approval: expected, decision: request.interaction.decision })}`;
482
+ const reply = { interactionId: expected.interactionId, decision: request.interaction.decision,
483
+ ...(record.configuration.approvalOutcomePolicy === 'owner-outcome/v1'
484
+ && Object.hasOwn(request.interaction, 'approvalOutcome') ? { approvalOutcome: request.interaction.approvalOutcome } : {}) };
485
+ const commandId = `parent-approval-${hash({ parent: identity(request), approval: expected,
486
+ decision: Object.hasOwn(reply, 'approvalOutcome') ? reply : request.interaction.decision })}`;
480
487
  // A promotion may detach this observer after the decision was
481
488
  // durably delivered. Accept only that same saved decision; never
482
489
  // infer approval from a child's phase or ask for it a second time.
@@ -485,11 +492,10 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
485
492
  `parent-approval-${hash({ parent: item.operationKey, approval: expected, decision: request.interaction.decision })}`);
486
493
  const delivered = record.commands.some(row => row.command.kind === 'submit_interaction'
487
494
  && [commandId, ...previousIds].includes(row.command.commandId)
488
- && same(row.command.payload, { interactionId: expected.interactionId, decision: request.interaction.decision }));
495
+ && same(row.command.payload, reply));
489
496
  if (!delivered) {
490
497
  check(same(childApproval(record, reservation), expected), 'child_approval_identity_conflict');
491
- submit(entry, { commandId, kind: 'submit_interaction',
492
- payload: { interactionId: expected.interactionId, decision: request.interaction.decision } });
498
+ submit(entry, { commandId, kind: 'submit_interaction', payload: reply });
493
499
  }
494
500
  }
495
501
  if (!childNeedsApproval(record) || request.action === 'cancel' || request.childApproval?.childRunId === entry.runId) {
@@ -570,10 +576,13 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
570
576
  // Reconcile observes ledgers only. A proven original receipt wait may
571
577
  // remain pending after the parent collector died; it is not a failed
572
578
  // collection and grants no authority to query/send/drive that child.
579
+ // A known pause with no outstanding effect is also a ledger fact. It
580
+ // can restore the parent's join without resuming the child implicitly.
573
581
  // Rebinding and execution happen later in a fresh fenced collect.
574
582
  if (records.some(record => terminal(record.snapshot.phase)
575
583
  ? record.snapshot.phase === 'interrupted' || unsafeReceipt(record)
576
- : request.action === 'cancel' || !canWaitForReceipt?.(record))) return null;
584
+ : request.action === 'cancel' || !canWaitForReceipt?.(record)
585
+ && !(childResumeAllowed(record.snapshot) && !unsafeReceipt(record)))) return null;
577
586
  return { operationKey: request.operationKey,
578
587
  results: records.flatMap((record, index) => terminal(record.snapshot.phase) ? [terminalReceipt(record, request.reservations[index], false)] : []),
579
588
  ...(request.responseCursors === undefined ? {} : { responses: records.flatMap(record => responses(record, request.responseCursors)) }),
@@ -602,6 +611,32 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
602
611
  ? { ...terminalReceipt(record, reservation), childBudgetReservation: copy(reservation) }
603
612
  : startupReceipt(reservation, record.configuration.childOwnerBinding.role) }];
604
613
  },
614
+ // Host disposal is not an operator cancellation. Only detach settled idle
615
+ // workers: their identity, pending decision and join stay in the ledger for
616
+ // a replacement Host. A busy worker requires an explicit stop/recovery
617
+ // path; do not drop its owner or infer that its effect never ran.
618
+ detachRun(request) {
619
+ check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
620
+ const parent = store.load(parentScope, request.runId);
621
+ check(['paused', 'awaiting_interaction'].includes(parent.snapshot.phase), 'child_detach_parent_not_idle');
622
+ const owned = [...entries.values()].filter(entry => entry.configuration.childOwnerBinding.parent.runId === request.runId);
623
+ for (const entry of owned) {
624
+ const record = store.load(entry.scope, entry.runId);
625
+ check(!entry.promise && !entry.idle && !record.lease
626
+ && record.snapshot.pendingIntent === null && !unsafeReceipt(record)
627
+ && (terminal(record.snapshot.phase) || ['paused', 'awaiting_interaction'].includes(record.snapshot.phase)),
628
+ 'child_detach_worker_not_idle');
629
+ }
630
+ for (const entry of owned) entries.delete(entry.runId);
631
+ },
632
+ async closeRun(request) {
633
+ check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
634
+ const parent = store.load(parentScope, request.runId);
635
+ // Terminal cleanup owns cancellation of descendants. Host shutdown does
636
+ // not grant that authority while the durable parent is still resumable.
637
+ if (terminal(parent.snapshot.phase)) return this.releaseRun(request);
638
+ return this.detachRun(request);
639
+ },
605
640
  async releaseRun(request) {
606
641
  check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
607
642
  const jobs = [];
@@ -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, conversationPresentation, toolExecutionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }) }) {
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 }) }) {
116
116
  if (!roles.length) return null;
117
117
  if (workspaceContext !== undefined) {
118
118
  validateNativeWorkspaceContext(workspaceContext);
@@ -121,10 +121,13 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
121
121
  invariant(typeof goalContractFactory === 'function', 'native_child_goal_contract_factory_invalid');
122
122
  invariant(childAllocationPolicy === undefined || childAllocationPolicy === CHILD_ALLOCATION_POLICY, 'studio_native_child_allocation_policy_invalid');
123
123
  invariant(childCapabilityPolicy === undefined || childCapabilityPolicy === CHILD_CAPABILITY_POLICY, 'studio_native_child_capability_policy_invalid');
124
+ invariant(toolAdmissionPolicy === undefined || toolAdmissionPolicy === 'discover-before-retry/v1', 'studio_native_child_admission_policy_invalid');
124
125
  invariant(toolExecutionPolicy === undefined || toolExecutionPolicy === 'owner-execution/v1', 'studio_native_child_execution_policy_invalid');
125
126
  invariant(providerRecoveryPolicy === undefined || providerRecoveryPolicy === 'provider-recovery/v2', 'native_child_provider_recovery_policy_invalid');
126
- invariant(outputRecoveryPolicy === undefined || outputRecoveryPolicy === 'response-boundary/v2', 'studio_native_child_output_policy_invalid');
127
- invariant(outputRestartPolicy === undefined || outputRestartPolicy === 'per-response/v1' && outputRecoveryPolicy === 'response-boundary/v2', 'native_child_output_restart_policy_invalid');
127
+ invariant(outputRecoveryPolicy === undefined || ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'studio_native_child_output_policy_invalid');
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');
130
+ invariant(approvalOutcomePolicy === undefined || approvalOutcomePolicy === 'owner-outcome/v1', 'native_child_approval_outcome_policy_invalid');
128
131
  if (conversationPresentation !== undefined) validateConversationPresentation(conversationPresentation);
129
132
  invariant(childTaskPolicy === undefined || childTaskPolicy === CHILD_TASK_POLICY, 'studio_native_child_task_policy_invalid');
130
133
  invariant(childPlanPolicy === undefined || childPlanPolicy === CHILD_PLAN_POLICY, 'studio_native_child_plan_policy_invalid');
@@ -230,9 +233,11 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
230
233
  const hostBindingDigest = hash({ contract: STUDIO_NATIVE_CHILD_CONTRACT, role, profile: bound.model.profile, scope: child, tools: bound.tools,
231
234
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
232
235
  ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
236
+ ...(approvalOutcomePolicy ? { approvalOutcomePolicy } : {}),
233
237
  ...(conversationPresentation ? { conversationPresentation } : {}),
234
238
  ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
235
239
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
240
+ ...(toolAdmissionPolicy && bound.toolDiscoveryPolicy ? { toolAdmissionPolicy } : {}),
236
241
  ...(childPlanPolicy ? { childPlanPolicy } : {}),
237
242
  ...(childTaskPolicy ? { childTaskPolicy } : {}),
238
243
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
@@ -263,8 +268,10 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
263
268
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
264
269
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
265
270
  ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
271
+ ...(approvalOutcomePolicy ? { approvalOutcomePolicy } : {}),
266
272
  ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
267
273
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
274
+ ...(toolAdmissionPolicy && bound.toolDiscoveryPolicy ? { toolAdmissionPolicy } : {}),
268
275
  ...(executionResource ? { backgroundNotificationPolicy: 'completed-before-model/v1' } : {}),
269
276
  ...(childTaskPolicy ? { todoPolicy: 'session-todos/v1', coordinatorResponsePolicy: COORDINATOR_RESPONSE_POLICY } : {}),
270
277
  ...(bound.toolDiscoveryPolicy ? { toolDiscoveryPolicy: bound.toolDiscoveryPolicy } : {}),
@@ -321,8 +328,10 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
321
328
  invariant(bound && role && canonical(configuration.tools) === canonical(bound.tools)
322
329
  && configuration.outputRecoveryPolicy === outputRecoveryPolicy
323
330
  && configuration.outputRestartPolicy === outputRestartPolicy
331
+ && configuration.approvalOutcomePolicy === approvalOutcomePolicy
324
332
  && configuration.providerRecoveryPolicy === providerRecoveryPolicy
325
333
  && configuration.toolExecutionPolicy === toolExecutionPolicy
334
+ && configuration.toolAdmissionPolicy === (bound.toolDiscoveryPolicy ? toolAdmissionPolicy : undefined)
326
335
  && configuration.inputPolicy === (instructionSource ? 'before-first-model/v1' : undefined)
327
336
  && canonical(configuration.contextSources) === canonical(instructionSource ? [instructionSource.source] : [])
328
337
  && (configuration.childAllocationPolicy ?? null) === (childAllocationPolicy ?? null)
@@ -343,9 +352,11 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
343
352
  profile: bound.model.profile, scope: childScope(role), tools: bound.tools,
344
353
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
345
354
  ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
355
+ ...(approvalOutcomePolicy ? { approvalOutcomePolicy } : {}),
346
356
  ...(conversationPresentation ? { conversationPresentation } : {}),
347
357
  ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
348
358
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
359
+ ...(toolAdmissionPolicy && bound.toolDiscoveryPolicy ? { toolAdmissionPolicy } : {}),
349
360
  ...(childPlanPolicy ? { childPlanPolicy } : {}),
350
361
  ...(childTaskPolicy ? { childTaskPolicy } : {}),
351
362
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
@@ -169,7 +169,7 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
169
169
  invariant(Number.isSafeInteger(ownershipFlushTimeoutMs) && ownershipFlushTimeoutMs > 0
170
170
  && ownershipFlushTimeoutMs <= 2_147_483_647, 'native_dsh_ownership_flush_timeout_invalid');
171
171
  const active = new Set(), backgroundDrivers = new Set(), revisions = streamRevisions;
172
- const run = async (payload, admission, background = null) => {
172
+ const run = async (payload, admission, background = null, operatorResume = false) => {
173
173
  const { agent, input, turn, signal } = payload;
174
174
  invariant(agent?.session && typeof agent.session.id === 'string' && agent.session.id.trim()
175
175
  && input?.kind === 'enter' && Array.isArray(input.messages)
@@ -280,7 +280,16 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
280
280
  taskChainId: binding.taskChainId ?? sessionId };
281
281
  const start = () => background ? store.load(scope, runId).snapshot : kernel.start({ ...identity, parentRunId: null }, configuration,
282
282
  durableOwnership || binding.taskContractFactory ? { expectedParentRunId: parentRunId } : {});
283
+ // The SDK disposes the owner on graceful Host shutdown. A persisted
284
+ // approval wait has no live effect to cancel and may be rebound later,
285
+ // including shutdown between its commit and the idle driver registering.
286
+ const detachingApproval = () => {
287
+ if (!durableOwnership || cancelReason(signal.reason)?.kind !== 'disposed') return null;
288
+ const { snapshot } = store.load(scope, runId);
289
+ return snapshot.phase === 'awaiting_interaction' && snapshot.pendingIntent === null ? snapshot : null;
290
+ };
283
291
  const persistCancel = () => {
292
+ if (detachingApproval()) return;
284
293
  const commandId = `${runId}:dsh-turn-cancel`;
285
294
  const original = store.load(scope, runId).commands.find(row => row.command.commandId === commandId)?.command;
286
295
  return kernel.submit(scope, runId, original ?? { commandId, kind: 'cancel',
@@ -307,11 +316,29 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
307
316
  signal.addEventListener('abort', cancelListener, { once: true });
308
317
  }
309
318
  let wakeIdle = () => {};
310
- releaseControls = onActive?.(payload, { kernel, scope: structuredClone(scope), sessionId, runId, wake: () => wakeIdle() });
319
+ releaseControls = onActive?.(payload, { kernel, scope: structuredClone(scope), sessionId, runId, wake: () => wakeIdle(),
320
+ ...(binding.sessionApproval ? { sessionApproval: binding.sessionApproval } : {}) });
311
321
  invariant(releaseControls === undefined || typeof releaseControls === 'function', 'native_dsh_controls_cleanup_invalid');
322
+ if (operatorResume) {
323
+ signal.throwIfAborted();
324
+ const current = store.load(scope, runId).snapshot;
325
+ if (current.phase === 'paused') {
326
+ // Rebinding an SDK turn is not a Native state transition. Only this
327
+ // explicit Host entry submits the durable command; ordinary delivery
328
+ // and crash reattachment keep user/policy pauses intact. Core owns
329
+ // cancellation precedence and any permitted budget recovery.
330
+ const commandId = `native-dsh-resume-${hash({ scope, runId, revision: current.revision, eventSeq: current.eventSeq })}`;
331
+ invariant(kernel.submit(scope, runId, { commandId, kind: 'resume', payload: {} }).status !== 'rejected',
332
+ 'native_dsh_resume_rejected');
333
+ }
334
+ }
312
335
  let snapshot;
336
+ // The durable DSH listener above owns cancellation and interrupts the
337
+ // worker by submitting its command. A second generic Kernel listener
338
+ // would enqueue an unconditional cancel at the approval checkpoint.
339
+ const driveOptions = durableOwnership ? undefined : { signal };
313
340
  try {
314
- snapshot = await kernel.runUntilIdle(scope, runId, { signal });
341
+ snapshot = await kernel.runUntilIdle(scope, runId, driveOptions);
315
342
  while (!terminal(snapshot.phase)) {
316
343
  signal.throwIfAborted();
317
344
  if (!onIdle) throw failure('NATIVE_TURN_SUSPENDED', snapshot);
@@ -322,21 +349,25 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
322
349
  if (store.load(scope, runId).commands.some(row => !row.consumed)) wakeIdle();
323
350
  command = await resolveWhileLive(() => onIdle(idlePayload, structuredClone(snapshot), {
324
351
  waitForToolReceipt: binding.ports.tools.waitForReceipt,
352
+ ...(binding.sessionApproval ? { sessionApproval: binding.sessionApproval } : {}),
325
353
  }), idlePayload);
326
354
  } catch (error) {
327
355
  if (!woken || signal.aborted) throw error;
328
- snapshot = await kernel.runUntilIdle(scope, runId, { signal });
356
+ snapshot = await kernel.runUntilIdle(scope, runId, driveOptions);
329
357
  continue;
330
358
  } finally { wakeIdle = () => {}; idle.abort(); }
331
359
  if (!command) throw failure('NATIVE_TURN_SUSPENDED', snapshot);
360
+ signal.throwIfAborted();
332
361
  const revision = snapshot.revision;
333
362
  const receipt = kernel.submit(scope, runId, command);
334
363
  invariant(receipt.status !== 'rejected', 'native_dsh_command_rejected');
335
- snapshot = await kernel.runUntilIdle(scope, runId, { signal });
364
+ snapshot = await kernel.runUntilIdle(scope, runId, driveOptions);
336
365
  invariant(terminal(snapshot.phase) || snapshot.revision > revision, 'native_dsh_command_made_no_progress');
337
366
  }
338
367
  signal.throwIfAborted();
339
368
  } catch (error) {
369
+ const approval = detachingApproval();
370
+ if (approval) throw failure('NATIVE_TURN_SUSPENDED', approval);
340
371
  if (signal.aborted && !terminal(store.load(scope, runId).snapshot.phase)) {
341
372
  // A turn can be canceled while no kernel worker is active (approval
342
373
  // or host checkpoint). Persist first, then drain without allowing a
@@ -451,7 +482,7 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
451
482
  const admission = readNativeDshOwnership(resumed.ownership, { sessionId: agent.session.id, turn: resumed.turn });
452
483
  return run({ ...request, ...resumed, agent,
453
484
  signal: request.signal ? AbortSignal.any([request.signal, resumed.signal]) : resumed.signal,
454
- input: { kind: 'enter', messages: structuredClone(admission.messages) } }, admission);
485
+ input: { kind: 'enter', messages: structuredClone(admission.messages) } }, admission, null, true);
455
486
  });
456
487
  };
457
488
  /** Drive only the persisted notification identified by an already claimed owner. */
@@ -476,7 +507,9 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
476
507
  // it can only validate the existing notice and enqueue its cancel.
477
508
  verified ??= await verifyNativeDshBackgroundOwnership(ownership, { ...facts, signal: new AbortController().signal });
478
509
  const { identity } = verified.admission, record = store.load(identity.scope, identity.runId);
479
- if (!['completed', 'failed', 'canceled'].includes(record.snapshot.phase)) {
510
+ if (!['completed', 'failed', 'canceled'].includes(record.snapshot.phase)
511
+ && !(cancelReason(payload.signal.reason)?.kind === 'disposed' && record.snapshot.phase === 'awaiting_interaction'
512
+ && record.snapshot.pendingIntent === null)) {
480
513
  const commandId = `${identity.runId}:dsh-turn-cancel`;
481
514
  const previous = record.commands.find(row => row.command.commandId === commandId)?.command;
482
515
  new NativeKernel({ store, digest: hash, owner, ports: {} }).submit(identity.scope, identity.runId,
@@ -182,9 +182,9 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
182
182
  // body read rejects cleanly instead of leaving an orphaned read to cancel.
183
183
  const abort = (reason) => internal.abort(reason);
184
184
  let frameIndex = -1;
185
- const failed = (result, code) => withFailure(result, binding, 'stream', code,
185
+ const failed = (result, code, fields = {}) => withFailure(result, binding, 'stream', code,
186
186
  { ...(frameIndex < 0 ? {} : { frameIndex }),
187
- ...(code === 'usage_conflict' && state.usageConflict ? { usageConflict: state.usageConflict } : {}) });
187
+ ...(code === 'usage_conflict' && state.usageConflict ? { usageConflict: state.usageConflict } : {}), ...fields });
188
188
  try {
189
189
  for await (const frame of readModelSse(response.body, { maxBytes, idleTimeoutMs, abort, observeBytes: observation.bytes })) {
190
190
  if (idlePolicy && !frame.data.trim()) continue;
@@ -205,7 +205,8 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
205
205
  if (error instanceof ProtocolError) {
206
206
  // Typed provider error envelopes carry a closed, credential-free classification.
207
207
  if (error.streamError) {
208
- return failed(state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }), 'provider_error');
208
+ return failed(state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }), 'provider_error',
209
+ error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {});
209
210
  }
210
211
  return failed(state.finalize({ errorKind: 'provider_terminal_error', failureKind: 'invalid_response' }), protocolCode(error));
211
212
  }
@@ -218,7 +219,8 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
218
219
  }
219
220
  const result = state.finalize();
220
221
  return failed(result, state.streamError ? 'provider_error' : result.kind === 'malformed_tool_call' ? 'tool_payload_invalid'
221
- : result.failureKind === 'incomplete_response' ? 'stream_incomplete' : 'protocol_invalid');
222
+ : result.failureKind === 'incomplete_response' ? 'stream_incomplete' : 'protocol_invalid',
223
+ state.streamError?.diagnostic ? { providerError: state.streamError.diagnostic } : {});
222
224
  }
223
225
 
224
226
  async function bufferedResponse(response, request, binding, maxBytes, emit, observation) {
@@ -239,7 +241,8 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
239
241
  } catch (error) {
240
242
  if (error instanceof ProtocolError && error.streamError) {
241
243
  const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
242
- return withFailure(result, binding, 'buffered', 'provider_error');
244
+ return withFailure(result, binding, 'buffered', 'provider_error',
245
+ error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {});
243
246
  }
244
247
  return withFailure(terminalResult('invalid_response'), binding, 'buffered', protocolCode(error));
245
248
  }
@@ -295,7 +298,7 @@ function protocolCode(error) {
295
298
  function withFailure(result, binding, phase, code, fields = {}) {
296
299
  if (!['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)) return result;
297
300
  const protocol = ['openai-chat', 'openai-responses', 'anthropic-messages'].includes(binding?.protocol) ? binding.protocol : 'unknown';
298
- return { ...result, failureDiagnostic: { contract: fields.usageConflict
301
+ return { ...result, failureDiagnostic: { contract: fields.providerError ? 'model-failure-diagnostic/v3' : fields.usageConflict
299
302
  ? 'model-failure-diagnostic/v2' : 'model-failure-diagnostic/v1', protocol, phase, code, ...fields } };
300
303
  }
301
304
 
@@ -44,24 +44,31 @@ export function applyAnthropicThinking(payload, profile, binding) {
44
44
  }
45
45
 
46
46
  export function admitProviderCompatibilityPolicy(override) {
47
- return { contract: 'provider-compat/v3', rule: admitInlineReasoningPolicy(override).rule };
47
+ return { contract: 'provider-compat/v4', rule: admitInlineReasoningPolicy(override).rule };
48
48
  }
49
49
 
50
50
  export function resolveProviderCompatibility(policy, binding) {
51
51
  if (!policy) return null;
52
- if (!['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3'].includes(policy.contract)) throw new ProtocolError('invalid_provider_compatibility_policy');
52
+ if (!['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)) throw new ProtocolError('invalid_provider_compatibility_policy');
53
53
  const rule = resolveCompatibilityRule(policy.rule, binding);
54
54
  const name = String(binding.model ?? '').trim().toLowerCase();
55
55
  const kimi = ['kspmas-gateway', 'moonshot'].includes(rule)
56
56
  && ['kimi-k2.7-code', 'kimi-k2.7-code-highspeed'].includes(name);
57
- const reasoningRequired = policy.contract === 'provider-compat/v3' && rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
57
+ const modern = ['provider-compat/v3', 'provider-compat/v4'].includes(policy.contract);
58
+ const reasoningRequired = modern && rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
58
59
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === 'claude-haiku-5-5' ? ['low', 'medium', 'high'] : null;
59
60
  return { rule, supportsUsage: !strict.has(rule), supportsThinking: !strict.has(rule) && !kimi,
60
- supportsToolArgumentStreaming: ['provider-compat/v2', 'provider-compat/v3'].includes(policy.contract)
61
+ supportsToolArgumentStreaming: ['provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)
61
62
  && ['zai', 'kspmas-gateway'].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
62
- reasoningRequired, modern: policy.contract === 'provider-compat/v3',
63
+ reasoningRequired, modern,
64
+ // This route already uses the supported non-thinking mode for tool work.
65
+ // A bounded summary has no tools: omitting the switch can instead select
66
+ // the provider's default high reasoning and consume its whole output cap.
67
+ // Freeze this purpose-specific default only on new admissions; mandatory
68
+ // thinking models and explicit caller choices remain authoritative.
69
+ compactionThinkingOff: policy.contract === 'provider-compat/v4' && rule === 'kspmas-gateway' && !kimi,
63
70
  // Only the observed provider/model dialects may seal without [DONE].
64
- finishOnEof: policy.contract === 'provider-compat/v3' && ['permissive', 'kspmas-gateway'].includes(rule)
71
+ finishOnEof: modern && ['permissive', 'kspmas-gateway'].includes(rule)
65
72
  && ['minimax-m3', 'minimax-m2.5'].includes(name),
66
73
  supportsEffort: !kimi, toolThinkingOff: ['zai', 'kspmas-gateway'].includes(rule) && !kimi,
67
74
  thinkingBudget: rule === 'zai' && !kimi && !disabledEfforts ? 32000 : null,
@@ -116,11 +123,13 @@ export function applyProviderChatCompatibility(payload, request, binding) {
116
123
  if (mode === 'disabled' && compat.reasoningRequired) throw new ProtocolError('model_thinking_disable_unsupported');
117
124
  const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
118
125
  const summaryOff = request.purpose === 'compaction' && requested === null && compat.rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
126
+ const boundedSummaryOff = request.purpose === 'compaction' && compat.compactionThinkingOff
127
+ && requested === null && mode === undefined;
119
128
  const budget = result.max_completion_tokens ?? result.max_tokens;
120
129
  if (mode === 'enabled') {
121
130
  if (!compat.supportsThinking) throw new ProtocolError('model_thinking_mode_unsupported');
122
131
  result.thinking = { type: 'enabled' };
123
- } else if (mayDisable && (mode === 'disabled' || summaryOff
132
+ } else if (mayDisable && (mode === 'disabled' || summaryOff || boundedSummaryOff
124
133
  || compat.toolThinkingOff && !!result.tools?.length && result.tool_choice !== 'none'
125
134
  || compat.thinkingBudget !== null && budget <= compat.thinkingBudget)) result.thinking = { type: 'disabled' };
126
135
  if (!compat.supportsThinking) delete result.thinking;
@@ -1,6 +1,8 @@
1
1
  // Shared OpenAI-compatible provider error classification for JSON and SSE.
2
2
  // HTTP transport status is handled separately. Never infer retries from raw
3
3
  // messages or retain provider bytes; unknown/malformed envelopes fail closed.
4
+ import { createHash } from 'node:crypto';
5
+ import { canonical, MODEL_PROVIDER_ERROR_CODES, MODEL_PROVIDER_ERROR_TYPES } from '@kingsoftcloud/agentkit-harness-core';
4
6
  const RETRYABLE_ERROR_CODES = new Set([
5
7
  'rate_limit_error', 'rate_limit_exceeded', 'overloaded_error', 'server_error',
6
8
  'api_error', 'service_unavailable_error', 'server_is_overloaded', 'timeout_error',
@@ -15,6 +17,22 @@ const TERMINAL_ERROR_CODES = new Set([
15
17
  ]);
16
18
 
17
19
  export function classifyOpenAIProviderError(error) {
20
+ const decision = classifyError(error);
21
+ // Classification and evidence are separate: evidence never authorizes a retry.
22
+ // Unknown message/code/type bytes remain outside the durable result. Their
23
+ // fingerprint supports grouping repeated failures without copying credentials.
24
+ let fingerprint;
25
+ try { fingerprint = `sha256:${createHash('sha256').update(canonical(error)).digest('hex')}`; }
26
+ catch { return decision; }
27
+ const object = error && typeof error === 'object' && !Array.isArray(error) ? error : {};
28
+ return { ...decision, diagnostic: { category: decision.failureKind, fingerprint,
29
+ ...(MODEL_PROVIDER_ERROR_CODES.includes(object.code) ? { code: object.code } : {}),
30
+ ...(MODEL_PROVIDER_ERROR_TYPES.includes(object.type) ? { type: object.type } : {}),
31
+ ...(Number.isInteger(object.code) && object.code >= 400 && object.code <= 599 ? { status: object.code } : {}),
32
+ } };
33
+ }
34
+
35
+ function classifyError(error) {
18
36
  const invalid = { kind: 'provider_terminal_error', failureKind: 'invalid_response' };
19
37
  if (!error || typeof error !== 'object' || Array.isArray(error)) return invalid;
20
38
  if (error.type != null && typeof error.type !== 'string') return invalid;
@@ -0,0 +1,91 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { canonical, copy, invariant, scopeKey } from '@kingsoftcloud/agentkit-harness-core';
3
+
4
+ export const SESSION_TOOL_APPROVAL_CONTRACT = 'agentkit.native-session-tool-approval/v1';
5
+ const bindingKeys = ['scope', 'sessionId', 'buildId', 'authorityDigest', 'toolName', 'definitionDigest'];
6
+ const opaque = value => typeof value === 'string' && value.trim().length > 0 && value.length <= 256;
7
+ function bindingOf(value) {
8
+ invariant(value && !Array.isArray(value) && Object.keys(value).length === bindingKeys.length
9
+ && bindingKeys.every(key => Object.hasOwn(value, key)), 'session_tool_approval_binding_invalid');
10
+ scopeKey(value.scope);
11
+ invariant(['sessionId', 'buildId', 'toolName'].every(key => opaque(value[key]))
12
+ && ['authorityDigest', 'definitionDigest'].every(key => /^[a-f0-9]{64}$/.test(value[key])), 'session_tool_approval_binding_invalid');
13
+ return copy(value);
14
+ }
15
+
16
+ /** Live, explicit Session grants for one additional permission constraint.
17
+ * The Host must still run every downstream policy, guard and sandbox check.
18
+ * Offers cannot be reconstructed from model output or an old audit record;
19
+ * a new process starts without grants. Audit failure never installs a grant.
20
+ */
21
+ export function createSessionToolApprovalOwner({ audit, now = Date.now, token = randomUUID,
22
+ maxOffers = 256, maxGrants = 1024, offerTimeoutMs = 120000 } = {}) {
23
+ invariant(typeof audit === 'function' && typeof now === 'function' && typeof token === 'function'
24
+ && [maxOffers, maxGrants, offerTimeoutMs].every(value => Number.isSafeInteger(value) && value > 0),
25
+ 'session_tool_approval_owner_invalid');
26
+ const offers = new Map(), grants = new Map();
27
+ let closed = false;
28
+ const current = entry => {
29
+ try { return !closed && !entry.signal.aborted && now() < entry.expiresAt && entry.isCurrent() === true; }
30
+ catch { return false; }
31
+ };
32
+ const record = entry => {
33
+ const event = { contract: SESSION_TOOL_APPROVAL_CONTRACT, offerId: entry.offerId,
34
+ requestId: entry.requestId, binding: copy(entry.binding), offerExpiresAt: entry.expiresAt };
35
+ const result = audit(copy(event));
36
+ if (result && typeof result.then === 'function') {
37
+ Promise.resolve(result).catch(() => {});
38
+ invariant(false, 'session_tool_approval_audit_must_commit_synchronously');
39
+ }
40
+ return Object.freeze(event);
41
+ };
42
+ const prune = () => {
43
+ for (const [id, entry] of offers) if (!current(entry)) offers.delete(id);
44
+ };
45
+ return Object.freeze({
46
+ offer({ binding, requestId, signal, isCurrent }) {
47
+ invariant(!closed && opaque(requestId) && signal instanceof AbortSignal && typeof isCurrent === 'function',
48
+ 'session_tool_approval_offer_invalid');
49
+ const admitted = bindingOf(binding); prune();
50
+ invariant(offers.size < maxOffers, 'session_tool_approval_offer_capacity');
51
+ const offerId = token();
52
+ invariant(opaque(offerId) && !offers.has(offerId) && ![...grants.values()].some(item => item.offerId === offerId),
53
+ 'session_tool_approval_token_invalid');
54
+ const entry = { offerId, requestId, binding: admitted, signal, isCurrent, expiresAt: now() + offerTimeoutMs };
55
+ invariant(current(entry), 'session_tool_approval_offer_stale');
56
+ offers.set(offerId, entry);
57
+ return Object.freeze({ contract: SESSION_TOOL_APPROVAL_CONTRACT, offerId, requestId,
58
+ sessionId: admitted.sessionId, toolName: admitted.toolName, expiresAt: entry.expiresAt });
59
+ },
60
+ grant({ offerId, requestId, binding }) {
61
+ invariant(!closed, 'session_tool_approval_closed');
62
+ const admitted = bindingOf(binding), key = canonical(admitted), previous = grants.get(key);
63
+ if (previous?.offerId === offerId && previous.requestId === requestId)
64
+ return { status: 'duplicate', receipt: copy(previous) };
65
+ const entry = offers.get(offerId);
66
+ invariant(entry && entry.requestId === requestId && canonical(entry.binding) === key && current(entry),
67
+ 'session_tool_approval_offer_stale');
68
+ invariant(grants.has(key) || grants.size < maxGrants, 'session_tool_approval_grant_capacity');
69
+ const receipt = record(entry);
70
+ // A synchronous audit callback may revoke/withdraw the offer.
71
+ invariant(offers.get(offerId) === entry && current(entry), 'session_tool_approval_offer_stale');
72
+ grants.set(key, receipt); offers.delete(offerId);
73
+ return { status: 'accepted', receipt: copy(receipt) };
74
+ },
75
+ has(binding) { return !closed && grants.has(canonical(bindingOf(binding))); },
76
+ withdraw(offerId, { revokeGrant = false } = {}) {
77
+ offers.delete(offerId);
78
+ const revoked = [];
79
+ if (revokeGrant) for (const [key, receipt] of grants) if (receipt.offerId === offerId) {
80
+ revoked.push(copy(receipt)); grants.delete(key);
81
+ }
82
+ return revoked;
83
+ },
84
+ revokeSession(scope, sessionId) {
85
+ const identity = canonical({ scope, sessionId });
86
+ for (const [id, entry] of offers) if (canonical({ scope: entry.binding.scope, sessionId: entry.binding.sessionId }) === identity) offers.delete(id);
87
+ for (const [id, entry] of grants) if (canonical({ scope: entry.binding.scope, sessionId: entry.binding.sessionId }) === identity) grants.delete(id);
88
+ },
89
+ close() { closed = true; offers.clear(); grants.clear(); },
90
+ });
91
+ }
@@ -176,12 +176,17 @@ export function createWorkspaceCheckpointJournal({ stateDir, sessionId, workspac
176
176
  files: files.map(file => ({ path: file.path, action: file.desired.kind === 'absent' ? 'delete' : 'restore',
177
177
  current_sha256: file.current.sha256 ?? null, restored_sha256: file.desired.sha256 ?? null })) } };
178
178
  }
179
- function originalRecord(request, original = false) {
180
- return rows().toReversed().find(row =>
181
- row.binding && ['scope', 'sessionId', 'runId', 'turnId', 'buildId'].every(key => canonical(row.binding[key] ?? null) === canonical(request[key] ?? null))
179
+ function sameRun(row, request) {
180
+ return row.binding && ['scope', 'sessionId', 'runId', 'turnId', 'buildId'].every(key =>
181
+ canonical(row.binding[key] ?? null) === canonical(request[key] ?? null));
182
+ }
183
+ function originalRecord(request, original = false, entries = rows()) {
184
+ const callDigest = sha256(canonical(request.call)), definitionDigest = sha256(canonical(request.definition));
185
+ return entries.toReversed().find(row =>
186
+ sameRun(row, request)
182
187
  && row.binding.operationKey === (original ? request.originalOperationKey : request.operationKey)
183
188
  && row.binding.executionFence === (original ? request.originalClaimedFence : request.executionFence)
184
- && row.callDigest === sha256(canonical(request.call)) && row.definitionDigest === sha256(canonical(request.definition)));
189
+ && row.callDigest === callDigest && row.definitionDigest === definitionDigest);
185
190
  }
186
191
  function receiptRecord(request, original = false) {
187
192
  const row = originalRecord(request, original);
@@ -267,7 +272,17 @@ export function createWorkspaceCheckpointJournal({ stateDir, sessionId, workspac
267
272
  if (row.receipt && canonical(row.receipt) !== canonical(result)) fail('checkpoint_receipt_conflict');
268
273
  save({ ...row, receipt: structuredClone(result) });
269
274
  },
270
- readReceipt(request) { return structuredClone(receiptRecord(request, true)?.receipt ?? null); },
275
+ readReceipt(request) {
276
+ const entries = rows();
277
+ const row = originalRecord(request, true, entries);
278
+ if (row) return structuredClone(['completed', 'failed'].includes(row.status) ? row.receipt ?? null : null);
279
+ // Every checkpoint-governed mutation writes its operation identity before
280
+ // publication. Require an intact journal anchored to this same Run, and
281
+ // keep a conflicting operation identity unknown even if its digest differs.
282
+ if (!entries.some(entry => sameRun(entry, request))
283
+ || entries.some(entry => entry.binding?.operationKey === request.originalOperationKey)) return null;
284
+ return { status: 'error', content: { code: 'workspace_mutation_not_started', executed: false } };
285
+ },
271
286
  list: () => rows().toReversed().slice(0, 50).map(row => ({ checkpoint_id: row.id, created_at: row.createdAt,
272
287
  status: row.status, run_id: row.binding?.runId ?? row.controlBinding?.expectedHeadRunId ?? null,
273
288
  tool: row.binding?.toolName ?? 'conversation_workspace_rewind', paths: row.files.map(file => file.path) })) };
@@ -1442,7 +1442,8 @@ export function createNativeWorkspaceTools({
1442
1442
  const signal = request.signal, sealed = canonical({ ...request, signal: null });
1443
1443
  const check = () => {
1444
1444
  checkRootBoundary(); signal?.throwIfAborted();
1445
- if (request.sessionId !== store.sessionId || request.signal !== signal || canonical({ ...request, signal: null }) !== sealed
1445
+ if (!enableRewind || !MUTATING.has(request.call?.name) || request.sessionId !== store.sessionId
1446
+ || request.signal !== signal || canonical({ ...request, signal: null }) !== sealed
1446
1447
  || request.contract !== 'agentkit.tool-receipt-observation/v1' || request.definition?.workspaceCheckpointPolicy !== WORKSPACE_CHECKPOINT_POLICY
1447
1448
  || request.definition?.recoveryPolicy !== 'receipt-observation/v1' || typeof assertCurrent !== 'function' || assertCurrent(request) !== true)
1448
1449
  throw Object.assign(Error('checkpoint_receipt_authority_changed'), { code: 'checkpoint_receipt_authority_changed' });