coremind-runtime 0.3.1 → 0.7.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.
- package/README.md +49 -1
- package/dist/active-run-binding.d.ts +24 -0
- package/dist/active-run-binding.d.ts.map +1 -0
- package/dist/active-run-binding.js +22 -0
- package/dist/active-run-binding.js.map +1 -0
- package/dist/agent-driver.d.ts +139 -0
- package/dist/agent-driver.d.ts.map +1 -0
- package/dist/agent-driver.js +135 -0
- package/dist/agent-driver.js.map +1 -0
- package/dist/agent-factory.d.ts +10 -10
- package/dist/agent-factory.d.ts.map +1 -1
- package/dist/agent-factory.js +179 -14
- package/dist/agent-factory.js.map +1 -1
- package/dist/budget.d.ts +11 -1
- package/dist/budget.d.ts.map +1 -1
- package/dist/budget.js +59 -16
- package/dist/budget.js.map +1 -1
- package/dist/canonical-json.d.ts +3 -0
- package/dist/canonical-json.d.ts.map +1 -0
- package/dist/canonical-json.js +28 -0
- package/dist/canonical-json.js.map +1 -0
- package/dist/chat-session.d.ts +3 -0
- package/dist/chat-session.d.ts.map +1 -1
- package/dist/chat-session.js +5 -0
- package/dist/chat-session.js.map +1 -1
- package/dist/checkpoint.d.ts +25 -8
- package/dist/checkpoint.d.ts.map +1 -1
- package/dist/checkpoint.js +135 -52
- package/dist/checkpoint.js.map +1 -1
- package/dist/child-run.d.ts +344 -0
- package/dist/child-run.d.ts.map +1 -0
- package/dist/child-run.js +1373 -0
- package/dist/child-run.js.map +1 -0
- package/dist/child-runtime-adapter.d.ts +18 -0
- package/dist/child-runtime-adapter.d.ts.map +1 -0
- package/dist/child-runtime-adapter.js +309 -0
- package/dist/child-runtime-adapter.js.map +1 -0
- package/dist/compaction-projection.d.ts +5 -0
- package/dist/compaction-projection.d.ts.map +1 -1
- package/dist/compaction-projection.js +19 -1
- package/dist/compaction-projection.js.map +1 -1
- package/dist/context-lifecycle.d.ts +182 -0
- package/dist/context-lifecycle.d.ts.map +1 -0
- package/dist/context-lifecycle.js +455 -0
- package/dist/context-lifecycle.js.map +1 -0
- package/dist/context-task-state.d.ts +23 -0
- package/dist/context-task-state.d.ts.map +1 -0
- package/dist/context-task-state.js +183 -0
- package/dist/context-task-state.js.map +1 -0
- package/dist/control-inbox.d.ts +106 -0
- package/dist/control-inbox.d.ts.map +1 -0
- package/dist/control-inbox.js +291 -0
- package/dist/control-inbox.js.map +1 -0
- package/dist/delegated-context.d.ts +29 -0
- package/dist/delegated-context.d.ts.map +1 -0
- package/dist/delegated-context.js +76 -0
- package/dist/delegated-context.js.map +1 -0
- package/dist/delegation-tool.d.ts +30 -0
- package/dist/delegation-tool.d.ts.map +1 -0
- package/dist/delegation-tool.js +232 -0
- package/dist/delegation-tool.js.map +1 -0
- package/dist/effect-receipt-binding.d.ts +34 -0
- package/dist/effect-receipt-binding.d.ts.map +1 -0
- package/dist/effect-receipt-binding.js +125 -0
- package/dist/effect-receipt-binding.js.map +1 -0
- package/dist/errors.d.ts +11 -315
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +7 -129
- package/dist/errors.js.map +1 -1
- package/dist/evaluation.d.ts.map +1 -1
- package/dist/evaluation.js +12 -5
- package/dist/evaluation.js.map +1 -1
- package/dist/events.d.ts +91 -3
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +44 -0
- package/dist/events.js.map +1 -1
- package/dist/execution-error.d.ts +14 -0
- package/dist/execution-error.d.ts.map +1 -0
- package/dist/execution-error.js +129 -0
- package/dist/execution-error.js.map +1 -0
- package/dist/execution-security.d.ts +11 -0
- package/dist/execution-security.d.ts.map +1 -0
- package/dist/execution-security.js +40 -0
- package/dist/execution-security.js.map +1 -0
- package/dist/fact-ledger.d.ts +60 -0
- package/dist/fact-ledger.d.ts.map +1 -0
- package/dist/fact-ledger.js +167 -0
- package/dist/fact-ledger.js.map +1 -0
- package/dist/ids.d.ts +4 -0
- package/dist/ids.d.ts.map +1 -1
- package/dist/ids.js.map +1 -1
- package/dist/index.d.ts +15 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -2
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +11 -0
- package/dist/internal.d.ts.map +1 -0
- package/dist/internal.js +11 -0
- package/dist/internal.js.map +1 -0
- package/dist/invariant-checker.d.ts.map +1 -1
- package/dist/invariant-checker.js +51 -10
- package/dist/invariant-checker.js.map +1 -1
- package/dist/loop-runner.d.ts.map +1 -1
- package/dist/loop-runner.js +14 -8
- package/dist/loop-runner.js.map +1 -1
- package/dist/observability.d.ts +211 -0
- package/dist/observability.d.ts.map +1 -0
- package/dist/observability.js +814 -0
- package/dist/observability.js.map +1 -0
- package/dist/orchestrator.d.ts +2 -2
- package/dist/orchestrator.d.ts.map +1 -1
- package/dist/orchestrator.js +12 -6
- package/dist/orchestrator.js.map +1 -1
- package/dist/project-check.d.ts +3 -0
- package/dist/project-check.d.ts.map +1 -1
- package/dist/project-check.js +21 -5
- package/dist/project-check.js.map +1 -1
- package/dist/projection.d.ts +131 -0
- package/dist/projection.d.ts.map +1 -0
- package/dist/projection.js +972 -0
- package/dist/projection.js.map +1 -0
- package/dist/provider.d.ts +23 -1
- package/dist/provider.d.ts.map +1 -1
- package/dist/provider.js +134 -23
- package/dist/provider.js.map +1 -1
- package/dist/public-tool.d.ts +3 -0
- package/dist/public-tool.d.ts.map +1 -1
- package/dist/public-tool.js +28 -3
- package/dist/public-tool.js.map +1 -1
- package/dist/replay-kit.d.ts +41 -0
- package/dist/replay-kit.d.ts.map +1 -0
- package/dist/replay-kit.js +96 -0
- package/dist/replay-kit.js.map +1 -0
- package/dist/result.d.ts +17 -1
- package/dist/result.d.ts.map +1 -1
- package/dist/result.js +16 -0
- package/dist/result.js.map +1 -1
- package/dist/retry-policy.d.ts.map +1 -1
- package/dist/retry-policy.js +22 -72
- package/dist/retry-policy.js.map +1 -1
- package/dist/run-context.d.ts +77 -0
- package/dist/run-context.d.ts.map +1 -0
- package/dist/run-context.js +159 -0
- package/dist/run-context.js.map +1 -0
- package/dist/run-effect-coordinator.d.ts.map +1 -1
- package/dist/run-effect-coordinator.js +3 -0
- package/dist/run-effect-coordinator.js.map +1 -1
- package/dist/run-kernel.d.ts +14 -0
- package/dist/run-kernel.d.ts.map +1 -0
- package/dist/run-kernel.js +34 -0
- package/dist/run-kernel.js.map +1 -0
- package/dist/run-state.d.ts +65 -4
- package/dist/run-state.d.ts.map +1 -1
- package/dist/run-state.js +502 -76
- package/dist/run-state.js.map +1 -1
- package/dist/run-terminalizer.d.ts.map +1 -1
- package/dist/run-terminalizer.js +4 -3
- package/dist/run-terminalizer.js.map +1 -1
- package/dist/runtime-instance-authority.d.ts +3 -0
- package/dist/runtime-instance-authority.d.ts.map +1 -0
- package/dist/runtime-instance-authority.js +8 -0
- package/dist/runtime-instance-authority.js.map +1 -0
- package/dist/runtime.d.ts +83 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2048 -348
- package/dist/runtime.js.map +1 -1
- package/dist/session.d.ts +4 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js.map +1 -1
- package/dist/tool-call-lifecycle.d.ts +89 -0
- package/dist/tool-call-lifecycle.d.ts.map +1 -0
- package/dist/tool-call-lifecycle.js +379 -0
- package/dist/tool-call-lifecycle.js.map +1 -0
- package/dist/tool-capability-identity.d.ts +3 -0
- package/dist/tool-capability-identity.d.ts.map +1 -0
- package/dist/tool-capability-identity.js +5 -0
- package/dist/tool-capability-identity.js.map +1 -0
- package/dist/tool-capability-projection.d.ts +17 -0
- package/dist/tool-capability-projection.d.ts.map +1 -0
- package/dist/tool-capability-projection.js +99 -0
- package/dist/tool-capability-projection.js.map +1 -0
- package/dist/tool-effect-selectors.d.ts +3 -0
- package/dist/tool-effect-selectors.d.ts.map +1 -0
- package/dist/tool-effect-selectors.js +18 -0
- package/dist/tool-effect-selectors.js.map +1 -0
- package/dist/tool-policy.d.ts +13 -2
- package/dist/tool-policy.d.ts.map +1 -1
- package/dist/tool-policy.js +149 -44
- package/dist/tool-policy.js.map +1 -1
- package/dist/trace.d.ts +1 -0
- package/dist/trace.d.ts.map +1 -1
- package/dist/trace.js +10 -3
- package/dist/trace.js.map +1 -1
- package/dist/turn-tracker.d.ts.map +1 -1
- package/dist/turn-tracker.js +1 -0
- package/dist/turn-tracker.js.map +1 -1
- package/dist/workspace-lease.d.ts +81 -0
- package/dist/workspace-lease.d.ts.map +1 -0
- package/dist/workspace-lease.js +300 -0
- package/dist/workspace-lease.js.map +1 -0
- package/package.json +11 -5
package/dist/runtime.js
CHANGED
|
@@ -1,33 +1,53 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { loadDirectorySkills, resolveSkills, SKILLS } from "coremind-templates";
|
|
4
|
-
import { ArtifactStore,
|
|
5
|
-
import {
|
|
4
|
+
import { ArtifactStore, extractArtifactRecord, inferLegacyToolCapability, recoveryDispositionFor, resolveToolCapability, wrapToolWithArtifactCapture, } from "coremind-tools";
|
|
5
|
+
import { buildToolsWithExecutionEnvironment, createPlatformExecutionEnvironment, resolveExecutionEnvironment, } from "coremind-tools/internal";
|
|
6
|
+
import { bindActiveRun, boundDelegationDispositionExecutor, boundDelegationExecutor, } from "./active-run-binding.js";
|
|
7
|
+
import { buildAgentDriver } from "./agent-factory.js";
|
|
6
8
|
import { RunBudgetController, resolveRuntimeLimits } from "./budget.js";
|
|
7
9
|
import { CheckpointManager, inspectCheckpoint as inspectStoredCheckpoint, restoreCheckpoint as restoreStoredCheckpoint, } from "./checkpoint.js";
|
|
10
|
+
import { CHILD_RUN_LIMIT_DEFAULTS, ChildRunCoordinator, childRunInputFingerprint, } from "./child-run.js";
|
|
11
|
+
import { createCoreMindChildRunAdapter, isCoreMindChildRunAdapter, } from "./child-runtime-adapter.js";
|
|
8
12
|
import { assessRuntimeEngineeringEvidence, createToolExecutionEvidence, } from "./coding/runtime-engineering-evidence.js";
|
|
9
|
-
import { projectBranchMessages } from "./compaction-projection.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
13
|
+
import { projectBranchMessages, projectContextCompactionLedger, projectRawBranchMessages, } from "./compaction-projection.js";
|
|
14
|
+
import { ContextLifecycleError, ContextLifecycleManager, } from "./context-lifecycle.js";
|
|
15
|
+
import { projectContextTaskState } from "./context-task-state.js";
|
|
16
|
+
import { ControlInbox, } from "./control-inbox.js";
|
|
17
|
+
import { buildDelegatedInitialPrompt, resolveDelegatedContextReferences, } from "./delegated-context.js";
|
|
18
|
+
import { createDelegationAgentTool, createDelegationDispositionAgentTool, DELEGATION_DISPOSITION_TOOL_CAPABILITY, DELEGATION_DISPOSITION_TOOL_EFFECT, DELEGATION_DISPOSITION_TOOL_NAME, DELEGATION_TOOL_CAPABILITY, DELEGATION_TOOL_EFFECT, DELEGATION_TOOL_NAME, parseDelegationDispositionToolArgs, parseDelegationToolArgs, resolveDelegationAllocation, resolveDelegationHierarchyLimits, } from "./delegation-tool.js";
|
|
19
|
+
import { createEffectReceiptBinding, fingerprintEffectReceiptValue, } from "./effect-receipt-binding.js";
|
|
20
|
+
import { CoreMindError, isErrorCode } from "./errors.js";
|
|
12
21
|
import { extractAgentError, extractText } from "./events.js";
|
|
22
|
+
import { normalizeExecutionError } from "./execution-error.js";
|
|
23
|
+
import { enforceExecutionSecurity } from "./execution-security.js";
|
|
13
24
|
import { receiptId } from "./ids.js";
|
|
14
25
|
import { claimInput, completeInput, createInputReceipt, discardInput, inputFingerprint, newInputId, receiptStatusOf, } from "./input-receipt.js";
|
|
15
26
|
import { LifecycleExtensionHost, } from "./lifecycle-extension.js";
|
|
16
27
|
import { LoopRunner } from "./loop-runner.js";
|
|
28
|
+
import { createTelemetryConfigurationFact, projectLocalObservability, TelemetryEgressController, validateTelemetryConsentBinding, validateTelemetryConsentFact, } from "./observability.js";
|
|
17
29
|
import { DurableOperation, restoreDurableOperation, } from "./operation-state.js";
|
|
18
30
|
import { Orchestrator } from "./orchestrator.js";
|
|
19
|
-
import {
|
|
31
|
+
import { ProjectionEngine } from "./projection.js";
|
|
32
|
+
import { buildProviderRuntime, contextCapabilityCandidatesForModel, resolveProviderModel, } from "./provider.js";
|
|
20
33
|
import { adaptCoreMindTool } from "./public-tool.js";
|
|
34
|
+
import { createProviderRequestReplayFact } from "./replay-kit.js";
|
|
21
35
|
import { analyzeRunMetrics, assessReleaseReadiness, createEvaluationReport, } from "./result.js";
|
|
22
|
-
import {
|
|
36
|
+
import { runWithTransientRetry } from "./retry-policy.js";
|
|
37
|
+
import { RunContext } from "./run-context.js";
|
|
23
38
|
import { RunEffectCoordinator } from "./run-effect-coordinator.js";
|
|
24
|
-
import {
|
|
39
|
+
import { RunKernel } from "./run-kernel.js";
|
|
40
|
+
import { FileRunStore, fingerprintRunConfig, RunStateJournal, } from "./run-state.js";
|
|
25
41
|
import { RunTerminalizer } from "./run-terminalizer.js";
|
|
42
|
+
import { registerCoreMindRuntimeInstance } from "./runtime-instance-authority.js";
|
|
26
43
|
import { CoreMindSession } from "./session.js";
|
|
27
44
|
import { createRunSnapshot } from "./snapshot.js";
|
|
45
|
+
import { ToolExecutionEngine } from "./tool-call-lifecycle.js";
|
|
46
|
+
import { toolCapabilityCallKey } from "./tool-capability-identity.js";
|
|
28
47
|
import { ToolPolicy } from "./tool-policy.js";
|
|
29
48
|
import { TraceRecorder } from "./trace.js";
|
|
30
49
|
import { TurnTracker } from "./turn-tracker.js";
|
|
50
|
+
import { canonicalizeWorkspace, WorkspaceLeaseService, } from "./workspace-lease.js";
|
|
31
51
|
/**
|
|
32
52
|
* CoreMind 运行时门面:配置 → provider/工具/agent → 执行。
|
|
33
53
|
* 库形式嵌入入口:buildAgentFromConfig / CoreMindRuntime.create().run()
|
|
@@ -35,9 +55,13 @@ import { TurnTracker } from "./turn-tracker.js";
|
|
|
35
55
|
export class CoreMindRuntime {
|
|
36
56
|
config;
|
|
37
57
|
agentConfigs;
|
|
38
|
-
|
|
58
|
+
agentModels;
|
|
59
|
+
driverBuilders;
|
|
39
60
|
toolEffectsByAgent;
|
|
61
|
+
toolCapabilitiesByAgent;
|
|
40
62
|
providerRuntime;
|
|
63
|
+
executionEnvironment;
|
|
64
|
+
workspaceLeaseService;
|
|
41
65
|
options;
|
|
42
66
|
/** 最近创建的每个 agent 实例(收集最终消息/落盘用) */
|
|
43
67
|
lastAgents = new Map();
|
|
@@ -54,60 +78,146 @@ export class CoreMindRuntime {
|
|
|
54
78
|
activeRunPromise;
|
|
55
79
|
/** 当前 run 的 journal(persistSession 的准入/abort 语义用) */
|
|
56
80
|
runJournal;
|
|
81
|
+
/** 当前或最近一次 run 的 canonical store(只读 Projection 查询用)。 */
|
|
82
|
+
activeRunStore;
|
|
57
83
|
/** 本次 run 打开的会话(压缩条目落盘与 persist 复用同一句柄) */
|
|
58
84
|
activeSession;
|
|
59
85
|
/** 会话树已落盘视图消息 + 来源条目 id(压缩替换范围的桥接) */
|
|
60
86
|
sessionBranch;
|
|
61
87
|
/** 压缩后 agent 消息数组中被会话树代表的前缀长度(persist 跳过,避免重复落盘) */
|
|
62
88
|
compactedPrefixEnd;
|
|
63
|
-
constructor(config, agentConfigs,
|
|
89
|
+
constructor(config, agentConfigs, agentModels, driverBuilders, toolEffectsByAgent, toolCapabilitiesByAgent, providerRuntime, executionEnvironment, workspaceLeaseService, options, sessionMessages, resumedContextLength, skillsByAgent) {
|
|
64
90
|
this.config = config;
|
|
65
91
|
this.agentConfigs = agentConfigs;
|
|
66
|
-
this.
|
|
92
|
+
this.agentModels = agentModels;
|
|
93
|
+
this.driverBuilders = driverBuilders;
|
|
67
94
|
this.toolEffectsByAgent = toolEffectsByAgent;
|
|
95
|
+
this.toolCapabilitiesByAgent = toolCapabilitiesByAgent;
|
|
68
96
|
this.providerRuntime = providerRuntime;
|
|
97
|
+
this.executionEnvironment = executionEnvironment;
|
|
98
|
+
this.workspaceLeaseService = workspaceLeaseService;
|
|
69
99
|
this.options = options;
|
|
100
|
+
registerCoreMindRuntimeInstance(this);
|
|
70
101
|
this.sessionMessages = sessionMessages;
|
|
71
102
|
this.resumedContextLength = resumedContextLength;
|
|
72
103
|
this.mainAgentName = config.defaultAgent ?? firstKey(config.agents) ?? "";
|
|
73
104
|
this.skillsByAgent = skillsByAgent;
|
|
105
|
+
// 这些读取只用于保留已冻结的私有声明布局;执行状态已迁移到 RunContext。
|
|
106
|
+
void this.lastAgents;
|
|
107
|
+
void this.activeHarnessFactory;
|
|
108
|
+
void this.activeRunPromise;
|
|
109
|
+
void this.runJournal;
|
|
110
|
+
void this.activeSession;
|
|
74
111
|
}
|
|
75
112
|
/** 由配置构建运行时(注册 provider、构建工具与全部 agent 定义) */
|
|
76
113
|
static async create(options) {
|
|
114
|
+
return CoreMindRuntime.createWithWorkspaceLease(options, new WorkspaceLeaseService());
|
|
115
|
+
}
|
|
116
|
+
/** 同一父子树复用一个 Lease 服务;跨进程一致性仍由 canonical lock file 提供。 */
|
|
117
|
+
static async createWithWorkspaceLease(options, workspaceLeaseService) {
|
|
77
118
|
const { config, configDir } = options;
|
|
78
119
|
const cwd = options.cwd ?? process.cwd();
|
|
79
120
|
const env = options.env ?? process.env;
|
|
121
|
+
const requestedToolEnv = options.toolEnv ?? env;
|
|
122
|
+
const toolEnv = options.childRunAuthority
|
|
123
|
+
? delegatedToolEnvironment(requestedToolEnv)
|
|
124
|
+
: requestedToolEnv;
|
|
125
|
+
enforceExecutionSecurity(config);
|
|
80
126
|
const emit = options.events ?? (() => { });
|
|
127
|
+
if (options.toolDefinitions?.some((definition) => definition.name === DELEGATION_TOOL_NAME)) {
|
|
128
|
+
throw new CoreMindError("invalid_tool", "自定义工具不得使用内建工具名 delegate");
|
|
129
|
+
}
|
|
130
|
+
if (options.childRunAuthority && (options.toolDefinitions?.length ?? 0) > 0) {
|
|
131
|
+
throw new CoreMindError("child_run_policy_escalation", "Child Runtime 不接受缺少内建 provenance 的注入工具");
|
|
132
|
+
}
|
|
81
133
|
// 1. provider(解析模型,警告转发)
|
|
82
|
-
const providerRuntime = await buildProviderRuntime(config.provider, env);
|
|
134
|
+
const providerRuntime = await buildProviderRuntime(config.provider, env, options.secretResolver);
|
|
83
135
|
for (const warning of providerRuntime.warnings) {
|
|
84
136
|
emit({ type: "error", message: warning, fatal: false });
|
|
85
137
|
}
|
|
86
138
|
// 2. 每个 agent:构建工具与技能(Agent 实例按需创建,避免并发冲突)
|
|
87
139
|
const agentConfigs = new Map();
|
|
88
|
-
const
|
|
140
|
+
const agentModels = new Map();
|
|
141
|
+
const driverBuilders = new Map();
|
|
89
142
|
const toolEffectsByAgent = new Map();
|
|
143
|
+
const toolCapabilitiesByAgent = new Map();
|
|
90
144
|
const skillsByAgent = new Map();
|
|
91
145
|
const artifactStore = new ArtifactStore({ cwd });
|
|
146
|
+
const executionEnvironment = createPlatformExecutionEnvironment({
|
|
147
|
+
workspaceRoot: cwd,
|
|
148
|
+
env: toolEnv,
|
|
149
|
+
});
|
|
92
150
|
const externalTools = (options.toolDefinitions ?? []).map((definition) => wrapToolWithArtifactCapture(adaptCoreMindTool(definition), artifactStore));
|
|
151
|
+
let runtime;
|
|
93
152
|
// 自定义技能(生态机制):配置文件所在目录的 skills/ 下,每个子目录的 README.md 即一个技能
|
|
94
153
|
const customSkills = await loadDirectorySkills(path.join(configDir, "skills"));
|
|
95
154
|
for (const [name, agentCfg] of Object.entries(config.agents)) {
|
|
155
|
+
const agentModel = resolveProviderModel(providerRuntime, agentCfg.model);
|
|
156
|
+
agentModels.set(name, agentModel);
|
|
96
157
|
const toolConfigs = (agentCfg.tools?.length ?? 0) > 0 ? agentCfg.tools : config.tools;
|
|
97
|
-
const { tools, warnings, effects } = await
|
|
158
|
+
const { tools, warnings, effects, capabilities } = await buildToolsWithExecutionEnvironment(toolConfigs ?? [], {
|
|
98
159
|
cwd,
|
|
99
160
|
configDir,
|
|
100
|
-
env,
|
|
161
|
+
env: toolEnv,
|
|
101
162
|
artifactStore,
|
|
102
|
-
});
|
|
163
|
+
}, executionEnvironment);
|
|
103
164
|
for (const warning of warnings) {
|
|
104
165
|
emit({ type: "error", message: warning, fatal: false });
|
|
105
166
|
}
|
|
106
167
|
agentConfigs.set(name, agentCfg);
|
|
107
|
-
|
|
168
|
+
const delegationTargets = Object.keys(agentCfg.delegation?.targets ?? {});
|
|
169
|
+
const delegationTool = delegationTargets.length > 0
|
|
170
|
+
? createDelegationAgentTool(delegationTargets, async (args, callId) => {
|
|
171
|
+
if (!runtime) {
|
|
172
|
+
throw new CoreMindError("child_run_unavailable", "Runtime 尚未完成初始化");
|
|
173
|
+
}
|
|
174
|
+
return runtime.executeConfiguredDelegation(name, args, callId);
|
|
175
|
+
})
|
|
176
|
+
: undefined;
|
|
177
|
+
const delegationDispositionTool = delegationTool
|
|
178
|
+
? createDelegationDispositionAgentTool(async (args, callId) => {
|
|
179
|
+
if (!runtime) {
|
|
180
|
+
throw new CoreMindError("child_run_unavailable", "Runtime 尚未完成初始化");
|
|
181
|
+
}
|
|
182
|
+
return runtime.executeConfiguredDelegationDisposition(name, args, callId);
|
|
183
|
+
})
|
|
184
|
+
: undefined;
|
|
185
|
+
const driverTools = [
|
|
186
|
+
...tools,
|
|
187
|
+
...externalTools,
|
|
188
|
+
...(delegationTool ? [delegationTool] : []),
|
|
189
|
+
...(delegationDispositionTool ? [delegationDispositionTool] : []),
|
|
190
|
+
];
|
|
191
|
+
const delegationEffects = delegationTool
|
|
192
|
+
? [
|
|
193
|
+
[DELEGATION_TOOL_NAME, DELEGATION_TOOL_EFFECT],
|
|
194
|
+
[DELEGATION_DISPOSITION_TOOL_NAME, DELEGATION_DISPOSITION_TOOL_EFFECT],
|
|
195
|
+
]
|
|
196
|
+
: [];
|
|
197
|
+
const delegationCapabilities = delegationTool
|
|
198
|
+
? [
|
|
199
|
+
[DELEGATION_TOOL_NAME, DELEGATION_TOOL_CAPABILITY],
|
|
200
|
+
[DELEGATION_DISPOSITION_TOOL_NAME, DELEGATION_DISPOSITION_TOOL_CAPABILITY],
|
|
201
|
+
]
|
|
202
|
+
: [];
|
|
108
203
|
toolEffectsByAgent.set(name, new Map([
|
|
109
204
|
...effects,
|
|
110
205
|
...(options.toolDefinitions ?? []).map((definition) => [definition.name, definition.effect]),
|
|
206
|
+
...delegationEffects,
|
|
207
|
+
]));
|
|
208
|
+
toolCapabilitiesByAgent.set(name, new Map([
|
|
209
|
+
...capabilities,
|
|
210
|
+
...(options.toolDefinitions ?? []).map((definition) => [
|
|
211
|
+
definition.name,
|
|
212
|
+
definition.capability
|
|
213
|
+
? resolveToolCapability({
|
|
214
|
+
tool: definition.name,
|
|
215
|
+
source: "registered",
|
|
216
|
+
declaration: definition.capability,
|
|
217
|
+
})
|
|
218
|
+
: inferLegacyToolCapability(definition.name, definition.effect),
|
|
219
|
+
]),
|
|
220
|
+
...delegationCapabilities,
|
|
111
221
|
]));
|
|
112
222
|
// 技能:内置优先,未命中的查自定义目录,仍缺失才告警(不阻断)
|
|
113
223
|
const { contents, missing } = resolveSkills(agentCfg.skills ?? []);
|
|
@@ -126,6 +236,25 @@ export class CoreMindRuntime {
|
|
|
126
236
|
}
|
|
127
237
|
}
|
|
128
238
|
skillsByAgent.set(name, allContents);
|
|
239
|
+
driverBuilders.set(name, ({ onEvent, harness, sessionMessages }) => buildAgentDriver(agentCfg, {
|
|
240
|
+
models: providerRuntime.models,
|
|
241
|
+
model: agentModel,
|
|
242
|
+
tools: driverTools,
|
|
243
|
+
agentName: name,
|
|
244
|
+
onEvent,
|
|
245
|
+
apiKeyOverride: providerRuntime.apiKeyOverride,
|
|
246
|
+
sessionMessages,
|
|
247
|
+
skillsContent: allContents,
|
|
248
|
+
stableFacts: {
|
|
249
|
+
provider: agentModel.provider,
|
|
250
|
+
model: agentModel.id,
|
|
251
|
+
contextWindow: agentModel.contextWindow,
|
|
252
|
+
},
|
|
253
|
+
promptCacheStatus: agentModel.cost.cacheRead > 0 || agentModel.cost.cacheWrite > 0
|
|
254
|
+
? "available"
|
|
255
|
+
: "unavailable",
|
|
256
|
+
harness,
|
|
257
|
+
}));
|
|
129
258
|
}
|
|
130
259
|
// 会话恢复:--session 且 session.enabled 时,打开已有会话注入历史视图(非破坏)
|
|
131
260
|
let sessionMessages;
|
|
@@ -135,10 +264,10 @@ export class CoreMindRuntime {
|
|
|
135
264
|
try {
|
|
136
265
|
if (await CoreMindSession.exists(dir, options.sessionId, cwd)) {
|
|
137
266
|
const cm = await CoreMindSession.open({ dir, sessionId: options.sessionId, cwd });
|
|
138
|
-
const
|
|
139
|
-
if (
|
|
140
|
-
sessionMessages =
|
|
141
|
-
resumedContextLength =
|
|
267
|
+
const restored = projectBranchMessages(await cm.branchEntries()).map((item) => item.message);
|
|
268
|
+
if (restored.length > 0) {
|
|
269
|
+
sessionMessages = restored;
|
|
270
|
+
resumedContextLength = restored.length;
|
|
142
271
|
}
|
|
143
272
|
}
|
|
144
273
|
}
|
|
@@ -147,44 +276,62 @@ export class CoreMindRuntime {
|
|
|
147
276
|
throw new CoreMindError("session_restore_failed", `会话 ${options.sessionId} 恢复失败:${detail}`);
|
|
148
277
|
}
|
|
149
278
|
}
|
|
150
|
-
|
|
279
|
+
runtime = new CoreMindRuntime(config, agentConfigs, agentModels, driverBuilders, toolEffectsByAgent, toolCapabilitiesByAgent, providerRuntime, executionEnvironment, workspaceLeaseService, options, sessionMessages, resumedContextLength, skillsByAgent);
|
|
280
|
+
return runtime;
|
|
151
281
|
}
|
|
152
|
-
/** 按名字创建独立
|
|
282
|
+
/** 按名字创建独立 Driver 实例(每次新实例,消息历史独立) */
|
|
153
283
|
createAgent(name, onEvent = this.options.events ?? (() => { }), stepId) {
|
|
154
|
-
const
|
|
155
|
-
if (!
|
|
284
|
+
const buildDriver = this.driverBuilders.get(name);
|
|
285
|
+
if (!buildDriver)
|
|
156
286
|
return undefined;
|
|
157
|
-
const
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
model: this.providerRuntime.model,
|
|
161
|
-
tools: this.toolsByAgent.get(name) ?? [],
|
|
162
|
-
agentName: name,
|
|
287
|
+
const context = runContextFor(this);
|
|
288
|
+
const harness = context.harnessFor(name, stepId);
|
|
289
|
+
const agent = buildDriver({
|
|
163
290
|
onEvent,
|
|
164
|
-
apiKeyOverride: this.providerRuntime.apiKeyOverride,
|
|
165
291
|
// 恢复视图只注入主 agent(会话归属者)
|
|
166
292
|
sessionMessages: name === this.mainAgentName ? this.sessionMessages : undefined,
|
|
167
|
-
skillsContent: this.skillsByAgent.get(name),
|
|
168
|
-
stableFacts: {
|
|
169
|
-
provider: this.providerRuntime.model.provider,
|
|
170
|
-
model: this.providerRuntime.model.id,
|
|
171
|
-
contextWindow: this.providerRuntime.model.contextWindow,
|
|
172
|
-
},
|
|
173
|
-
promptCacheStatus: this.providerRuntime.promptCacheStatus,
|
|
174
293
|
harness,
|
|
175
294
|
});
|
|
176
|
-
|
|
177
|
-
agent.shouldStopAfterTurn = harness?.shouldStopAfterTurn;
|
|
178
|
-
if (harness?.throwIfDenied) {
|
|
179
|
-
const waitForIdle = agent.waitForIdle.bind(agent);
|
|
180
|
-
agent.waitForIdle = async () => {
|
|
181
|
-
await waitForIdle();
|
|
182
|
-
harness.throwIfDenied?.();
|
|
183
|
-
};
|
|
184
|
-
}
|
|
185
|
-
this.lastAgents.set(name, agent);
|
|
295
|
+
context.registerAgent(name, agent);
|
|
186
296
|
return agent;
|
|
187
297
|
}
|
|
298
|
+
/** 返回命名 Agent 在项目 Provider 内的固定模型与参数快照。 */
|
|
299
|
+
modelSnapshotFor(agentName, tokenLimit) {
|
|
300
|
+
const model = this.agentModels.get(agentName);
|
|
301
|
+
if (!model) {
|
|
302
|
+
throw new CoreMindError("unknown_agent", `配置中没有可用的 agent:${agentName}`);
|
|
303
|
+
}
|
|
304
|
+
const configuredOptions = this.agentConfigs.get(agentName)?.options;
|
|
305
|
+
const options = tokenLimit === undefined
|
|
306
|
+
? configuredOptions
|
|
307
|
+
: {
|
|
308
|
+
...configuredOptions,
|
|
309
|
+
maxTokens: Math.min(configuredOptions?.maxTokens ?? tokenLimit, tokenLimit),
|
|
310
|
+
};
|
|
311
|
+
return {
|
|
312
|
+
providerId: model.provider,
|
|
313
|
+
model: model.id,
|
|
314
|
+
providerConfigFingerprint: fingerprintEffectReceiptValue(this.config.provider ?? null),
|
|
315
|
+
agentPromptFingerprint: fingerprintEffectReceiptValue({
|
|
316
|
+
systemPrompt: this.agentConfigs.get(agentName)?.systemPrompt ?? "",
|
|
317
|
+
skillsContent: this.skillsByAgent.get(agentName) ?? [],
|
|
318
|
+
}),
|
|
319
|
+
agentDelegationFingerprint: fingerprintEffectReceiptValue(this.agentConfigs.get(agentName)?.delegation ?? null),
|
|
320
|
+
...(options ? { options: structuredClone(options) } : {}),
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
/** 只从当前父 Agent 的 Config allowlist 构建可委派模型路由。 */
|
|
324
|
+
delegationModelRoutesFor(agentName) {
|
|
325
|
+
const targets = this.agentConfigs.get(agentName)?.delegation?.targets ?? {};
|
|
326
|
+
return Object.fromEntries(Object.keys(targets).map((targetName) => [targetName, this.modelSnapshotFor(targetName)]));
|
|
327
|
+
}
|
|
328
|
+
/** 为同一 Runtime 内所有可能发起委派的 Agent 固化二级模型路由。 */
|
|
329
|
+
delegationModelRoutes() {
|
|
330
|
+
return Object.fromEntries([...this.agentConfigs.keys()].map((agentName) => [
|
|
331
|
+
agentName,
|
|
332
|
+
this.delegationModelRoutesFor(agentName),
|
|
333
|
+
]));
|
|
334
|
+
}
|
|
188
335
|
/** 查询配置中是否存在 Agent,供交互会话在首轮前快速失败。 */
|
|
189
336
|
hasAgent(name) {
|
|
190
337
|
return this.agentConfigs.has(name);
|
|
@@ -205,14 +352,35 @@ export class CoreMindRuntime {
|
|
|
205
352
|
}
|
|
206
353
|
const turnConfig = { ...this.config, defaultAgent: agentName };
|
|
207
354
|
delete turnConfig.workflow;
|
|
208
|
-
const turnRuntime = new CoreMindRuntime(turnConfig, this.agentConfigs, this.
|
|
355
|
+
const turnRuntime = new CoreMindRuntime(turnConfig, this.agentConfigs, this.agentModels, this.driverBuilders, this.toolEffectsByAgent, this.toolCapabilitiesByAgent, this.providerRuntime, this.executionEnvironment, this.workspaceLeaseService, {
|
|
209
356
|
...this.options,
|
|
210
357
|
config: turnConfig,
|
|
211
358
|
initialPrompt: message,
|
|
212
359
|
events,
|
|
213
360
|
signal,
|
|
214
361
|
}, history, history.length, this.skillsByAgent);
|
|
215
|
-
|
|
362
|
+
const unbindActiveRun = bindActiveRun(this, {
|
|
363
|
+
inspectProjection: () => turnRuntime.inspectPersistedRunProjection(),
|
|
364
|
+
executeDelegation: (parentAgentName, rawArgs, callId) => turnRuntime.executeConfiguredDelegation(parentAgentName, rawArgs, callId),
|
|
365
|
+
executeDelegationDisposition: (parentAgentName, rawArgs, callId) => turnRuntime.executeConfiguredDelegationDisposition(parentAgentName, rawArgs, callId),
|
|
366
|
+
});
|
|
367
|
+
try {
|
|
368
|
+
return await turnRuntime.run();
|
|
369
|
+
}
|
|
370
|
+
finally {
|
|
371
|
+
unbindActiveRun();
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
/** 从已持久化 canonical Facts 重建当前运行视图。 */
|
|
375
|
+
async inspectPersistedRunProjection() {
|
|
376
|
+
const context = executionSlotFor(this).kernel?.currentContext();
|
|
377
|
+
const runId = context?.currentRunId();
|
|
378
|
+
if (!context || !runId || !this.activeRunStore)
|
|
379
|
+
return undefined;
|
|
380
|
+
const records = await this.activeRunStore.read(runId);
|
|
381
|
+
return records.length > 0
|
|
382
|
+
? ProjectionEngine.projectTree(this.activeRunStore, runId)
|
|
383
|
+
: undefined;
|
|
216
384
|
}
|
|
217
385
|
inspectCheckpoint(record) {
|
|
218
386
|
return inspectStoredCheckpoint(record, this.options.cwd ?? process.cwd());
|
|
@@ -222,49 +390,404 @@ export class CoreMindRuntime {
|
|
|
222
390
|
}
|
|
223
391
|
/** 执行:有 workflow 走编排,否则单 agent 直答。返回结果含质量摘要 */
|
|
224
392
|
async run() {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
393
|
+
const slot = executionSlotFor(this);
|
|
394
|
+
slot.kernel ??= new RunKernel({ execute: (context) => this.executeRunBody(context) });
|
|
395
|
+
return slot.kernel.run();
|
|
396
|
+
}
|
|
397
|
+
/** 在活动父 Run 上创建类型化 Child Run;未配置或尚未启动时失败关闭。 */
|
|
398
|
+
async delegateChildRun(request) {
|
|
399
|
+
if (!executionSlotFor(this).kernel?.currentContext()) {
|
|
400
|
+
throw new CoreMindError("child_run_unavailable", "当前 Runtime 没有活动父 Run");
|
|
228
401
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
402
|
+
for (let attempt = 0; attempt < 5_000; attempt++) {
|
|
403
|
+
const childRuns = executionSlotFor(this).kernel?.currentContext()?.currentChildRuns();
|
|
404
|
+
if (childRuns)
|
|
405
|
+
return childRuns.delegate(request);
|
|
406
|
+
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
233
407
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
408
|
+
throw new CoreMindError("child_run_unavailable", "当前 Runtime 未启用 Child Run 或尚未进入活动状态");
|
|
409
|
+
}
|
|
410
|
+
/** Adapter 执行前验证工厂没有丢失或放宽 Child Run 身份、取消与策略。 */
|
|
411
|
+
async verifyChildRunAuthority(input) {
|
|
412
|
+
if (this.options.childRunAuthority !== input ||
|
|
413
|
+
this.options.runId !== input.childRunId ||
|
|
414
|
+
this.options.signal !== input.signal ||
|
|
415
|
+
this.options.initialPrompt !== delegatedInitialPrompt(input.request)) {
|
|
416
|
+
throw new CoreMindError("child_run_identity_mismatch", "Child Runtime 未绑定原始委派输入、RunId、AbortSignal 或任务输入");
|
|
417
|
+
}
|
|
418
|
+
if (this.mainAgentName !== input.request.agentName) {
|
|
419
|
+
throw new CoreMindError("child_run_identity_mismatch", "Child Runtime 默认 Agent 与持久化 Delegation Target 不一致");
|
|
420
|
+
}
|
|
421
|
+
if ((this.config.workflow?.length ?? 0) > 0 || this.config.loop) {
|
|
422
|
+
throw new CoreMindError("child_run_policy_escalation", "Child Runtime 只能执行固定命名目标,不能通过 workflow 或 loop 切换 Agent");
|
|
423
|
+
}
|
|
424
|
+
await assertRuntimeChildPolicyAuthority({
|
|
425
|
+
policy: input.inheritedPolicy,
|
|
426
|
+
config: this.config,
|
|
427
|
+
model: this.modelSnapshotFor(this.mainAgentName),
|
|
428
|
+
executionEnvironment: this.executionEnvironment,
|
|
429
|
+
workspaceRoot: this.options.cwd ?? process.cwd(),
|
|
430
|
+
tools: new Set(this.runtimeAuthorityToolIds()),
|
|
431
|
+
limits: resolveRuntimeLimits(this.config.runtime, {
|
|
432
|
+
maxSteps: this.options.maxSteps,
|
|
433
|
+
stepTimeoutMs: this.options.stepTimeoutMs,
|
|
434
|
+
}),
|
|
435
|
+
enforceRuntimeBudget: true,
|
|
436
|
+
enforceDelegatedToolBoundary: true,
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
runtimeAuthorityToolIds() {
|
|
440
|
+
const activeAgent = this.options.childRunAuthority ? this.config.defaultAgent : undefined;
|
|
441
|
+
const capabilities = activeAgent
|
|
442
|
+
? [this.toolCapabilitiesByAgent.get(activeAgent)]
|
|
443
|
+
: [...this.toolCapabilitiesByAgent.values()];
|
|
444
|
+
return [
|
|
445
|
+
...new Set(capabilities.flatMap((items) => items
|
|
446
|
+
? [...items.keys()].filter((tool) => tool !== DELEGATION_TOOL_NAME && tool !== DELEGATION_DISPOSITION_TOOL_NAME)
|
|
447
|
+
: [])),
|
|
448
|
+
];
|
|
449
|
+
}
|
|
450
|
+
/** 接收已类型化控制;ACK 只由当前 Run 的持久 ControlInbox 产生。 */
|
|
451
|
+
async acceptControl(command) {
|
|
452
|
+
for (let attempt = 0; attempt < 5_000; attempt++) {
|
|
453
|
+
const inbox = this.currentControlInbox();
|
|
454
|
+
if (inbox)
|
|
455
|
+
return inbox.accept(command);
|
|
456
|
+
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
457
|
+
}
|
|
458
|
+
throw new CoreMindError("control_unavailable", `等待 Runtime ${command.runId} 的 ControlInbox 超时`);
|
|
459
|
+
}
|
|
460
|
+
/** 当新的可应用点出现时,重试仍处于 accepted 的持久控制。 */
|
|
461
|
+
async applyPendingControls() {
|
|
462
|
+
const inbox = this.currentControlInbox();
|
|
463
|
+
return inbox?.applyPending() ?? [];
|
|
464
|
+
}
|
|
465
|
+
currentControlInbox() {
|
|
466
|
+
return executionSlotFor(this).kernel?.currentContext()?.currentControlInbox();
|
|
467
|
+
}
|
|
468
|
+
async createConfiguredChildRunOptions(limits, runStore) {
|
|
469
|
+
const configuredDelegations = [...this.agentConfigs.entries()].filter(([, agent]) => agent.delegation && Object.keys(agent.delegation.targets).length > 0);
|
|
470
|
+
if (configuredDelegations.length === 0)
|
|
471
|
+
return undefined;
|
|
472
|
+
if (limits.maxTokens === undefined || limits.maxCostUsd === undefined) {
|
|
473
|
+
throw new CoreMindError("child_run_policy_escalation", "启用 Delegation Tool 前必须为 Runtime 显式配置 maxTokens 与 maxCostUsd");
|
|
474
|
+
}
|
|
475
|
+
const permissions = this.config.permissions ?? {};
|
|
476
|
+
const inheritedPolicy = this.options.childRunAuthority?.inheritedPolicy;
|
|
477
|
+
const runtimeBudget = inheritedPolicy?.budget ?? {
|
|
478
|
+
tokens: limits.maxTokens,
|
|
479
|
+
toolCalls: limits.maxToolCalls,
|
|
480
|
+
costUsd: limits.maxCostUsd,
|
|
481
|
+
wallTimeMs: limits.runTimeoutMs,
|
|
482
|
+
steps: limits.maxSteps,
|
|
483
|
+
descendants: CHILD_RUN_LIMIT_DEFAULTS.maxDescendants,
|
|
484
|
+
};
|
|
485
|
+
const delegationBudgetPools = Object.fromEntries(configuredDelegations.map(([agentName, agent]) => [
|
|
486
|
+
agentName,
|
|
487
|
+
tightenDelegationBudget(agent.delegation.budget, runtimeBudget),
|
|
488
|
+
]));
|
|
489
|
+
const delegationHierarchyLimits = Object.fromEntries(configuredDelegations.map(([agentName, agent]) => {
|
|
490
|
+
const budget = delegationBudgetPools[agentName];
|
|
491
|
+
return [
|
|
492
|
+
agentName,
|
|
493
|
+
{
|
|
494
|
+
maxDepth: Math.min(agent.delegation.limits?.maxDepth ?? CHILD_RUN_LIMIT_DEFAULTS.maxDepth, inheritedPolicy?.maxDepth ?? CHILD_RUN_LIMIT_DEFAULTS.maxDepth),
|
|
495
|
+
maxActiveChildren: Math.min(agent.delegation.limits?.maxActiveChildren ??
|
|
496
|
+
CHILD_RUN_LIMIT_DEFAULTS.maxActiveChildren, inheritedPolicy?.maxActiveChildren ?? CHILD_RUN_LIMIT_DEFAULTS.maxActiveChildren),
|
|
497
|
+
maxDescendants: Math.min(agent.delegation.limits?.maxDescendants ?? CHILD_RUN_LIMIT_DEFAULTS.maxDescendants, inheritedPolicy?.maxDescendants ?? CHILD_RUN_LIMIT_DEFAULTS.maxDescendants, budget.descendants),
|
|
498
|
+
},
|
|
499
|
+
];
|
|
500
|
+
}));
|
|
501
|
+
const parentPolicy = {
|
|
502
|
+
depth: inheritedPolicy?.depth ?? 0,
|
|
503
|
+
budget: structuredClone(runtimeBudget),
|
|
504
|
+
permissions: inheritedPolicy?.permissions ??
|
|
505
|
+
{
|
|
506
|
+
mode: permissions.mode ?? "ask",
|
|
507
|
+
workspaceOnly: permissions.workspaceOnly ?? true,
|
|
508
|
+
network: permissions.network ?? "ask",
|
|
509
|
+
tools: [
|
|
510
|
+
...new Set([...this.toolCapabilitiesByAgent.values()].flatMap((capabilities) => [
|
|
511
|
+
...capabilities.keys(),
|
|
512
|
+
])),
|
|
513
|
+
],
|
|
514
|
+
paths: ["."],
|
|
515
|
+
credentials: [],
|
|
516
|
+
},
|
|
517
|
+
environment: inheritedPolicy?.environment ?? {},
|
|
518
|
+
model: inheritedPolicy?.model ?? this.modelSnapshotFor(this.mainAgentName),
|
|
519
|
+
workspace: inheritedPolicy?.workspace ??
|
|
520
|
+
{
|
|
521
|
+
canonicalRoot: await canonicalizeWorkspace(this.options.cwd ?? process.cwd()),
|
|
522
|
+
lease: "shared_canonical",
|
|
523
|
+
},
|
|
524
|
+
protectedContextReferences: inheritedPolicy?.protectedContextReferences ?? [],
|
|
525
|
+
protectedContextResolvedReferences: inheritedPolicy?.protectedContextResolvedReferences ?? [],
|
|
526
|
+
delegationModelRoutes: this.delegationModelRoutes(),
|
|
527
|
+
maxDepth: inheritedPolicy?.maxDepth ?? CHILD_RUN_LIMIT_DEFAULTS.maxDepth,
|
|
528
|
+
maxActiveChildren: inheritedPolicy?.maxActiveChildren ?? CHILD_RUN_LIMIT_DEFAULTS.maxActiveChildren,
|
|
529
|
+
maxDescendants: Math.min(inheritedPolicy?.maxDescendants ?? CHILD_RUN_LIMIT_DEFAULTS.maxDescendants, runtimeBudget.descendants),
|
|
530
|
+
};
|
|
531
|
+
return {
|
|
532
|
+
parentPolicy,
|
|
533
|
+
delegationBudgetPools,
|
|
534
|
+
delegationHierarchyLimits,
|
|
535
|
+
createChildRunId: () => randomUUID(),
|
|
536
|
+
adapter: createCoreMindChildRunAdapter({
|
|
537
|
+
createRuntime: async (authority) => {
|
|
538
|
+
const target = this.config.agents[authority.request.agentName];
|
|
539
|
+
if (!target) {
|
|
540
|
+
throw new CoreMindError("child_run_policy_escalation", `委派目标 Agent ${authority.request.agentName} 不存在`);
|
|
541
|
+
}
|
|
542
|
+
const { workflow: _workflow, loop: _loop, ...baseConfig } = this.config;
|
|
543
|
+
const childAgents = structuredClone(this.config.agents);
|
|
544
|
+
for (const agent of Object.values(childAgents)) {
|
|
545
|
+
if (agent.tools)
|
|
546
|
+
agent.tools = agent.tools.filter(isDelegatedBuiltinToolConfig);
|
|
547
|
+
}
|
|
548
|
+
childAgents[authority.request.agentName] = {
|
|
549
|
+
...target,
|
|
550
|
+
...(target.tools ? { tools: target.tools.filter(isDelegatedBuiltinToolConfig) } : {}),
|
|
551
|
+
model: authority.request.model.model,
|
|
552
|
+
options: authority.request.model.options,
|
|
553
|
+
};
|
|
554
|
+
const childConfig = {
|
|
555
|
+
...baseConfig,
|
|
556
|
+
...(baseConfig.tools
|
|
557
|
+
? { tools: baseConfig.tools.filter(isDelegatedBuiltinToolConfig) }
|
|
558
|
+
: {}),
|
|
559
|
+
agents: childAgents,
|
|
560
|
+
defaultAgent: authority.request.agentName,
|
|
561
|
+
runtime: {
|
|
562
|
+
...baseConfig.runtime,
|
|
563
|
+
maxSteps: authority.request.allocation.steps,
|
|
564
|
+
maxToolCalls: authority.request.allocation.toolCalls,
|
|
565
|
+
maxTokens: authority.request.allocation.tokens,
|
|
566
|
+
maxCostUsd: authority.request.allocation.costUsd,
|
|
567
|
+
runTimeoutMs: authority.request.allocation.wallTimeMs,
|
|
568
|
+
stepTimeoutMs: Math.min(baseConfig.runtime?.stepTimeoutMs ?? authority.request.allocation.wallTimeMs, authority.request.allocation.wallTimeMs),
|
|
569
|
+
},
|
|
570
|
+
};
|
|
571
|
+
return CoreMindRuntime.createWithWorkspaceLease({
|
|
572
|
+
config: childConfig,
|
|
573
|
+
configDir: this.options.configDir,
|
|
574
|
+
cwd: this.options.cwd,
|
|
575
|
+
env: this.options.env,
|
|
576
|
+
toolEnv: delegatedToolEnvironment(this.options.env ?? process.env),
|
|
577
|
+
secretResolver: this.options.secretResolver,
|
|
578
|
+
initialPrompt: delegatedInitialPrompt(authority.request),
|
|
579
|
+
events: this.options.events,
|
|
580
|
+
trace: this.options.trace,
|
|
581
|
+
approveTool: this.options.approveTool,
|
|
582
|
+
runStore,
|
|
583
|
+
runId: authority.childRunId,
|
|
584
|
+
childRunAuthority: authority,
|
|
585
|
+
signal: authority.signal,
|
|
586
|
+
}, this.workspaceLeaseService);
|
|
587
|
+
},
|
|
588
|
+
}),
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
async executeConfiguredDelegation(parentAgentName, rawArgs, callId) {
|
|
592
|
+
const executeInActiveRun = boundDelegationExecutor(this);
|
|
593
|
+
if (executeInActiveRun)
|
|
594
|
+
return executeInActiveRun(parentAgentName, rawArgs, callId);
|
|
595
|
+
const { context, childRuns, request } = await this.prepareConfiguredDelegationRequest(parentAgentName, rawArgs, callId);
|
|
596
|
+
const inputFingerprint = childRunInputFingerprint(request);
|
|
597
|
+
const approvedInputFingerprint = context.consumeDelegationApproval(parentAgentName, callId);
|
|
598
|
+
if (approvedInputFingerprint !== inputFingerprint) {
|
|
599
|
+
throw new CoreMindError("child_run_policy_escalation", "Delegation Approval 与实际 Child Run 输入指纹不一致");
|
|
600
|
+
}
|
|
601
|
+
const handle = await childRuns.delegate(request);
|
|
602
|
+
const result = await handle.join({ timeoutMs: request.allocation.wallTimeMs });
|
|
603
|
+
const output = {
|
|
604
|
+
childRunId: handle.childRunId,
|
|
605
|
+
delegationId: handle.delegationId,
|
|
606
|
+
result,
|
|
607
|
+
};
|
|
608
|
+
return {
|
|
609
|
+
content: [{ type: "text", text: JSON.stringify(output) }],
|
|
610
|
+
details: output,
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
async executeConfiguredDelegationDisposition(parentAgentName, rawArgs, callId) {
|
|
614
|
+
const executeInActiveRun = boundDelegationDispositionExecutor(this);
|
|
615
|
+
if (executeInActiveRun)
|
|
616
|
+
return executeInActiveRun(parentAgentName, rawArgs, callId);
|
|
617
|
+
const context = executionSlotFor(this).kernel?.currentContext();
|
|
618
|
+
const call = context?.toolCall(parentAgentName, callId);
|
|
619
|
+
const childRuns = context?.currentChildRuns();
|
|
620
|
+
if (!context || !call || !childRuns) {
|
|
621
|
+
throw new CoreMindError("child_run_unavailable", "Delegation Disposition 只能在已登记 Tool Call 的活动父 Run 内执行");
|
|
622
|
+
}
|
|
623
|
+
const args = parseDelegationDispositionToolArgs(rawArgs);
|
|
624
|
+
const disposition = await childRuns.recordDisposition({
|
|
625
|
+
dispositionId: `disposition:${call.turnId}:${call.callId}`,
|
|
626
|
+
delegationId: args.delegationId,
|
|
627
|
+
action: args.action,
|
|
628
|
+
decidedBy: "parent_agent",
|
|
629
|
+
reason: args.reason,
|
|
630
|
+
});
|
|
631
|
+
const output = { delegationId: args.delegationId, disposition };
|
|
632
|
+
return {
|
|
633
|
+
content: [{ type: "text", text: JSON.stringify(output) }],
|
|
634
|
+
details: output,
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
/** 在审批和执行阶段生成同一份 Child Run 请求,不产生 Fact 或预留预算副作用。 */
|
|
638
|
+
async prepareConfiguredDelegationRequest(parentAgentName, rawArgs, callId) {
|
|
639
|
+
const context = executionSlotFor(this).kernel?.currentContext();
|
|
640
|
+
const parentRunId = context?.currentRunId();
|
|
641
|
+
const call = context?.toolCall(parentAgentName, callId);
|
|
642
|
+
const childRuns = context?.currentChildRuns();
|
|
643
|
+
if (!context || !parentRunId || !call || !childRuns) {
|
|
644
|
+
throw new CoreMindError("child_run_unavailable", "Delegation Tool 只能在已登记 Tool Call 的活动父 Run 内执行");
|
|
645
|
+
}
|
|
646
|
+
const { args, targetTools, allocation, hierarchyLimits } = this.resolveDelegationAuthority(parentAgentName, rawArgs);
|
|
647
|
+
const permissions = this.config.permissions ?? {};
|
|
648
|
+
const activeRunStore = this.activeRunStore;
|
|
649
|
+
if (!activeRunStore) {
|
|
650
|
+
throw new CoreMindError("child_run_unavailable", "活动父 Run 缺少可解析 Fact 的 RunStore");
|
|
651
|
+
}
|
|
652
|
+
const resolvedReferences = resolveDelegatedContextReferences({
|
|
653
|
+
references: args.references,
|
|
654
|
+
parentFacts: await activeRunStore.read(parentRunId),
|
|
655
|
+
artifacts: context.artifactRecords(),
|
|
656
|
+
inheritedReferences: this.options.childRunAuthority?.inheritedPolicy.protectedContextResolvedReferences,
|
|
657
|
+
});
|
|
658
|
+
const request = {
|
|
659
|
+
delegationId: `delegation:${call.turnId}:${call.callId}`,
|
|
660
|
+
...(args.recoveryOf ? { predecessorDelegationId: args.recoveryOf } : {}),
|
|
661
|
+
budgetScope: parentAgentName,
|
|
662
|
+
parentTurnId: call.turnId,
|
|
663
|
+
parentStepId: call.stepId ?? `step:${parentAgentName}:default`,
|
|
664
|
+
agentName: args.target,
|
|
665
|
+
task: args.task,
|
|
666
|
+
model: this.modelSnapshotFor(args.target, allocation.tokens),
|
|
667
|
+
workspace: {
|
|
668
|
+
canonicalRoot: await canonicalizeWorkspace(this.options.cwd ?? process.cwd()),
|
|
669
|
+
lease: "shared_canonical",
|
|
670
|
+
},
|
|
671
|
+
lifecyclePolicy: {
|
|
672
|
+
join: "structured",
|
|
673
|
+
cancel: "propagate_parent",
|
|
674
|
+
orphan: "audit_pause",
|
|
675
|
+
detach: "forbidden",
|
|
676
|
+
},
|
|
677
|
+
context: {
|
|
678
|
+
workingSetFingerprint: fingerprintEffectReceiptValue({
|
|
679
|
+
parentRunId,
|
|
680
|
+
parentTurnId: call.turnId,
|
|
681
|
+
task: args.task,
|
|
682
|
+
references: args.references,
|
|
683
|
+
resolvedReferences,
|
|
684
|
+
}),
|
|
685
|
+
references: args.references,
|
|
686
|
+
resolvedReferences,
|
|
687
|
+
},
|
|
688
|
+
allocation,
|
|
689
|
+
hierarchyLimits,
|
|
690
|
+
permissions: {
|
|
691
|
+
mode: permissions.mode ?? "ask",
|
|
692
|
+
workspaceOnly: permissions.workspaceOnly ?? true,
|
|
693
|
+
network: permissions.network ?? "ask",
|
|
694
|
+
tools: targetTools,
|
|
695
|
+
paths: ["."],
|
|
696
|
+
credentials: [],
|
|
697
|
+
},
|
|
698
|
+
environment: {},
|
|
699
|
+
};
|
|
700
|
+
return { context, childRuns, request };
|
|
701
|
+
}
|
|
702
|
+
/** 把用户批准绑定到固定目标、任务、引用和实际生效的六维预算。 */
|
|
703
|
+
canonicalDelegationApprovalArgs(request) {
|
|
704
|
+
return {
|
|
705
|
+
target: request.agentName,
|
|
706
|
+
task: request.task,
|
|
707
|
+
references: [...request.context.references],
|
|
708
|
+
...(request.predecessorDelegationId ? { recoveryOf: request.predecessorDelegationId } : {}),
|
|
709
|
+
limits: { ...request.allocation, ...request.hierarchyLimits },
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
/** 审批前先执行不可被人工批准绕过的 Delegation authority 硬边界。 */
|
|
713
|
+
resolveDelegationAuthority(parentAgentName, rawArgs) {
|
|
714
|
+
const args = parseDelegationToolArgs(rawArgs);
|
|
715
|
+
const delegation = this.agentConfigs.get(parentAgentName)?.delegation;
|
|
716
|
+
const target = delegation?.targets[args.target];
|
|
717
|
+
if (!target) {
|
|
718
|
+
throw new CoreMindError("child_run_policy_escalation", `Agent ${parentAgentName} 未获准委派给 ${args.target}`);
|
|
238
719
|
}
|
|
720
|
+
const parentTools = new Set(this.toolCapabilitiesByAgent.get(parentAgentName)?.keys() ?? []);
|
|
721
|
+
const targetTools = [...(this.toolCapabilitiesByAgent.get(args.target)?.keys() ?? [])].filter((tool) => tool !== DELEGATION_TOOL_NAME && isDelegatedSafeToolName(tool));
|
|
722
|
+
const expandedTools = targetTools.filter((tool) => !parentTools.has(tool));
|
|
723
|
+
if (expandedTools.length > 0) {
|
|
724
|
+
throw new CoreMindError("child_run_policy_escalation", `Delegation Target ${args.target} 的工具超出父 Agent authority:${expandedTools.join("、")}`);
|
|
725
|
+
}
|
|
726
|
+
return {
|
|
727
|
+
args,
|
|
728
|
+
targetTools,
|
|
729
|
+
allocation: resolveDelegationAllocation(target.budget, args.limits),
|
|
730
|
+
hierarchyLimits: resolveDelegationHierarchyLimits(delegation?.limits, args.limits),
|
|
731
|
+
};
|
|
239
732
|
}
|
|
240
733
|
/** run() 主体(并发检测由外层 run() 包装) */
|
|
241
|
-
async executeRunBody() {
|
|
734
|
+
async executeRunBody(context) {
|
|
735
|
+
context.attachExecutionEnvironment(this.executionEnvironment);
|
|
242
736
|
const started = performance.now();
|
|
243
737
|
const lifecycleHost = this.options.lifecycleExtensions
|
|
244
738
|
? new LifecycleExtensionHost(this.options.lifecycleExtensions)
|
|
245
739
|
: undefined;
|
|
246
740
|
const runStore = this.options.runStore ??
|
|
247
741
|
new FileRunStore(path.join(this.options.configDir, ".coremind", "runs"));
|
|
742
|
+
this.activeRunStore = runStore;
|
|
248
743
|
const configFingerprint = fingerprintRunConfig(this.config);
|
|
744
|
+
const telemetryPolicy = telemetryPolicyFromConfig(this.config);
|
|
745
|
+
const telemetryConfiguration = createTelemetryConfigurationFact(telemetryPolicy, new Date().toISOString());
|
|
746
|
+
const telemetryConsents = (this.options.telemetry?.consents ?? []).map((consent) => validateTelemetryConsentFact(consent));
|
|
249
747
|
// 会话树关联:打开会话拿 seq 水位与已落盘视图(压缩条目落盘与重建桥接用)
|
|
250
748
|
let sessionSeqStart;
|
|
749
|
+
let canonicalSessionBranch = [];
|
|
750
|
+
let previousContextCompactions = [];
|
|
251
751
|
if (this.options.sessionId && this.config.session?.enabled) {
|
|
252
|
-
|
|
752
|
+
const session = await CoreMindSession.open({
|
|
253
753
|
dir: sessionDir(this.config, this.options.configDir),
|
|
254
754
|
sessionId: this.options.sessionId,
|
|
255
755
|
cwd: this.options.cwd ?? process.cwd(),
|
|
256
756
|
});
|
|
257
|
-
|
|
258
|
-
|
|
757
|
+
const sessionEntries = await session.branchEntries();
|
|
758
|
+
sessionSeqStart = sessionEntries.reduce((max, entry) => Math.max(max, entry.seq), 0);
|
|
759
|
+
context.attachSession(session, projectBranchMessages(sessionEntries));
|
|
760
|
+
canonicalSessionBranch = projectRawBranchMessages(sessionEntries);
|
|
761
|
+
previousContextCompactions = projectContextCompactionLedger(sessionEntries);
|
|
259
762
|
}
|
|
260
|
-
const
|
|
261
|
-
?
|
|
763
|
+
const resumeRecords = this.options.resumeRunId
|
|
764
|
+
? await runStore.read(this.options.resumeRunId)
|
|
262
765
|
: undefined;
|
|
766
|
+
let deferredTerminalError = restoreDeferredTerminalError(resumeRecords);
|
|
767
|
+
const canRestoreChildRuns = this.options.childRuns !== undefined ||
|
|
768
|
+
[...this.agentConfigs.values()].some((agent) => agent.delegation && Object.keys(agent.delegation.targets).length > 0);
|
|
769
|
+
if (resumeRecords && resumeRecords.length > 0 && !canRestoreChildRuns) {
|
|
770
|
+
const childRuns = ProjectionEngine.project(resumeRecords).childRuns;
|
|
771
|
+
if (childRuns && !childRuns.quiescent) {
|
|
772
|
+
throw new CoreMindError("child_run_orphan_audit_required", "恢复记录包含未处置 Child Run,必须配置 Child Run Coordinator 完成 orphan audit");
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
const resumePlan = resumeRecords
|
|
776
|
+
? ProjectionEngine.prepareResume(resumeRecords, configFingerprint, this.options.initialPrompt)
|
|
777
|
+
: undefined;
|
|
778
|
+
for (const candidate of resumePlan?.toolReplayCandidates ?? []) {
|
|
779
|
+
const currentCapability = this.toolCapabilitiesByAgent.get(candidate.agent)?.get(candidate.tool) ??
|
|
780
|
+
resolveToolCapability({ tool: candidate.tool });
|
|
781
|
+
if (fingerprintEffectReceiptValue(currentCapability) !== candidate.capabilityFingerprint) {
|
|
782
|
+
throw new CoreMindError("tool_capability_conflict", `恢复调用 ${candidate.previousCallId} 的 Tool Capability 已漂移,不能自动重放`);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
263
785
|
// 预生成 runId(D-1):resume 时以恢复记录为准,否则优先使用调用方预生成值
|
|
264
786
|
const runId = (resumePlan?.runId ?? this.options.runId ?? randomUUID());
|
|
787
|
+
context.attachRunId(runId);
|
|
265
788
|
const effectiveInitialPrompt = resumePlan?.initialPrompt ?? this.options.initialPrompt;
|
|
266
789
|
const journal = new RunStateJournal(runId, runStore, resumePlan?.nextJournalSequence ?? 0);
|
|
267
|
-
|
|
790
|
+
context.attachJournal(journal);
|
|
268
791
|
const operation = resumePlan && resumePlan.operationRecords.length > 0
|
|
269
792
|
? restoreDurableOperation(resumePlan.operationRecords)
|
|
270
793
|
: DurableOperation.create({
|
|
@@ -288,11 +811,15 @@ export class CoreMindRuntime {
|
|
|
288
811
|
journal.resume({
|
|
289
812
|
completedStepIds: [...resumePlan.completedSteps.keys()],
|
|
290
813
|
resumedAt: new Date().toISOString(),
|
|
814
|
+
...(this.options.protocolStart ? { protocolStart: this.options.protocolStart } : {}),
|
|
291
815
|
...(this.options.sessionId ? { sessionId: this.options.sessionId } : {}),
|
|
292
816
|
...(sessionSeqStart !== undefined
|
|
293
817
|
? { sessionSeqStart, turnSeqStart: sessionSeqStart }
|
|
294
818
|
: {}),
|
|
295
819
|
});
|
|
820
|
+
await journal.appendFact("telemetry_configuration", telemetryConfiguration, {
|
|
821
|
+
durability: "critical",
|
|
822
|
+
});
|
|
296
823
|
}
|
|
297
824
|
else {
|
|
298
825
|
await journal.start({
|
|
@@ -305,8 +832,14 @@ export class CoreMindRuntime {
|
|
|
305
832
|
? { sessionSeqStart, turnSeqStart: sessionSeqStart }
|
|
306
833
|
: {}),
|
|
307
834
|
operationId: operation.snapshot().operationId,
|
|
835
|
+
telemetry: telemetryConfiguration,
|
|
836
|
+
...(this.options.protocolStart ? { protocolStart: this.options.protocolStart } : {}),
|
|
308
837
|
});
|
|
309
838
|
}
|
|
839
|
+
for (const consent of telemetryConsents) {
|
|
840
|
+
validateTelemetryConsentBinding(consent, await runStore.read(runId));
|
|
841
|
+
await journal.appendFact("telemetry_consent", consent, { durability: "critical" });
|
|
842
|
+
}
|
|
310
843
|
if (!resumePlan || resumePlan.operationRecords.length === 0) {
|
|
311
844
|
journal.operation(operation.records()[0]);
|
|
312
845
|
}
|
|
@@ -327,14 +860,26 @@ export class CoreMindRuntime {
|
|
|
327
860
|
throw new CoreMindError("operation_not_resumable", `操作 ${operation.snapshot().operationId} 处于 ${operation.snapshot().state},不能继续执行`);
|
|
328
861
|
}
|
|
329
862
|
await journal.flush();
|
|
863
|
+
context.attachControlInbox(new ControlInbox({
|
|
864
|
+
runId,
|
|
865
|
+
journal,
|
|
866
|
+
records: await runStore.read(runId),
|
|
867
|
+
apply: (command) => this.applyRunControl(command, context, deferredTerminalError),
|
|
868
|
+
}));
|
|
869
|
+
const capabilityByCallId = new Map();
|
|
330
870
|
const trace = new TraceRecorder(runId, (entry) => {
|
|
331
|
-
journal.event
|
|
871
|
+
void journal.appendFact("event", entry, {
|
|
872
|
+
durability: traceFactDurability(entry.event, capabilityByCallId),
|
|
873
|
+
eventId: entry.eventId,
|
|
874
|
+
});
|
|
332
875
|
this.options.trace?.(entry);
|
|
333
876
|
}, resumePlan?.previousTrace);
|
|
334
877
|
const collected = resumePlan?.previousTrace.map((entry) => entry.event) ?? [];
|
|
878
|
+
const toolReplayCandidates = [...(resumePlan?.toolReplayCandidates ?? [])];
|
|
335
879
|
const userEvents = this.options.events ?? (() => { });
|
|
336
|
-
const extensionReceipts = [];
|
|
337
880
|
const turnTracker = new TurnTracker();
|
|
881
|
+
const effectBindingByCall = new Map();
|
|
882
|
+
const effectBindingByReceipt = new Map();
|
|
338
883
|
// 输入收据(规格 03 §4):恢复时沿用原 run 的 inputId(收据链连续),否则新生成
|
|
339
884
|
const inputId = effectiveInitialPrompt === undefined
|
|
340
885
|
? undefined
|
|
@@ -344,19 +889,68 @@ export class CoreMindRuntime {
|
|
|
344
889
|
// pending→pending / claimed→claimed),仅收尾按终态推进
|
|
345
890
|
const existingInputState = inputId === undefined ? undefined : receiptStatusOf(collected, inputId);
|
|
346
891
|
let inputReceiptState = existingInputState ?? (inputId === undefined ? undefined : "pending");
|
|
892
|
+
let onToolResultRecorded;
|
|
893
|
+
const lifecycleFinalizers = new Set();
|
|
894
|
+
let lifecycleFailure;
|
|
347
895
|
const emitInputEvent = (event) => {
|
|
348
896
|
collected.push(event);
|
|
349
897
|
trace.record(event);
|
|
350
898
|
userEvents(event);
|
|
351
899
|
};
|
|
352
900
|
const recordEvent = (event) => {
|
|
353
|
-
|
|
901
|
+
let enriched = turnTracker.withTurnId(event);
|
|
902
|
+
if (enriched.type === "tool_call" && enriched.callId && enriched.turnId) {
|
|
903
|
+
context.recordToolCall({
|
|
904
|
+
agent: enriched.agent,
|
|
905
|
+
callId: enriched.callId,
|
|
906
|
+
turnId: enriched.turnId,
|
|
907
|
+
...(enriched.stepId ? { stepId: enriched.stepId } : {}),
|
|
908
|
+
});
|
|
909
|
+
effectBindingByCall.set(toolCapabilityCallKey(enriched.agent, enriched.stepId, enriched.callId), {
|
|
910
|
+
args: enriched.args,
|
|
911
|
+
turnId: enriched.turnId,
|
|
912
|
+
tool: enriched.tool,
|
|
913
|
+
agent: enriched.agent,
|
|
914
|
+
callId: enriched.callId,
|
|
915
|
+
...(enriched.stepId ? { stepId: enriched.stepId } : {}),
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
if (enriched.type === "effect_receipt") {
|
|
919
|
+
if (!enriched.agent || !enriched.callId || !enriched.turnId) {
|
|
920
|
+
throw new CoreMindError("effect_receipt_conflict", `EffectReceipt ${enriched.idempotencyKey} 缺少 Agent、Turn 或 Call 身份`);
|
|
921
|
+
}
|
|
922
|
+
const callKey = toolCapabilityCallKey(enriched.agent, enriched.stepId, enriched.callId);
|
|
923
|
+
const call = effectBindingByCall.get(callKey);
|
|
924
|
+
const capability = capabilityByCallId.get(callKey)?.capability;
|
|
925
|
+
if (!call || !capability || call.tool !== enriched.tool) {
|
|
926
|
+
throw new CoreMindError("effect_receipt_conflict", `EffectReceipt ${enriched.idempotencyKey} 无法绑定到冻结的 Tool Call 与 Capability`);
|
|
927
|
+
}
|
|
928
|
+
const binding = createEffectReceiptBinding({
|
|
929
|
+
runId,
|
|
930
|
+
turnId: enriched.turnId,
|
|
931
|
+
agent: enriched.agent,
|
|
932
|
+
...(enriched.stepId ? { stepId: enriched.stepId } : {}),
|
|
933
|
+
callId: enriched.callId,
|
|
934
|
+
tool: enriched.tool,
|
|
935
|
+
args: call.args,
|
|
936
|
+
capability,
|
|
937
|
+
});
|
|
938
|
+
const previous = effectBindingByReceipt.get(enriched.idempotencyKey);
|
|
939
|
+
if (previous &&
|
|
940
|
+
fingerprintEffectReceiptValue(previous) !== fingerprintEffectReceiptValue(binding)) {
|
|
941
|
+
throw new CoreMindError("effect_receipt_conflict", `EffectReceipt ${enriched.idempotencyKey} 关联了不同的 Run、Turn、Call、参数或 Capability`);
|
|
942
|
+
}
|
|
943
|
+
effectBindingByReceipt.set(enriched.idempotencyKey, binding);
|
|
944
|
+
enriched = { ...enriched, binding };
|
|
945
|
+
}
|
|
354
946
|
// 事件准入(规格 03 §3):abort 后的迟到终态事实不入 trace/collected/回调(ADR:不入 Trace 或 journal)
|
|
355
947
|
if (!journal.admitEvent(enriched))
|
|
356
948
|
return;
|
|
357
949
|
collected.push(enriched);
|
|
358
950
|
trace.record(enriched);
|
|
359
951
|
userEvents(enriched);
|
|
952
|
+
if (enriched.type === "tool_result")
|
|
953
|
+
onToolResultRecorded?.(enriched);
|
|
360
954
|
// 输入被首个 Turn 认领(规格 03 §4:claim 绑定 TurnId;resume 时已 claimed 不再重复);
|
|
361
955
|
// 排在 agent_start 之后,保证事件顺序:agent_start → input_claimed
|
|
362
956
|
if (enriched.type === "agent_start" && inputReceiptState === "pending") {
|
|
@@ -374,12 +968,107 @@ export class CoreMindRuntime {
|
|
|
374
968
|
}
|
|
375
969
|
const effectCoordinator = new RunEffectCoordinator(runId, recordEvent);
|
|
376
970
|
const emit = (event) => effectCoordinator.emit(event);
|
|
971
|
+
const toolExecutionEngine = new ToolExecutionEngine({
|
|
972
|
+
persist: async (fact) => {
|
|
973
|
+
recordEvent(fact);
|
|
974
|
+
},
|
|
975
|
+
});
|
|
976
|
+
const workspaceLeaseService = this.workspaceLeaseService;
|
|
977
|
+
const workspaceLeaseByCall = new Map();
|
|
978
|
+
const releaseWorkspaceLease = async (identity) => {
|
|
979
|
+
const callKey = toolCapabilityCallKey(identity.agent, identity.stepId, identity.callId);
|
|
980
|
+
const held = workspaceLeaseByCall.get(callKey);
|
|
981
|
+
if (!held)
|
|
982
|
+
return;
|
|
983
|
+
const { lease } = held;
|
|
984
|
+
await journal.flush("critical");
|
|
985
|
+
const lifecycle = toolExecutionEngine.inspect(identity);
|
|
986
|
+
await lease.release({
|
|
987
|
+
activeTools: lifecycle?.terminal ? 0 : 1,
|
|
988
|
+
activeProcesses: 0,
|
|
989
|
+
pendingCriticalFacts: journal.pendingFactCount(),
|
|
990
|
+
});
|
|
991
|
+
workspaceLeaseByCall.delete(callKey);
|
|
992
|
+
emit({
|
|
993
|
+
type: "workspace_lease",
|
|
994
|
+
status: "released",
|
|
995
|
+
canonicalRoot: lease.canonicalRoot,
|
|
996
|
+
lane: lease.lane,
|
|
997
|
+
owner: {
|
|
998
|
+
runId: lease.owner.runId,
|
|
999
|
+
callId: lease.owner.callId,
|
|
1000
|
+
pid: lease.owner.pid,
|
|
1001
|
+
},
|
|
1002
|
+
agent: identity.agent,
|
|
1003
|
+
callId: identity.callId,
|
|
1004
|
+
...(identity.stepId ? { stepId: identity.stepId } : {}),
|
|
1005
|
+
});
|
|
1006
|
+
await journal.flush("critical");
|
|
1007
|
+
};
|
|
1008
|
+
const rollbackWorkspaceLease = async (identity) => {
|
|
1009
|
+
const callKey = toolCapabilityCallKey(identity.agent, identity.stepId, identity.callId);
|
|
1010
|
+
const held = workspaceLeaseByCall.get(callKey);
|
|
1011
|
+
if (!held)
|
|
1012
|
+
return;
|
|
1013
|
+
await held.lease.rollbackBeforeExecution();
|
|
1014
|
+
workspaceLeaseByCall.delete(callKey);
|
|
1015
|
+
emit({
|
|
1016
|
+
type: "workspace_lease",
|
|
1017
|
+
status: "released",
|
|
1018
|
+
canonicalRoot: held.lease.canonicalRoot,
|
|
1019
|
+
lane: held.lease.lane,
|
|
1020
|
+
owner: {
|
|
1021
|
+
runId: held.lease.owner.runId,
|
|
1022
|
+
callId: held.lease.owner.callId,
|
|
1023
|
+
pid: held.lease.owner.pid,
|
|
1024
|
+
},
|
|
1025
|
+
agent: identity.agent,
|
|
1026
|
+
callId: identity.callId,
|
|
1027
|
+
...(identity.stepId ? { stepId: identity.stepId } : {}),
|
|
1028
|
+
});
|
|
1029
|
+
await journal.flush("critical");
|
|
1030
|
+
};
|
|
1031
|
+
onToolResultRecorded = (event) => {
|
|
1032
|
+
const recorded = toolExecutionEngine.inspect({
|
|
1033
|
+
...toolCallIdentity(event.agent, event.stepId, event.callId),
|
|
1034
|
+
});
|
|
1035
|
+
if (!recorded || recorded.tool !== event.tool)
|
|
1036
|
+
return;
|
|
1037
|
+
queueMicrotask(() => {
|
|
1038
|
+
const identity = toolCallIdentity(event.agent, event.stepId, event.callId);
|
|
1039
|
+
const finalizer = (async () => {
|
|
1040
|
+
try {
|
|
1041
|
+
await journal.flush();
|
|
1042
|
+
await toolExecutionEngine.finalizeResult(identity);
|
|
1043
|
+
await releaseWorkspaceLease(identity);
|
|
1044
|
+
}
|
|
1045
|
+
catch (error) {
|
|
1046
|
+
const failure = error instanceof CoreMindError
|
|
1047
|
+
? error
|
|
1048
|
+
: new CoreMindError("durability_barrier_failed", error instanceof Error ? error.message : String(error));
|
|
1049
|
+
if (toolExecutionEngine.inspect(identity)?.currentPhase === "observed") {
|
|
1050
|
+
await toolExecutionEngine.failResultDurability(identity, failure.message);
|
|
1051
|
+
}
|
|
1052
|
+
throw failure;
|
|
1053
|
+
}
|
|
1054
|
+
})();
|
|
1055
|
+
lifecycleFinalizers.add(finalizer);
|
|
1056
|
+
void finalizer
|
|
1057
|
+
.catch((error) => {
|
|
1058
|
+
lifecycleFailure =
|
|
1059
|
+
error instanceof CoreMindError
|
|
1060
|
+
? error
|
|
1061
|
+
: new CoreMindError("tool_lifecycle_invalid", error instanceof Error ? error.message : String(error));
|
|
1062
|
+
})
|
|
1063
|
+
.finally(() => lifecycleFinalizers.delete(finalizer));
|
|
1064
|
+
});
|
|
1065
|
+
};
|
|
377
1066
|
const dispatchLifecycle = async (lifecycle, payload) => {
|
|
378
1067
|
if (!lifecycleHost)
|
|
379
1068
|
return undefined;
|
|
380
1069
|
const result = await lifecycleHost.dispatch(lifecycle, payload);
|
|
381
1070
|
for (const receipt of result.receipts) {
|
|
382
|
-
|
|
1071
|
+
context.recordExtension(receipt);
|
|
383
1072
|
emit({
|
|
384
1073
|
type: "extension_lifecycle",
|
|
385
1074
|
extensionId: receipt.extensionId,
|
|
@@ -402,77 +1091,125 @@ export class CoreMindRuntime {
|
|
|
402
1091
|
const budget = new RunBudgetController(limits, emit);
|
|
403
1092
|
for (const event of collected)
|
|
404
1093
|
budget.restore(event);
|
|
1094
|
+
const childRunOptions = this.options.childRuns ?? (await this.createConfiguredChildRunOptions(limits, runStore));
|
|
1095
|
+
if (childRunOptions) {
|
|
1096
|
+
if (!isCoreMindChildRunAdapter(childRunOptions.adapter)) {
|
|
1097
|
+
throw new CoreMindError("child_run_identity_mismatch", "CoreMindRuntime 只接受由 createCoreMindChildRunAdapter 创建的受信 Adapter");
|
|
1098
|
+
}
|
|
1099
|
+
await assertRuntimeChildPolicyAuthority({
|
|
1100
|
+
policy: childRunOptions.parentPolicy,
|
|
1101
|
+
config: this.config,
|
|
1102
|
+
model: this.modelSnapshotFor(this.mainAgentName),
|
|
1103
|
+
executionEnvironment: this.executionEnvironment,
|
|
1104
|
+
workspaceRoot: this.options.cwd ?? process.cwd(),
|
|
1105
|
+
tools: new Set(this.runtimeAuthorityToolIds()),
|
|
1106
|
+
limits,
|
|
1107
|
+
enforceRuntimeBudget: false,
|
|
1108
|
+
enforceDelegatedToolBoundary: false,
|
|
1109
|
+
});
|
|
1110
|
+
context.attachChildRuns(await ChildRunCoordinator.open({
|
|
1111
|
+
...childRunOptions,
|
|
1112
|
+
parentRunId: runId,
|
|
1113
|
+
parentJournal: journal,
|
|
1114
|
+
runStore,
|
|
1115
|
+
reserveParentBudget: (allocation) => budget.reserveChild(allocation, performance.now() - started),
|
|
1116
|
+
}));
|
|
1117
|
+
await context.currentControlInbox()?.applyPending("delegation_disposition");
|
|
1118
|
+
}
|
|
405
1119
|
const checkpointManager = new CheckpointManager({
|
|
406
1120
|
cwd: this.options.cwd ?? process.cwd(),
|
|
407
1121
|
rootDir: path.join(this.options.configDir, ".coremind", "checkpoints"),
|
|
408
1122
|
runId: trace.runId,
|
|
409
1123
|
});
|
|
410
1124
|
let checkpointFailure;
|
|
411
|
-
|
|
1125
|
+
let capabilityFailure;
|
|
1126
|
+
let delegationPolicyFailure;
|
|
1127
|
+
let delegationDispositionFailure;
|
|
1128
|
+
const delegationDispositionTurns = new Set();
|
|
1129
|
+
const adapterFailures = new Map();
|
|
1130
|
+
const selectedAdapterFailure = () => [...adapterFailures.entries()].sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)[0]?.[1];
|
|
412
1131
|
const checkpointByCallId = new Map();
|
|
413
|
-
const
|
|
414
|
-
const
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
}, async (result) => {
|
|
419
|
-
let sessionEntryId;
|
|
420
|
-
const range = result.replacedRange;
|
|
421
|
-
const branch = this.sessionBranch;
|
|
422
|
-
if (this.activeSession && branch && range && branch.length > 0) {
|
|
423
|
-
// 替换范围延伸进本轮未落盘消息时,会话树内的范围终点截到已落盘末尾,
|
|
424
|
-
// 未落盘尾部由 retainedTail 快照携带——重建依然无损(发送 = 摘要 + 保留区)。
|
|
425
|
-
const coveredEnd = Math.min(range.end, branch.length);
|
|
426
|
-
const summaryMessage = result.messages[0];
|
|
427
|
-
const entry = await this.activeSession.appendCompaction({
|
|
428
|
-
summary: summaryMessage.content,
|
|
429
|
-
retainedTail: result.messages.slice(1),
|
|
430
|
-
tokensBefore: result.beforeTokens,
|
|
431
|
-
details: {
|
|
432
|
-
fingerprint: result.summaryFingerprint,
|
|
433
|
-
rangeStartId: branch[range.start].entryId,
|
|
434
|
-
rangeEndId: branch[coveredEnd - 1].entryId,
|
|
435
|
-
summaryTimestamp: summaryMessage.timestamp,
|
|
436
|
-
},
|
|
437
|
-
});
|
|
438
|
-
sessionEntryId = entry.id;
|
|
439
|
-
// 更新已落盘视图:压缩产物(摘要 + 保留区)由该条目代表
|
|
440
|
-
this.sessionBranch = [
|
|
441
|
-
{
|
|
442
|
-
message: result.messages[0],
|
|
443
|
-
entryId: entry.id,
|
|
444
|
-
seq: entry.seq,
|
|
445
|
-
},
|
|
446
|
-
...result.messages.slice(1).map((message) => ({
|
|
447
|
-
message: message,
|
|
448
|
-
entryId: entry.id,
|
|
449
|
-
seq: entry.seq,
|
|
450
|
-
})),
|
|
451
|
-
];
|
|
452
|
-
// persist 跳过压缩产物代表的部分:摘要 + 保留区(保留区=压缩后消息数-1,起点=range.end)
|
|
453
|
-
this.compactedPrefixEnd = result.messages.length + range.end - 1;
|
|
454
|
-
}
|
|
1132
|
+
const contextLifecycleManager = new ContextLifecycleManager();
|
|
1133
|
+
const contextContracts = new Map();
|
|
1134
|
+
let contextFailure;
|
|
1135
|
+
const recordContextFailure = (failure, preservedMessages) => {
|
|
1136
|
+
contextFailure = failure;
|
|
455
1137
|
emit({
|
|
456
|
-
type: "
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
summaryFingerprint: result.summaryFingerprint,
|
|
463
|
-
...(sessionEntryId ? { sessionEntryId } : {}),
|
|
1138
|
+
type: "context_lifecycle_failed",
|
|
1139
|
+
code: failure.code,
|
|
1140
|
+
reason: failure.reason,
|
|
1141
|
+
pausable: failure.pausable,
|
|
1142
|
+
preservedMessages,
|
|
1143
|
+
providerCallBlocked: true,
|
|
464
1144
|
});
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
}
|
|
1145
|
+
};
|
|
1146
|
+
const throwIfContextFailed = () => {
|
|
1147
|
+
if (contextFailure)
|
|
1148
|
+
throw new CoreMindError(contextFailure.code, contextFailure.message);
|
|
1149
|
+
};
|
|
1150
|
+
const throwIfDelegationBlocksModel = () => {
|
|
1151
|
+
const gate = context.currentChildRuns()?.continuationGate();
|
|
1152
|
+
if (gate?.status === "disposition_required" && gate.requiredActor === "human") {
|
|
1153
|
+
delegationDispositionFailure ??= delegationDispositionRequiredError(gate.delegationId);
|
|
1154
|
+
throw delegationDispositionFailure;
|
|
1155
|
+
}
|
|
1156
|
+
if (gate?.status === "propagate_terminal")
|
|
1157
|
+
throw propagatedChildRunError(gate.result);
|
|
1158
|
+
};
|
|
1159
|
+
const persistContextCompaction = async (preparation, sourceMessages, originalMessageCount) => {
|
|
1160
|
+
const compaction = preparation.compaction;
|
|
1161
|
+
if (!compaction)
|
|
1162
|
+
return undefined;
|
|
1163
|
+
const activeSession = context.sessionHandle();
|
|
1164
|
+
if (!activeSession) {
|
|
1165
|
+
throw new ContextLifecycleError("Context 压缩需要可持久化 Session;摘要不能只存在于内存", "budget_exhausted", "context_budget_exhausted");
|
|
1166
|
+
}
|
|
1167
|
+
let branch = compaction.ledgerEntry.rebuiltFromCanonical
|
|
1168
|
+
? canonicalSessionBranch
|
|
1169
|
+
: (context.sessionBranch() ?? []);
|
|
1170
|
+
if (branch.length < sourceMessages.length) {
|
|
1171
|
+
await activeSession.appendMessages(sourceMessages.slice(branch.length));
|
|
1172
|
+
const appendedEntries = await activeSession.branchEntries();
|
|
1173
|
+
canonicalSessionBranch = projectRawBranchMessages(appendedEntries);
|
|
1174
|
+
context.replaceSessionBranch(projectBranchMessages(appendedEntries));
|
|
1175
|
+
branch = compaction.ledgerEntry.rebuiltFromCanonical
|
|
1176
|
+
? canonicalSessionBranch
|
|
1177
|
+
: (context.sessionBranch() ?? []);
|
|
1178
|
+
}
|
|
1179
|
+
const range = compaction.replacedRange;
|
|
1180
|
+
if (range.end > branch.length || !branch[range.start] || !branch[range.end - 1]) {
|
|
1181
|
+
throw new ContextLifecycleError("Context 压缩范围无法绑定到 canonical Session Facts", "lineage_corrupt", "context_lineage_corrupt");
|
|
1182
|
+
}
|
|
1183
|
+
const summaryMessage = preparation.workingSet.messages[0];
|
|
1184
|
+
const entry = await activeSession.appendCompaction({
|
|
1185
|
+
summary: summaryMessage.content,
|
|
1186
|
+
retainedTail: preparation.workingSet.messages.slice(1),
|
|
1187
|
+
tokensBefore: compaction.tokensBefore,
|
|
1188
|
+
details: {
|
|
1189
|
+
fingerprint: compaction.summaryFingerprint,
|
|
1190
|
+
rangeStartId: branch[range.start].entryId,
|
|
1191
|
+
rangeEndId: branch[range.end - 1].entryId,
|
|
1192
|
+
summaryTimestamp: summaryMessage.timestamp,
|
|
1193
|
+
contextLifecycle: compaction.ledgerEntry,
|
|
1194
|
+
},
|
|
1195
|
+
});
|
|
1196
|
+
previousContextCompactions.push(compaction.ledgerEntry);
|
|
1197
|
+
const updatedEntries = await activeSession.branchEntries();
|
|
1198
|
+
canonicalSessionBranch = projectRawBranchMessages(updatedEntries);
|
|
1199
|
+
context.replaceSessionBranch(projectBranchMessages(updatedEntries));
|
|
1200
|
+
context.setCompactedPrefixEnd(originalMessageCount);
|
|
1201
|
+
return entry.id;
|
|
1202
|
+
};
|
|
470
1203
|
const policy = new ToolPolicy({
|
|
471
1204
|
permissions: this.config.permissions,
|
|
1205
|
+
allowedPaths: this.options.childRunAuthority?.inheritedPolicy.permissions.paths,
|
|
472
1206
|
cwd: this.options.cwd ?? process.cwd(),
|
|
473
1207
|
runId: trace.runId,
|
|
474
1208
|
approve: this.options.approveTool,
|
|
475
1209
|
createApprovalId: randomUUID,
|
|
1210
|
+
delegation: {
|
|
1211
|
+
isAssistedPreapproved: (agent, target) => this.agentConfigs.get(agent)?.delegation?.targets[target]?.preapproved === true,
|
|
1212
|
+
},
|
|
476
1213
|
onApprovalRequired: (request) => emit({
|
|
477
1214
|
type: "approval_required",
|
|
478
1215
|
approvalId: request.approvalId,
|
|
@@ -480,171 +1217,697 @@ export class CoreMindRuntime {
|
|
|
480
1217
|
agent: request.agent,
|
|
481
1218
|
tool: request.tool,
|
|
482
1219
|
args: request.args,
|
|
1220
|
+
argumentsFingerprint: request.argumentsFingerprint,
|
|
1221
|
+
delegationInputFingerprint: request.delegationInputFingerprint,
|
|
483
1222
|
risk: request.risk,
|
|
484
1223
|
effect: request.effect,
|
|
1224
|
+
capability: request.capability,
|
|
485
1225
|
}),
|
|
486
1226
|
onApprovalResolved: (request, decision) => emit({
|
|
487
1227
|
type: "approval_resolved",
|
|
488
1228
|
approvalId: request.approvalId,
|
|
489
1229
|
runId: request.runId,
|
|
490
1230
|
decision,
|
|
1231
|
+
argumentsFingerprint: request.argumentsFingerprint,
|
|
1232
|
+
delegationInputFingerprint: request.delegationInputFingerprint,
|
|
491
1233
|
}),
|
|
492
1234
|
});
|
|
493
1235
|
const deniedAgents = new Set();
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
const blockedByBudget = budget.beforeToolCall();
|
|
514
|
-
if (blockedByBudget)
|
|
515
|
-
return blockedByBudget;
|
|
516
|
-
const decision = await policy.authorize(agentName, context.toolCall.name, context.args, this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.name));
|
|
517
|
-
if (!decision.allowed) {
|
|
518
|
-
deniedAgents.add(agentName);
|
|
1236
|
+
const activeRunContext = context;
|
|
1237
|
+
context.setHarnessFactory((agentName, stepId) => {
|
|
1238
|
+
const agentModel = this.agentModels.get(agentName) ?? this.providerRuntime.model;
|
|
1239
|
+
let contextWorkingSet;
|
|
1240
|
+
let providerRequestOrdinal = 0;
|
|
1241
|
+
let pendingProviderCapabilityFingerprint;
|
|
1242
|
+
return {
|
|
1243
|
+
maxRetries: loop ? 0 : limits.maxRetries,
|
|
1244
|
+
registerContextContract: (contract) => contextContracts.set(agentName, contract),
|
|
1245
|
+
beforeModelRequest: () => {
|
|
1246
|
+
throwIfContextFailed();
|
|
1247
|
+
throwIfDelegationBlocksModel();
|
|
1248
|
+
},
|
|
1249
|
+
onModelRequestDispatched: ({ providerId, modelId, messages }) => {
|
|
1250
|
+
const contract = contextContracts.get(agentName);
|
|
1251
|
+
if (!contract || !pendingProviderCapabilityFingerprint) {
|
|
1252
|
+
throw new ContextLifecycleError("Provider 请求缺少已解析的 Context Working Set", "budget_exhausted", "context_budget_exhausted");
|
|
1253
|
+
}
|
|
1254
|
+
providerRequestOrdinal += 1;
|
|
519
1255
|
emit({
|
|
520
|
-
type: "
|
|
1256
|
+
type: "provider_request",
|
|
521
1257
|
agent: agentName,
|
|
522
|
-
|
|
523
|
-
|
|
1258
|
+
...(stepId ? { stepId } : {}),
|
|
1259
|
+
...createProviderRequestReplayFact({
|
|
1260
|
+
requestId: `${agentName}:${stepId ?? "default"}:${providerRequestOrdinal}`,
|
|
1261
|
+
providerId,
|
|
1262
|
+
modelId,
|
|
1263
|
+
messages,
|
|
1264
|
+
stablePrefix: contract.stablePrefix,
|
|
1265
|
+
toolSchemas: contract.toolSchemas,
|
|
1266
|
+
capabilityFingerprint: pendingProviderCapabilityFingerprint,
|
|
1267
|
+
}),
|
|
524
1268
|
});
|
|
525
|
-
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
1269
|
+
pendingProviderCapabilityFingerprint = undefined;
|
|
1270
|
+
},
|
|
1271
|
+
throwIfContextFailed,
|
|
1272
|
+
executeTool: async ({ call, invoke }) => {
|
|
1273
|
+
try {
|
|
1274
|
+
return await toolExecutionEngine.executeAdapter(toolCallIdentity(agentName, stepId, call.callId), invoke);
|
|
1275
|
+
}
|
|
1276
|
+
catch (error) {
|
|
1277
|
+
const normalized = normalizeExecutionError(error);
|
|
1278
|
+
if (normalized.code !== "tool_execution_failed") {
|
|
1279
|
+
adapterFailures.set(toolCapabilityCallKey(agentName, stepId, call.callId), normalized);
|
|
1280
|
+
}
|
|
1281
|
+
throw normalized;
|
|
1282
|
+
}
|
|
1283
|
+
},
|
|
1284
|
+
transformContext: async (messages) => {
|
|
1285
|
+
if (contextFailure)
|
|
1286
|
+
return messages;
|
|
1287
|
+
while (lifecycleFinalizers.size > 0) {
|
|
1288
|
+
await Promise.allSettled([...lifecycleFinalizers]);
|
|
1289
|
+
}
|
|
1290
|
+
if (lifecycleFailure)
|
|
1291
|
+
throw lifecycleFailure;
|
|
1292
|
+
await dispatchLifecycle("before-model", {
|
|
1293
|
+
runId,
|
|
541
1294
|
agent: agentName,
|
|
542
|
-
|
|
543
|
-
|
|
1295
|
+
stepId,
|
|
1296
|
+
messageCount: messages.length,
|
|
544
1297
|
});
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
1298
|
+
const contract = contextContracts.get(agentName);
|
|
1299
|
+
if (!contract) {
|
|
1300
|
+
recordContextFailure(new ContextLifecycleError(`Agent ${agentName} 没有注册可预算的稳定 Context 合同`, "invalid_budget", "context_capability_conflict"), messages.length);
|
|
1301
|
+
return messages;
|
|
1302
|
+
}
|
|
1303
|
+
const remembered = contextWorkingSet;
|
|
1304
|
+
const effectiveMessages = remembered
|
|
1305
|
+
? [...remembered.messages, ...messages.slice(remembered.sourceLength)]
|
|
1306
|
+
: messages;
|
|
1307
|
+
const canonicalMessages = context.sessionHandle()
|
|
1308
|
+
? [
|
|
1309
|
+
...canonicalSessionBranch.map((item) => item.message),
|
|
1310
|
+
...messages.slice(context.compactedPrefixEnd() ?? this.resumedContextLength),
|
|
1311
|
+
]
|
|
1312
|
+
: messages;
|
|
1313
|
+
const taskState = projectContextTaskState({
|
|
1314
|
+
runId,
|
|
1315
|
+
agentName,
|
|
1316
|
+
initialPrompt: effectiveInitialPrompt,
|
|
1317
|
+
projectInstructions: this.agentConfigs.get(agentName)?.systemPrompt,
|
|
1318
|
+
permissions: this.config.permissions,
|
|
1319
|
+
workflowSteps: this.config.workflow,
|
|
1320
|
+
trace: trace.entries,
|
|
553
1321
|
});
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
1322
|
+
const artifactReferences = context.artifactRecords().flatMap((record) => record.status === "stored" && record.relativePath && record.sha256
|
|
1323
|
+
? [
|
|
1324
|
+
{
|
|
1325
|
+
artifactId: record.artifactId,
|
|
1326
|
+
relativePath: record.relativePath,
|
|
1327
|
+
sizeBytes: record.sizeBytes,
|
|
1328
|
+
sha256: record.sha256,
|
|
1329
|
+
},
|
|
1330
|
+
]
|
|
1331
|
+
: []);
|
|
1332
|
+
try {
|
|
1333
|
+
const preparation = await contextLifecycleManager.prepare({
|
|
1334
|
+
providerId: agentModel.provider,
|
|
1335
|
+
modelId: agentModel.id,
|
|
1336
|
+
resolvedAt: Date.now(),
|
|
1337
|
+
capabilityCandidates: contextCapabilityCandidatesForModel(this.providerRuntime, agentModel),
|
|
1338
|
+
request: {
|
|
1339
|
+
messages: effectiveMessages,
|
|
1340
|
+
stablePrefix: contract.stablePrefix,
|
|
1341
|
+
toolSchemas: contract.toolSchemas,
|
|
1342
|
+
...(this.agentConfigs.get(agentName)?.options?.maxTokens === undefined
|
|
1343
|
+
? {}
|
|
1344
|
+
: {
|
|
1345
|
+
requestedMaxOutputTokens: this.agentConfigs.get(agentName).options.maxTokens,
|
|
1346
|
+
}),
|
|
1347
|
+
taskState,
|
|
1348
|
+
workspaceRoot: this.options.cwd ?? process.cwd(),
|
|
1349
|
+
artifactReferences,
|
|
1350
|
+
canonicalMessages: canonicalMessages,
|
|
1351
|
+
previousCompactions: previousContextCompactions,
|
|
1352
|
+
compactionTrigger: "threshold",
|
|
1353
|
+
},
|
|
1354
|
+
});
|
|
557
1355
|
emit({
|
|
558
|
-
type: "
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
1356
|
+
type: "context_budget_resolved",
|
|
1357
|
+
providerId: preparation.capability.providerId,
|
|
1358
|
+
modelId: preparation.capability.modelId,
|
|
1359
|
+
capabilityFingerprint: preparation.capability.configFingerprint,
|
|
1360
|
+
source: preparation.capability.source,
|
|
1361
|
+
confidence: preparation.capability.confidence,
|
|
1362
|
+
effectiveContextWindow: preparation.budget.effectiveContextWindow,
|
|
1363
|
+
reservedOutputTokens: preparation.budget.reservedOutputTokens,
|
|
1364
|
+
availableInputTokens: preparation.budget.availableInputTokens,
|
|
1365
|
+
messageTokens: preparation.budget.messageTokens,
|
|
1366
|
+
stablePrefixTokens: preparation.budget.stablePrefixTokens,
|
|
1367
|
+
toolSchemaTokens: preparation.budget.toolSchemaTokens,
|
|
1368
|
+
structuredOutputTokens: preparation.budget.structuredOutputTokens,
|
|
1369
|
+
multimodalTokens: preparation.budget.multimodalTokens,
|
|
1370
|
+
protocolOverheadTokens: preparation.budget.protocolOverheadTokens,
|
|
1371
|
+
safetyMarginTokens: preparation.budget.safetyMarginTokens,
|
|
1372
|
+
estimator: preparation.budget.estimator,
|
|
1373
|
+
evidence: preparation.evidence.map((item) => item.type),
|
|
565
1374
|
});
|
|
1375
|
+
const sourceMessages = preparation.compaction?.ledgerEntry.rebuiltFromCanonical
|
|
1376
|
+
? canonicalMessages
|
|
1377
|
+
: effectiveMessages;
|
|
1378
|
+
const sessionEntryId = await persistContextCompaction(preparation, sourceMessages, messages.length);
|
|
1379
|
+
contextWorkingSet = {
|
|
1380
|
+
sourceLength: messages.length,
|
|
1381
|
+
messages: [...preparation.workingSet.messages],
|
|
1382
|
+
};
|
|
1383
|
+
pendingProviderCapabilityFingerprint = preparation.capability.configFingerprint;
|
|
1384
|
+
if (preparation.compaction) {
|
|
1385
|
+
emit({
|
|
1386
|
+
type: "context_compacted",
|
|
1387
|
+
beforeTokens: preparation.compaction.tokensBefore,
|
|
1388
|
+
afterTokens: preparation.compaction.tokensAfter,
|
|
1389
|
+
removedMessages: preparation.compaction.removedMessages,
|
|
1390
|
+
strategy: "task-state-v1",
|
|
1391
|
+
reason: "threshold",
|
|
1392
|
+
summaryFingerprint: preparation.compaction.summaryFingerprint,
|
|
1393
|
+
capabilityFingerprint: preparation.capability.configFingerprint,
|
|
1394
|
+
lineageDepth: preparation.compaction.ledgerEntry.lineageDepth,
|
|
1395
|
+
rebuiltFromCanonical: preparation.compaction.ledgerEntry.rebuiltFromCanonical,
|
|
1396
|
+
trigger: preparation.compaction.ledgerEntry.trigger,
|
|
1397
|
+
...(sessionEntryId ? { sessionEntryId } : {}),
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
return preparation.workingSet.messages;
|
|
566
1401
|
}
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
checkpointFailure =
|
|
570
|
-
error instanceof CoreMindError
|
|
1402
|
+
catch (error) {
|
|
1403
|
+
const failure = error instanceof ContextLifecycleError
|
|
571
1404
|
? error
|
|
572
|
-
: new
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
1405
|
+
: new ContextLifecycleError(`Context 生命周期持久化失败:${error instanceof Error ? error.message : String(error)}`, "budget_exhausted", "context_budget_exhausted");
|
|
1406
|
+
recordContextFailure(failure, messages.length);
|
|
1407
|
+
return messages;
|
|
1408
|
+
}
|
|
1409
|
+
},
|
|
1410
|
+
beforeToolCall: async (context, signal) => {
|
|
1411
|
+
const lifecycleIdentity = toolCallIdentity(agentName, stepId, context.toolCall.callId);
|
|
1412
|
+
const callKey = toolCapabilityCallKey(agentName, stepId, context.toolCall.callId);
|
|
1413
|
+
const argumentsFingerprint = fingerprintEffectReceiptValue(context.toolCall.args);
|
|
1414
|
+
const replayCandidateIndex = toolReplayCandidates.findIndex((candidate) => candidate.agent === agentName &&
|
|
1415
|
+
candidate.stepId === stepId &&
|
|
1416
|
+
candidate.tool === context.toolCall.tool &&
|
|
1417
|
+
candidate.argumentsFingerprint === argumentsFingerprint);
|
|
1418
|
+
if (replayCandidateIndex >= 0) {
|
|
1419
|
+
const candidate = toolReplayCandidates.splice(replayCandidateIndex, 1)[0];
|
|
1420
|
+
const nextReceiptId = receiptId(runId, stepId, context.toolCall.callId);
|
|
1421
|
+
emit({
|
|
1422
|
+
type: "tool_attempt",
|
|
1423
|
+
attemptId: `${nextReceiptId}:attempt:${candidate.attempt}`,
|
|
1424
|
+
previousReceiptId: candidate.previousReceiptId,
|
|
1425
|
+
attempt: candidate.attempt,
|
|
1426
|
+
agent: agentName,
|
|
1427
|
+
tool: context.toolCall.tool,
|
|
1428
|
+
callId: context.toolCall.callId,
|
|
1429
|
+
...(stepId ? { stepId } : {}),
|
|
1430
|
+
argumentsFingerprint,
|
|
1431
|
+
});
|
|
1432
|
+
await journal.flush("critical");
|
|
1433
|
+
}
|
|
1434
|
+
const existingCapability = capabilityByCallId.get(callKey);
|
|
1435
|
+
if (existingCapability && existingCapability.tool !== context.toolCall.tool) {
|
|
1436
|
+
capabilityFailure = new CoreMindError("tool_capability_conflict", `Call ${agentName}/${stepId ?? "-"}/${context.toolCall.callId} 从 ${existingCapability.tool} 变更为 ${context.toolCall.tool},Tool Capability 不可变`);
|
|
1437
|
+
emit({ type: "error", message: capabilityFailure.message, fatal: true });
|
|
1438
|
+
return { block: true, reason: capabilityFailure.message };
|
|
1439
|
+
}
|
|
1440
|
+
await toolExecutionEngine.recordCall({
|
|
1441
|
+
...lifecycleIdentity,
|
|
1442
|
+
tool: context.toolCall.tool,
|
|
609
1443
|
});
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
1444
|
+
let capability = existingCapability?.capability;
|
|
1445
|
+
if (!existingCapability) {
|
|
1446
|
+
capability =
|
|
1447
|
+
this.toolCapabilitiesByAgent.get(agentName)?.get(context.toolCall.tool) ??
|
|
1448
|
+
resolveToolCapability({ tool: context.toolCall.tool });
|
|
1449
|
+
capabilityByCallId.set(callKey, {
|
|
1450
|
+
tool: context.toolCall.tool,
|
|
1451
|
+
capability,
|
|
1452
|
+
});
|
|
1453
|
+
emit({
|
|
1454
|
+
type: "capability_resolved",
|
|
1455
|
+
agent: agentName,
|
|
1456
|
+
tool: context.toolCall.tool,
|
|
1457
|
+
callId: context.toolCall.callId,
|
|
1458
|
+
...(stepId ? { stepId } : {}),
|
|
1459
|
+
capability,
|
|
1460
|
+
recoveryDisposition: recoveryDispositionFor(capability),
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
if (!capability) {
|
|
1464
|
+
throw new CoreMindError("tool_capability_conflict", `Call ${context.toolCall.callId} 缺少已解析 Tool Capability`);
|
|
1465
|
+
}
|
|
1466
|
+
const resolvedCapability = capability;
|
|
1467
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1468
|
+
phase: "capability_resolved",
|
|
1469
|
+
status: "completed",
|
|
1470
|
+
result: { recoveryDisposition: recoveryDispositionFor(resolvedCapability) },
|
|
1471
|
+
});
|
|
1472
|
+
const registeredCall = activeRunContext.toolCall(agentName, context.toolCall.callId);
|
|
1473
|
+
const turnId = registeredCall?.turnId;
|
|
1474
|
+
if (context.toolCall.tool === DELEGATION_DISPOSITION_TOOL_NAME && turnId) {
|
|
1475
|
+
delegationDispositionTurns.add(turnId);
|
|
1476
|
+
}
|
|
1477
|
+
else {
|
|
1478
|
+
const gate = activeRunContext.currentChildRuns()?.continuationGate();
|
|
1479
|
+
const linkedRedelegation = gate?.status === "redelegation_required" &&
|
|
1480
|
+
context.toolCall.tool === DELEGATION_TOOL_NAME &&
|
|
1481
|
+
(() => {
|
|
1482
|
+
try {
|
|
1483
|
+
return (parseDelegationToolArgs(context.toolCall.args).recoveryOf === gate.delegationId);
|
|
1484
|
+
}
|
|
1485
|
+
catch {
|
|
1486
|
+
return false;
|
|
1487
|
+
}
|
|
1488
|
+
})();
|
|
1489
|
+
const blockedByDisposition = (turnId !== undefined && delegationDispositionTurns.has(turnId)) ||
|
|
1490
|
+
gate?.status === "disposition_required" ||
|
|
1491
|
+
gate?.status === "propagate_terminal" ||
|
|
1492
|
+
(gate?.status === "redelegation_required" && !linkedRedelegation);
|
|
1493
|
+
if (blockedByDisposition) {
|
|
1494
|
+
delegationDispositionFailure = new CoreMindError("delegation_disposition_required", gate?.status === "redelegation_required"
|
|
1495
|
+
? `DelegationId ${gate.delegationId} 必须先通过带 recoveryOf 的新 delegate 建立关联尝试`
|
|
1496
|
+
: "Child Run 尚未满足自动接受条件且未完成持久处置,已阻断同批或后续工具调用");
|
|
1497
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, delegationDispositionFailure.message);
|
|
1498
|
+
emit({
|
|
1499
|
+
type: "policy_denied",
|
|
1500
|
+
agent: agentName,
|
|
1501
|
+
tool: context.toolCall.tool,
|
|
1502
|
+
reason: delegationDispositionFailure.message,
|
|
1503
|
+
});
|
|
1504
|
+
return {
|
|
1505
|
+
block: true,
|
|
1506
|
+
reason: delegationDispositionFailure.message,
|
|
1507
|
+
terminate: true,
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
if (deniedAgents.has(agentName)) {
|
|
1512
|
+
const reason = "同一工具批次已有请求被拒绝";
|
|
1513
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, reason);
|
|
1514
|
+
return { block: true, reason, terminate: true };
|
|
1515
|
+
}
|
|
1516
|
+
const blockedByBudget = budget.beforeToolCall();
|
|
1517
|
+
if (blockedByBudget) {
|
|
1518
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, blockedByBudget.reason ?? "工具调用预算已阻断 Call");
|
|
1519
|
+
return blockedByBudget;
|
|
1520
|
+
}
|
|
1521
|
+
let authorizationArgs = context.toolCall.args;
|
|
1522
|
+
let delegationInputFingerprint;
|
|
1523
|
+
if (context.toolCall.tool === DELEGATION_TOOL_NAME) {
|
|
1524
|
+
try {
|
|
1525
|
+
const prepared = await this.prepareConfiguredDelegationRequest(agentName, context.toolCall.args, context.toolCall.callId);
|
|
1526
|
+
authorizationArgs = this.canonicalDelegationApprovalArgs(prepared.request);
|
|
1527
|
+
delegationInputFingerprint = childRunInputFingerprint(prepared.request);
|
|
1528
|
+
}
|
|
1529
|
+
catch (error) {
|
|
1530
|
+
delegationPolicyFailure =
|
|
1531
|
+
error instanceof CoreMindError
|
|
1532
|
+
? error
|
|
1533
|
+
: new CoreMindError("child_run_policy_escalation", error instanceof Error ? error.message : String(error));
|
|
1534
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1535
|
+
phase: "policy_resolved",
|
|
1536
|
+
status: "completed",
|
|
1537
|
+
result: { authorizationState: "denied" },
|
|
1538
|
+
});
|
|
1539
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1540
|
+
phase: "approval_resolved",
|
|
1541
|
+
status: "skipped",
|
|
1542
|
+
reason: "Delegation authority 硬边界在审批前拒绝 Call",
|
|
1543
|
+
});
|
|
1544
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, delegationPolicyFailure.message);
|
|
1545
|
+
emit({
|
|
1546
|
+
type: "policy_denied",
|
|
1547
|
+
agent: agentName,
|
|
1548
|
+
tool: context.toolCall.tool,
|
|
1549
|
+
reason: delegationPolicyFailure.message,
|
|
1550
|
+
});
|
|
1551
|
+
emit({ type: "error", message: delegationPolicyFailure.message, fatal: true });
|
|
1552
|
+
return { block: true, reason: delegationPolicyFailure.message, terminate: true };
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
const decision = await policy.authorize(agentName, context.toolCall.tool, authorizationArgs, resolvedCapability, this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.tool), delegationInputFingerprint);
|
|
1556
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1557
|
+
phase: "policy_resolved",
|
|
1558
|
+
status: "completed",
|
|
1559
|
+
result: {
|
|
1560
|
+
authorizationState: decision.allowed
|
|
1561
|
+
? decision.approvedBy === "user"
|
|
1562
|
+
? "approved"
|
|
1563
|
+
: "allowed"
|
|
1564
|
+
: "denied",
|
|
1565
|
+
},
|
|
1566
|
+
});
|
|
1567
|
+
if (!decision.allowed) {
|
|
1568
|
+
await toolExecutionEngine.advance(lifecycleIdentity, decision.approvalId
|
|
1569
|
+
? { phase: "approval_resolved", status: "completed" }
|
|
1570
|
+
: {
|
|
1571
|
+
phase: "approval_resolved",
|
|
1572
|
+
status: "skipped",
|
|
1573
|
+
reason: "Policy 在审批前拒绝 Call",
|
|
1574
|
+
});
|
|
1575
|
+
if (decision.approvalId) {
|
|
1576
|
+
try {
|
|
1577
|
+
await journal.flush();
|
|
1578
|
+
}
|
|
1579
|
+
catch (error) {
|
|
1580
|
+
checkpointFailure = durabilityFailure(error);
|
|
1581
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, checkpointFailure.message);
|
|
1582
|
+
emit({ type: "error", message: checkpointFailure.message, fatal: true });
|
|
1583
|
+
return { block: true, reason: checkpointFailure.message, terminate: true };
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, decision.reason);
|
|
1587
|
+
deniedAgents.add(agentName);
|
|
1588
|
+
emit({
|
|
1589
|
+
type: "policy_denied",
|
|
1590
|
+
agent: agentName,
|
|
1591
|
+
tool: context.toolCall.tool,
|
|
1592
|
+
reason: decision.reason,
|
|
1593
|
+
});
|
|
1594
|
+
return { block: true, reason: decision.reason, terminate: true };
|
|
1595
|
+
}
|
|
1596
|
+
await toolExecutionEngine.advance(lifecycleIdentity, decision.approvedBy === "user"
|
|
1597
|
+
? { phase: "approval_resolved", status: "completed" }
|
|
1598
|
+
: {
|
|
1599
|
+
phase: "approval_resolved",
|
|
1600
|
+
status: "skipped",
|
|
1601
|
+
reason: decision.reason,
|
|
1602
|
+
});
|
|
1603
|
+
if (decision.approvedBy === "user") {
|
|
1604
|
+
try {
|
|
1605
|
+
await journal.flush();
|
|
1606
|
+
}
|
|
1607
|
+
catch (error) {
|
|
1608
|
+
checkpointFailure = durabilityFailure(error);
|
|
1609
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, checkpointFailure.message);
|
|
1610
|
+
emit({ type: "error", message: checkpointFailure.message, fatal: true });
|
|
1611
|
+
return { block: true, reason: checkpointFailure.message, terminate: true };
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
const extensionDecision = await dispatchLifecycle("before-tool", {
|
|
1615
|
+
runId,
|
|
1616
|
+
agent: agentName,
|
|
1617
|
+
stepId,
|
|
1618
|
+
tool: context.toolCall.tool,
|
|
1619
|
+
callId: context.toolCall.callId,
|
|
1620
|
+
args: context.toolCall.args,
|
|
1621
|
+
approvalAllowed: true,
|
|
1622
|
+
});
|
|
1623
|
+
if (extensionDecision?.denied) {
|
|
1624
|
+
deniedAgents.add(agentName);
|
|
1625
|
+
const reason = extensionDecision.denied.reason;
|
|
1626
|
+
emit({
|
|
1627
|
+
type: "policy_denied",
|
|
1628
|
+
agent: agentName,
|
|
1629
|
+
tool: context.toolCall.tool,
|
|
1630
|
+
reason,
|
|
1631
|
+
});
|
|
1632
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, reason);
|
|
1633
|
+
return { block: true, reason, terminate: true };
|
|
1634
|
+
}
|
|
1635
|
+
if (delegationInputFingerprint) {
|
|
1636
|
+
runContextFor(this).recordDelegationApproval(agentName, context.toolCall.callId, delegationInputFingerprint);
|
|
1637
|
+
}
|
|
1638
|
+
if (resolvedCapability.concurrency === "parallel") {
|
|
1639
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1640
|
+
phase: "lease_acquired",
|
|
1641
|
+
status: "skipped",
|
|
1642
|
+
reason: "Pure Local Read 不需要 Workspace Lease",
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
else {
|
|
1646
|
+
try {
|
|
1647
|
+
const lease = await workspaceLeaseService.acquire({
|
|
1648
|
+
workspaceRoot: this.options.cwd ?? process.cwd(),
|
|
1649
|
+
lane: resolvedCapability.concurrency,
|
|
1650
|
+
owner: { runId, callId: context.toolCall.callId },
|
|
1651
|
+
});
|
|
1652
|
+
workspaceLeaseByCall.set(toolCapabilityCallKey(agentName, stepId, context.toolCall.callId), {
|
|
1653
|
+
lease,
|
|
1654
|
+
identity: lifecycleIdentity,
|
|
1655
|
+
});
|
|
1656
|
+
emit({
|
|
1657
|
+
type: "workspace_lease",
|
|
1658
|
+
status: "acquired",
|
|
1659
|
+
canonicalRoot: lease.canonicalRoot,
|
|
1660
|
+
lane: lease.lane,
|
|
1661
|
+
owner: {
|
|
1662
|
+
runId: lease.owner.runId,
|
|
1663
|
+
callId: lease.owner.callId,
|
|
1664
|
+
pid: lease.owner.pid,
|
|
1665
|
+
},
|
|
1666
|
+
agent: agentName,
|
|
1667
|
+
callId: context.toolCall.callId,
|
|
1668
|
+
...(stepId ? { stepId } : {}),
|
|
1669
|
+
});
|
|
1670
|
+
await journal.flush("critical");
|
|
1671
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1672
|
+
phase: "lease_acquired",
|
|
1673
|
+
status: "completed",
|
|
1674
|
+
});
|
|
1675
|
+
}
|
|
1676
|
+
catch (error) {
|
|
1677
|
+
const callKey = toolCapabilityCallKey(agentName, stepId, context.toolCall.callId);
|
|
1678
|
+
const held = workspaceLeaseByCall.get(callKey);
|
|
1679
|
+
if (held) {
|
|
1680
|
+
await rollbackWorkspaceLease(lifecycleIdentity).catch(() => undefined);
|
|
1681
|
+
}
|
|
1682
|
+
let leaseFailure = error instanceof CoreMindError
|
|
1683
|
+
? error
|
|
1684
|
+
: new CoreMindError("workspace_lease_invalid", error instanceof Error ? error.message : String(error));
|
|
1685
|
+
if (leaseFailure.code === "workspace_lease_recovery_required") {
|
|
1686
|
+
const inspection = await workspaceLeaseService.inspect(this.options.cwd ?? process.cwd());
|
|
1687
|
+
if (inspection.state === "recovery_required" && inspection.owner) {
|
|
1688
|
+
emit({
|
|
1689
|
+
type: "workspace_lease",
|
|
1690
|
+
status: "recovery_required",
|
|
1691
|
+
canonicalRoot: inspection.canonicalRoot,
|
|
1692
|
+
lane: resolvedCapability.concurrency,
|
|
1693
|
+
owner: {
|
|
1694
|
+
runId: inspection.owner.runId,
|
|
1695
|
+
callId: inspection.owner.callId,
|
|
1696
|
+
pid: inspection.owner.pid,
|
|
1697
|
+
},
|
|
1698
|
+
agent: agentName,
|
|
1699
|
+
callId: context.toolCall.callId,
|
|
1700
|
+
...(stepId ? { stepId } : {}),
|
|
1701
|
+
});
|
|
1702
|
+
try {
|
|
1703
|
+
await journal.flush("critical");
|
|
1704
|
+
}
|
|
1705
|
+
catch (durabilityError) {
|
|
1706
|
+
leaseFailure = durabilityFailure(durabilityError);
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
checkpointFailure = leaseFailure;
|
|
1711
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, checkpointFailure.message);
|
|
1712
|
+
emit({ type: "error", message: checkpointFailure.message, fatal: true });
|
|
1713
|
+
return { block: true, reason: checkpointFailure.message, terminate: true };
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
614
1716
|
try {
|
|
615
|
-
|
|
1717
|
+
const idempotencyKey = receiptId(runId, stepId, context.toolCall.callId);
|
|
1718
|
+
const checkpoints = await checkpointManager.captureAll(context.toolCall.tool, context.toolCall.args, {
|
|
1719
|
+
operationId: operation.snapshot().operationId,
|
|
1720
|
+
toolCallId: context.toolCall.callId,
|
|
1721
|
+
idempotencyKey,
|
|
1722
|
+
capability: resolvedCapability,
|
|
1723
|
+
pathFields: this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.tool)
|
|
1724
|
+
?.pathFields,
|
|
1725
|
+
});
|
|
1726
|
+
if (checkpoints.length > 0) {
|
|
1727
|
+
checkpointByCallId.set(context.toolCall.callId, checkpoints.map((checkpoint) => checkpoint.checkpointId));
|
|
1728
|
+
for (const checkpoint of checkpoints) {
|
|
1729
|
+
await journal.appendFact("checkpoint", checkpoint, { durability: "critical" });
|
|
1730
|
+
emit({
|
|
1731
|
+
type: "checkpoint_created",
|
|
1732
|
+
checkpointId: checkpoint.checkpointId,
|
|
1733
|
+
tool: checkpoint.tool,
|
|
1734
|
+
callId: context.toolCall.callId,
|
|
1735
|
+
idempotencyKey,
|
|
1736
|
+
targetPath: checkpoint.targetPath,
|
|
1737
|
+
reversible: checkpoint.reversible,
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
await journal.flush();
|
|
1741
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1742
|
+
phase: "checkpoint_durable",
|
|
1743
|
+
status: "completed",
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
else {
|
|
1747
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1748
|
+
phase: "checkpoint_durable",
|
|
1749
|
+
status: "skipped",
|
|
1750
|
+
reason: "Tool Capability 不要求 Workspace Checkpoint",
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
616
1753
|
}
|
|
617
1754
|
catch (error) {
|
|
618
1755
|
checkpointFailure =
|
|
619
1756
|
error instanceof CoreMindError
|
|
620
1757
|
? error
|
|
621
1758
|
: new CoreMindError("checkpoint_failed", error instanceof Error ? error.message : String(error));
|
|
1759
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1760
|
+
phase: "checkpoint_durable",
|
|
1761
|
+
status: "failed",
|
|
1762
|
+
reason: checkpointFailure.message,
|
|
1763
|
+
});
|
|
1764
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, checkpointFailure.message);
|
|
622
1765
|
emit({ type: "error", message: checkpointFailure.message, fatal: true });
|
|
1766
|
+
await rollbackWorkspaceLease(lifecycleIdentity);
|
|
1767
|
+
return { block: true, reason: checkpointFailure.message };
|
|
623
1768
|
}
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
1769
|
+
effectCoordinator.markStarted(stepId, context.toolCall.callId, context.toolCall.tool);
|
|
1770
|
+
if (resolvedCapability.durability === "critical") {
|
|
1771
|
+
try {
|
|
1772
|
+
await journal.flush();
|
|
1773
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1774
|
+
phase: "started_durable",
|
|
1775
|
+
status: "completed",
|
|
1776
|
+
result: {
|
|
1777
|
+
effectState: resolvedCapability.effect === "none" ? "not_started" : "started",
|
|
1778
|
+
cleanupState: resolvedCapability.effect === "none" ? "not_needed" : "pending",
|
|
1779
|
+
},
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
catch (error) {
|
|
1783
|
+
checkpointFailure = durabilityFailure(error);
|
|
1784
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1785
|
+
phase: "started_durable",
|
|
1786
|
+
status: "failed",
|
|
1787
|
+
reason: checkpointFailure.message,
|
|
1788
|
+
});
|
|
1789
|
+
await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, checkpointFailure.message);
|
|
1790
|
+
emit({ type: "error", message: checkpointFailure.message, fatal: true });
|
|
1791
|
+
await rollbackWorkspaceLease(lifecycleIdentity);
|
|
1792
|
+
return { block: true, reason: checkpointFailure.message };
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
else {
|
|
1796
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1797
|
+
phase: "started_durable",
|
|
1798
|
+
status: "skipped",
|
|
1799
|
+
reason: "Pure Local Read 不需要 started Durability Barrier",
|
|
1800
|
+
});
|
|
1801
|
+
}
|
|
1802
|
+
signal?.throwIfAborted();
|
|
1803
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1804
|
+
phase: "executing",
|
|
1805
|
+
status: "completed",
|
|
1806
|
+
});
|
|
1807
|
+
return undefined;
|
|
1808
|
+
},
|
|
1809
|
+
afterToolCall: async (context) => {
|
|
1810
|
+
const lifecycleIdentity = toolCallIdentity(agentName, stepId, context.toolCall.callId);
|
|
1811
|
+
const capability = capabilityByCallId.get(toolCapabilityCallKey(agentName, stepId, context.toolCall.callId))?.capability;
|
|
1812
|
+
await toolExecutionEngine.advance(lifecycleIdentity, {
|
|
1813
|
+
phase: "observed",
|
|
1814
|
+
status: "completed",
|
|
1815
|
+
result: {
|
|
1816
|
+
executionOutcome: context.isError ? "threw" : "returned",
|
|
1817
|
+
effectState: capability?.effect === "none"
|
|
1818
|
+
? "not_started"
|
|
1819
|
+
: context.isError
|
|
1820
|
+
? "unknown"
|
|
1821
|
+
: "committed",
|
|
1822
|
+
cleanupState: capability?.effect === "none" ? "not_needed" : "pending",
|
|
1823
|
+
},
|
|
1824
|
+
});
|
|
1825
|
+
const execution = createToolExecutionEvidence({
|
|
1826
|
+
tool: context.toolCall.tool,
|
|
1827
|
+
args: context.toolCall.args,
|
|
1828
|
+
isError: context.isError,
|
|
1829
|
+
result: context.result,
|
|
1830
|
+
durationMs: effectCoordinator.consumeDuration(stepId, context.toolCall.callId),
|
|
1831
|
+
});
|
|
1832
|
+
emit({
|
|
1833
|
+
type: "tool_execution_evidence",
|
|
1834
|
+
agent: agentName,
|
|
1835
|
+
tool: context.toolCall.tool,
|
|
1836
|
+
callId: context.toolCall.callId,
|
|
1837
|
+
...(stepId ? { stepId } : {}),
|
|
1838
|
+
execution,
|
|
1839
|
+
});
|
|
1840
|
+
const artifact = extractArtifactRecord(context.result.details);
|
|
1841
|
+
if (artifact) {
|
|
1842
|
+
runContextFor(this).recordArtifact(artifact);
|
|
1843
|
+
emit({
|
|
1844
|
+
type: "artifact_created",
|
|
1845
|
+
artifactId: artifact.artifactId,
|
|
1846
|
+
status: artifact.status,
|
|
1847
|
+
sizeBytes: artifact.sizeBytes,
|
|
1848
|
+
relativePath: artifact.relativePath,
|
|
1849
|
+
sha256: artifact.sha256,
|
|
1850
|
+
mediaType: artifact.mediaType,
|
|
1851
|
+
redaction: artifact.redaction,
|
|
1852
|
+
tool: context.toolCall.tool,
|
|
1853
|
+
callId: context.toolCall.callId,
|
|
1854
|
+
});
|
|
1855
|
+
}
|
|
1856
|
+
const checkpointIds = checkpointByCallId.get(context.toolCall.callId);
|
|
1857
|
+
const checkpointId = checkpointIds?.[0];
|
|
1858
|
+
checkpointByCallId.delete(context.toolCall.callId);
|
|
1859
|
+
if (checkpointIds) {
|
|
1860
|
+
try {
|
|
1861
|
+
await Promise.all(checkpointIds.map((storedCheckpointId) => checkpointManager.markApplied(storedCheckpointId)));
|
|
1862
|
+
for (const storedCheckpointId of checkpointIds) {
|
|
1863
|
+
const applied = checkpointManager.records.find((candidate) => candidate.checkpointId === storedCheckpointId);
|
|
1864
|
+
if (!applied) {
|
|
1865
|
+
throw new CoreMindError("checkpoint_failed", `检查点 ${storedCheckpointId} 的写后状态不存在`);
|
|
1866
|
+
}
|
|
1867
|
+
await journal.appendFact("checkpoint", applied, { durability: "critical" });
|
|
1868
|
+
}
|
|
1869
|
+
await journal.flush("critical");
|
|
1870
|
+
}
|
|
1871
|
+
catch (error) {
|
|
1872
|
+
checkpointFailure =
|
|
1873
|
+
error instanceof CoreMindError
|
|
1874
|
+
? error
|
|
1875
|
+
: new CoreMindError("checkpoint_failed", error instanceof Error ? error.message : String(error));
|
|
1876
|
+
emit({ type: "error", message: checkpointFailure.message, fatal: true });
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
const budgetResult = budget.afterToolCall(context.isError);
|
|
1880
|
+
await dispatchLifecycle("after-tool", {
|
|
1881
|
+
runId,
|
|
1882
|
+
agent: agentName,
|
|
1883
|
+
stepId,
|
|
1884
|
+
tool: context.toolCall.tool,
|
|
1885
|
+
callId: context.toolCall.callId,
|
|
1886
|
+
isError: context.isError,
|
|
1887
|
+
checkpointId,
|
|
1888
|
+
artifactId: artifact?.artifactId,
|
|
1889
|
+
});
|
|
1890
|
+
return checkpointFailure || adapterFailures.size > 0 ? { terminate: true } : budgetResult;
|
|
1891
|
+
},
|
|
1892
|
+
shouldStopAfterTurn: () => deniedAgents.has(agentName),
|
|
1893
|
+
throwIfDenied: () => {
|
|
1894
|
+
if (deniedAgents.has(agentName)) {
|
|
1895
|
+
throw new CoreMindError("loop_paused", stepId
|
|
1896
|
+
? `步骤 ${stepId} 的工具请求未获批准`
|
|
1897
|
+
: `Agent ${agentName} 的工具请求未获批准`);
|
|
1898
|
+
}
|
|
1899
|
+
},
|
|
1900
|
+
onObservation: (observation) => {
|
|
1901
|
+
const driver = context.agent(agentName);
|
|
1902
|
+
if (observation.type === "turn_end" &&
|
|
1903
|
+
"contextOverflow" in observation &&
|
|
1904
|
+
observation.contextOverflow) {
|
|
1905
|
+
recordContextFailure(new ContextLifecycleError(`Provider 报告 ${agentModel.provider}/${agentModel.id} 超出 Context 窗口;相同请求不会重试`, "provider_overflow", "context_budget_exhausted"), driver?.messages().length ?? 0);
|
|
1906
|
+
}
|
|
1907
|
+
if (budget.observeAgentEvent(observation))
|
|
1908
|
+
driver?.abort();
|
|
1909
|
+
},
|
|
1910
|
+
};
|
|
648
1911
|
});
|
|
649
1912
|
let outputs = new Map();
|
|
650
1913
|
let transcript = "";
|
|
@@ -653,6 +1916,17 @@ export class CoreMindRuntime {
|
|
|
653
1916
|
let activeLoopRunner;
|
|
654
1917
|
try {
|
|
655
1918
|
({ outputs, transcript } = await this.runWithGuard(limits.runTimeoutMs, journal, () => knownTurnIdsFrom(collected), async () => {
|
|
1919
|
+
if (deferredTerminalError) {
|
|
1920
|
+
const childRuns = context.currentChildRuns();
|
|
1921
|
+
const gate = childRuns?.continuationGate();
|
|
1922
|
+
if (gate?.status === "disposition_required") {
|
|
1923
|
+
throw delegationDispositionRequiredError(gate.delegationId);
|
|
1924
|
+
}
|
|
1925
|
+
if (gate?.status === "redelegation_required") {
|
|
1926
|
+
await childRuns.cancelPendingRedelegations(deferredTerminalError.code, `父 Run 已有待恢复终态 ${deferredTerminalError.code},撤销尚未执行的重新委派`);
|
|
1927
|
+
}
|
|
1928
|
+
throw deferredTerminalError;
|
|
1929
|
+
}
|
|
656
1930
|
if (loop) {
|
|
657
1931
|
let retryCount = resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry" && entry.event.scope === "provider").length ?? 0;
|
|
658
1932
|
const runner = new LoopRunner({
|
|
@@ -726,28 +2000,50 @@ export class CoreMindRuntime {
|
|
|
726
2000
|
if (!agent) {
|
|
727
2001
|
throw new CoreMindError("unknown_agent", `默认 agent ${name} 不存在`);
|
|
728
2002
|
}
|
|
729
|
-
const messageCursor = agent.
|
|
2003
|
+
const messageCursor = agent.messages().length;
|
|
730
2004
|
await agent.prompt(effectiveInitialPrompt);
|
|
731
2005
|
await agent.waitForIdle();
|
|
732
|
-
const
|
|
2006
|
+
const messages = agent.messages();
|
|
2007
|
+
const agentError = extractAgentError(messages);
|
|
733
2008
|
if (agentError) {
|
|
734
|
-
throw
|
|
2009
|
+
throw normalizeExecutionError({
|
|
2010
|
+
role: "assistant",
|
|
2011
|
+
stopReason: "error",
|
|
2012
|
+
errorMessage: agentError,
|
|
2013
|
+
});
|
|
735
2014
|
}
|
|
736
|
-
transcript = extractText(
|
|
2015
|
+
transcript = extractText(messages.slice(messageCursor));
|
|
737
2016
|
return { outputs: new Map(), transcript };
|
|
738
2017
|
}, (error) => activeLoopRunner?.interrupt(error)));
|
|
2018
|
+
if (delegationDispositionFailure)
|
|
2019
|
+
throw delegationDispositionFailure;
|
|
2020
|
+
if (delegationPolicyFailure)
|
|
2021
|
+
throw delegationPolicyFailure;
|
|
2022
|
+
if (capabilityFailure)
|
|
2023
|
+
throw capabilityFailure;
|
|
2024
|
+
const adapterFailure = selectedAdapterFailure();
|
|
2025
|
+
if (adapterFailure)
|
|
2026
|
+
throw adapterFailure;
|
|
739
2027
|
if (checkpointFailure)
|
|
740
2028
|
throw checkpointFailure;
|
|
741
2029
|
budget.throwIfExceeded();
|
|
742
2030
|
}
|
|
743
2031
|
catch (error) {
|
|
744
|
-
terminalError =
|
|
2032
|
+
terminalError =
|
|
2033
|
+
checkpointFailure ??
|
|
2034
|
+
delegationDispositionFailure ??
|
|
2035
|
+
delegationPolicyFailure ??
|
|
2036
|
+
capabilityFailure ??
|
|
2037
|
+
selectedAdapterFailure() ??
|
|
2038
|
+
error;
|
|
745
2039
|
try {
|
|
746
2040
|
if (!checkpointFailure)
|
|
747
2041
|
budget.throwIfExceeded();
|
|
748
2042
|
}
|
|
749
2043
|
catch (budgetError) {
|
|
750
|
-
terminalError
|
|
2044
|
+
if (!(terminalError instanceof CoreMindError && terminalError.code === "unclassified_error")) {
|
|
2045
|
+
terminalError = budgetError;
|
|
2046
|
+
}
|
|
751
2047
|
}
|
|
752
2048
|
// step_timeout / budget_exceeded 与 Abort 共用准入机制(规格 03 §1):
|
|
753
2049
|
// 终止确定后设置分界点,拦截其后的迟到终态事实
|
|
@@ -755,20 +2051,97 @@ export class CoreMindRuntime {
|
|
|
755
2051
|
if (!journal.isAborted() && (code === "step_timeout" || code === "budget_exceeded")) {
|
|
756
2052
|
journal.markAborted(knownTurnIdsFrom(collected));
|
|
757
2053
|
}
|
|
2054
|
+
if (code === "aborted" ||
|
|
2055
|
+
code === "run_timeout" ||
|
|
2056
|
+
code === "step_timeout" ||
|
|
2057
|
+
code === "budget_exceeded") {
|
|
2058
|
+
try {
|
|
2059
|
+
await toolExecutionEngine.settleInterrupted(code === "run_timeout" || code === "step_timeout" ? "timed_out" : "aborted", `Run 以 ${code} 终止`);
|
|
2060
|
+
}
|
|
2061
|
+
catch (lifecycleError) {
|
|
2062
|
+
lifecycleFailure =
|
|
2063
|
+
lifecycleError instanceof CoreMindError
|
|
2064
|
+
? lifecycleError
|
|
2065
|
+
: new CoreMindError("tool_lifecycle_invalid", lifecycleError instanceof Error ? lifecycleError.message : String(lifecycleError));
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
758
2068
|
}
|
|
759
2069
|
finally {
|
|
760
|
-
|
|
2070
|
+
context.setHarnessFactory(undefined);
|
|
2071
|
+
}
|
|
2072
|
+
while (lifecycleFinalizers.size > 0) {
|
|
2073
|
+
await Promise.allSettled([...lifecycleFinalizers]);
|
|
2074
|
+
}
|
|
2075
|
+
if (lifecycleFailure &&
|
|
2076
|
+
(terminalError === undefined ||
|
|
2077
|
+
(terminalError instanceof CoreMindError && terminalError.code === "agent_failed"))) {
|
|
2078
|
+
terminalError = lifecycleFailure;
|
|
761
2079
|
}
|
|
762
2080
|
// 静止等待(规格 03 §5):runWithGuard 收尾路径调用,等所有 agent 真正 idle、
|
|
763
2081
|
// pending 工具结束、journal 落盘队列清空;超时记录 quiescence_timeout 事件不改变终态
|
|
764
|
-
await
|
|
2082
|
+
await context.currentControlInbox()?.sealForTerminal();
|
|
2083
|
+
await context.currentChildRuns()?.sealForTerminal();
|
|
2084
|
+
const runtimeQuiescent = await this.waitForQuiescence(DEFAULT_QUIESCENCE_TIMEOUT_MS);
|
|
2085
|
+
let delegationGate = context.currentChildRuns()?.continuationGate();
|
|
2086
|
+
const environmentTerminationError = context.environmentTerminationError();
|
|
2087
|
+
if (environmentTerminationError) {
|
|
2088
|
+
terminalError = new CoreMindError("environment_terminate_failed", environmentTerminationError instanceof Error
|
|
2089
|
+
? environmentTerminationError.message
|
|
2090
|
+
: String(environmentTerminationError));
|
|
2091
|
+
}
|
|
2092
|
+
const childRunsNotQuiescent = !runtimeQuiescent &&
|
|
2093
|
+
context.currentChildRuns() !== undefined &&
|
|
2094
|
+
!context.currentChildRuns()?.isExecutionQuiescent();
|
|
2095
|
+
if (childRunsNotQuiescent) {
|
|
2096
|
+
terminalError ??= new CoreMindError("child_run_not_quiescent", "Runtime 的 Child Run 未完成取消、清理与结构化 join,不能形成父级终态");
|
|
2097
|
+
}
|
|
2098
|
+
if (!runtimeQuiescent && workspaceLeaseByCall.size > 0) {
|
|
2099
|
+
terminalError ??= new CoreMindError("workspace_lease_not_quiescent", "Runtime 未达到静止条件,Workspace Lease 保持占用并等待恢复审计");
|
|
2100
|
+
}
|
|
2101
|
+
else {
|
|
2102
|
+
for (const { identity } of [...workspaceLeaseByCall.values()]) {
|
|
2103
|
+
try {
|
|
2104
|
+
await releaseWorkspaceLease(identity);
|
|
2105
|
+
}
|
|
2106
|
+
catch (error) {
|
|
2107
|
+
terminalError ??=
|
|
2108
|
+
error instanceof CoreMindError
|
|
2109
|
+
? error
|
|
2110
|
+
: new CoreMindError("workspace_lease_not_quiescent", error instanceof Error ? error.message : String(error));
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
if (terminalError === undefined && delegationGate?.status === "propagate_terminal") {
|
|
2115
|
+
terminalError = propagatedChildRunError(delegationGate.result);
|
|
2116
|
+
}
|
|
2117
|
+
if (terminalError !== undefined && context.currentChildRuns()) {
|
|
2118
|
+
try {
|
|
2119
|
+
delegationGate = await cancelPendingRedelegationsBeforeTerminal(context.currentChildRuns(), terminalError);
|
|
2120
|
+
}
|
|
2121
|
+
catch (error) {
|
|
2122
|
+
terminalError = error;
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
if (delegationGate?.status === "disposition_required" ||
|
|
2126
|
+
delegationGate?.status === "redelegation_required") {
|
|
2127
|
+
if (terminalError !== undefined) {
|
|
2128
|
+
const normalized = normalizeExecutionError(terminalError);
|
|
2129
|
+
if (normalized.code !== "delegation_disposition_required") {
|
|
2130
|
+
deferredTerminalError ??= normalized;
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
terminalError = delegationDispositionRequiredError(delegationGate.delegationId);
|
|
2134
|
+
}
|
|
2135
|
+
else if (terminalError === undefined && deferredTerminalError) {
|
|
2136
|
+
terminalError = deferredTerminalError;
|
|
2137
|
+
}
|
|
765
2138
|
let sessionFile;
|
|
766
2139
|
// D-4 方案 A:abort 后也写会话树(只写已确认部分,竞态赢家文本丢弃);
|
|
767
2140
|
// 审批拒绝等 paused(loop_paused)是可在用户处置后继续的暂停态,同样应落盘已确认部分,
|
|
768
2141
|
// 使持久事实可重建该 Run 的请求(规格 01 §2 请求重建契约的适用范围)
|
|
769
2142
|
const terminalCode = terminalError instanceof CoreMindError ? terminalError.code : undefined;
|
|
770
|
-
|
|
771
|
-
if (terminalError === undefined || journal.isAborted() ||
|
|
2143
|
+
context.setSessionPersistPaused(terminalCode === "loop_paused");
|
|
2144
|
+
if (terminalError === undefined || journal.isAborted() || context.shouldTrimRejectedTrail()) {
|
|
772
2145
|
try {
|
|
773
2146
|
sessionFile = await this.persistSession();
|
|
774
2147
|
}
|
|
@@ -782,8 +2155,14 @@ export class CoreMindRuntime {
|
|
|
782
2155
|
if (terminalError !== undefined && transcript.length === 0 && !journal.isAborted()) {
|
|
783
2156
|
transcript = extractText(allMessages);
|
|
784
2157
|
}
|
|
2158
|
+
try {
|
|
2159
|
+
await journal.flush();
|
|
2160
|
+
}
|
|
2161
|
+
catch (error) {
|
|
2162
|
+
terminalError = durabilityFailure(error);
|
|
2163
|
+
}
|
|
785
2164
|
const metrics = analyzeRunMetrics(collected, allMessages, performance.now() - started, transcript.length, journal.rejectedAfterAbort());
|
|
786
|
-
|
|
2165
|
+
let outcome = new RunTerminalizer().terminalize(collected, terminalError);
|
|
787
2166
|
// 输入收据终态(规格 03 §4):succeeded → completed;abort/超时/预算/失败 → discarded
|
|
788
2167
|
// (未消费输入);paused(审批拒绝等)保持 claimed,resume 继续同一输入
|
|
789
2168
|
if (inputReceiptState !== undefined && inputReceiptState !== "completed") {
|
|
@@ -796,8 +2175,8 @@ export class CoreMindRuntime {
|
|
|
796
2175
|
emitInputEvent(discardInput({ inputId: inputId }));
|
|
797
2176
|
}
|
|
798
2177
|
}
|
|
799
|
-
|
|
800
|
-
|
|
2178
|
+
let evaluation = createEvaluationReport(this.config.quality, metrics);
|
|
2179
|
+
let releaseReadiness = assessReleaseReadiness(outcome, evaluation);
|
|
801
2180
|
const irreversibleTools = [
|
|
802
2181
|
...new Set(checkpointManager.records
|
|
803
2182
|
.filter((checkpoint) => !checkpoint.reversible)
|
|
@@ -845,57 +2224,116 @@ export class CoreMindRuntime {
|
|
|
845
2224
|
evaluation,
|
|
846
2225
|
releaseReadiness,
|
|
847
2226
|
checkpointCount: checkpointManager.records.length,
|
|
848
|
-
artifactCount:
|
|
2227
|
+
artifactCount: context.artifactRecords().length,
|
|
849
2228
|
});
|
|
850
|
-
|
|
851
|
-
|
|
2229
|
+
// operation/input/lifecycle 收尾事实必须先形成稳定前缀,终态 Fact 才能成为最后一条。
|
|
2230
|
+
try {
|
|
2231
|
+
await journal.flush();
|
|
2232
|
+
}
|
|
2233
|
+
catch (error) {
|
|
2234
|
+
terminalError = durabilityFailure(error);
|
|
2235
|
+
outcome = new RunTerminalizer().terminalize(collected, terminalError);
|
|
2236
|
+
evaluation = createEvaluationReport(this.config.quality, metrics);
|
|
2237
|
+
releaseReadiness = assessReleaseReadiness(outcome, evaluation);
|
|
2238
|
+
}
|
|
2239
|
+
const terminalKind = outcome.status === "paused" ? "pause" : "finish";
|
|
2240
|
+
const terminalPayload = {
|
|
2241
|
+
operation: operation.snapshot(),
|
|
2242
|
+
outcome,
|
|
2243
|
+
metrics,
|
|
2244
|
+
evaluation,
|
|
2245
|
+
releaseReadiness,
|
|
2246
|
+
artifacts: context.artifactRecords(),
|
|
2247
|
+
extensions: context.extensions(),
|
|
2248
|
+
...(outcome.status === "paused" && loopSnapshot ? { loopSnapshot } : {}),
|
|
2249
|
+
...(outcome.status === "paused" && deferredTerminalError
|
|
2250
|
+
? { deferredTerminalError: serializeDeferredTerminalError(deferredTerminalError) }
|
|
2251
|
+
: {}),
|
|
2252
|
+
};
|
|
2253
|
+
const terminalDurabilityFailure = journal.factStatus().state === "poisoned" ||
|
|
2254
|
+
(terminalError instanceof CoreMindError &&
|
|
2255
|
+
(terminalError.code === "durability_unsupported" ||
|
|
2256
|
+
terminalError.code === "durability_barrier_failed" ||
|
|
2257
|
+
terminalError.code === "fact_ledger_poisoned"));
|
|
2258
|
+
let terminalPersisted = false;
|
|
2259
|
+
if (!terminalDurabilityFailure) {
|
|
2260
|
+
try {
|
|
2261
|
+
await journal.appendFact(terminalKind, terminalPayload, { durability: "critical" });
|
|
2262
|
+
terminalPersisted = true;
|
|
2263
|
+
}
|
|
2264
|
+
catch (error) {
|
|
2265
|
+
const finalDurabilityFailure = durabilityFailure(error);
|
|
2266
|
+
terminalError = finalDurabilityFailure;
|
|
2267
|
+
userEvents({ type: "error", message: finalDurabilityFailure.message, fatal: true });
|
|
2268
|
+
outcome = new RunTerminalizer().terminalize(collected, terminalError);
|
|
2269
|
+
evaluation = createEvaluationReport(this.config.quality, metrics);
|
|
2270
|
+
releaseReadiness = assessReleaseReadiness(outcome, evaluation);
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
const persistedRecords = terminalPersisted ? await runStore.read(runId) : undefined;
|
|
2274
|
+
const persistedProjection = persistedRecords
|
|
2275
|
+
? ProjectionEngine.project(persistedRecords)
|
|
2276
|
+
: undefined;
|
|
2277
|
+
const snapshot = terminalPersisted
|
|
2278
|
+
? persistedProjection?.snapshot
|
|
2279
|
+
: createRunSnapshot({
|
|
2280
|
+
runId: trace.runId,
|
|
852
2281
|
operation: operation.snapshot(),
|
|
853
2282
|
outcome,
|
|
854
2283
|
metrics,
|
|
855
2284
|
evaluation,
|
|
856
2285
|
releaseReadiness,
|
|
857
|
-
|
|
2286
|
+
trace: trace.entries,
|
|
2287
|
+
checkpoints: checkpointManager.records,
|
|
2288
|
+
artifacts: context.artifactRecords(),
|
|
2289
|
+
extensions: context.extensions(),
|
|
858
2290
|
});
|
|
2291
|
+
if (!snapshot) {
|
|
2292
|
+
throw new CoreMindError("run_state_corrupt", "终态 Fact 已持久化,但无法重建 RunSnapshot");
|
|
859
2293
|
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
operation: operation.snapshot(),
|
|
2294
|
+
let observability = persistedProjection?.observability ??
|
|
2295
|
+
fallbackObservability({
|
|
863
2296
|
outcome,
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
releaseReadiness,
|
|
2297
|
+
operation: operation.snapshot(),
|
|
2298
|
+
telemetry: telemetryConfiguration,
|
|
867
2299
|
});
|
|
2300
|
+
if (persistedRecords) {
|
|
2301
|
+
const { consents: _consents, ...egressOptions } = this.options.telemetry ?? {};
|
|
2302
|
+
const delivery = await new TelemetryEgressController({
|
|
2303
|
+
policy: telemetryPolicy,
|
|
2304
|
+
...egressOptions,
|
|
2305
|
+
}).export(persistedRecords);
|
|
2306
|
+
observability = {
|
|
2307
|
+
...observability,
|
|
2308
|
+
telemetry: {
|
|
2309
|
+
...observability.telemetry,
|
|
2310
|
+
...delivery,
|
|
2311
|
+
source: observability.telemetry.source,
|
|
2312
|
+
},
|
|
2313
|
+
};
|
|
868
2314
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
operation: operation.snapshot(),
|
|
873
|
-
outcome,
|
|
874
|
-
metrics,
|
|
875
|
-
evaluation,
|
|
876
|
-
releaseReadiness,
|
|
877
|
-
trace: trace.entries,
|
|
878
|
-
checkpoints: checkpointManager.records,
|
|
879
|
-
artifacts,
|
|
880
|
-
extensions: extensionReceipts,
|
|
881
|
-
});
|
|
2315
|
+
const childRuns = persistedRecords
|
|
2316
|
+
? (await ProjectionEngine.projectTree(runStore, runId)).childRuns
|
|
2317
|
+
: undefined;
|
|
882
2318
|
return {
|
|
883
2319
|
runId: trace.runId,
|
|
884
|
-
operation: operation
|
|
885
|
-
outcome,
|
|
886
|
-
metrics,
|
|
887
|
-
evaluation,
|
|
888
|
-
releaseReadiness,
|
|
889
|
-
trace: trace
|
|
2320
|
+
operation: snapshot.operation,
|
|
2321
|
+
outcome: snapshot.outcome,
|
|
2322
|
+
metrics: snapshot.metrics,
|
|
2323
|
+
evaluation: snapshot.evaluation,
|
|
2324
|
+
releaseReadiness: snapshot.releaseReadiness,
|
|
2325
|
+
trace: snapshot.trace,
|
|
890
2326
|
runStateFile: runStore.pathFor?.(runId),
|
|
891
|
-
checkpoints:
|
|
2327
|
+
checkpoints: snapshot.checkpoints,
|
|
892
2328
|
outputs,
|
|
893
2329
|
messages: this.collectMessages(),
|
|
894
2330
|
transcript,
|
|
895
2331
|
sessionFile,
|
|
896
|
-
artifacts,
|
|
897
|
-
extensions:
|
|
2332
|
+
artifacts: snapshot.artifacts,
|
|
2333
|
+
extensions: snapshot.extensions,
|
|
898
2334
|
snapshot,
|
|
2335
|
+
observability,
|
|
2336
|
+
...(childRuns ? { childRuns } : {}),
|
|
899
2337
|
};
|
|
900
2338
|
}
|
|
901
2339
|
async runWithGuard(timeoutMs, journal, knownTurnIds, operation, onGuardError) {
|
|
@@ -948,7 +2386,7 @@ export class CoreMindRuntime {
|
|
|
948
2386
|
if (!agent) {
|
|
949
2387
|
throw new CoreMindError("unknown_agent", `Loop 引用了未定义的 agent:${request.agent}(${request.stepId})`);
|
|
950
2388
|
}
|
|
951
|
-
const messageCursor = agent.
|
|
2389
|
+
const messageCursor = agent.messages().length;
|
|
952
2390
|
let timer;
|
|
953
2391
|
const operation = (async () => {
|
|
954
2392
|
await agent.prompt(request.input);
|
|
@@ -982,28 +2420,64 @@ export class CoreMindRuntime {
|
|
|
982
2420
|
if (stepEvents.some((event) => event.type === "policy_denied")) {
|
|
983
2421
|
throw new CoreMindError("loop_paused", `步骤 ${request.stepId} 的工具请求未获批准`);
|
|
984
2422
|
}
|
|
985
|
-
const
|
|
986
|
-
|
|
987
|
-
.find((message) => message.role === "assistant");
|
|
2423
|
+
const messages = agent.messages();
|
|
2424
|
+
const lastAssistant = [...messages].reverse().find((message) => message.role === "assistant");
|
|
988
2425
|
if (lastAssistant?.stopReason === "aborted") {
|
|
989
2426
|
throw new CoreMindError("aborted", `步骤 ${request.stepId} 已中止`);
|
|
990
2427
|
}
|
|
991
2428
|
if (lastAssistant?.stopReason === "error") {
|
|
992
2429
|
const agentError = lastAssistant.errorMessage ?? "模型执行失败,但未提供错误详情";
|
|
993
|
-
|
|
994
|
-
throw new CoreMindError(code, `步骤 ${request.stepId} 的 Agent 执行失败:${agentError}`);
|
|
2430
|
+
throw normalizeExecutionError({ ...lastAssistant, errorMessage: agentError });
|
|
995
2431
|
}
|
|
996
|
-
return extractText(
|
|
2432
|
+
return extractText(messages.slice(messageCursor));
|
|
997
2433
|
}
|
|
998
2434
|
abortAll() {
|
|
999
|
-
|
|
1000
|
-
|
|
2435
|
+
const context = runContextFor(this);
|
|
2436
|
+
context.abortAgents();
|
|
2437
|
+
void context.cancelChildRuns("Runtime cancel").catch(() => undefined);
|
|
2438
|
+
void context.terminateEnvironment("Runtime cancel").catch(() => undefined);
|
|
2439
|
+
}
|
|
2440
|
+
async applyRunControl(command, context, deferredTerminalError) {
|
|
2441
|
+
if (command.type === "delegation_disposition") {
|
|
2442
|
+
const childRuns = context.currentChildRuns();
|
|
2443
|
+
if (!childRuns) {
|
|
2444
|
+
return { status: "rejected", reason: "当前 Run 没有可处置的 Child Run" };
|
|
2445
|
+
}
|
|
2446
|
+
if (deferredTerminalError && command.action === "redelegate") {
|
|
2447
|
+
return {
|
|
2448
|
+
status: "rejected",
|
|
2449
|
+
reason: "父级已有待恢复终态,不能重新委派 Child Run",
|
|
2450
|
+
};
|
|
2451
|
+
}
|
|
2452
|
+
try {
|
|
2453
|
+
await childRuns.recordDisposition({
|
|
2454
|
+
dispositionId: command.controlId,
|
|
2455
|
+
delegationId: command.delegationId,
|
|
2456
|
+
action: command.action,
|
|
2457
|
+
decidedBy: "human",
|
|
2458
|
+
reason: command.reason,
|
|
2459
|
+
});
|
|
2460
|
+
return "applied";
|
|
2461
|
+
}
|
|
2462
|
+
catch (error) {
|
|
2463
|
+
const normalized = normalizeExecutionError(error);
|
|
2464
|
+
return { status: "rejected", reason: normalized.message };
|
|
2465
|
+
}
|
|
2466
|
+
}
|
|
2467
|
+
if (command.type === "steering" || command.type === "follow_up") {
|
|
2468
|
+
const agent = context.agent(this.mainAgentName);
|
|
2469
|
+
if (!agent)
|
|
2470
|
+
return "accepted";
|
|
2471
|
+
agent.queueControl({ type: command.type, message: command.message });
|
|
2472
|
+
return "applied";
|
|
2473
|
+
}
|
|
2474
|
+
return (this.options.applyControl?.(command) ?? {
|
|
2475
|
+
status: "rejected",
|
|
2476
|
+
reason: `当前入口不能应用 ${command.type} 控制`,
|
|
2477
|
+
});
|
|
1001
2478
|
}
|
|
1002
2479
|
collectMessages() {
|
|
1003
|
-
|
|
1004
|
-
for (const [name, agent] of this.lastAgents)
|
|
1005
|
-
messages.set(name, agent.state.messages);
|
|
1006
|
-
return messages;
|
|
2480
|
+
return runContextFor(this).collectMessages();
|
|
1007
2481
|
}
|
|
1008
2482
|
/**
|
|
1009
2483
|
* 等待静止(规格 03 §5):所有 agent 已 idle ∧ 无 pending 工具结果 ∧
|
|
@@ -1012,10 +2486,10 @@ export class CoreMindRuntime {
|
|
|
1012
2486
|
* 超时记录 quiescence_timeout 事件但不改变终态。返回是否达到静止。
|
|
1013
2487
|
*/
|
|
1014
2488
|
async waitForQuiescence(timeoutMs = DEFAULT_QUIESCENCE_TIMEOUT_MS) {
|
|
1015
|
-
const
|
|
2489
|
+
const context = runContextFor(this);
|
|
1016
2490
|
const deadline = performance.now() + timeoutMs;
|
|
1017
2491
|
for (;;) {
|
|
1018
|
-
if (
|
|
2492
|
+
if (context.isExecutionQuiescent())
|
|
1019
2493
|
return true;
|
|
1020
2494
|
if (performance.now() >= deadline) {
|
|
1021
2495
|
this.options.events?.({ type: "quiescence_timeout", timeoutMs });
|
|
@@ -1030,33 +2504,52 @@ export class CoreMindRuntime {
|
|
|
1030
2504
|
const session = this.config.session;
|
|
1031
2505
|
if (!sessionId || !session?.enabled)
|
|
1032
2506
|
return undefined;
|
|
1033
|
-
const
|
|
2507
|
+
const context = runContextFor(this);
|
|
2508
|
+
const main = context.agent(this.mainAgentName);
|
|
1034
2509
|
if (!main)
|
|
1035
2510
|
return undefined;
|
|
1036
|
-
const cm =
|
|
2511
|
+
const cm = context.sessionHandle() ??
|
|
1037
2512
|
(await CoreMindSession.open({
|
|
1038
2513
|
dir: sessionDir(this.config, this.options.configDir),
|
|
1039
2514
|
sessionId,
|
|
1040
2515
|
cwd: this.options.cwd ?? process.cwd(),
|
|
1041
2516
|
}));
|
|
1042
2517
|
// 只追加本轮新增:恢复历史已落盘;请求级压缩的摘要与保留区已由压缩条目代表
|
|
1043
|
-
let messages = main.
|
|
1044
|
-
if (
|
|
2518
|
+
let messages = main.messages().slice(context.compactedPrefixEnd() ?? this.resumedContextLength);
|
|
2519
|
+
if (context.currentJournal()?.isAborted()) {
|
|
1045
2520
|
// D-4 方案 A:abort 后只写已确认部分——去掉尾部未正常终止的 assistant 消息(竞态赢家文本)
|
|
1046
2521
|
messages = trimUnconfirmedTail(messages);
|
|
1047
2522
|
}
|
|
1048
|
-
else if (
|
|
2523
|
+
else if (context.shouldTrimRejectedTrail()) {
|
|
1049
2524
|
// 审批拒绝等 paused:只落已发送部分——去掉尾部未发送的工具调用产物(toolResult + toolUse)
|
|
1050
2525
|
messages = trimRejectedTrail(messages);
|
|
1051
2526
|
}
|
|
1052
2527
|
await cm.appendMessages(messages);
|
|
1053
2528
|
// P2b:配置 session.compact 时,上下文超预算自动压缩(LLM 摘要,消耗 token)
|
|
1054
2529
|
if (session.compact) {
|
|
1055
|
-
|
|
2530
|
+
const mainModel = this.agentModels.get(this.mainAgentName) ?? this.providerRuntime.model;
|
|
2531
|
+
await cm.maybeCompact(this.providerRuntime.models, mainModel, mainModel.contextWindow);
|
|
1056
2532
|
}
|
|
1057
2533
|
return cm.filePath;
|
|
1058
2534
|
}
|
|
1059
2535
|
}
|
|
2536
|
+
const runtimeExecutionSlots = new WeakMap();
|
|
2537
|
+
function executionSlotFor(runtime) {
|
|
2538
|
+
const existing = runtimeExecutionSlots.get(runtime);
|
|
2539
|
+
if (existing)
|
|
2540
|
+
return existing;
|
|
2541
|
+
const created = {};
|
|
2542
|
+
runtimeExecutionSlots.set(runtime, created);
|
|
2543
|
+
return created;
|
|
2544
|
+
}
|
|
2545
|
+
function runContextFor(runtime) {
|
|
2546
|
+
const slot = executionSlotFor(runtime);
|
|
2547
|
+
const kernelContext = slot.kernel?.currentContext();
|
|
2548
|
+
if (kernelContext)
|
|
2549
|
+
return kernelContext;
|
|
2550
|
+
slot.context ??= new RunContext();
|
|
2551
|
+
return slot.context;
|
|
2552
|
+
}
|
|
1060
2553
|
/** 便捷入口:加载配置 → 构建运行时 */
|
|
1061
2554
|
export async function buildAgentFromConfig(options) {
|
|
1062
2555
|
return CoreMindRuntime.create(options);
|
|
@@ -1064,24 +2557,181 @@ export async function buildAgentFromConfig(options) {
|
|
|
1064
2557
|
/** 静止等待默认超时(规格 03 §5:默认 5s,与 runTimeout 解耦) */
|
|
1065
2558
|
const DEFAULT_QUIESCENCE_TIMEOUT_MS = 5_000;
|
|
1066
2559
|
/** 静止轮询间隔:兼顾及时性(Cancel → Quiescent p95 < 250ms)与避免忙等 */
|
|
1067
|
-
const QUIESCENCE_POLL_INTERVAL_MS =
|
|
2560
|
+
const QUIESCENCE_POLL_INTERVAL_MS = 1;
|
|
2561
|
+
const DELEGATED_SAFE_BUILTIN_TOOLS = new Set(["web-fetch", "write"]);
|
|
2562
|
+
/** Child 只保留显式网络读取与受 Checkpoint/Lease 保护的写入,不加载脚本、进程或扫描工具。 */
|
|
2563
|
+
function isDelegatedBuiltinToolConfig(tool) {
|
|
2564
|
+
return !("path" in tool) && DELEGATED_SAFE_BUILTIN_TOOLS.has(tool.id);
|
|
2565
|
+
}
|
|
2566
|
+
function isDelegatedSafeToolName(tool) {
|
|
2567
|
+
return DELEGATED_SAFE_BUILTIN_TOOLS.has(tool);
|
|
2568
|
+
}
|
|
2569
|
+
const DELEGATED_TOOL_ENV_ALLOWLIST = new Set([
|
|
2570
|
+
"PATH",
|
|
2571
|
+
"PATHEXT",
|
|
2572
|
+
"SYSTEMROOT",
|
|
2573
|
+
"WINDIR",
|
|
2574
|
+
"COMSPEC",
|
|
2575
|
+
"TEMP",
|
|
2576
|
+
"TMP",
|
|
2577
|
+
"TMPDIR",
|
|
2578
|
+
"LANG",
|
|
2579
|
+
"LC_ALL",
|
|
2580
|
+
"LC_CTYPE",
|
|
2581
|
+
"TERM",
|
|
2582
|
+
"COLORTERM",
|
|
2583
|
+
"NO_COLOR",
|
|
2584
|
+
"FORCE_COLOR",
|
|
2585
|
+
]);
|
|
2586
|
+
/** Provider 仍使用完整认证环境;Child 工具只取得平台运行必需变量。 */
|
|
2587
|
+
export function delegatedToolEnvironment(env) {
|
|
2588
|
+
return Object.fromEntries(Object.entries(env).filter(([name]) => DELEGATED_TOOL_ENV_ALLOWLIST.has(name.toUpperCase())));
|
|
2589
|
+
}
|
|
2590
|
+
/** 只把本次任务与显式引用标识符交给 Child;父 Session、文件和工具输出不参与构造。 */
|
|
2591
|
+
function propagatedChildRunError(result) {
|
|
2592
|
+
return normalizeExecutionError(result.outcome.error ?? {
|
|
2593
|
+
code: result.outcome.finishReason,
|
|
2594
|
+
message: `Child Run 终态已由 Delegation Disposition 传播:${result.outcome.finishReason}`,
|
|
2595
|
+
});
|
|
2596
|
+
}
|
|
2597
|
+
/** 父级形成任何真实终态前,撤销所有尚未建立 successor 的重新委派意图。 */
|
|
2598
|
+
export async function cancelPendingRedelegationsBeforeTerminal(childRuns, terminalError) {
|
|
2599
|
+
if (!childRuns)
|
|
2600
|
+
return undefined;
|
|
2601
|
+
const normalized = normalizeExecutionError(terminalError);
|
|
2602
|
+
const gateBeforeTerminal = childRuns.continuationGate();
|
|
2603
|
+
if (normalized.code !== "delegation_disposition_required" ||
|
|
2604
|
+
gateBeforeTerminal.status === "propagate_terminal") {
|
|
2605
|
+
await childRuns.cancelPendingRedelegations(normalized.code, `父 Run 以 ${normalized.code} 形成终态,撤销尚未执行的重新委派`);
|
|
2606
|
+
}
|
|
2607
|
+
return childRuns.continuationGate();
|
|
2608
|
+
}
|
|
2609
|
+
function delegationDispositionRequiredError(delegationId) {
|
|
2610
|
+
return new CoreMindError("delegation_disposition_required", `DelegationId ${delegationId} 尚未完成持久处置,父 Run 不能继续或形成终态`);
|
|
2611
|
+
}
|
|
2612
|
+
function serializeDeferredTerminalError(error) {
|
|
2613
|
+
const normalized = normalizeExecutionError(error);
|
|
2614
|
+
return {
|
|
2615
|
+
schemaVersion: 1,
|
|
2616
|
+
code: normalized.code,
|
|
2617
|
+
message: normalized.message,
|
|
2618
|
+
...(normalized.audit ? { audit: structuredClone(normalized.audit) } : {}),
|
|
2619
|
+
};
|
|
2620
|
+
}
|
|
2621
|
+
function restoreDeferredTerminalError(records) {
|
|
2622
|
+
const pause = records
|
|
2623
|
+
? [...records].reverse().find((record) => record.kind === "pause")
|
|
2624
|
+
: undefined;
|
|
2625
|
+
if (!pause || pause.payload === null || typeof pause.payload !== "object")
|
|
2626
|
+
return undefined;
|
|
2627
|
+
const candidate = pause.payload.deferredTerminalError;
|
|
2628
|
+
if (candidate === undefined)
|
|
2629
|
+
return undefined;
|
|
2630
|
+
if (candidate === null || typeof candidate !== "object") {
|
|
2631
|
+
throw new CoreMindError("run_state_corrupt", "暂停记录的父级延迟终态不是对象");
|
|
2632
|
+
}
|
|
2633
|
+
const payload = candidate;
|
|
2634
|
+
const audit = payload.audit;
|
|
2635
|
+
if (payload.schemaVersion !== 1 ||
|
|
2636
|
+
typeof payload.code !== "string" ||
|
|
2637
|
+
!isErrorCode(payload.code) ||
|
|
2638
|
+
typeof payload.message !== "string" ||
|
|
2639
|
+
payload.message.length === 0 ||
|
|
2640
|
+
(audit !== undefined &&
|
|
2641
|
+
(audit === null ||
|
|
2642
|
+
typeof audit !== "object" ||
|
|
2643
|
+
typeof audit.originalCode !== "string" ||
|
|
2644
|
+
audit.originalCode.length === 0))) {
|
|
2645
|
+
throw new CoreMindError("run_state_corrupt", "暂停记录的父级延迟终态合同非法");
|
|
2646
|
+
}
|
|
2647
|
+
return new CoreMindError(payload.code, payload.message, audit ? { originalCode: audit.originalCode } : undefined);
|
|
2648
|
+
}
|
|
2649
|
+
function delegatedInitialPrompt(request) {
|
|
2650
|
+
const resolvedReferences = request.context.resolvedReferences ?? [];
|
|
2651
|
+
const references = [...new Set(request.context.references)];
|
|
2652
|
+
if (resolvedReferences.length !== references.length ||
|
|
2653
|
+
resolvedReferences.some((resolved, index) => resolved.reference !== references[index])) {
|
|
2654
|
+
throw new CoreMindError("child_run_policy_escalation", "Child Runtime 拒绝未解析或不完整的 Delegated Context 引用");
|
|
2655
|
+
}
|
|
2656
|
+
return buildDelegatedInitialPrompt(request.task, resolvedReferences);
|
|
2657
|
+
}
|
|
2658
|
+
function tightenDelegationBudget(configured, inherited) {
|
|
2659
|
+
return Object.fromEntries(Object.keys(configured).map((key) => [
|
|
2660
|
+
key,
|
|
2661
|
+
Math.min(configured[key], inherited[key]),
|
|
2662
|
+
]));
|
|
2663
|
+
}
|
|
2664
|
+
async function assertRuntimeChildPolicyAuthority(input) {
|
|
2665
|
+
const { policy, config, model, executionEnvironment, workspaceRoot, tools, limits, enforceRuntimeBudget, enforceDelegatedToolBoundary, } = input;
|
|
2666
|
+
const unsafeTool = enforceDelegatedToolBoundary
|
|
2667
|
+
? [...tools].find((tool) => !isDelegatedSafeToolName(tool))
|
|
2668
|
+
: undefined;
|
|
2669
|
+
if (unsafeTool) {
|
|
2670
|
+
throw new CoreMindError("child_run_policy_escalation", `Child Runtime 工具 ${unsafeTool} 不能证明不会扩展 Delegated Context`);
|
|
2671
|
+
}
|
|
2672
|
+
const canonicalRoot = await canonicalizeWorkspace(workspaceRoot);
|
|
2673
|
+
if (!matchesRuntimeChildModel(policy.model, model)) {
|
|
2674
|
+
throw new CoreMindError("child_run_policy_escalation", "Child Run 父策略模型与当前 Runtime 的实际 Provider/model 不一致");
|
|
2675
|
+
}
|
|
2676
|
+
if (policy.workspace.canonicalRoot !== canonicalRoot ||
|
|
2677
|
+
policy.workspace.lease !== "shared_canonical") {
|
|
2678
|
+
throw new CoreMindError("child_run_policy_escalation", "Child Run 父策略 Workspace 必须绑定当前 Runtime 的 canonical root 与共享租约");
|
|
2679
|
+
}
|
|
2680
|
+
const permissions = {
|
|
2681
|
+
mode: config.permissions?.mode ?? "ask",
|
|
2682
|
+
workspaceOnly: config.permissions?.workspaceOnly ?? true,
|
|
2683
|
+
network: config.permissions?.network ?? "ask",
|
|
2684
|
+
};
|
|
2685
|
+
if (policy.permissions.mode !== permissions.mode ||
|
|
2686
|
+
policy.permissions.workspaceOnly !== permissions.workspaceOnly ||
|
|
2687
|
+
policy.permissions.network !== permissions.network ||
|
|
2688
|
+
[...tools].some((tool) => !policy.permissions.tools.includes(tool)) ||
|
|
2689
|
+
policy.permissions.paths.some((allowedPath) => path.isAbsolute(allowedPath) || allowedPath.split(/[\\/]/u).includes("..")) ||
|
|
2690
|
+
policy.permissions.credentials.length > 0) {
|
|
2691
|
+
throw new CoreMindError("child_run_policy_escalation", "Child Run 父策略权限、工具、路径或凭据范围不是当前 Runtime 的真实子集");
|
|
2692
|
+
}
|
|
2693
|
+
if (limits.maxTokens === undefined || limits.maxCostUsd === undefined) {
|
|
2694
|
+
throw new CoreMindError("child_run_policy_escalation", "启用 Child Run 前必须为父 Runtime 显式配置 maxTokens 与 maxCostUsd");
|
|
2695
|
+
}
|
|
2696
|
+
if (enforceRuntimeBudget) {
|
|
2697
|
+
const budgetBounds = {
|
|
2698
|
+
tokens: limits.maxTokens,
|
|
2699
|
+
toolCalls: limits.maxToolCalls,
|
|
2700
|
+
costUsd: limits.maxCostUsd,
|
|
2701
|
+
wallTimeMs: limits.runTimeoutMs,
|
|
2702
|
+
steps: limits.maxSteps,
|
|
2703
|
+
};
|
|
2704
|
+
for (const key of Object.keys(budgetBounds)) {
|
|
2705
|
+
if (budgetBounds[key] > policy.budget[key]) {
|
|
2706
|
+
throw new CoreMindError("child_run_policy_escalation", `Child Runtime 的 ${key} 实际上限超过父级划拨预算`);
|
|
2707
|
+
}
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
try {
|
|
2711
|
+
await resolveExecutionEnvironment(executionEnvironment, policy.environment);
|
|
2712
|
+
}
|
|
2713
|
+
catch (error) {
|
|
2714
|
+
throw new CoreMindError("child_run_policy_escalation", error instanceof Error ? error.message : String(error));
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
function matchesRuntimeChildModel(expected, actual) {
|
|
2718
|
+
return (expected.providerId === actual.providerId &&
|
|
2719
|
+
expected.model === actual.model &&
|
|
2720
|
+
fingerprintEffectReceiptValue(expected.options ?? null) ===
|
|
2721
|
+
fingerprintEffectReceiptValue(actual.options ?? null) &&
|
|
2722
|
+
expected.providerConfigFingerprint === actual.providerConfigFingerprint &&
|
|
2723
|
+
expected.agentPromptFingerprint === actual.agentPromptFingerprint &&
|
|
2724
|
+
expected.agentDelegationFingerprint === actual.agentDelegationFingerprint);
|
|
2725
|
+
}
|
|
1068
2726
|
/**
|
|
1069
2727
|
* 静止判定(规格 03 §5):quiescent ⇔ 所有 agent 已 idle ∧ 无 pending 工具结果 ∧
|
|
1070
2728
|
* journal 无 pending flush。模块级函数而非 private 方法:避免进入 untrimmed d.ts
|
|
1071
2729
|
* (#39 教训:类私有成员也会进 d.ts,冻结基线逐字哈希会失败)。
|
|
1072
2730
|
*/
|
|
1073
|
-
function
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
if (agent.state.pendingToolCalls.size > 0)
|
|
1078
|
-
return false;
|
|
1079
|
-
if (agent.hasQueuedMessages())
|
|
1080
|
-
return false;
|
|
1081
|
-
}
|
|
1082
|
-
if (journal !== undefined && hasPendingJournalFlush(journal))
|
|
1083
|
-
return false;
|
|
1084
|
-
return true;
|
|
2731
|
+
function durabilityFailure(error) {
|
|
2732
|
+
return error instanceof CoreMindError
|
|
2733
|
+
? error
|
|
2734
|
+
: new CoreMindError("durability_barrier_failed", error instanceof Error ? error.message : String(error));
|
|
1085
2735
|
}
|
|
1086
2736
|
/**
|
|
1087
2737
|
* 从既有事件序列提取已登记的输入 ID(resume 时沿用原 run 的收据,
|
|
@@ -1094,6 +2744,9 @@ function resumedInputId(events) {
|
|
|
1094
2744
|
}
|
|
1095
2745
|
return undefined;
|
|
1096
2746
|
}
|
|
2747
|
+
function toolCallIdentity(agent, stepId, callId) {
|
|
2748
|
+
return { agent, callId, ...(stepId ? { stepId } : {}) };
|
|
2749
|
+
}
|
|
1097
2750
|
/** 分界前已启动的活动集合(R3 判定用):从已收集事件的 turnId 提取 */
|
|
1098
2751
|
function knownTurnIdsFrom(collected) {
|
|
1099
2752
|
return new Set(collected.flatMap((event) => {
|
|
@@ -1101,12 +2754,33 @@ function knownTurnIdsFrom(collected) {
|
|
|
1101
2754
|
return turnId ? [turnId] : [];
|
|
1102
2755
|
}));
|
|
1103
2756
|
}
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
2757
|
+
function traceFactDurability(event, capabilities) {
|
|
2758
|
+
switch (event.type) {
|
|
2759
|
+
case "capability_resolved":
|
|
2760
|
+
return "ordinary";
|
|
2761
|
+
case "workspace_lease":
|
|
2762
|
+
return "critical";
|
|
2763
|
+
case "tool_result": {
|
|
2764
|
+
const callId = event.callId;
|
|
2765
|
+
if (!callId)
|
|
2766
|
+
return "critical";
|
|
2767
|
+
return (capabilities.get(toolCapabilityCallKey(event.agent, event.stepId, callId))?.capability
|
|
2768
|
+
.durability ?? "critical");
|
|
2769
|
+
}
|
|
2770
|
+
case "tool_attempt":
|
|
2771
|
+
return "critical";
|
|
2772
|
+
case "tool_lifecycle":
|
|
2773
|
+
return "ordinary";
|
|
2774
|
+
case "effect_receipt":
|
|
2775
|
+
return event.status === "not_started" ? "ordinary" : "critical";
|
|
2776
|
+
case "approval_required":
|
|
2777
|
+
case "approval_resolved":
|
|
2778
|
+
case "policy_denied":
|
|
2779
|
+
return "critical";
|
|
2780
|
+
default:
|
|
2781
|
+
return "ordinary";
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
1110
2784
|
/** D-4 方案 A:去掉尾部未正常终止的 assistant 消息(abort 竞态赢家文本不落会话树) */
|
|
1111
2785
|
function trimUnconfirmedTail(messages) {
|
|
1112
2786
|
let end = messages.length;
|
|
@@ -1145,6 +2819,32 @@ function lastOutputText(outputs) {
|
|
|
1145
2819
|
const last = values[values.length - 1];
|
|
1146
2820
|
return last ? last.text : "";
|
|
1147
2821
|
}
|
|
2822
|
+
function telemetryPolicyFromConfig(config) {
|
|
2823
|
+
return {
|
|
2824
|
+
mode: config.telemetry?.mode ?? "DISABLED",
|
|
2825
|
+
contentLevel: config.telemetry?.contentLevel ?? "metrics_only",
|
|
2826
|
+
allowedFields: config.telemetry?.allowedFields ?? [],
|
|
2827
|
+
...(config.telemetry?.endpoint ? { endpoint: config.telemetry.endpoint } : {}),
|
|
2828
|
+
};
|
|
2829
|
+
}
|
|
2830
|
+
function fallbackObservability(input) {
|
|
2831
|
+
const projection = projectLocalObservability([], {
|
|
2832
|
+
runStatus: input.outcome.status === "paused" ? "paused" : "finished",
|
|
2833
|
+
resumable: input.outcome.status === "paused" && input.operation.state === "paused",
|
|
2834
|
+
operationState: input.operation.state,
|
|
2835
|
+
});
|
|
2836
|
+
return {
|
|
2837
|
+
...projection,
|
|
2838
|
+
telemetry: {
|
|
2839
|
+
...projection.telemetry,
|
|
2840
|
+
mode: input.telemetry.mode,
|
|
2841
|
+
contentLevel: input.telemetry.contentLevel,
|
|
2842
|
+
allowedFields: input.telemetry.allowedFields,
|
|
2843
|
+
...(input.telemetry.endpointOrigin ? { endpointOrigin: input.telemetry.endpointOrigin } : {}),
|
|
2844
|
+
source: input.telemetry.mode === "DISABLED" ? "default" : "configured",
|
|
2845
|
+
},
|
|
2846
|
+
};
|
|
2847
|
+
}
|
|
1148
2848
|
function firstKey(record) {
|
|
1149
2849
|
return Object.keys(record)[0];
|
|
1150
2850
|
}
|