@kingsoftcloud/agentkit-harness-core 0.0.14 → 0.0.16

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.
Files changed (49) hide show
  1. package/dist/approval-outcome.d.mts +7 -0
  2. package/dist/approval-outcome.mjs +8 -0
  3. package/dist/background-contract.d.mts +3 -0
  4. package/dist/background-contract.mjs +14 -0
  5. package/dist/background-notification.mjs +3 -2
  6. package/dist/child-contract.d.mts +8 -1
  7. package/dist/child-control.d.mts +4 -0
  8. package/dist/child-control.mjs +15 -2
  9. package/dist/child-runtime.mjs +11 -1
  10. package/dist/configuration.d.mts +2 -0
  11. package/dist/configuration.mjs +7 -4
  12. package/dist/context-planning.mjs +6 -3
  13. package/dist/contracts.d.mts +13 -7
  14. package/dist/contracts.mjs +1 -1
  15. package/dist/index.d.mts +1 -0
  16. package/dist/index.mjs +1 -0
  17. package/dist/kernel.d.mts +1 -0
  18. package/dist/kernel.mjs +41 -5
  19. package/dist/machine.mjs +40 -22
  20. package/dist/model-failure.d.mts +13 -1
  21. package/dist/model-failure.mjs +29 -2
  22. package/dist/model-json.mjs +21 -12
  23. package/dist/output-recovery.mjs +6 -2
  24. package/dist/response-continuation.d.mts +4 -0
  25. package/dist/response-continuation.mjs +9 -1
  26. package/dist/store.mjs +2 -1
  27. package/dist/tool-discovery.d.mts +8 -0
  28. package/dist/tool-discovery.mjs +44 -0
  29. package/dist/transitions.mjs +22 -2
  30. package/package.json +1 -1
  31. package/src/approval-outcome.mts +12 -0
  32. package/src/background-contract.mts +12 -0
  33. package/src/background-notification.mts +3 -2
  34. package/src/child-contract.mts +5 -1
  35. package/src/child-control.mts +16 -2
  36. package/src/child-runtime.mts +7 -1
  37. package/src/configuration.mts +9 -4
  38. package/src/context-planning.mts +6 -3
  39. package/src/contracts.mts +14 -8
  40. package/src/index.mts +1 -0
  41. package/src/kernel.mts +38 -5
  42. package/src/machine.mts +41 -22
  43. package/src/model-failure.mts +40 -3
  44. package/src/model-json.mts +20 -9
  45. package/src/output-recovery.mts +6 -2
  46. package/src/response-continuation.mts +11 -1
  47. package/src/store.mts +2 -1
  48. package/src/tool-discovery.mts +37 -0
  49. package/src/transitions.mts +20 -2
@@ -0,0 +1,7 @@
1
+ /** Host answers are not interchangeable. Unknown answers never grant access.
2
+ * Session permissions are a separate scoped Host authority, not an outcome a
3
+ * model or tool may claim in this vocabulary. */
4
+ export type HostApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';
5
+ export declare const APPROVAL_OUTCOME_POLICY: "owner-outcome/v1";
6
+ export declare function normalizeHostApprovalOutcome(value: unknown): HostApprovalOutcome;
7
+ export declare function approvalOutcomePauseReason(value: HostApprovalOutcome): string | null;
@@ -0,0 +1,8 @@
1
+ export const APPROVAL_OUTCOME_POLICY = 'owner-outcome/v1';
2
+ export function normalizeHostApprovalOutcome(value) {
3
+ return value === 'allowed-once' || value === 'rejected' || value === 'cancelled' ? value : 'unavailable';
4
+ }
5
+ export function approvalOutcomePauseReason(value) {
6
+ return value === 'rejected' ? 'approval_rejected' : value === 'cancelled' ? 'approval_cancelled'
7
+ : value === 'unavailable' ? 'approval_unavailable' : null;
8
+ }
@@ -9,6 +9,9 @@ export interface BackgroundCommandState {
9
9
  ref: BackgroundCommandRef;
10
10
  notified: boolean;
11
11
  }
12
+ /** Bound a read view without retiring any durable command ownership. Prefer
13
+ * commands whose completion has not been accounted for, then recent history. */
14
+ export declare function projectBackgroundCommands(rows: readonly BackgroundCommandState[], limit: number, recentLimit?: number): BackgroundCommandState[];
12
15
  export interface BackgroundCommandRequest extends Omit<PortContext, 'signal'> {
13
16
  schemaVersion: typeof BACKGROUND_COMMAND_CONTRACT;
14
17
  cursor: string;
@@ -1,5 +1,19 @@
1
1
  import { copy, invariant } from './values.mjs';
2
2
  export const BACKGROUND_COMMAND_CONTRACT = 'agentkit.background-command-observation/v1';
3
+ /** Bound a read view without retiring any durable command ownership. Prefer
4
+ * commands whose completion has not been accounted for, then recent history. */
5
+ export function projectBackgroundCommands(rows, limit, recentLimit = limit) {
6
+ const outstanding = [], recent = [];
7
+ for (let index = rows.length - 1; index >= 0 && outstanding.length < limit; index--) {
8
+ if (rows[index].notified === true) {
9
+ if (recent.length < recentLimit)
10
+ recent.push(index);
11
+ }
12
+ else
13
+ outstanding.push(index);
14
+ }
15
+ return [...outstanding, ...recent.slice(0, limit - outstanding.length)].sort((a, b) => a - b).map(index => rows[index]);
16
+ }
3
17
  function object(input) {
4
18
  invariant(input !== null && typeof input === 'object' && !Array.isArray(input), 'invalid_background_command_object');
5
19
  return copy(input);
@@ -3,6 +3,7 @@ import { backgroundCommandObservation, backgroundCommandRef } from './background
3
3
  import { initialSnapshot, configure } from './configuration.mjs';
4
4
  import { projectSessionHistory } from './history.mjs';
5
5
  import { canonical, copy, invariant, NativeError, isNativeError, scopeKey } from './values.mjs';
6
+ import { responseScopedOutputRestarts } from './response-continuation.mjs';
6
7
  export const BACKGROUND_NOTIFICATION_ADMISSION = 'agentkit.background-notification-admission/v1';
7
8
  function assertSettled(record) {
8
9
  const snapshot = record.snapshot;
@@ -162,12 +163,12 @@ export async function admitBackgroundNotification({ store, scope, sourceRunId, t
162
163
  limits.maxWallMs -= used.wall + elapsed;
163
164
  invariant((limits.maxModelCalls === null || limits.maxModelCalls > 0) && (limits.maxWallMs === null || limits.maxWallMs > 0), 'background_notification_budget_exhausted');
164
165
  limits.maxRepairs = Math.max(0, limits.maxRepairs - used.repairs);
165
- if (source.configuration.outputRestartPolicy !== 'per-response/v1')
166
+ if (!responseScopedOutputRestarts(source.configuration))
166
167
  limits.maxOutputRestarts = Math.max(0, limits.maxOutputRestarts - used.outputRestarts);
167
168
  limits.maxRecoveryRetries = Math.max(0, limits.maxRecoveryRetries - used.recovery);
168
169
  const contract = copy(head.taskContract ?? parent.configuration.contract);
169
170
  const configuration = configure({ ...copy(source.configuration), contract, limits, inputMessages: null,
170
- profile: { ...source.configuration.profile, maxContinuations: source.configuration.outputRestartPolicy === 'per-response/v1'
171
+ profile: { ...source.configuration.profile, maxContinuations: responseScopedOutputRestarts(source.configuration)
171
172
  ? source.configuration.profile.maxContinuations : Math.max(0, source.configuration.profile.maxContinuations - used.continuations) } });
172
173
  const snapshot = initialSnapshot({ scope: fixedScope, runId, sessionId: source.snapshot.sessionId,
173
174
  turnId: runId, buildId: source.snapshot.buildId, parentRunId: head.runId, taskChainId: source.snapshot.taskChainId }, configuration, digest(configuration));
@@ -67,6 +67,8 @@ export interface ChildTaskControlState {
67
67
  canPromote: boolean;
68
68
  canCancel: boolean;
69
69
  canSendInput: boolean;
70
+ /** Explicit Host control, not a model tool or implicit side effect of guidance. */
71
+ canResume?: boolean;
70
72
  }
71
73
  export interface ChildControlTarget {
72
74
  scope: RunScope;
@@ -97,7 +99,12 @@ export interface ChildLifecyclePort {
97
99
  }): Promise<{
98
100
  childRunIds: string[];
99
101
  }>;
100
- /** Host teardown is independent of a parent's write lease. */
102
+ /** Dispose Host ownership without canceling an idle, resumable parent or its children. */
103
+ closeRun?(request: {
104
+ scope: RunScope;
105
+ runId: string;
106
+ }): Promise<void>;
107
+ /** Release terminal or explicitly canceled work, canceling any live descendants. */
101
108
  releaseRun?(request: {
102
109
  scope: RunScope;
103
110
  runId: string;
@@ -1,5 +1,9 @@
1
1
  import type { ChildControlDelivery, ChildControlTarget } from './child-contract.mjs';
2
2
  import type { RunCommand, RunSnapshot, StoredRun } from './contracts.mjs';
3
+ /** An explicit control resumes a known pause, not an uncertain effect. This
4
+ * applies to output, provider and context pauses without changing their
5
+ * frozen policies, total budgets or required permission decisions. */
6
+ export declare function childResumeAllowed(snapshot: RunSnapshot): boolean;
3
7
  export declare function childControlDelivery(parent: RunSnapshot, command: RunCommand, target: ChildControlTarget): ChildControlDelivery;
4
8
  /** Runs under the Store's multi-record transaction, before either ledger changes. */
5
9
  export declare function validateChildControlDelivery(parent: StoredRun, child: StoredRun, command: RunCommand, delivery: ChildControlDelivery): void;
@@ -1,16 +1,25 @@
1
1
  import { terminal } from './contracts.mjs';
2
2
  import { CHILD_OWNER_CONTRACT } from './child-contract.mjs';
3
3
  import { canonical, copy, invariant } from './values.mjs';
4
+ /** An explicit control resumes a known pause, not an uncertain effect. This
5
+ * applies to output, provider and context pauses without changing their
6
+ * frozen policies, total budgets or required permission decisions. */
7
+ export function childResumeAllowed(snapshot) {
8
+ return snapshot.phase === 'paused' && snapshot.pendingIntent === null
9
+ && snapshot.toolReconciliation == null && snapshot.resumePhase !== 'awaiting_reconciliation'
10
+ && !['effect_outcome_unknown', 'recovery_retry_exhausted', 'browser_session_unavailable'].includes(snapshot.reason ?? '');
11
+ }
4
12
  export function childControlDelivery(parent, command, target) {
5
13
  const send = command.kind === 'message_child', input = command.payload;
6
- invariant(['message_child', 'cancel_child'].includes(command.kind)
14
+ invariant(['message_child', 'cancel_child', 'resume_child'].includes(command.kind)
7
15
  && typeof input.childRunId === 'string' && input.childRunId.trim() && input.childRunId.length <= 256
8
16
  && Object.keys(input).every(key => (send ? ['childRunId', 'text', 'expectedGoalRevision'] : ['childRunId']).includes(key))
9
17
  && (!send || typeof input.text === 'string' && input.text.trim() && input.text.length <= 32768
10
18
  && Number.isSafeInteger(input.expectedGoalRevision) && input.expectedGoalRevision >= 0), 'invalid_child_control');
11
19
  return { target: copy(target), command: {
12
20
  commandId: `child-control:${canonical([parent.scope, parent.runId, command.commandId])}`,
13
- kind: send ? 'guide' : 'cancel', payload: send ? { text: input.text, expectedGoalRevision: input.expectedGoalRevision } : {},
21
+ kind: send ? 'guide' : command.kind === 'resume_child' ? 'resume' : 'cancel',
22
+ payload: send ? { text: input.text, expectedGoalRevision: input.expectedGoalRevision } : {},
14
23
  } };
15
24
  }
16
25
  /** Runs under the Store's multi-record transaction, before either ledger changes. */
@@ -46,6 +55,10 @@ export function validateChildControlDelivery(parent, child, command, delivery) {
46
55
  && !(receipt.result.retryScheduled === true && ['safe-read/v1', 'workspace-observation/v1'].includes(String(receipt.result.recoveryPolicy)))), 'child_control_result_unknown');
47
56
  const preempts = (record, kinds) => record.commands.some(row => !row.consumed && kinds.includes(row.command.kind));
48
57
  invariant(!preempts(parent, ['cancel', 'policy_revoked', 'steer']), 'parent_control_preempts_child_control');
58
+ if (command.kind === 'resume_child') {
59
+ invariant(childResumeAllowed(c)
60
+ && !preempts(child, ['cancel', 'policy_revoked', 'steer', 'resume']), 'child_control_unavailable');
61
+ }
49
62
  if (command.kind === 'message_child') {
50
63
  invariant(!preempts(child, ['cancel', 'policy_revoked', 'steer']), 'child_control_preempts_input');
51
64
  invariant(command.payload.expectedGoalRevision === c.goalRevision, 'stale_child_goal_revision');
@@ -138,7 +138,7 @@ export function reduceChildLifecycle(snapshot, config, request, result, digest,
138
138
  const owned = request.reservations.find(item => item.childRunId === child.runId);
139
139
  invariant(owned && owned.parentOperationKey === child.operationKey && owned.parentToolCallId === child.callId
140
140
  && child.reservedModelCalls === owned.maxModelCalls && child.reservedToolCalls === owned.maxToolCalls
141
- && ['prepared', 'running', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
141
+ && ['prepared', 'running', 'paused', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
142
142
  && (settled.includes(child.runId) ? ['completed', 'failed', 'canceled'].includes(child.state)
143
143
  : !['completed', 'failed', 'canceled'].includes(child.state))
144
144
  && child.usage.modelCalls <= owned.maxModelCalls && child.usage.toolCalls <= owned.maxToolCalls
@@ -164,6 +164,16 @@ export function reduceChildLifecycle(snapshot, config, request, result, digest,
164
164
  callId: approval.toolCall.callId, operationKey: request.operationKey };
165
165
  updated.interaction = null;
166
166
  }
167
+ else if (!result.errorCode && request.action === 'wait' && result.children?.some(child => child.state === 'paused'
168
+ && pending.includes(child.runId) && (!request.waitForChildRunIds || request.waitForChildRunIds.includes(child.runId)))) {
169
+ // A joined child can still own valid results and an unspent reservation.
170
+ // Preserve that original run until an explicit control resumes or cancels
171
+ // it. Background polls do not block the parent's independent work.
172
+ updated.resumePhase = updated.phase;
173
+ updated.phase = 'paused';
174
+ updated.reason = 'child_paused';
175
+ updated.outcome = null;
176
+ }
167
177
  else if (result.errorCode || !observationOnly && request.action !== 'poll'
168
178
  && pending.some(id => !request.waitForChildRunIds || request.waitForChildRunIds.includes(id))) {
169
179
  updated.phase = 'finalizing';
@@ -25,9 +25,11 @@ export interface ConfigurationInput {
25
25
  sourceReadPolicy?: RunConfiguration['sourceReadPolicy'];
26
26
  outputRecoveryPolicy?: RunConfiguration['outputRecoveryPolicy'];
27
27
  outputRestartPolicy?: RunConfiguration['outputRestartPolicy'];
28
+ approvalOutcomePolicy?: RunConfiguration['approvalOutcomePolicy'];
28
29
  providerRecoveryPolicy?: RunConfiguration['providerRecoveryPolicy'];
29
30
  toolErrorRecoveryPolicy?: RunConfiguration['toolErrorRecoveryPolicy'];
30
31
  toolDiscoveryPolicy?: RunConfiguration['toolDiscoveryPolicy'];
32
+ toolAdmissionPolicy?: RunConfiguration['toolAdmissionPolicy'];
31
33
  todoPolicy?: RunConfiguration['todoPolicy'];
32
34
  toolExecutionPolicy?: RunConfiguration['toolExecutionPolicy'];
33
35
  childTaskPolicy?: RunConfiguration['childTaskPolicy'];
@@ -49,9 +49,11 @@ export function configure(input) {
49
49
  ...(input.sourceReadPolicy === undefined ? {} : { sourceReadPolicy: input.sourceReadPolicy }),
50
50
  ...(input.outputRecoveryPolicy === undefined ? {} : { outputRecoveryPolicy: input.outputRecoveryPolicy }),
51
51
  ...(input.outputRestartPolicy === undefined ? {} : { outputRestartPolicy: input.outputRestartPolicy }),
52
+ ...(input.approvalOutcomePolicy === undefined ? {} : { approvalOutcomePolicy: input.approvalOutcomePolicy }),
52
53
  ...(input.providerRecoveryPolicy === undefined ? {} : { providerRecoveryPolicy: input.providerRecoveryPolicy }),
53
54
  ...(input.toolErrorRecoveryPolicy === undefined ? {} : { toolErrorRecoveryPolicy: input.toolErrorRecoveryPolicy }),
54
55
  ...(input.toolDiscoveryPolicy === undefined ? {} : { toolDiscoveryPolicy: input.toolDiscoveryPolicy }),
56
+ ...(input.toolAdmissionPolicy === undefined ? {} : { toolAdmissionPolicy: input.toolAdmissionPolicy }),
55
57
  ...(input.todoPolicy === undefined ? {} : { todoPolicy: input.todoPolicy }),
56
58
  ...(input.toolExecutionPolicy === undefined ? {} : { toolExecutionPolicy: input.toolExecutionPolicy }),
57
59
  ...(input.childTaskPolicy === undefined ? {} : { childTaskPolicy: input.childTaskPolicy }),
@@ -105,9 +107,10 @@ export function configure(input) {
105
107
  && typeof config.hostRecoveryBinding === 'object' && !Array.isArray(config.hostRecoveryBinding), 'invalid_host_recovery_binding');
106
108
  invariant(config.guidancePolicy == null || config.guidancePolicy === 'boundary-guide/v1', 'invalid_guidance_policy');
107
109
  invariant(config.inputPolicy === undefined || config.inputPolicy === 'before-first-model/v1', 'invalid_input_policy');
108
- invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
109
- invariant(config.outputRestartPolicy === undefined || config.outputRestartPolicy === 'per-response/v1'
110
- && config.outputRecoveryPolicy === 'response-boundary/v2', 'invalid_output_restart_policy');
110
+ invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
111
+ invariant(config.outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(config.outputRestartPolicy)
112
+ && ['response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy ?? ''), 'invalid_output_restart_policy');
113
+ invariant(config.approvalOutcomePolicy === undefined || config.approvalOutcomePolicy === 'owner-outcome/v1', 'invalid_approval_outcome_policy');
111
114
  invariant(config.providerRecoveryPolicy == null || config.providerRecoveryPolicy === 'provider-recovery/v2', 'invalid_provider_recovery_policy');
112
115
  invariant(config.toolExecutionPolicy === undefined || config.toolExecutionPolicy === 'owner-execution/v1', 'invalid_tool_execution_policy');
113
116
  invariant(config.toolErrorRecoveryPolicy == null || ['diagnose-before-repeat/v1', 'diagnose-before-repeat/v2'].includes(config.toolErrorRecoveryPolicy), 'invalid_tool_error_recovery_policy');
@@ -191,7 +194,7 @@ export function configure(input) {
191
194
  const policy = profile.providerCompatibilityPolicy;
192
195
  invariant(policy !== null && typeof policy === 'object' && !Array.isArray(policy)
193
196
  && Object.keys(policy).every(key => ['contract', 'rule'].includes(key))
194
- && ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3'].includes(policy.contract)
197
+ && ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)
195
198
  && ['auto', 'permissive', 'openai', 'strict-openai', 'cerebras', 'groq', 'deepseek',
196
199
  'zai', 'kspmas-gateway', 'moonshot', 'mimo'].includes(policy.rule), 'invalid_provider_compatibility_policy');
197
200
  }
@@ -9,9 +9,10 @@ import { sourceWorkingSetGroup } from './source-working-set-group.mjs';
9
9
  import { sourceReuseProjector } from './context-source-reuse.mjs';
10
10
  import { defaultToolPruningThreshold, projectOldToolResults, toolPruningIdleElapsed } from './context-microcompact.mjs';
11
11
  import { summaryContinuityInstructions, validSummaryContinuity } from './summary-continuity.mjs';
12
- import { responseContinuationPairs } from './response-continuation.mjs';
12
+ import { responseBoundaryRecovery, responseContinuationPairs } from './response-continuation.mjs';
13
13
  import { verificationModelView } from './model-surface.mjs';
14
14
  import { currentInstructionContribution } from './context-contributions.mjs';
15
+ import { projectBackgroundCommands } from './background-contract.mjs';
15
16
  const emptyState = () => ({ history: null, compaction: null, compactions: 0,
16
17
  compactionsWithoutProgress: 0, progressDigest: null, lastModelCall: 0 });
17
18
  export const contextMessageRef = (message, index, digest) => `message:${index}:${digest(message)}`;
@@ -39,6 +40,7 @@ export function contextContinuity(snapshot, config, policies = new NativePolicyR
39
40
  const scopedEvidence = config.modelSurface?.verificationProjection === 'readable-evidence/v1';
40
41
  const canReadArtifacts = config.artifactPolicy === 'runtime-artifacts/v1' && config.tools.some(tool => tool.name === 'ArtifactRead'
41
42
  && (config.contract.allowedToolNames === null || config.contract.allowedToolNames.includes(tool.name)));
43
+ const commands = projectBackgroundCommands(snapshot.backgroundCommands, 32, 8);
42
44
  return copy({ schemaVersion: scopedEvidence ? 'agentkit.native-context-continuity/v2' : 'agentkit.native-context-continuity/v1', authority: 'host_record', goal: snapshot.goal,
43
45
  ...(snapshot.todos ? { todos: snapshot.todos.items, todoRevision: snapshot.todos.revision } : {}),
44
46
  ...(snapshot.planMode ? { planMode: snapshot.planMode, planModeGuidance: policies.forRun(config).planning.planModeGuidance(snapshot, config) } : {}),
@@ -54,7 +56,8 @@ export function contextContinuity(snapshot, config, policies = new NativePolicyR
54
56
  childBudgetReservations: snapshot.childBudgetReservations ?? [], childRunIds: snapshot.childRunIds ?? [],
55
57
  childApproval: snapshot.childApproval ?? null,
56
58
  children: snapshot.children.map(child => ({ runId: child.runId, state: child.state, notified: child.notified })),
57
- backgroundCommands: snapshot.backgroundCommands.map(command => ({ ...command.ref, notified: command.notified })),
59
+ backgroundCommands: commands.map(command => ({ ...command.ref, notified: command.notified })),
60
+ ...(commands.length < snapshot.backgroundCommands.length ? { omittedBackgroundCommands: snapshot.backgroundCommands.length - commands.length } : {}),
58
61
  verification: scopedEvidence ? verificationModelView(snapshot.verification, canReadArtifacts ? snapshot.artifactRefs : []) : snapshot.verification,
59
62
  hostBindingDigest: config.hostBindingDigest,
60
63
  ...(snapshot.executionBudgetObservation ? { executionBudget: snapshot.executionBudgetObservation } : {}),
@@ -120,7 +123,7 @@ function groupsOf(messages, indexes) {
120
123
  }
121
124
  function mandatoryIndexes(snapshot, groups, config) {
122
125
  const mandatory = new Set(), messages = snapshot.messages;
123
- if (config.outputRecoveryPolicy === 'response-boundary/v2')
126
+ if (responseBoundaryRecovery(config))
124
127
  for (const pair of responseContinuationPairs(messages))
125
128
  for (const index of pair)
126
129
  mandatory.add(index);
@@ -182,7 +182,7 @@ export interface ModelProfile {
182
182
  rule: 'auto' | 'permissive' | 'openai' | 'strict-openai' | 'cerebras' | 'groq' | 'deepseek' | 'zai' | 'kspmas-gateway' | 'moonshot' | 'mimo';
183
183
  };
184
184
  providerCompatibilityPolicy?: {
185
- contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3';
185
+ contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3' | 'provider-compat/v4';
186
186
  rule: NonNullable<ModelProfile['inlineReasoningPolicy']>['rule'];
187
187
  };
188
188
  streaming?: boolean;
@@ -516,6 +516,8 @@ export interface RunConfiguration {
516
516
  planModeInitialActive?: boolean;
517
517
  childPlanPolicy?: 'inherit-plan/v1';
518
518
  toolDiscoveryPolicy?: 'local-tool-search/v1';
519
+ /** A premature call may load an already authorized schema, but never dispatch its operation. */
520
+ toolAdmissionPolicy?: 'discover-before-retry/v1';
519
521
  artifactPolicy?: 'runtime-artifacts/v1' | null;
520
522
  /** The execution owner must prepare Host context before the first inference. */
521
523
  inputPolicy?: 'before-first-model/v1';
@@ -542,10 +544,14 @@ export interface RunConfiguration {
542
544
  delegationDepth: number;
543
545
  modelRecoveryPolicy: 'manual' | 'pure-inference/v1';
544
546
  guidancePolicy?: 'boundary-guide/v1' | null;
545
- outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | null;
546
- /** Restart allowance belongs to one interrupted response chain. Legacy Runs
547
- * without this policy retain their original run-wide accounting. */
548
- outputRestartPolicy?: 'per-response/v1';
547
+ outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | 'response-boundary/v3' | null;
548
+ /** Restart allowance belongs to one interrupted response chain. v2 pauses
549
+ * exhausted chains for explicit resume instead of terminating the Run.
550
+ * Legacy Runs retain their frozen accounting and exhaustion behavior. */
551
+ outputRestartPolicy?: 'per-response/v1' | 'per-response/v2';
552
+ /** The interactive owner preserves typed Host outcomes and pauses on a
553
+ * non-grant. Children retain the outcome without duplicating that pause. */
554
+ approvalOutcomePolicy?: 'owner-outcome/v1';
549
555
  /** v2 counts consecutive provider failures and pauses (resumable) instead of failing when they run out. */
550
556
  providerRecoveryPolicy?: 'provider-recovery/v2' | null;
551
557
  /** v2 admits a ten-inference diagnostic allowance unless explicitly configured.
@@ -712,7 +718,7 @@ export interface ChildState {
712
718
  sessionId: string;
713
719
  operationKey: string;
714
720
  callId: string;
715
- state: 'prepared' | 'running' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
721
+ state: 'prepared' | 'running' | 'paused' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
716
722
  reservedModelCalls: number | null;
717
723
  reservedToolCalls: number | null;
718
724
  usage: Usage;
@@ -966,7 +972,7 @@ export interface EffectReceipt {
966
972
  status: 'committed' | 'failed' | 'uncertain' | 'not_dispatched';
967
973
  result: ObjectValue;
968
974
  }
969
- export type CommandKind = 'cancel' | 'policy_revoked' | 'pause' | 'resume' | 'submit_interaction' | 'reconcile_tool' | 'repair_workspace' | 'steer' | 'guide' | 'promote_child' | 'message_child' | 'cancel_child';
975
+ export type CommandKind = 'cancel' | 'policy_revoked' | 'pause' | 'resume' | 'submit_interaction' | 'reconcile_tool' | 'repair_workspace' | 'steer' | 'guide' | 'promote_child' | 'message_child' | 'cancel_child' | 'resume_child';
970
976
  export interface RunCommand {
971
977
  commandId: string;
972
978
  kind: CommandKind;
@@ -6,5 +6,5 @@ export const terminal = (phase) => ['completed', 'failed', 'canceled', 'interrup
6
6
  export const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, modelCalls: 0, toolCalls: 0, cost: 0 });
7
7
  export const commandPriority = {
8
8
  cancel: 100, policy_revoked: 95, submit_interaction: 90, cancel_child: 85,
9
- pause: 80, resume: 80, reconcile_tool: 75, repair_workspace: 75, promote_child: 70, message_child: 70, steer: 60, guide: 60,
9
+ pause: 80, resume: 80, reconcile_tool: 75, repair_workspace: 75, promote_child: 70, message_child: 70, resume_child: 70, steer: 60, guide: 60,
10
10
  };
package/dist/index.d.mts CHANGED
@@ -49,6 +49,7 @@ export * from './child-budget.mjs';
49
49
  export * from './child-contract.mjs';
50
50
  export * from './child-runtime.mjs';
51
51
  export * from './child-control.mjs';
52
+ export * from './approval-outcome.mjs';
52
53
  export * from './guidance.mjs';
53
54
  export * from './tool-receipt.mjs';
54
55
  export * from './output-recovery.mjs';
package/dist/index.mjs CHANGED
@@ -49,6 +49,7 @@ export * from './child-budget.mjs';
49
49
  export * from './child-contract.mjs';
50
50
  export * from './child-runtime.mjs';
51
51
  export * from './child-control.mjs';
52
+ export * from './approval-outcome.mjs';
52
53
  export * from './guidance.mjs';
53
54
  export * from './tool-receipt.mjs';
54
55
  export * from './output-recovery.mjs';
package/dist/kernel.d.mts CHANGED
@@ -40,6 +40,7 @@ export declare class NativeKernel {
40
40
  promoteChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
41
41
  sendChildInput(scope: RunScope, runId: string, childRunId: string, text: string, expectedGoalRevision: number, commandId: string): import("./contracts.mjs").CommandReceipt;
42
42
  cancelChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
43
+ resumeChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
43
44
  private submitChildControl;
44
45
  private childTaskStates;
45
46
  private consumeChildControl;
package/dist/kernel.mjs CHANGED
@@ -147,7 +147,7 @@ export class NativeKernel {
147
147
  if (result.status !== 'rejected' && ['cancel', 'policy_revoked'].includes(command.kind)) {
148
148
  this.active.get(runKey(scope, runId))?.abort(new NativeError('command_interrupt'));
149
149
  }
150
- if (result.status === 'accepted' && ['pause', 'promote_child', 'message_child', 'cancel_child'].includes(command.kind)) {
150
+ if (result.status === 'accepted' && ['pause', 'promote_child', 'message_child', 'cancel_child', 'resume_child'].includes(command.kind)) {
151
151
  const observer = this.childObservers.get(runKey(scope, runId));
152
152
  if (observer && (command.kind !== 'pause' || observer.canPause))
153
153
  observer.controller.abort(new NativeError(command.kind === 'pause' ? 'child_observation_paused' : 'child_observation_promoted'));
@@ -172,6 +172,9 @@ export class NativeKernel {
172
172
  cancelChild(scope, runId, childRunId, commandId) {
173
173
  return this.submitChildControl(scope, runId, { commandId, kind: 'cancel_child', payload: { childRunId } });
174
174
  }
175
+ resumeChild(scope, runId, childRunId, commandId) {
176
+ return this.submitChildControl(scope, runId, { commandId, kind: 'resume_child', payload: { childRunId } });
177
+ }
175
178
  submitChildControl(scope, runId, command) {
176
179
  const record = this.store.load(scope, runId), send = command.kind === 'message_child';
177
180
  // Stable retries retain the original target, even after it becomes terminal.
@@ -183,7 +186,7 @@ export class NativeKernel {
183
186
  invariant(target, 'child_control_not_owned');
184
187
  childControlDelivery(record.snapshot, command, target);
185
188
  const task = this.childTaskStates(record.snapshot).find(task => task.childRunId === target.runId);
186
- invariant(task && (send ? task.canSendInput : task.canCancel), 'child_control_unavailable');
189
+ invariant(task && (send ? task.canSendInput : command.kind === 'resume_child' ? task.canResume === true : task.canCancel), 'child_control_unavailable');
187
190
  return this.submit(scope, runId, command);
188
191
  }
189
192
  childTaskStates(snapshot) {
@@ -192,6 +195,7 @@ export class NativeKernel {
192
195
  return copy(this.ports.children?.tasks?.({ scope: copy(snapshot.scope), runId: snapshot.runId, sessionId: snapshot.sessionId,
193
196
  turnId: snapshot.turnId, buildId: snapshot.buildId, parentRunId: snapshot.parentRunId, taskChainId: snapshot.taskChainId }) ?? [])
194
197
  .map(task => ({ ...task, canCancel: task.canCancel && controls,
198
+ ...(task.canResume === undefined ? {} : { canResume: task.canResume && controls }),
195
199
  canSendInput: task.canSendInput && controls && config.childInputPolicy === 'owned-child-input/v1' }));
196
200
  }
197
201
  async consumeChildControl(snapshot, config, command, lease) {
@@ -203,9 +207,13 @@ export class NativeKernel {
203
207
  const target = port.controlTarget(snapshot, id);
204
208
  invariant(target, 'child_control_not_owned');
205
209
  const delivery = childControlDelivery(snapshot, command, target), changes = { childLifecycleCursor: null };
206
- const facts = [{ kind: send ? 'child.input_queued' : 'child.cancel_requested',
210
+ const facts = [{ kind: send ? 'child.input_queued'
211
+ : command.kind === 'resume_child' ? 'child.resume_requested' : 'child.cancel_requested',
207
212
  payload: { childRunId: id, commandId: command.commandId } }];
208
- if (!send && snapshot.childApproval?.childRunId === id) {
213
+ if (['resume_child', 'cancel_child'].includes(command.kind) && snapshot.phase === 'paused' && snapshot.reason === 'child_paused') {
214
+ Object.assign(changes, { phase: snapshot.resumePhase ?? 'preparing_context', resumePhase: null, reason: null });
215
+ }
216
+ if (command.kind === 'cancel_child' && snapshot.childApproval?.childRunId === id) {
209
217
  facts.push({ kind: 'approval.resolved', payload: { interactionId: snapshot.pendingInteraction?.interactionId ?? '',
210
218
  callId: snapshot.childApproval.toolCall.callId, decision: 'canceled', reason: 'child_cancel_requested' } });
211
219
  Object.assign(changes, { childApproval: null, pendingInteraction: null, interaction: null,
@@ -292,6 +300,8 @@ export class NativeKernel {
292
300
  }
293
301
  }, Math.max(10, Math.floor(initial.configuration.limits.leaseMs / 3)));
294
302
  let deliveredRevision = -1;
303
+ let recoveredChildControls = false;
304
+ const wokenChildControls = new Set();
295
305
  let browserChecked = !(initial.snapshot.browserSessionRefs?.length || initial.snapshot.lastBrowserObservation);
296
306
  try {
297
307
  while (true) {
@@ -323,8 +333,9 @@ export class NativeKernel {
323
333
  : prepareToolReceipt(this.store.load(scope, runId), command));
324
334
  continue;
325
335
  }
326
- if (['message_child', 'cancel_child'].includes(command.kind)) {
336
+ if (['message_child', 'cancel_child', 'resume_child'].includes(command.kind)) {
327
337
  await this.consumeChildControl(snapshot, config, command, lease);
338
+ wokenChildControls.add(command.commandId);
328
339
  continue;
329
340
  }
330
341
  const intent = record.pendingIntent;
@@ -345,6 +356,31 @@ export class NativeKernel {
345
356
  }
346
357
  continue;
347
358
  }
359
+ if (!recoveredChildControls) {
360
+ recoveredChildControls = true;
361
+ // The pair transaction may have committed immediately before a
362
+ // process died, leaving a paused child with an existing resume inbox
363
+ // entry but no wake. Recover notification, never re-enqueue a command
364
+ // or infer permission from a child's phase. The owner authenticates
365
+ // the exact inbox entry before it can drive the original child.
366
+ const children = this.ports.children;
367
+ if (config.childLifecyclePolicy === 'owned-background/v2' && snapshot.childRunIds.length
368
+ && snapshot.phase !== 'finalizing' && !snapshot.childTerminalPhase
369
+ && children?.controlTarget && children.wakeControl) {
370
+ const saved = this.store.load(scope, runId);
371
+ const delivered = new Set(saved.events.filter(event => event.kind === 'child.resume_requested')
372
+ .map(event => event.payload.commandId));
373
+ for (const row of saved.commands)
374
+ if (row.consumed && row.command.kind === 'resume_child'
375
+ && delivered.has(row.command.commandId) && !wokenChildControls.has(row.command.commandId)) {
376
+ const target = children.controlTarget(snapshot, String(row.command.payload.childRunId));
377
+ if (target)
378
+ await children.wakeControl(snapshot, childControlDelivery(snapshot, row.command, target));
379
+ }
380
+ if (controller.signal.aborted || this.drivingCommands(this.drivingState(scope, runId)).length)
381
+ continue;
382
+ }
383
+ }
348
384
  if (!browserChecked) {
349
385
  const pending = record.pendingIntent;
350
386
  // Resource loss must not conceal an already claimed effect. Classify
package/dist/machine.mjs CHANGED
@@ -16,11 +16,11 @@ import { admittedToolBudget, outstandingChildCalls, reduceChildBudget } from './
16
16
  import { prepareChildLifecycle, unsettledChildren } from './child-runtime.mjs';
17
17
  import { toolResourceUsage, toolUsageIncomplete } from './tool-resource-usage.mjs';
18
18
  import { completeContinuation, outputRecoveryMode, restartContinuation } from './output-recovery.mjs';
19
- import { responseContinuationPending } from './response-continuation.mjs';
19
+ import { responseBoundaryRecovery, responseContinuationPending, responseScopedOutputRestarts } from './response-continuation.mjs';
20
20
  import { advanceDiagnosticRecovery, advanceObservedProgress, advanceToolErrorStreak, guardedToolErrorAction, refuseUndiagnosedToolAction, reserveDiagnosticTrial, toolErrorRecoveryBoundary, toolErrorRecoveryEnabled, toolErrorStreakExhausted } from './tool-error-recovery.mjs';
21
21
  import { deliveryReadOutsidePaths, deliverySummaryAllowed, deliveryTaskMessages, observeExecutionBudget, rememberDeliveryWrite, scopedDeliveryReader, wallDeliveryOnly } from './deadline-delivery.mjs';
22
22
  import { contextContinuity } from './context-planning.mjs';
23
- import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
23
+ import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, discoverRejectedCalls, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
24
24
  import { NativePolicyRegistry } from './policy-registry.mjs';
25
25
  import { reduceCoordinatorResponses } from './coordinator-response.mjs';
26
26
  import { RESULT_DELIVERY_POLICY } from './deliverables.mjs';
@@ -402,20 +402,25 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
402
402
  }
403
403
  const tools = advertisedTools({ ...snapshot,
404
404
  usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies);
405
- if (result.toolCalls.some(call => !tools.some(tool => tool.name === call.name)
405
+ const discovery = discoverRejectedCalls(snapshot, config, result.toolCalls, tools);
406
+ const discovered = discovery ? { ...snapshot, toolDiscovery: discovery.state } : snapshot;
407
+ if (discovery || result.toolCalls.some(call => !tools.some(tool => tool.name === call.name)
406
408
  || !discoveredCallExposed(snapshot, config, call))) {
407
- const unbound = result.toolCalls.some(call => !config.tools.some(tool => tool.name === call.name)
408
- || !discoveredCallExposed(snapshot, config, call));
409
+ const unbound = result.toolCalls.some(call => !(config.toolAdmissionPolicy ? tools : config.tools).some(tool => tool.name === call.name)
410
+ || !discoveredCallExposed(discovered, config, call));
409
411
  const errors = snapshot.modelErrors + Number(unbound), exhausted = errors > config.profile.maxRetries;
410
412
  return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [], modelErrors: errors,
413
+ ...(discovery ? { toolDiscovery: discovery.state } : {}),
411
414
  outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'tool_call_not_advertised_retry_exhausted' : null, messages: [...snapshot.messages,
412
415
  { ...message, toolCalls: result.toolCalls }, ...result.toolCalls.map(call => ({ role: 'tool',
413
- callId: call.callId, name: call.name, content: canonical(toolAdmissionRejection(snapshot, config, call, tools)) }))] };
416
+ callId: call.callId, name: call.name, content: canonical({ ...toolAdmissionRejection(discovered, config, call, tools),
417
+ ...(discovery ? { loaded_tool_names: discovery.names,
418
+ instruction: 'The whole batch was not executed. Complete definitions for the listed tools are loaded in the next request. Resubmit valid calls by their exact names; normal permissions and approvals still apply.' } : {}) }) }))] };
414
419
  }
415
420
  return { ...base, phase: 'executing_tools', pendingTools: result.toolCalls,
416
421
  messages: [...snapshot.messages, { ...message, toolCalls: result.toolCalls }],
417
422
  continuations: 0, modelErrors: 0,
418
- ...(config.outputRestartPolicy === 'per-response/v1' ? { outputRestarts: 0 } : {}) };
423
+ ...(responseScopedOutputRestarts(config) ? { outputRestarts: 0 } : {}) };
419
424
  case 'final_candidate': {
420
425
  if (config.contract.finalSubmissionSchema) {
421
426
  const errors = snapshot.modelErrors + 1;
@@ -432,9 +437,33 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
432
437
  messages: [...snapshot.messages, { ...message, content: text, kind: 'final_candidate' }] };
433
438
  }
434
439
  case 'output_limit': {
440
+ const resumable = config.outputRestartPolicy === 'per-response/v2';
441
+ const continuation = () => {
442
+ const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config, advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
443
+ const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
444
+ const messages = [...snapshot.messages,
445
+ ...(result.text ? [{ ...message, kind: 'continuation_fragment', continuationResponseId: responseId }] : []),
446
+ { role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
447
+ ...(responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
448
+ ? { continuationPolicy: 'response-boundary/v2' } : {}),
449
+ continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
450
+ ? 'The previous output was interrupted while task tools remain available. It is work in progress, not a completed delivery. Continue from the last committed state using the available tools as needed; break remaining work into smaller actions. Incomplete tool calls were not executed. Give a fresh final answer only after the task is complete.'
451
+ : result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
452
+ + (responseBoundaryRecovery(config) ? 'You may replay the final incomplete line verbatim before continuing; the Host joins this exact overlap. Do not replay any complete line. ' : '')
453
+ + 'Incomplete tool calls were not executed.'
454
+ : 'The last response hit its output limit without visible content or a committed tool call. Continue the task from the last committed state; take the next useful action or answer only if the task is complete.' }];
455
+ return { mode, messages };
456
+ };
457
+ const exhausted = () => resumable
458
+ ? { phase: 'paused', resumePhase: 'preparing_context', outcome: null, reason: 'output_budget_exhausted',
459
+ messages: result.text ? continuation().messages : snapshot.messages }
460
+ : { phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
435
461
  if (snapshot.continuations >= config.profile.maxContinuations) {
436
- if (responseContinuationPending(snapshot, config))
437
- return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
462
+ // Committed answer text stays a suffix contract even when the first
463
+ // response has no remaining continuation allowance. It is not a tool
464
+ // fragment that may be discarded for an output restart.
465
+ if (responseContinuationPending(snapshot, config) || resumable && continuation().mode === 'suffix')
466
+ return { ...base, ...exhausted() };
438
467
  if (snapshot.outputRestarts < config.limits.maxOutputRestarts) {
439
468
  try {
440
469
  return { ...base, ...restartContinuation(snapshot, config, result.text, digest), phase: 'preparing_context',
@@ -446,26 +475,15 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
446
475
  return { ...base, phase: 'finalizing', outcome: 'blocked', reason: String(error.code) };
447
476
  }
448
477
  }
449
- return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
478
+ return { ...base, ...exhausted() };
450
479
  }
451
480
  if (!result.text && responseContinuationPending(snapshot, config))
452
481
  return { ...base, phase: 'preparing_context',
453
482
  continuations: snapshot.continuations + 1,
454
483
  messages: [...snapshot.messages, { role: 'user', kind: 'response_continuation_feedback',
455
484
  content: 'No visible continuation was returned. The interrupted text response is still pending. Return only its missing text suffix.' }] };
456
- const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config, advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
457
- const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
458
485
  return { ...base, phase: 'preparing_context', continuations: snapshot.continuations + 1,
459
- messages: [...snapshot.messages, ...(result.text ? [{ ...message, kind: 'continuation_fragment', continuationResponseId: responseId }] : []),
460
- { role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
461
- ...(config.outputRecoveryPolicy === 'response-boundary/v2' && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
462
- ? { continuationPolicy: 'response-boundary/v2' } : {}),
463
- continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
464
- ? 'The previous output was interrupted while task tools remain available. It is work in progress, not a completed delivery. Continue from the last committed state using the available tools as needed; break remaining work into smaller actions. Incomplete tool calls were not executed. Give a fresh final answer only after the task is complete.'
465
- : result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
466
- + (config.outputRecoveryPolicy === 'response-boundary/v2' ? 'You may replay the final incomplete line verbatim before continuing; the Host joins this exact overlap. Do not replay any complete line. ' : '')
467
- + 'Incomplete tool calls were not executed.'
468
- : 'The last response hit its output limit without visible content or a committed tool call. Continue the task from the last committed state; take the next useful action or answer only if the task is complete.' }] };
486
+ messages: continuation().messages };
469
487
  }
470
488
  case 'context_overflow':
471
489
  return { ...base, phase: 'compacting', context: { ...snapshot.context, preparedCursor: null } };