@kingsoftcloud/agentkit-harness-core 0.0.30 → 0.0.32

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.
Files changed (41) hide show
  1. package/dist/artifact-runtime.mjs +73 -6
  2. package/dist/background-runtime.d.mts +1 -0
  3. package/dist/background-runtime.mjs +10 -5
  4. package/dist/builtin-policies.d.mts +296 -36
  5. package/dist/configuration.mjs +6 -2
  6. package/dist/context-planning.d.mts +8 -0
  7. package/dist/context-planning.mjs +129 -36
  8. package/dist/contracts.d.mts +11 -3
  9. package/dist/deliverables.d.mts +89 -3
  10. package/dist/deliverables.mjs +24 -2
  11. package/dist/delivery-command-checks.d.mts +10 -0
  12. package/dist/delivery-command-checks.mjs +66 -0
  13. package/dist/final-submission.d.mts +1 -0
  14. package/dist/final-submission.mjs +24 -3
  15. package/dist/kernel.d.mts +2 -0
  16. package/dist/kernel.mjs +73 -28
  17. package/dist/machine.mjs +36 -16
  18. package/dist/model-surface.d.mts +1 -1
  19. package/dist/model-surface.mjs +1 -1
  20. package/dist/recovery.mjs +4 -0
  21. package/dist/retry.d.mts +2 -0
  22. package/dist/retry.mjs +10 -1
  23. package/dist/todos.d.mts +4 -1
  24. package/dist/todos.mjs +16 -0
  25. package/dist/transitions.mjs +5 -3
  26. package/package.json +1 -1
  27. package/src/artifact-runtime.mts +61 -6
  28. package/src/background-runtime.mts +12 -6
  29. package/src/configuration.mts +6 -2
  30. package/src/context-planning.mts +115 -31
  31. package/src/contracts.mts +11 -3
  32. package/src/deliverables.mts +22 -2
  33. package/src/delivery-command-checks.mts +58 -0
  34. package/src/final-submission.mts +21 -3
  35. package/src/kernel.mts +57 -19
  36. package/src/machine.mts +35 -15
  37. package/src/model-surface.mts +1 -1
  38. package/src/recovery.mts +4 -0
  39. package/src/retry.mts +12 -1
  40. package/src/todos.mts +11 -1
  41. package/src/transitions.mts +5 -3
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,8 +2,8 @@ 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';
6
- import { FINAL_SUBMISSION_TOOL, finalSubmissionTool, submittedFinalText, normalizedFinalText, finalDeliveryChanges } from './final-submission.mjs';
5
+ import { providerRetryDeadline, retryDeadline, retryDelay } from './retry.mjs';
6
+ import { FINAL_SUBMISSION_TOOL, finalSubmissionTool, finalSubmissionFailure, 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';
9
9
  import { validateWorkspaceChange, workspaceChangeUnobserved } from './workspace-change.mjs';
@@ -26,6 +26,8 @@ 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';
30
+ import { TODO_WRITE, isTodoCall } from './todos.mjs';
29
31
  export function objectValue(value) {
30
32
  invariant(value !== null && typeof value === 'object' && !Array.isArray(value), 'expected_json_object');
31
33
  return copy(value);
@@ -291,24 +293,35 @@ export function plan(snapshot, config, capabilities, digest = canonical, policie
291
293
  if (snapshot.phase === 'verifying') {
292
294
  invariant(snapshot.candidate, 'verification_candidate_missing');
293
295
  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
296
  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) {
297
+ const canRepairDelivery = config.todoPolicy === 'session-todos/v1' && snapshot.candidate.purpose !== 'checkpoint'
298
+ && snapshot.lastWorkspaceMutationToolCall != null;
299
+ const failedCommands = canRepairDelivery ? failedDeliveryCommands(snapshot.messages) : [];
300
+ // Use observed failures directly instead of asking for an extra review
301
+ // model call to rediscover the same checks.
302
+ if (!failedCommands.length) {
303
+ const review = policies.forRun(config).review.scheduleDeliveryReview(snapshot, config, 'verification_report_missing', digest);
304
+ if (review)
305
+ return transition(snapshot, review, [{ kind: 'completion.delivery_review_started', payload: {} }]);
306
+ }
307
+ if (canRepairDelivery && (remaining.length || failedCommands.length)) {
300
308
  const progress = digest({ goal: snapshot.goalRevision, workspace: snapshot.workspaceRevision,
301
- checks: remaining.map(item => item.content).sort() });
309
+ checks: remaining.map(item => item.content).sort(),
310
+ ...(failedCommands.length ? { failedCommands: failedCommands.map(canonical).sort() } : {}) });
302
311
  const reason = snapshot.deliveryContinuationDigest === progress ? 'delivery_no_progress'
303
312
  : snapshot.repairs >= config.limits.maxRepairs || finalizationOnly(snapshot, config)
304
313
  || toolRoom(snapshot, config) <= 0 || wallDeliveryOnly(snapshot, config) ? 'delivery_repair_budget_exhausted' : null;
305
314
  if (reason)
306
315
  return transition(snapshot, { phase: 'paused', resumePhase: 'preparing_context', candidate: null, reason, outcome: null }, [{ kind: 'run.paused', payload: { reason } }]);
316
+ const issue = failedCommands.length ? 'delivery_checks_failed' : 'delivery_todos_incomplete';
307
317
  return transition(snapshot, { phase: 'preparing_context', candidate: null, preparedContext: null,
308
318
  repairs: snapshot.repairs + 1, deliveryContinuationDigest: progress, messages: [...snapshot.messages,
309
- { role: 'user', kind: 'verification_observation', content: canonical({ reason: 'delivery_todos_incomplete',
319
+ { role: 'user', kind: 'verification_observation', content: canonical({ reason: issue,
310
320
  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' } }]);
321
+ ...(failedCommands.length ? { failedCommands: failedCommands.map(check => ({
322
+ command: check.command.slice(0, 320), cwd: check.cwd.slice(0, 240), exitCode: check.exitCode,
323
+ })) } : {}),
324
+ 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
325
  }
313
326
  return finalizing(snapshot, 'unverified', 'verification_report_missing');
314
327
  }
@@ -375,7 +388,7 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
375
388
  ...(result.usageReported === false ? { providerUsageIncomplete: true } : {}),
376
389
  ...(result.failureDiagnostic || snapshot.diagnostics.lastModelFailure
377
390
  ? { lastModelFailure: result.failureDiagnostic ? objectValue(result.failureDiagnostic) : null } : {}) } } : {}) };
378
- if (policies.forRun(config).review.reviewPending(snapshot)) {
391
+ if (policies.forRun(config).review.reviewPending(snapshot) && result.kind !== 'provider_retryable_error') {
379
392
  const beforeCall = { ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } };
380
393
  const readers = policies.forRun(config).review.deliveryReviewReaders(beforeCall, config);
381
394
  if (result.kind === 'tool_calls' && result.toolCalls.length && readers.length
@@ -426,10 +439,11 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
426
439
  callId: call.callId, name: call.name, content: canonical({ status: 'error', content: { reason: 'delivery_read_path_not_written', executed: false } }) }))] };
427
440
  if (finalSubmissionTool(config) && result.toolCalls.some(call => call.name === FINAL_SUBMISSION_TOOL)) {
428
441
  const text = result.toolCalls.length === 1 ? submittedFinalText(result.toolCalls[0], config) : null;
442
+ const receipt = text === null ? { status: 'not_dispatched', ...finalSubmissionFailure(result.toolCalls, config) }
443
+ : { status: 'accepted', reason: 'final_submission_candidate' };
429
444
  const messages = [...snapshot.messages, { ...message, toolCalls: result.toolCalls },
430
445
  ...result.toolCalls.map(call => ({ role: 'tool', callId: call.callId, name: call.name,
431
- content: canonical({ status: text === null ? 'not_dispatched' : 'accepted',
432
- reason: text === null ? 'final_submission_schema_or_batch_invalid' : 'final_submission_candidate' }) }))];
446
+ content: canonical(receipt) }))];
433
447
  if (text !== null) {
434
448
  if (config.deliveryScopePolicy === RESULT_DELIVERY_POLICY)
435
449
  messages[snapshot.messages.length] = {
@@ -572,10 +586,13 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
572
586
  : oversizedTool ? Math.min(config.profile.maxRetries, 1) : config.profile.maxRetries;
573
587
  const exhausted = attempts > limit;
574
588
  const delay = retryDelay(result, attempts, config, random);
589
+ const providerRetryNotBefore = providerRetryDeadline(result, now);
590
+ const providerWait = providerRetryNotBefore === undefined ? {} : { providerRetryNotBefore };
575
591
  // An unavailable provider is not a task failure: pause with a fresh budget so the Host can resume later.
576
592
  if (provider && exhausted && config.providerRecoveryPolicy === 'provider-recovery/v2')
577
593
  return { ...base, phase: 'paused',
578
- resumePhase: 'preparing_context', outcome: null, reason: 'provider_unavailable', providerErrors: 0, retryNotBefore: 0 };
594
+ resumePhase: 'preparing_context', outcome: null, reason: 'provider_unavailable', providerErrors: 0,
595
+ retryNotBefore: providerRetryNotBefore ?? 0, ...providerWait };
579
596
  const messages = provider ? snapshot.messages : [...snapshot.messages, { role: 'user', kind: responseContinuationPending(snapshot, config)
580
597
  ? 'response_continuation_feedback' : 'model_feedback',
581
598
  content: oversizedTool
@@ -589,7 +606,8 @@ export function reduceModel(snapshot, input, config, now, random, digest = canon
589
606
  return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', outcome: exhausted ? 'failed' : null,
590
607
  reason: exhausted ? `${result.kind}_retry_exhausted` : null,
591
608
  providerErrors: provider ? attempts : base.providerErrors ?? snapshot.providerErrors,
592
- modelErrors: provider ? snapshot.modelErrors : attempts, retryNotBefore: exhausted ? 0 : now + delay, messages };
609
+ modelErrors: provider ? snapshot.modelErrors : attempts, retryNotBefore: exhausted ? 0 : retryDeadline(now, delay),
610
+ ...(!exhausted ? providerWait : {}), messages };
593
611
  }
594
612
  case 'policy_abort': return { ...base, phase: 'finalizing', outcome: 'blocked', reason: 'model_policy_abort' };
595
613
  case 'user_abort': return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'model_user_abort' };
@@ -701,7 +719,9 @@ export function reduceTools(snapshot, results, calls, intent, config, digest = c
701
719
  }
702
720
  updated.messages.push({ ...projectToolResultContext(result, config),
703
721
  role: 'tool', callId: call.callId, name: call.name,
704
- ...(config.contextPolicy?.pruneToolResults || config.contextPolicy?.sourceReusePolicy ? { toolOutcome: result.status } : {}),
722
+ ...(config.contextPolicy?.pruneToolResults || config.contextPolicy?.sourceReusePolicy
723
+ || call.name === TODO_WRITE && isTodoCall(config, call) && config.modelSurface?.verificationProjection === 'readable-evidence/v1'
724
+ ? { toolOutcome: result.status } : {}),
705
725
  ...(definition?.contextRetention === 'persistent' ? { persistent: true } : {}) });
706
726
  if (updated.toolDiscovery && call.name === TOOL_SEARCH && result.status === 'ok'
707
727
  && result.content && typeof result.content === 'object' && !Array.isArray(result.content)) {
@@ -1,5 +1,5 @@
1
1
  import type { ArtifactRef, Message, RunConfiguration, VerificationReport } from './contracts.mjs';
2
- export declare const NATIVE_LOCAL_RESOURCE_PROFILES: readonly ["bounded/v1", "local-development/v1", "local-development/v2"];
2
+ export declare const NATIVE_LOCAL_RESOURCE_PROFILES: readonly ["bounded/v1", "local-development/v1", "local-development/v2", "local-development/v3"];
3
3
  /** Facts are supplied by the execution owner, never inferred from prompt prose. */
4
4
  export interface WorkspaceBrowserCapability {
5
5
  contract: 'agentkit.workspace-browser-capability/v1';
@@ -1,5 +1,5 @@
1
1
  import { canonical, copy, invariant } from './values.mjs';
2
- export const NATIVE_LOCAL_RESOURCE_PROFILES = ['bounded/v1', 'local-development/v1', 'local-development/v2'];
2
+ export const NATIVE_LOCAL_RESOURCE_PROFILES = ['bounded/v1', 'local-development/v1', 'local-development/v2', 'local-development/v3'];
3
3
  const bytes = (value) => new TextEncoder().encode(canonical(value)).length;
4
4
  export function validateModelSurface(surface) {
5
5
  if (surface === undefined)
package/dist/recovery.mjs CHANGED
@@ -11,6 +11,10 @@ export function safeReadRecoveryCalls(calls, configuration) {
11
11
  function replayPolicy(intent, configuration) {
12
12
  if (intent.kind === 'workspace')
13
13
  return 'workspace-observation/v1';
14
+ // Kernel planning with a local counter has no external effects. A legacy
15
+ // prepare adapter or a host context source has no such replay contract.
16
+ if (intent.kind === 'context' && configuration.contextPolicy && configuration.contextSources.length === 0)
17
+ return 'local-context-planning/v1';
14
18
  if (intent.kind === 'verify' && configuration.hostVerification)
15
19
  return 'host-verification-read/v1';
16
20
  if (intent.kind === 'model' && configuration.modelRecoveryPolicy === 'pure-inference/v1')
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
+ }
package/dist/todos.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ObjectValue, RunConfiguration, RunSnapshot, TodoItem, ToolCall, ToolDefinition, ToolResult } from './contracts.mjs';
1
+ import type { Message, ObjectValue, RunConfiguration, RunSnapshot, TodoItem, ToolCall, ToolDefinition, ToolResult } from './contracts.mjs';
2
2
  export declare const TODO_POLICY = "session-todos/v1";
3
3
  export declare const TODO_READ = "TodoRead";
4
4
  export declare const TODO_WRITE = "TodoWrite";
@@ -10,6 +10,9 @@ export declare function validateTodoConfiguration(config: RunConfiguration): voi
10
10
  export declare function todoItems(value: unknown): TodoItem[];
11
11
  export declare function executeTodo(snapshot: RunSnapshot, config: RunConfiguration, call: ToolCall): ToolResult;
12
12
  export declare function reduceTodo(snapshot: RunSnapshot, config: RunConfiguration, call: ToolCall, result: ToolResult): RunSnapshot['todos'] | undefined;
13
+ /** The complete list is already present in execution continuity. Keep the
14
+ * committed receipt and the request arguments intact for replay and history. */
15
+ export declare function projectTodoWriteReceipt(message: Message): Message;
13
16
  /** Reference cadence: ten assistant requests since both write and previous reminder. */
14
17
  export declare function todoReminder(snapshot: RunSnapshot, config: RunConfiguration): Partial<RunSnapshot> | null;
15
18
  export declare function todoUpdateFact(snapshot: RunSnapshot, messageCursor: number): ObjectValue;
package/dist/todos.mjs CHANGED
@@ -63,6 +63,22 @@ export function reduceTodo(snapshot, config, call, result) {
63
63
  return { ...copy(snapshot.todos), items, revision: snapshot.todos.revision + 1,
64
64
  lastWriteAssistantTurn: snapshot.todos.assistantTurns };
65
65
  }
66
+ /** The complete list is already present in execution continuity. Keep the
67
+ * committed receipt and the request arguments intact for replay and history. */
68
+ export function projectTodoWriteReceipt(message) {
69
+ if (message.role !== 'tool' || message.name !== TODO_WRITE || message.toolOutcome !== 'ok')
70
+ return message;
71
+ let receipt;
72
+ try {
73
+ receipt = JSON.parse(message.content);
74
+ }
75
+ catch {
76
+ return message;
77
+ }
78
+ if (!Array.isArray(receipt?.todos) || !Array.isArray(receipt.oldTodos) || !receipt.summary)
79
+ return message;
80
+ return { ...message, content: canonical({ status: 'updated', summary: receipt.summary }) };
81
+ }
66
82
  /** Reference cadence: ten assistant requests since both write and previous reminder. */
67
83
  export function todoReminder(snapshot, config) {
68
84
  const state = snapshot.todos;
@@ -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.32",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Host-independent Native Harness contracts, transitions and durable execution.",
@@ -72,26 +72,70 @@ function modelSize(result: ToolResult): number {
72
72
  additionalContexts: result.additionalContexts ?? [] }));
73
73
  }
74
74
  function offloadedView(result: ToolResult, payloadBytes: number, maximum: number, ref: ArtifactRef | null,
75
- preview: string, unavailable: boolean): string {
75
+ preview: string, unavailable: boolean, commandPreview: ObjectValue | null): string {
76
76
  const base = { code: ref ? 'tool_result_offloaded' : 'tool_result_truncated', execution_status: result.status,
77
77
  original_bytes: payloadBytes, artifact_state: ref ? 'available' : 'unavailable',
78
78
  instruction: ref ? 'Read the granted artifact for omitted text. The original tool has already returned; do not repeat its effects.'
79
79
  : 'Omitted text is unavailable. The original execution status is unchanged; do not repeat effects to recover its output.',
80
80
  ...(ref ? { artifact_uri: ref.uri } : {}), ...(unavailable ? { archive_error: 'archive_unavailable' } : {}),
81
81
  ...(result.context?.media?.length ? { media_observation: 'Inline media omitted; it has not been observed in this response.' } : {}) };
82
+ const evidence: ObjectValue = {};
83
+ if (commandPreview) {
84
+ const { exit_code, task_id, stdout_cursor, stderr_cursor } = commandPreview;
85
+ if (exit_code === null || typeof exit_code === 'number' && Number.isSafeInteger(exit_code)) evidence.exit_code = exit_code;
86
+ if (typeof task_id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(task_id)) evidence.task_id = task_id;
87
+ if (typeof stdout_cursor === 'number' && Number.isSafeInteger(stdout_cursor) && stdout_cursor >= 0)
88
+ evidence.stdout_cursor = stdout_cursor;
89
+ if (typeof stderr_cursor === 'number' && Number.isSafeInteger(stderr_cursor) && stderr_cursor >= 0)
90
+ evidence.stderr_cursor = stderr_cursor;
91
+ preview = ['stdout', 'stderr'].filter(key => typeof commandPreview[key] === 'string')
92
+ .map(key => key + ': ' + commandPreview[key]).join('\n');
93
+ }
82
94
  // Account for JSON escaping and the complete ToolContext framing, not just preview characters.
83
95
  const chars = Array.from(preview);
84
96
  let low = 0, high = chars.length;
85
- const encode = (count: number) => canonical({ ...base, preview: chars.slice(0, count).join('') });
86
- invariant(bytes(canonical({ content: encode(0), media: [], additionalContexts: [] })) <= maximum, 'artifact_result_budget_too_small');
97
+ const encode = (count: number) => {
98
+ const head = commandPreview && count > 1 && count < chars.length ? Math.ceil(count / 2) : count;
99
+ const excerpt = chars.slice(0, head).join('') + (count > head ? '\n…\n' + chars.slice(-(count - head)).join('') : '');
100
+ return canonical({ ...base, ...evidence, preview: excerpt });
101
+ };
102
+ const fits = (count: number) => bytes(canonical({ content: encode(count), media: [], additionalContexts: [] })) <= maximum;
103
+ for (const key of ['task_id', 'stderr_cursor', 'stdout_cursor', 'exit_code']) {
104
+ if (fits(0)) break;
105
+ delete evidence[key];
106
+ }
107
+ invariant(fits(0), 'artifact_result_budget_too_small');
108
+ if (fits(high)) return encode(high);
87
109
  while (low < high) {
88
110
  const mid = Math.ceil((low + high) / 2);
89
- if (bytes(canonical({ content: encode(mid), media: [], additionalContexts: [] })) <= maximum) low = mid;
111
+ if (fits(mid)) low = mid;
90
112
  else high = mid - 1;
91
113
  }
92
114
  return encode(low);
93
115
  }
94
116
 
117
+ function commandOutputPreview(result: ToolResult, definition: ToolDefinition, config: RunConfiguration): ObjectValue | null {
118
+ if (config.contextPolicy?.commandOutputProjection !== 'receipt-preview/v1'
119
+ || definition.name !== 'run_command' || definition.workspaceChangePolicy !== 'observed-command/v1'
120
+ || result.context?.media?.length || result.additionalContexts?.length
121
+ || config.contract.allowedToolNames !== null && !config.contract.allowedToolNames.includes('ArtifactRead')) return null;
122
+ let observed: Json;
123
+ try { observed = parseNativeJson(projectToolResultContext(result, config).content); }
124
+ catch { return null; }
125
+ if (!object(observed)) return null;
126
+ const sizes: ObjectValue = {}, preview = { ...observed };
127
+ for (const stream of ['stdout', 'stderr'] as const) {
128
+ const text = observed[stream];
129
+ if (typeof text !== 'string' || bytes(text) <= 2048) continue;
130
+ const chars = Array.from(text);
131
+ const tail = stream === 'stderr' ? 768 : 512;
132
+ if (chars.length <= 128 + tail) continue;
133
+ sizes[`${stream}_receipt_bytes`] = bytes(text);
134
+ preview[stream] = chars.slice(0, 128).join('') + '\n…\n' + chars.slice(-tail).join('');
135
+ }
136
+ return Object.keys(sizes).length ? { ...preview, output_preview: sizes } : null;
137
+ }
138
+
95
139
  /** Runs within the original durable tool intent. Archive failures never relabel a known mutation or cause a retry. */
96
140
  export async function governArtifactResult(context: PortContext, definition: ToolDefinition, input: ToolResult,
97
141
  config: RunConfiguration, artifacts?: ArtifactPort): Promise<ToolResult> {
@@ -128,7 +172,8 @@ export async function governArtifactResult(context: PortContext, definition: Too
128
172
  if (isArtifactTool(definition.name)) return result;
129
173
  const tooLarge = modelObservationBytes(result, config) > config.limits.maxToolResultBytes;
130
174
  const force = ['archived-model-view/v4', 'archived-model-view/v5'].includes(definition.resultArchivePolicy ?? '') && result.status === 'ok';
131
- if (!tooLarge && !force) return result;
175
+ const commandPreview = commandOutputPreview(result, definition, config);
176
+ if (!tooLarge && !force && !commandPreview) return result;
132
177
  // Preserve the canonical receipt in SQLite. The readable archive follows the actual post-policy model view;
133
178
  // hidden/raw Host facts must not become visible merely by asking ArtifactRead for the overflow.
134
179
  const observation = result.archiveContext ?? result.context;
@@ -146,6 +191,16 @@ export async function governArtifactResult(context: PortContext, definition: Too
146
191
  }
147
192
  } catch { /* The original tool outcome remains authoritative even when storage fails. */ }
148
193
  if (ref) result.artifactRefs = [ref];
194
+ if (commandPreview && ref) {
195
+ const content = canonical({ ...commandPreview, artifact_uri: ref.uri, artifact_state: 'available',
196
+ output_preview_instruction: 'Read the granted artifact for omitted receipt text. Output cursors still refer to the original command. Do not repeat its effects.' });
197
+ if (modelSize({ ...result, context: { content } }) <= config.limits.maxToolResultBytes
198
+ && bytes(content) < bytes(projectToolResultContext(result, config).content)) {
199
+ result.context = { ...result.context, content };
200
+ return result;
201
+ }
202
+ if (!tooLarge && !force) return result;
203
+ }
149
204
  // Pixel observations use the independent image allowance; a forced text archive cannot erase them.
150
205
  if (config.modelSurface && !tooLarge && result.context?.media?.length) return result;
151
206
  if (sourceView && !result.context?.media?.length && !result.additionalContexts?.length) {
@@ -164,7 +219,7 @@ export async function governArtifactResult(context: PortContext, definition: Too
164
219
  }
165
220
  if (!tooLarge && !ref) return result;
166
221
  result.context = { content: offloadedView(result, bytes(content), config.limits.maxToolResultBytes, ref,
167
- result.context?.content ?? canonical(result.content), !ref) };
222
+ result.context?.content ?? canonical(result.content), !ref, commandPreview) };
168
223
  delete result.additionalContexts;
169
224
  return result;
170
225
  }
@@ -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;
@@ -253,7 +253,7 @@ export function configure(input: ConfigurationInput): RunConfiguration {
253
253
  const policy = profile.providerCompatibilityPolicy;
254
254
  invariant(policy !== null && typeof policy === 'object' && !Array.isArray(policy)
255
255
  && Object.keys(policy).every(key => ['contract', 'rule'].includes(key))
256
- && ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4', 'provider-compat/v5'].includes(policy.contract)
256
+ && ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4', 'provider-compat/v5', 'provider-compat/v6'].includes(policy.contract)
257
257
  && ['auto', 'permissive', 'openai', 'strict-openai', 'cerebras', 'groq', 'deepseek',
258
258
  'zai', 'kspmas-gateway', 'moonshot', 'mimo'].includes(policy.rule), 'invalid_provider_compatibility_policy');
259
259
  }
@@ -404,8 +404,12 @@ export function configure(input: ConfigurationInput): RunConfiguration {
404
404
  && Number.isSafeInteger(policy.summaryMaxTokens) && policy.summaryMaxTokens > 0
405
405
  && ['strict', 'context_bounded_estimate'].includes(policy.summaryBudgetMode ?? 'strict')
406
406
  && (policy.budgetTiming === undefined || policy.budgetTiming === 'before-model/v1')
407
- && (policy.continuityPlacement === undefined || policy.continuityPlacement === 'after-history/v1'
407
+ && (policy.continuityPlacement === undefined || ['after-history/v1', 'split-after-history/v1'].includes(policy.continuityPlacement)
408
408
  && profile.operatorGuidancePolicy === undefined)
409
+ && (policy.continuityProjection === undefined || policy.continuityProjection === 'decision-input/v1'
410
+ && config.modelSurface?.verificationProjection === 'readable-evidence/v1')
411
+ && (policy.commandOutputProjection === undefined || policy.commandOutputProjection === 'receipt-preview/v1'
412
+ && config.artifactPolicy === 'runtime-artifacts/v1')
409
413
  && (policy.sourceReusePolicy === undefined || policy.sourceReusePolicy === 'captured-source/v1'
410
414
  && profile.providerFamily === 'openai-chat' && config.artifactPolicy === 'runtime-artifacts/v1')
411
415
  && (policy.maxCompactions === null || Number.isSafeInteger(policy.maxCompactions) && policy.maxCompactions >= 0)