@kingsoftcloud/agentkit-harness-node 0.0.13 → 0.0.15

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-node",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Standalone Native Harness Node adapters: a durable SQLite run store, a one-request model HTTP port, and a minimal versioned JSON-RPC 2.0 over NDJSON process entry. Reuses the shared Native adapter implementations and externalizes @kingsoftcloud/agentkit-harness-core; depends on no Studio/DSH code at runtime.",
@@ -25,6 +25,8 @@
25
25
  "./native/child-history": "./src/native/child-history.mjs",
26
26
  "./native/child-command-resource": "./src/native/child-command-resource.mjs",
27
27
  "./native/child-owner": "./src/native/child-owner.mjs",
28
+ "./native/session-tool-approval": "./src/native/session-tool-approval.mjs",
29
+ "./native/approval-preflight": "./src/native/approval-preflight.mjs",
28
30
  "./native/child-publication": "./src/native/child-publication.mjs",
29
31
  "./native/child-readers": "./src/native/child-readers.mjs",
30
32
  "./native/child-tools": "./src/native/child-tools.mjs",
@@ -35,6 +37,7 @@
35
37
  "./native/component-tools": "./src/native/component-tools.mjs",
36
38
  "./native/context-counter": "./src/native/context-counter.mjs",
37
39
  "./native/conversation-command-control": "./src/native/conversation-command-control.mjs",
40
+ "./native/conversation-presentation": "./src/native/conversation-presentation.mjs",
38
41
  "./native/delivery-timeline": "./src/native/delivery-timeline.mjs",
39
42
  "./native/dsh-background-ownership": "./src/native/dsh-background-ownership.mjs",
40
43
  "./native/dsh-managed-ownership": "./src/native/dsh-managed-ownership.mjs",
@@ -137,7 +140,7 @@
137
140
  "src/package-integrity.mjs"
138
141
  ],
139
142
  "dependencies": {
140
- "@kingsoftcloud/agentkit-harness-core": "0.0.13",
143
+ "@kingsoftcloud/agentkit-harness-core": "0.0.15",
141
144
  "@astral-sh/ruff-wasm-nodejs": "0.16.8",
142
145
  "parse5": "7.3.0",
143
146
  "playwright-core": "1.58.2",
@@ -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,
@@ -0,0 +1,35 @@
1
+ import { canonical, invariant, parseNativeJson } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ export const SCHEMA_BOUND_PREFLIGHT = 'dsh.tool-preflight-defer/v1';
4
+ export const CONTROL_PREFLIGHT = 'dsh.tool-preflight-defer/v2';
5
+
6
+ /** Select an explicitly advertised Host seam. Never guess support from a tool
7
+ * name or relax the actual tool's output schema to carry an approval request. */
8
+ export function nativeApprovalPreflightContract(capabilities) {
9
+ const advertised = capabilities?.preflightDeferContracts ?? [capabilities?.preflightDeferContract];
10
+ if (!Array.isArray(advertised)) return null;
11
+ return advertised.includes(CONTROL_PREFLIGHT) ? CONTROL_PREFLIGHT
12
+ : advertised.includes(SCHEMA_BOUND_PREFLIGHT) ? SCHEMA_BOUND_PREFLIGHT : null;
13
+ }
14
+
15
+ /** A pre-dispatch control value is not a successful tool body value. The v1
16
+ * envelope is retained only for historical Hosts whose owned tools declare it.
17
+ * The v2 Host renders marked control data without invoking the body projector. */
18
+ export function nativeApprovalPreflight(content, contract) {
19
+ invariant([SCHEMA_BOUND_PREFLIGHT, CONTROL_PREFLIGHT].includes(contract), 'native_approval_preflight_contract_unavailable');
20
+ const text = canonical(content);
21
+ const value = contract === SCHEMA_BOUND_PREFLIGHT ? { result: text } : parseNativeJson(text);
22
+ return { contract, value, text, decision: { kind: 'defer', value: structuredClone(value) } };
23
+ }
24
+
25
+ /** Post-policy denial remains a denial. A success-shaped replacement cannot
26
+ * turn a deferred request into an execution receipt or change its authority. */
27
+ export function assertNativeApprovalPreflightProjection(expected, result) {
28
+ if (result?.isError === true) return;
29
+ invariant(result?.isError === false && !result.concludesTurn
30
+ && (expected.contract === CONTROL_PREFLIGHT ? result.preflightDeferred === CONTROL_PREFLIGHT
31
+ : result.preflightDeferred === undefined)
32
+ && canonical(result.value) === canonical(expected.value)
33
+ && canonical(result.content) === canonical([{ type: 'text', text: expected.text }]),
34
+ 'native_approval_preflight_projection_changed');
35
+ }
@@ -42,7 +42,8 @@ export function mergeNativeChildHistory(request, inventories) {
42
42
  for (const parent of sourceParents) parents.add(parent);
43
43
  }
44
44
  const selected = tasks.map(task => task.parentRunId === runId ? task
45
- : { ...task, canPromote: false, canCancel: false, canSendInput: false });
45
+ : { ...task, canPromote: false, canCancel: false, canSendInput: false,
46
+ ...(task.canResume === undefined ? {} : { canResume: false }) });
46
47
  return pageInventory(request, { contract: NATIVE_CHILD_HISTORY_CONTRACT, sessionId: request.sessionId, runId,
47
48
  inventoryDigest: hash({ contract: 'agentkit.native-child-inventory-merge/v1', sessionId: request.sessionId,
48
49
  sources: present.map(value => [value.runId, value.inventoryDigest]) }), tasks: selected });
@@ -118,7 +119,7 @@ export function createNativeChildHistory({ scope, store, liveTasks = () => [], l
118
119
  const taskRow = ({ parent, child, control }) => {
119
120
  const snapshot = child.snapshot, binding = child.configuration.childOwnerBinding;
120
121
  const accounted = Boolean(accountedChildDelivery(parent, child));
121
- const command = parent.commands.filter(row => ['message_child', 'cancel_child', 'promote_child'].includes(row.command.kind)
122
+ const command = parent.commands.filter(row => ['message_child', 'cancel_child', 'promote_child', 'resume_child'].includes(row.command.kind)
122
123
  && row.command.payload.childRunId === snapshot.runId).at(-1);
123
124
  const applied = command && parent.events.find(event => event.kind === 'command.applied' && event.payload.commandId === command.command.commandId);
124
125
  const lastControl = command ? { commandId: command.command.commandId, action: command.command.kind,
@@ -135,6 +136,8 @@ export function createNativeChildHistory({ scope, store, liveTasks = () => [], l
135
136
  delivery: control?.delivery ?? (binding.deliveryMode === 'foreground'
136
137
  && !(parent.snapshot.promotedChildRunIds ?? []).includes(snapshot.runId) ? 'foreground' : 'background'),
137
138
  canPromote: control?.canPromote === true, canCancel: control?.canCancel === true, canSendInput: control?.canSendInput === true,
139
+ ...(child.configuration.outputRestartPolicy === 'per-response/v2' || child.configuration.providerRecoveryPolicy === 'provider-recovery/v2'
140
+ || control?.canResume !== undefined ? { canResume: control?.canResume === true } : {}),
138
141
  goalRevision: snapshot.goalRevision,
139
142
  lastControl,
140
143
  goalPreview: [...snapshot.goal].slice(0, 256).join(''), goalComplete: [...snapshot.goal].length <= 256,
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { NativeKernel, NativeError, isNativeError, CHILD_OWNER_CONTRACT, canonical, copy, configure,
3
3
  addUsage, admittedToolBudget, childLifecycleRequest, childReadyProbe, scopeKey, terminal,
4
- CHILD_TASK_POLICY, COORDINATOR_RESPONSE_POLICY, activePlanMode, isPlanChildCall, planModeWriteDenial,
4
+ CHILD_TASK_POLICY, COORDINATOR_RESPONSE_POLICY, activePlanMode, isPlanChildCall, planModeWriteDenial, childResumeAllowed,
5
5
  CHILD_PLAN_POLICY, CHILD_PLAN_MODE_POLICY, defaultPolicyBindings } from '@kingsoftcloud/agentkit-harness-core';
6
6
  import { loadSessionChild, accountedChildDelivery, hasUnsafeChildReceipt, childNeedsApproval } from './owned-child.mjs';
7
7
  import { CHILD_ALLOCATION_POLICY, CHILD_ALLOCATION_DEFAULTS, LEGACY_CALL_DEFAULTS,
@@ -222,23 +222,23 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
222
222
  request.signal.throwIfAborted();
223
223
  toolInvocation(request);
224
224
  if (entry && !terminal(record.snapshot.phase)) drive(entry);
225
- while (!terminal(record.snapshot.phase) && !childNeedsApproval(record)) {
225
+ while (!terminal(record.snapshot.phase) && record.snapshot.phase !== 'paused' && !childNeedsApproval(record)) {
226
226
  request.signal.throwIfAborted(); const parent = toolInvocation(request);
227
- if (parent.commands.some(row => !row.consumed && ['pause', 'promote_child', 'message_child', 'cancel_child'].includes(row.command.kind))
227
+ if (parent.commands.some(row => !row.consumed && ['pause', 'promote_child', 'message_child', 'cancel_child', 'resume_child'].includes(row.command.kind))
228
228
  || entry?.error && entry.error.code !== 'lease_busy') return startup();
229
229
  await observeWhileLive(new Promise(resolve => setTimeout(resolve, 25)), request.signal);
230
230
  record = ownedChild(request, reservation);
231
231
  if (entry?.error?.code === 'lease_busy') drive(entry);
232
232
  }
233
233
  request.signal.throwIfAborted(); toolInvocation(request);
234
- if (childNeedsApproval(record) || record.snapshot.phase === 'interrupted' || unsafeReceipt(record)) return startup();
234
+ if (childNeedsApproval(record) || record.snapshot.phase === 'paused' || record.snapshot.phase === 'interrupted' || unsafeReceipt(record)) return startup();
235
235
  return { ...terminalReceipt(record, reservation), childBudgetReservation: copy(reservation) };
236
236
  } finally { request.signal.removeEventListener('abort', cancel); }
237
237
  };
238
238
  const projection = (record, reservation) => ({ runId: record.snapshot.runId, sessionId: record.snapshot.sessionId,
239
239
  operationKey: reservation.parentOperationKey, callId: reservation.parentToolCallId,
240
240
  state: unsafeReceipt(record) && !canWaitForReceipt?.(record) ? 'interrupted' : record.snapshot.phase === 'created' ? 'prepared' : childNeedsApproval(record) ? 'awaiting_interaction'
241
- : terminal(record.snapshot.phase) ? record.snapshot.phase : 'running',
241
+ : record.snapshot.phase === 'paused' || terminal(record.snapshot.phase) ? record.snapshot.phase : 'running',
242
242
  reservedModelCalls: reservation.maxModelCalls, reservedToolCalls: reservation.maxToolCalls,
243
243
  usage: addUsage(record.snapshot.usage, record.snapshot.descendantUsage), notified: false, metadata: {} });
244
244
 
@@ -283,7 +283,10 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
283
283
  && !terminal(child.phase) && (!unsafeReceipt(record) || canWaitForReceipt?.(record)) && reservation.settledUsageDigest === null;
284
284
  rows.push({ childRunId: child.runId, sessionId: child.sessionId, role: binding.role, phase: child.phase, goalRevision: child.goalRevision, delivery,
285
285
  canPromote: live && delivery === 'foreground' && effective(parent).childPromotionPolicy === 'owned-child-promotion/v1',
286
- canCancel: live, canSendInput: live });
286
+ canCancel: live, canSendInput: live,
287
+ ...(child.phase === 'paused' || record.configuration.outputRestartPolicy === 'per-response/v2'
288
+ || record.configuration.providerRecoveryPolicy === 'provider-recovery/v2'
289
+ ? { canResume: live && childResumeAllowed(record.snapshot) } : {}) });
287
290
  }
288
291
  return rows;
289
292
  },
@@ -476,7 +479,11 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
476
479
  const expected = request.childApproval;
477
480
  check(request.interaction.interactionId === `native-child-${hash(expected)}`
478
481
  && request.interaction.callId === expected.toolCall.callId && ['allow', 'deny'].includes(request.interaction.decision), 'child_approval_identity_conflict');
479
- const commandId = `parent-approval-${hash({ parent: identity(request), approval: expected, decision: request.interaction.decision })}`;
482
+ const reply = { interactionId: expected.interactionId, decision: request.interaction.decision,
483
+ ...(record.configuration.approvalOutcomePolicy === 'owner-outcome/v1'
484
+ && Object.hasOwn(request.interaction, 'approvalOutcome') ? { approvalOutcome: request.interaction.approvalOutcome } : {}) };
485
+ const commandId = `parent-approval-${hash({ parent: identity(request), approval: expected,
486
+ decision: Object.hasOwn(reply, 'approvalOutcome') ? reply : request.interaction.decision })}`;
480
487
  // A promotion may detach this observer after the decision was
481
488
  // durably delivered. Accept only that same saved decision; never
482
489
  // infer approval from a child's phase or ask for it a second time.
@@ -485,11 +492,10 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
485
492
  `parent-approval-${hash({ parent: item.operationKey, approval: expected, decision: request.interaction.decision })}`);
486
493
  const delivered = record.commands.some(row => row.command.kind === 'submit_interaction'
487
494
  && [commandId, ...previousIds].includes(row.command.commandId)
488
- && same(row.command.payload, { interactionId: expected.interactionId, decision: request.interaction.decision }));
495
+ && same(row.command.payload, reply));
489
496
  if (!delivered) {
490
497
  check(same(childApproval(record, reservation), expected), 'child_approval_identity_conflict');
491
- submit(entry, { commandId, kind: 'submit_interaction',
492
- payload: { interactionId: expected.interactionId, decision: request.interaction.decision } });
498
+ submit(entry, { commandId, kind: 'submit_interaction', payload: reply });
493
499
  }
494
500
  }
495
501
  if (!childNeedsApproval(record) || request.action === 'cancel' || request.childApproval?.childRunId === entry.runId) {
@@ -570,10 +576,13 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
570
576
  // Reconcile observes ledgers only. A proven original receipt wait may
571
577
  // remain pending after the parent collector died; it is not a failed
572
578
  // collection and grants no authority to query/send/drive that child.
579
+ // A known pause with no outstanding effect is also a ledger fact. It
580
+ // can restore the parent's join without resuming the child implicitly.
573
581
  // Rebinding and execution happen later in a fresh fenced collect.
574
582
  if (records.some(record => terminal(record.snapshot.phase)
575
583
  ? record.snapshot.phase === 'interrupted' || unsafeReceipt(record)
576
- : request.action === 'cancel' || !canWaitForReceipt?.(record))) return null;
584
+ : request.action === 'cancel' || !canWaitForReceipt?.(record)
585
+ && !(childResumeAllowed(record.snapshot) && !unsafeReceipt(record)))) return null;
577
586
  return { operationKey: request.operationKey,
578
587
  results: records.flatMap((record, index) => terminal(record.snapshot.phase) ? [terminalReceipt(record, request.reservations[index], false)] : []),
579
588
  ...(request.responseCursors === undefined ? {} : { responses: records.flatMap(record => responses(record, request.responseCursors)) }),
@@ -602,6 +611,32 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
602
611
  ? { ...terminalReceipt(record, reservation), childBudgetReservation: copy(reservation) }
603
612
  : startupReceipt(reservation, record.configuration.childOwnerBinding.role) }];
604
613
  },
614
+ // Host disposal is not an operator cancellation. Only detach settled idle
615
+ // workers: their identity, pending decision and join stay in the ledger for
616
+ // a replacement Host. A busy worker requires an explicit stop/recovery
617
+ // path; do not drop its owner or infer that its effect never ran.
618
+ detachRun(request) {
619
+ check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
620
+ const parent = store.load(parentScope, request.runId);
621
+ check(['paused', 'awaiting_interaction'].includes(parent.snapshot.phase), 'child_detach_parent_not_idle');
622
+ const owned = [...entries.values()].filter(entry => entry.configuration.childOwnerBinding.parent.runId === request.runId);
623
+ for (const entry of owned) {
624
+ const record = store.load(entry.scope, entry.runId);
625
+ check(!entry.promise && !entry.idle && !record.lease
626
+ && record.snapshot.pendingIntent === null && !unsafeReceipt(record)
627
+ && (terminal(record.snapshot.phase) || ['paused', 'awaiting_interaction'].includes(record.snapshot.phase)),
628
+ 'child_detach_worker_not_idle');
629
+ }
630
+ for (const entry of owned) entries.delete(entry.runId);
631
+ },
632
+ async closeRun(request) {
633
+ check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
634
+ const parent = store.load(parentScope, request.runId);
635
+ // Terminal cleanup owns cancellation of descendants. Host shutdown does
636
+ // not grant that authority while the durable parent is still resumable.
637
+ if (terminal(parent.snapshot.phase)) return this.releaseRun(request);
638
+ return this.detachRun(request);
639
+ },
605
640
  async releaseRun(request) {
606
641
  check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
607
642
  const jobs = [];
@@ -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, approvalOutcomePolicy, conversationPresentation, toolExecutionPolicy, toolAdmissionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }) }) {
115
116
  if (!roles.length) return null;
116
117
  if (workspaceContext !== undefined) {
117
118
  validateNativeWorkspaceContext(workspaceContext);
@@ -120,9 +121,14 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
120
121
  invariant(typeof goalContractFactory === 'function', 'native_child_goal_contract_factory_invalid');
121
122
  invariant(childAllocationPolicy === undefined || childAllocationPolicy === CHILD_ALLOCATION_POLICY, 'studio_native_child_allocation_policy_invalid');
122
123
  invariant(childCapabilityPolicy === undefined || childCapabilityPolicy === CHILD_CAPABILITY_POLICY, 'studio_native_child_capability_policy_invalid');
124
+ invariant(toolAdmissionPolicy === undefined || toolAdmissionPolicy === 'discover-before-retry/v1', 'studio_native_child_admission_policy_invalid');
123
125
  invariant(toolExecutionPolicy === undefined || toolExecutionPolicy === 'owner-execution/v1', 'studio_native_child_execution_policy_invalid');
124
126
  invariant(providerRecoveryPolicy === undefined || providerRecoveryPolicy === 'provider-recovery/v2', 'native_child_provider_recovery_policy_invalid');
125
- invariant(outputRecoveryPolicy === undefined || outputRecoveryPolicy === 'response-boundary/v2', 'studio_native_child_output_policy_invalid');
127
+ invariant(outputRecoveryPolicy === undefined || ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'studio_native_child_output_policy_invalid');
128
+ invariant(outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(outputRestartPolicy)
129
+ && ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'native_child_output_restart_policy_invalid');
130
+ invariant(approvalOutcomePolicy === undefined || approvalOutcomePolicy === 'owner-outcome/v1', 'native_child_approval_outcome_policy_invalid');
131
+ if (conversationPresentation !== undefined) validateConversationPresentation(conversationPresentation);
126
132
  invariant(childTaskPolicy === undefined || childTaskPolicy === CHILD_TASK_POLICY, 'studio_native_child_task_policy_invalid');
127
133
  invariant(childPlanPolicy === undefined || childPlanPolicy === CHILD_PLAN_POLICY, 'studio_native_child_plan_policy_invalid');
128
134
  invariant(artifactPolicy == null || artifactPolicy === 'runtime-artifacts/v1' && typeof artifactFactory === 'function',
@@ -219,14 +225,19 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
219
225
  : workspaceContext ? nativeWorkspaceContextBinding(isolated?.root ?? workspaceContext.workspaceRoot,
220
226
  { instructionRoots: workspaceContext.instructionSource.globalRoots }) : undefined;
221
227
  validateInstructionWorkspace(childContext, isolated, workspaceContext);
222
- const instructionSource = childContext ? createNativeWorkspaceInstructions(childContext) : null;
228
+ const instructionSource = childContext ? createNativeWorkspaceInstructions(childContext, { timeoutRecovery: source
229
+ ? nativeWorkspaceInstructionTimeoutRecovery(source.configuration) : instructionTimeoutRecovery }) : null;
223
230
  const executionResource = bound.commandResource ? { ...bound.commandResource, workspaceBindingDigest: hash(isolated.binding) } : undefined;
224
231
  invariant(!source || canonical(source.configuration.hostRecoveryBinding?.childExecutionResource ?? null) === canonical(executionResource ?? null),
225
232
  'studio_native_child_command_resource_changed');
226
233
  const hostBindingDigest = hash({ contract: STUDIO_NATIVE_CHILD_CONTRACT, role, profile: bound.model.profile, scope: child, tools: bound.tools,
227
234
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
235
+ ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
236
+ ...(approvalOutcomePolicy ? { approvalOutcomePolicy } : {}),
237
+ ...(conversationPresentation ? { conversationPresentation } : {}),
228
238
  ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
229
239
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
240
+ ...(toolAdmissionPolicy && bound.toolDiscoveryPolicy ? { toolAdmissionPolicy } : {}),
230
241
  ...(childPlanPolicy ? { childPlanPolicy } : {}),
231
242
  ...(childTaskPolicy ? { childTaskPolicy } : {}),
232
243
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
@@ -256,8 +267,11 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
256
267
  supportsImages: bound.model.supportsImages, tools: bound.tools }) } : {}),
257
268
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
258
269
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
270
+ ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
271
+ ...(approvalOutcomePolicy ? { approvalOutcomePolicy } : {}),
259
272
  ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
260
273
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
274
+ ...(toolAdmissionPolicy && bound.toolDiscoveryPolicy ? { toolAdmissionPolicy } : {}),
261
275
  ...(executionResource ? { backgroundNotificationPolicy: 'completed-before-model/v1' } : {}),
262
276
  ...(childTaskPolicy ? { todoPolicy: 'session-todos/v1', coordinatorResponsePolicy: COORDINATOR_RESPONSE_POLICY } : {}),
263
277
  ...(bound.toolDiscoveryPolicy ? { toolDiscoveryPolicy: bound.toolDiscoveryPolicy } : {}),
@@ -265,7 +279,7 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
265
279
  ...(sourceReadPolicy ? { sourceReadPolicy } : {}),
266
280
  guidancePolicy: 'boundary-guide/v1',
267
281
  ...(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,
282
+ instructions: [conversationPresentationInstructions(conversationPresentation), role.instructions, ...(childSkills ? [skillInstructions] : [])].filter(Boolean).join('\n\n'), contract, tools: bound.tools,
269
283
  modelRecoveryPolicy: bound.model.modelRecoveryPolicy ?? 'manual',
270
284
  ...(isolated || childSkills || childContext ? { hostRecoveryBinding: {
271
285
  ...(childContext ? { workspaceContext: childContext } : {}),
@@ -300,7 +314,8 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
300
314
  'studio_native_child_workspace_binding_changed');
301
315
  const childContext = configuration.hostRecoveryBinding?.workspaceContext;
302
316
  validateInstructionWorkspace(childContext, isolated, workspaceContext);
303
- const instructionSource = childContext ? createNativeWorkspaceInstructions(childContext) : null;
317
+ const instructionSource = childContext ? createNativeWorkspaceInstructions(childContext,
318
+ { timeoutRecovery: nativeWorkspaceInstructionTimeoutRecovery(configuration) }) : null;
304
319
  const executionResource = bound?.commandResource ? { ...bound.commandResource, workspaceBindingDigest: hash(isolated.binding) } : undefined;
305
320
  invariant(canonical(configuration.hostRecoveryBinding?.childExecutionResource ?? null) === canonical(executionResource ?? null)
306
321
  && configuration.backgroundNotificationPolicy === (executionResource ? 'completed-before-model/v1' : undefined),
@@ -312,8 +327,11 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
312
327
  hostBindingDigest: configuration.hostBindingDigest }).profile;
313
328
  invariant(bound && role && canonical(configuration.tools) === canonical(bound.tools)
314
329
  && configuration.outputRecoveryPolicy === outputRecoveryPolicy
330
+ && configuration.outputRestartPolicy === outputRestartPolicy
331
+ && configuration.approvalOutcomePolicy === approvalOutcomePolicy
315
332
  && configuration.providerRecoveryPolicy === providerRecoveryPolicy
316
333
  && configuration.toolExecutionPolicy === toolExecutionPolicy
334
+ && configuration.toolAdmissionPolicy === (bound.toolDiscoveryPolicy ? toolAdmissionPolicy : undefined)
317
335
  && configuration.inputPolicy === (instructionSource ? 'before-first-model/v1' : undefined)
318
336
  && canonical(configuration.contextSources) === canonical(instructionSource ? [instructionSource.source] : [])
319
337
  && (configuration.childAllocationPolicy ?? null) === (childAllocationPolicy ?? null)
@@ -333,8 +351,12 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
333
351
  && configuration.hostBindingDigest === hash({ contract: STUDIO_NATIVE_CHILD_CONTRACT, role,
334
352
  profile: bound.model.profile, scope: childScope(role), tools: bound.tools,
335
353
  ...(outputRecoveryPolicy ? { outputRecoveryPolicy } : {}),
336
- ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
354
+ ...(outputRestartPolicy ? { outputRestartPolicy } : {}),
355
+ ...(approvalOutcomePolicy ? { approvalOutcomePolicy } : {}),
356
+ ...(conversationPresentation ? { conversationPresentation } : {}),
357
+ ...(providerRecoveryPolicy ? { providerRecoveryPolicy } : {}),
337
358
  ...(toolExecutionPolicy ? { toolExecutionPolicy } : {}),
359
+ ...(toolAdmissionPolicy && bound.toolDiscoveryPolicy ? { toolAdmissionPolicy } : {}),
338
360
  ...(childPlanPolicy ? { childPlanPolicy } : {}),
339
361
  ...(childTaskPolicy ? { childTaskPolicy } : {}),
340
362
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
@@ -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
+ }
@@ -169,7 +169,7 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
169
169
  invariant(Number.isSafeInteger(ownershipFlushTimeoutMs) && ownershipFlushTimeoutMs > 0
170
170
  && ownershipFlushTimeoutMs <= 2_147_483_647, 'native_dsh_ownership_flush_timeout_invalid');
171
171
  const active = new Set(), backgroundDrivers = new Set(), revisions = streamRevisions;
172
- const run = async (payload, admission, background = null) => {
172
+ const run = async (payload, admission, background = null, operatorResume = false) => {
173
173
  const { agent, input, turn, signal } = payload;
174
174
  invariant(agent?.session && typeof agent.session.id === 'string' && agent.session.id.trim()
175
175
  && input?.kind === 'enter' && Array.isArray(input.messages)
@@ -280,7 +280,12 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
280
280
  taskChainId: binding.taskChainId ?? sessionId };
281
281
  const start = () => background ? store.load(scope, runId).snapshot : kernel.start({ ...identity, parentRunId: null }, configuration,
282
282
  durableOwnership || binding.taskContractFactory ? { expectedParentRunId: parentRunId } : {});
283
+ let idleApproval = null;
284
+ // The SDK disposes the owner on graceful Host shutdown. A persisted
285
+ // approval wait has no live effect to cancel and may be rebound later.
286
+ const detachingApproval = () => durableOwnership && idleApproval && cancelReason(signal.reason)?.kind === 'disposed';
283
287
  const persistCancel = () => {
288
+ if (detachingApproval()) return;
284
289
  const commandId = `${runId}:dsh-turn-cancel`;
285
290
  const original = store.load(scope, runId).commands.find(row => row.command.commandId === commandId)?.command;
286
291
  return kernel.submit(scope, runId, original ?? { commandId, kind: 'cancel',
@@ -307,8 +312,22 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
307
312
  signal.addEventListener('abort', cancelListener, { once: true });
308
313
  }
309
314
  let wakeIdle = () => {};
310
- releaseControls = onActive?.(payload, { kernel, scope: structuredClone(scope), sessionId, runId, wake: () => wakeIdle() });
315
+ releaseControls = onActive?.(payload, { kernel, scope: structuredClone(scope), sessionId, runId, wake: () => wakeIdle(),
316
+ ...(binding.sessionApproval ? { sessionApproval: binding.sessionApproval } : {}) });
311
317
  invariant(releaseControls === undefined || typeof releaseControls === 'function', 'native_dsh_controls_cleanup_invalid');
318
+ if (operatorResume) {
319
+ signal.throwIfAborted();
320
+ const current = store.load(scope, runId).snapshot;
321
+ if (current.phase === 'paused') {
322
+ // Rebinding an SDK turn is not a Native state transition. Only this
323
+ // explicit Host entry submits the durable command; ordinary delivery
324
+ // and crash reattachment keep user/policy pauses intact. Core owns
325
+ // cancellation precedence and any permitted budget recovery.
326
+ const commandId = `native-dsh-resume-${hash({ scope, runId, revision: current.revision, eventSeq: current.eventSeq })}`;
327
+ invariant(kernel.submit(scope, runId, { commandId, kind: 'resume', payload: {} }).status !== 'rejected',
328
+ 'native_dsh_resume_rejected');
329
+ }
330
+ }
312
331
  let snapshot;
313
332
  try {
314
333
  snapshot = await kernel.runUntilIdle(scope, runId, { signal });
@@ -317,18 +336,23 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
317
336
  if (!onIdle) throw failure('NATIVE_TURN_SUSPENDED', snapshot);
318
337
  const idle = new AbortController(), idlePayload = { ...payload, signal: AbortSignal.any([signal, idle.signal]) };
319
338
  let command, woken = false;
339
+ idleApproval = snapshot.phase === 'awaiting_interaction' ? snapshot : null;
320
340
  wakeIdle = () => { woken = true; idle.abort(new NativeError('native_idle_woken')); };
321
341
  try {
322
342
  if (store.load(scope, runId).commands.some(row => !row.consumed)) wakeIdle();
323
343
  command = await resolveWhileLive(() => onIdle(idlePayload, structuredClone(snapshot), {
324
344
  waitForToolReceipt: binding.ports.tools.waitForReceipt,
345
+ ...(binding.sessionApproval ? { sessionApproval: binding.sessionApproval } : {}),
325
346
  }), idlePayload);
326
347
  } catch (error) {
327
348
  if (!woken || signal.aborted) throw error;
349
+ idleApproval = null;
328
350
  snapshot = await kernel.runUntilIdle(scope, runId, { signal });
329
351
  continue;
330
352
  } finally { wakeIdle = () => {}; idle.abort(); }
331
353
  if (!command) throw failure('NATIVE_TURN_SUSPENDED', snapshot);
354
+ signal.throwIfAborted();
355
+ idleApproval = null;
332
356
  const revision = snapshot.revision;
333
357
  const receipt = kernel.submit(scope, runId, command);
334
358
  invariant(receipt.status !== 'rejected', 'native_dsh_command_rejected');
@@ -337,6 +361,7 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
337
361
  }
338
362
  signal.throwIfAborted();
339
363
  } catch (error) {
364
+ if (detachingApproval()) throw failure('NATIVE_TURN_SUSPENDED', idleApproval);
340
365
  if (signal.aborted && !terminal(store.load(scope, runId).snapshot.phase)) {
341
366
  // A turn can be canceled while no kernel worker is active (approval
342
367
  // or host checkpoint). Persist first, then drain without allowing a
@@ -451,7 +476,7 @@ export function createNativeDshTurnExecutor({ store, resolveTurn, resolveRecover
451
476
  const admission = readNativeDshOwnership(resumed.ownership, { sessionId: agent.session.id, turn: resumed.turn });
452
477
  return run({ ...request, ...resumed, agent,
453
478
  signal: request.signal ? AbortSignal.any([request.signal, resumed.signal]) : resumed.signal,
454
- input: { kind: 'enter', messages: structuredClone(admission.messages) } }, admission);
479
+ input: { kind: 'enter', messages: structuredClone(admission.messages) } }, admission, null, true);
455
480
  });
456
481
  };
457
482
  /** Drive only the persisted notification identified by an already claimed owner. */
@@ -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) {