@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/src/machine.mts CHANGED
@@ -3,8 +3,8 @@ 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';
7
- import { FINAL_SUBMISSION_TOOL, finalSubmissionTool, submittedFinalText, normalizedFinalText, finalDeliveryChanges } from './final-submission.mjs';
6
+ import { providerRetryDeadline, retryDeadline, retryDelay } from './retry.mjs';
7
+ import { FINAL_SUBMISSION_TOOL, finalSubmissionTool, finalSubmissionFailure, 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';
10
10
  import { validateWorkspaceChange, workspaceChangeUnobserved } from './workspace-change.mjs';
@@ -29,6 +29,8 @@ 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';
33
+ import { TODO_WRITE, isTodoCall } from './todos.mjs';
32
34
 
33
35
  export function objectValue(value: unknown): ObjectValue {
34
36
  invariant(value !== null && typeof value === 'object' && !Array.isArray(value), 'expected_json_object');
@@ -273,24 +275,35 @@ export function plan(snapshot: RunSnapshot, config: RunConfiguration, capabiliti
273
275
  if (snapshot.phase === 'verifying') {
274
276
  invariant(snapshot.candidate, 'verification_candidate_missing');
275
277
  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
278
  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) {
279
+ const canRepairDelivery = config.todoPolicy === 'session-todos/v1' && snapshot.candidate.purpose !== 'checkpoint'
280
+ && snapshot.lastWorkspaceMutationToolCall != null;
281
+ const failedCommands = canRepairDelivery ? failedDeliveryCommands(snapshot.messages) : [];
282
+ // Use observed failures directly instead of asking for an extra review
283
+ // model call to rediscover the same checks.
284
+ if (!failedCommands.length) {
285
+ const review = policies.forRun(config).review.scheduleDeliveryReview(snapshot, config, 'verification_report_missing', digest);
286
+ if (review) return transition(snapshot, review, [{ kind: 'completion.delivery_review_started', payload: {} }]);
287
+ }
288
+ if (canRepairDelivery && (remaining.length || failedCommands.length)) {
281
289
  const progress = digest({ goal: snapshot.goalRevision, workspace: snapshot.workspaceRevision,
282
- checks: remaining.map(item => item.content).sort() });
290
+ checks: remaining.map(item => item.content).sort(),
291
+ ...(failedCommands.length ? { failedCommands: failedCommands.map(canonical).sort() } : {}) });
283
292
  const reason = snapshot.deliveryContinuationDigest === progress ? 'delivery_no_progress'
284
293
  : snapshot.repairs >= config.limits.maxRepairs || finalizationOnly(snapshot, config)
285
294
  || toolRoom(snapshot, config) <= 0 || wallDeliveryOnly(snapshot, config) ? 'delivery_repair_budget_exhausted' : null;
286
295
  if (reason) return transition(snapshot, { phase: 'paused', resumePhase: 'preparing_context', candidate: null, reason, outcome: null },
287
296
  [{ kind: 'run.paused', payload: { reason } }]);
297
+ const issue = failedCommands.length ? 'delivery_checks_failed' : 'delivery_todos_incomplete';
288
298
  return transition(snapshot, { phase: 'preparing_context', candidate: null, preparedContext: null,
289
299
  repairs: snapshot.repairs + 1, deliveryContinuationDigest: progress, messages: [...snapshot.messages,
290
- { role: 'user', kind: 'verification_observation', content: canonical({ reason: 'delivery_todos_incomplete',
300
+ { role: 'user', kind: 'verification_observation', content: canonical({ reason: issue,
291
301
  remaining: remaining.map(item => item.content),
302
+ ...(failedCommands.length ? { failedCommands: failedCommands.map(check => ({
303
+ command: check.command.slice(0, 320), cwd: check.cwd.slice(0, 240), exitCode: check.exitCode,
304
+ })) } : {}),
292
305
  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' } }]);
306
+ [{ kind: 'completion.continued', payload: { reason: issue } }]);
294
307
  }
295
308
  return finalizing(snapshot, 'unverified', 'verification_report_missing');
296
309
  }
@@ -357,7 +370,7 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
357
370
  ...(result.usageReported === false ? { providerUsageIncomplete: true } : {}),
358
371
  ...(result.failureDiagnostic || snapshot.diagnostics.lastModelFailure
359
372
  ? { lastModelFailure: result.failureDiagnostic ? objectValue(result.failureDiagnostic) : null } : {}) } } : {}) };
360
- if (policies.forRun(config).review.reviewPending(snapshot)) {
373
+ if (policies.forRun(config).review.reviewPending(snapshot) && result.kind !== 'provider_retryable_error') {
361
374
  const beforeCall = { ...snapshot, usage: { ...snapshot.usage, modelCalls: snapshot.usage.modelCalls - 1 } };
362
375
  const readers = policies.forRun(config).review.deliveryReviewReaders(beforeCall, config);
363
376
  if (result.kind === 'tool_calls' && result.toolCalls.length && readers.length
@@ -403,10 +416,11 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
403
416
  callId: call.callId, name: call.name, content: canonical({ status: 'error', content: { reason: 'delivery_read_path_not_written', executed: false } }) }))] };
404
417
  if (finalSubmissionTool(config) && result.toolCalls.some(call => call.name === FINAL_SUBMISSION_TOOL)) {
405
418
  const text = result.toolCalls.length === 1 ? submittedFinalText(result.toolCalls[0]!, config) : null;
419
+ const receipt = text === null ? { status: 'not_dispatched', ...finalSubmissionFailure(result.toolCalls, config) }
420
+ : { status: 'accepted', reason: 'final_submission_candidate' };
406
421
  const messages: Message[] = [...snapshot.messages, { ...message, toolCalls: result.toolCalls },
407
422
  ...result.toolCalls.map(call => ({ role: 'tool' as const, callId: call.callId, name: call.name,
408
- content: canonical({ status: text === null ? 'not_dispatched' : 'accepted',
409
- reason: text === null ? 'final_submission_schema_or_batch_invalid' : 'final_submission_candidate' }) }))];
423
+ content: canonical(receipt) }))];
410
424
  if (text !== null) {
411
425
  if (config.deliveryScopePolicy === RESULT_DELIVERY_POLICY) messages[snapshot.messages.length] = {
412
426
  ...messages[snapshot.messages.length]!, content: text, kind: 'final_candidate' };
@@ -541,9 +555,12 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
541
555
  : oversizedTool ? Math.min(config.profile.maxRetries, 1) : config.profile.maxRetries;
542
556
  const exhausted = attempts > limit;
543
557
  const delay = retryDelay(result, attempts, config, random);
558
+ const providerRetryNotBefore = providerRetryDeadline(result, now);
559
+ const providerWait = providerRetryNotBefore === undefined ? {} : { providerRetryNotBefore };
544
560
  // An unavailable provider is not a task failure: pause with a fresh budget so the Host can resume later.
545
561
  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 };
562
+ resumePhase: 'preparing_context', outcome: null, reason: 'provider_unavailable', providerErrors: 0,
563
+ retryNotBefore: providerRetryNotBefore ?? 0, ...providerWait };
547
564
  const messages: Message[] = provider ? snapshot.messages : [...snapshot.messages, { role: 'user', kind: responseContinuationPending(snapshot, config)
548
565
  ? 'response_continuation_feedback' : 'model_feedback',
549
566
  content: oversizedTool
@@ -556,7 +573,8 @@ export function reduceModel(snapshot: RunSnapshot, input: ModelResult, config: R
556
573
  return { ...base, phase: exhausted ? 'finalizing' : 'preparing_context', outcome: exhausted ? 'failed' : null,
557
574
  reason: exhausted ? `${result.kind}_retry_exhausted` : null,
558
575
  providerErrors: provider ? attempts : base.providerErrors ?? snapshot.providerErrors,
559
- modelErrors: provider ? snapshot.modelErrors : attempts, retryNotBefore: exhausted ? 0 : now + delay, messages };
576
+ modelErrors: provider ? snapshot.modelErrors : attempts, retryNotBefore: exhausted ? 0 : retryDeadline(now, delay),
577
+ ...(!exhausted ? providerWait : {}), messages };
560
578
  }
561
579
  case 'policy_abort': return { ...base, phase: 'finalizing', outcome: 'blocked', reason: 'model_policy_abort' };
562
580
  case 'user_abort': return { ...base, phase: 'finalizing', outcome: 'unverified', reason: 'model_user_abort' };
@@ -666,7 +684,9 @@ export function reduceTools(snapshot: RunSnapshot, results: ToolResult[], calls:
666
684
  }
667
685
  updated.messages.push({ ...projectToolResultContext(result, config),
668
686
  role: 'tool', callId: call.callId, name: call.name,
669
- ...(config.contextPolicy?.pruneToolResults || config.contextPolicy?.sourceReusePolicy ? { toolOutcome: result.status } : {}),
687
+ ...(config.contextPolicy?.pruneToolResults || config.contextPolicy?.sourceReusePolicy
688
+ || call.name === TODO_WRITE && isTodoCall(config, call) && config.modelSurface?.verificationProjection === 'readable-evidence/v1'
689
+ ? { toolOutcome: result.status } : {}),
670
690
  ...(definition?.contextRetention === 'persistent' ? { persistent: true } : {}) });
671
691
  if (updated.toolDiscovery && call.name === TOOL_SEARCH && result.status === 'ok'
672
692
  && result.content && typeof result.content === 'object' && !Array.isArray(result.content)) {
@@ -1,7 +1,7 @@
1
1
  import type { ArtifactRef, Message, RunConfiguration, VerificationReport } from './contracts.mjs';
2
2
  import { canonical, copy, invariant } from './values.mjs';
3
3
 
4
- export const NATIVE_LOCAL_RESOURCE_PROFILES = ['bounded/v1', 'local-development/v1', 'local-development/v2'] as const;
4
+ export const NATIVE_LOCAL_RESOURCE_PROFILES = ['bounded/v1', 'local-development/v1', 'local-development/v2', 'local-development/v3'] as const;
5
5
 
6
6
  /** Facts are supplied by the execution owner, never inferred from prompt prose. */
7
7
  export interface WorkspaceBrowserCapability {
package/src/recovery.mts CHANGED
@@ -12,6 +12,10 @@ export function safeReadRecoveryCalls(calls: ToolCall[], configuration: RunConfi
12
12
  }
13
13
  function replayPolicy(intent: EffectIntent, configuration: RunConfiguration): string | null {
14
14
  if (intent.kind === 'workspace') return 'workspace-observation/v1';
15
+ // Kernel planning with a local counter has no external effects. A legacy
16
+ // prepare adapter or a host context source has no such replay contract.
17
+ if (intent.kind === 'context' && configuration.contextPolicy && configuration.contextSources.length === 0)
18
+ return 'local-context-planning/v1';
15
19
  if (intent.kind === 'verify' && configuration.hostVerification) return 'host-verification-read/v1';
16
20
  if (intent.kind === 'model' && configuration.modelRecoveryPolicy === 'pure-inference/v1') return 'pure-inference/v1';
17
21
  if (intent.kind === 'tool') {
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
+ }
package/src/todos.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
  import { canonical, copy, invariant } from './values.mjs';
3
3
  import { toolInputRejection } from './tool-input.mjs';
4
4
 
@@ -66,6 +66,16 @@ export function reduceTodo(snapshot: RunSnapshot, config: RunConfiguration, call
66
66
  lastWriteAssistantTurn: snapshot.todos.assistantTurns };
67
67
  }
68
68
 
69
+ /** The complete list is already present in execution continuity. Keep the
70
+ * committed receipt and the request arguments intact for replay and history. */
71
+ export function projectTodoWriteReceipt(message: Message): Message {
72
+ if (message.role !== 'tool' || message.name !== TODO_WRITE || message.toolOutcome !== 'ok') return message;
73
+ let receipt;
74
+ try { receipt = JSON.parse(message.content); } catch { return message; }
75
+ if (!Array.isArray(receipt?.todos) || !Array.isArray(receipt.oldTodos) || !receipt.summary) return message;
76
+ return { ...message, content: canonical({ status: 'updated', summary: receipt.summary }) };
77
+ }
78
+
69
79
  /** Reference cadence: ten assistant requests since both write and previous reminder. */
70
80
  export function todoReminder(snapshot: RunSnapshot, config: RunConfiguration): Partial<RunSnapshot> | null {
71
81
  const state = snapshot.todos;
@@ -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,