@kingsoftcloud/agentkit-harness-core 0.0.13 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/approval-outcome.d.mts +7 -0
- package/dist/approval-outcome.mjs +8 -0
- package/dist/background-notification.mjs +5 -2
- package/dist/child-contract.d.mts +2 -0
- package/dist/child-control.d.mts +4 -0
- package/dist/child-control.mjs +15 -2
- package/dist/child-runtime.mjs +11 -1
- package/dist/configuration.d.mts +3 -0
- package/dist/configuration.mjs +13 -4
- package/dist/context-contributions.d.mts +2 -0
- package/dist/context-contributions.mjs +100 -48
- package/dist/context-planning.mjs +2 -2
- package/dist/contracts.d.mts +22 -5
- package/dist/contracts.mjs +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -0
- package/dist/kernel.d.mts +1 -0
- package/dist/kernel.mjs +52 -6
- package/dist/machine.mjs +44 -24
- package/dist/model-failure.d.mts +13 -1
- package/dist/model-failure.mjs +29 -2
- package/dist/model-json.mjs +21 -12
- package/dist/output-recovery.mjs +6 -2
- package/dist/response-continuation.d.mts +4 -0
- package/dist/response-continuation.mjs +9 -1
- package/dist/store.mjs +2 -1
- package/dist/tool-discovery.d.mts +13 -1
- package/dist/tool-discovery.mjs +67 -0
- package/dist/transitions.mjs +21 -2
- package/package.json +1 -1
- package/src/approval-outcome.mts +12 -0
- package/src/background-notification.mts +5 -2
- package/src/child-contract.mts +2 -0
- package/src/child-control.mts +16 -2
- package/src/child-runtime.mts +7 -1
- package/src/configuration.mts +17 -4
- package/src/context-contributions.mts +84 -38
- package/src/context-planning.mts +2 -2
- package/src/contracts.mts +19 -6
- package/src/index.mts +1 -0
- package/src/kernel.mts +47 -6
- package/src/machine.mts +46 -24
- package/src/model-failure.mts +40 -3
- package/src/model-json.mts +20 -9
- package/src/output-recovery.mts +6 -2
- package/src/response-continuation.mts +11 -1
- package/src/store.mts +2 -1
- package/src/tool-discovery.mts +63 -1
- package/src/transitions.mts +19 -2
package/dist/transitions.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { admitSteering } from './task-contract.mjs';
|
|
|
4
4
|
import { admitChildPromotion, unsettledChildren } from './child-runtime.mjs';
|
|
5
5
|
import { guidanceReason } from './guidance.mjs';
|
|
6
6
|
import { bindOperatorInput } from './anthropic-context.mjs';
|
|
7
|
+
import { APPROVAL_OUTCOME_POLICY, normalizeHostApprovalOutcome, approvalOutcomePauseReason } from './approval-outcome.mjs';
|
|
7
8
|
export function transition(snapshot, changes, facts = [], options = {}) {
|
|
8
9
|
invariant(!terminal(snapshot.phase), 'terminal_immutable');
|
|
9
10
|
const pendingGuidanceIds = changes.pendingGuidanceIds ?? snapshot.pendingGuidanceIds;
|
|
@@ -149,19 +150,37 @@ export function reduceCommand(snapshot, command, pending = null, bindings = {})
|
|
|
149
150
|
reason = 'not_paused';
|
|
150
151
|
else
|
|
151
152
|
changes = { phase: snapshot.resumePhase ?? 'preparing_context', resumePhase: null,
|
|
152
|
-
...(
|
|
153
|
+
...(snapshot.reason === 'output_budget_exhausted' && bindings.configuration?.outputRestartPolicy === 'per-response/v2'
|
|
154
|
+
? { reason: null, continuations: 0, outputRestarts: 0 } : {}),
|
|
155
|
+
...(bindings.configuration?.approvalOutcomePolicy === APPROVAL_OUTCOME_POLICY
|
|
156
|
+
&& ['approval_rejected', 'approval_cancelled', 'approval_unavailable'].includes(snapshot.reason ?? '') ? { reason: null } : {}),
|
|
157
|
+
...(['provider_unavailable', 'context_summary_unavailable', 'child_paused'].includes(snapshot.reason ?? '') ? { reason: null } : {}) };
|
|
153
158
|
break;
|
|
154
159
|
case 'submit_interaction': {
|
|
155
160
|
const pending = snapshot.pendingInteraction;
|
|
161
|
+
const hasOutcome = Object.hasOwn(command.payload, 'approvalOutcome');
|
|
162
|
+
const approvalOutcome = normalizeHostApprovalOutcome(command.payload.approvalOutcome);
|
|
156
163
|
if (snapshot.phase !== 'awaiting_interaction' || !pending || command.payload.interactionId !== pending.interactionId
|
|
157
164
|
|| command.payload.decision !== 'allow' && command.payload.decision !== 'deny')
|
|
158
165
|
reason = 'interaction_mismatch';
|
|
166
|
+
else if (hasOutcome && (bindings.configuration?.approvalOutcomePolicy !== APPROVAL_OUTCOME_POLICY
|
|
167
|
+
|| approvalOutcome !== command.payload.approvalOutcome
|
|
168
|
+
|| (approvalOutcome === 'allowed-once') !== (command.payload.decision === 'allow')))
|
|
169
|
+
reason = 'interaction_outcome_mismatch';
|
|
159
170
|
else {
|
|
160
171
|
changes = { phase: snapshot.childApproval ? snapshot.resumePhase ?? 'preparing_context' : 'executing_tools',
|
|
161
172
|
...(snapshot.childApproval ? { resumePhase: null, childLifecycleCursor: null } : {}), pendingInteraction: null,
|
|
162
173
|
interaction: pending.approvalPolicy === 'durable-preflight/v1' ? null : { interactionId: pending.hostInteractionId, callId: pending.callId, decision: command.payload.decision,
|
|
174
|
+
...(hasOutcome ? { approvalOutcome } : {}),
|
|
163
175
|
...(snapshot.planMode && typeof command.payload.feedback === 'string' ? { feedback: command.payload.feedback } : {}) } };
|
|
164
|
-
|
|
176
|
+
// One human answer pauses the interactive owner once. Its children
|
|
177
|
+
// receive the same denied decision after that owner is explicitly
|
|
178
|
+
// resumed; no second pause or implicit tool permission is introduced.
|
|
179
|
+
const pauseReason = hasOutcome && !bindings.configuration?.childOwnerBinding ? approvalOutcomePauseReason(approvalOutcome) : null;
|
|
180
|
+
if (pauseReason)
|
|
181
|
+
Object.assign(changes, { resumePhase: changes.phase, phase: 'paused', reason: pauseReason, outcome: null });
|
|
182
|
+
facts.push({ kind: 'approval.resolved', payload: { interactionId: pending.interactionId, callId: pending.callId, decision: command.payload.decision,
|
|
183
|
+
...(hasOutcome ? { approvalOutcome } : {}) } });
|
|
165
184
|
}
|
|
166
185
|
break;
|
|
167
186
|
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Host answers are not interchangeable. Unknown answers never grant access.
|
|
2
|
+
* Session permissions are a separate scoped Host authority, not an outcome a
|
|
3
|
+
* model or tool may claim in this vocabulary. */
|
|
4
|
+
export type HostApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';
|
|
5
|
+
export const APPROVAL_OUTCOME_POLICY = 'owner-outcome/v1' as const;
|
|
6
|
+
export function normalizeHostApprovalOutcome(value: unknown): HostApprovalOutcome {
|
|
7
|
+
return value === 'allowed-once' || value === 'rejected' || value === 'cancelled' ? value : 'unavailable';
|
|
8
|
+
}
|
|
9
|
+
export function approvalOutcomePauseReason(value: HostApprovalOutcome): string | null {
|
|
10
|
+
return value === 'rejected' ? 'approval_rejected' : value === 'cancelled' ? 'approval_cancelled'
|
|
11
|
+
: value === 'unavailable' ? 'approval_unavailable' : null;
|
|
12
|
+
}
|
|
@@ -5,6 +5,7 @@ import { backgroundCommandObservation, backgroundCommandRef } from './background
|
|
|
5
5
|
import { initialSnapshot, configure } from './configuration.mjs';
|
|
6
6
|
import { projectSessionHistory } from './history.mjs';
|
|
7
7
|
import { canonical, copy, invariant, NativeError, isNativeError, scopeKey } from './values.mjs';
|
|
8
|
+
import { responseScopedOutputRestarts } from './response-continuation.mjs';
|
|
8
9
|
|
|
9
10
|
export const BACKGROUND_NOTIFICATION_ADMISSION = 'agentkit.background-notification-admission/v1' as const;
|
|
10
11
|
type Digest = (value: unknown) => string;
|
|
@@ -161,11 +162,13 @@ export async function admitBackgroundNotification({ store, scope, sourceRunId, t
|
|
|
161
162
|
invariant((limits.maxModelCalls === null || limits.maxModelCalls > 0) && (limits.maxWallMs === null || limits.maxWallMs > 0),
|
|
162
163
|
'background_notification_budget_exhausted');
|
|
163
164
|
limits.maxRepairs = Math.max(0, limits.maxRepairs - used.repairs);
|
|
164
|
-
|
|
165
|
+
if (!responseScopedOutputRestarts(source.configuration))
|
|
166
|
+
limits.maxOutputRestarts = Math.max(0, limits.maxOutputRestarts - used.outputRestarts);
|
|
165
167
|
limits.maxRecoveryRetries = Math.max(0, limits.maxRecoveryRetries - used.recovery);
|
|
166
168
|
const contract = copy(head.taskContract ?? parent.configuration.contract);
|
|
167
169
|
const configuration = configure({ ...copy(source.configuration), contract, limits, inputMessages: null,
|
|
168
|
-
profile: { ...source.configuration.profile, maxContinuations:
|
|
170
|
+
profile: { ...source.configuration.profile, maxContinuations: responseScopedOutputRestarts(source.configuration)
|
|
171
|
+
? source.configuration.profile.maxContinuations : Math.max(0, source.configuration.profile.maxContinuations - used.continuations) } });
|
|
169
172
|
const snapshot = initialSnapshot({ scope: fixedScope, runId, sessionId: source.snapshot.sessionId,
|
|
170
173
|
turnId: runId, buildId: source.snapshot.buildId, parentRunId: head.runId, taskChainId: source.snapshot.taskChainId }, configuration, digest(configuration));
|
|
171
174
|
snapshot.backgroundNotification = { ...origin, admissionElapsedMs: elapsed };
|
package/src/child-contract.mts
CHANGED
|
@@ -40,6 +40,8 @@ export interface ChildTaskControlState {
|
|
|
40
40
|
childRunId: string; sessionId: string; role: string; phase: string;
|
|
41
41
|
goalRevision: number;
|
|
42
42
|
delivery: 'foreground' | 'background'; canPromote: boolean; canCancel: boolean; canSendInput: boolean;
|
|
43
|
+
/** Explicit Host control, not a model tool or implicit side effect of guidance. */
|
|
44
|
+
canResume?: boolean;
|
|
43
45
|
}
|
|
44
46
|
export interface ChildControlTarget {
|
|
45
47
|
scope: RunScope; runId: string; configurationDigest: string; parentOperationKey: string; parentToolCallId: string;
|
package/src/child-control.mts
CHANGED
|
@@ -4,16 +4,26 @@ import { terminal } from './contracts.mjs';
|
|
|
4
4
|
import { CHILD_OWNER_CONTRACT } from './child-contract.mjs';
|
|
5
5
|
import { canonical, copy, invariant } from './values.mjs';
|
|
6
6
|
|
|
7
|
+
/** An explicit control resumes a known pause, not an uncertain effect. This
|
|
8
|
+
* applies to output, provider and context pauses without changing their
|
|
9
|
+
* frozen policies, total budgets or required permission decisions. */
|
|
10
|
+
export function childResumeAllowed(snapshot: RunSnapshot): boolean {
|
|
11
|
+
return snapshot.phase === 'paused' && snapshot.pendingIntent === null
|
|
12
|
+
&& snapshot.toolReconciliation == null && snapshot.resumePhase !== 'awaiting_reconciliation'
|
|
13
|
+
&& !['effect_outcome_unknown', 'recovery_retry_exhausted', 'browser_session_unavailable'].includes(snapshot.reason ?? '');
|
|
14
|
+
}
|
|
15
|
+
|
|
7
16
|
export function childControlDelivery(parent: RunSnapshot, command: RunCommand, target: ChildControlTarget): ChildControlDelivery {
|
|
8
17
|
const send = command.kind === 'message_child', input = command.payload;
|
|
9
|
-
invariant(['message_child', 'cancel_child'].includes(command.kind)
|
|
18
|
+
invariant(['message_child', 'cancel_child', 'resume_child'].includes(command.kind)
|
|
10
19
|
&& typeof input.childRunId === 'string' && input.childRunId.trim() && input.childRunId.length <= 256
|
|
11
20
|
&& Object.keys(input).every(key => (send ? ['childRunId', 'text', 'expectedGoalRevision'] : ['childRunId']).includes(key))
|
|
12
21
|
&& (!send || typeof input.text === 'string' && input.text.trim() && input.text.length <= 32768
|
|
13
22
|
&& Number.isSafeInteger(input.expectedGoalRevision) && (input.expectedGoalRevision as number) >= 0), 'invalid_child_control');
|
|
14
23
|
return { target: copy(target), command: {
|
|
15
24
|
commandId: `child-control:${canonical([parent.scope, parent.runId, command.commandId])}`,
|
|
16
|
-
kind: send ? 'guide' : '
|
|
25
|
+
kind: send ? 'guide' : command.kind === 'resume_child' ? 'resume' : 'cancel',
|
|
26
|
+
payload: send ? { text: input.text!, expectedGoalRevision: input.expectedGoalRevision! } : {},
|
|
17
27
|
} };
|
|
18
28
|
}
|
|
19
29
|
|
|
@@ -52,6 +62,10 @@ export function validateChildControlDelivery(parent: StoredRun, child: StoredRun
|
|
|
52
62
|
'child_control_result_unknown');
|
|
53
63
|
const preempts = (record: StoredRun, kinds: string[]) => record.commands.some(row => !row.consumed && kinds.includes(row.command.kind));
|
|
54
64
|
invariant(!preempts(parent, ['cancel', 'policy_revoked', 'steer']), 'parent_control_preempts_child_control');
|
|
65
|
+
if (command.kind === 'resume_child') {
|
|
66
|
+
invariant(childResumeAllowed(c)
|
|
67
|
+
&& !preempts(child, ['cancel', 'policy_revoked', 'steer', 'resume']), 'child_control_unavailable');
|
|
68
|
+
}
|
|
55
69
|
if (command.kind === 'message_child') {
|
|
56
70
|
invariant(!preempts(child, ['cancel', 'policy_revoked', 'steer']), 'child_control_preempts_input');
|
|
57
71
|
invariant(command.payload.expectedGoalRevision === c.goalRevision, 'stale_child_goal_revision');
|
package/src/child-runtime.mts
CHANGED
|
@@ -132,7 +132,7 @@ export function reduceChildLifecycle(snapshot: RunSnapshot, config: RunConfigura
|
|
|
132
132
|
const owned = request.reservations.find(item => item.childRunId === child.runId);
|
|
133
133
|
invariant(owned && owned.parentOperationKey === child.operationKey && owned.parentToolCallId === child.callId
|
|
134
134
|
&& child.reservedModelCalls === owned.maxModelCalls && child.reservedToolCalls === owned.maxToolCalls
|
|
135
|
-
&& ['prepared', 'running', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
|
|
135
|
+
&& ['prepared', 'running', 'paused', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
|
|
136
136
|
&& (settled.includes(child.runId) ? ['completed', 'failed', 'canceled'].includes(child.state)
|
|
137
137
|
: !['completed', 'failed', 'canceled'].includes(child.state))
|
|
138
138
|
&& child.usage.modelCalls <= owned.maxModelCalls && child.usage.toolCalls <= owned.maxToolCalls
|
|
@@ -152,6 +152,12 @@ export function reduceChildLifecycle(snapshot: RunSnapshot, config: RunConfigura
|
|
|
152
152
|
updated.pendingInteraction = { interactionId: `${request.operationKey}:approval`, hostInteractionId: `native-child-${digest(approval)}`,
|
|
153
153
|
callId: approval.toolCall.callId, operationKey: request.operationKey };
|
|
154
154
|
updated.interaction = null;
|
|
155
|
+
} else if (!result.errorCode && request.action === 'wait' && result.children?.some(child => child.state === 'paused'
|
|
156
|
+
&& pending.includes(child.runId) && (!request.waitForChildRunIds || request.waitForChildRunIds.includes(child.runId)))) {
|
|
157
|
+
// A joined child can still own valid results and an unspent reservation.
|
|
158
|
+
// Preserve that original run until an explicit control resumes or cancels
|
|
159
|
+
// it. Background polls do not block the parent's independent work.
|
|
160
|
+
updated.resumePhase = updated.phase; updated.phase = 'paused'; updated.reason = 'child_paused'; updated.outcome = null;
|
|
155
161
|
} else if (result.errorCode || !observationOnly && request.action !== 'poll'
|
|
156
162
|
&& pending.some(id => !request.waitForChildRunIds || request.waitForChildRunIds.includes(id))) {
|
|
157
163
|
updated.phase = 'finalizing'; updated.candidate = null; updated.verification = null;
|
package/src/configuration.mts
CHANGED
|
@@ -36,9 +36,12 @@ export interface ConfigurationInput {
|
|
|
36
36
|
inputPolicy?: RunConfiguration['inputPolicy'];
|
|
37
37
|
sourceReadPolicy?: RunConfiguration['sourceReadPolicy'];
|
|
38
38
|
outputRecoveryPolicy?: RunConfiguration['outputRecoveryPolicy'];
|
|
39
|
+
outputRestartPolicy?: RunConfiguration['outputRestartPolicy'];
|
|
40
|
+
approvalOutcomePolicy?: RunConfiguration['approvalOutcomePolicy'];
|
|
39
41
|
providerRecoveryPolicy?: RunConfiguration['providerRecoveryPolicy'];
|
|
40
42
|
toolErrorRecoveryPolicy?: RunConfiguration['toolErrorRecoveryPolicy'];
|
|
41
43
|
toolDiscoveryPolicy?: RunConfiguration['toolDiscoveryPolicy'];
|
|
44
|
+
toolAdmissionPolicy?: RunConfiguration['toolAdmissionPolicy'];
|
|
42
45
|
todoPolicy?: RunConfiguration['todoPolicy'];
|
|
43
46
|
toolExecutionPolicy?: RunConfiguration['toolExecutionPolicy'];
|
|
44
47
|
childTaskPolicy?: RunConfiguration['childTaskPolicy'];
|
|
@@ -96,9 +99,12 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
96
99
|
...(input.inputPolicy === undefined ? {} : { inputPolicy: input.inputPolicy }),
|
|
97
100
|
...(input.sourceReadPolicy === undefined ? {} : { sourceReadPolicy: input.sourceReadPolicy }),
|
|
98
101
|
...(input.outputRecoveryPolicy === undefined ? {} : { outputRecoveryPolicy: input.outputRecoveryPolicy }),
|
|
102
|
+
...(input.outputRestartPolicy === undefined ? {} : { outputRestartPolicy: input.outputRestartPolicy }),
|
|
103
|
+
...(input.approvalOutcomePolicy === undefined ? {} : { approvalOutcomePolicy: input.approvalOutcomePolicy }),
|
|
99
104
|
...(input.providerRecoveryPolicy === undefined ? {} : { providerRecoveryPolicy: input.providerRecoveryPolicy }),
|
|
100
105
|
...(input.toolErrorRecoveryPolicy === undefined ? {} : { toolErrorRecoveryPolicy: input.toolErrorRecoveryPolicy }),
|
|
101
106
|
...(input.toolDiscoveryPolicy === undefined ? {} : { toolDiscoveryPolicy: input.toolDiscoveryPolicy }),
|
|
107
|
+
...(input.toolAdmissionPolicy === undefined ? {} : { toolAdmissionPolicy: input.toolAdmissionPolicy }),
|
|
102
108
|
...(input.todoPolicy === undefined ? {} : { todoPolicy: input.todoPolicy }),
|
|
103
109
|
...(input.toolExecutionPolicy === undefined ? {} : { toolExecutionPolicy: input.toolExecutionPolicy }),
|
|
104
110
|
...(input.childTaskPolicy === undefined ? {} : { childTaskPolicy: input.childTaskPolicy }),
|
|
@@ -106,7 +112,9 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
106
112
|
...(input.planModePolicy === undefined ? {} : { planModePolicy: input.planModePolicy }),
|
|
107
113
|
...(input.planModeInitialActive === undefined ? {} : { planModeInitialActive: input.planModeInitialActive }),
|
|
108
114
|
...(input.childPlanPolicy === undefined ? {} : { childPlanPolicy: input.childPlanPolicy }),
|
|
109
|
-
...(input.toolErrorRecoveryModelCalls === undefined
|
|
115
|
+
...(input.toolErrorRecoveryModelCalls === undefined
|
|
116
|
+
? input.toolErrorRecoveryPolicy === 'diagnose-before-repeat/v2' ? { toolErrorRecoveryModelCalls: 10 } : {}
|
|
117
|
+
: { toolErrorRecoveryModelCalls: input.toolErrorRecoveryModelCalls }),
|
|
110
118
|
...(input.deliveryReviewPolicy === undefined ? {} : { deliveryReviewPolicy: input.deliveryReviewPolicy === null ? null : normalizeDeliveryReviewPolicy(input.deliveryReviewPolicy) }),
|
|
111
119
|
...(input.hostRecoveryBinding === undefined ? {} : { hostRecoveryBinding: input.hostRecoveryBinding }),
|
|
112
120
|
...(input.backgroundSessionBindingDigest === undefined ? {} : { backgroundSessionBindingDigest: input.backgroundSessionBindingDigest }),
|
|
@@ -151,10 +159,15 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
151
159
|
&& typeof config.hostRecoveryBinding === 'object' && !Array.isArray(config.hostRecoveryBinding), 'invalid_host_recovery_binding');
|
|
152
160
|
invariant(config.guidancePolicy == null || config.guidancePolicy === 'boundary-guide/v1', 'invalid_guidance_policy');
|
|
153
161
|
invariant(config.inputPolicy === undefined || config.inputPolicy === 'before-first-model/v1', 'invalid_input_policy');
|
|
154
|
-
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
162
|
+
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
163
|
+
invariant(config.outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(config.outputRestartPolicy)
|
|
164
|
+
&& ['response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy ?? ''), 'invalid_output_restart_policy');
|
|
165
|
+
invariant(config.approvalOutcomePolicy === undefined || config.approvalOutcomePolicy === 'owner-outcome/v1', 'invalid_approval_outcome_policy');
|
|
155
166
|
invariant(config.providerRecoveryPolicy == null || config.providerRecoveryPolicy === 'provider-recovery/v2', 'invalid_provider_recovery_policy');
|
|
156
167
|
invariant(config.toolExecutionPolicy === undefined || config.toolExecutionPolicy === 'owner-execution/v1', 'invalid_tool_execution_policy');
|
|
157
|
-
invariant(config.toolErrorRecoveryPolicy == null ||
|
|
168
|
+
invariant(config.toolErrorRecoveryPolicy == null || ['diagnose-before-repeat/v1', 'diagnose-before-repeat/v2'].includes(config.toolErrorRecoveryPolicy), 'invalid_tool_error_recovery_policy');
|
|
169
|
+
invariant(config.toolErrorRecoveryPolicy !== 'diagnose-before-repeat/v2' || config.toolErrorRecoveryModelCalls !== undefined,
|
|
170
|
+
'missing_tool_error_recovery_model_calls');
|
|
158
171
|
invariant(config.toolErrorRecoveryModelCalls == null || Number.isSafeInteger(config.toolErrorRecoveryModelCalls)
|
|
159
172
|
&& config.toolErrorRecoveryModelCalls >= 1 && config.toolErrorRecoveryModelCalls <= 10, 'invalid_tool_error_recovery_model_calls');
|
|
160
173
|
invariant(config.deliveryReviewPolicy == null || !config.tools.some(tool => tool.name === REVIEW_SUBMISSION_TOOL), 'reserved_delivery_review_tool');
|
|
@@ -236,7 +249,7 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
236
249
|
const policy = profile.providerCompatibilityPolicy;
|
|
237
250
|
invariant(policy !== null && typeof policy === 'object' && !Array.isArray(policy)
|
|
238
251
|
&& Object.keys(policy).every(key => ['contract', 'rule'].includes(key))
|
|
239
|
-
&& ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3'].includes(policy.contract)
|
|
252
|
+
&& ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)
|
|
240
253
|
&& ['auto', 'permissive', 'openai', 'strict-openai', 'cerebras', 'groq', 'deepseek',
|
|
241
254
|
'zai', 'kspmas-gateway', 'moonshot', 'mimo'].includes(policy.rule), 'invalid_provider_compatibility_policy');
|
|
242
255
|
}
|
|
@@ -1,9 +1,23 @@
|
|
|
1
1
|
import type { ContextPort, ContextSourceDefinition, Message, ObjectValue, PortContext, RunConfiguration, RunSnapshot } from './contracts.mjs';
|
|
2
|
-
import { canonical, copy, invariant, NativeError } from './values.mjs';
|
|
2
|
+
import { canonical, copy, invariant, isNativeError, NativeError } from './values.mjs';
|
|
3
3
|
|
|
4
4
|
export const CONTEXT_SOURCE_CONTRACT = 'agentkit.native-context-source/v1';
|
|
5
5
|
export const CONTEXT_CONTRIBUTION_CONTRACT = 'agentkit.native-context-contribution/v1';
|
|
6
6
|
|
|
7
|
+
class ContextSourceUnavailable extends NativeError {
|
|
8
|
+
constructor(readonly sourceId: string, readonly bindingDigest: string, readonly timeoutRetries: number) {
|
|
9
|
+
super('context_source_unavailable');
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Only exhaustion produced by this collector can authorize a recoverable pause. */
|
|
13
|
+
export function contextSourceUnavailable(error: unknown, config: RunConfiguration): ObjectValue | null {
|
|
14
|
+
if (!(error instanceof ContextSourceUnavailable)) return null;
|
|
15
|
+
const source = config.contextSources.find(source => source.sourceId === error.sourceId
|
|
16
|
+
&& source.bindingDigest === error.bindingDigest && source.required
|
|
17
|
+
&& source.timeoutRecovery?.maxRetries === error.timeoutRetries);
|
|
18
|
+
return source ? { sourceId: source.sourceId, bindingDigest: source.bindingDigest, timeoutRetries: error.timeoutRetries } : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
7
21
|
export function validateContextSource(source: ContextSourceDefinition, timeoutMs: number): void {
|
|
8
22
|
invariant(source.contract === CONTEXT_SOURCE_CONTRACT && typeof source.sourceId === 'string' && !!source.sourceId.trim()
|
|
9
23
|
&& typeof source.bindingDigest === 'string' && !!source.bindingDigest.trim()
|
|
@@ -14,6 +28,24 @@ export function validateContextSource(source: ContextSourceDefinition, timeoutMs
|
|
|
14
28
|
'invalid_context_source');
|
|
15
29
|
invariant(source.instructionPolicy === undefined || source.instructionPolicy === 'current-files/v1' && source.required,
|
|
16
30
|
'invalid_context_instruction_source');
|
|
31
|
+
const recovery = source.timeoutRecovery;
|
|
32
|
+
invariant(recovery === undefined || recovery && !Array.isArray(recovery)
|
|
33
|
+
&& Object.keys(recovery).sort().join(',') === 'contract,maxRetries,retryDelayMs' && recovery.contract === 'context-source-timeout/v1'
|
|
34
|
+
&& Number.isSafeInteger(recovery.maxRetries) && recovery.maxRetries >= 0 && recovery.maxRetries <= 3
|
|
35
|
+
&& Number.isSafeInteger(recovery.retryDelayMs) && recovery.retryDelayMs >= 0 && recovery.retryDelayMs <= 60000
|
|
36
|
+
&& source.timeoutMs * (recovery.maxRetries + 1) + recovery.retryDelayMs * recovery.maxRetries < timeoutMs,
|
|
37
|
+
'invalid_context_source_timeout_recovery');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function retryDelay(ms: number, signal: AbortSignal): Promise<void> {
|
|
41
|
+
signal.throwIfAborted();
|
|
42
|
+
await new Promise<void>((resolve, reject) => {
|
|
43
|
+
const done = () => { signal.removeEventListener('abort', canceled); resolve(); };
|
|
44
|
+
const timer = setTimeout(done, ms);
|
|
45
|
+
const canceled = () => { clearTimeout(timer); signal.removeEventListener('abort', canceled); reject(signal.reason); };
|
|
46
|
+
signal.addEventListener('abort', canceled, { once: true });
|
|
47
|
+
if (signal.aborted) canceled();
|
|
48
|
+
});
|
|
17
49
|
}
|
|
18
50
|
|
|
19
51
|
export function contextContributionMessage(source: ContextSourceDefinition, item: ObjectValue): Message {
|
|
@@ -46,45 +78,59 @@ export async function collectContextContributions(context: PortContext, snapshot
|
|
|
46
78
|
port: ContextPort, count: (messages: Message[]) => Promise<number>): Promise<{ messages: Message[]; diagnostics: ObjectValue[] }> {
|
|
47
79
|
const messages: Message[] = [], diagnostics: ObjectValue[] = [];
|
|
48
80
|
for (const source of [...config.contextSources].sort((a, b) => b.priority - a.priority)) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
&&
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
81
|
+
for (let attempt = 0; ; attempt++) {
|
|
82
|
+
context.signal.throwIfAborted();
|
|
83
|
+
const abort = new AbortController(), signal = AbortSignal.any([context.signal, abort.signal]);
|
|
84
|
+
let listener: () => void = () => {};
|
|
85
|
+
const timer = setTimeout(() => abort.abort(new NativeError('context_source_timeout')), source.timeoutMs);
|
|
86
|
+
const deadline = Date.now() + source.timeoutMs;
|
|
87
|
+
const canceled = new Promise<never>((_, reject) => {
|
|
88
|
+
listener = () => reject(signal.reason); signal.addEventListener('abort', listener, { once: true });
|
|
89
|
+
if (signal.aborted) listener();
|
|
90
|
+
});
|
|
91
|
+
try {
|
|
92
|
+
invariant(port.readSource, 'context_source_port_missing');
|
|
93
|
+
const result = await Promise.race([port.readSource({ ...context, signal, source: copy(source), snapshot: copy(snapshot),
|
|
94
|
+
configuration: copy(config), remainingTokens: Math.min(source.maxTokens, config.profile.contextWindow - config.profile.maxOutputTokens) }), canceled]);
|
|
95
|
+
signal.throwIfAborted(); invariant(Date.now() < deadline, 'context_source_timeout');
|
|
96
|
+
invariant(result && Array.isArray(result.items) && result.items.length <= 64
|
|
97
|
+
&& new TextEncoder().encode(canonical(result)).length <= 4 * 1024 * 1024, 'context_source_result_invalid');
|
|
98
|
+
invariant(!source.instructionPolicy || result.items.length > 0, 'context_instruction_source_snapshot_missing');
|
|
99
|
+
const admitted: Message[] = [];
|
|
100
|
+
for (const item of result.items) {
|
|
101
|
+
invariant(item && typeof item === 'object' && !Array.isArray(item), 'context_source_result_invalid');
|
|
102
|
+
const candidate = [...admitted, contextContributionMessage(source, item)];
|
|
103
|
+
if (new TextEncoder().encode(canonical(candidate)).length > source.maxBytes) {
|
|
104
|
+
invariant(!source.instructionPolicy, 'context_instruction_source_byte_budget_exceeded'); continue;
|
|
105
|
+
}
|
|
106
|
+
const tokens = await Promise.race([count(copy(candidate)), canceled]); signal.throwIfAborted();
|
|
107
|
+
invariant(Date.now() < deadline, 'context_source_timeout');
|
|
108
|
+
invariant(Number.isSafeInteger(tokens) && tokens >= 0, 'context_token_count_invalid');
|
|
109
|
+
invariant(!source.instructionPolicy || tokens <= source.maxTokens, 'context_instruction_source_token_budget_exceeded');
|
|
110
|
+
if (tokens <= source.maxTokens) admitted.push(candidate.at(-1)!);
|
|
72
111
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
112
|
+
messages.push(...admitted);
|
|
113
|
+
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: 'ok',
|
|
114
|
+
proposed: result.items.length, admitted: admitted.length,
|
|
115
|
+
...(source.timeoutRecovery ? { timeoutRetries: attempt } : {}) });
|
|
116
|
+
break;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
context.signal.throwIfAborted();
|
|
119
|
+
if (isNativeError(error) && error.code === 'context_source_timeout' && source.timeoutRecovery) {
|
|
120
|
+
abort.abort(error);
|
|
121
|
+
if (attempt < source.timeoutRecovery.maxRetries) {
|
|
122
|
+
await retryDelay(source.timeoutRecovery.retryDelayMs, context.signal);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (source.required) throw new ContextSourceUnavailable(source.sourceId, source.bindingDigest, attempt);
|
|
126
|
+
}
|
|
127
|
+
if (source.required) throw error;
|
|
128
|
+
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: 'skipped',
|
|
129
|
+
...(source.timeoutRecovery ? { timeoutRetries: attempt } : {}) });
|
|
130
|
+
break;
|
|
131
|
+
} finally {
|
|
132
|
+
clearTimeout(timer); signal.removeEventListener('abort', listener); abort.abort();
|
|
78
133
|
}
|
|
79
|
-
messages.push(...admitted);
|
|
80
|
-
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: 'ok',
|
|
81
|
-
proposed: result.items.length, admitted: admitted.length });
|
|
82
|
-
} catch (error) {
|
|
83
|
-
context.signal.throwIfAborted();
|
|
84
|
-
if (source.required) throw error;
|
|
85
|
-
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: 'skipped' });
|
|
86
|
-
} finally {
|
|
87
|
-
clearTimeout(timer); signal.removeEventListener('abort', listener); abort.abort();
|
|
88
134
|
}
|
|
89
135
|
}
|
|
90
136
|
return { messages, diagnostics };
|
package/src/context-planning.mts
CHANGED
|
@@ -11,7 +11,7 @@ import { sourceWorkingSetGroup } from './source-working-set-group.mjs';
|
|
|
11
11
|
import { sourceReuseProjector } from './context-source-reuse.mjs';
|
|
12
12
|
import { defaultToolPruningThreshold, projectOldToolResults, toolPruningIdleElapsed } from './context-microcompact.mjs';
|
|
13
13
|
import { summaryContinuityInstructions, validSummaryContinuity } from './summary-continuity.mjs';
|
|
14
|
-
import { responseContinuationPairs } from './response-continuation.mjs';
|
|
14
|
+
import { responseBoundaryRecovery, responseContinuationPairs } from './response-continuation.mjs';
|
|
15
15
|
import { verificationModelView } from './model-surface.mjs';
|
|
16
16
|
import { currentInstructionContribution } from './context-contributions.mjs';
|
|
17
17
|
|
|
@@ -118,7 +118,7 @@ function groupsOf(messages: Message[], indexes: number[]): number[][] {
|
|
|
118
118
|
}
|
|
119
119
|
function mandatoryIndexes(snapshot: RunSnapshot, groups: number[][], config: RunConfiguration): Set<number> {
|
|
120
120
|
const mandatory = new Set<number>(), messages = snapshot.messages;
|
|
121
|
-
if (config
|
|
121
|
+
if (responseBoundaryRecovery(config))
|
|
122
122
|
for (const pair of responseContinuationPairs(messages)) for (const index of pair) mandatory.add(index);
|
|
123
123
|
// The next inference must observe the just-completed batch, but that must
|
|
124
124
|
// not exempt all older history from its soft budget on every tool turn.
|
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. */
|
|
@@ -257,6 +257,8 @@ export interface ContextSourceDefinition {
|
|
|
257
257
|
priority: number; timeoutMs: number; required: boolean; maxTokens: number; maxBytes: number;
|
|
258
258
|
/** Current file guidance is refreshed before inference, never substituted by a historical summary. */
|
|
259
259
|
instructionPolicy?: 'current-files/v1';
|
|
260
|
+
/** Retry only a timed-out read; required sources pause after exhaustion. Absence keeps the frozen legacy behavior. */
|
|
261
|
+
timeoutRecovery?: { contract: 'context-source-timeout/v1'; maxRetries: number; retryDelayMs: number };
|
|
260
262
|
}
|
|
261
263
|
/** A frozen transcript import, never a parent Run or an execution checkpoint. */
|
|
262
264
|
export interface ConversationSeed {
|
|
@@ -288,6 +290,8 @@ export interface RunConfiguration {
|
|
|
288
290
|
planModeInitialActive?: boolean;
|
|
289
291
|
childPlanPolicy?: 'inherit-plan/v1';
|
|
290
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';
|
|
291
295
|
artifactPolicy?: 'runtime-artifacts/v1' | null;
|
|
292
296
|
/** The execution owner must prepare Host context before the first inference. */
|
|
293
297
|
inputPolicy?: 'before-first-model/v1';
|
|
@@ -305,10 +309,19 @@ export interface RunConfiguration {
|
|
|
305
309
|
stopHookContinuationLimit: number; delegationDepth: number;
|
|
306
310
|
modelRecoveryPolicy: 'manual' | 'pure-inference/v1';
|
|
307
311
|
guidancePolicy?: 'boundary-guide/v1' | null;
|
|
308
|
-
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | null;
|
|
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';
|
|
309
320
|
/** v2 counts consecutive provider failures and pauses (resumable) instead of failing when they run out. */
|
|
310
321
|
providerRecoveryPolicy?: 'provider-recovery/v2' | null;
|
|
311
|
-
|
|
322
|
+
/** v2 admits a ten-inference diagnostic allowance unless explicitly configured.
|
|
323
|
+
* Frozen v1 configurations retain their original unbounded/default semantics. */
|
|
324
|
+
toolErrorRecoveryPolicy?: 'diagnose-before-repeat/v1' | 'diagnose-before-repeat/v2' | null;
|
|
312
325
|
toolErrorRecoveryModelCalls?: number | null;
|
|
313
326
|
deliveryReviewPolicy?: DeliveryReviewPolicy | null;
|
|
314
327
|
/** Opaque, Host-owned recovery locator. The core never interprets it as authority. */
|
|
@@ -410,7 +423,7 @@ export interface CompletionCandidate {
|
|
|
410
423
|
}
|
|
411
424
|
export interface ChildState {
|
|
412
425
|
runId: string; sessionId: string; operationKey: string; callId: string;
|
|
413
|
-
state: 'prepared' | 'running' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
|
|
426
|
+
state: 'prepared' | 'running' | 'paused' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
|
|
414
427
|
reservedModelCalls: number | null; reservedToolCalls: number | null; usage: Usage;
|
|
415
428
|
notified: boolean; metadata: ObjectValue;
|
|
416
429
|
}
|
|
@@ -520,7 +533,7 @@ export type EffectKind = 'workspace' | 'model' | 'tool' | 'verify' | 'context' |
|
|
|
520
533
|
export interface EffectIntent { operationKey: string; kind: EffectKind; payload: ObjectValue; status: 'prepared' | 'running'; claimedAtMs?: number; claimedFence?: number }
|
|
521
534
|
export interface EffectReceipt { operationKey: string; status: 'committed' | 'failed' | 'uncertain' | 'not_dispatched'; result: ObjectValue }
|
|
522
535
|
export type CommandKind = 'cancel' | 'policy_revoked' | 'pause' | 'resume' | 'submit_interaction'
|
|
523
|
-
| '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';
|
|
524
537
|
export interface RunCommand { commandId: string; kind: CommandKind; payload: ObjectValue }
|
|
525
538
|
export interface CommandReceipt { commandId: string; status: 'accepted' | 'duplicate' | 'rejected'; reason: string | null }
|
|
526
539
|
export interface Lease { owner: string; fence: number; expiresAt: number }
|
|
@@ -729,5 +742,5 @@ export const terminal = (phase: Phase): boolean => ['completed', 'failed', 'canc
|
|
|
729
742
|
export const emptyUsage = (): Usage => ({ inputTokens: 0, outputTokens: 0, modelCalls: 0, toolCalls: 0, cost: 0 });
|
|
730
743
|
export const commandPriority: Record<CommandKind, number> = {
|
|
731
744
|
cancel: 100, policy_revoked: 95, submit_interaction: 90, cancel_child: 85,
|
|
732
|
-
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,
|
|
733
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';
|