@kingsoftcloud/agentkit-harness-node 0.0.13 → 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 +225 -102
- package/dist/rpc-entry.mjs +231 -108
- package/package.json +5 -2
- package/src/native/activity-status.mjs +32 -1
- 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 +30 -8
- package/src/native/conversation-presentation.mjs +31 -0
- package/src/native/dsh-turn-runtime.mjs +28 -3
- package/src/native/local-command-policy-worker.mjs +2 -1
- package/src/native/local-command-tools.mjs +6 -1
- package/src/native/model-anthropic.mjs +6 -1
- package/src/native/model-openai-chat.mjs +17 -2
- package/src/native/model-port.mjs +13 -6
- package/src/native/model-provider-compat.mjs +16 -7
- package/src/native/model-provider-error.mjs +62 -0
- package/src/native/model-responses.mjs +15 -37
- package/src/native/python-grammar.mjs +14 -0
- package/src/native/python-syntax-worker.mjs +4 -3
- package/src/native/run-observation.mjs +2 -2
- package/src/native/session-tool-approval.mjs +91 -0
- package/src/native/sqlite-store.mjs +24 -0
- package/src/native/workspace-checkpoints.mjs +20 -5
- package/src/native/workspace-instructions.mjs +18 -3
- package/src/native/workspace-tools.mjs +2 -1
|
@@ -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;
|
|
@@ -203,9 +203,10 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
203
203
|
return failed(state.finalize({ errorKind: 'provider_terminal_error', failureKind: 'invalid_response' }), protocolCode(error));
|
|
204
204
|
}
|
|
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) {
|
|
@@ -237,6 +239,11 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
|
|
|
237
239
|
}
|
|
238
240
|
return withFailure(parseOpenAIBuffered(bodyText, request, { captureReplay, binding, onThinking }), binding, 'buffered', 'protocol_invalid');
|
|
239
241
|
} catch (error) {
|
|
242
|
+
if (error instanceof ProtocolError && error.streamError) {
|
|
243
|
+
const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
|
|
244
|
+
return withFailure(result, binding, 'buffered', 'provider_error',
|
|
245
|
+
error.streamError.diagnostic ? { providerError: error.streamError.diagnostic } : {});
|
|
246
|
+
}
|
|
240
247
|
return withFailure(terminalResult('invalid_response'), binding, 'buffered', protocolCode(error));
|
|
241
248
|
}
|
|
242
249
|
}
|
|
@@ -291,7 +298,7 @@ function protocolCode(error) {
|
|
|
291
298
|
function withFailure(result, binding, phase, code, fields = {}) {
|
|
292
299
|
if (!['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)) return result;
|
|
293
300
|
const protocol = ['openai-chat', 'openai-responses', 'anthropic-messages'].includes(binding?.protocol) ? binding.protocol : 'unknown';
|
|
294
|
-
return { ...result, failureDiagnostic: { contract: fields.usageConflict
|
|
301
|
+
return { ...result, failureDiagnostic: { contract: fields.providerError ? 'model-failure-diagnostic/v3' : fields.usageConflict
|
|
295
302
|
? 'model-failure-diagnostic/v2' : 'model-failure-diagnostic/v1', protocol, phase, code, ...fields } };
|
|
296
303
|
}
|
|
297
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;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Shared OpenAI-compatible provider error classification for JSON and SSE.
|
|
2
|
+
// HTTP transport status is handled separately. Never infer retries from raw
|
|
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';
|
|
6
|
+
const RETRYABLE_ERROR_CODES = new Set([
|
|
7
|
+
'rate_limit_error', 'rate_limit_exceeded', 'overloaded_error', 'server_error',
|
|
8
|
+
'api_error', 'service_unavailable_error', 'server_is_overloaded', 'timeout_error',
|
|
9
|
+
'MODEL_PROVIDER_RATE_LIMIT', 'MODEL_PROVIDER_UNAVAILABLE',
|
|
10
|
+
]);
|
|
11
|
+
const TERMINAL_ERROR_CODES = new Set([
|
|
12
|
+
'invalid_request_error', 'invalid_api_key', 'authentication_error',
|
|
13
|
+
'permission_error', 'not_found_error', 'request_too_large', 'billing_error',
|
|
14
|
+
'insufficient_quota', 'MODEL_PROVIDER_AUTHENTICATION', 'MODEL_PROVIDER_PERMISSION',
|
|
15
|
+
'MODEL_PROVIDER_INVALID_REQUEST', 'MODEL_PROVIDER_NOT_FOUND',
|
|
16
|
+
'MODEL_PROVIDER_QUOTA_EXHAUSTED',
|
|
17
|
+
]);
|
|
18
|
+
|
|
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) {
|
|
36
|
+
const invalid = { kind: 'provider_terminal_error', failureKind: 'invalid_response' };
|
|
37
|
+
if (!error || typeof error !== 'object' || Array.isArray(error)) return invalid;
|
|
38
|
+
if (error.type != null && typeof error.type !== 'string') return invalid;
|
|
39
|
+
// vLLM ErrorInfo encodes the HTTP rejection status in error.code even
|
|
40
|
+
// when the response headers have already committed HTTP 200 for SSE.
|
|
41
|
+
// https://docs.vllm.ai/en/v0.16.0/api/vllm/entrypoints/openai/engine/serving/
|
|
42
|
+
const status = typeof error.code === 'number' ? error.code : null;
|
|
43
|
+
if (status != null && (!Number.isInteger(status) || status < 400 || status > 599)) return invalid;
|
|
44
|
+
const codes = [status == null ? error.code : null, error.type].filter(value => value != null);
|
|
45
|
+
if (codes.some(value => typeof value !== 'string')) return invalid;
|
|
46
|
+
// A permanent quota/auth/request failure must never be retried just because
|
|
47
|
+
// a generic outer type also says rate_limit_error or server_error.
|
|
48
|
+
if (codes.some(value => TERMINAL_ERROR_CODES.has(value))) {
|
|
49
|
+
return { kind: 'provider_terminal_error', failureKind: 'client_error' };
|
|
50
|
+
}
|
|
51
|
+
if (status != null) {
|
|
52
|
+
if (status === 408) return { kind: 'provider_retryable_error', failureKind: 'request_timeout' };
|
|
53
|
+
if (status === 429) return { kind: 'provider_retryable_error', failureKind: 'rate_limit' };
|
|
54
|
+
return { kind: status >= 500 ? 'provider_retryable_error' : 'provider_terminal_error',
|
|
55
|
+
failureKind: status >= 500 ? 'server_error' : 'client_error' };
|
|
56
|
+
}
|
|
57
|
+
const code = codes.find(value => RETRYABLE_ERROR_CODES.has(value));
|
|
58
|
+
if (code) return { kind: 'provider_retryable_error',
|
|
59
|
+
failureKind: ['rate_limit_error', 'rate_limit_exceeded', 'MODEL_PROVIDER_RATE_LIMIT'].includes(code) ? 'rate_limit'
|
|
60
|
+
: code === 'timeout_error' ? 'request_timeout' : 'server_error' };
|
|
61
|
+
return invalid;
|
|
62
|
+
}
|
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
normalizeResponse, sealUsage, ProtocolError, resolveUrl, boundOutputTokens,
|
|
28
28
|
emptyUsage,
|
|
29
29
|
} from './model-normalize.mjs';
|
|
30
|
+
import { classifyOpenAIProviderError } from './model-provider-error.mjs';
|
|
30
31
|
import { sealModelReplay } from './model-replay.mjs';
|
|
31
32
|
import { validateMediaBlock, MediaError } from './model-media.mjs';
|
|
32
33
|
// parseModelJson is the kernel's strict finite JSON parser (rejects duplicate
|
|
@@ -59,24 +60,6 @@ const HOSTED_ITEM_TYPES = new Set([
|
|
|
59
60
|
'mcp_call', 'local_shell_call',
|
|
60
61
|
]);
|
|
61
62
|
|
|
62
|
-
// In-stream error code/type → retryable/terminal classification. A 2xx stream
|
|
63
|
-
// that emits an error/response.failed event is a provider rejection, never a
|
|
64
|
-
// final; unknown codes stay terminal so a foreign payload cannot become a
|
|
65
|
-
// silent retry or final. Mirrors the Anthropic stream classifier and the
|
|
66
|
-
// Python provider_error code map.
|
|
67
|
-
const RETRYABLE_ERROR_CODES = new Set([
|
|
68
|
-
'rate_limit_error', 'rate_limit_exceeded', 'overloaded_error', 'server_error',
|
|
69
|
-
'api_error', 'service_unavailable_error', 'server_is_overloaded', 'timeout_error',
|
|
70
|
-
'MODEL_PROVIDER_RATE_LIMIT', 'MODEL_PROVIDER_UNAVAILABLE',
|
|
71
|
-
]);
|
|
72
|
-
const TERMINAL_ERROR_CODES = new Set([
|
|
73
|
-
'invalid_request_error', 'invalid_api_key', 'authentication_error',
|
|
74
|
-
'permission_error', 'not_found_error', 'request_too_large', 'billing_error',
|
|
75
|
-
'insufficient_quota', 'MODEL_PROVIDER_AUTHENTICATION', 'MODEL_PROVIDER_PERMISSION',
|
|
76
|
-
'MODEL_PROVIDER_INVALID_REQUEST', 'MODEL_PROVIDER_NOT_FOUND',
|
|
77
|
-
'MODEL_PROVIDER_QUOTA_EXHAUSTED',
|
|
78
|
-
]);
|
|
79
|
-
|
|
80
63
|
function securityHeaders() {
|
|
81
64
|
return new Set(['authorization', 'x-api-key', 'anthropic-version', 'content-type', 'accept']);
|
|
82
65
|
}
|
|
@@ -449,18 +432,21 @@ function partsText(value, types) {
|
|
|
449
432
|
|
|
450
433
|
// Parse a buffered 2xx Responses body into a sealed result. Used when a 2xx
|
|
451
434
|
// response is not SSE (rare for stream:true); also the basis for envelope
|
|
452
|
-
// validation.
|
|
453
|
-
//
|
|
435
|
+
// validation. Known provider error envelopes retain their classification;
|
|
436
|
+
// contradictory success/error envelopes are terminal protocol conflicts.
|
|
454
437
|
export function parseResponsesBuffered(bodyText, request, { captureReplay = false, onThinking } = {}) {
|
|
455
438
|
let payload;
|
|
456
439
|
try { payload = strictParseJson(bodyText); } catch { throw new ProtocolError('invalid response json', 'json_invalid'); }
|
|
457
440
|
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
458
441
|
throw new ProtocolError('invalid response envelope', 'envelope_invalid');
|
|
459
442
|
}
|
|
443
|
+
if (payload.error != null || payload.status === 'failed') {
|
|
444
|
+
if (payload.status != null && payload.status !== 'failed') throw new ProtocolError('conflicting response envelope', 'envelope_invalid');
|
|
445
|
+
throw Object.assign(new ProtocolError('provider rejected generation', 'provider_error'), {
|
|
446
|
+
streamError: classifyOpenAIProviderError(payload.error),
|
|
447
|
+
});
|
|
448
|
+
}
|
|
460
449
|
const status = identityOf(payload.status);
|
|
461
|
-
// A 2xx body that carries an error alongside a purported successful answer,
|
|
462
|
-
// or an explicit failed status, is a protocol conflict, never a final.
|
|
463
|
-
if (payload.error != null) throw new ProtocolError('invalid response envelope', 'envelope_invalid');
|
|
464
450
|
if (status === 'failed') throw new ProtocolError('invalid response envelope', 'envelope_invalid');
|
|
465
451
|
validateBufferedIdentity(payload);
|
|
466
452
|
const reportedUsage = parseResponsesUsage(payload.usage);
|
|
@@ -1036,20 +1022,7 @@ export function createResponsesStreamState(profile) {
|
|
|
1036
1022
|
}
|
|
1037
1023
|
const usage = parseResponsesUsage(failedBody.usage);
|
|
1038
1024
|
if (usage != null) this.usage = usage;
|
|
1039
|
-
|
|
1040
|
-
const code = String(errorObj.code || errorObj.type || '');
|
|
1041
|
-
let kind; let failureKind;
|
|
1042
|
-
if (RETRYABLE_ERROR_CODES.has(code)) {
|
|
1043
|
-
kind = 'provider_retryable_error';
|
|
1044
|
-
failureKind = code === 'rate_limit_error' || code === 'rate_limit_exceeded' ? 'rate_limit' : 'server_error';
|
|
1045
|
-
} else if (TERMINAL_ERROR_CODES.has(code)) {
|
|
1046
|
-
kind = 'provider_terminal_error';
|
|
1047
|
-
failureKind = 'client_error';
|
|
1048
|
-
} else {
|
|
1049
|
-
kind = 'provider_terminal_error';
|
|
1050
|
-
failureKind = 'invalid_response';
|
|
1051
|
-
}
|
|
1052
|
-
this.streamError = { kind, failureKind };
|
|
1025
|
+
this.streamError = classifyOpenAIProviderError(failedBody.error);
|
|
1053
1026
|
},
|
|
1054
1027
|
|
|
1055
1028
|
handleTerminal(event, { text: drainText, reasoning: drainReasoning }, emit) {
|
|
@@ -1142,6 +1115,11 @@ export function createResponsesStreamState(profile) {
|
|
|
1142
1115
|
// An in-stream error or a transport error during the attempt seals the
|
|
1143
1116
|
// observed text with no tools; usage is preserved when reported.
|
|
1144
1117
|
if (this.streamError) {
|
|
1118
|
+
// A provider refusal is an observed stop decision, not permission to
|
|
1119
|
+
// reopen generation because a later stream error is transient.
|
|
1120
|
+
if (this.streamError.kind === 'provider_retryable_error' && (this.refused || this.finish === 'content_filter')) {
|
|
1121
|
+
return { kind: 'policy_abort', text: this.text, toolCalls: [], usage, usageReported };
|
|
1122
|
+
}
|
|
1145
1123
|
return {
|
|
1146
1124
|
kind: this.streamError.kind, text: this.text, toolCalls: [], usage, usageReported,
|
|
1147
1125
|
...(this.streamError.failureKind ? { failureKind: this.streamError.failureKind } : {}),
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Ruff's public parse() recovers from invalid syntax and check() also applies
|
|
2
|
+
* compilation checks (e.g. duplicate parameters), so neither is an ast.parse
|
|
3
|
+
* grammar boundary. format() first uses ParsedModule::from_source, the strict
|
|
4
|
+
* grammar parser. Discard its output: validation must never rewrite the file.
|
|
5
|
+
*
|
|
6
|
+
* Do not use comments() for this boundary. Its debug renderer in pinned Ruff
|
|
7
|
+
* 0.16.8 truncates node source by byte offsets and panics on Unicode boundaries.
|
|
8
|
+
* Both workspace syntax validation and command-risk inspection use this same
|
|
9
|
+
* boundary, before their own version/token/AST checks.
|
|
10
|
+
* See astral-sh/ruff 0.16.8 crates/ruff_wasm/src/lib.rs.
|
|
11
|
+
*/
|
|
12
|
+
export function assertPythonGrammar(workspace, source) {
|
|
13
|
+
workspace.format(source);
|
|
14
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parentPort, workerData } from 'node:worker_threads';
|
|
2
2
|
import { Workspace, PositionEncoding } from '@astral-sh/ruff-wasm-nodejs';
|
|
3
3
|
import { NATIVE_PYTHON_SYNTAX } from './python-syntax.mjs';
|
|
4
|
+
import { assertPythonGrammar } from './python-grammar.mjs';
|
|
4
5
|
|
|
5
6
|
if (Workspace.version() !== NATIVE_PYTHON_SYNTAX.parserVersion) throw new Error('Python parser version mismatch');
|
|
6
7
|
const workspace = new Workspace({ 'target-version': NATIVE_PYTHON_SYNTAX.targetVersion,
|
|
@@ -16,9 +17,9 @@ try {
|
|
|
16
17
|
if (nul !== -1) issues = issueAt(nul, 'Source code cannot contain NUL bytes.');
|
|
17
18
|
// `check` also performs compile-time checks even with no lint rules selected:
|
|
18
19
|
// duplicate parameters, module nonlocal, unreachable match cases, etc.
|
|
19
|
-
// CPython ast.parse deliberately permits these.
|
|
20
|
-
//
|
|
21
|
-
try { if (!issues) workspace
|
|
20
|
+
// CPython ast.parse deliberately permits these. Use the shared strict grammar
|
|
21
|
+
// boundary without the comment debug renderer or later compilation checks.
|
|
22
|
+
try { if (!issues) assertPythonGrammar(workspace, workerData); }
|
|
22
23
|
catch (error) {
|
|
23
24
|
const match = /^(.*) at byte range (\d+)\.\.(\d+)$/s.exec(error.message);
|
|
24
25
|
if (!match) throw error;
|
|
@@ -9,7 +9,7 @@ import { canCloseNativeReadInterruption } from './read-interruption.mjs';
|
|
|
9
9
|
import { advanceNativeContextMarkerState, nativeContextMarkerFactsFromState } from './context-markers.mjs';
|
|
10
10
|
|
|
11
11
|
export const NATIVE_RUN_OBSERVATION = 'agentkit.native-run-observation/v1';
|
|
12
|
-
export const NATIVE_COMMIT_PROJECTION = 'agentkit.native-commit-projection/
|
|
12
|
+
export const NATIVE_COMMIT_PROJECTION = 'agentkit.native-commit-projection/v3';
|
|
13
13
|
|
|
14
14
|
function contextProjection(previous, record) {
|
|
15
15
|
let lastPlan = previous?.lastPlan ?? null, lastAdmission = previous?.lastAdmission ?? null;
|
|
@@ -24,7 +24,7 @@ function contextProjection(previous, record) {
|
|
|
24
24
|
function observationHeader(s) {
|
|
25
25
|
const header = Object.fromEntries(['scope', 'runId', 'sessionId', 'turnId', 'buildId', 'parentRunId', 'taskChainId',
|
|
26
26
|
'configDigest', 'phase', 'revision', 'eventSeq', 'usage', 'descendantUsage', 'outcome', 'reason', 'pendingIntent',
|
|
27
|
-
'toolReconciliation'].filter(key => s[key] !== undefined).map(key => [key, s[key]]));
|
|
27
|
+
'toolReconciliation', 'retryNotBefore'].filter(key => s[key] !== undefined).map(key => [key, s[key]]));
|
|
28
28
|
header.diagnostics = Object.fromEntries(['providerUsageIncomplete', 'descendantUsageIncomplete', 'lastModelFailure']
|
|
29
29
|
.filter(key => s.diagnostics[key] !== undefined).map(key => [key, s.diagnostics[key]]));
|
|
30
30
|
return header;
|
|
@@ -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
|
+
}
|
|
@@ -475,6 +475,30 @@ export class SqliteRunStore extends TransactionalRunStore {
|
|
|
475
475
|
} catch (error) { db.exec('ROLLBACK'); throw error; }
|
|
476
476
|
},
|
|
477
477
|
});
|
|
478
|
+
/** Read-only observability state and an append-only event suffix from one
|
|
479
|
+
* SQLite snapshot. Execution receipts, transcripts and configuration are
|
|
480
|
+
* deliberately excluded; this view cannot authorize execution. */
|
|
481
|
+
this.traceView = (scope, runId, after = 0) => {
|
|
482
|
+
open();
|
|
483
|
+
invariant(Number.isSafeInteger(after) && after >= 0, 'invalid_trace_cursor');
|
|
484
|
+
const key = runKey(scope, runId);
|
|
485
|
+
db.exec('BEGIN');
|
|
486
|
+
try {
|
|
487
|
+
const row = db.prepare(`SELECT json_object(
|
|
488
|
+
'scope',json_extract(data,'$.snapshot.scope'), 'runId',json_extract(data,'$.snapshot.runId'),
|
|
489
|
+
'sessionId',json_extract(data,'$.snapshot.sessionId'), 'phase',json_extract(data,'$.snapshot.phase'),
|
|
490
|
+
'revision',json_extract(data,'$.snapshot.revision'), 'eventSeq',json_extract(data,'$.snapshot.eventSeq'),
|
|
491
|
+
'usage',json_extract(data,'$.snapshot.usage'), 'outcome',json_extract(data,'$.snapshot.outcome')) AS snapshot
|
|
492
|
+
FROM native_runs WHERE key=?`).get(key);
|
|
493
|
+
invariant(row, 'run_not_found');
|
|
494
|
+
const snapshot = parseNativeJson(row.snapshot);
|
|
495
|
+
invariant(snapshot.runId === runId && canonical(snapshot.scope) === canonical(scope), 'native_trace_identity_mismatch');
|
|
496
|
+
const events = db.prepare('SELECT data FROM native_events WHERE run_key=? AND seq>? AND seq<=? ORDER BY seq')
|
|
497
|
+
.all(key, after, snapshot.eventSeq).map(row => parseNativeJson(row.data));
|
|
498
|
+
db.exec('COMMIT');
|
|
499
|
+
return { contract: 'agentkit.native-trace-view/v1', snapshot, events };
|
|
500
|
+
} catch (error) { db.exec('ROLLBACK'); throw error; }
|
|
501
|
+
};
|
|
478
502
|
/** A presentation-only read: current transcript, display events and exact
|
|
479
503
|
* unresolved closures. Historical raw tool bodies never enter this view. */
|
|
480
504
|
this.sessionDeliveryState = (scope, runId) => {
|
|
@@ -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) })) };
|
|
@@ -13,6 +13,13 @@ const hash = value => createHash('sha256').update(value).digest('hex');
|
|
|
13
13
|
const missing = error => ['ENOENT', 'ENOTDIR'].includes(error.code);
|
|
14
14
|
const sameFile = (a, b) => ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].every(key => a[key] === b[key]);
|
|
15
15
|
|
|
16
|
+
/** New admissions get bounded read recovery; cold restoration retains the exact source policy. */
|
|
17
|
+
export function nativeWorkspaceInstructionTimeoutRecovery(configuration) {
|
|
18
|
+
return configuration === undefined
|
|
19
|
+
? { contract: 'context-source-timeout/v1', maxRetries: 2, retryDelayMs: 100 }
|
|
20
|
+
: structuredClone(configuration.contextSources.find(source => source.sourceId === 'native.workspace-instructions')?.timeoutRecovery);
|
|
21
|
+
}
|
|
22
|
+
|
|
16
23
|
/** Stable bounded reads, using the physical file identity both before and after
|
|
17
24
|
* open. A concurrent replacement causes a retryable source failure, not stale
|
|
18
25
|
* guidance or a partially read instruction file. */
|
|
@@ -45,13 +52,21 @@ async function readFile(root, path, signal) {
|
|
|
45
52
|
|
|
46
53
|
/** Node-owned live source. Only discovery directories are durable; file bodies
|
|
47
54
|
* and deletion state never depend on a summary or a process-local cache. */
|
|
48
|
-
export function createNativeWorkspaceInstructions(binding) {
|
|
55
|
+
export function createNativeWorkspaceInstructions(binding, { timeoutRecovery } = {}) {
|
|
49
56
|
validateNativeWorkspaceContext(binding);
|
|
50
57
|
invariant(binding.instructionSource?.contract === CONTRACT, 'workspace_instruction_source_unbound');
|
|
58
|
+
invariant(timeoutRecovery === undefined || timeoutRecovery && !Array.isArray(timeoutRecovery)
|
|
59
|
+
&& Object.keys(timeoutRecovery).sort().join(',') === 'contract,maxRetries,retryDelayMs'
|
|
60
|
+
&& timeoutRecovery.contract === 'context-source-timeout/v1'
|
|
61
|
+
&& Number.isSafeInteger(timeoutRecovery.maxRetries) && timeoutRecovery.maxRetries >= 0 && timeoutRecovery.maxRetries <= 3
|
|
62
|
+
&& Number.isSafeInteger(timeoutRecovery.retryDelayMs) && timeoutRecovery.retryDelayMs >= 0 && timeoutRecovery.retryDelayMs <= 60000,
|
|
63
|
+
'invalid_context_source_timeout_recovery');
|
|
51
64
|
const root = binding.workspaceRoot, roots = structuredClone(binding.instructionSource.globalRoots);
|
|
52
65
|
const source = Object.freeze({ contract: 'agentkit.native-context-source/v1', sourceId: 'native.workspace-instructions',
|
|
53
|
-
bindingDigest: hash(canonical({ contract: CONTRACT, root, roots, candidates: CANDIDATES, MAX_FILE_BYTES, MAX_TOTAL_BYTES
|
|
54
|
-
|
|
66
|
+
bindingDigest: hash(canonical({ contract: CONTRACT, root, roots, candidates: CANDIDATES, MAX_FILE_BYTES, MAX_TOTAL_BYTES,
|
|
67
|
+
...(timeoutRecovery ? { timeoutRecovery } : {}) })),
|
|
68
|
+
instructionPolicy: 'current-files/v1', priority: 1000, required: true, timeoutMs: 5000, maxTokens: 32768, maxBytes: 131072,
|
|
69
|
+
...(timeoutRecovery ? { timeoutRecovery: structuredClone(timeoutRecovery) } : {}) });
|
|
55
70
|
const initialScopes = () => ({ contract: INSTRUCTION_SCOPES, sourceId: source.sourceId,
|
|
56
71
|
bindingDigest: source.bindingDigest, directories: [''] });
|
|
57
72
|
const scopesOf = state => state === undefined ? initialScopes() : validateInstructionScopes(state, { contextSources: [source] });
|
|
@@ -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' });
|