@kingsoftcloud/agentkit-harness-core 0.0.14 → 0.0.16
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-contract.d.mts +3 -0
- package/dist/background-contract.mjs +14 -0
- package/dist/background-notification.mjs +3 -2
- package/dist/child-contract.d.mts +8 -1
- 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 +2 -0
- package/dist/configuration.mjs +7 -4
- package/dist/context-planning.mjs +6 -3
- package/dist/contracts.d.mts +13 -7
- 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 +41 -5
- package/dist/machine.mjs +40 -22
- 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 +8 -0
- package/dist/tool-discovery.mjs +44 -0
- package/dist/transitions.mjs +22 -2
- package/package.json +1 -1
- package/src/approval-outcome.mts +12 -0
- package/src/background-contract.mts +12 -0
- package/src/background-notification.mts +3 -2
- package/src/child-contract.mts +5 -1
- package/src/child-control.mts +16 -2
- package/src/child-runtime.mts +7 -1
- package/src/configuration.mts +9 -4
- package/src/context-planning.mts +6 -3
- package/src/contracts.mts +14 -8
- package/src/index.mts +1 -0
- package/src/kernel.mts +38 -5
- package/src/machine.mts +41 -22
- 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 +37 -0
- package/src/transitions.mts +20 -2
package/dist/model-failure.d.mts
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
/** Observational only: these facts never authorize retries or tool execution. */
|
|
2
2
|
export declare const MODEL_FAILURE_CODES: readonly ["host_binding", "request_invalid", "http_authentication", "http_permission", "http_client", "http_server", "http_rate_limit", "http_timeout", "protocol_invalid", "json_invalid", "envelope_invalid", "provider_error", "identity_conflict", "usage_invalid", "usage_conflict", "choice_invalid", "delta_invalid", "termination_conflict", "framing_invalid", "body_limit", "body_encoding", "transport_error", "stream_timeout", "stream_incomplete", "tool_payload_invalid"];
|
|
3
|
+
/** Closed provider identifiers only; arbitrary provider strings can contain credentials. */
|
|
4
|
+
export declare const MODEL_PROVIDER_ERROR_CODES: readonly ["rate_limit_error", "rate_limit_exceeded", "overloaded_error", "server_error", "api_error", "service_unavailable_error", "server_is_overloaded", "timeout_error", "MODEL_PROVIDER_RATE_LIMIT", "MODEL_PROVIDER_UNAVAILABLE", "invalid_request_error", "invalid_api_key", "authentication_error", "permission_error", "not_found_error", "request_too_large", "billing_error", "insufficient_quota", "MODEL_PROVIDER_AUTHENTICATION", "MODEL_PROVIDER_PERMISSION", "MODEL_PROVIDER_INVALID_REQUEST", "MODEL_PROVIDER_NOT_FOUND", "MODEL_PROVIDER_QUOTA_EXHAUSTED"];
|
|
5
|
+
export declare const MODEL_PROVIDER_ERROR_TYPES: readonly ["rate_limit_error", "rate_limit_exceeded", "overloaded_error", "server_error", "api_error", "service_unavailable_error", "server_is_overloaded", "timeout_error", "MODEL_PROVIDER_RATE_LIMIT", "MODEL_PROVIDER_UNAVAILABLE", "invalid_request_error", "invalid_api_key", "authentication_error", "permission_error", "not_found_error", "request_too_large", "billing_error", "insufficient_quota", "MODEL_PROVIDER_AUTHENTICATION", "MODEL_PROVIDER_PERMISSION", "MODEL_PROVIDER_INVALID_REQUEST", "MODEL_PROVIDER_NOT_FOUND", "MODEL_PROVIDER_QUOTA_EXHAUSTED", "TooManyRequestsError", "ServiceUnavailableError", "RequestTimeoutError", "UnauthorizedError", "ForbiddenError", "InternalServerError", "BadRequestError", "NotFoundError", "AuthenticationError", "PermissionDeniedError", "RateLimitError"];
|
|
6
|
+
export interface ModelProviderErrorDiagnostic {
|
|
7
|
+
category: 'rate_limit' | 'server_error' | 'request_timeout' | 'client_error' | 'invalid_response';
|
|
8
|
+
fingerprint: string;
|
|
9
|
+
code?: typeof MODEL_PROVIDER_ERROR_CODES[number];
|
|
10
|
+
type?: typeof MODEL_PROVIDER_ERROR_TYPES[number];
|
|
11
|
+
status?: number;
|
|
12
|
+
}
|
|
3
13
|
export interface ModelFailureDiagnostic {
|
|
4
|
-
contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2';
|
|
14
|
+
contract: 'model-failure-diagnostic/v1' | 'model-failure-diagnostic/v2' | 'model-failure-diagnostic/v3';
|
|
5
15
|
protocol: 'openai-chat' | 'openai-responses' | 'anthropic-messages' | 'unknown';
|
|
6
16
|
phase: 'binding' | 'request' | 'headers' | 'http-error' | 'stream' | 'buffered';
|
|
7
17
|
code: typeof MODEL_FAILURE_CODES[number];
|
|
8
18
|
frameIndex?: number;
|
|
9
19
|
httpStatus?: number;
|
|
20
|
+
/** Observational only. Raw error messages, headers and bodies are excluded. */
|
|
21
|
+
providerError?: ModelProviderErrorDiagnostic;
|
|
10
22
|
/** Observed counters only, never a replacement for the sealed billable usage. */
|
|
11
23
|
usageConflict?: {
|
|
12
24
|
previousFrameIndex: number;
|
package/dist/model-failure.mjs
CHANGED
|
@@ -7,6 +7,21 @@ export const MODEL_FAILURE_CODES = [
|
|
|
7
7
|
'choice_invalid', 'delta_invalid', 'termination_conflict', 'framing_invalid', 'body_limit',
|
|
8
8
|
'body_encoding', 'transport_error', 'stream_timeout', 'stream_incomplete', 'tool_payload_invalid',
|
|
9
9
|
];
|
|
10
|
+
/** Closed provider identifiers only; arbitrary provider strings can contain credentials. */
|
|
11
|
+
export const MODEL_PROVIDER_ERROR_CODES = Object.freeze([
|
|
12
|
+
'rate_limit_error', 'rate_limit_exceeded', 'overloaded_error', 'server_error',
|
|
13
|
+
'api_error', 'service_unavailable_error', 'server_is_overloaded', 'timeout_error',
|
|
14
|
+
'MODEL_PROVIDER_RATE_LIMIT', 'MODEL_PROVIDER_UNAVAILABLE',
|
|
15
|
+
'invalid_request_error', 'invalid_api_key', 'authentication_error', 'permission_error',
|
|
16
|
+
'not_found_error', 'request_too_large', 'billing_error', 'insufficient_quota',
|
|
17
|
+
'MODEL_PROVIDER_AUTHENTICATION', 'MODEL_PROVIDER_PERMISSION', 'MODEL_PROVIDER_INVALID_REQUEST',
|
|
18
|
+
'MODEL_PROVIDER_NOT_FOUND', 'MODEL_PROVIDER_QUOTA_EXHAUSTED',
|
|
19
|
+
]);
|
|
20
|
+
export const MODEL_PROVIDER_ERROR_TYPES = Object.freeze([...MODEL_PROVIDER_ERROR_CODES,
|
|
21
|
+
'TooManyRequestsError', 'ServiceUnavailableError', 'RequestTimeoutError',
|
|
22
|
+
'UnauthorizedError', 'ForbiddenError', 'InternalServerError', 'BadRequestError',
|
|
23
|
+
'NotFoundError', 'AuthenticationError', 'PermissionDeniedError', 'RateLimitError',
|
|
24
|
+
]);
|
|
10
25
|
const usageCounterKeys = ['inputTokens', 'outputTokens', 'cachedInputTokens', 'reasoningTokens'];
|
|
11
26
|
function validUsageCounters(value) {
|
|
12
27
|
return Boolean(value && typeof value === 'object' && !Array.isArray(value)
|
|
@@ -17,9 +32,10 @@ function validUsageCounters(value) {
|
|
|
17
32
|
export function validateModelFailure(value) {
|
|
18
33
|
if (value === undefined)
|
|
19
34
|
return;
|
|
20
|
-
invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2'].includes(value.contract)
|
|
35
|
+
invariant(value && ['model-failure-diagnostic/v1', 'model-failure-diagnostic/v2', 'model-failure-diagnostic/v3'].includes(value.contract)
|
|
21
36
|
&& Object.keys(value).every(key => ['contract', 'protocol', 'phase', 'code', 'frameIndex', 'httpStatus',
|
|
22
|
-
...(value.contract === 'model-failure-diagnostic/v2' ? ['usageConflict'] : [])
|
|
37
|
+
...(value.contract === 'model-failure-diagnostic/v2' ? ['usageConflict'] : []),
|
|
38
|
+
...(value.contract === 'model-failure-diagnostic/v3' ? ['providerError'] : [])].includes(key))
|
|
23
39
|
&& ['openai-chat', 'openai-responses', 'anthropic-messages', 'unknown'].includes(value.protocol)
|
|
24
40
|
&& ['binding', 'request', 'headers', 'http-error', 'stream', 'buffered'].includes(value.phase)
|
|
25
41
|
&& MODEL_FAILURE_CODES.includes(value.code)
|
|
@@ -37,6 +53,17 @@ export function validateModelFailure(value) {
|
|
|
37
53
|
&& (conflict.previous.inputTokens !== conflict.reported.inputTokens
|
|
38
54
|
|| conflict.previous.outputTokens !== conflict.reported.outputTokens), 'invalid_model_failure_diagnostic');
|
|
39
55
|
}
|
|
56
|
+
if (value.contract === 'model-failure-diagnostic/v3') {
|
|
57
|
+
const provider = value.providerError;
|
|
58
|
+
invariant(value.code === 'provider_error' && ['openai-chat', 'openai-responses'].includes(value.protocol)
|
|
59
|
+
&& ['stream', 'buffered'].includes(value.phase) && provider && typeof provider === 'object'
|
|
60
|
+
&& !Array.isArray(provider) && Object.keys(provider).every(key => ['category', 'fingerprint', 'code', 'type', 'status'].includes(key))
|
|
61
|
+
&& ['rate_limit', 'server_error', 'request_timeout', 'client_error', 'invalid_response'].includes(provider.category)
|
|
62
|
+
&& typeof provider.fingerprint === 'string' && /^sha256:[0-9a-f]{64}$/.test(provider.fingerprint)
|
|
63
|
+
&& (provider.code === undefined || MODEL_PROVIDER_ERROR_CODES.includes(provider.code))
|
|
64
|
+
&& (provider.type === undefined || MODEL_PROVIDER_ERROR_TYPES.includes(provider.type))
|
|
65
|
+
&& (provider.status === undefined || Number.isInteger(provider.status) && provider.status >= 400 && provider.status <= 599), 'invalid_model_failure_diagnostic');
|
|
66
|
+
}
|
|
40
67
|
invariant(!value.code.startsWith('http_') || value.phase === 'http-error' && value.httpStatus !== undefined
|
|
41
68
|
&& (value.code === 'http_authentication' ? value.httpStatus === 401
|
|
42
69
|
: value.code === 'http_permission' ? value.httpStatus === 403
|
package/dist/model-json.mjs
CHANGED
|
@@ -6,18 +6,26 @@ export function parseModelJson(text) { return decodeJson(text, false, 256); }
|
|
|
6
6
|
export function parseNativeJson(text) { return decodeJson(text, true, 1024); }
|
|
7
7
|
function decodeJson(text, plainObjects, maxDepth) {
|
|
8
8
|
let position = 0;
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
// The strict structural decoder still owns duplicate keys, exact integers
|
|
10
|
+
// and depth. Scan text spans in the engine rather than visiting each code
|
|
11
|
+
// unit in JS: persisted code/log strings dominate long-session reads.
|
|
12
|
+
const stringToken = /"[^"\\]*(?:\\[\s\S][^"\\]*)*"/y;
|
|
13
|
+
const numberToken = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
|
|
14
|
+
function space() {
|
|
13
15
|
while (position < text.length) {
|
|
14
|
-
const
|
|
15
|
-
if (
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
return JSON.parse(text.slice(start, position));
|
|
16
|
+
const code = text.charCodeAt(position);
|
|
17
|
+
if (code !== 9 && code !== 10 && code !== 13 && code !== 32)
|
|
18
|
+
break;
|
|
19
|
+
position++;
|
|
19
20
|
}
|
|
20
|
-
|
|
21
|
+
}
|
|
22
|
+
function string() {
|
|
23
|
+
stringToken.lastIndex = position;
|
|
24
|
+
const token = stringToken.exec(text);
|
|
25
|
+
invariant(token, 'invalid_model_json');
|
|
26
|
+
position = stringToken.lastIndex;
|
|
27
|
+
// Native decoding validates escapes and rejects raw control characters.
|
|
28
|
+
return JSON.parse(token[0]);
|
|
21
29
|
}
|
|
22
30
|
function value(depth) {
|
|
23
31
|
invariant(depth <= maxDepth, 'model_json_nesting_exceeded');
|
|
@@ -74,9 +82,10 @@ function decodeJson(text, plainObjects, maxDepth) {
|
|
|
74
82
|
return result;
|
|
75
83
|
}
|
|
76
84
|
}
|
|
77
|
-
|
|
85
|
+
numberToken.lastIndex = position;
|
|
86
|
+
const number = numberToken.exec(text);
|
|
78
87
|
invariant(number, 'invalid_model_json');
|
|
79
|
-
position
|
|
88
|
+
position = numberToken.lastIndex;
|
|
80
89
|
const lexeme = number[0], result = Number(lexeme);
|
|
81
90
|
if (!/[.eE]/.test(lexeme) && !Number.isSafeInteger(result)) {
|
|
82
91
|
// Python's JSON decoder uses arbitrary precision int, with its default
|
package/dist/output-recovery.mjs
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import { responseContinuationPairs, responseContinuationPending, joinResponseContinuation } from './response-continuation.mjs';
|
|
1
|
+
import { responseBoundaryRecovery, responseContinuationPairs, responseContinuationPending, joinResponseContinuation } from './response-continuation.mjs';
|
|
2
2
|
import { canonical, copy, invariant } from './values.mjs';
|
|
3
3
|
import { contextMessageRef } from './context-planning.mjs';
|
|
4
4
|
/** Select from actual admission after the completed model claim, never the catalog. */
|
|
5
5
|
export function outputRecoveryMode(snapshot, config, toolsAvailable, result) {
|
|
6
|
-
if (config
|
|
6
|
+
if (responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text') {
|
|
7
|
+
// A provider length boundary identifies truncated text, not task completion.
|
|
8
|
+
// Preserve explicit sealed delivery, otherwise retain the admitted tools.
|
|
9
|
+
if (config.outputRecoveryPolicy === 'response-boundary/v3')
|
|
10
|
+
return responseContinuationPending(snapshot, config) || !toolsAvailable ? 'suffix' : 'task_resume';
|
|
7
11
|
if (responseContinuationPending(snapshot, config)
|
|
8
12
|
|| result?.textCommitVersion === 'provider-finished-text/v1' && result.outputBoundary === 'assistant-text/v1')
|
|
9
13
|
return 'suffix';
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import type { Message, RunConfiguration, RunSnapshot } from './contracts.mjs';
|
|
2
|
+
/** The output recovery strategy is versioned separately from the sealed v2
|
|
3
|
+
* text-fragment protocol. A v3 task may still own an explicit suffix chain. */
|
|
4
|
+
export declare function responseBoundaryRecovery(config: Pick<RunConfiguration, 'outputRecoveryPolicy'>): boolean;
|
|
5
|
+
export declare function responseScopedOutputRestarts(config: Pick<RunConfiguration, 'outputRestartPolicy'>): boolean;
|
|
2
6
|
export declare function responseContinuationPairs(messages: Message[], digest?: (value: unknown) => string): [number, number][];
|
|
3
7
|
/** This only narrows admission. Digest validation is required for assembly. */
|
|
4
8
|
export declare function responseContinuationPending(snapshot: RunSnapshot, config: RunConfiguration): boolean;
|
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
/** The output recovery strategy is versioned separately from the sealed v2
|
|
2
|
+
* text-fragment protocol. A v3 task may still own an explicit suffix chain. */
|
|
3
|
+
export function responseBoundaryRecovery(config) {
|
|
4
|
+
return config.outputRecoveryPolicy === 'response-boundary/v2' || config.outputRecoveryPolicy === 'response-boundary/v3';
|
|
5
|
+
}
|
|
6
|
+
export function responseScopedOutputRestarts(config) {
|
|
7
|
+
return config.outputRestartPolicy === 'per-response/v1' || config.outputRestartPolicy === 'per-response/v2';
|
|
8
|
+
}
|
|
1
9
|
/** Journaled Host controls may be staged between response fragments. Actual
|
|
2
10
|
* user input, tool observations and new assistant messages end the chain. */
|
|
3
11
|
function hostControl(message) {
|
|
@@ -26,7 +34,7 @@ export function responseContinuationPairs(messages, digest) {
|
|
|
26
34
|
}
|
|
27
35
|
/** This only narrows admission. Digest validation is required for assembly. */
|
|
28
36
|
export function responseContinuationPending(snapshot, config) {
|
|
29
|
-
return config
|
|
37
|
+
return responseBoundaryRecovery(config) && responseContinuationPairs(snapshot.messages).length > 0;
|
|
30
38
|
}
|
|
31
39
|
/** The v2 wire contract permits replay of exactly the unfinished final line.
|
|
32
40
|
* No complete line, fuzzy match, arbitrary suffix or raw receipt is removed. */
|
package/dist/store.mjs
CHANGED
|
@@ -358,7 +358,8 @@ export class TransactionalRunStore {
|
|
|
358
358
|
const command = parent.commands.find(row => !row.consumed && row.command.commandId === batch.consumedCommandId)?.command;
|
|
359
359
|
invariant(command, 'child_control_command_missing');
|
|
360
360
|
validateChildControlDelivery(parent, childRecord, command, delivery);
|
|
361
|
-
invariant(batch.events.some(event => event.kind === (command.kind === 'message_child' ? 'child.input_queued'
|
|
361
|
+
invariant(batch.events.some(event => event.kind === (command.kind === 'message_child' ? 'child.input_queued'
|
|
362
|
+
: command.kind === 'resume_child' ? 'child.resume_requested' : 'child.cancel_requested')
|
|
362
363
|
&& event.payload.commandId === command.commandId && event.payload.childRunId === target.runId), 'child_control_event_missing');
|
|
363
364
|
invariant(!previous || canonical(previous.command) === canonical(delivery.command), 'command_replay_conflict');
|
|
364
365
|
return { records: [updated.record, previous ? childRecord : { ...childRecord,
|
|
@@ -12,6 +12,14 @@ 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
|
+
/** Exact, scoped names are sufficient evidence to discover a definition, not to
|
|
16
|
+
* authorize its proposed operation. Promote only newly exposed schemas, bounded
|
|
17
|
+
* like a search result. The next model request must resubmit through the normal
|
|
18
|
+
* schema/permission/approval path. Omission preserves historical admission. */
|
|
19
|
+
export declare function discoverRejectedCalls(snapshot: RunSnapshot, config: RunConfiguration, calls: ToolCall[], tools: ToolDefinition[]): {
|
|
20
|
+
state: NonNullable<RunSnapshot['toolDiscovery']>;
|
|
21
|
+
names: string[];
|
|
22
|
+
} | null;
|
|
15
23
|
/** Describe a rejected model call using only the current, scoped execution
|
|
16
24
|
* catalog. Discovery is a suggested next call, never authority to dispatch the
|
|
17
25
|
* rejected operation. Historical events and frozen tool definitions stay intact. */
|
package/dist/tool-discovery.mjs
CHANGED
|
@@ -24,6 +24,8 @@ export function toolDiscoveryDefinitions() {
|
|
|
24
24
|
}
|
|
25
25
|
export function validateToolDiscovery(config) {
|
|
26
26
|
invariant(config.toolDiscoveryPolicy === undefined || config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_tool_discovery_policy');
|
|
27
|
+
invariant(config.toolAdmissionPolicy === undefined || config.toolAdmissionPolicy === 'discover-before-retry/v1'
|
|
28
|
+
&& config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_tool_admission_policy');
|
|
27
29
|
invariant(config.profile.providerToolSearchPolicy === undefined || config.profile.providerToolSearchPolicy === 'local-only/v1'
|
|
28
30
|
|| config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1'
|
|
29
31
|
&& config.profile.providerFamily === 'anthropic-messages' && config.toolDiscoveryPolicy === TOOL_DISCOVERY_POLICY, 'invalid_provider_tool_search_policy');
|
|
@@ -133,6 +135,48 @@ export function discoveredCallExposed(snapshot, config, call) {
|
|
|
133
135
|
|| config.profile.providerToolSearchPolicy === 'anthropic-deferred/v1'
|
|
134
136
|
&& snapshot.toolDiscovery?.discovered.includes(call.name) === true;
|
|
135
137
|
}
|
|
138
|
+
/** Exact, scoped names are sufficient evidence to discover a definition, not to
|
|
139
|
+
* authorize its proposed operation. Promote only newly exposed schemas, bounded
|
|
140
|
+
* like a search result. The next model request must resubmit through the normal
|
|
141
|
+
* schema/permission/approval path. Omission preserves historical admission. */
|
|
142
|
+
export function discoverRejectedCalls(snapshot, config, calls, tools) {
|
|
143
|
+
if (config.toolAdmissionPolicy !== 'discover-before-retry/v1' || !snapshot.toolDiscovery)
|
|
144
|
+
return null;
|
|
145
|
+
const wrapper = tools.find(tool => tool.name === DEFERRED_TOOL_CALL);
|
|
146
|
+
const names = [], definitions = [];
|
|
147
|
+
for (const call of calls) {
|
|
148
|
+
if (call.wireArgumentsInvalid || call.modelCallWrapper)
|
|
149
|
+
continue;
|
|
150
|
+
const wrapped = call.name === DEFERRED_TOOL_CALL;
|
|
151
|
+
if (wrapped && (!wrapper || toolInputRejection(wrapper, call)))
|
|
152
|
+
continue;
|
|
153
|
+
if (!wrapped && discoveredCallExposed(snapshot, config, call))
|
|
154
|
+
continue;
|
|
155
|
+
const name = wrapped ? String(call.arguments.name) : call.name;
|
|
156
|
+
if (names.includes(name) || snapshot.toolDiscovery.promoted.includes(name)
|
|
157
|
+
|| wrapped && snapshot.toolDiscovery.discovered.includes(name))
|
|
158
|
+
continue;
|
|
159
|
+
const target = tools.find(tool => tool.name === name && tool.discovery?.deferred
|
|
160
|
+
&& (config.contract.allowedToolNames === null || config.contract.allowedToolNames.includes(name)));
|
|
161
|
+
if (!target)
|
|
162
|
+
continue;
|
|
163
|
+
const entry = { name, description: target.description, parameters: copy(target.parameters) };
|
|
164
|
+
// Keep metadata discovery finite and no larger than the existing search
|
|
165
|
+
// model-view envelope. Oversized schemas must use the explicit search path.
|
|
166
|
+
const bytes = new TextEncoder().encode(canonical({ content: canonical({ definitions: [...definitions, entry] }),
|
|
167
|
+
media: [], additionalContexts: [] })).length;
|
|
168
|
+
if (bytes + 32 > config.limits.maxToolResultBytes)
|
|
169
|
+
continue;
|
|
170
|
+
names.push(name);
|
|
171
|
+
definitions.push(entry);
|
|
172
|
+
if (names.length === 20)
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
return names.length ? { names, state: {
|
|
176
|
+
discovered: [...new Set([...snapshot.toolDiscovery.discovered, ...names])],
|
|
177
|
+
promoted: [...snapshot.toolDiscovery.promoted, ...names],
|
|
178
|
+
} } : null;
|
|
179
|
+
}
|
|
136
180
|
/** Describe a rejected model call using only the current, scoped execution
|
|
137
181
|
* catalog. Discovery is a suggested next call, never authority to dispatch the
|
|
138
182
|
* rejected operation. Historical events and frozen tool definitions stay intact. */
|
package/dist/transitions.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { admitSteering } from './task-contract.mjs';
|
|
|
4
4
|
import { admitChildPromotion, unsettledChildren } from './child-runtime.mjs';
|
|
5
5
|
import { guidanceReason } from './guidance.mjs';
|
|
6
6
|
import { bindOperatorInput } from './anthropic-context.mjs';
|
|
7
|
+
import { APPROVAL_OUTCOME_POLICY, normalizeHostApprovalOutcome, approvalOutcomePauseReason } from './approval-outcome.mjs';
|
|
7
8
|
export function transition(snapshot, changes, facts = [], options = {}) {
|
|
8
9
|
invariant(!terminal(snapshot.phase), 'terminal_immutable');
|
|
9
10
|
const pendingGuidanceIds = changes.pendingGuidanceIds ?? snapshot.pendingGuidanceIds;
|
|
@@ -149,19 +150,38 @@ export function reduceCommand(snapshot, command, pending = null, bindings = {})
|
|
|
149
150
|
reason = 'not_paused';
|
|
150
151
|
else
|
|
151
152
|
changes = { phase: snapshot.resumePhase ?? 'preparing_context', resumePhase: null,
|
|
152
|
-
...(
|
|
153
|
+
...(snapshot.reason === 'output_budget_exhausted' && bindings.configuration?.outputRestartPolicy === 'per-response/v2'
|
|
154
|
+
? { reason: null, continuations: 0, outputRestarts: 0 } : {}),
|
|
155
|
+
...(bindings.configuration?.approvalOutcomePolicy === APPROVAL_OUTCOME_POLICY
|
|
156
|
+
&& ['approval_rejected', 'approval_cancelled', 'approval_unavailable'].includes(snapshot.reason ?? '') ? { reason: null } : {}),
|
|
157
|
+
...(['provider_unavailable', 'context_summary_unavailable', 'context_source_unavailable', 'child_paused']
|
|
158
|
+
.includes(snapshot.reason ?? '') ? { reason: null } : {}) };
|
|
153
159
|
break;
|
|
154
160
|
case 'submit_interaction': {
|
|
155
161
|
const pending = snapshot.pendingInteraction;
|
|
162
|
+
const hasOutcome = Object.hasOwn(command.payload, 'approvalOutcome');
|
|
163
|
+
const approvalOutcome = normalizeHostApprovalOutcome(command.payload.approvalOutcome);
|
|
156
164
|
if (snapshot.phase !== 'awaiting_interaction' || !pending || command.payload.interactionId !== pending.interactionId
|
|
157
165
|
|| command.payload.decision !== 'allow' && command.payload.decision !== 'deny')
|
|
158
166
|
reason = 'interaction_mismatch';
|
|
167
|
+
else if (hasOutcome && (bindings.configuration?.approvalOutcomePolicy !== APPROVAL_OUTCOME_POLICY
|
|
168
|
+
|| approvalOutcome !== command.payload.approvalOutcome
|
|
169
|
+
|| (approvalOutcome === 'allowed-once') !== (command.payload.decision === 'allow')))
|
|
170
|
+
reason = 'interaction_outcome_mismatch';
|
|
159
171
|
else {
|
|
160
172
|
changes = { phase: snapshot.childApproval ? snapshot.resumePhase ?? 'preparing_context' : 'executing_tools',
|
|
161
173
|
...(snapshot.childApproval ? { resumePhase: null, childLifecycleCursor: null } : {}), pendingInteraction: null,
|
|
162
174
|
interaction: pending.approvalPolicy === 'durable-preflight/v1' ? null : { interactionId: pending.hostInteractionId, callId: pending.callId, decision: command.payload.decision,
|
|
175
|
+
...(hasOutcome ? { approvalOutcome } : {}),
|
|
163
176
|
...(snapshot.planMode && typeof command.payload.feedback === 'string' ? { feedback: command.payload.feedback } : {}) } };
|
|
164
|
-
|
|
177
|
+
// One human answer pauses the interactive owner once. Its children
|
|
178
|
+
// receive the same denied decision after that owner is explicitly
|
|
179
|
+
// resumed; no second pause or implicit tool permission is introduced.
|
|
180
|
+
const pauseReason = hasOutcome && !bindings.configuration?.childOwnerBinding ? approvalOutcomePauseReason(approvalOutcome) : null;
|
|
181
|
+
if (pauseReason)
|
|
182
|
+
Object.assign(changes, { resumePhase: changes.phase, phase: 'paused', reason: pauseReason, outcome: null });
|
|
183
|
+
facts.push({ kind: 'approval.resolved', payload: { interactionId: pending.interactionId, callId: pending.callId, decision: command.payload.decision,
|
|
184
|
+
...(hasOutcome ? { approvalOutcome } : {}) } });
|
|
165
185
|
}
|
|
166
186
|
break;
|
|
167
187
|
}
|
package/package.json
CHANGED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Host answers are not interchangeable. Unknown answers never grant access.
|
|
2
|
+
* Session permissions are a separate scoped Host authority, not an outcome a
|
|
3
|
+
* model or tool may claim in this vocabulary. */
|
|
4
|
+
export type HostApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';
|
|
5
|
+
export const APPROVAL_OUTCOME_POLICY = 'owner-outcome/v1' as const;
|
|
6
|
+
export function normalizeHostApprovalOutcome(value: unknown): HostApprovalOutcome {
|
|
7
|
+
return value === 'allowed-once' || value === 'rejected' || value === 'cancelled' ? value : 'unavailable';
|
|
8
|
+
}
|
|
9
|
+
export function approvalOutcomePauseReason(value: HostApprovalOutcome): string | null {
|
|
10
|
+
return value === 'rejected' ? 'approval_rejected' : value === 'cancelled' ? 'approval_cancelled'
|
|
11
|
+
: value === 'unavailable' ? 'approval_unavailable' : null;
|
|
12
|
+
}
|
|
@@ -4,6 +4,18 @@ import { copy, invariant } from './values.mjs';
|
|
|
4
4
|
export const BACKGROUND_COMMAND_CONTRACT = 'agentkit.background-command-observation/v1' as const;
|
|
5
5
|
export interface BackgroundCommandRef { taskId: string; sourceRunId: string; operationKey: string }
|
|
6
6
|
export interface BackgroundCommandState { ref: BackgroundCommandRef; notified: boolean }
|
|
7
|
+
/** Bound a read view without retiring any durable command ownership. Prefer
|
|
8
|
+
* commands whose completion has not been accounted for, then recent history. */
|
|
9
|
+
export function projectBackgroundCommands(rows: readonly BackgroundCommandState[], limit: number,
|
|
10
|
+
recentLimit = limit): BackgroundCommandState[] {
|
|
11
|
+
const outstanding: number[] = [], recent: number[] = [];
|
|
12
|
+
for (let index = rows.length - 1; index >= 0 && outstanding.length < limit; index--) {
|
|
13
|
+
if (rows[index]!.notified === true) {
|
|
14
|
+
if (recent.length < recentLimit) recent.push(index);
|
|
15
|
+
} else outstanding.push(index);
|
|
16
|
+
}
|
|
17
|
+
return [...outstanding, ...recent.slice(0, limit - outstanding.length)].sort((a, b) => a - b).map(index => rows[index]!);
|
|
18
|
+
}
|
|
7
19
|
export interface BackgroundCommandRequest extends Omit<PortContext, 'signal'> {
|
|
8
20
|
schemaVersion: typeof BACKGROUND_COMMAND_CONTRACT; cursor: string; refs: BackgroundCommandRef[];
|
|
9
21
|
}
|
|
@@ -5,6 +5,7 @@ import { backgroundCommandObservation, backgroundCommandRef } from './background
|
|
|
5
5
|
import { initialSnapshot, configure } from './configuration.mjs';
|
|
6
6
|
import { projectSessionHistory } from './history.mjs';
|
|
7
7
|
import { canonical, copy, invariant, NativeError, isNativeError, scopeKey } from './values.mjs';
|
|
8
|
+
import { responseScopedOutputRestarts } from './response-continuation.mjs';
|
|
8
9
|
|
|
9
10
|
export const BACKGROUND_NOTIFICATION_ADMISSION = 'agentkit.background-notification-admission/v1' as const;
|
|
10
11
|
type Digest = (value: unknown) => string;
|
|
@@ -161,12 +162,12 @@ export async function admitBackgroundNotification({ store, scope, sourceRunId, t
|
|
|
161
162
|
invariant((limits.maxModelCalls === null || limits.maxModelCalls > 0) && (limits.maxWallMs === null || limits.maxWallMs > 0),
|
|
162
163
|
'background_notification_budget_exhausted');
|
|
163
164
|
limits.maxRepairs = Math.max(0, limits.maxRepairs - used.repairs);
|
|
164
|
-
if (source.configuration
|
|
165
|
+
if (!responseScopedOutputRestarts(source.configuration))
|
|
165
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: source.configuration
|
|
170
|
+
profile: { ...source.configuration.profile, maxContinuations: responseScopedOutputRestarts(source.configuration)
|
|
170
171
|
? source.configuration.profile.maxContinuations : Math.max(0, source.configuration.profile.maxContinuations - used.continuations) } });
|
|
171
172
|
const snapshot = initialSnapshot({ scope: fixedScope, runId, sessionId: source.snapshot.sessionId,
|
|
172
173
|
turnId: runId, buildId: source.snapshot.buildId, parentRunId: head.runId, taskChainId: source.snapshot.taskChainId }, configuration, digest(configuration));
|
package/src/child-contract.mts
CHANGED
|
@@ -40,6 +40,8 @@ export interface ChildTaskControlState {
|
|
|
40
40
|
childRunId: string; sessionId: string; role: string; phase: string;
|
|
41
41
|
goalRevision: number;
|
|
42
42
|
delivery: 'foreground' | 'background'; canPromote: boolean; canCancel: boolean; canSendInput: boolean;
|
|
43
|
+
/** Explicit Host control, not a model tool or implicit side effect of guidance. */
|
|
44
|
+
canResume?: boolean;
|
|
43
45
|
}
|
|
44
46
|
export interface ChildControlTarget {
|
|
45
47
|
scope: RunScope; runId: string; configurationDigest: string; parentOperationKey: string; parentToolCallId: string;
|
|
@@ -59,7 +61,9 @@ export interface ChildLifecyclePort {
|
|
|
59
61
|
/** Read already sealed child facts after a lost parent claim. Never starts, approves or cancels execution. */
|
|
60
62
|
reconcile?(request: ChildLifecycleRequest): Promise<ChildLifecycleResult | null>;
|
|
61
63
|
readyChildren?(request: ChildReadyRequest & { signal: AbortSignal }): Promise<{ childRunIds: string[] }>;
|
|
62
|
-
/** Host
|
|
64
|
+
/** Dispose Host ownership without canceling an idle, resumable parent or its children. */
|
|
65
|
+
closeRun?(request: { scope: RunScope; runId: string }): Promise<void>;
|
|
66
|
+
/** Release terminal or explicitly canceled work, canceling any live descendants. */
|
|
63
67
|
releaseRun?(request: { scope: RunScope; runId: string }): Promise<void>;
|
|
64
68
|
interruptedReceipts?(request: { scope: RunScope; runId: string; parentOperationKey: string }): Promise<{
|
|
65
69
|
parentOperationKey: string; parentToolCallId: string; result: ToolResult;
|
package/src/child-control.mts
CHANGED
|
@@ -4,16 +4,26 @@ import { terminal } from './contracts.mjs';
|
|
|
4
4
|
import { CHILD_OWNER_CONTRACT } from './child-contract.mjs';
|
|
5
5
|
import { canonical, copy, invariant } from './values.mjs';
|
|
6
6
|
|
|
7
|
+
/** An explicit control resumes a known pause, not an uncertain effect. This
|
|
8
|
+
* applies to output, provider and context pauses without changing their
|
|
9
|
+
* frozen policies, total budgets or required permission decisions. */
|
|
10
|
+
export function childResumeAllowed(snapshot: RunSnapshot): boolean {
|
|
11
|
+
return snapshot.phase === 'paused' && snapshot.pendingIntent === null
|
|
12
|
+
&& snapshot.toolReconciliation == null && snapshot.resumePhase !== 'awaiting_reconciliation'
|
|
13
|
+
&& !['effect_outcome_unknown', 'recovery_retry_exhausted', 'browser_session_unavailable'].includes(snapshot.reason ?? '');
|
|
14
|
+
}
|
|
15
|
+
|
|
7
16
|
export function childControlDelivery(parent: RunSnapshot, command: RunCommand, target: ChildControlTarget): ChildControlDelivery {
|
|
8
17
|
const send = command.kind === 'message_child', input = command.payload;
|
|
9
|
-
invariant(['message_child', 'cancel_child'].includes(command.kind)
|
|
18
|
+
invariant(['message_child', 'cancel_child', 'resume_child'].includes(command.kind)
|
|
10
19
|
&& typeof input.childRunId === 'string' && input.childRunId.trim() && input.childRunId.length <= 256
|
|
11
20
|
&& Object.keys(input).every(key => (send ? ['childRunId', 'text', 'expectedGoalRevision'] : ['childRunId']).includes(key))
|
|
12
21
|
&& (!send || typeof input.text === 'string' && input.text.trim() && input.text.length <= 32768
|
|
13
22
|
&& Number.isSafeInteger(input.expectedGoalRevision) && (input.expectedGoalRevision as number) >= 0), 'invalid_child_control');
|
|
14
23
|
return { target: copy(target), command: {
|
|
15
24
|
commandId: `child-control:${canonical([parent.scope, parent.runId, command.commandId])}`,
|
|
16
|
-
kind: send ? 'guide' : '
|
|
25
|
+
kind: send ? 'guide' : command.kind === 'resume_child' ? 'resume' : 'cancel',
|
|
26
|
+
payload: send ? { text: input.text!, expectedGoalRevision: input.expectedGoalRevision! } : {},
|
|
17
27
|
} };
|
|
18
28
|
}
|
|
19
29
|
|
|
@@ -52,6 +62,10 @@ export function validateChildControlDelivery(parent: StoredRun, child: StoredRun
|
|
|
52
62
|
'child_control_result_unknown');
|
|
53
63
|
const preempts = (record: StoredRun, kinds: string[]) => record.commands.some(row => !row.consumed && kinds.includes(row.command.kind));
|
|
54
64
|
invariant(!preempts(parent, ['cancel', 'policy_revoked', 'steer']), 'parent_control_preempts_child_control');
|
|
65
|
+
if (command.kind === 'resume_child') {
|
|
66
|
+
invariant(childResumeAllowed(c)
|
|
67
|
+
&& !preempts(child, ['cancel', 'policy_revoked', 'steer', 'resume']), 'child_control_unavailable');
|
|
68
|
+
}
|
|
55
69
|
if (command.kind === 'message_child') {
|
|
56
70
|
invariant(!preempts(child, ['cancel', 'policy_revoked', 'steer']), 'child_control_preempts_input');
|
|
57
71
|
invariant(command.payload.expectedGoalRevision === c.goalRevision, 'stale_child_goal_revision');
|
package/src/child-runtime.mts
CHANGED
|
@@ -132,7 +132,7 @@ export function reduceChildLifecycle(snapshot: RunSnapshot, config: RunConfigura
|
|
|
132
132
|
const owned = request.reservations.find(item => item.childRunId === child.runId);
|
|
133
133
|
invariant(owned && owned.parentOperationKey === child.operationKey && owned.parentToolCallId === child.callId
|
|
134
134
|
&& child.reservedModelCalls === owned.maxModelCalls && child.reservedToolCalls === owned.maxToolCalls
|
|
135
|
-
&& ['prepared', 'running', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
|
|
135
|
+
&& ['prepared', 'running', 'paused', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
|
|
136
136
|
&& (settled.includes(child.runId) ? ['completed', 'failed', 'canceled'].includes(child.state)
|
|
137
137
|
: !['completed', 'failed', 'canceled'].includes(child.state))
|
|
138
138
|
&& child.usage.modelCalls <= owned.maxModelCalls && child.usage.toolCalls <= owned.maxToolCalls
|
|
@@ -152,6 +152,12 @@ export function reduceChildLifecycle(snapshot: RunSnapshot, config: RunConfigura
|
|
|
152
152
|
updated.pendingInteraction = { interactionId: `${request.operationKey}:approval`, hostInteractionId: `native-child-${digest(approval)}`,
|
|
153
153
|
callId: approval.toolCall.callId, operationKey: request.operationKey };
|
|
154
154
|
updated.interaction = null;
|
|
155
|
+
} else if (!result.errorCode && request.action === 'wait' && result.children?.some(child => child.state === 'paused'
|
|
156
|
+
&& pending.includes(child.runId) && (!request.waitForChildRunIds || request.waitForChildRunIds.includes(child.runId)))) {
|
|
157
|
+
// A joined child can still own valid results and an unspent reservation.
|
|
158
|
+
// Preserve that original run until an explicit control resumes or cancels
|
|
159
|
+
// it. Background polls do not block the parent's independent work.
|
|
160
|
+
updated.resumePhase = updated.phase; updated.phase = 'paused'; updated.reason = 'child_paused'; updated.outcome = null;
|
|
155
161
|
} else if (result.errorCode || !observationOnly && request.action !== 'poll'
|
|
156
162
|
&& pending.some(id => !request.waitForChildRunIds || request.waitForChildRunIds.includes(id))) {
|
|
157
163
|
updated.phase = 'finalizing'; updated.candidate = null; updated.verification = null;
|
package/src/configuration.mts
CHANGED
|
@@ -37,9 +37,11 @@ export interface ConfigurationInput {
|
|
|
37
37
|
sourceReadPolicy?: RunConfiguration['sourceReadPolicy'];
|
|
38
38
|
outputRecoveryPolicy?: RunConfiguration['outputRecoveryPolicy'];
|
|
39
39
|
outputRestartPolicy?: RunConfiguration['outputRestartPolicy'];
|
|
40
|
+
approvalOutcomePolicy?: RunConfiguration['approvalOutcomePolicy'];
|
|
40
41
|
providerRecoveryPolicy?: RunConfiguration['providerRecoveryPolicy'];
|
|
41
42
|
toolErrorRecoveryPolicy?: RunConfiguration['toolErrorRecoveryPolicy'];
|
|
42
43
|
toolDiscoveryPolicy?: RunConfiguration['toolDiscoveryPolicy'];
|
|
44
|
+
toolAdmissionPolicy?: RunConfiguration['toolAdmissionPolicy'];
|
|
43
45
|
todoPolicy?: RunConfiguration['todoPolicy'];
|
|
44
46
|
toolExecutionPolicy?: RunConfiguration['toolExecutionPolicy'];
|
|
45
47
|
childTaskPolicy?: RunConfiguration['childTaskPolicy'];
|
|
@@ -98,9 +100,11 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
98
100
|
...(input.sourceReadPolicy === undefined ? {} : { sourceReadPolicy: input.sourceReadPolicy }),
|
|
99
101
|
...(input.outputRecoveryPolicy === undefined ? {} : { outputRecoveryPolicy: input.outputRecoveryPolicy }),
|
|
100
102
|
...(input.outputRestartPolicy === undefined ? {} : { outputRestartPolicy: input.outputRestartPolicy }),
|
|
103
|
+
...(input.approvalOutcomePolicy === undefined ? {} : { approvalOutcomePolicy: input.approvalOutcomePolicy }),
|
|
101
104
|
...(input.providerRecoveryPolicy === undefined ? {} : { providerRecoveryPolicy: input.providerRecoveryPolicy }),
|
|
102
105
|
...(input.toolErrorRecoveryPolicy === undefined ? {} : { toolErrorRecoveryPolicy: input.toolErrorRecoveryPolicy }),
|
|
103
106
|
...(input.toolDiscoveryPolicy === undefined ? {} : { toolDiscoveryPolicy: input.toolDiscoveryPolicy }),
|
|
107
|
+
...(input.toolAdmissionPolicy === undefined ? {} : { toolAdmissionPolicy: input.toolAdmissionPolicy }),
|
|
104
108
|
...(input.todoPolicy === undefined ? {} : { todoPolicy: input.todoPolicy }),
|
|
105
109
|
...(input.toolExecutionPolicy === undefined ? {} : { toolExecutionPolicy: input.toolExecutionPolicy }),
|
|
106
110
|
...(input.childTaskPolicy === undefined ? {} : { childTaskPolicy: input.childTaskPolicy }),
|
|
@@ -155,9 +159,10 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
155
159
|
&& typeof config.hostRecoveryBinding === 'object' && !Array.isArray(config.hostRecoveryBinding), 'invalid_host_recovery_binding');
|
|
156
160
|
invariant(config.guidancePolicy == null || config.guidancePolicy === 'boundary-guide/v1', 'invalid_guidance_policy');
|
|
157
161
|
invariant(config.inputPolicy === undefined || config.inputPolicy === 'before-first-model/v1', 'invalid_input_policy');
|
|
158
|
-
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
159
|
-
invariant(config.outputRestartPolicy === undefined ||
|
|
160
|
-
&&
|
|
162
|
+
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
163
|
+
invariant(config.outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(config.outputRestartPolicy)
|
|
164
|
+
&& ['response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy ?? ''), 'invalid_output_restart_policy');
|
|
165
|
+
invariant(config.approvalOutcomePolicy === undefined || config.approvalOutcomePolicy === 'owner-outcome/v1', 'invalid_approval_outcome_policy');
|
|
161
166
|
invariant(config.providerRecoveryPolicy == null || config.providerRecoveryPolicy === 'provider-recovery/v2', 'invalid_provider_recovery_policy');
|
|
162
167
|
invariant(config.toolExecutionPolicy === undefined || config.toolExecutionPolicy === 'owner-execution/v1', 'invalid_tool_execution_policy');
|
|
163
168
|
invariant(config.toolErrorRecoveryPolicy == null || ['diagnose-before-repeat/v1', 'diagnose-before-repeat/v2'].includes(config.toolErrorRecoveryPolicy), 'invalid_tool_error_recovery_policy');
|
|
@@ -244,7 +249,7 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
244
249
|
const policy = profile.providerCompatibilityPolicy;
|
|
245
250
|
invariant(policy !== null && typeof policy === 'object' && !Array.isArray(policy)
|
|
246
251
|
&& Object.keys(policy).every(key => ['contract', 'rule'].includes(key))
|
|
247
|
-
&& ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3'].includes(policy.contract)
|
|
252
|
+
&& ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)
|
|
248
253
|
&& ['auto', 'permissive', 'openai', 'strict-openai', 'cerebras', 'groq', 'deepseek',
|
|
249
254
|
'zai', 'kspmas-gateway', 'moonshot', 'mimo'].includes(policy.rule), 'invalid_provider_compatibility_policy');
|
|
250
255
|
}
|
package/src/context-planning.mts
CHANGED
|
@@ -11,9 +11,10 @@ import { sourceWorkingSetGroup } from './source-working-set-group.mjs';
|
|
|
11
11
|
import { sourceReuseProjector } from './context-source-reuse.mjs';
|
|
12
12
|
import { defaultToolPruningThreshold, projectOldToolResults, toolPruningIdleElapsed } from './context-microcompact.mjs';
|
|
13
13
|
import { summaryContinuityInstructions, validSummaryContinuity } from './summary-continuity.mjs';
|
|
14
|
-
import { responseContinuationPairs } from './response-continuation.mjs';
|
|
14
|
+
import { responseBoundaryRecovery, responseContinuationPairs } from './response-continuation.mjs';
|
|
15
15
|
import { verificationModelView } from './model-surface.mjs';
|
|
16
16
|
import { currentInstructionContribution } from './context-contributions.mjs';
|
|
17
|
+
import { projectBackgroundCommands } from './background-contract.mjs';
|
|
17
18
|
|
|
18
19
|
export interface ContextCounters {
|
|
19
20
|
/** Clock observation for this journaled context effect; never recomputed during counting. */
|
|
@@ -46,6 +47,7 @@ export function contextContinuity(snapshot: RunSnapshot, config: RunConfiguratio
|
|
|
46
47
|
const scopedEvidence = config.modelSurface?.verificationProjection === 'readable-evidence/v1';
|
|
47
48
|
const canReadArtifacts = config.artifactPolicy === 'runtime-artifacts/v1' && config.tools.some(tool => tool.name === 'ArtifactRead'
|
|
48
49
|
&& (config.contract.allowedToolNames === null || config.contract.allowedToolNames.includes(tool.name)));
|
|
50
|
+
const commands = projectBackgroundCommands(snapshot.backgroundCommands, 32, 8);
|
|
49
51
|
return copy({ schemaVersion: scopedEvidence ? 'agentkit.native-context-continuity/v2' : 'agentkit.native-context-continuity/v1', authority: 'host_record', goal: snapshot.goal,
|
|
50
52
|
...(snapshot.todos ? { todos: snapshot.todos.items, todoRevision: snapshot.todos.revision } : {}),
|
|
51
53
|
...(snapshot.planMode ? { planMode: snapshot.planMode, planModeGuidance: policies.forRun(config).planning.planModeGuidance(snapshot, config) } : {}),
|
|
@@ -61,7 +63,8 @@ export function contextContinuity(snapshot: RunSnapshot, config: RunConfiguratio
|
|
|
61
63
|
childBudgetReservations: snapshot.childBudgetReservations ?? [], childRunIds: snapshot.childRunIds ?? [],
|
|
62
64
|
childApproval: snapshot.childApproval ?? null,
|
|
63
65
|
children: snapshot.children.map(child => ({ runId: child.runId, state: child.state, notified: child.notified })),
|
|
64
|
-
backgroundCommands:
|
|
66
|
+
backgroundCommands: commands.map(command => ({ ...command.ref, notified: command.notified })),
|
|
67
|
+
...(commands.length < snapshot.backgroundCommands.length ? { omittedBackgroundCommands: snapshot.backgroundCommands.length - commands.length } : {}),
|
|
65
68
|
verification: scopedEvidence ? verificationModelView(snapshot.verification,
|
|
66
69
|
canReadArtifacts ? snapshot.artifactRefs : []) : snapshot.verification,
|
|
67
70
|
hostBindingDigest: config.hostBindingDigest,
|
|
@@ -118,7 +121,7 @@ function groupsOf(messages: Message[], indexes: number[]): number[][] {
|
|
|
118
121
|
}
|
|
119
122
|
function mandatoryIndexes(snapshot: RunSnapshot, groups: number[][], config: RunConfiguration): Set<number> {
|
|
120
123
|
const mandatory = new Set<number>(), messages = snapshot.messages;
|
|
121
|
-
if (config
|
|
124
|
+
if (responseBoundaryRecovery(config))
|
|
122
125
|
for (const pair of responseContinuationPairs(messages)) for (const index of pair) mandatory.add(index);
|
|
123
126
|
// The next inference must observe the just-completed batch, but that must
|
|
124
127
|
// not exempt all older history from its soft budget on every tool turn.
|