@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.
- package/dist/approval-outcome.d.mts +7 -0
- package/dist/approval-outcome.mjs +8 -0
- package/dist/background-notification.mjs +5 -2
- package/dist/child-contract.d.mts +2 -0
- package/dist/child-control.d.mts +4 -0
- package/dist/child-control.mjs +15 -2
- package/dist/child-runtime.mjs +11 -1
- package/dist/configuration.d.mts +3 -0
- package/dist/configuration.mjs +13 -4
- package/dist/context-contributions.d.mts +2 -0
- package/dist/context-contributions.mjs +100 -48
- package/dist/context-planning.mjs +2 -2
- package/dist/contracts.d.mts +22 -5
- package/dist/contracts.mjs +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -0
- package/dist/kernel.d.mts +1 -0
- package/dist/kernel.mjs +52 -6
- package/dist/machine.mjs +44 -24
- package/dist/model-failure.d.mts +13 -1
- package/dist/model-failure.mjs +29 -2
- package/dist/model-json.mjs +21 -12
- package/dist/output-recovery.mjs +6 -2
- package/dist/response-continuation.d.mts +4 -0
- package/dist/response-continuation.mjs +9 -1
- package/dist/store.mjs +2 -1
- package/dist/tool-discovery.d.mts +13 -1
- package/dist/tool-discovery.mjs +67 -0
- package/dist/transitions.mjs +21 -2
- package/package.json +1 -1
- package/src/approval-outcome.mts +12 -0
- package/src/background-notification.mts +5 -2
- package/src/child-contract.mts +2 -0
- package/src/child-control.mts +16 -2
- package/src/child-runtime.mts +7 -1
- package/src/configuration.mts +17 -4
- package/src/context-contributions.mts +84 -38
- package/src/context-planning.mts +2 -2
- package/src/contracts.mts +19 -6
- package/src/index.mts +1 -0
- package/src/kernel.mts +47 -6
- package/src/machine.mts +46 -24
- package/src/model-failure.mts +40 -3
- package/src/model-json.mts +20 -9
- package/src/output-recovery.mts +6 -2
- package/src/response-continuation.mts +11 -1
- package/src/store.mts +2 -1
- package/src/tool-discovery.mts +63 -1
- package/src/transitions.mts +19 -2
package/src/kernel.mts
CHANGED
|
@@ -32,7 +32,7 @@ import { assertHookFeedbackRetained, deniedByHook, reduceHook, stagePostHooks }
|
|
|
32
32
|
import { hookBytes, hookResult } from './hook-contract.mjs';
|
|
33
33
|
import { planNativeContext, reduceContextModel } from './context-planning.mjs';
|
|
34
34
|
import type { ContextCounters } from './context-planning.mjs';
|
|
35
|
-
import { collectContextContributions } from './context-contributions.mjs';
|
|
35
|
+
import { collectContextContributions, contextSourceUnavailable } from './context-contributions.mjs';
|
|
36
36
|
import { validateInstructionScopes } from './instruction-scopes.mjs';
|
|
37
37
|
import { refreshContextSources } from './context-source-refresh.mjs';
|
|
38
38
|
import { outputRestartPayload } from './output-recovery.mjs';
|
|
@@ -155,7 +155,7 @@ export class NativeKernel {
|
|
|
155
155
|
if (result.status !== 'rejected' && ['cancel', 'policy_revoked'].includes(command.kind)) {
|
|
156
156
|
this.active.get(runKey(scope, runId))?.abort(new NativeError('command_interrupt'));
|
|
157
157
|
}
|
|
158
|
-
if (result.status === 'accepted' && ['pause', 'promote_child', 'message_child', 'cancel_child'].includes(command.kind)) {
|
|
158
|
+
if (result.status === 'accepted' && ['pause', 'promote_child', 'message_child', 'cancel_child', 'resume_child'].includes(command.kind)) {
|
|
159
159
|
const observer = this.childObservers.get(runKey(scope, runId));
|
|
160
160
|
if (observer && (command.kind !== 'pause' || observer.canPause)) observer.controller.abort(
|
|
161
161
|
new NativeError(command.kind === 'pause' ? 'child_observation_paused' : 'child_observation_promoted'));
|
|
@@ -180,6 +180,9 @@ export class NativeKernel {
|
|
|
180
180
|
cancelChild(scope: RunScope, runId: string, childRunId: string, commandId: string) {
|
|
181
181
|
return this.submitChildControl(scope, runId, { commandId, kind: 'cancel_child', payload: { childRunId } });
|
|
182
182
|
}
|
|
183
|
+
resumeChild(scope: RunScope, runId: string, childRunId: string, commandId: string) {
|
|
184
|
+
return this.submitChildControl(scope, runId, { commandId, kind: 'resume_child', payload: { childRunId } });
|
|
185
|
+
}
|
|
183
186
|
private submitChildControl(scope: RunScope, runId: string, command: RunCommand) {
|
|
184
187
|
const record = this.store.load(scope, runId), send = command.kind === 'message_child';
|
|
185
188
|
// Stable retries retain the original target, even after it becomes terminal.
|
|
@@ -190,7 +193,7 @@ export class NativeKernel {
|
|
|
190
193
|
invariant(target, 'child_control_not_owned');
|
|
191
194
|
childControlDelivery(record.snapshot, command, target);
|
|
192
195
|
const task = this.childTaskStates(record.snapshot).find(task => task.childRunId === target.runId);
|
|
193
|
-
invariant(task && (send ? task.canSendInput : task.canCancel), 'child_control_unavailable');
|
|
196
|
+
invariant(task && (send ? task.canSendInput : command.kind === 'resume_child' ? task.canResume === true : task.canCancel), 'child_control_unavailable');
|
|
194
197
|
return this.submit(scope, runId, command);
|
|
195
198
|
}
|
|
196
199
|
private childTaskStates(snapshot: RunSnapshot): ChildTaskControlState[] {
|
|
@@ -199,6 +202,7 @@ export class NativeKernel {
|
|
|
199
202
|
return copy(this.ports.children?.tasks?.({ scope: copy(snapshot.scope), runId: snapshot.runId, sessionId: snapshot.sessionId,
|
|
200
203
|
turnId: snapshot.turnId, buildId: snapshot.buildId, parentRunId: snapshot.parentRunId, taskChainId: snapshot.taskChainId }) ?? [])
|
|
201
204
|
.map(task => ({ ...task, canCancel: task.canCancel && controls,
|
|
205
|
+
...(task.canResume === undefined ? {} : { canResume: task.canResume && controls }),
|
|
202
206
|
canSendInput: task.canSendInput && controls && config.childInputPolicy === 'owned-child-input/v1' }));
|
|
203
207
|
}
|
|
204
208
|
private async consumeChildControl(snapshot: RunSnapshot, config: RunConfiguration, command: RunCommand, lease: Lease): Promise<void> {
|
|
@@ -210,9 +214,13 @@ export class NativeKernel {
|
|
|
210
214
|
const target = port.controlTarget(snapshot, id);
|
|
211
215
|
invariant(target, 'child_control_not_owned');
|
|
212
216
|
const delivery = childControlDelivery(snapshot, command, target), changes: Partial<RunSnapshot> = { childLifecycleCursor: null };
|
|
213
|
-
const facts: { kind: string; payload: ObjectValue }[] = [{ kind: send ? 'child.input_queued'
|
|
217
|
+
const facts: { kind: string; payload: ObjectValue }[] = [{ kind: send ? 'child.input_queued'
|
|
218
|
+
: command.kind === 'resume_child' ? 'child.resume_requested' : 'child.cancel_requested',
|
|
214
219
|
payload: { childRunId: id, commandId: command.commandId } }];
|
|
215
|
-
if (
|
|
220
|
+
if (['resume_child', 'cancel_child'].includes(command.kind) && snapshot.phase === 'paused' && snapshot.reason === 'child_paused') {
|
|
221
|
+
Object.assign(changes, { phase: snapshot.resumePhase ?? 'preparing_context', resumePhase: null, reason: null });
|
|
222
|
+
}
|
|
223
|
+
if (command.kind === 'cancel_child' && snapshot.childApproval?.childRunId === id) {
|
|
216
224
|
facts.push({ kind: 'approval.resolved', payload: { interactionId: snapshot.pendingInteraction?.interactionId ?? '',
|
|
217
225
|
callId: snapshot.childApproval.toolCall.callId, decision: 'canceled', reason: 'child_cancel_requested' } });
|
|
218
226
|
Object.assign(changes, { childApproval: null, pendingInteraction: null, interaction: null,
|
|
@@ -283,6 +291,8 @@ export class NativeKernel {
|
|
|
283
291
|
} catch (error) { leaseError = error; controller.abort(new NativeError('lease_lost')); }
|
|
284
292
|
}, Math.max(10, Math.floor(initial.configuration.limits.leaseMs / 3)));
|
|
285
293
|
let deliveredRevision = -1;
|
|
294
|
+
let recoveredChildControls = false;
|
|
295
|
+
const wokenChildControls = new Set<string>();
|
|
286
296
|
let browserChecked = !(initial.snapshot.browserSessionRefs?.length || initial.snapshot.lastBrowserObservation);
|
|
287
297
|
try {
|
|
288
298
|
while (true) {
|
|
@@ -311,8 +321,9 @@ export class NativeKernel {
|
|
|
311
321
|
: prepareToolReceipt(this.store.load(scope, runId), command));
|
|
312
322
|
continue;
|
|
313
323
|
}
|
|
314
|
-
if (['message_child', 'cancel_child'].includes(command.kind)) {
|
|
324
|
+
if (['message_child', 'cancel_child', 'resume_child'].includes(command.kind)) {
|
|
315
325
|
await this.consumeChildControl(snapshot, config, command, lease);
|
|
326
|
+
wokenChildControls.add(command.commandId);
|
|
316
327
|
continue;
|
|
317
328
|
}
|
|
318
329
|
const intent = record.pendingIntent;
|
|
@@ -332,6 +343,28 @@ export class NativeKernel {
|
|
|
332
343
|
}
|
|
333
344
|
continue;
|
|
334
345
|
}
|
|
346
|
+
if (!recoveredChildControls) {
|
|
347
|
+
recoveredChildControls = true;
|
|
348
|
+
// The pair transaction may have committed immediately before a
|
|
349
|
+
// process died, leaving a paused child with an existing resume inbox
|
|
350
|
+
// entry but no wake. Recover notification, never re-enqueue a command
|
|
351
|
+
// or infer permission from a child's phase. The owner authenticates
|
|
352
|
+
// the exact inbox entry before it can drive the original child.
|
|
353
|
+
const children = this.ports.children;
|
|
354
|
+
if (config.childLifecyclePolicy === 'owned-background/v2' && snapshot.childRunIds.length
|
|
355
|
+
&& snapshot.phase !== 'finalizing' && !snapshot.childTerminalPhase
|
|
356
|
+
&& children?.controlTarget && children.wakeControl) {
|
|
357
|
+
const saved = this.store.load(scope, runId);
|
|
358
|
+
const delivered = new Set(saved.events.filter(event => event.kind === 'child.resume_requested')
|
|
359
|
+
.map(event => event.payload.commandId));
|
|
360
|
+
for (const row of saved.commands) if (row.consumed && row.command.kind === 'resume_child'
|
|
361
|
+
&& delivered.has(row.command.commandId) && !wokenChildControls.has(row.command.commandId)) {
|
|
362
|
+
const target = children.controlTarget(snapshot, String(row.command.payload.childRunId));
|
|
363
|
+
if (target) await children.wakeControl(snapshot, childControlDelivery(snapshot, row.command, target));
|
|
364
|
+
}
|
|
365
|
+
if (controller.signal.aborted || this.drivingCommands(this.drivingState(scope, runId)).length) continue;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
335
368
|
if (!browserChecked) {
|
|
336
369
|
const pending = record.pendingIntent;
|
|
337
370
|
// Resource loss must not conceal an already claimed effect. Classify
|
|
@@ -888,6 +921,7 @@ export class NativeKernel {
|
|
|
888
921
|
}
|
|
889
922
|
} catch (error) {
|
|
890
923
|
const code = isNativeError(error) ? error.code : 'effect_port_error';
|
|
924
|
+
const unavailableSource = contextSourceUnavailable(error, configuration);
|
|
891
925
|
facts.push(observedEffectFailure({ operationKey: intent.operationKey, kind: intent.kind, code,
|
|
892
926
|
nativeError: isNativeError(error), signalAborted: effectSignal.aborted,
|
|
893
927
|
elapsedMs: this.monotonicNow() - started, initialTimeoutMs: timeoutMs, observedAtMs: this.now(),
|
|
@@ -934,6 +968,13 @@ export class NativeKernel {
|
|
|
934
968
|
changes = { pendingIntent: null, phase: 'finalizing', candidate: null, verification: null, finalText: '',
|
|
935
969
|
childLifecycleFailure: intent.payload.action as 'poll' | 'wait' | 'cancel', outcome: 'unverified', reason: 'child_owner_unavailable' };
|
|
936
970
|
}
|
|
971
|
+
} else if (intent.kind === 'context' && !effectSignal.aborted && code === 'context_source_unavailable'
|
|
972
|
+
&& unavailableSource
|
|
973
|
+
&& ['preparing_context', 'compacting'].includes(snapshot.phase)) {
|
|
974
|
+
raw = { code }; status = 'failed';
|
|
975
|
+
changes = { pendingIntent: null, preparedContext: null, phase: 'paused', resumePhase: snapshot.phase,
|
|
976
|
+
outcome: null, reason: code, context: { ...snapshot.context, preparedCursor: null } };
|
|
977
|
+
facts.push({ kind: 'context.source_unavailable', payload: { ...unavailableSource, reason: code, operationKey: intent.operationKey } });
|
|
937
978
|
} 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)) {
|
|
938
979
|
raw = { code }; status = 'failed';
|
|
939
980
|
changes = { pendingIntent: null, preparedContext: null, phase: 'finalizing', outcome: 'blocked', reason: code };
|
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, 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';
|
|
@@ -232,7 +232,8 @@ export function plan(snapshot: RunSnapshot, config: RunConfiguration, capabiliti
|
|
|
232
232
|
const definition = config.tools.find(tool => tool.name === first.name);
|
|
233
233
|
if (!definition || config.contract.allowedToolNames !== null && !config.contract.allowedToolNames.includes(first.name)) {
|
|
234
234
|
return transition(snapshot, { pendingTools: snapshot.pendingTools.slice(1), messages: [...snapshot.messages,
|
|
235
|
-
{ role: 'tool', content: canonical(
|
|
235
|
+
{ role: 'tool', content: canonical(toolAdmissionRejection(snapshot, config, first,
|
|
236
|
+
advertisedTools(snapshot, config, policies))), callId: first.callId, name: first.name }] },
|
|
236
237
|
[{ kind: 'tool.rejected', payload: { callId: first.callId, name: first.name, reason: 'tool_not_advertised' } }]);
|
|
237
238
|
}
|
|
238
239
|
if (toolRoom(snapshot, config) <= 0) {
|
|
@@ -375,20 +376,27 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
375
376
|
if (finalizationOnly({ ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config)) {
|
|
376
377
|
return { ...base, phase: 'finalizing', outcome: 'budget_exhausted', reason: 'tool_call_after_finalization_reserve' };
|
|
377
378
|
}
|
|
378
|
-
|
|
379
|
-
usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies)
|
|
379
|
+
const tools = advertisedTools({ ...snapshot,
|
|
380
|
+
usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies);
|
|
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)
|
|
380
384
|
|| !discoveredCallExposed(snapshot, config, call))) {
|
|
381
|
-
const unbound = result.toolCalls.some(call => !config.tools.some(tool => tool.name === call.name)
|
|
382
|
-
|| !discoveredCallExposed(
|
|
385
|
+
const unbound = result.toolCalls.some(call => !(config.toolAdmissionPolicy ? tools : config.tools).some(tool => tool.name === call.name)
|
|
386
|
+
|| !discoveredCallExposed(discovered, config, call));
|
|
383
387
|
const errors = snapshot.modelErrors + Number(unbound), exhausted = errors > config.profile.maxRetries;
|
|
384
388
|
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [], modelErrors: errors,
|
|
389
|
+
...(discovery ? { toolDiscovery: discovery.state } : {}),
|
|
385
390
|
outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'tool_call_not_advertised_retry_exhausted' : null, messages: [...snapshot.messages,
|
|
386
391
|
{ ...message, toolCalls: result.toolCalls }, ...result.toolCalls.map(call => ({ role: 'tool' as const,
|
|
387
|
-
callId: call.callId, name: call.name, content: canonical({
|
|
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.' } : {}) }) }))] };
|
|
388
395
|
}
|
|
389
396
|
return { ...base, phase: 'executing_tools', pendingTools: result.toolCalls,
|
|
390
397
|
messages: [...snapshot.messages, { ...message, toolCalls: result.toolCalls }],
|
|
391
|
-
continuations: 0, modelErrors: 0
|
|
398
|
+
continuations: 0, modelErrors: 0,
|
|
399
|
+
...(responseScopedOutputRestarts(config) ? { outputRestarts: 0 } : {}) };
|
|
392
400
|
case 'final_candidate': {
|
|
393
401
|
if (config.contract.finalSubmissionSchema) {
|
|
394
402
|
const errors = snapshot.modelErrors + 1;
|
|
@@ -405,34 +413,48 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
405
413
|
messages: [...snapshot.messages, { ...message, content: text, kind: 'final_candidate' }] };
|
|
406
414
|
}
|
|
407
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' };
|
|
408
438
|
if (snapshot.continuations >= config.profile.maxContinuations) {
|
|
409
|
-
|
|
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() };
|
|
410
444
|
if (snapshot.outputRestarts < config.limits.maxOutputRestarts) {
|
|
411
445
|
try { return { ...base, ...restartContinuation(snapshot, config, result.text, digest), phase: 'preparing_context',
|
|
412
446
|
continuations: 0, outputRestarts: snapshot.outputRestarts + 1 }; }
|
|
413
447
|
catch (error) { if (!(error instanceof Error) || !('code' in error)) throw error;
|
|
414
448
|
return { ...base, phase: 'finalizing', outcome: 'blocked', reason: String(error.code) }; }
|
|
415
449
|
}
|
|
416
|
-
return { ...base,
|
|
450
|
+
return { ...base, ...exhausted() };
|
|
417
451
|
}
|
|
418
452
|
if (!result.text && responseContinuationPending(snapshot, config)) return { ...base, phase: 'preparing_context',
|
|
419
453
|
continuations: snapshot.continuations + 1,
|
|
420
454
|
messages: [...snapshot.messages, { role: 'user', kind: 'response_continuation_feedback',
|
|
421
455
|
content: 'No visible continuation was returned. The interrupted text response is still pending. Return only its missing text suffix.' }] };
|
|
422
|
-
const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config,
|
|
423
|
-
advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
|
|
424
|
-
const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
|
|
425
456
|
return { ...base, phase: 'preparing_context', continuations: snapshot.continuations + 1,
|
|
426
|
-
messages:
|
|
427
|
-
{ role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
|
|
428
|
-
...(config.outputRecoveryPolicy === 'response-boundary/v2' && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
|
|
429
|
-
? { continuationPolicy: 'response-boundary/v2' as const } : {}),
|
|
430
|
-
continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
|
|
431
|
-
? '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.'
|
|
432
|
-
: result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
|
|
433
|
-
+ (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. ' : '')
|
|
434
|
-
+ 'Incomplete tool calls were not executed.'
|
|
435
|
-
: '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 };
|
|
436
458
|
}
|
|
437
459
|
case 'context_overflow':
|
|
438
460
|
return { ...base, phase: 'compacting', context: { ...snapshot.context, preparedCursor: null } };
|
package/src/model-failure.mts
CHANGED
|
@@ -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'] : [])
|
|
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
|
package/src/model-json.mts
CHANGED
|
@@ -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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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
|
|
17
|
-
if (
|
|
18
|
-
|
|
19
|
+
const code = text.charCodeAt(position);
|
|
20
|
+
if (code !== 9 && code !== 10 && code !== 13 && code !== 32) break;
|
|
21
|
+
position++;
|
|
19
22
|
}
|
|
20
|
-
|
|
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
|
-
|
|
52
|
-
|
|
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
|
package/src/output-recovery.mts
CHANGED
|
@@ -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
|
|
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
|
|
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'
|
|
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,
|
package/src/tool-discovery.mts
CHANGED
|
@@ -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 { canonical, copy, invariant } from './values.mjs';
|
|
3
3
|
import { toolInputRejection } from './tool-input.mjs';
|
|
4
4
|
import { searchTools } from './tool-search-ranking.mjs';
|
|
@@ -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,66 @@ 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
|
+
|
|
167
|
+
/** Describe a rejected model call using only the current, scoped execution
|
|
168
|
+
* catalog. Discovery is a suggested next call, never authority to dispatch the
|
|
169
|
+
* rejected operation. Historical events and frozen tool definitions stay intact. */
|
|
170
|
+
export function toolAdmissionRejection(snapshot: RunSnapshot, config: RunConfiguration, call: ToolCall,
|
|
171
|
+
tools: ToolDefinition[]): ObjectValue {
|
|
172
|
+
const base = { status: 'error', code: 'tool_not_advertised', executed: false };
|
|
173
|
+
const available = tools.some(tool => tool.name === call.name);
|
|
174
|
+
const search = tools.find(tool => tool.name === TOOL_SEARCH);
|
|
175
|
+
const arguments_ = { query: `select:${call.name}` };
|
|
176
|
+
if (available && !discoveredCallExposed(snapshot, config, call) && search
|
|
177
|
+
&& call.name === call.name.trim() && !/[,\r\n]/.test(call.name)
|
|
178
|
+
&& !toolInputRejection(search, { callId: call.callId, name: TOOL_SEARCH, arguments: arguments_ })) {
|
|
179
|
+
const direct = config.profile.discoveredToolExposure === 'direct-after-search/v1'
|
|
180
|
+
|| config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1';
|
|
181
|
+
return { ...base, reason: 'definition_not_loaded', recovery: {
|
|
182
|
+
name: TOOL_SEARCH, arguments: arguments_,
|
|
183
|
+
call_after_discovery: direct ? 'direct' : DEFERRED_TOOL_CALL,
|
|
184
|
+
} };
|
|
185
|
+
}
|
|
186
|
+
const catalog = boundedCapabilityCatalog(discoveryModelTools(snapshot, config, tools)
|
|
187
|
+
.map(tool => ({ name: tool.name, description: '' })), 1024);
|
|
188
|
+
return { ...base, reason: available && discoveredCallExposed(snapshot, config, call) ? 'batch_not_executed' : 'tool_unavailable',
|
|
189
|
+
available_tool_names: catalog.entries.map(tool => tool.name), omitted_tool_names: catalog.omitted };
|
|
190
|
+
}
|
|
191
|
+
|
|
130
192
|
/** Reconstitute the provider's original call; execution records keep the real target. */
|
|
131
193
|
export function modelWireToolCall(call: ToolCall): ToolCall {
|
|
132
194
|
if (call.modelCallWrapper !== DEFERRED_TOOL_CALL) return call;
|
package/src/transitions.mts
CHANGED
|
@@ -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
|
-
...(
|
|
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
|
-
|
|
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
|
}
|