coremind-runtime 0.7.1 → 1.0.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 (73) hide show
  1. package/README.md +1 -1
  2. package/dist/active-run-binding.d.ts.map +1 -1
  3. package/dist/active-run-binding.js +4 -0
  4. package/dist/active-run-binding.js.map +1 -1
  5. package/dist/agent-factory.d.ts.map +1 -1
  6. package/dist/agent-factory.js +35 -6
  7. package/dist/agent-factory.js.map +1 -1
  8. package/dist/budget.d.ts +4 -0
  9. package/dist/budget.d.ts.map +1 -1
  10. package/dist/budget.js +28 -0
  11. package/dist/budget.js.map +1 -1
  12. package/dist/chat-session.d.ts.map +1 -1
  13. package/dist/chat-session.js +3 -0
  14. package/dist/chat-session.js.map +1 -1
  15. package/dist/checkpoint.d.ts +1 -0
  16. package/dist/checkpoint.d.ts.map +1 -1
  17. package/dist/checkpoint.js +19 -1
  18. package/dist/checkpoint.js.map +1 -1
  19. package/dist/control-inbox.d.ts +14 -0
  20. package/dist/control-inbox.d.ts.map +1 -1
  21. package/dist/control-inbox.js +27 -3
  22. package/dist/control-inbox.js.map +1 -1
  23. package/dist/host-verification.d.ts +45 -0
  24. package/dist/host-verification.d.ts.map +1 -0
  25. package/dist/host-verification.js +150 -0
  26. package/dist/host-verification.js.map +1 -0
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/internal.d.ts +1 -1
  31. package/dist/internal.d.ts.map +1 -1
  32. package/dist/internal.js +1 -1
  33. package/dist/internal.js.map +1 -1
  34. package/dist/loop-runner.d.ts +9 -0
  35. package/dist/loop-runner.d.ts.map +1 -1
  36. package/dist/loop-runner.js +27 -0
  37. package/dist/loop-runner.js.map +1 -1
  38. package/dist/projection.d.ts +2 -0
  39. package/dist/projection.d.ts.map +1 -1
  40. package/dist/projection.js +111 -104
  41. package/dist/projection.js.map +1 -1
  42. package/dist/run-context.d.ts +6 -5
  43. package/dist/run-context.d.ts.map +1 -1
  44. package/dist/run-context.js +33 -15
  45. package/dist/run-context.js.map +1 -1
  46. package/dist/run-state.d.ts +1 -1
  47. package/dist/run-state.d.ts.map +1 -1
  48. package/dist/run-state.js +2 -0
  49. package/dist/run-state.js.map +1 -1
  50. package/dist/runtime.d.ts +7 -0
  51. package/dist/runtime.d.ts.map +1 -1
  52. package/dist/runtime.js +168 -37
  53. package/dist/runtime.js.map +1 -1
  54. package/dist/session-maintenance.d.ts +19 -0
  55. package/dist/session-maintenance.d.ts.map +1 -0
  56. package/dist/session-maintenance.js +102 -0
  57. package/dist/session-maintenance.js.map +1 -0
  58. package/dist/session.d.ts +4 -2
  59. package/dist/session.d.ts.map +1 -1
  60. package/dist/session.js +21 -3
  61. package/dist/session.js.map +1 -1
  62. package/dist/tool-policy.d.ts.map +1 -1
  63. package/dist/tool-policy.js +27 -4
  64. package/dist/tool-policy.js.map +1 -1
  65. package/dist/trace.d.ts +3 -1
  66. package/dist/trace.d.ts.map +1 -1
  67. package/dist/trace.js +78 -8
  68. package/dist/trace.js.map +1 -1
  69. package/dist/turn-tracker.d.ts +2 -0
  70. package/dist/turn-tracker.d.ts.map +1 -1
  71. package/dist/turn-tracker.js +15 -0
  72. package/dist/turn-tracker.js.map +1 -1
  73. package/package.json +5 -5
package/dist/runtime.js CHANGED
@@ -21,6 +21,7 @@ import { CoreMindError, isErrorCode } from "./errors.js";
21
21
  import { extractAgentError, extractText } from "./events.js";
22
22
  import { normalizeExecutionError } from "./execution-error.js";
23
23
  import { enforceExecutionSecurity } from "./execution-security.js";
24
+ import { HostVerificationGate } from "./host-verification.js";
24
25
  import { receiptId } from "./ids.js";
25
26
  import { claimInput, completeInput, createInputReceipt, discardInput, inputFingerprint, newInputId, receiptStatusOf, } from "./input-receipt.js";
26
27
  import { LifecycleExtensionHost, } from "./lifecycle-extension.js";
@@ -41,11 +42,12 @@ import { FileRunStore, fingerprintRunConfig, RunStateJournal, } from "./run-stat
41
42
  import { RunTerminalizer } from "./run-terminalizer.js";
42
43
  import { registerCoreMindRuntimeInstance } from "./runtime-instance-authority.js";
43
44
  import { CoreMindSession } from "./session.js";
45
+ import { compactSessionInRun } from "./session-maintenance.js";
44
46
  import { createRunSnapshot } from "./snapshot.js";
45
47
  import { ToolExecutionEngine } from "./tool-call-lifecycle.js";
46
48
  import { toolCapabilityCallKey } from "./tool-capability-identity.js";
47
49
  import { ToolPolicy } from "./tool-policy.js";
48
- import { TraceRecorder } from "./trace.js";
50
+ import { redactSensitiveText, TraceRecorder } from "./trace.js";
49
51
  import { TurnTracker } from "./turn-tracker.js";
50
52
  import { canonicalizeWorkspace, WorkspaceLeaseService, } from "./workspace-lease.js";
51
53
  /**
@@ -285,14 +287,16 @@ export class CoreMindRuntime {
285
287
  if (!buildDriver)
286
288
  return undefined;
287
289
  const context = runContextFor(this);
288
- const harness = context.harnessFor(name, stepId);
290
+ const executionId = randomUUID();
291
+ const turnTracker = new TurnTracker();
292
+ const harness = context.harnessFor(name, stepId, executionId);
289
293
  const agent = buildDriver({
290
- onEvent,
294
+ onEvent: (event) => onEvent(turnTracker.withTurnId(event)),
291
295
  // 恢复视图只注入主 agent(会话归属者)
292
296
  sessionMessages: name === this.mainAgentName ? this.sessionMessages : undefined,
293
297
  harness,
294
298
  });
295
- context.registerAgent(name, agent);
299
+ context.registerAgent(name, agent, executionId);
296
300
  return agent;
297
301
  }
298
302
  /** 返回命名 Agent 在项目 Provider 内的固定模型与参数快照。 */
@@ -306,7 +310,7 @@ export class CoreMindRuntime {
306
310
  ? configuredOptions
307
311
  : {
308
312
  ...configuredOptions,
309
- maxTokens: Math.min(configuredOptions?.maxTokens ?? tokenLimit, tokenLimit),
313
+ maxTokens: Math.min(configuredOptions?.maxTokens ?? model.maxTokens, tokenLimit),
310
314
  };
311
315
  return {
312
316
  providerId: model.provider,
@@ -347,6 +351,12 @@ export class CoreMindRuntime {
347
351
  * 因此 chat/TUI 与无头 run 共用预算、权限、checkpoint、Trace 和失败语义。
348
352
  */
349
353
  async runAgentTurn(agentName, message, history, events, signal) {
354
+ if (this.config.loop?.verify.mode === "host") {
355
+ throw new CoreMindError("loop_config_invalid", "宿主验收模式须通过 run() 与绑定该 Run 的控制接口执行");
356
+ }
357
+ if (executionSlotFor(this).running) {
358
+ throw new CoreMindError("concurrent_run", "同一 Runtime 不支持并发 run() 与交互 Turn");
359
+ }
350
360
  if (!this.agentConfigs.has(agentName)) {
351
361
  throw new CoreMindError("unknown_agent", `配置中没有可用的 agent:${agentName}`);
352
362
  }
@@ -391,12 +401,21 @@ export class CoreMindRuntime {
391
401
  /** 执行:有 workflow 走编排,否则单 agent 直答。返回结果含质量摘要 */
392
402
  async run() {
393
403
  const slot = executionSlotFor(this);
404
+ if (slot.running || boundDelegationExecutor(this)) {
405
+ throw new CoreMindError("concurrent_run", "同一 Runtime 不支持并发执行");
406
+ }
407
+ slot.running = true;
394
408
  slot.kernel ??= new RunKernel({ execute: (context) => this.executeRunBody(context) });
395
409
  try {
396
410
  return await slot.kernel.run();
397
411
  }
398
412
  finally {
399
- await settleProtocolToolResultFacts(this);
413
+ try {
414
+ await settleProtocolToolResultFacts(this);
415
+ }
416
+ finally {
417
+ slot.running = false;
418
+ }
400
419
  }
401
420
  }
402
421
  /** 在活动父 Run 上创建类型化 Child Run;未配置或尚未启动时失败关闭。 */
@@ -454,6 +473,9 @@ export class CoreMindRuntime {
454
473
  }
455
474
  /** 接收已类型化控制;ACK 只由当前 Run 的持久 ControlInbox 产生。 */
456
475
  async acceptControl(command) {
476
+ if (command.type === "verification" && !this.currentControlInbox()) {
477
+ throw new CoreMindError("control_unavailable", "当前没有可接收宿主验收回复的 Run");
478
+ }
457
479
  for (let attempt = 0; attempt < 5_000; attempt++) {
458
480
  const inbox = this.currentControlInbox();
459
481
  if (inbox)
@@ -791,7 +813,10 @@ export class CoreMindRuntime {
791
813
  const runId = (resumePlan?.runId ?? this.options.runId ?? randomUUID());
792
814
  context.attachRunId(runId);
793
815
  const effectiveInitialPrompt = resumePlan?.initialPrompt ?? this.options.initialPrompt;
794
- const journal = new RunStateJournal(runId, runStore, resumePlan?.nextJournalSequence ?? 0);
816
+ const admissionRecords = !resumePlan && this.options.protocolStart ? await runStore.read(runId) : [];
817
+ if (admissionRecords.some((record) => record.kind !== "admission"))
818
+ throw new CoreMindError("run_id_conflict", "新 Run 已存在执行事实");
819
+ const journal = new RunStateJournal(runId, runStore, resumePlan?.nextJournalSequence ?? admissionRecords.at(-1)?.sequence ?? 0);
795
820
  context.attachJournal(journal);
796
821
  const operation = resumePlan && resumePlan.operationRecords.length > 0
797
822
  ? restoreDurableOperation(resumePlan.operationRecords)
@@ -865,11 +890,33 @@ export class CoreMindRuntime {
865
890
  throw new CoreMindError("operation_not_resumable", `操作 ${operation.snapshot().operationId} 处于 ${operation.snapshot().state},不能继续执行`);
866
891
  }
867
892
  await journal.flush();
893
+ const hostVerification = this.config.loop?.verify.mode === "host"
894
+ ? new HostVerificationGate({
895
+ runId,
896
+ journal,
897
+ records: await runStore.read(runId),
898
+ timeoutMs: this.config.loop.verify.timeoutMs ?? 60_000,
899
+ notify: this.options.onVerification,
900
+ applyPending: () => context.currentControlInbox().applyPending("verification"),
901
+ })
902
+ : undefined;
868
903
  context.attachControlInbox(new ControlInbox({
869
904
  runId,
870
905
  journal,
871
906
  records: await runStore.read(runId),
872
- apply: (command) => this.applyRunControl(command, context, deferredTerminalError),
907
+ apply: (command) => {
908
+ if (command.type === "verification") {
909
+ return Promise.resolve(hostVerification?.apply(command) ?? {
910
+ status: "rejected",
911
+ reason: "当前 Run 未启用宿主验证",
912
+ });
913
+ }
914
+ if (hostVerification?.waiting &&
915
+ (command.type === "steering" || command.type === "follow_up")) {
916
+ return Promise.resolve({ status: "rejected", reason: "宿主验收期间不能改变候选输入" });
917
+ }
918
+ return this.applyRunControl(command, context, deferredTerminalError);
919
+ },
873
920
  }));
874
921
  const capabilityByCallId = new Map();
875
922
  const trace = new TraceRecorder(runId, (entry) => {
@@ -925,6 +972,12 @@ export class CoreMindRuntime {
925
972
  };
926
973
  const recordEvent = (event) => {
927
974
  let enriched = turnTracker.withTurnId(event);
975
+ if ((enriched.type === "tool_result" || enriched.type === "tool_lifecycle") &&
976
+ enriched.callId) {
977
+ const call = effectBindingByCall.get(toolCapabilityCallKey(enriched.agent, enriched.stepId, enriched.callId));
978
+ if (call)
979
+ enriched = { ...enriched, turnId: call.turnId };
980
+ }
928
981
  if (enriched.type === "tool_call" && enriched.callId && enriched.turnId) {
929
982
  context.recordToolCall({
930
983
  agent: enriched.agent,
@@ -953,7 +1006,7 @@ export class CoreMindRuntime {
953
1006
  }
954
1007
  const binding = createEffectReceiptBinding({
955
1008
  runId,
956
- turnId: enriched.turnId,
1009
+ turnId: call.turnId,
957
1010
  agent: enriched.agent,
958
1011
  ...(enriched.stepId ? { stepId: enriched.stepId } : {}),
959
1012
  callId: enriched.callId,
@@ -967,11 +1020,14 @@ export class CoreMindRuntime {
967
1020
  throw new CoreMindError("effect_receipt_conflict", `EffectReceipt ${enriched.idempotencyKey} 关联了不同的 Run、Turn、Call、参数或 Capability`);
968
1021
  }
969
1022
  effectBindingByReceipt.set(enriched.idempotencyKey, binding);
970
- enriched = { ...enriched, binding };
1023
+ enriched = { ...enriched, turnId: call.turnId, binding };
971
1024
  }
972
1025
  // 事件准入(规格 03 §3):abort 后的迟到终态事实不入 trace/collected/回调(ADR:不入 Trace 或 journal)
973
1026
  if (!journal.admitEvent(enriched))
974
1027
  return;
1028
+ if (enriched.type === "step_output" && redactSensitiveText(enriched.text) !== enriched.text) {
1029
+ throw new CoreMindError("redaction_failed", "步骤输出包含凭据,已阻止持久化与候选验收");
1030
+ }
975
1031
  collected.push(enriched);
976
1032
  trace.record(enriched);
977
1033
  userEvents(enriched);
@@ -1260,20 +1316,21 @@ export class CoreMindRuntime {
1260
1316
  });
1261
1317
  const deniedAgents = new Set();
1262
1318
  const activeRunContext = context;
1263
- context.setHarnessFactory((agentName, stepId) => {
1319
+ context.setHarnessFactory((agentName, stepId, executionId) => {
1264
1320
  const agentModel = this.agentModels.get(agentName) ?? this.providerRuntime.model;
1265
1321
  let contextWorkingSet;
1266
1322
  let providerRequestOrdinal = 0;
1267
1323
  let pendingProviderCapabilityFingerprint;
1268
1324
  return {
1269
1325
  maxRetries: loop ? 0 : limits.maxRetries,
1270
- registerContextContract: (contract) => contextContracts.set(agentName, contract),
1326
+ registerContextContract: (contract) => contextContracts.set(executionId, contract),
1271
1327
  beforeModelRequest: () => {
1272
1328
  throwIfContextFailed();
1273
1329
  throwIfDelegationBlocksModel();
1330
+ budget.beforeModelRequest();
1274
1331
  },
1275
1332
  onModelRequestDispatched: ({ providerId, modelId, messages }) => {
1276
- const contract = contextContracts.get(agentName);
1333
+ const contract = contextContracts.get(executionId);
1277
1334
  if (!contract || !pendingProviderCapabilityFingerprint) {
1278
1335
  throw new ContextLifecycleError("Provider 请求缺少已解析的 Context Working Set", "budget_exhausted", "context_budget_exhausted");
1279
1336
  }
@@ -1321,7 +1378,7 @@ export class CoreMindRuntime {
1321
1378
  stepId,
1322
1379
  messageCount: messages.length,
1323
1380
  });
1324
- const contract = contextContracts.get(agentName);
1381
+ const contract = contextContracts.get(executionId);
1325
1382
  if (!contract) {
1326
1383
  recordContextFailure(new ContextLifecycleError(`Agent ${agentName} 没有注册可预算的稳定 Context 合同`, "invalid_budget", "context_capability_conflict"), messages.length);
1327
1384
  return messages;
@@ -1495,7 +1552,7 @@ export class CoreMindRuntime {
1495
1552
  status: "completed",
1496
1553
  result: { recoveryDisposition: recoveryDispositionFor(resolvedCapability) },
1497
1554
  });
1498
- const registeredCall = activeRunContext.toolCall(agentName, context.toolCall.callId);
1555
+ const registeredCall = activeRunContext.toolCall(agentName, context.toolCall.callId, stepId);
1499
1556
  const turnId = registeredCall?.turnId;
1500
1557
  if (context.toolCall.tool === DELEGATION_DISPOSITION_TOOL_NAME && turnId) {
1501
1558
  delegationDispositionTurns.add(turnId);
@@ -1534,7 +1591,7 @@ export class CoreMindRuntime {
1534
1591
  };
1535
1592
  }
1536
1593
  }
1537
- if (deniedAgents.has(agentName)) {
1594
+ if (deniedAgents.has(executionId)) {
1538
1595
  const reason = "同一工具批次已有请求被拒绝";
1539
1596
  await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, reason);
1540
1597
  return { block: true, reason, terminate: true };
@@ -1610,7 +1667,7 @@ export class CoreMindRuntime {
1610
1667
  }
1611
1668
  }
1612
1669
  await toolExecutionEngine.blockBeforeExecution(lifecycleIdentity, decision.reason);
1613
- deniedAgents.add(agentName);
1670
+ deniedAgents.add(executionId);
1614
1671
  emit({
1615
1672
  type: "policy_denied",
1616
1673
  agent: agentName,
@@ -1647,7 +1704,7 @@ export class CoreMindRuntime {
1647
1704
  approvalAllowed: true,
1648
1705
  });
1649
1706
  if (extensionDecision?.denied) {
1650
- deniedAgents.add(agentName);
1707
+ deniedAgents.add(executionId);
1651
1708
  const reason = extensionDecision.denied.reason;
1652
1709
  emit({
1653
1710
  type: "policy_denied",
@@ -1750,7 +1807,7 @@ export class CoreMindRuntime {
1750
1807
  ?.pathFields,
1751
1808
  });
1752
1809
  if (checkpoints.length > 0) {
1753
- checkpointByCallId.set(context.toolCall.callId, checkpoints.map((checkpoint) => checkpoint.checkpointId));
1810
+ checkpointByCallId.set(callKey, checkpoints.map((checkpoint) => checkpoint.checkpointId));
1754
1811
  for (const checkpoint of checkpoints) {
1755
1812
  await journal.appendFact("checkpoint", checkpoint, { durability: "critical" });
1756
1813
  emit({
@@ -1879,9 +1936,9 @@ export class CoreMindRuntime {
1879
1936
  callId: context.toolCall.callId,
1880
1937
  });
1881
1938
  }
1882
- const checkpointIds = checkpointByCallId.get(context.toolCall.callId);
1939
+ const checkpointIds = checkpointByCallId.get(toolCapabilityCallKey(agentName, stepId, context.toolCall.callId));
1883
1940
  const checkpointId = checkpointIds?.[0];
1884
- checkpointByCallId.delete(context.toolCall.callId);
1941
+ checkpointByCallId.delete(toolCapabilityCallKey(agentName, stepId, context.toolCall.callId));
1885
1942
  if (checkpointIds) {
1886
1943
  try {
1887
1944
  await Promise.all(checkpointIds.map((storedCheckpointId) => checkpointManager.markApplied(storedCheckpointId)));
@@ -1915,16 +1972,16 @@ export class CoreMindRuntime {
1915
1972
  });
1916
1973
  return checkpointFailure || adapterFailures.size > 0 ? { terminate: true } : budgetResult;
1917
1974
  },
1918
- shouldStopAfterTurn: () => deniedAgents.has(agentName),
1975
+ shouldStopAfterTurn: () => deniedAgents.has(executionId),
1919
1976
  throwIfDenied: () => {
1920
- if (deniedAgents.has(agentName)) {
1977
+ if (deniedAgents.has(executionId)) {
1921
1978
  throw new CoreMindError("loop_paused", stepId
1922
1979
  ? `步骤 ${stepId} 的工具请求未获批准`
1923
1980
  : `Agent ${agentName} 的工具请求未获批准`);
1924
1981
  }
1925
1982
  },
1926
1983
  onObservation: (observation) => {
1927
- const driver = context.agent(agentName);
1984
+ const driver = context.agent(agentName, executionId);
1928
1985
  if (observation.type === "turn_end" &&
1929
1986
  "contextOverflow" in observation &&
1930
1987
  observation.contextOverflow) {
@@ -1954,6 +2011,7 @@ export class CoreMindRuntime {
1954
2011
  throw deferredTerminalError;
1955
2012
  }
1956
2013
  if (loop) {
2014
+ const engineeringEvidence = loop.verify.mode === "host" ? undefined : loop.verify.evidence;
1957
2015
  let retryCount = resumePlan?.previousTrace.filter((entry) => entry.event.type === "retry" && entry.event.scope === "provider").length ?? 0;
1958
2016
  const runner = new LoopRunner({
1959
2017
  runId,
@@ -1968,9 +2026,20 @@ export class CoreMindRuntime {
1968
2026
  journal.loop(snapshot);
1969
2027
  await journal.flush();
1970
2028
  },
1971
- verifyEvidence: loop.verify.evidence
2029
+ verifyHost: hostVerification
2030
+ ? async (request) => {
2031
+ if (journal.isAborted())
2032
+ throw new CoreMindError("aborted", "验收前 Run 已中止");
2033
+ await journal.flush("critical");
2034
+ const decision = await hostVerification.verify(request);
2035
+ if (journal.isAborted())
2036
+ throw new CoreMindError("aborted", "验收期间 Run 已中止");
2037
+ return decision;
2038
+ }
2039
+ : undefined,
2040
+ verifyEvidence: engineeringEvidence
1972
2041
  ? ({ stepId, textPassed }) => {
1973
- const report = assessRuntimeEngineeringEvidence(collected, loop.verify.evidence, stepId);
2042
+ const report = assessRuntimeEngineeringEvidence(collected, engineeringEvidence, stepId);
1974
2043
  emit({ type: "engineering_evidence", stepId, textPassed, ...report });
1975
2044
  return report.passed;
1976
2045
  }
@@ -2040,7 +2109,10 @@ export class CoreMindRuntime {
2040
2109
  }
2041
2110
  transcript = extractText(messages.slice(messageCursor));
2042
2111
  return { outputs: new Map(), transcript };
2043
- }, (error) => activeLoopRunner?.interrupt(error)));
2112
+ }, (error) => {
2113
+ hostVerification?.interrupt(error);
2114
+ return activeLoopRunner?.interrupt(error);
2115
+ }));
2044
2116
  if (delegationDispositionFailure)
2045
2117
  throw delegationDispositionFailure;
2046
2118
  if (delegationPolicyFailure)
@@ -2093,8 +2165,67 @@ export class CoreMindRuntime {
2093
2165
  }
2094
2166
  }
2095
2167
  finally {
2168
+ hostVerification?.interrupt(new CoreMindError("run_already_finished", "Run 已结束验收等待"));
2096
2169
  context.setHarnessFactory(undefined);
2097
2170
  }
2171
+ let sessionFile;
2172
+ let sessionPersisted = false;
2173
+ if (terminalError === undefined && this.config.session?.enabled && this.options.sessionId) {
2174
+ try {
2175
+ sessionFile = await this.persistSession();
2176
+ sessionPersisted = true;
2177
+ const session = context.sessionHandle();
2178
+ const remainingMs = limits.runTimeoutMs > 0
2179
+ ? Math.floor(limits.runTimeoutMs - (performance.now() - started))
2180
+ : 0;
2181
+ if (this.options.signal?.aborted || journal.isAborted()) {
2182
+ journal.markAborted(knownTurnIdsFrom(collected));
2183
+ this.abortAll();
2184
+ throw new CoreMindError("aborted", "会话维护前运行已取消");
2185
+ }
2186
+ if (session &&
2187
+ this.config.session.compact &&
2188
+ !this.options.signal?.aborted &&
2189
+ (limits.runTimeoutMs === 0 || remainingMs > 0)) {
2190
+ await this.runWithGuard(remainingMs, journal, () => knownTurnIdsFrom(collected), async () => {
2191
+ const activity = this.executionEnvironment.beginActivity({
2192
+ id: `session-maintenance:${runId}`,
2193
+ kind: "network",
2194
+ });
2195
+ const signal = this.options.signal
2196
+ ? AbortSignal.any([activity.signal, this.options.signal])
2197
+ : activity.signal;
2198
+ try {
2199
+ await compactSessionInRun({
2200
+ runId,
2201
+ agent: this.mainAgentName,
2202
+ session,
2203
+ models: this.providerRuntime.models,
2204
+ model: this.agentModels.get(this.mainAgentName) ?? this.providerRuntime.model,
2205
+ apiKeyOverride: this.providerRuntime.apiKeyOverride,
2206
+ budget,
2207
+ journal,
2208
+ signal,
2209
+ emit,
2210
+ });
2211
+ }
2212
+ finally {
2213
+ activity.settle();
2214
+ }
2215
+ });
2216
+ }
2217
+ else if (session && this.config.session.compact) {
2218
+ await session.appendMaintenanceRecord({
2219
+ runId,
2220
+ status: "skipped",
2221
+ reason: "deadline_exhausted",
2222
+ });
2223
+ }
2224
+ }
2225
+ catch (error) {
2226
+ terminalError = error;
2227
+ }
2228
+ }
2098
2229
  while (lifecycleFinalizers.size > 0) {
2099
2230
  await Promise.allSettled([...lifecycleFinalizers]);
2100
2231
  }
@@ -2161,13 +2292,13 @@ export class CoreMindRuntime {
2161
2292
  else if (terminalError === undefined && deferredTerminalError) {
2162
2293
  terminalError = deferredTerminalError;
2163
2294
  }
2164
- let sessionFile;
2165
2295
  // D-4 方案 A:abort 后也写会话树(只写已确认部分,竞态赢家文本丢弃);
2166
2296
  // 审批拒绝等 paused(loop_paused)是可在用户处置后继续的暂停态,同样应落盘已确认部分,
2167
2297
  // 使持久事实可重建该 Run 的请求(规格 01 §2 请求重建契约的适用范围)
2168
2298
  const terminalCode = terminalError instanceof CoreMindError ? terminalError.code : undefined;
2169
2299
  context.setSessionPersistPaused(terminalCode === "loop_paused");
2170
- if (terminalError === undefined || journal.isAborted() || context.shouldTrimRejectedTrail()) {
2300
+ if (!sessionPersisted &&
2301
+ (terminalError === undefined || journal.isAborted() || context.shouldTrimRejectedTrail())) {
2171
2302
  try {
2172
2303
  sessionFile = await this.persistSession();
2173
2304
  }
@@ -2531,8 +2662,8 @@ export class CoreMindRuntime {
2531
2662
  if (!sessionId || !session?.enabled)
2532
2663
  return undefined;
2533
2664
  const context = runContextFor(this);
2534
- const main = context.agent(this.mainAgentName);
2535
- if (!main)
2665
+ const mains = context.agentsNamed(this.mainAgentName);
2666
+ if (mains.length === 0)
2536
2667
  return undefined;
2537
2668
  const cm = context.sessionHandle() ??
2538
2669
  (await CoreMindSession.open({
@@ -2540,8 +2671,10 @@ export class CoreMindRuntime {
2540
2671
  sessionId,
2541
2672
  cwd: this.options.cwd ?? process.cwd(),
2542
2673
  }));
2674
+ if (!context.sessionHandle())
2675
+ context.attachSession(cm, projectBranchMessages(await cm.branchEntries()));
2543
2676
  // 只追加本轮新增:恢复历史已落盘;请求级压缩的摘要与保留区已由压缩条目代表
2544
- let messages = main.messages().slice(context.compactedPrefixEnd() ?? this.resumedContextLength);
2677
+ let messages = mains.flatMap((main) => main.messages().slice(context.compactedPrefixEnd() ?? this.resumedContextLength));
2545
2678
  if (context.currentJournal()?.isAborted()) {
2546
2679
  // D-4 方案 A:abort 后只写已确认部分——去掉尾部未正常终止的 assistant 消息(竞态赢家文本)
2547
2680
  messages = trimUnconfirmedTail(messages);
@@ -2551,11 +2684,6 @@ export class CoreMindRuntime {
2551
2684
  messages = trimRejectedTrail(messages);
2552
2685
  }
2553
2686
  await cm.appendMessages(messages);
2554
- // P2b:配置 session.compact 时,上下文超预算自动压缩(LLM 摘要,消耗 token)
2555
- if (session.compact) {
2556
- const mainModel = this.agentModels.get(this.mainAgentName) ?? this.providerRuntime.model;
2557
- await cm.maybeCompact(this.providerRuntime.models, mainModel, mainModel.contextWindow);
2558
- }
2559
2687
  return cm.filePath;
2560
2688
  }
2561
2689
  }
@@ -2787,6 +2915,9 @@ async function assertRuntimeChildPolicyAuthority(input) {
2787
2915
  }
2788
2916
  try {
2789
2917
  await resolveExecutionEnvironment(executionEnvironment, policy.environment);
2918
+ if (executionEnvironment.hostNetwork && (tools.has("web-fetch") || tools.has("web-search"))) {
2919
+ await resolveExecutionEnvironment(executionEnvironment.hostNetwork, policy.environment);
2920
+ }
2790
2921
  }
2791
2922
  catch (error) {
2792
2923
  throw new CoreMindError("child_run_policy_escalation", error instanceof Error ? error.message : String(error));