@kingsoftcloud/agentkit-harness-core 0.0.14 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/approval-outcome.d.mts +7 -0
- package/dist/approval-outcome.mjs +8 -0
- package/dist/background-contract.d.mts +3 -0
- package/dist/background-contract.mjs +14 -0
- package/dist/background-notification.mjs +3 -2
- package/dist/child-contract.d.mts +8 -1
- 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 +2 -0
- package/dist/configuration.mjs +7 -4
- package/dist/context-planning.mjs +6 -3
- package/dist/contracts.d.mts +13 -7
- 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 +41 -5
- package/dist/machine.mjs +40 -22
- 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 +8 -0
- package/dist/tool-discovery.mjs +44 -0
- package/dist/transitions.mjs +22 -2
- package/package.json +1 -1
- package/src/approval-outcome.mts +12 -0
- package/src/background-contract.mts +12 -0
- package/src/background-notification.mts +3 -2
- package/src/child-contract.mts +5 -1
- package/src/child-control.mts +16 -2
- package/src/child-runtime.mts +7 -1
- package/src/configuration.mts +9 -4
- package/src/context-planning.mts +6 -3
- package/src/contracts.mts +14 -8
- package/src/index.mts +1 -0
- package/src/kernel.mts +38 -5
- package/src/machine.mts +41 -22
- 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 +37 -0
- package/src/transitions.mts +20 -2
package/src/contracts.mts
CHANGED
|
@@ -105,7 +105,7 @@ export interface ModelProfile {
|
|
|
105
105
|
/** Absent on older Runs; projection policy is frozen at admission. */
|
|
106
106
|
inlineReasoningPolicy?: { contract: 'profiled-content/v1' | 'profiled-content/v2'; rule: 'auto' | 'permissive' | 'openai'
|
|
107
107
|
| 'strict-openai' | 'cerebras' | 'groq' | 'deepseek' | 'zai' | 'kspmas-gateway' | 'moonshot' | 'mimo' };
|
|
108
|
-
providerCompatibilityPolicy?: { contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3'; rule: NonNullable<ModelProfile['inlineReasoningPolicy']>['rule'] };
|
|
108
|
+
providerCompatibilityPolicy?: { contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3' | 'provider-compat/v4'; rule: NonNullable<ModelProfile['inlineReasoningPolicy']>['rule'] };
|
|
109
109
|
streaming?: boolean; outputTokenParameter?: 'max_tokens' | 'max_completion_tokens';
|
|
110
110
|
streamTimeoutPolicy?: 'idle/v1'; providerThinkingDisplay?: boolean;
|
|
111
111
|
/** Absent on historical Runs, whose OpenAI usage reports required equality. */
|
|
@@ -290,6 +290,8 @@ export interface RunConfiguration {
|
|
|
290
290
|
planModeInitialActive?: boolean;
|
|
291
291
|
childPlanPolicy?: 'inherit-plan/v1';
|
|
292
292
|
toolDiscoveryPolicy?: 'local-tool-search/v1';
|
|
293
|
+
/** A premature call may load an already authorized schema, but never dispatch its operation. */
|
|
294
|
+
toolAdmissionPolicy?: 'discover-before-retry/v1';
|
|
293
295
|
artifactPolicy?: 'runtime-artifacts/v1' | null;
|
|
294
296
|
/** The execution owner must prepare Host context before the first inference. */
|
|
295
297
|
inputPolicy?: 'before-first-model/v1';
|
|
@@ -307,10 +309,14 @@ export interface RunConfiguration {
|
|
|
307
309
|
stopHookContinuationLimit: number; delegationDepth: number;
|
|
308
310
|
modelRecoveryPolicy: 'manual' | 'pure-inference/v1';
|
|
309
311
|
guidancePolicy?: 'boundary-guide/v1' | null;
|
|
310
|
-
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | null;
|
|
311
|
-
/** Restart allowance belongs to one interrupted response chain.
|
|
312
|
-
*
|
|
313
|
-
|
|
312
|
+
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | 'response-boundary/v3' | null;
|
|
313
|
+
/** Restart allowance belongs to one interrupted response chain. v2 pauses
|
|
314
|
+
* exhausted chains for explicit resume instead of terminating the Run.
|
|
315
|
+
* Legacy Runs retain their frozen accounting and exhaustion behavior. */
|
|
316
|
+
outputRestartPolicy?: 'per-response/v1' | 'per-response/v2';
|
|
317
|
+
/** The interactive owner preserves typed Host outcomes and pauses on a
|
|
318
|
+
* non-grant. Children retain the outcome without duplicating that pause. */
|
|
319
|
+
approvalOutcomePolicy?: 'owner-outcome/v1';
|
|
314
320
|
/** v2 counts consecutive provider failures and pauses (resumable) instead of failing when they run out. */
|
|
315
321
|
providerRecoveryPolicy?: 'provider-recovery/v2' | null;
|
|
316
322
|
/** v2 admits a ten-inference diagnostic allowance unless explicitly configured.
|
|
@@ -417,7 +423,7 @@ export interface CompletionCandidate {
|
|
|
417
423
|
}
|
|
418
424
|
export interface ChildState {
|
|
419
425
|
runId: string; sessionId: string; operationKey: string; callId: string;
|
|
420
|
-
state: 'prepared' | 'running' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
|
|
426
|
+
state: 'prepared' | 'running' | 'paused' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
|
|
421
427
|
reservedModelCalls: number | null; reservedToolCalls: number | null; usage: Usage;
|
|
422
428
|
notified: boolean; metadata: ObjectValue;
|
|
423
429
|
}
|
|
@@ -527,7 +533,7 @@ export type EffectKind = 'workspace' | 'model' | 'tool' | 'verify' | 'context' |
|
|
|
527
533
|
export interface EffectIntent { operationKey: string; kind: EffectKind; payload: ObjectValue; status: 'prepared' | 'running'; claimedAtMs?: number; claimedFence?: number }
|
|
528
534
|
export interface EffectReceipt { operationKey: string; status: 'committed' | 'failed' | 'uncertain' | 'not_dispatched'; result: ObjectValue }
|
|
529
535
|
export type CommandKind = 'cancel' | 'policy_revoked' | 'pause' | 'resume' | 'submit_interaction'
|
|
530
|
-
| 'reconcile_tool' | 'repair_workspace' | 'steer' | 'guide' | 'promote_child' | 'message_child' | 'cancel_child';
|
|
536
|
+
| 'reconcile_tool' | 'repair_workspace' | 'steer' | 'guide' | 'promote_child' | 'message_child' | 'cancel_child' | 'resume_child';
|
|
531
537
|
export interface RunCommand { commandId: string; kind: CommandKind; payload: ObjectValue }
|
|
532
538
|
export interface CommandReceipt { commandId: string; status: 'accepted' | 'duplicate' | 'rejected'; reason: string | null }
|
|
533
539
|
export interface Lease { owner: string; fence: number; expiresAt: number }
|
|
@@ -736,5 +742,5 @@ export const terminal = (phase: Phase): boolean => ['completed', 'failed', 'canc
|
|
|
736
742
|
export const emptyUsage = (): Usage => ({ inputTokens: 0, outputTokens: 0, modelCalls: 0, toolCalls: 0, cost: 0 });
|
|
737
743
|
export const commandPriority: Record<CommandKind, number> = {
|
|
738
744
|
cancel: 100, policy_revoked: 95, submit_interaction: 90, cancel_child: 85,
|
|
739
|
-
pause: 80, resume: 80, reconcile_tool: 75, repair_workspace: 75, promote_child: 70, message_child: 70, steer: 60, guide: 60,
|
|
745
|
+
pause: 80, resume: 80, reconcile_tool: 75, repair_workspace: 75, promote_child: 70, message_child: 70, resume_child: 70, steer: 60, guide: 60,
|
|
740
746
|
};
|
package/src/index.mts
CHANGED
|
@@ -49,6 +49,7 @@ export * from './child-budget.mjs';
|
|
|
49
49
|
export * from './child-contract.mjs';
|
|
50
50
|
export * from './child-runtime.mjs';
|
|
51
51
|
export * from './child-control.mjs';
|
|
52
|
+
export * from './approval-outcome.mjs';
|
|
52
53
|
export * from './guidance.mjs';
|
|
53
54
|
export * from './tool-receipt.mjs';
|
|
54
55
|
export * from './output-recovery.mjs';
|
package/src/kernel.mts
CHANGED
|
@@ -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
|
package/src/machine.mts
CHANGED
|
@@ -17,13 +17,13 @@ import { admittedToolBudget, outstandingChildCalls, reduceChildBudget } from './
|
|
|
17
17
|
import { prepareChildLifecycle, unsettledChildren } from './child-runtime.mjs';
|
|
18
18
|
import { toolResourceUsage, toolUsageIncomplete } from './tool-resource-usage.mjs';
|
|
19
19
|
import { completeContinuation, outputRecoveryMode, restartContinuation } from './output-recovery.mjs';
|
|
20
|
-
import { responseContinuationPending } from './response-continuation.mjs';
|
|
20
|
+
import { responseBoundaryRecovery, responseContinuationPending, responseScopedOutputRestarts } from './response-continuation.mjs';
|
|
21
21
|
import { advanceDiagnosticRecovery, advanceObservedProgress, advanceToolErrorStreak, guardedToolErrorAction,
|
|
22
22
|
refuseUndiagnosedToolAction, reserveDiagnosticTrial, toolErrorRecoveryBoundary, toolErrorRecoveryEnabled,
|
|
23
23
|
toolErrorStreakExhausted } from './tool-error-recovery.mjs';
|
|
24
24
|
import { deliveryReadOutsidePaths, deliverySummaryAllowed, deliveryTaskMessages, observeExecutionBudget, rememberDeliveryWrite, scopedDeliveryReader, wallDeliveryOnly } from './deadline-delivery.mjs';
|
|
25
25
|
import { contextContinuity } from './context-planning.mjs';
|
|
26
|
-
import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
|
|
26
|
+
import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, discoverRejectedCalls, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
|
|
27
27
|
import { NativePolicyRegistry } from './policy-registry.mjs';
|
|
28
28
|
import { reduceCoordinatorResponses } from './coordinator-response.mjs';
|
|
29
29
|
import { RESULT_DELIVERY_POLICY } from './deliverables.mjs';
|
|
@@ -378,20 +378,25 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
378
378
|
}
|
|
379
379
|
const tools = advertisedTools({ ...snapshot,
|
|
380
380
|
usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies);
|
|
381
|
-
|
|
381
|
+
const discovery = discoverRejectedCalls(snapshot, config, result.toolCalls, tools);
|
|
382
|
+
const discovered = discovery ? { ...snapshot, toolDiscovery: discovery.state } : snapshot;
|
|
383
|
+
if (discovery || result.toolCalls.some(call => !tools.some(tool => tool.name === call.name)
|
|
382
384
|
|| !discoveredCallExposed(snapshot, config, call))) {
|
|
383
|
-
const unbound = result.toolCalls.some(call => !config.tools.some(tool => tool.name === call.name)
|
|
384
|
-
|| !discoveredCallExposed(
|
|
385
|
+
const unbound = result.toolCalls.some(call => !(config.toolAdmissionPolicy ? tools : config.tools).some(tool => tool.name === call.name)
|
|
386
|
+
|| !discoveredCallExposed(discovered, config, call));
|
|
385
387
|
const errors = snapshot.modelErrors + Number(unbound), exhausted = errors > config.profile.maxRetries;
|
|
386
388
|
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [], modelErrors: errors,
|
|
389
|
+
...(discovery ? { toolDiscovery: discovery.state } : {}),
|
|
387
390
|
outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'tool_call_not_advertised_retry_exhausted' : null, messages: [...snapshot.messages,
|
|
388
391
|
{ ...message, toolCalls: result.toolCalls }, ...result.toolCalls.map(call => ({ role: 'tool' as const,
|
|
389
|
-
callId: call.callId, name: call.name, content: canonical(toolAdmissionRejection(
|
|
392
|
+
callId: call.callId, name: call.name, content: canonical({ ...toolAdmissionRejection(discovered, config, call, tools),
|
|
393
|
+
...(discovery ? { loaded_tool_names: discovery.names,
|
|
394
|
+
instruction: 'The whole batch was not executed. Complete definitions for the listed tools are loaded in the next request. Resubmit valid calls by their exact names; normal permissions and approvals still apply.' } : {}) }) }))] };
|
|
390
395
|
}
|
|
391
396
|
return { ...base, phase: 'executing_tools', pendingTools: result.toolCalls,
|
|
392
397
|
messages: [...snapshot.messages, { ...message, toolCalls: result.toolCalls }],
|
|
393
398
|
continuations: 0, modelErrors: 0,
|
|
394
|
-
...(config
|
|
399
|
+
...(responseScopedOutputRestarts(config) ? { outputRestarts: 0 } : {}) };
|
|
395
400
|
case 'final_candidate': {
|
|
396
401
|
if (config.contract.finalSubmissionSchema) {
|
|
397
402
|
const errors = snapshot.modelErrors + 1;
|
|
@@ -408,34 +413,48 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
408
413
|
messages: [...snapshot.messages, { ...message, content: text, kind: 'final_candidate' }] };
|
|
409
414
|
}
|
|
410
415
|
case 'output_limit': {
|
|
416
|
+
const resumable = config.outputRestartPolicy === 'per-response/v2';
|
|
417
|
+
const continuation = () => {
|
|
418
|
+
const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config,
|
|
419
|
+
advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
|
|
420
|
+
const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
|
|
421
|
+
const messages: Message[] = [...snapshot.messages,
|
|
422
|
+
...(result.text ? [{ ...message, kind: 'continuation_fragment', continuationResponseId: responseId }] : []),
|
|
423
|
+
{ role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
|
|
424
|
+
...(responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
|
|
425
|
+
? { continuationPolicy: 'response-boundary/v2' as const } : {}),
|
|
426
|
+
continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
|
|
427
|
+
? 'The previous output was interrupted while task tools remain available. It is work in progress, not a completed delivery. Continue from the last committed state using the available tools as needed; break remaining work into smaller actions. Incomplete tool calls were not executed. Give a fresh final answer only after the task is complete.'
|
|
428
|
+
: result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
|
|
429
|
+
+ (responseBoundaryRecovery(config) ? 'You may replay the final incomplete line verbatim before continuing; the Host joins this exact overlap. Do not replay any complete line. ' : '')
|
|
430
|
+
+ 'Incomplete tool calls were not executed.'
|
|
431
|
+
: 'The last response hit its output limit without visible content or a committed tool call. Continue the task from the last committed state; take the next useful action or answer only if the task is complete.' }];
|
|
432
|
+
return { mode, messages };
|
|
433
|
+
};
|
|
434
|
+
const exhausted = (): Partial<RunSnapshot> => resumable
|
|
435
|
+
? { phase: 'paused', resumePhase: 'preparing_context', outcome: null, reason: 'output_budget_exhausted',
|
|
436
|
+
messages: result.text ? continuation().messages : snapshot.messages }
|
|
437
|
+
: { phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
|
|
411
438
|
if (snapshot.continuations >= config.profile.maxContinuations) {
|
|
412
|
-
|
|
439
|
+
// Committed answer text stays a suffix contract even when the first
|
|
440
|
+
// response has no remaining continuation allowance. It is not a tool
|
|
441
|
+
// fragment that may be discarded for an output restart.
|
|
442
|
+
if (responseContinuationPending(snapshot, config) || resumable && continuation().mode === 'suffix')
|
|
443
|
+
return { ...base, ...exhausted() };
|
|
413
444
|
if (snapshot.outputRestarts < config.limits.maxOutputRestarts) {
|
|
414
445
|
try { return { ...base, ...restartContinuation(snapshot, config, result.text, digest), phase: 'preparing_context',
|
|
415
446
|
continuations: 0, outputRestarts: snapshot.outputRestarts + 1 }; }
|
|
416
447
|
catch (error) { if (!(error instanceof Error) || !('code' in error)) throw error;
|
|
417
448
|
return { ...base, phase: 'finalizing', outcome: 'blocked', reason: String(error.code) }; }
|
|
418
449
|
}
|
|
419
|
-
return { ...base,
|
|
450
|
+
return { ...base, ...exhausted() };
|
|
420
451
|
}
|
|
421
452
|
if (!result.text && responseContinuationPending(snapshot, config)) return { ...base, phase: 'preparing_context',
|
|
422
453
|
continuations: snapshot.continuations + 1,
|
|
423
454
|
messages: [...snapshot.messages, { role: 'user', kind: 'response_continuation_feedback',
|
|
424
455
|
content: 'No visible continuation was returned. The interrupted text response is still pending. Return only its missing text suffix.' }] };
|
|
425
|
-
const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config,
|
|
426
|
-
advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
|
|
427
|
-
const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
|
|
428
456
|
return { ...base, phase: 'preparing_context', continuations: snapshot.continuations + 1,
|
|
429
|
-
messages:
|
|
430
|
-
{ role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
|
|
431
|
-
...(config.outputRecoveryPolicy === 'response-boundary/v2' && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
|
|
432
|
-
? { continuationPolicy: 'response-boundary/v2' as const } : {}),
|
|
433
|
-
continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
|
|
434
|
-
? 'The previous output was interrupted while task tools remain available. It is work in progress, not a completed delivery. Continue from the last committed state using the available tools as needed; break remaining work into smaller actions. Incomplete tool calls were not executed. Give a fresh final answer only after the task is complete.'
|
|
435
|
-
: result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
|
|
436
|
-
+ (config.outputRecoveryPolicy === 'response-boundary/v2' ? 'You may replay the final incomplete line verbatim before continuing; the Host joins this exact overlap. Do not replay any complete line. ' : '')
|
|
437
|
-
+ 'Incomplete tool calls were not executed.'
|
|
438
|
-
: 'The last response hit its output limit without visible content or a committed tool call. Continue the task from the last committed state; take the next useful action or answer only if the task is complete.' }] };
|
|
457
|
+
messages: continuation().messages };
|
|
439
458
|
}
|
|
440
459
|
case 'context_overflow':
|
|
441
460
|
return { ...base, phase: 'compacting', context: { ...snapshot.context, preparedCursor: null } };
|
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
|
@@ -27,6 +27,8 @@ export function toolDiscoveryDefinitions(): ToolDefinition[] {
|
|
|
27
27
|
|
|
28
28
|
export function validateToolDiscovery(config: RunConfiguration): void {
|
|
29
29
|
invariant(config.toolDiscoveryPolicy === undefined || config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_tool_discovery_policy');
|
|
30
|
+
invariant(config.toolAdmissionPolicy === undefined || config.toolAdmissionPolicy === 'discover-before-retry/v1'
|
|
31
|
+
&& config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_tool_admission_policy');
|
|
30
32
|
invariant(config.profile.providerToolSearchPolicy === undefined || config.profile.providerToolSearchPolicy === 'local-only/v1'
|
|
31
33
|
|| config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1'
|
|
32
34
|
&& config.profile.providerFamily === 'anthropic-messages' && config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY,
|
|
@@ -127,6 +129,41 @@ export function discoveredCallExposed(snapshot: RunSnapshot, config: RunConfigur
|
|
|
127
129
|
&& snapshot.toolDiscovery?.discovered.includes(call.name) === true;
|
|
128
130
|
}
|
|
129
131
|
|
|
132
|
+
/** Exact, scoped names are sufficient evidence to discover a definition, not to
|
|
133
|
+
* authorize its proposed operation. Promote only newly exposed schemas, bounded
|
|
134
|
+
* like a search result. The next model request must resubmit through the normal
|
|
135
|
+
* schema/permission/approval path. Omission preserves historical admission. */
|
|
136
|
+
export function discoverRejectedCalls(snapshot: RunSnapshot, config: RunConfiguration, calls: ToolCall[],
|
|
137
|
+
tools: ToolDefinition[]): { state: NonNullable<RunSnapshot['toolDiscovery']>; names: string[] } | null {
|
|
138
|
+
if (config.toolAdmissionPolicy !== 'discover-before-retry/v1' || !snapshot.toolDiscovery) return null;
|
|
139
|
+
const wrapper = tools.find(tool => tool.name === DEFERRED_TOOL_CALL);
|
|
140
|
+
const names: string[] = [], definitions: ObjectValue[] = [];
|
|
141
|
+
for (const call of calls) {
|
|
142
|
+
if (call.wireArgumentsInvalid || call.modelCallWrapper) continue;
|
|
143
|
+
const wrapped = call.name === DEFERRED_TOOL_CALL;
|
|
144
|
+
if (wrapped && (!wrapper || toolInputRejection(wrapper, call))) continue;
|
|
145
|
+
if (!wrapped && discoveredCallExposed(snapshot, config, call)) continue;
|
|
146
|
+
const name = wrapped ? String(call.arguments.name) : call.name;
|
|
147
|
+
if (names.includes(name) || snapshot.toolDiscovery.promoted.includes(name)
|
|
148
|
+
|| wrapped && snapshot.toolDiscovery.discovered.includes(name)) continue;
|
|
149
|
+
const target = tools.find(tool => tool.name === name && tool.discovery?.deferred
|
|
150
|
+
&& (config.contract.allowedToolNames === null || config.contract.allowedToolNames.includes(name)));
|
|
151
|
+
if (!target) continue;
|
|
152
|
+
const entry = { name, description: target.description, parameters: copy(target.parameters) };
|
|
153
|
+
// Keep metadata discovery finite and no larger than the existing search
|
|
154
|
+
// model-view envelope. Oversized schemas must use the explicit search path.
|
|
155
|
+
const bytes = new TextEncoder().encode(canonical({ content: canonical({ definitions: [...definitions, entry] }),
|
|
156
|
+
media: [], additionalContexts: [] })).length;
|
|
157
|
+
if (bytes + 32 > config.limits.maxToolResultBytes) continue;
|
|
158
|
+
names.push(name); definitions.push(entry);
|
|
159
|
+
if (names.length === 20) break;
|
|
160
|
+
}
|
|
161
|
+
return names.length ? { names, state: {
|
|
162
|
+
discovered: [...new Set([...snapshot.toolDiscovery.discovered, ...names])],
|
|
163
|
+
promoted: [...snapshot.toolDiscovery.promoted, ...names],
|
|
164
|
+
} } : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
130
167
|
/** Describe a rejected model call using only the current, scoped execution
|
|
131
168
|
* catalog. Discovery is a suggested next call, never authority to dispatch the
|
|
132
169
|
* rejected operation. Historical events and frozen tool definitions stay intact. */
|
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,35 @@ 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', 'context_source_unavailable', 'child_paused']
|
|
153
|
+
.includes(snapshot.reason ?? '') ? { reason: null } : {}) };
|
|
148
154
|
break;
|
|
149
155
|
case 'submit_interaction': {
|
|
150
156
|
const pending = snapshot.pendingInteraction;
|
|
157
|
+
const hasOutcome = Object.hasOwn(command.payload, 'approvalOutcome');
|
|
158
|
+
const approvalOutcome = normalizeHostApprovalOutcome(command.payload.approvalOutcome);
|
|
151
159
|
if (snapshot.phase !== 'awaiting_interaction' || !pending || command.payload.interactionId !== pending.interactionId
|
|
152
160
|
|| command.payload.decision !== 'allow' && command.payload.decision !== 'deny') reason = 'interaction_mismatch';
|
|
161
|
+
else if (hasOutcome && (bindings.configuration?.approvalOutcomePolicy !== APPROVAL_OUTCOME_POLICY
|
|
162
|
+
|| approvalOutcome !== command.payload.approvalOutcome
|
|
163
|
+
|| (approvalOutcome === 'allowed-once') !== (command.payload.decision === 'allow'))) reason = 'interaction_outcome_mismatch';
|
|
153
164
|
else {
|
|
154
165
|
changes = { phase: snapshot.childApproval ? snapshot.resumePhase ?? 'preparing_context' : 'executing_tools',
|
|
155
166
|
...(snapshot.childApproval ? { resumePhase: null, childLifecycleCursor: null } : {}), pendingInteraction: null,
|
|
156
167
|
interaction: pending.approvalPolicy === 'durable-preflight/v1' ? null : { interactionId: pending.hostInteractionId, callId: pending.callId, decision: command.payload.decision,
|
|
168
|
+
...(hasOutcome ? { approvalOutcome } : {}),
|
|
157
169
|
...(snapshot.planMode && typeof command.payload.feedback === 'string' ? { feedback: command.payload.feedback } : {}) } };
|
|
158
|
-
|
|
170
|
+
// One human answer pauses the interactive owner once. Its children
|
|
171
|
+
// receive the same denied decision after that owner is explicitly
|
|
172
|
+
// resumed; no second pause or implicit tool permission is introduced.
|
|
173
|
+
const pauseReason = hasOutcome && !bindings.configuration?.childOwnerBinding ? approvalOutcomePauseReason(approvalOutcome) : null;
|
|
174
|
+
if (pauseReason) Object.assign(changes, { resumePhase: changes.phase, phase: 'paused', reason: pauseReason, outcome: null });
|
|
175
|
+
facts.push({ kind: 'approval.resolved', payload: { interactionId: pending.interactionId, callId: pending.callId, decision: command.payload.decision,
|
|
176
|
+
...(hasOutcome ? { approvalOutcome } : {}) } });
|
|
159
177
|
}
|
|
160
178
|
break;
|
|
161
179
|
}
|