coremind-runtime 1.0.1 → 1.4.0

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 (254) hide show
  1. package/README.md +1 -1
  2. package/dist/active-run-binding.d.ts +10 -0
  3. package/dist/active-run-binding.d.ts.map +1 -1
  4. package/dist/active-run-binding.js +7 -0
  5. package/dist/active-run-binding.js.map +1 -1
  6. package/dist/agent-driver.d.ts +34 -0
  7. package/dist/agent-driver.d.ts.map +1 -1
  8. package/dist/agent-driver.js +24 -4
  9. package/dist/agent-driver.js.map +1 -1
  10. package/dist/agent-factory.d.ts.map +1 -1
  11. package/dist/agent-factory.js +227 -32
  12. package/dist/agent-factory.js.map +1 -1
  13. package/dist/bounded-output.d.ts +13 -0
  14. package/dist/bounded-output.d.ts.map +1 -0
  15. package/dist/bounded-output.js +200 -0
  16. package/dist/bounded-output.js.map +1 -0
  17. package/dist/chat-session.d.ts +26 -4
  18. package/dist/chat-session.d.ts.map +1 -1
  19. package/dist/chat-session.js +63 -10
  20. package/dist/chat-session.js.map +1 -1
  21. package/dist/compaction-projection.d.ts +1 -1
  22. package/dist/compaction-projection.d.ts.map +1 -1
  23. package/dist/compaction-projection.js +1 -1
  24. package/dist/compaction-projection.js.map +1 -1
  25. package/dist/context-lifecycle.d.ts.map +1 -1
  26. package/dist/context-lifecycle.js +1 -1
  27. package/dist/context-lifecycle.js.map +1 -1
  28. package/dist/context.d.ts.map +1 -1
  29. package/dist/context.js +1 -1
  30. package/dist/context.js.map +1 -1
  31. package/dist/control-inbox.d.ts +2 -0
  32. package/dist/control-inbox.d.ts.map +1 -1
  33. package/dist/control-inbox.js +27 -4
  34. package/dist/control-inbox.js.map +1 -1
  35. package/dist/dependency-adapter.d.ts.map +1 -1
  36. package/dist/dependency-adapter.js +4 -4
  37. package/dist/dependency-adapter.js.map +1 -1
  38. package/dist/errors.d.ts.map +1 -1
  39. package/dist/errors.js +3 -2
  40. package/dist/errors.js.map +1 -1
  41. package/dist/evaluation-graders.js +9 -10
  42. package/dist/evaluation-graders.js.map +1 -1
  43. package/dist/evaluation.d.ts +2 -0
  44. package/dist/evaluation.d.ts.map +1 -1
  45. package/dist/evaluation.js +12 -1
  46. package/dist/evaluation.js.map +1 -1
  47. package/dist/events.d.ts +15 -0
  48. package/dist/events.d.ts.map +1 -1
  49. package/dist/events.js.map +1 -1
  50. package/dist/execution-security.d.ts.map +1 -1
  51. package/dist/execution-security.js +12 -3
  52. package/dist/execution-security.js.map +1 -1
  53. package/dist/index.d.ts +7 -1
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +3 -0
  56. package/dist/index.js.map +1 -1
  57. package/dist/input-receipt.d.ts +4 -0
  58. package/dist/input-receipt.d.ts.map +1 -1
  59. package/dist/input-receipt.js +11 -0
  60. package/dist/input-receipt.js.map +1 -1
  61. package/dist/internal.d.ts +5 -0
  62. package/dist/internal.d.ts.map +1 -1
  63. package/dist/internal.js +5 -0
  64. package/dist/internal.js.map +1 -1
  65. package/dist/mcp-authentication.d.ts +11 -0
  66. package/dist/mcp-authentication.d.ts.map +1 -0
  67. package/dist/mcp-authentication.js +24 -0
  68. package/dist/mcp-authentication.js.map +1 -0
  69. package/dist/mcp-runtime.d.ts +91 -0
  70. package/dist/mcp-runtime.d.ts.map +1 -0
  71. package/dist/mcp-runtime.js +514 -0
  72. package/dist/mcp-runtime.js.map +1 -0
  73. package/dist/observability.d.ts.map +1 -1
  74. package/dist/observability.js +8 -3
  75. package/dist/observability.js.map +1 -1
  76. package/dist/orchestrator.d.ts +2 -2
  77. package/dist/orchestrator.d.ts.map +1 -1
  78. package/dist/orchestrator.js +59 -33
  79. package/dist/orchestrator.js.map +1 -1
  80. package/dist/project-check.d.ts.map +1 -1
  81. package/dist/project-check.js +25 -0
  82. package/dist/project-check.js.map +1 -1
  83. package/dist/project-code-trust.d.ts +12 -0
  84. package/dist/project-code-trust.d.ts.map +1 -0
  85. package/dist/project-code-trust.js +97 -0
  86. package/dist/project-code-trust.js.map +1 -0
  87. package/dist/projection.d.ts.map +1 -1
  88. package/dist/projection.js +6 -3
  89. package/dist/projection.js.map +1 -1
  90. package/dist/provider.d.ts +2 -2
  91. package/dist/provider.d.ts.map +1 -1
  92. package/dist/provider.js +58 -15
  93. package/dist/provider.js.map +1 -1
  94. package/dist/rebuild-request.d.ts +3 -1
  95. package/dist/rebuild-request.d.ts.map +1 -1
  96. package/dist/rebuild-request.js +6 -2
  97. package/dist/rebuild-request.js.map +1 -1
  98. package/dist/redaction.d.ts +4 -0
  99. package/dist/redaction.d.ts.map +1 -0
  100. package/dist/redaction.js +40 -0
  101. package/dist/redaction.js.map +1 -0
  102. package/dist/run-context.d.ts +6 -2
  103. package/dist/run-context.d.ts.map +1 -1
  104. package/dist/run-context.js +16 -1
  105. package/dist/run-context.js.map +1 -1
  106. package/dist/run-state.d.ts +8 -1
  107. package/dist/run-state.d.ts.map +1 -1
  108. package/dist/run-state.js +151 -84
  109. package/dist/run-state.js.map +1 -1
  110. package/dist/runtime.d.ts +13 -3
  111. package/dist/runtime.d.ts.map +1 -1
  112. package/dist/runtime.js +1159 -177
  113. package/dist/runtime.js.map +1 -1
  114. package/dist/session-tree.d.ts +51 -0
  115. package/dist/session-tree.d.ts.map +1 -0
  116. package/dist/session-tree.js +14 -0
  117. package/dist/session-tree.js.map +1 -0
  118. package/dist/session-v4/compaction/compaction.d.ts +84 -0
  119. package/dist/session-v4/compaction/compaction.d.ts.map +1 -0
  120. package/dist/session-v4/compaction/compaction.js +581 -0
  121. package/dist/session-v4/compaction/compaction.js.map +1 -0
  122. package/dist/session-v4/compaction/utils.d.ts +39 -0
  123. package/dist/session-v4/compaction/utils.d.ts.map +1 -0
  124. package/dist/session-v4/compaction/utils.js +139 -0
  125. package/dist/session-v4/compaction/utils.js.map +1 -0
  126. package/dist/session-v4/file-system.d.ts +25 -0
  127. package/dist/session-v4/file-system.d.ts.map +1 -0
  128. package/dist/session-v4/file-system.js +257 -0
  129. package/dist/session-v4/file-system.js.map +1 -0
  130. package/dist/session-v4/index.d.ts +33 -0
  131. package/dist/session-v4/index.d.ts.map +1 -0
  132. package/dist/session-v4/index.js +33 -0
  133. package/dist/session-v4/index.js.map +1 -0
  134. package/dist/session-v4/message-types.d.ts +28 -0
  135. package/dist/session-v4/message-types.d.ts.map +1 -0
  136. package/dist/session-v4/message-types.js +2 -0
  137. package/dist/session-v4/message-types.js.map +1 -0
  138. package/dist/session-v4/messages.d.ts +66 -0
  139. package/dist/session-v4/messages.d.ts.map +1 -0
  140. package/dist/session-v4/messages.js +112 -0
  141. package/dist/session-v4/messages.js.map +1 -0
  142. package/dist/session-v4/session/context.d.ts +45 -0
  143. package/dist/session-v4/session/context.d.ts.map +1 -0
  144. package/dist/session-v4/session/context.js +69 -0
  145. package/dist/session-v4/session/context.js.map +1 -0
  146. package/dist/session-v4/session/jsonl/codec.d.ts +31 -0
  147. package/dist/session-v4/session/jsonl/codec.d.ts.map +1 -0
  148. package/dist/session-v4/session/jsonl/codec.js +195 -0
  149. package/dist/session-v4/session/jsonl/codec.js.map +1 -0
  150. package/dist/session-v4/session/jsonl/errors.d.ts +28 -0
  151. package/dist/session-v4/session/jsonl/errors.d.ts.map +1 -0
  152. package/dist/session-v4/session/jsonl/errors.js +11 -0
  153. package/dist/session-v4/session/jsonl/errors.js.map +1 -0
  154. package/dist/session-v4/session/jsonl/repo.d.ts +25 -0
  155. package/dist/session-v4/session/jsonl/repo.d.ts.map +1 -0
  156. package/dist/session-v4/session/jsonl/repo.js +161 -0
  157. package/dist/session-v4/session/jsonl/repo.js.map +1 -0
  158. package/dist/session-v4/session/jsonl/storage.d.ts +43 -0
  159. package/dist/session-v4/session/jsonl/storage.d.ts.map +1 -0
  160. package/dist/session-v4/session/jsonl/storage.js +245 -0
  161. package/dist/session-v4/session/jsonl/storage.js.map +1 -0
  162. package/dist/session-v4/session/jsonl/types.d.ts +58 -0
  163. package/dist/session-v4/session/jsonl/types.d.ts.map +1 -0
  164. package/dist/session-v4/session/jsonl/types.js +2 -0
  165. package/dist/session-v4/session/jsonl/types.js.map +1 -0
  166. package/dist/session-v4/session/jsonl.d.ts +26 -0
  167. package/dist/session-v4/session/jsonl.d.ts.map +1 -0
  168. package/dist/session-v4/session/jsonl.js +26 -0
  169. package/dist/session-v4/session/jsonl.js.map +1 -0
  170. package/dist/session-v4/session/memory.d.ts +44 -0
  171. package/dist/session-v4/session/memory.d.ts.map +1 -0
  172. package/dist/session-v4/session/memory.js +166 -0
  173. package/dist/session-v4/session/memory.js.map +1 -0
  174. package/dist/session-v4/session/session.d.ts +50 -0
  175. package/dist/session-v4/session/session.d.ts.map +1 -0
  176. package/dist/session-v4/session/session.js +246 -0
  177. package/dist/session-v4/session/session.js.map +1 -0
  178. package/dist/session-v4/session/state.d.ts +88 -0
  179. package/dist/session-v4/session/state.d.ts.map +1 -0
  180. package/dist/session-v4/session/state.js +355 -0
  181. package/dist/session-v4/session/state.js.map +1 -0
  182. package/dist/session-v4/session/testing/conformance.d.ts +3 -0
  183. package/dist/session-v4/session/testing/conformance.d.ts.map +1 -0
  184. package/dist/session-v4/session/testing/conformance.js +812 -0
  185. package/dist/session-v4/session/testing/conformance.js.map +1 -0
  186. package/dist/session-v4/session/testing/types.d.ts +34 -0
  187. package/dist/session-v4/session/testing/types.d.ts.map +1 -0
  188. package/dist/session-v4/session/testing/types.js +2 -0
  189. package/dist/session-v4/session/testing/types.js.map +1 -0
  190. package/dist/session-v4/session/types.d.ts +343 -0
  191. package/dist/session-v4/session/types.d.ts.map +1 -0
  192. package/dist/session-v4/session/types.js +10 -0
  193. package/dist/session-v4/session/types.js.map +1 -0
  194. package/dist/session-v4/types.d.ts +72 -0
  195. package/dist/session-v4/types.d.ts.map +1 -0
  196. package/dist/session-v4/types.js +37 -0
  197. package/dist/session-v4/types.js.map +1 -0
  198. package/dist/session-write-lease.d.ts +13 -0
  199. package/dist/session-write-lease.d.ts.map +1 -0
  200. package/dist/session-write-lease.js +310 -0
  201. package/dist/session-write-lease.js.map +1 -0
  202. package/dist/session.d.ts +21 -3
  203. package/dist/session.d.ts.map +1 -1
  204. package/dist/session.js +334 -78
  205. package/dist/session.js.map +1 -1
  206. package/dist/skill-privacy.d.ts +3 -0
  207. package/dist/skill-privacy.d.ts.map +1 -0
  208. package/dist/skill-privacy.js +22 -0
  209. package/dist/skill-privacy.js.map +1 -0
  210. package/dist/skill-runtime.d.ts +55 -0
  211. package/dist/skill-runtime.d.ts.map +1 -0
  212. package/dist/skill-runtime.js +223 -0
  213. package/dist/skill-runtime.js.map +1 -0
  214. package/dist/task-calls.d.ts +126 -0
  215. package/dist/task-calls.d.ts.map +1 -0
  216. package/dist/task-calls.js +187 -0
  217. package/dist/task-calls.js.map +1 -0
  218. package/dist/task-commit.d.ts +82 -0
  219. package/dist/task-commit.d.ts.map +1 -0
  220. package/dist/task-commit.js +364 -0
  221. package/dist/task-commit.js.map +1 -0
  222. package/dist/task-session.d.ts +108 -0
  223. package/dist/task-session.d.ts.map +1 -0
  224. package/dist/task-session.js +688 -0
  225. package/dist/task-session.js.map +1 -0
  226. package/dist/task-tool-driver.d.ts +10 -0
  227. package/dist/task-tool-driver.d.ts.map +1 -0
  228. package/dist/task-tool-driver.js +108 -0
  229. package/dist/task-tool-driver.js.map +1 -0
  230. package/dist/tool-discovery-declaration.d.ts +8 -0
  231. package/dist/tool-discovery-declaration.d.ts.map +1 -0
  232. package/dist/tool-discovery-declaration.js +15 -0
  233. package/dist/tool-discovery-declaration.js.map +1 -0
  234. package/dist/tool-discovery-replay.d.ts +13 -0
  235. package/dist/tool-discovery-replay.d.ts.map +1 -0
  236. package/dist/tool-discovery-replay.js +89 -0
  237. package/dist/tool-discovery-replay.js.map +1 -0
  238. package/dist/tool-discovery.d.ts +95 -0
  239. package/dist/tool-discovery.d.ts.map +1 -0
  240. package/dist/tool-discovery.js +532 -0
  241. package/dist/tool-discovery.js.map +1 -0
  242. package/dist/tool-policy.d.ts +17 -1
  243. package/dist/tool-policy.d.ts.map +1 -1
  244. package/dist/tool-policy.js +147 -60
  245. package/dist/tool-policy.js.map +1 -1
  246. package/dist/trace.d.ts +2 -2
  247. package/dist/trace.d.ts.map +1 -1
  248. package/dist/trace.js +6 -36
  249. package/dist/trace.js.map +1 -1
  250. package/dist/turn-tracker.d.ts +2 -0
  251. package/dist/turn-tracker.d.ts.map +1 -1
  252. package/dist/turn-tracker.js +13 -0
  253. package/dist/turn-tracker.js.map +1 -1
  254. package/package.json +10 -7
package/dist/runtime.js CHANGED
@@ -1,8 +1,9 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import path from "node:path";
3
- import { loadDirectorySkills, resolveSkills, SKILLS } from "coremind-templates";
3
+ import { SKILLS } from "coremind-templates";
4
+ import { resolveSelectedSkills } from "coremind-templates/internal";
4
5
  import { ArtifactStore, extractArtifactRecord, inferLegacyToolCapability, recoveryDispositionFor, resolveToolCapability, wrapToolWithArtifactCapture, } from "coremind-tools";
5
- import { buildToolsWithExecutionEnvironment, createPlatformExecutionEnvironment, resolveExecutionEnvironment, } from "coremind-tools/internal";
6
+ import { buildToolsWithExecutionEnvironment, configuredToolSource, createPlatformExecutionEnvironment, resolveExecutionEnvironment, } from "coremind-tools/internal";
6
7
  import { bindActiveRun, boundDelegationDispositionExecutor, boundDelegationExecutor, } from "./active-run-binding.js";
7
8
  import { buildAgentDriver } from "./agent-factory.js";
8
9
  import { RunBudgetController, resolveRuntimeLimits } from "./budget.js";
@@ -16,36 +17,45 @@ import { projectContextTaskState } from "./context-task-state.js";
16
17
  import { ControlInbox, } from "./control-inbox.js";
17
18
  import { buildDelegatedInitialPrompt, resolveDelegatedContextReferences, } from "./delegated-context.js";
18
19
  import { createDelegationAgentTool, createDelegationDispositionAgentTool, DELEGATION_DISPOSITION_TOOL_CAPABILITY, DELEGATION_DISPOSITION_TOOL_EFFECT, DELEGATION_DISPOSITION_TOOL_NAME, DELEGATION_TOOL_CAPABILITY, DELEGATION_TOOL_EFFECT, DELEGATION_TOOL_NAME, parseDelegationDispositionToolArgs, parseDelegationToolArgs, resolveDelegationAllocation, resolveDelegationHierarchyLimits, } from "./delegation-tool.js";
19
- import { createEffectReceiptBinding, fingerprintEffectReceiptValue, } from "./effect-receipt-binding.js";
20
+ import { createEffectReceiptBinding, fingerprintEffectReceiptValue, projectEffectReceiptBindings, } from "./effect-receipt-binding.js";
20
21
  import { CoreMindError, isErrorCode } from "./errors.js";
21
22
  import { extractAgentError, extractText } from "./events.js";
22
23
  import { normalizeExecutionError } from "./execution-error.js";
23
24
  import { enforceExecutionSecurity } from "./execution-security.js";
24
25
  import { HostVerificationGate } from "./host-verification.js";
25
26
  import { receiptId } from "./ids.js";
26
- import { claimInput, completeInput, createInputReceipt, discardInput, inputFingerprint, newInputId, receiptStatusOf, } from "./input-receipt.js";
27
+ import { claimInput, completeInput, controlInputId, createInputReceipt, discardInput, foldInputReceipts, inputFingerprint, isControlInputId, newInputId, receiptStatusOf, } from "./input-receipt.js";
27
28
  import { LifecycleExtensionHost, } from "./lifecycle-extension.js";
28
29
  import { LoopRunner } from "./loop-runner.js";
30
+ import { createMcpRun } from "./mcp-runtime.js";
29
31
  import { createTelemetryConfigurationFact, projectLocalObservability, TelemetryEgressController, validateTelemetryConsentBinding, validateTelemetryConsentFact, } from "./observability.js";
30
32
  import { DurableOperation, restoreDurableOperation, } from "./operation-state.js";
31
33
  import { Orchestrator } from "./orchestrator.js";
34
+ import { prepareProjectCodeImports } from "./project-code-trust.js";
32
35
  import { ProjectionEngine } from "./projection.js";
33
36
  import { buildProviderRuntime, contextCapabilityCandidatesForModel, resolveProviderModel, } from "./provider.js";
34
37
  import { adaptCoreMindTool } from "./public-tool.js";
35
38
  import { createProviderRequestReplayFact } from "./replay-kit.js";
36
39
  import { analyzeRunMetrics, assessReleaseReadiness, createEvaluationReport, } from "./result.js";
37
- import { runWithTransientRetry } from "./retry-policy.js";
40
+ import { classifyRetry, runWithTransientRetry } from "./retry-policy.js";
38
41
  import { RunContext } from "./run-context.js";
39
42
  import { RunEffectCoordinator } from "./run-effect-coordinator.js";
40
43
  import { RunKernel } from "./run-kernel.js";
41
- import { FileRunStore, fingerprintRunConfig, RunStateJournal, } from "./run-state.js";
44
+ import { FileRunStore, fingerprintRunConfig, isManagedRunPath, RunStateJournal, } from "./run-state.js";
42
45
  import { RunTerminalizer } from "./run-terminalizer.js";
43
46
  import { registerCoreMindRuntimeInstance } from "./runtime-instance-authority.js";
44
- import { CoreMindSession } from "./session.js";
47
+ import { CoreMindSession, copySessionHistory, historySessionSnapshot, isManagedSessionPath, openWritableSession, rememberSessionHistory, sessionSnapshot, } from "./session.js";
45
48
  import { compactSessionInRun } from "./session-maintenance.js";
49
+ import { bindSessionNavigation, } from "./session-tree.js";
50
+ import { assertJsonSerializable } from "./session-v4/session/session.js";
51
+ import { acquireSessionWriteLease, withSessionWriteLease, } from "./session-write-lease.js";
52
+ import { assertSkillSnapshotSize, freezeSkillSnapshot, restoreSkillSnapshot, SKILL_TOOL_CAPABILITY, SKILL_TOOL_EFFECT, SKILL_TOOL_NAME, SkillExecution, skillPrefixContents, } from "./skill-runtime.js";
46
53
  import { createRunSnapshot } from "./snapshot.js";
54
+ import { buildTaskToolDriver } from "./task-tool-driver.js";
47
55
  import { ToolExecutionEngine } from "./tool-call-lifecycle.js";
48
56
  import { toolCapabilityCallKey } from "./tool-capability-identity.js";
57
+ import { DISCOVER_TOOLS_NAME, restoreToolDiscovery, restoreToolDiscoveryContinuations, ToolDiscoveryExecution, } from "./tool-discovery.js";
58
+ import { TOOL_DISCOVERY_DECLARATION } from "./tool-discovery-declaration.js";
49
59
  import { ToolPolicy } from "./tool-policy.js";
50
60
  import { redactSensitiveText, TraceRecorder } from "./trace.js";
51
61
  import { TurnTracker } from "./turn-tracker.js";
@@ -104,6 +114,16 @@ export class CoreMindRuntime {
104
114
  this.resumedContextLength = resumedContextLength;
105
115
  this.mainAgentName = config.defaultAgent ?? firstKey(config.agents) ?? "";
106
116
  this.skillsByAgent = skillsByAgent;
117
+ bindSessionNavigation(this, (agentName, history, operation) => navigateRuntimeSession(this, agentName, history, operation));
118
+ const slot = executionSlotFor(this);
119
+ slot.sessionAgent = this.mainAgentName;
120
+ if (options.sessionId && config.session?.enabled) {
121
+ slot.sessionOptions = {
122
+ dir: sessionDir(config, options.configDir),
123
+ sessionId: options.sessionId,
124
+ cwd: options.cwd ?? process.cwd(),
125
+ };
126
+ }
107
127
  // 这些读取只用于保留已冻结的私有声明布局;执行状态已迁移到 RunContext。
108
128
  void this.lastAgents;
109
129
  void this.activeHarnessFactory;
@@ -116,8 +136,12 @@ export class CoreMindRuntime {
116
136
  return CoreMindRuntime.createWithWorkspaceLease(options, new WorkspaceLeaseService());
117
137
  }
118
138
  /** 同一父子树复用一个 Lease 服务;跨进程一致性仍由 canonical lock file 提供。 */
119
- static async createWithWorkspaceLease(options, workspaceLeaseService) {
139
+ static async createWithWorkspaceLease(options, workspaceLeaseService, frozenSkills) {
120
140
  const { config, configDir } = options;
141
+ if (config.schemaVersion !== 3 &&
142
+ [config.tools ?? [], ...Object.values(config.agents).map((agent) => agent.tools ?? [])].some((tools) => tools.some((tool) => tool.exposure === "deferred"))) {
143
+ throw new CoreMindError("invalid_config", "deferred 必须显式配置 schemaVersion: 3");
144
+ }
121
145
  const cwd = options.cwd ?? process.cwd();
122
146
  const env = options.env ?? process.env;
123
147
  const requestedToolEnv = options.toolEnv ?? env;
@@ -132,6 +156,17 @@ export class CoreMindRuntime {
132
156
  if (options.childRunAuthority && (options.toolDefinitions?.length ?? 0) > 0) {
133
157
  throw new CoreMindError("child_run_policy_escalation", "Child Runtime 不接受缺少内建 provenance 的注入工具");
134
158
  }
159
+ if (options.childRunAuthority &&
160
+ (options.mcpAuthentication !== undefined ||
161
+ config.mcp !== undefined ||
162
+ Object.values(config.agents).some((agent) => agent.mcpResources !== undefined) ||
163
+ [
164
+ config.tools ?? [],
165
+ ...Object.values(config.agents).map((agent) => agent.tools ?? []),
166
+ ].some((tools) => tools.some((tool) => "mcp" in tool)))) {
167
+ throw new CoreMindError("child_run_policy_escalation", "Child Runtime 不接受宿主本地服务工具");
168
+ }
169
+ const beforeScriptImport = await prepareProjectCodeImports(config, configDir, options.approveProjectCode, options.signal);
135
170
  // 1. provider(解析模型,警告转发)
136
171
  const providerRuntime = await buildProviderRuntime(config.provider, env, options.secretResolver);
137
172
  for (const warning of providerRuntime.warnings) {
@@ -152,17 +187,44 @@ export class CoreMindRuntime {
152
187
  const externalTools = (options.toolDefinitions ?? []).map((definition) => wrapToolWithArtifactCapture(adaptCoreMindTool(definition), artifactStore));
153
188
  let runtime;
154
189
  // 自定义技能(生态机制):配置文件所在目录的 skills/ 下,每个子目录的 README.md 即一个技能
155
- const customSkills = await loadDirectorySkills(path.join(configDir, "skills"));
190
+ const restoredSkills = frozenSkills ??
191
+ (options.resumeRunId
192
+ ? restoreSkillSnapshot(await (options.runStore ?? new FileRunStore(path.join(configDir, ".coremind", "runs"))).read(options.resumeRunId), config.agents)
193
+ : undefined);
194
+ const selectedSkills = Object.create(null);
156
195
  for (const [name, agentCfg] of Object.entries(config.agents)) {
157
196
  const agentModel = resolveProviderModel(providerRuntime, agentCfg.model);
158
197
  agentModels.set(name, agentModel);
198
+ const selected = restoredSkills
199
+ ? { ...restoredSkills.agents[name], missing: [], warnings: [] }
200
+ : await resolveSelectedSkills(agentCfg.skills ?? [], configDir);
201
+ if (options.resumeRunId && !restoredSkills && selected.standard.length > 0) {
202
+ throw new CoreMindError("context_capability_conflict", "恢复标准技能缺少原 Run 冻结快照");
203
+ }
204
+ selectedSkills[name] = {
205
+ legacyContents: selected.legacyContents,
206
+ standard: selected.standard,
207
+ };
208
+ if (Object.values(selectedSkills).some((selection) => selection.standard.length > 0)) {
209
+ assertSkillSnapshotSize({ version: 1, agents: selectedSkills });
210
+ }
211
+ for (const warning of selected.warnings)
212
+ emit({ type: "error", message: warning, fatal: false });
213
+ if (selected.standard.length > 0 &&
214
+ externalTools.some((tool) => tool.name === SKILL_TOOL_NAME)) {
215
+ throw new CoreMindError("invalid_tool", "标准技能启用时,自定义工具不得使用 load_skill 名称");
216
+ }
159
217
  const toolConfigs = (agentCfg.tools?.length ?? 0) > 0 ? agentCfg.tools : config.tools;
160
- const { tools, warnings, effects, capabilities } = await buildToolsWithExecutionEnvironment(toolConfigs ?? [], {
218
+ const { tools, warnings, effects, capabilities } = await buildToolsWithExecutionEnvironment((toolConfigs ?? []).filter((tool) => !("mcp" in tool)), {
161
219
  cwd,
162
220
  configDir,
163
221
  env: toolEnv,
164
222
  artifactStore,
223
+ beforeScriptImport,
165
224
  }, executionEnvironment);
225
+ if (selected.standard.length > 0 && tools.some((tool) => tool.name === SKILL_TOOL_NAME)) {
226
+ throw new CoreMindError("invalid_tool", "标准技能启用时,脚本工具不得使用 load_skill 名称");
227
+ }
166
228
  for (const warning of warnings) {
167
229
  emit({ type: "error", message: warning, fatal: false });
168
230
  }
@@ -206,6 +268,7 @@ export class CoreMindRuntime {
206
268
  ...effects,
207
269
  ...(options.toolDefinitions ?? []).map((definition) => [definition.name, definition.effect]),
208
270
  ...delegationEffects,
271
+ ...(selected.standard.length > 0 ? [[SKILL_TOOL_NAME, SKILL_TOOL_EFFECT]] : []),
209
272
  ]));
210
273
  toolCapabilitiesByAgent.set(name, new Map([
211
274
  ...capabilities,
@@ -220,43 +283,60 @@ export class CoreMindRuntime {
220
283
  : inferLegacyToolCapability(definition.name, definition.effect),
221
284
  ]),
222
285
  ...delegationCapabilities,
286
+ ...(selected.standard.length > 0
287
+ ? [[SKILL_TOOL_NAME, SKILL_TOOL_CAPABILITY]]
288
+ : []),
223
289
  ]));
224
290
  // 技能:内置优先,未命中的查自定义目录,仍缺失才告警(不阻断)
225
- const { contents, missing } = resolveSkills(agentCfg.skills ?? []);
226
- const allContents = [...contents];
227
- for (const id of missing) {
228
- const custom = customSkills.get(id);
229
- if (custom) {
230
- allContents.push(custom);
231
- }
232
- else {
233
- emit({
234
- type: "error",
235
- message: `技能 ${id} 不存在(内置:${SKILLS.map((s) => s.id).join("、")};自定义:放配置目录的 skills/${id}/README.md),已忽略`,
236
- fatal: false,
237
- });
238
- }
291
+ const allContents = skillPrefixContents(selectedSkills[name]);
292
+ for (const id of selected.missing) {
293
+ emit({
294
+ type: "error",
295
+ message: `技能 ${id} 不存在(内置:${SKILLS.map((s) => s.id).join("、")};自定义:放配置目录的 skills/${id}/README.md),已忽略`,
296
+ fatal: false,
297
+ });
239
298
  }
240
299
  skillsByAgent.set(name, allContents);
241
- driverBuilders.set(name, ({ onEvent, harness, sessionMessages }) => buildAgentDriver(agentCfg, {
242
- models: providerRuntime.models,
243
- model: agentModel,
244
- tools: driverTools,
245
- agentName: name,
246
- onEvent,
247
- apiKeyOverride: providerRuntime.apiKeyOverride,
248
- sessionMessages,
249
- skillsContent: allContents,
250
- stableFacts: {
251
- provider: agentModel.provider,
252
- model: agentModel.id,
253
- contextWindow: agentModel.contextWindow,
254
- },
255
- promptCacheStatus: agentModel.cost.cacheRead > 0 || agentModel.cost.cacheWrite > 0
256
- ? "available"
257
- : "unavailable",
258
- harness,
259
- }));
300
+ driverBuilders.set(name, ({ onEvent, harness, sessionMessages, skillTool, mcpTools, discoveryTool, taskTool }) => {
301
+ for (const tool of driverTools)
302
+ harness?.registerToolSource?.(tool.name, configuredToolSource(tool));
303
+ if (taskTool)
304
+ return buildTaskToolDriver({
305
+ tools: [
306
+ ...driverTools,
307
+ ...(mcpTools ?? []),
308
+ ...(skillTool ? [skillTool] : []),
309
+ ...(discoveryTool ? [discoveryTool] : []),
310
+ ],
311
+ agentName: name,
312
+ harness,
313
+ onEvent,
314
+ }, taskTool);
315
+ return buildAgentDriver(agentCfg, {
316
+ models: providerRuntime.models,
317
+ model: agentModel,
318
+ tools: [
319
+ ...driverTools,
320
+ ...(mcpTools ?? []),
321
+ ...(skillTool ? [skillTool] : []),
322
+ ...(discoveryTool ? [discoveryTool] : []),
323
+ ],
324
+ agentName: name,
325
+ onEvent,
326
+ apiKeyOverride: providerRuntime.apiKeyOverride,
327
+ sessionMessages,
328
+ skillsContent: allContents,
329
+ stableFacts: {
330
+ provider: agentModel.provider,
331
+ model: agentModel.id,
332
+ contextWindow: agentModel.contextWindow,
333
+ },
334
+ promptCacheStatus: agentModel.cost.cacheRead > 0 || agentModel.cost.cacheWrite > 0
335
+ ? "available"
336
+ : "unavailable",
337
+ harness,
338
+ });
339
+ });
260
340
  }
261
341
  // 会话恢复:--session 且 session.enabled 时,打开已有会话注入历史视图(非破坏)
262
342
  let sessionMessages;
@@ -264,14 +344,10 @@ export class CoreMindRuntime {
264
344
  if (options.sessionId && config.session?.enabled) {
265
345
  const dir = sessionDir(config, configDir);
266
346
  try {
267
- if (await CoreMindSession.exists(dir, options.sessionId, cwd)) {
268
- const cm = await CoreMindSession.open({ dir, sessionId: options.sessionId, cwd });
269
- const restored = projectBranchMessages(await cm.branchEntries()).map((item) => item.message);
270
- if (restored.length > 0) {
271
- sessionMessages = restored;
272
- resumedContextLength = restored.length;
273
- }
274
- }
347
+ const cm = await CoreMindSession.open({ dir, sessionId: options.sessionId, cwd });
348
+ const restored = projectBranchMessages(await cm.branchEntries()).map((item) => item.message);
349
+ sessionMessages = rememberSessionHistory(cm, restored);
350
+ resumedContextLength = restored.length;
275
351
  }
276
352
  catch (error) {
277
353
  const detail = error instanceof Error ? error.message : String(error);
@@ -279,22 +355,55 @@ export class CoreMindRuntime {
279
355
  }
280
356
  }
281
357
  runtime = new CoreMindRuntime(config, agentConfigs, agentModels, driverBuilders, toolEffectsByAgent, toolCapabilitiesByAgent, providerRuntime, executionEnvironment, workspaceLeaseService, options, sessionMessages, resumedContextLength, skillsByAgent);
358
+ executionSlotFor(runtime).skills = restoredSkills ?? freezeSkillSnapshot(selectedSkills);
282
359
  return runtime;
283
360
  }
284
361
  /** 按名字创建独立 Driver 实例(每次新实例,消息历史独立) */
285
- createAgent(name, onEvent = this.options.events ?? (() => { }), stepId) {
362
+ async createAgent(name, onEvent = this.options.events ?? (() => { }), stepId, signal, taskTool) {
286
363
  const buildDriver = this.driverBuilders.get(name);
287
364
  if (!buildDriver)
288
365
  return undefined;
289
366
  const context = runContextFor(this);
290
367
  const executionId = randomUUID();
291
368
  const turnTracker = new TurnTracker();
292
- const harness = context.harnessFor(name, stepId, executionId);
369
+ const originalHarness = context.harnessFor(name, stepId, executionId);
370
+ signal?.throwIfAborted();
371
+ const mcpTools = await originalHarness?.prepareMcpTools?.(signal);
372
+ signal?.throwIfAborted();
373
+ const harness = {
374
+ ...originalHarness,
375
+ beforePrompt: async () => {
376
+ signal?.throwIfAborted();
377
+ if (originalHarness?.beforePrompt)
378
+ await originalHarness.beforePrompt();
379
+ if (name === this.mainAgentName) {
380
+ await context.currentControlInbox()?.applyPending("steering");
381
+ await context.currentControlInbox()?.applyPending("follow_up");
382
+ }
383
+ signal?.throwIfAborted();
384
+ if (this.options.signal?.aborted || context.currentJournal()?.isAborted()) {
385
+ throw new CoreMindError("aborted", "控制恢复完成前运行已取消");
386
+ }
387
+ },
388
+ beforeModelRequest: () => {
389
+ signal?.throwIfAborted();
390
+ originalHarness?.beforeModelRequest?.();
391
+ },
392
+ onObservation: (observation) => originalHarness?.onObservation?.(observation.type === "control_consumed"
393
+ ? { ...observation, turnId: turnTracker.ensureCurrentTurn(name) }
394
+ : observation),
395
+ };
293
396
  const agent = buildDriver({
294
397
  onEvent: (event) => onEvent(turnTracker.withTurnId(event)),
295
398
  // 恢复视图只注入主 agent(会话归属者)
296
- sessionMessages: name === this.mainAgentName ? this.sessionMessages : undefined,
399
+ sessionMessages: name === this.mainAgentName
400
+ ? (context.initialSessionMessages() ?? this.sessionMessages)
401
+ : undefined,
297
402
  harness,
403
+ mcpTools,
404
+ skillTool: executionSlotFor(this).skillExecutions?.get(executionId)?.tool,
405
+ discoveryTool: originalHarness?.discoveryTool,
406
+ taskTool,
298
407
  });
299
408
  context.registerAgent(name, agent, executionId);
300
409
  return agent;
@@ -342,9 +451,10 @@ export class CoreMindRuntime {
342
451
  }
343
452
  /** 返回交互会话应继承的恢复消息副本。 */
344
453
  initialMessagesFor(name) {
345
- return (name === this.mainAgentName
346
- ? [...(this.sessionMessages ?? [])]
347
- : []);
454
+ const copied = copySessionHistory(executionSlotFor(this).sessionPreviewHistory ?? this.sessionMessages ?? []);
455
+ if (name !== this.mainAgentName)
456
+ copied.length = 0;
457
+ return copied;
348
458
  }
349
459
  /**
350
460
  * 把一轮交互对话作为完整 Run 执行。
@@ -354,7 +464,7 @@ export class CoreMindRuntime {
354
464
  if (this.config.loop?.verify.mode === "host") {
355
465
  throw new CoreMindError("loop_config_invalid", "宿主验收模式须通过 run() 与绑定该 Run 的控制接口执行");
356
466
  }
357
- if (executionSlotFor(this).running) {
467
+ if (executionSlotFor(this).running || executionSlotFor(this).navigatingSession) {
358
468
  throw new CoreMindError("concurrent_run", "同一 Runtime 不支持并发 run() 与交互 Turn");
359
469
  }
360
470
  if (!this.agentConfigs.has(agentName)) {
@@ -369,13 +479,31 @@ export class CoreMindRuntime {
369
479
  events,
370
480
  signal,
371
481
  }, history, history.length, this.skillsByAgent);
482
+ executionSlotFor(turnRuntime).skills = executionSlotFor(this).skills;
483
+ executionSlotFor(turnRuntime).explicitSessionHistory = history;
484
+ executionSlotFor(turnRuntime).expectedSessionSnapshot =
485
+ historySessionSnapshot(history) ??
486
+ (this.sessionMessages ? historySessionSnapshot(this.sessionMessages) : undefined);
372
487
  const unbindActiveRun = bindActiveRun(this, {
488
+ acceptInputControl: (command) => {
489
+ const context = executionSlotFor(turnRuntime).kernel?.currentContext();
490
+ const inbox = context?.currentControlInbox();
491
+ const runId = context?.currentRunId();
492
+ if (!inbox || !runId) {
493
+ return Promise.reject(new CoreMindError("control_unavailable", "活动 Run 的控制收件箱尚未就绪"));
494
+ }
495
+ return inbox.accept({ schemaVersion: 1, ...command, runId: command.runId ?? runId });
496
+ },
373
497
  inspectProjection: () => turnRuntime.inspectPersistedRunProjection(),
374
498
  executeDelegation: (parentAgentName, rawArgs, callId) => turnRuntime.executeConfiguredDelegation(parentAgentName, rawArgs, callId),
375
499
  executeDelegationDisposition: (parentAgentName, rawArgs, callId) => turnRuntime.executeConfiguredDelegationDisposition(parentAgentName, rawArgs, callId),
376
500
  });
377
501
  try {
378
- return await turnRuntime.run();
502
+ const result = await turnRuntime.run();
503
+ const preview = executionSlotFor(turnRuntime).sessionPreviewHistory;
504
+ if (preview)
505
+ executionSlotFor(this).sessionPreviewHistory = copySessionHistory(preview);
506
+ return result;
379
507
  }
380
508
  finally {
381
509
  unbindActiveRun();
@@ -401,11 +529,13 @@ export class CoreMindRuntime {
401
529
  /** 执行:有 workflow 走编排,否则单 agent 直答。返回结果含质量摘要 */
402
530
  async run() {
403
531
  const slot = executionSlotFor(this);
404
- if (slot.running || boundDelegationExecutor(this)) {
532
+ if (slot.running || slot.navigatingSession || boundDelegationExecutor(this)) {
405
533
  throw new CoreMindError("concurrent_run", "同一 Runtime 不支持并发执行");
406
534
  }
407
535
  slot.running = true;
408
- slot.kernel ??= new RunKernel({ execute: (context) => this.executeRunBody(context) });
536
+ slot.kernel ??= new RunKernel({
537
+ execute: (context) => executeWithSessionLease(this, this.options, this.config, context, (ownership) => this.executeRunBody(context, ownership)),
538
+ });
409
539
  try {
410
540
  return await slot.kernel.run();
411
541
  }
@@ -458,6 +588,8 @@ export class CoreMindRuntime {
458
588
  }),
459
589
  enforceRuntimeBudget: true,
460
590
  enforceDelegatedToolBoundary: true,
591
+ trustedSkillLoader: this.toolCapabilitiesByAgent.get(this.mainAgentName)?.get(SKILL_TOOL_NAME) ===
592
+ SKILL_TOOL_CAPABILITY,
461
593
  });
462
594
  }
463
595
  runtimeAuthorityToolIds() {
@@ -566,14 +698,15 @@ export class CoreMindRuntime {
566
698
  if (!target) {
567
699
  throw new CoreMindError("child_run_policy_escalation", `委派目标 Agent ${authority.request.agentName} 不存在`);
568
700
  }
569
- const { workflow: _workflow, loop: _loop, ...baseConfig } = this.config;
701
+ const { workflow: _workflow, loop: _loop, mcp: _mcp, ...baseConfig } = this.config;
570
702
  const childAgents = structuredClone(this.config.agents);
571
703
  for (const agent of Object.values(childAgents)) {
572
704
  if (agent.tools)
573
705
  agent.tools = agent.tools.filter(isDelegatedBuiltinToolConfig);
706
+ delete agent.mcpResources;
574
707
  }
575
708
  childAgents[authority.request.agentName] = {
576
- ...target,
709
+ ...childAgents[authority.request.agentName],
577
710
  ...(target.tools ? { tools: target.tools.filter(isDelegatedBuiltinToolConfig) } : {}),
578
711
  model: authority.request.model.model,
579
712
  options: authority.request.model.options,
@@ -606,11 +739,12 @@ export class CoreMindRuntime {
606
739
  events: this.options.events,
607
740
  trace: this.options.trace,
608
741
  approveTool: this.options.approveTool,
742
+ approveProjectCode: this.options.approveProjectCode,
609
743
  runStore,
610
744
  runId: authority.childRunId,
611
745
  childRunAuthority: authority,
612
746
  signal: authority.signal,
613
- }, this.workspaceLeaseService);
747
+ }, this.workspaceLeaseService, executionSlotFor(this).skills);
614
748
  },
615
749
  }),
616
750
  };
@@ -745,8 +879,16 @@ export class CoreMindRuntime {
745
879
  throw new CoreMindError("child_run_policy_escalation", `Agent ${parentAgentName} 未获准委派给 ${args.target}`);
746
880
  }
747
881
  const parentTools = new Set(this.toolCapabilitiesByAgent.get(parentAgentName)?.keys() ?? []);
882
+ const targetAgent = this.agentConfigs.get(args.target);
883
+ const configuredTools = (targetAgent?.tools?.length ?? 0) > 0 ? targetAgent.tools : (this.config.tools ?? []);
884
+ if (configuredTools.some((tool) => "mcp" in tool) || targetAgent?.mcpResources !== undefined) {
885
+ throw new CoreMindError("child_run_policy_escalation", "Child Run 不继承宿主本地服务、工具或凭据");
886
+ }
748
887
  const targetTools = [...(this.toolCapabilitiesByAgent.get(args.target)?.keys() ?? [])].filter((tool) => tool !== DELEGATION_TOOL_NAME && isDelegatedSafeToolName(tool));
749
- const expandedTools = targetTools.filter((tool) => !parentTools.has(tool));
888
+ const frozenSkillAuthority = needsFrozenSkillAuthority(this.config.agents, executionSlotFor(this).skills, args.target);
889
+ if (frozenSkillAuthority)
890
+ targetTools.push(SKILL_TOOL_NAME);
891
+ const expandedTools = targetTools.filter((tool) => !parentTools.has(tool) && !(frozenSkillAuthority && tool === SKILL_TOOL_NAME));
750
892
  if (expandedTools.length > 0) {
751
893
  throw new CoreMindError("child_run_policy_escalation", `Delegation Target ${args.target} 的工具超出父 Agent authority:${expandedTools.join("、")}`);
752
894
  }
@@ -758,7 +900,7 @@ export class CoreMindRuntime {
758
900
  };
759
901
  }
760
902
  /** run() 主体(并发检测由外层 run() 包装) */
761
- async executeRunBody(context) {
903
+ async executeRunBody(context, ownership) {
762
904
  context.attachExecutionEnvironment(this.executionEnvironment);
763
905
  const started = performance.now();
764
906
  const lifecycleHost = this.options.lifecycleExtensions
@@ -776,20 +918,39 @@ export class CoreMindRuntime {
776
918
  let canonicalSessionBranch = [];
777
919
  let previousContextCompactions = [];
778
920
  if (this.options.sessionId && this.config.session?.enabled) {
779
- const session = await CoreMindSession.open({
921
+ const session = await openWritableSession({
780
922
  dir: sessionDir(this.config, this.options.configDir),
781
923
  sessionId: this.options.sessionId,
782
924
  cwd: this.options.cwd ?? process.cwd(),
783
- });
925
+ }, ownership.lease);
784
926
  const sessionEntries = await session.branchEntries();
785
927
  sessionSeqStart = sessionEntries.reduce((max, entry) => Math.max(max, entry.seq), 0);
786
- context.attachSession(session, projectBranchMessages(sessionEntries));
928
+ const slot = executionSlotFor(this);
929
+ if (slot.explicitSessionHistory !== undefined &&
930
+ slot.expectedSessionSnapshot !== sessionSnapshot(session)) {
931
+ throw new CoreMindError("session_snapshot_stale", "会话已被其他运行修改,请重新打开交互历史");
932
+ }
933
+ const branch = projectBranchMessages(sessionEntries);
934
+ context.attachSession(session, branch, slot.explicitSessionHistory ?? branch.map((item) => item.message));
787
935
  canonicalSessionBranch = projectRawBranchMessages(sessionEntries);
788
936
  previousContextCompactions = projectContextCompactionLedger(sessionEntries);
789
937
  }
790
938
  const resumeRecords = this.options.resumeRunId
791
939
  ? await runStore.read(this.options.resumeRunId)
792
940
  : undefined;
941
+ const taskProgram = executionSlotFor(this).taskProgram;
942
+ const storedProgram = resumeRecords?.find((record) => record.kind === "start")?.payload?.taskProgram;
943
+ if (resumeRecords && storedProgram !== taskProgram?.id)
944
+ throw new CoreMindError("resume_config_mismatch", "任务调用 Run 必须由原任务作用域恢复");
945
+ const skillSnapshot = executionSlotFor(this).skills;
946
+ if (resumeRecords &&
947
+ restoreSkillSnapshot(resumeRecords, this.config.agents)?.sha256 !== skillSnapshot?.sha256) {
948
+ throw new CoreMindError("context_capability_conflict", "原技能快照在恢复准入前已变化");
949
+ }
950
+ executionSlotFor(this).skillExecutions = skillSnapshot ? new Map() : undefined;
951
+ const skillFactDurability = runStore.supportedDurability?.includes("critical")
952
+ ? "critical"
953
+ : "ordinary";
793
954
  let deferredTerminalError = restoreDeferredTerminalError(resumeRecords);
794
955
  const canRestoreChildRuns = this.options.childRuns !== undefined ||
795
956
  [...this.agentConfigs.values()].some((agent) => agent.delegation && Object.keys(agent.delegation.targets).length > 0);
@@ -811,6 +972,16 @@ export class CoreMindRuntime {
811
972
  }
812
973
  // 预生成 runId(D-1):resume 时以恢复记录为准,否则优先使用调用方预生成值
813
974
  const runId = (resumePlan?.runId ?? this.options.runId ?? randomUUID());
975
+ const admission = resumeRecords?.at(-1);
976
+ // 当前 Worker 的明确 resume 准入不取代它刚验证过的暂停绑定。
977
+ const discoveryResumeRecords = admission?.kind === "admission" &&
978
+ this.options.protocolStart?.method === "resume" &&
979
+ fingerprintEffectReceiptValue(admission.payload.protocolStart) === fingerprintEffectReceiptValue(this.options.protocolStart)
980
+ ? resumeRecords.slice(0, -1)
981
+ : (resumeRecords ?? []);
982
+ const discoveryContinuations = restoreToolDiscoveryContinuations(discoveryResumeRecords, runId);
983
+ const consumedDiscoveryContinuations = new Set();
984
+ const liveDiscoveryExecutions = new Map();
814
985
  context.attachRunId(runId);
815
986
  const effectiveInitialPrompt = resumePlan?.initialPrompt ?? this.options.initialPrompt;
816
987
  const admissionRecords = !resumePlan && this.options.protocolStart ? await runStore.read(runId) : [];
@@ -852,11 +1023,12 @@ export class CoreMindRuntime {
852
1023
  });
853
1024
  }
854
1025
  else {
855
- await journal.start({
1026
+ await journal.appendFact("start", {
856
1027
  configName: this.config.name,
857
1028
  schemaVersion: this.config.schemaVersion,
858
1029
  configFingerprint,
859
1030
  initialPrompt: this.options.initialPrompt,
1031
+ ...(taskProgram ? { taskProgram: taskProgram.id } : {}),
860
1032
  sessionId: this.options.sessionId,
861
1033
  ...(sessionSeqStart !== undefined
862
1034
  ? { sessionSeqStart, turnSeqStart: sessionSeqStart }
@@ -864,7 +1036,8 @@ export class CoreMindRuntime {
864
1036
  operationId: operation.snapshot().operationId,
865
1037
  telemetry: telemetryConfiguration,
866
1038
  ...(this.options.protocolStart ? { protocolStart: this.options.protocolStart } : {}),
867
- });
1039
+ ...(skillSnapshot ? { skillSnapshot } : {}),
1040
+ }, { durability: skillSnapshot ? skillFactDurability : "ordinary" });
868
1041
  }
869
1042
  for (const consent of telemetryConsents) {
870
1043
  validateTelemetryConsentBinding(consent, await runStore.read(runId));
@@ -900,40 +1073,58 @@ export class CoreMindRuntime {
900
1073
  applyPending: () => context.currentControlInbox().applyPending("verification"),
901
1074
  })
902
1075
  : undefined;
903
- context.attachControlInbox(new ControlInbox({
904
- runId,
905
- journal,
906
- records: await runStore.read(runId),
907
- apply: (command) => {
908
- if (command.type === "verification") {
909
- return Promise.resolve(hostVerification?.apply(command) ?? {
910
- status: "rejected",
911
- reason: "当前 Run 未启用宿主验证",
912
- });
913
- }
914
- if (hostVerification?.waiting &&
915
- (command.type === "steering" || command.type === "follow_up")) {
916
- return Promise.resolve({ status: "rejected", reason: "宿主验收期间不能改变候选输入" });
917
- }
918
- return this.applyRunControl(command, context, deferredTerminalError);
919
- },
920
- }));
921
1076
  const capabilityByCallId = new Map();
1077
+ const skillLoadsByCall = new Map();
1078
+ const discoverySearchesByCall = new Map();
1079
+ const discoveryGenerations = new Map();
1080
+ const userEvents = this.options.events ?? (() => { });
922
1081
  const trace = new TraceRecorder(runId, (entry) => {
923
1082
  const toolResultCallId = entry.event.type === "tool_result" ? entry.event.callId : undefined;
924
1083
  const pendingProtocolToolResult = toolResultCallId
925
1084
  ? executionSlotFor(this).protocolToolResultFacts?.get(protocolToolResultKey(entry.runId, toolResultCallId))
926
1085
  : undefined;
927
- const payload = pendingProtocolToolResult
928
- ? {
929
- ...entry,
930
- protocolToolResult: structuredClone(pendingProtocolToolResult.fact),
931
- }
932
- : entry;
1086
+ const skillCallKey = toolResultCallId && entry.event.type === "tool_result"
1087
+ ? toolCapabilityCallKey(entry.event.agent, entry.event.stepId, toolResultCallId)
1088
+ : undefined;
1089
+ const skillLoad = skillCallKey ? skillLoadsByCall.get(skillCallKey) : undefined;
1090
+ const discoverySearch = skillCallKey
1091
+ ? discoverySearchesByCall.get(skillCallKey)
1092
+ : undefined;
1093
+ const discoveryGeneration = entry.event.type === "context_prefix" && entry.event.toolDiscovery
1094
+ ? discoveryGenerations.get(entry.event.toolDiscovery.selectionFingerprint)
1095
+ : undefined;
1096
+ const payload = {
1097
+ ...entry,
1098
+ ...(pendingProtocolToolResult
1099
+ ? { protocolToolResult: structuredClone(pendingProtocolToolResult.fact) }
1100
+ : {}),
1101
+ ...(skillLoad ? { skillLoad } : {}),
1102
+ ...(discoverySearch ? { toolDiscoverySearch: discoverySearch.fact } : {}),
1103
+ ...(discoveryGeneration
1104
+ ? {
1105
+ ...(discoveryGeneration.prepared.catalog
1106
+ ? { toolDiscoveryCatalog: discoveryGeneration.prepared.catalog }
1107
+ : {}),
1108
+ toolDiscoverySelection: discoveryGeneration.prepared.selection,
1109
+ }
1110
+ : {}),
1111
+ };
1112
+ if (skillCallKey)
1113
+ skillLoadsByCall.delete(skillCallKey);
933
1114
  const persisted = journal.appendFact("event", payload, {
934
- durability: traceFactDurability(entry.event, capabilityByCallId),
1115
+ durability: discoverySearch || discoveryGeneration
1116
+ ? "critical"
1117
+ : skillLoad
1118
+ ? skillFactDurability
1119
+ : traceFactDurability(entry.event, capabilityByCallId),
935
1120
  eventId: entry.eventId,
936
1121
  });
1122
+ if (discoveryGeneration)
1123
+ discoveryGeneration.receipt = persisted;
1124
+ if (discoverySearch) {
1125
+ discoverySearchesByCall.delete(skillCallKey);
1126
+ void persisted.then(() => discoverySearch.durable.push(discoverySearch.fact), () => { });
1127
+ }
937
1128
  if (pendingProtocolToolResult) {
938
1129
  pendingProtocolToolResult.appendStarted = true;
939
1130
  void persisted
@@ -945,11 +1136,14 @@ export class CoreMindRuntime {
945
1136
  facts.delete(key);
946
1137
  });
947
1138
  }
948
- this.options.trace?.(entry);
1139
+ this.options.trace?.(structuredClone(entry));
1140
+ const callbackEntry = structuredClone(entry);
1141
+ userEvents(callbackEntry.event, callbackEntry);
949
1142
  }, resumePlan?.previousTrace);
950
1143
  const collected = resumePlan?.previousTrace.map((entry) => entry.event) ?? [];
1144
+ // 历史拒绝保留审计与预算,但不决定本次恢复执行的终态。
1145
+ const terminalEventCursor = collected.length;
951
1146
  const toolReplayCandidates = [...(resumePlan?.toolReplayCandidates ?? [])];
952
- const userEvents = this.options.events ?? (() => { });
953
1147
  const turnTracker = new TurnTracker();
954
1148
  const effectBindingByCall = new Map();
955
1149
  const effectBindingByReceipt = new Map();
@@ -963,15 +1157,82 @@ export class CoreMindRuntime {
963
1157
  const existingInputState = inputId === undefined ? undefined : receiptStatusOf(collected, inputId);
964
1158
  let inputReceiptState = existingInputState ?? (inputId === undefined ? undefined : "pending");
965
1159
  let onToolResultRecorded;
966
- const lifecycleFinalizers = new Set();
1160
+ const lifecycleFinalizers = new Map();
1161
+ const immediateToolRejections = new Map();
1162
+ const mcpAuthorizations = new Map();
1163
+ const bindMcpArguments = (agent, tool, args) => {
1164
+ const authorization = mcpAuthorizations.get(JSON.stringify([agent, tool]));
1165
+ return authorization ? { mcp: authorization, arguments: args } : args;
1166
+ };
967
1167
  let lifecycleFailure;
968
1168
  const emitInputEvent = (event) => {
969
1169
  collected.push(event);
970
1170
  trace.record(event);
971
- userEvents(event);
972
1171
  };
1172
+ const prepareControlInput = (command) => {
1173
+ const id = controlInputId(runId, command.controlId);
1174
+ if (receiptStatusOf(collected, id) === undefined) {
1175
+ emitInputEvent(createInputReceipt({
1176
+ inputId: id,
1177
+ contentFingerprint: inputFingerprint(command.message),
1178
+ }));
1179
+ }
1180
+ return id;
1181
+ };
1182
+ context.attachControlInbox(new ControlInbox({
1183
+ runId,
1184
+ journal,
1185
+ records: await runStore.read(runId),
1186
+ apply: (command) => {
1187
+ if (command.type === "verification") {
1188
+ return Promise.resolve(hostVerification?.apply(command) ?? {
1189
+ status: "rejected",
1190
+ reason: "当前 Run 未启用宿主验证",
1191
+ });
1192
+ }
1193
+ if (command.type === "steering" || command.type === "follow_up") {
1194
+ const id = prepareControlInput(command);
1195
+ if (hostVerification?.waiting) {
1196
+ const state = receiptStatusOf(collected, id);
1197
+ if (state === "pending" || state === "claimed")
1198
+ emitInputEvent(discardInput({ inputId: id }));
1199
+ return Promise.resolve({
1200
+ status: "rejected",
1201
+ reason: "宿主验收期间不能改变候选输入",
1202
+ });
1203
+ }
1204
+ }
1205
+ return this.applyRunControl(command, context, deferredTerminalError);
1206
+ },
1207
+ }));
1208
+ // applied 与内存交付间可能中断;没有消费事实时只明确丢弃,不能自动重投。
1209
+ const previousInputControls = new Map();
1210
+ const previouslyApplied = new Set();
1211
+ for (const record of resumeRecords ?? []) {
1212
+ if (record.kind !== "control")
1213
+ continue;
1214
+ const fact = record.payload;
1215
+ if (fact.command?.type === "steering" || fact.command?.type === "follow_up")
1216
+ previousInputControls.set(fact.controlId, fact.command);
1217
+ if (fact.state === "applied")
1218
+ previouslyApplied.add(fact.controlId);
1219
+ }
1220
+ for (const id of previouslyApplied) {
1221
+ const command = previousInputControls.get(id);
1222
+ if (!command)
1223
+ continue;
1224
+ const input = prepareControlInput(command);
1225
+ if (receiptStatusOf(collected, input) === "pending")
1226
+ emitInputEvent(discardInput({ inputId: input }));
1227
+ }
973
1228
  const recordEvent = (event) => {
974
1229
  let enriched = turnTracker.withTurnId(event);
1230
+ if (enriched.type === "tool_call") {
1231
+ enriched = {
1232
+ ...enriched,
1233
+ args: bindMcpArguments(enriched.agent, enriched.tool, enriched.args),
1234
+ };
1235
+ }
975
1236
  if ((enriched.type === "tool_result" || enriched.type === "tool_lifecycle") &&
976
1237
  enriched.callId) {
977
1238
  const call = effectBindingByCall.get(toolCapabilityCallKey(enriched.agent, enriched.stepId, enriched.callId));
@@ -979,6 +1240,17 @@ export class CoreMindRuntime {
979
1240
  enriched = { ...enriched, turnId: call.turnId };
980
1241
  }
981
1242
  if (enriched.type === "tool_call" && enriched.callId && enriched.turnId) {
1243
+ const callKey = toolCapabilityCallKey(enriched.agent, enriched.stepId, enriched.callId);
1244
+ if (effectBindingByCall.has(callKey) ||
1245
+ resumePlan?.previousTrace.some(({ event: previous }) => previous.type === "tool_call" &&
1246
+ previous.callId !== undefined &&
1247
+ toolCapabilityCallKey(previous.agent, previous.stepId, previous.callId) === callKey)) {
1248
+ // 不覆盖首次冻结事实;取消分界后的重复输入保持原取消语义。
1249
+ lifecycleFailure = journal.isAborted()
1250
+ ? new CoreMindError("aborted", "运行已中止,拒绝重复工具调用")
1251
+ : new CoreMindError("effect_receipt_conflict", "工具 Call 身份重复,已拒绝后续调用");
1252
+ throw lifecycleFailure;
1253
+ }
982
1254
  context.recordToolCall({
983
1255
  agent: enriched.agent,
984
1256
  callId: enriched.callId,
@@ -1029,8 +1301,9 @@ export class CoreMindRuntime {
1029
1301
  throw new CoreMindError("redaction_failed", "步骤输出包含凭据,已阻止持久化与候选验收");
1030
1302
  }
1031
1303
  collected.push(enriched);
1032
- trace.record(enriched);
1033
- userEvents(enriched);
1304
+ trace.record(enriched, enriched.type === "context_prefix" && enriched.toolDiscovery
1305
+ ? discoveryGenerations.get(enriched.toolDiscovery.selectionFingerprint)?.prepared.eventId
1306
+ : undefined);
1034
1307
  if (enriched.type === "tool_result")
1035
1308
  onToolResultRecorded?.(enriched);
1036
1309
  // 输入被首个 Turn 认领(规格 03 §4:claim 绑定 TurnId;resume 时已 claimed 不再重复);
@@ -1057,6 +1330,12 @@ export class CoreMindRuntime {
1057
1330
  });
1058
1331
  const workspaceLeaseService = this.workspaceLeaseService;
1059
1332
  const workspaceLeaseByCall = new Map();
1333
+ // 原生文件 Store 的租约关键 Fact 已同步完整前缀;自定义实现仍保留全局屏障。
1334
+ const leaseFlushDurability = Object.getPrototypeOf(runStore) === FileRunStore.prototype &&
1335
+ runStore.commit === FileRunStore.prototype.commit &&
1336
+ runStore.barrier === FileRunStore.prototype.barrier
1337
+ ? "ordinary"
1338
+ : "critical";
1060
1339
  const releaseWorkspaceLease = async (identity) => {
1061
1340
  const callKey = toolCapabilityCallKey(identity.agent, identity.stepId, identity.callId);
1062
1341
  const held = workspaceLeaseByCall.get(callKey);
@@ -1085,7 +1364,7 @@ export class CoreMindRuntime {
1085
1364
  callId: identity.callId,
1086
1365
  ...(identity.stepId ? { stepId: identity.stepId } : {}),
1087
1366
  });
1088
- await journal.flush("critical");
1367
+ await journal.flush(leaseFlushDurability);
1089
1368
  };
1090
1369
  const rollbackWorkspaceLease = async (identity) => {
1091
1370
  const callKey = toolCapabilityCallKey(identity.agent, identity.stepId, identity.callId);
@@ -1108,41 +1387,45 @@ export class CoreMindRuntime {
1108
1387
  callId: identity.callId,
1109
1388
  ...(identity.stepId ? { stepId: identity.stepId } : {}),
1110
1389
  });
1111
- await journal.flush("critical");
1390
+ await journal.flush(leaseFlushDurability);
1112
1391
  };
1113
1392
  onToolResultRecorded = (event) => {
1114
1393
  const recorded = toolExecutionEngine.inspect({
1115
1394
  ...toolCallIdentity(event.agent, event.stepId, event.callId),
1116
1395
  });
1117
- if (!recorded || recorded.tool !== event.tool)
1396
+ const identity = toolCallIdentity(event.agent, event.stepId, event.callId);
1397
+ const callKey = toolCapabilityCallKey(event.agent, event.stepId, event.callId);
1398
+ if ((!recorded || recorded.tool !== event.tool) && !immediateToolRejections.has(callKey))
1118
1399
  return;
1119
- queueMicrotask(() => {
1120
- const identity = toolCallIdentity(event.agent, event.stepId, event.callId);
1121
- const finalizer = (async () => {
1122
- try {
1123
- await journal.flush();
1124
- await toolExecutionEngine.finalizeResult(identity);
1125
- await releaseWorkspaceLease(identity);
1126
- }
1127
- catch (error) {
1128
- const failure = error instanceof CoreMindError
1129
- ? error
1130
- : new CoreMindError("durability_barrier_failed", error instanceof Error ? error.message : String(error));
1131
- if (toolExecutionEngine.inspect(identity)?.currentPhase === "observed") {
1132
- await toolExecutionEngine.failResultDurability(identity, failure.message);
1133
- }
1134
- throw failure;
1400
+ // 仍在结果事件之后的微任务提交;宿主准备只等待同一个 Call 的结果屏障。
1401
+ const finalizer = Promise.resolve().then(async () => {
1402
+ try {
1403
+ await immediateToolRejections.get(callKey);
1404
+ await journal.flush();
1405
+ await toolExecutionEngine.finalizeResult(identity);
1406
+ await releaseWorkspaceLease(identity);
1407
+ }
1408
+ catch (error) {
1409
+ const failure = error instanceof CoreMindError
1410
+ ? error
1411
+ : new CoreMindError("durability_barrier_failed", error instanceof Error ? error.message : String(error));
1412
+ if (toolExecutionEngine.inspect(identity)?.currentPhase === "observed") {
1413
+ await toolExecutionEngine.failResultDurability(identity, failure.message);
1135
1414
  }
1136
- })();
1137
- lifecycleFinalizers.add(finalizer);
1138
- void finalizer
1139
- .catch((error) => {
1140
- lifecycleFailure =
1141
- error instanceof CoreMindError
1142
- ? error
1143
- : new CoreMindError("tool_lifecycle_invalid", error instanceof Error ? error.message : String(error));
1144
- })
1145
- .finally(() => lifecycleFinalizers.delete(finalizer));
1415
+ throw failure;
1416
+ }
1417
+ });
1418
+ lifecycleFinalizers.set(callKey, finalizer);
1419
+ void finalizer
1420
+ .catch((error) => {
1421
+ lifecycleFailure =
1422
+ error instanceof CoreMindError
1423
+ ? error
1424
+ : new CoreMindError("tool_lifecycle_invalid", error instanceof Error ? error.message : String(error));
1425
+ })
1426
+ .finally(() => {
1427
+ if (lifecycleFinalizers.get(callKey) === finalizer)
1428
+ lifecycleFinalizers.delete(callKey);
1146
1429
  });
1147
1430
  };
1148
1431
  const dispatchLifecycle = async (lifecycle, payload) => {
@@ -1238,6 +1521,19 @@ export class CoreMindRuntime {
1238
1521
  if (gate?.status === "propagate_terminal")
1239
1522
  throw propagatedChildRunError(gate.result);
1240
1523
  };
1524
+ const mcpRun = this.config.mcp
1525
+ ? createMcpRun({
1526
+ config: this.config,
1527
+ configDir: this.options.configDir,
1528
+ cwd: this.options.cwd ?? process.cwd(),
1529
+ env: this.options.toolEnv ?? this.options.env ?? process.env,
1530
+ secretResolver: this.options.secretResolver,
1531
+ mcpAuthentication: this.options.mcpAuthentication,
1532
+ environment: this.executionEnvironment,
1533
+ signal: this.options.signal,
1534
+ artifactStore: new ArtifactStore({ cwd: this.options.cwd ?? process.cwd() }),
1535
+ })
1536
+ : undefined;
1241
1537
  const persistContextCompaction = async (preparation, sourceMessages, originalMessageCount) => {
1242
1538
  const compaction = preparation.compaction;
1243
1539
  if (!compaction)
@@ -1285,6 +1581,29 @@ export class CoreMindRuntime {
1285
1581
  const policy = new ToolPolicy({
1286
1582
  permissions: this.config.permissions,
1287
1583
  allowedPaths: this.options.childRunAuthority?.inheritedPolicy.permissions.paths,
1584
+ protectedPaths: [
1585
+ path.resolve(this.options.configDir, ".coremind", "runs"),
1586
+ path.resolve(this.options.configDir, ".coremind", "tasks"),
1587
+ path.resolve(this.options.cwd ?? process.cwd(), ".coremind", "tasks"),
1588
+ path.resolve(this.options.configDir, ".coremind", "checkpoints"),
1589
+ path.resolve(this.options.configDir, ".coremind", "quality-overrides.jsonl"),
1590
+ path.resolve(this.options.cwd ?? process.cwd(), ".coremind", "quality-overrides.jsonl"),
1591
+ path.resolve(this.options.cwd ?? process.cwd(), ".coremind", "artifacts"),
1592
+ path.resolve(this.options.cwd ?? process.cwd(), ".coremind", "leases"),
1593
+ ...(runStore instanceof FileRunStore
1594
+ ? [{ path: path.resolve(runStore.directory), contains: isManagedRunPath }]
1595
+ : runStore.pathFor
1596
+ ? [path.resolve(runStore.pathFor(runId))]
1597
+ : []),
1598
+ ...(this.config.session?.enabled
1599
+ ? [
1600
+ {
1601
+ path: sessionDir(this.config, this.options.configDir),
1602
+ contains: isManagedSessionPath,
1603
+ },
1604
+ ]
1605
+ : []),
1606
+ ],
1288
1607
  cwd: this.options.cwd ?? process.cwd(),
1289
1608
  runId: trace.runId,
1290
1609
  approve: this.options.approveTool,
@@ -1297,6 +1616,8 @@ export class CoreMindRuntime {
1297
1616
  approvalId: request.approvalId,
1298
1617
  runId: request.runId,
1299
1618
  agent: request.agent,
1619
+ ...(request.callId === undefined ? {} : { callId: request.callId }),
1620
+ ...(request.stepId === undefined ? {} : { stepId: request.stepId }),
1300
1621
  tool: request.tool,
1301
1622
  args: request.args,
1302
1623
  argumentsFingerprint: request.argumentsFingerprint,
@@ -1316,17 +1637,67 @@ export class CoreMindRuntime {
1316
1637
  });
1317
1638
  const deniedAgents = new Set();
1318
1639
  const activeRunContext = context;
1640
+ let modelRequestsOpen = true;
1319
1641
  context.setHarnessFactory((agentName, stepId, executionId) => {
1320
1642
  const agentModel = this.agentModels.get(agentName) ?? this.providerRuntime.model;
1643
+ const skillExecution = skillSnapshot?.agents[agentName]?.standard.length
1644
+ ? new SkillExecution(skillSnapshot, agentName, resumeRecords, stepId)
1645
+ : undefined;
1646
+ if (skillExecution)
1647
+ executionSlotFor(this).skillExecutions.set(executionId, skillExecution);
1321
1648
  let contextWorkingSet;
1322
1649
  let providerRequestOrdinal = 0;
1323
1650
  let pendingProviderCapabilityFingerprint;
1324
- return {
1651
+ const executionEffects = new Map(this.toolEffectsByAgent.get(agentName));
1652
+ const executionCapabilities = new Map(this.toolCapabilitiesByAgent.get(agentName));
1653
+ const effectiveTools = this.agentConfigs.get(agentName)?.tools?.length
1654
+ ? this.agentConfigs.get(agentName).tools
1655
+ : (this.config.tools ?? []);
1656
+ const discoveryEnabled = effectiveTools.some((tool) => tool.exposure === "deferred");
1657
+ if (discoveryEnabled && !runStore.supportedDurability?.includes("critical")) {
1658
+ throw new CoreMindError("durability_unsupported", "工具发现需要支持 critical 确认的 RunStore");
1659
+ }
1660
+ let discovery;
1661
+ let initialDiscovery;
1662
+ const durableSearches = [];
1663
+ const discoveryBindings = new Map();
1664
+ const toolSources = new Map();
1665
+ const withdrawnSources = new Set();
1666
+ const adapterSelection = (selection) => Object.freeze({
1667
+ names: [...selection.names, DISCOVER_TOOLS_NAME],
1668
+ generation: selection.generation,
1669
+ fingerprint: selection.fingerprint,
1670
+ });
1671
+ const discoverySummary = (selection) => ({
1672
+ version: 1,
1673
+ catalogFingerprint: selection.catalogFingerprint,
1674
+ generation: selection.generation,
1675
+ selectionFingerprint: selection.fingerprint,
1676
+ toolCount: selection.names.length + 1,
1677
+ });
1678
+ const checkDiscoveryCall = (tool, callId) => {
1679
+ if (!discovery || tool === DISCOVER_TOOLS_NAME)
1680
+ return;
1681
+ const binding = discovery.assertCallable(tool, discoveryBindings.get(callId));
1682
+ discoveryBindings.set(callId, binding);
1683
+ };
1684
+ const harness = {
1325
1685
  maxRetries: loop ? 0 : limits.maxRetries,
1326
1686
  registerContextContract: (contract) => contextContracts.set(executionId, contract),
1327
1687
  beforeModelRequest: () => {
1688
+ const facts = journal.factStatus();
1689
+ if (facts.state === "poisoned") {
1690
+ throw new CoreMindError("fact_ledger_poisoned", `事实账本已失效,不能继续模型请求:${facts.reason}`);
1691
+ }
1692
+ if (!modelRequestsOpen || facts.terminal) {
1693
+ throw new CoreMindError("run_already_finished", "Run 已封闭,不能继续模型请求");
1694
+ }
1695
+ if (journal.isAborted())
1696
+ throw new CoreMindError("aborted", "Run 已取消,不能继续模型请求");
1328
1697
  throwIfContextFailed();
1329
1698
  throwIfDelegationBlocksModel();
1699
+ for (const name of discovery?.current?.names ?? [])
1700
+ discovery.assertCallable(name);
1330
1701
  budget.beforeModelRequest();
1331
1702
  },
1332
1703
  onModelRequestDispatched: ({ providerId, modelId, messages }) => {
@@ -1339,8 +1710,11 @@ export class CoreMindRuntime {
1339
1710
  type: "provider_request",
1340
1711
  agent: agentName,
1341
1712
  ...(stepId ? { stepId } : {}),
1713
+ ...(discovery?.current ? { toolDiscovery: discoverySummary(discovery.current) } : {}),
1342
1714
  ...createProviderRequestReplayFact({
1343
- requestId: `${agentName}:${stepId ?? "default"}:${providerRequestOrdinal}`,
1715
+ requestId: discovery
1716
+ ? `${discovery.catalog.owner.executionId}:${providerRequestOrdinal}`
1717
+ : `${agentName}:${stepId ?? "default"}:${providerRequestOrdinal}`,
1344
1718
  providerId,
1345
1719
  modelId,
1346
1720
  messages,
@@ -1354,7 +1728,10 @@ export class CoreMindRuntime {
1354
1728
  throwIfContextFailed,
1355
1729
  executeTool: async ({ call, invoke }) => {
1356
1730
  try {
1357
- return await toolExecutionEngine.executeAdapter(toolCallIdentity(agentName, stepId, call.callId), invoke);
1731
+ return await toolExecutionEngine.executeAdapter(toolCallIdentity(agentName, stepId, call.callId), () => {
1732
+ checkDiscoveryCall(call.tool, call.callId);
1733
+ return invoke();
1734
+ });
1358
1735
  }
1359
1736
  catch (error) {
1360
1737
  const normalized = normalizeExecutionError(error);
@@ -1368,7 +1745,7 @@ export class CoreMindRuntime {
1368
1745
  if (contextFailure)
1369
1746
  return messages;
1370
1747
  while (lifecycleFinalizers.size > 0) {
1371
- await Promise.allSettled([...lifecycleFinalizers]);
1748
+ await Promise.allSettled([...lifecycleFinalizers.values()]);
1372
1749
  }
1373
1750
  if (lifecycleFailure)
1374
1751
  throw lifecycleFailure;
@@ -1390,7 +1767,9 @@ export class CoreMindRuntime {
1390
1767
  const canonicalMessages = context.sessionHandle()
1391
1768
  ? [
1392
1769
  ...canonicalSessionBranch.map((item) => item.message),
1393
- ...messages.slice(context.compactedPrefixEnd() ?? this.resumedContextLength),
1770
+ ...messages.slice(context.compactedPrefixEnd() ??
1771
+ context.initialSessionLength() ??
1772
+ this.resumedContextLength),
1394
1773
  ]
1395
1774
  : messages;
1396
1775
  const taskState = projectContextTaskState({
@@ -1463,6 +1842,7 @@ export class CoreMindRuntime {
1463
1842
  sourceLength: messages.length,
1464
1843
  messages: [...preparation.workingSet.messages],
1465
1844
  };
1845
+ skillExecution?.refresh(preparation.workingSet.messages);
1466
1846
  pendingProviderCapabilityFingerprint = preparation.capability.configFingerprint;
1467
1847
  if (preparation.compaction) {
1468
1848
  emit({
@@ -1490,9 +1870,17 @@ export class CoreMindRuntime {
1490
1870
  return messages;
1491
1871
  }
1492
1872
  },
1493
- beforeToolCall: async (context, signal) => {
1873
+ beforeToolCall: async (driverContext, signal) => {
1874
+ const context = {
1875
+ ...driverContext,
1876
+ toolCall: {
1877
+ ...driverContext.toolCall,
1878
+ args: bindMcpArguments(agentName, driverContext.toolCall.tool, driverContext.toolCall.args),
1879
+ },
1880
+ };
1494
1881
  const lifecycleIdentity = toolCallIdentity(agentName, stepId, context.toolCall.callId);
1495
1882
  const callKey = toolCapabilityCallKey(agentName, stepId, context.toolCall.callId);
1883
+ checkDiscoveryCall(context.toolCall.tool, context.toolCall.callId);
1496
1884
  const argumentsFingerprint = fingerprintEffectReceiptValue(context.toolCall.args);
1497
1885
  const replayCandidateIndex = toolReplayCandidates.findIndex((candidate) => candidate.agent === agentName &&
1498
1886
  candidate.stepId === stepId &&
@@ -1527,7 +1915,7 @@ export class CoreMindRuntime {
1527
1915
  let capability = existingCapability?.capability;
1528
1916
  if (!existingCapability) {
1529
1917
  capability =
1530
- this.toolCapabilitiesByAgent.get(agentName)?.get(context.toolCall.tool) ??
1918
+ executionCapabilities.get(context.toolCall.tool) ??
1531
1919
  resolveToolCapability({ tool: context.toolCall.tool });
1532
1920
  capabilityByCallId.set(callKey, {
1533
1921
  tool: context.toolCall.tool,
@@ -1635,7 +2023,8 @@ export class CoreMindRuntime {
1635
2023
  return { block: true, reason: delegationPolicyFailure.message, terminate: true };
1636
2024
  }
1637
2025
  }
1638
- const decision = await policy.authorize(agentName, context.toolCall.tool, authorizationArgs, resolvedCapability, this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.tool), delegationInputFingerprint);
2026
+ const decision = await policy.authorize(agentName, context.toolCall.tool, authorizationArgs, resolvedCapability, executionEffects.get(context.toolCall.tool), delegationInputFingerprint, { callId: context.toolCall.callId, ...(stepId ? { stepId } : {}), signal });
2027
+ signal?.throwIfAborted();
1639
2028
  await toolExecutionEngine.advance(lifecycleIdentity, {
1640
2029
  phase: "policy_resolved",
1641
2030
  status: "completed",
@@ -1722,7 +2111,7 @@ export class CoreMindRuntime {
1722
2111
  await toolExecutionEngine.advance(lifecycleIdentity, {
1723
2112
  phase: "lease_acquired",
1724
2113
  status: "skipped",
1725
- reason: "Pure Local Read 不需要 Workspace Lease",
2114
+ reason: "该工具声明允许并行执行,不需要 Workspace Lease",
1726
2115
  });
1727
2116
  }
1728
2117
  else {
@@ -1750,7 +2139,7 @@ export class CoreMindRuntime {
1750
2139
  callId: context.toolCall.callId,
1751
2140
  ...(stepId ? { stepId } : {}),
1752
2141
  });
1753
- await journal.flush("critical");
2142
+ await journal.flush(leaseFlushDurability);
1754
2143
  await toolExecutionEngine.advance(lifecycleIdentity, {
1755
2144
  phase: "lease_acquired",
1756
2145
  status: "completed",
@@ -1803,8 +2192,7 @@ export class CoreMindRuntime {
1803
2192
  toolCallId: context.toolCall.callId,
1804
2193
  idempotencyKey,
1805
2194
  capability: resolvedCapability,
1806
- pathFields: this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.tool)
1807
- ?.pathFields,
2195
+ pathFields: executionEffects.get(context.toolCall.tool)?.pathFields,
1808
2196
  });
1809
2197
  if (checkpoints.length > 0) {
1810
2198
  checkpointByCallId.set(callKey, checkpoints.map((checkpoint) => checkpoint.checkpointId));
@@ -1849,6 +2237,15 @@ export class CoreMindRuntime {
1849
2237
  await rollbackWorkspaceLease(lifecycleIdentity);
1850
2238
  return { block: true, reason: checkpointFailure.message };
1851
2239
  }
2240
+ try {
2241
+ checkDiscoveryCall(context.toolCall.tool, context.toolCall.callId);
2242
+ }
2243
+ catch (error) {
2244
+ capabilityFailure = normalizeExecutionError(error);
2245
+ await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, capabilityFailure.message);
2246
+ await rollbackWorkspaceLease(lifecycleIdentity);
2247
+ return { block: true, reason: capabilityFailure.message };
2248
+ }
1852
2249
  effectCoordinator.markStarted(stepId, context.toolCall.callId, context.toolCall.tool);
1853
2250
  if (resolvedCapability.durability === "critical") {
1854
2251
  try {
@@ -1889,7 +2286,14 @@ export class CoreMindRuntime {
1889
2286
  });
1890
2287
  return undefined;
1891
2288
  },
1892
- afterToolCall: async (context) => {
2289
+ afterToolCall: async (driverContext) => {
2290
+ const context = {
2291
+ ...driverContext,
2292
+ toolCall: {
2293
+ ...driverContext.toolCall,
2294
+ args: bindMcpArguments(agentName, driverContext.toolCall.tool, driverContext.toolCall.args),
2295
+ },
2296
+ };
1893
2297
  const lifecycleIdentity = toolCallIdentity(agentName, stepId, context.toolCall.callId);
1894
2298
  const capability = capabilityByCallId.get(toolCapabilityCallKey(agentName, stepId, context.toolCall.callId))?.capability;
1895
2299
  await toolExecutionEngine.advance(lifecycleIdentity, {
@@ -1925,6 +2329,8 @@ export class CoreMindRuntime {
1925
2329
  runContextFor(this).recordArtifact(artifact);
1926
2330
  emit({
1927
2331
  type: "artifact_created",
2332
+ agent: agentName,
2333
+ ...(stepId ? { stepId } : {}),
1928
2334
  artifactId: artifact.artifactId,
1929
2335
  status: artifact.status,
1930
2336
  sizeBytes: artifact.sizeBytes,
@@ -1981,6 +2387,82 @@ export class CoreMindRuntime {
1981
2387
  }
1982
2388
  },
1983
2389
  onObservation: (observation) => {
2390
+ let immediateRejection;
2391
+ if (observation.type === "tool_execution_start" &&
2392
+ discovery &&
2393
+ observation.call.tool !== DISCOVER_TOOLS_NAME) {
2394
+ try {
2395
+ discovery.assertCallable(observation.call.tool);
2396
+ }
2397
+ catch {
2398
+ immediateRejection = "工具不在当前已声明集合";
2399
+ }
2400
+ }
2401
+ if (observation.type === "tool_execution_end" && observation.isError) {
2402
+ const call = observation.call;
2403
+ const key = toolCapabilityCallKey(agentName, stepId, call.callId);
2404
+ const binding = effectBindingByCall.get(key);
2405
+ // 已冻结真实 start,且从未准入的参数拒绝也必须形成完整的未执行收据。
2406
+ if (binding?.tool === call.tool &&
2407
+ !capabilityByCallId.has(key) &&
2408
+ !toolExecutionEngine.inspect(toolCallIdentity(agentName, stepId, call.callId)) &&
2409
+ !immediateToolRejections.has(key)) {
2410
+ immediateRejection = "工具在执行准入前被拒绝";
2411
+ }
2412
+ }
2413
+ if (immediateRejection !== undefined &&
2414
+ (observation.type === "tool_execution_start" ||
2415
+ observation.type === "tool_execution_end")) {
2416
+ const call = observation.call;
2417
+ const key = toolCapabilityCallKey(agentName, stepId, call.callId);
2418
+ const capability = executionCapabilities.get(call.tool) ?? resolveToolCapability({ tool: call.tool });
2419
+ const previous = capabilityByCallId.get(key);
2420
+ if (previous && previous.tool !== call.tool) {
2421
+ throw new CoreMindError("tool_capability_conflict", "同一 Call 不得更换工具身份");
2422
+ }
2423
+ capabilityByCallId.set(key, { tool: call.tool, capability });
2424
+ emit({
2425
+ type: "capability_resolved",
2426
+ agent: agentName,
2427
+ tool: call.tool,
2428
+ callId: call.callId,
2429
+ ...(stepId ? { stepId } : {}),
2430
+ capability,
2431
+ recoveryDisposition: recoveryDispositionFor(capability),
2432
+ });
2433
+ const identity = toolCallIdentity(agentName, stepId, call.callId);
2434
+ const reason = immediateRejection;
2435
+ const rejection = toolExecutionEngine
2436
+ .recordCall({ ...identity, tool: call.tool })
2437
+ .then(() => toolExecutionEngine.blockBeforeExecution(identity, reason));
2438
+ immediateToolRejections.set(key, rejection);
2439
+ void rejection.catch((error) => {
2440
+ lifecycleFailure = normalizeExecutionError(error);
2441
+ });
2442
+ }
2443
+ if (observation.type === "control_consumed" || observation.type === "control_discarded") {
2444
+ const state = receiptStatusOf(collected, observation.inputId);
2445
+ if (observation.type === "control_consumed" &&
2446
+ state === "pending" &&
2447
+ !journal.isAborted()) {
2448
+ if (!observation.turnId)
2449
+ throw new CoreMindError("control_unavailable", "控制消费缺少本执行的 Turn 身份");
2450
+ emitInputEvent(claimInput({ inputId: observation.inputId, turnId: observation.turnId }));
2451
+ }
2452
+ else if ((observation.type === "control_discarded" || journal.isAborted()) &&
2453
+ (state === "pending" || state === "claimed")) {
2454
+ emitInputEvent(discardInput({ inputId: observation.inputId }));
2455
+ }
2456
+ return;
2457
+ }
2458
+ if (observation.type === "tool_execution_end") {
2459
+ const search = discovery?.observe(observation);
2460
+ if (search)
2461
+ discoverySearchesByCall.set(toolCapabilityCallKey(agentName, stepId, observation.call.callId), { fact: search, durable: durableSearches });
2462
+ const fact = skillExecution?.observe(observation);
2463
+ if (fact)
2464
+ skillLoadsByCall.set(toolCapabilityCallKey(agentName, stepId, observation.call.callId), fact);
2465
+ }
1984
2466
  const driver = context.agent(agentName, executionId);
1985
2467
  if (observation.type === "turn_end" &&
1986
2468
  "contextOverflow" in observation &&
@@ -1991,6 +2473,252 @@ export class CoreMindRuntime {
1991
2473
  driver?.abort();
1992
2474
  },
1993
2475
  };
2476
+ if (discoveryEnabled) {
2477
+ const capability = resolveToolCapability({
2478
+ tool: DISCOVER_TOOLS_NAME,
2479
+ source: "registered",
2480
+ declaration: {
2481
+ effect: "none",
2482
+ replay: "safe",
2483
+ concurrency: "parallel",
2484
+ checkpoint: "none",
2485
+ durability: "critical",
2486
+ },
2487
+ });
2488
+ executionEffects.set(DISCOVER_TOOLS_NAME, { operations: ["read"], reversible: true });
2489
+ executionCapabilities.set(DISCOVER_TOOLS_NAME, capability);
2490
+ harness.discoveryTool = adaptCoreMindTool({
2491
+ ...structuredClone(TOOL_DISCOVERY_DECLARATION),
2492
+ effect: { operations: ["read"], reversible: true },
2493
+ capability,
2494
+ execute: async (args, call) => {
2495
+ if (!discovery)
2496
+ throw new CoreMindError("invalid_tool", "工具目录尚未就绪");
2497
+ const result = discovery.search(call.callId, args, call.signal);
2498
+ return { text: result.content[0].text, details: result.details };
2499
+ },
2500
+ });
2501
+ harness.registerToolSource = (name, source) => toolSources.set(name, {
2502
+ exposure: source?.exposure ?? "direct",
2503
+ sourceIdentity: fingerprintEffectReceiptValue(source ?? { source: "host", name }),
2504
+ });
2505
+ harness.registerDeclarationCatalog = (entries) => {
2506
+ const continuation = discoveryContinuations.find((owner) => owner.agent === agentName &&
2507
+ owner.stepId === stepId &&
2508
+ !consumedDiscoveryContinuations.has(owner.executionId));
2509
+ if (continuation)
2510
+ consumedDiscoveryContinuations.add(continuation.executionId);
2511
+ const owner = continuation ?? {
2512
+ runId,
2513
+ agent: agentName,
2514
+ executionId: executionId,
2515
+ ...(stepId ? { stepId } : {}),
2516
+ };
2517
+ const catalog = entries
2518
+ .filter((entry) => entry.name !== DISCOVER_TOOLS_NAME)
2519
+ .filter((entry) => policy.allowsDeclaration(entry.name, executionCapabilities.get(entry.name) ??
2520
+ resolveToolCapability({ tool: entry.name })))
2521
+ .map((entry) => ({
2522
+ ...entry,
2523
+ declaration: entry.declaration,
2524
+ ...(toolSources.get(entry.name) ?? {
2525
+ exposure: "direct",
2526
+ sourceIdentity: fingerprintEffectReceiptValue({ source: "host", name: entry.name }),
2527
+ }),
2528
+ effect: executionEffects.get(entry.name),
2529
+ capability: executionCapabilities.get(entry.name),
2530
+ }));
2531
+ discovery = new ToolDiscoveryExecution({
2532
+ owner,
2533
+ entries: catalog,
2534
+ restored: continuation ? restoreToolDiscovery(resumeRecords, owner) : undefined,
2535
+ });
2536
+ for (const [id, previous] of liveDiscoveryExecutions) {
2537
+ if (previous.catalog.owner.agent === agentName &&
2538
+ previous.catalog.owner.stepId === stepId)
2539
+ liveDiscoveryExecutions.delete(id);
2540
+ }
2541
+ liveDiscoveryExecutions.set(executionId, discovery);
2542
+ providerRequestOrdinal =
2543
+ resumePlan?.previousTrace.filter((entry) => entry.event.type === "provider_request" &&
2544
+ entry.event.toolDiscovery?.catalogFingerprint === discovery.catalog.fingerprint).length ?? 0;
2545
+ for (const source of withdrawnSources)
2546
+ discovery.withdraw(source);
2547
+ initialDiscovery = discovery.prepare([]);
2548
+ return adapterSelection(initialDiscovery?.selection ?? discovery.current);
2549
+ };
2550
+ harness.prepareRequest = async (prepare, signal) => {
2551
+ while (lifecycleFinalizers.size > 0)
2552
+ await Promise.allSettled([...lifecycleFinalizers.values()]);
2553
+ if (lifecycleFailure)
2554
+ throw lifecycleFailure;
2555
+ signal?.throwIfAborted();
2556
+ await journal.flush("critical");
2557
+ const prepared = initialDiscovery ?? discovery.prepare(durableSearches);
2558
+ if (!prepared)
2559
+ return undefined;
2560
+ const selection = adapterSelection(prepared.selection);
2561
+ const contract = prepare(selection);
2562
+ const generation = { prepared };
2563
+ discoveryGenerations.set(prepared.selection.fingerprint, generation);
2564
+ try {
2565
+ emit({
2566
+ type: "context_prefix",
2567
+ agent: agentName,
2568
+ fingerprint: createHash("sha256").update(contract.stablePrefix, "utf8").digest("hex"),
2569
+ toolDiscovery: discoverySummary(prepared.selection),
2570
+ });
2571
+ if (!generation.receipt)
2572
+ throw new CoreMindError("fact_ledger_poisoned", "声明事实未获准持久化");
2573
+ const receipt = await generation.receipt;
2574
+ signal?.throwIfAborted();
2575
+ if (journal.isAborted())
2576
+ throw new CoreMindError("aborted", "声明发布前 Run 已取消");
2577
+ discovery.commit(prepared, receipt);
2578
+ initialDiscovery = undefined;
2579
+ return selection;
2580
+ }
2581
+ finally {
2582
+ discoveryGenerations.delete(prepared.selection.fingerprint);
2583
+ }
2584
+ };
2585
+ }
2586
+ harness.onPromptCompleted = () => liveDiscoveryExecutions.delete(executionId);
2587
+ if (mcpRun) {
2588
+ harness.prepareMcpTools = async (signal) => {
2589
+ const prepared = await mcpRun.prepare({
2590
+ agentName,
2591
+ executionId: executionId,
2592
+ signal,
2593
+ reservedToolNames: [...executionCapabilities.keys()],
2594
+ onToolsChanged: (sourceIdentity) => {
2595
+ withdrawnSources.add(sourceIdentity);
2596
+ discovery?.withdraw(sourceIdentity);
2597
+ },
2598
+ executeHost: async (operation) => {
2599
+ if (executionCapabilities.has(operation.name)) {
2600
+ throw new CoreMindError("invalid_tool", "本地服务准备操作与已有工具重名");
2601
+ }
2602
+ executionEffects.set(operation.name, operation.effect);
2603
+ executionCapabilities.set(operation.name, resolveToolCapability({
2604
+ tool: operation.name,
2605
+ source: "registered",
2606
+ declaration: operation.capability,
2607
+ }));
2608
+ const call = { callId: randomUUID(), tool: operation.name, args: operation.args };
2609
+ const callKey = toolCapabilityCallKey(agentName, stepId, call.callId);
2610
+ const turnId = randomUUID();
2611
+ emit({
2612
+ type: "tool_call",
2613
+ agent: agentName,
2614
+ ...call,
2615
+ ...(stepId ? { stepId } : {}),
2616
+ turnId,
2617
+ });
2618
+ const blocked = await harness.beforeToolCall({ toolCall: call }, signal);
2619
+ if (blocked?.block) {
2620
+ emit({
2621
+ type: "tool_result",
2622
+ agent: agentName,
2623
+ tool: call.tool,
2624
+ callId: call.callId,
2625
+ isError: true,
2626
+ ...(stepId ? { stepId } : {}),
2627
+ turnId,
2628
+ });
2629
+ await lifecycleFinalizers.get(callKey);
2630
+ if (checkpointFailure)
2631
+ throw checkpointFailure;
2632
+ harness.throwIfDenied?.();
2633
+ throw new CoreMindError("tool_execution_failed", blocked.reason ?? "本地服务准备未获准");
2634
+ }
2635
+ let output;
2636
+ let failure;
2637
+ let result = {
2638
+ content: [{ type: "text", text: "本地服务准备失败" }],
2639
+ details: { mcp: { operation: operation.name } },
2640
+ };
2641
+ try {
2642
+ result = await harness.executeTool({
2643
+ call,
2644
+ signal,
2645
+ invoke: async () => {
2646
+ output = await operation.invoke();
2647
+ return {
2648
+ content: [{ type: "text", text: output.text }],
2649
+ details: output.details,
2650
+ };
2651
+ },
2652
+ });
2653
+ }
2654
+ catch (error) {
2655
+ failure = error;
2656
+ }
2657
+ let isError = failure !== undefined || output?.isError === true;
2658
+ try {
2659
+ await harness.afterToolCall({ toolCall: call, result, isError }, signal);
2660
+ }
2661
+ catch (error) {
2662
+ failure ??= error;
2663
+ isError = true;
2664
+ }
2665
+ finally {
2666
+ emit({
2667
+ type: "tool_result",
2668
+ agent: agentName,
2669
+ tool: call.tool,
2670
+ callId: call.callId,
2671
+ isError,
2672
+ ...(stepId ? { stepId } : {}),
2673
+ turnId,
2674
+ });
2675
+ await lifecycleFinalizers.get(callKey);
2676
+ }
2677
+ if (failure)
2678
+ throw failure;
2679
+ if (lifecycleFailure)
2680
+ throw lifecycleFailure;
2681
+ if (checkpointFailure)
2682
+ throw checkpointFailure;
2683
+ budget.throwIfExceeded();
2684
+ if (!output || output.isError)
2685
+ throw new CoreMindError("tool_execution_failed", "本地服务准备失败");
2686
+ return output;
2687
+ },
2688
+ });
2689
+ for (const tool of prepared) {
2690
+ const { definition, authorization } = tool;
2691
+ toolSources.set(definition.name, {
2692
+ exposure: tool.exposure ?? "direct",
2693
+ sourceIdentity: String(authorization.serverIdentity),
2694
+ });
2695
+ const key = JSON.stringify([agentName, definition.name]);
2696
+ const previous = mcpAuthorizations.get(key);
2697
+ if (previous &&
2698
+ fingerprintEffectReceiptValue(previous) !==
2699
+ fingerprintEffectReceiptValue(authorization)) {
2700
+ throw new CoreMindError("tool_capability_conflict", "本 Run 的本地工具授权身份发生变化");
2701
+ }
2702
+ mcpAuthorizations.set(key, authorization);
2703
+ executionEffects.set(definition.name, {
2704
+ ...definition.effect,
2705
+ ...(definition.effect.pathFields
2706
+ ? { pathFields: definition.effect.pathFields.map((field) => `arguments.${field}`) }
2707
+ : {}),
2708
+ ...(definition.effect.urlFields
2709
+ ? { urlFields: definition.effect.urlFields.map((field) => `arguments.${field}`) }
2710
+ : {}),
2711
+ });
2712
+ executionCapabilities.set(definition.name, resolveToolCapability({
2713
+ tool: definition.name,
2714
+ source: "registered",
2715
+ declaration: definition.capability,
2716
+ }));
2717
+ }
2718
+ return prepared.map(({ definition }) => adaptCoreMindTool(definition));
2719
+ };
2720
+ }
2721
+ return harness;
1994
2722
  });
1995
2723
  let outputs = new Map();
1996
2724
  let transcript = "";
@@ -2010,6 +2738,67 @@ export class CoreMindRuntime {
2010
2738
  }
2011
2739
  throw deferredTerminalError;
2012
2740
  }
2741
+ if (taskProgram) {
2742
+ if (loop || this.config.workflow)
2743
+ throw new CoreMindError("invalid_config", "精确任务调用不能替代已配置的 workflow/loop 验收");
2744
+ const name = this.mainAgentName;
2745
+ await taskProgram.execute(async (stepId, tool, args) => {
2746
+ if (journal.isAborted())
2747
+ throw new CoreMindError("aborted", "任务 Run 已停止");
2748
+ const completed = resumePlan?.completedSteps.get(stepId);
2749
+ if (completed)
2750
+ return JSON.parse(completed.output.text);
2751
+ const start = { type: "step_start", stepId, kind: "task_tool" };
2752
+ budget.observeAgentEvent(start);
2753
+ budget.throwIfExceeded();
2754
+ emit(start);
2755
+ let result;
2756
+ const agent = await this.createAgent(name, (event) => emit({ ...event, stepId }), stepId, this.options.signal, {
2757
+ tool,
2758
+ args,
2759
+ accept: (value) => {
2760
+ result = value;
2761
+ },
2762
+ });
2763
+ if (!agent)
2764
+ throw new CoreMindError("unknown_agent", "任务默认 Agent 不存在");
2765
+ await agent.prompt("任务工具调用");
2766
+ await agent.waitForIdle();
2767
+ while (lifecycleFinalizers.size > 0)
2768
+ await Promise.all([...lifecycleFinalizers.values()]);
2769
+ if (lifecycleFailure)
2770
+ throw lifecycleFailure;
2771
+ if (checkpointFailure)
2772
+ throw checkpointFailure;
2773
+ const adapterFailure = selectedAdapterFailure();
2774
+ if (adapterFailure)
2775
+ throw adapterFailure;
2776
+ budget.throwIfExceeded();
2777
+ if (journal.isAborted() || !result)
2778
+ throw new CoreMindError("aborted", "任务调用未收敛");
2779
+ const receipts = projectEffectReceiptBindings(collected).filter((item) => item.binding?.stepId === stepId);
2780
+ const committed = new Set(receipts
2781
+ .filter((item) => item.status === "committed")
2782
+ .map((item) => item.idempotencyKey));
2783
+ for (const event of [...collected].reverse()) {
2784
+ if (event.type === "tool_attempt" &&
2785
+ event.stepId === stepId &&
2786
+ committed.has(receiptId(runId, stepId, event.callId)))
2787
+ committed.add(event.previousReceiptId);
2788
+ }
2789
+ if (receipts.some((item) => !committed.has(item.idempotencyKey)))
2790
+ throw new CoreMindError("tool_execution_failed", "任务工具存在尚未收敛的副作用回执");
2791
+ // 先保存完整结果,再交给任务账本;此间崩溃由同一 Run 的整步结果恢复。
2792
+ const durable = { content: result.content, details: result.details ?? null };
2793
+ assertJsonSerializable(durable);
2794
+ const text = JSON.stringify(durable);
2795
+ emit({ type: "step_output", stepId, agent: name, text });
2796
+ emit({ type: "step_end", stepId, ok: true });
2797
+ await journal.flush("critical");
2798
+ return JSON.parse(text);
2799
+ });
2800
+ return { outputs: new Map(), transcript: "" };
2801
+ }
2013
2802
  if (loop) {
2014
2803
  const engineeringEvidence = loop.verify.mode === "host" ? undefined : loop.verify.evidence;
2015
2804
  let retryCount = resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry" && entry.event.scope === "provider").length ?? 0;
@@ -2044,7 +2833,30 @@ export class CoreMindRuntime {
2044
2833
  return report.passed;
2045
2834
  }
2046
2835
  : undefined,
2047
- executeStep: (request) => runWithTransientRetry(() => this.executeLoopStep(request, emit, limits.stepTimeoutMs, collected), {
2836
+ executeStep: (request) => runWithTransientRetry(async () => {
2837
+ const attemptCursor = collected.length;
2838
+ try {
2839
+ return await this.executeLoopStep(request, emit, limits.stepTimeoutMs, collected);
2840
+ }
2841
+ catch (error) {
2842
+ // 重起步骤会丢弃本次 Driver;已开始的委派也不能证明子任务可以重放。
2843
+ if (retryCount < limits.maxRetries &&
2844
+ classifyRetry(error).retryable &&
2845
+ collected
2846
+ .slice(attemptCursor)
2847
+ .some((event) => event.type === "effect_receipt" &&
2848
+ event.stepId === request.stepId &&
2849
+ event.status !== "not_started" &&
2850
+ (event.tool === DELEGATION_TOOL_NAME ||
2851
+ capabilityByCallId.get(toolCapabilityCallKey(event.agent, event.stepId, event.callId))?.capability.effect !== "none"))) {
2852
+ const original = normalizeExecutionError(error);
2853
+ throw new CoreMindError("unclassified_error", `步骤 ${request.stepId} 已产生副作用或已开始委派,模型请求失败后须人工核对,禁止整步重试`, {
2854
+ originalCode: `${original.code}: ${original.audit?.originalCode ?? original.message}`.slice(0, 512),
2855
+ });
2856
+ }
2857
+ throw error;
2858
+ }
2859
+ }, {
2048
2860
  maxRetries: Math.max(0, limits.maxRetries - retryCount),
2049
2861
  signal: this.options.signal,
2050
2862
  onRetry: () => {
@@ -2069,7 +2881,7 @@ export class CoreMindRuntime {
2069
2881
  }
2070
2882
  if (workflow && workflow.length > 0) {
2071
2883
  const orchestrator = new Orchestrator(workflow, {
2072
- createAgent: (name, stepId) => this.createAgent(name, (event) => emit(stepId ? { ...event, stepId } : event), stepId),
2884
+ createAgent: (name, stepId, signal) => this.createAgent(name, (event) => emit(stepId ? { ...event, stepId } : event), stepId, signal),
2073
2885
  events: emit,
2074
2886
  initialPrompt: effectiveInitialPrompt,
2075
2887
  signal: this.options.signal,
@@ -2091,7 +2903,7 @@ export class CoreMindRuntime {
2091
2903
  if (effectiveInitialPrompt === undefined) {
2092
2904
  throw new CoreMindError("no_prompt", "未提供输入:单 agent 模式需要 --prompt 参数,或配置 workflow 步骤");
2093
2905
  }
2094
- const agent = this.createAgent(name, emit);
2906
+ const agent = await this.createAgent(name, emit);
2095
2907
  if (!agent) {
2096
2908
  throw new CoreMindError("unknown_agent", `默认 agent ${name} 不存在`);
2097
2909
  }
@@ -2165,6 +2977,7 @@ export class CoreMindRuntime {
2165
2977
  }
2166
2978
  }
2167
2979
  finally {
2980
+ modelRequestsOpen = false;
2168
2981
  hostVerification?.interrupt(new CoreMindError("run_already_finished", "Run 已结束验收等待"));
2169
2982
  context.setHarnessFactory(undefined);
2170
2983
  }
@@ -2227,7 +3040,7 @@ export class CoreMindRuntime {
2227
3040
  }
2228
3041
  }
2229
3042
  while (lifecycleFinalizers.size > 0) {
2230
- await Promise.allSettled([...lifecycleFinalizers]);
3043
+ await Promise.allSettled([...lifecycleFinalizers.values()]);
2231
3044
  }
2232
3045
  if (lifecycleFailure &&
2233
3046
  (terminalError === undefined ||
@@ -2238,6 +3051,18 @@ export class CoreMindRuntime {
2238
3051
  // pending 工具结束、journal 落盘队列清空;超时记录 quiescence_timeout 事件不改变终态
2239
3052
  await context.currentControlInbox()?.sealForTerminal();
2240
3053
  await context.currentChildRuns()?.sealForTerminal();
3054
+ for (const name of this.agentConfigs.keys()) {
3055
+ for (const driver of context.agentsNamed(name))
3056
+ driver.clearQueuedControls();
3057
+ }
3058
+ try {
3059
+ await mcpRun?.close();
3060
+ }
3061
+ catch {
3062
+ const failure = new CoreMindError("environment_terminate_failed", "本 Run 的本地服务未能完成资源回收");
3063
+ terminalError ??= failure;
3064
+ emit({ type: "error", message: failure.message, fatal: true });
3065
+ }
2241
3066
  const runtimeQuiescent = await this.waitForQuiescence(DEFAULT_QUIESCENCE_TIMEOUT_MS);
2242
3067
  let delegationGate = context.currentChildRuns()?.continuationGate();
2243
3068
  const environmentTerminationError = context.environmentTerminationError();
@@ -2312,14 +3137,40 @@ export class CoreMindRuntime {
2312
3137
  if (terminalError !== undefined && transcript.length === 0 && !journal.isAborted()) {
2313
3138
  transcript = extractText(allMessages);
2314
3139
  }
3140
+ transcript = redactSensitiveText(transcript);
2315
3141
  try {
2316
3142
  await journal.flush();
2317
3143
  }
2318
3144
  catch (error) {
2319
3145
  terminalError = durabilityFailure(error);
2320
3146
  }
3147
+ if (ownership) {
3148
+ try {
3149
+ await releaseRunSession(ownership, context);
3150
+ }
3151
+ catch (error) {
3152
+ terminalError = error;
3153
+ }
3154
+ }
2321
3155
  const metrics = analyzeRunMetrics(collected, allMessages, performance.now() - started, transcript.length, journal.rejectedAfterAbort());
2322
- let outcome = new RunTerminalizer().terminalize(collected, terminalError);
3156
+ let outcome = new RunTerminalizer().terminalize(collected.slice(terminalEventCursor), terminalError);
3157
+ if (outcome.status !== "paused") {
3158
+ try {
3159
+ await context.currentControlInbox()?.rejectPendingInputs();
3160
+ }
3161
+ catch (error) {
3162
+ terminalError = durabilityFailure(error);
3163
+ outcome = new RunTerminalizer().terminalize(collected.slice(terminalEventCursor), terminalError);
3164
+ }
3165
+ }
3166
+ for (const [id, state] of foldInputReceipts(collected)) {
3167
+ if (!isControlInputId(id))
3168
+ continue;
3169
+ if (state === "claimed" && outcome.status === "succeeded")
3170
+ emitInputEvent(completeInput({ inputId: id }));
3171
+ else if (outcome.status !== "paused" && (state === "pending" || state === "claimed"))
3172
+ emitInputEvent(discardInput({ inputId: id }));
3173
+ }
2323
3174
  // 输入收据终态(规格 03 §4):succeeded → completed;abort/超时/预算/失败 → discarded
2324
3175
  // (未消费输入);paused(审批拒绝等)保持 claimed,resume 继续同一输入
2325
3176
  if (inputReceiptState !== undefined && inputReceiptState !== "completed") {
@@ -2389,11 +3240,17 @@ export class CoreMindRuntime {
2389
3240
  }
2390
3241
  catch (error) {
2391
3242
  terminalError = durabilityFailure(error);
2392
- outcome = new RunTerminalizer().terminalize(collected, terminalError);
3243
+ outcome = new RunTerminalizer().terminalize(collected.slice(terminalEventCursor), terminalError);
2393
3244
  evaluation = createEvaluationReport(this.config.quality, metrics);
2394
3245
  releaseReadiness = assessReleaseReadiness(outcome, evaluation);
2395
3246
  }
2396
3247
  const terminalKind = outcome.status === "paused" ? "pause" : "finish";
3248
+ const pausedDiscoveryOwners = [
3249
+ ...discoveryContinuations.filter((owner) => !consumedDiscoveryContinuations.has(owner.executionId)),
3250
+ ...[...liveDiscoveryExecutions.values()]
3251
+ .filter((execution) => execution.current)
3252
+ .map((execution) => execution.catalog.owner),
3253
+ ];
2397
3254
  const terminalPayload = {
2398
3255
  operation: operation.snapshot(),
2399
3256
  outcome,
@@ -2403,6 +3260,14 @@ export class CoreMindRuntime {
2403
3260
  artifacts: context.artifactRecords(),
2404
3261
  extensions: context.extensions(),
2405
3262
  ...(outcome.status === "paused" && loopSnapshot ? { loopSnapshot } : {}),
3263
+ ...(outcome.status === "paused" && pausedDiscoveryOwners.length > 0
3264
+ ? {
3265
+ toolDiscoveryContinuations: {
3266
+ version: 1,
3267
+ owners: pausedDiscoveryOwners,
3268
+ },
3269
+ }
3270
+ : {}),
2406
3271
  ...(outcome.status === "paused" && deferredTerminalError
2407
3272
  ? { deferredTerminalError: serializeDeferredTerminalError(deferredTerminalError) }
2408
3273
  : {}),
@@ -2421,8 +3286,12 @@ export class CoreMindRuntime {
2421
3286
  catch (error) {
2422
3287
  const finalDurabilityFailure = durabilityFailure(error);
2423
3288
  terminalError = finalDurabilityFailure;
2424
- userEvents({ type: "error", message: finalDurabilityFailure.message, fatal: true });
2425
- outcome = new RunTerminalizer().terminalize(collected, terminalError);
3289
+ userEvents({
3290
+ type: "error",
3291
+ message: redactSensitiveText(finalDurabilityFailure.message),
3292
+ fatal: true,
3293
+ });
3294
+ outcome = new RunTerminalizer().terminalize(collected.slice(terminalEventCursor), terminalError);
2426
3295
  evaluation = createEvaluationReport(this.config.quality, metrics);
2427
3296
  releaseReadiness = assessReleaseReadiness(outcome, evaluation);
2428
3297
  }
@@ -2539,13 +3408,20 @@ export class CoreMindRuntime {
2539
3408
  }
2540
3409
  async executeLoopStep(request, emit, timeoutMs, collected) {
2541
3410
  const eventCursor = collected.length;
2542
- const agent = this.createAgent(request.agent, (event) => emit({ ...event, stepId: request.stepId }), request.stepId);
2543
- if (!agent) {
2544
- throw new CoreMindError("unknown_agent", `Loop 引用了未定义的 agent:${request.agent}(${request.stepId})`);
2545
- }
2546
- const messageCursor = agent.messages().length;
3411
+ const controller = new AbortController();
3412
+ const signal = this.options.signal
3413
+ ? AbortSignal.any([this.options.signal, controller.signal])
3414
+ : controller.signal;
3415
+ let agent;
3416
+ let messageCursor = 0;
2547
3417
  let timer;
2548
3418
  const operation = (async () => {
3419
+ agent = await this.createAgent(request.agent, (event) => emit({ ...event, stepId: request.stepId }), request.stepId, signal);
3420
+ signal.throwIfAborted();
3421
+ if (!agent) {
3422
+ throw new CoreMindError("unknown_agent", `Loop 引用了未定义的 agent:${request.agent}(${request.stepId})`);
3423
+ }
3424
+ messageCursor = agent.messages().length;
2549
3425
  await agent.prompt(request.input);
2550
3426
  await agent.waitForIdle();
2551
3427
  })();
@@ -2555,8 +3431,10 @@ export class CoreMindRuntime {
2555
3431
  operation,
2556
3432
  new Promise((_resolve, reject) => {
2557
3433
  timer = setTimeout(() => {
2558
- agent.abort();
2559
- reject(new CoreMindError("step_timeout", `步骤 ${request.stepId} 执行超时(${timeoutMs}ms),已中止`));
3434
+ const failure = new CoreMindError("step_timeout", `步骤 ${request.stepId} 执行超时(${timeoutMs}ms),已中止`);
3435
+ controller.abort(failure);
3436
+ agent?.abort();
3437
+ reject(failure);
2560
3438
  }, timeoutMs);
2561
3439
  }),
2562
3440
  ]);
@@ -2622,11 +3500,20 @@ export class CoreMindRuntime {
2622
3500
  }
2623
3501
  }
2624
3502
  if (command.type === "steering" || command.type === "follow_up") {
2625
- const agent = context.agent(this.mainAgentName);
2626
- if (!agent)
3503
+ const candidates = context
3504
+ .agentsNamed(this.mainAgentName)
3505
+ .filter((driver) => driver.canAcceptControl());
3506
+ if (candidates.length !== 1)
2627
3507
  return "accepted";
2628
- agent.queueControl({ type: command.type, message: command.message });
2629
- return "applied";
3508
+ const agent = candidates[0];
3509
+ return {
3510
+ status: "applied",
3511
+ afterDurable: () => agent.queueControl({
3512
+ inputId: controlInputId(command.runId, command.controlId),
3513
+ type: command.type,
3514
+ message: command.message,
3515
+ }),
3516
+ };
2630
3517
  }
2631
3518
  return (this.options.applyControl?.(command) ?? {
2632
3519
  status: "rejected",
@@ -2665,16 +3552,15 @@ export class CoreMindRuntime {
2665
3552
  const mains = context.agentsNamed(this.mainAgentName);
2666
3553
  if (mains.length === 0)
2667
3554
  return undefined;
2668
- const cm = context.sessionHandle() ??
2669
- (await CoreMindSession.open({
2670
- dir: sessionDir(this.config, this.options.configDir),
2671
- sessionId,
2672
- cwd: this.options.cwd ?? process.cwd(),
2673
- }));
2674
- if (!context.sessionHandle())
2675
- context.attachSession(cm, projectBranchMessages(await cm.branchEntries()));
3555
+ const cm = context.sessionHandle();
3556
+ if (!cm)
3557
+ throw new CoreMindError("session_write_lease_invalid", "当前 Run 没有可写会话身份");
2676
3558
  // 只追加本轮新增:恢复历史已落盘;请求级压缩的摘要与保留区已由压缩条目代表
2677
- let messages = mains.flatMap((main) => main.messages().slice(context.compactedPrefixEnd() ?? this.resumedContextLength));
3559
+ let messages = mains.flatMap((main) => main
3560
+ .messages()
3561
+ .slice(context.compactedPrefixEnd() ??
3562
+ context.initialSessionLength() ??
3563
+ this.resumedContextLength));
2678
3564
  if (context.currentJournal()?.isAborted()) {
2679
3565
  // D-4 方案 A:abort 后只写已确认部分——去掉尾部未正常终止的 assistant 消息(竞态赢家文本)
2680
3566
  messages = trimUnconfirmedTail(messages);
@@ -2687,6 +3573,95 @@ export class CoreMindRuntime {
2687
3573
  return cm.filePath;
2688
3574
  }
2689
3575
  }
3576
+ /** 仅供 ChatSession 使用;导航与 Run 使用相同的写身份和历史水位。 */
3577
+ async function navigateRuntimeSession(runtime, agentName, history, navigation) {
3578
+ const slot = executionSlotFor(runtime);
3579
+ if (!slot.sessionOptions || slot.sessionAgent !== agentName)
3580
+ throw new CoreMindError("session_navigation_invalid", "导航需要启用持久会话并使用会话所属主 Agent");
3581
+ if (slot.running || slot.navigatingSession || boundDelegationExecutor(runtime))
3582
+ throw new CoreMindError("concurrent_run", "活动 Run 或导航期间不能操作会话树");
3583
+ slot.navigatingSession = true;
3584
+ try {
3585
+ const opts = slot.sessionOptions;
3586
+ return await withSessionWriteLease(opts.dir, opts.sessionId, async (lease) => {
3587
+ const session = await openWritableSession(opts, lease);
3588
+ if (navigation.type !== "inspect" &&
3589
+ historySessionSnapshot(history) !== sessionSnapshot(session))
3590
+ throw new CoreMindError("session_snapshot_stale", "会话已变化,请重新打开后再导航");
3591
+ if (navigation.type === "fork")
3592
+ return { tree: await session.fork(navigation.at) };
3593
+ if (navigation.type === "create")
3594
+ await session.createBranch(navigation.branchId, navigation.at);
3595
+ if (navigation.type === "select")
3596
+ await session.selectBranch(navigation.branchId);
3597
+ const tree = await session.inspectTree();
3598
+ if (navigation.type === "inspect")
3599
+ return { tree };
3600
+ const restored = rememberSessionHistory(session, projectBranchMessages(await session.branchEntries()).map((item) => item.message));
3601
+ slot.sessionPreviewHistory = copySessionHistory(restored);
3602
+ return { tree, history: restored };
3603
+ });
3604
+ }
3605
+ finally {
3606
+ slot.navigatingSession = false;
3607
+ }
3608
+ }
3609
+ /** 只供 TaskSession 使用:精确工具与子任务共享同一个 Run 的全部治理。 */
3610
+ export async function runTaskProgram(runtime, id, execute) {
3611
+ const slot = executionSlotFor(runtime);
3612
+ if (slot.running || slot.taskProgram)
3613
+ throw new CoreMindError("concurrent_run", "任务 Run 已在执行");
3614
+ slot.taskProgram = { id, execute };
3615
+ try {
3616
+ return await runtime.run();
3617
+ }
3618
+ finally {
3619
+ slot.taskProgram = undefined;
3620
+ }
3621
+ }
3622
+ async function executeWithSessionLease(runtime, options, config, context, execute) {
3623
+ if (!options.sessionId || !config.session?.enabled)
3624
+ return execute();
3625
+ const ownership = {
3626
+ lease: await acquireSessionWriteLease(sessionDir(config, options.configDir), options.sessionId),
3627
+ released: false,
3628
+ retained: false,
3629
+ };
3630
+ try {
3631
+ const result = await execute(ownership);
3632
+ const session = context.sessionHandle();
3633
+ if (session) {
3634
+ for (const messages of result.messages.values())
3635
+ rememberSessionHistory(session, messages);
3636
+ executionSlotFor(runtime).sessionPreviewHistory = rememberSessionHistory(session, projectBranchMessages(await session.branchEntries()).map((item) => item.message));
3637
+ }
3638
+ return result;
3639
+ }
3640
+ catch (error) {
3641
+ try {
3642
+ await releaseRunSession(ownership, context);
3643
+ }
3644
+ catch (cleanupError) {
3645
+ throw Object.assign(new CoreMindError("session_lock_recovery_required", "运行失败且会话所有权未能安全释放"), { cause: new AggregateError([error, cleanupError]) });
3646
+ }
3647
+ throw error;
3648
+ }
3649
+ }
3650
+ async function releaseRunSession(ownership, context) {
3651
+ if (ownership.released || ownership.retained)
3652
+ return;
3653
+ if (!context.isExecutionQuiescent()) {
3654
+ ownership.retained = true;
3655
+ throw new CoreMindError("session_not_quiescent", "会话写入或运行尚未静止,保留写租约并等待恢复审计");
3656
+ }
3657
+ ownership.released = true;
3658
+ try {
3659
+ await ownership.lease.release();
3660
+ }
3661
+ catch (error) {
3662
+ throw Object.assign(new CoreMindError("session_lock_recovery_required", "会话写租约释放失败,需核验所有权"), { cause: error });
3663
+ }
3664
+ }
2690
3665
  const runtimeExecutionSlots = new WeakMap();
2691
3666
  function executionSlotFor(runtime) {
2692
3667
  const existing = runtimeExecutionSlots.get(runtime);
@@ -2767,11 +3742,18 @@ const QUIESCENCE_POLL_INTERVAL_MS = 1;
2767
3742
  const DELEGATED_SAFE_BUILTIN_TOOLS = new Set(["web-fetch", "write"]);
2768
3743
  /** Child 只保留显式网络读取与受 Checkpoint/Lease 保护的写入,不加载脚本、进程或扫描工具。 */
2769
3744
  function isDelegatedBuiltinToolConfig(tool) {
2770
- return !("path" in tool) && DELEGATED_SAFE_BUILTIN_TOOLS.has(tool.id);
3745
+ return "id" in tool && DELEGATED_SAFE_BUILTIN_TOOLS.has(tool.id);
2771
3746
  }
2772
3747
  function isDelegatedSafeToolName(tool) {
2773
3748
  return DELEGATED_SAFE_BUILTIN_TOOLS.has(tool);
2774
3749
  }
3750
+ function needsFrozenSkillAuthority(agents, snapshot, name, seen = new Set()) {
3751
+ if (!snapshot || seen.has(name) || !Object.hasOwn(agents, name))
3752
+ return false;
3753
+ seen.add(name);
3754
+ return ((snapshot.agents[name]?.standard.length ?? 0) > 0 ||
3755
+ Object.keys(agents[name].delegation?.targets ?? {}).some((target) => needsFrozenSkillAuthority(agents, snapshot, target, seen)));
3756
+ }
2775
3757
  const DELEGATED_TOOL_ENV_ALLOWLIST = new Set([
2776
3758
  "PATH",
2777
3759
  "PATHEXT",
@@ -2868,9 +3850,9 @@ function tightenDelegationBudget(configured, inherited) {
2868
3850
  ]));
2869
3851
  }
2870
3852
  async function assertRuntimeChildPolicyAuthority(input) {
2871
- const { policy, config, model, executionEnvironment, workspaceRoot, tools, limits, enforceRuntimeBudget, enforceDelegatedToolBoundary, } = input;
3853
+ const { policy, config, model, executionEnvironment, workspaceRoot, tools, limits, enforceRuntimeBudget, enforceDelegatedToolBoundary, trustedSkillLoader, } = input;
2872
3854
  const unsafeTool = enforceDelegatedToolBoundary
2873
- ? [...tools].find((tool) => !isDelegatedSafeToolName(tool))
3855
+ ? [...tools].find((tool) => !isDelegatedSafeToolName(tool) && !(trustedSkillLoader && tool === SKILL_TOOL_NAME))
2874
3856
  : undefined;
2875
3857
  if (unsafeTool) {
2876
3858
  throw new CoreMindError("child_run_policy_escalation", `Child Runtime 工具 ${unsafeTool} 不能证明不会扩展 Delegated Context`);
@@ -2948,7 +3930,7 @@ function durabilityFailure(error) {
2948
3930
  */
2949
3931
  function resumedInputId(events) {
2950
3932
  for (const event of events) {
2951
- if (event.type === "input_receipt")
3933
+ if (event.type === "input_receipt" && !isControlInputId(event.inputId))
2952
3934
  return event.inputId;
2953
3935
  }
2954
3936
  return undefined;