coremind-runtime 0.3.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/README.md +49 -1
  2. package/dist/active-run-binding.d.ts +24 -0
  3. package/dist/active-run-binding.d.ts.map +1 -0
  4. package/dist/active-run-binding.js +22 -0
  5. package/dist/active-run-binding.js.map +1 -0
  6. package/dist/agent-driver.d.ts +139 -0
  7. package/dist/agent-driver.d.ts.map +1 -0
  8. package/dist/agent-driver.js +135 -0
  9. package/dist/agent-driver.js.map +1 -0
  10. package/dist/agent-factory.d.ts +10 -10
  11. package/dist/agent-factory.d.ts.map +1 -1
  12. package/dist/agent-factory.js +179 -14
  13. package/dist/agent-factory.js.map +1 -1
  14. package/dist/budget.d.ts +11 -1
  15. package/dist/budget.d.ts.map +1 -1
  16. package/dist/budget.js +59 -16
  17. package/dist/budget.js.map +1 -1
  18. package/dist/canonical-json.d.ts +3 -0
  19. package/dist/canonical-json.d.ts.map +1 -0
  20. package/dist/canonical-json.js +28 -0
  21. package/dist/canonical-json.js.map +1 -0
  22. package/dist/chat-session.d.ts +3 -0
  23. package/dist/chat-session.d.ts.map +1 -1
  24. package/dist/chat-session.js +5 -0
  25. package/dist/chat-session.js.map +1 -1
  26. package/dist/checkpoint.d.ts +25 -8
  27. package/dist/checkpoint.d.ts.map +1 -1
  28. package/dist/checkpoint.js +135 -52
  29. package/dist/checkpoint.js.map +1 -1
  30. package/dist/child-run.d.ts +344 -0
  31. package/dist/child-run.d.ts.map +1 -0
  32. package/dist/child-run.js +1373 -0
  33. package/dist/child-run.js.map +1 -0
  34. package/dist/child-runtime-adapter.d.ts +18 -0
  35. package/dist/child-runtime-adapter.d.ts.map +1 -0
  36. package/dist/child-runtime-adapter.js +309 -0
  37. package/dist/child-runtime-adapter.js.map +1 -0
  38. package/dist/compaction-projection.d.ts +45 -0
  39. package/dist/compaction-projection.d.ts.map +1 -0
  40. package/dist/compaction-projection.js +133 -0
  41. package/dist/compaction-projection.js.map +1 -0
  42. package/dist/context-lifecycle.d.ts +182 -0
  43. package/dist/context-lifecycle.d.ts.map +1 -0
  44. package/dist/context-lifecycle.js +455 -0
  45. package/dist/context-lifecycle.js.map +1 -0
  46. package/dist/context-task-state.d.ts +23 -0
  47. package/dist/context-task-state.d.ts.map +1 -0
  48. package/dist/context-task-state.js +183 -0
  49. package/dist/context-task-state.js.map +1 -0
  50. package/dist/context.d.ts +9 -1
  51. package/dist/context.d.ts.map +1 -1
  52. package/dist/context.js +24 -1
  53. package/dist/context.js.map +1 -1
  54. package/dist/control-inbox.d.ts +106 -0
  55. package/dist/control-inbox.d.ts.map +1 -0
  56. package/dist/control-inbox.js +291 -0
  57. package/dist/control-inbox.js.map +1 -0
  58. package/dist/delegated-context.d.ts +29 -0
  59. package/dist/delegated-context.d.ts.map +1 -0
  60. package/dist/delegated-context.js +76 -0
  61. package/dist/delegated-context.js.map +1 -0
  62. package/dist/delegation-tool.d.ts +30 -0
  63. package/dist/delegation-tool.d.ts.map +1 -0
  64. package/dist/delegation-tool.js +232 -0
  65. package/dist/delegation-tool.js.map +1 -0
  66. package/dist/effect-receipt-binding.d.ts +34 -0
  67. package/dist/effect-receipt-binding.d.ts.map +1 -0
  68. package/dist/effect-receipt-binding.js +125 -0
  69. package/dist/effect-receipt-binding.js.map +1 -0
  70. package/dist/errors.d.ts +18 -4
  71. package/dist/errors.d.ts.map +1 -1
  72. package/dist/errors.js +36 -2
  73. package/dist/errors.js.map +1 -1
  74. package/dist/evaluation.d.ts.map +1 -1
  75. package/dist/evaluation.js +12 -5
  76. package/dist/evaluation.js.map +1 -1
  77. package/dist/events.d.ts +131 -3
  78. package/dist/events.d.ts.map +1 -1
  79. package/dist/events.js +44 -0
  80. package/dist/events.js.map +1 -1
  81. package/dist/execution-error.d.ts +14 -0
  82. package/dist/execution-error.d.ts.map +1 -0
  83. package/dist/execution-error.js +129 -0
  84. package/dist/execution-error.js.map +1 -0
  85. package/dist/execution-security.d.ts +11 -0
  86. package/dist/execution-security.d.ts.map +1 -0
  87. package/dist/execution-security.js +40 -0
  88. package/dist/execution-security.js.map +1 -0
  89. package/dist/fact-ledger.d.ts +60 -0
  90. package/dist/fact-ledger.d.ts.map +1 -0
  91. package/dist/fact-ledger.js +167 -0
  92. package/dist/fact-ledger.js.map +1 -0
  93. package/dist/ids.d.ts +51 -0
  94. package/dist/ids.d.ts.map +1 -0
  95. package/dist/ids.js +27 -0
  96. package/dist/ids.js.map +1 -0
  97. package/dist/index.d.ts +16 -5
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +12 -2
  100. package/dist/index.js.map +1 -1
  101. package/dist/input-receipt.d.ts +59 -0
  102. package/dist/input-receipt.d.ts.map +1 -0
  103. package/dist/input-receipt.js +102 -0
  104. package/dist/input-receipt.js.map +1 -0
  105. package/dist/internal.d.ts +11 -0
  106. package/dist/internal.d.ts.map +1 -0
  107. package/dist/internal.js +11 -0
  108. package/dist/internal.js.map +1 -0
  109. package/dist/invariant-checker.d.ts +28 -0
  110. package/dist/invariant-checker.d.ts.map +1 -0
  111. package/dist/invariant-checker.js +441 -0
  112. package/dist/invariant-checker.js.map +1 -0
  113. package/dist/loop-runner.d.ts.map +1 -1
  114. package/dist/loop-runner.js +37 -24
  115. package/dist/loop-runner.js.map +1 -1
  116. package/dist/observability.d.ts +211 -0
  117. package/dist/observability.d.ts.map +1 -0
  118. package/dist/observability.js +814 -0
  119. package/dist/observability.js.map +1 -0
  120. package/dist/orchestrator.d.ts +2 -2
  121. package/dist/orchestrator.d.ts.map +1 -1
  122. package/dist/orchestrator.js +12 -6
  123. package/dist/orchestrator.js.map +1 -1
  124. package/dist/project-check.d.ts +3 -0
  125. package/dist/project-check.d.ts.map +1 -1
  126. package/dist/project-check.js +21 -5
  127. package/dist/project-check.js.map +1 -1
  128. package/dist/projection.d.ts +131 -0
  129. package/dist/projection.d.ts.map +1 -0
  130. package/dist/projection.js +972 -0
  131. package/dist/projection.js.map +1 -0
  132. package/dist/provider.d.ts +23 -1
  133. package/dist/provider.d.ts.map +1 -1
  134. package/dist/provider.js +134 -23
  135. package/dist/provider.js.map +1 -1
  136. package/dist/public-tool.d.ts +3 -0
  137. package/dist/public-tool.d.ts.map +1 -1
  138. package/dist/public-tool.js +28 -3
  139. package/dist/public-tool.js.map +1 -1
  140. package/dist/race-seeds.d.ts +43 -0
  141. package/dist/race-seeds.d.ts.map +1 -0
  142. package/dist/race-seeds.js +53 -0
  143. package/dist/race-seeds.js.map +1 -0
  144. package/dist/rebuild-request.d.ts +30 -0
  145. package/dist/rebuild-request.d.ts.map +1 -0
  146. package/dist/rebuild-request.js +37 -0
  147. package/dist/rebuild-request.js.map +1 -0
  148. package/dist/replay-kit.d.ts +41 -0
  149. package/dist/replay-kit.d.ts.map +1 -0
  150. package/dist/replay-kit.js +96 -0
  151. package/dist/replay-kit.js.map +1 -0
  152. package/dist/result.d.ts +20 -2
  153. package/dist/result.d.ts.map +1 -1
  154. package/dist/result.js +18 -1
  155. package/dist/result.js.map +1 -1
  156. package/dist/retry-policy.d.ts.map +1 -1
  157. package/dist/retry-policy.js +21 -85
  158. package/dist/retry-policy.js.map +1 -1
  159. package/dist/run-context.d.ts +77 -0
  160. package/dist/run-context.d.ts.map +1 -0
  161. package/dist/run-context.js +159 -0
  162. package/dist/run-context.js.map +1 -0
  163. package/dist/run-effect-coordinator.d.ts +2 -1
  164. package/dist/run-effect-coordinator.d.ts.map +1 -1
  165. package/dist/run-effect-coordinator.js +6 -5
  166. package/dist/run-effect-coordinator.js.map +1 -1
  167. package/dist/run-kernel.d.ts +14 -0
  168. package/dist/run-kernel.d.ts.map +1 -0
  169. package/dist/run-kernel.js +34 -0
  170. package/dist/run-kernel.js.map +1 -0
  171. package/dist/run-state.d.ts +107 -4
  172. package/dist/run-state.d.ts.map +1 -1
  173. package/dist/run-state.js +627 -77
  174. package/dist/run-state.js.map +1 -1
  175. package/dist/run-terminalizer.d.ts.map +1 -1
  176. package/dist/run-terminalizer.js +6 -17
  177. package/dist/run-terminalizer.js.map +1 -1
  178. package/dist/runtime-instance-authority.d.ts +3 -0
  179. package/dist/runtime-instance-authority.d.ts.map +1 -0
  180. package/dist/runtime-instance-authority.js +8 -0
  181. package/dist/runtime-instance-authority.js.map +1 -0
  182. package/dist/runtime.d.ts +104 -2
  183. package/dist/runtime.d.ts.map +1 -1
  184. package/dist/runtime.js +2242 -288
  185. package/dist/runtime.js.map +1 -1
  186. package/dist/session.d.ts +19 -3
  187. package/dist/session.d.ts.map +1 -1
  188. package/dist/session.js +43 -2
  189. package/dist/session.js.map +1 -1
  190. package/dist/snapshot.d.ts.map +1 -1
  191. package/dist/snapshot.js +3 -20
  192. package/dist/snapshot.js.map +1 -1
  193. package/dist/tool-call-lifecycle.d.ts +89 -0
  194. package/dist/tool-call-lifecycle.d.ts.map +1 -0
  195. package/dist/tool-call-lifecycle.js +379 -0
  196. package/dist/tool-call-lifecycle.js.map +1 -0
  197. package/dist/tool-capability-identity.d.ts +3 -0
  198. package/dist/tool-capability-identity.d.ts.map +1 -0
  199. package/dist/tool-capability-identity.js +5 -0
  200. package/dist/tool-capability-identity.js.map +1 -0
  201. package/dist/tool-capability-projection.d.ts +17 -0
  202. package/dist/tool-capability-projection.d.ts.map +1 -0
  203. package/dist/tool-capability-projection.js +99 -0
  204. package/dist/tool-capability-projection.js.map +1 -0
  205. package/dist/tool-effect-selectors.d.ts +3 -0
  206. package/dist/tool-effect-selectors.d.ts.map +1 -0
  207. package/dist/tool-effect-selectors.js +18 -0
  208. package/dist/tool-effect-selectors.js.map +1 -0
  209. package/dist/tool-policy.d.ts +13 -2
  210. package/dist/tool-policy.d.ts.map +1 -1
  211. package/dist/tool-policy.js +149 -44
  212. package/dist/tool-policy.js.map +1 -1
  213. package/dist/trace.d.ts +1 -0
  214. package/dist/trace.d.ts.map +1 -1
  215. package/dist/trace.js +10 -3
  216. package/dist/trace.js.map +1 -1
  217. package/dist/turn-tracker.d.ts +14 -0
  218. package/dist/turn-tracker.d.ts.map +1 -0
  219. package/dist/turn-tracker.js +50 -0
  220. package/dist/turn-tracker.js.map +1 -0
  221. package/dist/workspace-lease.d.ts +81 -0
  222. package/dist/workspace-lease.d.ts.map +1 -0
  223. package/dist/workspace-lease.js +300 -0
  224. package/dist/workspace-lease.js.map +1 -0
  225. package/package.json +11 -5
@@ -0,0 +1,1373 @@
1
+ import { createHash } from "node:crypto";
2
+ import { tightenExecutionEnvironmentRequirement } from "coremind-tools/internal";
3
+ import { canonicalJson } from "./canonical-json.js";
4
+ import { isResolvedDelegatedContextReference, } from "./delegated-context.js";
5
+ import { CoreMindError, terminalStatusForCode } from "./errors.js";
6
+ import { normalizeExecutionError } from "./execution-error.js";
7
+ import { redactSensitiveText } from "./trace.js";
8
+ export const CHILD_RUN_LIMIT_DEFAULTS = Object.freeze({
9
+ maxDepth: 3,
10
+ maxActiveChildren: 4,
11
+ maxDescendants: 32,
12
+ });
13
+ const DEFAULT_BUDGET_SCOPE = "__default__";
14
+ /**
15
+ * Child Run 深模块:把幂等身份、持久生命周期和结构化 join 隐藏在一个委派接口后。
16
+ * 实际子运行由 Adapter 执行;父 Run 只保存关系与结构化结果,不复制子级消息或 Receipt。
17
+ */
18
+ export class ChildRunCoordinator {
19
+ options;
20
+ delegations = new Map();
21
+ now;
22
+ remainingBudgets = new Map();
23
+ hierarchyLimits = new Map();
24
+ parentPolicy;
25
+ delegationTransitionLocked = false;
26
+ delegationTransitionWaiters = [];
27
+ terminalSealed = false;
28
+ constructor(options) {
29
+ this.options = options;
30
+ this.now = options.now ?? (() => new Date().toISOString());
31
+ this.parentPolicy = normalizeParentPolicy(options.parentPolicy);
32
+ const configuredPools = Object.entries(options.delegationBudgetPools ?? {});
33
+ if (configuredPools.length === 0) {
34
+ this.remainingBudgets.set(DEFAULT_BUDGET_SCOPE, structuredClone(this.parentPolicy.budget));
35
+ this.hierarchyLimits.set(DEFAULT_BUDGET_SCOPE, hierarchyFromPolicy(this.parentPolicy));
36
+ }
37
+ else {
38
+ for (const [scope, budget] of configuredPools) {
39
+ if (scope.length === 0)
40
+ throw policyEscalation("Delegation Budget 作用域不能为空");
41
+ assertDelegationBudgetPool(this.parentPolicy, budget);
42
+ this.remainingBudgets.set(scope, structuredClone(budget));
43
+ this.hierarchyLimits.set(scope, normalizeScopeHierarchy(this.parentPolicy, budget, options.delegationHierarchyLimits?.[scope]));
44
+ }
45
+ const unknownHierarchyScope = Object.keys(options.delegationHierarchyLimits ?? {}).find((scope) => !this.remainingBudgets.has(scope));
46
+ if (unknownHierarchyScope) {
47
+ throw policyEscalation(`Delegation 层级作用域 ${unknownHierarchyScope} 没有匹配的预算池`);
48
+ }
49
+ }
50
+ }
51
+ static async open(options) {
52
+ if (options.parentJournal.runId !== options.parentRunId) {
53
+ throw new CoreMindError("child_run_parent_mismatch", "Child Run Coordinator 的父 Run 身份不一致");
54
+ }
55
+ const coordinator = new ChildRunCoordinator(options);
56
+ coordinator.restore(await options.runStore.read(options.parentRunId));
57
+ await coordinator.auditRestoredOrphans();
58
+ return coordinator;
59
+ }
60
+ async delegate(request) {
61
+ const requestSnapshot = deepFreeze(structuredClone(request));
62
+ const existing = this.delegations.get(requestSnapshot.delegationId);
63
+ if (existing) {
64
+ if (existing.inputFingerprint !== childRunInputFingerprint(requestSnapshot)) {
65
+ throw new CoreMindError("delegation_conflict", `DelegationId ${requestSnapshot.delegationId} 已绑定不同输入`);
66
+ }
67
+ return this.handleFor(existing);
68
+ }
69
+ return this.withDelegationTransition(async () => {
70
+ if (this.terminalSealed) {
71
+ throw new CoreMindError("child_run_unavailable", "父 Run 已进入终态封口,不能再创建 Child Run");
72
+ }
73
+ return this.delegateWithinTransition(requestSnapshot);
74
+ });
75
+ }
76
+ async delegateWithinTransition(requestSnapshot) {
77
+ const inputFingerprint = childRunInputFingerprint(requestSnapshot);
78
+ const existing = this.delegations.get(requestSnapshot.delegationId);
79
+ if (existing) {
80
+ if (existing.inputFingerprint !== inputFingerprint) {
81
+ throw new CoreMindError("delegation_conflict", `DelegationId ${requestSnapshot.delegationId} 已绑定不同输入`);
82
+ }
83
+ return this.handleFor(existing);
84
+ }
85
+ const scope = this.scopeFor(requestSnapshot.budgetScope);
86
+ this.assertActiveChildLimit(scope.key, scope.hierarchy.maxActiveChildren);
87
+ const scopedParentPolicy = { ...this.parentPolicy, ...scope.hierarchy };
88
+ assertChildRunPolicyIsNarrower(scopedParentPolicy, scope.remainingBudget, requestSnapshot);
89
+ const predecessor = this.assertRedelegationRequest(requestSnapshot);
90
+ const childPolicy = effectiveChildPolicy(scopedParentPolicy, requestSnapshot);
91
+ const releaseParentBudget = this.options.reserveParentBudget?.(requestSnapshot.allocation);
92
+ const childRunId = this.options.createChildRunId();
93
+ const state = {
94
+ childRunId,
95
+ delegationId: requestSnapshot.delegationId,
96
+ budgetScope: requestSnapshot.budgetScope,
97
+ inputFingerprint,
98
+ predecessorDelegationId: requestSnapshot.predecessorDelegationId,
99
+ status: "recorded",
100
+ abortController: new AbortController(),
101
+ releaseParentBudget,
102
+ };
103
+ this.delegations.set(requestSnapshot.delegationId, state);
104
+ if (predecessor)
105
+ predecessor.successorDelegationId = requestSnapshot.delegationId;
106
+ reserveBudget(scope.remainingBudget, requestSnapshot.allocation);
107
+ let delegationRecorded = false;
108
+ state.initialization = (async () => {
109
+ await this.options.parentJournal.appendFact("delegation", {
110
+ type: "delegation_recorded",
111
+ parentRunId: this.options.parentRunId,
112
+ childRunId,
113
+ delegationId: requestSnapshot.delegationId,
114
+ predecessorDelegationId: requestSnapshot.predecessorDelegationId,
115
+ budgetScope: requestSnapshot.budgetScope,
116
+ parentTurnId: requestSnapshot.parentTurnId,
117
+ parentStepId: requestSnapshot.parentStepId,
118
+ inputFingerprint,
119
+ agentName: requestSnapshot.agentName,
120
+ model: requestSnapshot.model,
121
+ workspace: requestSnapshot.workspace,
122
+ lifecyclePolicy: requestSnapshot.lifecyclePolicy,
123
+ context: requestSnapshot.context,
124
+ inheritedPolicy: childPolicy,
125
+ requestedAllocation: requestSnapshot.allocation,
126
+ requestedPermissions: requestSnapshot.permissions,
127
+ requestedEnvironment: requestSnapshot.environment,
128
+ recordedAt: this.now(),
129
+ }, { durability: "critical" });
130
+ delegationRecorded = true;
131
+ await this.appendLifecycle(state, "child_created", "critical");
132
+ state.completion = this.execute(state, requestSnapshot, childPolicy);
133
+ })();
134
+ try {
135
+ await state.initialization;
136
+ return this.handleFor(state);
137
+ }
138
+ catch (error) {
139
+ const definitelyNotRecorded = !delegationRecorded &&
140
+ (await this.isDelegationDefinitelyAbsent(requestSnapshot.delegationId));
141
+ if (definitelyNotRecorded) {
142
+ this.delegations.delete(requestSnapshot.delegationId);
143
+ if (predecessor?.successorDelegationId === requestSnapshot.delegationId) {
144
+ predecessor.successorDelegationId = undefined;
145
+ }
146
+ releaseBudget(scope.remainingBudget, requestSnapshot.allocation);
147
+ state.releaseParentBudget?.();
148
+ }
149
+ throw error;
150
+ }
151
+ }
152
+ async isDelegationDefinitelyAbsent(delegationId) {
153
+ try {
154
+ const records = await this.options.runStore.read(this.options.parentRunId);
155
+ return !records.some((record) => record.kind === "delegation" &&
156
+ isRecord(record.payload) &&
157
+ record.payload.delegationId === delegationId);
158
+ }
159
+ catch {
160
+ return false;
161
+ }
162
+ }
163
+ async cancelAll(reason) {
164
+ const active = [...this.delegations.values()].filter((state) => state.status !== "joined");
165
+ await Promise.all(active.map(async (state) => {
166
+ await this.cancelState(state, "parent", reason, "parent_cancelled", false);
167
+ await this.join(state);
168
+ }));
169
+ }
170
+ isExecutionQuiescent() {
171
+ return [...this.delegations.values()].every((state) => state.status === "joined");
172
+ }
173
+ isQuiescent() {
174
+ if (!this.isExecutionQuiescent())
175
+ return false;
176
+ return [...this.delegations.values()].every((state) => {
177
+ if (!state.result)
178
+ return false;
179
+ if (!childRunResultRequiresDisposition(state.result))
180
+ return true;
181
+ if (!state.disposition)
182
+ return false;
183
+ return (state.disposition.action !== "redelegate" ||
184
+ state.successorDelegationId !== undefined ||
185
+ state.redelegationCancellation !== undefined);
186
+ });
187
+ }
188
+ continuationGate() {
189
+ let pendingDisposition;
190
+ let propagatedTerminal;
191
+ let pendingRedelegation;
192
+ for (const state of this.delegations.values()) {
193
+ if (state.status !== "joined" || !state.result)
194
+ continue;
195
+ if (!childRunResultRequiresDisposition(state.result))
196
+ continue;
197
+ const recovery = childRunRecoveryAssessment(state.result);
198
+ if (!state.disposition) {
199
+ const requiredActor = requiredDispositionActor(state.result);
200
+ const gate = {
201
+ status: "disposition_required",
202
+ delegationId: state.delegationId,
203
+ childRunId: state.childRunId,
204
+ requiredActor,
205
+ recovery,
206
+ };
207
+ if (requiredActor === "human")
208
+ return gate;
209
+ pendingDisposition ??= gate;
210
+ continue;
211
+ }
212
+ if (state.disposition.action === "redelegate" &&
213
+ !state.successorDelegationId &&
214
+ !state.redelegationCancellation) {
215
+ pendingRedelegation ??= {
216
+ status: "redelegation_required",
217
+ delegationId: state.delegationId,
218
+ childRunId: state.childRunId,
219
+ recovery,
220
+ };
221
+ }
222
+ if (state.disposition.action === "propagate_terminal") {
223
+ propagatedTerminal ??= {
224
+ status: "propagate_terminal",
225
+ delegationId: state.delegationId,
226
+ childRunId: state.childRunId,
227
+ result: structuredClone(state.result),
228
+ };
229
+ }
230
+ }
231
+ return pendingDisposition ?? propagatedTerminal ?? pendingRedelegation ?? { status: "allowed" };
232
+ }
233
+ async recordDisposition(request) {
234
+ return this.withDelegationTransition(async () => {
235
+ if (this.terminalSealed) {
236
+ throw new CoreMindError("child_run_unavailable", "父 Run 已进入终态封口,不能再记录 Child Run 处置");
237
+ }
238
+ return this.recordDispositionWithinTransition(request);
239
+ });
240
+ }
241
+ async recordDispositionWithinTransition(request) {
242
+ assertDispositionRequest(request);
243
+ const state = this.delegations.get(request.delegationId);
244
+ if (!state) {
245
+ throw new CoreMindError("delegation_disposition_conflict", `DelegationId ${request.delegationId} 不存在,不能记录处置`);
246
+ }
247
+ if (state.dispositionPromise) {
248
+ await state.dispositionPromise;
249
+ return this.recordDispositionWithinTransition(request);
250
+ }
251
+ if (state.status !== "joined" ||
252
+ !state.result ||
253
+ !childRunResultRequiresDisposition(state.result)) {
254
+ throw new CoreMindError("delegation_disposition_conflict", `DelegationId ${request.delegationId} 尚无需要处置的 join 结果`);
255
+ }
256
+ const recovery = childRunRecoveryAssessment(state.result);
257
+ const recorded = {
258
+ dispositionId: request.dispositionId,
259
+ delegationId: request.delegationId,
260
+ action: request.action,
261
+ decidedBy: request.decidedBy,
262
+ reason: redactSensitiveText(request.reason),
263
+ evidence: [...new Set((request.evidence ?? []).map(redactSensitiveText))],
264
+ resultFingerprint: childRunResultFingerprint(state.result),
265
+ recovery,
266
+ };
267
+ if (state.disposition) {
268
+ if (canonicalJson(state.disposition) === canonicalJson(recorded)) {
269
+ return structuredClone(state.disposition);
270
+ }
271
+ throw new CoreMindError("delegation_disposition_conflict", `DelegationId ${request.delegationId} 已绑定不同处置`);
272
+ }
273
+ const semanticViolation = delegationDispositionViolation(state.result, request.action, request.decidedBy);
274
+ if (semanticViolation === "human_required") {
275
+ throw new CoreMindError("delegation_disposition_required", `DelegationId ${request.delegationId} 包含未知或未证明安全的 Effect,必须由人工处置`);
276
+ }
277
+ if (semanticViolation === "unsafe_redelegation") {
278
+ throw new CoreMindError("delegation_redelegation_unsafe", `DelegationId ${request.delegationId} 的 RecoveryDisposition 未证明可安全重新委派`);
279
+ }
280
+ const write = (async () => {
281
+ await this.options.parentJournal.appendFact("delegation", {
282
+ type: "delegation_disposition_recorded",
283
+ parentRunId: this.options.parentRunId,
284
+ childRunId: state.childRunId,
285
+ delegationId: state.delegationId,
286
+ ...(state.budgetScope ? { budgetScope: state.budgetScope } : {}),
287
+ inputFingerprint: state.inputFingerprint,
288
+ dispositionId: recorded.dispositionId,
289
+ action: recorded.action,
290
+ decidedBy: recorded.decidedBy,
291
+ reason: recorded.reason,
292
+ evidence: recorded.evidence,
293
+ resultFingerprint: recorded.resultFingerprint,
294
+ recovery: recorded.recovery,
295
+ recordedAt: this.now(),
296
+ }, { durability: "critical" });
297
+ state.disposition = structuredClone(recorded);
298
+ return structuredClone(recorded);
299
+ })();
300
+ state.dispositionPromise = write;
301
+ try {
302
+ return await write;
303
+ }
304
+ finally {
305
+ state.dispositionPromise = undefined;
306
+ }
307
+ }
308
+ /** 父 Run 已形成终态时,持久撤销尚未创建 successor 的重新委派意图。 */
309
+ async cancelPendingRedelegations(parentTerminalCode, reason) {
310
+ await this.withDelegationTransition(() => this.cancelPendingRedelegationsWithinTransition(parentTerminalCode, reason));
311
+ }
312
+ async cancelPendingRedelegationsWithinTransition(parentTerminalCode, reason) {
313
+ const sanitizedReason = redactSensitiveText(reason);
314
+ for (const state of this.delegations.values()) {
315
+ if (state.disposition?.action !== "redelegate" ||
316
+ state.successorDelegationId ||
317
+ state.redelegationCancellation) {
318
+ continue;
319
+ }
320
+ await this.options.parentJournal.appendFact("delegation", {
321
+ type: "delegation_redelegation_cancelled",
322
+ parentRunId: this.options.parentRunId,
323
+ childRunId: state.childRunId,
324
+ delegationId: state.delegationId,
325
+ ...(state.budgetScope ? { budgetScope: state.budgetScope } : {}),
326
+ inputFingerprint: state.inputFingerprint,
327
+ dispositionId: state.disposition.dispositionId,
328
+ parentTerminalCode,
329
+ reason: sanitizedReason,
330
+ recordedAt: this.now(),
331
+ }, { durability: "critical" });
332
+ state.redelegationCancellation = { parentTerminalCode, reason: sanitizedReason };
333
+ }
334
+ }
335
+ /** 等待已进入 Coordinator 的委派变更完成,并阻止父终态后的新变更。 */
336
+ async sealForTerminal() {
337
+ await this.withDelegationTransition(async () => {
338
+ this.terminalSealed = true;
339
+ });
340
+ }
341
+ async withDelegationTransition(operation) {
342
+ if (this.delegationTransitionLocked) {
343
+ await new Promise((resolve) => {
344
+ this.delegationTransitionWaiters.push(resolve);
345
+ });
346
+ }
347
+ else {
348
+ this.delegationTransitionLocked = true;
349
+ }
350
+ try {
351
+ return await operation();
352
+ }
353
+ finally {
354
+ const next = this.delegationTransitionWaiters.shift();
355
+ if (next)
356
+ next();
357
+ else
358
+ this.delegationTransitionLocked = false;
359
+ }
360
+ }
361
+ assertRedelegationRequest(request) {
362
+ const gate = this.continuationGate();
363
+ if (!request.predecessorDelegationId) {
364
+ if (gate.status === "allowed")
365
+ return undefined;
366
+ throw new CoreMindError("delegation_disposition_required", `DelegationId ${gate.delegationId} 尚未完成允许父级继续的处置`);
367
+ }
368
+ const predecessor = this.delegations.get(request.predecessorDelegationId);
369
+ if (gate.status !== "redelegation_required" ||
370
+ gate.delegationId !== request.predecessorDelegationId ||
371
+ !predecessor?.disposition ||
372
+ predecessor.disposition.action !== "redelegate" ||
373
+ predecessor.successorDelegationId ||
374
+ predecessor.delegationId === request.delegationId ||
375
+ !isChildRunRecoverySafeForRedelegation(predecessor.disposition.recovery)) {
376
+ throw new CoreMindError("delegation_redelegation_unsafe", `DelegationId ${request.delegationId} 没有匹配的安全重新委派处置`);
377
+ }
378
+ return predecessor;
379
+ }
380
+ async execute(state, request, childPolicy) {
381
+ await this.appendLifecycle(state, "child_running", "ordinary");
382
+ const signal = state.abortController?.signal ?? AbortSignal.abort("Child Run 执行所有权已丢失");
383
+ let result;
384
+ if (signal.aborted) {
385
+ result = cancellationResult(state.cancellationFinishReason ?? "parent_cancelled");
386
+ }
387
+ else {
388
+ try {
389
+ const executionInput = Object.freeze({
390
+ parentRunId: this.options.parentRunId,
391
+ childRunId: state.childRunId,
392
+ delegationId: state.delegationId,
393
+ inputFingerprint: state.inputFingerprint,
394
+ request: deepFreeze(structuredClone(request)),
395
+ inheritedPolicy: deepFreeze(structuredClone(childPolicy)),
396
+ signal,
397
+ });
398
+ result = normalizeChildRunResult(await this.options.adapter.execute(executionInput));
399
+ }
400
+ catch (error) {
401
+ result = signal.aborted
402
+ ? cancellationResult(state.cancellationFinishReason ?? "parent_cancelled")
403
+ : adapterFailureResult(error);
404
+ }
405
+ }
406
+ state.status = "terminalizing";
407
+ const terminalFact = result.outcome.status === "paused" ? "child_paused" : "child_terminal";
408
+ await this.options.parentJournal.appendFact("delegation", this.lifecycleFact(state, terminalFact, { result }), { durability: "critical" });
409
+ state.status = terminalFact === "child_paused" ? "paused" : "terminal";
410
+ state.result = structuredClone(result);
411
+ return structuredClone(result);
412
+ }
413
+ handleFor(state) {
414
+ return Object.freeze({
415
+ parentRunId: this.options.parentRunId,
416
+ childRunId: state.childRunId,
417
+ delegationId: state.delegationId,
418
+ inputFingerprint: state.inputFingerprint,
419
+ cancel: (reason) => this.cancelState(state, "child", reason ?? "Child Run 已取消", "child_cancelled"),
420
+ join: (options) => this.join(state, options),
421
+ });
422
+ }
423
+ assertActiveChildLimit(scope, maxActiveChildren) {
424
+ const active = [...this.delegations.values()].filter((state) => (state.budgetScope ?? DEFAULT_BUDGET_SCOPE) === scope &&
425
+ (state.status === "recorded" || state.status === "created" || state.status === "running")).length;
426
+ if (active >= maxActiveChildren) {
427
+ throw new CoreMindError("child_run_concurrency_limit", `父 Run 的活动 Child Run 已达到上限 ${maxActiveChildren}`);
428
+ }
429
+ }
430
+ scopeFor(scope) {
431
+ const key = scope ?? DEFAULT_BUDGET_SCOPE;
432
+ const remainingBudget = this.remainingBudgets.get(key);
433
+ const hierarchy = this.hierarchyLimits.get(key);
434
+ if (!remainingBudget || !hierarchy) {
435
+ throw policyEscalation(`父 Agent ${scope ?? "default"} 没有可用的 Delegation Budget 池`);
436
+ }
437
+ return { key, remainingBudget, hierarchy };
438
+ }
439
+ remainingBudgetFor(scope) {
440
+ return this.scopeFor(scope).remainingBudget;
441
+ }
442
+ async auditRestoredOrphans() {
443
+ for (const state of this.delegations.values()) {
444
+ if (state.status === "recorded" || state.status === "created" || state.status === "running") {
445
+ const result = normalizeChildRunResult(orphanedResult(state.childRunId));
446
+ await this.options.parentJournal.appendFact("delegation", this.lifecycleFact(state, "child_orphaned", { result }), { durability: "critical" });
447
+ state.status = "orphaned";
448
+ state.result = structuredClone(result);
449
+ }
450
+ if ((state.status === "terminal" || state.status === "paused" || state.status === "orphaned") &&
451
+ state.result) {
452
+ const result = structuredClone(state.result);
453
+ await this.options.parentJournal.appendFact("delegation", this.lifecycleFact(state, "parent_joined", { result }), { durability: "critical" });
454
+ state.status = "joined";
455
+ }
456
+ }
457
+ }
458
+ join(state, options) {
459
+ if (state.joinPromise)
460
+ return state.joinPromise;
461
+ state.joinPromise = (async () => {
462
+ if (state.status === "joined" && state.result)
463
+ return structuredClone(state.result);
464
+ await state.initialization;
465
+ if ((state.status === "terminal" || state.status === "paused" || state.status === "orphaned") &&
466
+ state.result) {
467
+ const result = structuredClone(state.result);
468
+ await this.options.parentJournal.appendFact("delegation", this.lifecycleFact(state, "parent_joined", { result }), { durability: "critical" });
469
+ state.status = "joined";
470
+ return result;
471
+ }
472
+ if (!state.completion) {
473
+ throw new CoreMindError("child_run_orphan_audit_required", `Child Run ${state.childRunId} 没有当前进程执行所有权,必须先执行 orphan audit`);
474
+ }
475
+ let result;
476
+ if (options?.timeoutMs !== undefined && options.timeoutMs >= 0) {
477
+ let timer;
478
+ const timeout = Symbol("child-run-join-timeout");
479
+ const settled = await Promise.race([
480
+ state.completion,
481
+ new Promise((resolve) => {
482
+ timer = setTimeout(() => resolve(timeout), options.timeoutMs);
483
+ }),
484
+ ]);
485
+ if (timer)
486
+ clearTimeout(timer);
487
+ if (settled === timeout) {
488
+ await this.cancelState(state, "join_timeout", `Child Run ${state.childRunId} join 超时`, "child_join_timeout", false);
489
+ const cancellationGraceMs = this.options.cancellationGraceMs ?? 5_000;
490
+ const afterCancellation = await Promise.race([
491
+ state.completion,
492
+ new Promise((resolve) => {
493
+ timer = setTimeout(() => resolve(timeout), cancellationGraceMs);
494
+ }),
495
+ ]);
496
+ if (timer)
497
+ clearTimeout(timer);
498
+ if (afterCancellation === timeout) {
499
+ throw new CoreMindError("child_run_not_quiescent", `Child Run ${state.childRunId} 取消后 ${cancellationGraceMs}ms 内仍未静止`);
500
+ }
501
+ result = afterCancellation;
502
+ }
503
+ else {
504
+ result = settled;
505
+ }
506
+ }
507
+ else {
508
+ result = await state.completion;
509
+ }
510
+ await this.options.parentJournal.appendFact("delegation", this.lifecycleFact(state, "parent_joined", { result }), { durability: "critical" });
511
+ state.status = "joined";
512
+ state.result = structuredClone(result);
513
+ return structuredClone(result);
514
+ })().catch((error) => {
515
+ state.joinPromise = undefined;
516
+ if (error instanceof CoreMindError && error.code === "child_run_not_quiescent") {
517
+ this.joinAfterLateCompletion(state);
518
+ }
519
+ throw error;
520
+ });
521
+ return state.joinPromise;
522
+ }
523
+ /** grace 超时后 Adapter 若最终收敛,仍补齐结构化 join;永不收敛时保持非静止。 */
524
+ joinAfterLateCompletion(state) {
525
+ if (!state.completion)
526
+ return;
527
+ void state.completion
528
+ .then(async () => {
529
+ await this.join(state);
530
+ })
531
+ .catch(() => undefined);
532
+ }
533
+ async cancelState(state, requestedBy, reason, finishReason, awaitCompletion = true) {
534
+ if (state.status !== "recorded" && state.status !== "created" && state.status !== "running") {
535
+ return;
536
+ }
537
+ state.cancellationFinishReason = finishReason;
538
+ await this.options.parentJournal.appendFact("delegation", this.lifecycleFact(state, "child_cancel_requested", { requestedBy, reason }), { durability: "critical" });
539
+ state.abortController?.abort(reason);
540
+ if (awaitCompletion && state.completion)
541
+ await state.completion;
542
+ }
543
+ async appendLifecycle(state, type, durability) {
544
+ await this.options.parentJournal.appendFact("delegation", this.lifecycleFact(state, type), {
545
+ durability,
546
+ });
547
+ state.status = type === "child_created" ? "created" : "running";
548
+ }
549
+ lifecycleFact(state, type, extra = {}) {
550
+ return {
551
+ type,
552
+ parentRunId: this.options.parentRunId,
553
+ childRunId: state.childRunId,
554
+ delegationId: state.delegationId,
555
+ ...(state.budgetScope ? { budgetScope: state.budgetScope } : {}),
556
+ inputFingerprint: state.inputFingerprint,
557
+ recordedAt: this.now(),
558
+ ...extra,
559
+ };
560
+ }
561
+ restore(records) {
562
+ for (const record of records) {
563
+ if (record.kind !== "delegation")
564
+ continue;
565
+ const fact = decodeChildRunFact(record.payload);
566
+ if (!fact)
567
+ continue;
568
+ if (fact.parentRunId !== this.options.parentRunId) {
569
+ throw new CoreMindError("run_state_corrupt", "Delegation Fact 的父 Run 身份不一致");
570
+ }
571
+ const existing = this.delegations.get(fact.delegationId);
572
+ if (fact.type === "delegation_recorded") {
573
+ if (existing) {
574
+ throw new CoreMindError("run_state_corrupt", "同一 DelegationId 存在重复 recorded Fact");
575
+ }
576
+ const restored = {
577
+ childRunId: fact.childRunId,
578
+ delegationId: fact.delegationId,
579
+ budgetScope: fact.budgetScope,
580
+ inputFingerprint: fact.inputFingerprint,
581
+ predecessorDelegationId: fact.predecessorDelegationId,
582
+ status: "recorded",
583
+ };
584
+ if (fact.predecessorDelegationId) {
585
+ const predecessor = this.delegations.get(fact.predecessorDelegationId);
586
+ if (predecessor?.disposition?.action !== "redelegate" ||
587
+ predecessor.successorDelegationId ||
588
+ predecessor.redelegationCancellation ||
589
+ !isChildRunRecoverySafeForRedelegation(predecessor.disposition.recovery)) {
590
+ throw new CoreMindError("run_state_corrupt", "关联 Child Run 缺少匹配的安全重新委派处置");
591
+ }
592
+ predecessor.successorDelegationId = fact.delegationId;
593
+ }
594
+ this.delegations.set(fact.delegationId, restored);
595
+ try {
596
+ reserveBudget(this.remainingBudgetFor(fact.budgetScope), fact.requestedAllocation);
597
+ restored.releaseParentBudget = this.options.reserveParentBudget?.(fact.requestedAllocation);
598
+ }
599
+ catch {
600
+ throw new CoreMindError("run_state_corrupt", "Child Run 的累计预算划拨超过父级预算");
601
+ }
602
+ continue;
603
+ }
604
+ if (!existing ||
605
+ existing.childRunId !== fact.childRunId ||
606
+ existing.inputFingerprint !== fact.inputFingerprint) {
607
+ throw new CoreMindError("run_state_corrupt", "Child Run 生命周期缺少匹配的 Delegation Fact");
608
+ }
609
+ if (fact.type === "delegation_disposition_recorded") {
610
+ if (existing.status !== "joined" ||
611
+ !existing.result ||
612
+ !childRunResultRequiresDisposition(existing.result) ||
613
+ existing.disposition ||
614
+ childRunResultFingerprint(existing.result) !== fact.resultFingerprint ||
615
+ canonicalJson(childRunRecoveryAssessment(existing.result)) !==
616
+ canonicalJson(fact.recovery) ||
617
+ delegationDispositionViolation(existing.result, fact.action, fact.decidedBy) !== undefined) {
618
+ throw new CoreMindError("run_state_corrupt", "Delegation Disposition 与已 join 的 Child Run 结果不匹配");
619
+ }
620
+ existing.disposition = {
621
+ dispositionId: fact.dispositionId,
622
+ delegationId: fact.delegationId,
623
+ action: fact.action,
624
+ decidedBy: fact.decidedBy,
625
+ reason: fact.reason,
626
+ evidence: [...fact.evidence],
627
+ resultFingerprint: fact.resultFingerprint,
628
+ recovery: structuredClone(fact.recovery),
629
+ };
630
+ continue;
631
+ }
632
+ if (fact.type === "delegation_redelegation_cancelled") {
633
+ if (existing.status !== "joined" ||
634
+ existing.disposition?.action !== "redelegate" ||
635
+ existing.disposition.dispositionId !== fact.dispositionId ||
636
+ existing.successorDelegationId ||
637
+ existing.redelegationCancellation) {
638
+ throw new CoreMindError("run_state_corrupt", "重新委派撤销 Fact 与待建立 successor 的处置不匹配");
639
+ }
640
+ existing.redelegationCancellation = {
641
+ parentTerminalCode: fact.parentTerminalCode,
642
+ reason: fact.reason,
643
+ };
644
+ continue;
645
+ }
646
+ existing.status = foldChildRunLifecycleStatus(existing.status, fact.type);
647
+ if (fact.type === "child_terminal" ||
648
+ fact.type === "child_paused" ||
649
+ fact.type === "child_orphaned" ||
650
+ fact.type === "parent_joined") {
651
+ existing.result = normalizeChildRunResult(fact.result);
652
+ }
653
+ }
654
+ }
655
+ }
656
+ export function childRunInputFingerprint(request) {
657
+ const { delegationId: _delegationId, ...input } = request;
658
+ return `sha256:${createHash("sha256").update(canonicalJson(input)).digest("hex")}`;
659
+ }
660
+ function assertChildRunPolicyIsNarrower(parent, remainingBudget, request) {
661
+ if (request.lifecyclePolicy.join !== "structured" ||
662
+ request.lifecyclePolicy.cancel !== "propagate_parent" ||
663
+ request.lifecyclePolicy.orphan !== "audit_pause" ||
664
+ request.lifecyclePolicy.detach !== "forbidden") {
665
+ throw policyEscalation("当前 Child Run 只支持结构化 join,尚不支持脱离父生命周期");
666
+ }
667
+ if (parent.depth + 1 > parent.maxDepth) {
668
+ throw policyEscalation("Child Run 深度超过父级允许上限");
669
+ }
670
+ effectiveChildHierarchy(parent, request);
671
+ const routeScope = request.budgetScope ?? DEFAULT_BUDGET_SCOPE;
672
+ const configuredModel = parent.delegationModelRoutes?.[routeScope]?.[request.agentName];
673
+ if (!configuredModel) {
674
+ throw policyEscalation("Child Run 缺少命名 Delegation Target 的固定模型路由");
675
+ }
676
+ if (!matchesConfiguredDelegationModel(configuredModel, request.model, request.allocation.tokens)) {
677
+ throw policyEscalation("Child Run 模型与命名 Delegation Target 的固定路由不一致");
678
+ }
679
+ if (canonicalJson(request.workspace) !== canonicalJson(parent.workspace)) {
680
+ throw policyEscalation("Child Run Workspace 身份或租约要求与父级不一致");
681
+ }
682
+ const requestedReferences = new Set(request.context.references);
683
+ if (parent.protectedContextReferences.some((reference) => !requestedReferences.has(reference))) {
684
+ throw policyEscalation("Child Run Context 缺少父级不可删除引用");
685
+ }
686
+ for (const key of Object.keys(parent.budget)) {
687
+ const requested = request.allocation[key];
688
+ const reserved = key === "descendants" ? requested + 1 : requested;
689
+ if (!Number.isFinite(requested) || requested < 0 || reserved > remainingBudget[key]) {
690
+ throw policyEscalation(`Child Run 的 ${key} 预算超过父级分配`);
691
+ }
692
+ }
693
+ const parentPermissions = parent.permissions;
694
+ const requestedPermissions = request.permissions;
695
+ if (permissionModeRank(requestedPermissions.mode) < permissionModeRank(parentPermissions.mode)) {
696
+ throw policyEscalation("Child Run 权限模式比父级更宽");
697
+ }
698
+ if (parentPermissions.workspaceOnly && !requestedPermissions.workspaceOnly) {
699
+ throw policyEscalation("Child Run 不能移除父级工作区边界");
700
+ }
701
+ if (networkPermissionRank(requestedPermissions.network) <
702
+ networkPermissionRank(parentPermissions.network)) {
703
+ throw policyEscalation("Child Run 网络权限比父级更宽");
704
+ }
705
+ assertSubset("工具", requestedPermissions.tools, parentPermissions.tools);
706
+ assertSubset("路径", requestedPermissions.paths, parentPermissions.paths);
707
+ assertSubset("凭据", requestedPermissions.credentials, parentPermissions.credentials);
708
+ const tightenedEnvironment = tightenChildRunEnvironment(parent.environment, request.environment);
709
+ if (canonicalJson(tightenedEnvironment) !== canonicalJson(request.environment)) {
710
+ throw policyEscalation("Child Run 执行环境要求比父级更宽");
711
+ }
712
+ }
713
+ function normalizeParentPolicy(policy) {
714
+ const maxDepth = policy.maxDepth ?? CHILD_RUN_LIMIT_DEFAULTS.maxDepth;
715
+ const maxActiveChildren = policy.maxActiveChildren ?? CHILD_RUN_LIMIT_DEFAULTS.maxActiveChildren;
716
+ const maxDescendants = policy.maxDescendants ?? CHILD_RUN_LIMIT_DEFAULTS.maxDescendants;
717
+ for (const [label, value] of [
718
+ ["depth", policy.depth],
719
+ ["maxDepth", maxDepth],
720
+ ["maxActiveChildren", maxActiveChildren],
721
+ ["maxDescendants", maxDescendants],
722
+ ]) {
723
+ if (!Number.isSafeInteger(value) || value < 0) {
724
+ throw policyEscalation(`Child Run 的 ${label} 必须是有限非负整数`);
725
+ }
726
+ }
727
+ for (const [key, value] of Object.entries(policy.budget)) {
728
+ if (!Number.isFinite(value) || value < 0) {
729
+ throw policyEscalation(`Child Run 父级 ${key} 预算必须是有限非负数`);
730
+ }
731
+ }
732
+ if (policy.budget.descendants > maxDescendants) {
733
+ throw policyEscalation("Child Run 父级后代预算超过 maxDescendants");
734
+ }
735
+ return {
736
+ ...structuredClone(policy),
737
+ maxDepth,
738
+ maxActiveChildren,
739
+ maxDescendants,
740
+ };
741
+ }
742
+ function assertDelegationBudgetPool(parent, budget) {
743
+ for (const key of Object.keys(parent.budget)) {
744
+ const value = budget[key];
745
+ if (!Number.isFinite(value) || value < 0 || value > parent.budget[key]) {
746
+ throw policyEscalation(`Delegation Budget 池的 ${key} 不能超过父 Run 预算`);
747
+ }
748
+ }
749
+ if (budget.descendants > parent.maxDescendants) {
750
+ throw policyEscalation("Delegation Budget 池的 descendants 不能超过父级后代上限");
751
+ }
752
+ }
753
+ function hierarchyFromPolicy(policy) {
754
+ return {
755
+ maxDepth: policy.maxDepth,
756
+ maxActiveChildren: policy.maxActiveChildren,
757
+ maxDescendants: policy.maxDescendants,
758
+ };
759
+ }
760
+ function normalizeScopeHierarchy(parent, budget, configured) {
761
+ const maxDepth = checkedHierarchyLimit("maxDepth", configured?.maxDepth ?? parent.maxDepth, parent.maxDepth);
762
+ const maxActiveChildren = checkedHierarchyLimit("maxActiveChildren", configured?.maxActiveChildren ?? parent.maxActiveChildren, parent.maxActiveChildren);
763
+ const maxDescendants = checkedHierarchyLimit("maxDescendants", configured?.maxDescendants ?? Math.min(parent.maxDescendants, budget.descendants), Math.min(parent.maxDescendants, budget.descendants));
764
+ return { maxDepth, maxActiveChildren, maxDescendants };
765
+ }
766
+ function effectiveChildPolicy(parent, request) {
767
+ const hierarchy = effectiveChildHierarchy(parent, request);
768
+ return {
769
+ depth: parent.depth + 1,
770
+ budget: structuredClone(request.allocation),
771
+ permissions: structuredClone(request.permissions),
772
+ environment: tightenChildRunEnvironment(parent.environment, request.environment),
773
+ model: structuredClone(request.model),
774
+ workspace: structuredClone(request.workspace),
775
+ protectedContextReferences: [...new Set(request.context.references)],
776
+ ...((request.context.resolvedReferences?.length ?? 0) > 0
777
+ ? {
778
+ protectedContextResolvedReferences: structuredClone(request.context.resolvedReferences),
779
+ }
780
+ : {}),
781
+ ...hierarchy,
782
+ };
783
+ }
784
+ function effectiveChildHierarchy(parent, request) {
785
+ const requested = request.hierarchyLimits ?? {};
786
+ const maxDepth = checkedHierarchyLimit("maxDepth", requested.maxDepth ?? parent.maxDepth, parent.maxDepth);
787
+ if (maxDepth < parent.depth + 1) {
788
+ throw policyEscalation("Child Run 的 maxDepth 不能小于当前子级深度");
789
+ }
790
+ const maxActiveChildren = checkedHierarchyLimit("maxActiveChildren", requested.maxActiveChildren ?? parent.maxActiveChildren, parent.maxActiveChildren);
791
+ const maxDescendants = request.allocation.descendants;
792
+ return { maxDepth, maxActiveChildren, maxDescendants };
793
+ }
794
+ function checkedHierarchyLimit(label, value, inherited) {
795
+ if (!Number.isSafeInteger(value) || value < 0 || value > inherited) {
796
+ throw policyEscalation(`Child Run 的 ${label} 只能是有限非负整数且不能超过父级限制`);
797
+ }
798
+ return value;
799
+ }
800
+ function reserveBudget(remaining, allocation) {
801
+ for (const key of Object.keys(remaining)) {
802
+ const reserved = key === "descendants" ? allocation[key] + 1 : allocation[key];
803
+ if (!Number.isFinite(reserved) || reserved < 0 || reserved > remaining[key]) {
804
+ throw policyEscalation(`Child Run 的 ${key} 预算超过父级剩余预算`);
805
+ }
806
+ remaining[key] -= reserved;
807
+ }
808
+ }
809
+ function releaseBudget(remaining, allocation) {
810
+ for (const key of Object.keys(remaining)) {
811
+ remaining[key] += key === "descendants" ? allocation[key] + 1 : allocation[key];
812
+ }
813
+ }
814
+ function assertSubset(label, requested, inherited) {
815
+ const inheritedValues = new Set(inherited);
816
+ if (requested.some((value) => !inheritedValues.has(value))) {
817
+ throw policyEscalation(`Child Run ${label}集合包含父级未授权项`);
818
+ }
819
+ }
820
+ function permissionModeRank(mode) {
821
+ return mode === "ask" ? 2 : mode === "assisted" ? 1 : 0;
822
+ }
823
+ function networkPermissionRank(network) {
824
+ return network === "deny" ? 2 : network === "ask" ? 1 : 0;
825
+ }
826
+ function policyEscalation(message) {
827
+ return new CoreMindError("child_run_policy_escalation", message);
828
+ }
829
+ function tightenChildRunEnvironment(inherited, requested) {
830
+ return removeUndefined(structuredClone(tightenExecutionEnvironmentRequirement(inherited, requested)));
831
+ }
832
+ function removeUndefined(value) {
833
+ if (Array.isArray(value))
834
+ return value.map(removeUndefined);
835
+ if (!isRecord(value))
836
+ return value;
837
+ return Object.fromEntries(Object.entries(value)
838
+ .filter(([, item]) => item !== undefined)
839
+ .map(([key, item]) => [key, removeUndefined(item)]));
840
+ }
841
+ function adapterFailureResult(error) {
842
+ const normalized = normalizeExecutionError(error);
843
+ const { code, message, audit } = normalized;
844
+ return {
845
+ outcome: {
846
+ status: terminalStatusForCode(code),
847
+ finishReason: code,
848
+ error: { code, message, ...(audit ? { audit } : {}) },
849
+ },
850
+ evidence: [],
851
+ artifacts: [],
852
+ workspaceChanges: [],
853
+ unresolvedRisks: [message],
854
+ };
855
+ }
856
+ function normalizeChildRunResult(result) {
857
+ if (!isChildRunResult(result)) {
858
+ throw new Error("Child Run Adapter 返回了无效结果");
859
+ }
860
+ const sanitized = {
861
+ ...structuredClone(result),
862
+ evidence: result.evidence.map(redactSensitiveText),
863
+ artifacts: result.artifacts.map(redactSensitiveText),
864
+ workspaceChanges: result.workspaceChanges.map((change) => ({
865
+ ...structuredClone(change),
866
+ path: redactSensitiveText(change.path),
867
+ })),
868
+ unresolvedRisks: result.unresolvedRisks.map(redactSensitiveText),
869
+ recovery: childRunRecoveryAssessment(result),
870
+ };
871
+ const error = result.outcome.status === "succeeded" ||
872
+ isChildLifecycleOutcomeWithStableFinishReason(result.outcome)
873
+ ? undefined
874
+ : (result.outcome.error ?? {
875
+ code: result.outcome.finishReason,
876
+ message: result.outcome.finishReason,
877
+ });
878
+ if (!error)
879
+ return sanitized;
880
+ const normalized = normalizeExecutionError(error);
881
+ return {
882
+ ...sanitized,
883
+ outcome: {
884
+ status: terminalStatusForCode(normalized.code),
885
+ finishReason: normalized.code,
886
+ error: {
887
+ code: normalized.code,
888
+ message: normalized.message,
889
+ ...(normalized.audit ? { audit: normalized.audit } : {}),
890
+ },
891
+ },
892
+ };
893
+ }
894
+ function isChildLifecycleOutcomeWithStableFinishReason(outcome) {
895
+ return ((outcome.status === "aborted" &&
896
+ (outcome.finishReason === "parent_cancelled" ||
897
+ outcome.finishReason === "child_cancelled")) ||
898
+ (outcome.status === "timeout" && outcome.finishReason === "child_join_timeout") ||
899
+ (outcome.status === "paused" && outcome.finishReason === "child_run_orphaned"));
900
+ }
901
+ function cancellationResult(finishReason) {
902
+ return {
903
+ outcome: {
904
+ status: finishReason === "child_join_timeout" ? "timeout" : "aborted",
905
+ finishReason,
906
+ },
907
+ evidence: [],
908
+ artifacts: [],
909
+ workspaceChanges: [],
910
+ unresolvedRisks: [],
911
+ };
912
+ }
913
+ function orphanedResult(childRunId) {
914
+ const message = `Child Run ${childRunId} 恢复时无法确认执行所有权,已停止自动恢复`;
915
+ return {
916
+ outcome: {
917
+ status: "paused",
918
+ finishReason: "child_run_orphaned",
919
+ error: { code: "child_run_orphan_audit_required", message },
920
+ },
921
+ evidence: [],
922
+ artifacts: [],
923
+ workspaceChanges: [],
924
+ unresolvedRisks: [message],
925
+ recovery: {
926
+ recoveryDisposition: "requires_human",
927
+ effectState: "unknown",
928
+ quiescent: false,
929
+ executionOwnership: "unknown",
930
+ evidence: [],
931
+ },
932
+ };
933
+ }
934
+ export function childRunRecoveryAssessment(result) {
935
+ if (result.recovery && isChildRunRecoveryAssessment(result.recovery)) {
936
+ return {
937
+ ...structuredClone(result.recovery),
938
+ evidence: [...new Set(result.recovery.evidence.map(redactSensitiveText))],
939
+ };
940
+ }
941
+ if (result.outcome.status === "succeeded") {
942
+ return {
943
+ recoveryDisposition: "replay_safe",
944
+ effectState: "none",
945
+ quiescent: true,
946
+ executionOwnership: "released",
947
+ evidence: [],
948
+ };
949
+ }
950
+ return {
951
+ recoveryDisposition: "requires_human",
952
+ effectState: "unknown",
953
+ quiescent: true,
954
+ executionOwnership: "unknown",
955
+ evidence: [],
956
+ };
957
+ }
958
+ export function childRunResultRequiresDisposition(result) {
959
+ if (result.outcome.status !== "succeeded")
960
+ return true;
961
+ const recovery = childRunRecoveryAssessment(result);
962
+ const unresolvedRecoveryWithoutCommittedSuccess = recovery.effectState !== "committed" &&
963
+ (recovery.recoveryDisposition === "requires_human" ||
964
+ recovery.recoveryDisposition === "forbidden");
965
+ return (unresolvedRecoveryWithoutCommittedSuccess ||
966
+ recovery.effectState === "started" ||
967
+ recovery.effectState === "unknown" ||
968
+ !recovery.quiescent ||
969
+ recovery.executionOwnership !== "released");
970
+ }
971
+ export function childRunResultFingerprint(result) {
972
+ return `sha256:${createHash("sha256")
973
+ .update(canonicalJson({ ...structuredClone(result), recovery: childRunRecoveryAssessment(result) }))
974
+ .digest("hex")}`;
975
+ }
976
+ function requiredDispositionActor(result) {
977
+ const recovery = childRunRecoveryAssessment(result);
978
+ return isChildRunRecoverySafeForRedelegation(recovery) ? "parent_agent" : "human";
979
+ }
980
+ export function delegationDispositionViolation(result, action, decidedBy) {
981
+ const recovery = childRunRecoveryAssessment(result);
982
+ if (requiredDispositionActor(result) === "human" && decidedBy !== "human") {
983
+ return "human_required";
984
+ }
985
+ if (action === "redelegate" && !isChildRunRecoverySafeForRedelegation(recovery)) {
986
+ return "unsafe_redelegation";
987
+ }
988
+ return undefined;
989
+ }
990
+ export function isChildRunRecoverySafeForRedelegation(recovery) {
991
+ return (recovery.recoveryDisposition === "replay_safe" &&
992
+ recovery.quiescent &&
993
+ recovery.executionOwnership === "released" &&
994
+ (recovery.effectState === "none" || recovery.effectState === "not_started"));
995
+ }
996
+ function assertDispositionRequest(request) {
997
+ if (request.dispositionId.trim().length === 0 ||
998
+ request.delegationId.trim().length === 0 ||
999
+ request.reason.trim().length === 0 ||
1000
+ !["accept_failure", "choose_alternative", "redelegate", "propagate_terminal"].includes(request.action) ||
1001
+ (request.decidedBy !== "parent_agent" && request.decidedBy !== "human") ||
1002
+ (request.evidence !== undefined &&
1003
+ (!Array.isArray(request.evidence) ||
1004
+ request.evidence.some((item) => typeof item !== "string")))) {
1005
+ throw new CoreMindError("delegation_disposition_conflict", "Delegation Disposition 请求合同非法");
1006
+ }
1007
+ }
1008
+ export function isChildRunFact(value) {
1009
+ if (!isRecord(value) || typeof value.type !== "string")
1010
+ return false;
1011
+ if (typeof value.parentRunId !== "string" ||
1012
+ typeof value.childRunId !== "string" ||
1013
+ typeof value.delegationId !== "string" ||
1014
+ typeof value.inputFingerprint !== "string" ||
1015
+ typeof value.recordedAt !== "string") {
1016
+ return false;
1017
+ }
1018
+ if (value.budgetScope !== undefined && typeof value.budgetScope !== "string")
1019
+ return false;
1020
+ if (value.type === "delegation_recorded") {
1021
+ return ((value.predecessorDelegationId === undefined ||
1022
+ typeof value.predecessorDelegationId === "string") &&
1023
+ typeof value.parentTurnId === "string" &&
1024
+ typeof value.parentStepId === "string" &&
1025
+ typeof value.agentName === "string" &&
1026
+ isChildRunModelSnapshot(value.model) &&
1027
+ isChildRunWorkspaceSnapshot(value.workspace) &&
1028
+ isChildRunLifecyclePolicy(value.lifecyclePolicy) &&
1029
+ isChildRunContextReference(value.context) &&
1030
+ isChildRunPolicySnapshot(value.inheritedPolicy) &&
1031
+ isChildRunBudgetAllocation(value.requestedAllocation) &&
1032
+ isChildRunPermissionSnapshot(value.requestedPermissions) &&
1033
+ isChildRunEnvironmentRequirement(value.requestedEnvironment));
1034
+ }
1035
+ if (value.type === "delegation_disposition_recorded") {
1036
+ return (typeof value.dispositionId === "string" &&
1037
+ value.dispositionId.length > 0 &&
1038
+ (value.action === "accept_failure" ||
1039
+ value.action === "choose_alternative" ||
1040
+ value.action === "redelegate" ||
1041
+ value.action === "propagate_terminal") &&
1042
+ (value.decidedBy === "parent_agent" || value.decidedBy === "human") &&
1043
+ typeof value.reason === "string" &&
1044
+ value.reason.length > 0 &&
1045
+ isStringArray(value.evidence) &&
1046
+ typeof value.resultFingerprint === "string" &&
1047
+ isChildRunRecoveryAssessment(value.recovery));
1048
+ }
1049
+ if (value.type === "delegation_redelegation_cancelled") {
1050
+ return (typeof value.dispositionId === "string" &&
1051
+ value.dispositionId.length > 0 &&
1052
+ typeof value.parentTerminalCode === "string" &&
1053
+ value.parentTerminalCode.length > 0 &&
1054
+ typeof value.reason === "string" &&
1055
+ value.reason.length > 0);
1056
+ }
1057
+ if (value.type === "child_created" || value.type === "child_running")
1058
+ return true;
1059
+ if (value.type === "child_cancel_requested") {
1060
+ return ((value.requestedBy === "parent" ||
1061
+ value.requestedBy === "child" ||
1062
+ value.requestedBy === "join_timeout") &&
1063
+ typeof value.reason === "string");
1064
+ }
1065
+ return ((value.type === "child_terminal" ||
1066
+ value.type === "child_paused" ||
1067
+ value.type === "child_orphaned" ||
1068
+ value.type === "parent_joined") &&
1069
+ isChildRunResult(value.result));
1070
+ }
1071
+ /** 读取历史 Child Fact;旧版字符串变更只能保留为证据,不能伪造结构化路径或变更类型。 */
1072
+ export function decodeChildRunFact(value) {
1073
+ if (isChildRunFact(value))
1074
+ return structuredClone(value);
1075
+ if (!isRecord(value) || !isChildRunResultFactType(value.type))
1076
+ return undefined;
1077
+ const result = decodeLegacyChildRunResult(value.result);
1078
+ if (!result)
1079
+ return undefined;
1080
+ const normalized = { ...structuredClone(value), result };
1081
+ return isChildRunFact(normalized) ? normalized : undefined;
1082
+ }
1083
+ function decodeLegacyChildRunResult(value) {
1084
+ if (!isRecord(value) ||
1085
+ !isRecord(value.outcome) ||
1086
+ !isRunOutcome(value.outcome) ||
1087
+ !isStringArray(value.evidence) ||
1088
+ !isStringArray(value.artifacts) ||
1089
+ !isStringArray(value.workspaceChanges) ||
1090
+ !isStringArray(value.unresolvedRisks)) {
1091
+ return undefined;
1092
+ }
1093
+ const legacyReferences = value.workspaceChanges;
1094
+ return {
1095
+ outcome: structuredClone(value.outcome),
1096
+ evidence: [...new Set([...value.evidence, ...legacyReferences])],
1097
+ artifacts: [...value.artifacts],
1098
+ workspaceChanges: [],
1099
+ unresolvedRisks: [
1100
+ ...value.unresolvedRisks,
1101
+ "历史 Child Run 的 Workspace 变更仅保留为证据引用,无法重建结构化 change summary",
1102
+ ],
1103
+ };
1104
+ }
1105
+ function isChildRunResultFactType(value) {
1106
+ return (value === "child_terminal" ||
1107
+ value === "child_paused" ||
1108
+ value === "child_orphaned" ||
1109
+ value === "parent_joined");
1110
+ }
1111
+ function isChildRunContextReference(value) {
1112
+ if (!isRecord(value) ||
1113
+ typeof value.workingSetFingerprint !== "string" ||
1114
+ !isStringArray(value.references)) {
1115
+ return false;
1116
+ }
1117
+ if (value.resolvedReferences === undefined)
1118
+ return true;
1119
+ if (!Array.isArray(value.resolvedReferences) ||
1120
+ !value.resolvedReferences.every(isResolvedDelegatedContextReference)) {
1121
+ return false;
1122
+ }
1123
+ const references = [...new Set(value.references)];
1124
+ return (references.length === value.resolvedReferences.length &&
1125
+ value.resolvedReferences.every((resolved, index) => resolved.reference === references[index]));
1126
+ }
1127
+ function isChildRunBudgetAllocation(value) {
1128
+ if (!isRecord(value))
1129
+ return false;
1130
+ return ["tokens", "toolCalls", "costUsd", "wallTimeMs", "steps", "descendants"].every((key) => {
1131
+ const item = value[key];
1132
+ return typeof item === "number" && Number.isFinite(item) && item >= 0;
1133
+ });
1134
+ }
1135
+ function isChildRunPermissionSnapshot(value) {
1136
+ return (isRecord(value) &&
1137
+ (value.mode === "ask" || value.mode === "assisted" || value.mode === "full") &&
1138
+ typeof value.workspaceOnly === "boolean" &&
1139
+ (value.network === "ask" || value.network === "allow" || value.network === "deny") &&
1140
+ isStringArray(value.tools) &&
1141
+ isStringArray(value.paths) &&
1142
+ isStringArray(value.credentials));
1143
+ }
1144
+ function isChildRunPolicySnapshot(value) {
1145
+ return (isRecord(value) &&
1146
+ typeof value.depth === "number" &&
1147
+ Number.isInteger(value.depth) &&
1148
+ value.depth >= 0 &&
1149
+ isChildRunBudgetAllocation(value.budget) &&
1150
+ isChildRunPermissionSnapshot(value.permissions) &&
1151
+ isChildRunEnvironmentRequirement(value.environment) &&
1152
+ isChildRunModelSnapshot(value.model) &&
1153
+ isChildRunWorkspaceSnapshot(value.workspace) &&
1154
+ isStringArray(value.protectedContextReferences) &&
1155
+ (value.protectedContextResolvedReferences === undefined ||
1156
+ (Array.isArray(value.protectedContextResolvedReferences) &&
1157
+ value.protectedContextResolvedReferences.every(isResolvedDelegatedContextReference))) &&
1158
+ (value.delegationModelRoutes === undefined ||
1159
+ (isRecord(value.delegationModelRoutes) &&
1160
+ Object.values(value.delegationModelRoutes).every((routes) => isRecord(routes) && Object.values(routes).every(isChildRunModelSnapshot)))) &&
1161
+ typeof value.maxDepth === "number" &&
1162
+ Number.isInteger(value.maxDepth) &&
1163
+ value.maxDepth >= 0 &&
1164
+ typeof value.maxActiveChildren === "number" &&
1165
+ Number.isInteger(value.maxActiveChildren) &&
1166
+ value.maxActiveChildren >= 0 &&
1167
+ (value.maxDescendants === undefined ||
1168
+ (typeof value.maxDescendants === "number" &&
1169
+ Number.isSafeInteger(value.maxDescendants) &&
1170
+ value.maxDescendants >= 0)));
1171
+ }
1172
+ function matchesConfiguredDelegationModel(configured, requested, tokenAllocation) {
1173
+ if (!isChildRunModelSnapshot(configured) || !isChildRunModelSnapshot(requested))
1174
+ return false;
1175
+ if (configured.providerId !== requested.providerId || configured.model !== requested.model) {
1176
+ return false;
1177
+ }
1178
+ if (configured.providerConfigFingerprint !== requested.providerConfigFingerprint ||
1179
+ configured.agentPromptFingerprint !== requested.agentPromptFingerprint ||
1180
+ configured.agentDelegationFingerprint !== requested.agentDelegationFingerprint) {
1181
+ return false;
1182
+ }
1183
+ if (configured.options?.temperature !== requested.options?.temperature ||
1184
+ configured.options?.thinkingLevel !== requested.options?.thinkingLevel) {
1185
+ return false;
1186
+ }
1187
+ const configuredMaxTokens = configured.options?.maxTokens;
1188
+ if (configuredMaxTokens === undefined) {
1189
+ return (requested.options?.maxTokens === undefined || requested.options.maxTokens <= tokenAllocation);
1190
+ }
1191
+ return requested.options?.maxTokens === Math.min(configuredMaxTokens, tokenAllocation);
1192
+ }
1193
+ function isChildRunModelSnapshot(value) {
1194
+ if (!isRecord(value) || typeof value.providerId !== "string" || typeof value.model !== "string") {
1195
+ return false;
1196
+ }
1197
+ if (typeof value.providerConfigFingerprint !== "string" ||
1198
+ typeof value.agentPromptFingerprint !== "string" ||
1199
+ typeof value.agentDelegationFingerprint !== "string") {
1200
+ return false;
1201
+ }
1202
+ if (value.options === undefined)
1203
+ return true;
1204
+ if (!isRecord(value.options))
1205
+ return false;
1206
+ const { temperature, maxTokens, thinkingLevel } = value.options;
1207
+ return ((temperature === undefined ||
1208
+ (typeof temperature === "number" && temperature >= 0 && temperature <= 2)) &&
1209
+ (maxTokens === undefined ||
1210
+ (typeof maxTokens === "number" && Number.isInteger(maxTokens) && maxTokens >= 1)) &&
1211
+ (thinkingLevel === undefined ||
1212
+ thinkingLevel === "off" ||
1213
+ thinkingLevel === "low" ||
1214
+ thinkingLevel === "medium" ||
1215
+ thinkingLevel === "high" ||
1216
+ thinkingLevel === "xhigh"));
1217
+ }
1218
+ function deepFreeze(value) {
1219
+ if (value === null || typeof value !== "object" || Object.isFrozen(value))
1220
+ return value;
1221
+ for (const nested of Object.values(value))
1222
+ deepFreeze(nested);
1223
+ return Object.freeze(value);
1224
+ }
1225
+ function isChildRunWorkspaceSnapshot(value) {
1226
+ return (isRecord(value) && typeof value.canonicalRoot === "string" && value.lease === "shared_canonical");
1227
+ }
1228
+ function isChildRunLifecyclePolicy(value) {
1229
+ return (isRecord(value) &&
1230
+ value.join === "structured" &&
1231
+ value.cancel === "propagate_parent" &&
1232
+ value.orphan === "audit_pause" &&
1233
+ (value.detach === "forbidden" || value.detach === "durable_preaccepted"));
1234
+ }
1235
+ function isChildRunResult(value) {
1236
+ return (isRecord(value) &&
1237
+ isRecord(value.outcome) &&
1238
+ isRunOutcome(value.outcome) &&
1239
+ isStringArray(value.evidence) &&
1240
+ isStringArray(value.artifacts) &&
1241
+ Array.isArray(value.workspaceChanges) &&
1242
+ value.workspaceChanges.every(isChildRunWorkspaceChange) &&
1243
+ isStringArray(value.unresolvedRisks) &&
1244
+ (value.recovery === undefined || isChildRunRecoveryAssessment(value.recovery)));
1245
+ }
1246
+ function isChildRunRecoveryAssessment(value) {
1247
+ return (isRecord(value) &&
1248
+ (value.recoveryDisposition === "replay_safe" ||
1249
+ value.recoveryDisposition === "requires_proof" ||
1250
+ value.recoveryDisposition === "requires_human" ||
1251
+ value.recoveryDisposition === "forbidden") &&
1252
+ (value.effectState === "none" ||
1253
+ value.effectState === "not_started" ||
1254
+ value.effectState === "started" ||
1255
+ value.effectState === "committed" ||
1256
+ value.effectState === "unknown") &&
1257
+ typeof value.quiescent === "boolean" &&
1258
+ (value.executionOwnership === "released" || value.executionOwnership === "unknown") &&
1259
+ isStringArray(value.evidence));
1260
+ }
1261
+ function isChildRunWorkspaceChange(value) {
1262
+ return (isRecord(value) &&
1263
+ typeof value.checkpointId === "string" &&
1264
+ typeof value.path === "string" &&
1265
+ (value.kind === "created" || value.kind === "modified" || value.kind === "deleted") &&
1266
+ (value.beforeSha256 === undefined || typeof value.beforeSha256 === "string") &&
1267
+ (value.afterSha256 === undefined || typeof value.afterSha256 === "string"));
1268
+ }
1269
+ function isRunOutcome(value) {
1270
+ const statuses = new Set([
1271
+ "succeeded",
1272
+ "failed",
1273
+ "paused",
1274
+ "aborted",
1275
+ "timeout",
1276
+ "budget_exceeded",
1277
+ ]);
1278
+ return (typeof value.status === "string" &&
1279
+ statuses.has(value.status) &&
1280
+ typeof value.finishReason === "string" &&
1281
+ (value.error === undefined ||
1282
+ (isRecord(value.error) &&
1283
+ typeof value.error.code === "string" &&
1284
+ typeof value.error.message === "string")));
1285
+ }
1286
+ function isChildRunEnvironmentRequirement(value) {
1287
+ if (!isRecord(value))
1288
+ return false;
1289
+ const allowedKeys = new Set([
1290
+ "isolation",
1291
+ "readAccess",
1292
+ "writeAccess",
1293
+ "outsideWorkspaceAccess",
1294
+ "networkEgress",
1295
+ "credentialIsolation",
1296
+ "processControl",
1297
+ "termination",
1298
+ "durability",
1299
+ ]);
1300
+ if (Object.keys(value).some((key) => !allowedKeys.has(key)))
1301
+ return false;
1302
+ return ((value.isolation === undefined || value.isolation === "sandbox") &&
1303
+ (value.readAccess === undefined ||
1304
+ value.readAccess === "workspace" ||
1305
+ value.readAccess === "none") &&
1306
+ (value.writeAccess === undefined ||
1307
+ value.writeAccess === "workspace" ||
1308
+ value.writeAccess === "none") &&
1309
+ (value.outsideWorkspaceAccess === undefined || value.outsideWorkspaceAccess === "blocked") &&
1310
+ (value.networkEgress === undefined ||
1311
+ value.networkEgress === "controlled" ||
1312
+ value.networkEgress === "denied") &&
1313
+ (value.credentialIsolation === undefined ||
1314
+ value.credentialIsolation === "environment" ||
1315
+ value.credentialIsolation === "environment_and_files") &&
1316
+ (value.processControl === undefined ||
1317
+ value.processControl === "process" ||
1318
+ value.processControl === "process_tree") &&
1319
+ (value.durability === undefined || value.durability === "critical") &&
1320
+ (value.termination === undefined || isChildRunTerminationRequirement(value.termination)));
1321
+ }
1322
+ function isChildRunTerminationRequirement(value) {
1323
+ return (isRecord(value) &&
1324
+ Object.keys(value).every((key) => key === "kill" || key === "timeout" || key === "pty") &&
1325
+ (value.kill === undefined || value.kill === "process" || value.kill === "process_tree") &&
1326
+ (value.timeout === undefined || typeof value.timeout === "boolean") &&
1327
+ (value.pty === undefined || typeof value.pty === "boolean"));
1328
+ }
1329
+ export function foldChildRunLifecycleStatus(current, type) {
1330
+ if (current === "terminalizing") {
1331
+ throw new CoreMindError("run_state_corrupt", "Child Run terminalizing 不是可持久恢复状态");
1332
+ }
1333
+ if (current === "joined") {
1334
+ throw new CoreMindError("run_state_corrupt", "Child Run joined 后出现新的生命周期 Fact");
1335
+ }
1336
+ if (current === "terminal" || current === "paused" || current === "orphaned") {
1337
+ if (type === "parent_joined")
1338
+ return "joined";
1339
+ throw new CoreMindError("run_state_corrupt", "Child Run 已有结果后出现非法生命周期倒退");
1340
+ }
1341
+ if (type === "child_cancel_requested")
1342
+ return current;
1343
+ if (type === "child_orphaned")
1344
+ return "orphaned";
1345
+ switch (type) {
1346
+ case "child_created":
1347
+ if (current !== "recorded")
1348
+ break;
1349
+ return "created";
1350
+ case "child_running":
1351
+ if (current !== "created")
1352
+ break;
1353
+ return "running";
1354
+ case "child_terminal":
1355
+ if (current !== "running")
1356
+ break;
1357
+ return "terminal";
1358
+ case "child_paused":
1359
+ if (current !== "running")
1360
+ break;
1361
+ return "paused";
1362
+ case "parent_joined":
1363
+ throw new CoreMindError("run_state_corrupt", "Child Run 尚无结果时不能 parent_joined");
1364
+ }
1365
+ throw new CoreMindError("run_state_corrupt", `Child Run ${current} 状态不能接受 ${type} Fact`);
1366
+ }
1367
+ function isRecord(value) {
1368
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1369
+ }
1370
+ function isStringArray(value) {
1371
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
1372
+ }
1373
+ //# sourceMappingURL=child-run.js.map