@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
|
@@ -0,0 +1,7 @@
|
|
|
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 declare const APPROVAL_OUTCOME_POLICY: "owner-outcome/v1";
|
|
6
|
+
export declare function normalizeHostApprovalOutcome(value: unknown): HostApprovalOutcome;
|
|
7
|
+
export declare function approvalOutcomePauseReason(value: HostApprovalOutcome): string | null;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const APPROVAL_OUTCOME_POLICY = 'owner-outcome/v1';
|
|
2
|
+
export function normalizeHostApprovalOutcome(value) {
|
|
3
|
+
return value === 'allowed-once' || value === 'rejected' || value === 'cancelled' ? value : 'unavailable';
|
|
4
|
+
}
|
|
5
|
+
export function approvalOutcomePauseReason(value) {
|
|
6
|
+
return value === 'rejected' ? 'approval_rejected' : value === 'cancelled' ? 'approval_cancelled'
|
|
7
|
+
: value === 'unavailable' ? 'approval_unavailable' : null;
|
|
8
|
+
}
|
|
@@ -3,6 +3,7 @@ import { backgroundCommandObservation, backgroundCommandRef } from './background
|
|
|
3
3
|
import { initialSnapshot, configure } from './configuration.mjs';
|
|
4
4
|
import { projectSessionHistory } from './history.mjs';
|
|
5
5
|
import { canonical, copy, invariant, NativeError, isNativeError, scopeKey } from './values.mjs';
|
|
6
|
+
import { responseScopedOutputRestarts } from './response-continuation.mjs';
|
|
6
7
|
export const BACKGROUND_NOTIFICATION_ADMISSION = 'agentkit.background-notification-admission/v1';
|
|
7
8
|
function assertSettled(record) {
|
|
8
9
|
const snapshot = record.snapshot;
|
|
@@ -162,11 +163,13 @@ export async function admitBackgroundNotification({ store, scope, sourceRunId, t
|
|
|
162
163
|
limits.maxWallMs -= used.wall + elapsed;
|
|
163
164
|
invariant((limits.maxModelCalls === null || limits.maxModelCalls > 0) && (limits.maxWallMs === null || limits.maxWallMs > 0), 'background_notification_budget_exhausted');
|
|
164
165
|
limits.maxRepairs = Math.max(0, limits.maxRepairs - used.repairs);
|
|
165
|
-
|
|
166
|
+
if (!responseScopedOutputRestarts(source.configuration))
|
|
167
|
+
limits.maxOutputRestarts = Math.max(0, limits.maxOutputRestarts - used.outputRestarts);
|
|
166
168
|
limits.maxRecoveryRetries = Math.max(0, limits.maxRecoveryRetries - used.recovery);
|
|
167
169
|
const contract = copy(head.taskContract ?? parent.configuration.contract);
|
|
168
170
|
const configuration = configure({ ...copy(source.configuration), contract, limits, inputMessages: null,
|
|
169
|
-
profile: { ...source.configuration.profile, maxContinuations:
|
|
171
|
+
profile: { ...source.configuration.profile, maxContinuations: responseScopedOutputRestarts(source.configuration)
|
|
172
|
+
? source.configuration.profile.maxContinuations : Math.max(0, source.configuration.profile.maxContinuations - used.continuations) } });
|
|
170
173
|
const snapshot = initialSnapshot({ scope: fixedScope, runId, sessionId: source.snapshot.sessionId,
|
|
171
174
|
turnId: runId, buildId: source.snapshot.buildId, parentRunId: head.runId, taskChainId: source.snapshot.taskChainId }, configuration, digest(configuration));
|
|
172
175
|
snapshot.backgroundNotification = { ...origin, admissionElapsedMs: elapsed };
|
|
@@ -67,6 +67,8 @@ export interface ChildTaskControlState {
|
|
|
67
67
|
canPromote: boolean;
|
|
68
68
|
canCancel: boolean;
|
|
69
69
|
canSendInput: boolean;
|
|
70
|
+
/** Explicit Host control, not a model tool or implicit side effect of guidance. */
|
|
71
|
+
canResume?: boolean;
|
|
70
72
|
}
|
|
71
73
|
export interface ChildControlTarget {
|
|
72
74
|
scope: RunScope;
|
package/dist/child-control.d.mts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { ChildControlDelivery, ChildControlTarget } from './child-contract.mjs';
|
|
2
2
|
import type { RunCommand, RunSnapshot, StoredRun } from './contracts.mjs';
|
|
3
|
+
/** An explicit control resumes a known pause, not an uncertain effect. This
|
|
4
|
+
* applies to output, provider and context pauses without changing their
|
|
5
|
+
* frozen policies, total budgets or required permission decisions. */
|
|
6
|
+
export declare function childResumeAllowed(snapshot: RunSnapshot): boolean;
|
|
3
7
|
export declare function childControlDelivery(parent: RunSnapshot, command: RunCommand, target: ChildControlTarget): ChildControlDelivery;
|
|
4
8
|
/** Runs under the Store's multi-record transaction, before either ledger changes. */
|
|
5
9
|
export declare function validateChildControlDelivery(parent: StoredRun, child: StoredRun, command: RunCommand, delivery: ChildControlDelivery): void;
|
package/dist/child-control.mjs
CHANGED
|
@@ -1,16 +1,25 @@
|
|
|
1
1
|
import { terminal } from './contracts.mjs';
|
|
2
2
|
import { CHILD_OWNER_CONTRACT } from './child-contract.mjs';
|
|
3
3
|
import { canonical, copy, invariant } from './values.mjs';
|
|
4
|
+
/** An explicit control resumes a known pause, not an uncertain effect. This
|
|
5
|
+
* applies to output, provider and context pauses without changing their
|
|
6
|
+
* frozen policies, total budgets or required permission decisions. */
|
|
7
|
+
export function childResumeAllowed(snapshot) {
|
|
8
|
+
return snapshot.phase === 'paused' && snapshot.pendingIntent === null
|
|
9
|
+
&& snapshot.toolReconciliation == null && snapshot.resumePhase !== 'awaiting_reconciliation'
|
|
10
|
+
&& !['effect_outcome_unknown', 'recovery_retry_exhausted', 'browser_session_unavailable'].includes(snapshot.reason ?? '');
|
|
11
|
+
}
|
|
4
12
|
export function childControlDelivery(parent, command, target) {
|
|
5
13
|
const send = command.kind === 'message_child', input = command.payload;
|
|
6
|
-
invariant(['message_child', 'cancel_child'].includes(command.kind)
|
|
14
|
+
invariant(['message_child', 'cancel_child', 'resume_child'].includes(command.kind)
|
|
7
15
|
&& typeof input.childRunId === 'string' && input.childRunId.trim() && input.childRunId.length <= 256
|
|
8
16
|
&& Object.keys(input).every(key => (send ? ['childRunId', 'text', 'expectedGoalRevision'] : ['childRunId']).includes(key))
|
|
9
17
|
&& (!send || typeof input.text === 'string' && input.text.trim() && input.text.length <= 32768
|
|
10
18
|
&& Number.isSafeInteger(input.expectedGoalRevision) && input.expectedGoalRevision >= 0), 'invalid_child_control');
|
|
11
19
|
return { target: copy(target), command: {
|
|
12
20
|
commandId: `child-control:${canonical([parent.scope, parent.runId, command.commandId])}`,
|
|
13
|
-
kind: send ? 'guide' : '
|
|
21
|
+
kind: send ? 'guide' : command.kind === 'resume_child' ? 'resume' : 'cancel',
|
|
22
|
+
payload: send ? { text: input.text, expectedGoalRevision: input.expectedGoalRevision } : {},
|
|
14
23
|
} };
|
|
15
24
|
}
|
|
16
25
|
/** Runs under the Store's multi-record transaction, before either ledger changes. */
|
|
@@ -46,6 +55,10 @@ export function validateChildControlDelivery(parent, child, command, delivery) {
|
|
|
46
55
|
&& !(receipt.result.retryScheduled === true && ['safe-read/v1', 'workspace-observation/v1'].includes(String(receipt.result.recoveryPolicy)))), 'child_control_result_unknown');
|
|
47
56
|
const preempts = (record, kinds) => record.commands.some(row => !row.consumed && kinds.includes(row.command.kind));
|
|
48
57
|
invariant(!preempts(parent, ['cancel', 'policy_revoked', 'steer']), 'parent_control_preempts_child_control');
|
|
58
|
+
if (command.kind === 'resume_child') {
|
|
59
|
+
invariant(childResumeAllowed(c)
|
|
60
|
+
&& !preempts(child, ['cancel', 'policy_revoked', 'steer', 'resume']), 'child_control_unavailable');
|
|
61
|
+
}
|
|
49
62
|
if (command.kind === 'message_child') {
|
|
50
63
|
invariant(!preempts(child, ['cancel', 'policy_revoked', 'steer']), 'child_control_preempts_input');
|
|
51
64
|
invariant(command.payload.expectedGoalRevision === c.goalRevision, 'stale_child_goal_revision');
|
package/dist/child-runtime.mjs
CHANGED
|
@@ -138,7 +138,7 @@ export function reduceChildLifecycle(snapshot, config, request, result, digest,
|
|
|
138
138
|
const owned = request.reservations.find(item => item.childRunId === child.runId);
|
|
139
139
|
invariant(owned && owned.parentOperationKey === child.operationKey && owned.parentToolCallId === child.callId
|
|
140
140
|
&& child.reservedModelCalls === owned.maxModelCalls && child.reservedToolCalls === owned.maxToolCalls
|
|
141
|
-
&& ['prepared', 'running', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
|
|
141
|
+
&& ['prepared', 'running', 'paused', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
|
|
142
142
|
&& (settled.includes(child.runId) ? ['completed', 'failed', 'canceled'].includes(child.state)
|
|
143
143
|
: !['completed', 'failed', 'canceled'].includes(child.state))
|
|
144
144
|
&& child.usage.modelCalls <= owned.maxModelCalls && child.usage.toolCalls <= owned.maxToolCalls
|
|
@@ -164,6 +164,16 @@ export function reduceChildLifecycle(snapshot, config, request, result, digest,
|
|
|
164
164
|
callId: approval.toolCall.callId, operationKey: request.operationKey };
|
|
165
165
|
updated.interaction = null;
|
|
166
166
|
}
|
|
167
|
+
else if (!result.errorCode && request.action === 'wait' && result.children?.some(child => child.state === 'paused'
|
|
168
|
+
&& pending.includes(child.runId) && (!request.waitForChildRunIds || request.waitForChildRunIds.includes(child.runId)))) {
|
|
169
|
+
// A joined child can still own valid results and an unspent reservation.
|
|
170
|
+
// Preserve that original run until an explicit control resumes or cancels
|
|
171
|
+
// it. Background polls do not block the parent's independent work.
|
|
172
|
+
updated.resumePhase = updated.phase;
|
|
173
|
+
updated.phase = 'paused';
|
|
174
|
+
updated.reason = 'child_paused';
|
|
175
|
+
updated.outcome = null;
|
|
176
|
+
}
|
|
167
177
|
else if (result.errorCode || !observationOnly && request.action !== 'poll'
|
|
168
178
|
&& pending.some(id => !request.waitForChildRunIds || request.waitForChildRunIds.includes(id))) {
|
|
169
179
|
updated.phase = 'finalizing';
|
package/dist/configuration.d.mts
CHANGED
|
@@ -24,9 +24,12 @@ export interface ConfigurationInput {
|
|
|
24
24
|
inputPolicy?: RunConfiguration['inputPolicy'];
|
|
25
25
|
sourceReadPolicy?: RunConfiguration['sourceReadPolicy'];
|
|
26
26
|
outputRecoveryPolicy?: RunConfiguration['outputRecoveryPolicy'];
|
|
27
|
+
outputRestartPolicy?: RunConfiguration['outputRestartPolicy'];
|
|
28
|
+
approvalOutcomePolicy?: RunConfiguration['approvalOutcomePolicy'];
|
|
27
29
|
providerRecoveryPolicy?: RunConfiguration['providerRecoveryPolicy'];
|
|
28
30
|
toolErrorRecoveryPolicy?: RunConfiguration['toolErrorRecoveryPolicy'];
|
|
29
31
|
toolDiscoveryPolicy?: RunConfiguration['toolDiscoveryPolicy'];
|
|
32
|
+
toolAdmissionPolicy?: RunConfiguration['toolAdmissionPolicy'];
|
|
30
33
|
todoPolicy?: RunConfiguration['todoPolicy'];
|
|
31
34
|
toolExecutionPolicy?: RunConfiguration['toolExecutionPolicy'];
|
|
32
35
|
childTaskPolicy?: RunConfiguration['childTaskPolicy'];
|
package/dist/configuration.mjs
CHANGED
|
@@ -48,9 +48,12 @@ export function configure(input) {
|
|
|
48
48
|
...(input.inputPolicy === undefined ? {} : { inputPolicy: input.inputPolicy }),
|
|
49
49
|
...(input.sourceReadPolicy === undefined ? {} : { sourceReadPolicy: input.sourceReadPolicy }),
|
|
50
50
|
...(input.outputRecoveryPolicy === undefined ? {} : { outputRecoveryPolicy: input.outputRecoveryPolicy }),
|
|
51
|
+
...(input.outputRestartPolicy === undefined ? {} : { outputRestartPolicy: input.outputRestartPolicy }),
|
|
52
|
+
...(input.approvalOutcomePolicy === undefined ? {} : { approvalOutcomePolicy: input.approvalOutcomePolicy }),
|
|
51
53
|
...(input.providerRecoveryPolicy === undefined ? {} : { providerRecoveryPolicy: input.providerRecoveryPolicy }),
|
|
52
54
|
...(input.toolErrorRecoveryPolicy === undefined ? {} : { toolErrorRecoveryPolicy: input.toolErrorRecoveryPolicy }),
|
|
53
55
|
...(input.toolDiscoveryPolicy === undefined ? {} : { toolDiscoveryPolicy: input.toolDiscoveryPolicy }),
|
|
56
|
+
...(input.toolAdmissionPolicy === undefined ? {} : { toolAdmissionPolicy: input.toolAdmissionPolicy }),
|
|
54
57
|
...(input.todoPolicy === undefined ? {} : { todoPolicy: input.todoPolicy }),
|
|
55
58
|
...(input.toolExecutionPolicy === undefined ? {} : { toolExecutionPolicy: input.toolExecutionPolicy }),
|
|
56
59
|
...(input.childTaskPolicy === undefined ? {} : { childTaskPolicy: input.childTaskPolicy }),
|
|
@@ -58,7 +61,9 @@ export function configure(input) {
|
|
|
58
61
|
...(input.planModePolicy === undefined ? {} : { planModePolicy: input.planModePolicy }),
|
|
59
62
|
...(input.planModeInitialActive === undefined ? {} : { planModeInitialActive: input.planModeInitialActive }),
|
|
60
63
|
...(input.childPlanPolicy === undefined ? {} : { childPlanPolicy: input.childPlanPolicy }),
|
|
61
|
-
...(input.toolErrorRecoveryModelCalls === undefined
|
|
64
|
+
...(input.toolErrorRecoveryModelCalls === undefined
|
|
65
|
+
? input.toolErrorRecoveryPolicy === 'diagnose-before-repeat/v2' ? { toolErrorRecoveryModelCalls: 10 } : {}
|
|
66
|
+
: { toolErrorRecoveryModelCalls: input.toolErrorRecoveryModelCalls }),
|
|
62
67
|
...(input.deliveryReviewPolicy === undefined ? {} : { deliveryReviewPolicy: input.deliveryReviewPolicy === null ? null : normalizeDeliveryReviewPolicy(input.deliveryReviewPolicy) }),
|
|
63
68
|
...(input.hostRecoveryBinding === undefined ? {} : { hostRecoveryBinding: input.hostRecoveryBinding }),
|
|
64
69
|
...(input.backgroundSessionBindingDigest === undefined ? {} : { backgroundSessionBindingDigest: input.backgroundSessionBindingDigest }),
|
|
@@ -102,10 +107,14 @@ export function configure(input) {
|
|
|
102
107
|
&& typeof config.hostRecoveryBinding === 'object' && !Array.isArray(config.hostRecoveryBinding), 'invalid_host_recovery_binding');
|
|
103
108
|
invariant(config.guidancePolicy == null || config.guidancePolicy === 'boundary-guide/v1', 'invalid_guidance_policy');
|
|
104
109
|
invariant(config.inputPolicy === undefined || config.inputPolicy === 'before-first-model/v1', 'invalid_input_policy');
|
|
105
|
-
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
110
|
+
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
111
|
+
invariant(config.outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(config.outputRestartPolicy)
|
|
112
|
+
&& ['response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy ?? ''), 'invalid_output_restart_policy');
|
|
113
|
+
invariant(config.approvalOutcomePolicy === undefined || config.approvalOutcomePolicy === 'owner-outcome/v1', 'invalid_approval_outcome_policy');
|
|
106
114
|
invariant(config.providerRecoveryPolicy == null || config.providerRecoveryPolicy === 'provider-recovery/v2', 'invalid_provider_recovery_policy');
|
|
107
115
|
invariant(config.toolExecutionPolicy === undefined || config.toolExecutionPolicy === 'owner-execution/v1', 'invalid_tool_execution_policy');
|
|
108
|
-
invariant(config.toolErrorRecoveryPolicy == null ||
|
|
116
|
+
invariant(config.toolErrorRecoveryPolicy == null || ['diagnose-before-repeat/v1', 'diagnose-before-repeat/v2'].includes(config.toolErrorRecoveryPolicy), 'invalid_tool_error_recovery_policy');
|
|
117
|
+
invariant(config.toolErrorRecoveryPolicy !== 'diagnose-before-repeat/v2' || config.toolErrorRecoveryModelCalls !== undefined, 'missing_tool_error_recovery_model_calls');
|
|
109
118
|
invariant(config.toolErrorRecoveryModelCalls == null || Number.isSafeInteger(config.toolErrorRecoveryModelCalls)
|
|
110
119
|
&& config.toolErrorRecoveryModelCalls >= 1 && config.toolErrorRecoveryModelCalls <= 10, 'invalid_tool_error_recovery_model_calls');
|
|
111
120
|
invariant(config.deliveryReviewPolicy == null || !config.tools.some(tool => tool.name === REVIEW_SUBMISSION_TOOL), 'reserved_delivery_review_tool');
|
|
@@ -185,7 +194,7 @@ export function configure(input) {
|
|
|
185
194
|
const policy = profile.providerCompatibilityPolicy;
|
|
186
195
|
invariant(policy !== null && typeof policy === 'object' && !Array.isArray(policy)
|
|
187
196
|
&& Object.keys(policy).every(key => ['contract', 'rule'].includes(key))
|
|
188
|
-
&& ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3'].includes(policy.contract)
|
|
197
|
+
&& ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)
|
|
189
198
|
&& ['auto', 'permissive', 'openai', 'strict-openai', 'cerebras', 'groq', 'deepseek',
|
|
190
199
|
'zai', 'kspmas-gateway', 'moonshot', 'mimo'].includes(policy.rule), 'invalid_provider_compatibility_policy');
|
|
191
200
|
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { ContextPort, ContextSourceDefinition, Message, ObjectValue, PortContext, RunConfiguration, RunSnapshot } from './contracts.mjs';
|
|
2
2
|
export declare const CONTEXT_SOURCE_CONTRACT = "agentkit.native-context-source/v1";
|
|
3
3
|
export declare const CONTEXT_CONTRIBUTION_CONTRACT = "agentkit.native-context-contribution/v1";
|
|
4
|
+
/** Only exhaustion produced by this collector can authorize a recoverable pause. */
|
|
5
|
+
export declare function contextSourceUnavailable(error: unknown, config: RunConfiguration): ObjectValue | null;
|
|
4
6
|
export declare function validateContextSource(source: ContextSourceDefinition, timeoutMs: number): void;
|
|
5
7
|
export declare function contextContributionMessage(source: ContextSourceDefinition, item: ObjectValue): Message;
|
|
6
8
|
/** Only the outer envelope from a frozen source can select instruction retention.
|
|
@@ -1,6 +1,26 @@
|
|
|
1
|
-
import { canonical, copy, invariant, NativeError } from './values.mjs';
|
|
1
|
+
import { canonical, copy, invariant, isNativeError, NativeError } from './values.mjs';
|
|
2
2
|
export const CONTEXT_SOURCE_CONTRACT = 'agentkit.native-context-source/v1';
|
|
3
3
|
export const CONTEXT_CONTRIBUTION_CONTRACT = 'agentkit.native-context-contribution/v1';
|
|
4
|
+
class ContextSourceUnavailable extends NativeError {
|
|
5
|
+
sourceId;
|
|
6
|
+
bindingDigest;
|
|
7
|
+
timeoutRetries;
|
|
8
|
+
constructor(sourceId, bindingDigest, timeoutRetries) {
|
|
9
|
+
super('context_source_unavailable');
|
|
10
|
+
this.sourceId = sourceId;
|
|
11
|
+
this.bindingDigest = bindingDigest;
|
|
12
|
+
this.timeoutRetries = timeoutRetries;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** Only exhaustion produced by this collector can authorize a recoverable pause. */
|
|
16
|
+
export function contextSourceUnavailable(error, config) {
|
|
17
|
+
if (!(error instanceof ContextSourceUnavailable))
|
|
18
|
+
return null;
|
|
19
|
+
const source = config.contextSources.find(source => source.sourceId === error.sourceId
|
|
20
|
+
&& source.bindingDigest === error.bindingDigest && source.required
|
|
21
|
+
&& source.timeoutRecovery?.maxRetries === error.timeoutRetries);
|
|
22
|
+
return source ? { sourceId: source.sourceId, bindingDigest: source.bindingDigest, timeoutRetries: error.timeoutRetries } : null;
|
|
23
|
+
}
|
|
4
24
|
export function validateContextSource(source, timeoutMs) {
|
|
5
25
|
invariant(source.contract === CONTEXT_SOURCE_CONTRACT && typeof source.sourceId === 'string' && !!source.sourceId.trim()
|
|
6
26
|
&& typeof source.bindingDigest === 'string' && !!source.bindingDigest.trim()
|
|
@@ -9,6 +29,23 @@ export function validateContextSource(source, timeoutMs) {
|
|
|
9
29
|
&& Number.isSafeInteger(source.maxTokens) && source.maxTokens > 0
|
|
10
30
|
&& Number.isSafeInteger(source.maxBytes) && source.maxBytes > 0 && source.maxBytes <= 131072, 'invalid_context_source');
|
|
11
31
|
invariant(source.instructionPolicy === undefined || source.instructionPolicy === 'current-files/v1' && source.required, 'invalid_context_instruction_source');
|
|
32
|
+
const recovery = source.timeoutRecovery;
|
|
33
|
+
invariant(recovery === undefined || recovery && !Array.isArray(recovery)
|
|
34
|
+
&& Object.keys(recovery).sort().join(',') === 'contract,maxRetries,retryDelayMs' && recovery.contract === 'context-source-timeout/v1'
|
|
35
|
+
&& Number.isSafeInteger(recovery.maxRetries) && recovery.maxRetries >= 0 && recovery.maxRetries <= 3
|
|
36
|
+
&& Number.isSafeInteger(recovery.retryDelayMs) && recovery.retryDelayMs >= 0 && recovery.retryDelayMs <= 60000
|
|
37
|
+
&& source.timeoutMs * (recovery.maxRetries + 1) + recovery.retryDelayMs * recovery.maxRetries < timeoutMs, 'invalid_context_source_timeout_recovery');
|
|
38
|
+
}
|
|
39
|
+
async function retryDelay(ms, signal) {
|
|
40
|
+
signal.throwIfAborted();
|
|
41
|
+
await new Promise((resolve, reject) => {
|
|
42
|
+
const done = () => { signal.removeEventListener('abort', canceled); resolve(); };
|
|
43
|
+
const timer = setTimeout(done, ms);
|
|
44
|
+
const canceled = () => { clearTimeout(timer); signal.removeEventListener('abort', canceled); reject(signal.reason); };
|
|
45
|
+
signal.addEventListener('abort', canceled, { once: true });
|
|
46
|
+
if (signal.aborted)
|
|
47
|
+
canceled();
|
|
48
|
+
});
|
|
12
49
|
}
|
|
13
50
|
export function contextContributionMessage(source, item) {
|
|
14
51
|
return { role: 'user', kind: 'context_contribution', content: canonical({ schemaVersion: CONTEXT_CONTRIBUTION_CONTRACT,
|
|
@@ -43,56 +80,71 @@ export function currentInstructionContribution(message, config) {
|
|
|
43
80
|
export async function collectContextContributions(context, snapshot, config, port, count) {
|
|
44
81
|
const messages = [], diagnostics = [];
|
|
45
82
|
for (const source of [...config.contextSources].sort((a, b) => b.priority - a.priority)) {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
invariant(Date.now() < deadline, 'context_source_timeout');
|
|
63
|
-
invariant(result && Array.isArray(result.items) && result.items.length <= 64
|
|
64
|
-
&& new TextEncoder().encode(canonical(result)).length <= 4 * 1024 * 1024, 'context_source_result_invalid');
|
|
65
|
-
invariant(!source.instructionPolicy || result.items.length > 0, 'context_instruction_source_snapshot_missing');
|
|
66
|
-
const admitted = [];
|
|
67
|
-
for (const item of result.items) {
|
|
68
|
-
invariant(item && typeof item === 'object' && !Array.isArray(item), 'context_source_result_invalid');
|
|
69
|
-
const candidate = [...admitted, contextContributionMessage(source, item)];
|
|
70
|
-
if (new TextEncoder().encode(canonical(candidate)).length > source.maxBytes) {
|
|
71
|
-
invariant(!source.instructionPolicy, 'context_instruction_source_byte_budget_exceeded');
|
|
72
|
-
continue;
|
|
73
|
-
}
|
|
74
|
-
const tokens = await Promise.race([count(copy(candidate)), canceled]);
|
|
83
|
+
for (let attempt = 0;; attempt++) {
|
|
84
|
+
context.signal.throwIfAborted();
|
|
85
|
+
const abort = new AbortController(), signal = AbortSignal.any([context.signal, abort.signal]);
|
|
86
|
+
let listener = () => { };
|
|
87
|
+
const timer = setTimeout(() => abort.abort(new NativeError('context_source_timeout')), source.timeoutMs);
|
|
88
|
+
const deadline = Date.now() + source.timeoutMs;
|
|
89
|
+
const canceled = new Promise((_, reject) => {
|
|
90
|
+
listener = () => reject(signal.reason);
|
|
91
|
+
signal.addEventListener('abort', listener, { once: true });
|
|
92
|
+
if (signal.aborted)
|
|
93
|
+
listener();
|
|
94
|
+
});
|
|
95
|
+
try {
|
|
96
|
+
invariant(port.readSource, 'context_source_port_missing');
|
|
97
|
+
const result = await Promise.race([port.readSource({ ...context, signal, source: copy(source), snapshot: copy(snapshot),
|
|
98
|
+
configuration: copy(config), remainingTokens: Math.min(source.maxTokens, config.profile.contextWindow - config.profile.maxOutputTokens) }), canceled]);
|
|
75
99
|
signal.throwIfAborted();
|
|
76
100
|
invariant(Date.now() < deadline, 'context_source_timeout');
|
|
77
|
-
invariant(
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
101
|
+
invariant(result && Array.isArray(result.items) && result.items.length <= 64
|
|
102
|
+
&& new TextEncoder().encode(canonical(result)).length <= 4 * 1024 * 1024, 'context_source_result_invalid');
|
|
103
|
+
invariant(!source.instructionPolicy || result.items.length > 0, 'context_instruction_source_snapshot_missing');
|
|
104
|
+
const admitted = [];
|
|
105
|
+
for (const item of result.items) {
|
|
106
|
+
invariant(item && typeof item === 'object' && !Array.isArray(item), 'context_source_result_invalid');
|
|
107
|
+
const candidate = [...admitted, contextContributionMessage(source, item)];
|
|
108
|
+
if (new TextEncoder().encode(canonical(candidate)).length > source.maxBytes) {
|
|
109
|
+
invariant(!source.instructionPolicy, 'context_instruction_source_byte_budget_exceeded');
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const tokens = await Promise.race([count(copy(candidate)), canceled]);
|
|
113
|
+
signal.throwIfAborted();
|
|
114
|
+
invariant(Date.now() < deadline, 'context_source_timeout');
|
|
115
|
+
invariant(Number.isSafeInteger(tokens) && tokens >= 0, 'context_token_count_invalid');
|
|
116
|
+
invariant(!source.instructionPolicy || tokens <= source.maxTokens, 'context_instruction_source_token_budget_exceeded');
|
|
117
|
+
if (tokens <= source.maxTokens)
|
|
118
|
+
admitted.push(candidate.at(-1));
|
|
119
|
+
}
|
|
120
|
+
messages.push(...admitted);
|
|
121
|
+
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: 'ok',
|
|
122
|
+
proposed: result.items.length, admitted: admitted.length,
|
|
123
|
+
...(source.timeoutRecovery ? { timeoutRetries: attempt } : {}) });
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
context.signal.throwIfAborted();
|
|
128
|
+
if (isNativeError(error) && error.code === 'context_source_timeout' && source.timeoutRecovery) {
|
|
129
|
+
abort.abort(error);
|
|
130
|
+
if (attempt < source.timeoutRecovery.maxRetries) {
|
|
131
|
+
await retryDelay(source.timeoutRecovery.retryDelayMs, context.signal);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (source.required)
|
|
135
|
+
throw new ContextSourceUnavailable(source.sourceId, source.bindingDigest, attempt);
|
|
136
|
+
}
|
|
137
|
+
if (source.required)
|
|
138
|
+
throw error;
|
|
139
|
+
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: 'skipped',
|
|
140
|
+
...(source.timeoutRecovery ? { timeoutRetries: attempt } : {}) });
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
signal.removeEventListener('abort', listener);
|
|
146
|
+
abort.abort();
|
|
81
147
|
}
|
|
82
|
-
messages.push(...admitted);
|
|
83
|
-
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: 'ok',
|
|
84
|
-
proposed: result.items.length, admitted: admitted.length });
|
|
85
|
-
}
|
|
86
|
-
catch (error) {
|
|
87
|
-
context.signal.throwIfAborted();
|
|
88
|
-
if (source.required)
|
|
89
|
-
throw error;
|
|
90
|
-
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: 'skipped' });
|
|
91
|
-
}
|
|
92
|
-
finally {
|
|
93
|
-
clearTimeout(timer);
|
|
94
|
-
signal.removeEventListener('abort', listener);
|
|
95
|
-
abort.abort();
|
|
96
148
|
}
|
|
97
149
|
}
|
|
98
150
|
return { messages, diagnostics };
|
|
@@ -9,7 +9,7 @@ import { sourceWorkingSetGroup } from './source-working-set-group.mjs';
|
|
|
9
9
|
import { sourceReuseProjector } from './context-source-reuse.mjs';
|
|
10
10
|
import { defaultToolPruningThreshold, projectOldToolResults, toolPruningIdleElapsed } from './context-microcompact.mjs';
|
|
11
11
|
import { summaryContinuityInstructions, validSummaryContinuity } from './summary-continuity.mjs';
|
|
12
|
-
import { responseContinuationPairs } from './response-continuation.mjs';
|
|
12
|
+
import { responseBoundaryRecovery, responseContinuationPairs } from './response-continuation.mjs';
|
|
13
13
|
import { verificationModelView } from './model-surface.mjs';
|
|
14
14
|
import { currentInstructionContribution } from './context-contributions.mjs';
|
|
15
15
|
const emptyState = () => ({ history: null, compaction: null, compactions: 0,
|
|
@@ -120,7 +120,7 @@ function groupsOf(messages, indexes) {
|
|
|
120
120
|
}
|
|
121
121
|
function mandatoryIndexes(snapshot, groups, config) {
|
|
122
122
|
const mandatory = new Set(), messages = snapshot.messages;
|
|
123
|
-
if (config
|
|
123
|
+
if (responseBoundaryRecovery(config))
|
|
124
124
|
for (const pair of responseContinuationPairs(messages))
|
|
125
125
|
for (const index of pair)
|
|
126
126
|
mandatory.add(index);
|
package/dist/contracts.d.mts
CHANGED
|
@@ -182,7 +182,7 @@ export interface ModelProfile {
|
|
|
182
182
|
rule: 'auto' | 'permissive' | 'openai' | 'strict-openai' | 'cerebras' | 'groq' | 'deepseek' | 'zai' | 'kspmas-gateway' | 'moonshot' | 'mimo';
|
|
183
183
|
};
|
|
184
184
|
providerCompatibilityPolicy?: {
|
|
185
|
-
contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3';
|
|
185
|
+
contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3' | 'provider-compat/v4';
|
|
186
186
|
rule: NonNullable<ModelProfile['inlineReasoningPolicy']>['rule'];
|
|
187
187
|
};
|
|
188
188
|
streaming?: boolean;
|
|
@@ -465,6 +465,12 @@ export interface ContextSourceDefinition {
|
|
|
465
465
|
maxBytes: number;
|
|
466
466
|
/** Current file guidance is refreshed before inference, never substituted by a historical summary. */
|
|
467
467
|
instructionPolicy?: 'current-files/v1';
|
|
468
|
+
/** Retry only a timed-out read; required sources pause after exhaustion. Absence keeps the frozen legacy behavior. */
|
|
469
|
+
timeoutRecovery?: {
|
|
470
|
+
contract: 'context-source-timeout/v1';
|
|
471
|
+
maxRetries: number;
|
|
472
|
+
retryDelayMs: number;
|
|
473
|
+
};
|
|
468
474
|
}
|
|
469
475
|
/** A frozen transcript import, never a parent Run or an execution checkpoint. */
|
|
470
476
|
export interface ConversationSeed {
|
|
@@ -510,6 +516,8 @@ export interface RunConfiguration {
|
|
|
510
516
|
planModeInitialActive?: boolean;
|
|
511
517
|
childPlanPolicy?: 'inherit-plan/v1';
|
|
512
518
|
toolDiscoveryPolicy?: 'local-tool-search/v1';
|
|
519
|
+
/** A premature call may load an already authorized schema, but never dispatch its operation. */
|
|
520
|
+
toolAdmissionPolicy?: 'discover-before-retry/v1';
|
|
513
521
|
artifactPolicy?: 'runtime-artifacts/v1' | null;
|
|
514
522
|
/** The execution owner must prepare Host context before the first inference. */
|
|
515
523
|
inputPolicy?: 'before-first-model/v1';
|
|
@@ -536,10 +544,19 @@ export interface RunConfiguration {
|
|
|
536
544
|
delegationDepth: number;
|
|
537
545
|
modelRecoveryPolicy: 'manual' | 'pure-inference/v1';
|
|
538
546
|
guidancePolicy?: 'boundary-guide/v1' | null;
|
|
539
|
-
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | null;
|
|
547
|
+
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | 'response-boundary/v3' | null;
|
|
548
|
+
/** Restart allowance belongs to one interrupted response chain. v2 pauses
|
|
549
|
+
* exhausted chains for explicit resume instead of terminating the Run.
|
|
550
|
+
* Legacy Runs retain their frozen accounting and exhaustion behavior. */
|
|
551
|
+
outputRestartPolicy?: 'per-response/v1' | 'per-response/v2';
|
|
552
|
+
/** The interactive owner preserves typed Host outcomes and pauses on a
|
|
553
|
+
* non-grant. Children retain the outcome without duplicating that pause. */
|
|
554
|
+
approvalOutcomePolicy?: 'owner-outcome/v1';
|
|
540
555
|
/** v2 counts consecutive provider failures and pauses (resumable) instead of failing when they run out. */
|
|
541
556
|
providerRecoveryPolicy?: 'provider-recovery/v2' | null;
|
|
542
|
-
|
|
557
|
+
/** v2 admits a ten-inference diagnostic allowance unless explicitly configured.
|
|
558
|
+
* Frozen v1 configurations retain their original unbounded/default semantics. */
|
|
559
|
+
toolErrorRecoveryPolicy?: 'diagnose-before-repeat/v1' | 'diagnose-before-repeat/v2' | null;
|
|
543
560
|
toolErrorRecoveryModelCalls?: number | null;
|
|
544
561
|
deliveryReviewPolicy?: DeliveryReviewPolicy | null;
|
|
545
562
|
/** Opaque, Host-owned recovery locator. The core never interprets it as authority. */
|
|
@@ -701,7 +718,7 @@ export interface ChildState {
|
|
|
701
718
|
sessionId: string;
|
|
702
719
|
operationKey: string;
|
|
703
720
|
callId: string;
|
|
704
|
-
state: 'prepared' | 'running' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
|
|
721
|
+
state: 'prepared' | 'running' | 'paused' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
|
|
705
722
|
reservedModelCalls: number | null;
|
|
706
723
|
reservedToolCalls: number | null;
|
|
707
724
|
usage: Usage;
|
|
@@ -955,7 +972,7 @@ export interface EffectReceipt {
|
|
|
955
972
|
status: 'committed' | 'failed' | 'uncertain' | 'not_dispatched';
|
|
956
973
|
result: ObjectValue;
|
|
957
974
|
}
|
|
958
|
-
export type CommandKind = 'cancel' | 'policy_revoked' | 'pause' | 'resume' | 'submit_interaction' | 'reconcile_tool' | 'repair_workspace' | 'steer' | 'guide' | 'promote_child' | 'message_child' | 'cancel_child';
|
|
975
|
+
export type CommandKind = 'cancel' | 'policy_revoked' | 'pause' | 'resume' | 'submit_interaction' | 'reconcile_tool' | 'repair_workspace' | 'steer' | 'guide' | 'promote_child' | 'message_child' | 'cancel_child' | 'resume_child';
|
|
959
976
|
export interface RunCommand {
|
|
960
977
|
commandId: string;
|
|
961
978
|
kind: CommandKind;
|
package/dist/contracts.mjs
CHANGED
|
@@ -6,5 +6,5 @@ export const terminal = (phase) => ['completed', 'failed', 'canceled', 'interrup
|
|
|
6
6
|
export const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, modelCalls: 0, toolCalls: 0, cost: 0 });
|
|
7
7
|
export const commandPriority = {
|
|
8
8
|
cancel: 100, policy_revoked: 95, submit_interaction: 90, cancel_child: 85,
|
|
9
|
-
pause: 80, resume: 80, reconcile_tool: 75, repair_workspace: 75, promote_child: 70, message_child: 70, steer: 60, guide: 60,
|
|
9
|
+
pause: 80, resume: 80, reconcile_tool: 75, repair_workspace: 75, promote_child: 70, message_child: 70, resume_child: 70, steer: 60, guide: 60,
|
|
10
10
|
};
|
package/dist/index.d.mts
CHANGED
|
@@ -49,6 +49,7 @@ export * from './child-budget.mjs';
|
|
|
49
49
|
export * from './child-contract.mjs';
|
|
50
50
|
export * from './child-runtime.mjs';
|
|
51
51
|
export * from './child-control.mjs';
|
|
52
|
+
export * from './approval-outcome.mjs';
|
|
52
53
|
export * from './guidance.mjs';
|
|
53
54
|
export * from './tool-receipt.mjs';
|
|
54
55
|
export * from './output-recovery.mjs';
|
package/dist/index.mjs
CHANGED
|
@@ -49,6 +49,7 @@ export * from './child-budget.mjs';
|
|
|
49
49
|
export * from './child-contract.mjs';
|
|
50
50
|
export * from './child-runtime.mjs';
|
|
51
51
|
export * from './child-control.mjs';
|
|
52
|
+
export * from './approval-outcome.mjs';
|
|
52
53
|
export * from './guidance.mjs';
|
|
53
54
|
export * from './tool-receipt.mjs';
|
|
54
55
|
export * from './output-recovery.mjs';
|
package/dist/kernel.d.mts
CHANGED
|
@@ -40,6 +40,7 @@ export declare class NativeKernel {
|
|
|
40
40
|
promoteChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
|
|
41
41
|
sendChildInput(scope: RunScope, runId: string, childRunId: string, text: string, expectedGoalRevision: number, commandId: string): import("./contracts.mjs").CommandReceipt;
|
|
42
42
|
cancelChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
|
|
43
|
+
resumeChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
|
|
43
44
|
private submitChildControl;
|
|
44
45
|
private childTaskStates;
|
|
45
46
|
private consumeChildControl;
|