@kingsoftcloud/agentkit-harness-core 0.0.14 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/approval-outcome.d.mts +7 -0
- package/dist/approval-outcome.mjs +8 -0
- package/dist/background-notification.mjs +3 -2
- package/dist/child-contract.d.mts +2 -0
- package/dist/child-control.d.mts +4 -0
- package/dist/child-control.mjs +15 -2
- package/dist/child-runtime.mjs +11 -1
- package/dist/configuration.d.mts +2 -0
- package/dist/configuration.mjs +7 -4
- package/dist/context-planning.mjs +2 -2
- 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 +21 -2
- package/package.json +1 -1
- package/src/approval-outcome.mts +12 -0
- package/src/background-notification.mts +3 -2
- package/src/child-contract.mts +2 -0
- package/src/child-control.mts +16 -2
- package/src/child-runtime.mts +7 -1
- package/src/configuration.mts +9 -4
- package/src/context-planning.mts +2 -2
- 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 +19 -2
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Host answers are not interchangeable. Unknown answers never grant access.
|
|
2
|
+
* Session permissions are a separate scoped Host authority, not an outcome a
|
|
3
|
+
* model or tool may claim in this vocabulary. */
|
|
4
|
+
export type HostApprovalOutcome = 'allowed-once' | 'rejected' | 'cancelled' | 'unavailable';
|
|
5
|
+
export declare const APPROVAL_OUTCOME_POLICY: "owner-outcome/v1";
|
|
6
|
+
export declare function normalizeHostApprovalOutcome(value: unknown): HostApprovalOutcome;
|
|
7
|
+
export declare function approvalOutcomePauseReason(value: HostApprovalOutcome): string | null;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const APPROVAL_OUTCOME_POLICY = 'owner-outcome/v1';
|
|
2
|
+
export function normalizeHostApprovalOutcome(value) {
|
|
3
|
+
return value === 'allowed-once' || value === 'rejected' || value === 'cancelled' ? value : 'unavailable';
|
|
4
|
+
}
|
|
5
|
+
export function approvalOutcomePauseReason(value) {
|
|
6
|
+
return value === 'rejected' ? 'approval_rejected' : value === 'cancelled' ? 'approval_cancelled'
|
|
7
|
+
: value === 'unavailable' ? 'approval_unavailable' : null;
|
|
8
|
+
}
|
|
@@ -3,6 +3,7 @@ import { backgroundCommandObservation, backgroundCommandRef } from './background
|
|
|
3
3
|
import { initialSnapshot, configure } from './configuration.mjs';
|
|
4
4
|
import { projectSessionHistory } from './history.mjs';
|
|
5
5
|
import { canonical, copy, invariant, NativeError, isNativeError, scopeKey } from './values.mjs';
|
|
6
|
+
import { responseScopedOutputRestarts } from './response-continuation.mjs';
|
|
6
7
|
export const BACKGROUND_NOTIFICATION_ADMISSION = 'agentkit.background-notification-admission/v1';
|
|
7
8
|
function assertSettled(record) {
|
|
8
9
|
const snapshot = record.snapshot;
|
|
@@ -162,12 +163,12 @@ export async function admitBackgroundNotification({ store, scope, sourceRunId, t
|
|
|
162
163
|
limits.maxWallMs -= used.wall + elapsed;
|
|
163
164
|
invariant((limits.maxModelCalls === null || limits.maxModelCalls > 0) && (limits.maxWallMs === null || limits.maxWallMs > 0), 'background_notification_budget_exhausted');
|
|
164
165
|
limits.maxRepairs = Math.max(0, limits.maxRepairs - used.repairs);
|
|
165
|
-
if (source.configuration
|
|
166
|
+
if (!responseScopedOutputRestarts(source.configuration))
|
|
166
167
|
limits.maxOutputRestarts = Math.max(0, limits.maxOutputRestarts - used.outputRestarts);
|
|
167
168
|
limits.maxRecoveryRetries = Math.max(0, limits.maxRecoveryRetries - used.recovery);
|
|
168
169
|
const contract = copy(head.taskContract ?? parent.configuration.contract);
|
|
169
170
|
const configuration = configure({ ...copy(source.configuration), contract, limits, inputMessages: null,
|
|
170
|
-
profile: { ...source.configuration.profile, maxContinuations: source.configuration
|
|
171
|
+
profile: { ...source.configuration.profile, maxContinuations: responseScopedOutputRestarts(source.configuration)
|
|
171
172
|
? source.configuration.profile.maxContinuations : Math.max(0, source.configuration.profile.maxContinuations - used.continuations) } });
|
|
172
173
|
const snapshot = initialSnapshot({ scope: fixedScope, runId, sessionId: source.snapshot.sessionId,
|
|
173
174
|
turnId: runId, buildId: source.snapshot.buildId, parentRunId: head.runId, taskChainId: source.snapshot.taskChainId }, configuration, digest(configuration));
|
|
@@ -67,6 +67,8 @@ export interface ChildTaskControlState {
|
|
|
67
67
|
canPromote: boolean;
|
|
68
68
|
canCancel: boolean;
|
|
69
69
|
canSendInput: boolean;
|
|
70
|
+
/** Explicit Host control, not a model tool or implicit side effect of guidance. */
|
|
71
|
+
canResume?: boolean;
|
|
70
72
|
}
|
|
71
73
|
export interface ChildControlTarget {
|
|
72
74
|
scope: RunScope;
|
package/dist/child-control.d.mts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { ChildControlDelivery, ChildControlTarget } from './child-contract.mjs';
|
|
2
2
|
import type { RunCommand, RunSnapshot, StoredRun } from './contracts.mjs';
|
|
3
|
+
/** An explicit control resumes a known pause, not an uncertain effect. This
|
|
4
|
+
* applies to output, provider and context pauses without changing their
|
|
5
|
+
* frozen policies, total budgets or required permission decisions. */
|
|
6
|
+
export declare function childResumeAllowed(snapshot: RunSnapshot): boolean;
|
|
3
7
|
export declare function childControlDelivery(parent: RunSnapshot, command: RunCommand, target: ChildControlTarget): ChildControlDelivery;
|
|
4
8
|
/** Runs under the Store's multi-record transaction, before either ledger changes. */
|
|
5
9
|
export declare function validateChildControlDelivery(parent: StoredRun, child: StoredRun, command: RunCommand, delivery: ChildControlDelivery): void;
|
package/dist/child-control.mjs
CHANGED
|
@@ -1,16 +1,25 @@
|
|
|
1
1
|
import { terminal } from './contracts.mjs';
|
|
2
2
|
import { CHILD_OWNER_CONTRACT } from './child-contract.mjs';
|
|
3
3
|
import { canonical, copy, invariant } from './values.mjs';
|
|
4
|
+
/** An explicit control resumes a known pause, not an uncertain effect. This
|
|
5
|
+
* applies to output, provider and context pauses without changing their
|
|
6
|
+
* frozen policies, total budgets or required permission decisions. */
|
|
7
|
+
export function childResumeAllowed(snapshot) {
|
|
8
|
+
return snapshot.phase === 'paused' && snapshot.pendingIntent === null
|
|
9
|
+
&& snapshot.toolReconciliation == null && snapshot.resumePhase !== 'awaiting_reconciliation'
|
|
10
|
+
&& !['effect_outcome_unknown', 'recovery_retry_exhausted', 'browser_session_unavailable'].includes(snapshot.reason ?? '');
|
|
11
|
+
}
|
|
4
12
|
export function childControlDelivery(parent, command, target) {
|
|
5
13
|
const send = command.kind === 'message_child', input = command.payload;
|
|
6
|
-
invariant(['message_child', 'cancel_child'].includes(command.kind)
|
|
14
|
+
invariant(['message_child', 'cancel_child', 'resume_child'].includes(command.kind)
|
|
7
15
|
&& typeof input.childRunId === 'string' && input.childRunId.trim() && input.childRunId.length <= 256
|
|
8
16
|
&& Object.keys(input).every(key => (send ? ['childRunId', 'text', 'expectedGoalRevision'] : ['childRunId']).includes(key))
|
|
9
17
|
&& (!send || typeof input.text === 'string' && input.text.trim() && input.text.length <= 32768
|
|
10
18
|
&& Number.isSafeInteger(input.expectedGoalRevision) && input.expectedGoalRevision >= 0), 'invalid_child_control');
|
|
11
19
|
return { target: copy(target), command: {
|
|
12
20
|
commandId: `child-control:${canonical([parent.scope, parent.runId, command.commandId])}`,
|
|
13
|
-
kind: send ? 'guide' : '
|
|
21
|
+
kind: send ? 'guide' : command.kind === 'resume_child' ? 'resume' : 'cancel',
|
|
22
|
+
payload: send ? { text: input.text, expectedGoalRevision: input.expectedGoalRevision } : {},
|
|
14
23
|
} };
|
|
15
24
|
}
|
|
16
25
|
/** Runs under the Store's multi-record transaction, before either ledger changes. */
|
|
@@ -46,6 +55,10 @@ export function validateChildControlDelivery(parent, child, command, delivery) {
|
|
|
46
55
|
&& !(receipt.result.retryScheduled === true && ['safe-read/v1', 'workspace-observation/v1'].includes(String(receipt.result.recoveryPolicy)))), 'child_control_result_unknown');
|
|
47
56
|
const preempts = (record, kinds) => record.commands.some(row => !row.consumed && kinds.includes(row.command.kind));
|
|
48
57
|
invariant(!preempts(parent, ['cancel', 'policy_revoked', 'steer']), 'parent_control_preempts_child_control');
|
|
58
|
+
if (command.kind === 'resume_child') {
|
|
59
|
+
invariant(childResumeAllowed(c)
|
|
60
|
+
&& !preempts(child, ['cancel', 'policy_revoked', 'steer', 'resume']), 'child_control_unavailable');
|
|
61
|
+
}
|
|
49
62
|
if (command.kind === 'message_child') {
|
|
50
63
|
invariant(!preempts(child, ['cancel', 'policy_revoked', 'steer']), 'child_control_preempts_input');
|
|
51
64
|
invariant(command.payload.expectedGoalRevision === c.goalRevision, 'stale_child_goal_revision');
|
package/dist/child-runtime.mjs
CHANGED
|
@@ -138,7 +138,7 @@ export function reduceChildLifecycle(snapshot, config, request, result, digest,
|
|
|
138
138
|
const owned = request.reservations.find(item => item.childRunId === child.runId);
|
|
139
139
|
invariant(owned && owned.parentOperationKey === child.operationKey && owned.parentToolCallId === child.callId
|
|
140
140
|
&& child.reservedModelCalls === owned.maxModelCalls && child.reservedToolCalls === owned.maxToolCalls
|
|
141
|
-
&& ['prepared', 'running', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
|
|
141
|
+
&& ['prepared', 'running', 'paused', 'awaiting_interaction', 'completed', 'failed', 'canceled', 'interrupted'].includes(child.state)
|
|
142
142
|
&& (settled.includes(child.runId) ? ['completed', 'failed', 'canceled'].includes(child.state)
|
|
143
143
|
: !['completed', 'failed', 'canceled'].includes(child.state))
|
|
144
144
|
&& child.usage.modelCalls <= owned.maxModelCalls && child.usage.toolCalls <= owned.maxToolCalls
|
|
@@ -164,6 +164,16 @@ export function reduceChildLifecycle(snapshot, config, request, result, digest,
|
|
|
164
164
|
callId: approval.toolCall.callId, operationKey: request.operationKey };
|
|
165
165
|
updated.interaction = null;
|
|
166
166
|
}
|
|
167
|
+
else if (!result.errorCode && request.action === 'wait' && result.children?.some(child => child.state === 'paused'
|
|
168
|
+
&& pending.includes(child.runId) && (!request.waitForChildRunIds || request.waitForChildRunIds.includes(child.runId)))) {
|
|
169
|
+
// A joined child can still own valid results and an unspent reservation.
|
|
170
|
+
// Preserve that original run until an explicit control resumes or cancels
|
|
171
|
+
// it. Background polls do not block the parent's independent work.
|
|
172
|
+
updated.resumePhase = updated.phase;
|
|
173
|
+
updated.phase = 'paused';
|
|
174
|
+
updated.reason = 'child_paused';
|
|
175
|
+
updated.outcome = null;
|
|
176
|
+
}
|
|
167
177
|
else if (result.errorCode || !observationOnly && request.action !== 'poll'
|
|
168
178
|
&& pending.some(id => !request.waitForChildRunIds || request.waitForChildRunIds.includes(id))) {
|
|
169
179
|
updated.phase = 'finalizing';
|
package/dist/configuration.d.mts
CHANGED
|
@@ -25,9 +25,11 @@ export interface ConfigurationInput {
|
|
|
25
25
|
sourceReadPolicy?: RunConfiguration['sourceReadPolicy'];
|
|
26
26
|
outputRecoveryPolicy?: RunConfiguration['outputRecoveryPolicy'];
|
|
27
27
|
outputRestartPolicy?: RunConfiguration['outputRestartPolicy'];
|
|
28
|
+
approvalOutcomePolicy?: RunConfiguration['approvalOutcomePolicy'];
|
|
28
29
|
providerRecoveryPolicy?: RunConfiguration['providerRecoveryPolicy'];
|
|
29
30
|
toolErrorRecoveryPolicy?: RunConfiguration['toolErrorRecoveryPolicy'];
|
|
30
31
|
toolDiscoveryPolicy?: RunConfiguration['toolDiscoveryPolicy'];
|
|
32
|
+
toolAdmissionPolicy?: RunConfiguration['toolAdmissionPolicy'];
|
|
31
33
|
todoPolicy?: RunConfiguration['todoPolicy'];
|
|
32
34
|
toolExecutionPolicy?: RunConfiguration['toolExecutionPolicy'];
|
|
33
35
|
childTaskPolicy?: RunConfiguration['childTaskPolicy'];
|
package/dist/configuration.mjs
CHANGED
|
@@ -49,9 +49,11 @@ export function configure(input) {
|
|
|
49
49
|
...(input.sourceReadPolicy === undefined ? {} : { sourceReadPolicy: input.sourceReadPolicy }),
|
|
50
50
|
...(input.outputRecoveryPolicy === undefined ? {} : { outputRecoveryPolicy: input.outputRecoveryPolicy }),
|
|
51
51
|
...(input.outputRestartPolicy === undefined ? {} : { outputRestartPolicy: input.outputRestartPolicy }),
|
|
52
|
+
...(input.approvalOutcomePolicy === undefined ? {} : { approvalOutcomePolicy: input.approvalOutcomePolicy }),
|
|
52
53
|
...(input.providerRecoveryPolicy === undefined ? {} : { providerRecoveryPolicy: input.providerRecoveryPolicy }),
|
|
53
54
|
...(input.toolErrorRecoveryPolicy === undefined ? {} : { toolErrorRecoveryPolicy: input.toolErrorRecoveryPolicy }),
|
|
54
55
|
...(input.toolDiscoveryPolicy === undefined ? {} : { toolDiscoveryPolicy: input.toolDiscoveryPolicy }),
|
|
56
|
+
...(input.toolAdmissionPolicy === undefined ? {} : { toolAdmissionPolicy: input.toolAdmissionPolicy }),
|
|
55
57
|
...(input.todoPolicy === undefined ? {} : { todoPolicy: input.todoPolicy }),
|
|
56
58
|
...(input.toolExecutionPolicy === undefined ? {} : { toolExecutionPolicy: input.toolExecutionPolicy }),
|
|
57
59
|
...(input.childTaskPolicy === undefined ? {} : { childTaskPolicy: input.childTaskPolicy }),
|
|
@@ -105,9 +107,10 @@ export function configure(input) {
|
|
|
105
107
|
&& typeof config.hostRecoveryBinding === 'object' && !Array.isArray(config.hostRecoveryBinding), 'invalid_host_recovery_binding');
|
|
106
108
|
invariant(config.guidancePolicy == null || config.guidancePolicy === 'boundary-guide/v1', 'invalid_guidance_policy');
|
|
107
109
|
invariant(config.inputPolicy === undefined || config.inputPolicy === 'before-first-model/v1', 'invalid_input_policy');
|
|
108
|
-
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
109
|
-
invariant(config.outputRestartPolicy === undefined ||
|
|
110
|
-
&&
|
|
110
|
+
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
111
|
+
invariant(config.outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(config.outputRestartPolicy)
|
|
112
|
+
&& ['response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy ?? ''), 'invalid_output_restart_policy');
|
|
113
|
+
invariant(config.approvalOutcomePolicy === undefined || config.approvalOutcomePolicy === 'owner-outcome/v1', 'invalid_approval_outcome_policy');
|
|
111
114
|
invariant(config.providerRecoveryPolicy == null || config.providerRecoveryPolicy === 'provider-recovery/v2', 'invalid_provider_recovery_policy');
|
|
112
115
|
invariant(config.toolExecutionPolicy === undefined || config.toolExecutionPolicy === 'owner-execution/v1', 'invalid_tool_execution_policy');
|
|
113
116
|
invariant(config.toolErrorRecoveryPolicy == null || ['diagnose-before-repeat/v1', 'diagnose-before-repeat/v2'].includes(config.toolErrorRecoveryPolicy), 'invalid_tool_error_recovery_policy');
|
|
@@ -191,7 +194,7 @@ export function configure(input) {
|
|
|
191
194
|
const policy = profile.providerCompatibilityPolicy;
|
|
192
195
|
invariant(policy !== null && typeof policy === 'object' && !Array.isArray(policy)
|
|
193
196
|
&& Object.keys(policy).every(key => ['contract', 'rule'].includes(key))
|
|
194
|
-
&& ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3'].includes(policy.contract)
|
|
197
|
+
&& ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)
|
|
195
198
|
&& ['auto', 'permissive', 'openai', 'strict-openai', 'cerebras', 'groq', 'deepseek',
|
|
196
199
|
'zai', 'kspmas-gateway', 'moonshot', 'mimo'].includes(policy.rule), 'invalid_provider_compatibility_policy');
|
|
197
200
|
}
|
|
@@ -9,7 +9,7 @@ import { sourceWorkingSetGroup } from './source-working-set-group.mjs';
|
|
|
9
9
|
import { sourceReuseProjector } from './context-source-reuse.mjs';
|
|
10
10
|
import { defaultToolPruningThreshold, projectOldToolResults, toolPruningIdleElapsed } from './context-microcompact.mjs';
|
|
11
11
|
import { summaryContinuityInstructions, validSummaryContinuity } from './summary-continuity.mjs';
|
|
12
|
-
import { responseContinuationPairs } from './response-continuation.mjs';
|
|
12
|
+
import { responseBoundaryRecovery, responseContinuationPairs } from './response-continuation.mjs';
|
|
13
13
|
import { verificationModelView } from './model-surface.mjs';
|
|
14
14
|
import { currentInstructionContribution } from './context-contributions.mjs';
|
|
15
15
|
const emptyState = () => ({ history: null, compaction: null, compactions: 0,
|
|
@@ -120,7 +120,7 @@ function groupsOf(messages, indexes) {
|
|
|
120
120
|
}
|
|
121
121
|
function mandatoryIndexes(snapshot, groups, config) {
|
|
122
122
|
const mandatory = new Set(), messages = snapshot.messages;
|
|
123
|
-
if (config
|
|
123
|
+
if (responseBoundaryRecovery(config))
|
|
124
124
|
for (const pair of responseContinuationPairs(messages))
|
|
125
125
|
for (const index of pair)
|
|
126
126
|
mandatory.add(index);
|
package/dist/contracts.d.mts
CHANGED
|
@@ -182,7 +182,7 @@ export interface ModelProfile {
|
|
|
182
182
|
rule: 'auto' | 'permissive' | 'openai' | 'strict-openai' | 'cerebras' | 'groq' | 'deepseek' | 'zai' | 'kspmas-gateway' | 'moonshot' | 'mimo';
|
|
183
183
|
};
|
|
184
184
|
providerCompatibilityPolicy?: {
|
|
185
|
-
contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3';
|
|
185
|
+
contract: 'provider-compat/v1' | 'provider-compat/v2' | 'provider-compat/v3' | 'provider-compat/v4';
|
|
186
186
|
rule: NonNullable<ModelProfile['inlineReasoningPolicy']>['rule'];
|
|
187
187
|
};
|
|
188
188
|
streaming?: boolean;
|
|
@@ -516,6 +516,8 @@ export interface RunConfiguration {
|
|
|
516
516
|
planModeInitialActive?: boolean;
|
|
517
517
|
childPlanPolicy?: 'inherit-plan/v1';
|
|
518
518
|
toolDiscoveryPolicy?: 'local-tool-search/v1';
|
|
519
|
+
/** A premature call may load an already authorized schema, but never dispatch its operation. */
|
|
520
|
+
toolAdmissionPolicy?: 'discover-before-retry/v1';
|
|
519
521
|
artifactPolicy?: 'runtime-artifacts/v1' | null;
|
|
520
522
|
/** The execution owner must prepare Host context before the first inference. */
|
|
521
523
|
inputPolicy?: 'before-first-model/v1';
|
|
@@ -542,10 +544,14 @@ export interface RunConfiguration {
|
|
|
542
544
|
delegationDepth: number;
|
|
543
545
|
modelRecoveryPolicy: 'manual' | 'pure-inference/v1';
|
|
544
546
|
guidancePolicy?: 'boundary-guide/v1' | null;
|
|
545
|
-
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | null;
|
|
546
|
-
/** Restart allowance belongs to one interrupted response chain.
|
|
547
|
-
*
|
|
548
|
-
|
|
547
|
+
outputRecoveryPolicy?: 'task-or-delivery/v1' | 'response-boundary/v2' | 'response-boundary/v3' | null;
|
|
548
|
+
/** Restart allowance belongs to one interrupted response chain. v2 pauses
|
|
549
|
+
* exhausted chains for explicit resume instead of terminating the Run.
|
|
550
|
+
* Legacy Runs retain their frozen accounting and exhaustion behavior. */
|
|
551
|
+
outputRestartPolicy?: 'per-response/v1' | 'per-response/v2';
|
|
552
|
+
/** The interactive owner preserves typed Host outcomes and pauses on a
|
|
553
|
+
* non-grant. Children retain the outcome without duplicating that pause. */
|
|
554
|
+
approvalOutcomePolicy?: 'owner-outcome/v1';
|
|
549
555
|
/** v2 counts consecutive provider failures and pauses (resumable) instead of failing when they run out. */
|
|
550
556
|
providerRecoveryPolicy?: 'provider-recovery/v2' | null;
|
|
551
557
|
/** v2 admits a ten-inference diagnostic allowance unless explicitly configured.
|
|
@@ -712,7 +718,7 @@ export interface ChildState {
|
|
|
712
718
|
sessionId: string;
|
|
713
719
|
operationKey: string;
|
|
714
720
|
callId: string;
|
|
715
|
-
state: 'prepared' | 'running' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
|
|
721
|
+
state: 'prepared' | 'running' | 'paused' | 'awaiting_interaction' | 'completed' | 'failed' | 'canceled' | 'interrupted';
|
|
716
722
|
reservedModelCalls: number | null;
|
|
717
723
|
reservedToolCalls: number | null;
|
|
718
724
|
usage: Usage;
|
|
@@ -966,7 +972,7 @@ export interface EffectReceipt {
|
|
|
966
972
|
status: 'committed' | 'failed' | 'uncertain' | 'not_dispatched';
|
|
967
973
|
result: ObjectValue;
|
|
968
974
|
}
|
|
969
|
-
export type CommandKind = 'cancel' | 'policy_revoked' | 'pause' | 'resume' | 'submit_interaction' | 'reconcile_tool' | 'repair_workspace' | 'steer' | 'guide' | 'promote_child' | 'message_child' | 'cancel_child';
|
|
975
|
+
export type CommandKind = 'cancel' | 'policy_revoked' | 'pause' | 'resume' | 'submit_interaction' | 'reconcile_tool' | 'repair_workspace' | 'steer' | 'guide' | 'promote_child' | 'message_child' | 'cancel_child' | 'resume_child';
|
|
970
976
|
export interface RunCommand {
|
|
971
977
|
commandId: string;
|
|
972
978
|
kind: CommandKind;
|
package/dist/contracts.mjs
CHANGED
|
@@ -6,5 +6,5 @@ export const terminal = (phase) => ['completed', 'failed', 'canceled', 'interrup
|
|
|
6
6
|
export const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, modelCalls: 0, toolCalls: 0, cost: 0 });
|
|
7
7
|
export const commandPriority = {
|
|
8
8
|
cancel: 100, policy_revoked: 95, submit_interaction: 90, cancel_child: 85,
|
|
9
|
-
pause: 80, resume: 80, reconcile_tool: 75, repair_workspace: 75, promote_child: 70, message_child: 70, steer: 60, guide: 60,
|
|
9
|
+
pause: 80, resume: 80, reconcile_tool: 75, repair_workspace: 75, promote_child: 70, message_child: 70, resume_child: 70, steer: 60, guide: 60,
|
|
10
10
|
};
|
package/dist/index.d.mts
CHANGED
|
@@ -49,6 +49,7 @@ export * from './child-budget.mjs';
|
|
|
49
49
|
export * from './child-contract.mjs';
|
|
50
50
|
export * from './child-runtime.mjs';
|
|
51
51
|
export * from './child-control.mjs';
|
|
52
|
+
export * from './approval-outcome.mjs';
|
|
52
53
|
export * from './guidance.mjs';
|
|
53
54
|
export * from './tool-receipt.mjs';
|
|
54
55
|
export * from './output-recovery.mjs';
|
package/dist/index.mjs
CHANGED
|
@@ -49,6 +49,7 @@ export * from './child-budget.mjs';
|
|
|
49
49
|
export * from './child-contract.mjs';
|
|
50
50
|
export * from './child-runtime.mjs';
|
|
51
51
|
export * from './child-control.mjs';
|
|
52
|
+
export * from './approval-outcome.mjs';
|
|
52
53
|
export * from './guidance.mjs';
|
|
53
54
|
export * from './tool-receipt.mjs';
|
|
54
55
|
export * from './output-recovery.mjs';
|
package/dist/kernel.d.mts
CHANGED
|
@@ -40,6 +40,7 @@ export declare class NativeKernel {
|
|
|
40
40
|
promoteChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
|
|
41
41
|
sendChildInput(scope: RunScope, runId: string, childRunId: string, text: string, expectedGoalRevision: number, commandId: string): import("./contracts.mjs").CommandReceipt;
|
|
42
42
|
cancelChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
|
|
43
|
+
resumeChild(scope: RunScope, runId: string, childRunId: string, commandId: string): import("./contracts.mjs").CommandReceipt;
|
|
43
44
|
private submitChildControl;
|
|
44
45
|
private childTaskStates;
|
|
45
46
|
private consumeChildControl;
|
package/dist/kernel.mjs
CHANGED
|
@@ -147,7 +147,7 @@ export class NativeKernel {
|
|
|
147
147
|
if (result.status !== 'rejected' && ['cancel', 'policy_revoked'].includes(command.kind)) {
|
|
148
148
|
this.active.get(runKey(scope, runId))?.abort(new NativeError('command_interrupt'));
|
|
149
149
|
}
|
|
150
|
-
if (result.status === 'accepted' && ['pause', 'promote_child', 'message_child', 'cancel_child'].includes(command.kind)) {
|
|
150
|
+
if (result.status === 'accepted' && ['pause', 'promote_child', 'message_child', 'cancel_child', 'resume_child'].includes(command.kind)) {
|
|
151
151
|
const observer = this.childObservers.get(runKey(scope, runId));
|
|
152
152
|
if (observer && (command.kind !== 'pause' || observer.canPause))
|
|
153
153
|
observer.controller.abort(new NativeError(command.kind === 'pause' ? 'child_observation_paused' : 'child_observation_promoted'));
|
|
@@ -172,6 +172,9 @@ export class NativeKernel {
|
|
|
172
172
|
cancelChild(scope, runId, childRunId, commandId) {
|
|
173
173
|
return this.submitChildControl(scope, runId, { commandId, kind: 'cancel_child', payload: { childRunId } });
|
|
174
174
|
}
|
|
175
|
+
resumeChild(scope, runId, childRunId, commandId) {
|
|
176
|
+
return this.submitChildControl(scope, runId, { commandId, kind: 'resume_child', payload: { childRunId } });
|
|
177
|
+
}
|
|
175
178
|
submitChildControl(scope, runId, command) {
|
|
176
179
|
const record = this.store.load(scope, runId), send = command.kind === 'message_child';
|
|
177
180
|
// Stable retries retain the original target, even after it becomes terminal.
|
|
@@ -183,7 +186,7 @@ export class NativeKernel {
|
|
|
183
186
|
invariant(target, 'child_control_not_owned');
|
|
184
187
|
childControlDelivery(record.snapshot, command, target);
|
|
185
188
|
const task = this.childTaskStates(record.snapshot).find(task => task.childRunId === target.runId);
|
|
186
|
-
invariant(task && (send ? task.canSendInput : task.canCancel), 'child_control_unavailable');
|
|
189
|
+
invariant(task && (send ? task.canSendInput : command.kind === 'resume_child' ? task.canResume === true : task.canCancel), 'child_control_unavailable');
|
|
187
190
|
return this.submit(scope, runId, command);
|
|
188
191
|
}
|
|
189
192
|
childTaskStates(snapshot) {
|
|
@@ -192,6 +195,7 @@ export class NativeKernel {
|
|
|
192
195
|
return copy(this.ports.children?.tasks?.({ scope: copy(snapshot.scope), runId: snapshot.runId, sessionId: snapshot.sessionId,
|
|
193
196
|
turnId: snapshot.turnId, buildId: snapshot.buildId, parentRunId: snapshot.parentRunId, taskChainId: snapshot.taskChainId }) ?? [])
|
|
194
197
|
.map(task => ({ ...task, canCancel: task.canCancel && controls,
|
|
198
|
+
...(task.canResume === undefined ? {} : { canResume: task.canResume && controls }),
|
|
195
199
|
canSendInput: task.canSendInput && controls && config.childInputPolicy === 'owned-child-input/v1' }));
|
|
196
200
|
}
|
|
197
201
|
async consumeChildControl(snapshot, config, command, lease) {
|
|
@@ -203,9 +207,13 @@ export class NativeKernel {
|
|
|
203
207
|
const target = port.controlTarget(snapshot, id);
|
|
204
208
|
invariant(target, 'child_control_not_owned');
|
|
205
209
|
const delivery = childControlDelivery(snapshot, command, target), changes = { childLifecycleCursor: null };
|
|
206
|
-
const facts = [{ kind: send ? 'child.input_queued'
|
|
210
|
+
const facts = [{ kind: send ? 'child.input_queued'
|
|
211
|
+
: command.kind === 'resume_child' ? 'child.resume_requested' : 'child.cancel_requested',
|
|
207
212
|
payload: { childRunId: id, commandId: command.commandId } }];
|
|
208
|
-
if (
|
|
213
|
+
if (['resume_child', 'cancel_child'].includes(command.kind) && snapshot.phase === 'paused' && snapshot.reason === 'child_paused') {
|
|
214
|
+
Object.assign(changes, { phase: snapshot.resumePhase ?? 'preparing_context', resumePhase: null, reason: null });
|
|
215
|
+
}
|
|
216
|
+
if (command.kind === 'cancel_child' && snapshot.childApproval?.childRunId === id) {
|
|
209
217
|
facts.push({ kind: 'approval.resolved', payload: { interactionId: snapshot.pendingInteraction?.interactionId ?? '',
|
|
210
218
|
callId: snapshot.childApproval.toolCall.callId, decision: 'canceled', reason: 'child_cancel_requested' } });
|
|
211
219
|
Object.assign(changes, { childApproval: null, pendingInteraction: null, interaction: null,
|
|
@@ -292,6 +300,8 @@ export class NativeKernel {
|
|
|
292
300
|
}
|
|
293
301
|
}, Math.max(10, Math.floor(initial.configuration.limits.leaseMs / 3)));
|
|
294
302
|
let deliveredRevision = -1;
|
|
303
|
+
let recoveredChildControls = false;
|
|
304
|
+
const wokenChildControls = new Set();
|
|
295
305
|
let browserChecked = !(initial.snapshot.browserSessionRefs?.length || initial.snapshot.lastBrowserObservation);
|
|
296
306
|
try {
|
|
297
307
|
while (true) {
|
|
@@ -323,8 +333,9 @@ export class NativeKernel {
|
|
|
323
333
|
: prepareToolReceipt(this.store.load(scope, runId), command));
|
|
324
334
|
continue;
|
|
325
335
|
}
|
|
326
|
-
if (['message_child', 'cancel_child'].includes(command.kind)) {
|
|
336
|
+
if (['message_child', 'cancel_child', 'resume_child'].includes(command.kind)) {
|
|
327
337
|
await this.consumeChildControl(snapshot, config, command, lease);
|
|
338
|
+
wokenChildControls.add(command.commandId);
|
|
328
339
|
continue;
|
|
329
340
|
}
|
|
330
341
|
const intent = record.pendingIntent;
|
|
@@ -345,6 +356,31 @@ export class NativeKernel {
|
|
|
345
356
|
}
|
|
346
357
|
continue;
|
|
347
358
|
}
|
|
359
|
+
if (!recoveredChildControls) {
|
|
360
|
+
recoveredChildControls = true;
|
|
361
|
+
// The pair transaction may have committed immediately before a
|
|
362
|
+
// process died, leaving a paused child with an existing resume inbox
|
|
363
|
+
// entry but no wake. Recover notification, never re-enqueue a command
|
|
364
|
+
// or infer permission from a child's phase. The owner authenticates
|
|
365
|
+
// the exact inbox entry before it can drive the original child.
|
|
366
|
+
const children = this.ports.children;
|
|
367
|
+
if (config.childLifecyclePolicy === 'owned-background/v2' && snapshot.childRunIds.length
|
|
368
|
+
&& snapshot.phase !== 'finalizing' && !snapshot.childTerminalPhase
|
|
369
|
+
&& children?.controlTarget && children.wakeControl) {
|
|
370
|
+
const saved = this.store.load(scope, runId);
|
|
371
|
+
const delivered = new Set(saved.events.filter(event => event.kind === 'child.resume_requested')
|
|
372
|
+
.map(event => event.payload.commandId));
|
|
373
|
+
for (const row of saved.commands)
|
|
374
|
+
if (row.consumed && row.command.kind === 'resume_child'
|
|
375
|
+
&& delivered.has(row.command.commandId) && !wokenChildControls.has(row.command.commandId)) {
|
|
376
|
+
const target = children.controlTarget(snapshot, String(row.command.payload.childRunId));
|
|
377
|
+
if (target)
|
|
378
|
+
await children.wakeControl(snapshot, childControlDelivery(snapshot, row.command, target));
|
|
379
|
+
}
|
|
380
|
+
if (controller.signal.aborted || this.drivingCommands(this.drivingState(scope, runId)).length)
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
348
384
|
if (!browserChecked) {
|
|
349
385
|
const pending = record.pendingIntent;
|
|
350
386
|
// Resource loss must not conceal an already claimed effect. Classify
|
package/dist/machine.mjs
CHANGED
|
@@ -16,11 +16,11 @@ import { admittedToolBudget, outstandingChildCalls, reduceChildBudget } from './
|
|
|
16
16
|
import { prepareChildLifecycle, unsettledChildren } from './child-runtime.mjs';
|
|
17
17
|
import { toolResourceUsage, toolUsageIncomplete } from './tool-resource-usage.mjs';
|
|
18
18
|
import { completeContinuation, outputRecoveryMode, restartContinuation } from './output-recovery.mjs';
|
|
19
|
-
import { responseContinuationPending } from './response-continuation.mjs';
|
|
19
|
+
import { responseBoundaryRecovery, responseContinuationPending, responseScopedOutputRestarts } 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, toolAdmissionRejection, TOOL_SEARCH } from './tool-discovery.mjs';
|
|
23
|
+
import { discoveryModelTools, resolveDiscoveredCalls, discoveredCallExposed, discoverRejectedCalls, 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';
|
|
@@ -402,20 +402,25 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
402
402
|
}
|
|
403
403
|
const tools = advertisedTools({ ...snapshot,
|
|
404
404
|
usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } }, config, policies);
|
|
405
|
-
|
|
405
|
+
const discovery = discoverRejectedCalls(snapshot, config, result.toolCalls, tools);
|
|
406
|
+
const discovered = discovery ? { ...snapshot, toolDiscovery: discovery.state } : snapshot;
|
|
407
|
+
if (discovery || result.toolCalls.some(call => !tools.some(tool => tool.name === call.name)
|
|
406
408
|
|| !discoveredCallExposed(snapshot, config, call))) {
|
|
407
|
-
const unbound = result.toolCalls.some(call => !config.tools.some(tool => tool.name === call.name)
|
|
408
|
-
|| !discoveredCallExposed(
|
|
409
|
+
const unbound = result.toolCalls.some(call => !(config.toolAdmissionPolicy ? tools : config.tools).some(tool => tool.name === call.name)
|
|
410
|
+
|| !discoveredCallExposed(discovered, config, call));
|
|
409
411
|
const errors = snapshot.modelErrors + Number(unbound), exhausted = errors > config.profile.maxRetries;
|
|
410
412
|
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [], modelErrors: errors,
|
|
413
|
+
...(discovery ? { toolDiscovery: discovery.state } : {}),
|
|
411
414
|
outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'tool_call_not_advertised_retry_exhausted' : null, messages: [...snapshot.messages,
|
|
412
415
|
{ ...message, toolCalls: result.toolCalls }, ...result.toolCalls.map(call => ({ role: 'tool',
|
|
413
|
-
callId: call.callId, name: call.name, content: canonical(toolAdmissionRejection(
|
|
416
|
+
callId: call.callId, name: call.name, content: canonical({ ...toolAdmissionRejection(discovered, config, call, tools),
|
|
417
|
+
...(discovery ? { loaded_tool_names: discovery.names,
|
|
418
|
+
instruction: 'The whole batch was not executed. Complete definitions for the listed tools are loaded in the next request. Resubmit valid calls by their exact names; normal permissions and approvals still apply.' } : {}) }) }))] };
|
|
414
419
|
}
|
|
415
420
|
return { ...base, phase: 'executing_tools', pendingTools: result.toolCalls,
|
|
416
421
|
messages: [...snapshot.messages, { ...message, toolCalls: result.toolCalls }],
|
|
417
422
|
continuations: 0, modelErrors: 0,
|
|
418
|
-
...(config
|
|
423
|
+
...(responseScopedOutputRestarts(config) ? { outputRestarts: 0 } : {}) };
|
|
419
424
|
case 'final_candidate': {
|
|
420
425
|
if (config.contract.finalSubmissionSchema) {
|
|
421
426
|
const errors = snapshot.modelErrors + 1;
|
|
@@ -432,9 +437,33 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
432
437
|
messages: [...snapshot.messages, { ...message, content: text, kind: 'final_candidate' }] };
|
|
433
438
|
}
|
|
434
439
|
case 'output_limit': {
|
|
440
|
+
const resumable = config.outputRestartPolicy === 'per-response/v2';
|
|
441
|
+
const continuation = () => {
|
|
442
|
+
const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config, advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
|
|
443
|
+
const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
|
|
444
|
+
const messages = [...snapshot.messages,
|
|
445
|
+
...(result.text ? [{ ...message, kind: 'continuation_fragment', continuationResponseId: responseId }] : []),
|
|
446
|
+
{ role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
|
|
447
|
+
...(responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
|
|
448
|
+
? { continuationPolicy: 'response-boundary/v2' } : {}),
|
|
449
|
+
continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
|
|
450
|
+
? 'The previous output was interrupted while task tools remain available. It is work in progress, not a completed delivery. Continue from the last committed state using the available tools as needed; break remaining work into smaller actions. Incomplete tool calls were not executed. Give a fresh final answer only after the task is complete.'
|
|
451
|
+
: result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
|
|
452
|
+
+ (responseBoundaryRecovery(config) ? 'You may replay the final incomplete line verbatim before continuing; the Host joins this exact overlap. Do not replay any complete line. ' : '')
|
|
453
|
+
+ 'Incomplete tool calls were not executed.'
|
|
454
|
+
: 'The last response hit its output limit without visible content or a committed tool call. Continue the task from the last committed state; take the next useful action or answer only if the task is complete.' }];
|
|
455
|
+
return { mode, messages };
|
|
456
|
+
};
|
|
457
|
+
const exhausted = () => resumable
|
|
458
|
+
? { phase: 'paused', resumePhase: 'preparing_context', outcome: null, reason: 'output_budget_exhausted',
|
|
459
|
+
messages: result.text ? continuation().messages : snapshot.messages }
|
|
460
|
+
: { phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
|
|
435
461
|
if (snapshot.continuations >= config.profile.maxContinuations) {
|
|
436
|
-
|
|
437
|
-
|
|
462
|
+
// Committed answer text stays a suffix contract even when the first
|
|
463
|
+
// response has no remaining continuation allowance. It is not a tool
|
|
464
|
+
// fragment that may be discarded for an output restart.
|
|
465
|
+
if (responseContinuationPending(snapshot, config) || resumable && continuation().mode === 'suffix')
|
|
466
|
+
return { ...base, ...exhausted() };
|
|
438
467
|
if (snapshot.outputRestarts < config.limits.maxOutputRestarts) {
|
|
439
468
|
try {
|
|
440
469
|
return { ...base, ...restartContinuation(snapshot, config, result.text, digest), phase: 'preparing_context',
|
|
@@ -446,26 +475,15 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
446
475
|
return { ...base, phase: 'finalizing', outcome: 'blocked', reason: String(error.code) };
|
|
447
476
|
}
|
|
448
477
|
}
|
|
449
|
-
return { ...base,
|
|
478
|
+
return { ...base, ...exhausted() };
|
|
450
479
|
}
|
|
451
480
|
if (!result.text && responseContinuationPending(snapshot, config))
|
|
452
481
|
return { ...base, phase: 'preparing_context',
|
|
453
482
|
continuations: snapshot.continuations + 1,
|
|
454
483
|
messages: [...snapshot.messages, { role: 'user', kind: 'response_continuation_feedback',
|
|
455
484
|
content: 'No visible continuation was returned. The interrupted text response is still pending. Return only its missing text suffix.' }] };
|
|
456
|
-
const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config, advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
|
|
457
|
-
const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
|
|
458
485
|
return { ...base, phase: 'preparing_context', continuations: snapshot.continuations + 1,
|
|
459
|
-
messages:
|
|
460
|
-
{ role: 'user', kind: 'continuation_observation', continuationMode: mode, continuationResponseId: responseId,
|
|
461
|
-
...(config.outputRecoveryPolicy === 'response-boundary/v2' && config.contract.finalOutputFormat === 'text' && mode === 'suffix'
|
|
462
|
-
? { continuationPolicy: 'response-boundary/v2' } : {}),
|
|
463
|
-
continuationFragmentDigest: digest(result.text), content: mode === 'task_resume'
|
|
464
|
-
? 'The previous output was interrupted while task tools remain available. It is work in progress, not a completed delivery. Continue from the last committed state using the available tools as needed; break remaining work into smaller actions. Incomplete tool calls were not executed. Give a fresh final answer only after the task is complete.'
|
|
465
|
-
: result.text ? 'The last response hit its output limit. Return only the exact missing suffix of that response. '
|
|
466
|
-
+ (config.outputRecoveryPolicy === 'response-boundary/v2' ? 'You may replay the final incomplete line verbatim before continuing; the Host joins this exact overlap. Do not replay any complete line. ' : '')
|
|
467
|
-
+ 'Incomplete tool calls were not executed.'
|
|
468
|
-
: 'The last response hit its output limit without visible content or a committed tool call. Continue the task from the last committed state; take the next useful action or answer only if the task is complete.' }] };
|
|
486
|
+
messages: continuation().messages };
|
|
469
487
|
}
|
|
470
488
|
case 'context_overflow':
|
|
471
489
|
return { ...base, phase: 'compacting', context: { ...snapshot.context, preparedCursor: null } };
|
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
|