@kingsoftcloud/agentkit-harness-core 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.
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-notification.mjs +5 -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 +3 -0
  9. package/dist/configuration.mjs +13 -4
  10. package/dist/context-contributions.d.mts +2 -0
  11. package/dist/context-contributions.mjs +100 -48
  12. package/dist/context-planning.mjs +2 -2
  13. package/dist/contracts.d.mts +22 -5
  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 +52 -6
  19. package/dist/machine.mjs +44 -24
  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 +13 -1
  28. package/dist/tool-discovery.mjs +67 -0
  29. package/dist/transitions.mjs +21 -2
  30. package/package.json +1 -1
  31. package/src/approval-outcome.mts +12 -0
  32. package/src/background-notification.mts +5 -2
  33. package/src/child-contract.mts +2 -0
  34. package/src/child-control.mts +16 -2
  35. package/src/child-runtime.mts +7 -1
  36. package/src/configuration.mts +17 -4
  37. package/src/context-contributions.mts +84 -38
  38. package/src/context-planning.mts +2 -2
  39. package/src/contracts.mts +19 -6
  40. package/src/index.mts +1 -0
  41. package/src/kernel.mts +47 -6
  42. package/src/machine.mts +46 -24
  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 +63 -1
  49. package/src/transitions.mts +19 -2
package/dist/kernel.mjs CHANGED
@@ -26,7 +26,7 @@ import { contextSourceDigest, modelContextMessages, validateContextMessages } fr
26
26
  import { assertHookFeedbackRetained, deniedByHook, reduceHook, stagePostHooks } from './hook-runtime.mjs';
27
27
  import { hookBytes, hookResult } from './hook-contract.mjs';
28
28
  import { planNativeContext, reduceContextModel } from './context-planning.mjs';
29
- import { collectContextContributions } from './context-contributions.mjs';
29
+ import { collectContextContributions, contextSourceUnavailable } from './context-contributions.mjs';
30
30
  import { validateInstructionScopes } from './instruction-scopes.mjs';
31
31
  import { refreshContextSources } from './context-source-refresh.mjs';
32
32
  import { outputRestartPayload } from './output-recovery.mjs';
@@ -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
@@ -1011,6 +1047,7 @@ export class NativeKernel {
1011
1047
  }
1012
1048
  catch (error) {
1013
1049
  const code = isNativeError(error) ? error.code : 'effect_port_error';
1050
+ const unavailableSource = contextSourceUnavailable(error, configuration);
1014
1051
  facts.push(observedEffectFailure({ operationKey: intent.operationKey, kind: intent.kind, code,
1015
1052
  nativeError: isNativeError(error), signalAborted: effectSignal.aborted,
1016
1053
  elapsedMs: this.monotonicNow() - started, initialTimeoutMs: timeoutMs, observedAtMs: this.now(),
@@ -1065,6 +1102,15 @@ export class NativeKernel {
1065
1102
  childLifecycleFailure: intent.payload.action, outcome: 'unverified', reason: 'child_owner_unavailable' };
1066
1103
  }
1067
1104
  }
1105
+ else if (intent.kind === 'context' && !effectSignal.aborted && code === 'context_source_unavailable'
1106
+ && unavailableSource
1107
+ && ['preparing_context', 'compacting'].includes(snapshot.phase)) {
1108
+ raw = { code };
1109
+ status = 'failed';
1110
+ changes = { pendingIntent: null, preparedContext: null, phase: 'paused', resumePhase: snapshot.phase,
1111
+ outcome: null, reason: code, context: { ...snapshot.context, preparedCursor: null } };
1112
+ facts.push({ kind: 'context.source_unavailable', payload: { ...unavailableSource, reason: code, operationKey: intent.operationKey } });
1113
+ }
1068
1114
  else if (intent.kind === 'context' && configuration.contextPolicy || ['invalid_context_messages', 'invalid_context_tool_pairing', 'context_binding_mismatch', 'context_hook_feedback_missing', 'context_guidance_missing'].includes(code)) {
1069
1115
  raw = { code };
1070
1116
  status = 'failed';
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, 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';
@@ -251,7 +251,7 @@ export function plan(snapshot, config, capabilities, digest = canonical, policie
251
251
  const definition = config.tools.find(tool => tool.name === first.name);
252
252
  if (!definition || config.contract.allowedToolNames !== null && !config.contract.allowedToolNames.includes(first.name)) {
253
253
  return transition(snapshot, { pendingTools: snapshot.pendingTools.slice(1), messages: [...snapshot.messages,
254
- { role: 'tool', content: canonical({ status: 'error', code: 'tool_not_advertised' }), callId: first.callId, name: first.name }] }, [{ kind: 'tool.rejected', payload: { callId: first.callId, name: first.name, reason: 'tool_not_advertised' } }]);
254
+ { role: 'tool', content: canonical(toolAdmissionRejection(snapshot, config, first, advertisedTools(snapshot, config, policies))), callId: first.callId, name: first.name }] }, [{ kind: 'tool.rejected', payload: { callId: first.callId, name: first.name, reason: 'tool_not_advertised' } }]);
255
255
  }
256
256
  if (toolRoom(snapshot, config) <= 0) {
257
257
  const messages = snapshot.pendingTools.map(call => ({ role: 'tool', callId: call.callId, name: call.name,
@@ -400,20 +400,27 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
400
400
  if (finalizationOnly({ ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config)) {
401
401
  return { ...base, phase: 'finalizing', outcome: 'budget_exhausted', reason: 'tool_call_after_finalization_reserve' };
402
402
  }
403
- if (result.toolCalls.some(call => !advertisedTools({ ...snapshot,
404
- usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies).some(tool => tool.name === call.name)
403
+ const tools = advertisedTools({ ...snapshot,
404
+ usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies);
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)
405
408
  || !discoveredCallExposed(snapshot, config, call))) {
406
- const unbound = result.toolCalls.some(call => !config.tools.some(tool => tool.name === call.name)
407
- || !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));
408
411
  const errors = snapshot.modelErrors + Number(unbound), exhausted = errors > config.profile.maxRetries;
409
412
  return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [], modelErrors: errors,
413
+ ...(discovery ? { toolDiscovery: discovery.state } : {}),
410
414
  outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'tool_call_not_advertised_retry_exhausted' : null, messages: [...snapshot.messages,
411
415
  { ...message, toolCalls: result.toolCalls }, ...result.toolCalls.map(call => ({ role: 'tool',
412
- callId: call.callId, name: call.name, content: canonical({ status: 'error', code: 'tool_not_advertised' }) }))] };
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.' } : {}) }) }))] };
413
419
  }
414
420
  return { ...base, phase: 'executing_tools', pendingTools: result.toolCalls,
415
421
  messages: [...snapshot.messages, { ...message, toolCalls: result.toolCalls }],
416
- continuations: 0, modelErrors: 0 };
422
+ continuations: 0, modelErrors: 0,
423
+ ...(responseScopedOutputRestarts(config) ? { outputRestarts: 0 } : {}) };
417
424
  case 'final_candidate': {
418
425
  if (config.contract.finalSubmissionSchema) {
419
426
  const errors = snapshot.modelErrors + 1;
@@ -430,9 +437,33 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
430
437
  messages: [...snapshot.messages, { ...message, content: text, kind: 'final_candidate' }] };
431
438
  }
432
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' };
433
461
  if (snapshot.continuations >= config.profile.maxContinuations) {
434
- if (responseContinuationPending(snapshot, config))
435
- 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() };
436
467
  if (snapshot.outputRestarts < config.limits.maxOutputRestarts) {
437
468
  try {
438
469
  return { ...base, ...restartContinuation(snapshot, config, result.text, digest), phase: 'preparing_context',
@@ -444,26 +475,15 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
444
475
  return { ...base, phase: 'finalizing', outcome: 'blocked', reason: String(error.code) };
445
476
  }
446
477
  }
447
- return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
478
+ return { ...base, ...exhausted() };
448
479
  }
449
480
  if (!result.text && responseContinuationPending(snapshot, config))
450
481
  return { ...base, phase: 'preparing_context',
451
482
  continuations: snapshot.continuations + 1,
452
483
  messages: [...snapshot.messages, { role: 'user', kind: 'response_continuation_feedback',
453
484
  content: 'No visible continuation was returned. The interrupted text response is still pending. Return only its missing text suffix.' }] };
454
- const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config, advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
455
- const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
456
485
  return { ...base, phase: 'preparing_context', continuations: snapshot.continuations + 1,
457
- messages: [...snapshot.messages, ...(result.text ? [{ ...message, kind: 'continuation_fragment', continuationResponseId: responseId }] : []),
458
- { role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
459
- ...(config.outputRecoveryPolicy === 'response-boundary/v2' && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
460
- ? { continuationPolicy: 'response-boundary/v2' } : {}),
461
- continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
462
- ? '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.'
463
- : result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
464
- + (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. ' : '')
465
- + 'Incomplete tool calls were not executed.'
466
- : '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 };
467
487
  }
468
488
  case 'context_overflow':
469
489
  return { ...base, phase: 'compacting', context: { ...snapshot.context, preparedCursor: null } };
@@ -1,12 +1,24 @@
1
1
  /** Observational only: these facts never authorize retries or tool execution. */
2
2
  export declare const MODEL_FAILURE_CODES: readonly ["host_binding", "request_invalid", "http_authentication", "http_permission", "http_client", "http_server", "http_rate_limit", "http_timeout", "protocol_invalid", "json_invalid", "envelope_invalid", "provider_error", "identity_conflict", "usage_invalid", "usage_conflict", "choice_invalid", "delta_invalid", "termination_conflict", "framing_invalid", "body_limit", "body_encoding", "transport_error", "stream_timeout", "stream_incomplete", "tool_payload_invalid"];
3
+ /** Closed provider identifiers only; arbitrary provider strings can contain credentials. */
4
+ export declare const MODEL_PROVIDER_ERROR_CODES: readonly ["rate_limit_error", "rate_limit_exceeded", "overloaded_error", "server_error", "api_error", "service_unavailable_error", "server_is_overloaded", "timeout_error", "MODEL_PROVIDER_RATE_LIMIT", "MODEL_PROVIDER_UNAVAILABLE", "invalid_request_error", "invalid_api_key", "authentication_error", "permission_error", "not_found_error", "request_too_large", "billing_error", "insufficient_quota", "MODEL_PROVIDER_AUTHENTICATION", "MODEL_PROVIDER_PERMISSION", "MODEL_PROVIDER_INVALID_REQUEST", "MODEL_PROVIDER_NOT_FOUND", "MODEL_PROVIDER_QUOTA_EXHAUSTED"];
5
+ export declare const MODEL_PROVIDER_ERROR_TYPES: readonly ["rate_limit_error", "rate_limit_exceeded", "overloaded_error", "server_error", "api_error", "service_unavailable_error", "server_is_overloaded", "timeout_error", "MODEL_PROVIDER_RATE_LIMIT", "MODEL_PROVIDER_UNAVAILABLE", "invalid_request_error", "invalid_api_key", "authentication_error", "permission_error", "not_found_error", "request_too_large", "billing_error", "insufficient_quota", "MODEL_PROVIDER_AUTHENTICATION", "MODEL_PROVIDER_PERMISSION", "MODEL_PROVIDER_INVALID_REQUEST", "MODEL_PROVIDER_NOT_FOUND", "MODEL_PROVIDER_QUOTA_EXHAUSTED", "TooManyRequestsError", "ServiceUnavailableError", "RequestTimeoutError", "UnauthorizedError", "ForbiddenError", "InternalServerError", "BadRequestError", "NotFoundError", "AuthenticationError", "PermissionDeniedError", "RateLimitError"];
6
+ export interface ModelProviderErrorDiagnostic {
7
+ category: 'rate_limit' | 'server_error' | 'request_timeout' | 'client_error' | 'invalid_response';
8
+ fingerprint: string;
9
+ code?: typeof MODEL_PROVIDER_ERROR_CODES[number];
10
+ type?: typeof MODEL_PROVIDER_ERROR_TYPES[number];
11
+ status?: number;
12
+ }
3
13
  export interface ModelFailureDiagnostic {
4
- contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2';
14
+ contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2' | 'model-failure-diagnostic/v3';
5
15
  protocol: 'openai-chat' | 'openai-responses' | 'anthropic-messages' | 'unknown';
6
16
  phase: 'binding' | 'request' | 'headers' | 'http-error' | 'stream' | 'buffered';
7
17
  code: typeof MODEL_FAILURE_CODES[number];
8
18
  frameIndex?: number;
9
19
  httpStatus?: number;
20
+ /** Observational only. Raw error messages, headers and bodies are excluded. */
21
+ providerError?: ModelProviderErrorDiagnostic;
10
22
  /** Observed counters only, never a replacement for the sealed billable usage. */
11
23
  usageConflict?: {
12
24
  previousFrameIndex: number;
@@ -7,6 +7,21 @@ export const MODEL_FAILURE_CODES = [
7
7
  'choice_invalid', 'delta_invalid', 'termination_conflict', 'framing_invalid', 'body_limit',
8
8
  'body_encoding', 'transport_error', 'stream_timeout', 'stream_incomplete', 'tool_payload_invalid',
9
9
  ];
10
+ /** Closed provider identifiers only; arbitrary provider strings can contain credentials. */
11
+ export const MODEL_PROVIDER_ERROR_CODES = Object.freeze([
12
+ 'rate_limit_error', 'rate_limit_exceeded', 'overloaded_error', 'server_error',
13
+ 'api_error', 'service_unavailable_error', 'server_is_overloaded', 'timeout_error',
14
+ 'MODEL_PROVIDER_RATE_LIMIT', 'MODEL_PROVIDER_UNAVAILABLE',
15
+ 'invalid_request_error', 'invalid_api_key', 'authentication_error', 'permission_error',
16
+ 'not_found_error', 'request_too_large', 'billing_error', 'insufficient_quota',
17
+ 'MODEL_PROVIDER_AUTHENTICATION', 'MODEL_PROVIDER_PERMISSION', 'MODEL_PROVIDER_INVALID_REQUEST',
18
+ 'MODEL_PROVIDER_NOT_FOUND', 'MODEL_PROVIDER_QUOTA_EXHAUSTED',
19
+ ]);
20
+ export const MODEL_PROVIDER_ERROR_TYPES = Object.freeze([...MODEL_PROVIDER_ERROR_CODES,
21
+ 'TooManyRequestsError', 'ServiceUnavailableError', 'RequestTimeoutError',
22
+ 'UnauthorizedError', 'ForbiddenError', 'InternalServerError', 'BadRequestError',
23
+ 'NotFoundError', 'AuthenticationError', 'PermissionDeniedError', 'RateLimitError',
24
+ ]);
10
25
  const usageCounterKeys = ['inputTokens', 'outputTokens', 'cachedInputTokens', 'reasoningTokens'];
11
26
  function validUsageCounters(value) {
12
27
  return Boolean(value && typeof value === 'object' && !Array.isArray(value)
@@ -17,9 +32,10 @@ function validUsageCounters(value) {
17
32
  export function validateModelFailure(value) {
18
33
  if (value === undefined)
19
34
  return;
20
- invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2'].includes(value.contract)
35
+ invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2', 'model-failure-diagnostic/v3'].includes(value.contract)
21
36
  && Object.keys(value).every(key => ['contract', 'protocol', 'phase', 'code', 'frameIndex', 'httpStatus',
22
- ...(value.contract === 'model-failure-diagnostic/v2' ? ['usageConflict'] : [])].includes(key))
37
+ ...(value.contract === 'model-failure-diagnostic/v2' ? ['usageConflict'] : []),
38
+ ...(value.contract === 'model-failure-diagnostic/v3' ? ['providerError'] : [])].includes(key))
23
39
  && ['openai-chat', 'openai-responses', 'anthropic-messages', 'unknown'].includes(value.protocol)
24
40
  && ['binding', 'request', 'headers', 'http-error', 'stream', 'buffered'].includes(value.phase)
25
41
  && MODEL_FAILURE_CODES.includes(value.code)
@@ -37,6 +53,17 @@ export function validateModelFailure(value) {
37
53
  && (conflict.previous.inputTokens !== conflict.reported.inputTokens
38
54
  || conflict.previous.outputTokens !== conflict.reported.outputTokens), 'invalid_model_failure_diagnostic');
39
55
  }
56
+ if (value.contract === 'model-failure-diagnostic/v3') {
57
+ const provider = value.providerError;
58
+ invariant(value.code === 'provider_error' && ['openai-chat', 'openai-responses'].includes(value.protocol)
59
+ && ['stream', 'buffered'].includes(value.phase) && provider && typeof provider === 'object'
60
+ && !Array.isArray(provider) && Object.keys(provider).every(key => ['category', 'fingerprint', 'code', 'type', 'status'].includes(key))
61
+ && ['rate_limit', 'server_error', 'request_timeout', 'client_error', 'invalid_response'].includes(provider.category)
62
+ && typeof provider.fingerprint === 'string' && /^sha256:[0-9a-f]{64}$/.test(provider.fingerprint)
63
+ && (provider.code === undefined || MODEL_PROVIDER_ERROR_CODES.includes(provider.code))
64
+ && (provider.type === undefined || MODEL_PROVIDER_ERROR_TYPES.includes(provider.type))
65
+ && (provider.status === undefined || Number.isInteger(provider.status) && provider.status >= 400 && provider.status <= 599), 'invalid_model_failure_diagnostic');
66
+ }
40
67
  invariant(!value.code.startsWith('http_') || value.phase === 'http-error' && value.httpStatus !== undefined
41
68
  && (value.code === 'http_authentication' ? value.httpStatus === 401
42
69
  : value.code === 'http_permission' ? value.httpStatus === 403
@@ -6,18 +6,26 @@ export function parseModelJson(text) { return decodeJson(text, false, 256); }
6
6
  export function parseNativeJson(text) { return decodeJson(text, true, 1024); }
7
7
  function decodeJson(text, plainObjects, maxDepth) {
8
8
  let position = 0;
9
- function space() { while (/[\u0009\u000a\u000d\u0020]/.test(text[position] ?? '\0'))
10
- position++; }
11
- function string() {
12
- const start = position++;
9
+ // The strict structural decoder still owns duplicate keys, exact integers
10
+ // and depth. Scan text spans in the engine rather than visiting each code
11
+ // unit in JS: persisted code/log strings dominate long-session reads.
12
+ const stringToken = /"[^"\\]*(?:\\[\s\S][^"\\]*)*"/y;
13
+ const numberToken = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
14
+ function space() {
13
15
  while (position < text.length) {
14
- const character = text[position++];
15
- if (character === '\\')
16
- position++;
17
- else if (character === '"')
18
- return JSON.parse(text.slice(start, position));
16
+ const code = text.charCodeAt(position);
17
+ if (code !== 9 && code !== 10 && code !== 13 && code !== 32)
18
+ break;
19
+ position++;
19
20
  }
20
- invariant(false, 'invalid_model_json');
21
+ }
22
+ function string() {
23
+ stringToken.lastIndex = position;
24
+ const token = stringToken.exec(text);
25
+ invariant(token, 'invalid_model_json');
26
+ position = stringToken.lastIndex;
27
+ // Native decoding validates escapes and rejects raw control characters.
28
+ return JSON.parse(token[0]);
21
29
  }
22
30
  function value(depth) {
23
31
  invariant(depth <= maxDepth, 'model_json_nesting_exceeded');
@@ -74,9 +82,10 @@ function decodeJson(text, plainObjects, maxDepth) {
74
82
  return result;
75
83
  }
76
84
  }
77
- const number = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/.exec(text.slice(position));
85
+ numberToken.lastIndex = position;
86
+ const number = numberToken.exec(text);
78
87
  invariant(number, 'invalid_model_json');
79
- position += number[0].length;
88
+ position = numberToken.lastIndex;
80
89
  const lexeme = number[0], result = Number(lexeme);
81
90
  if (!/[.eE]/.test(lexeme) && !Number.isSafeInteger(result)) {
82
91
  // Python's JSON decoder uses arbitrary precision int, with its default
@@ -1,9 +1,13 @@
1
- import { responseContinuationPairs, responseContinuationPending, joinResponseContinuation } from './response-continuation.mjs';
1
+ import { responseBoundaryRecovery, responseContinuationPairs, responseContinuationPending, joinResponseContinuation } from './response-continuation.mjs';
2
2
  import { canonical, copy, invariant } from './values.mjs';
3
3
  import { contextMessageRef } from './context-planning.mjs';
4
4
  /** Select from actual admission after the completed model claim, never the catalog. */
5
5
  export function outputRecoveryMode(snapshot, config, toolsAvailable, result) {
6
- if (config.outputRecoveryPolicy === 'response-boundary/v2' && config.contract.finalOutputFormat === 'text') {
6
+ if (responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text') {
7
+ // A provider length boundary identifies truncated text, not task completion.
8
+ // Preserve explicit sealed delivery, otherwise retain the admitted tools.
9
+ if (config.outputRecoveryPolicy === 'response-boundary/v3')
10
+ return responseContinuationPending(snapshot, config) || !toolsAvailable ? 'suffix' : 'task_resume';
7
11
  if (responseContinuationPending(snapshot, config)
8
12
  || result?.textCommitVersion === 'provider-finished-text/v1' && result.outputBoundary === 'assistant-text/v1')
9
13
  return 'suffix';
@@ -1,4 +1,8 @@
1
1
  import type { Message, RunConfiguration, RunSnapshot } from './contracts.mjs';
2
+ /** The output recovery strategy is versioned separately from the sealed v2
3
+ * text-fragment protocol. A v3 task may still own an explicit suffix chain. */
4
+ export declare function responseBoundaryRecovery(config: Pick<RunConfiguration, 'outputRecoveryPolicy'>): boolean;
5
+ export declare function responseScopedOutputRestarts(config: Pick<RunConfiguration, 'outputRestartPolicy'>): boolean;
2
6
  export declare function responseContinuationPairs(messages: Message[], digest?: (value: unknown) => string): [number, number][];
3
7
  /** This only narrows admission. Digest validation is required for assembly. */
4
8
  export declare function responseContinuationPending(snapshot: RunSnapshot, config: RunConfiguration): boolean;
@@ -1,3 +1,11 @@
1
+ /** The output recovery strategy is versioned separately from the sealed v2
2
+ * text-fragment protocol. A v3 task may still own an explicit suffix chain. */
3
+ export function responseBoundaryRecovery(config) {
4
+ return config.outputRecoveryPolicy === 'response-boundary/v2' || config.outputRecoveryPolicy === 'response-boundary/v3';
5
+ }
6
+ export function responseScopedOutputRestarts(config) {
7
+ return config.outputRestartPolicy === 'per-response/v1' || config.outputRestartPolicy === 'per-response/v2';
8
+ }
1
9
  /** Journaled Host controls may be staged between response fragments. Actual
2
10
  * user input, tool observations and new assistant messages end the chain. */
3
11
  function hostControl(message) {
@@ -26,7 +34,7 @@ export function responseContinuationPairs(messages, digest) {
26
34
  }
27
35
  /** This only narrows admission. Digest validation is required for assembly. */
28
36
  export function responseContinuationPending(snapshot, config) {
29
- return config.outputRecoveryPolicy === 'response-boundary/v2' && responseContinuationPairs(snapshot.messages).length > 0;
37
+ return responseBoundaryRecovery(config) && responseContinuationPairs(snapshot.messages).length > 0;
30
38
  }
31
39
  /** The v2 wire contract permits replay of exactly the unfinished final line.
32
40
  * No complete line, fuzzy match, arbitrary suffix or raw receipt is removed. */
package/dist/store.mjs CHANGED
@@ -358,7 +358,8 @@ export class TransactionalRunStore {
358
358
  const command = parent.commands.find(row => !row.consumed && row.command.commandId === batch.consumedCommandId)?.command;
359
359
  invariant(command, 'child_control_command_missing');
360
360
  validateChildControlDelivery(parent, childRecord, command, delivery);
361
- invariant(batch.events.some(event => event.kind === (command.kind === 'message_child' ? 'child.input_queued' : 'child.cancel_requested')
361
+ invariant(batch.events.some(event => event.kind === (command.kind === 'message_child' ? 'child.input_queued'
362
+ : command.kind === 'resume_child' ? 'child.resume_requested' : 'child.cancel_requested')
362
363
  && event.payload.commandId === command.commandId && event.payload.childRunId === target.runId), 'child_control_event_missing');
363
364
  invariant(!previous || canonical(previous.command) === canonical(delivery.command), 'command_replay_conflict');
364
365
  return { records: [updated.record, previous ? childRecord : { ...childRecord,
@@ -1,4 +1,4 @@
1
- import type { ContextPlanningResult, RunConfiguration, RunSnapshot, ToolCall, ToolDefinition, ToolResult } from './contracts.mjs';
1
+ import type { ContextPlanningResult, ObjectValue, RunConfiguration, RunSnapshot, ToolCall, ToolDefinition, ToolResult } from './contracts.mjs';
2
2
  import type { ToolSearchCandidate } from './tool-search-ranking.mjs';
3
3
  export declare const TOOL_DISCOVERY_POLICY = "local-tool-search/v1";
4
4
  export declare const TOOL_SEARCH = "ToolSearch";
@@ -12,6 +12,18 @@ export declare function discoveryModelTools(snapshot: RunSnapshot, config: RunCo
12
12
  /** Resolve before permission, grouping, budgets and durable operation identity use the target. */
13
13
  export declare function resolveDiscoveredCalls(snapshot: RunSnapshot, config: RunConfiguration, calls: ToolCall[]): ToolCall[];
14
14
  export declare function discoveredCallExposed(snapshot: RunSnapshot, config: RunConfiguration, call: ToolCall): boolean;
15
+ /** Exact, scoped names are sufficient evidence to discover a definition, not to
16
+ * authorize its proposed operation. Promote only newly exposed schemas, bounded
17
+ * like a search result. The next model request must resubmit through the normal
18
+ * schema/permission/approval path. Omission preserves historical admission. */
19
+ export declare function discoverRejectedCalls(snapshot: RunSnapshot, config: RunConfiguration, calls: ToolCall[], tools: ToolDefinition[]): {
20
+ state: NonNullable<RunSnapshot['toolDiscovery']>;
21
+ names: string[];
22
+ } | null;
23
+ /** Describe a rejected model call using only the current, scoped execution
24
+ * catalog. Discovery is a suggested next call, never authority to dispatch the
25
+ * rejected operation. Historical events and frozen tool definitions stay intact. */
26
+ export declare function toolAdmissionRejection(snapshot: RunSnapshot, config: RunConfiguration, call: ToolCall, tools: ToolDefinition[]): ObjectValue;
15
27
  /** Reconstitute the provider's original call; execution records keep the real target. */
16
28
  export declare function modelWireToolCall(call: ToolCall): ToolCall;
17
29
  /** Pure, bounded discovery result. No external tool or resource is executed here. */
@@ -24,6 +24,8 @@ export function toolDiscoveryDefinitions() {
24
24
  }
25
25
  export function validateToolDiscovery(config) {
26
26
  invariant(config.toolDiscoveryPolicy === undefined || config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_tool_discovery_policy');
27
+ invariant(config.toolAdmissionPolicy === undefined || config.toolAdmissionPolicy === 'discover-before-retry/v1'
28
+ && config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_tool_admission_policy');
27
29
  invariant(config.profile.providerToolSearchPolicy === undefined || config.profile.providerToolSearchPolicy === 'local-only/v1'
28
30
  || config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1'
29
31
  && config.profile.providerFamily === 'anthropic-messages' && config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_provider_tool_search_policy');
@@ -133,6 +135,71 @@ export function discoveredCallExposed(snapshot, config, call) {
133
135
  || config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1'
134
136
  && snapshot.toolDiscovery?.discovered.includes(call.name) === true;
135
137
  }
138
+ /** Exact, scoped names are sufficient evidence to discover a definition, not to
139
+ * authorize its proposed operation. Promote only newly exposed schemas, bounded
140
+ * like a search result. The next model request must resubmit through the normal
141
+ * schema/permission/approval path. Omission preserves historical admission. */
142
+ export function discoverRejectedCalls(snapshot, config, calls, tools) {
143
+ if (config.toolAdmissionPolicy !== 'discover-before-retry/v1' || !snapshot.toolDiscovery)
144
+ return null;
145
+ const wrapper = tools.find(tool => tool.name === DEFERRED_TOOL_CALL);
146
+ const names = [], definitions = [];
147
+ for (const call of calls) {
148
+ if (call.wireArgumentsInvalid || call.modelCallWrapper)
149
+ continue;
150
+ const wrapped = call.name === DEFERRED_TOOL_CALL;
151
+ if (wrapped && (!wrapper || toolInputRejection(wrapper, call)))
152
+ continue;
153
+ if (!wrapped && discoveredCallExposed(snapshot, config, call))
154
+ continue;
155
+ const name = wrapped ? String(call.arguments.name) : call.name;
156
+ if (names.includes(name) || snapshot.toolDiscovery.promoted.includes(name)
157
+ || wrapped && snapshot.toolDiscovery.discovered.includes(name))
158
+ continue;
159
+ const target = tools.find(tool => tool.name === name && tool.discovery?.deferred
160
+ && (config.contract.allowedToolNames === null || config.contract.allowedToolNames.includes(name)));
161
+ if (!target)
162
+ continue;
163
+ const entry = { name, description: target.description, parameters: copy(target.parameters) };
164
+ // Keep metadata discovery finite and no larger than the existing search
165
+ // model-view envelope. Oversized schemas must use the explicit search path.
166
+ const bytes = new TextEncoder().encode(canonical({ content: canonical({ definitions: [...definitions, entry] }),
167
+ media: [], additionalContexts: [] })).length;
168
+ if (bytes + 32 > config.limits.maxToolResultBytes)
169
+ continue;
170
+ names.push(name);
171
+ definitions.push(entry);
172
+ if (names.length === 20)
173
+ break;
174
+ }
175
+ return names.length ? { names, state: {
176
+ discovered: [...new Set([...snapshot.toolDiscovery.discovered, ...names])],
177
+ promoted: [...snapshot.toolDiscovery.promoted, ...names],
178
+ } } : null;
179
+ }
180
+ /** Describe a rejected model call using only the current, scoped execution
181
+ * catalog. Discovery is a suggested next call, never authority to dispatch the
182
+ * rejected operation. Historical events and frozen tool definitions stay intact. */
183
+ export function toolAdmissionRejection(snapshot, config, call, tools) {
184
+ const base = { status: 'error', code: 'tool_not_advertised', executed: false };
185
+ const available = tools.some(tool => tool.name === call.name);
186
+ const search = tools.find(tool => tool.name === TOOL_SEARCH);
187
+ const arguments_ = { query: `select:${call.name}` };
188
+ if (available && !discoveredCallExposed(snapshot, config, call) && search
189
+ && call.name === call.name.trim() && !/[,\r\n]/.test(call.name)
190
+ && !toolInputRejection(search, { callId: call.callId, name: TOOL_SEARCH, arguments: arguments_ })) {
191
+ const direct = config.profile.discoveredToolExposure === 'direct-after-search/v1'
192
+ || config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1';
193
+ return { ...base, reason: 'definition_not_loaded', recovery: {
194
+ name: TOOL_SEARCH, arguments: arguments_,
195
+ call_after_discovery: direct ? 'direct' : DEFERRED_TOOL_CALL,
196
+ } };
197
+ }
198
+ const catalog = boundedCapabilityCatalog(discoveryModelTools(snapshot, config, tools)
199
+ .map(tool => ({ name: tool.name, description: '' })), 1024);
200
+ return { ...base, reason: available && discoveredCallExposed(snapshot, config, call) ? 'batch_not_executed' : 'tool_unavailable',
201
+ available_tool_names: catalog.entries.map(tool => tool.name), omitted_tool_names: catalog.omitted };
202
+ }
136
203
  /** Reconstitute the provider's original call; execution records keep the real target. */
137
204
  export function modelWireToolCall(call) {
138
205
  if (call.modelCallWrapper !== DEFERRED_TOOL_CALL)