@kingsoftcloud/agentkit-harness-node 0.0.14 → 0.0.15
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 +58 -16
- package/dist/rpc-entry.mjs +64 -22
- package/package.json +4 -2
- package/src/native/approval-preflight.mjs +35 -0
- package/src/native/child-history.mjs +5 -2
- package/src/native/child-owner.mjs +46 -11
- package/src/native/children.mjs +14 -3
- package/src/native/dsh-turn-runtime.mjs +28 -3
- package/src/native/model-port.mjs +9 -6
- package/src/native/model-provider-compat.mjs +16 -7
- package/src/native/model-provider-error.mjs +18 -0
- package/src/native/session-tool-approval.mjs +91 -0
- package/src/native/workspace-checkpoints.mjs +20 -5
- package/src/native/workspace-tools.mjs +2 -1
package/dist/index.mjs
CHANGED
|
@@ -2037,21 +2037,28 @@ function applyAnthropicThinking(payload, profile, binding) {
|
|
|
2037
2037
|
}
|
|
2038
2038
|
function resolveProviderCompatibility(policy, binding) {
|
|
2039
2039
|
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");
|
|
2040
|
+
if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
|
|
2041
2041
|
const rule = resolveCompatibilityRule(policy.rule, binding);
|
|
2042
2042
|
const name = String(binding.model ?? "").trim().toLowerCase();
|
|
2043
2043
|
const kimi = ["kspmas-gateway", "moonshot"].includes(rule) && ["kimi-k2.7-code", "kimi-k2.7-code-highspeed"].includes(name);
|
|
2044
|
-
const
|
|
2044
|
+
const modern = ["provider-compat/v3", "provider-compat/v4"].includes(policy.contract);
|
|
2045
|
+
const reasoningRequired = modern && rule === "kspmas-gateway" && name === "glm-5.3-flash";
|
|
2045
2046
|
const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === "claude-haiku-5-5" ? ["low", "medium", "high"] : null;
|
|
2046
2047
|
return {
|
|
2047
2048
|
rule,
|
|
2048
2049
|
supportsUsage: !strict.has(rule),
|
|
2049
2050
|
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)),
|
|
2051
|
+
supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
|
|
2051
2052
|
reasoningRequired,
|
|
2052
|
-
modern
|
|
2053
|
+
modern,
|
|
2054
|
+
// This route already uses the supported non-thinking mode for tool work.
|
|
2055
|
+
// A bounded summary has no tools: omitting the switch can instead select
|
|
2056
|
+
// the provider's default high reasoning and consume its whole output cap.
|
|
2057
|
+
// Freeze this purpose-specific default only on new admissions; mandatory
|
|
2058
|
+
// thinking models and explicit caller choices remain authoritative.
|
|
2059
|
+
compactionThinkingOff: policy.contract === "provider-compat/v4" && rule === "kspmas-gateway" && !kimi,
|
|
2053
2060
|
// Only the observed provider/model dialects may seal without [DONE].
|
|
2054
|
-
finishOnEof:
|
|
2061
|
+
finishOnEof: modern && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
|
|
2055
2062
|
supportsEffort: !kimi,
|
|
2056
2063
|
toolThinkingOff: ["zai", "kspmas-gateway"].includes(rule) && !kimi,
|
|
2057
2064
|
thinkingBudget: rule === "zai" && !kimi && !disabledEfforts ? 32e3 : null,
|
|
@@ -2106,11 +2113,12 @@ function applyProviderChatCompatibility(payload, request, binding) {
|
|
|
2106
2113
|
if (mode === "disabled" && compat.reasoningRequired) throw new ProtocolError("model_thinking_disable_unsupported");
|
|
2107
2114
|
const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
|
|
2108
2115
|
const summaryOff = request.purpose === "compaction" && requested === null && compat.rule === "kspmas-gateway" && name === "glm-5.3-flash";
|
|
2116
|
+
const boundedSummaryOff = request.purpose === "compaction" && compat.compactionThinkingOff && requested === null && mode === void 0;
|
|
2109
2117
|
const budget = result.max_completion_tokens ?? result.max_tokens;
|
|
2110
2118
|
if (mode === "enabled") {
|
|
2111
2119
|
if (!compat.supportsThinking) throw new ProtocolError("model_thinking_mode_unsupported");
|
|
2112
2120
|
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" };
|
|
2121
|
+
} 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
2122
|
if (!compat.supportsThinking) delete result.thinking;
|
|
2115
2123
|
if (!compat.supportsEffort) delete result.reasoning_effort;
|
|
2116
2124
|
if (compat.modern && ["moonshot", "kspmas-gateway"].includes(compat.rule) && result.tools) {
|
|
@@ -2148,6 +2156,8 @@ function explicitLiteralTypes(schema) {
|
|
|
2148
2156
|
}
|
|
2149
2157
|
|
|
2150
2158
|
// packages/agentkit-harness-node/src/native/model-provider-error.mjs
|
|
2159
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
2160
|
+
import { canonical as canonical8, MODEL_PROVIDER_ERROR_CODES, MODEL_PROVIDER_ERROR_TYPES } from "@kingsoftcloud/agentkit-harness-core";
|
|
2151
2161
|
var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
2152
2162
|
"rate_limit_error",
|
|
2153
2163
|
"rate_limit_exceeded",
|
|
@@ -2176,6 +2186,23 @@ var TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
|
2176
2186
|
"MODEL_PROVIDER_QUOTA_EXHAUSTED"
|
|
2177
2187
|
]);
|
|
2178
2188
|
function classifyOpenAIProviderError(error) {
|
|
2189
|
+
const decision = classifyError(error);
|
|
2190
|
+
let fingerprint;
|
|
2191
|
+
try {
|
|
2192
|
+
fingerprint = `sha256:${createHash6("sha256").update(canonical8(error)).digest("hex")}`;
|
|
2193
|
+
} catch {
|
|
2194
|
+
return decision;
|
|
2195
|
+
}
|
|
2196
|
+
const object2 = error && typeof error === "object" && !Array.isArray(error) ? error : {};
|
|
2197
|
+
return { ...decision, diagnostic: {
|
|
2198
|
+
category: decision.failureKind,
|
|
2199
|
+
fingerprint,
|
|
2200
|
+
...MODEL_PROVIDER_ERROR_CODES.includes(object2.code) ? { code: object2.code } : {},
|
|
2201
|
+
...MODEL_PROVIDER_ERROR_TYPES.includes(object2.type) ? { type: object2.type } : {},
|
|
2202
|
+
...Number.isInteger(object2.code) && object2.code >= 400 && object2.code <= 599 ? { status: object2.code } : {}
|
|
2203
|
+
} };
|
|
2204
|
+
}
|
|
2205
|
+
function classifyError(error) {
|
|
2179
2206
|
const invalid = { kind: "provider_terminal_error", failureKind: "invalid_response" };
|
|
2180
2207
|
if (!error || typeof error !== "object" || Array.isArray(error)) return invalid;
|
|
2181
2208
|
if (error.type != null && typeof error.type !== "string") return invalid;
|
|
@@ -3038,7 +3065,7 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
|
|
|
3038
3065
|
if (profile.providerReplayProjectionPolicy === "anthropic-client-compaction/v1") {
|
|
3039
3066
|
const originals = message.providerReplay.anthropicContent.filter((block) => block?.type === "tool_use");
|
|
3040
3067
|
for (const [index, block] of originals.entries()) wireIds.set(message.toolCalls[index].callId, block.id);
|
|
3041
|
-
const inverse = new Map([...wireIds].map(([
|
|
3068
|
+
const inverse = new Map([...wireIds].map(([canonical9, original]) => [canonical9, original]));
|
|
3042
3069
|
blocks = replayContent.map((block) => block?.type === "tool_use" ? { ...block, id: inverse.get(block.id) ?? block.id } : block);
|
|
3043
3070
|
} else blocks = replayContent;
|
|
3044
3071
|
} else {
|
|
@@ -3859,9 +3886,9 @@ function projectResponsesOutput(payload, { status }) {
|
|
|
3859
3886
|
reasoning.push(partsText(item.content, /* @__PURE__ */ new Set(["reasoning_text", "text"])));
|
|
3860
3887
|
}
|
|
3861
3888
|
}
|
|
3862
|
-
const
|
|
3889
|
+
const canonical9 = messages.join("");
|
|
3863
3890
|
const convenience = optionalText(payload.output_text);
|
|
3864
|
-
if ("output" in payload && payload.output_text != null &&
|
|
3891
|
+
if ("output" in payload && payload.output_text != null && canonical9 !== convenience) {
|
|
3865
3892
|
throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
3866
3893
|
}
|
|
3867
3894
|
let finish;
|
|
@@ -3881,7 +3908,7 @@ function projectResponsesOutput(payload, { status }) {
|
|
|
3881
3908
|
finish = "content_filter";
|
|
3882
3909
|
calls.length = 0;
|
|
3883
3910
|
}
|
|
3884
|
-
return { finish, content:
|
|
3911
|
+
return { finish, content: canonical9 || convenience, reasoning: reasoning.join(""), calls, refused };
|
|
3885
3912
|
}
|
|
3886
3913
|
function responseMessageContent(value) {
|
|
3887
3914
|
if (!Array.isArray(value)) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
@@ -4818,14 +4845,15 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4818
4845
|
const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
|
|
4819
4846
|
const abort = (reason) => internal.abort(reason);
|
|
4820
4847
|
let frameIndex = -1;
|
|
4821
|
-
const failed = (result2, code) => withFailure(
|
|
4848
|
+
const failed = (result2, code, fields2 = {}) => withFailure(
|
|
4822
4849
|
result2,
|
|
4823
4850
|
binding,
|
|
4824
4851
|
"stream",
|
|
4825
4852
|
code,
|
|
4826
4853
|
{
|
|
4827
4854
|
...frameIndex < 0 ? {} : { frameIndex },
|
|
4828
|
-
...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {}
|
|
4855
|
+
...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {},
|
|
4856
|
+
...fields2
|
|
4829
4857
|
}
|
|
4830
4858
|
);
|
|
4831
4859
|
try {
|
|
@@ -4847,7 +4875,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4847
4875
|
}
|
|
4848
4876
|
if (error instanceof ProtocolError) {
|
|
4849
4877
|
if (error.streamError) {
|
|
4850
|
-
return failed(
|
|
4878
|
+
return failed(
|
|
4879
|
+
state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }),
|
|
4880
|
+
"provider_error",
|
|
4881
|
+
error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
|
|
4882
|
+
);
|
|
4851
4883
|
}
|
|
4852
4884
|
return failed(state.finalize({ errorKind: "provider_terminal_error", failureKind: "invalid_response" }), protocolCode(error));
|
|
4853
4885
|
}
|
|
@@ -4857,7 +4889,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4857
4889
|
return failed(state.finalize({ errorKind: "provider_retryable_error", failureKind: sanitizeFailureKind(error, "network_error") }), "transport_error");
|
|
4858
4890
|
}
|
|
4859
4891
|
const result = state.finalize();
|
|
4860
|
-
return failed(
|
|
4892
|
+
return failed(
|
|
4893
|
+
result,
|
|
4894
|
+
state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid",
|
|
4895
|
+
state.streamError?.diagnostic ? { providerError: state.streamError.diagnostic } : {}
|
|
4896
|
+
);
|
|
4861
4897
|
}
|
|
4862
4898
|
async function bufferedResponse(response, request, binding, maxBytes, emit, observation) {
|
|
4863
4899
|
const bodyText = await readBoundedText(response, maxBytes, observation.bytes);
|
|
@@ -4876,7 +4912,13 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
|
|
|
4876
4912
|
} catch (error) {
|
|
4877
4913
|
if (error instanceof ProtocolError && error.streamError) {
|
|
4878
4914
|
const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
|
|
4879
|
-
return withFailure(
|
|
4915
|
+
return withFailure(
|
|
4916
|
+
result,
|
|
4917
|
+
binding,
|
|
4918
|
+
"buffered",
|
|
4919
|
+
"provider_error",
|
|
4920
|
+
error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
|
|
4921
|
+
);
|
|
4880
4922
|
}
|
|
4881
4923
|
return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
|
|
4882
4924
|
}
|
|
@@ -4922,7 +4964,7 @@ function protocolCode(error) {
|
|
|
4922
4964
|
function withFailure(result, binding, phase, code, fields2 = {}) {
|
|
4923
4965
|
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind)) return result;
|
|
4924
4966
|
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 } };
|
|
4967
|
+
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
4968
|
}
|
|
4927
4969
|
function retryableResult(failureKind, retryAfterMs = null) {
|
|
4928
4970
|
const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
|
package/dist/rpc-entry.mjs
CHANGED
|
@@ -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
|
|
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
|
|
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";
|
|
@@ -2048,21 +2048,28 @@ function applyAnthropicThinking(payload, profile, binding) {
|
|
|
2048
2048
|
}
|
|
2049
2049
|
function resolveProviderCompatibility(policy, binding) {
|
|
2050
2050
|
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");
|
|
2051
|
+
if (!["provider-compat/v1", "provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract)) throw new ProtocolError("invalid_provider_compatibility_policy");
|
|
2052
2052
|
const rule = resolveCompatibilityRule(policy.rule, binding);
|
|
2053
2053
|
const name = String(binding.model ?? "").trim().toLowerCase();
|
|
2054
2054
|
const kimi = ["kspmas-gateway", "moonshot"].includes(rule) && ["kimi-k2.7-code", "kimi-k2.7-code-highspeed"].includes(name);
|
|
2055
|
-
const
|
|
2055
|
+
const modern = ["provider-compat/v3", "provider-compat/v4"].includes(policy.contract);
|
|
2056
|
+
const reasoningRequired = modern && rule === "kspmas-gateway" && name === "glm-5.3-flash";
|
|
2056
2057
|
const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === "claude-haiku-5-5" ? ["low", "medium", "high"] : null;
|
|
2057
2058
|
return {
|
|
2058
2059
|
rule,
|
|
2059
2060
|
supportsUsage: !strict.has(rule),
|
|
2060
2061
|
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)),
|
|
2062
|
+
supportsToolArgumentStreaming: ["provider-compat/v2", "provider-compat/v3", "provider-compat/v4"].includes(policy.contract) && ["zai", "kspmas-gateway"].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
|
|
2062
2063
|
reasoningRequired,
|
|
2063
|
-
modern
|
|
2064
|
+
modern,
|
|
2065
|
+
// This route already uses the supported non-thinking mode for tool work.
|
|
2066
|
+
// A bounded summary has no tools: omitting the switch can instead select
|
|
2067
|
+
// the provider's default high reasoning and consume its whole output cap.
|
|
2068
|
+
// Freeze this purpose-specific default only on new admissions; mandatory
|
|
2069
|
+
// thinking models and explicit caller choices remain authoritative.
|
|
2070
|
+
compactionThinkingOff: policy.contract === "provider-compat/v4" && rule === "kspmas-gateway" && !kimi,
|
|
2064
2071
|
// Only the observed provider/model dialects may seal without [DONE].
|
|
2065
|
-
finishOnEof:
|
|
2072
|
+
finishOnEof: modern && ["permissive", "kspmas-gateway"].includes(rule) && ["minimax-m3", "minimax-m2.5"].includes(name),
|
|
2066
2073
|
supportsEffort: !kimi,
|
|
2067
2074
|
toolThinkingOff: ["zai", "kspmas-gateway"].includes(rule) && !kimi,
|
|
2068
2075
|
thinkingBudget: rule === "zai" && !kimi && !disabledEfforts ? 32e3 : null,
|
|
@@ -2117,11 +2124,12 @@ function applyProviderChatCompatibility(payload, request, binding) {
|
|
|
2117
2124
|
if (mode === "disabled" && compat.reasoningRequired) throw new ProtocolError("model_thinking_disable_unsupported");
|
|
2118
2125
|
const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
|
|
2119
2126
|
const summaryOff = request.purpose === "compaction" && requested === null && compat.rule === "kspmas-gateway" && name === "glm-5.3-flash";
|
|
2127
|
+
const boundedSummaryOff = request.purpose === "compaction" && compat.compactionThinkingOff && requested === null && mode === void 0;
|
|
2120
2128
|
const budget = result.max_completion_tokens ?? result.max_tokens;
|
|
2121
2129
|
if (mode === "enabled") {
|
|
2122
2130
|
if (!compat.supportsThinking) throw new ProtocolError("model_thinking_mode_unsupported");
|
|
2123
2131
|
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" };
|
|
2132
|
+
} 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
2133
|
if (!compat.supportsThinking) delete result.thinking;
|
|
2126
2134
|
if (!compat.supportsEffort) delete result.reasoning_effort;
|
|
2127
2135
|
if (compat.modern && ["moonshot", "kspmas-gateway"].includes(compat.rule) && result.tools) {
|
|
@@ -2159,6 +2167,8 @@ function explicitLiteralTypes(schema) {
|
|
|
2159
2167
|
}
|
|
2160
2168
|
|
|
2161
2169
|
// packages/agentkit-harness-node/src/native/model-provider-error.mjs
|
|
2170
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
2171
|
+
import { canonical as canonical8, MODEL_PROVIDER_ERROR_CODES, MODEL_PROVIDER_ERROR_TYPES } from "@kingsoftcloud/agentkit-harness-core";
|
|
2162
2172
|
var RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
2163
2173
|
"rate_limit_error",
|
|
2164
2174
|
"rate_limit_exceeded",
|
|
@@ -2187,6 +2197,23 @@ var TERMINAL_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
|
2187
2197
|
"MODEL_PROVIDER_QUOTA_EXHAUSTED"
|
|
2188
2198
|
]);
|
|
2189
2199
|
function classifyOpenAIProviderError(error) {
|
|
2200
|
+
const decision = classifyError(error);
|
|
2201
|
+
let fingerprint;
|
|
2202
|
+
try {
|
|
2203
|
+
fingerprint = `sha256:${createHash6("sha256").update(canonical8(error)).digest("hex")}`;
|
|
2204
|
+
} catch {
|
|
2205
|
+
return decision;
|
|
2206
|
+
}
|
|
2207
|
+
const object2 = error && typeof error === "object" && !Array.isArray(error) ? error : {};
|
|
2208
|
+
return { ...decision, diagnostic: {
|
|
2209
|
+
category: decision.failureKind,
|
|
2210
|
+
fingerprint,
|
|
2211
|
+
...MODEL_PROVIDER_ERROR_CODES.includes(object2.code) ? { code: object2.code } : {},
|
|
2212
|
+
...MODEL_PROVIDER_ERROR_TYPES.includes(object2.type) ? { type: object2.type } : {},
|
|
2213
|
+
...Number.isInteger(object2.code) && object2.code >= 400 && object2.code <= 599 ? { status: object2.code } : {}
|
|
2214
|
+
} };
|
|
2215
|
+
}
|
|
2216
|
+
function classifyError(error) {
|
|
2190
2217
|
const invalid = { kind: "provider_terminal_error", failureKind: "invalid_response" };
|
|
2191
2218
|
if (!error || typeof error !== "object" || Array.isArray(error)) return invalid;
|
|
2192
2219
|
if (error.type != null && typeof error.type !== "string") return invalid;
|
|
@@ -3049,7 +3076,7 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
|
|
|
3049
3076
|
if (profile.providerReplayProjectionPolicy === "anthropic-client-compaction/v1") {
|
|
3050
3077
|
const originals = message.providerReplay.anthropicContent.filter((block) => block?.type === "tool_use");
|
|
3051
3078
|
for (const [index, block] of originals.entries()) wireIds.set(message.toolCalls[index].callId, block.id);
|
|
3052
|
-
const inverse = new Map([...wireIds].map(([
|
|
3079
|
+
const inverse = new Map([...wireIds].map(([canonical10, original]) => [canonical10, original]));
|
|
3053
3080
|
blocks = replayContent.map((block) => block?.type === "tool_use" ? { ...block, id: inverse.get(block.id) ?? block.id } : block);
|
|
3054
3081
|
} else blocks = replayContent;
|
|
3055
3082
|
} else {
|
|
@@ -3870,9 +3897,9 @@ function projectResponsesOutput(payload, { status }) {
|
|
|
3870
3897
|
reasoning.push(partsText(item.content, /* @__PURE__ */ new Set(["reasoning_text", "text"])));
|
|
3871
3898
|
}
|
|
3872
3899
|
}
|
|
3873
|
-
const
|
|
3900
|
+
const canonical10 = messages.join("");
|
|
3874
3901
|
const convenience = optionalText(payload.output_text);
|
|
3875
|
-
if ("output" in payload && payload.output_text != null &&
|
|
3902
|
+
if ("output" in payload && payload.output_text != null && canonical10 !== convenience) {
|
|
3876
3903
|
throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
3877
3904
|
}
|
|
3878
3905
|
let finish;
|
|
@@ -3892,7 +3919,7 @@ function projectResponsesOutput(payload, { status }) {
|
|
|
3892
3919
|
finish = "content_filter";
|
|
3893
3920
|
calls.length = 0;
|
|
3894
3921
|
}
|
|
3895
|
-
return { finish, content:
|
|
3922
|
+
return { finish, content: canonical10 || convenience, reasoning: reasoning.join(""), calls, refused };
|
|
3896
3923
|
}
|
|
3897
3924
|
function responseMessageContent(value) {
|
|
3898
3925
|
if (!Array.isArray(value)) throw new ProtocolError("invalid model frame", "envelope_invalid");
|
|
@@ -4829,14 +4856,15 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4829
4856
|
const state = binding.protocol === "anthropic-messages" ? createAnthropicStreamState(profile) : binding.protocol === "openai-responses" ? createResponsesStreamState(profile) : createOpenAIStreamTurn(profile, binding);
|
|
4830
4857
|
const abort = (reason) => internal.abort(reason);
|
|
4831
4858
|
let frameIndex = -1;
|
|
4832
|
-
const failed = (result2, code) => withFailure(
|
|
4859
|
+
const failed = (result2, code, fields2 = {}) => withFailure(
|
|
4833
4860
|
result2,
|
|
4834
4861
|
binding,
|
|
4835
4862
|
"stream",
|
|
4836
4863
|
code,
|
|
4837
4864
|
{
|
|
4838
4865
|
...frameIndex < 0 ? {} : { frameIndex },
|
|
4839
|
-
...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {}
|
|
4866
|
+
...code === "usage_conflict" && state.usageConflict ? { usageConflict: state.usageConflict } : {},
|
|
4867
|
+
...fields2
|
|
4840
4868
|
}
|
|
4841
4869
|
);
|
|
4842
4870
|
try {
|
|
@@ -4858,7 +4886,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4858
4886
|
}
|
|
4859
4887
|
if (error instanceof ProtocolError) {
|
|
4860
4888
|
if (error.streamError) {
|
|
4861
|
-
return failed(
|
|
4889
|
+
return failed(
|
|
4890
|
+
state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }),
|
|
4891
|
+
"provider_error",
|
|
4892
|
+
error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
|
|
4893
|
+
);
|
|
4862
4894
|
}
|
|
4863
4895
|
return failed(state.finalize({ errorKind: "provider_terminal_error", failureKind: "invalid_response" }), protocolCode(error));
|
|
4864
4896
|
}
|
|
@@ -4868,7 +4900,11 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
4868
4900
|
return failed(state.finalize({ errorKind: "provider_retryable_error", failureKind: sanitizeFailureKind(error, "network_error") }), "transport_error");
|
|
4869
4901
|
}
|
|
4870
4902
|
const result = state.finalize();
|
|
4871
|
-
return failed(
|
|
4903
|
+
return failed(
|
|
4904
|
+
result,
|
|
4905
|
+
state.streamError ? "provider_error" : result.kind === "malformed_tool_call" ? "tool_payload_invalid" : result.failureKind === "incomplete_response" ? "stream_incomplete" : "protocol_invalid",
|
|
4906
|
+
state.streamError?.diagnostic ? { providerError: state.streamError.diagnostic } : {}
|
|
4907
|
+
);
|
|
4872
4908
|
}
|
|
4873
4909
|
async function bufferedResponse(response, request, binding, maxBytes, emit, observation) {
|
|
4874
4910
|
const bodyText = await readBoundedText(response, maxBytes, observation.bytes);
|
|
@@ -4887,7 +4923,13 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
|
|
|
4887
4923
|
} catch (error) {
|
|
4888
4924
|
if (error instanceof ProtocolError && error.streamError) {
|
|
4889
4925
|
const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
|
|
4890
|
-
return withFailure(
|
|
4926
|
+
return withFailure(
|
|
4927
|
+
result,
|
|
4928
|
+
binding,
|
|
4929
|
+
"buffered",
|
|
4930
|
+
"provider_error",
|
|
4931
|
+
error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {}
|
|
4932
|
+
);
|
|
4891
4933
|
}
|
|
4892
4934
|
return withFailure(terminalResult("invalid_response"), binding, "buffered", protocolCode(error));
|
|
4893
4935
|
}
|
|
@@ -4933,7 +4975,7 @@ function protocolCode(error) {
|
|
|
4933
4975
|
function withFailure(result, binding, phase, code, fields2 = {}) {
|
|
4934
4976
|
if (!["provider_terminal_error", "provider_retryable_error", "policy_abort", "malformed_tool_call"].includes(result.kind)) return result;
|
|
4935
4977
|
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 } };
|
|
4978
|
+
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
4979
|
}
|
|
4938
4980
|
function retryableResult(failureKind, retryAfterMs = null) {
|
|
4939
4981
|
const result = { kind: "provider_retryable_error", text: "", toolCalls: [], usage: emptyUsage(), usageReported: false, failureKind };
|
|
@@ -4994,7 +5036,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
|
|
|
4994
5036
|
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
4995
5037
|
import { mkdirSync as mkdirSync2 } from "node:fs";
|
|
4996
5038
|
import { dirname as dirname2 } from "node:path";
|
|
4997
|
-
import { createHash as
|
|
5039
|
+
import { createHash as createHash7 } from "node:crypto";
|
|
4998
5040
|
function stable(value) {
|
|
4999
5041
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
5000
5042
|
if (Array.isArray(value)) return "[" + value.map(stable).join(",") + "]";
|
|
@@ -5002,7 +5044,7 @@ function stable(value) {
|
|
|
5002
5044
|
return "{" + keys.map((k) => JSON.stringify(k) + ":" + stable(value[k])).join(",") + "}";
|
|
5003
5045
|
}
|
|
5004
5046
|
function digestRequest(method, params) {
|
|
5005
|
-
return
|
|
5047
|
+
return createHash7("sha256").update(stable({ method, params: params ?? null })).digest("hex");
|
|
5006
5048
|
}
|
|
5007
5049
|
var RpcRequestLedger = class {
|
|
5008
5050
|
constructor(filename, { now = Date.now } = {}) {
|
|
@@ -5276,8 +5318,8 @@ var ERR = {
|
|
|
5276
5318
|
var success = (id, result) => ({ jsonrpc: "2.0", id, result });
|
|
5277
5319
|
var errorResponse = (id, e, data) => ({ jsonrpc: "2.0", id, error: publicFailureContent({ code: e.code, message: e.message, ...data ? { data } : {} }) });
|
|
5278
5320
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
5279
|
-
var digest = (value) =>
|
|
5280
|
-
var runIdFor = (requestId) => "rpc:" +
|
|
5321
|
+
var digest = (value) => createHash8("sha256").update(canonical9(value)).digest("hex");
|
|
5322
|
+
var runIdFor = (requestId) => "rpc:" + createHash8("sha256").update(requestId).digest("hex");
|
|
5281
5323
|
function nativeErrorToRpc(e) {
|
|
5282
5324
|
if (isNativeError(e)) {
|
|
5283
5325
|
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.
|
|
3
|
+
"version": "0.0.15",
|
|
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.
|
|
143
|
+
"@kingsoftcloud/agentkit-harness-core": "0.0.15",
|
|
142
144
|
"@astral-sh/ruff-wasm-nodejs": "0.16.8",
|
|
143
145
|
"parse5": "7.3.0",
|
|
144
146
|
"playwright-core": "1.58.2",
|
|
@@ -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
|
|
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,
|
|
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)
|
|
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 = [];
|
package/src/native/children.mjs
CHANGED
|
@@ -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 ||
|
|
127
|
-
invariant(outputRestartPolicy === undefined ||
|
|
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,12 @@ 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
|
+
let idleApproval = null;
|
|
284
|
+
// The SDK disposes the owner on graceful Host shutdown. A persisted
|
|
285
|
+
// approval wait has no live effect to cancel and may be rebound later.
|
|
286
|
+
const detachingApproval = () => durableOwnership && idleApproval && cancelReason(signal.reason)?.kind === 'disposed';
|
|
283
287
|
const persistCancel = () => {
|
|
288
|
+
if (detachingApproval()) return;
|
|
284
289
|
const commandId = `${runId}:dsh-turn-cancel`;
|
|
285
290
|
const original = store.load(scope, runId).commands.find(row => row.command.commandId === commandId)?.command;
|
|
286
291
|
return kernel.submit(scope, runId, original ?? { commandId, kind: 'cancel',
|
|
@@ -307,8 +312,22 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
|
|
|
307
312
|
signal.addEventListener('abort', cancelListener, { once: true });
|
|
308
313
|
}
|
|
309
314
|
let wakeIdle = () => {};
|
|
310
|
-
releaseControls = onActive?.(payload, { kernel, scope: structuredClone(scope), sessionId, runId, wake: () => wakeIdle()
|
|
315
|
+
releaseControls = onActive?.(payload, { kernel, scope: structuredClone(scope), sessionId, runId, wake: () => wakeIdle(),
|
|
316
|
+
...(binding.sessionApproval ? { sessionApproval: binding.sessionApproval } : {}) });
|
|
311
317
|
invariant(releaseControls === undefined || typeof releaseControls === 'function', 'native_dsh_controls_cleanup_invalid');
|
|
318
|
+
if (operatorResume) {
|
|
319
|
+
signal.throwIfAborted();
|
|
320
|
+
const current = store.load(scope, runId).snapshot;
|
|
321
|
+
if (current.phase === 'paused') {
|
|
322
|
+
// Rebinding an SDK turn is not a Native state transition. Only this
|
|
323
|
+
// explicit Host entry submits the durable command; ordinary delivery
|
|
324
|
+
// and crash reattachment keep user/policy pauses intact. Core owns
|
|
325
|
+
// cancellation precedence and any permitted budget recovery.
|
|
326
|
+
const commandId = `native-dsh-resume-${hash({ scope, runId, revision: current.revision, eventSeq: current.eventSeq })}`;
|
|
327
|
+
invariant(kernel.submit(scope, runId, { commandId, kind: 'resume', payload: {} }).status !== 'rejected',
|
|
328
|
+
'native_dsh_resume_rejected');
|
|
329
|
+
}
|
|
330
|
+
}
|
|
312
331
|
let snapshot;
|
|
313
332
|
try {
|
|
314
333
|
snapshot = await kernel.runUntilIdle(scope, runId, { signal });
|
|
@@ -317,18 +336,23 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
|
|
|
317
336
|
if (!onIdle) throw failure('NATIVE_TURN_SUSPENDED', snapshot);
|
|
318
337
|
const idle = new AbortController(), idlePayload = { ...payload, signal: AbortSignal.any([signal, idle.signal]) };
|
|
319
338
|
let command, woken = false;
|
|
339
|
+
idleApproval = snapshot.phase === 'awaiting_interaction' ? snapshot : null;
|
|
320
340
|
wakeIdle = () => { woken = true; idle.abort(new NativeError('native_idle_woken')); };
|
|
321
341
|
try {
|
|
322
342
|
if (store.load(scope, runId).commands.some(row => !row.consumed)) wakeIdle();
|
|
323
343
|
command = await resolveWhileLive(() => onIdle(idlePayload, structuredClone(snapshot), {
|
|
324
344
|
waitForToolReceipt: binding.ports.tools.waitForReceipt,
|
|
345
|
+
...(binding.sessionApproval ? { sessionApproval: binding.sessionApproval } : {}),
|
|
325
346
|
}), idlePayload);
|
|
326
347
|
} catch (error) {
|
|
327
348
|
if (!woken || signal.aborted) throw error;
|
|
349
|
+
idleApproval = null;
|
|
328
350
|
snapshot = await kernel.runUntilIdle(scope, runId, { signal });
|
|
329
351
|
continue;
|
|
330
352
|
} finally { wakeIdle = () => {}; idle.abort(); }
|
|
331
353
|
if (!command) throw failure('NATIVE_TURN_SUSPENDED', snapshot);
|
|
354
|
+
signal.throwIfAborted();
|
|
355
|
+
idleApproval = null;
|
|
332
356
|
const revision = snapshot.revision;
|
|
333
357
|
const receipt = kernel.submit(scope, runId, command);
|
|
334
358
|
invariant(receipt.status !== 'rejected', 'native_dsh_command_rejected');
|
|
@@ -337,6 +361,7 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
|
|
|
337
361
|
}
|
|
338
362
|
signal.throwIfAborted();
|
|
339
363
|
} catch (error) {
|
|
364
|
+
if (detachingApproval()) throw failure('NATIVE_TURN_SUSPENDED', idleApproval);
|
|
340
365
|
if (signal.aborted && !terminal(store.load(scope, runId).snapshot.phase)) {
|
|
341
366
|
// A turn can be canceled while no kernel worker is active (approval
|
|
342
367
|
// or host checkpoint). Persist first, then drain without allowing a
|
|
@@ -451,7 +476,7 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
|
|
|
451
476
|
const admission = readNativeDshOwnership(resumed.ownership, { sessionId: agent.session.id, turn: resumed.turn });
|
|
452
477
|
return run({ ...request, ...resumed, agent,
|
|
453
478
|
signal: request.signal ? AbortSignal.any([request.signal, resumed.signal]) : resumed.signal,
|
|
454
|
-
input: { kind: 'enter', messages: structuredClone(admission.messages) } }, admission);
|
|
479
|
+
input: { kind: 'enter', messages: structuredClone(admission.messages) } }, admission, null, true);
|
|
455
480
|
});
|
|
456
481
|
};
|
|
457
482
|
/** Drive only the persisted notification identified by an already claimed owner. */
|
|
@@ -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/
|
|
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
|
|
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
|
|
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:
|
|
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
|
|
180
|
-
return
|
|
181
|
-
|
|
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 ===
|
|
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) {
|
|
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 (
|
|
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' });
|