@kingsoftcloud/agentkit-harness-core 0.0.17 → 0.0.18
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/configuration.d.mts +2 -0
- package/dist/configuration.mjs +19 -2
- package/dist/context-contributions.d.mts +2 -0
- package/dist/context-contributions.mjs +57 -2
- package/dist/context-planning.mjs +7 -4
- package/dist/contracts.d.mts +21 -1
- package/dist/engine-preset.d.mts +48 -0
- package/dist/engine-preset.mjs +75 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -0
- package/dist/kernel.d.mts +2 -1
- package/dist/kernel.mjs +49 -19
- package/dist/machine.d.mts +3 -1
- package/dist/machine.mjs +57 -7
- package/dist/output-recovery.d.mts +2 -0
- package/dist/output-recovery.mjs +11 -1
- package/dist/recovery.mjs +2 -0
- package/dist/response-continuation.mjs +2 -1
- package/dist/transitions.mjs +2 -1
- package/package.json +1 -1
- package/src/configuration.mts +24 -2
- package/src/context-contributions.mts +53 -2
- package/src/context-planning.mts +7 -4
- package/src/contracts.mts +18 -1
- package/src/engine-preset.mts +110 -0
- package/src/index.mts +1 -0
- package/src/kernel.mts +52 -19
- package/src/machine.mts +55 -7
- package/src/output-recovery.mts +13 -1
- package/src/recovery.mts +1 -0
- package/src/response-continuation.mts +2 -1
- package/src/transitions.mts +2 -1
package/dist/kernel.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import { NativeError, isNativeError, canonical, copy, invariant, runKey } from '
|
|
|
9
9
|
import { executeTimedTool } from './tool-execution.mjs';
|
|
10
10
|
import { executeKernelTool, kernelToolPolicy } from './kernel-tool-staging.mjs';
|
|
11
11
|
import { reduceCommand, transition } from './transitions.mjs';
|
|
12
|
-
import { addUsage, modelToolCatalog, modelRoom, objectValue, plan, reduceModel, reduceTools, settle, validateModelResult } from './machine.mjs';
|
|
12
|
+
import { addUsage, initialPlanMessages, initialPlanPending, modelToolCatalog, modelRoom, objectValue, plan, reduceModel, reduceTools, settle, validateModelResult } from './machine.mjs';
|
|
13
13
|
import { browserTaskMessages } from './task-policy.mjs';
|
|
14
14
|
import { normalizeToolIdentities, projectSessionHistory } from './history.mjs';
|
|
15
15
|
import { prepareSourceReadQuote, sourceReadBudgetFor, SOURCE_READ_POLICY } from './source-read-budget.mjs';
|
|
@@ -26,10 +26,10 @@ import { contextSourceDigest, modelContextMessages, validateContextMessages } fr
|
|
|
26
26
|
import { assertHookFeedbackRetained, deniedByHook, reduceHook, stagePostHooks } from './hook-runtime.mjs';
|
|
27
27
|
import { hookBytes, hookResult } from './hook-contract.mjs';
|
|
28
28
|
import { planNativeContext, reduceContextModel } from './context-planning.mjs';
|
|
29
|
-
import { collectContextContributions, contextSourceUnavailable } from './context-contributions.mjs';
|
|
29
|
+
import { collectContextContributions, contextSourceUnavailable, expiredHostContribution } from './context-contributions.mjs';
|
|
30
30
|
import { validateInstructionScopes } from './instruction-scopes.mjs';
|
|
31
31
|
import { refreshContextSources } from './context-source-refresh.mjs';
|
|
32
|
-
import { outputRestartPayload } from './output-recovery.mjs';
|
|
32
|
+
import { outputRestartPayload, reasoningStallRetryTokens } from './output-recovery.mjs';
|
|
33
33
|
import { reduceTurnInput } from './turn-input.mjs';
|
|
34
34
|
import { modelStreamCapture } from './model-stream.mjs';
|
|
35
35
|
import { browserRecoveryTransition } from './browser-runtime.mjs';
|
|
@@ -259,7 +259,8 @@ export class NativeKernel {
|
|
|
259
259
|
const promotion = admitChildPromotion({ ...snapshot, ...changes }, config, command, this.childTaskStates(snapshot));
|
|
260
260
|
return promotion.reason === 'applied' ? { ...promotion, commandId: command.commandId } : null;
|
|
261
261
|
}
|
|
262
|
-
async runUntilIdle(scope, runId, { signal, waitForRetry = true } = {}) {
|
|
262
|
+
async runUntilIdle(scope, runId, { signal, detachSignal, waitForRetry = true } = {}) {
|
|
263
|
+
detachSignal?.throwIfAborted();
|
|
263
264
|
const initial = this.drivingState(scope, runId);
|
|
264
265
|
invariant(this.digest(initial.configuration) === initial.snapshot.configDigest, 'stored_configuration_mismatch');
|
|
265
266
|
this.policies.bindings(effectiveRunConfiguration(initial.snapshot, initial.configuration, this.digest));
|
|
@@ -285,6 +286,12 @@ export class NativeKernel {
|
|
|
285
286
|
if (signal?.aborted)
|
|
286
287
|
externalAbort();
|
|
287
288
|
signal?.addEventListener('abort', externalAbort, { once: true });
|
|
289
|
+
// Worker shutdown releases ownership without submitting a user cancel.
|
|
290
|
+
// A claimed effect with no committed receipt follows normal lease recovery.
|
|
291
|
+
const detach = () => controller.abort(new NativeError('worker_detached'));
|
|
292
|
+
detachSignal?.addEventListener('abort', detach, { once: true });
|
|
293
|
+
if (detachSignal?.aborted)
|
|
294
|
+
detach();
|
|
288
295
|
let leaseError;
|
|
289
296
|
const heartbeat = setInterval(() => {
|
|
290
297
|
try {
|
|
@@ -308,6 +315,7 @@ export class NativeKernel {
|
|
|
308
315
|
// Immediate ports and synchronous storage can otherwise form an
|
|
309
316
|
// unbounded microtask chain that starves lease renewal and cancellation.
|
|
310
317
|
await new Promise(resolve => setTimeout(resolve, 0));
|
|
318
|
+
detachSignal?.throwIfAborted();
|
|
311
319
|
if (leaseError)
|
|
312
320
|
throw leaseError;
|
|
313
321
|
if (this.onCheckpoint) {
|
|
@@ -505,12 +513,13 @@ export class NativeKernel {
|
|
|
505
513
|
throw error;
|
|
506
514
|
}
|
|
507
515
|
const claimedSnapshot = (this.store.authority?.(scope, runId) ?? this.store.load(scope, runId)).snapshot;
|
|
508
|
-
const batch = await this.execute(claimedSnapshot, config, claimed, controller.signal, lease.fence);
|
|
516
|
+
const batch = await this.execute(claimedSnapshot, config, claimed, controller.signal, lease.fence, detachSignal);
|
|
509
517
|
this.commit(claimedSnapshot, lease, batch);
|
|
510
518
|
continue;
|
|
511
519
|
}
|
|
512
520
|
const next = plan({ ...snapshot, activeElapsedMs: this.elapsed(snapshot) }, config, { context: !!this.ports.context, workspace: !!this.ports.workspace,
|
|
513
|
-
verification: !!this.ports.verification
|
|
521
|
+
verification: !!this.ports.verification && this.ports.verification.available?.(config) !== false,
|
|
522
|
+
input: !!this.ports.input }, this.digest, this.policies);
|
|
514
523
|
if (!next)
|
|
515
524
|
return snapshot;
|
|
516
525
|
try {
|
|
@@ -528,6 +537,7 @@ export class NativeKernel {
|
|
|
528
537
|
this.active.delete(key);
|
|
529
538
|
this.clockAnchors.delete(key);
|
|
530
539
|
signal?.removeEventListener('abort', externalAbort);
|
|
540
|
+
detachSignal?.removeEventListener('abort', detach);
|
|
531
541
|
try {
|
|
532
542
|
this.store.release(scope, runId, lease);
|
|
533
543
|
}
|
|
@@ -708,7 +718,7 @@ export class NativeKernel {
|
|
|
708
718
|
}
|
|
709
719
|
return recoverClaimed(snapshot, config, intent, this.now(), observedFacts);
|
|
710
720
|
}
|
|
711
|
-
async execute(snapshot, configuration, intent, signal, executionFence) {
|
|
721
|
+
async execute(snapshot, configuration, intent, signal, executionFence, detachSignal) {
|
|
712
722
|
const started = this.monotonicNow(), abort = new AbortController();
|
|
713
723
|
const effectSignal = AbortSignal.any([signal, abort.signal]);
|
|
714
724
|
const context = { scope: copy(snapshot.scope), runId: snapshot.runId, sessionId: snapshot.sessionId,
|
|
@@ -843,12 +853,15 @@ export class NativeKernel {
|
|
|
843
853
|
changes.todos = { ...copy(snapshot.todos), assistantTurns,
|
|
844
854
|
...(result.toolCalls.some(call => call.name === this.policies.forRun(configuration).todo.TODO_WRITE) ? { lastWriteAssistantTurn: assistantTurns } : {}) };
|
|
845
855
|
}
|
|
846
|
-
|
|
847
|
-
|
|
856
|
+
const planning = intent.payload.purpose === 'initial_plan';
|
|
857
|
+
const planText = planning && changes.initialPlanCompleted && assistantOffset >= 0 ? appended[assistantOffset].content : null;
|
|
858
|
+
facts.push({ kind: 'model.completed', payload: { kind: planText === null ? result.kind : 'initial_plan',
|
|
859
|
+
text: planning ? planText ?? '' : rejectedDraft ? '' : result.text,
|
|
860
|
+
...(!planning && rejectedDraft ? { candidateStatus: 'rejected' } : {}),
|
|
848
861
|
messageIndex: assistantOffset < 0 ? null : snapshot.messages.length + assistantOffset,
|
|
849
862
|
messageCursor: changes.messages?.length ?? snapshot.messages.length,
|
|
850
863
|
usageReported: result.usageReported !== false,
|
|
851
|
-
toolCalls: result.toolCalls.map(objectValue), usage: objectValue(result.usage) } });
|
|
864
|
+
toolCalls: planning ? [] : result.toolCalls.map(objectValue), usage: objectValue(result.usage) } });
|
|
852
865
|
break;
|
|
853
866
|
}
|
|
854
867
|
case 'input':
|
|
@@ -1046,6 +1059,8 @@ export class NativeKernel {
|
|
|
1046
1059
|
}
|
|
1047
1060
|
}
|
|
1048
1061
|
catch (error) {
|
|
1062
|
+
// Leave an unsettled claim for fenced recovery when the worker shuts down.
|
|
1063
|
+
detachSignal?.throwIfAborted();
|
|
1049
1064
|
const code = isNativeError(error) ? error.code : 'effect_port_error';
|
|
1050
1065
|
const unavailableSource = contextSourceUnavailable(error, configuration);
|
|
1051
1066
|
facts.push(observedEffectFailure({ operationKey: intent.operationKey, kind: intent.kind, code,
|
|
@@ -1179,11 +1194,17 @@ export class NativeKernel {
|
|
|
1179
1194
|
taskModelRequest(context, snapshot, configuration, intent) {
|
|
1180
1195
|
const review = intent.payload.purpose === 'delivery_review';
|
|
1181
1196
|
const beforeCall = { ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } };
|
|
1182
|
-
|
|
1197
|
+
const profile = copy(configuration.profile);
|
|
1198
|
+
// Admission reserved the full allowance. Lowering the dispatched request
|
|
1199
|
+
// preserves that admission and the frozen Run profile.
|
|
1200
|
+
if (!review && configuration.outputRecoveryPolicy === 'response-boundary/v4' && snapshot.reasoningStallRetry)
|
|
1201
|
+
profile.maxOutputTokens = reasoningStallRetryTokens(profile.maxOutputTokens);
|
|
1202
|
+
const messages = review ? snapshot.preparedContext ? modelContextMessages(snapshot, this.digest) : this.policies.forRun(configuration).review.deliveryReviewMessages(snapshot)
|
|
1203
|
+
: configuration.profile.operatorGuidancePolicy === 'journaled-system/v1' ? modelContextMessages(snapshot, this.digest)
|
|
1204
|
+
: deliveryTaskMessages(beforeCall, configuration, browserTaskMessages(beforeCall, configuration, modelContextMessages(snapshot, this.digest)));
|
|
1205
|
+
return { ...context, profile, ...(review ? { purpose: 'delivery_review' } : {}),
|
|
1183
1206
|
...(!review && snapshot.usage.toolCalls === 0 ? { beforeFirstTool: true } : {}),
|
|
1184
|
-
messages:
|
|
1185
|
-
: configuration.profile.operatorGuidancePolicy === 'journaled-system/v1' ? modelContextMessages(snapshot, this.digest)
|
|
1186
|
-
: deliveryTaskMessages(beforeCall, configuration, browserTaskMessages(beforeCall, configuration, modelContextMessages(snapshot, this.digest))),
|
|
1207
|
+
messages: intent.payload.purpose === 'initial_plan' ? initialPlanMessages(snapshot, configuration, messages) : messages,
|
|
1187
1208
|
tools: copy(modelToolCatalog(beforeCall, configuration, this.policies)), finalizationOnly: intent.payload.finalizationOnly === true,
|
|
1188
1209
|
maxInlineImageBytes: configuration.limits.maxInlineImageBytes };
|
|
1189
1210
|
}
|
|
@@ -1221,12 +1242,14 @@ export class NativeKernel {
|
|
|
1221
1242
|
}
|
|
1222
1243
|
case 'model': {
|
|
1223
1244
|
const review = intent.payload.purpose === 'delivery_review';
|
|
1224
|
-
|
|
1245
|
+
const compaction = intent.payload.purpose === 'compaction';
|
|
1246
|
+
invariant(compaction || review === this.policies.forRun(configuration).review.reviewPending(snapshot)
|
|
1247
|
+
&& (intent.payload.purpose === 'initial_plan') === initialPlanPending(snapshot, configuration), 'model_purpose_changed');
|
|
1225
1248
|
if (configuration.contextPolicy) {
|
|
1226
1249
|
invariant(this.ports.context?.tokens?.tokenizerId === configuration.contextPolicy.tokenizerId
|
|
1227
1250
|
&& this.ports.context.tokens.tokenizerDigest === configuration.contextPolicy.tokenizerDigest, 'context_tokenizer_binding_mismatch');
|
|
1228
1251
|
}
|
|
1229
|
-
if (
|
|
1252
|
+
if (compaction) {
|
|
1230
1253
|
const chunk = snapshot.contextState?.compaction?.chunk;
|
|
1231
1254
|
invariant(chunk && chunk.projectionDigest === this.digest(chunk.messages), 'context_summary_quote_changed');
|
|
1232
1255
|
return this.ports.model.generate({ ...context, profile: { ...copy(configuration.profile), maxOutputTokens: chunk.maxOutputTokens },
|
|
@@ -1242,6 +1265,12 @@ export class NativeKernel {
|
|
|
1242
1265
|
&& admission.countedInputTokens + admission.maxOutputTokens <= configuration.profile.contextWindow, 'context_admission_invalid');
|
|
1243
1266
|
}
|
|
1244
1267
|
const request = this.taskModelRequest(context, snapshot, configuration, intent);
|
|
1268
|
+
const now = Date.now();
|
|
1269
|
+
request.messages = request.messages.filter(message => {
|
|
1270
|
+
const expired = expiredHostContribution(message, configuration, now);
|
|
1271
|
+
invariant(!expired?.required, 'context_source_expired');
|
|
1272
|
+
return !expired;
|
|
1273
|
+
});
|
|
1245
1274
|
return this.ports.model.generate(request, emit);
|
|
1246
1275
|
}
|
|
1247
1276
|
case 'tool': {
|
|
@@ -1362,10 +1391,11 @@ export class NativeKernel {
|
|
|
1362
1391
|
countRequest: async (messages, tools, purpose, maxOutputTokens) => {
|
|
1363
1392
|
context.signal.throwIfAborted();
|
|
1364
1393
|
assertBinding();
|
|
1394
|
+
const projected = purpose === 'task' ? configuration.profile.operatorGuidancePolicy === 'journaled-system/v1'
|
|
1395
|
+
? this.policies.forRun(configuration).providerContext.projectAnthropicReplay(this.policies.forRun(configuration).providerContext.operatorInputView(this.policies.forRun(configuration).providerContext.anthropicTaskFeedback(snapshot, configuration, messages), configuration.profile, this.digest), tools, configuration.profile, snapshot.abandonedReplayDigests ?? [], this.digest).messages
|
|
1396
|
+
: deliveryTaskMessages(snapshot, configuration, browserTaskMessages(snapshot, configuration, messages)) : messages;
|
|
1365
1397
|
const count = await counter.countRequest({ ...context, profile: { ...copy(configuration.profile), maxOutputTokens },
|
|
1366
|
-
messages: purpose === 'task' ? configuration
|
|
1367
|
-
? this.policies.forRun(configuration).providerContext.projectAnthropicReplay(this.policies.forRun(configuration).providerContext.operatorInputView(this.policies.forRun(configuration).providerContext.anthropicTaskFeedback(snapshot, configuration, messages), configuration.profile, this.digest), tools, configuration.profile, snapshot.abandonedReplayDigests ?? [], this.digest).messages
|
|
1368
|
-
: deliveryTaskMessages(snapshot, configuration, browserTaskMessages(snapshot, configuration, messages)) : messages, tools, purpose, maxOutputTokens,
|
|
1398
|
+
messages: purpose === 'task' ? initialPlanMessages(snapshot, configuration, projected) : projected, tools, purpose, maxOutputTokens,
|
|
1369
1399
|
maxInlineImageBytes: configuration.limits.maxInlineImageBytes });
|
|
1370
1400
|
context.signal.throwIfAborted();
|
|
1371
1401
|
assertBinding();
|
package/dist/machine.d.mts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import type { CommitBatch, EffectIntent, EffectReceipt, ModelResult, ObjectValue, RunConfiguration, RunSnapshot, ToolCall, ToolResult, Usage } from './contracts.mjs';
|
|
1
|
+
import type { CommitBatch, EffectIntent, EffectReceipt, Message, ModelResult, ObjectValue, RunConfiguration, RunSnapshot, ToolCall, ToolResult, Usage } from './contracts.mjs';
|
|
2
2
|
import { NativePolicyRegistry } from './policy-registry.mjs';
|
|
3
3
|
export declare function objectValue(value: unknown): ObjectValue;
|
|
4
4
|
export declare function addUsage(left: Usage, right: Usage): Usage;
|
|
5
5
|
export declare function modelRoom(snapshot: RunSnapshot, config: RunConfiguration): number;
|
|
6
6
|
export declare function toolRoom(snapshot: RunSnapshot, config: RunConfiguration): number;
|
|
7
7
|
export declare function finalizationOnly(snapshot: RunSnapshot, config: RunConfiguration): boolean;
|
|
8
|
+
export declare function initialPlanPending(snapshot: RunSnapshot, config: RunConfiguration): boolean;
|
|
9
|
+
export declare function initialPlanMessages(snapshot: RunSnapshot, config: RunConfiguration, messages: Message[]): Message[];
|
|
8
10
|
export declare function advertisedTools(snapshot: RunSnapshot, config: RunConfiguration, policies?: NativePolicyRegistry): import("./contracts.mjs").ToolDefinition[];
|
|
9
11
|
export interface PlanCapabilities {
|
|
10
12
|
context: boolean;
|
package/dist/machine.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { rememberCommand } from './background-runtime.mjs';
|
|
|
15
15
|
import { admittedToolBudget, outstandingChildCalls, reduceChildBudget } from './child-budget.mjs';
|
|
16
16
|
import { prepareChildLifecycle, unsettledChildren } from './child-runtime.mjs';
|
|
17
17
|
import { toolResourceUsage, toolUsageIncomplete } from './tool-resource-usage.mjs';
|
|
18
|
-
import { completeContinuation, outputRecoveryMode, restartContinuation } from './output-recovery.mjs';
|
|
18
|
+
import { completeContinuation, outputRecoveryMode, reasoningStall, reasoningStallRetryTokens, restartContinuation } from './output-recovery.mjs';
|
|
19
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';
|
|
@@ -63,8 +63,19 @@ export function finalizationOnly(snapshot, config) {
|
|
|
63
63
|
const calls = modelRoom(snapshot, config);
|
|
64
64
|
return calls <= config.limits.finalizationReserveModelCalls;
|
|
65
65
|
}
|
|
66
|
+
export function initialPlanPending(snapshot, config) {
|
|
67
|
+
return config.initialPlanPolicy === 'plan-act-observe/v1' && !snapshot.initialPlanCompleted;
|
|
68
|
+
}
|
|
69
|
+
export function initialPlanMessages(snapshot, config, messages) {
|
|
70
|
+
if (!initialPlanPending(snapshot, config))
|
|
71
|
+
return messages;
|
|
72
|
+
const instruction = responseContinuationPending(snapshot, config)
|
|
73
|
+
? 'Continue the unfinished execution plan. Return only its missing text suffix.'
|
|
74
|
+
: 'First give a concise step-by-step execution plan for the current user request. Tools are unavailable in this step. The next step will execute the plan.';
|
|
75
|
+
return [{ role: 'system', content: instruction }, ...messages];
|
|
76
|
+
}
|
|
66
77
|
export function advertisedTools(snapshot, config, policies = new NativePolicyRegistry()) {
|
|
67
|
-
if (responseContinuationPending(snapshot, config))
|
|
78
|
+
if (initialPlanPending(snapshot, config) || responseContinuationPending(snapshot, config))
|
|
68
79
|
return [];
|
|
69
80
|
if (policies.forRun(config).review.reviewPending(snapshot))
|
|
70
81
|
return policies.forRun(config).review.deliveryReviewTools(snapshot, config);
|
|
@@ -81,7 +92,7 @@ export function advertisedTools(snapshot, config, policies = new NativePolicyReg
|
|
|
81
92
|
}
|
|
82
93
|
/** Stable declaration is distinct from the per-turn execution admission above. */
|
|
83
94
|
export function modelToolCatalog(snapshot, config, policies = new NativePolicyRegistry()) {
|
|
84
|
-
if (responseContinuationPending(snapshot, config))
|
|
95
|
+
if (initialPlanPending(snapshot, config) || responseContinuationPending(snapshot, config))
|
|
85
96
|
return [];
|
|
86
97
|
if ((config.profile.toolCatalogPolicy !== 'stable-task/v1' && config.profile.providerToolSearchPolicy !== 'anthropic-deferred/v1')
|
|
87
98
|
|| policies.forRun(config).review.reviewPending(snapshot))
|
|
@@ -233,6 +244,8 @@ export function plan(snapshot, config, capabilities, digest = canonical, policie
|
|
|
233
244
|
if (candidate)
|
|
234
245
|
return transition(snapshot, { phase: 'verifying', candidate, verification: null, preparedContext: null }, [{ kind: 'verification.checkpoint_started', payload: { workspaceRevision: snapshot.workspaceRevision } }]);
|
|
235
246
|
}
|
|
247
|
+
if (initialPlanPending(snapshot, config))
|
|
248
|
+
return prepareEffect(snapshot, 'model', 'requesting_model', { purpose: 'initial_plan', finalizationOnly: false });
|
|
236
249
|
return prepareEffect(snapshot, 'model', 'requesting_model', policies.forRun(config).review.reviewPending(snapshot)
|
|
237
250
|
? { purpose: 'delivery_review', finalizationOnly: false } : { finalizationOnly: finalizationOnly(snapshot, config) }, policies.forRun(config).review.reviewPending(snapshot) ? {} : policies.forRun(config).providerContext.captureAnthropicContext(snapshot, config, modelToolCatalog(snapshot, config, policies), digest));
|
|
238
251
|
}
|
|
@@ -259,11 +272,11 @@ export function plan(snapshot, config, capabilities, digest = canonical, policie
|
|
|
259
272
|
return transition(snapshot, { phase: 'preparing_context', pendingTools: [], messages: [...snapshot.messages, ...messages] }, [{ kind: 'tools.budget_exhausted', payload: {} }]);
|
|
260
273
|
}
|
|
261
274
|
let calls = [first];
|
|
262
|
-
if (definition.readOnly && definition.concurrentSafe && !definition.delegatedReadOnly && !guardedToolErrorAction(snapshot, first, digest)) {
|
|
275
|
+
if (definition.readOnly && definition.concurrentSafe && !definition.approvalPolicy && !definition.delegatedReadOnly && !guardedToolErrorAction(snapshot, first, digest)) {
|
|
263
276
|
calls = [];
|
|
264
277
|
for (const call of snapshot.pendingTools.slice(0, Math.min(config.limits.maxParallelTools, toolRoom(snapshot, config)))) {
|
|
265
278
|
const tool = config.tools.find(item => item.name === call.name);
|
|
266
|
-
if (!tool?.readOnly || !tool.concurrentSafe || tool.delegatedReadOnly || tool.observationRole !== 'none')
|
|
279
|
+
if (!tool?.readOnly || !tool.concurrentSafe || tool.approvalPolicy || tool.delegatedReadOnly || tool.observationRole !== 'none')
|
|
267
280
|
break;
|
|
268
281
|
if (guardedToolErrorAction(snapshot, call, digest))
|
|
269
282
|
break;
|
|
@@ -358,12 +371,23 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
358
371
|
if (snapshot.hookState && ['tool_calls', 'final_candidate', 'output_limit'].includes(result.kind)
|
|
359
372
|
&& (result.toolCalls.length > 0 || result.text.trim()))
|
|
360
373
|
base.hookState = { ...currentHookState(snapshot), feedback: [] };
|
|
374
|
+
const stalled = config.outputRecoveryPolicy === 'response-boundary/v4' && reasoningStall(result);
|
|
375
|
+
// Keep the narrowed retry through transport errors and context preparation.
|
|
376
|
+
// A sealed cutoff with text or an unfinished tool call uses the ordinary budget again.
|
|
377
|
+
if (snapshot.reasoningStallRetry && (result.kind === 'tool_calls' || result.kind === 'final_candidate'
|
|
378
|
+
|| result.kind === 'output_limit' && !stalled))
|
|
379
|
+
base.reasoningStallRetry = false;
|
|
361
380
|
const message = { role: 'assistant', content: result.text,
|
|
362
381
|
...(config.contextPolicy?.pruneIdleThresholdMinutes !== undefined && Number.isSafeInteger(now) && now >= 0
|
|
363
382
|
&& ['tool_calls', 'final_candidate', 'output_limit'].includes(result.kind) ? { completedAtMs: now } : {}),
|
|
364
383
|
...(replay ? { providerReplay: replay, ...(result.replayToolIds ? { replayToolIds: result.replayToolIds } : {}) } : {}) };
|
|
365
384
|
switch (result.kind) {
|
|
366
385
|
case 'tool_calls':
|
|
386
|
+
if (initialPlanPending(snapshot, config)) {
|
|
387
|
+
const errors = snapshot.modelErrors + 1, exhausted = errors > config.profile.maxRetries;
|
|
388
|
+
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', pendingTools: [],
|
|
389
|
+
modelErrors: errors, outcome: exhausted ? 'blocked' : null, reason: exhausted ? 'initial_plan_invalid' : null };
|
|
390
|
+
}
|
|
367
391
|
if (responseContinuationPending(snapshot, config)) {
|
|
368
392
|
const errors = snapshot.modelErrors + 1, exhausted = errors > config.profile.maxRetries;
|
|
369
393
|
return { ...base, pendingTools: [], modelErrors: errors, phase: exhausted ? 'finalizing' : 'preparing_context',
|
|
@@ -422,6 +446,17 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
422
446
|
continuations: 0, modelErrors: 0,
|
|
423
447
|
...(responseScopedOutputRestarts(config) ? { outputRestarts: 0 } : {}) };
|
|
424
448
|
case 'final_candidate': {
|
|
449
|
+
if (initialPlanPending(snapshot, config)) {
|
|
450
|
+
const text = completeContinuation(snapshot.messages, result.text, digest).trim();
|
|
451
|
+
if (!text) {
|
|
452
|
+
const errors = snapshot.modelErrors + 1, exhausted = errors > config.profile.maxRetries;
|
|
453
|
+
return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', modelErrors: errors,
|
|
454
|
+
outcome: exhausted ? 'failed' : null, reason: exhausted ? 'initial_plan_empty' : null };
|
|
455
|
+
}
|
|
456
|
+
return { ...base, phase: 'preparing_context', initialPlanCompleted: true, modelErrors: 0,
|
|
457
|
+
continuations: 0, outputRestarts: 0,
|
|
458
|
+
messages: [...snapshot.messages, { role: 'assistant', kind: 'initial_plan', content: text }] };
|
|
459
|
+
}
|
|
425
460
|
if (config.contract.finalSubmissionSchema) {
|
|
426
461
|
const errors = snapshot.modelErrors + 1;
|
|
427
462
|
const exhausted = errors > config.profile.maxRetries || modelRoom(snapshot, config) <= 0;
|
|
@@ -438,6 +473,10 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
438
473
|
}
|
|
439
474
|
case 'output_limit': {
|
|
440
475
|
const resumable = config.outputRestartPolicy === 'per-response/v2';
|
|
476
|
+
const boundedRecovery = config.outputRecoveryPolicy === 'response-boundary/v4' || config.outputRecoveryPolicy === 'response-boundary/v5';
|
|
477
|
+
// Honor stricter caller limits. The experimental retry spends the same
|
|
478
|
+
// continuation allowance as the ordinary retry.
|
|
479
|
+
const continuationLimit = boundedRecovery ? Math.min(config.profile.maxContinuations, 2) : config.profile.maxContinuations;
|
|
441
480
|
const continuation = () => {
|
|
442
481
|
const mode = result.text ? outputRecoveryMode({ ...snapshot, ...base }, config, advertisedTools({ ...snapshot, ...base }, config, policies).length > 0, result) : 'empty_output';
|
|
443
482
|
const responseId = snapshot.pendingIntent ?? `${snapshot.runId}:model:${snapshot.usage.modelCalls}`;
|
|
@@ -458,11 +497,22 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
|
|
|
458
497
|
? { phase: 'paused', resumePhase: 'preparing_context', outcome: null, reason: 'output_budget_exhausted',
|
|
459
498
|
messages: result.text ? continuation().messages : snapshot.messages }
|
|
460
499
|
: { phase: 'finalizing', outcome: 'unverified', reason: 'continuation_budget_exhausted' };
|
|
461
|
-
if (
|
|
500
|
+
if (stalled) {
|
|
501
|
+
if (snapshot.reasoningStallRetry || snapshot.continuations >= continuationLimit
|
|
502
|
+
|| reasoningStallRetryTokens(config.profile.maxOutputTokens) >= config.profile.maxOutputTokens)
|
|
503
|
+
return { ...base, ...exhausted(), messages: snapshot.messages };
|
|
504
|
+
const suffix = responseContinuationPending(snapshot, config);
|
|
505
|
+
return { ...base, phase: 'preparing_context', reasoningStallRetry: true, continuations: snapshot.continuations + 1,
|
|
506
|
+
messages: [...snapshot.messages, { role: 'user',
|
|
507
|
+
kind: suffix ? 'response_continuation_feedback' : 'output_limit_reasoning_observation',
|
|
508
|
+
content: suffix ? 'Continue with only the missing text suffix now.'
|
|
509
|
+
: 'The previous attempt spent its output budget on reasoning without taking action. Take the next useful tool action now, or answer directly if the task is complete.' }] };
|
|
510
|
+
}
|
|
511
|
+
if (snapshot.continuations >= continuationLimit) {
|
|
462
512
|
// Committed answer text stays a suffix contract even when the first
|
|
463
513
|
// response has no remaining continuation allowance. It is not a tool
|
|
464
514
|
// fragment that may be discarded for an output restart.
|
|
465
|
-
if (responseContinuationPending(snapshot, config) || resumable && continuation().mode === 'suffix')
|
|
515
|
+
if (boundedRecovery || responseContinuationPending(snapshot, config) || resumable && continuation().mode === 'suffix')
|
|
466
516
|
return { ...base, ...exhausted() };
|
|
467
517
|
if (snapshot.outputRestarts < config.limits.maxOutputRestarts) {
|
|
468
518
|
try {
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { CommitBatch, Message, ModelResult, ObjectValue, RunConfiguration, RunSnapshot, StoredRun } from './contracts.mjs';
|
|
2
2
|
type Digest = (value: unknown) => string;
|
|
3
|
+
export declare function reasoningStall(result: ModelResult): boolean;
|
|
4
|
+
export declare function reasoningStallRetryTokens(maxOutputTokens: number): number;
|
|
3
5
|
/** Select from actual admission after the completed model claim, never the catalog. */
|
|
4
6
|
export declare function outputRecoveryMode(snapshot: RunSnapshot, config: RunConfiguration, toolsAvailable: boolean, result?: ModelResult): 'suffix' | 'task_resume';
|
|
5
7
|
/** Only a contiguous host-sealed suffix chain can contribute to a delivery. */
|
package/dist/output-recovery.mjs
CHANGED
|
@@ -1,12 +1,22 @@
|
|
|
1
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
|
+
export function reasoningStall(result) {
|
|
5
|
+
// The adapter detects unfinished wire tool calls even when they aren't
|
|
6
|
+
// executable. Missing usage or a mixed response isn't proof of pure reasoning.
|
|
7
|
+
return result.kind === 'output_limit' && result.outputBoundary === 'no-visible-output/v1'
|
|
8
|
+
&& !result.text.trim() && !result.toolCalls.length && result.usageReported === true
|
|
9
|
+
&& result.usage.outputTokens > 0 && result.usage.reasoningTokens === result.usage.outputTokens;
|
|
10
|
+
}
|
|
11
|
+
export function reasoningStallRetryTokens(maxOutputTokens) {
|
|
12
|
+
return Math.max(1, Math.min(8192, Math.floor(maxOutputTokens / 2)));
|
|
13
|
+
}
|
|
4
14
|
/** Select from actual admission after the completed model claim, never the catalog. */
|
|
5
15
|
export function outputRecoveryMode(snapshot, config, toolsAvailable, result) {
|
|
6
16
|
if (responseBoundaryRecovery(config) && config.contract.finalOutputFormat === 'text') {
|
|
7
17
|
// A provider length boundary identifies truncated text, not task completion.
|
|
8
18
|
// Preserve explicit sealed delivery, otherwise retain the admitted tools.
|
|
9
|
-
if (config.outputRecoveryPolicy
|
|
19
|
+
if (config.outputRecoveryPolicy !== 'response-boundary/v2')
|
|
10
20
|
return responseContinuationPending(snapshot, config) || !toolsAvailable ? 'suffix' : 'task_resume';
|
|
11
21
|
if (responseContinuationPending(snapshot, config)
|
|
12
22
|
|| result?.textCommitVersion === 'provider-finished-text/v1' && result.outputBoundary === 'assistant-text/v1')
|
package/dist/recovery.mjs
CHANGED
|
@@ -11,6 +11,8 @@ export function safeReadRecoveryCalls(calls, configuration) {
|
|
|
11
11
|
function replayPolicy(intent, configuration) {
|
|
12
12
|
if (intent.kind === 'workspace')
|
|
13
13
|
return 'workspace-observation/v1';
|
|
14
|
+
if (intent.kind === 'verify' && configuration.hostVerification)
|
|
15
|
+
return 'host-verification-read/v1';
|
|
14
16
|
if (intent.kind === 'model' && configuration.modelRecoveryPolicy === 'pure-inference/v1')
|
|
15
17
|
return 'pure-inference/v1';
|
|
16
18
|
if (intent.kind === 'tool') {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/** The output recovery strategy is versioned separately from the sealed v2
|
|
2
2
|
* text-fragment protocol. A v3 task may still own an explicit suffix chain. */
|
|
3
3
|
export function responseBoundaryRecovery(config) {
|
|
4
|
-
return config.outputRecoveryPolicy === 'response-boundary/v2' || config.outputRecoveryPolicy === 'response-boundary/v3'
|
|
4
|
+
return config.outputRecoveryPolicy === 'response-boundary/v2' || config.outputRecoveryPolicy === 'response-boundary/v3'
|
|
5
|
+
|| config.outputRecoveryPolicy === 'response-boundary/v4' || config.outputRecoveryPolicy === 'response-boundary/v5';
|
|
5
6
|
}
|
|
6
7
|
export function responseScopedOutputRestarts(config) {
|
|
7
8
|
return config.outputRestartPolicy === 'per-response/v1' || config.outputRestartPolicy === 'per-response/v2';
|
package/dist/transitions.mjs
CHANGED
|
@@ -151,7 +151,8 @@ export function reduceCommand(snapshot, command, pending = null, bindings = {})
|
|
|
151
151
|
else
|
|
152
152
|
changes = { phase: snapshot.resumePhase ?? 'preparing_context', resumePhase: null,
|
|
153
153
|
...(snapshot.reason === 'output_budget_exhausted' && bindings.configuration?.outputRestartPolicy === 'per-response/v2'
|
|
154
|
-
? { reason: null, continuations: 0, outputRestarts: 0
|
|
154
|
+
? { reason: null, continuations: 0, outputRestarts: 0,
|
|
155
|
+
...(snapshot.reasoningStallRetry ? { reasoningStallRetry: false } : {}) } : {}),
|
|
155
156
|
...(bindings.configuration?.approvalOutcomePolicy === APPROVAL_OUTCOME_POLICY
|
|
156
157
|
&& ['approval_rejected', 'approval_cancelled', 'approval_unavailable'].includes(snapshot.reason ?? '') ? { reason: null } : {}),
|
|
157
158
|
...(['provider_unavailable', 'context_summary_unavailable', 'context_source_unavailable', 'child_paused']
|
package/package.json
CHANGED
package/src/configuration.mts
CHANGED
|
@@ -28,6 +28,7 @@ export interface ConfigurationInput {
|
|
|
28
28
|
contract: Pick<TaskContract, 'objective'> & Partial<TaskContract>;
|
|
29
29
|
tools?: ToolDefinition[]; limits?: Partial<RunLimits>; instructions?: string;
|
|
30
30
|
hostBindingDigest: string; contextSources?: RunConfiguration['contextSources']; hooks?: RunConfiguration['hooks'];
|
|
31
|
+
hostVerification?: RunConfiguration['hostVerification'];
|
|
31
32
|
stopHookContinuationLimit?: number; delegationDepth?: number;
|
|
32
33
|
modelRecoveryPolicy?: RunConfiguration['modelRecoveryPolicy'];
|
|
33
34
|
guidancePolicy?: RunConfiguration['guidancePolicy'];
|
|
@@ -47,6 +48,7 @@ export interface ConfigurationInput {
|
|
|
47
48
|
childTaskPolicy?: RunConfiguration['childTaskPolicy'];
|
|
48
49
|
coordinatorResponsePolicy?: RunConfiguration['coordinatorResponsePolicy'];
|
|
49
50
|
planModePolicy?: RunConfiguration['planModePolicy'];
|
|
51
|
+
initialPlanPolicy?: RunConfiguration['initialPlanPolicy'];
|
|
50
52
|
planModeInitialActive?: boolean;
|
|
51
53
|
childPlanPolicy?: RunConfiguration['childPlanPolicy'];
|
|
52
54
|
toolErrorRecoveryModelCalls?: RunConfiguration['toolErrorRecoveryModelCalls'];
|
|
@@ -90,6 +92,7 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
90
92
|
...(input.childCapabilityPolicy === undefined ? {} : { childCapabilityPolicy: input.childCapabilityPolicy }),
|
|
91
93
|
...(input.sessionInjectionPolicy === undefined ? {} : { sessionInjectionPolicy: input.sessionInjectionPolicy }),
|
|
92
94
|
tools: input.tools ?? [], instructions: input.instructions ?? '', hostBindingDigest: input.hostBindingDigest,
|
|
95
|
+
...(input.hostVerification === undefined ? {} : { hostVerification: input.hostVerification }),
|
|
93
96
|
inputMessages: input.inputMessages ?? null,
|
|
94
97
|
...(input.conversationSeed === undefined ? {} : { conversationSeed: input.conversationSeed }),
|
|
95
98
|
...(input.conversationRewind === undefined ? {} : { conversationRewind: input.conversationRewind }),
|
|
@@ -110,6 +113,7 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
110
113
|
...(input.childTaskPolicy === undefined ? {} : { childTaskPolicy: input.childTaskPolicy }),
|
|
111
114
|
...(input.coordinatorResponsePolicy === undefined ? {} : { coordinatorResponsePolicy: input.coordinatorResponsePolicy }),
|
|
112
115
|
...(input.planModePolicy === undefined ? {} : { planModePolicy: input.planModePolicy }),
|
|
116
|
+
...(input.initialPlanPolicy === undefined ? {} : { initialPlanPolicy: input.initialPlanPolicy }),
|
|
113
117
|
...(input.planModeInitialActive === undefined ? {} : { planModeInitialActive: input.planModeInitialActive }),
|
|
114
118
|
...(input.childPlanPolicy === undefined ? {} : { childPlanPolicy: input.childPlanPolicy }),
|
|
115
119
|
...(input.toolErrorRecoveryModelCalls === undefined
|
|
@@ -159,9 +163,9 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
159
163
|
&& typeof config.hostRecoveryBinding === 'object' && !Array.isArray(config.hostRecoveryBinding), 'invalid_host_recovery_binding');
|
|
160
164
|
invariant(config.guidancePolicy == null || config.guidancePolicy === 'boundary-guide/v1', 'invalid_guidance_policy');
|
|
161
165
|
invariant(config.inputPolicy === undefined || config.inputPolicy === 'before-first-model/v1', 'invalid_input_policy');
|
|
162
|
-
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2', 'response-boundary/v3'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
166
|
+
invariant(config.outputRecoveryPolicy == null || ['task-or-delivery/v1', 'response-boundary/v2', 'response-boundary/v3', 'response-boundary/v4', 'response-boundary/v5'].includes(config.outputRecoveryPolicy), 'invalid_output_recovery_policy');
|
|
163
167
|
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');
|
|
168
|
+
&& ['response-boundary/v2', 'response-boundary/v3', 'response-boundary/v4', 'response-boundary/v5'].includes(config.outputRecoveryPolicy ?? ''), 'invalid_output_restart_policy');
|
|
165
169
|
invariant(config.approvalOutcomePolicy === undefined || config.approvalOutcomePolicy === 'owner-outcome/v1', 'invalid_approval_outcome_policy');
|
|
166
170
|
invariant(config.providerRecoveryPolicy == null || config.providerRecoveryPolicy === 'provider-recovery/v2', 'invalid_provider_recovery_policy');
|
|
167
171
|
invariant(config.toolExecutionPolicy === undefined || config.toolExecutionPolicy === 'owner-execution/v1', 'invalid_tool_execution_policy');
|
|
@@ -288,6 +292,19 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
288
292
|
validateDeliveryConfiguration(config);
|
|
289
293
|
validateCoordinatorConfiguration(config);
|
|
290
294
|
validatePlanModeConfiguration(config);
|
|
295
|
+
const verifier = config.hostVerification;
|
|
296
|
+
if (verifier !== undefined) {
|
|
297
|
+
invariant(verifier && /^sha256:[a-f0-9]{64}$/.test(verifier.bindingDigest)
|
|
298
|
+
&& config.contract.acceptance.some(item => item.required && item.verificationMethod === 'deterministic'
|
|
299
|
+
&& item.verifierRef === verifier.verifierRef && item.verifierVersion === verifier.verifierVersion)
|
|
300
|
+
&& Array.isArray(verifier.evidenceTools) && verifier.evidenceTools.length <= 16
|
|
301
|
+
&& new Set(verifier.evidenceTools).size === verifier.evidenceTools.length
|
|
302
|
+
&& verifier.evidenceTools.every(name => config.tools.some(tool => tool.name === name))
|
|
303
|
+
&& (verifier.contextSourceId === null || config.contextSources.some(source => source.sourceId === verifier.contextSourceId)),
|
|
304
|
+
'invalid_host_verification_binding');
|
|
305
|
+
}
|
|
306
|
+
invariant(config.initialPlanPolicy === undefined || config.initialPlanPolicy === 'plan-act-observe/v1',
|
|
307
|
+
'invalid_initial_plan_policy');
|
|
291
308
|
const names = new Set<string>();
|
|
292
309
|
for (const tool of config.tools) {
|
|
293
310
|
invariant(tool.name.trim() && !names.has(tool.name), 'duplicate_or_invalid_tool');
|
|
@@ -296,6 +313,11 @@ export function configure(input: ConfigurationInput): RunConfiguration {
|
|
|
296
313
|
invariant(Number.isFinite(tool.timeoutMs) && tool.timeoutMs > 0 && tool.timeoutMs < limits.effectTimeoutMs, 'invalid_tool_timeout');
|
|
297
314
|
invariant(tool.executionTimeoutPolicy === undefined || ['dispatch/v1', 'dispatch/v2'].includes(tool.executionTimeoutPolicy), 'invalid_tool_execution_timeout_policy');
|
|
298
315
|
invariant(tool.approvalPolicy === undefined || tool.approvalPolicy === 'durable-preflight/v1', 'invalid_tool_approval_policy');
|
|
316
|
+
invariant(tool.hostApprovalRequired === undefined || tool.hostApprovalRequired === true
|
|
317
|
+
&& tool.approvalPolicy === 'durable-preflight/v1', 'invalid_tool_host_approval_policy');
|
|
318
|
+
invariant(tool.hostEffectProtocol === undefined
|
|
319
|
+
|| tool.hostEffectProtocol === 'agentkit.engine-host-tool-effect/v1' && !tool.readOnly,
|
|
320
|
+
'invalid_tool_host_effect_protocol');
|
|
299
321
|
invariant(!tool.concurrentSafe || tool.readOnly && tool.observationRole === 'none', 'invalid_tool_concurrency');
|
|
300
322
|
invariant(tool.workspaceEditPolicy === undefined || ['zcode-match/v1', 'zcode-match/v2'].includes(tool.workspaceEditPolicy)
|
|
301
323
|
&& ['edit_workspace_file', 'multi_edit_workspace_file'].includes(tool.name)
|
|
@@ -28,6 +28,10 @@ export function validateContextSource(source: ContextSourceDefinition, timeoutMs
|
|
|
28
28
|
'invalid_context_source');
|
|
29
29
|
invariant(source.instructionPolicy === undefined || source.instructionPolicy === 'current-files/v1' && source.required,
|
|
30
30
|
'invalid_context_instruction_source');
|
|
31
|
+
invariant(source.hostProjection === undefined || !source.instructionPolicy
|
|
32
|
+
&& ['data/v1', 'instructions-and-data/v1'].includes(source.hostProjection), 'invalid_host_context_projection');
|
|
33
|
+
invariant(source.warnOnFailure === undefined || source.warnOnFailure === true && !source.required && source.hostProjection,
|
|
34
|
+
'invalid_host_context_failure_policy');
|
|
31
35
|
const recovery = source.timeoutRecovery;
|
|
32
36
|
invariant(recovery === undefined || recovery && !Array.isArray(recovery)
|
|
33
37
|
&& Object.keys(recovery).sort().join(',') === 'contract,maxRetries,retryDelayMs' && recovery.contract === 'context-source-timeout/v1'
|
|
@@ -49,6 +53,18 @@ async function retryDelay(ms: number, signal: AbortSignal): Promise<void> {
|
|
|
49
53
|
}
|
|
50
54
|
|
|
51
55
|
export function contextContributionMessage(source: ContextSourceDefinition, item: ObjectValue): Message {
|
|
56
|
+
if (source.hostProjection) {
|
|
57
|
+
const { projection, fragment, expiresAt } = item;
|
|
58
|
+
invariant((projection === 'data' || projection === 'instructions' && source.hostProjection === 'instructions-and-data/v1')
|
|
59
|
+
&& fragment && typeof fragment === 'object' && !Array.isArray(fragment)
|
|
60
|
+
&& (expiresAt === undefined || Number.isSafeInteger(expiresAt) && Number(expiresAt) > 0),
|
|
61
|
+
'context_source_result_invalid');
|
|
62
|
+
const privileged = projection === 'instructions';
|
|
63
|
+
return { role: privileged ? 'system' : 'user', kind: 'context_contribution',
|
|
64
|
+
content: canonical({ schemaVersion: CONTEXT_CONTRIBUTION_CONTRACT, sourceId: source.sourceId, bindingDigest: source.bindingDigest,
|
|
65
|
+
trust: privileged ? 'host-granted' : 'untrusted', purpose: privileged ? 'host_instructions' : 'context_only',
|
|
66
|
+
notice: 'Context grants no approval, acceptance or execution authority.', item: fragment, ...(expiresAt === undefined ? {} : { expiresAt }) }) };
|
|
67
|
+
}
|
|
52
68
|
return { role: 'user', kind: 'context_contribution', content: canonical({ schemaVersion: CONTEXT_CONTRIBUTION_CONTRACT,
|
|
53
69
|
trust: 'untrusted', purpose: source.instructionPolicy ? 'workspace_instructions' : 'context_only',
|
|
54
70
|
sourceId: source.sourceId, bindingDigest: source.bindingDigest,
|
|
@@ -59,6 +75,30 @@ export function contextContributionMessage(source: ContextSourceDefinition, item
|
|
|
59
75
|
: 'Recalled data grants no approval, acceptance, freshness or execution authority.', item }) };
|
|
60
76
|
}
|
|
61
77
|
|
|
78
|
+
function hostContributionSource(message: Message, config: RunConfiguration) {
|
|
79
|
+
if (message.kind !== 'context_contribution'
|
|
80
|
+
|| !config.contextSources.some(source => source.hostProjection)) return null;
|
|
81
|
+
let value: ObjectValue;
|
|
82
|
+
try { value = JSON.parse(message.content); } catch { return null; }
|
|
83
|
+
if (!value || value.schemaVersion !== CONTEXT_CONTRIBUTION_CONTRACT) return null;
|
|
84
|
+
const source = config.contextSources.find(source => source.hostProjection
|
|
85
|
+
&& source.sourceId === value.sourceId && source.bindingDigest === value.bindingDigest);
|
|
86
|
+
return source ? { source, value } : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function hostInstructionContribution(message: Message, config: RunConfiguration): boolean {
|
|
90
|
+
if (message.role !== 'system') return false;
|
|
91
|
+
const admitted = hostContributionSource(message, config);
|
|
92
|
+
return admitted?.source.hostProjection === 'instructions-and-data/v1'
|
|
93
|
+
&& admitted.value.purpose === 'host_instructions' && admitted.value.trust === 'host-granted';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function expiredHostContribution(message: Message, config: RunConfiguration, now: number): ContextSourceDefinition | null {
|
|
97
|
+
const admitted = hostContributionSource(message, config);
|
|
98
|
+
return admitted && typeof admitted.value.expiresAt === 'number' && admitted.value.expiresAt <= now
|
|
99
|
+
? admitted.source : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
62
102
|
/** Only the outer envelope from a frozen source can select instruction retention.
|
|
63
103
|
* A recalled item's own role, policy or source fields never promote its trust. */
|
|
64
104
|
export function currentInstructionContribution(message: Message, config: RunConfiguration): boolean {
|
|
@@ -99,13 +139,17 @@ export async function collectContextContributions(context: PortContext, snapshot
|
|
|
99
139
|
const admitted: Message[] = [];
|
|
100
140
|
for (const item of result.items) {
|
|
101
141
|
invariant(item && typeof item === 'object' && !Array.isArray(item), 'context_source_result_invalid');
|
|
102
|
-
const
|
|
142
|
+
const message = contextContributionMessage(source, item);
|
|
143
|
+
invariant(!expiredHostContribution(message, config, Date.now()), 'context_source_expired');
|
|
144
|
+
const candidate = [...admitted, message];
|
|
103
145
|
if (new TextEncoder().encode(canonical(candidate)).length > source.maxBytes) {
|
|
146
|
+
invariant(!source.hostProjection, 'context_source_byte_budget_exceeded');
|
|
104
147
|
invariant(!source.instructionPolicy, 'context_instruction_source_byte_budget_exceeded'); continue;
|
|
105
148
|
}
|
|
106
149
|
const tokens = await Promise.race([count(copy(candidate)), canceled]); signal.throwIfAborted();
|
|
107
150
|
invariant(Date.now() < deadline, 'context_source_timeout');
|
|
108
151
|
invariant(Number.isSafeInteger(tokens) && tokens >= 0, 'context_token_count_invalid');
|
|
152
|
+
invariant(!source.hostProjection || tokens <= source.maxTokens, 'context_source_token_budget_exceeded');
|
|
109
153
|
invariant(!source.instructionPolicy || tokens <= source.maxTokens, 'context_instruction_source_token_budget_exceeded');
|
|
110
154
|
if (tokens <= source.maxTokens) admitted.push(candidate.at(-1)!);
|
|
111
155
|
}
|
|
@@ -125,7 +169,14 @@ export async function collectContextContributions(context: PortContext, snapshot
|
|
|
125
169
|
if (source.required) throw new ContextSourceUnavailable(source.sourceId, source.bindingDigest, attempt);
|
|
126
170
|
}
|
|
127
171
|
if (source.required) throw error;
|
|
128
|
-
|
|
172
|
+
if (source.warnOnFailure) {
|
|
173
|
+
const message = contextContributionMessage(source, { projection: 'data',
|
|
174
|
+
fragment: { status: 'unavailable', code: 'context_source_unavailable' } });
|
|
175
|
+
if (new TextEncoder().encode(canonical([message])).length <= source.maxBytes
|
|
176
|
+
&& await count([message]).catch(() => Infinity) <= source.maxTokens) messages.push(message);
|
|
177
|
+
}
|
|
178
|
+
context.signal.throwIfAborted();
|
|
179
|
+
diagnostics.push({ sourceId: source.sourceId, bindingDigest: source.bindingDigest, status: source.warnOnFailure ? 'warned' : 'skipped',
|
|
129
180
|
...(source.timeoutRecovery ? { timeoutRetries: attempt } : {}) });
|
|
130
181
|
break;
|
|
131
182
|
} finally {
|