@kingsoftcloud/agentkit-harness-node 0.0.30 → 0.0.32

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.
@@ -12,6 +12,7 @@
12
12
  // the sealed providerReplay but never emitted in a public stream event's
13
13
  // metadata, and never concatenated to visible text.
14
14
 
15
+ import { modelToolView } from './model-tool-view.mjs';
15
16
  import {
16
17
  normalizeResponse, parseAnthropicUsageFragment, parseRetryAfterMs,
17
18
  ProtocolError, resolveUrl, boundOutputTokens,
@@ -159,10 +160,9 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
159
160
  const native = isNativeToolSearch(profile) && !['compaction', 'delivery_review'].includes(request.purpose);
160
161
  const systemParts = [];
161
162
  const items = [];
162
- const pending = new Set();
163
- // Pending call name per receipt callId, so native tool_reference metadata
163
+ // Track the canonical call by ID so native tool_reference metadata
164
164
  // pairs only with a ToolSearch call. The wire id still keys the receipt.
165
- const pendingNames = new Map();
165
+ const pending = new Map();
166
166
  const wireIds = new Map();
167
167
  const midSystem = profile.anthropicPolicy?.midSystem === true;
168
168
  for (const message of request.messages || []) {
@@ -172,16 +172,12 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
172
172
  if (role !== 'tool' && pending.size) throw new ProtocolError('incomplete assistant tool batch before next message');
173
173
  if (role === 'assistant' && message.toolCalls?.length) {
174
174
  validateAssistantToolIds(message.toolCalls);
175
- for (const call of message.toolCalls) {
176
- pending.add(call.callId);
177
- pendingNames.set(call.callId, modelWireToolCall(call).name);
178
- }
175
+ for (const call of message.toolCalls) pending.set(call.callId, call);
179
176
  }
180
- let pairedName;
177
+ let pairedCall;
181
178
  if (role === 'tool') {
179
+ pairedCall = pending.get(message.callId);
182
180
  if (!pending.delete(message.callId)) throw new ProtocolError('tool receipt does not match the pending assistant batch');
183
- pairedName = pendingNames.get(message.callId);
184
- pendingNames.delete(message.callId);
185
181
  }
186
182
  if (role === 'system' || role === 'developer') {
187
183
  if (midSystem && items.length) items.push({ role: 'system', content: message.content || '' });
@@ -195,12 +191,12 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
195
191
  // (no metadata) or empty names keep the ordinary text/media projection;
196
192
  // malformed or unpaired metadata fails preflight rather than widening
197
193
  // authority. Non-native policy ignores the metadata entirely.
198
- const references = native ? nativeToolReferenceContent(message, pairedName, request.tools) : undefined;
194
+ const references = native ? nativeToolReferenceContent(message, modelWireToolCall(pairedCall).name, request.tools) : undefined;
199
195
  const media = message.media ? message.media.map((b) => validateMediaBlock(b, maxInlineImageBytes)) : null;
200
196
  let content;
201
197
  if (references) content = [...references, ...(media?.length ? projectMediaAnthropic(media) : [])];
202
198
  else if (media && media.length) content = [{ type: 'text', text: message.content || '' }, ...projectMediaAnthropic(media)];
203
- else content = (message.content || '');
199
+ else content = modelToolView(message.content || '', pairedCall.name, request.tools);
204
200
  item = {
205
201
  role: 'user',
206
202
  content: [{
@@ -183,8 +183,7 @@ export function parseRetryAfterMs(headerValue) {
183
183
  const trimmed = String(headerValue).trim();
184
184
  if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
185
185
  const seconds = Number(trimmed);
186
- if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);
187
- return null;
186
+ return Math.min(Number.MAX_SAFE_INTEGER, Math.round(seconds * 1000));
188
187
  }
189
188
  const parsed = Date.parse(trimmed);
190
189
  if (Number.isNaN(parsed)) return null;
@@ -8,6 +8,7 @@
8
8
  //
9
9
  // Profiled inline reasoning is projected under the Run's frozen policy.
10
10
 
11
+ import { modelToolView } from './model-tool-view.mjs';
11
12
  import { ModelStreamLimitError } from './model-stream-budget.mjs';
12
13
  import {
13
14
  normalizeResponse, parseOpenAIUsage, sealUsage, ProtocolError, resolveUrl, boundOutputTokens,
@@ -128,7 +129,7 @@ export function buildOpenAIRequest(binding, request) {
128
129
  export function projectMessagesOpenAI(request, maxInlineImageBytes) {
129
130
  const profile = request.profile;
130
131
  const projected = [];
131
- const pending = new Set();
132
+ const pending = new Map();
132
133
  let images = [];
133
134
  for (const message of request.messages || []) {
134
135
  const role = message.role;
@@ -137,12 +138,14 @@ export function projectMessagesOpenAI(request, maxInlineImageBytes) {
137
138
  }
138
139
  if (role === 'assistant' && message.toolCalls && message.toolCalls.length) {
139
140
  validateAssistantToolIds(message.toolCalls);
140
- for (const call of message.toolCalls) pending.add(call.callId);
141
+ for (const call of message.toolCalls) pending.set(call.callId, call.name);
141
142
  }
143
+ let toolName;
142
144
  if (role === 'tool') {
143
145
  if (!pending.has(message.callId)) {
144
146
  throw new ProtocolError('tool receipt does not match the pending assistant batch');
145
147
  }
148
+ toolName = pending.get(message.callId);
146
149
  pending.delete(message.callId);
147
150
  }
148
151
  const media = message.media ? message.media.map((b) => validateMediaBlock(b, maxInlineImageBytes)) : null;
@@ -173,7 +176,7 @@ export function projectMessagesOpenAI(request, maxInlineImageBytes) {
173
176
  Object.assign(msg, openAIReplayFields(message, profile));
174
177
  projected.push(msg);
175
178
  } else if (role === 'tool') {
176
- projected.push({ role: 'tool', tool_call_id: message.callId, content: message.content || '' });
179
+ projected.push({ role: 'tool', tool_call_id: message.callId, content: modelToolView(message.content || '', toolName, request.tools) });
177
180
  } else {
178
181
  projected.push({ role, content: message.content || '' });
179
182
  }
@@ -7,6 +7,7 @@ import { ProtocolError } from './model-normalize.mjs';
7
7
  const strict = new Set(['openai', 'strict-openai', 'cerebras', 'groq']);
8
8
  const requiredAuto = new Set(['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-fable-5-1', 'claude-mythos-5-1']);
9
9
  const mandatory = new Set(['claude-fable-5-1', 'claude-opus-5-5', 'claude-sonnet-5-5']);
10
+ const gatewayMandatoryGlm = new Set(['glm-5.3', 'glm-5.3-flash', 'glm-5.3-flashx']);
10
11
  const ranks = { none: 0, minimal: 1, low: 2, medium: 3, high: 4, xhigh: 5, max: 5 };
11
12
  const normalized = model => String(model ?? '').trim().toLowerCase().replaceAll('_', '-');
12
13
  const object = value => value && typeof value === 'object' && !Array.isArray(value);
@@ -44,25 +45,32 @@ export function applyAnthropicThinking(payload, profile, binding) {
44
45
  return { ...payload, thinking };
45
46
  }
46
47
 
47
- export function admitProviderCompatibilityPolicy(override) {
48
- return { contract: 'provider-compat/v5', rule: admitInlineReasoningPolicy(override).rule };
48
+ export function admitProviderCompatibilityPolicy(override, binding) {
49
+ const { rule } = admitInlineReasoningPolicy(override);
50
+ const needsThinkingGuard = binding?.protocol === 'openai-chat'
51
+ && gatewayMandatoryGlm.has(String(binding.model ?? '').trim().toLowerCase())
52
+ && resolveCompatibilityRule(rule, binding) === 'kspmas-gateway';
53
+ return { contract: needsThinkingGuard ? 'provider-compat/v6' : 'provider-compat/v5', rule };
49
54
  }
50
55
 
51
56
  export function resolveProviderCompatibility(policy, binding) {
52
57
  if (!policy) return null;
53
- const version = ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4', 'provider-compat/v5'].indexOf(policy.contract) + 1;
58
+ const version = ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4', 'provider-compat/v5', 'provider-compat/v6'].indexOf(policy.contract) + 1;
54
59
  if (!version) throw new ProtocolError('invalid_provider_compatibility_policy');
55
60
  const rule = resolveCompatibilityRule(policy.rule, binding);
56
61
  const name = String(binding.model ?? '').trim().toLowerCase();
57
62
  const kimi = ['kspmas-gateway', 'moonshot'].includes(rule)
58
63
  && ['kimi-k2.7-code', 'kimi-k2.7-code-highspeed'].includes(name);
59
64
  const modern = version >= 3;
60
- const reasoningRequired = modern && rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
65
+ const gatewayFlash = rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
66
+ const gatewayMandatoryThinking = version >= 6 && rule === 'kspmas-gateway' && gatewayMandatoryGlm.has(name);
67
+ const reasoningRequired = gatewayMandatoryThinking || modern && gatewayFlash;
61
68
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === 'claude-haiku-5-5' ? ['low', 'medium', 'high'] : null;
62
69
  return { rule, supportsUsage: !strict.has(rule), supportsThinking: !strict.has(rule) && !kimi,
63
70
  supportsToolArgumentStreaming: version >= 2
64
71
  && ['zai', 'kspmas-gateway'].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
65
- reasoningRequired, modern, firstToolLowEffort: version >= 5 && reasoningRequired,
72
+ reasoningRequired, modern, firstToolLowEffort: version >= 5 && gatewayFlash,
73
+ minimumReasoningEffort: gatewayMandatoryThinking ? 'low' : null,
66
74
  // This route already uses the supported non-thinking mode for tool work.
67
75
  // A bounded summary has no tools: omitting the switch can instead select
68
76
  // the provider's default high reasoning and consume its whole output cap.
@@ -118,6 +126,7 @@ export function applyProviderChatCompatibility(payload, request, binding) {
118
126
  if (requested === null && request.purpose === 'compaction' && compat.rule === 'kspmas-gateway'
119
127
  && ['glm-5.2', 'deepseek-v4-flash'].includes(name)) effort = 'none';
120
128
  if (requested === null && request.purpose === 'compaction' && compat.reasoningRequired) effort = 'low';
129
+ if (compat.minimumReasoningEffort && (effort === 'none' || effort === 'minimal')) effort = compat.minimumReasoningEffort;
121
130
  effort = compat.supportsEffort ? clampReasoningEffort(model, effort) : null;
122
131
  if (effort !== null) result.reasoning_effort = effort;
123
132
  if (result.stream) result.stream_options = { ...(object(result.stream_options) ? result.stream_options : {}), include_usage: true };
@@ -23,6 +23,7 @@
23
23
  // no reasoning items in its input array. See delivery evidence for the
24
24
  // audited gap.
25
25
 
26
+ import { modelToolView } from './model-tool-view.mjs';
26
27
  import {
27
28
  normalizeResponse, sealUsage, ProtocolError, resolveUrl, boundOutputTokens,
28
29
  emptyUsage,
@@ -199,7 +200,7 @@ export function projectMessagesResponses(request, maxInlineImageBytes) {
199
200
  const profile = request.profile;
200
201
  const instructions = [];
201
202
  const items = [];
202
- const pending = new Set();
203
+ const pending = new Map();
203
204
  for (const message of request.messages || []) {
204
205
  const role = message.role;
205
206
  if (role !== 'tool' && pending.size) {
@@ -207,12 +208,14 @@ export function projectMessagesResponses(request, maxInlineImageBytes) {
207
208
  }
208
209
  if (role === 'assistant' && message.toolCalls && message.toolCalls.length) {
209
210
  validateAssistantToolIds(message.toolCalls);
210
- for (const call of message.toolCalls) pending.add(call.callId);
211
+ for (const call of message.toolCalls) pending.set(call.callId, call.name);
211
212
  }
213
+ let toolName;
212
214
  if (role === 'tool') {
213
215
  if (!pending.has(message.callId)) {
214
216
  throw new ProtocolError('tool receipt does not match the pending assistant batch');
215
217
  }
218
+ toolName = pending.get(message.callId);
216
219
  pending.delete(message.callId);
217
220
  }
218
221
  // The Responses wire carries no Anthropic content; a cross-wire replay is
@@ -228,7 +231,7 @@ export function projectMessagesResponses(request, maxInlineImageBytes) {
228
231
  const media = message.media ? message.media.map((b) => validateMediaBlock(b, maxInlineImageBytes)) : null;
229
232
  const output = media && media.length
230
233
  ? [{ type: 'input_text', text: message.content || '' }, ...projectMediaResponses(media)]
231
- : (message.content || '');
234
+ : modelToolView(message.content || '', toolName, request.tools);
232
235
  items.push({ type: 'function_call_output', call_id: message.callId, output });
233
236
  continue;
234
237
  }
@@ -0,0 +1,24 @@
1
+ /** Compact receipts from the admitted local command tool. All other payloads
2
+ * keep their original framing and fields, including workspace and MCP data. */
3
+ export function modelToolView(text, toolName, tools) {
4
+ if (typeof text !== 'string' || !text) return text;
5
+ if (toolName !== 'run_command' || !tools?.some(tool => tool.name === toolName
6
+ && tool.backgroundCommandPolicy === 'owned-command-launch/v1'
7
+ && tool.workspaceChangePolicy === 'observed-command/v1'
8
+ && tool.permissions?.includes('sandbox:execute'))) return text;
9
+ // Re-serializing must not change an integer's digits (e.g. 9007199254740993
10
+ // would become ...992). Such receipts pass through verbatim.
11
+ let receipt, inexact = false;
12
+ try {
13
+ receipt = JSON.parse(text, (key, value, context) => {
14
+ const source = context?.source;
15
+ if (typeof value === 'number' && typeof source === 'string' && /^-?\d+$/.test(source) && JSON.stringify(value) !== source) inexact = true;
16
+ return value;
17
+ });
18
+ } catch { return text; }
19
+ if (inexact || receipt?.backend !== 'sandbox/local_process') return text;
20
+ // Output stays cursor-readable after the process exits. Preserve the task ID,
21
+ // cursors and paging instruction along with status and truncation evidence.
22
+ const { command, controls, sandbox_id, ...view } = receipt;
23
+ return JSON.stringify(view);
24
+ }
@@ -65,7 +65,7 @@ export function createOwnedCommandOutputReader({ scope, store, readers = {}, isC
65
65
  }
66
66
 
67
67
  /** The backend is a fact in the canonical launch receipt, never a model hint. */
68
- export function ownedCommandReceipt({ scope, store, current, ref: input, includeCommand = false }) {
68
+ export function ownedCommandReceipt({ scope, store, current, ref: input, includeCommand = false, verifyStartFailure = false }) {
69
69
  const ref = backgroundCommandRef(input), source = store.load(scope, ref.sourceRunId);
70
70
  const receipt = source.receipts.find(item => item.operationKey === ref.operationKey);
71
71
  const launch = source.intents.find(item => item.operationKey === ref.operationKey);
@@ -73,13 +73,17 @@ export function ownedCommandReceipt({ scope, store, current, ref: input, include
73
73
  const result = Array.isArray(results) && results.length === 1 ? results[0] : null;
74
74
  const definition = Array.isArray(calls) && calls.length === 1
75
75
  ? source.configuration.tools.find(tool => tool.name === calls[0].name) : null;
76
+ const requiresStartFailureProof = verifyStartFailure && calls?.[0]?.name === 'run_command'
77
+ && result?.status === 'uncertain' && ['sandbox/local_process', 'sandbox/e2b'].includes(result.content?.backend)
78
+ && result.content.status === 'unknown' && result.content.task_id === ref.taskId;
76
79
  check(same(source.snapshot.scope, scope) && source.snapshot.sessionId === current.snapshot.sessionId
77
80
  && receipt?.status === 'committed' && launch?.kind === 'tool'
78
- && definition?.backgroundCommandPolicy === 'owned-command-launch/v1' && result?.status === 'ok'
81
+ && definition?.backgroundCommandPolicy === 'owned-command-launch/v1' && (result?.status === 'ok' || requiresStartFailureProof)
79
82
  && same(result.backgroundCommandRef ?? null, ref), 'background_command_launcher_receipt_mismatch');
80
83
  const backend = typeof result.content?.backend === 'string' && result.content.backend.startsWith('sandbox/')
81
84
  ? result.content.backend.slice('sandbox/'.length) : null;
82
85
  return { ref, backend: ['local_process', 'e2b'].includes(backend) ? backend : null,
86
+ ...(requiresStartFailureProof ? { requiresStartFailureProof } : {}),
83
87
  ...(includeCommand ? { command: typeof calls[0].arguments?.command === 'string' ? calls[0].arguments.command.slice(0, 32768) : '' } : {}) };
84
88
  }
85
89