@kingsoftcloud/agentkit-harness-core 0.0.17 → 0.0.18
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/configuration.d.mts +2 -0
- package/dist/configuration.mjs +19 -2
- package/dist/context-contributions.d.mts +2 -0
- package/dist/context-contributions.mjs +57 -2
- package/dist/context-planning.mjs +7 -4
- package/dist/contracts.d.mts +21 -1
- package/dist/engine-preset.d.mts +48 -0
- package/dist/engine-preset.mjs +75 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -0
- package/dist/kernel.d.mts +2 -1
- package/dist/kernel.mjs +49 -19
- package/dist/machine.d.mts +3 -1
- package/dist/machine.mjs +57 -7
- package/dist/output-recovery.d.mts +2 -0
- package/dist/output-recovery.mjs +11 -1
- package/dist/recovery.mjs +2 -0
- package/dist/response-continuation.mjs +2 -1
- package/dist/transitions.mjs +2 -1
- package/package.json +1 -1
- package/src/configuration.mts +24 -2
- package/src/context-contributions.mts +53 -2
- package/src/context-planning.mts +7 -4
- package/src/contracts.mts +18 -1
- package/src/engine-preset.mts +110 -0
- package/src/index.mts +1 -0
- package/src/kernel.mts +52 -19
- package/src/machine.mts +55 -7
- package/src/output-recovery.mts +13 -1
- package/src/recovery.mts +1 -0
- package/src/response-continuation.mts +2 -1
- package/src/transitions.mts +2 -1
package/src/context-planning.mts
CHANGED
|
@@ -13,7 +13,7 @@ import { defaultToolPruningThreshold, projectOldToolResults, toolPruningIdleElap
|
|
|
13
13
|
import { summaryContinuityInstructions, validSummaryContinuity } from './summary-continuity.mjs';
|
|
14
14
|
import { responseBoundaryRecovery, responseContinuationPairs } from './response-continuation.mjs';
|
|
15
15
|
import { verificationModelView } from './model-surface.mjs';
|
|
16
|
-
import { currentInstructionContribution } from './context-contributions.mjs';
|
|
16
|
+
import { currentInstructionContribution, hostInstructionContribution } from './context-contributions.mjs';
|
|
17
17
|
import { projectBackgroundCommands } from './background-contract.mjs';
|
|
18
18
|
|
|
19
19
|
export interface ContextCounters {
|
|
@@ -88,10 +88,12 @@ function composeContext(messages: Message[], summary: string, continuity: Object
|
|
|
88
88
|
const host: Message = { role: 'system', kind: 'execution_continuity', content: canonical(continuity) };
|
|
89
89
|
const historical: Message[] = summary ? [contextSummaryMessage(summary)] : [];
|
|
90
90
|
const split = messages.findIndex(message => message.role !== 'system');
|
|
91
|
+
const instructions = contributions.filter(message => message.role === 'system');
|
|
92
|
+
const data = contributions.filter(message => message.role !== 'system');
|
|
91
93
|
if (placement === 'after-history/v1') return [...messages.slice(0, split < 0 ? messages.length : split),
|
|
92
|
-
...
|
|
94
|
+
...instructions, ...data, ...historical, ...messages.slice(split < 0 ? messages.length : split), ...currentInstructions, host];
|
|
93
95
|
return [...messages.slice(0, split < 0 ? messages.length : split),
|
|
94
|
-
...(continuity.operatorGuidancePolicy === 'journaled-system/v1' ? [] : [host]), ...
|
|
96
|
+
...(continuity.operatorGuidancePolicy === 'journaled-system/v1' ? [] : [host]), ...instructions, ...data, ...historical,
|
|
95
97
|
...messages.slice(split < 0 ? messages.length : split), ...currentInstructions];
|
|
96
98
|
}
|
|
97
99
|
function activeIndexes(snapshot: RunSnapshot, state: ContextPlanningState, config: RunConfiguration, digest: (value: unknown) => string): number[] {
|
|
@@ -284,7 +286,8 @@ export async function planNativeContext(snapshot: RunSnapshot, config: RunConfig
|
|
|
284
286
|
const state = copy(snapshot.contextState ?? emptyState());
|
|
285
287
|
const requiredContributions = inputContributions.filter(message => currentInstructionContribution(message, config));
|
|
286
288
|
const optionalContributions = inputContributions.filter(message => !currentInstructionContribution(message, config));
|
|
287
|
-
invariant(inputContributions.every(message => message.role === 'user'
|
|
289
|
+
invariant(inputContributions.every(message => (message.role === 'user' || hostInstructionContribution(message, config))
|
|
290
|
+
&& message.kind === 'context_contribution'
|
|
288
291
|
&& Object.keys(message).every(key => ['role', 'kind', 'content'].includes(key))), 'context_contribution_invalid');
|
|
289
292
|
if (policies.forRun(config).review.reviewPending(snapshot)) {
|
|
290
293
|
const active = activeIndexes(snapshot, state, config, digest).map(index => copy(snapshot.messages[index]!));
|
package/src/contracts.mts
CHANGED
|
@@ -65,6 +65,10 @@ export interface ToolDefinition {
|
|
|
65
65
|
executionTimeoutPolicy?: 'dispatch/v1' | 'dispatch/v2';
|
|
66
66
|
/** Host permission waits yield a durable Native interaction before dispatch. */
|
|
67
67
|
approvalPolicy?: 'durable-preflight/v1';
|
|
68
|
+
/** An explicit Run policy requires a user decision even if standing access permits the tool. */
|
|
69
|
+
hostApprovalRequired?: true;
|
|
70
|
+
/** This external owner receives a frozen effect identity and may request conditional approval. */
|
|
71
|
+
hostEffectProtocol?: 'agentkit.engine-host-tool-effect/v1';
|
|
68
72
|
contextRole: 'none' | 'workspace_read' | 'workspace_search' | 'workspace_list' | 'artifact_read' | 'task_planning';
|
|
69
73
|
observationRole: 'none' | 'browser';
|
|
70
74
|
progressObservation: boolean; contextRetention: 'normal' | 'persistent';
|
|
@@ -140,6 +144,10 @@ export interface AcceptanceItem {
|
|
|
140
144
|
id: string; required: boolean; verifierRef: string; verifierVersion: string;
|
|
141
145
|
verificationMethod: VerificationMethod; description: string;
|
|
142
146
|
}
|
|
147
|
+
export interface HostVerificationBinding {
|
|
148
|
+
verifierRef: string; verifierVersion: string; bindingDigest: string;
|
|
149
|
+
evidenceTools: string[]; contextSourceId: string | null;
|
|
150
|
+
}
|
|
143
151
|
export interface TaskContract {
|
|
144
152
|
objective: string; revision: string; constraints: string[]; acceptance: AcceptanceItem[];
|
|
145
153
|
allowedToolNames: string[] | null; finalSubmissionSchema: ObjectValue | null;
|
|
@@ -255,6 +263,9 @@ export interface ToolResultPruning {
|
|
|
255
263
|
export interface ContextSourceDefinition {
|
|
256
264
|
contract: 'agentkit.native-context-source/v1'; sourceId: string; bindingDigest: string;
|
|
257
265
|
priority: number; timeoutMs: number; required: boolean; maxTokens: number; maxBytes: number;
|
|
266
|
+
/** A frozen host grant controls whether a projected item can enter the system layer. */
|
|
267
|
+
hostProjection?: 'data/v1' | 'instructions-and-data/v1';
|
|
268
|
+
warnOnFailure?: true;
|
|
258
269
|
/** Current file guidance is refreshed before inference, never substituted by a historical summary. */
|
|
259
270
|
instructionPolicy?: 'current-files/v1';
|
|
260
271
|
/** Retry only a timed-out read; required sources pause after exhaustion. Absence keeps the frozen legacy behavior. */
|
|
@@ -270,6 +281,7 @@ export interface ConversationSeed {
|
|
|
270
281
|
discoveredToolNames?: string[];
|
|
271
282
|
}
|
|
272
283
|
export interface RunConfiguration {
|
|
284
|
+
hostVerification?: HostVerificationBinding;
|
|
273
285
|
workspaceCapturePolicy?: 'declared-subjects/v1';
|
|
274
286
|
deliveryScopePolicy?: 'declared-deliverables/v1' | 'answer-artifacts/v2';
|
|
275
287
|
childCapabilityPolicy?: 'required-tools/v1';
|
|
@@ -287,6 +299,7 @@ export interface RunConfiguration {
|
|
|
287
299
|
/** I/O deadlines belong to the execution owner, not kernel staging or result projection. */
|
|
288
300
|
toolExecutionPolicy?: 'owner-execution/v1';
|
|
289
301
|
planModePolicy?: 'session-plan/v1' | 'inherited-child-plan/v1';
|
|
302
|
+
initialPlanPolicy?: 'plan-act-observe/v1';
|
|
290
303
|
planModeInitialActive?: boolean;
|
|
291
304
|
childPlanPolicy?: 'inherit-plan/v1';
|
|
292
305
|
toolDiscoveryPolicy?: 'local-tool-search/v1';
|
|
@@ -309,7 +322,7 @@ export interface RunConfiguration {
|
|
|
309
322
|
stopHookContinuationLimit: number; delegationDepth: number;
|
|
310
323
|
modelRecoveryPolicy: 'manual' | 'pure-inference/v1';
|
|
311
324
|
guidancePolicy?: 'boundary-guide/v1' | null;
|
|
312
|
-
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | 'response-boundary/v3' | null;
|
|
325
|
+
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | 'response-boundary/v3' | 'response-boundary/v4' | 'response-boundary/v5' | null;
|
|
313
326
|
/** Restart allowance belongs to one interrupted response chain. v2 pauses
|
|
314
327
|
* exhausted chains for explicit resume instead of terminating the Run.
|
|
315
328
|
* Legacy Runs retain their frozen accounting and exhaustion behavior. */
|
|
@@ -469,6 +482,7 @@ export interface RunSnapshot extends RunIdentity {
|
|
|
469
482
|
policyContextCursor?: string;
|
|
470
483
|
conversationBranch?: { commandId: string; generation: number };
|
|
471
484
|
planMode?: { active: boolean; revision: number; approvedPlan?: { plan: string; allowedPrompts?: Json } };
|
|
485
|
+
initialPlanCompleted?: true;
|
|
472
486
|
todos?: { items: TodoItem[]; revision: number; assistantTurns: number; lastWriteAssistantTurn: number; lastReminderAssistantTurn: number };
|
|
473
487
|
toolDiscovery?: { discovered: string[]; promoted: string[] };
|
|
474
488
|
/** Runtime-owned capacity for the complete original assistant batch, never a dispatched subset. */
|
|
@@ -489,6 +503,8 @@ export interface RunSnapshot extends RunIdentity {
|
|
|
489
503
|
pendingInteraction: PendingInteraction | null; interaction: ObjectValue | null;
|
|
490
504
|
usage: Usage; descendantUsage: Usage; modelErrors: number; providerErrors: number;
|
|
491
505
|
continuations: number; outputRestarts: number; repairs: number;
|
|
506
|
+
/** A sealed reasoning-only cutoff has armed the short retry for this response. */
|
|
507
|
+
reasoningStallRetry?: boolean;
|
|
492
508
|
activeElapsedMs: number; retryNotBefore: number;
|
|
493
509
|
candidate: CompletionCandidate | null; verification: VerificationReport | null;
|
|
494
510
|
finalText: string; outcome: Outcome | null; reason: string | null;
|
|
@@ -718,6 +734,7 @@ export interface SourceReadBudget {
|
|
|
718
734
|
maxSourceUnits: number; maxResultUnits: number; maxResultBytes: number;
|
|
719
735
|
}
|
|
720
736
|
export interface VerificationPort {
|
|
737
|
+
available?(configuration: RunConfiguration): boolean;
|
|
721
738
|
verify(request: PortContext & { candidate: CompletionCandidate; contract: TaskContract; snapshot: RunSnapshot }): Promise<VerificationReport>;
|
|
722
739
|
}
|
|
723
740
|
export interface HookPort {
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { RunConfiguration, ToolDefinition } from './contracts.mjs';
|
|
2
|
+
import { artifactToolDefinitions } from './artifact-runtime.mjs';
|
|
3
|
+
import { deliveryToolDefinitions } from './deliverables.mjs';
|
|
4
|
+
import { invariant } from './values.mjs';
|
|
5
|
+
|
|
6
|
+
/** Engine-owned run defaults.
|
|
7
|
+
*
|
|
8
|
+
* A host names a preset; the engine decides which policy versions and budgets
|
|
9
|
+
* that name means. Publishing a better recovery policy therefore needs an
|
|
10
|
+
* engine release only: hosts that reference `official` pick it up for new
|
|
11
|
+
* Runs, while existing Runs keep the configuration frozen at their creation.
|
|
12
|
+
*
|
|
13
|
+
* Hosts must not copy the returned literals into their own source. */
|
|
14
|
+
export const ENGINE_PRESET_CONTRACT = 'agentkit.engine-preset/v1';
|
|
15
|
+
export const OFFICIAL_ENGINE_PRESET = 'official';
|
|
16
|
+
const EXPERIMENTAL_REASONING_STALL_PRESET = 'experimental-reasoning-stall';
|
|
17
|
+
|
|
18
|
+
/** Bump when the meaning of `official` changes for new Runs. */
|
|
19
|
+
const OFFICIAL_REVISION = 3;
|
|
20
|
+
const EXPERIMENTAL_REASONING_STALL_REVISION = 1;
|
|
21
|
+
|
|
22
|
+
/** Largest single response the engine asks for by default. Long greenfield
|
|
23
|
+
* edits need roughly 30k tokens in one response; smaller requests exhaust
|
|
24
|
+
* themselves on reasoning before any tool call is emitted. */
|
|
25
|
+
const DEFAULT_REQUEST_OUTPUT_TOKENS = 32000;
|
|
26
|
+
const MINIMUM_REQUEST_OUTPUT_TOKENS = 1024;
|
|
27
|
+
|
|
28
|
+
export interface EnginePresetRequest {
|
|
29
|
+
preset?: string;
|
|
30
|
+
/** Host-declared model call budget. Accepted for host compatibility. */
|
|
31
|
+
maxModelCalls?: number | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type PresetPolicyKey = 'providerRecoveryPolicy' | 'outputRecoveryPolicy' | 'outputRestartPolicy' | 'toolExecutionPolicy'
|
|
35
|
+
| 'toolErrorRecoveryPolicy' | 'artifactPolicy' | 'workspaceCapturePolicy' | 'deliveryScopePolicy' | 'toolErrorRecoveryModelCalls';
|
|
36
|
+
|
|
37
|
+
export interface EnginePreset {
|
|
38
|
+
contract: typeof ENGINE_PRESET_CONTRACT;
|
|
39
|
+
preset: string;
|
|
40
|
+
revision: number;
|
|
41
|
+
/** Spread into the configuration input of a NEW Run. */
|
|
42
|
+
policies: Required<Pick<RunConfiguration, PresetPolicyKey>>;
|
|
43
|
+
limits: { maxOutputRestarts: number };
|
|
44
|
+
/** Tool-surface options a Node host forwards to the engine tool binder. */
|
|
45
|
+
toolOptions: { executionTimeoutPolicy: 'dispatch/v2'; workspaceEditPolicy: 'zcode-match/v2' };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function listEnginePresets(): readonly string[] {
|
|
49
|
+
return Object.freeze([OFFICIAL_ENGINE_PRESET, EXPERIMENTAL_REASONING_STALL_PRESET]);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function resolveEnginePreset(request: EnginePresetRequest = {}): EnginePreset {
|
|
53
|
+
invariant(request !== null && typeof request === 'object' && !Array.isArray(request)
|
|
54
|
+
&& Object.keys(request).every(key => ['preset', 'maxModelCalls'].includes(key)), 'invalid_engine_preset_request');
|
|
55
|
+
const preset = request.preset ?? OFFICIAL_ENGINE_PRESET;
|
|
56
|
+
const experimental = preset === EXPERIMENTAL_REASONING_STALL_PRESET;
|
|
57
|
+
invariant(preset === OFFICIAL_ENGINE_PRESET || experimental, 'unknown_engine_preset');
|
|
58
|
+
const maxModelCalls = request.maxModelCalls ?? null;
|
|
59
|
+
invariant(maxModelCalls === null || Number.isSafeInteger(maxModelCalls) && maxModelCalls >= 1, 'invalid_engine_preset_request');
|
|
60
|
+
return {
|
|
61
|
+
contract: ENGINE_PRESET_CONTRACT, preset,
|
|
62
|
+
revision: experimental ? EXPERIMENTAL_REASONING_STALL_REVISION : OFFICIAL_REVISION,
|
|
63
|
+
policies: {
|
|
64
|
+
providerRecoveryPolicy: 'provider-recovery/v2',
|
|
65
|
+
outputRecoveryPolicy: experimental ? 'response-boundary/v4' : 'response-boundary/v5',
|
|
66
|
+
// v2: an admitted tool step ends the truncation streak and exhaustion pauses.
|
|
67
|
+
outputRestartPolicy: 'per-response/v2',
|
|
68
|
+
toolExecutionPolicy: 'owner-execution/v1',
|
|
69
|
+
toolErrorRecoveryPolicy: 'diagnose-before-repeat/v2',
|
|
70
|
+
// Spelled out so a host digest over these policies is identical at admission and restore.
|
|
71
|
+
toolErrorRecoveryModelCalls: 10,
|
|
72
|
+
artifactPolicy: 'runtime-artifacts/v1',
|
|
73
|
+
workspaceCapturePolicy: 'declared-subjects/v1',
|
|
74
|
+
// Results are the answer plus the artifacts it names.
|
|
75
|
+
deliveryScopePolicy: 'answer-artifacts/v2',
|
|
76
|
+
},
|
|
77
|
+
limits: { maxOutputRestarts: 0 },
|
|
78
|
+
toolOptions: { executionTimeoutPolicy: 'dispatch/v2', workspaceEditPolicy: 'zcode-match/v2' },
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface PresetOutputBudgetRequest {
|
|
83
|
+
/** An explicit user/operator choice always wins. */
|
|
84
|
+
configured?: number | null;
|
|
85
|
+
/** Largest response the bound model accepts, when known. */
|
|
86
|
+
modelMaxOutputTokens?: number | null;
|
|
87
|
+
contextWindow: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Per-request output budget for a new Run under the official preset.
|
|
91
|
+
* Never exceeds the model limit and leaves at least half the window for input. */
|
|
92
|
+
export function presetRequestOutputTokens(request: PresetOutputBudgetRequest): number {
|
|
93
|
+
const positive = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) > 0;
|
|
94
|
+
invariant(request !== null && typeof request === 'object' && positive(request.contextWindow)
|
|
95
|
+
&& (request.configured == null || positive(request.configured))
|
|
96
|
+
&& (request.modelMaxOutputTokens == null || positive(request.modelMaxOutputTokens)), 'invalid_preset_output_budget');
|
|
97
|
+
const ceiling = Math.min(request.modelMaxOutputTokens ?? Number.MAX_SAFE_INTEGER, Math.floor(request.contextWindow / 2));
|
|
98
|
+
invariant(ceiling >= 1, 'invalid_preset_output_budget');
|
|
99
|
+
if (request.configured != null) return Math.min(request.configured, ceiling);
|
|
100
|
+
return Math.max(Math.min(DEFAULT_REQUEST_OUTPUT_TOKENS, ceiling), Math.min(MINIMUM_REQUEST_OUTPUT_TOKENS, ceiling));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Engine control tools the preset policies require. A host appends these to
|
|
104
|
+
* its own tools instead of knowing which policy implies which control. */
|
|
105
|
+
export function enginePresetToolDefinitions(preset: Pick<EnginePreset, 'policies'>): ToolDefinition[] {
|
|
106
|
+
return [
|
|
107
|
+
...(preset.policies.deliveryScopePolicy ? deliveryToolDefinitions(preset.policies.deliveryScopePolicy) : []),
|
|
108
|
+
...(preset.policies.artifactPolicy ? artifactToolDefinitions() : []),
|
|
109
|
+
];
|
|
110
|
+
}
|
package/src/index.mts
CHANGED
package/src/kernel.mts
CHANGED
|
@@ -14,7 +14,8 @@ import { executeTimedTool } from './tool-execution.mjs';
|
|
|
14
14
|
import { executeKernelTool, kernelToolPolicy } from './kernel-tool-staging.mjs';
|
|
15
15
|
import type { ToolDispatchProof, ToolFailureObservation } from './tool-execution.mjs';
|
|
16
16
|
import { reduceCommand, transition } from './transitions.mjs';
|
|
17
|
-
import { addUsage, modelToolCatalog, modelRoom, objectValue, plan, reduceModel,
|
|
17
|
+
import { addUsage, initialPlanMessages, initialPlanPending, modelToolCatalog, modelRoom, objectValue, plan, reduceModel,
|
|
18
|
+
reduceTools, settle, validateModelResult } from './machine.mjs';
|
|
18
19
|
import { browserTaskMessages } from './task-policy.mjs';
|
|
19
20
|
import { normalizeToolIdentities, projectSessionHistory } from './history.mjs';
|
|
20
21
|
import { prepareSourceReadQuote, sourceReadBudgetFor, SOURCE_READ_POLICY } from './source-read-budget.mjs';
|
|
@@ -32,10 +33,10 @@ import { assertHookFeedbackRetained, deniedByHook, reduceHook, stagePostHooks }
|
|
|
32
33
|
import { hookBytes, hookResult } from './hook-contract.mjs';
|
|
33
34
|
import { planNativeContext, reduceContextModel } from './context-planning.mjs';
|
|
34
35
|
import type { ContextCounters } from './context-planning.mjs';
|
|
35
|
-
import { collectContextContributions, contextSourceUnavailable } from './context-contributions.mjs';
|
|
36
|
+
import { collectContextContributions, contextSourceUnavailable, expiredHostContribution } from './context-contributions.mjs';
|
|
36
37
|
import { validateInstructionScopes } from './instruction-scopes.mjs';
|
|
37
38
|
import { refreshContextSources } from './context-source-refresh.mjs';
|
|
38
|
-
import { outputRestartPayload } from './output-recovery.mjs';
|
|
39
|
+
import { outputRestartPayload, reasoningStallRetryTokens } from './output-recovery.mjs';
|
|
39
40
|
import { reduceTurnInput } from './turn-input.mjs';
|
|
40
41
|
import { modelStreamCapture } from './model-stream.mjs';
|
|
41
42
|
import { browserRecoveryTransition } from './browser-runtime.mjs';
|
|
@@ -261,7 +262,10 @@ export class NativeKernel {
|
|
|
261
262
|
const promotion = admitChildPromotion({ ...snapshot, ...changes }, config, command, this.childTaskStates(snapshot));
|
|
262
263
|
return promotion.reason === 'applied' ? { ...promotion, commandId: command.commandId } : null;
|
|
263
264
|
}
|
|
264
|
-
async runUntilIdle(scope: RunScope, runId: string, { signal, waitForRetry = true }: {
|
|
265
|
+
async runUntilIdle(scope: RunScope, runId: string, { signal, detachSignal, waitForRetry = true }: {
|
|
266
|
+
signal?: AbortSignal; detachSignal?: AbortSignal; waitForRetry?: boolean;
|
|
267
|
+
} = {}): Promise<RunSnapshot> {
|
|
268
|
+
detachSignal?.throwIfAborted();
|
|
265
269
|
const initial = this.drivingState(scope, runId);
|
|
266
270
|
invariant(this.digest(initial.configuration) === initial.snapshot.configDigest, 'stored_configuration_mismatch');
|
|
267
271
|
this.policies.bindings(effectiveRunConfiguration(initial.snapshot, initial.configuration, this.digest));
|
|
@@ -280,6 +284,11 @@ export class NativeKernel {
|
|
|
280
284
|
const externalAbort = () => this.submit(scope, runId, { commandId: `${key}:signal-cancel`, kind: 'cancel', payload: {} });
|
|
281
285
|
if (signal?.aborted) externalAbort();
|
|
282
286
|
signal?.addEventListener('abort', externalAbort, { once: true });
|
|
287
|
+
// Worker shutdown releases ownership without submitting a user cancel.
|
|
288
|
+
// A claimed effect with no committed receipt follows normal lease recovery.
|
|
289
|
+
const detach = () => controller.abort(new NativeError('worker_detached'));
|
|
290
|
+
detachSignal?.addEventListener('abort', detach, { once: true });
|
|
291
|
+
if (detachSignal?.aborted) detach();
|
|
283
292
|
let leaseError: unknown;
|
|
284
293
|
const heartbeat = setInterval(() => {
|
|
285
294
|
try {
|
|
@@ -299,6 +308,7 @@ export class NativeKernel {
|
|
|
299
308
|
// Immediate ports and synchronous storage can otherwise form an
|
|
300
309
|
// unbounded microtask chain that starves lease renewal and cancellation.
|
|
301
310
|
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
|
311
|
+
detachSignal?.throwIfAborted();
|
|
302
312
|
if (leaseError) throw leaseError;
|
|
303
313
|
if (this.onCheckpoint) {
|
|
304
314
|
const checkpoint = (this.store.authority?.(scope, runId) ?? this.store.load(scope, runId)).snapshot;
|
|
@@ -452,12 +462,13 @@ export class NativeKernel {
|
|
|
452
462
|
try { claimed = this.store.claim(scope, runId, lease, this.now(), intent.operationKey); }
|
|
453
463
|
catch (error) { if (isNativeError(error) && error.code === 'pending_command_conflict') continue; throw error; }
|
|
454
464
|
const claimedSnapshot = (this.store.authority?.(scope, runId) ?? this.store.load(scope, runId)).snapshot;
|
|
455
|
-
const batch = await this.execute(claimedSnapshot, config, claimed, controller.signal, lease.fence);
|
|
465
|
+
const batch = await this.execute(claimedSnapshot, config, claimed, controller.signal, lease.fence, detachSignal);
|
|
456
466
|
this.commit(claimedSnapshot, lease, batch);
|
|
457
467
|
continue;
|
|
458
468
|
}
|
|
459
469
|
const next = plan({ ...snapshot, activeElapsedMs: this.elapsed(snapshot) }, config, { context: !!this.ports.context, workspace: !!this.ports.workspace,
|
|
460
|
-
verification: !!this.ports.verification
|
|
470
|
+
verification: !!this.ports.verification && this.ports.verification.available?.(config) !== false,
|
|
471
|
+
input: !!this.ports.input }, this.digest, this.policies);
|
|
461
472
|
if (!next) return snapshot;
|
|
462
473
|
try { this.commit(snapshot, lease, next); }
|
|
463
474
|
catch (error) { if (isNativeError(error) && error.code === 'pending_command_conflict') continue; throw error; }
|
|
@@ -465,6 +476,7 @@ export class NativeKernel {
|
|
|
465
476
|
} finally {
|
|
466
477
|
clearInterval(heartbeat); this.active.delete(key); this.clockAnchors.delete(key);
|
|
467
478
|
signal?.removeEventListener('abort', externalAbort);
|
|
479
|
+
detachSignal?.removeEventListener('abort', detach);
|
|
468
480
|
try { this.store.release(scope, runId, lease); }
|
|
469
481
|
catch (error) { if (!(isNativeError(error) && error.code === 'stale_fence')) throw error; }
|
|
470
482
|
}
|
|
@@ -611,7 +623,8 @@ export class NativeKernel {
|
|
|
611
623
|
}
|
|
612
624
|
return recoverClaimed(snapshot, config, intent, this.now(), observedFacts);
|
|
613
625
|
}
|
|
614
|
-
private async execute(snapshot: RunSnapshot, configuration: RunConfiguration, intent: EffectIntent, signal: AbortSignal,
|
|
626
|
+
private async execute(snapshot: RunSnapshot, configuration: RunConfiguration, intent: EffectIntent, signal: AbortSignal,
|
|
627
|
+
executionFence: number, detachSignal?: AbortSignal): Promise<CommitBatch> {
|
|
615
628
|
const started = this.monotonicNow(), abort = new AbortController();
|
|
616
629
|
const effectSignal = AbortSignal.any([signal, abort.signal]);
|
|
617
630
|
const context: PortContext = { scope: copy(snapshot.scope), runId: snapshot.runId, sessionId: snapshot.sessionId,
|
|
@@ -734,12 +747,15 @@ export class NativeKernel {
|
|
|
734
747
|
changes.todos = { ...copy(snapshot.todos), assistantTurns,
|
|
735
748
|
...(result.toolCalls.some(call => call.name === this.policies.forRun(configuration).todo.TODO_WRITE) ? { lastWriteAssistantTurn: assistantTurns } : {}) };
|
|
736
749
|
}
|
|
737
|
-
|
|
738
|
-
|
|
750
|
+
const planning = intent.payload.purpose === 'initial_plan';
|
|
751
|
+
const planText = planning && changes.initialPlanCompleted && assistantOffset >= 0 ? appended[assistantOffset]!.content : null;
|
|
752
|
+
facts.push({ kind: 'model.completed', payload: { kind: planText === null ? result.kind : 'initial_plan',
|
|
753
|
+
text: planning ? planText ?? '' : rejectedDraft ? '' : result.text,
|
|
754
|
+
...(!planning && rejectedDraft ? { candidateStatus: 'rejected' } : {}),
|
|
739
755
|
messageIndex: assistantOffset < 0 ? null : snapshot.messages.length + assistantOffset,
|
|
740
756
|
messageCursor: changes.messages?.length ?? snapshot.messages.length,
|
|
741
757
|
usageReported: result.usageReported !== false,
|
|
742
|
-
toolCalls: result.toolCalls.map(objectValue), usage: objectValue(result.usage) } });
|
|
758
|
+
toolCalls: planning ? [] : result.toolCalls.map(objectValue), usage: objectValue(result.usage) } });
|
|
743
759
|
break;
|
|
744
760
|
}
|
|
745
761
|
case 'input':
|
|
@@ -920,6 +936,8 @@ export class NativeKernel {
|
|
|
920
936
|
default: throw new NativeError('effect_port_not_implemented');
|
|
921
937
|
}
|
|
922
938
|
} catch (error) {
|
|
939
|
+
// Leave an unsettled claim for fenced recovery when the worker shuts down.
|
|
940
|
+
detachSignal?.throwIfAborted();
|
|
923
941
|
const code = isNativeError(error) ? error.code : 'effect_port_error';
|
|
924
942
|
const unavailableSource = contextSourceUnavailable(error, configuration);
|
|
925
943
|
facts.push(observedEffectFailure({ operationKey: intent.operationKey, kind: intent.kind, code,
|
|
@@ -1034,11 +1052,17 @@ export class NativeKernel {
|
|
|
1034
1052
|
private taskModelRequest(context: PortContext, snapshot: RunSnapshot, configuration: RunConfiguration, intent: EffectIntent): ModelRequest {
|
|
1035
1053
|
const review = intent.payload.purpose === 'delivery_review';
|
|
1036
1054
|
const beforeCall = { ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } };
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1055
|
+
const profile = copy(configuration.profile);
|
|
1056
|
+
// Admission reserved the full allowance. Lowering the dispatched request
|
|
1057
|
+
// preserves that admission and the frozen Run profile.
|
|
1058
|
+
if (!review && configuration.outputRecoveryPolicy === 'response-boundary/v4' && snapshot.reasoningStallRetry)
|
|
1059
|
+
profile.maxOutputTokens = reasoningStallRetryTokens(profile.maxOutputTokens);
|
|
1060
|
+
const messages = review ? snapshot.preparedContext ? modelContextMessages(snapshot, this.digest) : this.policies.forRun(configuration).review.deliveryReviewMessages(snapshot)
|
|
1040
1061
|
: configuration.profile.operatorGuidancePolicy === 'journaled-system/v1' ? modelContextMessages(snapshot, this.digest)
|
|
1041
|
-
: deliveryTaskMessages(beforeCall, configuration, browserTaskMessages(beforeCall, configuration, modelContextMessages(snapshot, this.digest)))
|
|
1062
|
+
: deliveryTaskMessages(beforeCall, configuration, browserTaskMessages(beforeCall, configuration, modelContextMessages(snapshot, this.digest)));
|
|
1063
|
+
return { ...context, profile, ...(review ? { purpose: 'delivery_review' as const } : {}),
|
|
1064
|
+
...(!review && snapshot.usage.toolCalls === 0 ? { beforeFirstTool: true as const } : {}),
|
|
1065
|
+
messages: intent.payload.purpose === 'initial_plan' ? initialPlanMessages(snapshot, configuration, messages) : messages,
|
|
1042
1066
|
tools: copy(modelToolCatalog(beforeCall, configuration, this.policies)), finalizationOnly: intent.payload.finalizationOnly === true,
|
|
1043
1067
|
maxInlineImageBytes: configuration.limits.maxInlineImageBytes };
|
|
1044
1068
|
}
|
|
@@ -1072,12 +1096,14 @@ export class NativeKernel {
|
|
|
1072
1096
|
}
|
|
1073
1097
|
case 'model': {
|
|
1074
1098
|
const review = intent.payload.purpose === 'delivery_review';
|
|
1075
|
-
|
|
1099
|
+
const compaction = intent.payload.purpose === 'compaction';
|
|
1100
|
+
invariant(compaction || review === this.policies.forRun(configuration).review.reviewPending(snapshot)
|
|
1101
|
+
&& (intent.payload.purpose === 'initial_plan') === initialPlanPending(snapshot, configuration), 'model_purpose_changed');
|
|
1076
1102
|
if (configuration.contextPolicy) {
|
|
1077
1103
|
invariant(this.ports.context?.tokens?.tokenizerId === configuration.contextPolicy.tokenizerId
|
|
1078
1104
|
&& this.ports.context.tokens.tokenizerDigest === configuration.contextPolicy.tokenizerDigest, 'context_tokenizer_binding_mismatch');
|
|
1079
1105
|
}
|
|
1080
|
-
if (
|
|
1106
|
+
if (compaction) {
|
|
1081
1107
|
const chunk = snapshot.contextState?.compaction?.chunk;
|
|
1082
1108
|
invariant(chunk && chunk.projectionDigest === this.digest(chunk.messages), 'context_summary_quote_changed');
|
|
1083
1109
|
return this.ports.model.generate({ ...context, profile: { ...copy(configuration.profile), maxOutputTokens: chunk.maxOutputTokens },
|
|
@@ -1093,6 +1119,12 @@ export class NativeKernel {
|
|
|
1093
1119
|
&& admission.countedInputTokens + admission.maxOutputTokens <= configuration.profile.contextWindow, 'context_admission_invalid');
|
|
1094
1120
|
}
|
|
1095
1121
|
const request = this.taskModelRequest(context, snapshot, configuration, intent);
|
|
1122
|
+
const now = Date.now();
|
|
1123
|
+
request.messages = request.messages.filter(message => {
|
|
1124
|
+
const expired = expiredHostContribution(message, configuration, now);
|
|
1125
|
+
invariant(!expired?.required, 'context_source_expired');
|
|
1126
|
+
return !expired;
|
|
1127
|
+
});
|
|
1096
1128
|
return this.ports.model.generate(request, emit);
|
|
1097
1129
|
}
|
|
1098
1130
|
case 'tool': {
|
|
@@ -1206,11 +1238,12 @@ export class NativeKernel {
|
|
|
1206
1238
|
} } : {}),
|
|
1207
1239
|
countRequest: async (messages, tools, purpose, maxOutputTokens) => {
|
|
1208
1240
|
context.signal.throwIfAborted(); assertBinding();
|
|
1209
|
-
const
|
|
1210
|
-
messages: purpose === 'task' ? configuration.profile.operatorGuidancePolicy === 'journaled-system/v1'
|
|
1241
|
+
const projected = purpose === 'task' ? configuration.profile.operatorGuidancePolicy === 'journaled-system/v1'
|
|
1211
1242
|
? this.policies.forRun(configuration).providerContext.projectAnthropicReplay(this.policies.forRun(configuration).providerContext.operatorInputView(this.policies.forRun(configuration).providerContext.anthropicTaskFeedback(snapshot, configuration, messages), configuration.profile, this.digest), tools,
|
|
1212
1243
|
configuration.profile, snapshot.abandonedReplayDigests ?? [], this.digest).messages
|
|
1213
|
-
: deliveryTaskMessages(snapshot, configuration, browserTaskMessages(snapshot, configuration, messages)) : messages
|
|
1244
|
+
: deliveryTaskMessages(snapshot, configuration, browserTaskMessages(snapshot, configuration, messages)) : messages;
|
|
1245
|
+
const count = await counter.countRequest({ ...context, profile: { ...copy(configuration.profile), maxOutputTokens },
|
|
1246
|
+
messages: purpose === 'task' ? initialPlanMessages(snapshot, configuration, projected) : projected, tools, purpose, maxOutputTokens,
|
|
1214
1247
|
maxInlineImageBytes: configuration.limits.maxInlineImageBytes });
|
|
1215
1248
|
context.signal.throwIfAborted(); assertBinding(); return count;
|
|
1216
1249
|
},
|
package/src/machine.mts
CHANGED
|
@@ -16,7 +16,7 @@ import { rememberCommand } from './background-runtime.mjs';
|
|
|
16
16
|
import { admittedToolBudget, outstandingChildCalls, reduceChildBudget } from './child-budget.mjs';
|
|
17
17
|
import { prepareChildLifecycle, unsettledChildren } from './child-runtime.mjs';
|
|
18
18
|
import { toolResourceUsage, toolUsageIncomplete } from './tool-resource-usage.mjs';
|
|
19
|
-
import { completeContinuation, outputRecoveryMode, restartContinuation } from './output-recovery.mjs';
|
|
19
|
+
import { completeContinuation, outputRecoveryMode, reasoningStall, reasoningStallRetryTokens, restartContinuation } from './output-recovery.mjs';
|
|
20
20
|
import { responseBoundaryRecovery, responseContinuationPending, responseScopedOutputRestarts } from './response-continuation.mjs';
|
|
21
21
|
import { advanceDiagnosticRecovery, advanceObservedProgress, advanceToolErrorStreak, guardedToolErrorAction,
|
|
22
22
|
refuseUndiagnosedToolAction, reserveDiagnosticTrial, toolErrorRecoveryBoundary, toolErrorRecoveryEnabled,
|
|
@@ -66,8 +66,18 @@ export function finalizationOnly(snapshot: RunSnapshot, config: RunConfiguration
|
|
|
66
66
|
const calls = modelRoom(snapshot, config);
|
|
67
67
|
return calls <= config.limits.finalizationReserveModelCalls;
|
|
68
68
|
}
|
|
69
|
+
export function initialPlanPending(snapshot: RunSnapshot, config: RunConfiguration): boolean {
|
|
70
|
+
return config.initialPlanPolicy === 'plan-act-observe/v1' && !snapshot.initialPlanCompleted;
|
|
71
|
+
}
|
|
72
|
+
export function initialPlanMessages(snapshot: RunSnapshot, config: RunConfiguration, messages: Message[]): Message[] {
|
|
73
|
+
if (!initialPlanPending(snapshot, config)) return messages;
|
|
74
|
+
const instruction = responseContinuationPending(snapshot, config)
|
|
75
|
+
? 'Continue the unfinished execution plan. Return only its missing text suffix.'
|
|
76
|
+
: 'First give a concise step-by-step execution plan for the current user request. Tools are unavailable in this step. The next step will execute the plan.';
|
|
77
|
+
return [{ role: 'system', content: instruction }, ...messages];
|
|
78
|
+
}
|
|
69
79
|
export function advertisedTools(snapshot: RunSnapshot, config: RunConfiguration, policies = new NativePolicyRegistry()) {
|
|
70
|
-
if (responseContinuationPending(snapshot, config)) return [];
|
|
80
|
+
if (initialPlanPending(snapshot, config) || responseContinuationPending(snapshot, config)) return [];
|
|
71
81
|
if (policies.forRun(config).review.reviewPending(snapshot)) return policies.forRun(config).review.deliveryReviewTools(snapshot, config);
|
|
72
82
|
const submission = finalSubmissionTool(config);
|
|
73
83
|
const tools = finalizationOnly(snapshot, config) || toolRoom(snapshot, config) <= 0 ? []
|
|
@@ -80,7 +90,7 @@ export function advertisedTools(snapshot: RunSnapshot, config: RunConfiguration,
|
|
|
80
90
|
export interface PlanCapabilities { context: boolean; workspace: boolean; verification: boolean; input?: boolean }
|
|
81
91
|
/** Stable declaration is distinct from the per-turn execution admission above. */
|
|
82
92
|
export function modelToolCatalog(snapshot: RunSnapshot, config: RunConfiguration, policies = new NativePolicyRegistry()) {
|
|
83
|
-
if (responseContinuationPending(snapshot, config)) return [];
|
|
93
|
+
if (initialPlanPending(snapshot, config) || responseContinuationPending(snapshot, config)) return [];
|
|
84
94
|
if ((config.profile.toolCatalogPolicy !== 'stable-task/v1' && config.profile.providerToolSearchPolicy !== 'anthropic-deferred/v1')
|
|
85
95
|
|| policies.forRun(config).review.reviewPending(snapshot)) return discoveryModelTools(snapshot, config, advertisedTools(snapshot, config, policies));
|
|
86
96
|
const submission = finalSubmissionTool(config);
|
|
@@ -216,6 +226,8 @@ export function plan(snapshot: RunSnapshot, config: RunConfiguration, capabiliti
|
|
|
216
226
|
if (candidate) return transition(snapshot, { phase: 'verifying', candidate, verification: null, preparedContext: null },
|
|
217
227
|
[{ kind: 'verification.checkpoint_started', payload: { workspaceRevision: snapshot.workspaceRevision } }]);
|
|
218
228
|
}
|
|
229
|
+
if (initialPlanPending(snapshot, config)) return prepareEffect(snapshot, 'model', 'requesting_model',
|
|
230
|
+
{ purpose: 'initial_plan', finalizationOnly: false });
|
|
219
231
|
return prepareEffect(snapshot, 'model', 'requesting_model', policies.forRun(config).review.reviewPending(snapshot)
|
|
220
232
|
? { purpose: 'delivery_review', finalizationOnly: false } : { finalizationOnly: finalizationOnly(snapshot, config) },
|
|
221
233
|
policies.forRun(config).review.reviewPending(snapshot) ? {} : policies.forRun(config).providerContext.captureAnthropicContext(snapshot, config, modelToolCatalog(snapshot, config, policies), digest));
|
|
@@ -243,11 +255,11 @@ export function plan(snapshot: RunSnapshot, config: RunConfiguration, capabiliti
|
|
|
243
255
|
[{ kind: 'tools.budget_exhausted', payload: {} }]);
|
|
244
256
|
}
|
|
245
257
|
let calls: ToolCall[] = [first];
|
|
246
|
-
if (definition.readOnly && definition.concurrentSafe && !definition.delegatedReadOnly && !guardedToolErrorAction(snapshot, first, digest)) {
|
|
258
|
+
if (definition.readOnly && definition.concurrentSafe && !definition.approvalPolicy && !definition.delegatedReadOnly && !guardedToolErrorAction(snapshot, first, digest)) {
|
|
247
259
|
calls = [];
|
|
248
260
|
for (const call of snapshot.pendingTools.slice(0, Math.min(config.limits.maxParallelTools, toolRoom(snapshot, config)))) {
|
|
249
261
|
const tool = config.tools.find(item => item.name === call.name);
|
|
250
|
-
if (!tool?.readOnly || !tool.concurrentSafe || tool.delegatedReadOnly || tool.observationRole !== 'none') break;
|
|
262
|
+
if (!tool?.readOnly || !tool.concurrentSafe || tool.approvalPolicy || tool.delegatedReadOnly || tool.observationRole !== 'none') break;
|
|
251
263
|
if (guardedToolErrorAction(snapshot, call, digest)) break;
|
|
252
264
|
calls.push(call);
|
|
253
265
|
}
|
|
@@ -338,12 +350,22 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
338
350
|
// errors, malformed calls and context-overflow retries keep this input debt.
|
|
339
351
|
if (snapshot.hookState && ['tool_calls', 'final_candidate', 'output_limit'].includes(result.kind)
|
|
340
352
|
&& (result.toolCalls.length > 0 || result.text.trim())) base.hookState = { ...currentHookState(snapshot), feedback: [] };
|
|
353
|
+
const stalled = config.outputRecoveryPolicy === 'response-boundary/v4' && reasoningStall(result);
|
|
354
|
+
// Keep the narrowed retry through transport errors and context preparation.
|
|
355
|
+
// A sealed cutoff with text or an unfinished tool call uses the ordinary budget again.
|
|
356
|
+
if (snapshot.reasoningStallRetry && (result.kind === 'tool_calls' || result.kind === 'final_candidate'
|
|
357
|
+
|| result.kind === 'output_limit' && !stalled)) base.reasoningStallRetry = false;
|
|
341
358
|
const message: Message = { role: 'assistant', content: result.text,
|
|
342
359
|
...(config.contextPolicy?.pruneIdleThresholdMinutes !== undefined && Number.isSafeInteger(now) && now >= 0
|
|
343
360
|
&& ['tool_calls', 'final_candidate', 'output_limit'].includes(result.kind) ? { completedAtMs: now } : {}),
|
|
344
361
|
...(replay ? { providerReplay: replay, ...(result.replayToolIds ? { replayToolIds: result.replayToolIds } : {}) } : {}) };
|
|
345
362
|
switch (result.kind) {
|
|
346
363
|
case 'tool_calls':
|
|
364
|
+
if (initialPlanPending(snapshot, config)) {
|
|
365
|
+
const errors = snapshot.modelErrors + 1, exhausted = errors > config.profile.maxRetries;
|
|
366
|
+
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [],
|
|
367
|
+
modelErrors: errors, outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'initial_plan_invalid' : null };
|
|
368
|
+
}
|
|
347
369
|
if (responseContinuationPending(snapshot, config)) {
|
|
348
370
|
const errors = snapshot.modelErrors + 1, exhausted = errors > config.profile.maxRetries;
|
|
349
371
|
return { ...base, pendingTools: [], modelErrors: errors, phase: exhausted ? 'finalizing' : 'preparing_context',
|
|
@@ -398,6 +420,17 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
398
420
|
continuations: 0, modelErrors: 0,
|
|
399
421
|
...(responseScopedOutputRestarts(config) ? { outputRestarts: 0 } : {}) };
|
|
400
422
|
case 'final_candidate': {
|
|
423
|
+
if (initialPlanPending(snapshot, config)) {
|
|
424
|
+
const text = completeContinuation(snapshot.messages, result.text, digest).trim();
|
|
425
|
+
if (!text) {
|
|
426
|
+
const errors = snapshot.modelErrors + 1, exhausted = errors > config.profile.maxRetries;
|
|
427
|
+
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', modelErrors: errors,
|
|
428
|
+
outcome: exhausted ? 'failed' : null, reason: exhausted ? 'initial_plan_empty' : null };
|
|
429
|
+
}
|
|
430
|
+
return { ...base, phase: 'preparing_context', initialPlanCompleted: true, modelErrors: 0,
|
|
431
|
+
continuations: 0, outputRestarts: 0,
|
|
432
|
+
messages: [...snapshot.messages, { role: 'assistant', kind: 'initial_plan', content: text }] };
|
|
433
|
+
}
|
|
401
434
|
if (config.contract.finalSubmissionSchema) {
|
|
402
435
|
const errors = snapshot.modelErrors + 1;
|
|
403
436
|
const exhausted = errors > config.profile.maxRetries || modelRoom(snapshot, config) <= 0;
|
|
@@ -414,6 +447,10 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
414
447
|
}
|
|
415
448
|
case 'output_limit': {
|
|
416
449
|
const resumable = config.outputRestartPolicy === 'per-response/v2';
|
|
450
|
+
const boundedRecovery = config.outputRecoveryPolicy === 'response-boundary/v4' || config.outputRecoveryPolicy === 'response-boundary/v5';
|
|
451
|
+
// Honor stricter caller limits. The experimental retry spends the same
|
|
452
|
+
// continuation allowance as the ordinary retry.
|
|
453
|
+
const continuationLimit = boundedRecovery ? Math.min(config.profile.maxContinuations, 2) : config.profile.maxContinuations;
|
|
417
454
|
const continuation = () => {
|
|
418
455
|
const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config,
|
|
419
456
|
advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
|
|
@@ -435,11 +472,22 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
435
472
|
? { phase: 'paused', resumePhase: 'preparing_context', outcome: null, reason: 'output_budget_exhausted',
|
|
436
473
|
messages: result.text ? continuation().messages : snapshot.messages }
|
|
437
474
|
: { phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
|
|
438
|
-
if (
|
|
475
|
+
if (stalled) {
|
|
476
|
+
if (snapshot.reasoningStallRetry || snapshot.continuations >= continuationLimit
|
|
477
|
+
|| reasoningStallRetryTokens(config.profile.maxOutputTokens) >= config.profile.maxOutputTokens)
|
|
478
|
+
return { ...base, ...exhausted(), messages: snapshot.messages };
|
|
479
|
+
const suffix = responseContinuationPending(snapshot, config);
|
|
480
|
+
return { ...base, phase: 'preparing_context', reasoningStallRetry: true, continuations: snapshot.continuations + 1,
|
|
481
|
+
messages: [...snapshot.messages, { role: 'user',
|
|
482
|
+
kind: suffix ? 'response_continuation_feedback' : 'output_limit_reasoning_observation',
|
|
483
|
+
content: suffix ? 'Continue with only the missing text suffix now.'
|
|
484
|
+
: 'The previous attempt spent its output budget on reasoning without taking action. Take the next useful tool action now, or answer directly if the task is complete.' }] };
|
|
485
|
+
}
|
|
486
|
+
if (snapshot.continuations >= continuationLimit) {
|
|
439
487
|
// Committed answer text stays a suffix contract even when the first
|
|
440
488
|
// response has no remaining continuation allowance. It is not a tool
|
|
441
489
|
// fragment that may be discarded for an output restart.
|
|
442
|
-
if (responseContinuationPending(snapshot, config) || resumable && continuation().mode === 'suffix')
|
|
490
|
+
if (boundedRecovery || responseContinuationPending(snapshot, config) || resumable && continuation().mode === 'suffix')
|
|
443
491
|
return { ...base, ...exhausted() };
|
|
444
492
|
if (snapshot.outputRestarts < config.limits.maxOutputRestarts) {
|
|
445
493
|
try { return { ...base, ...restartContinuation(snapshot, config, result.text, digest), phase: 'preparing_context',
|
package/src/output-recovery.mts
CHANGED
|
@@ -5,12 +5,24 @@ import { contextMessageRef } from './context-planning.mjs';
|
|
|
5
5
|
|
|
6
6
|
type Digest = (value: unknown) => string;
|
|
7
7
|
|
|
8
|
+
export function reasoningStall(result: ModelResult): boolean {
|
|
9
|
+
// The adapter detects unfinished wire tool calls even when they aren't
|
|
10
|
+
// executable. Missing usage or a mixed response isn't proof of pure reasoning.
|
|
11
|
+
return result.kind === 'output_limit' && result.outputBoundary === 'no-visible-output/v1'
|
|
12
|
+
&& !result.text.trim() && !result.toolCalls.length && result.usageReported === true
|
|
13
|
+
&& result.usage.outputTokens > 0 && result.usage.reasoningTokens === result.usage.outputTokens;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function reasoningStallRetryTokens(maxOutputTokens: number): number {
|
|
17
|
+
return Math.max(1, Math.min(8192, Math.floor(maxOutputTokens / 2)));
|
|
18
|
+
}
|
|
19
|
+
|
|
8
20
|
/** Select from actual admission after the completed model claim, never the catalog. */
|
|
9
21
|
export function outputRecoveryMode(snapshot: RunSnapshot, config: RunConfiguration, toolsAvailable: boolean, result?: ModelResult): 'suffix' | 'task_resume' {
|
|
10
22
|
if (responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text') {
|
|
11
23
|
// A provider length boundary identifies truncated text, not task completion.
|
|
12
24
|
// Preserve explicit sealed delivery, otherwise retain the admitted tools.
|
|
13
|
-
if (config.outputRecoveryPolicy
|
|
25
|
+
if (config.outputRecoveryPolicy !== 'response-boundary/v2')
|
|
14
26
|
return responseContinuationPending(snapshot, config) || !toolsAvailable ? 'suffix' : 'task_resume';
|
|
15
27
|
if (responseContinuationPending(snapshot, config)
|
|
16
28
|
|| result?.textCommitVersion === 'provider-finished-text/v1' && result.outputBoundary === 'assistant-text/v1') return 'suffix';
|
package/src/recovery.mts
CHANGED
|
@@ -12,6 +12,7 @@ export function safeReadRecoveryCalls(calls: ToolCall[], configuration: RunConfi
|
|
|
12
12
|
}
|
|
13
13
|
function replayPolicy(intent: EffectIntent, configuration: RunConfiguration): string | null {
|
|
14
14
|
if (intent.kind === 'workspace') return 'workspace-observation/v1';
|
|
15
|
+
if (intent.kind === 'verify' && configuration.hostVerification) return 'host-verification-read/v1';
|
|
15
16
|
if (intent.kind === 'model' && configuration.modelRecoveryPolicy === 'pure-inference/v1') return 'pure-inference/v1';
|
|
16
17
|
if (intent.kind === 'tool') {
|
|
17
18
|
const calls = intent.payload.calls as unknown as ToolCall[];
|
|
@@ -3,7 +3,8 @@ import type { Message, RunConfiguration, RunSnapshot } from './contracts.mjs';
|
|
|
3
3
|
/** The output recovery strategy is versioned separately from the sealed v2
|
|
4
4
|
* text-fragment protocol. A v3 task may still own an explicit suffix chain. */
|
|
5
5
|
export function responseBoundaryRecovery(config: Pick<RunConfiguration, 'outputRecoveryPolicy'>): boolean {
|
|
6
|
-
return config.outputRecoveryPolicy === 'response-boundary/v2' || config.outputRecoveryPolicy === 'response-boundary/v3'
|
|
6
|
+
return config.outputRecoveryPolicy === 'response-boundary/v2' || config.outputRecoveryPolicy === 'response-boundary/v3'
|
|
7
|
+
|| config.outputRecoveryPolicy === 'response-boundary/v4' || config.outputRecoveryPolicy === 'response-boundary/v5';
|
|
7
8
|
}
|
|
8
9
|
|
|
9
10
|
export function responseScopedOutputRestarts(config: Pick<RunConfiguration, 'outputRestartPolicy'>): boolean {
|
package/src/transitions.mts
CHANGED
|
@@ -146,7 +146,8 @@ export function reduceCommand(snapshot: RunSnapshot, command: RunCommand, pendin
|
|
|
146
146
|
if (snapshot.phase !== 'paused') reason = 'not_paused';
|
|
147
147
|
else changes = { phase: snapshot.resumePhase ?? 'preparing_context', resumePhase: null,
|
|
148
148
|
...(snapshot.reason === 'output_budget_exhausted' && bindings.configuration?.outputRestartPolicy === 'per-response/v2'
|
|
149
|
-
? { reason: null, continuations: 0, outputRestarts: 0
|
|
149
|
+
? { reason: null, continuations: 0, outputRestarts: 0,
|
|
150
|
+
...(snapshot.reasoningStallRetry ? { reasoningStallRetry: false } : {}) } : {}),
|
|
150
151
|
...(bindings.configuration?.approvalOutcomePolicy === APPROVAL_OUTCOME_POLICY
|
|
151
152
|
&& ['approval_rejected', 'approval_cancelled', 'approval_unavailable'].includes(snapshot.reason ?? '') ? { reason: null } : {}),
|
|
152
153
|
...(['provider_unavailable', 'context_summary_unavailable', 'context_source_unavailable', 'child_paused']
|