evolcore 0.0.43-test.2 → 0.0.43-test.3

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 (110) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/agents/ecagent-runner.js +13 -6
  3. package/dist/aun/aid/agentmd.js +21 -1
  4. package/dist/aun/msg/p2p.js +4 -2
  5. package/dist/channels/aun.js +79 -48
  6. package/dist/channels/daemon.js +4 -0
  7. package/dist/cli/agent-create.js +3 -5
  8. package/dist/cli/aun-commands.js +17 -19
  9. package/dist/cli/directory.js +101 -56
  10. package/dist/cli/index.js +1 -1
  11. package/dist/cli/peer.js +2 -1
  12. package/dist/cli/task-context.js +3 -1
  13. package/dist/config/access-policy.js +0 -1
  14. package/dist/config/builtin-role-templates.js +2 -2
  15. package/dist/config/builtin-roles.js +2 -1
  16. package/dist/config/config-field-policy.js +5 -0
  17. package/dist/config/config-manager.js +25 -10
  18. package/dist/config/peer-role-resolver.js +23 -1
  19. package/dist/config/role-schema.js +26 -2
  20. package/dist/config/role-service.js +9 -4
  21. package/dist/config/role-store.js +30 -8
  22. package/dist/core/auth/auth-gateway.js +14 -4
  23. package/dist/core/auth/operation-authorizer.js +17 -0
  24. package/dist/core/auth/operation-catalog.js +12 -2
  25. package/dist/core/channel-runtime.js +5 -0
  26. package/dist/core/command/agent-control.js +1 -1
  27. package/dist/core/command/agentmd-menu-request.js +50 -0
  28. package/dist/core/command/agentmd-menu.js +156 -0
  29. package/dist/core/command/command-handler.js +39 -3
  30. package/dist/core/command/menu-catalog.js +13 -0
  31. package/dist/core/command/menu-handler.js +59 -9
  32. package/dist/core/command/menu-protocol.js +8 -0
  33. package/dist/core/command/role-menu.js +23 -9
  34. package/dist/core/command/slash-handler.js +48 -21
  35. package/dist/core/daemon-lifecycle.js +9 -1
  36. package/dist/core/evolagent.js +5 -4
  37. package/dist/core/lifecycle-notice.js +185 -0
  38. package/dist/core/message/aun-ipc-sender.js +30 -24
  39. package/dist/core/message/contact-admission.js +1 -19
  40. package/dist/core/message/im-renderer.js +64 -28
  41. package/dist/core/message/message-admission.js +15 -65
  42. package/dist/core/message/message-bridge.js +18 -5
  43. package/dist/core/message/message-utils.js +9 -0
  44. package/dist/core/message/peer-mode.js +16 -8
  45. package/dist/core/message/response-engine.js +56 -35
  46. package/dist/core/ownership/owner-resolver.js +72 -34
  47. package/dist/core/permission/ec-command-parser.js +24 -10
  48. package/dist/core/relation/pa-team.js +127 -0
  49. package/dist/core/role/runtime-policy.js +4 -3
  50. package/dist/core/thread/thread-service.js +6 -4
  51. package/dist/directory/owner-directory-admission.js +0 -3
  52. package/dist/directory/owner-directory-cache.js +197 -15
  53. package/dist/directory/owner-directory-markdown.js +44 -21
  54. package/dist/directory/owner-directory-policy.js +1 -1
  55. package/dist/directory/owner-directory-query-operation.js +219 -97
  56. package/dist/directory/owner-directory-request-operation.js +76 -0
  57. package/dist/directory/owner-directory-scope.js +35 -4
  58. package/dist/directory/owner-directory-search.js +76 -23
  59. package/dist/directory/owner-directory-store.js +5 -38
  60. package/dist/directory/owner-directory-text.js +60 -0
  61. package/dist/eck/kit-renderer.js +6 -3
  62. package/dist/eck/message-renderer.js +2 -5
  63. package/dist/ecweb/message-context-service.js +4 -0
  64. package/dist/index.js +11 -0
  65. package/dist/paths.js +4 -2
  66. package/dist/product.js +1 -0
  67. package/dist/response-system/engines/v1/index.js +2 -4
  68. package/dist/response-system/modes/single-session/index.js +1 -1
  69. package/dist/trigger/scheduler.js +8 -3
  70. package/dist/utils/error-utils.js +7 -5
  71. package/ecagent/README.md +18 -0
  72. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  73. package/ecagent/dist/harness/agent-harness.js +24 -8
  74. package/ecagent/dist/harness/compaction/compaction.js +3 -0
  75. package/ecagent/dist/harness/types.d.ts +1 -0
  76. package/kits/docs/channels/aun.md +1 -1
  77. package/kits/docs/context-assembly.md +1 -1
  78. package/kits/docs/evolcore/INDEX.md +4 -1
  79. package/kits/docs/evolcore/directory.md +125 -35
  80. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  81. package/kits/docs/evolcore/file-navigation.md +265 -0
  82. package/kits/docs/evolcore/msg.md +1 -0
  83. package/kits/docs/evolcore/peer.md +2 -1
  84. package/kits/docs/evolcore/response.md +2 -2
  85. package/kits/docs/evolcore/task.md +2 -0
  86. package/kits/docs/evolcore/tool-authorization.md +1 -1
  87. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  88. package/kits/eck_manifest.json +7 -3
  89. package/kits/eck_manifest.memory.json +26 -1
  90. package/kits/schemas/_meta.json +16 -3
  91. package/kits/schemas/agent-config.schema.20.json +925 -0
  92. package/kits/schemas/relation-config.schema.13.json +289 -0
  93. package/kits/schemas/role-config.schema.3.json +1038 -0
  94. package/kits/schemas/role-registry.schema.1.json +3 -2
  95. package/kits/templates/soul/00-GUIDE.md +20 -42
  96. package/kits/templates/system-fragments/channel.md +2 -2
  97. package/kits/templates/system-fragments/commands.md +1 -1
  98. package/kits/templates/system-fragments/directory-contacts.md +1 -1
  99. package/kits/templates/system-fragments/personal-assistant.md +2 -17
  100. package/kits/templates/system-fragments/reply.md +7 -0
  101. package/kits/templates/system-fragments/session.md +6 -2
  102. package/package.json +2 -2
  103. package/dist/eck/paactive-context.js +0 -45
  104. package/dist/response-system/engines/v1/paactive-flow.js +0 -18
  105. package/kits/eck_manifest.paactive.json +0 -528
  106. package/kits/eck_message_manifest.paactive.json +0 -233
  107. package/kits/templates/message-fragments/paactive/item.md +0 -3
  108. package/kits/templates/system-fragments/paactive/channel.md +0 -25
  109. package/kits/templates/system-fragments/paactive/reply.md +0 -25
  110. package/kits/templates/system-fragments/paactive/session.md +0 -32
@@ -28,6 +28,7 @@ import { WEB_PACKAGE_NAME, RESTART_REQUEST_ID_ENV, RUNTIME_HOME_ENV, SESSION_ID_
28
28
  import { read as cfgRead, resolveEffective, resolveEffectiveFieldWithSource, routeFieldPath, write as cfgWrite, ConfigTarget, } from '../../config/config-manager.js';
29
29
  import { agentCreateCapabilities, execAgentAction, execAgentQuery, execAgentOptions, execAidAvatar, resolveProjectPath } from './agent-control.js';
30
30
  import { readInitialization } from '../../cli/agent-create.js';
31
+ import { agentMdMenuService } from './agentmd-menu.js';
31
32
  import { isValidAid } from '../../aun/aid/validation.js';
32
33
  import { gatewayList, gatewayUpdate, gatewayDelete, gatewayTest, gatewayModels, gatewaySetPrice } from '../../config/gateway-config.js';
33
34
  import { displaySessionTitle } from '../session/session-title.js';
@@ -731,6 +732,8 @@ function resolveMenuChatmodeTarget(params) {
731
732
  };
732
733
  }
733
734
  function readMenuChatmode(target) {
735
+ if (target.field === 'group')
736
+ return { value: 'proactive', source: 'builtin' };
734
737
  if (target.roleLocked)
735
738
  return { value: 'proactive', source: 'role' };
736
739
  try {
@@ -741,7 +744,8 @@ function readMenuChatmode(target) {
741
744
  field: target.fieldPath,
742
745
  configuredValue: resolved.value,
743
746
  });
744
- const mode = target.scope === 'agent' ? decision.effectiveValue
747
+ const mode = target.scope === 'agent'
748
+ && (decision.effectiveValue !== 'paactive' || target.role === 'owner') ? decision.effectiveValue
745
749
  : resolveChatModeForField({ ...target.sel, role: target.role, field: target.field });
746
750
  if (isChatMode(mode)) {
747
751
  return {
@@ -750,7 +754,7 @@ function readMenuChatmode(target) {
750
754
  ? 'role'
751
755
  : toMenuSource(resolved.source) ?? 'builtin',
752
756
  ...(resolved.value === 'paactive' && mode !== 'paactive' ? {
753
- fallbackReason: 'paactive 仅在 active AUN 人类 owner/admin 私聊主会话或话题生效,当前场景或角色策略未满足条件。',
757
+ fallbackReason: 'paactive 仅在 active AUN 人类 owner 私聊主会话或话题生效,当前场景或角色策略未满足条件。',
754
758
  } : {}),
755
759
  };
756
760
  }
@@ -1083,6 +1087,8 @@ function buildMenuIntent(verb, cmdBase, args, action, value, fromControlChannel
1083
1087
  ? 'agent'
1084
1088
  : args?.scope === 'relation' ? 'relation' : 'agent';
1085
1089
  if (verb === 'query') {
1090
+ if (cmdBase === '/aid' && args?.view === 'agentmd')
1091
+ return intent('ec.aid.agentmd.get', 'agent');
1086
1092
  if (cmdBase === '/baseagent-models')
1087
1093
  return intent('baseagent.models.list', 'process');
1088
1094
  if (cmdBase === '/baseagents') {
@@ -1229,6 +1235,8 @@ function buildMenuIntent(verb, cmdBase, args, action, value, fromControlChannel
1229
1235
  }
1230
1236
  if (cmdBase === '/aid' && action === 'avatar')
1231
1237
  return intent('ec.aid.avatar', 'agent', { action });
1238
+ if (cmdBase === '/aid' && action === 'agentmd.publish')
1239
+ return intent('ec.aid.agentmd.put', 'agent', { action });
1232
1240
  if (cmdBase === '/trigger') {
1233
1241
  if (action === 'create' || action === 'set')
1234
1242
  return intent('trigger.create', 'relation', { action });
@@ -2204,9 +2212,10 @@ export async function getSubMenuItems(cmd, channel, channelId, userId, args, ove
2204
2212
  throw { code: target.code, message: target.error };
2205
2213
  const currentMode = readMenuChatmode(target).value;
2206
2214
  return [
2207
- { value: 'interactive', label: '交互模式', selected: currentMode === 'interactive' },
2215
+ ...(target.field !== 'group'
2216
+ ? [{ value: 'interactive', label: '交互模式', selected: currentMode === 'interactive' }] : []),
2208
2217
  { value: 'proactive', label: '主动模式', selected: currentMode === 'proactive' },
2209
- ...(target.field === 'private' && !target.roleLocked
2218
+ ...(target.field === 'private' && target.role === 'owner'
2210
2219
  && (target.scope === 'agent' || target.sel.peerKey?.startsWith('aun#'))
2211
2220
  ? [{ value: 'paactive', label: 'PA 模式', selected: currentMode === 'paactive' }] : []),
2212
2221
  ];
@@ -2593,6 +2602,14 @@ export async function execMenuQuery(cmd, channel, channelId, userId, args, expli
2593
2602
  });
2594
2603
  if (authDenied)
2595
2604
  return authDenied;
2605
+ if (cmdBase === '/aid' && args?.view === 'agentmd') {
2606
+ try {
2607
+ return { data: await agentMdMenuService.query(subject, args) };
2608
+ }
2609
+ catch (error) {
2610
+ return menuResultFailure(error);
2611
+ }
2612
+ }
2596
2613
  if (cmdBase === '/trigger') {
2597
2614
  if (args?.view !== 'detail' && args?.view !== 'history') {
2598
2615
  return { error: 'Unsupported trigger query view', code: 'INVALID_ARGS' };
@@ -3293,11 +3310,23 @@ export async function execMenuUpdate(cmd, value, channel, channelId, userId, ove
3293
3310
  let session = loadedContext.session;
3294
3311
  const evolagent = loadedContext.evolagent;
3295
3312
  if (transportReplyContext?.threadId) {
3296
- try {
3297
- session = await loadMenuTopicSession(this.sessionManager, channel, channelId, transportReplyContext.threadId);
3313
+ if (cmdBase === '/model' || cmdBase === '/effort') {
3314
+ // Model settings belong to the Agent and can be changed from a locally
3315
+ // created topic before its first message has registered a Core session.
3316
+ try {
3317
+ session = await this.sessionManager.getThreadSession(channel, channelId, transportReplyContext.threadId) ?? session;
3318
+ }
3319
+ catch (error) {
3320
+ logger.debug(`[MenuHandler] topic context unavailable for Agent model update: thread=${transportReplyContext.threadId}: ${error instanceof Error ? error.message : String(error)}`);
3321
+ }
3298
3322
  }
3299
- catch (error) {
3300
- return menuResultFailure(error);
3323
+ else {
3324
+ try {
3325
+ session = await loadMenuTopicSession(this.sessionManager, channel, channelId, transportReplyContext.threadId);
3326
+ }
3327
+ catch (error) {
3328
+ return menuResultFailure(error);
3329
+ }
3301
3330
  }
3302
3331
  }
3303
3332
  if (cmdBase === '/baseagent-models')
@@ -3676,6 +3705,12 @@ export async function execMenuUpdate(cmd, value, channel, channelId, userId, ove
3676
3705
  });
3677
3706
  if ('error' in target)
3678
3707
  return target;
3708
+ if (target.field === 'group' && arg !== 'proactive') {
3709
+ return { error: '群聊仅支持 proactive 模式', code: 'NOT_APPLICABLE' };
3710
+ }
3711
+ if (arg === 'paactive' && identity.role !== 'owner') {
3712
+ return { error: 'paactive 模式仅限 owner', code: 'ROLE_VALUE_NOT_ALLOWED' };
3713
+ }
3679
3714
  if ((arg === 'interactive' || arg === 'paactive') && target.roleLocked) {
3680
3715
  return { error: '私聊交互模式仅限 owner/admin,当前角色固定为 proactive', code: 'ROLE_VALUE_NOT_ALLOWED' };
3681
3716
  }
@@ -3941,9 +3976,24 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
3941
3976
  return { error: `不支持 gateway action: ${action}`, code: 'NOT_SUPPORTED' };
3942
3977
  }
3943
3978
  const isMenuAdmin = isManagementRole(authIdentity.role);
3944
- // ── /aid avatar ──
3979
+ // ── /aid AgentMD and avatar ──
3945
3980
  // Canonical avatar action; legacy agent/update patch.avatar reuses the same uploader.
3946
3981
  if (cmdBase === '/aid') {
3982
+ if (action === 'agentmd.publish') {
3983
+ try {
3984
+ const data = await agentMdMenuService.publish(subject, args ?? {});
3985
+ this.eventBus?.publish({
3986
+ type: 'agent:updated', aid: data.aid, nameChanged: data.nameChanged, timestamp: Date.now(),
3987
+ });
3988
+ if (typeof data.avatar === 'string') {
3989
+ this.eventBus?.publish({ type: 'agent:avatar_updated', aid: data.aid, avatar: data.avatar, timestamp: Date.now() });
3990
+ }
3991
+ return { data };
3992
+ }
3993
+ catch (error) {
3994
+ return menuResultFailure(error);
3995
+ }
3996
+ }
3947
3997
  if (action !== 'avatar')
3948
3998
  return { error: `不支持 aid action: ${action}`, code: 'NOT_SUPPORTED' };
3949
3999
  const result = await execAidAvatar(args);
@@ -8,6 +8,7 @@ import { validateIdleSeconds } from '../session/session-idle-monitor.js';
8
8
  import { parseFileSearchArgs } from './file-search.js';
9
9
  import { validateProviderMenuRequest } from '../../config/provider-menu-request.js';
10
10
  import { validatePaWorkspaceItemsArgs } from './pa-workspace-items.js';
11
+ import { validateAgentMdMenuRequest } from './agentmd-menu-request.js';
11
12
  export const MENU_REQUEST_TYPES = new Set([
12
13
  'menu.token.request',
13
14
  'menu.list',
@@ -353,6 +354,11 @@ export function validateMenuRequest(request) {
353
354
  if (request.args !== undefined && (!request.args || typeof request.args !== 'object' || Array.isArray(request.args))) {
354
355
  return { code: 'INVALID_ARGUMENT', message: 'Menu request args must be an object' };
355
356
  }
357
+ if ((request.name === 'aid' || firstCommandToken(request.cmd) === '/aid')
358
+ && (request.args?.view === 'agentmd'
359
+ || (typeof request.action === 'string' && request.action.startsWith('agentmd.')))) {
360
+ return validateAgentMdMenuRequest({ type: request.type, action: request.action, args: request.args });
361
+ }
356
362
  if (request.name === 'slash-commands' || firstCommandToken(request.cmd) === '/evolhelp') {
357
363
  if (type !== 'menu.query')
358
364
  return { code: 'NOT_SUPPORTED', message: 'slash-commands only supports menu.query' };
@@ -644,6 +650,8 @@ const STABLE_CODES = new Set([
644
650
  'INITIALIZE_AGENTMD_VERIFY_FAILED', 'INITIALIZE_OWNER_CONFLICT', 'INITIALIZE_AVATAR_FAILED',
645
651
  'INITIALIZE_FAILED', 'MODEL_UNAVAILABLE', 'MODEL_NOT_CONFIGURED', 'BASEAGENT_REQUIRED',
646
652
  'CONTROL_AID_RESERVED', 'CONTROL_AID_CONFLICT', 'HOST_AID_RESERVED', 'AGENT_IDENTITY_UNVERIFIED',
653
+ 'OWNER_UNAVAILABLE', 'OWNERSHIP_CONFLICT', 'PROTECTED_FIELD', 'AGENTMD_UNVERIFIED', 'AGENTMD_NOT_FOUND',
654
+ 'REMOTE_VERSION_UNAVAILABLE', 'REMOTE_VERSION_CONFLICT', 'PUBLISH_NOT_CONFIRMED',
647
655
  ]);
648
656
  export function normalizeMenuError(error) {
649
657
  const source = error && typeof error === 'object' ? error : {};
@@ -5,6 +5,7 @@ import { ConfigTarget, read, resolveEffectiveWithSources, write } from '../../co
5
5
  import { getBuiltinRolesConfig, getRoleDefinition, isValidUserRoleName, readRolesConfig, } from '../../config/roles.js';
6
6
  import { BUILTIN_USER_ROLES, MANAGEMENT_ROLES, expectedRoleRank, isManagementRole } from '../../config/builtin-roles.js';
7
7
  import { checkRoleAccess, isStaticAgentOwner, resolvePeerRoleDetail } from '../../config/peer-role-resolver.js';
8
+ import { preparePaTeamQualification } from '../relation/pa-team.js';
8
9
  import { relationFieldWriteOperation, resolveRoleFieldPermission, } from '../../config/config-field-policy.js';
9
10
  import { evaluateRoleOperationCapability } from '../auth/operation-authorizer.js';
10
11
  import { listOperations } from '../auth/operation-catalog.js';
@@ -476,17 +477,19 @@ function updateDefaultRoles(context, args, value) {
476
477
  const self = context.self;
477
478
  if (!isObject(value))
478
479
  throw invalidJsonType(self, 'defaultRoles', 'object');
479
- assertOnlyKeys(value, ['private', 'group'], 'defaultRoles', self);
480
+ assertOnlyKeys(value, ['private', 'group', 'paTeam'], 'defaultRoles', self);
480
481
  if (!Object.prototype.hasOwnProperty.call(value, 'private') || !Object.prototype.hasOwnProperty.call(value, 'group')) {
481
482
  throw validationFailed(self, undefined, [{ field: 'defaultRoles', code: 'MISSING_FIELD', message: 'private and group are required' }]);
482
483
  }
484
+ const registry = readRoleRegistry(self);
483
485
  const nextDefaults = {
484
486
  private: validateAssignableRole(value.private, self, 'defaultRoles.private'),
485
487
  group: validateAssignableRole(value.group, self, 'defaultRoles.group'),
488
+ paTeam: validateAssignableRole(Object.prototype.hasOwnProperty.call(value, 'paTeam')
489
+ ? value.paTeam ?? 'member' : registry.defaultRoles.paTeam ?? 'member', self, 'defaultRoles.paTeam'),
486
490
  };
487
491
  assertPolicyRevision(self, args);
488
- const registry = readRoleRegistry(self);
489
- const changesAdminDefault = ['private', 'group'].some(scene => registry.defaultRoles[scene] !== nextDefaults[scene]
492
+ const changesAdminDefault = ['private', 'group', 'paTeam'].some(scene => registry.defaultRoles[scene] !== nextDefaults[scene]
490
493
  && (registry.defaultRoles[scene] === 'admin' || nextDefaults[scene] === 'admin'));
491
494
  if (!isDaemonOwnerControl(context) && context.actorRole !== 'owner' && changesAdminDefault) {
492
495
  throw roleError('NOT_ALLOWED', 'Only an owner can set or replace an admin default role', self, {
@@ -741,9 +744,10 @@ async function deleteRole(context, args) {
741
744
  const registry = readRoleRegistry(self);
742
745
  const nextRegistry = clone(registry);
743
746
  nextRegistry.roles = nextRegistry.roles.filter(item => item !== roleId);
744
- for (const scene of ['private', 'group']) {
745
- if (nextRegistry.defaultRoles[scene] === roleId)
746
- nextRegistry.defaultRoles[scene] = replacement ?? null;
747
+ for (const scene of ['private', 'group', 'paTeam']) {
748
+ const current = scene === 'paTeam' ? nextRegistry.defaultRoles[scene] ?? 'member' : nextRegistry.defaultRoles[scene];
749
+ if (current === roleId)
750
+ nextRegistry.defaultRoles[scene] = replacement ?? (scene === 'paTeam' ? 'member' : null);
747
751
  }
748
752
  const changes = [
749
753
  {
@@ -775,7 +779,7 @@ async function assignmentInventory(context, args, policyRevision) {
775
779
  const items = [];
776
780
  if (args?.includeDefaults !== false) {
777
781
  const defaults = effectiveDefaultRoles(self);
778
- for (const scene of ['private', 'group']) {
782
+ for (const scene of ['private', 'group', 'paTeam']) {
779
783
  const roleId = defaults[scene];
780
784
  if (roleId && (!roleFilter || roleFilter === roleId)) {
781
785
  items.push({ target: { kind: 'default', scene }, roleId, relationRevision: null });
@@ -819,6 +823,8 @@ async function targetSnapshot(context, args, policyRevision) {
819
823
  const target = context.fromControlChannel
820
824
  ? normalized
821
825
  : await validateTargetExists(context, normalized, { allowAuthenticatedPrivateActor: true });
826
+ if (target.kind === 'private')
827
+ await preparePaTeamQualification(self, target.peerAid);
822
828
  const relation = readRelation(target.peerKey, self);
823
829
  const roleView = targetRoleView(self, target, relation?.config ?? null);
824
830
  const override = target.kind === 'private'
@@ -1306,7 +1312,7 @@ function readAgent(self) {
1306
1312
  }
1307
1313
  function effectiveDefaultRoles(self) {
1308
1314
  const defaults = readRolesConfig(self).defaultRoles ?? {};
1309
- return { private: defaults.private ?? null, group: defaults.group ?? null };
1315
+ return { private: defaults.private ?? null, group: defaults.group ?? null, paTeam: defaults.paTeam ?? 'member' };
1310
1316
  }
1311
1317
  function policyDocument(agent) {
1312
1318
  const store = readRoleStore(agent.aid);
@@ -1488,7 +1494,7 @@ function relationTargetKind(self, config, channelId, known = { groups: new Set()
1488
1494
  }
1489
1495
  function countRoleUsage(self, relations, roleId) {
1490
1496
  const configuredDefaults = effectiveDefaultRoles(self);
1491
- const defaultScenes = ['private', 'group'].filter(scene => configuredDefaults[scene] === roleId);
1497
+ const defaultScenes = ['private', 'group', 'paTeam'].filter(scene => configuredDefaults[scene] === roleId);
1492
1498
  let privateRelations = 0;
1493
1499
  let groupRelations = 0;
1494
1500
  for (const relation of relations) {
@@ -1525,6 +1531,14 @@ function validateRoleDomainTransactionChanges(self, registry, changes) {
1525
1531
  field: 'registry', code: 'SCHEMA_INVALID', message: error.message ?? 'invalid role registry',
1526
1532
  })));
1527
1533
  }
1534
+ const validatedRegistry = registry;
1535
+ for (const scene of ['private', 'group', 'paTeam']) {
1536
+ const roleId = scene === 'paTeam' ? validatedRegistry.defaultRoles[scene] ?? 'member' : validatedRegistry.defaultRoles[scene];
1537
+ if (roleId !== null && (roleId === 'owner' || !validatedRegistry.roles.includes(roleId))) {
1538
+ throw validationFailed(self, roleId, [{ field: `defaultRoles.${scene}`, code: 'INVALID_ROLE',
1539
+ message: 'Default role must reference an assignable registered role' }]);
1540
+ }
1541
+ }
1528
1542
  for (const change of changes) {
1529
1543
  if (!change.after || !change.file.endsWith('.json') || change.file.endsWith('index.json'))
1530
1544
  continue;
@@ -24,6 +24,7 @@ import { getDaemonOwners, ownerResolver, refreshOwnershipForAuthorization, OWNER
24
24
  import { authorizationNextStep, formatAuthorizationDenial } from '../auth/authorization-denial.js';
25
25
  import { resolvePermissionMode, writeAgentModelConfig } from '../model/config-scope.js';
26
26
  import { formatPeerKey } from '../relation/peer-identity.js';
27
+ import { preparePaTeamQualification } from '../relation/pa-team.js';
27
28
  import { auditFullAccessEvent } from '../auth/authorization-audit.js';
28
29
  import { isMainSession, isTopicSession, isTopicThreadId, sessionTopicThreadId } from '../thread/topic-id.js';
29
30
  import { modelMatches, getCatalog, assertCatalogSelectable, resolveCatalogModel, CONFIGURABLE_EFFORTS, configurableEfforts } from '../model/model-catalog.js';
@@ -42,6 +43,9 @@ import { MAX_AUN_ATTACHMENT_SIZE } from '../../aun/msg/upload.js';
42
43
  import { DEFAULT_SESSION_LOOP_SECONDS, MAX_SESSION_LOOP_SECONDS, MIN_SESSION_LOOP_SECONDS, refreshSessionLoopTarget, resolveCurrentSessionLoopTarget, resolveSessionLoopTarget, sessionLoopPayload, validateIdleSeconds, writeSessionLoopConfig, } from '../session/session-idle-monitor.js';
43
44
  const allEfforts = CONFIGURABLE_EFFORTS;
44
45
  const PERMISSION_MODE_KEYS = PUBLIC_PERMISSION_MODES;
46
+ function formatSessionPolicyStatus(name, scope, enabled, updated = false) {
47
+ return `${updated ? '✅ ' : ''}${name} 当前生效:${enabled ? '开启' : '关闭'}(${scope})`;
48
+ }
45
49
  function formatUpgradeEvent(event) {
46
50
  if (event.event === 'upgrade.progress')
47
51
  return `⏳ ${event.message}`;
@@ -428,6 +432,9 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
428
432
  allowTransient: true,
429
433
  includeDaemon: /^\/(?:restart|upgrade|update|reload|pair|fa|fullaccess|diag)(?:\s|$)/i.test(normalizedContent),
430
434
  });
435
+ if (this.resolveChannelType(channel) === 'aun' && narrowedChatType === 'private') {
436
+ await preparePaTeamQualification(selfAID ?? this.agentRegistry?.resolveByChannel(channel)?.aid ?? this.resolveSelfAID(channel), userId);
437
+ }
431
438
  const identityConversationId = narrowedChatType === 'group' ? channelId : userId;
432
439
  const resolvedIdentity = overrideIdentity ?? this.sessionManager.resolveIdentity(channel, userId, narrowedChatType, identityConversationId);
433
440
  const authSubject = overrideSubject ?? buildAuthSubject({
@@ -492,6 +499,8 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
492
499
  || topicAuthSession?.chatType
493
500
  || activeSession?.chatType
494
501
  || (chatType === 'group' ? 'group' : 'private');
502
+ const chatmodeChoices = activeChatType === 'group' ? 'proactive'
503
+ : identity.role === 'owner' ? 'interactive|proactive|paactive' : 'interactive|proactive';
495
504
  const groupSlash = applyGroupSlashPolicy && activeChatType === 'group';
496
505
  if (applyGroupSlashPolicy) {
497
506
  const groupGuard = guardGroupSlashCommand(normalizedContent, activeChatType);
@@ -623,7 +632,8 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
623
632
  const payload = sessionLoopPayload(current);
624
633
  return {
625
634
  kind: 'system.notice',
626
- text: `当前 idle 触发(${current.level},session=${current.session.id}):${payload.value ? `开启,${payload.idleSeconds} 秒` : '关闭'}`,
635
+ text: formatSessionPolicyStatus('idle 触发', current.level, payload.value === true)
636
+ + (payload.value ? `(${payload.idleSeconds} 秒)` : ''),
627
637
  subtype: 'session.loop.current',
628
638
  };
629
639
  }
@@ -655,7 +665,8 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
655
665
  return null;
656
666
  return {
657
667
  kind: 'system.notice',
658
- text: `✅ idle 触发(${updated.level},session=${updated.session.id})已${payload.value ? `开启(${payload.idleSeconds} 秒)` : '关闭'}`,
668
+ text: formatSessionPolicyStatus('idle 触发', updated.level, payload.value === true, true)
669
+ + (payload.value ? `(${payload.idleSeconds} 秒)` : ''),
659
670
  subtype: 'session.loop.updated',
660
671
  };
661
672
  }
@@ -681,21 +692,21 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
681
692
  return { kind: 'command.error', text: '❌ /fa 需要同一身份同时具备 Agent Owner 和 daemon Owner 权限' };
682
693
  }
683
694
  const status = sessionFullAccessStatus(commandSession, principalId);
695
+ const formatStatus = (current, updated = false) => formatSessionPolicyStatus('fullaccess', current.scope, current.effective, updated)
696
+ + ';Agent 全局:' + (current.globalEnabled ? '开启' : '关闭')
697
+ + ';作用域设置:' + (current.localEnabled ? '开启' : '关闭')
698
+ + (current.globalEnabled ? '(被全局覆盖)' : '');
684
699
  if (fullAccessControl.action === 'status') {
685
- const scope = isTopicSession(commandSession) ? 'session' : 'relation';
686
700
  return {
687
701
  kind: 'system.notice',
688
- text: '当前 fullaccess(' + scope + ',session=' + commandSession.id + '):'
689
- + (status.effective ? '开启' : '关闭')
690
- + '\nAgent 全局:' + (status.globalEnabled ? '开启(局部开关不生效)' : '关闭')
691
- + '\n局部开关:' + (status.localEnabled ? '开启' : '关闭'),
702
+ text: formatStatus(status),
692
703
  subtype: 'session.fullaccess.current',
693
704
  };
694
705
  }
695
706
  if (status.globalEnabled) {
696
707
  return {
697
708
  kind: 'system.notice',
698
- text: 'Agent 全局 fullaccess 已开启,/fa on/off 不生效;局部设置未修改。',
709
+ text: formatStatus(status) + ';Agent 全局已开启,当前作用域设置未修改。',
699
710
  subtype: 'session.fullaccess.unchanged',
700
711
  };
701
712
  }
@@ -704,12 +715,13 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
704
715
  }
705
716
  const enabled = fullAccessControl.action === 'on';
706
717
  try {
718
+ let updatedSession;
707
719
  if (isTopicSession(commandSession)) {
708
720
  const latest = await this.sessionManager.getThreadSession(channel, channelId, threadId);
709
721
  if (!latest || latest.id !== commandSession.id || !isTopicSession(latest)) {
710
722
  return { kind: 'command.error', text: '❌ 当前话题已发生变化,请重新执行 /fa' };
711
723
  }
712
- this.sessionManager.updateSessionFullAccess(latest.id, { enabled, authorizedBy: principalId });
724
+ updatedSession = this.sessionManager.updateSessionFullAccess(latest.id, { enabled, authorizedBy: principalId });
713
725
  }
714
726
  else {
715
727
  const latest = await this.sessionManager.getActiveSession(channel, channelId);
@@ -717,6 +729,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
717
729
  return { kind: 'command.error', text: '❌ 当前主会话已发生变化,请重新执行 /fa' };
718
730
  }
719
731
  updateRelationSessionFullAccess(latest, { enabled, authorizedBy: principalId });
732
+ updatedSession = latest;
720
733
  }
721
734
  auditFullAccessEvent({
722
735
  event: enabled ? 'fullaccess.session-policy.configured' : 'fullaccess.session-policy.deescalated',
@@ -730,8 +743,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
730
743
  });
731
744
  return {
732
745
  kind: 'system.notice',
733
- text: '✅ 当前' + (isTopicSession(commandSession) ? '话题 EC 会话' : '主会话')
734
- + ' fullaccess 已' + (enabled ? '开启' : '关闭'),
746
+ text: formatStatus(sessionFullAccessStatus(updatedSession, principalId), true),
735
747
  subtype: 'session.fullaccess.updated',
736
748
  };
737
749
  }
@@ -908,7 +920,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
908
920
  ...((canReadChatmode || canSetChatmode || canReadMentionmode || canSetMentionmode) ? [
909
921
  '',
910
922
  '💬 聊天设置:',
911
- ...(canReadChatmode || canSetChatmode ? [` /chatmode${canSetChatmode ? ' [interactive|proactive|paactive]' : ''} - 查看${canSetChatmode ? '或切换' : ''}会话模式`] : []),
923
+ ...(canReadChatmode || canSetChatmode ? [` /chatmode${canSetChatmode ? ` [${chatmodeChoices}]` : ''} - 查看${canSetChatmode ? '或切换' : ''}会话模式`] : []),
912
924
  ...(canReadLoop ? [` /loop${canUpdateLoop ? ' [on [seconds]|off]' : ''} - 查看${canUpdateLoop ? '或设置' : ''}当前会话的单次闲置触发`] : []),
913
925
  ...(canReadMentionmode || canSetMentionmode ? [` /mention${canSetMentionmode ? ' [mention-only|disabled]' : ''} - 查看${canSetMentionmode ? '或切换' : ''}群聊 @ 处理模式`] : []),
914
926
  ] : []),
@@ -952,7 +964,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
952
964
  ...((canReadChatmode || canSetChatmode) ? [
953
965
  '',
954
966
  '💬 聊天设置:',
955
- ` /chatmode${canSetChatmode ? ' [interactive|proactive|paactive]' : ''} - 查看${canSetChatmode ? '或切换' : ''}会话模式`,
967
+ ` /chatmode${canSetChatmode ? ` [${chatmodeChoices}]` : ''} - 查看${canSetChatmode ? '或切换' : ''}会话模式`,
956
968
  ] : []),
957
969
  ...(canReadLoop ? ['', ` /loop${canUpdateLoop ? ' [on [seconds]|off]' : ''} - 查看${canUpdateLoop ? '或设置' : ''}当前会话的单次闲置触发`] : []),
958
970
  ...(canReadPermission || canAnswerPermission ? [
@@ -1000,7 +1012,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1000
1012
  '',
1001
1013
  '💬 聊天设置:',
1002
1014
  ' /activity [all|text|none] - 查看/控制中间输出显示模式',
1003
- ...(canReadChatmode || canSetChatmode ? [` /chatmode${canSetChatmode ? ' [interactive|proactive|paactive]' : ''} - 查看${canSetChatmode ? '/切换' : ''}会话模式(被动响应或主动推进)`] : []),
1015
+ ...(canReadChatmode || canSetChatmode ? [` /chatmode${canSetChatmode ? ` [${chatmodeChoices}]` : ''} - 查看${canSetChatmode ? '/切换' : ''}会话模式(被动响应或主动推进)`] : []),
1004
1016
  ...(canReadMentionmode || canSetMentionmode ? [` /mention${canSetMentionmode ? ' [mention-only|disabled]' : ''} - 查看${canSetMentionmode ? '/切换' : ''}群聊 @ 处理模式`] : []),
1005
1017
  ...(canReadLoop ? [` /loop${canUpdateLoop ? ' [on [seconds]|off]' : ''} - 查看${canUpdateLoop ? '或设置' : ''}当前会话的单次闲置触发`] : []),
1006
1018
  '',
@@ -1212,7 +1224,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1212
1224
  cmds.push({ command: '/file', args: isOwner ? '[channel] <path>' : '<path>', description: '发送项目内文件', category: '工具', roles: [identity.role] });
1213
1225
  // 聊天设置
1214
1226
  if (canReadChatmode || canSetChatmode)
1215
- cmds.push({ command: '/chatmode', ...(canSetChatmode ? { args: '[interactive|proactive|paactive]' } : {}), description: `查看${canSetChatmode ? '/切换' : ''}会话模式(被动响应或主动推进)`, category: '聊天设置', roles: [identity.role] });
1227
+ cmds.push({ command: '/chatmode', ...(canSetChatmode ? { args: `[${chatmodeChoices}]` } : {}), description: `查看${canSetChatmode ? '/切换' : ''}会话模式(被动响应或主动推进)`, category: '聊天设置', roles: [identity.role] });
1216
1228
  if (canReadMentionmode || canSetMentionmode)
1217
1229
  cmds.push({ command: '/mention', ...(canSetMentionmode ? { args: '[mention-only|disabled]' } : {}), description: `查看${canSetMentionmode ? '/切换' : ''}群聊 @ 处理模式`, category: '聊天设置', roles: [identity.role] });
1218
1230
  // 交互
@@ -2186,7 +2198,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2186
2198
  return null;
2187
2199
  return { kind: 'command.result', text: `✅ 中间输出模式: ${activityArg}(${label})` };
2188
2200
  }
2189
- // /chatmode 命令:查看/切换当前 relation 的有效会话模式(interactive | proactive)
2201
+ // /chatmode 命令:私聊提供 interactive/proactive/paactive,群聊固定 proactive
2190
2202
  // - 查看:所有人可用
2191
2203
  // - 设置:单聊任何角色可设置;群聊仅管理员可设置
2192
2204
  if (normalizedContent === '/chatmode' || normalizedContent.startsWith('/chatmode ')) {
@@ -2196,10 +2208,11 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2196
2208
  const currentMode = getEffectiveChatmode(existingChatmodeSession);
2197
2209
  // 尝试发送 CommandCard 卡片
2198
2210
  const modes = [
2199
- { key: 'interactive', name: '交互模式', desc: '被动响应:收到消息时才回复,回复直接显示' },
2211
+ ...(activeChatType !== 'group'
2212
+ ? [{ key: 'interactive', name: '交互模式', desc: '被动响应:收到消息时才回复,回复直接显示' }] : []),
2200
2213
  { key: 'proactive', name: '主动模式', desc: '主动推进:流式输出静默,由 Agent 自调 ctl send 发声' },
2201
2214
  ...((existingChatmodeSession?.channelType ?? this.resolveChannelType?.(channel)) === 'aun'
2202
- && activeChatType === 'private' && !isPrivateChatmodeRoleLocked('private', identity.role)
2215
+ && activeChatType === 'private' && identity.role === 'owner'
2203
2216
  ? [{ key: 'paactive', name: 'PA 模式', desc: '自动文本显示为 activity,正式回复由 Agent 显式发送' }] : []),
2204
2217
  ];
2205
2218
  const interaction = {
@@ -2232,10 +2245,13 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2232
2245
  return null;
2233
2246
  // 卡片降级:fall through 到下方文本输出
2234
2247
  // 降级:文本
2235
- return { kind: 'command.result', text: `会话模式: ${currentMode} 用法: /chatmode <interactive|proactive|paactive>` };
2248
+ return { kind: 'command.result', text: `会话模式: ${currentMode} 用法: /chatmode <${chatmodeChoices}>` };
2236
2249
  }
2237
2250
  if (!isChatMode(arg)) {
2238
- return { kind: 'command.error', text: `❌ 无效模式: ${arg}\n可选: interactive / proactive / paactive` };
2251
+ return { kind: 'command.error', text: `❌ 无效模式: ${arg}\n可选: ${chatmodeChoices.split('|').join(' / ')}` };
2252
+ }
2253
+ if (activeChatType === 'group' && arg !== 'proactive') {
2254
+ return { kind: 'command.error', text: '❌ 群聊仅支持 proactive 模式' };
2239
2255
  }
2240
2256
  if (activeChatType === 'group' && !isAdmin) {
2241
2257
  return { kind: 'command.error', text: '❌ 群聊中切换会话模式仅限管理员使用' };
@@ -2254,6 +2270,12 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2254
2270
  return { kind: 'command.error', text: `❌ ${target.error}` };
2255
2271
  }
2256
2272
  const currentMode = readSlashChatmode(target);
2273
+ if (target.field === 'group' && arg !== 'proactive') {
2274
+ return { kind: 'command.error', text: '❌ 群聊仅支持 proactive 模式' };
2275
+ }
2276
+ if (arg === 'paactive' && identity.role !== 'owner') {
2277
+ return { kind: 'command.error', text: '❌ paactive 模式仅限 owner' };
2278
+ }
2257
2279
  if (arg === currentMode) {
2258
2280
  return { kind: 'command.result', text: `📋 当前会话模式已是 ${arg}` };
2259
2281
  }
@@ -2577,7 +2599,12 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2577
2599
  return { kind: 'command.error', text: `❌ 当前 Agent (${currentSessionAgent.name}) 不支持 /compact` };
2578
2600
  }
2579
2601
  if (sendMessage) {
2580
- await sendMessage(channelId, '⏳ 正在压缩会话上下文...', this.getReplyContext(session));
2602
+ const text = '⏳ 正在压缩会话上下文...';
2603
+ await sendMessage(channelId, text, this.getReplyContext(session), {
2604
+ kind: 'system.notice',
2605
+ text,
2606
+ subtype: 'session.compacting',
2607
+ });
2581
2608
  }
2582
2609
  // Resolve the same relation/agent effective model used for normal turns.
2583
2610
  // The runner instance's model is only the final fallback; without this
@@ -166,7 +166,7 @@ export function resumePendingSessions({ sessionManager, messageQueue, droppedTri
166
166
  });
167
167
  }
168
168
  }
169
- export function createDaemonShutdown({ disposePluginResources, ipcServer, readySignalPath, bindService, ecwebSupervisor, messageQueue, permissionGateway, removePermissionConfigListener, stopStatsPersistence, triggerSchedulers, agentMap, eventBus, removeGroupInviteConfigListener, groupInviteReviewService, channelLoader, channelInstances, controlChannel, sessionManager, removeAll, exit, }) {
169
+ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices, ipcServer, readySignalPath, bindService, ecwebSupervisor, messageQueue, permissionGateway, removePermissionConfigListener, stopStatsPersistence, triggerSchedulers, agentMap, eventBus, removeGroupInviteConfigListener, groupInviteReviewService, channelLoader, channelInstances, controlChannel, sessionManager, removeAll, exit, }) {
170
170
  let shutdownSignal = 'unknown';
171
171
  let shutdownInProgress = false;
172
172
  return async (signal, traceId) => {
@@ -175,6 +175,14 @@ export function createDaemonShutdown({ disposePluginResources, ipcServer, readyS
175
175
  shutdownInProgress = true;
176
176
  if (signal)
177
177
  shutdownSignal = signal;
178
+ // 先停掉还没发完的上线通知,避免和下面的下线通知交叉。
179
+ try {
180
+ lifecycleNotices?.beginShutdown();
181
+ }
182
+ catch { }
183
+ // 下线提示是 best-effort:发起后不等待,退出流程照常继续。
184
+ // 注意必须在这里触发——后面 daemon.channels 会断开 AUN 连接。
185
+ void lifecycleNotices?.sendOffline(shutdownSignal)?.catch(() => { });
178
186
  const pid = process.pid;
179
187
  const ppid = process.ppid;
180
188
  logger.info(`\n\nShutting down gracefully... (signal=${shutdownSignal}, pid=${pid}, ppid=${ppid})`);
@@ -294,10 +294,11 @@ export class EvolAgent {
294
294
  };
295
295
  }
296
296
  resolveChatMode(chatType, globalChatmode) {
297
- const key = chatType === 'group' ? 'group' : 'private';
298
- return (this.merged.chatmode?.[key]
299
- ?? globalChatmode?.[key]
300
- ?? (key === 'group' ? 'proactive' : 'interactive'));
297
+ if (chatType === 'group')
298
+ return 'proactive';
299
+ return (this.merged.chatmode?.private
300
+ ?? globalChatmode?.private
301
+ ?? 'interactive');
301
302
  }
302
303
  // ── Reload 支持:替换 in-memory config 并复用 channels Map ───────────
303
304
  /** 用新的 raw + merged 替换 in-memory 状态。channels 由调用方决定如何 reconcile。 */