@kingsoftcloud/agentkit-harness-core 0.0.19 → 0.0.21

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.
@@ -3,5 +3,6 @@
3
3
  * model or tool may claim in this vocabulary. */
4
4
  export type HostApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';
5
5
  export declare const APPROVAL_OUTCOME_POLICY: "owner-outcome/v1";
6
+ export declare function isApprovalDenialReason(value: unknown): value is 'approval_prompts_disabled' | 'approval_rejected' | 'approval_unavailable' | 'approval_cancelled';
6
7
  export declare function normalizeHostApprovalOutcome(value: unknown): HostApprovalOutcome;
7
8
  export declare function approvalOutcomePauseReason(value: HostApprovalOutcome): string | null;
@@ -1,4 +1,8 @@
1
1
  export const APPROVAL_OUTCOME_POLICY = 'owner-outcome/v1';
2
+ export function isApprovalDenialReason(value) {
3
+ return value === 'approval_prompts_disabled' || value === 'approval_rejected'
4
+ || value === 'approval_unavailable' || value === 'approval_cancelled';
5
+ }
2
6
  export function normalizeHostApprovalOutcome(value) {
3
7
  return value === 'allowed-once' || value === 'rejected' || value === 'cancelled' ? value : 'unavailable';
4
8
  }
package/dist/kernel.mjs CHANGED
@@ -815,6 +815,15 @@ export class NativeKernel {
815
815
  if (intent.payload.purpose === 'compaction') {
816
816
  const result = validateModelResult(raw);
817
817
  changes = reduceContextModel(snapshot, result, configuration, addUsage(snapshot.usage, { ...result.usage, modelCalls: 0, toolCalls: 0 }), this.now(), this.random());
818
+ if (result.failureDiagnostic || snapshot.diagnostics.lastModelFailure)
819
+ changes.diagnostics = {
820
+ ...(changes.diagnostics ?? snapshot.diagnostics),
821
+ lastModelFailure: result.failureDiagnostic ? objectValue(result.failureDiagnostic) : null,
822
+ };
823
+ if (result.failureDiagnostic)
824
+ facts.push({ kind: 'model.failure_observed', payload: objectValue(result.failureDiagnostic) });
825
+ if (changes.phase === 'paused' && changes.reason === 'provider_unavailable')
826
+ facts.push({ kind: 'model.retry_exhausted', payload: { reason: changes.reason } });
818
827
  facts.push({ kind: 'context.summary_completed', payload: { kind: result.kind, usage: objectValue(result.usage),
819
828
  messageCursor: snapshot.messages.length, usageReported: result.usageReported !== false,
820
829
  proposalAvailable: !!changes.contextState?.compaction?.proposal } });
@@ -845,6 +854,8 @@ export class NativeKernel {
845
854
  facts.push({ kind: 'model.transport_observed', payload: objectValue(result.transportObservation) });
846
855
  if (result.failureDiagnostic)
847
856
  facts.push({ kind: 'model.failure_observed', payload: objectValue(result.failureDiagnostic) });
857
+ if (changes.phase === 'paused' && changes.reason === 'provider_unavailable')
858
+ facts.push({ kind: 'model.retry_exhausted', payload: { reason: changes.reason } });
848
859
  const rejectedDraft = configuration.contract.finalSubmissionSchema !== null && result.kind === 'final_candidate';
849
860
  const appended = changes.messages?.slice(snapshot.messages.length) ?? [];
850
861
  const assistantOffset = appended.findIndex(message => message.role === 'assistant');
@@ -862,6 +873,9 @@ export class NativeKernel {
862
873
  messageCursor: changes.messages?.length ?? snapshot.messages.length,
863
874
  usageReported: result.usageReported !== false,
864
875
  toolCalls: planning ? [] : result.toolCalls.map(objectValue), usage: objectValue(result.usage) } });
876
+ if (typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
877
+ facts.push({ kind: 'model.retry_scheduled', payload: { retryAt: Math.ceil(changes.retryNotBefore),
878
+ ...(result.failureDiagnostic ? { failure: objectValue(result.failureDiagnostic) } : {}) } });
865
879
  break;
866
880
  }
867
881
  case 'input':
@@ -1197,7 +1211,8 @@ export class NativeKernel {
1197
1211
  const profile = copy(configuration.profile);
1198
1212
  // Admission reserved the full allowance. Lowering the dispatched request
1199
1213
  // preserves that admission and the frozen Run profile.
1200
- if (!review && configuration.outputRecoveryPolicy === 'response-boundary/v4' && snapshot.reasoningStallRetry)
1214
+ if (!review && snapshot.reasoningStallRetry
1215
+ && ['response-boundary/v4', 'response-boundary/v5'].includes(configuration.outputRecoveryPolicy ?? ''))
1201
1216
  profile.maxOutputTokens = reasoningStallRetryTokens(profile.maxOutputTokens);
1202
1217
  const messages = review ? snapshot.preparedContext ? modelContextMessages(snapshot, this.digest) : this.policies.forRun(configuration).review.deliveryReviewMessages(snapshot)
1203
1218
  : configuration.profile.operatorGuidancePolicy === 'journaled-system/v1' ? modelContextMessages(snapshot, this.digest)
package/dist/machine.mjs CHANGED
@@ -310,7 +310,12 @@ export function validateModelResult(input) {
310
310
  const result = copy(input);
311
311
  validateModelTransport(result.transportObservation);
312
312
  validateModelFailure(result.failureDiagnostic);
313
- invariant(!result.failureDiagnostic || ['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind), 'model_failure_diagnostic_requires_failure');
313
+ const failure = result.failureDiagnostic;
314
+ invariant(!failure || ['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)
315
+ || result.kind === 'output_limit' && result.outputBoundary === 'no-visible-output/v1'
316
+ && failure.phase === 'stream' && failure.code === 'reasoning_repetition'
317
+ || result.kind === 'context_overflow' && failure.httpStatus === 400
318
+ && (failure.gateway?.code === 'context_length_exceeded' || failure.gateway?.type === 'context_length_exceeded'), 'model_failure_diagnostic_requires_failure');
314
319
  invariant(['tool_calls', 'final_candidate', 'output_limit', 'context_overflow', 'empty_response', 'malformed_tool_call',
315
320
  'provider_retryable_error', 'provider_terminal_error', 'policy_abort', 'user_abort'].includes(result.kind)
316
321
  && typeof result.text === 'string' && Array.isArray(result.toolCalls), 'invalid_model_result');
@@ -371,7 +376,8 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
371
376
  if (snapshot.hookState && ['tool_calls', 'final_candidate', 'output_limit'].includes(result.kind)
372
377
  && (result.toolCalls.length > 0 || result.text.trim()))
373
378
  base.hookState = { ...currentHookState(snapshot), feedback: [] };
374
- const stalled = config.outputRecoveryPolicy === 'response-boundary/v4' && reasoningStall(result);
379
+ const stalled = config.outputRecoveryPolicy === 'response-boundary/v4' && reasoningStall(result)
380
+ || config.outputRecoveryPolicy === 'response-boundary/v5' && result.failureDiagnostic?.code === 'reasoning_repetition';
375
381
  // Keep the narrowed retry through transport errors and context preparation.
376
382
  // A sealed cutoff with text or an unfinished tool call uses the ordinary budget again.
377
383
  if (snapshot.reasoningStallRetry && (result.kind === 'tool_calls' || result.kind === 'final_candidate'
@@ -506,7 +512,7 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
506
512
  messages: [...snapshot.messages, { role: 'user',
507
513
  kind: suffix ? 'response_continuation_feedback' : 'output_limit_reasoning_observation',
508
514
  content: suffix ? 'Continue with only the missing text suffix now.'
509
- : 'The previous attempt spent its output budget on reasoning without taking action. Take the next useful tool action now, or answer directly if the task is complete.' }] };
515
+ : 'The previous response stopped during reasoning before taking action. Take the next useful tool action now, or answer directly if the task is complete.' }] };
510
516
  }
511
517
  if (snapshot.continuations >= continuationLimit) {
512
518
  // Committed answer text stays a suffix contract even when the first
@@ -1,8 +1,16 @@
1
1
  /** Observational only: these facts never authorize retries or tool execution. */
2
- export declare const MODEL_FAILURE_CODES: readonly ["host_binding", "request_invalid", "http_authentication", "http_permission", "http_client", "http_server", "http_rate_limit", "http_timeout", "protocol_invalid", "json_invalid", "envelope_invalid", "provider_error", "identity_conflict", "usage_invalid", "usage_conflict", "choice_invalid", "delta_invalid", "termination_conflict", "framing_invalid", "body_limit", "body_encoding", "transport_error", "stream_timeout", "stream_incomplete", "tool_payload_invalid"];
2
+ export declare const MODEL_FAILURE_CODES: readonly ["host_binding", "request_invalid", "http_authentication", "http_permission", "http_client", "http_server", "http_rate_limit", "http_timeout", "protocol_invalid", "json_invalid", "envelope_invalid", "provider_error", "identity_conflict", "usage_invalid", "usage_conflict", "choice_invalid", "delta_invalid", "termination_conflict", "framing_invalid", "body_limit", "body_encoding", "transport_error", "stream_timeout", "stream_incomplete", "tool_payload_invalid", "reasoning_repetition"];
3
3
  /** Closed provider identifiers only; arbitrary provider strings can contain credentials. */
4
4
  export declare const MODEL_PROVIDER_ERROR_CODES: readonly ["rate_limit_error", "rate_limit_exceeded", "overloaded_error", "server_error", "api_error", "service_unavailable_error", "server_is_overloaded", "timeout_error", "MODEL_PROVIDER_RATE_LIMIT", "MODEL_PROVIDER_UNAVAILABLE", "invalid_request_error", "invalid_api_key", "authentication_error", "permission_error", "not_found_error", "request_too_large", "billing_error", "insufficient_quota", "MODEL_PROVIDER_AUTHENTICATION", "MODEL_PROVIDER_PERMISSION", "MODEL_PROVIDER_INVALID_REQUEST", "MODEL_PROVIDER_NOT_FOUND", "MODEL_PROVIDER_QUOTA_EXHAUSTED"];
5
5
  export declare const MODEL_PROVIDER_ERROR_TYPES: readonly ["rate_limit_error", "rate_limit_exceeded", "overloaded_error", "server_error", "api_error", "service_unavailable_error", "server_is_overloaded", "timeout_error", "MODEL_PROVIDER_RATE_LIMIT", "MODEL_PROVIDER_UNAVAILABLE", "invalid_request_error", "invalid_api_key", "authentication_error", "permission_error", "not_found_error", "request_too_large", "billing_error", "insufficient_quota", "MODEL_PROVIDER_AUTHENTICATION", "MODEL_PROVIDER_PERMISSION", "MODEL_PROVIDER_INVALID_REQUEST", "MODEL_PROVIDER_NOT_FOUND", "MODEL_PROVIDER_QUOTA_EXHAUSTED", "TooManyRequestsError", "ServiceUnavailableError", "RequestTimeoutError", "UnauthorizedError", "ForbiddenError", "InternalServerError", "BadRequestError", "NotFoundError", "AuthenticationError", "PermissionDeniedError", "RateLimitError"];
6
+ export declare const MODEL_GATEWAY_ERROR_CODES: readonly ["rate_limit_error", "rate_limit_exceeded", "overloaded_error", "server_error", "api_error", "service_unavailable_error", "server_is_overloaded", "timeout_error", "MODEL_PROVIDER_RATE_LIMIT", "MODEL_PROVIDER_UNAVAILABLE", "invalid_request_error", "invalid_api_key", "authentication_error", "permission_error", "not_found_error", "request_too_large", "billing_error", "insufficient_quota", "MODEL_PROVIDER_AUTHENTICATION", "MODEL_PROVIDER_PERMISSION", "MODEL_PROVIDER_INVALID_REQUEST", "MODEL_PROVIDER_NOT_FOUND", "MODEL_PROVIDER_QUOTA_EXHAUSTED", "context_length_exceeded"];
7
+ export declare const MODEL_GATEWAY_ERROR_TYPES: readonly ["rate_limit_error", "rate_limit_exceeded", "overloaded_error", "server_error", "api_error", "service_unavailable_error", "server_is_overloaded", "timeout_error", "MODEL_PROVIDER_RATE_LIMIT", "MODEL_PROVIDER_UNAVAILABLE", "invalid_request_error", "invalid_api_key", "authentication_error", "permission_error", "not_found_error", "request_too_large", "billing_error", "insufficient_quota", "MODEL_PROVIDER_AUTHENTICATION", "MODEL_PROVIDER_PERMISSION", "MODEL_PROVIDER_INVALID_REQUEST", "MODEL_PROVIDER_NOT_FOUND", "MODEL_PROVIDER_QUOTA_EXHAUSTED", "TooManyRequestsError", "ServiceUnavailableError", "RequestTimeoutError", "UnauthorizedError", "ForbiddenError", "InternalServerError", "BadRequestError", "NotFoundError", "AuthenticationError", "PermissionDeniedError", "RateLimitError", "context_length_exceeded"];
8
+ export declare function isModelGatewayRequestId(value: unknown): value is string;
9
+ interface ModelGatewayDiagnostic {
10
+ code?: typeof MODEL_GATEWAY_ERROR_CODES[number] | number;
11
+ type?: typeof MODEL_GATEWAY_ERROR_TYPES[number];
12
+ requestId?: string;
13
+ }
6
14
  export interface ModelProviderErrorDiagnostic {
7
15
  category: 'rate_limit' | 'server_error' | 'request_timeout' | 'client_error' | 'invalid_response';
8
16
  fingerprint: string;
@@ -11,7 +19,7 @@ export interface ModelProviderErrorDiagnostic {
11
19
  status?: number;
12
20
  }
13
21
  export interface ModelFailureDiagnostic {
14
- contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2' | 'model-failure-diagnostic/v3';
22
+ contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2' | 'model-failure-diagnostic/v3' | 'model-failure-diagnostic/v4';
15
23
  protocol: 'openai-chat' | 'openai-responses' | 'anthropic-messages' | 'unknown';
16
24
  phase: 'binding' | 'request' | 'headers' | 'http-error' | 'stream' | 'buffered';
17
25
  code: typeof MODEL_FAILURE_CODES[number];
@@ -19,6 +27,7 @@ export interface ModelFailureDiagnostic {
19
27
  httpStatus?: number;
20
28
  /** Observational only. Raw error messages, headers and bodies are excluded. */
21
29
  providerError?: ModelProviderErrorDiagnostic;
30
+ gateway?: ModelGatewayDiagnostic;
22
31
  /** Observed counters only, never a replacement for the sealed billable usage. */
23
32
  usageConflict?: {
24
33
  previousFrameIndex: number;
@@ -33,3 +42,4 @@ export interface ModelUsageCounters {
33
42
  reasoningTokens?: number;
34
43
  }
35
44
  export declare function validateModelFailure(value: ModelFailureDiagnostic | undefined): void;
45
+ export {};
@@ -5,7 +5,7 @@ export const MODEL_FAILURE_CODES = [
5
5
  'http_server', 'http_rate_limit', 'http_timeout', 'protocol_invalid', 'json_invalid',
6
6
  'envelope_invalid', 'provider_error', 'identity_conflict', 'usage_invalid', 'usage_conflict',
7
7
  'choice_invalid', 'delta_invalid', 'termination_conflict', 'framing_invalid', 'body_limit',
8
- 'body_encoding', 'transport_error', 'stream_timeout', 'stream_incomplete', 'tool_payload_invalid',
8
+ 'body_encoding', 'transport_error', 'stream_timeout', 'stream_incomplete', 'tool_payload_invalid', 'reasoning_repetition',
9
9
  ];
10
10
  /** Closed provider identifiers only; arbitrary provider strings can contain credentials. */
11
11
  export const MODEL_PROVIDER_ERROR_CODES = Object.freeze([
@@ -22,6 +22,12 @@ export const MODEL_PROVIDER_ERROR_TYPES = Object.freeze([...MODEL_PROVIDER_ERROR
22
22
  'UnauthorizedError', 'ForbiddenError', 'InternalServerError', 'BadRequestError',
23
23
  'NotFoundError', 'AuthenticationError', 'PermissionDeniedError', 'RateLimitError',
24
24
  ]);
25
+ export const MODEL_GATEWAY_ERROR_CODES = Object.freeze([...MODEL_PROVIDER_ERROR_CODES, 'context_length_exceeded']);
26
+ export const MODEL_GATEWAY_ERROR_TYPES = Object.freeze([...MODEL_PROVIDER_ERROR_TYPES, 'context_length_exceeded']);
27
+ // Only structured correlation identifiers from the gateway are retained.
28
+ export function isModelGatewayRequestId(value) {
29
+ return typeof value === 'string' && value.length === 36 && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value);
30
+ }
25
31
  const usageCounterKeys = ['inputTokens', 'outputTokens', 'cachedInputTokens', 'reasoningTokens'];
26
32
  function validUsageCounters(value) {
27
33
  return Boolean(value && typeof value === 'object' && !Array.isArray(value)
@@ -32,10 +38,11 @@ function validUsageCounters(value) {
32
38
  export function validateModelFailure(value) {
33
39
  if (value === undefined)
34
40
  return;
35
- invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2', 'model-failure-diagnostic/v3'].includes(value.contract)
41
+ invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2', 'model-failure-diagnostic/v3', 'model-failure-diagnostic/v4'].includes(value.contract)
36
42
  && Object.keys(value).every(key => ['contract', 'protocol', 'phase', 'code', 'frameIndex', 'httpStatus',
37
43
  ...(value.contract === 'model-failure-diagnostic/v2' ? ['usageConflict'] : []),
38
- ...(value.contract === 'model-failure-diagnostic/v3' ? ['providerError'] : [])].includes(key))
44
+ ...(value.contract === 'model-failure-diagnostic/v3' ? ['providerError'] : []),
45
+ ...(value.contract === 'model-failure-diagnostic/v4' ? ['gateway'] : [])].includes(key))
39
46
  && ['openai-chat', 'openai-responses', 'anthropic-messages', 'unknown'].includes(value.protocol)
40
47
  && ['binding', 'request', 'headers', 'http-error', 'stream', 'buffered'].includes(value.phase)
41
48
  && MODEL_FAILURE_CODES.includes(value.code)
@@ -64,6 +71,17 @@ export function validateModelFailure(value) {
64
71
  && (provider.type === undefined || MODEL_PROVIDER_ERROR_TYPES.includes(provider.type))
65
72
  && (provider.status === undefined || Number.isInteger(provider.status) && provider.status >= 400 && provider.status <= 599), 'invalid_model_failure_diagnostic');
66
73
  }
74
+ if (value.contract === 'model-failure-diagnostic/v4') {
75
+ const gateway = value.gateway;
76
+ invariant(value.phase === 'http-error' && value.code.startsWith('http_') && gateway
77
+ && typeof gateway === 'object' && !Array.isArray(gateway) && Object.keys(gateway).length > 0
78
+ && Object.keys(gateway).every(key => ['code', 'type', 'requestId'].includes(key))
79
+ && (gateway.code === undefined || (typeof gateway.code === 'number'
80
+ ? Number.isInteger(gateway.code) && gateway.code >= 400 && gateway.code <= 599
81
+ : MODEL_GATEWAY_ERROR_CODES.includes(gateway.code)))
82
+ && (gateway.type === undefined || MODEL_GATEWAY_ERROR_TYPES.includes(gateway.type))
83
+ && (gateway.requestId === undefined || isModelGatewayRequestId(gateway.requestId)), 'invalid_model_failure_diagnostic');
84
+ }
67
85
  invariant(!value.code.startsWith('http_') || value.phase === 'http-error' && value.httpStatus !== undefined
68
86
  && (value.code === 'http_authentication' ? value.httpStatus === 401
69
87
  : value.code === 'http_permission' ? value.httpStatus === 403
@@ -4,7 +4,7 @@ import { admitSteering } from './task-contract.mjs';
4
4
  import { admitChildPromotion, unsettledChildren } from './child-runtime.mjs';
5
5
  import { guidanceReason } from './guidance.mjs';
6
6
  import { bindOperatorInput } from './anthropic-context.mjs';
7
- import { APPROVAL_OUTCOME_POLICY, normalizeHostApprovalOutcome, approvalOutcomePauseReason } from './approval-outcome.mjs';
7
+ import { APPROVAL_OUTCOME_POLICY, normalizeHostApprovalOutcome, approvalOutcomePauseReason, isApprovalDenialReason } from './approval-outcome.mjs';
8
8
  export function transition(snapshot, changes, facts = [], options = {}) {
9
9
  invariant(!terminal(snapshot.phase), 'terminal_immutable');
10
10
  const pendingGuidanceIds = changes.pendingGuidanceIds ?? snapshot.pendingGuidanceIds;
@@ -17,7 +17,8 @@ export function transition(snapshot, changes, facts = [], options = {}) {
17
17
  const diagnostics = changes.diagnostics ?? snapshot.diagnostics;
18
18
  facts = facts.map(fact => fact.kind === 'run.terminal' ? { ...fact, payload: { ...fact.payload,
19
19
  usageComplete: diagnostics.providerUsageIncomplete !== true && diagnostics.descendantUsageIncomplete !== true,
20
- ...(diagnostics.lastModelFailure && ['provider_terminal_error', 'provider_retryable_error_retry_exhausted', 'malformed_tool_call_retry_exhausted', 'model_policy_abort'].includes(String(fact.payload.reason))
20
+ ...(diagnostics.lastModelFailure && ['provider_terminal_error', 'provider_retryable_error_retry_exhausted', 'malformed_tool_call_retry_exhausted', 'model_policy_abort',
21
+ 'context_summary_provider_terminal_error', 'context_summary_retry_exhausted'].includes(String(fact.payload.reason))
21
22
  ? { modelFailure: copy(diagnostics.lastModelFailure) } : {}),
22
23
  } } : fact);
23
24
  const prefix = runKey(snapshot.scope, snapshot.runId);
@@ -33,7 +34,12 @@ export function transition(snapshot, changes, facts = [], options = {}) {
33
34
  export function prepareEffect(snapshot, kind, phase, payload, changes = {}) {
34
35
  invariant(snapshot.pendingIntent === null, 'effect_already_pending');
35
36
  const operationKey = `${runKey(snapshot.scope, snapshot.runId)}:effect:${snapshot.revision + 1}:${kind}`;
36
- return transition(snapshot, { ...changes, phase, pendingIntent: operationKey }, [{ kind: 'effect.prepared', payload: { operationKey, kind } }], { intents: [{ operationKey, kind, payload: copy(payload), status: 'prepared' }] });
37
+ const retry = kind === 'model' && (snapshot.reasoningStallRetry === true && payload.purpose !== 'compaction'
38
+ || snapshot.retryNotBefore > 0
39
+ && (payload.purpose === 'compaction' ? (snapshot.contextState?.compaction?.providerErrors ?? 0) > 0
40
+ || (snapshot.contextState?.compaction?.errors ?? 0) > 0 : snapshot.providerErrors > 0 || snapshot.modelErrors > 0));
41
+ return transition(snapshot, { ...changes, phase, pendingIntent: operationKey, ...(kind === 'model' ? { retryNotBefore: 0 } : {}) }, [{ kind: 'effect.prepared', payload: { operationKey, kind, ...(retry ? { retry: true } : {}),
42
+ ...(kind === 'model' && payload.purpose === 'compaction' ? { purpose: 'compaction' } : {}) } }], { intents: [{ operationKey, kind, payload: copy(payload), status: 'prepared' }] });
37
43
  }
38
44
  export function reduceCommand(snapshot, command, pending = null, bindings = {}) {
39
45
  if (snapshot.toolReconciliation && !['cancel', 'policy_revoked', 'pause', 'resume'].includes(command.kind)) {
@@ -162,6 +168,7 @@ export function reduceCommand(snapshot, command, pending = null, bindings = {})
162
168
  const pending = snapshot.pendingInteraction;
163
169
  const hasOutcome = Object.hasOwn(command.payload, 'approvalOutcome');
164
170
  const approvalOutcome = normalizeHostApprovalOutcome(command.payload.approvalOutcome);
171
+ const denialReason = command.payload.denialReason;
165
172
  if (snapshot.phase !== 'awaiting_interaction' || !pending || command.payload.interactionId !== pending.interactionId
166
173
  || command.payload.decision !== 'allow' && command.payload.decision !== 'deny')
167
174
  reason = 'interaction_mismatch';
@@ -169,6 +176,9 @@ export function reduceCommand(snapshot, command, pending = null, bindings = {})
169
176
  || approvalOutcome !== command.payload.approvalOutcome
170
177
  || (approvalOutcome === 'allowed-once') !== (command.payload.decision === 'allow')))
171
178
  reason = 'interaction_outcome_mismatch';
179
+ else if (Object.hasOwn(command.payload, 'denialReason') && (command.payload.decision !== 'deny'
180
+ || !isApprovalDenialReason(denialReason) || pending.approvalPolicy !== 'durable-preflight/v1'))
181
+ reason = 'interaction_denial_reason_mismatch';
172
182
  else {
173
183
  changes = { phase: snapshot.childApproval ? snapshot.resumePhase ?? 'preparing_context' : 'executing_tools',
174
184
  ...(snapshot.childApproval ? { resumePhase: null, childLifecycleCursor: null } : {}), pendingInteraction: null,
@@ -182,6 +192,7 @@ export function reduceCommand(snapshot, command, pending = null, bindings = {})
182
192
  if (pauseReason)
183
193
  Object.assign(changes, { resumePhase: changes.phase, phase: 'paused', reason: pauseReason, outcome: null });
184
194
  facts.push({ kind: 'approval.resolved', payload: { interactionId: pending.interactionId, callId: pending.callId, decision: command.payload.decision,
195
+ ...(isApprovalDenialReason(denialReason) ? { denialReason } : {}),
185
196
  ...(hasOutcome ? { approvalOutcome } : {}) } });
186
197
  }
187
198
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-core",
3
- "version": "0.0.19",
3
+ "version": "0.0.21",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Host-independent Native Harness contracts, transitions and durable execution.",
@@ -3,6 +3,10 @@
3
3
  * model or tool may claim in this vocabulary. */
4
4
  export type HostApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';
5
5
  export const APPROVAL_OUTCOME_POLICY = 'owner-outcome/v1' as const;
6
+ export function isApprovalDenialReason(value: unknown): value is 'approval_prompts_disabled' | 'approval_rejected' | 'approval_unavailable' | 'approval_cancelled' {
7
+ return value === 'approval_prompts_disabled' || value === 'approval_rejected'
8
+ || value === 'approval_unavailable' || value === 'approval_cancelled';
9
+ }
6
10
  export function normalizeHostApprovalOutcome(value: unknown): HostApprovalOutcome {
7
11
  return value === 'allowed-once' || value === 'rejected' || value === 'cancelled' ? value : 'unavailable';
8
12
  }
package/src/kernel.mts CHANGED
@@ -710,6 +710,13 @@ export class NativeKernel {
710
710
  const result = validateModelResult(raw as unknown as ModelResult);
711
711
  changes = reduceContextModel(snapshot, result, configuration,
712
712
  addUsage(snapshot.usage, { ...result.usage, modelCalls: 0, toolCalls: 0 }), this.now(), this.random());
713
+ if (result.failureDiagnostic || snapshot.diagnostics.lastModelFailure) changes.diagnostics = {
714
+ ...(changes.diagnostics ?? snapshot.diagnostics),
715
+ lastModelFailure: result.failureDiagnostic ? objectValue(result.failureDiagnostic) : null,
716
+ };
717
+ if (result.failureDiagnostic) facts.push({ kind: 'model.failure_observed', payload: objectValue(result.failureDiagnostic) });
718
+ if (changes.phase === 'paused' && changes.reason === 'provider_unavailable')
719
+ facts.push({ kind: 'model.retry_exhausted', payload: { reason: changes.reason } });
713
720
  facts.push({ kind: 'context.summary_completed', payload: { kind: result.kind, usage: objectValue(result.usage),
714
721
  messageCursor: snapshot.messages.length, usageReported: result.usageReported !== false,
715
722
  proposalAvailable: !!changes.contextState?.compaction?.proposal } });
@@ -739,6 +746,8 @@ export class NativeKernel {
739
746
  if (changes.candidate) changes.candidate = sealCandidate(changes.candidate, { ...snapshot, ...changes }, configuration, this.digest);
740
747
  if (result.transportObservation) facts.push({ kind: 'model.transport_observed', payload: objectValue(result.transportObservation) });
741
748
  if (result.failureDiagnostic) facts.push({ kind: 'model.failure_observed', payload: objectValue(result.failureDiagnostic) });
749
+ if (changes.phase === 'paused' && changes.reason === 'provider_unavailable')
750
+ facts.push({ kind: 'model.retry_exhausted', payload: { reason: changes.reason } });
742
751
  const rejectedDraft = configuration.contract.finalSubmissionSchema !== null && result.kind === 'final_candidate';
743
752
  const appended = changes.messages?.slice(snapshot.messages.length) ?? [];
744
753
  const assistantOffset = appended.findIndex(message => message.role === 'assistant');
@@ -756,6 +765,9 @@ export class NativeKernel {
756
765
  messageCursor: changes.messages?.length ?? snapshot.messages.length,
757
766
  usageReported: result.usageReported !== false,
758
767
  toolCalls: planning ? [] : result.toolCalls.map(objectValue), usage: objectValue(result.usage) } });
768
+ if (typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
769
+ facts.push({ kind: 'model.retry_scheduled', payload: { retryAt: Math.ceil(changes.retryNotBefore),
770
+ ...(result.failureDiagnostic ? { failure: objectValue(result.failureDiagnostic) } : {}) } });
759
771
  break;
760
772
  }
761
773
  case 'input':
@@ -1055,7 +1067,8 @@ export class NativeKernel {
1055
1067
  const profile = copy(configuration.profile);
1056
1068
  // Admission reserved the full allowance. Lowering the dispatched request
1057
1069
  // preserves that admission and the frozen Run profile.
1058
- if (!review && configuration.outputRecoveryPolicy === 'response-boundary/v4' && snapshot.reasoningStallRetry)
1070
+ if (!review && snapshot.reasoningStallRetry
1071
+ && ['response-boundary/v4', 'response-boundary/v5'].includes(configuration.outputRecoveryPolicy ?? ''))
1059
1072
  profile.maxOutputTokens = reasoningStallRetryTokens(profile.maxOutputTokens);
1060
1073
  const messages = review ? snapshot.preparedContext ? modelContextMessages(snapshot, this.digest) : this.policies.forRun(configuration).review.deliveryReviewMessages(snapshot)
1061
1074
  : configuration.profile.operatorGuidancePolicy === 'journaled-system/v1' ? modelContextMessages(snapshot, this.digest)
package/src/machine.mts CHANGED
@@ -291,7 +291,12 @@ export function validateModelResult(input: ModelResult): ModelResult {
291
291
  const result = copy(input);
292
292
  validateModelTransport(result.transportObservation);
293
293
  validateModelFailure(result.failureDiagnostic);
294
- invariant(!result.failureDiagnostic || ['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind),
294
+ const failure = result.failureDiagnostic;
295
+ invariant(!failure || ['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)
296
+ || result.kind === 'output_limit' && result.outputBoundary === 'no-visible-output/v1'
297
+ && failure.phase === 'stream' && failure.code === 'reasoning_repetition'
298
+ || result.kind === 'context_overflow' && failure.httpStatus === 400
299
+ && (failure.gateway?.code === 'context_length_exceeded' || failure.gateway?.type === 'context_length_exceeded'),
295
300
  'model_failure_diagnostic_requires_failure');
296
301
  invariant(['tool_calls', 'final_candidate', 'output_limit', 'context_overflow', 'empty_response', 'malformed_tool_call',
297
302
  'provider_retryable_error', 'provider_terminal_error', 'policy_abort', 'user_abort'].includes(result.kind)
@@ -350,7 +355,8 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
350
355
  // errors, malformed calls and context-overflow retries keep this input debt.
351
356
  if (snapshot.hookState && ['tool_calls', 'final_candidate', 'output_limit'].includes(result.kind)
352
357
  && (result.toolCalls.length > 0 || result.text.trim())) base.hookState = { ...currentHookState(snapshot), feedback: [] };
353
- const stalled = config.outputRecoveryPolicy === 'response-boundary/v4' && reasoningStall(result);
358
+ const stalled = config.outputRecoveryPolicy === 'response-boundary/v4' && reasoningStall(result)
359
+ || config.outputRecoveryPolicy === 'response-boundary/v5' && result.failureDiagnostic?.code === 'reasoning_repetition';
354
360
  // Keep the narrowed retry through transport errors and context preparation.
355
361
  // A sealed cutoff with text or an unfinished tool call uses the ordinary budget again.
356
362
  if (snapshot.reasoningStallRetry && (result.kind === 'tool_calls' || result.kind === 'final_candidate'
@@ -481,7 +487,7 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
481
487
  messages: [...snapshot.messages, { role: 'user',
482
488
  kind: suffix ? 'response_continuation_feedback' : 'output_limit_reasoning_observation',
483
489
  content: suffix ? 'Continue with only the missing text suffix now.'
484
- : 'The previous attempt spent its output budget on reasoning without taking action. Take the next useful tool action now, or answer directly if the task is complete.' }] };
490
+ : 'The previous response stopped during reasoning before taking action. Take the next useful tool action now, or answer directly if the task is complete.' }] };
485
491
  }
486
492
  if (snapshot.continuations >= continuationLimit) {
487
493
  // Committed answer text stays a suffix contract even when the first
@@ -6,7 +6,7 @@ export const MODEL_FAILURE_CODES = [
6
6
  'http_server', 'http_rate_limit', 'http_timeout', 'protocol_invalid', 'json_invalid',
7
7
  'envelope_invalid', 'provider_error', 'identity_conflict', 'usage_invalid', 'usage_conflict',
8
8
  'choice_invalid', 'delta_invalid', 'termination_conflict', 'framing_invalid', 'body_limit',
9
- 'body_encoding', 'transport_error', 'stream_timeout', 'stream_incomplete', 'tool_payload_invalid',
9
+ 'body_encoding', 'transport_error', 'stream_timeout', 'stream_incomplete', 'tool_payload_invalid', 'reasoning_repetition',
10
10
  ] as const;
11
11
  /** Closed provider identifiers only; arbitrary provider strings can contain credentials. */
12
12
  export const MODEL_PROVIDER_ERROR_CODES = Object.freeze([
@@ -23,6 +23,17 @@ export const MODEL_PROVIDER_ERROR_TYPES = Object.freeze([...MODEL_PROVIDER_ERROR
23
23
  'UnauthorizedError', 'ForbiddenError', 'InternalServerError', 'BadRequestError',
24
24
  'NotFoundError', 'AuthenticationError', 'PermissionDeniedError', 'RateLimitError',
25
25
  ] as const);
26
+ export const MODEL_GATEWAY_ERROR_CODES = Object.freeze([...MODEL_PROVIDER_ERROR_CODES, 'context_length_exceeded'] as const);
27
+ export const MODEL_GATEWAY_ERROR_TYPES = Object.freeze([...MODEL_PROVIDER_ERROR_TYPES, 'context_length_exceeded'] as const);
28
+ // Only structured correlation identifiers from the gateway are retained.
29
+ export function isModelGatewayRequestId(value: unknown): value is string {
30
+ return typeof value === 'string' && value.length === 36 && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value);
31
+ }
32
+ interface ModelGatewayDiagnostic {
33
+ code?: typeof MODEL_GATEWAY_ERROR_CODES[number] | number;
34
+ type?: typeof MODEL_GATEWAY_ERROR_TYPES[number];
35
+ requestId?: string;
36
+ }
26
37
  export interface ModelProviderErrorDiagnostic {
27
38
  category: 'rate_limit' | 'server_error' | 'request_timeout' | 'client_error' | 'invalid_response';
28
39
  fingerprint: string;
@@ -31,7 +42,7 @@ export interface ModelProviderErrorDiagnostic {
31
42
  status?: number;
32
43
  }
33
44
  export interface ModelFailureDiagnostic {
34
- contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2' | 'model-failure-diagnostic/v3';
45
+ contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2' | 'model-failure-diagnostic/v3' | 'model-failure-diagnostic/v4';
35
46
  protocol: 'openai-chat' | 'openai-responses' | 'anthropic-messages' | 'unknown';
36
47
  phase: 'binding' | 'request' | 'headers' | 'http-error' | 'stream' | 'buffered';
37
48
  code: typeof MODEL_FAILURE_CODES[number];
@@ -39,6 +50,7 @@ export interface ModelFailureDiagnostic {
39
50
  httpStatus?: number;
40
51
  /** Observational only. Raw error messages, headers and bodies are excluded. */
41
52
  providerError?: ModelProviderErrorDiagnostic;
53
+ gateway?: ModelGatewayDiagnostic;
42
54
  /** Observed counters only, never a replacement for the sealed billable usage. */
43
55
  usageConflict?: {
44
56
  previousFrameIndex: number;
@@ -61,10 +73,11 @@ function validUsageCounters(value: ModelUsageCounters): boolean {
61
73
  }
62
74
  export function validateModelFailure(value: ModelFailureDiagnostic | undefined): void {
63
75
  if (value === undefined) return;
64
- invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2', 'model-failure-diagnostic/v3'].includes(value.contract)
76
+ invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2', 'model-failure-diagnostic/v3', 'model-failure-diagnostic/v4'].includes(value.contract)
65
77
  && Object.keys(value).every(key => ['contract', 'protocol', 'phase', 'code', 'frameIndex', 'httpStatus',
66
78
  ...(value.contract === 'model-failure-diagnostic/v2' ? ['usageConflict'] : []),
67
- ...(value.contract === 'model-failure-diagnostic/v3' ? ['providerError'] : [])].includes(key))
79
+ ...(value.contract === 'model-failure-diagnostic/v3' ? ['providerError'] : []),
80
+ ...(value.contract === 'model-failure-diagnostic/v4' ? ['gateway'] : [])].includes(key))
68
81
  && ['openai-chat', 'openai-responses', 'anthropic-messages', 'unknown'].includes(value.protocol)
69
82
  && ['binding', 'request', 'headers', 'http-error', 'stream', 'buffered'].includes(value.phase)
70
83
  && MODEL_FAILURE_CODES.includes(value.code)
@@ -94,6 +107,17 @@ export function validateModelFailure(value: ModelFailureDiagnostic | undefined):
94
107
  && (provider.status === undefined || Number.isInteger(provider.status) && provider.status >= 400 && provider.status <= 599),
95
108
  'invalid_model_failure_diagnostic');
96
109
  }
110
+ if (value.contract === 'model-failure-diagnostic/v4') {
111
+ const gateway = value.gateway;
112
+ invariant(value.phase === 'http-error' && value.code.startsWith('http_') && gateway
113
+ && typeof gateway === 'object' && !Array.isArray(gateway) && Object.keys(gateway).length > 0
114
+ && Object.keys(gateway).every(key => ['code', 'type', 'requestId'].includes(key))
115
+ && (gateway.code === undefined || (typeof gateway.code === 'number'
116
+ ? Number.isInteger(gateway.code) && gateway.code >= 400 && gateway.code <= 599
117
+ : MODEL_GATEWAY_ERROR_CODES.includes(gateway.code)))
118
+ && (gateway.type === undefined || MODEL_GATEWAY_ERROR_TYPES.includes(gateway.type))
119
+ && (gateway.requestId === undefined || isModelGatewayRequestId(gateway.requestId)), 'invalid_model_failure_diagnostic');
120
+ }
97
121
  invariant(!value.code.startsWith('http_') || value.phase === 'http-error' && value.httpStatus !== undefined
98
122
  && (value.code === 'http_authentication' ? value.httpStatus === 401
99
123
  : value.code === 'http_permission' ? value.httpStatus === 403
@@ -6,7 +6,7 @@ import type { SteeringBindings } from './task-contract.mjs';
6
6
  import { admitChildPromotion, unsettledChildren } from './child-runtime.mjs';
7
7
  import { guidanceReason } from './guidance.mjs';
8
8
  import { bindOperatorInput } from './anthropic-context.mjs';
9
- import { APPROVAL_OUTCOME_POLICY, normalizeHostApprovalOutcome, approvalOutcomePauseReason } from './approval-outcome.mjs';
9
+ import { APPROVAL_OUTCOME_POLICY, normalizeHostApprovalOutcome, approvalOutcomePauseReason, isApprovalDenialReason } from './approval-outcome.mjs';
10
10
 
11
11
  export function transition(snapshot: RunSnapshot, changes: Partial<RunSnapshot>, facts: { kind: string; payload: ObjectValue }[] = [],
12
12
  options: { intents?: EffectIntent[]; receipts?: EffectReceipt[]; commandId?: string; requireNoPendingCommands?: boolean } = {}): CommitBatch {
@@ -21,7 +21,8 @@ export function transition(snapshot: RunSnapshot, changes: Partial<RunSnapshot>,
21
21
  const diagnostics = changes.diagnostics ?? snapshot.diagnostics;
22
22
  facts = facts.map(fact => fact.kind === 'run.terminal' ? { ...fact, payload: { ...fact.payload,
23
23
  usageComplete: diagnostics.providerUsageIncomplete !== true && diagnostics.descendantUsageIncomplete !== true,
24
- ...(diagnostics.lastModelFailure && ['provider_terminal_error', 'provider_retryable_error_retry_exhausted', 'malformed_tool_call_retry_exhausted', 'model_policy_abort'].includes(String(fact.payload.reason))
24
+ ...(diagnostics.lastModelFailure && ['provider_terminal_error', 'provider_retryable_error_retry_exhausted', 'malformed_tool_call_retry_exhausted', 'model_policy_abort',
25
+ 'context_summary_provider_terminal_error', 'context_summary_retry_exhausted'].includes(String(fact.payload.reason))
25
26
  ? { modelFailure: copy(diagnostics.lastModelFailure) } : {}),
26
27
  } } : fact);
27
28
  const prefix = runKey(snapshot.scope, snapshot.runId);
@@ -38,8 +39,13 @@ export function prepareEffect(snapshot: RunSnapshot, kind: EffectKind, phase: Ph
38
39
  changes: Partial<RunSnapshot> = {}): CommitBatch {
39
40
  invariant(snapshot.pendingIntent === null, 'effect_already_pending');
40
41
  const operationKey = `${runKey(snapshot.scope, snapshot.runId)}:effect:${snapshot.revision + 1}:${kind}`;
41
- return transition(snapshot, { ...changes, phase, pendingIntent: operationKey },
42
- [{ kind: 'effect.prepared', payload: { operationKey, kind } }],
42
+ const retry = kind === 'model' && (snapshot.reasoningStallRetry === true && payload.purpose !== 'compaction'
43
+ || snapshot.retryNotBefore > 0
44
+ && (payload.purpose === 'compaction' ? (snapshot.contextState?.compaction?.providerErrors ?? 0) > 0
45
+ || (snapshot.contextState?.compaction?.errors ?? 0) > 0 : snapshot.providerErrors > 0 || snapshot.modelErrors > 0));
46
+ return transition(snapshot, { ...changes, phase, pendingIntent: operationKey, ...(kind === 'model' ? { retryNotBefore: 0 } : {}) },
47
+ [{ kind: 'effect.prepared', payload: { operationKey, kind, ...(retry ? { retry: true } : {}),
48
+ ...(kind === 'model' && payload.purpose === 'compaction' ? { purpose: 'compaction' } : {}) } }],
43
49
  { intents: [{ operationKey, kind, payload: copy(payload), status: 'prepared' }] });
44
50
  }
45
51
  export function reduceCommand(snapshot: RunSnapshot, command: RunCommand, pending: EffectIntent | null = null,
@@ -157,11 +163,15 @@ export function reduceCommand(snapshot: RunSnapshot, command: RunCommand, pendin
157
163
  const pending = snapshot.pendingInteraction;
158
164
  const hasOutcome = Object.hasOwn(command.payload, 'approvalOutcome');
159
165
  const approvalOutcome = normalizeHostApprovalOutcome(command.payload.approvalOutcome);
166
+ const denialReason = command.payload.denialReason;
160
167
  if (snapshot.phase !== 'awaiting_interaction' || !pending || command.payload.interactionId !== pending.interactionId
161
168
  || command.payload.decision !== 'allow' && command.payload.decision !== 'deny') reason = 'interaction_mismatch';
162
169
  else if (hasOutcome && (bindings.configuration?.approvalOutcomePolicy !== APPROVAL_OUTCOME_POLICY
163
170
  || approvalOutcome !== command.payload.approvalOutcome
164
171
  || (approvalOutcome === 'allowed-once') !== (command.payload.decision === 'allow'))) reason = 'interaction_outcome_mismatch';
172
+ else if (Object.hasOwn(command.payload, 'denialReason') && (command.payload.decision !== 'deny'
173
+ || !isApprovalDenialReason(denialReason) || pending.approvalPolicy !== 'durable-preflight/v1'))
174
+ reason = 'interaction_denial_reason_mismatch';
165
175
  else {
166
176
  changes = { phase: snapshot.childApproval ? snapshot.resumePhase ?? 'preparing_context' : 'executing_tools',
167
177
  ...(snapshot.childApproval ? { resumePhase: null, childLifecycleCursor: null } : {}), pendingInteraction: null,
@@ -174,6 +184,7 @@ export function reduceCommand(snapshot: RunSnapshot, command: RunCommand, pendin
174
184
  const pauseReason = hasOutcome && !bindings.configuration?.childOwnerBinding ? approvalOutcomePauseReason(approvalOutcome) : null;
175
185
  if (pauseReason) Object.assign(changes, { resumePhase: changes.phase, phase: 'paused', reason: pauseReason, outcome: null });
176
186
  facts.push({ kind: 'approval.resolved', payload: { interactionId: pending.interactionId, callId: pending.callId, decision: command.payload.decision,
187
+ ...(isApprovalDenialReason(denialReason) ? { denialReason } : {}),
177
188
  ...(hasOutcome ? { approvalOutcome } : {}) } });
178
189
  }
179
190
  break;