@kingsoftcloud/agentkit-harness-core 0.0.30 → 0.0.31

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.
@@ -3,6 +3,7 @@ import type { BackgroundCommandObservation, BackgroundCommandRequest, Background
3
3
  export declare function rememberCommand(snapshot: RunSnapshot, result: ToolResult, definition?: ToolDefinition): BackgroundCommandState[];
4
4
  /** Only controlled context/model boundaries can collect already-owned handles. */
5
5
  export declare function commandProbe(snapshot: RunSnapshot, configuration: RunConfiguration, intent?: EffectIntent | null): BackgroundCommandRequest | null;
6
+ export declare function commandObservations(request: BackgroundCommandRequest, input: unknown): BackgroundCommandObservation[];
6
7
  /** Notice and deduplication marker commit together. Output remains untrusted data. */
7
8
  export declare function stageCommandObservations(snapshot: RunSnapshot, configuration: RunConfiguration, request: BackgroundCommandRequest, input: unknown, intent?: EffectIntent | null, elapsedMs?: number): CommitBatch;
8
9
  /** The ledger only retires an unclaimed model for the complete, reproducible observation transaction. */
@@ -39,11 +39,7 @@ export function commandProbe(snapshot, configuration, intent = null) {
39
39
  sessionId: snapshot.sessionId, turnId: snapshot.turnId, buildId: snapshot.buildId, parentRunId: snapshot.parentRunId,
40
40
  taskChainId: snapshot.taskChainId, operationKey: `${runKey(snapshot.scope, snapshot.runId)}:background-probe:${snapshot.revision}`, cursor, refs };
41
41
  }
42
- /** Notice and deduplication marker commit together. Output remains untrusted data. */
43
- export function stageCommandObservations(snapshot, configuration, request, input, intent = null, elapsedMs = 0) {
44
- const expected = commandProbe(snapshot, configuration, intent);
45
- invariant(expected && canonical(expected) === canonical(request), 'background_command_notification_request_identity_conflict');
46
- invariant(Number.isFinite(elapsedMs) && elapsedMs >= 0, 'invalid_background_probe_elapsed');
42
+ export function commandObservations(request, input) {
47
43
  invariant(Array.isArray(input) && input.length <= 8, 'background_command_notification_batch_exceeded');
48
44
  const observations = input.map(backgroundCommandObservation);
49
45
  const owned = new Map(request.refs.map(ref => [ref.taskId, ref])), ids = new Set();
@@ -51,6 +47,15 @@ export function stageCommandObservations(snapshot, configuration, request, input
51
47
  invariant(!ids.has(observation.ref.taskId) && canonical(owned.get(observation.ref.taskId) ?? null) === canonical(observation.ref), 'background_command_notification_identity_conflict');
52
48
  ids.add(observation.ref.taskId);
53
49
  }
50
+ return observations;
51
+ }
52
+ /** Notice and deduplication marker commit together. Output remains untrusted data. */
53
+ export function stageCommandObservations(snapshot, configuration, request, input, intent = null, elapsedMs = 0) {
54
+ const expected = commandProbe(snapshot, configuration, intent);
55
+ invariant(expected && canonical(expected) === canonical(request), 'background_command_notification_request_identity_conflict');
56
+ invariant(Number.isFinite(elapsedMs) && elapsedMs >= 0, 'invalid_background_probe_elapsed');
57
+ const observations = commandObservations(request, input);
58
+ const ids = new Set(observations.map(item => item.ref.taskId));
54
59
  const activeElapsedMs = snapshot.activeElapsedMs + elapsedMs;
55
60
  const uncertain = observations.some(item => ['unknown', 'unavailable'].includes(item.status));
56
61
  const exhausted = configuration.limits.maxWallMs !== null && activeElapsedMs >= configuration.limits.maxWallMs;
@@ -3,7 +3,7 @@ import { directoryProgressQuote } from './directory-progress.mjs';
3
3
  import { NativePolicyRegistry } from './policy-registry.mjs';
4
4
  import { contextSourceDigest, validateContextMessages } from './context-view.mjs';
5
5
  import { assertHookFeedbackRetained } from './hook-runtime.mjs';
6
- import { retryDelay } from './retry.mjs';
6
+ import { providerRetryDeadline, retryDeadline, retryDelay } from './retry.mjs';
7
7
  import { artifactProgressIdentity } from './artifact-runtime.mjs';
8
8
  import { sourceWorkingSetGroup } from './source-working-set-group.mjs';
9
9
  import { sourceReuseProjector } from './context-source-reuse.mjs';
@@ -620,12 +620,16 @@ export function reduceContextModel(snapshot, result, config, usage, now, random)
620
620
  else
621
621
  compaction.errors = attempts;
622
622
  const limit = provider ? config.profile.maxProviderRetries : config.contextPolicy.maxSummaryRetries;
623
+ const delay = retryDelay(result, attempts, config, random);
624
+ const providerRetryNotBefore = providerRetryDeadline(result, now);
625
+ const providerWait = providerRetryNotBefore === undefined ? {} : { providerRetryNotBefore };
623
626
  if (attempts > limit) {
624
627
  if (adaptive || provider && config.providerRecoveryPolicy === 'provider-recovery/v2') {
625
628
  compaction.errors = 0;
626
629
  compaction.providerErrors = 0;
627
630
  return { ...base, phase: 'paused', resumePhase: 'compacting', outcome: null,
628
- reason: provider ? 'provider_unavailable' : 'context_summary_unavailable', retryNotBefore: 0 };
631
+ reason: provider ? 'provider_unavailable' : 'context_summary_unavailable',
632
+ retryNotBefore: providerRetryNotBefore ?? 0, ...providerWait };
629
633
  }
630
634
  return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'context_summary_retry_exhausted' };
631
635
  }
@@ -646,5 +650,5 @@ export function reduceContextModel(snapshot, result, config, usage, now, random)
646
650
  compaction.quoteLimit = Math.max(1, Math.floor(length / 2));
647
651
  compaction.chunk = null;
648
652
  }
649
- return { ...base, retryNotBefore: now + retryDelay(result, attempts, config, random) };
653
+ return { ...base, retryNotBefore: retryDeadline(now, delay), ...providerWait };
650
654
  }
@@ -893,6 +893,8 @@ export interface RunSnapshot extends RunIdentity {
893
893
  reasoningStallRetry?: boolean;
894
894
  activeElapsedMs: number;
895
895
  retryNotBefore: number;
896
+ /** Provider-requested minimum that survives a change of goal or guidance. */
897
+ providerRetryNotBefore?: number;
896
898
  candidate: CompletionCandidate | null;
897
899
  verification: VerificationReport | null;
898
900
  finalText: string;
@@ -0,0 +1,10 @@
1
+ import type { Message } from './contracts.mjs';
2
+ type CommandCheck = {
3
+ command: string;
4
+ cwd: string;
5
+ exitCode: number;
6
+ };
7
+ /** These are repair signals from committed tool results. They never qualify
8
+ * formal acceptance or infer a failed check from assistant prose. */
9
+ export declare function failedDeliveryCommands(messages: Message[]): CommandCheck[];
10
+ export {};
@@ -0,0 +1,66 @@
1
+ // Recognize explicit check invocations. Shell pipelines and arbitrary command
2
+ // chains can hide a failing exit code, so their outer status cannot qualify.
3
+ const checkRunners = [
4
+ /^(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test(?::[\w-]+)?|lint|check)(?:\s|$)/,
5
+ /^(?:node|bun|deno)\s+(?:--test\b|(?:[\w./-]+\/)?(?:test[-\w.]*|[\w.-]+\.test)\.[cm]?[jt]s)(?:\s|$)/,
6
+ /^(?:python3?\s+-m\s+)?pytest(?:\s|$)/,
7
+ /^(?:npx\s+(?:--no-install\s+)?)?playwright\s+test(?:\s|$)/,
8
+ ];
9
+ const explicitExit = /^([^;&|<>\r\n]+)[ \t]+>[ \t]*[\w./-]+[ \t]+2>&1[ \t]*;[ \t]*echo "EXIT=\$\?"(?:[ \t]*;[^\r\n]*)?$/;
10
+ function observedCheck(call, message) {
11
+ const value = call.arguments.command;
12
+ if (typeof value !== 'string' || value.length > 4096 || call.arguments.background === true
13
+ || message.toolOutcome && message.toolOutcome !== 'ok')
14
+ return null;
15
+ let receipt;
16
+ try {
17
+ receipt = JSON.parse(message.content);
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ if (!receipt || !['sandbox/local_process', 'sandbox/e2b'].includes(receipt.backend)
23
+ || receipt.ok !== true || receipt.evidence_incomplete !== false || receipt.command !== value
24
+ || (receipt.status !== undefined && !['completed', 'failed'].includes(receipt.status))
25
+ || !Number.isSafeInteger(receipt.exit_code) || receipt.exit_code < 0)
26
+ return null;
27
+ const cd = /^cd[ \t]+([-\w./]+)[ \t]*&&[ \t]*/.exec(value.trim());
28
+ const shell = value.trim().slice(cd?.[0].length ?? 0);
29
+ const captured = explicitExit.exec(shell);
30
+ const command = captured ? captured[1].trim() : shell;
31
+ if (/[;&|<>\r\n\x60$]/.test(command) || !checkRunners.some(pattern => pattern.test(command)))
32
+ return null;
33
+ const exitCode = captured
34
+ ? Number(typeof receipt.stdout === 'string' ? /^EXIT=(\d+)\r?(?:\n|$)/.exec(receipt.stdout)?.[1] : undefined)
35
+ : receipt.exit_code;
36
+ if (!Number.isSafeInteger(exitCode) || exitCode < 0 || exitCode > 255)
37
+ return null;
38
+ const cwd = cd?.[1] ?? (typeof call.arguments.cwd === 'string' ? call.arguments.cwd : '.');
39
+ return { command, cwd, exitCode };
40
+ }
41
+ /** These are repair signals from committed tool results. They never qualify
42
+ * formal acceptance or infer a failed check from assistant prose. */
43
+ export function failedDeliveryCommands(messages) {
44
+ const pending = new Map(), latest = new Map();
45
+ for (const message of messages) {
46
+ // A fresh turn may point at another task, even in the same workspace.
47
+ // Durable resume of the current Run retains these original messages.
48
+ if (message.history)
49
+ continue;
50
+ if (message.role === 'assistant') {
51
+ for (const call of message.toolCalls ?? [])
52
+ if (call.name === 'run_command')
53
+ pending.set(call.callId, call);
54
+ }
55
+ else if (message.role === 'tool' && message.name === 'run_command' && message.callId) {
56
+ const call = pending.get(message.callId);
57
+ if (!call)
58
+ continue;
59
+ pending.delete(message.callId);
60
+ const check = observedCheck(call, message);
61
+ if (check)
62
+ latest.set(JSON.stringify([check.cwd, check.command]), check);
63
+ }
64
+ }
65
+ return [...latest.values()].filter(check => check.exitCode !== 0).slice(-8);
66
+ }
package/dist/kernel.d.mts CHANGED
@@ -27,6 +27,7 @@ export declare class NativeKernel {
27
27
  private readonly onStream;
28
28
  private readonly onCheckpoint;
29
29
  private readonly active;
30
+ private readonly retryWaiters;
30
31
  private readonly clockAnchors;
31
32
  private readonly childObservers;
32
33
  constructor(options: KernelOptions);
@@ -52,6 +53,7 @@ export declare class NativeKernel {
52
53
  detachSignal?: AbortSignal;
53
54
  waitForRetry?: boolean;
54
55
  }): Promise<RunSnapshot>;
56
+ private waitAtRetryBoundary;
55
57
  private inspectBackgroundCommands;
56
58
  private commit;
57
59
  private elapsed;
package/dist/kernel.mjs CHANGED
@@ -34,7 +34,7 @@ import { reduceTurnInput } from './turn-input.mjs';
34
34
  import { modelStreamCapture } from './model-stream.mjs';
35
35
  import { browserRecoveryTransition } from './browser-runtime.mjs';
36
36
  import { validateBrowserSessionRef } from './browser-contract.mjs';
37
- import { commandProbe, stageCommandObservations, unavailableCommands } from './background-runtime.mjs';
37
+ import { commandObservations, commandProbe, stageCommandObservations, unavailableCommands } from './background-runtime.mjs';
38
38
  import { assertGuidanceRetained } from './guidance.mjs';
39
39
  import { BACKGROUND_COMMAND_CONTRACT } from './background-contract.mjs';
40
40
  import { admittedToolBudget } from './child-budget.mjs';
@@ -55,6 +55,7 @@ export class NativeKernel {
55
55
  onStream;
56
56
  onCheckpoint;
57
57
  active = new Map();
58
+ retryWaiters = new Map();
58
59
  clockAnchors = new Map();
59
60
  childObservers = new Map();
60
61
  constructor(options) {
@@ -144,8 +145,11 @@ export class NativeKernel {
144
145
  }
145
146
  submit(scope, runId, command) {
146
147
  const result = this.store.enqueue(scope, runId, command);
148
+ const key = runKey(scope, runId);
149
+ if (result.status === 'accepted')
150
+ this.retryWaiters.get(key)?.();
147
151
  if (result.status !== 'rejected' && ['cancel', 'policy_revoked'].includes(command.kind)) {
148
- this.active.get(runKey(scope, runId))?.abort(new NativeError('command_interrupt'));
152
+ this.active.get(key)?.abort(new NativeError('command_interrupt'));
149
153
  }
150
154
  if (result.status === 'accepted' && ['pause', 'promote_child', 'message_child', 'cancel_child', 'resume_child'].includes(command.kind)) {
151
155
  const observer = this.childObservers.get(runKey(scope, runId));
@@ -429,7 +433,10 @@ export class NativeKernel {
429
433
  if (!wallExpired && snapshot.retryNotBefore > this.now()) {
430
434
  if (!waitForRetry)
431
435
  return snapshot;
432
- await new Promise(resolve => setTimeout(resolve, Math.min(50, snapshot.retryNotBefore - this.now())));
436
+ const wallRemaining = config.limits.maxWallMs === null ? Infinity : config.limits.maxWallMs - this.elapsed(snapshot);
437
+ // Locally submitted controls wake the wait immediately. The bounded
438
+ // poll also notices control rows enqueued by a different worker.
439
+ await this.waitAtRetryBoundary(key, Math.max(0, Math.min(500, wallRemaining, snapshot.retryNotBefore - this.now())), controller.signal);
433
440
  continue;
434
441
  }
435
442
  const backgroundIntent = record.pendingIntent;
@@ -547,35 +554,73 @@ export class NativeKernel {
547
554
  }
548
555
  }
549
556
  }
557
+ waitAtRetryBoundary(key, delay, signal) {
558
+ if (signal.aborted)
559
+ return Promise.resolve();
560
+ return new Promise(resolve => {
561
+ const wake = () => {
562
+ clearTimeout(timer);
563
+ signal.removeEventListener('abort', wake);
564
+ this.retryWaiters.delete(key);
565
+ resolve();
566
+ };
567
+ const timer = setTimeout(wake, delay);
568
+ this.retryWaiters.set(key, wake);
569
+ signal.addEventListener('abort', wake, { once: true });
570
+ });
571
+ }
550
572
  async inspectBackgroundCommands(request, snapshot, config, signal) {
551
573
  const remaining = config.limits.maxWallMs === null ? config.limits.effectTimeoutMs
552
574
  : Math.min(config.limits.effectTimeoutMs, Math.max(0, config.limits.maxWallMs - this.elapsed(snapshot)));
553
575
  if (remaining <= 0)
554
576
  return [];
555
- if (this.ports.background?.contract !== BACKGROUND_COMMAND_CONTRACT)
556
- return unavailableCommands(request);
557
- const timeout = new AbortController(), probeSignal = AbortSignal.any([signal, timeout.signal]);
558
- const timer = setTimeout(() => timeout.abort(new NativeError('background_command_probe_timeout')), remaining);
559
- let onAbort = () => { };
560
- const aborted = new Promise((_, reject) => {
561
- onAbort = () => reject(probeSignal.reason);
562
- if (probeSignal.aborted)
563
- onAbort();
564
- else
565
- probeSignal.addEventListener('abort', onAbort, { once: true });
566
- });
567
- try {
568
- const result = await Promise.race([this.ports.background.observe({ ...copy(request), signal: probeSignal }), aborted]);
569
- probeSignal.throwIfAborted();
570
- return result;
571
- }
572
- catch {
573
- return unavailableCommands(request);
574
- }
575
- finally {
576
- clearTimeout(timer);
577
- probeSignal.removeEventListener('abort', onAbort);
577
+ const port = this.ports.background;
578
+ const unavailable = unavailableCommands(request);
579
+ if (port?.contract !== BACKGROUND_COMMAND_CONTRACT)
580
+ return unavailable;
581
+ const expires = this.monotonicNow() + remaining, attempts = 3;
582
+ const settled = new Map();
583
+ let latest = unavailable;
584
+ for (let attempt = 0; attempt < attempts && !signal.aborted; attempt++) {
585
+ const left = expires - this.monotonicNow();
586
+ if (left <= 0)
587
+ break;
588
+ const timeout = new AbortController(), probeSignal = AbortSignal.any([signal, timeout.signal]);
589
+ const timer = setTimeout(() => timeout.abort(new NativeError('background_command_probe_timeout')), Math.min(2_147_483_647, Math.ceil(left / (attempts - attempt))));
590
+ let onAbort = () => { };
591
+ const aborted = new Promise((_, reject) => {
592
+ onAbort = () => reject(probeSignal.reason);
593
+ if (probeSignal.aborted)
594
+ onAbort();
595
+ else
596
+ probeSignal.addEventListener('abort', onAbort, { once: true });
597
+ });
598
+ try {
599
+ // Re-observe the sealed request. This port cannot dispatch a command.
600
+ const result = await Promise.race([port.observe({ ...copy(request), signal: probeSignal }), aborted]);
601
+ probeSignal.throwIfAborted();
602
+ latest = commandObservations(request, result);
603
+ }
604
+ catch {
605
+ latest = unavailable;
606
+ }
607
+ finally {
608
+ clearTimeout(timer);
609
+ probeSignal.removeEventListener('abort', onAbort);
610
+ }
611
+ for (const entry of latest)
612
+ if (entry.status !== 'unavailable')
613
+ settled.set(entry.ref.taskId, entry);
614
+ latest = latest.filter(entry => entry.status === 'unavailable' && !settled.has(entry.ref.taskId));
615
+ if (!latest.length)
616
+ break;
617
+ if (attempt + 1 < attempts && !signal.aborted) {
618
+ await new Promise(resolve => setTimeout(resolve, Math.min(50 * (attempt + 1), Math.max(0, expires - this.monotonicNow()))));
619
+ }
578
620
  }
621
+ for (const entry of latest)
622
+ settled.set(entry.ref.taskId, entry);
623
+ return request.refs.flatMap(ref => settled.get(ref.taskId) ?? []).slice(0, 8);
579
624
  }
580
625
  commit(snapshot, lease, batch) {
581
626
  const now = this.now(), measuredAt = this.monotonicNow(), key = runKey(snapshot.scope, snapshot.runId);
@@ -827,7 +872,7 @@ export class NativeKernel {
827
872
  facts.push({ kind: 'context.summary_completed', payload: { kind: result.kind, usage: objectValue(result.usage),
828
873
  messageCursor: snapshot.messages.length, usageReported: result.usageReported !== false,
829
874
  proposalAvailable: !!changes.contextState?.compaction?.proposal } });
830
- if (typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
875
+ if (changes.phase !== 'paused' && typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
831
876
  facts.push({ kind: 'model.retry_scheduled', payload: { retryAt: Math.ceil(changes.retryNotBefore), purpose: 'compaction',
832
877
  attempt: result.kind === 'provider_retryable_error' ? changes.contextState?.compaction?.providerErrors ?? 1
833
878
  : changes.contextState?.compaction?.errors ?? 1,
@@ -878,7 +923,7 @@ export class NativeKernel {
878
923
  messageCursor: changes.messages?.length ?? snapshot.messages.length,
879
924
  usageReported: result.usageReported !== false,
880
925
  toolCalls: planning ? [] : result.toolCalls.map(objectValue), usage: objectValue(result.usage) } });
881
- if (typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
926
+ if (changes.phase !== 'paused' && typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
882
927
  facts.push({ kind: 'model.retry_scheduled', payload: { retryAt: Math.ceil(changes.retryNotBefore),
883
928
  attempt: result.kind === 'provider_retryable_error' ? changes.providerErrors ?? 1 : changes.modelErrors ?? 1,
884
929
  ...(result.failureDiagnostic ? { failure: objectValue(result.failureDiagnostic) } : {}) } });
package/dist/machine.mjs CHANGED
@@ -2,7 +2,7 @@ import { emptyUsage } from './contracts.mjs';
2
2
  import { advanceDirectoryProgress } from './directory-progress.mjs';
3
3
  import { copy, invariant, canonical } from './values.mjs';
4
4
  import { prepareEffect, transition } from './transitions.mjs';
5
- import { retryDelay } from './retry.mjs';
5
+ import { providerRetryDeadline, retryDeadline, retryDelay } from './retry.mjs';
6
6
  import { FINAL_SUBMISSION_TOOL, finalSubmissionTool, submittedFinalText, normalizedFinalText, finalDeliveryChanges } from './final-submission.mjs';
7
7
  import { currentHookState, pendingHookFeedback, planHook } from './hook-runtime.mjs';
8
8
  import { projectToolResultContext, deferredToolContexts } from './tool-context.mjs';
@@ -26,6 +26,7 @@ import { reduceCoordinatorResponses } from './coordinator-response.mjs';
26
26
  import { RESULT_DELIVERY_POLICY } from './deliverables.mjs';
27
27
  import { validateModelTransport } from './model-transport.mjs';
28
28
  import { validateModelFailure } from './model-failure.mjs';
29
+ import { failedDeliveryCommands } from './delivery-command-checks.mjs';
29
30
  export function objectValue(value) {
30
31
  invariant(value !== null && typeof value === 'object' && !Array.isArray(value), 'expected_json_object');
31
32
  return copy(value);
@@ -291,24 +292,35 @@ export function plan(snapshot, config, capabilities, digest = canonical, policie
291
292
  if (snapshot.phase === 'verifying') {
292
293
  invariant(snapshot.candidate, 'verification_candidate_missing');
293
294
  if (!capabilities.verification) {
294
- const review = policies.forRun(config).review.scheduleDeliveryReview(snapshot, config, 'verification_report_missing', digest);
295
- if (review)
296
- return transition(snapshot, review, [{ kind: 'completion.delivery_review_started', payload: {} }]);
297
295
  const remaining = snapshot.todos?.items.filter(item => item.status !== 'completed') ?? [];
298
- if (config.todoPolicy === 'session-todos/v1' && snapshot.candidate.purpose !== 'checkpoint'
299
- && snapshot.lastWorkspaceMutationToolCall != null && remaining.length) {
296
+ const canRepairDelivery = config.todoPolicy === 'session-todos/v1' && snapshot.candidate.purpose !== 'checkpoint'
297
+ && snapshot.lastWorkspaceMutationToolCall != null;
298
+ const failedCommands = canRepairDelivery ? failedDeliveryCommands(snapshot.messages) : [];
299
+ // Use observed failures directly instead of asking for an extra review
300
+ // model call to rediscover the same checks.
301
+ if (!failedCommands.length) {
302
+ const review = policies.forRun(config).review.scheduleDeliveryReview(snapshot, config, 'verification_report_missing', digest);
303
+ if (review)
304
+ return transition(snapshot, review, [{ kind: 'completion.delivery_review_started', payload: {} }]);
305
+ }
306
+ if (canRepairDelivery && (remaining.length || failedCommands.length)) {
300
307
  const progress = digest({ goal: snapshot.goalRevision, workspace: snapshot.workspaceRevision,
301
- checks: remaining.map(item => item.content).sort() });
308
+ checks: remaining.map(item => item.content).sort(),
309
+ ...(failedCommands.length ? { failedCommands: failedCommands.map(canonical).sort() } : {}) });
302
310
  const reason = snapshot.deliveryContinuationDigest === progress ? 'delivery_no_progress'
303
311
  : snapshot.repairs >= config.limits.maxRepairs || finalizationOnly(snapshot, config)
304
312
  || toolRoom(snapshot, config) <= 0 || wallDeliveryOnly(snapshot, config) ? 'delivery_repair_budget_exhausted' : null;
305
313
  if (reason)
306
314
  return transition(snapshot, { phase: 'paused', resumePhase: 'preparing_context', candidate: null, reason, outcome: null }, [{ kind: 'run.paused', payload: { reason } }]);
315
+ const issue = failedCommands.length ? 'delivery_checks_failed' : 'delivery_todos_incomplete';
307
316
  return transition(snapshot, { phase: 'preparing_context', candidate: null, preparedContext: null,
308
317
  repairs: snapshot.repairs + 1, deliveryContinuationDigest: progress, messages: [...snapshot.messages,
309
- { role: 'user', kind: 'verification_observation', content: canonical({ reason: 'delivery_todos_incomplete',
318
+ { role: 'user', kind: 'verification_observation', content: canonical({ reason: issue,
310
319
  remaining: remaining.map(item => item.content),
311
- instruction: 'The preceding draft was a progress report. Continue from the current workspace. Use committed tool results to identify and repair failures, run the remaining checks, and update the checklist only with observed results. If a concrete blocker requires the user, ask for the required input.' }) }] }, [{ kind: 'completion.continued', payload: { reason: 'delivery_todos_incomplete' } }]);
320
+ ...(failedCommands.length ? { failedCommands: failedCommands.map(check => ({
321
+ command: check.command.slice(0, 320), cwd: check.cwd.slice(0, 240), exitCode: check.exitCode,
322
+ })) } : {}),
323
+ instruction: 'The preceding draft was a progress report. Continue from the current workspace. Use committed tool results to identify and repair failures, run the remaining checks, and update the checklist only with observed results. If a concrete blocker requires the user, ask for the required input.' }) }] }, [{ kind: 'completion.continued', payload: { reason: issue } }]);
312
324
  }
313
325
  return finalizing(snapshot, 'unverified', 'verification_report_missing');
314
326
  }
@@ -375,7 +387,7 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
375
387
  ...(result.usageReported === false ? { providerUsageIncomplete: true } : {}),
376
388
  ...(result.failureDiagnostic || snapshot.diagnostics.lastModelFailure
377
389
  ? { lastModelFailure: result.failureDiagnostic ? objectValue(result.failureDiagnostic) : null } : {}) } } : {}) };
378
- if (policies.forRun(config).review.reviewPending(snapshot)) {
390
+ if (policies.forRun(config).review.reviewPending(snapshot) && result.kind !== 'provider_retryable_error') {
379
391
  const beforeCall = { ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } };
380
392
  const readers = policies.forRun(config).review.deliveryReviewReaders(beforeCall, config);
381
393
  if (result.kind === 'tool_calls' && result.toolCalls.length && readers.length
@@ -572,10 +584,13 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
572
584
  : oversizedTool ? Math.min(config.profile.maxRetries, 1) : config.profile.maxRetries;
573
585
  const exhausted = attempts > limit;
574
586
  const delay = retryDelay(result, attempts, config, random);
587
+ const providerRetryNotBefore = providerRetryDeadline(result, now);
588
+ const providerWait = providerRetryNotBefore === undefined ? {} : { providerRetryNotBefore };
575
589
  // An unavailable provider is not a task failure: pause with a fresh budget so the Host can resume later.
576
590
  if (provider && exhausted && config.providerRecoveryPolicy === 'provider-recovery/v2')
577
591
  return { ...base, phase: 'paused',
578
- resumePhase: 'preparing_context', outcome: null, reason: 'provider_unavailable', providerErrors: 0, retryNotBefore: 0 };
592
+ resumePhase: 'preparing_context', outcome: null, reason: 'provider_unavailable', providerErrors: 0,
593
+ retryNotBefore: providerRetryNotBefore ?? 0, ...providerWait };
579
594
  const messages = provider ? snapshot.messages : [...snapshot.messages, { role: 'user', kind: responseContinuationPending(snapshot, config)
580
595
  ? 'response_continuation_feedback' : 'model_feedback',
581
596
  content: oversizedTool
@@ -589,7 +604,8 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
589
604
  return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', outcome: exhausted ? 'failed' : null,
590
605
  reason: exhausted ? `${result.kind}_retry_exhausted` : null,
591
606
  providerErrors: provider ? attempts : base.providerErrors ?? snapshot.providerErrors,
592
- modelErrors: provider ? snapshot.modelErrors : attempts, retryNotBefore: exhausted ? 0 : now + delay, messages };
607
+ modelErrors: provider ? snapshot.modelErrors : attempts, retryNotBefore: exhausted ? 0 : retryDeadline(now, delay),
608
+ ...(!exhausted ? providerWait : {}), messages };
593
609
  }
594
610
  case 'policy_abort': return { ...base, phase: 'finalizing', outcome: 'blocked', reason: 'model_policy_abort' };
595
611
  case 'user_abort': return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'model_user_abort' };
package/dist/retry.d.mts CHANGED
@@ -1,3 +1,5 @@
1
1
  import type { ModelResult, RunConfiguration } from './contracts.mjs';
2
2
  /** Resolve once per committed retry. Explicit provider waits are never jittered. */
3
3
  export declare function retryDelay(result: ModelResult, attempts: number, config: RunConfiguration, random: number): number;
4
+ export declare function retryDeadline(now: number, delay: number): number;
5
+ export declare function providerRetryDeadline(result: ModelResult, now: number): number | undefined;
package/dist/retry.mjs CHANGED
@@ -14,10 +14,19 @@ export function retryDelay(result, attempts, config, random) {
14
14
  }
15
15
  if (result.retryAfterMs !== undefined) {
16
16
  invariant(Number.isFinite(result.retryAfterMs) && result.retryAfterMs >= 0, 'invalid_retry_after');
17
- return Math.min(result.failureKind === 'rate_limit' ? 300_000 : cap, Math.max(floor, result.retryAfterMs));
17
+ // The provider's wait is a lower bound. The local cap applies only to
18
+ // our own backoff. A run deadline may end the wait, but cannot send early.
19
+ return Math.max(floor, result.retryAfterMs);
18
20
  }
19
21
  const limit = result.failureKind === 'rate_limit' ? 300_000 : cap;
20
22
  if (result.failureKind === 'rate_limit')
21
23
  floor = Math.max(floor, profile.rateLimitCooldownMs);
22
24
  return floor <= 0 || floor >= limit ? floor : Math.min(limit, floor + floor * 0.25 * random);
23
25
  }
26
+ export function retryDeadline(now, delay) {
27
+ return Math.min(Number.MAX_SAFE_INTEGER, now + delay);
28
+ }
29
+ export function providerRetryDeadline(result, now) {
30
+ return result.kind === 'provider_retryable_error' && result.retryAfterMs !== undefined
31
+ ? retryDeadline(now, result.retryAfterMs) : undefined;
32
+ }
@@ -38,7 +38,9 @@ export function prepareEffect(snapshot, kind, phase, payload, changes = {}) {
38
38
  || snapshot.retryNotBefore > 0
39
39
  && (payload.purpose === 'compaction' ? (snapshot.contextState?.compaction?.providerErrors ?? 0) > 0
40
40
  || (snapshot.contextState?.compaction?.errors ?? 0) > 0 : snapshot.providerErrors > 0 || snapshot.modelErrors > 0));
41
- return transition(snapshot, { ...changes, phase, pendingIntent: operationKey, ...(kind === 'model' ? { retryNotBefore: 0 } : {}) }, [{ kind: 'effect.prepared', payload: { operationKey, kind, ...(retry ? { retry: true } : {}),
41
+ return transition(snapshot, { ...changes, phase, pendingIntent: operationKey, ...(kind === 'model' ? {
42
+ retryNotBefore: 0, ...(snapshot.providerRetryNotBefore === undefined ? {} : { providerRetryNotBefore: 0 }),
43
+ } : {}) }, [{ kind: 'effect.prepared', payload: { operationKey, kind, ...(retry ? { retry: true } : {}),
42
44
  ...(kind === 'model' && payload.purpose === 'compaction' ? { purpose: 'compaction' } : {}) } }], { intents: [{ operationKey, kind, payload: copy(payload), status: 'prepared' }] });
43
45
  }
44
46
  export function reduceCommand(snapshot, command, pending = null, bindings = {}) {
@@ -70,7 +72,7 @@ export function reduceCommand(snapshot, command, pending = null, bindings = {})
70
72
  context: { ...snapshot.context, preparedCursor: null },
71
73
  contextState: snapshot.contextState ? { ...snapshot.contextState, compaction: null } : null,
72
74
  candidate: null, verification: null, verificationToolCalls: null,
73
- hookState, stopHookContinuations: 0, continuations: 0, retryNotBefore: 0,
75
+ hookState, stopHookContinuations: 0, continuations: 0, retryNotBefore: snapshot.providerRetryNotBefore ?? 0,
74
76
  outcome: null, finalText: '', reason: null,
75
77
  } : {}, [
76
78
  ...(reason === 'applied' ? [{ kind: 'input.guidance_applied', payload: {
@@ -214,7 +216,7 @@ export function reduceCommand(snapshot, command, pending = null, bindings = {})
214
216
  verificationToolCalls: null, checkpointWebMutationToolCall: null,
215
217
  failureFingerprint: null, failureEvidenceDigest: null,
216
218
  hookState: null, stopHookContinuations: 0,
217
- continuations: 0, retryNotBefore: 0, toolErrorStreak: null, workspaceRevision: null,
219
+ continuations: 0, retryNotBefore: snapshot.providerRetryNotBefore ?? 0, toolErrorStreak: null, workspaceRevision: null,
218
220
  ...(snapshot.toolErrorRecovery === undefined ? {} : { toolErrorRecovery: null }),
219
221
  ...(snapshot.deliveryReview === undefined ? {} : { deliveryReview: null }),
220
222
  contextState: snapshot.contextState ? { ...snapshot.contextState, compaction: null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-core",
3
- "version": "0.0.30",
3
+ "version": "0.0.31",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Host-independent Native Harness contracts, transitions and durable execution.",
@@ -36,12 +36,7 @@ export function commandProbe(snapshot: RunSnapshot, configuration: RunConfigurat
36
36
  taskChainId: snapshot.taskChainId, operationKey: `${runKey(snapshot.scope, snapshot.runId)}:background-probe:${snapshot.revision}`, cursor, refs };
37
37
  }
38
38
 
39
- /** Notice and deduplication marker commit together. Output remains untrusted data. */
40
- export function stageCommandObservations(snapshot: RunSnapshot, configuration: RunConfiguration, request: BackgroundCommandRequest,
41
- input: unknown, intent: EffectIntent | null = null, elapsedMs = 0): CommitBatch {
42
- const expected = commandProbe(snapshot, configuration, intent);
43
- invariant(expected && canonical(expected) === canonical(request), 'background_command_notification_request_identity_conflict');
44
- invariant(Number.isFinite(elapsedMs) && elapsedMs >= 0, 'invalid_background_probe_elapsed');
39
+ export function commandObservations(request: BackgroundCommandRequest, input: unknown): BackgroundCommandObservation[] {
45
40
  invariant(Array.isArray(input) && input.length <= 8, 'background_command_notification_batch_exceeded');
46
41
  const observations = input.map(backgroundCommandObservation);
47
42
  const owned = new Map(request.refs.map(ref => [ref.taskId, ref])), ids = new Set<string>();
@@ -50,6 +45,17 @@ export function stageCommandObservations(snapshot: RunSnapshot, configuration: R
50
45
  'background_command_notification_identity_conflict');
51
46
  ids.add(observation.ref.taskId);
52
47
  }
48
+ return observations;
49
+ }
50
+
51
+ /** Notice and deduplication marker commit together. Output remains untrusted data. */
52
+ export function stageCommandObservations(snapshot: RunSnapshot, configuration: RunConfiguration, request: BackgroundCommandRequest,
53
+ input: unknown, intent: EffectIntent | null = null, elapsedMs = 0): CommitBatch {
54
+ const expected = commandProbe(snapshot, configuration, intent);
55
+ invariant(expected && canonical(expected) === canonical(request), 'background_command_notification_request_identity_conflict');
56
+ invariant(Number.isFinite(elapsedMs) && elapsedMs >= 0, 'invalid_background_probe_elapsed');
57
+ const observations = commandObservations(request, input);
58
+ const ids = new Set(observations.map(item => item.ref.taskId));
53
59
  const activeElapsedMs = snapshot.activeElapsedMs + elapsedMs;
54
60
  const uncertain = observations.some(item => ['unknown', 'unavailable'].includes(item.status));
55
61
  const exhausted = configuration.limits.maxWallMs !== null && activeElapsedMs >= configuration.limits.maxWallMs;
@@ -5,7 +5,7 @@ import { directoryProgressQuote } from './directory-progress.mjs';
5
5
  import { NativePolicyRegistry } from './policy-registry.mjs';
6
6
  import { contextSourceDigest, validateContextMessages } from './context-view.mjs';
7
7
  import { assertHookFeedbackRetained } from './hook-runtime.mjs';
8
- import { retryDelay } from './retry.mjs';
8
+ import { providerRetryDeadline, retryDeadline, retryDelay } from './retry.mjs';
9
9
  import { artifactProgressIdentity } from './artifact-runtime.mjs';
10
10
  import { sourceWorkingSetGroup } from './source-working-set-group.mjs';
11
11
  import { sourceReuseProjector } from './context-source-reuse.mjs';
@@ -549,11 +549,15 @@ export function reduceContextModel(snapshot: RunSnapshot, result: ModelResult, c
549
549
  if (provider) compaction.providerErrors = attempts;
550
550
  else compaction.errors = attempts;
551
551
  const limit = provider ? config.profile.maxProviderRetries : config.contextPolicy!.maxSummaryRetries;
552
+ const delay = retryDelay(result, attempts, config, random);
553
+ const providerRetryNotBefore = providerRetryDeadline(result, now);
554
+ const providerWait = providerRetryNotBefore === undefined ? {} : { providerRetryNotBefore };
552
555
  if (attempts > limit) {
553
556
  if (adaptive || provider && config.providerRecoveryPolicy === 'provider-recovery/v2') {
554
557
  compaction.errors = 0; compaction.providerErrors = 0;
555
558
  return { ...base, phase: 'paused', resumePhase: 'compacting', outcome: null,
556
- reason: provider ? 'provider_unavailable' : 'context_summary_unavailable', retryNotBefore: 0 };
559
+ reason: provider ? 'provider_unavailable' : 'context_summary_unavailable',
560
+ retryNotBefore: providerRetryNotBefore ?? 0, ...providerWait };
557
561
  }
558
562
  return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'context_summary_retry_exhausted' };
559
563
  }
@@ -571,5 +575,5 @@ export function reduceContextModel(snapshot: RunSnapshot, result: ModelResult, c
571
575
  if (length <= 2) return { ...base, phase: 'finalizing', outcome: 'blocked', reason: 'context_summary_quote_overflow' };
572
576
  compaction.quoteLimit = Math.max(1, Math.floor(length / 2)); compaction.chunk = null;
573
577
  }
574
- return { ...base, retryNotBefore: now + retryDelay(result, attempts, config, random) };
578
+ return { ...base, retryNotBefore: retryDeadline(now, delay), ...providerWait };
575
579
  }
package/src/contracts.mts CHANGED
@@ -506,6 +506,8 @@ export interface RunSnapshot extends RunIdentity {
506
506
  /** A sealed reasoning-only cutoff has armed the short retry for this response. */
507
507
  reasoningStallRetry?: boolean;
508
508
  activeElapsedMs: number; retryNotBefore: number;
509
+ /** Provider-requested minimum that survives a change of goal or guidance. */
510
+ providerRetryNotBefore?: number;
509
511
  candidate: CompletionCandidate | null; verification: VerificationReport | null;
510
512
  finalText: string; outcome: Outcome | null; reason: string | null;
511
513
  workspaceRevision: string | null; workspaceModifiedPaths: string[]; artifactRefs: ArtifactRef[];
@@ -0,0 +1,58 @@
1
+ import type { Message, ToolCall } from './contracts.mjs';
2
+
3
+ type CommandCheck = { command: string; cwd: string; exitCode: number };
4
+
5
+ // Recognize explicit check invocations. Shell pipelines and arbitrary command
6
+ // chains can hide a failing exit code, so their outer status cannot qualify.
7
+ const checkRunners = [
8
+ /^(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test(?::[\w-]+)?|lint|check)(?:\s|$)/,
9
+ /^(?:node|bun|deno)\s+(?:--test\b|(?:[\w./-]+\/)?(?:test[-\w.]*|[\w.-]+\.test)\.[cm]?[jt]s)(?:\s|$)/,
10
+ /^(?:python3?\s+-m\s+)?pytest(?:\s|$)/,
11
+ /^(?:npx\s+(?:--no-install\s+)?)?playwright\s+test(?:\s|$)/,
12
+ ];
13
+ const explicitExit = /^([^;&|<>\r\n]+)[ \t]+>[ \t]*[\w./-]+[ \t]+2>&1[ \t]*;[ \t]*echo "EXIT=\$\?"(?:[ \t]*;[^\r\n]*)?$/;
14
+
15
+ function observedCheck(call: ToolCall, message: Message): CommandCheck | null {
16
+ const value = call.arguments.command;
17
+ if (typeof value !== 'string' || value.length > 4096 || call.arguments.background === true
18
+ || message.toolOutcome && message.toolOutcome !== 'ok') return null;
19
+ let receipt;
20
+ try { receipt = JSON.parse(message.content); } catch { return null; }
21
+ if (!receipt || !['sandbox/local_process', 'sandbox/e2b'].includes(receipt.backend)
22
+ || receipt.ok !== true || receipt.evidence_incomplete !== false || receipt.command !== value
23
+ || (receipt.status !== undefined && !['completed', 'failed'].includes(receipt.status))
24
+ || !Number.isSafeInteger(receipt.exit_code) || receipt.exit_code < 0) return null;
25
+
26
+ const cd = /^cd[ \t]+([-\w./]+)[ \t]*&&[ \t]*/.exec(value.trim());
27
+ const shell = value.trim().slice(cd?.[0].length ?? 0);
28
+ const captured = explicitExit.exec(shell);
29
+ const command = captured ? captured[1]!.trim() : shell;
30
+ if (/[;&|<>\r\n\x60$]/.test(command) || !checkRunners.some(pattern => pattern.test(command))) return null;
31
+ const exitCode = captured
32
+ ? Number(typeof receipt.stdout === 'string' ? /^EXIT=(\d+)\r?(?:\n|$)/.exec(receipt.stdout)?.[1] : undefined)
33
+ : receipt.exit_code;
34
+ if (!Number.isSafeInteger(exitCode) || exitCode < 0 || exitCode > 255) return null;
35
+ const cwd = cd?.[1] ?? (typeof call.arguments.cwd === 'string' ? call.arguments.cwd : '.');
36
+ return { command, cwd, exitCode };
37
+ }
38
+
39
+ /** These are repair signals from committed tool results. They never qualify
40
+ * formal acceptance or infer a failed check from assistant prose. */
41
+ export function failedDeliveryCommands(messages: Message[]): CommandCheck[] {
42
+ const pending = new Map<string, ToolCall>(), latest = new Map<string, CommandCheck>();
43
+ for (const message of messages) {
44
+ // A fresh turn may point at another task, even in the same workspace.
45
+ // Durable resume of the current Run retains these original messages.
46
+ if (message.history) continue;
47
+ if (message.role === 'assistant') {
48
+ for (const call of message.toolCalls ?? []) if (call.name === 'run_command') pending.set(call.callId, call);
49
+ } else if (message.role === 'tool' && message.name === 'run_command' && message.callId) {
50
+ const call = pending.get(message.callId);
51
+ if (!call) continue;
52
+ pending.delete(message.callId);
53
+ const check = observedCheck(call, message);
54
+ if (check) latest.set(JSON.stringify([check.cwd, check.command]), check);
55
+ }
56
+ }
57
+ return [...latest.values()].filter(check => check.exitCode !== 0).slice(-8);
58
+ }
package/src/kernel.mts CHANGED
@@ -42,14 +42,14 @@ import { modelStreamCapture } from './model-stream.mjs';
42
42
  import { browserRecoveryTransition } from './browser-runtime.mjs';
43
43
  import { validateBrowserSessionRef } from './browser-contract.mjs';
44
44
  import type { BrowserRecovery } from './browser-contract.mjs';
45
- import { commandProbe, stageCommandObservations, unavailableCommands } from './background-runtime.mjs';
45
+ import { commandObservations, commandProbe, stageCommandObservations, unavailableCommands } from './background-runtime.mjs';
46
46
  import { assertGuidanceRetained } from './guidance.mjs';
47
47
  import { BACKGROUND_COMMAND_CONTRACT } from './background-contract.mjs';
48
48
  import { admittedToolBudget } from './child-budget.mjs';
49
49
  import { admitChildPromotion, childLifecycleRequest, childReadyProbe, childUsageFacts, reduceChildLifecycle, stageChildReady, unsettledChildren } from './child-runtime.mjs';
50
50
  import type { ChildLifecycleResult, ChildTaskControlState } from './child-contract.mjs';
51
51
  import { childControlDelivery } from './child-control.mjs';
52
- import type { BackgroundCommandRequest } from './background-contract.mjs';
52
+ import type { BackgroundCommandObservation, BackgroundCommandRequest } from './background-contract.mjs';
53
53
  import { toolResourceUsageFacts, unknownToolResourceUsageFacts } from './tool-resource-usage.mjs';
54
54
  import { deliverySummaryAllowed, deliveryTaskMessages, wallBudgetStop } from './deadline-delivery.mjs';
55
55
 
@@ -75,6 +75,7 @@ export class NativeKernel {
75
75
  private readonly onStream: NonNullable<KernelOptions['onStream']>;
76
76
  private readonly onCheckpoint: KernelOptions['onCheckpoint'];
77
77
  private readonly active = new Map<string, AbortController>();
78
+ private readonly retryWaiters = new Map<string, () => void>();
78
79
  private readonly clockAnchors = new Map<string, number>();
79
80
  private readonly childObservers = new Map<string, { controller: AbortController; canPause: boolean }>();
80
81
  constructor(options: KernelOptions) {
@@ -153,8 +154,10 @@ export class NativeKernel {
153
154
  }
154
155
  submit(scope: RunScope, runId: string, command: RunCommand) {
155
156
  const result = this.store.enqueue(scope, runId, command);
157
+ const key = runKey(scope, runId);
158
+ if (result.status === 'accepted') this.retryWaiters.get(key)?.();
156
159
  if (result.status !== 'rejected' && ['cancel', 'policy_revoked'].includes(command.kind)) {
157
- this.active.get(runKey(scope, runId))?.abort(new NativeError('command_interrupt'));
160
+ this.active.get(key)?.abort(new NativeError('command_interrupt'));
158
161
  }
159
162
  if (result.status === 'accepted' && ['pause', 'promote_child', 'message_child', 'cancel_child', 'resume_child'].includes(command.kind)) {
160
163
  const observer = this.childObservers.get(runKey(scope, runId));
@@ -407,7 +410,11 @@ export class NativeKernel {
407
410
  }
408
411
  if (!wallExpired && snapshot.retryNotBefore > this.now()) {
409
412
  if (!waitForRetry) return snapshot;
410
- await new Promise(resolve => setTimeout(resolve, Math.min(50, snapshot.retryNotBefore - this.now())));
413
+ const wallRemaining = config.limits.maxWallMs === null ? Infinity : config.limits.maxWallMs - this.elapsed(snapshot);
414
+ // Locally submitted controls wake the wait immediately. The bounded
415
+ // poll also notices control rows enqueued by a different worker.
416
+ await this.waitAtRetryBoundary(key, Math.max(0, Math.min(500, wallRemaining, snapshot.retryNotBefore - this.now())),
417
+ controller.signal);
411
418
  continue;
412
419
  }
413
420
  const backgroundIntent = record.pendingIntent;
@@ -481,23 +488,54 @@ export class NativeKernel {
481
488
  catch (error) { if (!(isNativeError(error) && error.code === 'stale_fence')) throw error; }
482
489
  }
483
490
  }
491
+ private waitAtRetryBoundary(key: string, delay: number, signal: AbortSignal): Promise<void> {
492
+ if (signal.aborted) return Promise.resolve();
493
+ return new Promise(resolve => {
494
+ const wake = () => {
495
+ clearTimeout(timer); signal.removeEventListener('abort', wake); this.retryWaiters.delete(key); resolve();
496
+ };
497
+ const timer = setTimeout(wake, delay);
498
+ this.retryWaiters.set(key, wake);
499
+ signal.addEventListener('abort', wake, { once: true });
500
+ });
501
+ }
484
502
  private async inspectBackgroundCommands(request: BackgroundCommandRequest, snapshot: RunSnapshot, config: RunConfiguration, signal: AbortSignal): Promise<unknown> {
485
503
  const remaining = config.limits.maxWallMs === null ? config.limits.effectTimeoutMs
486
504
  : Math.min(config.limits.effectTimeoutMs, Math.max(0, config.limits.maxWallMs - this.elapsed(snapshot)));
487
505
  if (remaining <= 0) return [];
488
- if (this.ports.background?.contract !== BACKGROUND_COMMAND_CONTRACT) return unavailableCommands(request);
489
- const timeout = new AbortController(), probeSignal = AbortSignal.any([signal, timeout.signal]);
490
- const timer = setTimeout(() => timeout.abort(new NativeError('background_command_probe_timeout')), remaining);
491
- let onAbort = () => {};
492
- const aborted = new Promise<never>((_, reject) => {
493
- onAbort = () => reject(probeSignal.reason);
494
- if (probeSignal.aborted) onAbort(); else probeSignal.addEventListener('abort', onAbort, { once: true });
495
- });
496
- try {
497
- const result = await Promise.race([this.ports.background.observe({ ...copy(request), signal: probeSignal }), aborted]);
498
- probeSignal.throwIfAborted(); return result;
499
- } catch { return unavailableCommands(request); }
500
- finally { clearTimeout(timer); probeSignal.removeEventListener('abort', onAbort); }
506
+ const port = this.ports.background;
507
+ const unavailable = unavailableCommands(request);
508
+ if (port?.contract !== BACKGROUND_COMMAND_CONTRACT) return unavailable;
509
+ const expires = this.monotonicNow() + remaining, attempts = 3;
510
+ const settled = new Map<string, BackgroundCommandObservation>();
511
+ let latest = unavailable;
512
+ for (let attempt = 0; attempt < attempts && !signal.aborted; attempt++) {
513
+ const left = expires - this.monotonicNow();
514
+ if (left <= 0) break;
515
+ const timeout = new AbortController(), probeSignal = AbortSignal.any([signal, timeout.signal]);
516
+ const timer = setTimeout(() => timeout.abort(new NativeError('background_command_probe_timeout')),
517
+ Math.min(2_147_483_647, Math.ceil(left / (attempts - attempt))));
518
+ let onAbort = () => {};
519
+ const aborted = new Promise<never>((_, reject) => {
520
+ onAbort = () => reject(probeSignal.reason);
521
+ if (probeSignal.aborted) onAbort(); else probeSignal.addEventListener('abort', onAbort, { once: true });
522
+ });
523
+ try {
524
+ // Re-observe the sealed request. This port cannot dispatch a command.
525
+ const result = await Promise.race([port.observe({ ...copy(request), signal: probeSignal }), aborted]);
526
+ probeSignal.throwIfAborted();
527
+ latest = commandObservations(request, result);
528
+ } catch { latest = unavailable; }
529
+ finally { clearTimeout(timer); probeSignal.removeEventListener('abort', onAbort); }
530
+ for (const entry of latest) if (entry.status !== 'unavailable') settled.set(entry.ref.taskId, entry);
531
+ latest = latest.filter(entry => entry.status === 'unavailable' && !settled.has(entry.ref.taskId));
532
+ if (!latest.length) break;
533
+ if (attempt + 1 < attempts && !signal.aborted) {
534
+ await new Promise(resolve => setTimeout(resolve, Math.min(50 * (attempt + 1), Math.max(0, expires - this.monotonicNow()))));
535
+ }
536
+ }
537
+ for (const entry of latest) settled.set(entry.ref.taskId, entry);
538
+ return request.refs.flatMap(ref => settled.get(ref.taskId) ?? []).slice(0, 8);
501
539
  }
502
540
  private commit(snapshot: RunSnapshot, lease: Lease, batch: CommitBatch): RunSnapshot {
503
541
  const now = this.now(), measuredAt = this.monotonicNow(), key = runKey(snapshot.scope, snapshot.runId);
@@ -720,7 +758,7 @@ export class NativeKernel {
720
758
  facts.push({ kind: 'context.summary_completed', payload: { kind: result.kind, usage: objectValue(result.usage),
721
759
  messageCursor: snapshot.messages.length, usageReported: result.usageReported !== false,
722
760
  proposalAvailable: !!changes.contextState?.compaction?.proposal } });
723
- if (typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
761
+ if (changes.phase !== 'paused' && typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
724
762
  facts.push({ kind: 'model.retry_scheduled', payload: { retryAt: Math.ceil(changes.retryNotBefore), purpose: 'compaction',
725
763
  attempt: result.kind === 'provider_retryable_error' ? changes.contextState?.compaction?.providerErrors ?? 1
726
764
  : changes.contextState?.compaction?.errors ?? 1,
@@ -770,7 +808,7 @@ export class NativeKernel {
770
808
  messageCursor: changes.messages?.length ?? snapshot.messages.length,
771
809
  usageReported: result.usageReported !== false,
772
810
  toolCalls: planning ? [] : result.toolCalls.map(objectValue), usage: objectValue(result.usage) } });
773
- if (typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
811
+ if (changes.phase !== 'paused' && typeof changes.retryNotBefore === 'number' && changes.retryNotBefore > 0)
774
812
  facts.push({ kind: 'model.retry_scheduled', payload: { retryAt: Math.ceil(changes.retryNotBefore),
775
813
  attempt: result.kind === 'provider_retryable_error' ? changes.providerErrors ?? 1 : changes.modelErrors ?? 1,
776
814
  ...(result.failureDiagnostic ? { failure: objectValue(result.failureDiagnostic) } : {}) } });
package/src/machine.mts CHANGED
@@ -3,7 +3,7 @@ import { advanceDirectoryProgress } from './directory-progress.mjs';
3
3
  import type { CommitBatch, EffectIntent, EffectReceipt, Message, ModelResult, ObjectValue, RunConfiguration, RunSnapshot, ToolCall, ToolResult, Usage } from './contracts.mjs';
4
4
  import { copy, invariant, canonical } from './values.mjs';
5
5
  import { prepareEffect, transition } from './transitions.mjs';
6
- import { retryDelay } from './retry.mjs';
6
+ import { providerRetryDeadline, retryDeadline, retryDelay } from './retry.mjs';
7
7
  import { FINAL_SUBMISSION_TOOL, finalSubmissionTool, submittedFinalText, normalizedFinalText, finalDeliveryChanges } from './final-submission.mjs';
8
8
  import { currentHookState, pendingHookFeedback, planHook } from './hook-runtime.mjs';
9
9
  import { projectToolResultContext, deferredToolContexts } from './tool-context.mjs';
@@ -29,6 +29,7 @@ import { reduceCoordinatorResponses } from './coordinator-response.mjs';
29
29
  import { RESULT_DELIVERY_POLICY } from './deliverables.mjs';
30
30
  import { validateModelTransport } from './model-transport.mjs';
31
31
  import { validateModelFailure } from './model-failure.mjs';
32
+ import { failedDeliveryCommands } from './delivery-command-checks.mjs';
32
33
 
33
34
  export function objectValue(value: unknown): ObjectValue {
34
35
  invariant(value !== null && typeof value === 'object' && !Array.isArray(value), 'expected_json_object');
@@ -273,24 +274,35 @@ export function plan(snapshot: RunSnapshot, config: RunConfiguration, capabiliti
273
274
  if (snapshot.phase === 'verifying') {
274
275
  invariant(snapshot.candidate, 'verification_candidate_missing');
275
276
  if (!capabilities.verification) {
276
- const review = policies.forRun(config).review.scheduleDeliveryReview(snapshot, config, 'verification_report_missing', digest);
277
- if (review) return transition(snapshot, review, [{ kind: 'completion.delivery_review_started', payload: {} }]);
278
277
  const remaining = snapshot.todos?.items.filter(item => item.status !== 'completed') ?? [];
279
- if (config.todoPolicy === 'session-todos/v1' && snapshot.candidate.purpose !== 'checkpoint'
280
- && snapshot.lastWorkspaceMutationToolCall != null && remaining.length) {
278
+ const canRepairDelivery = config.todoPolicy === 'session-todos/v1' && snapshot.candidate.purpose !== 'checkpoint'
279
+ && snapshot.lastWorkspaceMutationToolCall != null;
280
+ const failedCommands = canRepairDelivery ? failedDeliveryCommands(snapshot.messages) : [];
281
+ // Use observed failures directly instead of asking for an extra review
282
+ // model call to rediscover the same checks.
283
+ if (!failedCommands.length) {
284
+ const review = policies.forRun(config).review.scheduleDeliveryReview(snapshot, config, 'verification_report_missing', digest);
285
+ if (review) return transition(snapshot, review, [{ kind: 'completion.delivery_review_started', payload: {} }]);
286
+ }
287
+ if (canRepairDelivery && (remaining.length || failedCommands.length)) {
281
288
  const progress = digest({ goal: snapshot.goalRevision, workspace: snapshot.workspaceRevision,
282
- checks: remaining.map(item => item.content).sort() });
289
+ checks: remaining.map(item => item.content).sort(),
290
+ ...(failedCommands.length ? { failedCommands: failedCommands.map(canonical).sort() } : {}) });
283
291
  const reason = snapshot.deliveryContinuationDigest === progress ? 'delivery_no_progress'
284
292
  : snapshot.repairs >= config.limits.maxRepairs || finalizationOnly(snapshot, config)
285
293
  || toolRoom(snapshot, config) <= 0 || wallDeliveryOnly(snapshot, config) ? 'delivery_repair_budget_exhausted' : null;
286
294
  if (reason) return transition(snapshot, { phase: 'paused', resumePhase: 'preparing_context', candidate: null, reason, outcome: null },
287
295
  [{ kind: 'run.paused', payload: { reason } }]);
296
+ const issue = failedCommands.length ? 'delivery_checks_failed' : 'delivery_todos_incomplete';
288
297
  return transition(snapshot, { phase: 'preparing_context', candidate: null, preparedContext: null,
289
298
  repairs: snapshot.repairs + 1, deliveryContinuationDigest: progress, messages: [...snapshot.messages,
290
- { role: 'user', kind: 'verification_observation', content: canonical({ reason: 'delivery_todos_incomplete',
299
+ { role: 'user', kind: 'verification_observation', content: canonical({ reason: issue,
291
300
  remaining: remaining.map(item => item.content),
301
+ ...(failedCommands.length ? { failedCommands: failedCommands.map(check => ({
302
+ command: check.command.slice(0, 320), cwd: check.cwd.slice(0, 240), exitCode: check.exitCode,
303
+ })) } : {}),
292
304
  instruction: 'The preceding draft was a progress report. Continue from the current workspace. Use committed tool results to identify and repair failures, run the remaining checks, and update the checklist only with observed results. If a concrete blocker requires the user, ask for the required input.' }) }] },
293
- [{ kind: 'completion.continued', payload: { reason: 'delivery_todos_incomplete' } }]);
305
+ [{ kind: 'completion.continued', payload: { reason: issue } }]);
294
306
  }
295
307
  return finalizing(snapshot, 'unverified', 'verification_report_missing');
296
308
  }
@@ -357,7 +369,7 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
357
369
  ...(result.usageReported === false ? { providerUsageIncomplete: true } : {}),
358
370
  ...(result.failureDiagnostic || snapshot.diagnostics.lastModelFailure
359
371
  ? { lastModelFailure: result.failureDiagnostic ? objectValue(result.failureDiagnostic) : null } : {}) } } : {}) };
360
- if (policies.forRun(config).review.reviewPending(snapshot)) {
372
+ if (policies.forRun(config).review.reviewPending(snapshot) && result.kind !== 'provider_retryable_error') {
361
373
  const beforeCall = { ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } };
362
374
  const readers = policies.forRun(config).review.deliveryReviewReaders(beforeCall, config);
363
375
  if (result.kind === 'tool_calls' && result.toolCalls.length && readers.length
@@ -541,9 +553,12 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
541
553
  : oversizedTool ? Math.min(config.profile.maxRetries, 1) : config.profile.maxRetries;
542
554
  const exhausted = attempts > limit;
543
555
  const delay = retryDelay(result, attempts, config, random);
556
+ const providerRetryNotBefore = providerRetryDeadline(result, now);
557
+ const providerWait = providerRetryNotBefore === undefined ? {} : { providerRetryNotBefore };
544
558
  // An unavailable provider is not a task failure: pause with a fresh budget so the Host can resume later.
545
559
  if (provider && exhausted && config.providerRecoveryPolicy === 'provider-recovery/v2') return { ...base, phase: 'paused',
546
- resumePhase: 'preparing_context', outcome: null, reason: 'provider_unavailable', providerErrors: 0, retryNotBefore: 0 };
560
+ resumePhase: 'preparing_context', outcome: null, reason: 'provider_unavailable', providerErrors: 0,
561
+ retryNotBefore: providerRetryNotBefore ?? 0, ...providerWait };
547
562
  const messages: Message[] = provider ? snapshot.messages : [...snapshot.messages, { role: 'user', kind: responseContinuationPending(snapshot, config)
548
563
  ? 'response_continuation_feedback' : 'model_feedback',
549
564
  content: oversizedTool
@@ -556,7 +571,8 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
556
571
  return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', outcome: exhausted ? 'failed' : null,
557
572
  reason: exhausted ? `${result.kind}_retry_exhausted` : null,
558
573
  providerErrors: provider ? attempts : base.providerErrors ?? snapshot.providerErrors,
559
- modelErrors: provider ? snapshot.modelErrors : attempts, retryNotBefore: exhausted ? 0 : now + delay, messages };
574
+ modelErrors: provider ? snapshot.modelErrors : attempts, retryNotBefore: exhausted ? 0 : retryDeadline(now, delay),
575
+ ...(!exhausted ? providerWait : {}), messages };
560
576
  }
561
577
  case 'policy_abort': return { ...base, phase: 'finalizing', outcome: 'blocked', reason: 'model_policy_abort' };
562
578
  case 'user_abort': return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'model_user_abort' };
package/src/retry.mts CHANGED
@@ -14,9 +14,20 @@ export function retryDelay(result: ModelResult, attempts: number, config: RunCon
14
14
  }
15
15
  if (result.retryAfterMs !== undefined) {
16
16
  invariant(Number.isFinite(result.retryAfterMs) && result.retryAfterMs >= 0, 'invalid_retry_after');
17
- return Math.min(result.failureKind === 'rate_limit' ? 300_000 : cap, Math.max(floor, result.retryAfterMs));
17
+ // The provider's wait is a lower bound. The local cap applies only to
18
+ // our own backoff. A run deadline may end the wait, but cannot send early.
19
+ return Math.max(floor, result.retryAfterMs);
18
20
  }
19
21
  const limit = result.failureKind === 'rate_limit' ? 300_000 : cap;
20
22
  if (result.failureKind === 'rate_limit') floor = Math.max(floor, profile.rateLimitCooldownMs);
21
23
  return floor <= 0 || floor >= limit ? floor : Math.min(limit, floor + floor * 0.25 * random);
22
24
  }
25
+
26
+ export function retryDeadline(now: number, delay: number): number {
27
+ return Math.min(Number.MAX_SAFE_INTEGER, now + delay);
28
+ }
29
+
30
+ export function providerRetryDeadline(result: ModelResult, now: number): number | undefined {
31
+ return result.kind === 'provider_retryable_error' && result.retryAfterMs !== undefined
32
+ ? retryDeadline(now, result.retryAfterMs) : undefined;
33
+ }
@@ -43,7 +43,9 @@ export function prepareEffect(snapshot: RunSnapshot, kind: EffectKind, phase: Ph
43
43
  || snapshot.retryNotBefore > 0
44
44
  && (payload.purpose === 'compaction' ? (snapshot.contextState?.compaction?.providerErrors ?? 0) > 0
45
45
  || (snapshot.contextState?.compaction?.errors ?? 0) > 0 : snapshot.providerErrors > 0 || snapshot.modelErrors > 0));
46
- return transition(snapshot, { ...changes, phase, pendingIntent: operationKey, ...(kind === 'model' ? { retryNotBefore: 0 } : {}) },
46
+ return transition(snapshot, { ...changes, phase, pendingIntent: operationKey, ...(kind === 'model' ? {
47
+ retryNotBefore: 0, ...(snapshot.providerRetryNotBefore === undefined ? {} : { providerRetryNotBefore: 0 }),
48
+ } : {}) },
47
49
  [{ kind: 'effect.prepared', payload: { operationKey, kind, ...(retry ? { retry: true } : {}),
48
50
  ...(kind === 'model' && payload.purpose === 'compaction' ? { purpose: 'compaction' } : {}) } }],
49
51
  { intents: [{ operationKey, kind, payload: copy(payload), status: 'prepared' }] });
@@ -75,7 +77,7 @@ export function reduceCommand(snapshot: RunSnapshot, command: RunCommand, pendin
75
77
  context: { ...snapshot.context, preparedCursor: null },
76
78
  contextState: snapshot.contextState ? { ...snapshot.contextState, compaction: null } : null,
77
79
  candidate: null, verification: null, verificationToolCalls: null,
78
- hookState, stopHookContinuations: 0, continuations: 0, retryNotBefore: 0,
80
+ hookState, stopHookContinuations: 0, continuations: 0, retryNotBefore: snapshot.providerRetryNotBefore ?? 0,
79
81
  outcome: null, finalText: '', reason: null,
80
82
  } : {}, [
81
83
  ...(reason === 'applied' ? [{ kind: 'input.guidance_applied', payload: {
@@ -203,7 +205,7 @@ export function reduceCommand(snapshot: RunSnapshot, command: RunCommand, pendin
203
205
  verificationToolCalls: null, checkpointWebMutationToolCall: null,
204
206
  failureFingerprint: null, failureEvidenceDigest: null,
205
207
  hookState: null, stopHookContinuations: 0,
206
- continuations: 0, retryNotBefore: 0, toolErrorStreak: null, workspaceRevision: null,
208
+ continuations: 0, retryNotBefore: snapshot.providerRetryNotBefore ?? 0, toolErrorStreak: null, workspaceRevision: null,
207
209
  ...(snapshot.toolErrorRecovery === undefined ? {} : { toolErrorRecovery: null }),
208
210
  ...(snapshot.deliveryReview === undefined ? {} : { deliveryReview: null }),
209
211
  contextState: snapshot.contextState ? { ...snapshot.contextState, compaction: null,