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