evolcore 0.0.39 → 0.0.41-test.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 (153) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +31 -20
  3. package/bin/codex-managed-hook.mjs +11 -0
  4. package/bin/ec-safe-output.js +25 -3
  5. package/dist/agents/baseagent-availability.js +1 -0
  6. package/dist/agents/claude-runner.js +53 -152
  7. package/dist/agents/codex-runner.js +485 -241
  8. package/dist/agents/ecagent-runner.js +48 -18
  9. package/dist/agents/gemini-runner.js +27 -8
  10. package/dist/agents/runner-types.js +39 -9
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/aid/control-aid.js +23 -98
  14. package/dist/aun/aid/ownership-operation.js +1 -3
  15. package/dist/aun/group/identity.js +8 -0
  16. package/dist/aun/group/invite-service.js +6 -0
  17. package/dist/aun/msg/managed-operation.js +4 -4
  18. package/dist/aun/msg/p2p.js +28 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +99 -52
  22. package/dist/channels/daemon.js +24 -4
  23. package/dist/channels/dingtalk.js +8 -2
  24. package/dist/channels/feishu.js +6 -1
  25. package/dist/channels/wecom.js +7 -3
  26. package/dist/cli/agent-command.js +2 -0
  27. package/dist/cli/agent-create.js +121 -23
  28. package/dist/cli/agent.js +10 -3
  29. package/dist/cli/aid-bind-command.js +4 -1
  30. package/dist/cli/aun-commands.js +82 -22
  31. package/dist/cli/daemon-commands.js +260 -26
  32. package/dist/cli/index.js +25 -13
  33. package/dist/cli/memory-command.js +33 -14
  34. package/dist/cli/restart-monitor.js +52 -13
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/task-context.js +1 -0
  38. package/dist/cli/trigger-command.js +2 -2
  39. package/dist/config/access-policy.js +2 -0
  40. package/dist/config/config-field-policy.js +1 -0
  41. package/dist/config/config-operation-service.js +17 -6
  42. package/dist/config/gateway-config.js +1 -1
  43. package/dist/config/peer-role-resolver.js +10 -8
  44. package/dist/contracts/ecweb-service-protocol.js +44 -0
  45. package/dist/core/agent-application-service.js +11 -1
  46. package/dist/core/agent-ipc-registration.js +4 -0
  47. package/dist/core/agent-runtime.js +6 -0
  48. package/dist/core/auth/agent-delegation.js +87 -9
  49. package/dist/core/auth/auth-gateway.js +3 -1
  50. package/dist/core/auth/authorization-audit.js +25 -4
  51. package/dist/core/auth/debug-context.js +5 -1
  52. package/dist/core/auth/operation-catalog.js +24 -0
  53. package/dist/core/command/agent-control.js +91 -12
  54. package/dist/core/command/command-handler.js +64 -47
  55. package/dist/core/command/connect-menu.js +23 -2
  56. package/dist/core/command/menu-catalog.js +49 -12
  57. package/dist/core/command/menu-handler.js +110 -105
  58. package/dist/core/command/menu-protocol.js +29 -3
  59. package/dist/core/command/role-menu.js +7 -6
  60. package/dist/core/command/slash-gate.js +22 -5
  61. package/dist/core/command/slash-handler.js +121 -102
  62. package/dist/core/event-catalog.js +17 -0
  63. package/dist/core/interaction-router.js +2 -1
  64. package/dist/core/ipc-registration.js +44 -8
  65. package/dist/core/memory/batch-meta.js +2 -0
  66. package/dist/core/memory/consolidation-context.js +42 -51
  67. package/dist/core/memory/consolidation-ops-records.js +39 -7
  68. package/dist/core/memory/consolidation-trigger.js +72 -65
  69. package/dist/core/memory/consolidation.js +226 -20
  70. package/dist/core/memory/memory-writer.js +160 -34
  71. package/dist/core/memory/relation-idle-monitor.js +287 -0
  72. package/dist/core/memory/relation-sweep.js +206 -0
  73. package/dist/core/message/aun-ipc-sender.js +31 -5
  74. package/dist/core/message/aun-request-registry.js +97 -3
  75. package/dist/core/message/im-renderer.js +4 -0
  76. package/dist/core/message/message-admission.js +8 -4
  77. package/dist/core/message/message-bridge.js +96 -53
  78. package/dist/core/message/message-log.js +72 -0
  79. package/dist/core/message/message-queue.js +11 -5
  80. package/dist/core/message/outbound.js +70 -0
  81. package/dist/core/message/peer-mode.js +7 -2
  82. package/dist/core/message/response-engine.js +633 -191
  83. package/dist/core/model/model-catalog.js +7 -6
  84. package/dist/core/ownership/owner-resolver.js +384 -178
  85. package/dist/core/permission/ec-command-parser.js +129 -8
  86. package/dist/core/permission/tool-policy.js +35 -14
  87. package/dist/core/role/runtime-policy.js +64 -0
  88. package/dist/core/session/session-capsule.js +197 -0
  89. package/dist/core/session/session-manager.js +172 -18
  90. package/dist/core/session/session-mapper.js +2 -0
  91. package/dist/core/system-session/memory.js +3 -18
  92. package/dist/ecweb/basic-settings-service.js +709 -0
  93. package/dist/ecweb/providers-service.js +172 -0
  94. package/dist/index.js +95 -7
  95. package/dist/ipc.js +100 -19
  96. package/dist/stats/budget.js +1 -1
  97. package/dist/stats/db.js +48 -0
  98. package/dist/stats/index.js +3 -3
  99. package/dist/stats/price-resolver.js +304 -5
  100. package/dist/stats/query.js +328 -3
  101. package/dist/stats/writer.js +79 -6
  102. package/dist/trigger/application-service.js +12 -0
  103. package/dist/trigger/authorization.js +2 -2
  104. package/dist/trigger/feedback.js +18 -7
  105. package/dist/trigger/history.js +36 -0
  106. package/dist/trigger/manager.js +20 -3
  107. package/dist/trigger/parser.js +6 -3
  108. package/dist/trigger/patch.js +1 -1
  109. package/dist/trigger/scheduler.js +3 -0
  110. package/dist/trigger/system-definitions.js +43 -7
  111. package/dist/trigger/validation.js +13 -5
  112. package/dist/utils/ecweb-supervisor.js +31 -10
  113. package/dist/utils/error-utils.js +22 -4
  114. package/dist/utils/evolcore-version.js +3 -2
  115. package/dist/utils/host-info.js +52 -0
  116. package/dist/utils/npm-ops.js +2 -1
  117. package/dist/utils/package-version-info.js +1 -1
  118. package/dist/utils/upgrade-jobs.js +45 -5
  119. package/ecagent/dist/harness/agent-harness.js +4 -1
  120. package/kits/docs/INDEX.md +1 -1
  121. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  122. package/kits/docs/evolcore/INDEX.md +3 -2
  123. package/kits/docs/evolcore/agent-create.md +3 -2
  124. package/kits/docs/evolcore/agent.md +1 -1
  125. package/kits/docs/evolcore/aid.md +29 -12
  126. package/kits/docs/evolcore/config.md +9 -7
  127. package/kits/docs/evolcore/event.md +1 -0
  128. package/kits/docs/evolcore/fs.md +5 -0
  129. package/kits/docs/evolcore/memory-architecture.md +3 -4
  130. package/kits/docs/evolcore/memory-consolidation.md +28 -7
  131. package/kits/docs/evolcore/memory-tags.md +1 -1
  132. package/kits/docs/evolcore/memory.md +1 -1
  133. package/kits/docs/evolcore/menu-client.md +1 -1
  134. package/kits/docs/evolcore/menu-protocol.md +38 -0
  135. package/kits/docs/evolcore/msg.md +18 -2
  136. package/kits/docs/evolcore/session.md +14 -0
  137. package/kits/eck_manifest.json +3 -3
  138. package/kits/rules/04-relation.md +3 -2
  139. package/kits/schemas/agent-config.schema.13.json +20 -1
  140. package/kits/skills/aid-ability/SKILL.md +35 -6
  141. package/kits/templates/memory-consolidation/generalize.md +32 -4
  142. package/kits/templates/memory-consolidation/notes.md +2 -2
  143. package/kits/templates/memory-consolidation/promote.md +10 -2
  144. package/kits/templates/session-capsule/recovery.md +5 -0
  145. package/kits/templates/session-capsule/renew.md +5 -0
  146. package/kits/templates/system-fragments/baseagent.md +5 -0
  147. package/kits/templates/system-fragments/bootstrap.md +6 -6
  148. package/kits/templates/system-fragments/channel.md +1 -1
  149. package/kits/templates/system-fragments/memory.md +12 -3
  150. package/kits/templates/system-fragments/session.md +1 -1
  151. package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
  152. package/package.json +3 -3
  153. package/dist/stats/billing.js +0 -215
@@ -19,7 +19,7 @@ import { findContactRequestNote, expirePendingContactRequests, reviewContactRequ
19
19
  import { isValidAid } from '../../aun/aid/validation.js';
20
20
  import { PeerIdentityCache, formatPeerKey } from '../relation/peer-identity.js';
21
21
  import { ownerResolver } from '../ownership/owner-resolver.js';
22
- import { isTopicSession, sessionLocalTopicId } from '../thread/topic-id.js';
22
+ import { isMainSession, isTopicSession, sessionLocalTopicId } from '../thread/topic-id.js';
23
23
  import { resolveEffective } from '../../config/config-manager.js';
24
24
  import { createDecisionInferenceProvider } from '../inference/text-inference.js';
25
25
  import { AutoMentionGate } from './auto-mention-gate.js';
@@ -39,7 +39,7 @@ import { recordCausationSpan } from '../causation/audit.js';
39
39
  import { renderActionAsText } from '../interaction-router.js';
40
40
  import { planApprovalRoute } from '../permission/approval-gateway.js';
41
41
  import { guardGroupSlashCommand, parseFullAccessCommand } from '../command/slash-gate.js';
42
- import { createAgentPolicyAuthorization } from '../role/runtime-policy.js';
42
+ import { createAgentPolicyAuthorization, createSessionFullAccessAuthorization, hasSessionFullAccessOverride } from '../role/runtime-policy.js';
43
43
  import { auditFullAccessEvent } from '../auth/authorization-audit.js';
44
44
  import { DIAGNOSTIC_AGENT_AID, DiagnosticSessionRouter, parseDiagnosticEvent, isDiagnosticSessionActive } from '../command/diag-service.js';
45
45
  import { consumeAdmissionReplyBudget, clearAdmissionReplyBudgets, evaluateInboundAdmissionPreflight, evaluateOrdinaryInboundAdmission, } from './message-admission.js';
@@ -279,6 +279,43 @@ export class MessageBridge {
279
279
  return { handled: true, status: 'not-first-owner', reply: '仅 Agent 配置中的首个 Owner 可在 AUN 私聊发送 /bind 发起 ownership 绑定。' };
280
280
  }
281
281
  try {
282
+ const current = await ownerResolver.refresh(selfAid, { force: true });
283
+ if (current.consensusStatus === 'consensus') {
284
+ return current.ownerAid === actorId
285
+ ? { handled: true, status: 'already-bound', reply: '协议 Owner 已绑定,无需重复操作。' }
286
+ : {
287
+ handled: true,
288
+ status: 'owner-already-bound',
289
+ reply: `该 Agent 已绑定协议 Owner ${current.ownerAid ?? '(身份未知)'},暂不支持重新绑定。`,
290
+ };
291
+ }
292
+ const taskStatus = current.task?.status;
293
+ const hasActiveSubmission = taskStatus === 'pending'
294
+ || (['requesting', 'submitted'].includes(current.requestStatus ?? '')
295
+ && (!taskStatus || taskStatus === 'completed'));
296
+ const interruptedSubmissionNeedsCheck = current.requestStatus === 'interrupted'
297
+ && current.consensusStatus === 'single_sided';
298
+ if (hasActiveSubmission || interruptedSubmissionNeedsCheck) {
299
+ const requestedOwner = current.requestedOwnerAid ?? current.task?.owner_aid;
300
+ if (interruptedSubmissionNeedsCheck) {
301
+ return {
302
+ handled: true,
303
+ status: 'ownership-unverified',
304
+ reply: '上一笔协议 Owner 绑定请求状态尚未确认,请先核验状态,暂不重复发起。',
305
+ };
306
+ }
307
+ return requestedOwner && requestedOwner !== actorId
308
+ ? {
309
+ handled: true,
310
+ status: 'ownership-pending-conflict',
311
+ reply: `已有发往 ${requestedOwner} 的协议 Owner 绑定请求正在处理中,请先完成或核验该请求。`,
312
+ }
313
+ : {
314
+ handled: true,
315
+ status: 'ownership-pending',
316
+ reply: '协议 Owner 绑定请求正在处理中,请在 Evol 中确认;无需重复发送 /bind。',
317
+ };
318
+ }
282
319
  const state = await ownerResolver.bind(selfAid, actorId);
283
320
  const alreadyBound = state.consensusStatus === 'consensus' && state.ownerAid === actorId;
284
321
  if (!alreadyBound && state.task && ['rejected', 'stopped', 'error'].includes(state.task.status)) {
@@ -670,6 +707,9 @@ export class MessageBridge {
670
707
  await sendReply(msg.channelId, payload.text, msg.replyContext);
671
708
  }
672
709
  admissionDeniedNotice(context, channelType) {
710
+ if (context.policy?.allowExternalContacts === false) {
711
+ return '当前 Agent 不接受外部联系消息,请由 Owner 将你的 AID 加入允许名单。';
712
+ }
673
713
  if (context.contactStatus === 'pending') {
674
714
  return '联系人申请审核中;可再次发送 /request 更新说明。';
675
715
  }
@@ -1150,9 +1190,9 @@ export class MessageBridge {
1150
1190
  return;
1151
1191
  }
1152
1192
  }
1153
- // /fa is an execution prefix, not a session-mode switch or a normal
1154
- // quick command. Only this trusted bridge path can construct the
1155
- // internal per-call authorization carried into ResponseEngine.
1193
+ // /fa on/off controls the current session; other non-empty arguments
1194
+ // request one fullaccess run. Only this trusted inbound path can create
1195
+ // the per-call authorization carried into ResponseEngine.
1156
1196
  const fullAccessCommand = parseFullAccessCommand(content);
1157
1197
  if (fullAccessCommand.matched) {
1158
1198
  const groupGuard = guardGroupSlashCommand(content, chatType);
@@ -1160,51 +1200,44 @@ export class MessageBridge {
1160
1200
  await this.sendSlashControlReply(channelName, msg, sendReply, groupGuard, adapter);
1161
1201
  return;
1162
1202
  }
1163
- const reject = async (text) => {
1164
- logger.warn(`[MessageBridge] fullaccess command rejected: channel=${channelName} `
1165
- + `actor=${authSubject.principalId ?? authSubject.actorId ?? '<none>'} reason=${text}`);
1203
+ if (msg.source !== undefined && msg.source !== 'user') {
1204
+ await sendReply(msg.channelId, '❌ /fa 只能由用户直接发送', msg.replyContext);
1205
+ return;
1206
+ }
1207
+ if (fullAccessCommand.action === 'prompt') {
1208
+ if (!authSubject.isDaemonOwner || !authSubject.principalId) {
1209
+ auditFullAccessEvent({
1210
+ event: 'fullaccess.command.rejected',
1211
+ source: 'fullaccess-command',
1212
+ decision: 'deny',
1213
+ actorId: authSubject.principalId ?? authSubject.actorId,
1214
+ processRole: authSubject.processRole,
1215
+ messageId: msg.messageId,
1216
+ reason: '仅可信 daemon-owner 可以使用 fullaccess',
1217
+ });
1218
+ await sendReply(msg.channelId, '❌ 仅可信 daemon-owner 可以使用 fullaccess', msg.replyContext);
1219
+ return;
1220
+ }
1221
+ if (!msg.messageLogContent)
1222
+ msg.messageLogContent = content;
1223
+ content = fullAccessCommand.prompt;
1224
+ executionPermissionOverride = {
1225
+ permissionMode: 'fullaccess',
1226
+ processRole: 'fullaccess-run',
1227
+ dataScope: 'daemon',
1228
+ source: 'fullaccess-command',
1229
+ authorizedBy: authSubject.principalId,
1230
+ };
1231
+ logger.warn(`[MessageBridge] fullaccess command accepted: channel=${channelName} `
1232
+ + `actor=${authSubject.principalId} message=${msg.messageId ?? '<none>'}`);
1166
1233
  auditFullAccessEvent({
1167
- event: 'fullaccess.command.rejected',
1234
+ event: 'fullaccess.command.accepted',
1168
1235
  source: 'fullaccess-command',
1169
- decision: 'deny',
1170
- actorId: authSubject.principalId ?? authSubject.actorId,
1236
+ actorId: authSubject.principalId,
1171
1237
  processRole: authSubject.processRole,
1172
1238
  messageId: msg.messageId,
1173
- reason: text,
1174
1239
  });
1175
- await sendReply(msg.channelId, `❌ ${text}`, msg.replyContext);
1176
- };
1177
- if (msg.source !== undefined && msg.source !== 'user') {
1178
- await reject('fullaccess 只能由用户直接发送的 /fa 或 /fullaccess 命令发起');
1179
- return;
1180
1240
  }
1181
- if (!fullAccessCommand.prompt) {
1182
- await reject('用法:/fa <提示词> 或 /fullaccess <提示词>');
1183
- return;
1184
- }
1185
- if (!authSubject.isDaemonOwner || !authSubject.principalId) {
1186
- await reject('仅可信 daemon-owner 可以使用 fullaccess');
1187
- return;
1188
- }
1189
- if (!msg.messageLogContent)
1190
- msg.messageLogContent = content;
1191
- content = fullAccessCommand.prompt;
1192
- executionPermissionOverride = {
1193
- permissionMode: 'fullaccess',
1194
- processRole: 'fullaccess-run',
1195
- dataScope: 'daemon',
1196
- source: 'fullaccess-command',
1197
- authorizedBy: authSubject.principalId,
1198
- };
1199
- logger.warn(`[MessageBridge] fullaccess command accepted: channel=${channelName} `
1200
- + `actor=${authSubject.principalId} message=${msg.messageId ?? '<none>'}`);
1201
- auditFullAccessEvent({
1202
- event: 'fullaccess.command.accepted',
1203
- source: 'fullaccess-command',
1204
- actorId: authSubject.principalId,
1205
- processRole: authSubject.processRole,
1206
- messageId: msg.messageId,
1207
- });
1208
1241
  }
1209
1242
  // 0. 仅阻止协议遥测进入 session / model / messages.jsonl;协议本身已在
1210
1243
  // channel/main/events/AUN/handoff 专用链路中处理和记录。
@@ -1248,6 +1281,7 @@ export class MessageBridge {
1248
1281
  // 2. 命令快速路径(去除引用前缀后检查,兼容话题中引用上文的情况)
1249
1282
  const contentForCmd = content.replace(/^(>[^\n]*\n)+\n?/, '').trim();
1250
1283
  const cmdContent = contentForCmd || content;
1284
+ const parsedFullAccessControl = parseFullAccessCommand(cmdContent);
1251
1285
  let autoMode = false;
1252
1286
  if (resolvedChannelType === 'aun' && chatType === 'group' && selfAid && msg.source !== 'handoff') {
1253
1287
  try {
@@ -1281,7 +1315,10 @@ export class MessageBridge {
1281
1315
  // A prompt such as `/fa /status` must not be re-routed as the
1282
1316
  // ordinary `/status` quick command after the prefix is removed.
1283
1317
  && !executionPermissionOverride
1284
- && !parseFullAccessCommand(cmdContent).matched
1318
+ && (!parsedFullAccessControl.matched
1319
+ || parsedFullAccessControl.action === 'status'
1320
+ || parsedFullAccessControl.action === 'on'
1321
+ || parsedFullAccessControl.action === 'off')
1285
1322
  && this.cmdHandler.isCommand(cmdContent);
1286
1323
  if (isCmd && /^\/new(?:\s|$)/i.test(cmdContent)) {
1287
1324
  // /new changes the active main-session boundary. Serialize it with
@@ -1333,14 +1370,6 @@ export class MessageBridge {
1333
1370
  return sendReply(msg.channelId, text, msg.replyContext);
1334
1371
  }, msg.peerId, msg.threadId, msg.chatType, msg.source, msg.replyContext, msg.messageId, msg.selfAID, authSubject))
1335
1372
  return;
1336
- // Commands retain their normal route. Only authenticated direct model
1337
- // input can obtain the Agent policy's per-call authorization.
1338
- if (!executionPermissionOverride && selfAid && owningAgent?.aid === selfAid) {
1339
- executionPermissionOverride = createAgentPolicyAuthorization({
1340
- agentAid: selfAid, actor: roleDetail.actor, chatType,
1341
- source: msg.source, peerType: msg.peerType,
1342
- });
1343
- }
1344
1373
  // 3. session 解析(使用 Channel 层填充的 chatType)
1345
1374
  if (!(await this.canCreateThreadSession(channelName, msg, chatType))) {
1346
1375
  // 静默丢弃:绝不向群里注入回复。
@@ -1481,6 +1510,20 @@ export class MessageBridge {
1481
1510
  causation: inboundCausation,
1482
1511
  });
1483
1512
  session = renewResult.session;
1513
+ if (!executionPermissionOverride && selfAid && owningAgent?.aid === selfAid) {
1514
+ executionPermissionOverride = createSessionFullAccessAuthorization({
1515
+ session,
1516
+ actor: roleDetail.actor,
1517
+ source: msg.source,
1518
+ peerType: msg.peerType,
1519
+ });
1520
+ if (!executionPermissionOverride && isMainSession(session) && !hasSessionFullAccessOverride(session)) {
1521
+ executionPermissionOverride = createAgentPolicyAuthorization({
1522
+ agentAid: selfAid, actor: roleDetail.actor, chatType,
1523
+ source: msg.source, peerType: msg.peerType,
1524
+ });
1525
+ }
1526
+ }
1484
1527
  if ('renewed' in renewResult && renewResult.renewed) {
1485
1528
  const notice = '已自动切换到新会话';
1486
1529
  try {
@@ -295,6 +295,20 @@ export function findMessageLogOperationMessageId(chatDir, operationId) {
295
295
  export function resolveChatDir(sessionsDir, channelType, channelId, selfAID) {
296
296
  return chatDirPath(sessionsDir, channelType, channelId, selfAID);
297
297
  }
298
+ let inboundLogListener;
299
+ export function setInboundLogListener(listener) {
300
+ inboundLogListener = listener;
301
+ }
302
+ function notifyInbound(chatDir, entry) {
303
+ if (entry.dir !== 'in' || !inboundLogListener)
304
+ return;
305
+ try {
306
+ inboundLogListener(chatDir, entry);
307
+ }
308
+ catch (e) {
309
+ logger.warn(`[MessageLog] Inbound listener failed: ${e}`);
310
+ }
311
+ }
298
312
  /** Append conversation history only. Protocol telemetry stays in its dedicated logs/stores. */
299
313
  export function appendMessageLog(chatDir, entry) {
300
314
  if (isTransientProtocolMessage(entry))
@@ -311,7 +325,9 @@ export function appendMessageLog(chatDir, entry) {
311
325
  }
312
326
  catch (e) {
313
327
  logger.warn(`[MessageLog] Failed to write message log: ${e}`);
328
+ return;
314
329
  }
330
+ notifyInbound(chatDir, entry);
315
331
  }
316
332
  /** Strict conversation-history append used by handoff reply binding. */
317
333
  export function appendMessageLogStrict(chatDir, entry, durable = false) {
@@ -323,6 +339,60 @@ export function appendMessageLogStrict(chatDir, entry, durable = false) {
323
339
  (durable ? appendJsonlDurable : appendJsonl)(messageLogPath(chatDir), entry);
324
340
  if (entry.dir === 'in')
325
341
  rememberMessageId(chatDir, entry.msgId);
342
+ notifyInbound(chatDir, entry);
343
+ }
344
+ /** Attach a capsule reference to the first admitted message of a renewed backend. */
345
+ export function associateMessageCapsule(chatDir, sessionId, capsuleId, messageId, timestamp) {
346
+ if (!capsuleId || (!messageId && timestamp === undefined))
347
+ return false;
348
+ const file = messageLogPath(chatDir);
349
+ if (!fs.existsSync(file))
350
+ return false;
351
+ try {
352
+ const lines = fs.readFileSync(file, 'utf8').split('\n');
353
+ let changed = false;
354
+ for (let index = lines.length - 1; index >= 0; index--) {
355
+ if (!lines[index]?.trim())
356
+ continue;
357
+ let entry;
358
+ try {
359
+ entry = JSON.parse(lines[index]);
360
+ }
361
+ catch {
362
+ continue;
363
+ }
364
+ if (entry.sessionId !== sessionId || entry.dir !== 'in' || isTransientProtocolMessage(entry)
365
+ || entry.msgType === 'command' || entry.content?.trim().startsWith('/renew'))
366
+ continue;
367
+ if (messageId && entry.msgId !== messageId)
368
+ continue;
369
+ if (!messageId && entry.ts !== timestamp)
370
+ continue;
371
+ if (entry.capsuleId)
372
+ return entry.capsuleId === capsuleId;
373
+ entry.capsuleId = capsuleId;
374
+ lines[index] = JSON.stringify(entry);
375
+ changed = true;
376
+ break;
377
+ }
378
+ if (!changed)
379
+ return false;
380
+ const temp = `${file}.capsule.tmp`;
381
+ const descriptor = fs.openSync(temp, 'w', 0o600);
382
+ try {
383
+ fs.writeFileSync(descriptor, lines.join('\n'));
384
+ fs.fsyncSync(descriptor);
385
+ }
386
+ finally {
387
+ fs.closeSync(descriptor);
388
+ }
389
+ fs.renameSync(temp, file);
390
+ return true;
391
+ }
392
+ catch (error) {
393
+ logger.warn(`[MessageLog] Failed to associate capsule ${capsuleId}: ${error instanceof Error ? error.message : String(error)}`);
394
+ return false;
395
+ }
326
396
  }
327
397
  export function buildInboundEntry(opts) {
328
398
  const ts = opts.timestamp || Date.now();
@@ -334,6 +404,7 @@ export function buildInboundEntry(opts) {
334
404
  ...(opts.gatewaySeq !== undefined ? { gatewaySeq: opts.gatewaySeq } : {}),
335
405
  time: formatTimestampMs(ts),
336
406
  sessionId: opts.sessionId,
407
+ capsuleId: opts.capsuleId,
337
408
  threadId: opts.threadId ?? null,
338
409
  dir: 'in',
339
410
  from: opts.from,
@@ -367,6 +438,7 @@ export function buildOutboundEntry(opts) {
367
438
  ts,
368
439
  time: formatTimestampMs(ts),
369
440
  sessionId: opts.sessionId,
441
+ capsuleId: opts.capsuleId,
370
442
  threadId: opts.threadId ?? null,
371
443
  dir: 'out',
372
444
  from: opts.from,
@@ -78,11 +78,11 @@ export class MessageQueue {
78
78
  this.activeTerminalReasons.set(queueKey, reason);
79
79
  let interruption;
80
80
  try {
81
- interruption = Promise.resolve(strict
82
- ? this.interruptCallback(sessionKey, baseagent, evolagentName, reason, timeout, true)
83
- : timeout
84
- ? this.interruptCallback(sessionKey, baseagent, evolagentName, reason, timeout)
85
- : this.interruptCallback(sessionKey, baseagent, evolagentName, reason));
81
+ const active = this.activeStates.get(queueKey);
82
+ const target = active?.taskId && Number.isSafeInteger(active.generation)
83
+ ? { taskId: active.taskId, generation: active.generation }
84
+ : undefined;
85
+ interruption = Promise.resolve(this.interruptCallback(sessionKey, baseagent, evolagentName, reason, timeout, strict, target));
86
86
  }
87
87
  catch (error) {
88
88
  interruption = Promise.reject(error);
@@ -719,6 +719,7 @@ export class MessageQueue {
719
719
  sessionId: sessionKey,
720
720
  reason: 'daemon_restart',
721
721
  agentName,
722
+ agentAid: this.activeStates.get(queueKey)?.selfAID,
722
723
  taskId: this.activeStates.get(queueKey)?.taskId,
723
724
  generation: this.activeStates.get(queueKey)?.generation,
724
725
  causation: item.message.causation,
@@ -1154,6 +1155,7 @@ export class MessageQueue {
1154
1155
  sessionId: sessionKey,
1155
1156
  reason: 'new_message',
1156
1157
  agentName: this.processingAgent.get(queueKey),
1158
+ agentAid: this.activeStates.get(queueKey)?.selfAID,
1157
1159
  taskId: this.activeStates.get(queueKey)?.taskId,
1158
1160
  generation: this.activeStates.get(queueKey)?.generation,
1159
1161
  causation: this.activeBatches.get(queueKey)?.message.causation,
@@ -1755,6 +1757,7 @@ export class MessageQueue {
1755
1757
  sessionId: sessionKey,
1756
1758
  reason,
1757
1759
  agentName,
1760
+ agentAid: activeState?.selfAID,
1758
1761
  taskId: activeState?.taskId,
1759
1762
  generation: activeState?.generation,
1760
1763
  causation: active?.message.causation,
@@ -2043,6 +2046,7 @@ export class MessageQueue {
2043
2046
  sessionId: sessionKey,
2044
2047
  reason: 'stop',
2045
2048
  agentName: name,
2049
+ agentAid: activeState?.selfAID,
2046
2050
  taskId: this.activeStates.get(queueKey)?.taskId,
2047
2051
  generation: this.activeStates.get(queueKey)?.generation,
2048
2052
  causation: this.activeBatches.get(queueKey)?.message.causation,
@@ -2317,6 +2321,7 @@ export class MessageQueue {
2317
2321
  sessionId: sessionKey,
2318
2322
  reason: 'new_message',
2319
2323
  agentName: targetAgentName,
2324
+ agentAid: this.activeStates.get(targetQueueKey)?.selfAID,
2320
2325
  taskId: this.activeStates.get(targetQueueKey)?.taskId,
2321
2326
  generation: this.activeStates.get(targetQueueKey)?.generation,
2322
2327
  causation: this.activeBatches.get(targetQueueKey)?.message.causation,
@@ -2336,6 +2341,7 @@ export class MessageQueue {
2336
2341
  this.eventBus?.publish({
2337
2342
  type: 'task:interrupted', sessionId, reason: 'new_message',
2338
2343
  agentName: this.processingAgent.get(queueKey),
2344
+ agentAid: this.activeStates.get(queueKey)?.selfAID,
2339
2345
  taskId: this.activeStates.get(queueKey)?.taskId,
2340
2346
  generation: this.activeStates.get(queueKey)?.generation,
2341
2347
  causation: active.message.causation,
@@ -1,5 +1,70 @@
1
1
  import { isDeliveryTargetForChannel } from './message-utils.js';
2
2
  import { readEvolcoreRuntimeFlavor, readEvolcoreStartedAtIso, readInstalledEvolcoreVersion, tagErrorTextWithEvolcoreVersion, } from '../../utils/evolcore-version.js';
3
+ import { getErrorRawText } from '../../utils/error-utils.js';
4
+ function appendRawErrorText(text, raw) {
5
+ if (!raw || text === raw || text.includes(`原因:${raw}`))
6
+ return text;
7
+ return `${text}\n原因:${raw}`;
8
+ }
9
+ function resolveRawErrorText(raw, fallback) {
10
+ return getErrorRawText(raw) || getErrorRawText(fallback);
11
+ }
12
+ /** Ensure every outbound error carries the best available diagnostic text. */
13
+ export function normalizeOutboundErrorPayload(payload) {
14
+ switch (payload.kind) {
15
+ case 'result.error':
16
+ case 'system.error':
17
+ case 'command.error': {
18
+ const raw = resolveRawErrorText(payload.raw, payload.text);
19
+ if (!raw)
20
+ return payload;
21
+ return {
22
+ ...payload,
23
+ text: appendRawErrorText(payload.text, raw),
24
+ raw,
25
+ };
26
+ }
27
+ case 'status.error': {
28
+ const metadata = payload.metadata;
29
+ if (!metadata)
30
+ return payload;
31
+ const raw = resolveRawErrorText(metadata.raw, metadata.message);
32
+ if (!raw)
33
+ return payload;
34
+ return {
35
+ ...payload,
36
+ metadata: {
37
+ ...metadata,
38
+ message: typeof metadata.message === 'string'
39
+ ? appendRawErrorText(metadata.message, raw)
40
+ : metadata.message,
41
+ raw,
42
+ },
43
+ };
44
+ }
45
+ case 'status.timeout': {
46
+ const metadata = payload.metadata;
47
+ if (!metadata)
48
+ return payload;
49
+ const message = metadata.message ?? (typeof metadata.totalExecutionMs === 'number'
50
+ ? `任务超过总执行时限(${Math.round(metadata.totalExecutionMs / 1000)}秒),已自动中断`
51
+ : typeof metadata.idleSec === 'number' && metadata.idleSec > 0
52
+ ? `任务超时(${metadata.idleSec}秒无响应),已自动中断`
53
+ : '任务超时,已自动中断');
54
+ const raw = resolveRawErrorText(metadata.raw, metadata.reason) || message;
55
+ return {
56
+ ...payload,
57
+ metadata: {
58
+ ...metadata,
59
+ message: appendRawErrorText(message, raw),
60
+ raw,
61
+ },
62
+ };
63
+ }
64
+ default:
65
+ return payload;
66
+ }
67
+ }
3
68
  /** 出站 payload 摘要(用于 channel-out.log)。 */
4
69
  export function summarizeOutboundPayload(payload) {
5
70
  if (!payload)
@@ -18,6 +83,8 @@ export function summarizeOutboundPayload(payload) {
18
83
  case 'command.error':
19
84
  case 'result.error':
20
85
  summary.text = payload.text;
86
+ if (payload.raw !== undefined)
87
+ summary.raw = payload.raw;
21
88
  break;
22
89
  case 'result.file':
23
90
  summary.filePath = payload.filePath;
@@ -26,6 +93,8 @@ export function summarizeOutboundPayload(payload) {
26
93
  case 'system.error':
27
94
  summary.subtype = payload.subtype;
28
95
  summary.text = payload.text;
96
+ if (payload.raw !== undefined)
97
+ summary.raw = payload.raw;
29
98
  break;
30
99
  case 'interaction':
31
100
  summary.interactionId = payload.interaction?.id;
@@ -47,6 +116,7 @@ export function summarizeOutboundPayload(payload) {
47
116
  }
48
117
  /** Add the current EvolCore version marker to user-visible error payloads. */
49
118
  export function tagErrorPayloadWithEvolcoreVersion(payload) {
119
+ payload = normalizeOutboundErrorPayload(payload);
50
120
  switch (payload.kind) {
51
121
  case 'result.error':
52
122
  case 'system.error':
@@ -51,10 +51,15 @@ export function isPrivateChatmodeRoleLocked(field, role) {
51
51
  * - 人类且非 owner/admin(含角色未知)→ proactive
52
52
  * - 人类且 owner/admin → 分层配置(未配置时取出厂默认)
53
53
  */
54
- export function chatmodeForPeerIdentity(identity, role) {
54
+ export function chatmodeForPeerIdentity(identity, role, configContext = {}) {
55
55
  if (identity.isMachine)
56
56
  return 'proactive';
57
- return resolveChatMode({ role: role ?? undefined, chatType: 'private', peerType: identity.type ?? 'human' });
57
+ return resolveChatMode({
58
+ ...configContext,
59
+ role: role ?? undefined,
60
+ chatType: 'private',
61
+ peerType: identity.type ?? 'human',
62
+ });
58
63
  }
59
64
  export function resolveChatModeForField(params) {
60
65
  return resolveChatMode({