coremind-runtime 1.0.0 → 1.2.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 (230) hide show
  1. package/dist/active-run-binding.d.ts +10 -0
  2. package/dist/active-run-binding.d.ts.map +1 -1
  3. package/dist/active-run-binding.js +7 -0
  4. package/dist/active-run-binding.js.map +1 -1
  5. package/dist/agent-driver.d.ts +34 -0
  6. package/dist/agent-driver.d.ts.map +1 -1
  7. package/dist/agent-driver.js +24 -4
  8. package/dist/agent-driver.js.map +1 -1
  9. package/dist/agent-factory.d.ts.map +1 -1
  10. package/dist/agent-factory.js +227 -32
  11. package/dist/agent-factory.js.map +1 -1
  12. package/dist/bounded-output.d.ts +13 -0
  13. package/dist/bounded-output.d.ts.map +1 -0
  14. package/dist/bounded-output.js +200 -0
  15. package/dist/bounded-output.js.map +1 -0
  16. package/dist/chat-session.d.ts +12 -1
  17. package/dist/chat-session.d.ts.map +1 -1
  18. package/dist/chat-session.js +27 -6
  19. package/dist/chat-session.js.map +1 -1
  20. package/dist/compaction-projection.d.ts +1 -1
  21. package/dist/compaction-projection.d.ts.map +1 -1
  22. package/dist/compaction-projection.js +1 -1
  23. package/dist/compaction-projection.js.map +1 -1
  24. package/dist/context-lifecycle.d.ts.map +1 -1
  25. package/dist/context-lifecycle.js +1 -1
  26. package/dist/context-lifecycle.js.map +1 -1
  27. package/dist/context.d.ts.map +1 -1
  28. package/dist/context.js +1 -1
  29. package/dist/context.js.map +1 -1
  30. package/dist/control-inbox.d.ts +2 -0
  31. package/dist/control-inbox.d.ts.map +1 -1
  32. package/dist/control-inbox.js +27 -4
  33. package/dist/control-inbox.js.map +1 -1
  34. package/dist/dependency-adapter.d.ts.map +1 -1
  35. package/dist/dependency-adapter.js +3 -3
  36. package/dist/dependency-adapter.js.map +1 -1
  37. package/dist/errors.d.ts.map +1 -1
  38. package/dist/errors.js +3 -2
  39. package/dist/errors.js.map +1 -1
  40. package/dist/evaluation.d.ts +2 -0
  41. package/dist/evaluation.d.ts.map +1 -1
  42. package/dist/evaluation.js +12 -1
  43. package/dist/evaluation.js.map +1 -1
  44. package/dist/events.d.ts +15 -0
  45. package/dist/events.d.ts.map +1 -1
  46. package/dist/events.js.map +1 -1
  47. package/dist/execution-security.d.ts.map +1 -1
  48. package/dist/execution-security.js +12 -3
  49. package/dist/execution-security.js.map +1 -1
  50. package/dist/index.d.ts +3 -1
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +1 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/input-receipt.d.ts +4 -0
  55. package/dist/input-receipt.d.ts.map +1 -1
  56. package/dist/input-receipt.js +11 -0
  57. package/dist/input-receipt.js.map +1 -1
  58. package/dist/internal.d.ts +4 -0
  59. package/dist/internal.d.ts.map +1 -1
  60. package/dist/internal.js +4 -0
  61. package/dist/internal.js.map +1 -1
  62. package/dist/mcp-authentication.d.ts +11 -0
  63. package/dist/mcp-authentication.d.ts.map +1 -0
  64. package/dist/mcp-authentication.js +24 -0
  65. package/dist/mcp-authentication.js.map +1 -0
  66. package/dist/mcp-runtime.d.ts +91 -0
  67. package/dist/mcp-runtime.d.ts.map +1 -0
  68. package/dist/mcp-runtime.js +514 -0
  69. package/dist/mcp-runtime.js.map +1 -0
  70. package/dist/observability.d.ts.map +1 -1
  71. package/dist/observability.js +8 -3
  72. package/dist/observability.js.map +1 -1
  73. package/dist/orchestrator.d.ts +2 -2
  74. package/dist/orchestrator.d.ts.map +1 -1
  75. package/dist/orchestrator.js +25 -16
  76. package/dist/orchestrator.js.map +1 -1
  77. package/dist/project-check.d.ts.map +1 -1
  78. package/dist/project-check.js +25 -0
  79. package/dist/project-check.js.map +1 -1
  80. package/dist/project-code-trust.d.ts +12 -0
  81. package/dist/project-code-trust.d.ts.map +1 -0
  82. package/dist/project-code-trust.js +97 -0
  83. package/dist/project-code-trust.js.map +1 -0
  84. package/dist/projection.d.ts.map +1 -1
  85. package/dist/projection.js +6 -3
  86. package/dist/projection.js.map +1 -1
  87. package/dist/provider.d.ts +2 -2
  88. package/dist/provider.d.ts.map +1 -1
  89. package/dist/provider.js +39 -11
  90. package/dist/provider.js.map +1 -1
  91. package/dist/rebuild-request.d.ts +3 -1
  92. package/dist/rebuild-request.d.ts.map +1 -1
  93. package/dist/rebuild-request.js +6 -2
  94. package/dist/rebuild-request.js.map +1 -1
  95. package/dist/redaction.d.ts +4 -0
  96. package/dist/redaction.d.ts.map +1 -0
  97. package/dist/redaction.js +40 -0
  98. package/dist/redaction.js.map +1 -0
  99. package/dist/run-context.d.ts +6 -2
  100. package/dist/run-context.d.ts.map +1 -1
  101. package/dist/run-context.js +16 -1
  102. package/dist/run-context.js.map +1 -1
  103. package/dist/run-state.d.ts.map +1 -1
  104. package/dist/run-state.js +141 -83
  105. package/dist/run-state.js.map +1 -1
  106. package/dist/runtime.d.ts +8 -3
  107. package/dist/runtime.d.ts.map +1 -1
  108. package/dist/runtime.js +971 -170
  109. package/dist/runtime.js.map +1 -1
  110. package/dist/session-v4/compaction/compaction.d.ts +84 -0
  111. package/dist/session-v4/compaction/compaction.d.ts.map +1 -0
  112. package/dist/session-v4/compaction/compaction.js +581 -0
  113. package/dist/session-v4/compaction/compaction.js.map +1 -0
  114. package/dist/session-v4/compaction/utils.d.ts +39 -0
  115. package/dist/session-v4/compaction/utils.d.ts.map +1 -0
  116. package/dist/session-v4/compaction/utils.js +139 -0
  117. package/dist/session-v4/compaction/utils.js.map +1 -0
  118. package/dist/session-v4/file-system.d.ts +25 -0
  119. package/dist/session-v4/file-system.d.ts.map +1 -0
  120. package/dist/session-v4/file-system.js +257 -0
  121. package/dist/session-v4/file-system.js.map +1 -0
  122. package/dist/session-v4/index.d.ts +33 -0
  123. package/dist/session-v4/index.d.ts.map +1 -0
  124. package/dist/session-v4/index.js +33 -0
  125. package/dist/session-v4/index.js.map +1 -0
  126. package/dist/session-v4/message-types.d.ts +28 -0
  127. package/dist/session-v4/message-types.d.ts.map +1 -0
  128. package/dist/session-v4/message-types.js +2 -0
  129. package/dist/session-v4/message-types.js.map +1 -0
  130. package/dist/session-v4/messages.d.ts +66 -0
  131. package/dist/session-v4/messages.d.ts.map +1 -0
  132. package/dist/session-v4/messages.js +112 -0
  133. package/dist/session-v4/messages.js.map +1 -0
  134. package/dist/session-v4/session/context.d.ts +45 -0
  135. package/dist/session-v4/session/context.d.ts.map +1 -0
  136. package/dist/session-v4/session/context.js +69 -0
  137. package/dist/session-v4/session/context.js.map +1 -0
  138. package/dist/session-v4/session/jsonl/codec.d.ts +31 -0
  139. package/dist/session-v4/session/jsonl/codec.d.ts.map +1 -0
  140. package/dist/session-v4/session/jsonl/codec.js +195 -0
  141. package/dist/session-v4/session/jsonl/codec.js.map +1 -0
  142. package/dist/session-v4/session/jsonl/errors.d.ts +28 -0
  143. package/dist/session-v4/session/jsonl/errors.d.ts.map +1 -0
  144. package/dist/session-v4/session/jsonl/errors.js +11 -0
  145. package/dist/session-v4/session/jsonl/errors.js.map +1 -0
  146. package/dist/session-v4/session/jsonl/repo.d.ts +23 -0
  147. package/dist/session-v4/session/jsonl/repo.d.ts.map +1 -0
  148. package/dist/session-v4/session/jsonl/repo.js +156 -0
  149. package/dist/session-v4/session/jsonl/repo.js.map +1 -0
  150. package/dist/session-v4/session/jsonl/storage.d.ts +43 -0
  151. package/dist/session-v4/session/jsonl/storage.d.ts.map +1 -0
  152. package/dist/session-v4/session/jsonl/storage.js +245 -0
  153. package/dist/session-v4/session/jsonl/storage.js.map +1 -0
  154. package/dist/session-v4/session/jsonl/types.d.ts +58 -0
  155. package/dist/session-v4/session/jsonl/types.d.ts.map +1 -0
  156. package/dist/session-v4/session/jsonl/types.js +2 -0
  157. package/dist/session-v4/session/jsonl/types.js.map +1 -0
  158. package/dist/session-v4/session/jsonl.d.ts +26 -0
  159. package/dist/session-v4/session/jsonl.d.ts.map +1 -0
  160. package/dist/session-v4/session/jsonl.js +26 -0
  161. package/dist/session-v4/session/jsonl.js.map +1 -0
  162. package/dist/session-v4/session/memory.d.ts +44 -0
  163. package/dist/session-v4/session/memory.d.ts.map +1 -0
  164. package/dist/session-v4/session/memory.js +166 -0
  165. package/dist/session-v4/session/memory.js.map +1 -0
  166. package/dist/session-v4/session/session.d.ts +50 -0
  167. package/dist/session-v4/session/session.d.ts.map +1 -0
  168. package/dist/session-v4/session/session.js +246 -0
  169. package/dist/session-v4/session/session.js.map +1 -0
  170. package/dist/session-v4/session/state.d.ts +88 -0
  171. package/dist/session-v4/session/state.d.ts.map +1 -0
  172. package/dist/session-v4/session/state.js +355 -0
  173. package/dist/session-v4/session/state.js.map +1 -0
  174. package/dist/session-v4/session/testing/conformance.d.ts +3 -0
  175. package/dist/session-v4/session/testing/conformance.d.ts.map +1 -0
  176. package/dist/session-v4/session/testing/conformance.js +812 -0
  177. package/dist/session-v4/session/testing/conformance.js.map +1 -0
  178. package/dist/session-v4/session/testing/types.d.ts +34 -0
  179. package/dist/session-v4/session/testing/types.d.ts.map +1 -0
  180. package/dist/session-v4/session/testing/types.js +2 -0
  181. package/dist/session-v4/session/testing/types.js.map +1 -0
  182. package/dist/session-v4/session/types.d.ts +343 -0
  183. package/dist/session-v4/session/types.d.ts.map +1 -0
  184. package/dist/session-v4/session/types.js +10 -0
  185. package/dist/session-v4/session/types.js.map +1 -0
  186. package/dist/session-v4/types.d.ts +72 -0
  187. package/dist/session-v4/types.d.ts.map +1 -0
  188. package/dist/session-v4/types.js +37 -0
  189. package/dist/session-v4/types.js.map +1 -0
  190. package/dist/session-write-lease.d.ts +11 -0
  191. package/dist/session-write-lease.d.ts.map +1 -0
  192. package/dist/session-write-lease.js +286 -0
  193. package/dist/session-write-lease.js.map +1 -0
  194. package/dist/session.d.ts +9 -1
  195. package/dist/session.d.ts.map +1 -1
  196. package/dist/session.js +183 -73
  197. package/dist/session.js.map +1 -1
  198. package/dist/skill-privacy.d.ts +3 -0
  199. package/dist/skill-privacy.d.ts.map +1 -0
  200. package/dist/skill-privacy.js +22 -0
  201. package/dist/skill-privacy.js.map +1 -0
  202. package/dist/skill-runtime.d.ts +55 -0
  203. package/dist/skill-runtime.d.ts.map +1 -0
  204. package/dist/skill-runtime.js +223 -0
  205. package/dist/skill-runtime.js.map +1 -0
  206. package/dist/tool-discovery-declaration.d.ts +8 -0
  207. package/dist/tool-discovery-declaration.d.ts.map +1 -0
  208. package/dist/tool-discovery-declaration.js +15 -0
  209. package/dist/tool-discovery-declaration.js.map +1 -0
  210. package/dist/tool-discovery-replay.d.ts +13 -0
  211. package/dist/tool-discovery-replay.d.ts.map +1 -0
  212. package/dist/tool-discovery-replay.js +89 -0
  213. package/dist/tool-discovery-replay.js.map +1 -0
  214. package/dist/tool-discovery.d.ts +95 -0
  215. package/dist/tool-discovery.d.ts.map +1 -0
  216. package/dist/tool-discovery.js +532 -0
  217. package/dist/tool-discovery.js.map +1 -0
  218. package/dist/tool-policy.d.ts +10 -1
  219. package/dist/tool-policy.d.ts.map +1 -1
  220. package/dist/tool-policy.js +49 -44
  221. package/dist/tool-policy.js.map +1 -1
  222. package/dist/trace.d.ts +2 -2
  223. package/dist/trace.d.ts.map +1 -1
  224. package/dist/trace.js +6 -36
  225. package/dist/trace.js.map +1 -1
  226. package/dist/turn-tracker.d.ts +2 -0
  227. package/dist/turn-tracker.d.ts.map +1 -1
  228. package/dist/turn-tracker.js +13 -0
  229. package/dist/turn-tracker.js.map +1 -1
  230. package/package.json +7 -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";
@@ -23,29 +24,35 @@ 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
44
  import { FileRunStore, fingerprintRunConfig, 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, openWritableSession, rememberSessionHistory, sessionSnapshot, } from "./session.js";
45
48
  import { compactSessionInRun } from "./session-maintenance.js";
49
+ import { acquireSessionWriteLease } from "./session-write-lease.js";
50
+ import { assertSkillSnapshotSize, freezeSkillSnapshot, restoreSkillSnapshot, SKILL_TOOL_CAPABILITY, SKILL_TOOL_EFFECT, SKILL_TOOL_NAME, SkillExecution, skillPrefixContents, } from "./skill-runtime.js";
46
51
  import { createRunSnapshot } from "./snapshot.js";
47
52
  import { ToolExecutionEngine } from "./tool-call-lifecycle.js";
48
53
  import { toolCapabilityCallKey } from "./tool-capability-identity.js";
54
+ import { DISCOVER_TOOLS_NAME, restoreToolDiscovery, restoreToolDiscoveryContinuations, ToolDiscoveryExecution, } from "./tool-discovery.js";
55
+ import { TOOL_DISCOVERY_DECLARATION } from "./tool-discovery-declaration.js";
49
56
  import { ToolPolicy } from "./tool-policy.js";
50
57
  import { redactSensitiveText, TraceRecorder } from "./trace.js";
51
58
  import { TurnTracker } from "./turn-tracker.js";
@@ -116,8 +123,12 @@ export class CoreMindRuntime {
116
123
  return CoreMindRuntime.createWithWorkspaceLease(options, new WorkspaceLeaseService());
117
124
  }
118
125
  /** 同一父子树复用一个 Lease 服务;跨进程一致性仍由 canonical lock file 提供。 */
119
- static async createWithWorkspaceLease(options, workspaceLeaseService) {
126
+ static async createWithWorkspaceLease(options, workspaceLeaseService, frozenSkills) {
120
127
  const { config, configDir } = options;
128
+ if (config.schemaVersion !== 3 &&
129
+ [config.tools ?? [], ...Object.values(config.agents).map((agent) => agent.tools ?? [])].some((tools) => tools.some((tool) => tool.exposure === "deferred"))) {
130
+ throw new CoreMindError("invalid_config", "deferred 必须显式配置 schemaVersion: 3");
131
+ }
121
132
  const cwd = options.cwd ?? process.cwd();
122
133
  const env = options.env ?? process.env;
123
134
  const requestedToolEnv = options.toolEnv ?? env;
@@ -132,6 +143,17 @@ export class CoreMindRuntime {
132
143
  if (options.childRunAuthority && (options.toolDefinitions?.length ?? 0) > 0) {
133
144
  throw new CoreMindError("child_run_policy_escalation", "Child Runtime 不接受缺少内建 provenance 的注入工具");
134
145
  }
146
+ if (options.childRunAuthority &&
147
+ (options.mcpAuthentication !== undefined ||
148
+ config.mcp !== undefined ||
149
+ Object.values(config.agents).some((agent) => agent.mcpResources !== undefined) ||
150
+ [
151
+ config.tools ?? [],
152
+ ...Object.values(config.agents).map((agent) => agent.tools ?? []),
153
+ ].some((tools) => tools.some((tool) => "mcp" in tool)))) {
154
+ throw new CoreMindError("child_run_policy_escalation", "Child Runtime 不接受宿主本地服务工具");
155
+ }
156
+ const beforeScriptImport = await prepareProjectCodeImports(config, configDir, options.approveProjectCode, options.signal);
135
157
  // 1. provider(解析模型,警告转发)
136
158
  const providerRuntime = await buildProviderRuntime(config.provider, env, options.secretResolver);
137
159
  for (const warning of providerRuntime.warnings) {
@@ -152,17 +174,44 @@ export class CoreMindRuntime {
152
174
  const externalTools = (options.toolDefinitions ?? []).map((definition) => wrapToolWithArtifactCapture(adaptCoreMindTool(definition), artifactStore));
153
175
  let runtime;
154
176
  // 自定义技能(生态机制):配置文件所在目录的 skills/ 下,每个子目录的 README.md 即一个技能
155
- const customSkills = await loadDirectorySkills(path.join(configDir, "skills"));
177
+ const restoredSkills = frozenSkills ??
178
+ (options.resumeRunId
179
+ ? restoreSkillSnapshot(await (options.runStore ?? new FileRunStore(path.join(configDir, ".coremind", "runs"))).read(options.resumeRunId), config.agents)
180
+ : undefined);
181
+ const selectedSkills = Object.create(null);
156
182
  for (const [name, agentCfg] of Object.entries(config.agents)) {
157
183
  const agentModel = resolveProviderModel(providerRuntime, agentCfg.model);
158
184
  agentModels.set(name, agentModel);
185
+ const selected = restoredSkills
186
+ ? { ...restoredSkills.agents[name], missing: [], warnings: [] }
187
+ : await resolveSelectedSkills(agentCfg.skills ?? [], configDir);
188
+ if (options.resumeRunId && !restoredSkills && selected.standard.length > 0) {
189
+ throw new CoreMindError("context_capability_conflict", "恢复标准技能缺少原 Run 冻结快照");
190
+ }
191
+ selectedSkills[name] = {
192
+ legacyContents: selected.legacyContents,
193
+ standard: selected.standard,
194
+ };
195
+ if (Object.values(selectedSkills).some((selection) => selection.standard.length > 0)) {
196
+ assertSkillSnapshotSize({ version: 1, agents: selectedSkills });
197
+ }
198
+ for (const warning of selected.warnings)
199
+ emit({ type: "error", message: warning, fatal: false });
200
+ if (selected.standard.length > 0 &&
201
+ externalTools.some((tool) => tool.name === SKILL_TOOL_NAME)) {
202
+ throw new CoreMindError("invalid_tool", "标准技能启用时,自定义工具不得使用 load_skill 名称");
203
+ }
159
204
  const toolConfigs = (agentCfg.tools?.length ?? 0) > 0 ? agentCfg.tools : config.tools;
160
- const { tools, warnings, effects, capabilities } = await buildToolsWithExecutionEnvironment(toolConfigs ?? [], {
205
+ const { tools, warnings, effects, capabilities } = await buildToolsWithExecutionEnvironment((toolConfigs ?? []).filter((tool) => !("mcp" in tool)), {
161
206
  cwd,
162
207
  configDir,
163
208
  env: toolEnv,
164
209
  artifactStore,
210
+ beforeScriptImport,
165
211
  }, executionEnvironment);
212
+ if (selected.standard.length > 0 && tools.some((tool) => tool.name === SKILL_TOOL_NAME)) {
213
+ throw new CoreMindError("invalid_tool", "标准技能启用时,脚本工具不得使用 load_skill 名称");
214
+ }
166
215
  for (const warning of warnings) {
167
216
  emit({ type: "error", message: warning, fatal: false });
168
217
  }
@@ -206,6 +255,7 @@ export class CoreMindRuntime {
206
255
  ...effects,
207
256
  ...(options.toolDefinitions ?? []).map((definition) => [definition.name, definition.effect]),
208
257
  ...delegationEffects,
258
+ ...(selected.standard.length > 0 ? [[SKILL_TOOL_NAME, SKILL_TOOL_EFFECT]] : []),
209
259
  ]));
210
260
  toolCapabilitiesByAgent.set(name, new Map([
211
261
  ...capabilities,
@@ -220,43 +270,48 @@ export class CoreMindRuntime {
220
270
  : inferLegacyToolCapability(definition.name, definition.effect),
221
271
  ]),
222
272
  ...delegationCapabilities,
273
+ ...(selected.standard.length > 0
274
+ ? [[SKILL_TOOL_NAME, SKILL_TOOL_CAPABILITY]]
275
+ : []),
223
276
  ]));
224
277
  // 技能:内置优先,未命中的查自定义目录,仍缺失才告警(不阻断)
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
- }
278
+ const allContents = skillPrefixContents(selectedSkills[name]);
279
+ for (const id of selected.missing) {
280
+ emit({
281
+ type: "error",
282
+ message: `技能 ${id} 不存在(内置:${SKILLS.map((s) => s.id).join("、")};自定义:放配置目录的 skills/${id}/README.md),已忽略`,
283
+ fatal: false,
284
+ });
239
285
  }
240
286
  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
- }));
287
+ driverBuilders.set(name, ({ onEvent, harness, sessionMessages, skillTool, mcpTools, discoveryTool }) => {
288
+ for (const tool of driverTools)
289
+ harness?.registerToolSource?.(tool.name, configuredToolSource(tool));
290
+ return buildAgentDriver(agentCfg, {
291
+ models: providerRuntime.models,
292
+ model: agentModel,
293
+ tools: [
294
+ ...driverTools,
295
+ ...(mcpTools ?? []),
296
+ ...(skillTool ? [skillTool] : []),
297
+ ...(discoveryTool ? [discoveryTool] : []),
298
+ ],
299
+ agentName: name,
300
+ onEvent,
301
+ apiKeyOverride: providerRuntime.apiKeyOverride,
302
+ sessionMessages,
303
+ skillsContent: allContents,
304
+ stableFacts: {
305
+ provider: agentModel.provider,
306
+ model: agentModel.id,
307
+ contextWindow: agentModel.contextWindow,
308
+ },
309
+ promptCacheStatus: agentModel.cost.cacheRead > 0 || agentModel.cost.cacheWrite > 0
310
+ ? "available"
311
+ : "unavailable",
312
+ harness,
313
+ });
314
+ });
260
315
  }
261
316
  // 会话恢复:--session 且 session.enabled 时,打开已有会话注入历史视图(非破坏)
262
317
  let sessionMessages;
@@ -264,14 +319,10 @@ export class CoreMindRuntime {
264
319
  if (options.sessionId && config.session?.enabled) {
265
320
  const dir = sessionDir(config, configDir);
266
321
  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
- }
322
+ const cm = await CoreMindSession.open({ dir, sessionId: options.sessionId, cwd });
323
+ const restored = projectBranchMessages(await cm.branchEntries()).map((item) => item.message);
324
+ sessionMessages = rememberSessionHistory(cm, restored);
325
+ resumedContextLength = restored.length;
275
326
  }
276
327
  catch (error) {
277
328
  const detail = error instanceof Error ? error.message : String(error);
@@ -279,22 +330,48 @@ export class CoreMindRuntime {
279
330
  }
280
331
  }
281
332
  runtime = new CoreMindRuntime(config, agentConfigs, agentModels, driverBuilders, toolEffectsByAgent, toolCapabilitiesByAgent, providerRuntime, executionEnvironment, workspaceLeaseService, options, sessionMessages, resumedContextLength, skillsByAgent);
333
+ executionSlotFor(runtime).skills = restoredSkills ?? freezeSkillSnapshot(selectedSkills);
282
334
  return runtime;
283
335
  }
284
336
  /** 按名字创建独立 Driver 实例(每次新实例,消息历史独立) */
285
- createAgent(name, onEvent = this.options.events ?? (() => { }), stepId) {
337
+ async createAgent(name, onEvent = this.options.events ?? (() => { }), stepId, signal) {
286
338
  const buildDriver = this.driverBuilders.get(name);
287
339
  if (!buildDriver)
288
340
  return undefined;
289
341
  const context = runContextFor(this);
290
342
  const executionId = randomUUID();
291
343
  const turnTracker = new TurnTracker();
292
- const harness = context.harnessFor(name, stepId, executionId);
344
+ const originalHarness = context.harnessFor(name, stepId, executionId);
345
+ signal?.throwIfAborted();
346
+ const mcpTools = await originalHarness?.prepareMcpTools?.(signal);
347
+ signal?.throwIfAborted();
348
+ const harness = {
349
+ ...originalHarness,
350
+ beforePrompt: async () => {
351
+ if (originalHarness?.beforePrompt)
352
+ await originalHarness.beforePrompt();
353
+ if (name === this.mainAgentName) {
354
+ await context.currentControlInbox()?.applyPending("steering");
355
+ await context.currentControlInbox()?.applyPending("follow_up");
356
+ }
357
+ if (this.options.signal?.aborted || context.currentJournal()?.isAborted()) {
358
+ throw new CoreMindError("aborted", "控制恢复完成前运行已取消");
359
+ }
360
+ },
361
+ onObservation: (observation) => originalHarness?.onObservation?.(observation.type === "control_consumed"
362
+ ? { ...observation, turnId: turnTracker.ensureCurrentTurn(name) }
363
+ : observation),
364
+ };
293
365
  const agent = buildDriver({
294
366
  onEvent: (event) => onEvent(turnTracker.withTurnId(event)),
295
367
  // 恢复视图只注入主 agent(会话归属者)
296
- sessionMessages: name === this.mainAgentName ? this.sessionMessages : undefined,
368
+ sessionMessages: name === this.mainAgentName
369
+ ? (context.initialSessionMessages() ?? this.sessionMessages)
370
+ : undefined,
297
371
  harness,
372
+ mcpTools,
373
+ skillTool: executionSlotFor(this).skillExecutions?.get(executionId)?.tool,
374
+ discoveryTool: originalHarness?.discoveryTool,
298
375
  });
299
376
  context.registerAgent(name, agent, executionId);
300
377
  return agent;
@@ -342,9 +419,10 @@ export class CoreMindRuntime {
342
419
  }
343
420
  /** 返回交互会话应继承的恢复消息副本。 */
344
421
  initialMessagesFor(name) {
345
- return (name === this.mainAgentName
346
- ? [...(this.sessionMessages ?? [])]
347
- : []);
422
+ const copied = copySessionHistory(executionSlotFor(this).sessionPreviewHistory ?? this.sessionMessages ?? []);
423
+ if (name !== this.mainAgentName)
424
+ copied.length = 0;
425
+ return copied;
348
426
  }
349
427
  /**
350
428
  * 把一轮交互对话作为完整 Run 执行。
@@ -369,13 +447,31 @@ export class CoreMindRuntime {
369
447
  events,
370
448
  signal,
371
449
  }, history, history.length, this.skillsByAgent);
450
+ executionSlotFor(turnRuntime).skills = executionSlotFor(this).skills;
451
+ executionSlotFor(turnRuntime).explicitSessionHistory = history;
452
+ executionSlotFor(turnRuntime).expectedSessionSnapshot =
453
+ historySessionSnapshot(history) ??
454
+ (this.sessionMessages ? historySessionSnapshot(this.sessionMessages) : undefined);
372
455
  const unbindActiveRun = bindActiveRun(this, {
456
+ acceptInputControl: (command) => {
457
+ const context = executionSlotFor(turnRuntime).kernel?.currentContext();
458
+ const inbox = context?.currentControlInbox();
459
+ const runId = context?.currentRunId();
460
+ if (!inbox || !runId) {
461
+ return Promise.reject(new CoreMindError("control_unavailable", "活动 Run 的控制收件箱尚未就绪"));
462
+ }
463
+ return inbox.accept({ schemaVersion: 1, ...command, runId: command.runId ?? runId });
464
+ },
373
465
  inspectProjection: () => turnRuntime.inspectPersistedRunProjection(),
374
466
  executeDelegation: (parentAgentName, rawArgs, callId) => turnRuntime.executeConfiguredDelegation(parentAgentName, rawArgs, callId),
375
467
  executeDelegationDisposition: (parentAgentName, rawArgs, callId) => turnRuntime.executeConfiguredDelegationDisposition(parentAgentName, rawArgs, callId),
376
468
  });
377
469
  try {
378
- return await turnRuntime.run();
470
+ const result = await turnRuntime.run();
471
+ const preview = executionSlotFor(turnRuntime).sessionPreviewHistory;
472
+ if (preview)
473
+ executionSlotFor(this).sessionPreviewHistory = copySessionHistory(preview);
474
+ return result;
379
475
  }
380
476
  finally {
381
477
  unbindActiveRun();
@@ -405,7 +501,9 @@ export class CoreMindRuntime {
405
501
  throw new CoreMindError("concurrent_run", "同一 Runtime 不支持并发执行");
406
502
  }
407
503
  slot.running = true;
408
- slot.kernel ??= new RunKernel({ execute: (context) => this.executeRunBody(context) });
504
+ slot.kernel ??= new RunKernel({
505
+ execute: (context) => executeWithSessionLease(this, this.options, this.config, context, (ownership) => this.executeRunBody(context, ownership)),
506
+ });
409
507
  try {
410
508
  return await slot.kernel.run();
411
509
  }
@@ -458,6 +556,8 @@ export class CoreMindRuntime {
458
556
  }),
459
557
  enforceRuntimeBudget: true,
460
558
  enforceDelegatedToolBoundary: true,
559
+ trustedSkillLoader: this.toolCapabilitiesByAgent.get(this.mainAgentName)?.get(SKILL_TOOL_NAME) ===
560
+ SKILL_TOOL_CAPABILITY,
461
561
  });
462
562
  }
463
563
  runtimeAuthorityToolIds() {
@@ -566,14 +666,15 @@ export class CoreMindRuntime {
566
666
  if (!target) {
567
667
  throw new CoreMindError("child_run_policy_escalation", `委派目标 Agent ${authority.request.agentName} 不存在`);
568
668
  }
569
- const { workflow: _workflow, loop: _loop, ...baseConfig } = this.config;
669
+ const { workflow: _workflow, loop: _loop, mcp: _mcp, ...baseConfig } = this.config;
570
670
  const childAgents = structuredClone(this.config.agents);
571
671
  for (const agent of Object.values(childAgents)) {
572
672
  if (agent.tools)
573
673
  agent.tools = agent.tools.filter(isDelegatedBuiltinToolConfig);
674
+ delete agent.mcpResources;
574
675
  }
575
676
  childAgents[authority.request.agentName] = {
576
- ...target,
677
+ ...childAgents[authority.request.agentName],
577
678
  ...(target.tools ? { tools: target.tools.filter(isDelegatedBuiltinToolConfig) } : {}),
578
679
  model: authority.request.model.model,
579
680
  options: authority.request.model.options,
@@ -606,11 +707,12 @@ export class CoreMindRuntime {
606
707
  events: this.options.events,
607
708
  trace: this.options.trace,
608
709
  approveTool: this.options.approveTool,
710
+ approveProjectCode: this.options.approveProjectCode,
609
711
  runStore,
610
712
  runId: authority.childRunId,
611
713
  childRunAuthority: authority,
612
714
  signal: authority.signal,
613
- }, this.workspaceLeaseService);
715
+ }, this.workspaceLeaseService, executionSlotFor(this).skills);
614
716
  },
615
717
  }),
616
718
  };
@@ -745,8 +847,16 @@ export class CoreMindRuntime {
745
847
  throw new CoreMindError("child_run_policy_escalation", `Agent ${parentAgentName} 未获准委派给 ${args.target}`);
746
848
  }
747
849
  const parentTools = new Set(this.toolCapabilitiesByAgent.get(parentAgentName)?.keys() ?? []);
850
+ const targetAgent = this.agentConfigs.get(args.target);
851
+ const configuredTools = (targetAgent?.tools?.length ?? 0) > 0 ? targetAgent.tools : (this.config.tools ?? []);
852
+ if (configuredTools.some((tool) => "mcp" in tool) || targetAgent?.mcpResources !== undefined) {
853
+ throw new CoreMindError("child_run_policy_escalation", "Child Run 不继承宿主本地服务、工具或凭据");
854
+ }
748
855
  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));
856
+ const frozenSkillAuthority = needsFrozenSkillAuthority(this.config.agents, executionSlotFor(this).skills, args.target);
857
+ if (frozenSkillAuthority)
858
+ targetTools.push(SKILL_TOOL_NAME);
859
+ const expandedTools = targetTools.filter((tool) => !parentTools.has(tool) && !(frozenSkillAuthority && tool === SKILL_TOOL_NAME));
750
860
  if (expandedTools.length > 0) {
751
861
  throw new CoreMindError("child_run_policy_escalation", `Delegation Target ${args.target} 的工具超出父 Agent authority:${expandedTools.join("、")}`);
752
862
  }
@@ -758,7 +868,7 @@ export class CoreMindRuntime {
758
868
  };
759
869
  }
760
870
  /** run() 主体(并发检测由外层 run() 包装) */
761
- async executeRunBody(context) {
871
+ async executeRunBody(context, ownership) {
762
872
  context.attachExecutionEnvironment(this.executionEnvironment);
763
873
  const started = performance.now();
764
874
  const lifecycleHost = this.options.lifecycleExtensions
@@ -776,20 +886,35 @@ export class CoreMindRuntime {
776
886
  let canonicalSessionBranch = [];
777
887
  let previousContextCompactions = [];
778
888
  if (this.options.sessionId && this.config.session?.enabled) {
779
- const session = await CoreMindSession.open({
889
+ const session = await openWritableSession({
780
890
  dir: sessionDir(this.config, this.options.configDir),
781
891
  sessionId: this.options.sessionId,
782
892
  cwd: this.options.cwd ?? process.cwd(),
783
- });
893
+ }, ownership.lease);
784
894
  const sessionEntries = await session.branchEntries();
785
895
  sessionSeqStart = sessionEntries.reduce((max, entry) => Math.max(max, entry.seq), 0);
786
- context.attachSession(session, projectBranchMessages(sessionEntries));
896
+ const slot = executionSlotFor(this);
897
+ if (slot.explicitSessionHistory !== undefined &&
898
+ slot.expectedSessionSnapshot !== sessionSnapshot(session)) {
899
+ throw new CoreMindError("session_snapshot_stale", "会话已被其他运行修改,请重新打开交互历史");
900
+ }
901
+ const branch = projectBranchMessages(sessionEntries);
902
+ context.attachSession(session, branch, slot.explicitSessionHistory ?? branch.map((item) => item.message));
787
903
  canonicalSessionBranch = projectRawBranchMessages(sessionEntries);
788
904
  previousContextCompactions = projectContextCompactionLedger(sessionEntries);
789
905
  }
790
906
  const resumeRecords = this.options.resumeRunId
791
907
  ? await runStore.read(this.options.resumeRunId)
792
908
  : undefined;
909
+ const skillSnapshot = executionSlotFor(this).skills;
910
+ if (resumeRecords &&
911
+ restoreSkillSnapshot(resumeRecords, this.config.agents)?.sha256 !== skillSnapshot?.sha256) {
912
+ throw new CoreMindError("context_capability_conflict", "原技能快照在恢复准入前已变化");
913
+ }
914
+ executionSlotFor(this).skillExecutions = skillSnapshot ? new Map() : undefined;
915
+ const skillFactDurability = runStore.supportedDurability?.includes("critical")
916
+ ? "critical"
917
+ : "ordinary";
793
918
  let deferredTerminalError = restoreDeferredTerminalError(resumeRecords);
794
919
  const canRestoreChildRuns = this.options.childRuns !== undefined ||
795
920
  [...this.agentConfigs.values()].some((agent) => agent.delegation && Object.keys(agent.delegation.targets).length > 0);
@@ -811,6 +936,16 @@ export class CoreMindRuntime {
811
936
  }
812
937
  // 预生成 runId(D-1):resume 时以恢复记录为准,否则优先使用调用方预生成值
813
938
  const runId = (resumePlan?.runId ?? this.options.runId ?? randomUUID());
939
+ const admission = resumeRecords?.at(-1);
940
+ // 当前 Worker 的明确 resume 准入不取代它刚验证过的暂停绑定。
941
+ const discoveryResumeRecords = admission?.kind === "admission" &&
942
+ this.options.protocolStart?.method === "resume" &&
943
+ fingerprintEffectReceiptValue(admission.payload.protocolStart) === fingerprintEffectReceiptValue(this.options.protocolStart)
944
+ ? resumeRecords.slice(0, -1)
945
+ : (resumeRecords ?? []);
946
+ const discoveryContinuations = restoreToolDiscoveryContinuations(discoveryResumeRecords, runId);
947
+ const consumedDiscoveryContinuations = new Set();
948
+ const liveDiscoveryExecutions = new Map();
814
949
  context.attachRunId(runId);
815
950
  const effectiveInitialPrompt = resumePlan?.initialPrompt ?? this.options.initialPrompt;
816
951
  const admissionRecords = !resumePlan && this.options.protocolStart ? await runStore.read(runId) : [];
@@ -852,7 +987,7 @@ export class CoreMindRuntime {
852
987
  });
853
988
  }
854
989
  else {
855
- await journal.start({
990
+ await journal.appendFact("start", {
856
991
  configName: this.config.name,
857
992
  schemaVersion: this.config.schemaVersion,
858
993
  configFingerprint,
@@ -864,7 +999,8 @@ export class CoreMindRuntime {
864
999
  operationId: operation.snapshot().operationId,
865
1000
  telemetry: telemetryConfiguration,
866
1001
  ...(this.options.protocolStart ? { protocolStart: this.options.protocolStart } : {}),
867
- });
1002
+ ...(skillSnapshot ? { skillSnapshot } : {}),
1003
+ }, { durability: skillSnapshot ? skillFactDurability : "ordinary" });
868
1004
  }
869
1005
  for (const consent of telemetryConsents) {
870
1006
  validateTelemetryConsentBinding(consent, await runStore.read(runId));
@@ -900,40 +1036,58 @@ export class CoreMindRuntime {
900
1036
  applyPending: () => context.currentControlInbox().applyPending("verification"),
901
1037
  })
902
1038
  : 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
1039
  const capabilityByCallId = new Map();
1040
+ const skillLoadsByCall = new Map();
1041
+ const discoverySearchesByCall = new Map();
1042
+ const discoveryGenerations = new Map();
1043
+ const userEvents = this.options.events ?? (() => { });
922
1044
  const trace = new TraceRecorder(runId, (entry) => {
923
1045
  const toolResultCallId = entry.event.type === "tool_result" ? entry.event.callId : undefined;
924
1046
  const pendingProtocolToolResult = toolResultCallId
925
1047
  ? executionSlotFor(this).protocolToolResultFacts?.get(protocolToolResultKey(entry.runId, toolResultCallId))
926
1048
  : undefined;
927
- const payload = pendingProtocolToolResult
928
- ? {
929
- ...entry,
930
- protocolToolResult: structuredClone(pendingProtocolToolResult.fact),
931
- }
932
- : entry;
1049
+ const skillCallKey = toolResultCallId && entry.event.type === "tool_result"
1050
+ ? toolCapabilityCallKey(entry.event.agent, entry.event.stepId, toolResultCallId)
1051
+ : undefined;
1052
+ const skillLoad = skillCallKey ? skillLoadsByCall.get(skillCallKey) : undefined;
1053
+ const discoverySearch = skillCallKey
1054
+ ? discoverySearchesByCall.get(skillCallKey)
1055
+ : undefined;
1056
+ const discoveryGeneration = entry.event.type === "context_prefix" && entry.event.toolDiscovery
1057
+ ? discoveryGenerations.get(entry.event.toolDiscovery.selectionFingerprint)
1058
+ : undefined;
1059
+ const payload = {
1060
+ ...entry,
1061
+ ...(pendingProtocolToolResult
1062
+ ? { protocolToolResult: structuredClone(pendingProtocolToolResult.fact) }
1063
+ : {}),
1064
+ ...(skillLoad ? { skillLoad } : {}),
1065
+ ...(discoverySearch ? { toolDiscoverySearch: discoverySearch.fact } : {}),
1066
+ ...(discoveryGeneration
1067
+ ? {
1068
+ ...(discoveryGeneration.prepared.catalog
1069
+ ? { toolDiscoveryCatalog: discoveryGeneration.prepared.catalog }
1070
+ : {}),
1071
+ toolDiscoverySelection: discoveryGeneration.prepared.selection,
1072
+ }
1073
+ : {}),
1074
+ };
1075
+ if (skillCallKey)
1076
+ skillLoadsByCall.delete(skillCallKey);
933
1077
  const persisted = journal.appendFact("event", payload, {
934
- durability: traceFactDurability(entry.event, capabilityByCallId),
1078
+ durability: discoverySearch || discoveryGeneration
1079
+ ? "critical"
1080
+ : skillLoad
1081
+ ? skillFactDurability
1082
+ : traceFactDurability(entry.event, capabilityByCallId),
935
1083
  eventId: entry.eventId,
936
1084
  });
1085
+ if (discoveryGeneration)
1086
+ discoveryGeneration.receipt = persisted;
1087
+ if (discoverySearch) {
1088
+ discoverySearchesByCall.delete(skillCallKey);
1089
+ void persisted.then(() => discoverySearch.durable.push(discoverySearch.fact), () => { });
1090
+ }
937
1091
  if (pendingProtocolToolResult) {
938
1092
  pendingProtocolToolResult.appendStarted = true;
939
1093
  void persisted
@@ -945,11 +1099,14 @@ export class CoreMindRuntime {
945
1099
  facts.delete(key);
946
1100
  });
947
1101
  }
948
- this.options.trace?.(entry);
1102
+ this.options.trace?.(structuredClone(entry));
1103
+ const callbackEntry = structuredClone(entry);
1104
+ userEvents(callbackEntry.event, callbackEntry);
949
1105
  }, resumePlan?.previousTrace);
950
1106
  const collected = resumePlan?.previousTrace.map((entry) => entry.event) ?? [];
1107
+ // 历史拒绝保留审计与预算,但不决定本次恢复执行的终态。
1108
+ const terminalEventCursor = collected.length;
951
1109
  const toolReplayCandidates = [...(resumePlan?.toolReplayCandidates ?? [])];
952
- const userEvents = this.options.events ?? (() => { });
953
1110
  const turnTracker = new TurnTracker();
954
1111
  const effectBindingByCall = new Map();
955
1112
  const effectBindingByReceipt = new Map();
@@ -963,15 +1120,82 @@ export class CoreMindRuntime {
963
1120
  const existingInputState = inputId === undefined ? undefined : receiptStatusOf(collected, inputId);
964
1121
  let inputReceiptState = existingInputState ?? (inputId === undefined ? undefined : "pending");
965
1122
  let onToolResultRecorded;
966
- const lifecycleFinalizers = new Set();
1123
+ const lifecycleFinalizers = new Map();
1124
+ const immediateToolRejections = new Map();
1125
+ const mcpAuthorizations = new Map();
1126
+ const bindMcpArguments = (agent, tool, args) => {
1127
+ const authorization = mcpAuthorizations.get(JSON.stringify([agent, tool]));
1128
+ return authorization ? { mcp: authorization, arguments: args } : args;
1129
+ };
967
1130
  let lifecycleFailure;
968
1131
  const emitInputEvent = (event) => {
969
1132
  collected.push(event);
970
1133
  trace.record(event);
971
- userEvents(event);
972
1134
  };
1135
+ const prepareControlInput = (command) => {
1136
+ const id = controlInputId(runId, command.controlId);
1137
+ if (receiptStatusOf(collected, id) === undefined) {
1138
+ emitInputEvent(createInputReceipt({
1139
+ inputId: id,
1140
+ contentFingerprint: inputFingerprint(command.message),
1141
+ }));
1142
+ }
1143
+ return id;
1144
+ };
1145
+ context.attachControlInbox(new ControlInbox({
1146
+ runId,
1147
+ journal,
1148
+ records: await runStore.read(runId),
1149
+ apply: (command) => {
1150
+ if (command.type === "verification") {
1151
+ return Promise.resolve(hostVerification?.apply(command) ?? {
1152
+ status: "rejected",
1153
+ reason: "当前 Run 未启用宿主验证",
1154
+ });
1155
+ }
1156
+ if (command.type === "steering" || command.type === "follow_up") {
1157
+ const id = prepareControlInput(command);
1158
+ if (hostVerification?.waiting) {
1159
+ const state = receiptStatusOf(collected, id);
1160
+ if (state === "pending" || state === "claimed")
1161
+ emitInputEvent(discardInput({ inputId: id }));
1162
+ return Promise.resolve({
1163
+ status: "rejected",
1164
+ reason: "宿主验收期间不能改变候选输入",
1165
+ });
1166
+ }
1167
+ }
1168
+ return this.applyRunControl(command, context, deferredTerminalError);
1169
+ },
1170
+ }));
1171
+ // applied 与内存交付间可能中断;没有消费事实时只明确丢弃,不能自动重投。
1172
+ const previousInputControls = new Map();
1173
+ const previouslyApplied = new Set();
1174
+ for (const record of resumeRecords ?? []) {
1175
+ if (record.kind !== "control")
1176
+ continue;
1177
+ const fact = record.payload;
1178
+ if (fact.command?.type === "steering" || fact.command?.type === "follow_up")
1179
+ previousInputControls.set(fact.controlId, fact.command);
1180
+ if (fact.state === "applied")
1181
+ previouslyApplied.add(fact.controlId);
1182
+ }
1183
+ for (const id of previouslyApplied) {
1184
+ const command = previousInputControls.get(id);
1185
+ if (!command)
1186
+ continue;
1187
+ const input = prepareControlInput(command);
1188
+ if (receiptStatusOf(collected, input) === "pending")
1189
+ emitInputEvent(discardInput({ inputId: input }));
1190
+ }
973
1191
  const recordEvent = (event) => {
974
1192
  let enriched = turnTracker.withTurnId(event);
1193
+ if (enriched.type === "tool_call") {
1194
+ enriched = {
1195
+ ...enriched,
1196
+ args: bindMcpArguments(enriched.agent, enriched.tool, enriched.args),
1197
+ };
1198
+ }
975
1199
  if ((enriched.type === "tool_result" || enriched.type === "tool_lifecycle") &&
976
1200
  enriched.callId) {
977
1201
  const call = effectBindingByCall.get(toolCapabilityCallKey(enriched.agent, enriched.stepId, enriched.callId));
@@ -979,6 +1203,17 @@ export class CoreMindRuntime {
979
1203
  enriched = { ...enriched, turnId: call.turnId };
980
1204
  }
981
1205
  if (enriched.type === "tool_call" && enriched.callId && enriched.turnId) {
1206
+ const callKey = toolCapabilityCallKey(enriched.agent, enriched.stepId, enriched.callId);
1207
+ if (effectBindingByCall.has(callKey) ||
1208
+ resumePlan?.previousTrace.some(({ event: previous }) => previous.type === "tool_call" &&
1209
+ previous.callId !== undefined &&
1210
+ toolCapabilityCallKey(previous.agent, previous.stepId, previous.callId) === callKey)) {
1211
+ // 不覆盖首次冻结事实;取消分界后的重复输入保持原取消语义。
1212
+ lifecycleFailure = journal.isAborted()
1213
+ ? new CoreMindError("aborted", "运行已中止,拒绝重复工具调用")
1214
+ : new CoreMindError("effect_receipt_conflict", "工具 Call 身份重复,已拒绝后续调用");
1215
+ throw lifecycleFailure;
1216
+ }
982
1217
  context.recordToolCall({
983
1218
  agent: enriched.agent,
984
1219
  callId: enriched.callId,
@@ -1029,8 +1264,9 @@ export class CoreMindRuntime {
1029
1264
  throw new CoreMindError("redaction_failed", "步骤输出包含凭据,已阻止持久化与候选验收");
1030
1265
  }
1031
1266
  collected.push(enriched);
1032
- trace.record(enriched);
1033
- userEvents(enriched);
1267
+ trace.record(enriched, enriched.type === "context_prefix" && enriched.toolDiscovery
1268
+ ? discoveryGenerations.get(enriched.toolDiscovery.selectionFingerprint)?.prepared.eventId
1269
+ : undefined);
1034
1270
  if (enriched.type === "tool_result")
1035
1271
  onToolResultRecorded?.(enriched);
1036
1272
  // 输入被首个 Turn 认领(规格 03 §4:claim 绑定 TurnId;resume 时已 claimed 不再重复);
@@ -1114,35 +1350,39 @@ export class CoreMindRuntime {
1114
1350
  const recorded = toolExecutionEngine.inspect({
1115
1351
  ...toolCallIdentity(event.agent, event.stepId, event.callId),
1116
1352
  });
1117
- if (!recorded || recorded.tool !== event.tool)
1353
+ const identity = toolCallIdentity(event.agent, event.stepId, event.callId);
1354
+ const callKey = toolCapabilityCallKey(event.agent, event.stepId, event.callId);
1355
+ if ((!recorded || recorded.tool !== event.tool) && !immediateToolRejections.has(callKey))
1118
1356
  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;
1357
+ // 仍在结果事件之后的微任务提交;宿主准备只等待同一个 Call 的结果屏障。
1358
+ const finalizer = Promise.resolve().then(async () => {
1359
+ try {
1360
+ await immediateToolRejections.get(callKey);
1361
+ await journal.flush();
1362
+ await toolExecutionEngine.finalizeResult(identity);
1363
+ await releaseWorkspaceLease(identity);
1364
+ }
1365
+ catch (error) {
1366
+ const failure = error instanceof CoreMindError
1367
+ ? error
1368
+ : new CoreMindError("durability_barrier_failed", error instanceof Error ? error.message : String(error));
1369
+ if (toolExecutionEngine.inspect(identity)?.currentPhase === "observed") {
1370
+ await toolExecutionEngine.failResultDurability(identity, failure.message);
1135
1371
  }
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));
1372
+ throw failure;
1373
+ }
1374
+ });
1375
+ lifecycleFinalizers.set(callKey, finalizer);
1376
+ void finalizer
1377
+ .catch((error) => {
1378
+ lifecycleFailure =
1379
+ error instanceof CoreMindError
1380
+ ? error
1381
+ : new CoreMindError("tool_lifecycle_invalid", error instanceof Error ? error.message : String(error));
1382
+ })
1383
+ .finally(() => {
1384
+ if (lifecycleFinalizers.get(callKey) === finalizer)
1385
+ lifecycleFinalizers.delete(callKey);
1146
1386
  });
1147
1387
  };
1148
1388
  const dispatchLifecycle = async (lifecycle, payload) => {
@@ -1238,6 +1478,19 @@ export class CoreMindRuntime {
1238
1478
  if (gate?.status === "propagate_terminal")
1239
1479
  throw propagatedChildRunError(gate.result);
1240
1480
  };
1481
+ const mcpRun = this.config.mcp
1482
+ ? createMcpRun({
1483
+ config: this.config,
1484
+ configDir: this.options.configDir,
1485
+ cwd: this.options.cwd ?? process.cwd(),
1486
+ env: this.options.toolEnv ?? this.options.env ?? process.env,
1487
+ secretResolver: this.options.secretResolver,
1488
+ mcpAuthentication: this.options.mcpAuthentication,
1489
+ environment: this.executionEnvironment,
1490
+ signal: this.options.signal,
1491
+ artifactStore: new ArtifactStore({ cwd: this.options.cwd ?? process.cwd() }),
1492
+ })
1493
+ : undefined;
1241
1494
  const persistContextCompaction = async (preparation, sourceMessages, originalMessageCount) => {
1242
1495
  const compaction = preparation.compaction;
1243
1496
  if (!compaction)
@@ -1297,6 +1550,8 @@ export class CoreMindRuntime {
1297
1550
  approvalId: request.approvalId,
1298
1551
  runId: request.runId,
1299
1552
  agent: request.agent,
1553
+ ...(request.callId === undefined ? {} : { callId: request.callId }),
1554
+ ...(request.stepId === undefined ? {} : { stepId: request.stepId }),
1300
1555
  tool: request.tool,
1301
1556
  args: request.args,
1302
1557
  argumentsFingerprint: request.argumentsFingerprint,
@@ -1318,15 +1573,59 @@ export class CoreMindRuntime {
1318
1573
  const activeRunContext = context;
1319
1574
  context.setHarnessFactory((agentName, stepId, executionId) => {
1320
1575
  const agentModel = this.agentModels.get(agentName) ?? this.providerRuntime.model;
1576
+ const skillExecution = skillSnapshot?.agents[agentName]?.standard.length
1577
+ ? new SkillExecution(skillSnapshot, agentName, resumeRecords, stepId)
1578
+ : undefined;
1579
+ if (skillExecution)
1580
+ executionSlotFor(this).skillExecutions.set(executionId, skillExecution);
1321
1581
  let contextWorkingSet;
1322
1582
  let providerRequestOrdinal = 0;
1323
1583
  let pendingProviderCapabilityFingerprint;
1324
- return {
1584
+ const executionEffects = new Map(this.toolEffectsByAgent.get(agentName));
1585
+ const executionCapabilities = new Map(this.toolCapabilitiesByAgent.get(agentName));
1586
+ const effectiveTools = this.agentConfigs.get(agentName)?.tools?.length
1587
+ ? this.agentConfigs.get(agentName).tools
1588
+ : (this.config.tools ?? []);
1589
+ const discoveryEnabled = effectiveTools.some((tool) => tool.exposure === "deferred");
1590
+ if (discoveryEnabled && !runStore.supportedDurability?.includes("critical")) {
1591
+ throw new CoreMindError("durability_unsupported", "工具发现需要支持 critical 确认的 RunStore");
1592
+ }
1593
+ let discovery;
1594
+ let initialDiscovery;
1595
+ const durableSearches = [];
1596
+ const discoveryBindings = new Map();
1597
+ const toolSources = new Map();
1598
+ const withdrawnSources = new Set();
1599
+ const adapterSelection = (selection) => Object.freeze({
1600
+ names: [...selection.names, DISCOVER_TOOLS_NAME],
1601
+ generation: selection.generation,
1602
+ fingerprint: selection.fingerprint,
1603
+ });
1604
+ const discoverySummary = (selection) => ({
1605
+ version: 1,
1606
+ catalogFingerprint: selection.catalogFingerprint,
1607
+ generation: selection.generation,
1608
+ selectionFingerprint: selection.fingerprint,
1609
+ toolCount: selection.names.length + 1,
1610
+ });
1611
+ const checkDiscoveryCall = (tool, callId) => {
1612
+ if (!discovery || tool === DISCOVER_TOOLS_NAME)
1613
+ return;
1614
+ const binding = discovery.assertCallable(tool, discoveryBindings.get(callId));
1615
+ discoveryBindings.set(callId, binding);
1616
+ };
1617
+ const harness = {
1325
1618
  maxRetries: loop ? 0 : limits.maxRetries,
1326
1619
  registerContextContract: (contract) => contextContracts.set(executionId, contract),
1327
1620
  beforeModelRequest: () => {
1621
+ const facts = journal.factStatus();
1622
+ if (facts.state === "poisoned") {
1623
+ throw new CoreMindError("fact_ledger_poisoned", `事实账本已失效,不能继续模型请求:${facts.reason}`);
1624
+ }
1328
1625
  throwIfContextFailed();
1329
1626
  throwIfDelegationBlocksModel();
1627
+ for (const name of discovery?.current?.names ?? [])
1628
+ discovery.assertCallable(name);
1330
1629
  budget.beforeModelRequest();
1331
1630
  },
1332
1631
  onModelRequestDispatched: ({ providerId, modelId, messages }) => {
@@ -1339,8 +1638,11 @@ export class CoreMindRuntime {
1339
1638
  type: "provider_request",
1340
1639
  agent: agentName,
1341
1640
  ...(stepId ? { stepId } : {}),
1641
+ ...(discovery?.current ? { toolDiscovery: discoverySummary(discovery.current) } : {}),
1342
1642
  ...createProviderRequestReplayFact({
1343
- requestId: `${agentName}:${stepId ?? "default"}:${providerRequestOrdinal}`,
1643
+ requestId: discovery
1644
+ ? `${discovery.catalog.owner.executionId}:${providerRequestOrdinal}`
1645
+ : `${agentName}:${stepId ?? "default"}:${providerRequestOrdinal}`,
1344
1646
  providerId,
1345
1647
  modelId,
1346
1648
  messages,
@@ -1354,7 +1656,10 @@ export class CoreMindRuntime {
1354
1656
  throwIfContextFailed,
1355
1657
  executeTool: async ({ call, invoke }) => {
1356
1658
  try {
1357
- return await toolExecutionEngine.executeAdapter(toolCallIdentity(agentName, stepId, call.callId), invoke);
1659
+ return await toolExecutionEngine.executeAdapter(toolCallIdentity(agentName, stepId, call.callId), () => {
1660
+ checkDiscoveryCall(call.tool, call.callId);
1661
+ return invoke();
1662
+ });
1358
1663
  }
1359
1664
  catch (error) {
1360
1665
  const normalized = normalizeExecutionError(error);
@@ -1368,7 +1673,7 @@ export class CoreMindRuntime {
1368
1673
  if (contextFailure)
1369
1674
  return messages;
1370
1675
  while (lifecycleFinalizers.size > 0) {
1371
- await Promise.allSettled([...lifecycleFinalizers]);
1676
+ await Promise.allSettled([...lifecycleFinalizers.values()]);
1372
1677
  }
1373
1678
  if (lifecycleFailure)
1374
1679
  throw lifecycleFailure;
@@ -1390,7 +1695,9 @@ export class CoreMindRuntime {
1390
1695
  const canonicalMessages = context.sessionHandle()
1391
1696
  ? [
1392
1697
  ...canonicalSessionBranch.map((item) => item.message),
1393
- ...messages.slice(context.compactedPrefixEnd() ?? this.resumedContextLength),
1698
+ ...messages.slice(context.compactedPrefixEnd() ??
1699
+ context.initialSessionLength() ??
1700
+ this.resumedContextLength),
1394
1701
  ]
1395
1702
  : messages;
1396
1703
  const taskState = projectContextTaskState({
@@ -1463,6 +1770,7 @@ export class CoreMindRuntime {
1463
1770
  sourceLength: messages.length,
1464
1771
  messages: [...preparation.workingSet.messages],
1465
1772
  };
1773
+ skillExecution?.refresh(preparation.workingSet.messages);
1466
1774
  pendingProviderCapabilityFingerprint = preparation.capability.configFingerprint;
1467
1775
  if (preparation.compaction) {
1468
1776
  emit({
@@ -1490,9 +1798,17 @@ export class CoreMindRuntime {
1490
1798
  return messages;
1491
1799
  }
1492
1800
  },
1493
- beforeToolCall: async (context, signal) => {
1801
+ beforeToolCall: async (driverContext, signal) => {
1802
+ const context = {
1803
+ ...driverContext,
1804
+ toolCall: {
1805
+ ...driverContext.toolCall,
1806
+ args: bindMcpArguments(agentName, driverContext.toolCall.tool, driverContext.toolCall.args),
1807
+ },
1808
+ };
1494
1809
  const lifecycleIdentity = toolCallIdentity(agentName, stepId, context.toolCall.callId);
1495
1810
  const callKey = toolCapabilityCallKey(agentName, stepId, context.toolCall.callId);
1811
+ checkDiscoveryCall(context.toolCall.tool, context.toolCall.callId);
1496
1812
  const argumentsFingerprint = fingerprintEffectReceiptValue(context.toolCall.args);
1497
1813
  const replayCandidateIndex = toolReplayCandidates.findIndex((candidate) => candidate.agent === agentName &&
1498
1814
  candidate.stepId === stepId &&
@@ -1527,7 +1843,7 @@ export class CoreMindRuntime {
1527
1843
  let capability = existingCapability?.capability;
1528
1844
  if (!existingCapability) {
1529
1845
  capability =
1530
- this.toolCapabilitiesByAgent.get(agentName)?.get(context.toolCall.tool) ??
1846
+ executionCapabilities.get(context.toolCall.tool) ??
1531
1847
  resolveToolCapability({ tool: context.toolCall.tool });
1532
1848
  capabilityByCallId.set(callKey, {
1533
1849
  tool: context.toolCall.tool,
@@ -1635,7 +1951,7 @@ export class CoreMindRuntime {
1635
1951
  return { block: true, reason: delegationPolicyFailure.message, terminate: true };
1636
1952
  }
1637
1953
  }
1638
- const decision = await policy.authorize(agentName, context.toolCall.tool, authorizationArgs, resolvedCapability, this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.tool), delegationInputFingerprint);
1954
+ const decision = await policy.authorize(agentName, context.toolCall.tool, authorizationArgs, resolvedCapability, executionEffects.get(context.toolCall.tool), delegationInputFingerprint, { callId: context.toolCall.callId, ...(stepId ? { stepId } : {}) });
1639
1955
  await toolExecutionEngine.advance(lifecycleIdentity, {
1640
1956
  phase: "policy_resolved",
1641
1957
  status: "completed",
@@ -1722,7 +2038,7 @@ export class CoreMindRuntime {
1722
2038
  await toolExecutionEngine.advance(lifecycleIdentity, {
1723
2039
  phase: "lease_acquired",
1724
2040
  status: "skipped",
1725
- reason: "Pure Local Read 不需要 Workspace Lease",
2041
+ reason: "该工具声明允许并行执行,不需要 Workspace Lease",
1726
2042
  });
1727
2043
  }
1728
2044
  else {
@@ -1803,8 +2119,7 @@ export class CoreMindRuntime {
1803
2119
  toolCallId: context.toolCall.callId,
1804
2120
  idempotencyKey,
1805
2121
  capability: resolvedCapability,
1806
- pathFields: this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.tool)
1807
- ?.pathFields,
2122
+ pathFields: executionEffects.get(context.toolCall.tool)?.pathFields,
1808
2123
  });
1809
2124
  if (checkpoints.length > 0) {
1810
2125
  checkpointByCallId.set(callKey, checkpoints.map((checkpoint) => checkpoint.checkpointId));
@@ -1849,6 +2164,15 @@ export class CoreMindRuntime {
1849
2164
  await rollbackWorkspaceLease(lifecycleIdentity);
1850
2165
  return { block: true, reason: checkpointFailure.message };
1851
2166
  }
2167
+ try {
2168
+ checkDiscoveryCall(context.toolCall.tool, context.toolCall.callId);
2169
+ }
2170
+ catch (error) {
2171
+ capabilityFailure = normalizeExecutionError(error);
2172
+ await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, capabilityFailure.message);
2173
+ await rollbackWorkspaceLease(lifecycleIdentity);
2174
+ return { block: true, reason: capabilityFailure.message };
2175
+ }
1852
2176
  effectCoordinator.markStarted(stepId, context.toolCall.callId, context.toolCall.tool);
1853
2177
  if (resolvedCapability.durability === "critical") {
1854
2178
  try {
@@ -1889,7 +2213,14 @@ export class CoreMindRuntime {
1889
2213
  });
1890
2214
  return undefined;
1891
2215
  },
1892
- afterToolCall: async (context) => {
2216
+ afterToolCall: async (driverContext) => {
2217
+ const context = {
2218
+ ...driverContext,
2219
+ toolCall: {
2220
+ ...driverContext.toolCall,
2221
+ args: bindMcpArguments(agentName, driverContext.toolCall.tool, driverContext.toolCall.args),
2222
+ },
2223
+ };
1893
2224
  const lifecycleIdentity = toolCallIdentity(agentName, stepId, context.toolCall.callId);
1894
2225
  const capability = capabilityByCallId.get(toolCapabilityCallKey(agentName, stepId, context.toolCall.callId))?.capability;
1895
2226
  await toolExecutionEngine.advance(lifecycleIdentity, {
@@ -1925,6 +2256,8 @@ export class CoreMindRuntime {
1925
2256
  runContextFor(this).recordArtifact(artifact);
1926
2257
  emit({
1927
2258
  type: "artifact_created",
2259
+ agent: agentName,
2260
+ ...(stepId ? { stepId } : {}),
1928
2261
  artifactId: artifact.artifactId,
1929
2262
  status: artifact.status,
1930
2263
  sizeBytes: artifact.sizeBytes,
@@ -1981,6 +2314,82 @@ export class CoreMindRuntime {
1981
2314
  }
1982
2315
  },
1983
2316
  onObservation: (observation) => {
2317
+ let immediateRejection;
2318
+ if (observation.type === "tool_execution_start" &&
2319
+ discovery &&
2320
+ observation.call.tool !== DISCOVER_TOOLS_NAME) {
2321
+ try {
2322
+ discovery.assertCallable(observation.call.tool);
2323
+ }
2324
+ catch {
2325
+ immediateRejection = "工具不在当前已声明集合";
2326
+ }
2327
+ }
2328
+ if (observation.type === "tool_execution_end" && observation.isError) {
2329
+ const call = observation.call;
2330
+ const key = toolCapabilityCallKey(agentName, stepId, call.callId);
2331
+ const binding = effectBindingByCall.get(key);
2332
+ // 已冻结真实 start,且从未准入的参数拒绝也必须形成完整的未执行收据。
2333
+ if (binding?.tool === call.tool &&
2334
+ !capabilityByCallId.has(key) &&
2335
+ !toolExecutionEngine.inspect(toolCallIdentity(agentName, stepId, call.callId)) &&
2336
+ !immediateToolRejections.has(key)) {
2337
+ immediateRejection = "工具在执行准入前被拒绝";
2338
+ }
2339
+ }
2340
+ if (immediateRejection !== undefined &&
2341
+ (observation.type === "tool_execution_start" ||
2342
+ observation.type === "tool_execution_end")) {
2343
+ const call = observation.call;
2344
+ const key = toolCapabilityCallKey(agentName, stepId, call.callId);
2345
+ const capability = executionCapabilities.get(call.tool) ?? resolveToolCapability({ tool: call.tool });
2346
+ const previous = capabilityByCallId.get(key);
2347
+ if (previous && previous.tool !== call.tool) {
2348
+ throw new CoreMindError("tool_capability_conflict", "同一 Call 不得更换工具身份");
2349
+ }
2350
+ capabilityByCallId.set(key, { tool: call.tool, capability });
2351
+ emit({
2352
+ type: "capability_resolved",
2353
+ agent: agentName,
2354
+ tool: call.tool,
2355
+ callId: call.callId,
2356
+ ...(stepId ? { stepId } : {}),
2357
+ capability,
2358
+ recoveryDisposition: recoveryDispositionFor(capability),
2359
+ });
2360
+ const identity = toolCallIdentity(agentName, stepId, call.callId);
2361
+ const reason = immediateRejection;
2362
+ const rejection = toolExecutionEngine
2363
+ .recordCall({ ...identity, tool: call.tool })
2364
+ .then(() => toolExecutionEngine.blockBeforeExecution(identity, reason));
2365
+ immediateToolRejections.set(key, rejection);
2366
+ void rejection.catch((error) => {
2367
+ lifecycleFailure = normalizeExecutionError(error);
2368
+ });
2369
+ }
2370
+ if (observation.type === "control_consumed" || observation.type === "control_discarded") {
2371
+ const state = receiptStatusOf(collected, observation.inputId);
2372
+ if (observation.type === "control_consumed" &&
2373
+ state === "pending" &&
2374
+ !journal.isAborted()) {
2375
+ if (!observation.turnId)
2376
+ throw new CoreMindError("control_unavailable", "控制消费缺少本执行的 Turn 身份");
2377
+ emitInputEvent(claimInput({ inputId: observation.inputId, turnId: observation.turnId }));
2378
+ }
2379
+ else if ((observation.type === "control_discarded" || journal.isAborted()) &&
2380
+ (state === "pending" || state === "claimed")) {
2381
+ emitInputEvent(discardInput({ inputId: observation.inputId }));
2382
+ }
2383
+ return;
2384
+ }
2385
+ if (observation.type === "tool_execution_end") {
2386
+ const search = discovery?.observe(observation);
2387
+ if (search)
2388
+ discoverySearchesByCall.set(toolCapabilityCallKey(agentName, stepId, observation.call.callId), { fact: search, durable: durableSearches });
2389
+ const fact = skillExecution?.observe(observation);
2390
+ if (fact)
2391
+ skillLoadsByCall.set(toolCapabilityCallKey(agentName, stepId, observation.call.callId), fact);
2392
+ }
1984
2393
  const driver = context.agent(agentName, executionId);
1985
2394
  if (observation.type === "turn_end" &&
1986
2395
  "contextOverflow" in observation &&
@@ -1991,6 +2400,252 @@ export class CoreMindRuntime {
1991
2400
  driver?.abort();
1992
2401
  },
1993
2402
  };
2403
+ if (discoveryEnabled) {
2404
+ const capability = resolveToolCapability({
2405
+ tool: DISCOVER_TOOLS_NAME,
2406
+ source: "registered",
2407
+ declaration: {
2408
+ effect: "none",
2409
+ replay: "safe",
2410
+ concurrency: "parallel",
2411
+ checkpoint: "none",
2412
+ durability: "critical",
2413
+ },
2414
+ });
2415
+ executionEffects.set(DISCOVER_TOOLS_NAME, { operations: ["read"], reversible: true });
2416
+ executionCapabilities.set(DISCOVER_TOOLS_NAME, capability);
2417
+ harness.discoveryTool = adaptCoreMindTool({
2418
+ ...structuredClone(TOOL_DISCOVERY_DECLARATION),
2419
+ effect: { operations: ["read"], reversible: true },
2420
+ capability,
2421
+ execute: async (args, call) => {
2422
+ if (!discovery)
2423
+ throw new CoreMindError("invalid_tool", "工具目录尚未就绪");
2424
+ const result = discovery.search(call.callId, args, call.signal);
2425
+ return { text: result.content[0].text, details: result.details };
2426
+ },
2427
+ });
2428
+ harness.registerToolSource = (name, source) => toolSources.set(name, {
2429
+ exposure: source?.exposure ?? "direct",
2430
+ sourceIdentity: fingerprintEffectReceiptValue(source ?? { source: "host", name }),
2431
+ });
2432
+ harness.registerDeclarationCatalog = (entries) => {
2433
+ const continuation = discoveryContinuations.find((owner) => owner.agent === agentName &&
2434
+ owner.stepId === stepId &&
2435
+ !consumedDiscoveryContinuations.has(owner.executionId));
2436
+ if (continuation)
2437
+ consumedDiscoveryContinuations.add(continuation.executionId);
2438
+ const owner = continuation ?? {
2439
+ runId,
2440
+ agent: agentName,
2441
+ executionId: executionId,
2442
+ ...(stepId ? { stepId } : {}),
2443
+ };
2444
+ const catalog = entries
2445
+ .filter((entry) => entry.name !== DISCOVER_TOOLS_NAME)
2446
+ .filter((entry) => policy.allowsDeclaration(entry.name, executionCapabilities.get(entry.name) ??
2447
+ resolveToolCapability({ tool: entry.name })))
2448
+ .map((entry) => ({
2449
+ ...entry,
2450
+ declaration: entry.declaration,
2451
+ ...(toolSources.get(entry.name) ?? {
2452
+ exposure: "direct",
2453
+ sourceIdentity: fingerprintEffectReceiptValue({ source: "host", name: entry.name }),
2454
+ }),
2455
+ effect: executionEffects.get(entry.name),
2456
+ capability: executionCapabilities.get(entry.name),
2457
+ }));
2458
+ discovery = new ToolDiscoveryExecution({
2459
+ owner,
2460
+ entries: catalog,
2461
+ restored: continuation ? restoreToolDiscovery(resumeRecords, owner) : undefined,
2462
+ });
2463
+ for (const [id, previous] of liveDiscoveryExecutions) {
2464
+ if (previous.catalog.owner.agent === agentName &&
2465
+ previous.catalog.owner.stepId === stepId)
2466
+ liveDiscoveryExecutions.delete(id);
2467
+ }
2468
+ liveDiscoveryExecutions.set(executionId, discovery);
2469
+ providerRequestOrdinal =
2470
+ resumePlan?.previousTrace.filter((entry) => entry.event.type === "provider_request" &&
2471
+ entry.event.toolDiscovery?.catalogFingerprint === discovery.catalog.fingerprint).length ?? 0;
2472
+ for (const source of withdrawnSources)
2473
+ discovery.withdraw(source);
2474
+ initialDiscovery = discovery.prepare([]);
2475
+ return adapterSelection(initialDiscovery?.selection ?? discovery.current);
2476
+ };
2477
+ harness.prepareRequest = async (prepare, signal) => {
2478
+ while (lifecycleFinalizers.size > 0)
2479
+ await Promise.allSettled([...lifecycleFinalizers.values()]);
2480
+ if (lifecycleFailure)
2481
+ throw lifecycleFailure;
2482
+ signal?.throwIfAborted();
2483
+ await journal.flush("critical");
2484
+ const prepared = initialDiscovery ?? discovery.prepare(durableSearches);
2485
+ if (!prepared)
2486
+ return undefined;
2487
+ const selection = adapterSelection(prepared.selection);
2488
+ const contract = prepare(selection);
2489
+ const generation = { prepared };
2490
+ discoveryGenerations.set(prepared.selection.fingerprint, generation);
2491
+ try {
2492
+ emit({
2493
+ type: "context_prefix",
2494
+ agent: agentName,
2495
+ fingerprint: createHash("sha256").update(contract.stablePrefix, "utf8").digest("hex"),
2496
+ toolDiscovery: discoverySummary(prepared.selection),
2497
+ });
2498
+ if (!generation.receipt)
2499
+ throw new CoreMindError("fact_ledger_poisoned", "声明事实未获准持久化");
2500
+ const receipt = await generation.receipt;
2501
+ signal?.throwIfAborted();
2502
+ if (journal.isAborted())
2503
+ throw new CoreMindError("aborted", "声明发布前 Run 已取消");
2504
+ discovery.commit(prepared, receipt);
2505
+ initialDiscovery = undefined;
2506
+ return selection;
2507
+ }
2508
+ finally {
2509
+ discoveryGenerations.delete(prepared.selection.fingerprint);
2510
+ }
2511
+ };
2512
+ }
2513
+ harness.onPromptCompleted = () => liveDiscoveryExecutions.delete(executionId);
2514
+ if (mcpRun) {
2515
+ harness.prepareMcpTools = async (signal) => {
2516
+ const prepared = await mcpRun.prepare({
2517
+ agentName,
2518
+ executionId: executionId,
2519
+ signal,
2520
+ reservedToolNames: [...executionCapabilities.keys()],
2521
+ onToolsChanged: (sourceIdentity) => {
2522
+ withdrawnSources.add(sourceIdentity);
2523
+ discovery?.withdraw(sourceIdentity);
2524
+ },
2525
+ executeHost: async (operation) => {
2526
+ if (executionCapabilities.has(operation.name)) {
2527
+ throw new CoreMindError("invalid_tool", "本地服务准备操作与已有工具重名");
2528
+ }
2529
+ executionEffects.set(operation.name, operation.effect);
2530
+ executionCapabilities.set(operation.name, resolveToolCapability({
2531
+ tool: operation.name,
2532
+ source: "registered",
2533
+ declaration: operation.capability,
2534
+ }));
2535
+ const call = { callId: randomUUID(), tool: operation.name, args: operation.args };
2536
+ const callKey = toolCapabilityCallKey(agentName, stepId, call.callId);
2537
+ const turnId = randomUUID();
2538
+ emit({
2539
+ type: "tool_call",
2540
+ agent: agentName,
2541
+ ...call,
2542
+ ...(stepId ? { stepId } : {}),
2543
+ turnId,
2544
+ });
2545
+ const blocked = await harness.beforeToolCall({ toolCall: call }, signal);
2546
+ if (blocked?.block) {
2547
+ emit({
2548
+ type: "tool_result",
2549
+ agent: agentName,
2550
+ tool: call.tool,
2551
+ callId: call.callId,
2552
+ isError: true,
2553
+ ...(stepId ? { stepId } : {}),
2554
+ turnId,
2555
+ });
2556
+ await lifecycleFinalizers.get(callKey);
2557
+ if (checkpointFailure)
2558
+ throw checkpointFailure;
2559
+ harness.throwIfDenied?.();
2560
+ throw new CoreMindError("tool_execution_failed", blocked.reason ?? "本地服务准备未获准");
2561
+ }
2562
+ let output;
2563
+ let failure;
2564
+ let result = {
2565
+ content: [{ type: "text", text: "本地服务准备失败" }],
2566
+ details: { mcp: { operation: operation.name } },
2567
+ };
2568
+ try {
2569
+ result = await harness.executeTool({
2570
+ call,
2571
+ signal,
2572
+ invoke: async () => {
2573
+ output = await operation.invoke();
2574
+ return {
2575
+ content: [{ type: "text", text: output.text }],
2576
+ details: output.details,
2577
+ };
2578
+ },
2579
+ });
2580
+ }
2581
+ catch (error) {
2582
+ failure = error;
2583
+ }
2584
+ let isError = failure !== undefined || output?.isError === true;
2585
+ try {
2586
+ await harness.afterToolCall({ toolCall: call, result, isError }, signal);
2587
+ }
2588
+ catch (error) {
2589
+ failure ??= error;
2590
+ isError = true;
2591
+ }
2592
+ finally {
2593
+ emit({
2594
+ type: "tool_result",
2595
+ agent: agentName,
2596
+ tool: call.tool,
2597
+ callId: call.callId,
2598
+ isError,
2599
+ ...(stepId ? { stepId } : {}),
2600
+ turnId,
2601
+ });
2602
+ await lifecycleFinalizers.get(callKey);
2603
+ }
2604
+ if (failure)
2605
+ throw failure;
2606
+ if (lifecycleFailure)
2607
+ throw lifecycleFailure;
2608
+ if (checkpointFailure)
2609
+ throw checkpointFailure;
2610
+ budget.throwIfExceeded();
2611
+ if (!output || output.isError)
2612
+ throw new CoreMindError("tool_execution_failed", "本地服务准备失败");
2613
+ return output;
2614
+ },
2615
+ });
2616
+ for (const tool of prepared) {
2617
+ const { definition, authorization } = tool;
2618
+ toolSources.set(definition.name, {
2619
+ exposure: tool.exposure ?? "direct",
2620
+ sourceIdentity: String(authorization.serverIdentity),
2621
+ });
2622
+ const key = JSON.stringify([agentName, definition.name]);
2623
+ const previous = mcpAuthorizations.get(key);
2624
+ if (previous &&
2625
+ fingerprintEffectReceiptValue(previous) !==
2626
+ fingerprintEffectReceiptValue(authorization)) {
2627
+ throw new CoreMindError("tool_capability_conflict", "本 Run 的本地工具授权身份发生变化");
2628
+ }
2629
+ mcpAuthorizations.set(key, authorization);
2630
+ executionEffects.set(definition.name, {
2631
+ ...definition.effect,
2632
+ ...(definition.effect.pathFields
2633
+ ? { pathFields: definition.effect.pathFields.map((field) => `arguments.${field}`) }
2634
+ : {}),
2635
+ ...(definition.effect.urlFields
2636
+ ? { urlFields: definition.effect.urlFields.map((field) => `arguments.${field}`) }
2637
+ : {}),
2638
+ });
2639
+ executionCapabilities.set(definition.name, resolveToolCapability({
2640
+ tool: definition.name,
2641
+ source: "registered",
2642
+ declaration: definition.capability,
2643
+ }));
2644
+ }
2645
+ return prepared.map(({ definition }) => adaptCoreMindTool(definition));
2646
+ };
2647
+ }
2648
+ return harness;
1994
2649
  });
1995
2650
  let outputs = new Map();
1996
2651
  let transcript = "";
@@ -2044,7 +2699,30 @@ export class CoreMindRuntime {
2044
2699
  return report.passed;
2045
2700
  }
2046
2701
  : undefined,
2047
- executeStep: (request) => runWithTransientRetry(() => this.executeLoopStep(request, emit, limits.stepTimeoutMs, collected), {
2702
+ executeStep: (request) => runWithTransientRetry(async () => {
2703
+ const attemptCursor = collected.length;
2704
+ try {
2705
+ return await this.executeLoopStep(request, emit, limits.stepTimeoutMs, collected);
2706
+ }
2707
+ catch (error) {
2708
+ // 重起步骤会丢弃本次 Driver;已开始的委派也不能证明子任务可以重放。
2709
+ if (retryCount < limits.maxRetries &&
2710
+ classifyRetry(error).retryable &&
2711
+ collected
2712
+ .slice(attemptCursor)
2713
+ .some((event) => event.type === "effect_receipt" &&
2714
+ event.stepId === request.stepId &&
2715
+ event.status !== "not_started" &&
2716
+ (event.tool === DELEGATION_TOOL_NAME ||
2717
+ capabilityByCallId.get(toolCapabilityCallKey(event.agent, event.stepId, event.callId))?.capability.effect !== "none"))) {
2718
+ const original = normalizeExecutionError(error);
2719
+ throw new CoreMindError("unclassified_error", `步骤 ${request.stepId} 已产生副作用或已开始委派,模型请求失败后须人工核对,禁止整步重试`, {
2720
+ originalCode: `${original.code}: ${original.audit?.originalCode ?? original.message}`.slice(0, 512),
2721
+ });
2722
+ }
2723
+ throw error;
2724
+ }
2725
+ }, {
2048
2726
  maxRetries: Math.max(0, limits.maxRetries - retryCount),
2049
2727
  signal: this.options.signal,
2050
2728
  onRetry: () => {
@@ -2069,7 +2747,7 @@ export class CoreMindRuntime {
2069
2747
  }
2070
2748
  if (workflow && workflow.length > 0) {
2071
2749
  const orchestrator = new Orchestrator(workflow, {
2072
- createAgent: (name, stepId) => this.createAgent(name, (event) => emit(stepId ? { ...event, stepId } : event), stepId),
2750
+ createAgent: (name, stepId, signal) => this.createAgent(name, (event) => emit(stepId ? { ...event, stepId } : event), stepId, signal),
2073
2751
  events: emit,
2074
2752
  initialPrompt: effectiveInitialPrompt,
2075
2753
  signal: this.options.signal,
@@ -2091,7 +2769,7 @@ export class CoreMindRuntime {
2091
2769
  if (effectiveInitialPrompt === undefined) {
2092
2770
  throw new CoreMindError("no_prompt", "未提供输入:单 agent 模式需要 --prompt 参数,或配置 workflow 步骤");
2093
2771
  }
2094
- const agent = this.createAgent(name, emit);
2772
+ const agent = await this.createAgent(name, emit);
2095
2773
  if (!agent) {
2096
2774
  throw new CoreMindError("unknown_agent", `默认 agent ${name} 不存在`);
2097
2775
  }
@@ -2227,7 +2905,7 @@ export class CoreMindRuntime {
2227
2905
  }
2228
2906
  }
2229
2907
  while (lifecycleFinalizers.size > 0) {
2230
- await Promise.allSettled([...lifecycleFinalizers]);
2908
+ await Promise.allSettled([...lifecycleFinalizers.values()]);
2231
2909
  }
2232
2910
  if (lifecycleFailure &&
2233
2911
  (terminalError === undefined ||
@@ -2238,6 +2916,18 @@ export class CoreMindRuntime {
2238
2916
  // pending 工具结束、journal 落盘队列清空;超时记录 quiescence_timeout 事件不改变终态
2239
2917
  await context.currentControlInbox()?.sealForTerminal();
2240
2918
  await context.currentChildRuns()?.sealForTerminal();
2919
+ for (const name of this.agentConfigs.keys()) {
2920
+ for (const driver of context.agentsNamed(name))
2921
+ driver.clearQueuedControls();
2922
+ }
2923
+ try {
2924
+ await mcpRun?.close();
2925
+ }
2926
+ catch {
2927
+ const failure = new CoreMindError("environment_terminate_failed", "本 Run 的本地服务未能完成资源回收");
2928
+ terminalError ??= failure;
2929
+ emit({ type: "error", message: failure.message, fatal: true });
2930
+ }
2241
2931
  const runtimeQuiescent = await this.waitForQuiescence(DEFAULT_QUIESCENCE_TIMEOUT_MS);
2242
2932
  let delegationGate = context.currentChildRuns()?.continuationGate();
2243
2933
  const environmentTerminationError = context.environmentTerminationError();
@@ -2312,14 +3002,40 @@ export class CoreMindRuntime {
2312
3002
  if (terminalError !== undefined && transcript.length === 0 && !journal.isAborted()) {
2313
3003
  transcript = extractText(allMessages);
2314
3004
  }
3005
+ transcript = redactSensitiveText(transcript);
2315
3006
  try {
2316
3007
  await journal.flush();
2317
3008
  }
2318
3009
  catch (error) {
2319
3010
  terminalError = durabilityFailure(error);
2320
3011
  }
3012
+ if (ownership) {
3013
+ try {
3014
+ await releaseRunSession(ownership, context);
3015
+ }
3016
+ catch (error) {
3017
+ terminalError = error;
3018
+ }
3019
+ }
2321
3020
  const metrics = analyzeRunMetrics(collected, allMessages, performance.now() - started, transcript.length, journal.rejectedAfterAbort());
2322
- let outcome = new RunTerminalizer().terminalize(collected, terminalError);
3021
+ let outcome = new RunTerminalizer().terminalize(collected.slice(terminalEventCursor), terminalError);
3022
+ if (outcome.status !== "paused") {
3023
+ try {
3024
+ await context.currentControlInbox()?.rejectPendingInputs();
3025
+ }
3026
+ catch (error) {
3027
+ terminalError = durabilityFailure(error);
3028
+ outcome = new RunTerminalizer().terminalize(collected.slice(terminalEventCursor), terminalError);
3029
+ }
3030
+ }
3031
+ for (const [id, state] of foldInputReceipts(collected)) {
3032
+ if (!isControlInputId(id))
3033
+ continue;
3034
+ if (state === "claimed" && outcome.status === "succeeded")
3035
+ emitInputEvent(completeInput({ inputId: id }));
3036
+ else if (outcome.status !== "paused" && (state === "pending" || state === "claimed"))
3037
+ emitInputEvent(discardInput({ inputId: id }));
3038
+ }
2323
3039
  // 输入收据终态(规格 03 §4):succeeded → completed;abort/超时/预算/失败 → discarded
2324
3040
  // (未消费输入);paused(审批拒绝等)保持 claimed,resume 继续同一输入
2325
3041
  if (inputReceiptState !== undefined && inputReceiptState !== "completed") {
@@ -2389,11 +3105,17 @@ export class CoreMindRuntime {
2389
3105
  }
2390
3106
  catch (error) {
2391
3107
  terminalError = durabilityFailure(error);
2392
- outcome = new RunTerminalizer().terminalize(collected, terminalError);
3108
+ outcome = new RunTerminalizer().terminalize(collected.slice(terminalEventCursor), terminalError);
2393
3109
  evaluation = createEvaluationReport(this.config.quality, metrics);
2394
3110
  releaseReadiness = assessReleaseReadiness(outcome, evaluation);
2395
3111
  }
2396
3112
  const terminalKind = outcome.status === "paused" ? "pause" : "finish";
3113
+ const pausedDiscoveryOwners = [
3114
+ ...discoveryContinuations.filter((owner) => !consumedDiscoveryContinuations.has(owner.executionId)),
3115
+ ...[...liveDiscoveryExecutions.values()]
3116
+ .filter((execution) => execution.current)
3117
+ .map((execution) => execution.catalog.owner),
3118
+ ];
2397
3119
  const terminalPayload = {
2398
3120
  operation: operation.snapshot(),
2399
3121
  outcome,
@@ -2403,6 +3125,14 @@ export class CoreMindRuntime {
2403
3125
  artifacts: context.artifactRecords(),
2404
3126
  extensions: context.extensions(),
2405
3127
  ...(outcome.status === "paused" && loopSnapshot ? { loopSnapshot } : {}),
3128
+ ...(outcome.status === "paused" && pausedDiscoveryOwners.length > 0
3129
+ ? {
3130
+ toolDiscoveryContinuations: {
3131
+ version: 1,
3132
+ owners: pausedDiscoveryOwners,
3133
+ },
3134
+ }
3135
+ : {}),
2406
3136
  ...(outcome.status === "paused" && deferredTerminalError
2407
3137
  ? { deferredTerminalError: serializeDeferredTerminalError(deferredTerminalError) }
2408
3138
  : {}),
@@ -2421,8 +3151,12 @@ export class CoreMindRuntime {
2421
3151
  catch (error) {
2422
3152
  const finalDurabilityFailure = durabilityFailure(error);
2423
3153
  terminalError = finalDurabilityFailure;
2424
- userEvents({ type: "error", message: finalDurabilityFailure.message, fatal: true });
2425
- outcome = new RunTerminalizer().terminalize(collected, terminalError);
3154
+ userEvents({
3155
+ type: "error",
3156
+ message: redactSensitiveText(finalDurabilityFailure.message),
3157
+ fatal: true,
3158
+ });
3159
+ outcome = new RunTerminalizer().terminalize(collected.slice(terminalEventCursor), terminalError);
2426
3160
  evaluation = createEvaluationReport(this.config.quality, metrics);
2427
3161
  releaseReadiness = assessReleaseReadiness(outcome, evaluation);
2428
3162
  }
@@ -2539,13 +3273,20 @@ export class CoreMindRuntime {
2539
3273
  }
2540
3274
  async executeLoopStep(request, emit, timeoutMs, collected) {
2541
3275
  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;
3276
+ const controller = new AbortController();
3277
+ const signal = this.options.signal
3278
+ ? AbortSignal.any([this.options.signal, controller.signal])
3279
+ : controller.signal;
3280
+ let agent;
3281
+ let messageCursor = 0;
2547
3282
  let timer;
2548
3283
  const operation = (async () => {
3284
+ agent = await this.createAgent(request.agent, (event) => emit({ ...event, stepId: request.stepId }), request.stepId, signal);
3285
+ signal.throwIfAborted();
3286
+ if (!agent) {
3287
+ throw new CoreMindError("unknown_agent", `Loop 引用了未定义的 agent:${request.agent}(${request.stepId})`);
3288
+ }
3289
+ messageCursor = agent.messages().length;
2549
3290
  await agent.prompt(request.input);
2550
3291
  await agent.waitForIdle();
2551
3292
  })();
@@ -2555,8 +3296,10 @@ export class CoreMindRuntime {
2555
3296
  operation,
2556
3297
  new Promise((_resolve, reject) => {
2557
3298
  timer = setTimeout(() => {
2558
- agent.abort();
2559
- reject(new CoreMindError("step_timeout", `步骤 ${request.stepId} 执行超时(${timeoutMs}ms),已中止`));
3299
+ const failure = new CoreMindError("step_timeout", `步骤 ${request.stepId} 执行超时(${timeoutMs}ms),已中止`);
3300
+ controller.abort(failure);
3301
+ agent?.abort();
3302
+ reject(failure);
2560
3303
  }, timeoutMs);
2561
3304
  }),
2562
3305
  ]);
@@ -2622,11 +3365,20 @@ export class CoreMindRuntime {
2622
3365
  }
2623
3366
  }
2624
3367
  if (command.type === "steering" || command.type === "follow_up") {
2625
- const agent = context.agent(this.mainAgentName);
2626
- if (!agent)
3368
+ const candidates = context
3369
+ .agentsNamed(this.mainAgentName)
3370
+ .filter((driver) => driver.canAcceptControl());
3371
+ if (candidates.length !== 1)
2627
3372
  return "accepted";
2628
- agent.queueControl({ type: command.type, message: command.message });
2629
- return "applied";
3373
+ const agent = candidates[0];
3374
+ return {
3375
+ status: "applied",
3376
+ afterDurable: () => agent.queueControl({
3377
+ inputId: controlInputId(command.runId, command.controlId),
3378
+ type: command.type,
3379
+ message: command.message,
3380
+ }),
3381
+ };
2630
3382
  }
2631
3383
  return (this.options.applyControl?.(command) ?? {
2632
3384
  status: "rejected",
@@ -2665,16 +3417,15 @@ export class CoreMindRuntime {
2665
3417
  const mains = context.agentsNamed(this.mainAgentName);
2666
3418
  if (mains.length === 0)
2667
3419
  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()));
3420
+ const cm = context.sessionHandle();
3421
+ if (!cm)
3422
+ throw new CoreMindError("session_write_lease_invalid", "当前 Run 没有可写会话身份");
2676
3423
  // 只追加本轮新增:恢复历史已落盘;请求级压缩的摘要与保留区已由压缩条目代表
2677
- let messages = mains.flatMap((main) => main.messages().slice(context.compactedPrefixEnd() ?? this.resumedContextLength));
3424
+ let messages = mains.flatMap((main) => main
3425
+ .messages()
3426
+ .slice(context.compactedPrefixEnd() ??
3427
+ context.initialSessionLength() ??
3428
+ this.resumedContextLength));
2678
3429
  if (context.currentJournal()?.isAborted()) {
2679
3430
  // D-4 方案 A:abort 后只写已确认部分——去掉尾部未正常终止的 assistant 消息(竞态赢家文本)
2680
3431
  messages = trimUnconfirmedTail(messages);
@@ -2687,6 +3438,49 @@ export class CoreMindRuntime {
2687
3438
  return cm.filePath;
2688
3439
  }
2689
3440
  }
3441
+ async function executeWithSessionLease(runtime, options, config, context, execute) {
3442
+ if (!options.sessionId || !config.session?.enabled)
3443
+ return execute();
3444
+ const ownership = {
3445
+ lease: await acquireSessionWriteLease(sessionDir(config, options.configDir), options.sessionId),
3446
+ released: false,
3447
+ retained: false,
3448
+ };
3449
+ try {
3450
+ const result = await execute(ownership);
3451
+ const session = context.sessionHandle();
3452
+ if (session) {
3453
+ for (const messages of result.messages.values())
3454
+ rememberSessionHistory(session, messages);
3455
+ executionSlotFor(runtime).sessionPreviewHistory = rememberSessionHistory(session, projectBranchMessages(await session.branchEntries()).map((item) => item.message));
3456
+ }
3457
+ return result;
3458
+ }
3459
+ catch (error) {
3460
+ try {
3461
+ await releaseRunSession(ownership, context);
3462
+ }
3463
+ catch (cleanupError) {
3464
+ throw Object.assign(new CoreMindError("session_lock_recovery_required", "运行失败且会话所有权未能安全释放"), { cause: new AggregateError([error, cleanupError]) });
3465
+ }
3466
+ throw error;
3467
+ }
3468
+ }
3469
+ async function releaseRunSession(ownership, context) {
3470
+ if (ownership.released || ownership.retained)
3471
+ return;
3472
+ if (!context.isExecutionQuiescent()) {
3473
+ ownership.retained = true;
3474
+ throw new CoreMindError("session_not_quiescent", "会话写入或运行尚未静止,保留写租约并等待恢复审计");
3475
+ }
3476
+ ownership.released = true;
3477
+ try {
3478
+ await ownership.lease.release();
3479
+ }
3480
+ catch (error) {
3481
+ throw Object.assign(new CoreMindError("session_lock_recovery_required", "会话写租约释放失败,需核验所有权"), { cause: error });
3482
+ }
3483
+ }
2690
3484
  const runtimeExecutionSlots = new WeakMap();
2691
3485
  function executionSlotFor(runtime) {
2692
3486
  const existing = runtimeExecutionSlots.get(runtime);
@@ -2767,11 +3561,18 @@ const QUIESCENCE_POLL_INTERVAL_MS = 1;
2767
3561
  const DELEGATED_SAFE_BUILTIN_TOOLS = new Set(["web-fetch", "write"]);
2768
3562
  /** Child 只保留显式网络读取与受 Checkpoint/Lease 保护的写入,不加载脚本、进程或扫描工具。 */
2769
3563
  function isDelegatedBuiltinToolConfig(tool) {
2770
- return !("path" in tool) && DELEGATED_SAFE_BUILTIN_TOOLS.has(tool.id);
3564
+ return "id" in tool && DELEGATED_SAFE_BUILTIN_TOOLS.has(tool.id);
2771
3565
  }
2772
3566
  function isDelegatedSafeToolName(tool) {
2773
3567
  return DELEGATED_SAFE_BUILTIN_TOOLS.has(tool);
2774
3568
  }
3569
+ function needsFrozenSkillAuthority(agents, snapshot, name, seen = new Set()) {
3570
+ if (!snapshot || seen.has(name) || !Object.hasOwn(agents, name))
3571
+ return false;
3572
+ seen.add(name);
3573
+ return ((snapshot.agents[name]?.standard.length ?? 0) > 0 ||
3574
+ Object.keys(agents[name].delegation?.targets ?? {}).some((target) => needsFrozenSkillAuthority(agents, snapshot, target, seen)));
3575
+ }
2775
3576
  const DELEGATED_TOOL_ENV_ALLOWLIST = new Set([
2776
3577
  "PATH",
2777
3578
  "PATHEXT",
@@ -2868,9 +3669,9 @@ function tightenDelegationBudget(configured, inherited) {
2868
3669
  ]));
2869
3670
  }
2870
3671
  async function assertRuntimeChildPolicyAuthority(input) {
2871
- const { policy, config, model, executionEnvironment, workspaceRoot, tools, limits, enforceRuntimeBudget, enforceDelegatedToolBoundary, } = input;
3672
+ const { policy, config, model, executionEnvironment, workspaceRoot, tools, limits, enforceRuntimeBudget, enforceDelegatedToolBoundary, trustedSkillLoader, } = input;
2872
3673
  const unsafeTool = enforceDelegatedToolBoundary
2873
- ? [...tools].find((tool) => !isDelegatedSafeToolName(tool))
3674
+ ? [...tools].find((tool) => !isDelegatedSafeToolName(tool) && !(trustedSkillLoader && tool === SKILL_TOOL_NAME))
2874
3675
  : undefined;
2875
3676
  if (unsafeTool) {
2876
3677
  throw new CoreMindError("child_run_policy_escalation", `Child Runtime 工具 ${unsafeTool} 不能证明不会扩展 Delegated Context`);
@@ -2948,7 +3749,7 @@ function durabilityFailure(error) {
2948
3749
  */
2949
3750
  function resumedInputId(events) {
2950
3751
  for (const event of events) {
2951
- if (event.type === "input_receipt")
3752
+ if (event.type === "input_receipt" && !isControlInputId(event.inputId))
2952
3753
  return event.inputId;
2953
3754
  }
2954
3755
  return undefined;