evolcore 0.0.47 → 0.0.48

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 (218) hide show
  1. package/CHANGELOG.md +56 -1
  2. package/bin/ec-build.mjs +86 -0
  3. package/dist/agent-template/jobs.js +12 -4
  4. package/dist/agent-template/runtime.js +139 -39
  5. package/dist/agent-template/service.js +66 -13
  6. package/dist/agents/baseagent.js +60 -20
  7. package/dist/agents/claude-runner.js +34 -17
  8. package/dist/agents/codex-runner.js +31 -16
  9. package/dist/agents/ecagent-runner.js +7 -4
  10. package/dist/agents/gemini-runner.js +5 -2
  11. package/dist/agents/runner-types.js +5 -21
  12. package/dist/aun/aid/agentmd.js +5 -1
  13. package/dist/aun/service-proxy.js +4 -2
  14. package/dist/build-identity.json +1 -0
  15. package/dist/channels/aun.js +81 -24
  16. package/dist/channels/daemon.js +9 -25
  17. package/dist/cli/aun-commands.js +86 -51
  18. package/dist/cli/code-stats.js +19 -8
  19. package/dist/cli/command-log.js +1 -1
  20. package/dist/cli/daemon-commands.js +44 -43
  21. package/dist/cli/directory.js +7 -1
  22. package/dist/cli/ecmsg-gateway.js +5 -2
  23. package/dist/cli/index.js +2 -8
  24. package/dist/cli/init-channel.js +4 -6
  25. package/dist/cli/init.js +72 -50
  26. package/dist/cli/invoke-command.js +1 -1
  27. package/dist/cli/provider-command.js +74 -13
  28. package/dist/cli/role.js +61 -17
  29. package/dist/cli/stats.js +3 -3
  30. package/dist/cli/thread-command.js +16 -51
  31. package/dist/config/boot-log.js +3 -9
  32. package/dist/config/builtin-roles.js +5 -7
  33. package/dist/config/config-manager.js +2 -6
  34. package/dist/config/daemon-services.js +30 -3
  35. package/dist/config/gateway-config.js +2 -2
  36. package/dist/config/invoke-ipc-service.js +6 -4
  37. package/dist/config/peer-bind-code.js +3 -4
  38. package/dist/config/peer-book-store.js +62 -229
  39. package/dist/config/peer-book.js +26 -27
  40. package/dist/config/peer-role-resolver.js +16 -1
  41. package/dist/config/provider-identity-migration.js +4 -1
  42. package/dist/config/provider-ipc-service.js +56 -11
  43. package/dist/config/provider-menu-request.js +24 -5
  44. package/dist/config/provider-templates.js +127 -0
  45. package/dist/config/providers-config.js +59 -8
  46. package/dist/config/providers-management.js +467 -49
  47. package/dist/config/role-command-service.js +248 -1
  48. package/dist/config/schema-migration.js +105 -4
  49. package/dist/core/agent-application-service.js +6 -1
  50. package/dist/core/agent-runtime.js +4 -0
  51. package/dist/core/auth/agent-delegation.js +2 -1
  52. package/dist/core/auth/auth-gateway.js +2 -1
  53. package/dist/core/auth/delegation-authorization.js +3 -0
  54. package/dist/core/auth/operation-authorizer.js +25 -0
  55. package/dist/core/auth/operation-catalog.js +28 -64
  56. package/dist/core/capability/providers/codex-capability-provider.js +7 -8
  57. package/dist/core/channel-loader.js +18 -0
  58. package/dist/core/command/agent-control.js +32 -0
  59. package/dist/core/command/command-handler.js +81 -85
  60. package/dist/core/command/menu-catalog.js +1 -0
  61. package/dist/core/command/menu-handler.js +61 -149
  62. package/dist/core/command/menu-protocol.js +7 -1
  63. package/dist/core/command/provider-menu.js +13 -3
  64. package/dist/core/command/role-menu.js +47 -23
  65. package/dist/core/command/slash-handler.js +26 -43
  66. package/dist/core/command/team-workspace-items.js +81 -12
  67. package/dist/core/command/team-workspace-team.js +9 -71
  68. package/dist/core/command/topic-slash.js +9 -30
  69. package/dist/core/daemon-bootstrap.js +8 -1
  70. package/dist/core/daemon-control.js +7 -7
  71. package/dist/core/evolagent-registry.js +14 -1
  72. package/dist/core/file-integrity/store.js +2 -0
  73. package/dist/core/handoff/runtime.js +37 -1
  74. package/dist/core/inference/text-inference.js +3 -1
  75. package/dist/core/initialization/service.js +11 -6
  76. package/dist/core/interaction-router.js +3 -0
  77. package/dist/core/invoke/executors/text.js +72 -19
  78. package/dist/core/ipc-registration.js +2 -1
  79. package/dist/core/message/aun-ipc-sender.js +165 -55
  80. package/dist/core/message/im-renderer.js +1 -1
  81. package/dist/core/message/message-bridge.js +51 -334
  82. package/dist/core/message/message-log.js +5 -0
  83. package/dist/core/message/message-queue.js +22 -0
  84. package/dist/core/message/message-utils.js +8 -0
  85. package/dist/core/message/response-engine.js +429 -116
  86. package/dist/core/message/send-routing.js +5 -1
  87. package/dist/core/model/catalog-service.js +31 -11
  88. package/dist/core/model/model-capabilities.js +22 -4
  89. package/dist/core/model/model-catalog.js +1 -0
  90. package/dist/core/ownership/owner-resolver.js +328 -50
  91. package/dist/core/permission/protected-paths.js +6 -6
  92. package/dist/core/relation/peer-identity.js +23 -1
  93. package/dist/core/relation/same-owner-proof.js +81 -112
  94. package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
  95. package/dist/core/session/session-file-health.js +13 -7
  96. package/dist/core/session/session-fs-store.js +91 -35
  97. package/dist/core/session/session-manager.js +68 -24
  98. package/dist/core/session/session-mapper.js +14 -34
  99. package/dist/core/session/session-transcript.js +5 -1
  100. package/dist/core/task/task-activity-store.js +84 -0
  101. package/dist/core/task/task-recovery-service.js +12 -0
  102. package/dist/core/thread/command-parser.js +7 -12
  103. package/dist/core/thread/thread-context-storage.js +3 -2
  104. package/dist/core/thread/thread-operation.js +2 -13
  105. package/dist/core/thread/thread-service.js +15 -46
  106. package/dist/directory/owner-directory-admission.js +1 -1
  107. package/dist/directory/owner-directory-cache.js +45 -28
  108. package/dist/directory/owner-directory-markdown.js +13 -1
  109. package/dist/directory/owner-directory-query-operation.js +29 -3
  110. package/dist/directory/owner-directory-remarks.js +11 -3
  111. package/dist/eck/message-renderer.js +84 -24
  112. package/dist/ecweb/basic-settings-service.js +3 -1
  113. package/dist/ecweb/message-context-service.js +1 -1
  114. package/dist/ecweb/pairing.js +4 -3
  115. package/dist/ecweb/providers-service.js +26 -1
  116. package/dist/ecweb/runtime/lifecycle.js +18 -8
  117. package/dist/ecweb/runtime/proxy-access.js +74 -0
  118. package/dist/ecweb/runtime/supervisor.js +4 -2
  119. package/dist/event-center/registry.js +13 -2
  120. package/dist/event-center/runtime.js +103 -11
  121. package/dist/event-center/script-runner.js +5 -5
  122. package/dist/index.js +92 -59
  123. package/dist/ipc.js +13 -2
  124. package/dist/outputs/events.js +62 -0
  125. package/dist/outputs/protocol.js +102 -0
  126. package/dist/outputs/service.js +279 -0
  127. package/dist/paths.js +3 -0
  128. package/dist/proxy/manager.js +43 -13
  129. package/dist/services/index.js +89 -4
  130. package/dist/services/ipc-operation.js +4 -15
  131. package/dist/services/pack-manager.js +12 -1
  132. package/dist/services/router.js +21 -6
  133. package/dist/services/script-runner.js +5 -4
  134. package/dist/services/validation.js +1 -1
  135. package/dist/stats/budget.js +1 -1
  136. package/dist/stats/db.js +19 -0
  137. package/dist/stats/index.js +1 -1
  138. package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
  139. package/dist/stats/normalizer.js +2 -0
  140. package/dist/stats/query.js +35 -27
  141. package/dist/stats/role-budget.js +5 -2
  142. package/dist/stats/writer.js +10 -6
  143. package/dist/trigger/audit.js +7 -0
  144. package/dist/trigger/authorization.js +105 -11
  145. package/dist/trigger/feedback.js +10 -0
  146. package/dist/trigger/history.js +37 -11
  147. package/dist/trigger/ipc-service.js +12 -1
  148. package/dist/trigger/manager.js +1 -0
  149. package/dist/trigger/scheduler.js +7 -5
  150. package/dist/trigger/script-executor.js +2 -1
  151. package/dist/trigger/script-sandbox.js +9 -3
  152. package/dist/trigger/validation.js +22 -0
  153. package/dist/utils/cross-platform.js +73 -26
  154. package/dist/utils/error-dict.json +94 -4
  155. package/dist/utils/error-utils.js +27 -4
  156. package/dist/utils/evolcore-version.js +36 -65
  157. package/dist/utils/msg-diag.js +1 -0
  158. package/dist/utils/process-introspect.js +12 -7
  159. package/dist/utils/process-tree.js +50 -2
  160. package/dist/utils/windows-shell-trust.js +2 -0
  161. package/dist/workbench/protocol.js +80 -0
  162. package/dist/workbench/service.js +359 -0
  163. package/ecagent/dist/types.d.ts +6 -2
  164. package/kits/docs/context-assembly.md +1 -1
  165. package/kits/docs/evolcore/INDEX.md +2 -2
  166. package/kits/docs/evolcore/config.md +12 -0
  167. package/kits/docs/evolcore/directory.md +22 -3
  168. package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
  169. package/kits/docs/evolcore/model.md +10 -0
  170. package/kits/docs/evolcore/peer.md +19 -65
  171. package/kits/docs/evolcore/provider.md +123 -3
  172. package/kits/docs/evolcore/role.md +80 -0
  173. package/kits/docs/evolcore/services.md +6 -6
  174. package/kits/docs/evolcore/team-workspace.md +1 -1
  175. package/kits/docs/evolcore/thread-chain.md +14 -15
  176. package/kits/docs/evolcore/tool-authorization.md +5 -0
  177. package/kits/docs/evolcore/trigger.md +10 -0
  178. package/kits/eck_message_manifest.json +12 -0
  179. package/kits/provider-templates.json +1213 -0
  180. package/kits/rules/04-relation.md +3 -3
  181. package/kits/schemas/_meta.json +14 -2
  182. package/kits/schemas/contact-book.schema.4.json +52 -0
  183. package/kits/schemas/providers.schema.3.json +200 -0
  184. package/kits/skills/.switches.json +4 -0
  185. package/kits/skills/ability/references/calling.md +1 -1
  186. package/kits/skills/ec-group/SKILL.md +2 -2
  187. package/kits/skills/ec-identity/SKILL.md +19 -72
  188. package/kits/skills/ec-provider/SKILL.md +221 -0
  189. package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
  190. package/kits/skills/ec-trigger/SKILL.md +1 -1
  191. package/kits/skills/thread-ops/SKILL.md +34 -21
  192. package/kits/templates/message-fragments/group-batch-item.md +1 -1
  193. package/kits/templates/message-fragments/group-batch.md +1 -1
  194. package/kits/templates/message-fragments/inject-default.md +1 -1
  195. package/kits/templates/message-fragments/interrupt-insert.md +1 -0
  196. package/kits/templates/message-fragments/item-group.md +1 -1
  197. package/kits/templates/message-fragments/item-private.md +1 -1
  198. package/kits/templates/message-fragments/thread-context.md +1 -1
  199. package/kits/templates/message-fragments/trigger-session.md +1 -1
  200. package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
  201. package/kits/templates/roles/admin.json +2 -19
  202. package/kits/templates/roles/member.json +0 -3
  203. package/kits/templates/system-fragments/baseagent.md +6 -0
  204. package/kits/templates/system-fragments/commands.md +3 -3
  205. package/kits/templates/system-fragments/managed-runtime.md +1 -1
  206. package/kits/templates/system-fragments/relation.md +1 -1
  207. package/kits/templates/system-fragments/thread.md +6 -5
  208. package/package.json +6 -4
  209. package/scripts/agent-template/inspect.mjs +4 -1
  210. package/scripts/agent-template/shared/common.mjs +2 -3
  211. package/scripts/agent-template/shared/template-contract.mjs +2 -1
  212. package/scripts/agent-template/shared/template-package.mjs +9 -2
  213. package/scripts/agent-template/shared/template-runtime.mjs +20 -5
  214. package/scripts/agent-template/team-pack.mjs +6 -3
  215. package/dist/cli/peer.js +0 -127
  216. package/dist/config/peer-operation-service.js +0 -132
  217. package/dist/config/peer-request-service.js +0 -532
  218. package/dist/core/command/connect-menu.js +0 -624
@@ -11,14 +11,13 @@ import { currentContactBinding, sameContactBinding } from './contact-admission.j
11
11
  import { logger, logPreview } from '../../utils/logger.js';
12
12
  import { StreamDebouncer } from './stream-debouncer.js';
13
13
  import { appendMessageLog, appendMessageLogStrict, buildInboundEntry, isTransientProtocolMessage } from './message-log.js';
14
- import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from './message-utils.js';
14
+ import { buildEnvelope } from './message-utils.js';
15
15
  import { chatDirPath } from '../session/session-fs-store.js';
16
- import { readTopicLabel, readTopicStatus } from '../session/session-mapper.js';
16
+ import { readTopicStatus } from '../session/session-mapper.js';
17
17
  import { formatChannelKey, tryParseChannelKey } from '../channel-loader.js';
18
18
  import { agentDir, resolvePaths } from '../../paths.js';
19
- import { listStaticAgentAdmins, listStaticAgentOwners, resolvePeerRoleDetail, } from '../../config/peer-role-resolver.js';
19
+ import { resolvePeerRoleDetail, } from '../../config/peer-role-resolver.js';
20
20
  import { resolvePeerView, resolvePeerDisplayLabel, resolvePrincipal } from '../../config/peer-book.js';
21
- import { findPeerRequestNote, expirePendingPeerRequests, reviewPeerRequest, submitPeerRequest, peerRequestSubmissionProtocolResult, queryOwnPeerRequestStatus, } from '../../config/peer-request-service.js';
22
21
  import { isValidAid } from '../../aun/aid/validation.js';
23
22
  import { prepareOwnerDirectoryAdmission } from '../../directory/owner-directory-admission.js';
24
23
  import { PeerIdentityCache, formatPeerKey } from '../relation/peer-identity.js';
@@ -36,8 +35,6 @@ import { MenuTokenStore } from '../command/menu-token-store.js';
36
35
  import { SessionRenewService } from '../session/session-renew.js';
37
36
  import { createRootCausation, deriveCausation, normalizeCausation } from '../causation/context.js';
38
37
  import { recordCausationSpan } from '../causation/audit.js';
39
- import { renderActionAsText } from '../interaction-router.js';
40
- import { planApprovalRoute } from '../permission/approval-gateway.js';
41
38
  import { guardGroupSlashCommand, parseFullAccessCommand } from '../command/slash-gate.js';
42
39
  import { createAgentPolicyAuthorization, createSessionFullAccessAuthorization } from '../role/runtime-policy.js';
43
40
  import { auditFullAccessEvent } from '../auth/authorization-audit.js';
@@ -48,6 +45,18 @@ const REJECTABLE_PEER_TYPES = new Set(['ai', 'bot', 'agent', 'service']);
48
45
  const REJECTION_MAX = 3;
49
46
  const REJECTION_WINDOW_MS = 60 * 60 * 1000;
50
47
  const rejectionState = new Map();
48
+ /** Topic admission runs after session resolution and before task queueing. */
49
+ function decideTopicInbound(input) {
50
+ if (!input.isTopic)
51
+ return { action: 'proceed', reopen: false, replyArchived: false };
52
+ if (input.topicStatus === 'archived') {
53
+ return { action: 'drop-archived', reopen: false, replyArchived: input.chatType !== 'group' };
54
+ }
55
+ if (input.topicStatus === 'closed') {
56
+ return { action: 'proceed', reopen: true, replyArchived: false };
57
+ }
58
+ return { action: 'proceed', reopen: false, replyArchived: false };
59
+ }
51
60
  export function shouldBlockInboundContact(input) {
52
61
  if (!input.selfAid) {
53
62
  return { blocked: false, status: 'unsupported-channel' };
@@ -467,175 +476,6 @@ export class MessageBridge {
467
476
  }
468
477
  return false;
469
478
  }
470
- async handleContactRequestProtocol(input) {
471
- const { context, msg, content, owningAgent, adapter, sendReply } = input;
472
- const requestMatch = /^\s*\/request(?:\s+([\s\S]*?))?\s*$/i.exec(content);
473
- let protocolType;
474
- let protocolPayload;
475
- try {
476
- const parsed = JSON.parse(content);
477
- protocolPayload = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
478
- ? parsed
479
- : undefined;
480
- protocolType = protocolPayload?.type === 'contact.request.query'
481
- ? 'query'
482
- : protocolPayload?.type === 'contact.request.submit' ? 'submit' : undefined;
483
- }
484
- catch { /* slash command */ }
485
- if (!requestMatch && !protocolType)
486
- return false;
487
- if (context.channelType === 'aun') {
488
- // The App owns requests; retired commands cannot create a second approval state.
489
- return true;
490
- }
491
- // Slash commands keep their human-facing response semantics. Structured
492
- // App requests use contact.request.response and never fall through to the
493
- // normal command/session pipeline.
494
- if (requestMatch) {
495
- // Blacklist remains the first gate even though slash controls are
496
- // recognized before ordinary admission. Let the normal blocked path
497
- // decide whether an agent/bot/service gets a limited rejection.
498
- if (context.contactStatus === 'blocked')
499
- return false;
500
- if (context.channelType !== 'aun') {
501
- await this.sendAdmissionControlReply(context, msg, sendReply, '联系人申请仅支持 AUN 私聊。');
502
- return true;
503
- }
504
- if (context.chatType !== 'private') {
505
- await this.sendAdmissionControlReply(context, msg, sendReply, '联系人申请仅支持 AUN 私聊。');
506
- return true;
507
- }
508
- if (!context.primaryId || context.principal?.principalStatus !== 'native_aid') {
509
- await this.sendAdmissionControlReply(context, msg, sendReply, '无法验证当前 AUN 身份,未提交联系人申请。');
510
- return true;
511
- }
512
- try {
513
- const submission = await submitPeerRequest({
514
- selfAid: context.selfAid,
515
- applicantAid: context.primaryId,
516
- note: requestMatch[1],
517
- sourceChannelKey: context.channelKey,
518
- routeKind: 'private',
519
- });
520
- if ((submission.code === 'submitted' || submission.code === 'resubmitted') && submission.requestId) {
521
- void this.deliverContactReviewCard(context.selfAid, context.primaryId, submission, owningAgent)
522
- .catch(error => logger.warn(`[MessageBridge] Contact review delivery failed: ${error instanceof Error ? error.message : String(error)}`));
523
- }
524
- await this.sendAdmissionControlReply(context, msg, sendReply, this.contactRequestReply(submission));
525
- }
526
- catch (error) {
527
- logger.warn(`[MessageBridge] Contact request submission failed: ${error instanceof Error ? error.message : String(error)}`);
528
- await this.sendAdmissionControlReply(context, msg, sendReply, '当前无法受理联系人申请,请稍后再试。');
529
- }
530
- return true;
531
- }
532
- // The structured protocol is AUN-only. For a blocked external alias,
533
- // return false so the existing blacklist response/silence policy applies;
534
- // never emit a custom payload through a non-AUN adapter.
535
- if (context.contactStatus === 'blocked' && context.channelType !== 'aun')
536
- return false;
537
- if (context.channelType !== 'aun')
538
- return true;
539
- if (context.chatType !== 'private')
540
- return true;
541
- if (context.principal?.principalStatus !== 'native_aid' || !context.primaryId) {
542
- await this.sendContactRequestProtocolResponse(adapter, msg, {
543
- status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
544
- }, owningAgent?.name);
545
- return true;
546
- }
547
- if (context.contactStatus === 'blocked') {
548
- await this.sendContactRequestProtocolResponse(adapter, msg, {
549
- status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
550
- }, owningAgent?.name);
551
- return true;
552
- }
553
- let result;
554
- if (protocolType === 'query') {
555
- try {
556
- result = await queryOwnPeerRequestStatus({
557
- selfAid: context.selfAid,
558
- applicantAid: context.primaryId,
559
- requestId: protocolPayload && Object.prototype.hasOwnProperty.call(protocolPayload, 'request_id')
560
- ? protocolPayload.request_id
561
- : undefined,
562
- });
563
- }
564
- catch (error) {
565
- logger.warn(`[MessageBridge] Contact request query failed: ${error instanceof Error ? error.message : String(error)}`);
566
- result = { status: 'NOT_ALLOWED', requestId: null, expiresAt: null };
567
- }
568
- }
569
- else {
570
- try {
571
- if (protocolPayload && Object.prototype.hasOwnProperty.call(protocolPayload, 'note')
572
- && typeof protocolPayload?.note !== 'string') {
573
- await this.sendContactRequestProtocolResponse(adapter, msg, {
574
- status: 'NOT_ALLOWED', requestId: null, expiresAt: null,
575
- }, owningAgent?.name);
576
- return true;
577
- }
578
- const submission = await submitPeerRequest({
579
- selfAid: context.selfAid,
580
- applicantAid: context.primaryId,
581
- note: typeof protocolPayload?.note === 'string' ? protocolPayload.note : undefined,
582
- sourceChannelKey: context.channelKey,
583
- routeKind: 'private',
584
- });
585
- result = peerRequestSubmissionProtocolResult(submission);
586
- if ((submission.code === 'submitted' || submission.code === 'resubmitted') && submission.requestId) {
587
- void this.deliverContactReviewCard(context.selfAid, context.primaryId, submission, owningAgent)
588
- .catch(error => logger.warn(`[MessageBridge] Contact review delivery failed: ${error instanceof Error ? error.message : String(error)}`));
589
- }
590
- }
591
- catch (error) {
592
- logger.warn(`[MessageBridge] Contact request submission failed: ${error instanceof Error ? error.message : String(error)}`);
593
- result = { status: 'NOT_ALLOWED', requestId: null, expiresAt: null };
594
- }
595
- }
596
- await this.sendContactRequestProtocolResponse(adapter, msg, result, owningAgent?.name);
597
- return true;
598
- }
599
- contactRequestReply(result) {
600
- switch (result.code) {
601
- case 'submitted': return '联系人申请已提交,等待管理员审核。';
602
- case 'resubmitted': return '联系人申请已更新,等待管理员审核。';
603
- case 'already-contact': return '你已经是联系人。';
604
- case 'owner': return '你已经是 Owner。';
605
- case 'blocked': return CONTACT_REJECTION_NOTICE;
606
- case 'rate-limited': return '联系人申请过于频繁,请稍后再试。';
607
- case 'capacity': return '当前申请较多,请稍后再试。';
608
- case 'no-owner': return '当前无法受理联系人申请。';
609
- case 'invalid-applicant': return '无法验证当前 AUN 身份,未提交联系人申请。';
610
- case 'invalid-note': return '申请说明不能超过 500 个字符。';
611
- }
612
- }
613
- async sendContactRequestProtocolResponse(adapter, msg, result, agentName) {
614
- if (!adapter?.send)
615
- return;
616
- await adapter.send(buildEnvelope({
617
- taskId: `contact-request-${randomBytes(4).toString('hex')}`,
618
- channel: adapter.channelName,
619
- channelId: msg.channelId,
620
- agentName: agentName ?? '<unknown>',
621
- replyContext: {
622
- ...(msg.replyContext ?? {}),
623
- metadata: {
624
- ...(msg.replyContext?.metadata ?? {}),
625
- ...evolMenuResponseTransportMetadata(msg.protectedHeaders?.sdk_version),
626
- },
627
- },
628
- }), {
629
- kind: 'custom',
630
- channelType: 'aun',
631
- payload: {
632
- type: 'contact.request.response',
633
- status: result.status,
634
- request_id: result.requestId,
635
- expires_at: result.expiresAt,
636
- },
637
- });
638
- }
639
479
  async sendAdmissionControlReply(context, msg, sendReply, text) {
640
480
  if (!text || !consumeAdmissionReplyBudget(context))
641
481
  return false;
@@ -685,155 +525,6 @@ export class MessageBridge {
685
525
  }
686
526
  return '当前不接受非联系人消息。联系人申请仅支持 AUN 私聊。';
687
527
  }
688
- async deliverContactReviewCard(selfAid, applicantAid, submission, owningAgent) {
689
- if (!this.interactionRouter || !submission.requestId || !submission.expiresAt || !submission.submittedAt) {
690
- return false;
691
- }
692
- const ownerAdapterKey = formatChannelKey({ type: 'aun', selfAID: selfAid, name: 'main' });
693
- const ownerAdapter = this.processor.getChannelInfo?.(ownerAdapterKey)?.adapter;
694
- const resolveApproverCandidates = () => ({
695
- owners: listStaticAgentOwners(selfAid, { fresh: true }),
696
- admins: listStaticAgentAdmins(selfAid, { fresh: true }),
697
- });
698
- const { owners, admins } = resolveApproverCandidates();
699
- const route = planApprovalRoute({
700
- id: submission.requestId,
701
- sessionId: `contact-request:${selfAid}:${submission.requestId}`,
702
- toolName: 'contact.request.review',
703
- toolInput: { applicantAid, requestId: submission.requestId },
704
- summary: `Review contact request from ${applicantAid}`,
705
- grantable: true,
706
- // Contact membership is an Agent-owner decision. Do not use the broader
707
- // agent_manager policy here: that policy intentionally prefers an Admin,
708
- // which made request cards invisible to the configured Owner.
709
- approverPolicy: 'agent_owner',
710
- createdAt: Date.parse(submission.submittedAt),
711
- }, {
712
- userId: applicantAid,
713
- chatType: 'private',
714
- selfAid,
715
- approvalRouting: {
716
- approverPolicy: 'agent_owner',
717
- owners,
718
- admins,
719
- resolveApproverCandidates,
720
- ownerAdapter,
721
- forceHandoff: true,
722
- selfAid,
723
- originSessionId: `contact-request:${selfAid}:${submission.requestId}`,
724
- originChannel: 'aun',
725
- originChannelId: applicantAid,
726
- originPeerId: applicantAid,
727
- originPrincipalId: applicantAid,
728
- },
729
- });
730
- if (route.kind !== 'handoff') {
731
- logger.warn(`[MessageBridge] Contact review route unavailable: self=${selfAid} request=${submission.requestId} reason=${route.kind === 'unavailable' ? route.reason : 'local-route-not-allowed'}`);
732
- return false;
733
- }
734
- let note = '申请说明不可用';
735
- try {
736
- note = findPeerRequestNote(selfAid, submission.requestId) || '(未填写)';
737
- }
738
- catch { }
739
- const expiresAtMs = Date.parse(submission.expiresAt);
740
- const sessionId = `contact-request:${selfAid}:${submission.requestId}`;
741
- const interaction = {
742
- type: 'interaction',
743
- id: submission.requestId,
744
- channelId: route.approverOperatorId,
745
- sessionId,
746
- initiatorId: route.approverOperatorId,
747
- expiresAt: expiresAtMs,
748
- kind: {
749
- kind: 'action',
750
- title: '联系人申请审核',
751
- bodyFormat: 'plain',
752
- body: `申请人:${applicantAid}\n申请说明:${note}\n提交时间:${submission.submittedAt}\n截止时间:${submission.expiresAt}\n\n此卡片只处理当前这一次联系人申请。申请人重新提交、已被他人处理或审批超时,均不会修改当前联系人状态。卡片因重启或投递失效时,可在联系人列表处理仍未到期的 pending;已过期申请需由申请人重新发送 /request。`,
753
- buttons: [
754
- { key: 'approve', label: '通过', style: 'primary' },
755
- { key: 'reject', label: '拒绝', style: 'default' },
756
- { key: 'block', label: '拉黑', style: 'danger', confirm: { title: '拉黑申请人', body: `确定拉黑 ${applicantAid}?` } },
757
- ],
758
- },
759
- };
760
- this.interactionRouter.register(submission.requestId, sessionId, async (action, _values, operatorId) => {
761
- if (action !== 'approve' && action !== 'reject' && action !== 'block')
762
- return false;
763
- const reviewed = await reviewPeerRequest({
764
- selfAid,
765
- primaryId: applicantAid,
766
- requestId: submission.requestId,
767
- expectedContactRevision: submission.peerRevision,
768
- approverId: route.approverOperatorId,
769
- actorId: String(operatorId || ''),
770
- decision: action,
771
- });
772
- try {
773
- await this.sendContactReviewOutcome(route.adapter, route.approverOperatorId, applicantAid, reviewed.code, owningAgent?.name);
774
- }
775
- catch (error) {
776
- logger.warn(`[MessageBridge] Contact review outcome notification failed: request=${submission.requestId} error=${error instanceof Error ? error.message : String(error)}`);
777
- }
778
- if (reviewed.code === 'approved' || reviewed.code === 'rejected' || reviewed.code === 'blocked') {
779
- try {
780
- await this.notifyContactApplicant(route.adapter, applicantAid, reviewed.code, submission.requestId, submission.expiresAt, owningAgent?.name);
781
- }
782
- catch (error) {
783
- logger.warn(`[MessageBridge] Contact applicant notification failed: request=${submission.requestId} error=${error instanceof Error ? error.message : String(error)}`);
784
- }
785
- return true;
786
- }
787
- return false;
788
- }, {
789
- timeoutMs: Math.max(1, expiresAtMs - Date.now()),
790
- initiatorId: route.approverOperatorId,
791
- initiatorChannelKey: route.approverChannelKey,
792
- onTimeout: () => { void expirePendingPeerRequests(selfAid); },
793
- onCancel: reason => route.adapter.invalidateInteraction?.(submission.requestId, reason),
794
- });
795
- const envelope = buildEnvelope({
796
- taskId: `contact-request-${submission.requestId}`,
797
- sessionId,
798
- channel: route.adapter.channelName,
799
- channelId: route.approverOperatorId,
800
- agentName: owningAgent?.name ?? selfAid,
801
- chatmode: 'interactive',
802
- replyContext: { delivery: { chatType: 'private' }, metadata: { source: 'handoff', chatmode: 'interactive' } },
803
- });
804
- const receipt = await sendInteractionPayload(route.adapter, envelope, interaction, renderActionAsText(interaction), envelope.replyContext);
805
- const accepted = isInteractionSendAccepted(receipt);
806
- if (!accepted)
807
- await this.interactionRouter.cancel(submission.requestId, 'delivery_failed');
808
- return accepted;
809
- }
810
- async sendContactReviewOutcome(adapter, ownerAid, applicantAid, code, agentName) {
811
- const text = code === 'approved' ? `已通过 ${applicantAid} 的联系人申请。`
812
- : code === 'rejected' ? `已拒绝 ${applicantAid} 的联系人申请。`
813
- : code === 'blocked' ? `已拉黑 ${applicantAid}。`
814
- : code === 'request-expired' ? '审核已过期。'
815
- : code === 'request-stale' ? '申请已更新或已被处理。'
816
- : code === 'revision-conflict' ? '联系人列表已变化,请从联系人列表重新审核。'
817
- : '当前无审核权限。';
818
- await adapter.send(buildEnvelope({ channel: adapter.channelName, channelId: ownerAid, agentName: agentName ?? '<unknown>', delivery: { chatType: 'private' } }), { kind: 'system.notice', text, subtype: 'contact-review' });
819
- }
820
- async notifyContactApplicant(adapter, applicantAid, code, requestId, expiresAt, agentName) {
821
- await adapter.send(buildEnvelope({
822
- channel: adapter.channelName,
823
- channelId: applicantAid,
824
- agentName: agentName ?? '<unknown>',
825
- replyContext: { delivery: { chatType: 'private' }, metadata: evolMenuResponseTransportMetadata() },
826
- }), {
827
- kind: 'custom',
828
- channelType: 'aun',
829
- payload: {
830
- type: 'contact.request.response',
831
- status: code === 'approved' ? 'APPROVED' : code === 'rejected' ? 'REJECTED' : 'NOT_ALLOWED',
832
- request_id: requestId,
833
- expires_at: expiresAt,
834
- },
835
- });
836
- }
837
528
  getDebouncer(channelName, channelType) {
838
529
  let d = this.debouncers.get(channelName);
839
530
  if (!d) {
@@ -939,16 +630,15 @@ export class MessageBridge {
939
630
  return;
940
631
  }
941
632
  }
942
- if (!trustedHandoffEcho && await this.handleContactRequestProtocol({
943
- context: admissionPreflight.context,
944
- msg,
945
- content,
946
- owningAgent,
947
- adapter,
948
- sendReply,
949
- })) {
633
+ // Retired controls must not enter the command/session/LLM pipeline.
634
+ if (/^\s*\/request(?:\s|$)/i.test(content))
950
635
  return;
636
+ try {
637
+ const legacyControl = JSON.parse(content);
638
+ if (typeof legacyControl?.type === 'string' && legacyControl.type.startsWith('contact.request.'))
639
+ return;
951
640
  }
641
+ catch { /* ordinary text */ }
952
642
  const ownershipFailure = selfAid ? ownerResolver.snapshot(selfAid) : undefined;
953
643
  if (!trustedHandoffEcho && !admissionPreflight.context.isOwner
954
644
  && admissionPreflight.allow
@@ -1495,7 +1185,35 @@ export class MessageBridge {
1495
1185
  if (!releaseAdmission)
1496
1186
  releaseAdmission = await this.acquireAdmission(admissionRoute);
1497
1187
  const hadMainSession = msg.threadId ? true : this.sessionManager.hasMainSession(channelName, msg.channelId, msg.channelType || effectiveChannelType, msg.selfAID || selfAid);
1498
- let session = diagnosticSession ?? await this.sessionManager.getOrCreateSession(channelName, msg.channelId, effectiveProjectPath, msg.threadId, Object.keys(metadata).length ? metadata : undefined, this.extractTopicName(msg), msg.peerId, chatType, owningAgent?.baseagent, msg.selfAID, msg.channelType || effectiveChannelType, msg.peerType, identity, readTopicLabel(msg) ?? readTopicLabel(msg.replyContext?.metadata), readTopicStatus(msg) ?? readTopicStatus(msg.replyContext?.metadata));
1188
+ let session = diagnosticSession ?? await this.sessionManager.getOrCreateSession(channelName, msg.channelId, effectiveProjectPath, msg.threadId, Object.keys(metadata).length ? metadata : undefined, this.extractTopicName(msg), msg.peerId, chatType, owningAgent?.baseagent, msg.selfAID, msg.channelType || effectiveChannelType, msg.peerType, identity, readTopicStatus(msg) ?? readTopicStatus(msg.replyContext?.metadata));
1189
+ // 归档话题不再入队;closed 收到新消息时回退 active,主话题不受此状态影响。
1190
+ const topicGate = decideTopicInbound({
1191
+ isTopic: isTopicSession(session),
1192
+ topicStatus: session.topicStatus,
1193
+ chatType,
1194
+ });
1195
+ if (topicGate.action === 'drop-archived') {
1196
+ logger.info(`[MessageBridge] 话题已归档,丢弃入站消息 session=${session.id} from=${msg.peerId} chatType=${chatType}`);
1197
+ if (topicGate.replyArchived && adapter?.send) {
1198
+ await adapter.send(buildEnvelope({
1199
+ taskId: `archived-${randomBytes(5).toString('hex')}`,
1200
+ channel: channelName,
1201
+ channelId: msg.channelId,
1202
+ chatmode: 'interactive',
1203
+ replyContext: {
1204
+ ...msg.replyContext,
1205
+ ...(msg.threadId ? { threadId: msg.threadId } : {}),
1206
+ },
1207
+ }), { kind: 'result.text', text: '话题已归档', isFinal: true }).catch((error) => {
1208
+ logger.warn(`[MessageBridge] 归档提示发送失败 session=${session.id}: ${error}`);
1209
+ });
1210
+ }
1211
+ return;
1212
+ }
1213
+ if (topicGate.reopen) {
1214
+ await this.sessionManager.setTopicStatus(session.id, 'active');
1215
+ session.topicStatus = 'active';
1216
+ }
1499
1217
  if (isTopicSession(session) && typeof this.messageQueue.reserveSessionIngress === 'function') {
1500
1218
  releaseSessionIngress = this.messageQueue.reserveSessionIngress(session.id);
1501
1219
  }
@@ -1594,7 +1312,6 @@ export class MessageBridge {
1594
1312
  mentions: msg.mentions, mentionAids: msg.mentionAids, threadId: msg.threadId,
1595
1313
  isMentioned: msg.isMentioned,
1596
1314
  topicName: this.extractTopicName(msg),
1597
- label: session.label,
1598
1315
  topicStatus: session.topicStatus,
1599
1316
  replyContext: msg.replyContext,
1600
1317
  source: msg.source,
@@ -98,6 +98,11 @@ export function classifyAunPayloadForLog(payload) {
98
98
  return { msgType: 'text', content };
99
99
  }
100
100
  const record = payload;
101
+ // Card submissions may carry credentials, including replies to expired cards
102
+ // after a restart. Never rely on the live card registry or caller flags to redact.
103
+ if (record.type === 'action_card_reply') {
104
+ return { msgType: 'action_card_reply', payloadType: 'action_card_reply', content: '[卡片回复]' };
105
+ }
101
106
  const rawType = typeof record.type === 'string' && record.type.trim()
102
107
  ? record.type.trim()
103
108
  : undefined;
@@ -60,6 +60,15 @@ export class MessageQueue {
60
60
  * 打乱既有调度顺序。
61
61
  */
62
62
  interruptingMessages = new Map();
63
+ /**
64
+ * 回队批次的打断者 ID:queueKey → messageId,由 disposeInterruptedBatch 在
65
+ * requeued_pre_submit 时写入,下一次 dequeue 取走(一次性)。
66
+ *
67
+ * 不能直接读 interruptingMessages:那个 map 在中断批次的 finally 里就被清掉了,
68
+ * 而回队的旧输入要到下一轮 processNext 才出队。渲染层据此把中断插入标记挂到
69
+ * 打断者身上,而不是被中断的旧输入。
70
+ */
71
+ requeuedByInterrupt = new Map();
63
72
  eventBus;
64
73
  recentMessageIds = new Set();
65
74
  DEDUP_WINDOW = 60_000; // 1 分钟窗口
@@ -1367,6 +1376,14 @@ export class MessageQueue {
1367
1376
  const pendingBeforeDequeue = queue.slice();
1368
1377
  const items = this.dequeueGreedy(queue, sessionId);
1369
1378
  const merged = items.length === 1 ? items[0] : this.mergeItems(items);
1379
+ // 批次里若有「打断了上一轮」的那条,把它的 ID 带下去:渲染层据此把中断插入标记
1380
+ // 挂到打断者身上。未提交的旧输入回队后与打断者同批(disposeInterruptedBatch),
1381
+ // 只按顺序取第一条会把标记错挂在被中断的那条旧消息上。
1382
+ const interruptingId = this.requeuedByInterrupt.get(queueKey);
1383
+ if (interruptingId) {
1384
+ this.requeuedByInterrupt.delete(queueKey); // 一次性:只标记紧接的这批
1385
+ merged.message.interruptedByMessageId = interruptingId;
1386
+ }
1370
1387
  const rawItems = items.flatMap(item => this.partsOf(item).map(part => this.itemFromPart(part)));
1371
1388
  const rawParts = rawItems.map(item => this.partFromItem(item));
1372
1389
  // activeItem 复用已合并的 message,仅额外持有 parts 用于持久化和撤回定位(不重复 merge)
@@ -1496,6 +1513,10 @@ export class MessageQueue {
1496
1513
  logger.info(`[Queue] pre-submit requeue skipped: key=${queueKey} other pending=${pendingWithoutInterrupt.length}`);
1497
1514
  return 'none';
1498
1515
  }
1516
+ // 记下打断者:回队批次里既有被中断的旧输入,也有打断它的那条新消息,
1517
+ // 渲染层只按顺序取第一条会把标记挂错对象(见 Message.interruptedByMessageId)。
1518
+ if (interrupting?.messageId)
1519
+ this.requeuedByInterrupt.set(queueKey, interrupting.messageId);
1499
1520
  queue.unshift(...requeued);
1500
1521
  // 按物理顺序重建逻辑队列,避免把旧输入追加到新消息之后,导致 FIFO
1501
1522
  // 在下一次 reorderPhysical 时颠倒回队消息与打断消息的顺序。
@@ -1583,6 +1604,7 @@ export class MessageQueue {
1583
1604
  || !!message.executionPermissionOverride
1584
1605
  || !!message.handoffDelivery
1585
1606
  || !!message.triggerMeta
1607
+ || !!message.selfAddressedMeta
1586
1608
  || !!message.causation?.trigger?.path.length;
1587
1609
  }
1588
1610
  isOriginHandoff(message) {
@@ -1,6 +1,14 @@
1
1
  import { sessionLocalTopicId, sessionTopicThreadId } from '../thread/topic-id.js';
2
2
  import { renderCommandCardAsText, renderActionAsText } from '../interaction-router.js';
3
3
  export const DEFAULT_NOOP_SENTINEL = '[[NOOP]]';
4
+ /** Only internal task sources may opt into silent completion. */
5
+ export function messageNoopSentinel(message) {
6
+ if (message.source === 'trigger')
7
+ return message.triggerMeta?.noopSentinel;
8
+ if (message.source === 'self-address')
9
+ return message.selfAddressedMeta?.noopSentinel;
10
+ return undefined;
11
+ }
4
12
  export function isNoopText(text, sentinel = DEFAULT_NOOP_SENTINEL) {
5
13
  return sentinel.length > 0 && text.trimStart().startsWith(sentinel);
6
14
  }