@kingsoftcloud/agentkit-harness-node 0.0.18 → 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.
@@ -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);