evolcore 0.0.41 → 0.0.42

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 (190) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/bin/codex-managed-hook.mjs +9 -5
  3. package/dist/agents/baseagent.js +156 -16
  4. package/dist/agents/claude-runner.js +10 -3
  5. package/dist/agents/codex/catalog.js +8 -4
  6. package/dist/agents/codex-runner.js +236 -59
  7. package/dist/agents/ecagent-runner.js +82 -13
  8. package/dist/aun/aid/agentmd.js +106 -27
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +65 -13
  11. package/dist/aun/aid/identity.js +70 -4
  12. package/dist/aun/aid/index.js +2 -2
  13. package/dist/aun/service-proxy.js +25 -1
  14. package/dist/channels/aun.js +242 -209
  15. package/dist/channels/dingtalk.js +1 -1
  16. package/dist/channels/feishu.js +1 -1
  17. package/dist/channels/qqbot.js +1 -1
  18. package/dist/channels/wechat.js +1 -1
  19. package/dist/channels/wecom.js +1 -1
  20. package/dist/cli/agent-command.js +183 -3
  21. package/dist/cli/agent-create.js +92 -86
  22. package/dist/cli/agent.js +136 -1
  23. package/dist/cli/aun-commands.js +137 -35
  24. package/dist/cli/bench.js +8 -2
  25. package/dist/cli/command-log.js +1 -1
  26. package/dist/cli/daemon-commands.js +235 -51
  27. package/dist/cli/debug-mode.js +1 -1
  28. package/dist/cli/directory.js +170 -0
  29. package/dist/cli/index.js +40 -30
  30. package/dist/cli/init-channel.js +4 -4
  31. package/dist/cli/init.js +47 -32
  32. package/dist/cli/managed-command-guard.js +4 -1
  33. package/dist/cli/model.js +27 -18
  34. package/dist/cli/pa-workspace-command.js +191 -0
  35. package/dist/cli/{contact.js → peer.js} +19 -25
  36. package/dist/cli/restart-monitor.js +11 -4
  37. package/dist/cli/thread-command.js +47 -18
  38. package/dist/cli/version.js +18 -18
  39. package/dist/config/access-policy.js +29 -12
  40. package/dist/config/boot-log.js +65 -10
  41. package/dist/config/builtin-roles.js +2 -4
  42. package/dist/config/config-field-policy.js +3 -0
  43. package/dist/config/config-manager.js +28 -20
  44. package/dist/config/{contact-bind-code.js → peer-bind-code.js} +6 -6
  45. package/dist/config/{contact-book-store.js → peer-book-store.js} +75 -75
  46. package/dist/config/{contact-book-v2-startup.js → peer-book-v2-startup.js} +2 -2
  47. package/dist/config/{contact-book.js → peer-book.js} +47 -47
  48. package/dist/config/peer-operation-service.js +132 -0
  49. package/dist/config/{contact-request-service.js → peer-request-service.js} +90 -90
  50. package/dist/config/peer-role-resolver.js +3 -3
  51. package/dist/config/providers-config.js +17 -8
  52. package/dist/config/providers.js +1 -1
  53. package/dist/config/schema-migration.js +336 -39
  54. package/dist/core/agent-application-service.js +8 -2
  55. package/dist/core/agent-create-status.js +4 -5
  56. package/dist/core/agent-ipc-registration.js +5 -4
  57. package/dist/core/agent-runtime.js +30 -17
  58. package/dist/core/auth/operation-authorizer.js +0 -24
  59. package/dist/core/auth/operation-catalog.js +4 -20
  60. package/dist/core/baseagent-loader.js +27 -3
  61. package/dist/core/bootstrap-service.js +5 -22
  62. package/dist/core/capability/capability-manager.js +52 -35
  63. package/dist/core/channel-loader.js +43 -2
  64. package/dist/core/channel-runtime.js +2 -2
  65. package/dist/core/command/agent-control.js +54 -18
  66. package/dist/core/command/command-handler.js +92 -72
  67. package/dist/core/command/connect-menu.js +35 -42
  68. package/dist/core/command/daemon-diagnostics.js +41 -5
  69. package/dist/core/command/data-root-error.js +10 -0
  70. package/dist/core/command/data-root-resolver.js +53 -13
  71. package/dist/core/command/menu-catalog.js +1 -0
  72. package/dist/core/command/menu-handler.js +163 -65
  73. package/dist/core/command/menu-protocol.js +52 -0
  74. package/dist/core/command/pa-workspace-calendar.js +223 -0
  75. package/dist/core/command/pa-workspace-store.js +459 -0
  76. package/dist/core/command/role-menu.js +2 -2
  77. package/dist/core/command/slash-gate.js +1 -1
  78. package/dist/core/command/slash-handler.js +57 -41
  79. package/dist/core/daemon-lifecycle.js +90 -31
  80. package/dist/core/evolagent.js +6 -10
  81. package/dist/core/handoff/runtime.js +11 -4
  82. package/dist/core/host-snapshot.js +208 -0
  83. package/dist/core/initialization/service.js +152 -20
  84. package/dist/core/ipc-registration.js +33 -4
  85. package/dist/core/memory/batch-meta.js +27 -0
  86. package/dist/core/memory/consolidation-ops-records.js +44 -1
  87. package/dist/core/memory/consolidation.js +169 -27
  88. package/dist/core/message/aun-ipc-sender.js +2 -8
  89. package/dist/core/message/im-renderer.js +56 -3
  90. package/dist/core/message/message-admission.js +121 -124
  91. package/dist/core/message/message-bridge.js +38 -54
  92. package/dist/core/message/message-queue.js +7 -0
  93. package/dist/core/message/outbound.js +34 -9
  94. package/dist/core/message/response-engine.js +154 -73
  95. package/dist/core/model/catalog-service.js +1 -1
  96. package/dist/core/model/config-scope.js +2 -2
  97. package/dist/core/model/model-catalog.js +5 -4
  98. package/dist/core/model/model-diagnostics.js +6 -5
  99. package/dist/core/model/model-fallback.js +3 -6
  100. package/dist/core/model/model-permission.js +1 -1
  101. package/dist/core/ownership/owner-resolver.js +9 -9
  102. package/dist/core/permission/approval-gateway.js +1 -1
  103. package/dist/core/permission/ec-command-parser.js +2 -2
  104. package/dist/core/permission/tool-canonical.js +96 -46
  105. package/dist/core/permission/tool-error-code.js +41 -0
  106. package/dist/core/permission/tool-policy.js +71 -47
  107. package/dist/core/role/runtime-policy.js +1 -1
  108. package/dist/core/session/session-idle-monitor.js +10 -0
  109. package/dist/core/session/session-manager.js +2 -4
  110. package/dist/core/session/session-title.js +36 -8
  111. package/dist/core/system-session/memory.js +2 -7
  112. package/dist/core/thread/command-parser.js +6 -2
  113. package/dist/core/thread/ipc-operation.js +51 -36
  114. package/dist/core/thread/thread-operation.js +29 -61
  115. package/dist/core/thread/thread-service.js +57 -13
  116. package/dist/directory/canonical-digest.js +54 -0
  117. package/dist/directory/owner-directory-admission.js +114 -43
  118. package/dist/directory/owner-directory-agentmd-sync.js +89 -0
  119. package/dist/directory/owner-directory-cache.js +847 -459
  120. package/dist/directory/owner-directory-markdown.js +272 -0
  121. package/dist/directory/owner-directory-query-operation.js +195 -0
  122. package/dist/directory/owner-directory-remark-operation.js +147 -0
  123. package/dist/directory/owner-directory-remarks.js +145 -0
  124. package/dist/directory/owner-directory-scope.js +55 -0
  125. package/dist/directory/owner-directory-search.js +148 -0
  126. package/dist/directory/owner-directory-store.js +227 -0
  127. package/dist/eck/kit-renderer.js +1 -0
  128. package/dist/ecweb/basic-settings-service.js +4 -1
  129. package/dist/ecweb/message-context-service.js +13 -9
  130. package/dist/index.js +195 -37
  131. package/dist/ipc.js +86 -22
  132. package/dist/paths.js +11 -8
  133. package/dist/product.js +2 -0
  134. package/dist/proxy/manager.js +13 -2
  135. package/dist/proxy/service-supervisor.js +8 -1
  136. package/dist/trigger/history.js +23 -0
  137. package/dist/trigger/scheduler.js +3 -0
  138. package/dist/utils/atomic-write.js +21 -0
  139. package/dist/utils/cross-platform.js +35 -0
  140. package/dist/utils/ecweb-supervisor.js +42 -0
  141. package/dist/utils/error-utils.js +2 -1
  142. package/dist/utils/evolcore-version.js +19 -0
  143. package/dist/utils/host-info.js +242 -5
  144. package/dist/utils/instance-registry.js +28 -6
  145. package/dist/utils/logger.js +59 -14
  146. package/dist/utils/machine-info.js +46 -0
  147. package/dist/utils/process-introspect.js +166 -2
  148. package/dist/utils/startup-trace.js +245 -0
  149. package/ecagent/dist/agent-loop.js +27 -13
  150. package/ecagent/dist/harness/agent-harness.js +3 -3
  151. package/ecagent/dist/harness/types.d.ts +1 -0
  152. package/ecagent/dist/types.d.ts +1 -0
  153. package/kits/docs/INDEX.md +1 -1
  154. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +72 -0
  155. package/kits/docs/evolcore/INDEX.md +3 -2
  156. package/kits/docs/evolcore/agent-create.md +17 -27
  157. package/kits/docs/evolcore/agent.md +4 -1
  158. package/kits/docs/evolcore/aid.md +3 -1
  159. package/kits/docs/evolcore/config.md +16 -5
  160. package/kits/docs/evolcore/ctl.md +9 -0
  161. package/kits/docs/evolcore/ec-capabilities.md +19 -0
  162. package/kits/docs/evolcore/memory-consolidation-batches.md +79 -5
  163. package/kits/docs/evolcore/menu-exec-schema-commands.md +2 -1
  164. package/kits/docs/evolcore/menu-protocol.md +1 -0
  165. package/kits/docs/evolcore/model.md +13 -4
  166. package/kits/docs/evolcore/msg.md +1 -1
  167. package/kits/docs/evolcore/pa-workspace.md +51 -0
  168. package/kits/docs/evolcore/peer.md +73 -0
  169. package/kits/docs/evolcore/thread-chain.md +4 -1
  170. package/kits/eck_manifest.json +21 -0
  171. package/kits/rules/06-channel.md +1 -1
  172. package/kits/schemas/_meta.json +12 -1
  173. package/kits/schemas/agent-config.schema.16.json +6 -0
  174. package/kits/schemas/agent-config.schema.17.json +897 -0
  175. package/kits/schemas/daemon.schema.9.json +8 -1
  176. package/kits/skills/ec-agent-create/SKILL.md +2 -2
  177. package/kits/skills/ec-identity/SKILL.md +45 -27
  178. package/kits/skills/ec-service-proxy/SKILL.md +7 -2
  179. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +4 -5
  180. package/kits/skills/thread-ops/SKILL.md +11 -11
  181. package/kits/templates/bootstrap-welcome.md +3 -15
  182. package/kits/templates/message-fragments/item.md +1 -1
  183. package/kits/templates/system-fragments/bootstrap.md +24 -23
  184. package/kits/templates/system-fragments/commands.md +12 -5
  185. package/kits/templates/system-fragments/thread.md +18 -3
  186. package/package.json +6 -4
  187. package/dist/config/contact-operation-service.js +0 -235
  188. package/dist/directory/owner-directory-authorization.js +0 -309
  189. package/kits/docs/evolcore/contact.md +0 -78
  190. /package/dist/config/{contact-alias.js → peer-alias.js} +0 -0
@@ -1,4 +1,4 @@
1
- import { resolveAnthropicConfig, resolveEcagentConfig, resolveOpenaiConfig } from '../../agents/baseagent.js';
1
+ import { resolveAnthropicConfig, resolveRuntimeBaseagentModelSelection, resolveEcagentConfig, resolveOpenaiConfig } from '../../agents/baseagent.js';
2
2
  import { buildModelRequestHeaders } from '../../agents/request-identity.js';
3
3
  import { appendV1RequestPath } from '../../agents/request-identity.js';
4
4
  import { resolveEffective, resolveEffectiveFieldWithSource } from '../../config/config-manager.js';
@@ -155,22 +155,23 @@ export async function runModelCheck(input) {
155
155
  log(catalog.freshness !== 'fresh'
156
156
  ? { label: '模型列表', ok: false, detail: `目录已降级,来源 ${catalog.source}(${modelIds.length} 个)` }
157
157
  : { label: '模型列表', ok: true, detail: `来源: ${catalog.source},共 ${modelIds.length} 个模型` });
158
- // 模型只在 Agent 级配置,不按对端解析。
158
+ // Apply role policy after resolving Agent/defaults and local/runner fallbacks.
159
159
  const selector = { self: input.self };
160
160
  const modelResolution = resolveEffectiveFieldWithSource(`baseagents.${input.baseagent}.model`, selector, { cache: true });
161
+ const selection = await resolveRuntimeBaseagentModelSelection(input.baseagent, resolveEffective(selector, { cache: true }).baseagents?.[input.baseagent]);
161
162
  const modelDecision = constrainResolvedModelForRole({
162
163
  selfAid: input.self,
163
164
  role: input.role,
164
165
  baseagent: input.baseagent,
165
- model: modelResolution.value,
166
+ model: selection?.model ?? modelResolution.value,
166
167
  });
167
168
  const configuredModel = modelDecision.model;
168
169
  const configuredModelSource = modelDecision.constrained
169
170
  ? 'role'
170
- : modelResolution.source?.target;
171
+ : selection?.modelSource === 'configured' ? modelResolution.source?.target : selection?.modelSource;
171
172
  log(configuredModel
172
173
  ? { label: '配置模型', ok: true, detail: `${configuredModel}(来源: ${configuredModelSource ?? '未知'})` }
173
- : { label: '配置模型', ok: false, detail: 'Agent 级未配置模型,该 Agent 无模型可用(owner/admin 用 /model 设置)' });
174
+ : { label: '配置模型', ok: false, detail: '无法解析当前基座的模型' });
174
175
  const probeResults = [];
175
176
  if (baseUrl) {
176
177
  const aliases = new Map();
@@ -1,6 +1,6 @@
1
1
  import { catalogEfforts, getCatalog, getProviderCatalog, resolveCatalogModel } from './model-catalog.js';
2
2
  import { resolveEffective } from '../../config/config-manager.js';
3
- import { providerServiceTypeForBaseagent, providerServiceTypeForPurpose, resolveServiceSelection } from '../../config/providers.js';
3
+ import { providerServiceTypeForPurpose, resolveServiceSelection } from '../../config/providers.js';
4
4
  export const MAX_FALLBACK_MODELS = 3;
5
5
  function isRecord(value) {
6
6
  return !!value && typeof value === 'object' && !Array.isArray(value);
@@ -59,11 +59,8 @@ async function eligibleCandidates(input) {
59
59
  const loadCatalog = (provider) => {
60
60
  const key = provider ?? '<legacy>';
61
61
  if (!catalogs.has(key)) {
62
- const serviceType = provider
63
- ? input.catalogProviderServiceType ?? (input.catalogBaseagent
64
- ? providerServiceTypeForBaseagent(input.catalogBaseagent)
65
- : input.serviceType)
66
- : input.serviceType;
62
+ const serviceType = provider && input.catalogBaseagent ? undefined
63
+ : input.catalogProviderServiceType ?? input.serviceType;
67
64
  catalogs.set(key, provider
68
65
  ? getProviderCatalog(provider, serviceType, false, false, input.catalogBaseagent)
69
66
  : input.catalog?.() ?? getCatalog(input.selfAid, input.serviceType));
@@ -88,7 +88,7 @@ export function validateModelSelectionForRole(opts) {
88
88
  return { ok: true, model: targetModel };
89
89
  }
90
90
  export function constrainResolvedModelForRole(opts) {
91
- // 角色策略只约束 Agent 级已配置的模型,不提供模型:Agent 级没有模型就是无模型可用。
91
+ // Role policy constrains the selected model, including any inherited default.
92
92
  if (!opts.model)
93
93
  return { model: undefined, constrained: false };
94
94
  const permission = getRoleModelPermission(opts.role, opts.baseagent, opts.selfAid);
@@ -411,7 +411,7 @@ export class OwnerResolver {
411
411
  let timeout;
412
412
  try {
413
413
  const consensus = await Promise.race([
414
- client.checkOwnershipConsensus(subjectAid),
414
+ client.checkOwnershipConsensus(subjectAid, true),
415
415
  new Promise((_resolve, reject) => {
416
416
  timeout = setTimeout(() => reject(new OwnershipError('OWNERSHIP_REFRESH_TIMEOUT', 'Ownership consensus check timed out')), this.options.timeoutMs ?? 8_000);
417
417
  timeout.unref?.();
@@ -692,7 +692,7 @@ export class OwnerResolver {
692
692
  }
693
693
  if (subject.transferIntents.has(subAid) || subject.transferTasks.has(subAid)) {
694
694
  const generation = subject.generation;
695
- const current = await this.withSubjectClient(ownerAid, client => client.checkOwnershipConsensus(subAid));
695
+ const current = await this.withSubjectClient(ownerAid, client => client.checkOwnershipConsensus(subAid, true));
696
696
  if (subject.generation !== generation) {
697
697
  throw new OwnershipError('CLIENT_REPLACED', 'Ownership state changed during transfer preflight; retry');
698
698
  }
@@ -789,7 +789,7 @@ export class OwnerResolver {
789
789
  if (task.status === 'error' || task.status === 'stopped' || (decision === 'accept' && task.status === 'rejected')) {
790
790
  throw Object.assign(new OwnershipError(task.code ?? 'OWNERSHIP_DECISION_FAILED', task.reason ?? `Ownership task ${task.status}`), { retryable: task.retryable });
791
791
  }
792
- const decisionConsensus = await client.checkOwnershipConsensus(task.sub_aid);
792
+ const decisionConsensus = await client.checkOwnershipConsensus(task.sub_aid, true);
793
793
  if (decisionConsensus?.sub_aid === task.sub_aid) {
794
794
  subject.view.decisionConsensus = decisionConsensus;
795
795
  if (task.sub_aid === subjectAid)
@@ -833,7 +833,7 @@ export class OwnerResolver {
833
833
  }
834
834
  const generation = subject.generation;
835
835
  return this.withSubjectClient(subjectAid, async (client) => {
836
- const consensus = await client.checkOwnershipConsensus(subjectAid);
836
+ const consensus = await client.checkOwnershipConsensus(subjectAid, true);
837
837
  if (subject.generation !== generation) {
838
838
  throw new OwnershipError('CLIENT_REPLACED', 'Subject state changed during status query; retry');
839
839
  }
@@ -848,7 +848,7 @@ export class OwnerResolver {
848
848
  const generation = subject.generation;
849
849
  for (const [subAid, task] of [...subject.transferTasks]) {
850
850
  try {
851
- const consensus = await client.checkOwnershipConsensus(subAid);
851
+ const consensus = await client.checkOwnershipConsensus(subAid, true);
852
852
  if ((attached && subject.client !== client) || subject.generation !== generation
853
853
  || subject.transferTasks.get(subAid)?.operation_id !== task.operation_id)
854
854
  return;
@@ -976,7 +976,7 @@ export class OwnerResolver {
976
976
  if (attached && (subject.client !== client || subject.generation !== generation)) {
977
977
  throw new OwnershipError('CLIENT_REPLACED', 'Owner SDK client changed before transfer');
978
978
  }
979
- const current = await client.checkOwnershipConsensus(subAid);
979
+ const current = await client.checkOwnershipConsensus(subAid, true);
980
980
  this.assertTransferBaseline(current, ownerAid, subAid, newOwnerAid);
981
981
  targetConsensus = current;
982
982
  subject.view.targetConsensus = current;
@@ -1015,7 +1015,7 @@ export class OwnerResolver {
1015
1015
  subject.transferIntents.set(subAid, newOwnerAid);
1016
1016
  this.syncTransferViews(subject);
1017
1017
  subject.view.task = task;
1018
- const after = await client.checkOwnershipConsensus(subAid);
1018
+ const after = await client.checkOwnershipConsensus(subAid, true);
1019
1019
  if (subject.client && (subject.client !== client || subject.generation !== generation)) {
1020
1020
  throw new OwnershipError('CLIENT_REPLACED', 'Owner SDK client changed during transfer verification; query status before retrying');
1021
1021
  }
@@ -1167,7 +1167,7 @@ export class OwnerResolver {
1167
1167
  retryable: task.retryable,
1168
1168
  });
1169
1169
  }
1170
- const consensus = await ownerClient.checkOwnershipConsensus(subAid);
1170
+ const consensus = await ownerClient.checkOwnershipConsensus(subAid, true);
1171
1171
  if (task.status === 'completed' && (consensus.status !== 'consensus' || consensus.owner_aid !== newOwnerAid
1172
1172
  || consensus.sub_aid !== subAid || consensus.relation_version !== task.target_relation_version
1173
1173
  || consensus.lock !== 'locked')) {
@@ -1232,7 +1232,7 @@ export class OwnerResolver {
1232
1232
  || task.status !== 'completed') {
1233
1233
  throw Object.assign(new OwnershipError(task?.code ?? 'LOCAL_BIND_FAILED', task?.reason ?? 'Local binding did not complete'), { retryable: task?.retryable });
1234
1234
  }
1235
- const consensus = await ownerClient.checkOwnershipConsensus(subjectAid);
1235
+ const consensus = await ownerClient.checkOwnershipConsensus(subjectAid, true);
1236
1236
  if (consensus.status !== 'consensus' || consensus.owner_aid !== ownerAid
1237
1237
  || consensus.sub_aid !== subjectAid || consensus.relation_version !== task.target_relation_version
1238
1238
  || consensus.lock !== 'locked') {
@@ -410,7 +410,7 @@ export class PermissionGateway {
410
410
  registerConfigRevalidation() {
411
411
  return onConfigWrite(({ target, selector }) => {
412
412
  if ((target !== ConfigTarget.Agent
413
- && target !== ConfigTarget.Contact
413
+ && target !== ConfigTarget.Peer
414
414
  && target !== ConfigTarget.Relation) || !selector.self)
415
415
  return;
416
416
  const cancelled = this.revalidatePendingApprovals(selector.self);
@@ -333,11 +333,11 @@ const APPLY_PATCH_EXECUTABLE_BASENAMES = new Set([
333
333
  'apply_patch.ps1',
334
334
  ]);
335
335
  const EVOLCORE_SUBCOMMANDS = new Set([
336
- 'agent', 'aid', 'bench', 'config', 'contact', 'ctl', 'data', 'diag', 'diagnose',
336
+ 'agent', 'aid', 'bench', 'config', 'peer', 'ctl', 'data', 'diag', 'diagnose',
337
337
  'fs', 'gateway', 'group', 'handoff', 'init', 'link-rules', 'logs', 'menu-client',
338
338
  'mode', 'model', 'msg', 'mv', 'net', 'queue', 'response', 'restart',
339
339
  'restart-monitor', 'rpc', 'start', 'stats', 'status', 'stop', 'storage', 'task',
340
- 'trigger', 'proxy', 'version', 'watch', 'session',
340
+ 'trigger', 'proxy', 'version', 'watch', 'session', 'pa-workspace',
341
341
  ]);
342
342
  // Development/install entrypoints that are part of this repository's CLI.
343
343
  // Only these exact relative paths are canonicalized; arbitrary Node scripts
@@ -60,38 +60,6 @@ export function isShellToolName(toolName) {
60
60
  export function isWriteToolName(toolName, input) {
61
61
  return canonicalToolCall(toolName, input).access === 'write';
62
62
  }
63
- // ── Internal helpers ─────────────────────────────────────────────────────────
64
- /**
65
- * Codex FileChange intent: if fileChanges contains an apply-patch style entry
66
- * (has an `oldContent` / `patch` key) it is Edit; otherwise Write.
67
- */
68
- function resolveFileChangeName(input) {
69
- if (!input)
70
- return 'Write'; // conservative fallback
71
- const changes = input.fileChanges;
72
- if (!Array.isArray(changes) || changes.length === 0)
73
- return 'Write';
74
- const first = changes[0];
75
- if (first && typeof first === 'object') {
76
- const obj = first;
77
- // A patch/edit operation carries 'patch', 'oldContent', or 'type': 'edit'
78
- if ('patch' in obj || 'oldContent' in obj || obj.type === 'edit')
79
- return 'Edit';
80
- }
81
- return 'Write';
82
- }
83
- /**
84
- * apply_patch: if the patch string starts with '--- ' or 'diff ' it is an
85
- * edit; otherwise (e.g. a full file replacement) treat as Write.
86
- */
87
- function resolveApplyPatchName(input) {
88
- if (!input)
89
- return 'Edit'; // apply_patch is most commonly a diff edit
90
- const patch = typeof input.patch === 'string' ? input.patch : '';
91
- if (patch.startsWith('--- ') || patch.startsWith('diff '))
92
- return 'Edit';
93
- return 'Write';
94
- }
95
63
  const READ_TOOL_NAMES = new Set(['Read', 'Glob', 'Grep']);
96
64
  /** Keys a write tool may carry its target in (Claude / ecagent file tools). */
97
65
  const FILE_WRITE_PATH_KEYS = ['file_path', 'notebook_path', 'path'];
@@ -106,23 +74,16 @@ const SHELL_TOOL_NAMES = new Set(['Shell', 'exec_command']);
106
74
  * checkReadonly, which owns the Glob/Grep rules.
107
75
  */
108
76
  function resolveToolIntent(toolName, input = {}) {
109
- if (toolName === 'FileChange') {
110
- const paths = [];
111
- if (typeof input.grantRoot === 'string' && input.grantRoot)
112
- paths.push(input.grantRoot);
113
- collectFileChangePaths(input.fileChanges, paths);
114
- return { access: 'write', name: resolveFileChangeName(input), via: 'tool', paths: unique(paths) };
77
+ const mutation = normalizeFileMutation(toolName, input);
78
+ if (mutation.kind === 'file-mutation') {
79
+ const via = mutation.source === 'shell-apply-patch' ? 'shell' : 'tool';
80
+ const call = applyPatchCall(mutation.fileChanges, via);
81
+ return { ...call, paths: mutation.paths };
115
82
  }
116
- if (toolName === 'apply_patch') {
117
- return applyPatchCall(standaloneApplyPatchChanges(input), 'tool');
83
+ if (mutation.kind === 'invalid') {
84
+ return { access: 'write', name: 'Edit', via: mutation.source === 'shell-apply-patch' ? 'shell' : 'tool', paths: [] };
118
85
  }
119
86
  if (toolName === 'Bash' || SHELL_TOOL_NAMES.has(toolName)) {
120
- const parsed = parseShellApplyPatchInvocation(input);
121
- if (parsed.kind === 'file-change')
122
- return applyPatchCall(parsed.fileChanges, 'shell');
123
- // A recognised but malformed apply_patch is still a write attempt.
124
- if (parsed.kind === 'invalid')
125
- return { access: 'write', name: 'Edit', via: 'shell', paths: [] };
126
87
  return { access: 'shell', name: 'Bash' };
127
88
  }
128
89
  // read_file is Codex's legacy read alias; Claude / ecagent use the name directly.
@@ -142,6 +103,93 @@ function resolveToolIntent(toolName, input = {}) {
142
103
  export function canonicalToolCall(toolName, input = {}) {
143
104
  return resolveToolIntent(toolName, input);
144
105
  }
106
+ /** Normalize every supported file mutation to one target/path contract. */
107
+ export function normalizeFileMutation(toolName, input = {}, options = {}) {
108
+ if (toolName === 'FileChange') {
109
+ const fileChanges = normalizeFileChanges(input.fileChanges);
110
+ const grantRoot = typeof input.grantRoot === 'string' && input.grantRoot ? input.grantRoot : undefined;
111
+ if (!fileChanges || (fileChanges.length === 0 && !grantRoot)) {
112
+ return { kind: 'invalid', source: 'file-change', reason: 'FileChange contains invalid or conflicting target paths' };
113
+ }
114
+ const paths = applyPatchChangePaths(fileChanges);
115
+ if (grantRoot)
116
+ paths.push(grantRoot);
117
+ return { kind: 'file-mutation', fileChanges, paths: unique(paths), source: 'file-change' };
118
+ }
119
+ if (toolName === 'apply_patch') {
120
+ const fileChanges = standaloneApplyPatchChanges(input);
121
+ if (fileChanges) {
122
+ return { kind: 'file-mutation', fileChanges, paths: unique(applyPatchChangePaths(fileChanges)), source: 'apply-patch' };
123
+ }
124
+ const documents = APPLY_PATCH_DOCUMENT_KEYS.map(key => input[key]);
125
+ const invalidArgument = !documents.some(value => typeof value === 'string' && value.trimStart().startsWith('*** '));
126
+ return {
127
+ kind: 'invalid', source: 'apply-patch', reason: 'patch documents are incomplete or disagree on their targets',
128
+ ...(invalidArgument ? { errorDetailCode: 'INVALID_ARGUMENT' } : {}),
129
+ };
130
+ }
131
+ if (toolName === 'Bash' || SHELL_TOOL_NAMES.has(toolName)) {
132
+ const parsed = parseShellApplyPatchInvocation(input, options);
133
+ if (parsed.kind === 'file-change') {
134
+ return { kind: 'file-mutation', fileChanges: parsed.fileChanges, paths: unique(applyPatchChangePaths(parsed.fileChanges)), source: 'shell-apply-patch' };
135
+ }
136
+ if (parsed.kind === 'invalid') {
137
+ return {
138
+ kind: 'invalid', source: 'shell-apply-patch', reason: parsed.reason,
139
+ ...(parsed.errorDetailCode ? { errorDetailCode: parsed.errorDetailCode } : {}),
140
+ };
141
+ }
142
+ }
143
+ return { kind: 'not-file-mutation' };
144
+ }
145
+ /** Preserve operation kinds and both sides of moves across provider payload shapes. */
146
+ function normalizeFileChanges(value) {
147
+ if (value === undefined)
148
+ return [];
149
+ if (!value || typeof value !== 'object')
150
+ return undefined;
151
+ const recordValue = value;
152
+ const pathKeys = ['path', 'filePath', 'file_path'];
153
+ const kindValue = recordValue.kind;
154
+ const nestedKind = kindValue && typeof kindValue === 'object' && !Array.isArray(kindValue)
155
+ ? kindValue : undefined;
156
+ const hasNestedExplicitPath = !!nestedKind && pathKeys.some(key => Object.hasOwn(nestedKind, key));
157
+ const hasRootMutationMetadata = ['kind', 'type', 'movePath', 'move_path', 'destinationPath', 'targetPath']
158
+ .some(key => Object.hasOwn(recordValue, key));
159
+ const hasExplicitPath = pathKeys.some(key => Object.hasOwn(recordValue, key)
160
+ && (hasRootMutationMetadata || !recordValue[key] || typeof recordValue[key] !== 'object'));
161
+ const isSingleRecord = hasExplicitPath || hasNestedExplicitPath;
162
+ const records = Array.isArray(value)
163
+ ? value.map(entry => ({ entry, mapPath: undefined }))
164
+ : isSingleRecord ? [{ entry: value, mapPath: undefined }]
165
+ : Object.entries(value).map(([mapPath, entry]) => ({ entry, mapPath }));
166
+ const changes = [];
167
+ for (const { entry, mapPath } of records) {
168
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
169
+ return undefined;
170
+ const record = entry;
171
+ const kind = record.kind && typeof record.kind === 'object'
172
+ ? record.kind : {};
173
+ const sources = [mapPath, record.path, record.filePath, record.file_path, kind.path, kind.filePath, kind.file_path]
174
+ .filter(candidate => candidate !== undefined);
175
+ const destinations = [record.movePath, record.move_path, record.destinationPath, record.targetPath,
176
+ kind.movePath, kind.move_path, kind.destinationPath, kind.targetPath]
177
+ .filter(candidate => candidate !== undefined && candidate !== null);
178
+ const validPath = (candidate) => typeof candidate === 'string' && candidate.trim().length > 0 && !/[\0\r\n]/u.test(candidate);
179
+ if (!sources.length || !sources.every(validPath) || !destinations.every(validPath))
180
+ return undefined;
181
+ if (new Set(sources).size !== 1 || new Set(destinations).size > 1)
182
+ return undefined;
183
+ const operation = typeof record.kind === 'string'
184
+ ? record.kind
185
+ : kind.type ?? kind.kind ?? kind.action ?? kind.operation ?? kind.op
186
+ ?? record.type ?? record.action ?? record.operation ?? record.op;
187
+ const normalizedKind = operation === 'add' || operation === 'create' ? 'add'
188
+ : operation === 'delete' || operation === 'remove' ? 'delete' : 'update';
189
+ changes.push({ path: sources[0], kind: normalizedKind, ...(destinations[0] ? { movePath: destinations[0] } : {}) });
190
+ }
191
+ return changes;
192
+ }
145
193
  function applyPatchCall(changes, via) {
146
194
  if (!changes || changes.length === 0)
147
195
  return { access: 'write', name: 'Edit', via, paths: [] };
@@ -158,6 +206,8 @@ function standaloneApplyPatchChanges(input) {
158
206
  let signature;
159
207
  for (const key of APPLY_PATCH_DOCUMENT_KEYS) {
160
208
  const value = input[key];
209
+ if (value !== undefined && typeof value !== 'string')
210
+ return undefined;
161
211
  if (typeof value !== 'string' || !value.trim())
162
212
  continue;
163
213
  const changes = parseApplyPatchDocument(value);
@@ -1,3 +1,42 @@
1
+ export const STRUCTURED_TOOL_ERROR_PREFIX = 'EVOLCORE_TOOL_ERROR_V1 ';
2
+ export function extractStructuredToolErrorMarker(output) {
3
+ const lines = output.split(/\r?\n/);
4
+ const matches = lines
5
+ .map((line, index) => ({ line, index }))
6
+ .filter(item => item.line.startsWith(STRUCTURED_TOOL_ERROR_PREFIX));
7
+ if (matches.length !== 1)
8
+ return undefined;
9
+ const { line, index } = matches[0];
10
+ let value;
11
+ try {
12
+ value = JSON.parse(line.slice(STRUCTURED_TOOL_ERROR_PREFIX.length));
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ if (!value || typeof value !== 'object' || Array.isArray(value))
18
+ return undefined;
19
+ const record = value;
20
+ const errorCode = normalizeToolErrorCode(record.errorCode);
21
+ const decisionSource = record.decisionSource;
22
+ if (!errorCode || (decisionSource !== 'policy' && decisionSource !== 'approval' && decisionSource !== 'infrastructure')
23
+ || typeof record.reason !== 'string')
24
+ return undefined;
25
+ const errorDetailCode = normalizeToolErrorDetailCode(record.errorDetailCode);
26
+ const policyCode = typeof record.policyCode === 'string' && /^[a-z][a-z0-9_.-]{0,127}$/i.test(record.policyCode)
27
+ ? record.policyCode : undefined;
28
+ lines.splice(index, 1);
29
+ return {
30
+ output: lines.join('\n'),
31
+ error: {
32
+ errorCode,
33
+ ...(errorDetailCode ? { errorDetailCode } : {}),
34
+ decisionSource,
35
+ ...(policyCode ? { policyCode } : {}),
36
+ reason: record.reason,
37
+ },
38
+ };
39
+ }
1
40
  const PERMISSION_ERROR_CODES = new Set([
2
41
  'POLICY_DENIED',
3
42
  'ROLE_DENIED',
@@ -6,6 +45,8 @@ const PERMISSION_ERROR_CODES = new Set([
6
45
  'DELEGATION_FAILED',
7
46
  ]);
8
47
  const DETAIL_CODE_BY_POLICY_CODE = {
48
+ h_class_protection: 'H_CLASS_PROTECTION',
49
+ l_class_protection: 'L_CLASS_PROTECTION',
9
50
  native_file_change_required: 'NATIVE_FILE_CHANGE_REQUIRED',
10
51
  apply_patch_invalid_argument: 'INVALID_ARGUMENT',
11
52
  apply_patch_unparseable: 'APPLY_PATCH_UNPARSEABLE',
@@ -6,9 +6,9 @@ import { randomUUID } from 'crypto';
6
6
  import { logger } from '../../utils/logger.js';
7
7
  import { resolveRoot } from '../../paths.js';
8
8
  import { containsHClassReference, containsAgentScopeReference, containsLClassReference, checkProtectedPathAccess, getExistingHClassMaskTargets, hClassGrantIncludesProtectedPath, isHClassPath, isSameOrDescendant, isLClassPath, lClassGrantIncludesProtectedPath, resolveProtectedCandidate, resolveProtectedCandidateWithoutFinalSymlink, } from './protected-paths.js';
9
- import { classifyEvolcoreShellCommand, canonicalizeEvolcoreCommandArgv, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseCodexToolCommand, literalShellParseRemedy, parseBoundedOutputShellCommand, buildCanonicalEvolcoreExecutionSpec, serializeCanonicalEvolcoreExecutionSpec, parseShellApplyPatchInvocation, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from './ec-command-parser.js';
9
+ import { classifyEvolcoreShellCommand, canonicalizeEvolcoreCommandArgv, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseCodexToolCommand, literalShellParseRemedy, parseBoundedOutputShellCommand, buildCanonicalEvolcoreExecutionSpec, serializeCanonicalEvolcoreExecutionSpec, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from './ec-command-parser.js';
10
10
  import { analyzeReadonlyShellQuery, } from './readonly-shell-query.js';
11
- import { applyPatchChangePaths, collectFileChangePaths } from './tool-canonical.js';
11
+ import { applyPatchChangePaths, collectFileChangePaths, normalizeFileMutation } from './tool-canonical.js';
12
12
  /** Resolve the session-owned temporary root supplied by the execution host. */
13
13
  export function resolveManagedTempDir(env = process.env) {
14
14
  const raw = typeof env.TMPDIR === 'string' ? env.TMPDIR.trim() : '';
@@ -2332,9 +2332,35 @@ export function checkBashDescription(toolName, input) {
2332
2332
  }
2333
2333
  /** Shared fail-closed preflight used before runner-specific mode and approval handling. */
2334
2334
  export function evaluateToolPreflight(toolName, input, context) {
2335
- let applyPatchFileChanges;
2336
2335
  let protectedPolicyCommand;
2337
- const managedPathCheck = checkManagedTempToolPaths(toolName, input, managedTempOptions(context));
2336
+ const fileMutation = normalizeFileMutation(toolName, input, {
2337
+ verifyShellExecutable: process.platform === 'win32',
2338
+ managedTempDir: context.managedTempDir,
2339
+ ...(context.sessionCredential ? { expectedCredentialToken: context.sessionCredential } : {}),
2340
+ });
2341
+ if (fileMutation.kind === 'invalid') {
2342
+ if (fileMutation.source === 'file-change') {
2343
+ return {
2344
+ behavior: 'deny', input, message: fileMutation.reason,
2345
+ policyCode: 'file_change_invalid_argument', errorDetailCode: 'INVALID_ARGUMENT',
2346
+ };
2347
+ }
2348
+ const invalidArgument = fileMutation.errorDetailCode === 'INVALID_ARGUMENT';
2349
+ return {
2350
+ behavior: 'deny',
2351
+ input,
2352
+ message: invalidArgument
2353
+ ? 'apply_patch 参数格式错误:需要一个完整补丁文档(以 *** Begin Patch 开头、以 *** End Patch 结尾),普通命令行参数不是补丁。'
2354
+ : '文件修改 patch 无法安全解析:' + fileMutation.reason,
2355
+ policyCode: invalidArgument ? 'apply_patch_invalid_argument' : 'apply_patch_unparseable',
2356
+ errorDetailCode: invalidArgument ? 'INVALID_ARGUMENT' : 'APPLY_PATCH_UNPARSEABLE',
2357
+ };
2358
+ }
2359
+ const fileChanges = fileMutation.kind === 'file-mutation' ? fileMutation.fileChanges : undefined;
2360
+ const shellTool = toolName === 'Bash' || toolName === 'Shell' || toolName === 'exec_command';
2361
+ const policyPathToolName = fileChanges ? 'FileChange' : shellTool ? 'Bash' : toolName;
2362
+ const policyPathInput = fileChanges ? { ...input, fileChanges } : input;
2363
+ const managedPathCheck = checkManagedTempToolPaths(policyPathToolName, policyPathInput, managedTempOptions(context));
2338
2364
  if (managedPathCheck.kind === 'deny') {
2339
2365
  const currentTmpDir = resolveManagedTempDir(managedTempOptions(context).env);
2340
2366
  return {
@@ -2345,7 +2371,39 @@ export function evaluateToolPreflight(toolName, input, context) {
2345
2371
  matchedPath: managedPathCheck.paths[0],
2346
2372
  };
2347
2373
  }
2348
- if (toolName === 'Bash') {
2374
+ if (fileMutation.kind === 'file-mutation' && fileMutation.fileChanges.length > 0) {
2375
+ if (context.permissionMode === 'readonly') {
2376
+ return {
2377
+ behavior: 'deny', input, message: '🔒 只读模式:禁止修改文件',
2378
+ policyCode: 'readonly_file_write', errorDetailCode: 'READONLY_FILE_WRITE',
2379
+ };
2380
+ }
2381
+ const escapedPath = applyPatchWorkspaceEscape(fileMutation.fileChanges, context);
2382
+ if (escapedPath && context.sessionId && context.permissionMode !== 'request' && context.permissionMode !== 'fullaccess') {
2383
+ return {
2384
+ behavior: 'deny', input,
2385
+ message: '🔒 文件修改目标必须位于当前 workspace 或会话 $TMPDIR 内',
2386
+ policyCode: fileMutation.source === 'file-change' ? 'file_change_workspace_escape' : 'apply_patch_workspace_escape',
2387
+ errorDetailCode: 'APPLY_PATCH_WORKSPACE_ESCAPE', matchedPath: escapedPath,
2388
+ };
2389
+ }
2390
+ for (const candidate of fileMutation.paths) {
2391
+ const resolved = resolveProtectedCandidate(candidate, context.projectPath);
2392
+ try {
2393
+ const stat = fs.statSync(resolved);
2394
+ if (stat.isFile() && stat.nlink > 1) {
2395
+ return {
2396
+ behavior: 'deny', input, message: '🔒 文件修改目标是硬链接,不能安全修改',
2397
+ policyCode: 'file_write_hardlink', errorDetailCode: 'HARDLINK_WRITE_FORBIDDEN', matchedPath: resolved,
2398
+ };
2399
+ }
2400
+ }
2401
+ catch {
2402
+ // New files remain subject to ancestor containment and protected-path checks.
2403
+ }
2404
+ }
2405
+ }
2406
+ if (shellTool) {
2349
2407
  const command = typeof input.command === 'string' ? input.command : '';
2350
2408
  const explicitCommandArgv = Array.isArray(input.commandArgv)
2351
2409
  && input.commandArgv.every(value => typeof value === 'string')
@@ -2365,7 +2423,11 @@ export function evaluateToolPreflight(toolName, input, context) {
2365
2423
  const commandForPolicy = explicitCommandArgv
2366
2424
  ? explicitCommandArgv.join(' ')
2367
2425
  : command;
2368
- const tempCheck = checkManagedTempShellCommand(commandForPolicy, managedTempOptions(context));
2426
+ // Parsed patch bodies are data. The normalized FileChange targets have
2427
+ // already passed the same managed-temp check above.
2428
+ const tempCheck = fileChanges
2429
+ ? { kind: 'none' }
2430
+ : checkManagedTempShellCommand(commandForPolicy, managedTempOptions(context));
2369
2431
  if (tempCheck.kind === 'deny') {
2370
2432
  const currentTmpDir = resolveManagedTempDir(managedTempOptions(context).env);
2371
2433
  return {
@@ -2406,44 +2468,6 @@ export function evaluateToolPreflight(toolName, input, context) {
2406
2468
  : {}),
2407
2469
  };
2408
2470
  const parsedCodex = context.sessionId ? parseCodexToolCommand(input, parserOptions) : null;
2409
- const applyPatch = parseShellApplyPatchInvocation(input, parserOptions, parsedCodex?.ok ? parsedCodex.argv : undefined);
2410
- if (applyPatch.kind === 'invalid') {
2411
- const invalidArgument = applyPatch.errorDetailCode === 'INVALID_ARGUMENT';
2412
- return {
2413
- behavior: 'deny',
2414
- input,
2415
- message: invalidArgument
2416
- ? 'apply_patch 参数格式错误:需要一个完整补丁文档(以 *** Begin Patch 开头、以 *** End Patch 结尾),普通命令行参数不是补丁;这不是权限不足。如果补丁内容本身完整但仍报此错,通常是 Windows apply_patch.bat 截断了多行参数;请改用 FileChange 工具直接写文件,或绕过 .bat 直接调用 codex.exe --codex-run-as-apply-patch,不要用 here-string 变体重试。'
2417
- : '文件修改 patch 无法安全解析:' + applyPatch.reason + '。Windows 上通过 PowerShell here-string 传递补丁时,结尾的 *** End Patch 行通常会被截断导致此错误;请改用 FileChange 工具直接写文件,不要继续用 here-string 变体重试。',
2418
- policyCode: invalidArgument ? 'apply_patch_invalid_argument' : 'apply_patch_unparseable',
2419
- errorDetailCode: invalidArgument ? 'INVALID_ARGUMENT' : 'APPLY_PATCH_UNPARSEABLE',
2420
- };
2421
- }
2422
- if (applyPatch.kind === 'file-change') {
2423
- applyPatchFileChanges = applyPatch.fileChanges;
2424
- if (context.permissionMode === 'readonly') {
2425
- return {
2426
- behavior: 'deny',
2427
- input,
2428
- message: '🔒 只读模式:禁止通过 apply_patch 修改文件',
2429
- policyCode: 'readonly_file_write',
2430
- errorDetailCode: 'READONLY_FILE_WRITE',
2431
- };
2432
- }
2433
- const escapedPath = applyPatchWorkspaceEscape(applyPatch.fileChanges, context);
2434
- if (escapedPath && context.sessionId
2435
- && context.permissionMode !== 'request'
2436
- && context.permissionMode !== 'fullaccess') {
2437
- return {
2438
- behavior: 'deny',
2439
- input,
2440
- message: '🔒 apply_patch 目标必须位于当前 workspace 或会话 $TMPDIR 内',
2441
- policyCode: 'apply_patch_workspace_escape',
2442
- errorDetailCode: 'APPLY_PATCH_WORKSPACE_ESCAPE',
2443
- matchedPath: escapedPath,
2444
- };
2445
- }
2446
- }
2447
2471
  if (context.sessionId && parsedCodex && !parsedCodex.ok && parsedCodex.issue === 'untrusted-shell') {
2448
2472
  return {
2449
2473
  behavior: 'deny',
@@ -2661,10 +2685,10 @@ export function evaluateToolPreflight(toolName, input, context) {
2661
2685
  return { behavior: 'deny', input, message: blacklist.message, policyCode: 'tool_blacklist' };
2662
2686
  }
2663
2687
  const checkedInput = blacklist.updatedInput;
2664
- const policyInput = applyPatchFileChanges
2665
- ? { ...checkedInput, fileChanges: applyPatchFileChanges }
2688
+ const policyInput = fileChanges
2689
+ ? { ...checkedInput, fileChanges }
2666
2690
  : checkedInput;
2667
- const policyToolName = applyPatchFileChanges ? 'FileChange' : toolName;
2691
+ const policyToolName = fileChanges ? 'FileChange' : shellTool ? 'Bash' : toolName;
2668
2692
  const protectedPolicyInput = policyToolName === 'Bash' && protectedPolicyCommand
2669
2693
  ? { ...policyInput, command: protectedPolicyCommand }
2670
2694
  : policyInput;
@@ -1,7 +1,7 @@
1
1
  import { getRoleDefinition } from '../../config/roles.js';
2
2
  import { PUBLIC_PERMISSION_MODES } from '../permission/mode.js';
3
3
  import { ConfigTarget, mutateConfig, read } from '../../config/config-manager.js';
4
- import { resolvePrincipal } from '../../config/contact-book.js';
4
+ import { resolvePrincipal } from '../../config/peer-book.js';
5
5
  import { getDaemonOwners, ownerResolver } from '../ownership/owner-resolver.js';
6
6
  import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
7
7
  import { isTopicSession } from '../thread/topic-id.js';
@@ -228,6 +228,16 @@ export class SessionIdleMonitor {
228
228
  for (const sessionId of this.sessions.keys())
229
229
  this.scheduleSession(sessionId);
230
230
  }
231
+ /**
232
+ * 重新采集 session:idle trigger 身份。
233
+ *
234
+ * `activate()` 时会采一次,但 trigger scheduler 可能晚于它启动(启动时推迟到
235
+ * ready 之后以缩短就绪时间)。不补采的话这段时间里由这些 trigger 产生的
236
+ * 任务终止事件会被误判成"普通活动",把空闲周期提前重置。
237
+ */
238
+ refreshTriggerIdentities() {
239
+ this.refreshSessionIdleTriggerIds();
240
+ }
231
241
  /** Re-read relation configuration and re-arm every restored/current session. */
232
242
  refresh() {
233
243
  if (!this.active)
@@ -2689,7 +2689,7 @@ export class SessionManager {
2689
2689
  async getHealthStatus(sessionId) {
2690
2690
  const chatInfo = this.chatDirForSession(sessionId);
2691
2691
  if (!chatInfo) {
2692
- return { consecutiveErrors: 0, safeMode: false, lastSuccessTime: Date.now() };
2692
+ return { consecutiveErrors: 0, safeMode: false };
2693
2693
  }
2694
2694
  const healthPath = path.join(chatInfo.dirPath, 'health.jsonl');
2695
2695
  const records = readAllJsonlLines(healthPath).filter(r => r.sessionId === sessionId);
@@ -2723,14 +2723,12 @@ export class SessionManager {
2723
2723
  }
2724
2724
  }
2725
2725
  }
2726
- if (lastSuccessTime === 0)
2727
- lastSuccessTime = Date.now();
2728
2726
  return {
2729
2727
  consecutiveErrors,
2730
2728
  lastError,
2731
2729
  lastErrorType,
2732
2730
  safeMode: false,
2733
- lastSuccessTime,
2731
+ ...(lastSuccessTime > 0 ? { lastSuccessTime } : {}),
2734
2732
  };
2735
2733
  }
2736
2734
  async recordSuccess(sessionId) {