@kingsoftcloud/agentkit-harness-node 0.0.13 → 0.0.14

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.
@@ -1,4 +1,35 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { canonical } from '@kingsoftcloud/agentkit-harness-core';
3
+
4
+ const settledCommandStates = new Set(['completed', 'failed', 'canceled', 'timed_out', 'output_limit']);
5
+
6
+ /** Project a committed retry deadline at the Host's current time. This is a
7
+ * display fact only; it cannot schedule, resume or extend a model request. */
8
+ export function nativeModelRetryWait(snapshot, { driving = false, now = Date.now() } = {}) {
9
+ if (!driving || !snapshot || !['preparing_context', 'compacting'].includes(snapshot.phase)
10
+ || snapshot.pendingIntent !== null || !Number.isFinite(now)
11
+ || !Number.isFinite(snapshot.retryNotBefore) || snapshot.retryNotBefore <= now) return null;
12
+ return { contract: 'agentkit.native-model-retry-wait/v1', notBefore: snapshot.retryNotBefore };
13
+ }
14
+
15
+ /** A completed foreground launch has no later background notification. Its
16
+ * exact committed launch receipt is already a lifecycle fact, not a liveness
17
+ * guess from a task ID, a notified bit or model-visible output text. */
18
+ function foregroundReceiptState(record, ref, intent) {
19
+ if (ref.sourceRunId !== record.snapshot.runId || intent?.kind !== 'tool'
20
+ || intent.payload.calls?.length !== 1) return null;
21
+ const definition = record.configuration?.tools.find(tool => tool.name === intent.payload.calls[0].name);
22
+ if (definition?.backgroundCommandPolicy !== 'owned-command-launch/v1') return null;
23
+ const receipt = record.receipts?.find(row => row.operationKey === ref.operationKey);
24
+ const results = receipt?.result?.results;
25
+ const result = results?.length === 1 ? results[0] : null;
26
+ if (receipt?.status !== 'committed' || result?.status !== 'ok'
27
+ || result.backgroundCommandFinished !== true || !result.backgroundCommandRef
28
+ || canonical(result.backgroundCommandRef) !== canonical(ref)
29
+ || result.content?.task_id !== ref.taskId || result.content.evidence_incomplete === true
30
+ || !settledCommandStates.has(result.content.status)) return null;
31
+ return result.content.status;
32
+ }
2
33
 
3
34
  /** Content and lifecycle facts from committed task state; no control authority. */
4
35
  export function nativeActivityStatus(record, { driving = false } = {}) {
@@ -20,7 +51,7 @@ export function nativeActivityStatus(record, { driving = false } = {}) {
20
51
  const call = calls.length === 1 ? calls[0] : null;
21
52
  return { id: ref.taskId, runId: snapshot.runId,
22
53
  title: call?.arguments.command?.slice(0, 512) || ref.taskId,
23
- state: observed?.status ?? 'unknown', canCancel: false };
54
+ state: observed?.status ?? foregroundReceiptState(record, ref, intent) ?? 'unknown', canCancel: false };
24
55
  });
25
56
  return { contract: 'agentkit.native-activity-status/v1', runId: snapshot.runId, snapshotRevision: snapshot.revision,
26
57
  isRunning: driving, plan: todos.length ? { items,
@@ -1,3 +1,4 @@
1
+ import { validateConversationPresentation, conversationPresentationInstructions } from './conversation-presentation.mjs';
1
2
  import { createHash } from 'node:crypto';
2
3
  import { canonical, configure, invariant, submissionOutputFormat, artifactToolDefinitions, isArtifactTool, toolDiscoveryDefinitions,
3
4
  TOOL_SEARCH, DEFERRED_TOOL_CALL, TODO_READ, TODO_WRITE, RESPOND_TO_COORDINATOR, CHILD_TASK_POLICY,
@@ -13,7 +14,7 @@ import { nativeA2aToolDefinitions } from '@kingsoftcloud/agentkit-harness-node/n
13
14
  import { NATIVE_CHILD_WORKSPACE_TOOLS, NATIVE_CHILD_COMMAND_TOOLS } from './child-workspace-tools.mjs';
14
15
  import { validChildCommandResource } from './child-command-resource.mjs';
15
16
  import { CHILD_CAPABILITY_POLICY, admitChildCapabilities } from './child-capabilities.mjs';
16
- import { createNativeWorkspaceInstructions } from './workspace-instructions.mjs';
17
+ import { createNativeWorkspaceInstructions, nativeWorkspaceInstructionTimeoutRecovery } from './workspace-instructions.mjs';
17
18
  import { nativeWorkspaceContextBinding, validateNativeWorkspaceContext } from './workspace-context.mjs';
18
19
  import { nativeInstructionTouches } from './instruction-context.mjs';
19
20
 
@@ -110,8 +111,8 @@ export function nativeChildRoles(spec = {}, { childAllocationPolicy } = {}) {
110
111
  }
111
112
 
112
113
  /** Bind every child to a declared role and its own scoped tool state. */
113
- export async function createNativeChildren({ roles, scope, sessionId, store, tools, hasSkills, hasMcp, mcpBinding, skillBinding, skillInstructions, workspaceContext,
114
- resolveModel, bindTools, verificationFactory, fileWorkspaces, commandResource, isClosed, onStream, a2aBinding, waitForChildReceipt, mediaSources = new Map(), artifactPolicy, artifactFactory, sourceReadPolicy, childTaskPolicy, childPlanPolicy, childAllocationPolicy, childCapabilityPolicy, outputRecoveryPolicy, toolExecutionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }) }) {
114
+ export async function createNativeChildren({ roles, scope, sessionId, store, tools, hasSkills, hasMcp, mcpBinding, skillBinding, skillInstructions, workspaceContext, instructionTimeoutRecovery,
115
+ resolveModel, bindTools, verificationFactory, fileWorkspaces, commandResource, isClosed, onStream, a2aBinding, waitForChildReceipt, mediaSources = new Map(), artifactPolicy, artifactFactory, sourceReadPolicy, childTaskPolicy, childPlanPolicy, childAllocationPolicy, childCapabilityPolicy, outputRecoveryPolicy, outputRestartPolicy, conversationPresentation, toolExecutionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }) }) {
115
116
  if (!roles.length) return null;
116
117
  if (workspaceContext !== undefined) {
117
118
  validateNativeWorkspaceContext(workspaceContext);
@@ -123,6 +124,8 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
123
124
  invariant(toolExecutionPolicy === undefined || toolExecutionPolicy === 'owner-execution/v1', 'studio_native_child_execution_policy_invalid');
124
125
  invariant(providerRecoveryPolicy === undefined || providerRecoveryPolicy === 'provider-recovery/v2', 'native_child_provider_recovery_policy_invalid');
125
126
  invariant(outputRecoveryPolicy === undefined || outputRecoveryPolicy === 'response-boundary/v2', 'studio_native_child_output_policy_invalid');
127
+ invariant(outputRestartPolicy === undefined || outputRestartPolicy === 'per-response/v1' && outputRecoveryPolicy === 'response-boundary/v2', 'native_child_output_restart_policy_invalid');
128
+ if (conversationPresentation !== undefined) validateConversationPresentation(conversationPresentation);
126
129
  invariant(childTaskPolicy === undefined || childTaskPolicy === CHILD_TASK_POLICY, 'studio_native_child_task_policy_invalid');
127
130
  invariant(childPlanPolicy === undefined || childPlanPolicy === CHILD_PLAN_POLICY, 'studio_native_child_plan_policy_invalid');
128
131
  invariant(artifactPolicy == null || artifactPolicy === 'runtime-artifacts/v1' && typeof artifactFactory === 'function',
@@ -219,12 +222,15 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
219
222
  : workspaceContext ? nativeWorkspaceContextBinding(isolated?.root ?? workspaceContext.workspaceRoot,
220
223
  { instructionRoots: workspaceContext.instructionSource.globalRoots }) : undefined;
221
224
  validateInstructionWorkspace(childContext, isolated, workspaceContext);
222
- const instructionSource = childContext ? createNativeWorkspaceInstructions(childContext) : null;
225
+ const instructionSource = childContext ? createNativeWorkspaceInstructions(childContext, { timeoutRecovery: source
226
+ ? nativeWorkspaceInstructionTimeoutRecovery(source.configuration) : instructionTimeoutRecovery }) : null;
223
227
  const executionResource = bound.commandResource ? { ...bound.commandResource, workspaceBindingDigest: hash(isolated.binding) } : undefined;
224
228
  invariant(!source || canonical(source.configuration.hostRecoveryBinding?.childExecutionResource ?? null) === canonical(executionResource ?? null),
225
229
  'studio_native_child_command_resource_changed');
226
230
  const hostBindingDigest = hash({ contract: STUDIO_NATIVE_CHILD_CONTRACT, role, profile: bound.model.profile, scope: child, tools: bound.tools,
227
231
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
232
+ ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
233
+ ...(conversationPresentation ? { conversationPresentation } : {}),
228
234
  ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
229
235
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
230
236
  ...(childPlanPolicy ? { childPlanPolicy } : {}),
@@ -256,6 +262,7 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
256
262
  supportsImages: bound.model.supportsImages, tools: bound.tools }) } : {}),
257
263
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
258
264
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
265
+ ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
259
266
  ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
260
267
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
261
268
  ...(executionResource ? { backgroundNotificationPolicy: 'completed-before-model/v1' } : {}),
@@ -265,7 +272,7 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
265
272
  ...(sourceReadPolicy ? { sourceReadPolicy } : {}),
266
273
  guidancePolicy: 'boundary-guide/v1',
267
274
  ...(media.length ? { inputMessages: [{ role: 'user', kind: 'user_input', content: request.task, media }] } : {}),
268
- instructions: [role.instructions, ...(childSkills ? [skillInstructions] : [])].filter(Boolean).join('\n\n'), contract, tools: bound.tools,
275
+ instructions: [conversationPresentationInstructions(conversationPresentation), role.instructions, ...(childSkills ? [skillInstructions] : [])].filter(Boolean).join('\n\n'), contract, tools: bound.tools,
269
276
  modelRecoveryPolicy: bound.model.modelRecoveryPolicy ?? 'manual',
270
277
  ...(isolated || childSkills || childContext ? { hostRecoveryBinding: {
271
278
  ...(childContext ? { workspaceContext: childContext } : {}),
@@ -300,7 +307,8 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
300
307
  'studio_native_child_workspace_binding_changed');
301
308
  const childContext = configuration.hostRecoveryBinding?.workspaceContext;
302
309
  validateInstructionWorkspace(childContext, isolated, workspaceContext);
303
- const instructionSource = childContext ? createNativeWorkspaceInstructions(childContext) : null;
310
+ const instructionSource = childContext ? createNativeWorkspaceInstructions(childContext,
311
+ { timeoutRecovery: nativeWorkspaceInstructionTimeoutRecovery(configuration) }) : null;
304
312
  const executionResource = bound?.commandResource ? { ...bound.commandResource, workspaceBindingDigest: hash(isolated.binding) } : undefined;
305
313
  invariant(canonical(configuration.hostRecoveryBinding?.childExecutionResource ?? null) === canonical(executionResource ?? null)
306
314
  && configuration.backgroundNotificationPolicy === (executionResource ? 'completed-before-model/v1' : undefined),
@@ -312,6 +320,7 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
312
320
  hostBindingDigest: configuration.hostBindingDigest }).profile;
313
321
  invariant(bound && role && canonical(configuration.tools) === canonical(bound.tools)
314
322
  && configuration.outputRecoveryPolicy === outputRecoveryPolicy
323
+ && configuration.outputRestartPolicy === outputRestartPolicy
315
324
  && configuration.providerRecoveryPolicy === providerRecoveryPolicy
316
325
  && configuration.toolExecutionPolicy === toolExecutionPolicy
317
326
  && configuration.inputPolicy === (instructionSource ? 'before-first-model/v1' : undefined)
@@ -333,7 +342,9 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
333
342
  && configuration.hostBindingDigest === hash({ contract: STUDIO_NATIVE_CHILD_CONTRACT, role,
334
343
  profile: bound.model.profile, scope: childScope(role), tools: bound.tools,
335
344
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
336
- ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
345
+ ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
346
+ ...(conversationPresentation ? { conversationPresentation } : {}),
347
+ ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
337
348
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
338
349
  ...(childPlanPolicy ? { childPlanPolicy } : {}),
339
350
  ...(childTaskPolicy ? { childTaskPolicy } : {}),
@@ -0,0 +1,31 @@
1
+ import { invariant } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ const LANGUAGES = { 'zh-CN': '简体中文', en: 'English', ja: 'Japanese', ko: 'Korean' };
4
+
5
+ /** A presentation preference inferred from user prose, never an authority or a
6
+ * translation of model reasoning. Freeze it once and pass it to child owners. */
7
+ export function admitConversationPresentation({ objective = '', locale } = {}) {
8
+ // An unknown language is not an English preference. Preserve the model's
9
+ // existing user-language behavior when this small script detector cannot
10
+ // establish a preference, including unsupported explicit locales.
11
+ if (locale !== undefined && !Object.hasOwn(LANGUAGES, locale)) return undefined;
12
+ const prose = String(objective).replace(/```[^]*?```/g, '').replace(/`[^`]*`/g, '').slice(0, 8000);
13
+ const selected = locale && Object.hasOwn(LANGUAGES, locale) ? locale
14
+ : /[\u3040-\u30ff]/u.test(prose) ? 'ja' : /[\uac00-\ud7af]/u.test(prose) ? 'ko'
15
+ : /\p{Script=Han}/u.test(prose) ? 'zh-CN' : undefined;
16
+ return selected ? { contract: 'agentkit.conversation-presentation/v1', language: selected } : undefined;
17
+ }
18
+
19
+ export function validateConversationPresentation(value) {
20
+ invariant(value && Object.keys(value).sort().join(',') === 'contract,language'
21
+ && value.contract === 'agentkit.conversation-presentation/v1' && Object.hasOwn(LANGUAGES, value.language),
22
+ 'native_conversation_presentation_invalid');
23
+ return { ...value };
24
+ }
25
+
26
+ export function conversationPresentationInstructions(value) {
27
+ if (value === undefined) return '';
28
+ const { language } = validateConversationPresentation(value);
29
+ if (language === 'zh-CN') return '会话展示语言:简体中文。面向用户的进度说明、任务清单(包括 TodoWrite 的 content)、子任务汇报和最终答复使用简体中文。用户最新消息中明确指定的语言要求优先。代码、命令、路径、产品名和原文引用保留原样。这项要求只约束公开输出,不要求展示内部推理。';
30
+ return `Conversation presentation language: ${LANGUAGES[language]}. Use it for public progress updates, task-list content, child-task reports and final answers. An explicit language request in the latest user message takes precedence. Preserve code, commands, paths, product names and quotations. This governs public output, not private reasoning.`;
31
+ }
@@ -4,6 +4,7 @@ import { basename, dirname, extname, isAbsolute, join, resolve, sep } from 'node
4
4
  import { homedir } from 'node:os';
5
5
  import { Workspace, PositionEncoding } from '@astral-sh/ruff-wasm-nodejs';
6
6
  import { NATIVE_PYTHON_SYNTAX } from './python-syntax.mjs';
7
+ import { assertPythonGrammar } from './python-grammar.mjs';
7
8
  import { LOCAL_COMMAND_POLICY } from './local-command-policy.mjs';
8
9
  import { analyzeShellSource } from './shell-analysis.mjs';
9
10
  import { decodeRuffAst, ruffIdentifier, ruffNodes, ruffString, unwrapRuff } from './ruff-ast.mjs';
@@ -123,7 +124,7 @@ function checkPython(source, path, depth) {
123
124
  limited(depth); if (Buffer.byteLength(source) > 2 * 1024 * 1024) throw Error('command_policy_source_limit');
124
125
  let wire;
125
126
  try {
126
- parser.comments(source); // Grammar only, matching ast.parse rather than compile.
127
+ assertPythonGrammar(parser, source);
127
128
  if (parser.check(source).some(item => / on Python 3\.12 \(syntax was added in Python 3\.\d+\)$/.test(item.message))) return null;
128
129
  wire = parser.parse(source);
129
130
  } catch (error) {
@@ -250,7 +250,12 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
250
250
  task_id: handle.commandId, ...output(observed), process_timeout_seconds: readRecord(handle.directory, store.owner, handle.commandId).timeoutMs / 1000,
251
251
  ...(!args.background ? { command, controls: readRecord(handle.directory, store.owner, handle.commandId).controls ?? null } : {}),
252
252
  instruction: 'Use read_command_output with task_id; stop_command cancels this task only. Do not relaunch unknown outcomes.' },
253
- ...(args.background ? { launchedCommand: { taskId: handle.commandId, operationKey } } : {}) };
253
+ // Persisted foreground output advertises the same cursor capability as
254
+ // a background launch. Commit its owner too: a task_id in model-facing
255
+ // content alone cannot authorize read_command_output after this step.
256
+ ...(args.background || outPolicy ? { launchedCommand: { taskId: handle.commandId, operationKey } } : {}),
257
+ ...(!args.background && outPolicy && !uncertain && TERMINAL.has(observed.status)
258
+ ? { backgroundCommandFinished: true } : {}) };
254
259
  } else {
255
260
  dispatched = true;
256
261
  const result = await runBoundedProcess({ argv: shellCommandArgv(command, LOCAL_COMMAND_SHELL), cwd, env, settings: policy, signal: request.signal,
@@ -281,8 +281,13 @@ export function parseAnthropicBuffered(bodyText, request, { captureReplay = fals
281
281
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
282
282
  throw new ProtocolError('invalid response envelope', 'envelope_invalid');
283
283
  }
284
+ if ('error' in payload) {
285
+ if (payload.type !== 'error') throw new ProtocolError('conflicting error envelope', 'envelope_invalid');
286
+ throw Object.assign(new ProtocolError('provider rejected generation', 'provider_error'), {
287
+ streamError: classifyAnthropicStreamError(payload.error),
288
+ });
289
+ }
284
290
  if ('type' in payload && payload.type !== 'message') throw new ProtocolError('invalid response envelope', 'envelope_invalid');
285
- if ('error' in payload) throw new ProtocolError('invalid response envelope', 'envelope_invalid');
286
291
  if (typeof payload.stop_sequence !== 'undefined' && payload.stop_sequence !== null && typeof payload.stop_sequence !== 'string') {
287
292
  throw new ProtocolError('invalid stop_sequence');
288
293
  }
@@ -15,6 +15,7 @@ import { sealModelReplay, openAIReplayFields } from './model-replay.mjs';
15
15
  import { validateMediaBlock, projectMediaOpenAI, MediaError } from './model-media.mjs';
16
16
  import { inlineReasoningMarker, projectInlineReasoning, createInlineReasoningProjector } from './model-inline-reasoning.mjs';
17
17
  import { applyProviderChatCompatibility, resolveProviderCompatibility } from './model-provider-compat.mjs';
18
+ import { classifyOpenAIProviderError } from './model-provider-error.mjs';
18
19
  import { mergeChatUsage } from './model-chat-usage.mjs';
19
20
  // parseModelJson is the kernel's strict finite JSON parser: it rejects
20
21
  // duplicate object keys and non-finite numbers (e.g. 1e400). Using it here keeps
@@ -209,7 +210,14 @@ export function parseOpenAIBuffered(bodyText, request, { captureReplay = false,
209
210
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
210
211
  throw new ProtocolError('invalid response envelope', 'envelope_invalid');
211
212
  }
212
- if ('error' in payload) throw new ProtocolError('invalid response envelope', 'provider_error');
213
+ if ('error' in payload) {
214
+ if (payload.choices != null && (!Array.isArray(payload.choices) || payload.choices.length)) {
215
+ throw new ProtocolError('conflicting error envelope', 'envelope_invalid');
216
+ }
217
+ throw Object.assign(new ProtocolError('provider rejected generation', 'provider_error'), {
218
+ streamError: classifyOpenAIProviderError(payload.error),
219
+ });
220
+ }
213
221
  const choices = payload.choices;
214
222
  if (!Array.isArray(choices) || choices.length > 1) {
215
223
  throw new ProtocolError('expected one completion choice', 'choice_invalid');
@@ -372,7 +380,14 @@ export function createOpenAIStreamTurn(profile, binding) {
372
380
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
373
381
  throw new ProtocolError('invalid stream envelope', 'envelope_invalid');
374
382
  }
375
- if ('error' in payload) throw new ProtocolError('invalid stream envelope', 'provider_error');
383
+ if ('error' in payload) {
384
+ if (payload.choices != null && (!Array.isArray(payload.choices) || payload.choices.length)) {
385
+ throw new ProtocolError('conflicting error envelope', 'envelope_invalid');
386
+ }
387
+ throw Object.assign(new ProtocolError('provider rejected generation', 'provider_error'), {
388
+ streamError: classifyOpenAIProviderError(payload.error),
389
+ });
390
+ }
376
391
  if (payload.id != null) {
377
392
  if (typeof payload.id !== 'string' || !payload.id) throw new ProtocolError('invalid completion ID', 'identity_conflict');
378
393
  if (this.completionId != null && payload.id !== this.completionId) {
@@ -203,7 +203,7 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
203
203
  return failed(state.finalize({ errorKind: 'provider_terminal_error', failureKind: 'invalid_response' }), protocolCode(error));
204
204
  }
205
205
  if (error instanceof ProtocolError) {
206
- // An Anthropic in-stream `error` event carries its own classification.
206
+ // Typed provider error envelopes carry a closed, credential-free classification.
207
207
  if (error.streamError) {
208
208
  return failed(state.finalize({ errorKind: error.streamError.kind, failureKind: error.streamError.failureKind }), 'provider_error');
209
209
  }
@@ -237,6 +237,10 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
237
237
  }
238
238
  return withFailure(parseOpenAIBuffered(bodyText, request, { captureReplay, binding, onThinking }), binding, 'buffered', 'protocol_invalid');
239
239
  } catch (error) {
240
+ if (error instanceof ProtocolError && error.streamError) {
241
+ const result = { ...terminalResult(error.streamError.failureKind), kind: error.streamError.kind };
242
+ return withFailure(result, binding, 'buffered', 'provider_error');
243
+ }
240
244
  return withFailure(terminalResult('invalid_response'), binding, 'buffered', protocolCode(error));
241
245
  }
242
246
  }
@@ -0,0 +1,44 @@
1
+ // Shared OpenAI-compatible provider error classification for JSON and SSE.
2
+ // HTTP transport status is handled separately. Never infer retries from raw
3
+ // messages or retain provider bytes; unknown/malformed envelopes fail closed.
4
+ const RETRYABLE_ERROR_CODES = new Set([
5
+ 'rate_limit_error', 'rate_limit_exceeded', 'overloaded_error', 'server_error',
6
+ 'api_error', 'service_unavailable_error', 'server_is_overloaded', 'timeout_error',
7
+ 'MODEL_PROVIDER_RATE_LIMIT', 'MODEL_PROVIDER_UNAVAILABLE',
8
+ ]);
9
+ const TERMINAL_ERROR_CODES = new Set([
10
+ 'invalid_request_error', 'invalid_api_key', 'authentication_error',
11
+ 'permission_error', 'not_found_error', 'request_too_large', 'billing_error',
12
+ 'insufficient_quota', 'MODEL_PROVIDER_AUTHENTICATION', 'MODEL_PROVIDER_PERMISSION',
13
+ 'MODEL_PROVIDER_INVALID_REQUEST', 'MODEL_PROVIDER_NOT_FOUND',
14
+ 'MODEL_PROVIDER_QUOTA_EXHAUSTED',
15
+ ]);
16
+
17
+ export function classifyOpenAIProviderError(error) {
18
+ const invalid = { kind: 'provider_terminal_error', failureKind: 'invalid_response' };
19
+ if (!error || typeof error !== 'object' || Array.isArray(error)) return invalid;
20
+ if (error.type != null && typeof error.type !== 'string') return invalid;
21
+ // vLLM ErrorInfo encodes the HTTP rejection status in error.code even
22
+ // when the response headers have already committed HTTP 200 for SSE.
23
+ // https://docs.vllm.ai/en/v0.16.0/api/vllm/entrypoints/openai/engine/serving/
24
+ const status = typeof error.code === 'number' ? error.code : null;
25
+ if (status != null && (!Number.isInteger(status) || status < 400 || status > 599)) return invalid;
26
+ const codes = [status == null ? error.code : null, error.type].filter(value => value != null);
27
+ if (codes.some(value => typeof value !== 'string')) return invalid;
28
+ // A permanent quota/auth/request failure must never be retried just because
29
+ // a generic outer type also says rate_limit_error or server_error.
30
+ if (codes.some(value => TERMINAL_ERROR_CODES.has(value))) {
31
+ return { kind: 'provider_terminal_error', failureKind: 'client_error' };
32
+ }
33
+ if (status != null) {
34
+ if (status === 408) return { kind: 'provider_retryable_error', failureKind: 'request_timeout' };
35
+ if (status === 429) return { kind: 'provider_retryable_error', failureKind: 'rate_limit' };
36
+ return { kind: status >= 500 ? 'provider_retryable_error' : 'provider_terminal_error',
37
+ failureKind: status >= 500 ? 'server_error' : 'client_error' };
38
+ }
39
+ const code = codes.find(value => RETRYABLE_ERROR_CODES.has(value));
40
+ if (code) return { kind: 'provider_retryable_error',
41
+ failureKind: ['rate_limit_error', 'rate_limit_exceeded', 'MODEL_PROVIDER_RATE_LIMIT'].includes(code) ? 'rate_limit'
42
+ : code === 'timeout_error' ? 'request_timeout' : 'server_error' };
43
+ return invalid;
44
+ }
@@ -27,6 +27,7 @@ import {
27
27
  normalizeResponse, sealUsage, ProtocolError, resolveUrl, boundOutputTokens,
28
28
  emptyUsage,
29
29
  } from './model-normalize.mjs';
30
+ import { classifyOpenAIProviderError } from './model-provider-error.mjs';
30
31
  import { sealModelReplay } from './model-replay.mjs';
31
32
  import { validateMediaBlock, MediaError } from './model-media.mjs';
32
33
  // parseModelJson is the kernel's strict finite JSON parser (rejects duplicate
@@ -59,24 +60,6 @@ const HOSTED_ITEM_TYPES = new Set([
59
60
  'mcp_call', 'local_shell_call',
60
61
  ]);
61
62
 
62
- // In-stream error code/type → retryable/terminal classification. A 2xx stream
63
- // that emits an error/response.failed event is a provider rejection, never a
64
- // final; unknown codes stay terminal so a foreign payload cannot become a
65
- // silent retry or final. Mirrors the Anthropic stream classifier and the
66
- // Python provider_error code map.
67
- const RETRYABLE_ERROR_CODES = new Set([
68
- 'rate_limit_error', 'rate_limit_exceeded', 'overloaded_error', 'server_error',
69
- 'api_error', 'service_unavailable_error', 'server_is_overloaded', 'timeout_error',
70
- 'MODEL_PROVIDER_RATE_LIMIT', 'MODEL_PROVIDER_UNAVAILABLE',
71
- ]);
72
- const TERMINAL_ERROR_CODES = new Set([
73
- 'invalid_request_error', 'invalid_api_key', 'authentication_error',
74
- 'permission_error', 'not_found_error', 'request_too_large', 'billing_error',
75
- 'insufficient_quota', 'MODEL_PROVIDER_AUTHENTICATION', 'MODEL_PROVIDER_PERMISSION',
76
- 'MODEL_PROVIDER_INVALID_REQUEST', 'MODEL_PROVIDER_NOT_FOUND',
77
- 'MODEL_PROVIDER_QUOTA_EXHAUSTED',
78
- ]);
79
-
80
63
  function securityHeaders() {
81
64
  return new Set(['authorization', 'x-api-key', 'anthropic-version', 'content-type', 'accept']);
82
65
  }
@@ -449,18 +432,21 @@ function partsText(value, types) {
449
432
 
450
433
  // Parse a buffered 2xx Responses body into a sealed result. Used when a 2xx
451
434
  // response is not SSE (rare for stream:true); also the basis for envelope
452
- // validation. Throws ProtocolError on a malformed envelope or a failed/error
453
- // status (a 2xx body that claims failure is a protocol conflict, terminal).
435
+ // validation. Known provider error envelopes retain their classification;
436
+ // contradictory success/error envelopes are terminal protocol conflicts.
454
437
  export function parseResponsesBuffered(bodyText, request, { captureReplay = false, onThinking } = {}) {
455
438
  let payload;
456
439
  try { payload = strictParseJson(bodyText); } catch { throw new ProtocolError('invalid response json', 'json_invalid'); }
457
440
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
458
441
  throw new ProtocolError('invalid response envelope', 'envelope_invalid');
459
442
  }
443
+ if (payload.error != null || payload.status === 'failed') {
444
+ if (payload.status != null && payload.status !== 'failed') throw new ProtocolError('conflicting response envelope', 'envelope_invalid');
445
+ throw Object.assign(new ProtocolError('provider rejected generation', 'provider_error'), {
446
+ streamError: classifyOpenAIProviderError(payload.error),
447
+ });
448
+ }
460
449
  const status = identityOf(payload.status);
461
- // A 2xx body that carries an error alongside a purported successful answer,
462
- // or an explicit failed status, is a protocol conflict, never a final.
463
- if (payload.error != null) throw new ProtocolError('invalid response envelope', 'envelope_invalid');
464
450
  if (status === 'failed') throw new ProtocolError('invalid response envelope', 'envelope_invalid');
465
451
  validateBufferedIdentity(payload);
466
452
  const reportedUsage = parseResponsesUsage(payload.usage);
@@ -1036,20 +1022,7 @@ export function createResponsesStreamState(profile) {
1036
1022
  }
1037
1023
  const usage = parseResponsesUsage(failedBody.usage);
1038
1024
  if (usage != null) this.usage = usage;
1039
- const errorObj = failedBody.error != null && typeof failedBody.error === 'object' ? failedBody.error : {};
1040
- const code = String(errorObj.code || errorObj.type || '');
1041
- let kind; let failureKind;
1042
- if (RETRYABLE_ERROR_CODES.has(code)) {
1043
- kind = 'provider_retryable_error';
1044
- failureKind = code === 'rate_limit_error' || code === 'rate_limit_exceeded' ? 'rate_limit' : 'server_error';
1045
- } else if (TERMINAL_ERROR_CODES.has(code)) {
1046
- kind = 'provider_terminal_error';
1047
- failureKind = 'client_error';
1048
- } else {
1049
- kind = 'provider_terminal_error';
1050
- failureKind = 'invalid_response';
1051
- }
1052
- this.streamError = { kind, failureKind };
1025
+ this.streamError = classifyOpenAIProviderError(failedBody.error);
1053
1026
  },
1054
1027
 
1055
1028
  handleTerminal(event, { text: drainText, reasoning: drainReasoning }, emit) {
@@ -1142,6 +1115,11 @@ export function createResponsesStreamState(profile) {
1142
1115
  // An in-stream error or a transport error during the attempt seals the
1143
1116
  // observed text with no tools; usage is preserved when reported.
1144
1117
  if (this.streamError) {
1118
+ // A provider refusal is an observed stop decision, not permission to
1119
+ // reopen generation because a later stream error is transient.
1120
+ if (this.streamError.kind === 'provider_retryable_error' && (this.refused || this.finish === 'content_filter')) {
1121
+ return { kind: 'policy_abort', text: this.text, toolCalls: [], usage, usageReported };
1122
+ }
1145
1123
  return {
1146
1124
  kind: this.streamError.kind, text: this.text, toolCalls: [], usage, usageReported,
1147
1125
  ...(this.streamError.failureKind ? { failureKind: this.streamError.failureKind } : {}),
@@ -0,0 +1,14 @@
1
+ /** Ruff's public parse() recovers from invalid syntax and check() also applies
2
+ * compilation checks (e.g. duplicate parameters), so neither is an ast.parse
3
+ * grammar boundary. format() first uses ParsedModule::from_source, the strict
4
+ * grammar parser. Discard its output: validation must never rewrite the file.
5
+ *
6
+ * Do not use comments() for this boundary. Its debug renderer in pinned Ruff
7
+ * 0.16.8 truncates node source by byte offsets and panics on Unicode boundaries.
8
+ * Both workspace syntax validation and command-risk inspection use this same
9
+ * boundary, before their own version/token/AST checks.
10
+ * See astral-sh/ruff 0.16.8 crates/ruff_wasm/src/lib.rs.
11
+ */
12
+ export function assertPythonGrammar(workspace, source) {
13
+ workspace.format(source);
14
+ }
@@ -1,6 +1,7 @@
1
1
  import { parentPort, workerData } from 'node:worker_threads';
2
2
  import { Workspace, PositionEncoding } from '@astral-sh/ruff-wasm-nodejs';
3
3
  import { NATIVE_PYTHON_SYNTAX } from './python-syntax.mjs';
4
+ import { assertPythonGrammar } from './python-grammar.mjs';
4
5
 
5
6
  if (Workspace.version() !== NATIVE_PYTHON_SYNTAX.parserVersion) throw new Error('Python parser version mismatch');
6
7
  const workspace = new Workspace({ 'target-version': NATIVE_PYTHON_SYNTAX.targetVersion,
@@ -16,9 +17,9 @@ try {
16
17
  if (nul !== -1) issues = issueAt(nul, 'Source code cannot contain NUL bytes.');
17
18
  // `check` also performs compile-time checks even with no lint rules selected:
18
19
  // duplicate parameters, module nonlocal, unreachable match cases, etc.
19
- // CPython ast.parse deliberately permits these. `comments` first calls the
20
- // strict grammar parser, without those later scoping/compilation checks.
21
- try { if (!issues) workspace.comments(workerData); }
20
+ // CPython ast.parse deliberately permits these. Use the shared strict grammar
21
+ // boundary without the comment debug renderer or later compilation checks.
22
+ try { if (!issues) assertPythonGrammar(workspace, workerData); }
22
23
  catch (error) {
23
24
  const match = /^(.*) at byte range (\d+)\.\.(\d+)$/s.exec(error.message);
24
25
  if (!match) throw error;
@@ -9,7 +9,7 @@ import { canCloseNativeReadInterruption } from './read-interruption.mjs';
9
9
  import { advanceNativeContextMarkerState, nativeContextMarkerFactsFromState } from './context-markers.mjs';
10
10
 
11
11
  export const NATIVE_RUN_OBSERVATION = 'agentkit.native-run-observation/v1';
12
- export const NATIVE_COMMIT_PROJECTION = 'agentkit.native-commit-projection/v2';
12
+ export const NATIVE_COMMIT_PROJECTION = 'agentkit.native-commit-projection/v3';
13
13
 
14
14
  function contextProjection(previous, record) {
15
15
  let lastPlan = previous?.lastPlan ?? null, lastAdmission = previous?.lastAdmission ?? null;
@@ -24,7 +24,7 @@ function contextProjection(previous, record) {
24
24
  function observationHeader(s) {
25
25
  const header = Object.fromEntries(['scope', 'runId', 'sessionId', 'turnId', 'buildId', 'parentRunId', 'taskChainId',
26
26
  'configDigest', 'phase', 'revision', 'eventSeq', 'usage', 'descendantUsage', 'outcome', 'reason', 'pendingIntent',
27
- 'toolReconciliation'].filter(key => s[key] !== undefined).map(key => [key, s[key]]));
27
+ 'toolReconciliation', 'retryNotBefore'].filter(key => s[key] !== undefined).map(key => [key, s[key]]));
28
28
  header.diagnostics = Object.fromEntries(['providerUsageIncomplete', 'descendantUsageIncomplete', 'lastModelFailure']
29
29
  .filter(key => s.diagnostics[key] !== undefined).map(key => [key, s.diagnostics[key]]));
30
30
  return header;
@@ -475,6 +475,30 @@ export class SqliteRunStore extends TransactionalRunStore {
475
475
  } catch (error) { db.exec('ROLLBACK'); throw error; }
476
476
  },
477
477
  });
478
+ /** Read-only observability state and an append-only event suffix from one
479
+ * SQLite snapshot. Execution receipts, transcripts and configuration are
480
+ * deliberately excluded; this view cannot authorize execution. */
481
+ this.traceView = (scope, runId, after = 0) => {
482
+ open();
483
+ invariant(Number.isSafeInteger(after) && after >= 0, 'invalid_trace_cursor');
484
+ const key = runKey(scope, runId);
485
+ db.exec('BEGIN');
486
+ try {
487
+ const row = db.prepare(`SELECT json_object(
488
+ 'scope',json_extract(data,'$.snapshot.scope'), 'runId',json_extract(data,'$.snapshot.runId'),
489
+ 'sessionId',json_extract(data,'$.snapshot.sessionId'), 'phase',json_extract(data,'$.snapshot.phase'),
490
+ 'revision',json_extract(data,'$.snapshot.revision'), 'eventSeq',json_extract(data,'$.snapshot.eventSeq'),
491
+ 'usage',json_extract(data,'$.snapshot.usage'), 'outcome',json_extract(data,'$.snapshot.outcome')) AS snapshot
492
+ FROM native_runs WHERE key=?`).get(key);
493
+ invariant(row, 'run_not_found');
494
+ const snapshot = parseNativeJson(row.snapshot);
495
+ invariant(snapshot.runId === runId && canonical(snapshot.scope) === canonical(scope), 'native_trace_identity_mismatch');
496
+ const events = db.prepare('SELECT data FROM native_events WHERE run_key=? AND seq>? AND seq<=? ORDER BY seq')
497
+ .all(key, after, snapshot.eventSeq).map(row => parseNativeJson(row.data));
498
+ db.exec('COMMIT');
499
+ return { contract: 'agentkit.native-trace-view/v1', snapshot, events };
500
+ } catch (error) { db.exec('ROLLBACK'); throw error; }
501
+ };
478
502
  /** A presentation-only read: current transcript, display events and exact
479
503
  * unresolved closures. Historical raw tool bodies never enter this view. */
480
504
  this.sessionDeliveryState = (scope, runId) => {
@@ -13,6 +13,13 @@ const hash = value => createHash('sha256').update(value).digest('hex');
13
13
  const missing = error => ['ENOENT', 'ENOTDIR'].includes(error.code);
14
14
  const sameFile = (a, b) => ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].every(key => a[key] === b[key]);
15
15
 
16
+ /** New admissions get bounded read recovery; cold restoration retains the exact source policy. */
17
+ export function nativeWorkspaceInstructionTimeoutRecovery(configuration) {
18
+ return configuration === undefined
19
+ ? { contract: 'context-source-timeout/v1', maxRetries: 2, retryDelayMs: 100 }
20
+ : structuredClone(configuration.contextSources.find(source => source.sourceId === 'native.workspace-instructions')?.timeoutRecovery);
21
+ }
22
+
16
23
  /** Stable bounded reads, using the physical file identity both before and after
17
24
  * open. A concurrent replacement causes a retryable source failure, not stale
18
25
  * guidance or a partially read instruction file. */
@@ -45,13 +52,21 @@ async function readFile(root, path, signal) {
45
52
 
46
53
  /** Node-owned live source. Only discovery directories are durable; file bodies
47
54
  * and deletion state never depend on a summary or a process-local cache. */
48
- export function createNativeWorkspaceInstructions(binding) {
55
+ export function createNativeWorkspaceInstructions(binding, { timeoutRecovery } = {}) {
49
56
  validateNativeWorkspaceContext(binding);
50
57
  invariant(binding.instructionSource?.contract === CONTRACT, 'workspace_instruction_source_unbound');
58
+ invariant(timeoutRecovery === undefined || timeoutRecovery && !Array.isArray(timeoutRecovery)
59
+ && Object.keys(timeoutRecovery).sort().join(',') === 'contract,maxRetries,retryDelayMs'
60
+ && timeoutRecovery.contract === 'context-source-timeout/v1'
61
+ && Number.isSafeInteger(timeoutRecovery.maxRetries) && timeoutRecovery.maxRetries >= 0 && timeoutRecovery.maxRetries <= 3
62
+ && Number.isSafeInteger(timeoutRecovery.retryDelayMs) && timeoutRecovery.retryDelayMs >= 0 && timeoutRecovery.retryDelayMs <= 60000,
63
+ 'invalid_context_source_timeout_recovery');
51
64
  const root = binding.workspaceRoot, roots = structuredClone(binding.instructionSource.globalRoots);
52
65
  const source = Object.freeze({ contract: 'agentkit.native-context-source/v1', sourceId: 'native.workspace-instructions',
53
- bindingDigest: hash(canonical({ contract: CONTRACT, root, roots, candidates: CANDIDATES, MAX_FILE_BYTES, MAX_TOTAL_BYTES })),
54
- instructionPolicy: 'current-files/v1', priority: 1000, required: true, timeoutMs: 5000, maxTokens: 32768, maxBytes: 131072 });
66
+ bindingDigest: hash(canonical({ contract: CONTRACT, root, roots, candidates: CANDIDATES, MAX_FILE_BYTES, MAX_TOTAL_BYTES,
67
+ ...(timeoutRecovery ? { timeoutRecovery } : {}) })),
68
+ instructionPolicy: 'current-files/v1', priority: 1000, required: true, timeoutMs: 5000, maxTokens: 32768, maxBytes: 131072,
69
+ ...(timeoutRecovery ? { timeoutRecovery: structuredClone(timeoutRecovery) } : {}) });
55
70
  const initialScopes = () => ({ contract: INSTRUCTION_SCOPES, sourceId: source.sourceId,
56
71
  bindingDigest: source.bindingDigest, directories: [''] });
57
72
  const scopesOf = state => state === undefined ? initialScopes() : validateInstructionScopes(state, { contextSources: [source] });