@kingsoftcloud/agentkit-harness-core 0.0.12 → 0.0.14
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/background-notification.mjs +4 -2
- package/dist/configuration.d.mts +1 -0
- package/dist/configuration.mjs +8 -2
- package/dist/context-contributions.d.mts +2 -0
- package/dist/context-contributions.mjs +100 -48
- package/dist/contracts.d.mts +12 -1
- package/dist/kernel.mjs +11 -1
- package/dist/machine.mjs +8 -6
- package/dist/tool-discovery.d.mts +5 -1
- package/dist/tool-discovery.mjs +23 -0
- package/package.json +1 -1
- package/src/background-notification.mts +4 -2
- package/src/configuration.mts +10 -2
- package/src/context-contributions.mts +84 -38
- package/src/contracts.mts +8 -1
- package/src/kernel.mts +9 -1
- package/src/machine.mts +9 -6
- package/src/tool-discovery.mts +26 -1
|
@@ -162,11 +162,13 @@ export async function admitBackgroundNotification({ store, scope, sourceRunId, t
|
|
|
162
162
|
limits.maxWallMs -= used.wall + elapsed;
|
|
163
163
|
invariant((limits.maxModelCalls === null || limits.maxModelCalls > 0) && (limits.maxWallMs === null || limits.maxWallMs > 0), 'background_notification_budget_exhausted');
|
|
164
164
|
limits.maxRepairs = Math.max(0, limits.maxRepairs - used.repairs);
|
|
165
|
-
|
|
165
|
+
if (source.configuration.outputRestartPolicy !== 'per-response/v1')
|
|
166
|
+
limits.maxOutputRestarts = Math.max(0, limits.maxOutputRestarts - used.outputRestarts);
|
|
166
167
|
limits.maxRecoveryRetries = Math.max(0, limits.maxRecoveryRetries - used.recovery);
|
|
167
168
|
const contract = copy(head.taskContract ?? parent.configuration.contract);
|
|
168
169
|
const configuration = configure({ ...copy(source.configuration), contract, limits, inputMessages: null,
|
|
169
|
-
profile: { ...source.configuration.profile, maxContinuations:
|
|
170
|
+
profile: { ...source.configuration.profile, maxContinuations: source.configuration.outputRestartPolicy === 'per-response/v1'
|
|
171
|
+
? source.configuration.profile.maxContinuations : Math.max(0, source.configuration.profile.maxContinuations - used.continuations) } });
|
|
170
172
|
const snapshot = initialSnapshot({ scope: fixedScope, runId, sessionId: source.snapshot.sessionId,
|
|
171
173
|
turnId: runId, buildId: source.snapshot.buildId, parentRunId: head.runId, taskChainId: source.snapshot.taskChainId }, configuration, digest(configuration));
|
|
172
174
|
snapshot.backgroundNotification = { ...origin, admissionElapsedMs: elapsed };
|
package/dist/configuration.d.mts
CHANGED
|
@@ -24,6 +24,7 @@ export interface ConfigurationInput {
|
|
|
24
24
|
inputPolicy?: RunConfiguration['inputPolicy'];
|
|
25
25
|
sourceReadPolicy?: RunConfiguration['sourceReadPolicy'];
|
|
26
26
|
outputRecoveryPolicy?: RunConfiguration['outputRecoveryPolicy'];
|
|
27
|
+
outputRestartPolicy?: RunConfiguration['outputRestartPolicy'];
|
|
27
28
|
providerRecoveryPolicy?: RunConfiguration['providerRecoveryPolicy'];
|
|
28
29
|
toolErrorRecoveryPolicy?: RunConfiguration['toolErrorRecoveryPolicy'];
|
|
29
30
|
toolDiscoveryPolicy?: RunConfiguration['toolDiscoveryPolicy'];
|
package/dist/configuration.mjs
CHANGED
|
@@ -48,6 +48,7 @@ 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 }),
|
|
51
52
|
...(input.providerRecoveryPolicy === undefined ? {} : { providerRecoveryPolicy: input.providerRecoveryPolicy }),
|
|
52
53
|
...(input.toolErrorRecoveryPolicy === undefined ? {} : { toolErrorRecoveryPolicy: input.toolErrorRecoveryPolicy }),
|
|
53
54
|
...(input.toolDiscoveryPolicy === undefined ? {} : { toolDiscoveryPolicy: input.toolDiscoveryPolicy }),
|
|
@@ -58,7 +59,9 @@ export function configure(input) {
|
|
|
58
59
|
...(input.planModePolicy === undefined ? {} : { planModePolicy: input.planModePolicy }),
|
|
59
60
|
...(input.planModeInitialActive === undefined ? {} : { planModeInitialActive: input.planModeInitialActive }),
|
|
60
61
|
...(input.childPlanPolicy === undefined ? {} : { childPlanPolicy: input.childPlanPolicy }),
|
|
61
|
-
...(input.toolErrorRecoveryModelCalls === undefined
|
|
62
|
+
...(input.toolErrorRecoveryModelCalls === undefined
|
|
63
|
+
? input.toolErrorRecoveryPolicy === 'diagnose-before-repeat/v2' ? { toolErrorRecoveryModelCalls: 10 } : {}
|
|
64
|
+
: { toolErrorRecoveryModelCalls: input.toolErrorRecoveryModelCalls }),
|
|
62
65
|
...(input.deliveryReviewPolicy === undefined ? {} : { deliveryReviewPolicy: input.deliveryReviewPolicy === null ? null : normalizeDeliveryReviewPolicy(input.deliveryReviewPolicy) }),
|
|
63
66
|
...(input.hostRecoveryBinding === undefined ? {} : { hostRecoveryBinding: input.hostRecoveryBinding }),
|
|
64
67
|
...(input.backgroundSessionBindingDigest === undefined ? {} : { backgroundSessionBindingDigest: input.backgroundSessionBindingDigest }),
|
|
@@ -103,9 +106,12 @@ export function configure(input) {
|
|
|
103
106
|
invariant(config.guidancePolicy == null || config.guidancePolicy === 'boundary-guide/v1', 'invalid_guidance_policy');
|
|
104
107
|
invariant(config.inputPolicy === undefined || config.inputPolicy === 'before-first-model/v1', 'invalid_input_policy');
|
|
105
108
|
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
109
|
+
invariant(config.outputRestartPolicy === undefined || config.outputRestartPolicy === 'per-response/v1'
|
|
110
|
+
&& config.outputRecoveryPolicy === 'response-boundary/v2', 'invalid_output_restart_policy');
|
|
106
111
|
invariant(config.providerRecoveryPolicy == null || config.providerRecoveryPolicy === 'provider-recovery/v2', 'invalid_provider_recovery_policy');
|
|
107
112
|
invariant(config.toolExecutionPolicy === undefined || config.toolExecutionPolicy === 'owner-execution/v1', 'invalid_tool_execution_policy');
|
|
108
|
-
invariant(config.toolErrorRecoveryPolicy == null ||
|
|
113
|
+
invariant(config.toolErrorRecoveryPolicy == null || ['diagnose-before-repeat/v1', 'diagnose-before-repeat/v2'].includes(config.toolErrorRecoveryPolicy), 'invalid_tool_error_recovery_policy');
|
|
114
|
+
invariant(config.toolErrorRecoveryPolicy !== 'diagnose-before-repeat/v2' || config.toolErrorRecoveryModelCalls !== undefined, 'missing_tool_error_recovery_model_calls');
|
|
109
115
|
invariant(config.toolErrorRecoveryModelCalls == null || Number.isSafeInteger(config.toolErrorRecoveryModelCalls)
|
|
110
116
|
&& config.toolErrorRecoveryModelCalls >= 1 && config.toolErrorRecoveryModelCalls <= 10, 'invalid_tool_error_recovery_model_calls');
|
|
111
117
|
invariant(config.deliveryReviewPolicy == null || !config.tools.some(tool => tool.name === REVIEW_SUBMISSION_TOOL), 'reserved_delivery_review_tool');
|
|
@@ -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 };
|
package/dist/contracts.d.mts
CHANGED
|
@@ -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 {
|
|
@@ -537,9 +543,14 @@ export interface RunConfiguration {
|
|
|
537
543
|
modelRecoveryPolicy: 'manual' | 'pure-inference/v1';
|
|
538
544
|
guidancePolicy?: 'boundary-guide/v1' | null;
|
|
539
545
|
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | null;
|
|
546
|
+
/** Restart allowance belongs to one interrupted response chain. Legacy Runs
|
|
547
|
+
* without this policy retain their original run-wide accounting. */
|
|
548
|
+
outputRestartPolicy?: 'per-response/v1';
|
|
540
549
|
/** v2 counts consecutive provider failures and pauses (resumable) instead of failing when they run out. */
|
|
541
550
|
providerRecoveryPolicy?: 'provider-recovery/v2' | null;
|
|
542
|
-
|
|
551
|
+
/** v2 admits a ten-inference diagnostic allowance unless explicitly configured.
|
|
552
|
+
* Frozen v1 configurations retain their original unbounded/default semantics. */
|
|
553
|
+
toolErrorRecoveryPolicy?: 'diagnose-before-repeat/v1' | 'diagnose-before-repeat/v2' | null;
|
|
543
554
|
toolErrorRecoveryModelCalls?: number | null;
|
|
544
555
|
deliveryReviewPolicy?: DeliveryReviewPolicy | null;
|
|
545
556
|
/** Opaque, Host-owned recovery locator. The core never interprets it as authority. */
|
package/dist/kernel.mjs
CHANGED
|
@@ -26,7 +26,7 @@ import { contextSourceDigest, modelContextMessages, validateContextMessages } fr
|
|
|
26
26
|
import { assertHookFeedbackRetained, deniedByHook, reduceHook, stagePostHooks } from './hook-runtime.mjs';
|
|
27
27
|
import { hookBytes, hookResult } from './hook-contract.mjs';
|
|
28
28
|
import { planNativeContext, reduceContextModel } from './context-planning.mjs';
|
|
29
|
-
import { collectContextContributions } from './context-contributions.mjs';
|
|
29
|
+
import { collectContextContributions, contextSourceUnavailable } from './context-contributions.mjs';
|
|
30
30
|
import { validateInstructionScopes } from './instruction-scopes.mjs';
|
|
31
31
|
import { refreshContextSources } from './context-source-refresh.mjs';
|
|
32
32
|
import { outputRestartPayload } from './output-recovery.mjs';
|
|
@@ -1011,6 +1011,7 @@ export class NativeKernel {
|
|
|
1011
1011
|
}
|
|
1012
1012
|
catch (error) {
|
|
1013
1013
|
const code = isNativeError(error) ? error.code : 'effect_port_error';
|
|
1014
|
+
const unavailableSource = contextSourceUnavailable(error, configuration);
|
|
1014
1015
|
facts.push(observedEffectFailure({ operationKey: intent.operationKey, kind: intent.kind, code,
|
|
1015
1016
|
nativeError: isNativeError(error), signalAborted: effectSignal.aborted,
|
|
1016
1017
|
elapsedMs: this.monotonicNow() - started, initialTimeoutMs: timeoutMs, observedAtMs: this.now(),
|
|
@@ -1065,6 +1066,15 @@ export class NativeKernel {
|
|
|
1065
1066
|
childLifecycleFailure: intent.payload.action, outcome: 'unverified', reason: 'child_owner_unavailable' };
|
|
1066
1067
|
}
|
|
1067
1068
|
}
|
|
1069
|
+
else if (intent.kind === 'context' && !effectSignal.aborted && code === 'context_source_unavailable'
|
|
1070
|
+
&& unavailableSource
|
|
1071
|
+
&& ['preparing_context', 'compacting'].includes(snapshot.phase)) {
|
|
1072
|
+
raw = { code };
|
|
1073
|
+
status = 'failed';
|
|
1074
|
+
changes = { pendingIntent: null, preparedContext: null, phase: 'paused', resumePhase: snapshot.phase,
|
|
1075
|
+
outcome: null, reason: code, context: { ...snapshot.context, preparedCursor: null } };
|
|
1076
|
+
facts.push({ kind: 'context.source_unavailable', payload: { ...unavailableSource, reason: code, operationKey: intent.operationKey } });
|
|
1077
|
+
}
|
|
1068
1078
|
else if (intent.kind === 'context' && configuration.contextPolicy || ['invalid_context_messages', 'invalid_context_tool_pairing', 'context_binding_mismatch', 'context_hook_feedback_missing', 'context_guidance_missing'].includes(code)) {
|
|
1069
1079
|
raw = { code };
|
|
1070
1080
|
status = 'failed';
|
package/dist/machine.mjs
CHANGED
|
@@ -20,7 +20,7 @@ import { responseContinuationPending } from './response-continuation.mjs';
|
|
|
20
20
|
import { advanceDiagnosticRecovery, advanceObservedProgress, advanceToolErrorStreak, guardedToolErrorAction, refuseUndiagnosedToolAction, reserveDiagnosticTrial, toolErrorRecoveryBoundary, toolErrorRecoveryEnabled, toolErrorStreakExhausted } from './tool-error-recovery.mjs';
|
|
21
21
|
import { deliveryReadOutsidePaths, deliverySummaryAllowed, deliveryTaskMessages, observeExecutionBudget, rememberDeliveryWrite, scopedDeliveryReader, wallDeliveryOnly } from './deadline-delivery.mjs';
|
|
22
22
|
import { contextContinuity } from './context-planning.mjs';
|
|
23
|
-
import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, TOOL_SEARCH } from './tool-discovery.mjs';
|
|
23
|
+
import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
|
|
24
24
|
import { NativePolicyRegistry } from './policy-registry.mjs';
|
|
25
25
|
import { reduceCoordinatorResponses } from './coordinator-response.mjs';
|
|
26
26
|
import { RESULT_DELIVERY_POLICY } from './deliverables.mjs';
|
|
@@ -251,7 +251,7 @@ export function plan(snapshot, config, capabilities, digest = canonical, policie
|
|
|
251
251
|
const definition = config.tools.find(tool => tool.name === first.name);
|
|
252
252
|
if (!definition || config.contract.allowedToolNames !== null && !config.contract.allowedToolNames.includes(first.name)) {
|
|
253
253
|
return transition(snapshot, { pendingTools: snapshot.pendingTools.slice(1), messages: [...snapshot.messages,
|
|
254
|
-
{ role: 'tool', content: canonical(
|
|
254
|
+
{ role: 'tool', content: canonical(toolAdmissionRejection(snapshot, config, first, advertisedTools(snapshot, config, policies))), callId: first.callId, name: first.name }] }, [{ kind: 'tool.rejected', payload: { callId: first.callId, name: first.name, reason: 'tool_not_advertised' } }]);
|
|
255
255
|
}
|
|
256
256
|
if (toolRoom(snapshot, config) <= 0) {
|
|
257
257
|
const messages = snapshot.pendingTools.map(call => ({ role: 'tool', callId: call.callId, name: call.name,
|
|
@@ -400,8 +400,9 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
400
400
|
if (finalizationOnly({ ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config)) {
|
|
401
401
|
return { ...base, phase: 'finalizing', outcome: 'budget_exhausted', reason: 'tool_call_after_finalization_reserve' };
|
|
402
402
|
}
|
|
403
|
-
|
|
404
|
-
usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies)
|
|
403
|
+
const tools = advertisedTools({ ...snapshot,
|
|
404
|
+
usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies);
|
|
405
|
+
if (result.toolCalls.some(call => !tools.some(tool => tool.name === call.name)
|
|
405
406
|
|| !discoveredCallExposed(snapshot, config, call))) {
|
|
406
407
|
const unbound = result.toolCalls.some(call => !config.tools.some(tool => tool.name === call.name)
|
|
407
408
|
|| !discoveredCallExposed(snapshot, config, call));
|
|
@@ -409,11 +410,12 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
409
410
|
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [], modelErrors: errors,
|
|
410
411
|
outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'tool_call_not_advertised_retry_exhausted' : null, messages: [...snapshot.messages,
|
|
411
412
|
{ ...message, toolCalls: result.toolCalls }, ...result.toolCalls.map(call => ({ role: 'tool',
|
|
412
|
-
callId: call.callId, name: call.name, content: canonical(
|
|
413
|
+
callId: call.callId, name: call.name, content: canonical(toolAdmissionRejection(snapshot, config, call, tools)) }))] };
|
|
413
414
|
}
|
|
414
415
|
return { ...base, phase: 'executing_tools', pendingTools: result.toolCalls,
|
|
415
416
|
messages: [...snapshot.messages, { ...message, toolCalls: result.toolCalls }],
|
|
416
|
-
continuations: 0, modelErrors: 0
|
|
417
|
+
continuations: 0, modelErrors: 0,
|
|
418
|
+
...(config.outputRestartPolicy === 'per-response/v1' ? { outputRestarts: 0 } : {}) };
|
|
417
419
|
case 'final_candidate': {
|
|
418
420
|
if (config.contract.finalSubmissionSchema) {
|
|
419
421
|
const errors = snapshot.modelErrors + 1;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ContextPlanningResult, RunConfiguration, RunSnapshot, ToolCall, ToolDefinition, ToolResult } from './contracts.mjs';
|
|
1
|
+
import type { ContextPlanningResult, ObjectValue, RunConfiguration, RunSnapshot, ToolCall, ToolDefinition, ToolResult } from './contracts.mjs';
|
|
2
2
|
import type { ToolSearchCandidate } from './tool-search-ranking.mjs';
|
|
3
3
|
export declare const TOOL_DISCOVERY_POLICY = "local-tool-search/v1";
|
|
4
4
|
export declare const TOOL_SEARCH = "ToolSearch";
|
|
@@ -12,6 +12,10 @@ export declare function discoveryModelTools(snapshot: RunSnapshot, config: RunCo
|
|
|
12
12
|
/** Resolve before permission, grouping, budgets and durable operation identity use the target. */
|
|
13
13
|
export declare function resolveDiscoveredCalls(snapshot: RunSnapshot, config: RunConfiguration, calls: ToolCall[]): ToolCall[];
|
|
14
14
|
export declare function discoveredCallExposed(snapshot: RunSnapshot, config: RunConfiguration, call: ToolCall): boolean;
|
|
15
|
+
/** Describe a rejected model call using only the current, scoped execution
|
|
16
|
+
* catalog. Discovery is a suggested next call, never authority to dispatch the
|
|
17
|
+
* rejected operation. Historical events and frozen tool definitions stay intact. */
|
|
18
|
+
export declare function toolAdmissionRejection(snapshot: RunSnapshot, config: RunConfiguration, call: ToolCall, tools: ToolDefinition[]): ObjectValue;
|
|
15
19
|
/** Reconstitute the provider's original call; execution records keep the real target. */
|
|
16
20
|
export declare function modelWireToolCall(call: ToolCall): ToolCall;
|
|
17
21
|
/** Pure, bounded discovery result. No external tool or resource is executed here. */
|
package/dist/tool-discovery.mjs
CHANGED
|
@@ -133,6 +133,29 @@ export function discoveredCallExposed(snapshot, config, call) {
|
|
|
133
133
|
|| config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1'
|
|
134
134
|
&& snapshot.toolDiscovery?.discovered.includes(call.name) === true;
|
|
135
135
|
}
|
|
136
|
+
/** Describe a rejected model call using only the current, scoped execution
|
|
137
|
+
* catalog. Discovery is a suggested next call, never authority to dispatch the
|
|
138
|
+
* rejected operation. Historical events and frozen tool definitions stay intact. */
|
|
139
|
+
export function toolAdmissionRejection(snapshot, config, call, tools) {
|
|
140
|
+
const base = { status: 'error', code: 'tool_not_advertised', executed: false };
|
|
141
|
+
const available = tools.some(tool => tool.name === call.name);
|
|
142
|
+
const search = tools.find(tool => tool.name === TOOL_SEARCH);
|
|
143
|
+
const arguments_ = { query: `select:${call.name}` };
|
|
144
|
+
if (available && !discoveredCallExposed(snapshot, config, call) && search
|
|
145
|
+
&& call.name === call.name.trim() && !/[,\r\n]/.test(call.name)
|
|
146
|
+
&& !toolInputRejection(search, { callId: call.callId, name: TOOL_SEARCH, arguments: arguments_ })) {
|
|
147
|
+
const direct = config.profile.discoveredToolExposure === 'direct-after-search/v1'
|
|
148
|
+
|| config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1';
|
|
149
|
+
return { ...base, reason: 'definition_not_loaded', recovery: {
|
|
150
|
+
name: TOOL_SEARCH, arguments: arguments_,
|
|
151
|
+
call_after_discovery: direct ? 'direct' : DEFERRED_TOOL_CALL,
|
|
152
|
+
} };
|
|
153
|
+
}
|
|
154
|
+
const catalog = boundedCapabilityCatalog(discoveryModelTools(snapshot, config, tools)
|
|
155
|
+
.map(tool => ({ name: tool.name, description: '' })), 1024);
|
|
156
|
+
return { ...base, reason: available && discoveredCallExposed(snapshot, config, call) ? 'batch_not_executed' : 'tool_unavailable',
|
|
157
|
+
available_tool_names: catalog.entries.map(tool => tool.name), omitted_tool_names: catalog.omitted };
|
|
158
|
+
}
|
|
136
159
|
/** Reconstitute the provider's original call; execution records keep the real target. */
|
|
137
160
|
export function modelWireToolCall(call) {
|
|
138
161
|
if (call.modelCallWrapper !== DEFERRED_TOOL_CALL)
|
package/package.json
CHANGED
|
@@ -161,11 +161,13 @@ export async function admitBackgroundNotification({ store, scope, sourceRunId, t
|
|
|
161
161
|
invariant((limits.maxModelCalls === null || limits.maxModelCalls > 0) && (limits.maxWallMs === null || limits.maxWallMs > 0),
|
|
162
162
|
'background_notification_budget_exhausted');
|
|
163
163
|
limits.maxRepairs = Math.max(0, limits.maxRepairs - used.repairs);
|
|
164
|
-
|
|
164
|
+
if (source.configuration.outputRestartPolicy !== 'per-response/v1')
|
|
165
|
+
limits.maxOutputRestarts = Math.max(0, limits.maxOutputRestarts - used.outputRestarts);
|
|
165
166
|
limits.maxRecoveryRetries = Math.max(0, limits.maxRecoveryRetries - used.recovery);
|
|
166
167
|
const contract = copy(head.taskContract ?? parent.configuration.contract);
|
|
167
168
|
const configuration = configure({ ...copy(source.configuration), contract, limits, inputMessages: null,
|
|
168
|
-
profile: { ...source.configuration.profile, maxContinuations:
|
|
169
|
+
profile: { ...source.configuration.profile, maxContinuations: source.configuration.outputRestartPolicy === 'per-response/v1'
|
|
170
|
+
? source.configuration.profile.maxContinuations : Math.max(0, source.configuration.profile.maxContinuations - used.continuations) } });
|
|
169
171
|
const snapshot = initialSnapshot({ scope: fixedScope, runId, sessionId: source.snapshot.sessionId,
|
|
170
172
|
turnId: runId, buildId: source.snapshot.buildId, parentRunId: head.runId, taskChainId: source.snapshot.taskChainId }, configuration, digest(configuration));
|
|
171
173
|
snapshot.backgroundNotification = { ...origin, admissionElapsedMs: elapsed };
|
package/src/configuration.mts
CHANGED
|
@@ -36,6 +36,7 @@ export interface ConfigurationInput {
|
|
|
36
36
|
inputPolicy?: RunConfiguration['inputPolicy'];
|
|
37
37
|
sourceReadPolicy?: RunConfiguration['sourceReadPolicy'];
|
|
38
38
|
outputRecoveryPolicy?: RunConfiguration['outputRecoveryPolicy'];
|
|
39
|
+
outputRestartPolicy?: RunConfiguration['outputRestartPolicy'];
|
|
39
40
|
providerRecoveryPolicy?: RunConfiguration['providerRecoveryPolicy'];
|
|
40
41
|
toolErrorRecoveryPolicy?: RunConfiguration['toolErrorRecoveryPolicy'];
|
|
41
42
|
toolDiscoveryPolicy?: RunConfiguration['toolDiscoveryPolicy'];
|
|
@@ -96,6 +97,7 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
96
97
|
...(input.inputPolicy === undefined ? {} : { inputPolicy: input.inputPolicy }),
|
|
97
98
|
...(input.sourceReadPolicy === undefined ? {} : { sourceReadPolicy: input.sourceReadPolicy }),
|
|
98
99
|
...(input.outputRecoveryPolicy === undefined ? {} : { outputRecoveryPolicy: input.outputRecoveryPolicy }),
|
|
100
|
+
...(input.outputRestartPolicy === undefined ? {} : { outputRestartPolicy: input.outputRestartPolicy }),
|
|
99
101
|
...(input.providerRecoveryPolicy === undefined ? {} : { providerRecoveryPolicy: input.providerRecoveryPolicy }),
|
|
100
102
|
...(input.toolErrorRecoveryPolicy === undefined ? {} : { toolErrorRecoveryPolicy: input.toolErrorRecoveryPolicy }),
|
|
101
103
|
...(input.toolDiscoveryPolicy === undefined ? {} : { toolDiscoveryPolicy: input.toolDiscoveryPolicy }),
|
|
@@ -106,7 +108,9 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
106
108
|
...(input.planModePolicy === undefined ? {} : { planModePolicy: input.planModePolicy }),
|
|
107
109
|
...(input.planModeInitialActive === undefined ? {} : { planModeInitialActive: input.planModeInitialActive }),
|
|
108
110
|
...(input.childPlanPolicy === undefined ? {} : { childPlanPolicy: input.childPlanPolicy }),
|
|
109
|
-
...(input.toolErrorRecoveryModelCalls === undefined
|
|
111
|
+
...(input.toolErrorRecoveryModelCalls === undefined
|
|
112
|
+
? input.toolErrorRecoveryPolicy === 'diagnose-before-repeat/v2' ? { toolErrorRecoveryModelCalls: 10 } : {}
|
|
113
|
+
: { toolErrorRecoveryModelCalls: input.toolErrorRecoveryModelCalls }),
|
|
110
114
|
...(input.deliveryReviewPolicy === undefined ? {} : { deliveryReviewPolicy: input.deliveryReviewPolicy === null ? null : normalizeDeliveryReviewPolicy(input.deliveryReviewPolicy) }),
|
|
111
115
|
...(input.hostRecoveryBinding === undefined ? {} : { hostRecoveryBinding: input.hostRecoveryBinding }),
|
|
112
116
|
...(input.backgroundSessionBindingDigest === undefined ? {} : { backgroundSessionBindingDigest: input.backgroundSessionBindingDigest }),
|
|
@@ -152,9 +156,13 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
152
156
|
invariant(config.guidancePolicy == null || config.guidancePolicy === 'boundary-guide/v1', 'invalid_guidance_policy');
|
|
153
157
|
invariant(config.inputPolicy === undefined || config.inputPolicy === 'before-first-model/v1', 'invalid_input_policy');
|
|
154
158
|
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
159
|
+
invariant(config.outputRestartPolicy === undefined || config.outputRestartPolicy === 'per-response/v1'
|
|
160
|
+
&& config.outputRecoveryPolicy === 'response-boundary/v2', 'invalid_output_restart_policy');
|
|
155
161
|
invariant(config.providerRecoveryPolicy == null || config.providerRecoveryPolicy === 'provider-recovery/v2', 'invalid_provider_recovery_policy');
|
|
156
162
|
invariant(config.toolExecutionPolicy === undefined || config.toolExecutionPolicy === 'owner-execution/v1', 'invalid_tool_execution_policy');
|
|
157
|
-
invariant(config.toolErrorRecoveryPolicy == null ||
|
|
163
|
+
invariant(config.toolErrorRecoveryPolicy == null || ['diagnose-before-repeat/v1', 'diagnose-before-repeat/v2'].includes(config.toolErrorRecoveryPolicy), 'invalid_tool_error_recovery_policy');
|
|
164
|
+
invariant(config.toolErrorRecoveryPolicy !== 'diagnose-before-repeat/v2' || config.toolErrorRecoveryModelCalls !== undefined,
|
|
165
|
+
'missing_tool_error_recovery_model_calls');
|
|
158
166
|
invariant(config.toolErrorRecoveryModelCalls == null || Number.isSafeInteger(config.toolErrorRecoveryModelCalls)
|
|
159
167
|
&& config.toolErrorRecoveryModelCalls >= 1 && config.toolErrorRecoveryModelCalls <= 10, 'invalid_tool_error_recovery_model_calls');
|
|
160
168
|
invariant(config.deliveryReviewPolicy == null || !config.tools.some(tool => tool.name === REVIEW_SUBMISSION_TOOL), 'reserved_delivery_review_tool');
|
|
@@ -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/contracts.mts
CHANGED
|
@@ -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 {
|
|
@@ -306,9 +308,14 @@ export interface RunConfiguration {
|
|
|
306
308
|
modelRecoveryPolicy: 'manual' | 'pure-inference/v1';
|
|
307
309
|
guidancePolicy?: 'boundary-guide/v1' | null;
|
|
308
310
|
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | null;
|
|
311
|
+
/** Restart allowance belongs to one interrupted response chain. Legacy Runs
|
|
312
|
+
* without this policy retain their original run-wide accounting. */
|
|
313
|
+
outputRestartPolicy?: 'per-response/v1';
|
|
309
314
|
/** v2 counts consecutive provider failures and pauses (resumable) instead of failing when they run out. */
|
|
310
315
|
providerRecoveryPolicy?: 'provider-recovery/v2' | null;
|
|
311
|
-
|
|
316
|
+
/** v2 admits a ten-inference diagnostic allowance unless explicitly configured.
|
|
317
|
+
* Frozen v1 configurations retain their original unbounded/default semantics. */
|
|
318
|
+
toolErrorRecoveryPolicy?: 'diagnose-before-repeat/v1' | 'diagnose-before-repeat/v2' | null;
|
|
312
319
|
toolErrorRecoveryModelCalls?: number | null;
|
|
313
320
|
deliveryReviewPolicy?: DeliveryReviewPolicy | null;
|
|
314
321
|
/** Opaque, Host-owned recovery locator. The core never interprets it as authority. */
|
package/src/kernel.mts
CHANGED
|
@@ -32,7 +32,7 @@ import { assertHookFeedbackRetained, deniedByHook, reduceHook, stagePostHooks }
|
|
|
32
32
|
import { hookBytes, hookResult } from './hook-contract.mjs';
|
|
33
33
|
import { planNativeContext, reduceContextModel } from './context-planning.mjs';
|
|
34
34
|
import type { ContextCounters } from './context-planning.mjs';
|
|
35
|
-
import { collectContextContributions } from './context-contributions.mjs';
|
|
35
|
+
import { collectContextContributions, contextSourceUnavailable } from './context-contributions.mjs';
|
|
36
36
|
import { validateInstructionScopes } from './instruction-scopes.mjs';
|
|
37
37
|
import { refreshContextSources } from './context-source-refresh.mjs';
|
|
38
38
|
import { outputRestartPayload } from './output-recovery.mjs';
|
|
@@ -888,6 +888,7 @@ export class NativeKernel {
|
|
|
888
888
|
}
|
|
889
889
|
} catch (error) {
|
|
890
890
|
const code = isNativeError(error) ? error.code : 'effect_port_error';
|
|
891
|
+
const unavailableSource = contextSourceUnavailable(error, configuration);
|
|
891
892
|
facts.push(observedEffectFailure({ operationKey: intent.operationKey, kind: intent.kind, code,
|
|
892
893
|
nativeError: isNativeError(error), signalAborted: effectSignal.aborted,
|
|
893
894
|
elapsedMs: this.monotonicNow() - started, initialTimeoutMs: timeoutMs, observedAtMs: this.now(),
|
|
@@ -934,6 +935,13 @@ export class NativeKernel {
|
|
|
934
935
|
changes = { pendingIntent: null, phase: 'finalizing', candidate: null, verification: null, finalText: '',
|
|
935
936
|
childLifecycleFailure: intent.payload.action as 'poll' | 'wait' | 'cancel', outcome: 'unverified', reason: 'child_owner_unavailable' };
|
|
936
937
|
}
|
|
938
|
+
} else if (intent.kind === 'context' && !effectSignal.aborted && code === 'context_source_unavailable'
|
|
939
|
+
&& unavailableSource
|
|
940
|
+
&& ['preparing_context', 'compacting'].includes(snapshot.phase)) {
|
|
941
|
+
raw = { code }; status = 'failed';
|
|
942
|
+
changes = { pendingIntent: null, preparedContext: null, phase: 'paused', resumePhase: snapshot.phase,
|
|
943
|
+
outcome: null, reason: code, context: { ...snapshot.context, preparedCursor: null } };
|
|
944
|
+
facts.push({ kind: 'context.source_unavailable', payload: { ...unavailableSource, reason: code, operationKey: intent.operationKey } });
|
|
937
945
|
} else if (intent.kind === 'context' && configuration.contextPolicy || ['invalid_context_messages', 'invalid_context_tool_pairing', 'context_binding_mismatch', 'context_hook_feedback_missing', 'context_guidance_missing'].includes(code)) {
|
|
938
946
|
raw = { code }; status = 'failed';
|
|
939
947
|
changes = { pendingIntent: null, preparedContext: null, phase: 'finalizing', outcome: 'blocked', reason: code };
|
package/src/machine.mts
CHANGED
|
@@ -23,7 +23,7 @@ import { advanceDiagnosticRecovery, advanceObservedProgress, advanceToolErrorStr
|
|
|
23
23
|
toolErrorStreakExhausted } from './tool-error-recovery.mjs';
|
|
24
24
|
import { deliveryReadOutsidePaths, deliverySummaryAllowed, deliveryTaskMessages, observeExecutionBudget, rememberDeliveryWrite, scopedDeliveryReader, wallDeliveryOnly } from './deadline-delivery.mjs';
|
|
25
25
|
import { contextContinuity } from './context-planning.mjs';
|
|
26
|
-
import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, TOOL_SEARCH } from './tool-discovery.mjs';
|
|
26
|
+
import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
|
|
27
27
|
import { NativePolicyRegistry } from './policy-registry.mjs';
|
|
28
28
|
import { reduceCoordinatorResponses } from './coordinator-response.mjs';
|
|
29
29
|
import { RESULT_DELIVERY_POLICY } from './deliverables.mjs';
|
|
@@ -232,7 +232,8 @@ export function plan(snapshot: RunSnapshot, config: RunConfiguration, capabiliti
|
|
|
232
232
|
const definition = config.tools.find(tool => tool.name === first.name);
|
|
233
233
|
if (!definition || config.contract.allowedToolNames !== null && !config.contract.allowedToolNames.includes(first.name)) {
|
|
234
234
|
return transition(snapshot, { pendingTools: snapshot.pendingTools.slice(1), messages: [...snapshot.messages,
|
|
235
|
-
{ role: 'tool', content: canonical(
|
|
235
|
+
{ role: 'tool', content: canonical(toolAdmissionRejection(snapshot, config, first,
|
|
236
|
+
advertisedTools(snapshot, config, policies))), callId: first.callId, name: first.name }] },
|
|
236
237
|
[{ kind: 'tool.rejected', payload: { callId: first.callId, name: first.name, reason: 'tool_not_advertised' } }]);
|
|
237
238
|
}
|
|
238
239
|
if (toolRoom(snapshot, config) <= 0) {
|
|
@@ -375,8 +376,9 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
375
376
|
if (finalizationOnly({ ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config)) {
|
|
376
377
|
return { ...base, phase: 'finalizing', outcome: 'budget_exhausted', reason: 'tool_call_after_finalization_reserve' };
|
|
377
378
|
}
|
|
378
|
-
|
|
379
|
-
usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies)
|
|
379
|
+
const tools = advertisedTools({ ...snapshot,
|
|
380
|
+
usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies);
|
|
381
|
+
if (result.toolCalls.some(call => !tools.some(tool => tool.name === call.name)
|
|
380
382
|
|| !discoveredCallExposed(snapshot, config, call))) {
|
|
381
383
|
const unbound = result.toolCalls.some(call => !config.tools.some(tool => tool.name === call.name)
|
|
382
384
|
|| !discoveredCallExposed(snapshot, config, call));
|
|
@@ -384,11 +386,12 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
|
|
|
384
386
|
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [], modelErrors: errors,
|
|
385
387
|
outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'tool_call_not_advertised_retry_exhausted' : null, messages: [...snapshot.messages,
|
|
386
388
|
{ ...message, toolCalls: result.toolCalls }, ...result.toolCalls.map(call => ({ role: 'tool' as const,
|
|
387
|
-
callId: call.callId, name: call.name, content: canonical(
|
|
389
|
+
callId: call.callId, name: call.name, content: canonical(toolAdmissionRejection(snapshot, config, call, tools)) }))] };
|
|
388
390
|
}
|
|
389
391
|
return { ...base, phase: 'executing_tools', pendingTools: result.toolCalls,
|
|
390
392
|
messages: [...snapshot.messages, { ...message, toolCalls: result.toolCalls }],
|
|
391
|
-
continuations: 0, modelErrors: 0
|
|
393
|
+
continuations: 0, modelErrors: 0,
|
|
394
|
+
...(config.outputRestartPolicy === 'per-response/v1' ? { outputRestarts: 0 } : {}) };
|
|
392
395
|
case 'final_candidate': {
|
|
393
396
|
if (config.contract.finalSubmissionSchema) {
|
|
394
397
|
const errors = snapshot.modelErrors + 1;
|
package/src/tool-discovery.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ContextPlanningResult, RunConfiguration, RunSnapshot, ToolCall, ToolDefinition, ToolResult } from './contracts.mjs';
|
|
1
|
+
import type { ContextPlanningResult, ObjectValue, RunConfiguration, RunSnapshot, ToolCall, ToolDefinition, ToolResult } from './contracts.mjs';
|
|
2
2
|
import { canonical, copy, invariant } from './values.mjs';
|
|
3
3
|
import { toolInputRejection } from './tool-input.mjs';
|
|
4
4
|
import { searchTools } from './tool-search-ranking.mjs';
|
|
@@ -127,6 +127,31 @@ export function discoveredCallExposed(snapshot: RunSnapshot, config: RunConfigur
|
|
|
127
127
|
&& snapshot.toolDiscovery?.discovered.includes(call.name) === true;
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
+
/** Describe a rejected model call using only the current, scoped execution
|
|
131
|
+
* catalog. Discovery is a suggested next call, never authority to dispatch the
|
|
132
|
+
* rejected operation. Historical events and frozen tool definitions stay intact. */
|
|
133
|
+
export function toolAdmissionRejection(snapshot: RunSnapshot, config: RunConfiguration, call: ToolCall,
|
|
134
|
+
tools: ToolDefinition[]): ObjectValue {
|
|
135
|
+
const base = { status: 'error', code: 'tool_not_advertised', executed: false };
|
|
136
|
+
const available = tools.some(tool => tool.name === call.name);
|
|
137
|
+
const search = tools.find(tool => tool.name === TOOL_SEARCH);
|
|
138
|
+
const arguments_ = { query: `select:${call.name}` };
|
|
139
|
+
if (available && !discoveredCallExposed(snapshot, config, call) && search
|
|
140
|
+
&& call.name === call.name.trim() && !/[,\r\n]/.test(call.name)
|
|
141
|
+
&& !toolInputRejection(search, { callId: call.callId, name: TOOL_SEARCH, arguments: arguments_ })) {
|
|
142
|
+
const direct = config.profile.discoveredToolExposure === 'direct-after-search/v1'
|
|
143
|
+
|| config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1';
|
|
144
|
+
return { ...base, reason: 'definition_not_loaded', recovery: {
|
|
145
|
+
name: TOOL_SEARCH, arguments: arguments_,
|
|
146
|
+
call_after_discovery: direct ? 'direct' : DEFERRED_TOOL_CALL,
|
|
147
|
+
} };
|
|
148
|
+
}
|
|
149
|
+
const catalog = boundedCapabilityCatalog(discoveryModelTools(snapshot, config, tools)
|
|
150
|
+
.map(tool => ({ name: tool.name, description: '' })), 1024);
|
|
151
|
+
return { ...base, reason: available && discoveredCallExposed(snapshot, config, call) ? 'batch_not_executed' : 'tool_unavailable',
|
|
152
|
+
available_tool_names: catalog.entries.map(tool => tool.name), omitted_tool_names: catalog.omitted };
|
|
153
|
+
}
|
|
154
|
+
|
|
130
155
|
/** Reconstitute the provider's original call; execution records keep the real target. */
|
|
131
156
|
export function modelWireToolCall(call: ToolCall): ToolCall {
|
|
132
157
|
if (call.modelCallWrapper !== DEFERRED_TOOL_CALL) return call;
|