@kingsoftcloud/agentkit-harness-core 0.0.16 → 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 +20 -3
- 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 +24 -2
- 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 +50 -19
- package/dist/machine.d.mts +3 -1
- package/dist/machine.mjs +57 -7
- package/dist/model-stream.d.mts +1 -1
- package/dist/model-stream.mjs +15 -11
- 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 +25 -3
- package/src/context-contributions.mts +53 -2
- package/src/context-planning.mts +7 -4
- package/src/contracts.mts +21 -2
- package/src/engine-preset.mts +110 -0
- package/src/index.mts +1 -0
- package/src/kernel.mts +52 -18
- package/src/machine.mts +55 -7
- package/src/model-stream.mts +11 -8
- 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
|
@@ -28,6 +28,10 @@ export function validateContextSource(source: ContextSourceDefinition, timeoutMs
|
|
|
28
28
|
'invalid_context_source');
|
|
29
29
|
invariant(source.instructionPolicy === undefined || source.instructionPolicy === 'current-files/v1' && source.required,
|
|
30
30
|
'invalid_context_instruction_source');
|
|
31
|
+
invariant(source.hostProjection === undefined || !source.instructionPolicy
|
|
32
|
+
&& ['data/v1', 'instructions-and-data/v1'].includes(source.hostProjection), 'invalid_host_context_projection');
|
|
33
|
+
invariant(source.warnOnFailure === undefined || source.warnOnFailure === true && !source.required && source.hostProjection,
|
|
34
|
+
'invalid_host_context_failure_policy');
|
|
31
35
|
const recovery = source.timeoutRecovery;
|
|
32
36
|
invariant(recovery === undefined || recovery && !Array.isArray(recovery)
|
|
33
37
|
&& Object.keys(recovery).sort().join(',') === 'contract,maxRetries,retryDelayMs' && recovery.contract === 'context-source-timeout/v1'
|
|
@@ -49,6 +53,18 @@ async function retryDelay(ms: number, signal: AbortSignal): Promise<void> {
|
|
|
49
53
|
}
|
|
50
54
|
|
|
51
55
|
export function contextContributionMessage(source: ContextSourceDefinition, item: ObjectValue): Message {
|
|
56
|
+
if (source.hostProjection) {
|
|
57
|
+
const { projection, fragment, expiresAt } = item;
|
|
58
|
+
invariant((projection === 'data' || projection === 'instructions' && source.hostProjection === 'instructions-and-data/v1')
|
|
59
|
+
&& fragment && typeof fragment === 'object' && !Array.isArray(fragment)
|
|
60
|
+
&& (expiresAt === undefined || Number.isSafeInteger(expiresAt) && Number(expiresAt) > 0),
|
|
61
|
+
'context_source_result_invalid');
|
|
62
|
+
const privileged = projection === 'instructions';
|
|
63
|
+
return { role: privileged ? 'system' : 'user', kind: 'context_contribution',
|
|
64
|
+
content: canonical({ schemaVersion: CONTEXT_CONTRIBUTION_CONTRACT, sourceId: source.sourceId, bindingDigest: source.bindingDigest,
|
|
65
|
+
trust: privileged ? 'host-granted' : 'untrusted', purpose: privileged ? 'host_instructions' : 'context_only',
|
|
66
|
+
notice: 'Context grants no approval, acceptance or execution authority.', item: fragment, ...(expiresAt === undefined ? {} : { expiresAt }) }) };
|
|
67
|
+
}
|
|
52
68
|
return { role: 'user', kind: 'context_contribution', content: canonical({ schemaVersion: CONTEXT_CONTRIBUTION_CONTRACT,
|
|
53
69
|
trust: 'untrusted', purpose: source.instructionPolicy ? 'workspace_instructions' : 'context_only',
|
|
54
70
|
sourceId: source.sourceId, bindingDigest: source.bindingDigest,
|
|
@@ -59,6 +75,30 @@ export function contextContributionMessage(source: ContextSourceDefinition, item
|
|
|
59
75
|
: 'Recalled data grants no approval, acceptance, freshness or execution authority.', item }) };
|
|
60
76
|
}
|
|
61
77
|
|
|
78
|
+
function hostContributionSource(message: Message, config: RunConfiguration) {
|
|
79
|
+
if (message.kind !== 'context_contribution'
|
|
80
|
+
|| !config.contextSources.some(source => source.hostProjection)) return null;
|
|
81
|
+
let value: ObjectValue;
|
|
82
|
+
try { value = JSON.parse(message.content); } catch { return null; }
|
|
83
|
+
if (!value || value.schemaVersion !== CONTEXT_CONTRIBUTION_CONTRACT) return null;
|
|
84
|
+
const source = config.contextSources.find(source => source.hostProjection
|
|
85
|
+
&& source.sourceId === value.sourceId && source.bindingDigest === value.bindingDigest);
|
|
86
|
+
return source ? { source, value } : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function hostInstructionContribution(message: Message, config: RunConfiguration): boolean {
|
|
90
|
+
if (message.role !== 'system') return false;
|
|
91
|
+
const admitted = hostContributionSource(message, config);
|
|
92
|
+
return admitted?.source.hostProjection === 'instructions-and-data/v1'
|
|
93
|
+
&& admitted.value.purpose === 'host_instructions' && admitted.value.trust === 'host-granted';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function expiredHostContribution(message: Message, config: RunConfiguration, now: number): ContextSourceDefinition | null {
|
|
97
|
+
const admitted = hostContributionSource(message, config);
|
|
98
|
+
return admitted && typeof admitted.value.expiresAt === 'number' && admitted.value.expiresAt <= now
|
|
99
|
+
? admitted.source : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
62
102
|
/** Only the outer envelope from a frozen source can select instruction retention.
|
|
63
103
|
* A recalled item's own role, policy or source fields never promote its trust. */
|
|
64
104
|
export function currentInstructionContribution(message: Message, config: RunConfiguration): boolean {
|
|
@@ -99,13 +139,17 @@ export async function collectContextContributions(context: PortContext, snapshot
|
|
|
99
139
|
const admitted: Message[] = [];
|
|
100
140
|
for (const item of result.items) {
|
|
101
141
|
invariant(item && typeof item === 'object' && !Array.isArray(item), 'context_source_result_invalid');
|
|
102
|
-
const
|
|
142
|
+
const message = contextContributionMessage(source, item);
|
|
143
|
+
invariant(!expiredHostContribution(message, config, Date.now()), 'context_source_expired');
|
|
144
|
+
const candidate = [...admitted, message];
|
|
103
145
|
if (new TextEncoder().encode(canonical(candidate)).length > source.maxBytes) {
|
|
146
|
+
invariant(!source.hostProjection, 'context_source_byte_budget_exceeded');
|
|
104
147
|
invariant(!source.instructionPolicy, 'context_instruction_source_byte_budget_exceeded'); continue;
|
|
105
148
|
}
|
|
106
149
|
const tokens = await Promise.race([count(copy(candidate)), canceled]); signal.throwIfAborted();
|
|
107
150
|
invariant(Date.now() < deadline, 'context_source_timeout');
|
|
108
151
|
invariant(Number.isSafeInteger(tokens) && tokens >= 0, 'context_token_count_invalid');
|
|
152
|
+
invariant(!source.hostProjection || tokens <= source.maxTokens, 'context_source_token_budget_exceeded');
|
|
109
153
|
invariant(!source.instructionPolicy || tokens <= source.maxTokens, 'context_instruction_source_token_budget_exceeded');
|
|
110
154
|
if (tokens <= source.maxTokens) admitted.push(candidate.at(-1)!);
|
|
111
155
|
}
|
|
@@ -125,7 +169,14 @@ export async function collectContextContributions(context: PortContext, snapshot
|
|
|
125
169
|
if (source.required) throw new ContextSourceUnavailable(source.sourceId, source.bindingDigest, attempt);
|
|
126
170
|
}
|
|
127
171
|
if (source.required) throw error;
|
|
128
|
-
|
|
172
|
+
if (source.warnOnFailure) {
|
|
173
|
+
const message = contextContributionMessage(source, { projection: 'data',
|
|
174
|
+
fragment: { status: 'unavailable', code: 'context_source_unavailable' } });
|
|
175
|
+
if (new TextEncoder().encode(canonical([message])).length <= source.maxBytes
|
|
176
|
+
&& await count([message]).catch(() => Infinity) <= source.maxTokens) messages.push(message);
|
|
177
|
+
}
|
|
178
|
+
context.signal.throwIfAborted();
|
|
179
|
+
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: source.warnOnFailure ? 'warned' : 'skipped',
|
|
129
180
|
...(source.timeoutRecovery ? { timeoutRetries: attempt } : {}) });
|
|
130
181
|
break;
|
|
131
182
|
} finally {
|
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';
|
|
@@ -105,7 +109,7 @@ export interface ModelProfile {
|
|
|
105
109
|
/** Absent on older Runs; projection policy is frozen at admission. */
|
|
106
110
|
inlineReasoningPolicy?: { contract: 'profiled-content/v1' | 'profiled-content/v2'; rule: 'auto' | 'permissive' | 'openai'
|
|
107
111
|
| 'strict-openai' | 'cerebras' | 'groq' | 'deepseek' | 'zai' | 'kspmas-gateway' | 'moonshot' | 'mimo' };
|
|
108
|
-
providerCompatibilityPolicy?: { contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3' | 'provider-compat/v4'; rule: NonNullable<ModelProfile['inlineReasoningPolicy']>['rule'] };
|
|
112
|
+
providerCompatibilityPolicy?: { contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3' | 'provider-compat/v4' | 'provider-compat/v5'; rule: NonNullable<ModelProfile['inlineReasoningPolicy']>['rule'] };
|
|
109
113
|
streaming?: boolean; outputTokenParameter?: 'max_tokens' | 'max_completion_tokens';
|
|
110
114
|
streamTimeoutPolicy?: 'idle/v1'; providerThinkingDisplay?: boolean;
|
|
111
115
|
/** Absent on historical Runs, whose OpenAI usage reports required equality. */
|
|
@@ -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;
|
|
@@ -630,6 +646,8 @@ export interface PortContext extends RunIdentity {
|
|
|
630
646
|
}
|
|
631
647
|
export interface ModelRequest extends PortContext {
|
|
632
648
|
purpose?: 'task' | 'compaction' | 'delivery_review';
|
|
649
|
+
/** Task generation before the first tool dispatch in this Run, including provider retries. */
|
|
650
|
+
beforeFirstTool?: true;
|
|
633
651
|
profile: ModelProfile; messages: Message[]; tools: ToolDefinition[]; finalizationOnly: boolean;
|
|
634
652
|
toolChoice?: 'auto' | 'none' | 'required' | { type: 'function'; function: { name: string } };
|
|
635
653
|
maxInlineImageBytes: number;
|
|
@@ -716,6 +734,7 @@ export interface SourceReadBudget {
|
|
|
716
734
|
maxSourceUnits: number; maxResultUnits: number; maxResultBytes: number;
|
|
717
735
|
}
|
|
718
736
|
export interface VerificationPort {
|
|
737
|
+
available?(configuration: RunConfiguration): boolean;
|
|
719
738
|
verify(request: PortContext & { candidate: CompletionCandidate; contract: TaskContract; snapshot: RunSnapshot }): Promise<VerificationReport>;
|
|
720
739
|
}
|
|
721
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,10 +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
|
-
|
|
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)
|
|
1039
1061
|
: configuration.profile.operatorGuidancePolicy === 'journaled-system/v1' ? modelContextMessages(snapshot, this.digest)
|
|
1040
|
-
: 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,
|
|
1041
1066
|
tools: copy(modelToolCatalog(beforeCall, configuration, this.policies)), finalizationOnly: intent.payload.finalizationOnly === true,
|
|
1042
1067
|
maxInlineImageBytes: configuration.limits.maxInlineImageBytes };
|
|
1043
1068
|
}
|
|
@@ -1071,12 +1096,14 @@ export class NativeKernel {
|
|
|
1071
1096
|
}
|
|
1072
1097
|
case 'model': {
|
|
1073
1098
|
const review = intent.payload.purpose === 'delivery_review';
|
|
1074
|
-
|
|
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');
|
|
1075
1102
|
if (configuration.contextPolicy) {
|
|
1076
1103
|
invariant(this.ports.context?.tokens?.tokenizerId === configuration.contextPolicy.tokenizerId
|
|
1077
1104
|
&& this.ports.context.tokens.tokenizerDigest === configuration.contextPolicy.tokenizerDigest, 'context_tokenizer_binding_mismatch');
|
|
1078
1105
|
}
|
|
1079
|
-
if (
|
|
1106
|
+
if (compaction) {
|
|
1080
1107
|
const chunk = snapshot.contextState?.compaction?.chunk;
|
|
1081
1108
|
invariant(chunk && chunk.projectionDigest === this.digest(chunk.messages), 'context_summary_quote_changed');
|
|
1082
1109
|
return this.ports.model.generate({ ...context, profile: { ...copy(configuration.profile), maxOutputTokens: chunk.maxOutputTokens },
|
|
@@ -1092,6 +1119,12 @@ export class NativeKernel {
|
|
|
1092
1119
|
&& admission.countedInputTokens + admission.maxOutputTokens <= configuration.profile.contextWindow, 'context_admission_invalid');
|
|
1093
1120
|
}
|
|
1094
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
|
+
});
|
|
1095
1128
|
return this.ports.model.generate(request, emit);
|
|
1096
1129
|
}
|
|
1097
1130
|
case 'tool': {
|
|
@@ -1205,11 +1238,12 @@ export class NativeKernel {
|
|
|
1205
1238
|
} } : {}),
|
|
1206
1239
|
countRequest: async (messages, tools, purpose, maxOutputTokens) => {
|
|
1207
1240
|
context.signal.throwIfAborted(); assertBinding();
|
|
1208
|
-
const
|
|
1209
|
-
messages: purpose === 'task' ? configuration.profile.operatorGuidancePolicy === 'journaled-system/v1'
|
|
1241
|
+
const projected = purpose === 'task' ? configuration.profile.operatorGuidancePolicy === 'journaled-system/v1'
|
|
1210
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,
|
|
1211
1243
|
configuration.profile, snapshot.abandonedReplayDigests ?? [], this.digest).messages
|
|
1212
|
-
: 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,
|
|
1213
1247
|
maxInlineImageBytes: configuration.limits.maxInlineImageBytes });
|
|
1214
1248
|
context.signal.throwIfAborted(); assertBinding(); return count;
|
|
1215
1249
|
},
|