coremind-runtime 0.3.0 → 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 +45 -0
- package/dist/compaction-projection.d.ts.map +1 -0
- package/dist/compaction-projection.js +133 -0
- package/dist/compaction-projection.js.map +1 -0
- 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/context.d.ts +9 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +24 -1
- package/dist/context.js.map +1 -1
- 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 +18 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +36 -2
- 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 +131 -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 +51 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +27 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +16 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -2
- package/dist/index.js.map +1 -1
- package/dist/input-receipt.d.ts +59 -0
- package/dist/input-receipt.d.ts.map +1 -0
- package/dist/input-receipt.js +102 -0
- package/dist/input-receipt.js.map +1 -0
- 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 +28 -0
- package/dist/invariant-checker.d.ts.map +1 -0
- package/dist/invariant-checker.js +441 -0
- package/dist/invariant-checker.js.map +1 -0
- package/dist/loop-runner.d.ts.map +1 -1
- package/dist/loop-runner.js +37 -24
- 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/race-seeds.d.ts +43 -0
- package/dist/race-seeds.d.ts.map +1 -0
- package/dist/race-seeds.js +53 -0
- package/dist/race-seeds.js.map +1 -0
- package/dist/rebuild-request.d.ts +30 -0
- package/dist/rebuild-request.d.ts.map +1 -0
- package/dist/rebuild-request.js +37 -0
- package/dist/rebuild-request.js.map +1 -0
- 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 +20 -2
- package/dist/result.d.ts.map +1 -1
- package/dist/result.js +18 -1
- package/dist/result.js.map +1 -1
- package/dist/retry-policy.d.ts.map +1 -1
- package/dist/retry-policy.js +21 -85
- 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 +2 -1
- package/dist/run-effect-coordinator.d.ts.map +1 -1
- package/dist/run-effect-coordinator.js +6 -5
- 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 +107 -4
- package/dist/run-state.d.ts.map +1 -1
- package/dist/run-state.js +627 -77
- package/dist/run-state.js.map +1 -1
- package/dist/run-terminalizer.d.ts.map +1 -1
- package/dist/run-terminalizer.js +6 -17
- 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 +104 -2
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +2242 -288
- package/dist/runtime.js.map +1 -1
- package/dist/session.d.ts +19 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +43 -2
- package/dist/session.js.map +1 -1
- package/dist/snapshot.d.ts.map +1 -1
- package/dist/snapshot.js +3 -20
- package/dist/snapshot.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 +14 -0
- package/dist/turn-tracker.d.ts.map +1 -0
- package/dist/turn-tracker.js +50 -0
- package/dist/turn-tracker.js.map +1 -0
- 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,29 +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 {
|
|
10
|
-
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";
|
|
11
21
|
import { extractAgentError, extractText } from "./events.js";
|
|
22
|
+
import { normalizeExecutionError } from "./execution-error.js";
|
|
23
|
+
import { enforceExecutionSecurity } from "./execution-security.js";
|
|
24
|
+
import { receiptId } from "./ids.js";
|
|
25
|
+
import { claimInput, completeInput, createInputReceipt, discardInput, inputFingerprint, newInputId, receiptStatusOf, } from "./input-receipt.js";
|
|
12
26
|
import { LifecycleExtensionHost, } from "./lifecycle-extension.js";
|
|
13
27
|
import { LoopRunner } from "./loop-runner.js";
|
|
28
|
+
import { createTelemetryConfigurationFact, projectLocalObservability, TelemetryEgressController, validateTelemetryConsentBinding, validateTelemetryConsentFact, } from "./observability.js";
|
|
14
29
|
import { DurableOperation, restoreDurableOperation, } from "./operation-state.js";
|
|
15
30
|
import { Orchestrator } from "./orchestrator.js";
|
|
16
|
-
import {
|
|
31
|
+
import { ProjectionEngine } from "./projection.js";
|
|
32
|
+
import { buildProviderRuntime, contextCapabilityCandidatesForModel, resolveProviderModel, } from "./provider.js";
|
|
17
33
|
import { adaptCoreMindTool } from "./public-tool.js";
|
|
34
|
+
import { createProviderRequestReplayFact } from "./replay-kit.js";
|
|
18
35
|
import { analyzeRunMetrics, assessReleaseReadiness, createEvaluationReport, } from "./result.js";
|
|
19
|
-
import {
|
|
36
|
+
import { runWithTransientRetry } from "./retry-policy.js";
|
|
37
|
+
import { RunContext } from "./run-context.js";
|
|
20
38
|
import { RunEffectCoordinator } from "./run-effect-coordinator.js";
|
|
21
|
-
import {
|
|
39
|
+
import { RunKernel } from "./run-kernel.js";
|
|
40
|
+
import { FileRunStore, fingerprintRunConfig, RunStateJournal, } from "./run-state.js";
|
|
22
41
|
import { RunTerminalizer } from "./run-terminalizer.js";
|
|
42
|
+
import { registerCoreMindRuntimeInstance } from "./runtime-instance-authority.js";
|
|
23
43
|
import { CoreMindSession } from "./session.js";
|
|
24
44
|
import { createRunSnapshot } from "./snapshot.js";
|
|
45
|
+
import { ToolExecutionEngine } from "./tool-call-lifecycle.js";
|
|
46
|
+
import { toolCapabilityCallKey } from "./tool-capability-identity.js";
|
|
25
47
|
import { ToolPolicy } from "./tool-policy.js";
|
|
26
48
|
import { TraceRecorder } from "./trace.js";
|
|
49
|
+
import { TurnTracker } from "./turn-tracker.js";
|
|
50
|
+
import { canonicalizeWorkspace, WorkspaceLeaseService, } from "./workspace-lease.js";
|
|
27
51
|
/**
|
|
28
52
|
* CoreMind 运行时门面:配置 → provider/工具/agent → 执行。
|
|
29
53
|
* 库形式嵌入入口:buildAgentFromConfig / CoreMindRuntime.create().run()
|
|
@@ -31,9 +55,13 @@ import { TraceRecorder } from "./trace.js";
|
|
|
31
55
|
export class CoreMindRuntime {
|
|
32
56
|
config;
|
|
33
57
|
agentConfigs;
|
|
34
|
-
|
|
58
|
+
agentModels;
|
|
59
|
+
driverBuilders;
|
|
35
60
|
toolEffectsByAgent;
|
|
61
|
+
toolCapabilitiesByAgent;
|
|
36
62
|
providerRuntime;
|
|
63
|
+
executionEnvironment;
|
|
64
|
+
workspaceLeaseService;
|
|
37
65
|
options;
|
|
38
66
|
/** 最近创建的每个 agent 实例(收集最终消息/落盘用) */
|
|
39
67
|
lastAgents = new Map();
|
|
@@ -46,54 +74,150 @@ export class CoreMindRuntime {
|
|
|
46
74
|
/** agent 名 → 注入的技能内容 */
|
|
47
75
|
skillsByAgent;
|
|
48
76
|
activeHarnessFactory;
|
|
49
|
-
|
|
77
|
+
/** 并发 run() 检测(R7):进行中的 run promise */
|
|
78
|
+
activeRunPromise;
|
|
79
|
+
/** 当前 run 的 journal(persistSession 的准入/abort 语义用) */
|
|
80
|
+
runJournal;
|
|
81
|
+
/** 当前或最近一次 run 的 canonical store(只读 Projection 查询用)。 */
|
|
82
|
+
activeRunStore;
|
|
83
|
+
/** 本次 run 打开的会话(压缩条目落盘与 persist 复用同一句柄) */
|
|
84
|
+
activeSession;
|
|
85
|
+
/** 会话树已落盘视图消息 + 来源条目 id(压缩替换范围的桥接) */
|
|
86
|
+
sessionBranch;
|
|
87
|
+
/** 压缩后 agent 消息数组中被会话树代表的前缀长度(persist 跳过,避免重复落盘) */
|
|
88
|
+
compactedPrefixEnd;
|
|
89
|
+
constructor(config, agentConfigs, agentModels, driverBuilders, toolEffectsByAgent, toolCapabilitiesByAgent, providerRuntime, executionEnvironment, workspaceLeaseService, options, sessionMessages, resumedContextLength, skillsByAgent) {
|
|
50
90
|
this.config = config;
|
|
51
91
|
this.agentConfigs = agentConfigs;
|
|
52
|
-
this.
|
|
92
|
+
this.agentModels = agentModels;
|
|
93
|
+
this.driverBuilders = driverBuilders;
|
|
53
94
|
this.toolEffectsByAgent = toolEffectsByAgent;
|
|
95
|
+
this.toolCapabilitiesByAgent = toolCapabilitiesByAgent;
|
|
54
96
|
this.providerRuntime = providerRuntime;
|
|
97
|
+
this.executionEnvironment = executionEnvironment;
|
|
98
|
+
this.workspaceLeaseService = workspaceLeaseService;
|
|
55
99
|
this.options = options;
|
|
100
|
+
registerCoreMindRuntimeInstance(this);
|
|
56
101
|
this.sessionMessages = sessionMessages;
|
|
57
102
|
this.resumedContextLength = resumedContextLength;
|
|
58
103
|
this.mainAgentName = config.defaultAgent ?? firstKey(config.agents) ?? "";
|
|
59
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;
|
|
60
111
|
}
|
|
61
112
|
/** 由配置构建运行时(注册 provider、构建工具与全部 agent 定义) */
|
|
62
113
|
static async create(options) {
|
|
114
|
+
return CoreMindRuntime.createWithWorkspaceLease(options, new WorkspaceLeaseService());
|
|
115
|
+
}
|
|
116
|
+
/** 同一父子树复用一个 Lease 服务;跨进程一致性仍由 canonical lock file 提供。 */
|
|
117
|
+
static async createWithWorkspaceLease(options, workspaceLeaseService) {
|
|
63
118
|
const { config, configDir } = options;
|
|
64
119
|
const cwd = options.cwd ?? process.cwd();
|
|
65
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);
|
|
66
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
|
+
}
|
|
67
133
|
// 1. provider(解析模型,警告转发)
|
|
68
|
-
const providerRuntime = await buildProviderRuntime(config.provider, env);
|
|
134
|
+
const providerRuntime = await buildProviderRuntime(config.provider, env, options.secretResolver);
|
|
69
135
|
for (const warning of providerRuntime.warnings) {
|
|
70
136
|
emit({ type: "error", message: warning, fatal: false });
|
|
71
137
|
}
|
|
72
138
|
// 2. 每个 agent:构建工具与技能(Agent 实例按需创建,避免并发冲突)
|
|
73
139
|
const agentConfigs = new Map();
|
|
74
|
-
const
|
|
140
|
+
const agentModels = new Map();
|
|
141
|
+
const driverBuilders = new Map();
|
|
75
142
|
const toolEffectsByAgent = new Map();
|
|
143
|
+
const toolCapabilitiesByAgent = new Map();
|
|
76
144
|
const skillsByAgent = new Map();
|
|
77
145
|
const artifactStore = new ArtifactStore({ cwd });
|
|
146
|
+
const executionEnvironment = createPlatformExecutionEnvironment({
|
|
147
|
+
workspaceRoot: cwd,
|
|
148
|
+
env: toolEnv,
|
|
149
|
+
});
|
|
78
150
|
const externalTools = (options.toolDefinitions ?? []).map((definition) => wrapToolWithArtifactCapture(adaptCoreMindTool(definition), artifactStore));
|
|
151
|
+
let runtime;
|
|
79
152
|
// 自定义技能(生态机制):配置文件所在目录的 skills/ 下,每个子目录的 README.md 即一个技能
|
|
80
153
|
const customSkills = await loadDirectorySkills(path.join(configDir, "skills"));
|
|
81
154
|
for (const [name, agentCfg] of Object.entries(config.agents)) {
|
|
155
|
+
const agentModel = resolveProviderModel(providerRuntime, agentCfg.model);
|
|
156
|
+
agentModels.set(name, agentModel);
|
|
82
157
|
const toolConfigs = (agentCfg.tools?.length ?? 0) > 0 ? agentCfg.tools : config.tools;
|
|
83
|
-
const { tools, warnings, effects } = await
|
|
158
|
+
const { tools, warnings, effects, capabilities } = await buildToolsWithExecutionEnvironment(toolConfigs ?? [], {
|
|
84
159
|
cwd,
|
|
85
160
|
configDir,
|
|
86
|
-
env,
|
|
161
|
+
env: toolEnv,
|
|
87
162
|
artifactStore,
|
|
88
|
-
});
|
|
163
|
+
}, executionEnvironment);
|
|
89
164
|
for (const warning of warnings) {
|
|
90
165
|
emit({ type: "error", message: warning, fatal: false });
|
|
91
166
|
}
|
|
92
167
|
agentConfigs.set(name, agentCfg);
|
|
93
|
-
|
|
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
|
+
: [];
|
|
94
203
|
toolEffectsByAgent.set(name, new Map([
|
|
95
204
|
...effects,
|
|
96
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,
|
|
97
221
|
]));
|
|
98
222
|
// 技能:内置优先,未命中的查自定义目录,仍缺失才告警(不阻断)
|
|
99
223
|
const { contents, missing } = resolveSkills(agentCfg.skills ?? []);
|
|
@@ -112,6 +236,25 @@ export class CoreMindRuntime {
|
|
|
112
236
|
}
|
|
113
237
|
}
|
|
114
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
|
+
}));
|
|
115
258
|
}
|
|
116
259
|
// 会话恢复:--session 且 session.enabled 时,打开已有会话注入历史视图(非破坏)
|
|
117
260
|
let sessionMessages;
|
|
@@ -121,10 +264,10 @@ export class CoreMindRuntime {
|
|
|
121
264
|
try {
|
|
122
265
|
if (await CoreMindSession.exists(dir, options.sessionId, cwd)) {
|
|
123
266
|
const cm = await CoreMindSession.open({ dir, sessionId: options.sessionId, cwd });
|
|
124
|
-
const
|
|
125
|
-
if (
|
|
126
|
-
sessionMessages =
|
|
127
|
-
resumedContextLength =
|
|
267
|
+
const restored = projectBranchMessages(await cm.branchEntries()).map((item) => item.message);
|
|
268
|
+
if (restored.length > 0) {
|
|
269
|
+
sessionMessages = restored;
|
|
270
|
+
resumedContextLength = restored.length;
|
|
128
271
|
}
|
|
129
272
|
}
|
|
130
273
|
}
|
|
@@ -133,44 +276,62 @@ export class CoreMindRuntime {
|
|
|
133
276
|
throw new CoreMindError("session_restore_failed", `会话 ${options.sessionId} 恢复失败:${detail}`);
|
|
134
277
|
}
|
|
135
278
|
}
|
|
136
|
-
|
|
279
|
+
runtime = new CoreMindRuntime(config, agentConfigs, agentModels, driverBuilders, toolEffectsByAgent, toolCapabilitiesByAgent, providerRuntime, executionEnvironment, workspaceLeaseService, options, sessionMessages, resumedContextLength, skillsByAgent);
|
|
280
|
+
return runtime;
|
|
137
281
|
}
|
|
138
|
-
/** 按名字创建独立
|
|
282
|
+
/** 按名字创建独立 Driver 实例(每次新实例,消息历史独立) */
|
|
139
283
|
createAgent(name, onEvent = this.options.events ?? (() => { }), stepId) {
|
|
140
|
-
const
|
|
141
|
-
if (!
|
|
284
|
+
const buildDriver = this.driverBuilders.get(name);
|
|
285
|
+
if (!buildDriver)
|
|
142
286
|
return undefined;
|
|
143
|
-
const
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
model: this.providerRuntime.model,
|
|
147
|
-
tools: this.toolsByAgent.get(name) ?? [],
|
|
148
|
-
agentName: name,
|
|
287
|
+
const context = runContextFor(this);
|
|
288
|
+
const harness = context.harnessFor(name, stepId);
|
|
289
|
+
const agent = buildDriver({
|
|
149
290
|
onEvent,
|
|
150
|
-
apiKeyOverride: this.providerRuntime.apiKeyOverride,
|
|
151
291
|
// 恢复视图只注入主 agent(会话归属者)
|
|
152
292
|
sessionMessages: name === this.mainAgentName ? this.sessionMessages : undefined,
|
|
153
|
-
skillsContent: this.skillsByAgent.get(name),
|
|
154
|
-
stableFacts: {
|
|
155
|
-
provider: this.providerRuntime.model.provider,
|
|
156
|
-
model: this.providerRuntime.model.id,
|
|
157
|
-
contextWindow: this.providerRuntime.model.contextWindow,
|
|
158
|
-
},
|
|
159
|
-
promptCacheStatus: this.providerRuntime.promptCacheStatus,
|
|
160
293
|
harness,
|
|
161
294
|
});
|
|
162
|
-
|
|
163
|
-
agent.shouldStopAfterTurn = harness?.shouldStopAfterTurn;
|
|
164
|
-
if (harness?.throwIfDenied) {
|
|
165
|
-
const waitForIdle = agent.waitForIdle.bind(agent);
|
|
166
|
-
agent.waitForIdle = async () => {
|
|
167
|
-
await waitForIdle();
|
|
168
|
-
harness.throwIfDenied?.();
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
this.lastAgents.set(name, agent);
|
|
295
|
+
context.registerAgent(name, agent);
|
|
172
296
|
return agent;
|
|
173
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
|
+
}
|
|
174
335
|
/** 查询配置中是否存在 Agent,供交互会话在首轮前快速失败。 */
|
|
175
336
|
hasAgent(name) {
|
|
176
337
|
return this.agentConfigs.has(name);
|
|
@@ -191,14 +352,35 @@ export class CoreMindRuntime {
|
|
|
191
352
|
}
|
|
192
353
|
const turnConfig = { ...this.config, defaultAgent: agentName };
|
|
193
354
|
delete turnConfig.workflow;
|
|
194
|
-
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, {
|
|
195
356
|
...this.options,
|
|
196
357
|
config: turnConfig,
|
|
197
358
|
initialPrompt: message,
|
|
198
359
|
events,
|
|
199
360
|
signal,
|
|
200
361
|
}, history, history.length, this.skillsByAgent);
|
|
201
|
-
|
|
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;
|
|
202
384
|
}
|
|
203
385
|
inspectCheckpoint(record) {
|
|
204
386
|
return inspectStoredCheckpoint(record, this.options.cwd ?? process.cwd());
|
|
@@ -208,19 +390,404 @@ export class CoreMindRuntime {
|
|
|
208
390
|
}
|
|
209
391
|
/** 执行:有 workflow 走编排,否则单 agent 直答。返回结果含质量摘要 */
|
|
210
392
|
async run() {
|
|
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");
|
|
401
|
+
}
|
|
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));
|
|
407
|
+
}
|
|
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}`);
|
|
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
|
+
};
|
|
732
|
+
}
|
|
733
|
+
/** run() 主体(并发检测由外层 run() 包装) */
|
|
734
|
+
async executeRunBody(context) {
|
|
735
|
+
context.attachExecutionEnvironment(this.executionEnvironment);
|
|
211
736
|
const started = performance.now();
|
|
212
737
|
const lifecycleHost = this.options.lifecycleExtensions
|
|
213
738
|
? new LifecycleExtensionHost(this.options.lifecycleExtensions)
|
|
214
739
|
: undefined;
|
|
215
740
|
const runStore = this.options.runStore ??
|
|
216
741
|
new FileRunStore(path.join(this.options.configDir, ".coremind", "runs"));
|
|
742
|
+
this.activeRunStore = runStore;
|
|
217
743
|
const configFingerprint = fingerprintRunConfig(this.config);
|
|
218
|
-
const
|
|
219
|
-
|
|
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));
|
|
747
|
+
// 会话树关联:打开会话拿 seq 水位与已落盘视图(压缩条目落盘与重建桥接用)
|
|
748
|
+
let sessionSeqStart;
|
|
749
|
+
let canonicalSessionBranch = [];
|
|
750
|
+
let previousContextCompactions = [];
|
|
751
|
+
if (this.options.sessionId && this.config.session?.enabled) {
|
|
752
|
+
const session = await CoreMindSession.open({
|
|
753
|
+
dir: sessionDir(this.config, this.options.configDir),
|
|
754
|
+
sessionId: this.options.sessionId,
|
|
755
|
+
cwd: this.options.cwd ?? process.cwd(),
|
|
756
|
+
});
|
|
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);
|
|
762
|
+
}
|
|
763
|
+
const resumeRecords = this.options.resumeRunId
|
|
764
|
+
? await runStore.read(this.options.resumeRunId)
|
|
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)
|
|
220
777
|
: undefined;
|
|
221
|
-
const
|
|
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
|
+
}
|
|
785
|
+
// 预生成 runId(D-1):resume 时以恢复记录为准,否则优先使用调用方预生成值
|
|
786
|
+
const runId = (resumePlan?.runId ?? this.options.runId ?? randomUUID());
|
|
787
|
+
context.attachRunId(runId);
|
|
222
788
|
const effectiveInitialPrompt = resumePlan?.initialPrompt ?? this.options.initialPrompt;
|
|
223
789
|
const journal = new RunStateJournal(runId, runStore, resumePlan?.nextJournalSequence ?? 0);
|
|
790
|
+
context.attachJournal(journal);
|
|
224
791
|
const operation = resumePlan && resumePlan.operationRecords.length > 0
|
|
225
792
|
? restoreDurableOperation(resumePlan.operationRecords)
|
|
226
793
|
: DurableOperation.create({
|
|
@@ -244,6 +811,14 @@ export class CoreMindRuntime {
|
|
|
244
811
|
journal.resume({
|
|
245
812
|
completedStepIds: [...resumePlan.completedSteps.keys()],
|
|
246
813
|
resumedAt: new Date().toISOString(),
|
|
814
|
+
...(this.options.protocolStart ? { protocolStart: this.options.protocolStart } : {}),
|
|
815
|
+
...(this.options.sessionId ? { sessionId: this.options.sessionId } : {}),
|
|
816
|
+
...(sessionSeqStart !== undefined
|
|
817
|
+
? { sessionSeqStart, turnSeqStart: sessionSeqStart }
|
|
818
|
+
: {}),
|
|
819
|
+
});
|
|
820
|
+
await journal.appendFact("telemetry_configuration", telemetryConfiguration, {
|
|
821
|
+
durability: "critical",
|
|
247
822
|
});
|
|
248
823
|
}
|
|
249
824
|
else {
|
|
@@ -253,9 +828,18 @@ export class CoreMindRuntime {
|
|
|
253
828
|
configFingerprint,
|
|
254
829
|
initialPrompt: this.options.initialPrompt,
|
|
255
830
|
sessionId: this.options.sessionId,
|
|
831
|
+
...(sessionSeqStart !== undefined
|
|
832
|
+
? { sessionSeqStart, turnSeqStart: sessionSeqStart }
|
|
833
|
+
: {}),
|
|
256
834
|
operationId: operation.snapshot().operationId,
|
|
835
|
+
telemetry: telemetryConfiguration,
|
|
836
|
+
...(this.options.protocolStart ? { protocolStart: this.options.protocolStart } : {}),
|
|
257
837
|
});
|
|
258
838
|
}
|
|
839
|
+
for (const consent of telemetryConsents) {
|
|
840
|
+
validateTelemetryConsentBinding(consent, await runStore.read(runId));
|
|
841
|
+
await journal.appendFact("telemetry_consent", consent, { durability: "critical" });
|
|
842
|
+
}
|
|
259
843
|
if (!resumePlan || resumePlan.operationRecords.length === 0) {
|
|
260
844
|
journal.operation(operation.records()[0]);
|
|
261
845
|
}
|
|
@@ -276,26 +860,215 @@ export class CoreMindRuntime {
|
|
|
276
860
|
throw new CoreMindError("operation_not_resumable", `操作 ${operation.snapshot().operationId} 处于 ${operation.snapshot().state},不能继续执行`);
|
|
277
861
|
}
|
|
278
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();
|
|
279
870
|
const trace = new TraceRecorder(runId, (entry) => {
|
|
280
|
-
journal.event
|
|
871
|
+
void journal.appendFact("event", entry, {
|
|
872
|
+
durability: traceFactDurability(entry.event, capabilityByCallId),
|
|
873
|
+
eventId: entry.eventId,
|
|
874
|
+
});
|
|
281
875
|
this.options.trace?.(entry);
|
|
282
876
|
}, resumePlan?.previousTrace);
|
|
283
877
|
const collected = resumePlan?.previousTrace.map((entry) => entry.event) ?? [];
|
|
878
|
+
const toolReplayCandidates = [...(resumePlan?.toolReplayCandidates ?? [])];
|
|
284
879
|
const userEvents = this.options.events ?? (() => { });
|
|
285
|
-
const
|
|
286
|
-
const
|
|
880
|
+
const turnTracker = new TurnTracker();
|
|
881
|
+
const effectBindingByCall = new Map();
|
|
882
|
+
const effectBindingByReceipt = new Map();
|
|
883
|
+
// 输入收据(规格 03 §4):恢复时沿用原 run 的 inputId(收据链连续),否则新生成
|
|
884
|
+
const inputId = effectiveInitialPrompt === undefined
|
|
885
|
+
? undefined
|
|
886
|
+
: (resumedInputId(collected) ?? newInputId());
|
|
887
|
+
// 收据状态由本 run 发出的事件推进(pending → claimed → completed/discarded);
|
|
888
|
+
// resume 时原 run 已登记(pending/claimed)则本 run 不重复登记与 claim(折叠不允许
|
|
889
|
+
// pending→pending / claimed→claimed),仅收尾按终态推进
|
|
890
|
+
const existingInputState = inputId === undefined ? undefined : receiptStatusOf(collected, inputId);
|
|
891
|
+
let inputReceiptState = existingInputState ?? (inputId === undefined ? undefined : "pending");
|
|
892
|
+
let onToolResultRecorded;
|
|
893
|
+
const lifecycleFinalizers = new Set();
|
|
894
|
+
let lifecycleFailure;
|
|
895
|
+
const emitInputEvent = (event) => {
|
|
287
896
|
collected.push(event);
|
|
288
897
|
trace.record(event);
|
|
289
898
|
userEvents(event);
|
|
290
899
|
};
|
|
900
|
+
const recordEvent = (event) => {
|
|
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
|
+
}
|
|
946
|
+
// 事件准入(规格 03 §3):abort 后的迟到终态事实不入 trace/collected/回调(ADR:不入 Trace 或 journal)
|
|
947
|
+
if (!journal.admitEvent(enriched))
|
|
948
|
+
return;
|
|
949
|
+
collected.push(enriched);
|
|
950
|
+
trace.record(enriched);
|
|
951
|
+
userEvents(enriched);
|
|
952
|
+
if (enriched.type === "tool_result")
|
|
953
|
+
onToolResultRecorded?.(enriched);
|
|
954
|
+
// 输入被首个 Turn 认领(规格 03 §4:claim 绑定 TurnId;resume 时已 claimed 不再重复);
|
|
955
|
+
// 排在 agent_start 之后,保证事件顺序:agent_start → input_claimed
|
|
956
|
+
if (enriched.type === "agent_start" && inputReceiptState === "pending") {
|
|
957
|
+
inputReceiptState = "claimed";
|
|
958
|
+
emitInputEvent(claimInput({ inputId: inputId, turnId: enriched.turnId }));
|
|
959
|
+
}
|
|
960
|
+
};
|
|
961
|
+
if (inputId !== undefined && existingInputState === undefined) {
|
|
962
|
+
// headless initialPrompt / chat 每轮 message:Run start 时登记 pending 收据(带指纹,
|
|
963
|
+
// 不落原文);resume 沿用原收据不重复登记
|
|
964
|
+
emitInputEvent(createInputReceipt({
|
|
965
|
+
inputId,
|
|
966
|
+
contentFingerprint: inputFingerprint(effectiveInitialPrompt),
|
|
967
|
+
}));
|
|
968
|
+
}
|
|
291
969
|
const effectCoordinator = new RunEffectCoordinator(runId, recordEvent);
|
|
292
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
|
+
};
|
|
293
1066
|
const dispatchLifecycle = async (lifecycle, payload) => {
|
|
294
1067
|
if (!lifecycleHost)
|
|
295
1068
|
return undefined;
|
|
296
1069
|
const result = await lifecycleHost.dispatch(lifecycle, payload);
|
|
297
1070
|
for (const receipt of result.receipts) {
|
|
298
|
-
|
|
1071
|
+
context.recordExtension(receipt);
|
|
299
1072
|
emit({
|
|
300
1073
|
type: "extension_lifecycle",
|
|
301
1074
|
extensionId: receipt.extensionId,
|
|
@@ -318,38 +1091,125 @@ export class CoreMindRuntime {
|
|
|
318
1091
|
const budget = new RunBudgetController(limits, emit);
|
|
319
1092
|
for (const event of collected)
|
|
320
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
|
+
}
|
|
321
1119
|
const checkpointManager = new CheckpointManager({
|
|
322
1120
|
cwd: this.options.cwd ?? process.cwd(),
|
|
323
1121
|
rootDir: path.join(this.options.configDir, ".coremind", "checkpoints"),
|
|
324
1122
|
runId: trace.runId,
|
|
325
1123
|
});
|
|
326
1124
|
let checkpointFailure;
|
|
327
|
-
|
|
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];
|
|
328
1131
|
const checkpointByCallId = new Map();
|
|
329
|
-
const
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
}
|
|
1132
|
+
const contextLifecycleManager = new ContextLifecycleManager();
|
|
1133
|
+
const contextContracts = new Map();
|
|
1134
|
+
let contextFailure;
|
|
1135
|
+
const recordContextFailure = (failure, preservedMessages) => {
|
|
1136
|
+
contextFailure = failure;
|
|
1137
|
+
emit({
|
|
1138
|
+
type: "context_lifecycle_failed",
|
|
1139
|
+
code: failure.code,
|
|
1140
|
+
reason: failure.reason,
|
|
1141
|
+
pausable: failure.pausable,
|
|
1142
|
+
preservedMessages,
|
|
1143
|
+
providerCallBlocked: true,
|
|
1144
|
+
});
|
|
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
|
+
};
|
|
347
1203
|
const policy = new ToolPolicy({
|
|
348
1204
|
permissions: this.config.permissions,
|
|
1205
|
+
allowedPaths: this.options.childRunAuthority?.inheritedPolicy.permissions.paths,
|
|
349
1206
|
cwd: this.options.cwd ?? process.cwd(),
|
|
350
1207
|
runId: trace.runId,
|
|
351
1208
|
approve: this.options.approveTool,
|
|
352
1209
|
createApprovalId: randomUUID,
|
|
1210
|
+
delegation: {
|
|
1211
|
+
isAssistedPreapproved: (agent, target) => this.agentConfigs.get(agent)?.delegation?.targets[target]?.preapproved === true,
|
|
1212
|
+
},
|
|
353
1213
|
onApprovalRequired: (request) => emit({
|
|
354
1214
|
type: "approval_required",
|
|
355
1215
|
approvalId: request.approvalId,
|
|
@@ -357,171 +1217,697 @@ export class CoreMindRuntime {
|
|
|
357
1217
|
agent: request.agent,
|
|
358
1218
|
tool: request.tool,
|
|
359
1219
|
args: request.args,
|
|
1220
|
+
argumentsFingerprint: request.argumentsFingerprint,
|
|
1221
|
+
delegationInputFingerprint: request.delegationInputFingerprint,
|
|
360
1222
|
risk: request.risk,
|
|
361
1223
|
effect: request.effect,
|
|
1224
|
+
capability: request.capability,
|
|
362
1225
|
}),
|
|
363
1226
|
onApprovalResolved: (request, decision) => emit({
|
|
364
1227
|
type: "approval_resolved",
|
|
365
1228
|
approvalId: request.approvalId,
|
|
366
1229
|
runId: request.runId,
|
|
367
1230
|
decision,
|
|
1231
|
+
argumentsFingerprint: request.argumentsFingerprint,
|
|
1232
|
+
delegationInputFingerprint: request.delegationInputFingerprint,
|
|
368
1233
|
}),
|
|
369
1234
|
});
|
|
370
1235
|
const deniedAgents = new Set();
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
const blockedByBudget = budget.beforeToolCall();
|
|
391
|
-
if (blockedByBudget)
|
|
392
|
-
return blockedByBudget;
|
|
393
|
-
const decision = await policy.authorize(agentName, context.toolCall.name, context.args, this.toolEffectsByAgent.get(agentName)?.get(context.toolCall.name));
|
|
394
|
-
if (!decision.allowed) {
|
|
395
|
-
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;
|
|
396
1255
|
emit({
|
|
397
|
-
type: "
|
|
1256
|
+
type: "provider_request",
|
|
398
1257
|
agent: agentName,
|
|
399
|
-
|
|
400
|
-
|
|
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
|
+
}),
|
|
401
1268
|
});
|
|
402
|
-
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
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,
|
|
418
1294
|
agent: agentName,
|
|
419
|
-
|
|
420
|
-
|
|
1295
|
+
stepId,
|
|
1296
|
+
messageCount: messages.length,
|
|
421
1297
|
});
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
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,
|
|
430
1321
|
});
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
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
|
+
});
|
|
434
1355
|
emit({
|
|
435
|
-
type: "
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
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),
|
|
442
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;
|
|
443
1401
|
}
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
checkpointFailure =
|
|
447
|
-
error instanceof CoreMindError
|
|
1402
|
+
catch (error) {
|
|
1403
|
+
const failure = error instanceof ContextLifecycleError
|
|
448
1404
|
? error
|
|
449
|
-
: new
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
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,
|
|
486
1443
|
});
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
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
|
+
}
|
|
491
1716
|
try {
|
|
492
|
-
|
|
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
|
+
}
|
|
493
1753
|
}
|
|
494
1754
|
catch (error) {
|
|
495
1755
|
checkpointFailure =
|
|
496
1756
|
error instanceof CoreMindError
|
|
497
1757
|
? error
|
|
498
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);
|
|
499
1765
|
emit({ type: "error", message: checkpointFailure.message, fatal: true });
|
|
1766
|
+
await rollbackWorkspaceLease(lifecycleIdentity);
|
|
1767
|
+
return { block: true, reason: checkpointFailure.message };
|
|
500
1768
|
}
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
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
|
+
};
|
|
525
1911
|
});
|
|
526
1912
|
let outputs = new Map();
|
|
527
1913
|
let transcript = "";
|
|
@@ -529,7 +1915,18 @@ export class CoreMindRuntime {
|
|
|
529
1915
|
let loopSnapshot = resumePlan?.loopSnapshot;
|
|
530
1916
|
let activeLoopRunner;
|
|
531
1917
|
try {
|
|
532
|
-
({ outputs, transcript } = await this.runWithGuard(limits.runTimeoutMs, async () => {
|
|
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
|
+
}
|
|
533
1930
|
if (loop) {
|
|
534
1931
|
let retryCount = resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry" && entry.event.scope === "provider").length ?? 0;
|
|
535
1932
|
const runner = new LoopRunner({
|
|
@@ -603,35 +2000,148 @@ export class CoreMindRuntime {
|
|
|
603
2000
|
if (!agent) {
|
|
604
2001
|
throw new CoreMindError("unknown_agent", `默认 agent ${name} 不存在`);
|
|
605
2002
|
}
|
|
606
|
-
const messageCursor = agent.
|
|
2003
|
+
const messageCursor = agent.messages().length;
|
|
607
2004
|
await agent.prompt(effectiveInitialPrompt);
|
|
608
2005
|
await agent.waitForIdle();
|
|
609
|
-
const
|
|
2006
|
+
const messages = agent.messages();
|
|
2007
|
+
const agentError = extractAgentError(messages);
|
|
610
2008
|
if (agentError) {
|
|
611
|
-
throw
|
|
2009
|
+
throw normalizeExecutionError({
|
|
2010
|
+
role: "assistant",
|
|
2011
|
+
stopReason: "error",
|
|
2012
|
+
errorMessage: agentError,
|
|
2013
|
+
});
|
|
612
2014
|
}
|
|
613
|
-
transcript = extractText(
|
|
2015
|
+
transcript = extractText(messages.slice(messageCursor));
|
|
614
2016
|
return { outputs: new Map(), transcript };
|
|
615
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;
|
|
616
2027
|
if (checkpointFailure)
|
|
617
2028
|
throw checkpointFailure;
|
|
618
2029
|
budget.throwIfExceeded();
|
|
619
2030
|
}
|
|
620
2031
|
catch (error) {
|
|
621
|
-
terminalError =
|
|
2032
|
+
terminalError =
|
|
2033
|
+
checkpointFailure ??
|
|
2034
|
+
delegationDispositionFailure ??
|
|
2035
|
+
delegationPolicyFailure ??
|
|
2036
|
+
capabilityFailure ??
|
|
2037
|
+
selectedAdapterFailure() ??
|
|
2038
|
+
error;
|
|
622
2039
|
try {
|
|
623
2040
|
if (!checkpointFailure)
|
|
624
2041
|
budget.throwIfExceeded();
|
|
625
2042
|
}
|
|
626
2043
|
catch (budgetError) {
|
|
627
|
-
terminalError
|
|
2044
|
+
if (!(terminalError instanceof CoreMindError && terminalError.code === "unclassified_error")) {
|
|
2045
|
+
terminalError = budgetError;
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
// step_timeout / budget_exceeded 与 Abort 共用准入机制(规格 03 §1):
|
|
2049
|
+
// 终止确定后设置分界点,拦截其后的迟到终态事实
|
|
2050
|
+
const code = terminalError instanceof CoreMindError ? terminalError.code : undefined;
|
|
2051
|
+
if (!journal.isAborted() && (code === "step_timeout" || code === "budget_exceeded")) {
|
|
2052
|
+
journal.markAborted(knownTurnIdsFrom(collected));
|
|
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
|
+
}
|
|
628
2067
|
}
|
|
629
2068
|
}
|
|
630
2069
|
finally {
|
|
631
|
-
|
|
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;
|
|
2079
|
+
}
|
|
2080
|
+
// 静止等待(规格 03 §5):runWithGuard 收尾路径调用,等所有 agent 真正 idle、
|
|
2081
|
+
// pending 工具结束、journal 落盘队列清空;超时记录 quiescence_timeout 事件不改变终态
|
|
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;
|
|
632
2137
|
}
|
|
633
2138
|
let sessionFile;
|
|
634
|
-
|
|
2139
|
+
// D-4 方案 A:abort 后也写会话树(只写已确认部分,竞态赢家文本丢弃);
|
|
2140
|
+
// 审批拒绝等 paused(loop_paused)是可在用户处置后继续的暂停态,同样应落盘已确认部分,
|
|
2141
|
+
// 使持久事实可重建该 Run 的请求(规格 01 §2 请求重建契约的适用范围)
|
|
2142
|
+
const terminalCode = terminalError instanceof CoreMindError ? terminalError.code : undefined;
|
|
2143
|
+
context.setSessionPersistPaused(terminalCode === "loop_paused");
|
|
2144
|
+
if (terminalError === undefined || journal.isAborted() || context.shouldTrimRejectedTrail()) {
|
|
635
2145
|
try {
|
|
636
2146
|
sessionFile = await this.persistSession();
|
|
637
2147
|
}
|
|
@@ -640,13 +2150,33 @@ export class CoreMindRuntime {
|
|
|
640
2150
|
}
|
|
641
2151
|
}
|
|
642
2152
|
const allMessages = [...this.collectMessages().values()].flat();
|
|
643
|
-
|
|
2153
|
+
// transcript 回退(方案 A):仅 abort 未生效且存在终态错误时允许回捞;
|
|
2154
|
+
// abort 生效后以已确认事实为准,不回捞竞态赢家文本(规格 03 §3)
|
|
2155
|
+
if (terminalError !== undefined && transcript.length === 0 && !journal.isAborted()) {
|
|
644
2156
|
transcript = extractText(allMessages);
|
|
645
2157
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
2158
|
+
try {
|
|
2159
|
+
await journal.flush();
|
|
2160
|
+
}
|
|
2161
|
+
catch (error) {
|
|
2162
|
+
terminalError = durabilityFailure(error);
|
|
2163
|
+
}
|
|
2164
|
+
const metrics = analyzeRunMetrics(collected, allMessages, performance.now() - started, transcript.length, journal.rejectedAfterAbort());
|
|
2165
|
+
let outcome = new RunTerminalizer().terminalize(collected, terminalError);
|
|
2166
|
+
// 输入收据终态(规格 03 §4):succeeded → completed;abort/超时/预算/失败 → discarded
|
|
2167
|
+
// (未消费输入);paused(审批拒绝等)保持 claimed,resume 继续同一输入
|
|
2168
|
+
if (inputReceiptState !== undefined && inputReceiptState !== "completed") {
|
|
2169
|
+
if (outcome.status === "succeeded") {
|
|
2170
|
+
inputReceiptState = "completed";
|
|
2171
|
+
emitInputEvent(completeInput({ inputId: inputId }));
|
|
2172
|
+
}
|
|
2173
|
+
else if (outcome.status !== "paused") {
|
|
2174
|
+
inputReceiptState = "discarded";
|
|
2175
|
+
emitInputEvent(discardInput({ inputId: inputId }));
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
let evaluation = createEvaluationReport(this.config.quality, metrics);
|
|
2179
|
+
let releaseReadiness = assessReleaseReadiness(outcome, evaluation);
|
|
650
2180
|
const irreversibleTools = [
|
|
651
2181
|
...new Set(checkpointManager.records
|
|
652
2182
|
.filter((checkpoint) => !checkpoint.reversible)
|
|
@@ -694,60 +2224,119 @@ export class CoreMindRuntime {
|
|
|
694
2224
|
evaluation,
|
|
695
2225
|
releaseReadiness,
|
|
696
2226
|
checkpointCount: checkpointManager.records.length,
|
|
697
|
-
artifactCount:
|
|
2227
|
+
artifactCount: context.artifactRecords().length,
|
|
698
2228
|
});
|
|
699
|
-
|
|
700
|
-
|
|
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,
|
|
701
2281
|
operation: operation.snapshot(),
|
|
702
2282
|
outcome,
|
|
703
2283
|
metrics,
|
|
704
2284
|
evaluation,
|
|
705
2285
|
releaseReadiness,
|
|
706
|
-
|
|
2286
|
+
trace: trace.entries,
|
|
2287
|
+
checkpoints: checkpointManager.records,
|
|
2288
|
+
artifacts: context.artifactRecords(),
|
|
2289
|
+
extensions: context.extensions(),
|
|
707
2290
|
});
|
|
2291
|
+
if (!snapshot) {
|
|
2292
|
+
throw new CoreMindError("run_state_corrupt", "终态 Fact 已持久化,但无法重建 RunSnapshot");
|
|
708
2293
|
}
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
operation: operation.snapshot(),
|
|
2294
|
+
let observability = persistedProjection?.observability ??
|
|
2295
|
+
fallbackObservability({
|
|
712
2296
|
outcome,
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
releaseReadiness,
|
|
2297
|
+
operation: operation.snapshot(),
|
|
2298
|
+
telemetry: telemetryConfiguration,
|
|
716
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
|
+
};
|
|
717
2314
|
}
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
operation: operation.snapshot(),
|
|
722
|
-
outcome,
|
|
723
|
-
metrics,
|
|
724
|
-
evaluation,
|
|
725
|
-
releaseReadiness,
|
|
726
|
-
trace: trace.entries,
|
|
727
|
-
checkpoints: checkpointManager.records,
|
|
728
|
-
artifacts,
|
|
729
|
-
extensions: extensionReceipts,
|
|
730
|
-
});
|
|
2315
|
+
const childRuns = persistedRecords
|
|
2316
|
+
? (await ProjectionEngine.projectTree(runStore, runId)).childRuns
|
|
2317
|
+
: undefined;
|
|
731
2318
|
return {
|
|
732
2319
|
runId: trace.runId,
|
|
733
|
-
operation: operation
|
|
734
|
-
outcome,
|
|
735
|
-
metrics,
|
|
736
|
-
evaluation,
|
|
737
|
-
releaseReadiness,
|
|
738
|
-
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,
|
|
739
2326
|
runStateFile: runStore.pathFor?.(runId),
|
|
740
|
-
checkpoints:
|
|
2327
|
+
checkpoints: snapshot.checkpoints,
|
|
741
2328
|
outputs,
|
|
742
2329
|
messages: this.collectMessages(),
|
|
743
2330
|
transcript,
|
|
744
2331
|
sessionFile,
|
|
745
|
-
artifacts,
|
|
746
|
-
extensions:
|
|
2332
|
+
artifacts: snapshot.artifacts,
|
|
2333
|
+
extensions: snapshot.extensions,
|
|
747
2334
|
snapshot,
|
|
2335
|
+
observability,
|
|
2336
|
+
...(childRuns ? { childRuns } : {}),
|
|
748
2337
|
};
|
|
749
2338
|
}
|
|
750
|
-
async runWithGuard(timeoutMs, operation, onGuardError) {
|
|
2339
|
+
async runWithGuard(timeoutMs, journal, knownTurnIds, operation, onGuardError) {
|
|
751
2340
|
const signal = this.options.signal;
|
|
752
2341
|
if (signal?.aborted)
|
|
753
2342
|
throw new CoreMindError("aborted", "执行已中止");
|
|
@@ -761,12 +2350,14 @@ export class CoreMindRuntime {
|
|
|
761
2350
|
if (guardTriggered)
|
|
762
2351
|
return;
|
|
763
2352
|
guardTriggered = true;
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
2353
|
+
// Abort 生效点(规格 03 §1):设置事件准入分界点,此后迟到终态事实不再写入;
|
|
2354
|
+
// 分界前已启动的活动集合用于 R3 判定(分界前启动的工具 receipt 放行)。
|
|
2355
|
+
// interrupt 先触发(loop 内部取消),随后同步 abortAll 尽早终止在飞活动,
|
|
2356
|
+
// 让静止判定尽快满足(Cancel → Quiescent)
|
|
2357
|
+
journal.markAborted(knownTurnIds());
|
|
2358
|
+
void Promise.resolve(onGuardError?.(error)).catch(() => undefined);
|
|
2359
|
+
this.abortAll();
|
|
2360
|
+
void Promise.resolve().then(() => reject(error));
|
|
770
2361
|
};
|
|
771
2362
|
const onAbort = () => {
|
|
772
2363
|
if (rejectAbort)
|
|
@@ -795,7 +2386,7 @@ export class CoreMindRuntime {
|
|
|
795
2386
|
if (!agent) {
|
|
796
2387
|
throw new CoreMindError("unknown_agent", `Loop 引用了未定义的 agent:${request.agent}(${request.stepId})`);
|
|
797
2388
|
}
|
|
798
|
-
const messageCursor = agent.
|
|
2389
|
+
const messageCursor = agent.messages().length;
|
|
799
2390
|
let timer;
|
|
800
2391
|
const operation = (async () => {
|
|
801
2392
|
await agent.prompt(request.input);
|
|
@@ -829,28 +2420,83 @@ export class CoreMindRuntime {
|
|
|
829
2420
|
if (stepEvents.some((event) => event.type === "policy_denied")) {
|
|
830
2421
|
throw new CoreMindError("loop_paused", `步骤 ${request.stepId} 的工具请求未获批准`);
|
|
831
2422
|
}
|
|
832
|
-
const
|
|
833
|
-
|
|
834
|
-
.find((message) => message.role === "assistant");
|
|
2423
|
+
const messages = agent.messages();
|
|
2424
|
+
const lastAssistant = [...messages].reverse().find((message) => message.role === "assistant");
|
|
835
2425
|
if (lastAssistant?.stopReason === "aborted") {
|
|
836
2426
|
throw new CoreMindError("aborted", `步骤 ${request.stepId} 已中止`);
|
|
837
2427
|
}
|
|
838
2428
|
if (lastAssistant?.stopReason === "error") {
|
|
839
2429
|
const agentError = lastAssistant.errorMessage ?? "模型执行失败,但未提供错误详情";
|
|
840
|
-
|
|
841
|
-
throw new CoreMindError(code, `步骤 ${request.stepId} 的 Agent 执行失败:${agentError}`);
|
|
2430
|
+
throw normalizeExecutionError({ ...lastAssistant, errorMessage: agentError });
|
|
842
2431
|
}
|
|
843
|
-
return extractText(
|
|
2432
|
+
return extractText(messages.slice(messageCursor));
|
|
844
2433
|
}
|
|
845
2434
|
abortAll() {
|
|
846
|
-
|
|
847
|
-
|
|
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
|
+
});
|
|
848
2478
|
}
|
|
849
2479
|
collectMessages() {
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
2480
|
+
return runContextFor(this).collectMessages();
|
|
2481
|
+
}
|
|
2482
|
+
/**
|
|
2483
|
+
* 等待静止(规格 03 §5):所有 agent 已 idle ∧ 无 pending 工具结果 ∧
|
|
2484
|
+
* journal 无 pending flush(append 队列空且已落盘)。
|
|
2485
|
+
* 超时上限与 runTimeout 解耦(独立 quiescenceTimeout,默认 5s):
|
|
2486
|
+
* 超时记录 quiescence_timeout 事件但不改变终态。返回是否达到静止。
|
|
2487
|
+
*/
|
|
2488
|
+
async waitForQuiescence(timeoutMs = DEFAULT_QUIESCENCE_TIMEOUT_MS) {
|
|
2489
|
+
const context = runContextFor(this);
|
|
2490
|
+
const deadline = performance.now() + timeoutMs;
|
|
2491
|
+
for (;;) {
|
|
2492
|
+
if (context.isExecutionQuiescent())
|
|
2493
|
+
return true;
|
|
2494
|
+
if (performance.now() >= deadline) {
|
|
2495
|
+
this.options.events?.({ type: "quiescence_timeout", timeoutMs });
|
|
2496
|
+
return false;
|
|
2497
|
+
}
|
|
2498
|
+
await new Promise((resolve) => setTimeout(resolve, QUIESCENCE_POLL_INTERVAL_MS));
|
|
2499
|
+
}
|
|
854
2500
|
}
|
|
855
2501
|
/** 会话配置开启时,把主 agent 本轮新增消息追加落盘(返回会话文件路径) */
|
|
856
2502
|
async persistSession() {
|
|
@@ -858,27 +2504,312 @@ export class CoreMindRuntime {
|
|
|
858
2504
|
const session = this.config.session;
|
|
859
2505
|
if (!sessionId || !session?.enabled)
|
|
860
2506
|
return undefined;
|
|
861
|
-
const
|
|
2507
|
+
const context = runContextFor(this);
|
|
2508
|
+
const main = context.agent(this.mainAgentName);
|
|
862
2509
|
if (!main)
|
|
863
2510
|
return undefined;
|
|
864
|
-
const cm =
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
2511
|
+
const cm = context.sessionHandle() ??
|
|
2512
|
+
(await CoreMindSession.open({
|
|
2513
|
+
dir: sessionDir(this.config, this.options.configDir),
|
|
2514
|
+
sessionId,
|
|
2515
|
+
cwd: this.options.cwd ?? process.cwd(),
|
|
2516
|
+
}));
|
|
2517
|
+
// 只追加本轮新增:恢复历史已落盘;请求级压缩的摘要与保留区已由压缩条目代表
|
|
2518
|
+
let messages = main.messages().slice(context.compactedPrefixEnd() ?? this.resumedContextLength);
|
|
2519
|
+
if (context.currentJournal()?.isAborted()) {
|
|
2520
|
+
// D-4 方案 A:abort 后只写已确认部分——去掉尾部未正常终止的 assistant 消息(竞态赢家文本)
|
|
2521
|
+
messages = trimUnconfirmedTail(messages);
|
|
2522
|
+
}
|
|
2523
|
+
else if (context.shouldTrimRejectedTrail()) {
|
|
2524
|
+
// 审批拒绝等 paused:只落已发送部分——去掉尾部未发送的工具调用产物(toolResult + toolUse)
|
|
2525
|
+
messages = trimRejectedTrail(messages);
|
|
2526
|
+
}
|
|
2527
|
+
await cm.appendMessages(messages);
|
|
871
2528
|
// P2b:配置 session.compact 时,上下文超预算自动压缩(LLM 摘要,消耗 token)
|
|
872
2529
|
if (session.compact) {
|
|
873
|
-
|
|
2530
|
+
const mainModel = this.agentModels.get(this.mainAgentName) ?? this.providerRuntime.model;
|
|
2531
|
+
await cm.maybeCompact(this.providerRuntime.models, mainModel, mainModel.contextWindow);
|
|
874
2532
|
}
|
|
875
2533
|
return cm.filePath;
|
|
876
2534
|
}
|
|
877
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
|
+
}
|
|
878
2553
|
/** 便捷入口:加载配置 → 构建运行时 */
|
|
879
2554
|
export async function buildAgentFromConfig(options) {
|
|
880
2555
|
return CoreMindRuntime.create(options);
|
|
881
2556
|
}
|
|
2557
|
+
/** 静止等待默认超时(规格 03 §5:默认 5s,与 runTimeout 解耦) */
|
|
2558
|
+
const DEFAULT_QUIESCENCE_TIMEOUT_MS = 5_000;
|
|
2559
|
+
/** 静止轮询间隔:兼顾及时性(Cancel → Quiescent p95 < 250ms)与避免忙等 */
|
|
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
|
+
}
|
|
2726
|
+
/**
|
|
2727
|
+
* 静止判定(规格 03 §5):quiescent ⇔ 所有 agent 已 idle ∧ 无 pending 工具结果 ∧
|
|
2728
|
+
* journal 无 pending flush。模块级函数而非 private 方法:避免进入 untrimmed d.ts
|
|
2729
|
+
* (#39 教训:类私有成员也会进 d.ts,冻结基线逐字哈希会失败)。
|
|
2730
|
+
*/
|
|
2731
|
+
function durabilityFailure(error) {
|
|
2732
|
+
return error instanceof CoreMindError
|
|
2733
|
+
? error
|
|
2734
|
+
: new CoreMindError("durability_barrier_failed", error instanceof Error ? error.message : String(error));
|
|
2735
|
+
}
|
|
2736
|
+
/**
|
|
2737
|
+
* 从既有事件序列提取已登记的输入 ID(resume 时沿用原 run 的收据,
|
|
2738
|
+
* 使收据链跨 run 连续——规格 03 §4:输入收据参与恢复合法性判定)。
|
|
2739
|
+
*/
|
|
2740
|
+
function resumedInputId(events) {
|
|
2741
|
+
for (const event of events) {
|
|
2742
|
+
if (event.type === "input_receipt")
|
|
2743
|
+
return event.inputId;
|
|
2744
|
+
}
|
|
2745
|
+
return undefined;
|
|
2746
|
+
}
|
|
2747
|
+
function toolCallIdentity(agent, stepId, callId) {
|
|
2748
|
+
return { agent, callId, ...(stepId ? { stepId } : {}) };
|
|
2749
|
+
}
|
|
2750
|
+
/** 分界前已启动的活动集合(R3 判定用):从已收集事件的 turnId 提取 */
|
|
2751
|
+
function knownTurnIdsFrom(collected) {
|
|
2752
|
+
return new Set(collected.flatMap((event) => {
|
|
2753
|
+
const turnId = event.turnId;
|
|
2754
|
+
return turnId ? [turnId] : [];
|
|
2755
|
+
}));
|
|
2756
|
+
}
|
|
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
|
+
}
|
|
2784
|
+
/** D-4 方案 A:去掉尾部未正常终止的 assistant 消息(abort 竞态赢家文本不落会话树) */
|
|
2785
|
+
function trimUnconfirmedTail(messages) {
|
|
2786
|
+
let end = messages.length;
|
|
2787
|
+
while (end > 0) {
|
|
2788
|
+
const last = messages[end - 1];
|
|
2789
|
+
if (last.role === "assistant" && last.stopReason !== "stop")
|
|
2790
|
+
end -= 1;
|
|
2791
|
+
else
|
|
2792
|
+
break;
|
|
2793
|
+
}
|
|
2794
|
+
return messages.slice(0, end);
|
|
2795
|
+
}
|
|
2796
|
+
/** 审批拒绝等 paused:去掉尾部未发送的工具调用产物(toolResult 及配对的 assistant toolUse) */
|
|
2797
|
+
function trimRejectedTrail(messages) {
|
|
2798
|
+
let end = messages.length;
|
|
2799
|
+
while (end > 0) {
|
|
2800
|
+
const last = messages[end - 1];
|
|
2801
|
+
if (last?.role === "toolResult") {
|
|
2802
|
+
end -= 1;
|
|
2803
|
+
continue;
|
|
2804
|
+
}
|
|
2805
|
+
if (last?.role === "assistant" && last.stopReason === "toolUse") {
|
|
2806
|
+
end -= 1;
|
|
2807
|
+
continue;
|
|
2808
|
+
}
|
|
2809
|
+
break;
|
|
2810
|
+
}
|
|
2811
|
+
return messages.slice(0, end);
|
|
2812
|
+
}
|
|
882
2813
|
function sessionDir(config, configDir) {
|
|
883
2814
|
const configured = config.session?.dir;
|
|
884
2815
|
return configured ? path.resolve(configDir, configured) : path.join(configDir, "sessions");
|
|
@@ -888,10 +2819,33 @@ function lastOutputText(outputs) {
|
|
|
888
2819
|
const last = values[values.length - 1];
|
|
889
2820
|
return last ? last.text : "";
|
|
890
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
|
+
}
|
|
891
2848
|
function firstKey(record) {
|
|
892
2849
|
return Object.keys(record)[0];
|
|
893
2850
|
}
|
|
894
|
-
function effectIdempotencyKey(runId, stepId, callId) {
|
|
895
|
-
return stepId ? `${runId}:${stepId}:${callId}` : `${runId}:${callId}`;
|
|
896
|
-
}
|
|
897
2851
|
//# sourceMappingURL=runtime.js.map
|