@kingsoftcloud/agentkit-harness-core 0.0.14 → 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.
Files changed (46) hide show
  1. package/dist/approval-outcome.d.mts +7 -0
  2. package/dist/approval-outcome.mjs +8 -0
  3. package/dist/background-notification.mjs +3 -2
  4. package/dist/child-contract.d.mts +2 -0
  5. package/dist/child-control.d.mts +4 -0
  6. package/dist/child-control.mjs +15 -2
  7. package/dist/child-runtime.mjs +11 -1
  8. package/dist/configuration.d.mts +2 -0
  9. package/dist/configuration.mjs +7 -4
  10. package/dist/context-planning.mjs +2 -2
  11. package/dist/contracts.d.mts +13 -7
  12. package/dist/contracts.mjs +1 -1
  13. package/dist/index.d.mts +1 -0
  14. package/dist/index.mjs +1 -0
  15. package/dist/kernel.d.mts +1 -0
  16. package/dist/kernel.mjs +41 -5
  17. package/dist/machine.mjs +40 -22
  18. package/dist/model-failure.d.mts +13 -1
  19. package/dist/model-failure.mjs +29 -2
  20. package/dist/model-json.mjs +21 -12
  21. package/dist/output-recovery.mjs +6 -2
  22. package/dist/response-continuation.d.mts +4 -0
  23. package/dist/response-continuation.mjs +9 -1
  24. package/dist/store.mjs +2 -1
  25. package/dist/tool-discovery.d.mts +8 -0
  26. package/dist/tool-discovery.mjs +44 -0
  27. package/dist/transitions.mjs +21 -2
  28. package/package.json +1 -1
  29. package/src/approval-outcome.mts +12 -0
  30. package/src/background-notification.mts +3 -2
  31. package/src/child-contract.mts +2 -0
  32. package/src/child-control.mts +16 -2
  33. package/src/child-runtime.mts +7 -1
  34. package/src/configuration.mts +9 -4
  35. package/src/context-planning.mts +2 -2
  36. package/src/contracts.mts +14 -8
  37. package/src/index.mts +1 -0
  38. package/src/kernel.mts +38 -5
  39. package/src/machine.mts +41 -22
  40. package/src/model-failure.mts +40 -3
  41. package/src/model-json.mts +20 -9
  42. package/src/output-recovery.mts +6 -2
  43. package/src/response-continuation.mts +11 -1
  44. package/src/store.mts +2 -1
  45. package/src/tool-discovery.mts +37 -0
  46. package/src/transitions.mts +19 -2
package/src/machine.mts CHANGED
@@ -17,13 +17,13 @@ import { admittedToolBudget, outstandingChildCalls, reduceChildBudget } from './
17
17
  import { prepareChildLifecycle, unsettledChildren } from './child-runtime.mjs';
18
18
  import { toolResourceUsage, toolUsageIncomplete } from './tool-resource-usage.mjs';
19
19
  import { completeContinuation, outputRecoveryMode, restartContinuation } from './output-recovery.mjs';
20
- import { responseContinuationPending } from './response-continuation.mjs';
20
+ import { responseBoundaryRecovery, responseContinuationPending, responseScopedOutputRestarts } from './response-continuation.mjs';
21
21
  import { advanceDiagnosticRecovery, advanceObservedProgress, advanceToolErrorStreak, guardedToolErrorAction,
22
22
  refuseUndiagnosedToolAction, reserveDiagnosticTrial, toolErrorRecoveryBoundary, toolErrorRecoveryEnabled,
23
23
  toolErrorStreakExhausted } from './tool-error-recovery.mjs';
24
24
  import { deliveryReadOutsidePaths, deliverySummaryAllowed, deliveryTaskMessages, observeExecutionBudget, rememberDeliveryWrite, scopedDeliveryReader, wallDeliveryOnly } from './deadline-delivery.mjs';
25
25
  import { contextContinuity } from './context-planning.mjs';
26
- import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
26
+ import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, discoverRejectedCalls, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
27
27
  import { NativePolicyRegistry } from './policy-registry.mjs';
28
28
  import { reduceCoordinatorResponses } from './coordinator-response.mjs';
29
29
  import { RESULT_DELIVERY_POLICY } from './deliverables.mjs';
@@ -378,20 +378,25 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
378
378
  }
379
379
  const tools = advertisedTools({ ...snapshot,
380
380
  usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies);
381
- if (result.toolCalls.some(call => !tools.some(tool => tool.name === call.name)
381
+ const discovery = discoverRejectedCalls(snapshot, config, result.toolCalls, tools);
382
+ const discovered = discovery ? { ...snapshot, toolDiscovery: discovery.state } : snapshot;
383
+ if (discovery || result.toolCalls.some(call => !tools.some(tool => tool.name === call.name)
382
384
  || !discoveredCallExposed(snapshot, config, call))) {
383
- const unbound = result.toolCalls.some(call => !config.tools.some(tool => tool.name === call.name)
384
- || !discoveredCallExposed(snapshot, config, call));
385
+ const unbound = result.toolCalls.some(call => !(config.toolAdmissionPolicy ? tools : config.tools).some(tool => tool.name === call.name)
386
+ || !discoveredCallExposed(discovered, config, call));
385
387
  const errors = snapshot.modelErrors + Number(unbound), exhausted = errors > config.profile.maxRetries;
386
388
  return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [], modelErrors: errors,
389
+ ...(discovery ? { toolDiscovery: discovery.state } : {}),
387
390
  outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'tool_call_not_advertised_retry_exhausted' : null, messages: [...snapshot.messages,
388
391
  { ...message, toolCalls: result.toolCalls }, ...result.toolCalls.map(call => ({ role: 'tool' as const,
389
- callId: call.callId, name: call.name, content: canonical(toolAdmissionRejection(snapshot, config, call, tools)) }))] };
392
+ callId: call.callId, name: call.name, content: canonical({ ...toolAdmissionRejection(discovered, config, call, tools),
393
+ ...(discovery ? { loaded_tool_names: discovery.names,
394
+ 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.' } : {}) }) }))] };
390
395
  }
391
396
  return { ...base, phase: 'executing_tools', pendingTools: result.toolCalls,
392
397
  messages: [...snapshot.messages, { ...message, toolCalls: result.toolCalls }],
393
398
  continuations: 0, modelErrors: 0,
394
- ...(config.outputRestartPolicy === 'per-response/v1' ? { outputRestarts: 0 } : {}) };
399
+ ...(responseScopedOutputRestarts(config) ? { outputRestarts: 0 } : {}) };
395
400
  case 'final_candidate': {
396
401
  if (config.contract.finalSubmissionSchema) {
397
402
  const errors = snapshot.modelErrors + 1;
@@ -408,34 +413,48 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
408
413
  messages: [...snapshot.messages, { ...message, content: text, kind: 'final_candidate' }] };
409
414
  }
410
415
  case 'output_limit': {
416
+ const resumable = config.outputRestartPolicy === 'per-response/v2';
417
+ const continuation = () => {
418
+ const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config,
419
+ advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
420
+ const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
421
+ const messages: Message[] = [...snapshot.messages,
422
+ ...(result.text ? [{ ...message, kind: 'continuation_fragment', continuationResponseId: responseId }] : []),
423
+ { role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
424
+ ...(responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
425
+ ? { continuationPolicy: 'response-boundary/v2' as const } : {}),
426
+ continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
427
+ ? '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.'
428
+ : result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
429
+ + (responseBoundaryRecovery(config) ? 'You may replay the final incomplete line verbatim before continuing; the Host joins this exact overlap. Do not replay any complete line. ' : '')
430
+ + 'Incomplete tool calls were not executed.'
431
+ : '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.' }];
432
+ return { mode, messages };
433
+ };
434
+ const exhausted = (): Partial<RunSnapshot> => resumable
435
+ ? { phase: 'paused', resumePhase: 'preparing_context', outcome: null, reason: 'output_budget_exhausted',
436
+ messages: result.text ? continuation().messages : snapshot.messages }
437
+ : { phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
411
438
  if (snapshot.continuations >= config.profile.maxContinuations) {
412
- if (responseContinuationPending(snapshot, config)) return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
439
+ // Committed answer text stays a suffix contract even when the first
440
+ // response has no remaining continuation allowance. It is not a tool
441
+ // fragment that may be discarded for an output restart.
442
+ if (responseContinuationPending(snapshot, config) || resumable && continuation().mode === 'suffix')
443
+ return { ...base, ...exhausted() };
413
444
  if (snapshot.outputRestarts < config.limits.maxOutputRestarts) {
414
445
  try { return { ...base, ...restartContinuation(snapshot, config, result.text, digest), phase: 'preparing_context',
415
446
  continuations: 0, outputRestarts: snapshot.outputRestarts + 1 }; }
416
447
  catch (error) { if (!(error instanceof Error) || !('code' in error)) throw error;
417
448
  return { ...base, phase: 'finalizing', outcome: 'blocked', reason: String(error.code) }; }
418
449
  }
419
- return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
450
+ return { ...base, ...exhausted() };
420
451
  }
421
452
  if (!result.text && responseContinuationPending(snapshot, config)) return { ...base, phase: 'preparing_context',
422
453
  continuations: snapshot.continuations + 1,
423
454
  messages: [...snapshot.messages, { role: 'user', kind: 'response_continuation_feedback',
424
455
  content: 'No visible continuation was returned. The interrupted text response is still pending. Return only its missing text suffix.' }] };
425
- const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config,
426
- advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
427
- const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
428
456
  return { ...base, phase: 'preparing_context', continuations: snapshot.continuations + 1,
429
- messages: [...snapshot.messages, ...(result.text ? [{ ...message, kind: 'continuation_fragment', continuationResponseId: responseId }] : []),
430
- { role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
431
- ...(config.outputRecoveryPolicy === 'response-boundary/v2' && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
432
- ? { continuationPolicy: 'response-boundary/v2' as const } : {}),
433
- continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
434
- ? '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.'
435
- : result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
436
- + (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. ' : '')
437
- + 'Incomplete tool calls were not executed.'
438
- : '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.' }] };
457
+ messages: continuation().messages };
439
458
  }
440
459
  case 'context_overflow':
441
460
  return { ...base, phase: 'compacting', context: { ...snapshot.context, preparedCursor: null } };
@@ -8,13 +8,37 @@ export const MODEL_FAILURE_CODES = [
8
8
  'choice_invalid', 'delta_invalid', 'termination_conflict', 'framing_invalid', 'body_limit',
9
9
  'body_encoding', 'transport_error', 'stream_timeout', 'stream_incomplete', 'tool_payload_invalid',
10
10
  ] as const;
11
+ /** Closed provider identifiers only; arbitrary provider strings can contain credentials. */
12
+ export const MODEL_PROVIDER_ERROR_CODES = Object.freeze([
13
+ 'rate_limit_error', 'rate_limit_exceeded', 'overloaded_error', 'server_error',
14
+ 'api_error', 'service_unavailable_error', 'server_is_overloaded', 'timeout_error',
15
+ 'MODEL_PROVIDER_RATE_LIMIT', 'MODEL_PROVIDER_UNAVAILABLE',
16
+ 'invalid_request_error', 'invalid_api_key', 'authentication_error', 'permission_error',
17
+ 'not_found_error', 'request_too_large', 'billing_error', 'insufficient_quota',
18
+ 'MODEL_PROVIDER_AUTHENTICATION', 'MODEL_PROVIDER_PERMISSION', 'MODEL_PROVIDER_INVALID_REQUEST',
19
+ 'MODEL_PROVIDER_NOT_FOUND', 'MODEL_PROVIDER_QUOTA_EXHAUSTED',
20
+ ] as const);
21
+ export const MODEL_PROVIDER_ERROR_TYPES = Object.freeze([...MODEL_PROVIDER_ERROR_CODES,
22
+ 'TooManyRequestsError', 'ServiceUnavailableError', 'RequestTimeoutError',
23
+ 'UnauthorizedError', 'ForbiddenError', 'InternalServerError', 'BadRequestError',
24
+ 'NotFoundError', 'AuthenticationError', 'PermissionDeniedError', 'RateLimitError',
25
+ ] as const);
26
+ export interface ModelProviderErrorDiagnostic {
27
+ category: 'rate_limit' | 'server_error' | 'request_timeout' | 'client_error' | 'invalid_response';
28
+ fingerprint: string;
29
+ code?: typeof MODEL_PROVIDER_ERROR_CODES[number];
30
+ type?: typeof MODEL_PROVIDER_ERROR_TYPES[number];
31
+ status?: number;
32
+ }
11
33
  export interface ModelFailureDiagnostic {
12
- contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2';
34
+ contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2' | 'model-failure-diagnostic/v3';
13
35
  protocol: 'openai-chat' | 'openai-responses' | 'anthropic-messages' | 'unknown';
14
36
  phase: 'binding' | 'request' | 'headers' | 'http-error' | 'stream' | 'buffered';
15
37
  code: typeof MODEL_FAILURE_CODES[number];
16
38
  frameIndex?: number;
17
39
  httpStatus?: number;
40
+ /** Observational only. Raw error messages, headers and bodies are excluded. */
41
+ providerError?: ModelProviderErrorDiagnostic;
18
42
  /** Observed counters only, never a replacement for the sealed billable usage. */
19
43
  usageConflict?: {
20
44
  previousFrameIndex: number;
@@ -37,9 +61,10 @@ function validUsageCounters(value: ModelUsageCounters): boolean {
37
61
  }
38
62
  export function validateModelFailure(value: ModelFailureDiagnostic | undefined): void {
39
63
  if (value === undefined) return;
40
- invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2'].includes(value.contract)
64
+ invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2', 'model-failure-diagnostic/v3'].includes(value.contract)
41
65
  && Object.keys(value).every(key => ['contract', 'protocol', 'phase', 'code', 'frameIndex', 'httpStatus',
42
- ...(value.contract === 'model-failure-diagnostic/v2' ? ['usageConflict'] : [])].includes(key))
66
+ ...(value.contract === 'model-failure-diagnostic/v2' ? ['usageConflict'] : []),
67
+ ...(value.contract === 'model-failure-diagnostic/v3' ? ['providerError'] : [])].includes(key))
43
68
  && ['openai-chat', 'openai-responses', 'anthropic-messages', 'unknown'].includes(value.protocol)
44
69
  && ['binding', 'request', 'headers', 'http-error', 'stream', 'buffered'].includes(value.phase)
45
70
  && MODEL_FAILURE_CODES.includes(value.code)
@@ -57,6 +82,18 @@ export function validateModelFailure(value: ModelFailureDiagnostic | undefined):
57
82
  && (conflict.previous.inputTokens !== conflict.reported.inputTokens
58
83
  || conflict.previous.outputTokens !== conflict.reported.outputTokens), 'invalid_model_failure_diagnostic');
59
84
  }
85
+ if (value.contract === 'model-failure-diagnostic/v3') {
86
+ const provider = value.providerError;
87
+ invariant(value.code === 'provider_error' && ['openai-chat', 'openai-responses'].includes(value.protocol)
88
+ && ['stream', 'buffered'].includes(value.phase) && provider && typeof provider === 'object'
89
+ && !Array.isArray(provider) && Object.keys(provider).every(key => ['category', 'fingerprint', 'code', 'type', 'status'].includes(key))
90
+ && ['rate_limit', 'server_error', 'request_timeout', 'client_error', 'invalid_response'].includes(provider.category)
91
+ && typeof provider.fingerprint === 'string' && /^sha256:[0-9a-f]{64}$/.test(provider.fingerprint)
92
+ && (provider.code === undefined || MODEL_PROVIDER_ERROR_CODES.includes(provider.code))
93
+ && (provider.type === undefined || MODEL_PROVIDER_ERROR_TYPES.includes(provider.type))
94
+ && (provider.status === undefined || Number.isInteger(provider.status) && provider.status >= 400 && provider.status <= 599),
95
+ 'invalid_model_failure_diagnostic');
96
+ }
60
97
  invariant(!value.code.startsWith('http_') || value.phase === 'http-error' && value.httpStatus !== undefined
61
98
  && (value.code === 'http_authentication' ? value.httpStatus === 401
62
99
  : value.code === 'http_permission' ? value.httpStatus === 403
@@ -9,15 +9,25 @@ export function parseModelJson(text: string): Json { return decodeJson(text, fal
9
9
  export function parseNativeJson(text: string): Json { return decodeJson(text, true, 1024); }
10
10
  function decodeJson(text: string, plainObjects: boolean, maxDepth: number): Json {
11
11
  let position = 0;
12
- function space(): void { while (/[\u0009\u000a\u000d\u0020]/.test(text[position] ?? '\0')) position++; }
13
- function string(): string {
14
- const start = position++;
12
+ // The strict structural decoder still owns duplicate keys, exact integers
13
+ // and depth. Scan text spans in the engine rather than visiting each code
14
+ // unit in JS: persisted code/log strings dominate long-session reads.
15
+ const stringToken = /"[^"\\]*(?:\\[\s\S][^"\\]*)*"/y;
16
+ const numberToken = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
17
+ function space(): void {
15
18
  while (position < text.length) {
16
- const character = text[position++];
17
- if (character === '\\') position++;
18
- else if (character === '"') return JSON.parse(text.slice(start, position)) as string;
19
+ const code = text.charCodeAt(position);
20
+ if (code !== 9 && code !== 10 && code !== 13 && code !== 32) break;
21
+ position++;
19
22
  }
20
- invariant(false, 'invalid_model_json');
23
+ }
24
+ function string(): string {
25
+ stringToken.lastIndex = position;
26
+ const token = stringToken.exec(text);
27
+ invariant(token, 'invalid_model_json');
28
+ position = stringToken.lastIndex;
29
+ // Native decoding validates escapes and rejects raw control characters.
30
+ return JSON.parse(token[0]) as string;
21
31
  }
22
32
  function value(depth: number): Json {
23
33
  invariant(depth <= maxDepth, 'model_json_nesting_exceeded'); space();
@@ -48,8 +58,9 @@ function decodeJson(text: string, plainObjects: boolean, maxDepth: number): Json
48
58
  for (const [literal, result] of [['null', null], ['true', true], ['false', false]] as const) {
49
59
  if (text.startsWith(literal, position)) { position += literal.length; return result; }
50
60
  }
51
- const number = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/.exec(text.slice(position));
52
- invariant(number, 'invalid_model_json'); position += number[0].length;
61
+ numberToken.lastIndex = position;
62
+ const number = numberToken.exec(text);
63
+ invariant(number, 'invalid_model_json'); position = numberToken.lastIndex;
53
64
  const lexeme = number[0], result = Number(lexeme);
54
65
  if (!/[.eE]/.test(lexeme) && !Number.isSafeInteger(result)) {
55
66
  // Python's JSON decoder uses arbitrary precision int, with its default
@@ -1,5 +1,5 @@
1
1
  import type { CommitBatch, Message, ModelResult, ObjectValue, RunConfiguration, RunSnapshot, StoredRun } from './contracts.mjs';
2
- import { responseContinuationPairs, responseContinuationPending, joinResponseContinuation } from './response-continuation.mjs';
2
+ import { responseBoundaryRecovery, responseContinuationPairs, responseContinuationPending, joinResponseContinuation } from './response-continuation.mjs';
3
3
  import { canonical, copy, invariant } from './values.mjs';
4
4
  import { contextMessageRef } from './context-planning.mjs';
5
5
 
@@ -7,7 +7,11 @@ type Digest = (value: unknown) => string;
7
7
 
8
8
  /** Select from actual admission after the completed model claim, never the catalog. */
9
9
  export function outputRecoveryMode(snapshot: RunSnapshot, config: RunConfiguration, toolsAvailable: boolean, result?: ModelResult): 'suffix' | 'task_resume' {
10
- if (config.outputRecoveryPolicy === 'response-boundary/v2' && config.contract.finalOutputFormat === 'text') {
10
+ if (responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text') {
11
+ // A provider length boundary identifies truncated text, not task completion.
12
+ // Preserve explicit sealed delivery, otherwise retain the admitted tools.
13
+ if (config.outputRecoveryPolicy === 'response-boundary/v3')
14
+ return responseContinuationPending(snapshot, config) || !toolsAvailable ? 'suffix' : 'task_resume';
11
15
  if (responseContinuationPending(snapshot, config)
12
16
  || result?.textCommitVersion === 'provider-finished-text/v1' && result.outputBoundary === 'assistant-text/v1') return 'suffix';
13
17
  if (result?.outputBoundary === 'tool-call/v1') return 'task_resume';
@@ -1,5 +1,15 @@
1
1
  import type { Message, RunConfiguration, RunSnapshot } from './contracts.mjs';
2
2
 
3
+ /** The output recovery strategy is versioned separately from the sealed v2
4
+ * text-fragment protocol. A v3 task may still own an explicit suffix chain. */
5
+ export function responseBoundaryRecovery(config: Pick<RunConfiguration, 'outputRecoveryPolicy'>): boolean {
6
+ return config.outputRecoveryPolicy === 'response-boundary/v2' || config.outputRecoveryPolicy === 'response-boundary/v3';
7
+ }
8
+
9
+ export function responseScopedOutputRestarts(config: Pick<RunConfiguration, 'outputRestartPolicy'>): boolean {
10
+ return config.outputRestartPolicy === 'per-response/v1' || config.outputRestartPolicy === 'per-response/v2';
11
+ }
12
+
3
13
  /** Journaled Host controls may be staged between response fragments. Actual
4
14
  * user input, tool observations and new assistant messages end the chain. */
5
15
  function hostControl(message: Message): boolean {
@@ -26,7 +36,7 @@ export function responseContinuationPairs(messages: Message[], digest?: (value:
26
36
 
27
37
  /** This only narrows admission. Digest validation is required for assembly. */
28
38
  export function responseContinuationPending(snapshot: RunSnapshot, config: RunConfiguration): boolean {
29
- return config.outputRecoveryPolicy === 'response-boundary/v2' && responseContinuationPairs(snapshot.messages).length > 0;
39
+ return responseBoundaryRecovery(config) && responseContinuationPairs(snapshot.messages).length > 0;
30
40
  }
31
41
 
32
42
  /** The v2 wire contract permits replay of exactly the unfinished final line.
package/src/store.mts CHANGED
@@ -412,7 +412,8 @@ export class TransactionalRunStore implements RunStore {
412
412
  const command = parent.commands.find(row => !row.consumed && row.command.commandId === batch.consumedCommandId)?.command;
413
413
  invariant(command, 'child_control_command_missing');
414
414
  validateChildControlDelivery(parent, childRecord, command, delivery);
415
- invariant(batch.events.some(event => event.kind === (command.kind === 'message_child' ? 'child.input_queued' : 'child.cancel_requested')
415
+ invariant(batch.events.some(event => event.kind === (command.kind === 'message_child' ? 'child.input_queued'
416
+ : command.kind === 'resume_child' ? 'child.resume_requested' : 'child.cancel_requested')
416
417
  && event.payload.commandId === command.commandId && event.payload.childRunId === target.runId), 'child_control_event_missing');
417
418
  invariant(!previous || canonical(previous.command) === canonical(delivery.command), 'command_replay_conflict');
418
419
  return { records: [updated.record, previous ? childRecord : { ...childRecord,
@@ -27,6 +27,8 @@ export function toolDiscoveryDefinitions(): ToolDefinition[] {
27
27
 
28
28
  export function validateToolDiscovery(config: RunConfiguration): void {
29
29
  invariant(config.toolDiscoveryPolicy === undefined || config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_tool_discovery_policy');
30
+ invariant(config.toolAdmissionPolicy === undefined || config.toolAdmissionPolicy === 'discover-before-retry/v1'
31
+ && config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_tool_admission_policy');
30
32
  invariant(config.profile.providerToolSearchPolicy === undefined || config.profile.providerToolSearchPolicy === 'local-only/v1'
31
33
  || config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1'
32
34
  && config.profile.providerFamily === 'anthropic-messages' && config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY,
@@ -127,6 +129,41 @@ export function discoveredCallExposed(snapshot: RunSnapshot, config: RunConfigur
127
129
  && snapshot.toolDiscovery?.discovered.includes(call.name) === true;
128
130
  }
129
131
 
132
+ /** Exact, scoped names are sufficient evidence to discover a definition, not to
133
+ * authorize its proposed operation. Promote only newly exposed schemas, bounded
134
+ * like a search result. The next model request must resubmit through the normal
135
+ * schema/permission/approval path. Omission preserves historical admission. */
136
+ export function discoverRejectedCalls(snapshot: RunSnapshot, config: RunConfiguration, calls: ToolCall[],
137
+ tools: ToolDefinition[]): { state: NonNullable<RunSnapshot['toolDiscovery']>; names: string[] } | null {
138
+ if (config.toolAdmissionPolicy !== 'discover-before-retry/v1' || !snapshot.toolDiscovery) return null;
139
+ const wrapper = tools.find(tool => tool.name === DEFERRED_TOOL_CALL);
140
+ const names: string[] = [], definitions: ObjectValue[] = [];
141
+ for (const call of calls) {
142
+ if (call.wireArgumentsInvalid || call.modelCallWrapper) continue;
143
+ const wrapped = call.name === DEFERRED_TOOL_CALL;
144
+ if (wrapped && (!wrapper || toolInputRejection(wrapper, call))) continue;
145
+ if (!wrapped && discoveredCallExposed(snapshot, config, call)) continue;
146
+ const name = wrapped ? String(call.arguments.name) : call.name;
147
+ if (names.includes(name) || snapshot.toolDiscovery.promoted.includes(name)
148
+ || wrapped && snapshot.toolDiscovery.discovered.includes(name)) continue;
149
+ const target = tools.find(tool => tool.name === name && tool.discovery?.deferred
150
+ && (config.contract.allowedToolNames === null || config.contract.allowedToolNames.includes(name)));
151
+ if (!target) continue;
152
+ const entry = { name, description: target.description, parameters: copy(target.parameters) };
153
+ // Keep metadata discovery finite and no larger than the existing search
154
+ // model-view envelope. Oversized schemas must use the explicit search path.
155
+ const bytes = new TextEncoder().encode(canonical({ content: canonical({ definitions: [...definitions, entry] }),
156
+ media: [], additionalContexts: [] })).length;
157
+ if (bytes + 32 > config.limits.maxToolResultBytes) continue;
158
+ names.push(name); definitions.push(entry);
159
+ if (names.length === 20) break;
160
+ }
161
+ return names.length ? { names, state: {
162
+ discovered: [...new Set([...snapshot.toolDiscovery.discovered, ...names])],
163
+ promoted: [...snapshot.toolDiscovery.promoted, ...names],
164
+ } } : null;
165
+ }
166
+
130
167
  /** Describe a rejected model call using only the current, scoped execution
131
168
  * catalog. Discovery is a suggested next call, never authority to dispatch the
132
169
  * rejected operation. Historical events and frozen tool definitions stay intact. */
@@ -6,6 +6,7 @@ import type { SteeringBindings } from './task-contract.mjs';
6
6
  import { admitChildPromotion, unsettledChildren } from './child-runtime.mjs';
7
7
  import { guidanceReason } from './guidance.mjs';
8
8
  import { bindOperatorInput } from './anthropic-context.mjs';
9
+ import { APPROVAL_OUTCOME_POLICY, normalizeHostApprovalOutcome, approvalOutcomePauseReason } from './approval-outcome.mjs';
9
10
 
10
11
  export function transition(snapshot: RunSnapshot, changes: Partial<RunSnapshot>, facts: { kind: string; payload: ObjectValue }[] = [],
11
12
  options: { intents?: EffectIntent[]; receipts?: EffectReceipt[]; commandId?: string; requireNoPendingCommands?: boolean } = {}): CommitBatch {
@@ -144,18 +145,34 @@ export function reduceCommand(snapshot: RunSnapshot, command: RunCommand, pendin
144
145
  case 'resume':
145
146
  if (snapshot.phase !== 'paused') reason = 'not_paused';
146
147
  else changes = { phase: snapshot.resumePhase ?? 'preparing_context', resumePhase: null,
147
- ...(['provider_unavailable', 'context_summary_unavailable'].includes(snapshot.reason ?? '') ? { reason: null } : {}) };
148
+ ...(snapshot.reason === 'output_budget_exhausted' && bindings.configuration?.outputRestartPolicy === 'per-response/v2'
149
+ ? { reason: null, continuations: 0, outputRestarts: 0 } : {}),
150
+ ...(bindings.configuration?.approvalOutcomePolicy === APPROVAL_OUTCOME_POLICY
151
+ && ['approval_rejected', 'approval_cancelled', 'approval_unavailable'].includes(snapshot.reason ?? '') ? { reason: null } : {}),
152
+ ...(['provider_unavailable', 'context_summary_unavailable', 'child_paused'].includes(snapshot.reason ?? '') ? { reason: null } : {}) };
148
153
  break;
149
154
  case 'submit_interaction': {
150
155
  const pending = snapshot.pendingInteraction;
156
+ const hasOutcome = Object.hasOwn(command.payload, 'approvalOutcome');
157
+ const approvalOutcome = normalizeHostApprovalOutcome(command.payload.approvalOutcome);
151
158
  if (snapshot.phase !== 'awaiting_interaction' || !pending || command.payload.interactionId !== pending.interactionId
152
159
  || command.payload.decision !== 'allow' && command.payload.decision !== 'deny') reason = 'interaction_mismatch';
160
+ else if (hasOutcome && (bindings.configuration?.approvalOutcomePolicy !== APPROVAL_OUTCOME_POLICY
161
+ || approvalOutcome !== command.payload.approvalOutcome
162
+ || (approvalOutcome === 'allowed-once') !== (command.payload.decision === 'allow'))) reason = 'interaction_outcome_mismatch';
153
163
  else {
154
164
  changes = { phase: snapshot.childApproval ? snapshot.resumePhase ?? 'preparing_context' : 'executing_tools',
155
165
  ...(snapshot.childApproval ? { resumePhase: null, childLifecycleCursor: null } : {}), pendingInteraction: null,
156
166
  interaction: pending.approvalPolicy === 'durable-preflight/v1' ? null : { interactionId: pending.hostInteractionId, callId: pending.callId, decision: command.payload.decision,
167
+ ...(hasOutcome ? { approvalOutcome } : {}),
157
168
  ...(snapshot.planMode && typeof command.payload.feedback === 'string' ? { feedback: command.payload.feedback } : {}) } };
158
- facts.push({ kind: 'approval.resolved', payload: { interactionId: pending.interactionId, callId: pending.callId, decision: command.payload.decision } });
169
+ // One human answer pauses the interactive owner once. Its children
170
+ // receive the same denied decision after that owner is explicitly
171
+ // resumed; no second pause or implicit tool permission is introduced.
172
+ const pauseReason = hasOutcome && !bindings.configuration?.childOwnerBinding ? approvalOutcomePauseReason(approvalOutcome) : null;
173
+ if (pauseReason) Object.assign(changes, { resumePhase: changes.phase, phase: 'paused', reason: pauseReason, outcome: null });
174
+ facts.push({ kind: 'approval.resolved', payload: { interactionId: pending.interactionId, callId: pending.callId, decision: command.payload.decision,
175
+ ...(hasOutcome ? { approvalOutcome } : {}) } });
159
176
  }
160
177
  break;
161
178
  }