@kingsoftcloud/agentkit-harness-node 0.0.19 → 0.0.20

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.
@@ -27,7 +27,8 @@ import { readFileSync, realpathSync } from 'node:fs';
27
27
  import * as readline from 'node:readline';
28
28
  import { setTimeout as wait } from 'node:timers/promises';
29
29
  import { fileURLToPath } from 'node:url';
30
- import { currentDeliveryManifest, FINAL_SUBMISSION_TOOL, isNativeError, TOOL_RECEIPT_OBSERVATION_CONTRACT } from '@kingsoftcloud/agentkit-harness-core';
30
+ import { currentDeliveryManifest, FINAL_SUBMISSION_TOOL, isApprovalDenialReason, isNativeError, TOOL_RECEIPT_OBSERVATION_CONTRACT,
31
+ validateModelFailure } from '@kingsoftcloud/agentkit-harness-core';
31
32
  import { publicErrorMessage } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
32
33
  import { createEngineRuntime, engineApprovalSubject, ENGINE_APPROVAL_CONTRACT, ENGINE_EXECUTION_POLICY,
33
34
  ENGINE_INPUT_IMAGES } from './engine-runtime.mjs';
@@ -38,14 +39,14 @@ import { ENGINE_HOOKS } from './engine-hooks.mjs';
38
39
  import { ENGINE_HOST_EFFECT, hostReceiptReply, hostReceiptSource, waitForHostReceipt } from './engine-host-effects.mjs';
39
40
  import { ENGINE_VERIFICATION } from './engine-verification.mjs';
40
41
  import { nativeTodoPlan } from './activity-status.mjs';
41
- import { engineDeliveryEvidence } from './engine-delivery-evidence.mjs';
42
+ import { nativeModelStopMessage } from './native-terminal-failure.mjs';
42
43
  export { ENGINE_VIEW_CONTRACT };
43
44
 
44
45
  export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
45
46
  export const ENGINE_EVENT_SCHEMA = 'agentkit.engine-event/v1';
46
47
  const THINKING_PAGE_CHARS = 8192;
47
48
  const THINKING_HISTORY_CHARS = 128 * 1024;
48
- const METHODS = ['initialize', 'run/start', 'run/status', 'run/events', 'run/resume', 'run/cancel', 'ui/view', 'shutdown'];
49
+ const METHODS = ['initialize', 'run/start', 'run/status', 'run/events', 'run/resume', 'run/guide', 'run/cancel', 'ui/view', 'shutdown'];
49
50
  const DURABLE_APPROVAL_METHOD = 'run/approve';
50
51
  const HOST_OBSERVATIONS_METHOD = 'run/host-observations';
51
52
  const ERRORS = { parse: -32700, request: -32600, method: -32601, params: -32602, internalError: -32603,
@@ -54,6 +55,11 @@ const text = value => typeof value === 'string' && value.trim().length > 0;
54
55
  const toolName = /^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/;
55
56
  const sleep = ms => new Promise(done => setTimeout(done, ms));
56
57
  const publicRequestId = operationKey => createHash('sha256').update(operationKey).digest('hex');
58
+ const modelUsageFields = ['inputTokens', 'outputTokens', 'cachedInputTokens', 'cacheWriteInputTokens', 'reasoningTokens'];
59
+ function modelUsage(usage) {
60
+ return Object.fromEntries(modelUsageFields.filter(key => Number.isSafeInteger(usage[key]) && usage[key] >= 0)
61
+ .map(key => [key, usage[key]]));
62
+ }
57
63
 
58
64
  /** The engine's own task view, built by agentkit-harness-ui into this package's dist. */
59
65
  let viewCache;
@@ -84,7 +90,9 @@ export function projectEngineEvent(event, requiredVerification = false, thinking
84
90
  ...(thinkingPresentation && Array.isArray(payload.todos) ? { plan: nativeTodoPlan(payload.todos) } : {}) };
85
91
  case 'effect.prepared':
86
92
  case 'effect.settled':
87
- return thinkingPresentation && payload.kind === 'model' ? { ...base, category: 'model', title: 'request', ...modelRequest }
93
+ return payload.kind === 'model' ? { ...base, category: 'model', title: 'request', ...modelRequest,
94
+ ...(event.kind === 'effect.prepared' && payload.retry === true ? { retry: true } : {}),
95
+ ...(event.kind === 'effect.prepared' && payload.purpose === 'compaction' ? { purpose: 'compaction' } : {}) }
88
96
  : { ...base, category: 'effect' };
89
97
  case 'model.completed':
90
98
  case 'model.stream_interrupted': {
@@ -100,10 +108,14 @@ export function projectEngineEvent(event, requiredVerification = false, thinking
100
108
  ...(text(payload.text) && !(requiredVerification && payload.kind === 'final_candidate') ? { detail: payload.text } : {}),
101
109
  ...(Array.isArray(payload.toolCalls) && payload.toolCalls.length ? { tools: payload.toolCalls.map(call => call.name),
102
110
  calls: payload.toolCalls.map(call => ({ callId: call.callId, name: call.name, arguments: bounded(call.arguments) })) } : {}),
103
- ...(payload.usage ? { usage: { inputTokens: payload.usage.inputTokens, outputTokens: payload.usage.outputTokens } } : {}) };
111
+ ...(payload.usage ? { usage: modelUsage(payload.usage) } : {}) };
104
112
  }
113
+ case 'context.summary_completed':
114
+ case 'completion.delivery_review_completed':
115
+ return { ...base, category: 'model', ...(payload.usage ? { usage: modelUsage(payload.usage) } : {}) };
105
116
  case 'tool.completed': return { ...base, category: 'tool', title: payload.name, status: payload.status,
106
- ...(text(payload.callId) ? { callId: payload.callId } : {}), ...(payload.content === undefined ? {} : { result: bounded(payload.content) }) };
117
+ ...(text(payload.callId) ? { callId: payload.callId } : {}),
118
+ ...(payload.content === undefined ? {} : { result: boundedToolResult(payload.name, payload.content) }) };
107
119
  case 'approval.requested': return { ...base, category: 'approval', title: payload.name, status: 'pending',
108
120
  callId: payload.callId, interactionId: payload.interactionId,
109
121
  ...(payload.source === 'child_tool' ? { approvalContract: ENGINE_APPROVAL_CONTRACT,
@@ -112,16 +124,34 @@ export function projectEngineEvent(event, requiredVerification = false, thinking
112
124
  ...(text(payload.content.subject) ? { detail: payload.content.subject } : {}) } : {}) };
113
125
  case 'approval.resolved': return { ...base, category: 'approval', status: payload.decision,
114
126
  callId: payload.callId, interactionId: payload.interactionId };
115
- case 'model.failure_observed': return { ...base, category: 'model', title: 'model_failure', status: 'retrying', detail: payload.code };
127
+ case 'input.guidance_applied':
128
+ return { ...base, category: 'input', inputId: payload.inputId };
129
+ case 'command.applied':
130
+ return payload.kind === 'guide' ? { ...base, category: 'command', inputId: payload.commandId, status: payload.reason }
131
+ : { ...base, category: 'command' };
132
+ case 'model.failure_observed': {
133
+ try { validateModelFailure(payload); } catch { return { ...base, category: 'model', title: 'model_failure' }; }
134
+ return { ...base, category: 'model', title: 'model_failure', detail: payload.code,
135
+ ...(payload.httpStatus === undefined ? {} : { httpStatus: payload.httpStatus }),
136
+ ...(payload.gateway ? { gateway: payload.gateway } : {}) };
137
+ }
138
+ case 'model.retry_exhausted': return { ...base, category: 'model', reason: 'provider_unavailable',
139
+ modelError: nativeModelStopMessage('provider_unavailable') };
116
140
  case 'run.started': return { ...base, category: 'run', title: 'started' };
117
141
  case 'run.terminal': return { ...base, category: 'run', title: payload.phase, status: payload.outcome,
118
142
  ...(requiredVerification ? { requiredVerification: true } : {}),
119
143
  ...(payload.reason ? { reason: payload.reason } : {}),
144
+ ...modelStopFields(payload.reason, payload.modelFailure),
120
145
  ...(text(payload.finalText) && (!requiredVerification || payload.outcome === 'verified') ? { detail: payload.finalText } : {}) };
121
146
  default: return { ...base, category: event.kind.split('.')[0] };
122
147
  }
123
148
  }
124
149
 
150
+ function modelStopFields(reason, failure) {
151
+ const modelError = nativeModelStopMessage(reason, failure);
152
+ return modelError ? { modelError } : {};
153
+ }
154
+
125
155
  /** Bound a value carried in a projected event: views show previews, never whole files. */
126
156
  const PREVIEW_CHARS = 4000;
127
157
  function bounded(value) {
@@ -131,6 +161,40 @@ function bounded(value) {
131
161
  return { truncated: true, preview: encoded.slice(0, PREVIEW_CHARS), chars: encoded.length };
132
162
  }
133
163
 
164
+ function boundedToolResult(name, value) {
165
+ const result = bounded(value);
166
+ if (typeof result?.preview !== 'string' || value?.ok !== true) return result;
167
+ // Keep the actual range and match locations when the raw result exceeds the
168
+ // event budget. Source lines can otherwise crowd out all of that metadata.
169
+ let observation;
170
+ if (name === 'read_workspace_file') {
171
+ const range = value.read_range;
172
+ observation = {
173
+ start_line: Number.isSafeInteger(range?.start) ? range.start : undefined,
174
+ end_line: Number.isSafeInteger(range?.end) ? range.end : undefined,
175
+ line_count: Number.isSafeInteger(value.line_count) ? value.line_count : undefined,
176
+ };
177
+ } else if (name === 'search_workspace_files' && Array.isArray(value.results)) {
178
+ const locations = [];
179
+ let locationBudget = 2200;
180
+ for (const hit of value.results.slice(0, 12)) {
181
+ if (typeof hit?.path !== 'string' || !Number.isSafeInteger(hit.line)) continue;
182
+ const location = { path: hit.path, line: hit.line };
183
+ const size = JSON.stringify(location).length + 1;
184
+ if (size > locationBudget) continue;
185
+ locations.push(location);
186
+ locationBudget -= size;
187
+ }
188
+ observation = {
189
+ searched_path: typeof value.searched_path === 'string' && value.searched_path.length <= 512 ? value.searched_path : undefined,
190
+ match_count: Number.isSafeInteger(value.match_count) ? value.match_count : undefined,
191
+ results: locations,
192
+ locations_truncated: value.truncated === true || locations.length < value.results.length,
193
+ };
194
+ } else return result;
195
+ return { ...result, ...observation, preview: result.preview.slice(0, PREVIEW_CHARS - JSON.stringify(observation).length) };
196
+ }
197
+
134
198
  export async function serveEngine({ input, output, log = () => {}, startup, env = process.env, fetchImpl = fetch, detachOnShutdown = false, viewStore }) {
135
199
  const frames = readline.createInterface({ input, crlfDelay: Infinity });
136
200
  const send = frame => output.write(`${JSON.stringify(frame)}\n`);
@@ -219,6 +283,8 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
219
283
  const pendingApproval = runtime.pendingApproval(snapshot, configuration);
220
284
  return { runId, phase: snapshot.phase, outcome: snapshot.outcome ?? null, reason: snapshot.reason ?? null,
221
285
  terminal: runtime.terminal(snapshot), running: active.has(runId), usage: snapshot.usage,
286
+ ...(['paused', 'failed', 'completed'].includes(snapshot.phase)
287
+ ? modelStopFields(snapshot.reason, snapshot.diagnostics.lastModelFailure) : {}),
222
288
  finalText: configuration.hostVerification && snapshot.outcome !== 'verified' ? null
223
289
  : snapshot.finalText ?? snapshot.candidate?.text ?? null, cursor: tail(runId),
224
290
  ...(pendingApproval ? { pendingApproval } : {}),
@@ -356,7 +422,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
356
422
  requireRun(params);
357
423
  const rest = status(params.runId);
358
424
  return params.deliveryPresentation === true && rest.phase === 'completed' && text(rest.finalText)
359
- ? { ...rest, deliveryEvidence: engineDeliveryEvidence(runtime.load(params.runId)) } : rest;
425
+ ? { ...rest, deliveryEvidence: runtime.deliveryEvidence(params.runId) } : rest;
360
426
  },
361
427
  async [HOST_OBSERVATIONS_METHOD](params) {
362
428
  if (!host.services.toolEffects) throw rpcError(ERRORS.method, 'host observations unavailable');
@@ -409,7 +475,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
409
475
  if (projected.kind !== 'run.terminal' || projected.title !== 'completed' || !text(projected.detail)) return projected;
410
476
  const artifacts = currentDeliveryManifest(snapshot)?.artifacts;
411
477
  return { ...projected, ...(artifacts?.length ? { deliverables: artifacts } : {}),
412
- ...((thinkingPresentation || draftPresentation) ? { deliveryEvidence: engineDeliveryEvidence(runtime.load(runId)) } : {}) };
478
+ ...((thinkingPresentation || draftPresentation) ? { deliveryEvidence: runtime.deliveryEvidence(runId) } : {}) };
413
479
  }), cursor: next,
414
480
  ...(thinking ? { thinking } : {}),
415
481
  ...(toolDraft ? { toolDraft } : {}),
@@ -426,17 +492,32 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
426
492
  if (!before.terminal) continueOnSubscription(params.runId, record);
427
493
  return status(params.runId);
428
494
  },
495
+ async 'run/guide'(params) {
496
+ const record = requireRun(params);
497
+ const { runId, inputId, text: input } = params;
498
+ if (record.configuration.guidancePolicy !== 'boundary-guide/v1') return { status: 'unsupported' };
499
+ if (!/^guide-[a-f0-9]{64}$/.test(inputId ?? '') || !text(input) || input.length > 32768)
500
+ throw rpcError(ERRORS.params, 'invalid run guidance');
501
+ // Recover the revision from the original command when its reply was
502
+ // lost. The store still checks that replay uses identical input.
503
+ const previous = runtime.load(runId).commands.find(row => row.command.commandId === inputId);
504
+ return runtime.submit(runId, { commandId: inputId, kind: 'guide',
505
+ payload: { text: input, expectedGoalRevision: previous?.command.payload.expectedGoalRevision ?? record.snapshot.goalRevision } });
506
+ },
429
507
  async [DURABLE_APPROVAL_METHOD](params) {
430
508
  requireRun(params);
431
509
  if (!detachOnShutdown || !text(params.interactionId) || !['allow', 'deny'].includes(params.decision))
432
510
  throw rpcError(ERRORS.params, 'interactionId and approval decision are required');
433
- const { runId, interactionId, decision } = params;
511
+ const { runId, interactionId, decision, denialReason } = params;
512
+ if (denialReason !== undefined && (decision !== 'deny' || !isApprovalDenialReason(denialReason)))
513
+ throw rpcError(ERRORS.params, 'invalid approval denial reason');
434
514
  const commandId = `approval-${createHash('sha256').update(interactionId).digest('hex')}`;
435
515
  const record = runtime.load(runId);
436
516
  if (!record.commands.some(row => row.command.commandId === commandId)
437
517
  && runtime.pendingApproval(record.snapshot, record.configuration)?.interactionId !== interactionId)
438
518
  throw rpcError(ERRORS.params, 'interaction_mismatch');
439
- const receipt = runtime.submit(runId, { commandId, kind: 'submit_interaction', payload: { interactionId, decision } });
519
+ const receipt = runtime.submit(runId, { commandId, kind: 'submit_interaction',
520
+ payload: { interactionId, decision, ...(denialReason === undefined ? {} : { denialReason }) } });
440
521
  if (receipt.status !== 'rejected') {
441
522
  const continueRun = () => { if (!closing && !status(runId).terminal) continueOnSubscription(runId, record); };
442
523
  const running = active.get(runId);
@@ -78,14 +78,17 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
78
78
  resolve(frame);
79
79
  }
80
80
  });
81
- const takeHostRequests = runId => {
82
- pruneHostRequests(Date.now());
81
+ const takeHostRequests = (runId, receiver) => {
82
+ const now = Date.now();
83
+ pruneHostRequests(now);
83
84
  const ready = [];
84
85
  for (const request of hostRequests.values()) {
85
- if (!request.claimed && (runId === undefined || request.frame.params?.runId === runId)) {
86
- request.claimed = true;
87
- ready.push(request.frame);
88
- }
86
+ if (runId !== undefined && request.frame.params?.runId !== runId) continue;
87
+ if (request.claimed && (!receiver || request.receiver !== receiver || now < request.redeliverAt)) continue;
88
+ request.claimed = true;
89
+ request.receiver = receiver;
90
+ request.redeliverAt = now + 500;
91
+ ready.push(request.frame);
89
92
  }
90
93
  return ready;
91
94
  };
@@ -97,8 +100,8 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
97
100
  input.write(JSON.stringify(frame) + '\n');
98
101
  });
99
102
  },
100
- async takeHostRequests(runId, waitMs, response) {
101
- const available = takeHostRequests(runId);
103
+ async takeHostRequests(runId, waitMs, response, receiver) {
104
+ const available = takeHostRequests(runId, receiver);
102
105
  if (available.length || !waitMs || response.destroyed) return available;
103
106
  return new Promise(resolve => {
104
107
  const finish = frames => {
@@ -110,7 +113,7 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
110
113
  const cancel = () => finish([]);
111
114
  const notify = stopped => {
112
115
  if (stopped || response.destroyed) return cancel();
113
- const ready = takeHostRequests(runId);
116
+ const ready = takeHostRequests(runId, receiver);
114
117
  if (ready.length) finish(ready);
115
118
  };
116
119
  const timer = setTimeout(cancel, waitMs);
@@ -202,7 +205,11 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
202
205
  const search = new URLSearchParams(query);
203
206
  const runId = search.get('runId') ?? undefined;
204
207
  const waitMs = Math.min(Math.max(Number(search.get('waitMs')) || 0, 0), 5000);
205
- const requests = await session.takeHostRequests(runId, waitMs, response);
208
+ // Existing hosts use one-shot delivery. Only a Run-scoped client
209
+ // that deduplicates execution by frame ID can request redelivery.
210
+ const requestedReceiver = search.get('receiver');
211
+ const receiver = runId !== undefined && /^[a-f0-9-]{36}$/.test(requestedReceiver ?? '') ? requestedReceiver : null;
212
+ const requests = await session.takeHostRequests(runId, waitMs, response, receiver);
206
213
  return respond(response, 200, { requests });
207
214
  }
208
215
  if (query !== undefined) return respond(response, 400, { error: 'invalid_query' });
@@ -33,7 +33,8 @@ import { buildNativeModelRequest } from './model-request.mjs';
33
33
  // parseModelJson is the kernel's strict finite JSON parser; used here for the
34
34
  // 400 context-length error heuristic so a malformed error body is never parsed
35
35
  // as a lenient ambiguity.
36
- import { parseModelJson, MODEL_FAILURE_CODES } from '@kingsoftcloud/agentkit-harness-core';
36
+ import { parseModelJson, MODEL_FAILURE_CODES, MODEL_GATEWAY_ERROR_CODES, MODEL_GATEWAY_ERROR_TYPES,
37
+ isModelGatewayRequestId } from '@kingsoftcloud/agentkit-harness-core';
37
38
  import { observeModelTransportPort } from './model-transport-observation.mjs';
38
39
 
39
40
  const DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
@@ -136,12 +137,14 @@ export function createNativeModelPort({
136
137
  try {
137
138
  if (!response.ok) {
138
139
  observation.phase('http-error');
139
- const result = await classifyHttpError(response, { maxBytes });
140
+ const body = await readHttpError(response, maxBytes);
141
+ const result = classifyHttpError(response, body);
142
+ const gateway = httpGatewayDiagnostic(response, body);
140
143
  request.signal?.throwIfAborted();
141
144
  const code = response.status === 401 ? 'http_authentication' : response.status === 403 ? 'http_permission'
142
145
  : response.status === 429 ? 'http_rate_limit' : response.status === 408 ? 'http_timeout'
143
146
  : response.status >= 500 ? 'http_server' : 'http_client';
144
- return withFailure(result, binding, 'http-error', code, { httpStatus: response.status });
147
+ return withFailure(result, binding, 'http-error', code, { httpStatus: response.status, ...(gateway ? { gateway } : {}) });
145
148
  }
146
149
  const contentType = response.headers.get('content-type') || '';
147
150
  if (contentType.includes('text/event-stream')) {
@@ -182,6 +185,27 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
182
185
  // body read rejects cleanly instead of leaving an orphaned read to cancel.
183
186
  const abort = (reason) => internal.abort(reason);
184
187
  let frameIndex = -1;
188
+ // Bound only a sustained, exact cycle before the response produces text or
189
+ // tool arguments. Inspect a small suffix independent of SSE chunk boundaries.
190
+ let reasoning = request.purpose == null || request.purpose === 'task' ? '' : null;
191
+ let sinceCheck = 0;
192
+ let repetition = false;
193
+ const observe = event => {
194
+ if ((event.kind === 'text' && event.text.trim()) || event.kind === 'tool_delta') reasoning = null;
195
+ if (reasoning !== null && event.kind === 'thinking' && event.text) {
196
+ reasoning = (reasoning + event.text).slice(-1024);
197
+ sinceCheck += event.text.length;
198
+ if (reasoning.length === 1024 && sinceCheck >= 128) {
199
+ sinceCheck = 0;
200
+ for (let size = 1; size <= 64; size++) {
201
+ if (reasoning.slice(size) !== reasoning.slice(0, -size)) continue;
202
+ repetition = true;
203
+ break;
204
+ }
205
+ }
206
+ }
207
+ emit(event);
208
+ };
185
209
  const failed = (result, code, fields = {}) => withFailure(result, binding, 'stream', code,
186
210
  { ...(frameIndex < 0 ? {} : { frameIndex }),
187
211
  ...(code === 'usage_conflict' && state.usageConflict ? { usageConflict: state.usageConflict } : {}), ...fields });
@@ -190,7 +214,12 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
190
214
  if (idlePolicy && !frame.data.trim()) continue;
191
215
  frameIndex++;
192
216
  observation.frame();
193
- state.consume(frame, emit);
217
+ state.consume(frame, observe);
218
+ if (repetition && reasoning !== null && !state.done) {
219
+ abort(new Error('reasoning_repetition'));
220
+ return failed({ kind: 'output_limit', text: '', toolCalls: [], usage: emptyUsage(), usageReported: false,
221
+ textCommitVersion: 'provider-finished-text/v1', outputBoundary: 'no-visible-output/v1' }, 'reasoning_repetition');
222
+ }
194
223
  if (idlePolicy) emit({ kind: 'activity', text: '' });
195
224
  if (state.done) break;
196
225
  }
@@ -248,41 +277,45 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
248
277
  }
249
278
  }
250
279
 
251
- // Classify a non-2xx HTTP response into a sealed ModelResult. The body is read
252
- // only for a 400 to detect a context_length_exceeded code; otherwise the
253
- // status and Retry-After header are the only facts that leave the adapter. A
254
- // body that cannot be read (timeout/overflow/bad utf-8) cannot erase the HTTP
255
- // failure fact — the status-based classification still stands.
256
- async function classifyHttpError(response, { maxBytes }) {
280
+ // Diagnostics are observational. Neither body identifiers nor correlation
281
+ // headers change retry behavior, except for the existing context-overflow rule.
282
+ function classifyHttpError(response, body) {
257
283
  const status = response.status;
258
284
  const retryAfterMs = parseRetryAfterMs(response.headers.get('retry-after'));
259
285
  if (status === 408) return retryableResult('request_timeout', retryAfterMs);
260
286
  if (status === 429) return retryableResult('rate_limit', retryAfterMs);
261
287
  if (status >= 500 && status <= 599) return retryableResult('server_error', retryAfterMs);
262
288
  if (status === 403) return { kind: 'policy_abort', text: '', toolCalls: [], usage: emptyUsage(), usageReported: false };
263
- if (status === 400) {
264
- try {
265
- const bodyText = await readBoundedText(response, maxBytes);
266
- if (hasContextLengthExceeded(bodyText)) {
267
- return { kind: 'context_overflow', text: '', toolCalls: [], usage: emptyUsage(), usageReported: false };
268
- }
269
- } catch { /* an unreadable 400 body cannot erase the 400 failure fact */ }
270
- return terminalResult('client_error');
289
+ if (status === 400 && (body?.error?.code === 'context_length_exceeded' || body?.error?.type === 'context_length_exceeded')) {
290
+ return { kind: 'context_overflow', text: '', toolCalls: [], usage: emptyUsage(), usageReported: false };
271
291
  }
272
292
  return terminalResult('client_error');
273
293
  }
274
294
 
275
- function hasContextLengthExceeded(bodyText) {
295
+ async function readHttpError(response, maxBytes) {
296
+ // Rate limiting is fully determined by status and Retry-After. Only the
297
+ // allowlisted correlation header is needed; never wait on a 429 body.
298
+ if (response.status === 429) return null;
299
+ const contextCheck = response.status === 400;
300
+ // Keep the original 400 compatibility check. For other statuses this is
301
+ // optional evidence; a stalled error body must not delay retries.
302
+ if (!contextCheck && !response.body?.getReader) return null;
276
303
  try {
277
- const payload = parseModelJson(bodyText);
278
- const error = payload && typeof payload === 'object' ? payload.error : null;
279
- if (error && typeof error === 'object') {
280
- const code = String(error.code || '');
281
- const type = String(error.type || '');
282
- if (code === 'context_length_exceeded' || type === 'context_length_exceeded') return true;
283
- }
284
- } catch { /* an unreadable error body cannot erase the HTTP failure fact */ }
285
- return false;
304
+ return parseModelJson(await readBoundedText(response, contextCheck ? maxBytes : Math.min(maxBytes, 8192),
305
+ undefined, contextCheck ? undefined : AbortSignal.timeout(200)));
306
+ } catch { return null; }
307
+ }
308
+
309
+ function httpGatewayDiagnostic(response, body) {
310
+ const diagnostic = {};
311
+ const error = body?.error && typeof body.error === 'object' ? body.error : body;
312
+ if (MODEL_GATEWAY_ERROR_CODES.includes(error?.code)
313
+ || Number.isInteger(error?.code) && error.code >= 400 && error.code <= 599) diagnostic.code = error.code;
314
+ if (MODEL_GATEWAY_ERROR_TYPES.includes(error?.type)) diagnostic.type = error.type;
315
+ const requestId = ['x-request-id', 'request-id', 'x-ksc-request-id']
316
+ .map(header => response.headers.get(header)).find(isModelGatewayRequestId);
317
+ if (requestId) diagnostic.requestId = requestId;
318
+ return Object.keys(diagnostic).length ? diagnostic : null;
286
319
  }
287
320
 
288
321
  function terminalResult(failureKind) {
@@ -296,9 +329,12 @@ function protocolCode(error) {
296
329
  ? error.code : 'protocol_invalid';
297
330
  }
298
331
  function withFailure(result, binding, phase, code, fields = {}) {
299
- if (!['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)) return result;
332
+ if (!['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)
333
+ && !(result.kind === 'output_limit' && code === 'reasoning_repetition')
334
+ && !(result.kind === 'context_overflow' && fields.gateway)) return result;
300
335
  const protocol = ['openai-chat', 'openai-responses', 'anthropic-messages'].includes(binding?.protocol) ? binding.protocol : 'unknown';
301
- return { ...result, failureDiagnostic: { contract: fields.providerError ? 'model-failure-diagnostic/v3' : fields.usageConflict
336
+ return { ...result, failureDiagnostic: { contract: fields.gateway ? 'model-failure-diagnostic/v4'
337
+ : fields.providerError ? 'model-failure-diagnostic/v3' : fields.usageConflict
302
338
  ? 'model-failure-diagnostic/v2' : 'model-failure-diagnostic/v1', protocol, phase, code, ...fields } };
303
339
  }
304
340
 
@@ -329,7 +365,7 @@ function cancelBody(response) {
329
365
  // truncating a prefix (a JSON prefix + overflow suffix must not masquerade as a
330
366
  // complete response). Reads to EOF before sealing. Throws OverflowError on
331
367
  // overflow; propagates abort and bad-UTF-8 errors for the caller to classify.
332
- async function readBoundedText(response, maxBytes, observeBytes) {
368
+ async function readBoundedText(response, maxBytes, observeBytes, signal) {
333
369
  const body = response.body;
334
370
  if (body == null) return '';
335
371
  const reader = body.getReader ? body.getReader() : null;
@@ -337,9 +373,13 @@ async function readBoundedText(response, maxBytes, observeBytes) {
337
373
  let total = 0;
338
374
  const chunks = [];
339
375
  if (reader) {
376
+ const abort = () => { void reader.cancel().catch(() => {}); };
340
377
  try {
378
+ signal?.throwIfAborted();
379
+ signal?.addEventListener('abort', abort, { once: true });
341
380
  while (true) {
342
381
  const { value, done } = await reader.read();
382
+ signal?.throwIfAborted();
343
383
  if (done) break;
344
384
  if (!value) continue;
345
385
  if (!(value instanceof Uint8Array) && !(value instanceof ArrayBuffer)) throw new ProtocolError('body requires bytes');
@@ -351,6 +391,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
351
391
  chunks.push(decoder.decode());
352
392
  return chunks.join('');
353
393
  } finally {
394
+ signal?.removeEventListener('abort', abort);
354
395
  reader.releaseLock?.();
355
396
  }
356
397
  }
@@ -27,13 +27,15 @@ const messages = Object.freeze({
27
27
  });
28
28
 
29
29
  const modelReasons = new Set(['provider_terminal_error', 'provider_retryable_error_retry_exhausted',
30
- 'malformed_tool_call_retry_exhausted', 'model_policy_abort']);
31
- function modelFailureMessage(value) {
30
+ 'malformed_tool_call_retry_exhausted', 'model_policy_abort', 'context_summary_provider_terminal_error',
31
+ 'context_summary_retry_exhausted']);
32
+ function modelFailureMessage(value, retriesExhausted = false) {
32
33
  if (!value) return null;
33
34
  try { validateModelFailure(value); } catch { return null; }
34
35
  if (value.code === 'http_authentication') return '模型服务拒绝身份认证,请检查模型凭据。';
35
36
  if (value.code === 'http_permission') return '模型请求被服务端权限或策略拒绝。';
36
- if (value.code === 'http_rate_limit') return '模型服务持续限流,本次运行的重试次数已耗尽。';
37
+ if (value.code === 'http_client') return `模型网关拒绝了请求(HTTP ${value.httpStatus})${retriesExhausted ? '。' : ',未自动重试。'}`;
38
+ if (value.code === 'http_rate_limit') return '模型服务返回限流错误(HTTP 429)。';
37
39
  if (value.code === 'host_binding') return '模型连接配置未能加载,请检查运行配置。';
38
40
  if (value.phase === 'request') return '模型请求在发送前未通过校验,请查看运行诊断。';
39
41
  if (value.code === 'stream_timeout' || value.code === 'http_timeout') return '等待模型服务响应超时,本次运行未能完成。';
@@ -42,11 +44,20 @@ function modelFailureMessage(value) {
42
44
  if (value.phase === 'stream' || value.phase === 'buffered') return '模型响应未通过协议校验,本次运行已停止,请查看运行诊断。';
43
45
  return null;
44
46
  }
47
+ export function nativeModelStopMessage(reason, modelFailure) {
48
+ if (reason === 'provider_unavailable') return '模型服务暂不可用,自动重试次数已用完。任务已暂停,可稍后继续。';
49
+ if (!modelReasons.has(reason)) return null;
50
+ if (reason.endsWith('_retry_exhausted')) {
51
+ const detail = modelFailureMessage(modelFailure, true);
52
+ return detail ? `${detail}自动重试次数已用完。` : '模型请求未能完成,自动重试次数已用完。';
53
+ }
54
+ return modelFailureMessage(modelFailure) ?? (Object.hasOwn(messages, reason) ? messages[reason] : '模型请求未能完成,任务已停止。');
55
+ }
45
56
  export function nativePublicTerminalError(phase, reason, modelFailure) {
46
57
  if (phase !== 'failed' && phase !== 'interrupted') return null;
47
58
  return {
48
59
  code: phase === 'interrupted' ? 'NATIVE_EXECUTION_INTERRUPTED' : 'NATIVE_EXECUTION_NOT_COMPLETED',
49
- message: (modelReasons.has(reason) ? modelFailureMessage(modelFailure) : null) ?? (Object.hasOwn(messages, reason) ? messages[reason] : (phase === 'interrupted'
60
+ message: nativeModelStopMessage(reason, modelFailure) ?? (Object.hasOwn(messages, reason) ? messages[reason] : (phase === 'interrupted'
50
61
  ? '原运行需要核对后才能继续,不会自动重复可能产生副作用的操作。'
51
62
  : 'Native 运行未完成,请检查运行记录和配置。')),
52
63
  };
@@ -18,7 +18,7 @@ import { publicErrorMessage, publicErrorCode, publicFailureContent } from '@king
18
18
  */
19
19
  import { createHash } from 'node:crypto';
20
20
  import {
21
- chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync,
21
+ chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readdirSync,
22
22
  readFileSync, readlinkSync, readSync, realpathSync, rmdirSync, statSync,
23
23
  unlinkSync,
24
24
  } from 'node:fs';
@@ -59,6 +59,8 @@ const READ_ONLY = new Set([
59
59
 
60
60
  const OBSERVE_MAX_ENTRIES = 2048;
61
61
  const OBSERVE_MAX_HASHED = 64 * 1024 * 1024;
62
+ const DELIVERY_MAX_FILE_BYTES = 128 * 1024;
63
+ const DELIVERY_MAX_TEXT_BYTES = 4 * 1024 * 1024;
62
64
 
63
65
  class CaptureError extends Error {
64
66
  constructor(reason) { super(reason); this.code = reason; this.name = 'CaptureError'; }
@@ -1331,9 +1333,9 @@ export function createNativeWorkspaceTools({
1331
1333
  return 'sha256:' + captureStable(real).digest;
1332
1334
  }
1333
1335
 
1334
- function captureStable(real) {
1335
- const first = captureInventory(real);
1336
- const second = captureInventory(real);
1336
+ function captureStable(real, delivery = false) {
1337
+ const first = captureInventory(real, false, delivery);
1338
+ const second = captureInventory(real, delivery, delivery);
1337
1339
  if (first.digest !== second.digest
1338
1340
  || first.entryCount !== second.entryCount
1339
1341
  || !entriesEqual(first.entries, second.entries)) {
@@ -1342,13 +1344,14 @@ export function createNativeWorkspaceTools({
1342
1344
  return second;
1343
1345
  }
1344
1346
 
1345
- function captureInventory(real) {
1347
+ function captureInventory(real, delivery = false, ignoreGit = false) {
1346
1348
  const hash = createHash('sha256');
1347
1349
  hash.update('ksadk.directory-workspace/v1\0');
1348
- const state = { entries: 0, hashedBytes: 0, list: [], byPath: Object.create(null) };
1350
+ const state = { entries: 0, hashedBytes: 0, list: [], byPath: Object.create(null),
1351
+ delivery: delivery ? Object.create(null) : null, deliveryBytes: 0, ignoreGit };
1349
1352
  scanDir(real, '', hash, state);
1350
1353
  state.list.sort();
1351
- return { digest: hash.digest('hex'), entryCount: state.entries, entries: state.list, byPath: state.byPath };
1354
+ return { digest: hash.digest('hex'), entryCount: state.entries, entries: state.list, byPath: state.byPath, delivery: state.delivery };
1352
1355
  }
1353
1356
 
1354
1357
  /** Compare two sorted entry-identity lists for exact equality. */
@@ -1364,6 +1367,7 @@ export function createNativeWorkspaceTools({
1364
1367
  try { dirents = readdirSync(dir, { withFileTypes: true }); } catch { throw new CaptureError('capture_failed'); }
1365
1368
  dirents.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1366
1369
  for (const d of dirents) {
1370
+ if (!rel && state.ignoreGit && d.name === '.git') continue;
1367
1371
  const entryRel = rel ? `${rel}/${d.name}` : d.name;
1368
1372
  if (entryRel.includes('\\') || entryRel.includes('\0')) throw new CaptureError('unsupported_workspace_path');
1369
1373
  state.entries += 1;
@@ -1391,7 +1395,11 @@ export function createNativeWorkspaceTools({
1391
1395
  } else if (info.isFile()) {
1392
1396
  if (state.hashedBytes + Number(info.size) > OBSERVE_MAX_HASHED) throw new CaptureError('capture_limit_exceeded');
1393
1397
  const fileHash = createHash('sha256');
1394
- const fd = openSync(abs, 'r');
1398
+ const size = Number(info.size);
1399
+ const deliveryFile = state.delivery;
1400
+ const retained = deliveryFile && size <= DELIVERY_MAX_FILE_BYTES && state.deliveryBytes + size <= DELIVERY_MAX_TEXT_BYTES
1401
+ ? Buffer.alloc(size) : null;
1402
+ const fd = openSync(abs, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1395
1403
  let readBytes = 0;
1396
1404
  try {
1397
1405
  let remaining = Number(info.size);
@@ -1399,6 +1407,7 @@ export function createNativeWorkspaceTools({
1399
1407
  while (remaining > 0) {
1400
1408
  const n = readSync(fd, buf, 0, Math.min(buf.length, remaining), null);
1401
1409
  if (n === 0) break; // short read: file shrank under us
1410
+ if (retained) buf.copy(retained, readBytes, 0, n);
1402
1411
  readBytes += n;
1403
1412
  state.hashedBytes += n;
1404
1413
  if (state.hashedBytes > OBSERVE_MAX_HASHED) throw new CaptureError('capture_limit_exceeded');
@@ -1415,6 +1424,15 @@ export function createNativeWorkspaceTools({
1415
1424
  const fileDigest = fileHash.digest();
1416
1425
  hash.update('\0file\0');
1417
1426
  hash.update(fileDigest);
1427
+ if (deliveryFile) {
1428
+ state.delivery[entryRel] = { digest: fileDigest.toString('hex') };
1429
+ if (retained && !retained.includes(0)) {
1430
+ try {
1431
+ state.delivery[entryRel].text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(retained);
1432
+ state.deliveryBytes += size;
1433
+ } catch { /* Binary files carry their identity only. */ }
1434
+ }
1435
+ }
1418
1436
  state.list.push(`${entryRel}\tfile\t${before}\t${fileDigest.toString('hex')}`);
1419
1437
  } else {
1420
1438
  throw new CaptureError('unsupported_workspace_entry');
@@ -1589,6 +1607,12 @@ export function createNativeWorkspaceTools({
1589
1607
  }),
1590
1608
  // Host-only change capture for a governed command. It shares the bounded,
1591
1609
  // stable observer; paths remain structured even when names contain tabs.
1610
+ captureDelivery() {
1611
+ checkRootBoundary();
1612
+ const captured = captureStable(pinnedRootReal, true);
1613
+ checkRootBoundary();
1614
+ return captured.delivery;
1615
+ },
1592
1616
  capture(request) {
1593
1617
  if (request.sessionId !== store.sessionId) throw new CaptureError('workspace_session_mismatch');
1594
1618
  checkRootBoundary(); const captured = captureStable(pinnedRootReal);