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
@@ -2,16 +2,18 @@ import { resolvePaths } from '../paths.js';
2
2
  import { daemonUnavailableMessage, getArgValue, isHelpFlag, queryDaemon, wantsHelp } from './help.js';
3
3
  import { AGENT_DELEGATION_TOKEN_ENV, readDelegationCredential } from '../core/auth/agent-delegation.js';
4
4
  import { DirectoryQueryError, executeDirectoryQueryCommand, resolveDirectoryQueryCommand, } from '../directory/owner-directory-query-operation.js';
5
- const QUERY_ACTIONS = new Set(['find', 'show', 'list', 'refresh', 'blocked']);
5
+ import { executeDirectoryRequestCommand, resolveDirectoryRequestCommand, } from '../directory/owner-directory-request-operation.js';
6
+ /** `find` / `show` 是旧名,仍接受:`find` → `list`,`show` → `info`。 */
7
+ const QUERY_ACTIONS = new Set(['list', 'info', 'refresh', 'blocked', 'find', 'show']);
6
8
  /**
7
9
  * `ec directory ...`
8
10
  *
9
- * 只读查询 + 重算注入。**备注不走命令**:它是一个 frontmatter markdown 文件,由 Agent
11
+ * 查询、重算注入与发起联系人邀请。**备注不走命令**:它是一个 frontmatter markdown 文件,由 Agent
10
12
  * 直接读写自己目录下的 `<agent>/directory/remarks/<联系人AID>.md`,改完再
11
13
  * `ec directory refresh` 让 `directory.md` 重算。
12
14
  *
13
- * 不给命令的理由:备注只落在自己的 agent 目录里,没有跨目录写入需求,
14
- * 包一层 CLI + daemon IPC 只是把「写一个文件」变复杂。
15
+ * 命令面与 `ec skill` 对齐:`list` 列举/过滤(含分页),`info` 看单条详情;
16
+ * 旧的 `find` / `show` 保留为别名。
15
17
  */
16
18
  export async function cmdDirectory(args) {
17
19
  if (args.length === 0 || isHelpFlag(args[0]) || wantsHelp(args)) {
@@ -19,13 +21,14 @@ export async function cmdDirectory(args) {
19
21
  return;
20
22
  }
21
23
  const action = args[0];
22
- if (!QUERY_ACTIONS.has(action)) {
24
+ if (!QUERY_ACTIONS.has(action) && action !== 'request') {
23
25
  console.error(`❌ 未知子命令: ${action}`);
24
26
  printHelp();
25
27
  process.exitCode = 1;
26
28
  return;
27
29
  }
28
- const json = getArgValue(args, '--format') === 'json';
30
+ // 与 `ec skill list` 对齐:`--json` 是 `--format json` 的同义写法。
31
+ const json = getArgValue(args, '--format') === 'json' || args.includes('--json');
29
32
  try {
30
33
  const result = process.env.EVOLCORE_SESSION_ID
31
34
  ? await runManaged(args, json)
@@ -34,17 +37,37 @@ export async function cmdDirectory(args) {
34
37
  }
35
38
  catch (error) {
36
39
  const known = error instanceof DirectoryQueryError;
37
- console.error(`❌ ${known ? error.message : (error instanceof Error ? error.message : String(error))}`);
38
- process.exitCode = 1;
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ fail(known ? error.code : 'DIRECTORY_OPERATION_FAILED', message, json);
39
42
  }
40
43
  }
41
44
  async function runLocal(argv) {
45
+ if (argv[0] === 'request') {
46
+ const command = resolveDirectoryRequestCommand(argv);
47
+ const { msgSend } = await import('../aun/msg/index.js');
48
+ return executeDirectoryRequestCommand(command, input => msgSend({
49
+ from: input.from, to: input.to, body: { mode: 'payload', payload: input.payload }, encrypt: input.encrypt,
50
+ }));
51
+ }
42
52
  return executeDirectoryQueryCommand(resolveDirectoryQueryCommand(argv));
43
53
  }
54
+ /**
55
+ * 失败输出:`--format json` 时要给出结构化结果。
56
+ *
57
+ * 之前无论 `--format json` 与否都只打印 `❌ <message>`,调用方拿不到错误码,
58
+ * 无法区分「人不在名录里」和「名录没授权/没快照」。结构化失败与成功结果保持
59
+ * 同一形状:`{ ok: false, code, error }`。
60
+ */
61
+ function fail(code, message, json) {
62
+ if (json)
63
+ console.log(JSON.stringify({ ok: false, code, error: message }));
64
+ else
65
+ console.error(`❌ ${message}`);
66
+ process.exitCode = 1;
67
+ }
44
68
  function output(result, json) {
45
69
  if (!result.ok) {
46
- console.error(`❌ ${result.error}`);
47
- process.exitCode = 1;
70
+ fail(result.code, result.error, json);
48
71
  return;
49
72
  }
50
73
  if (json) {
@@ -52,19 +75,27 @@ function output(result, json) {
52
75
  return;
53
76
  }
54
77
  switch (result.action) {
55
- case 'find': {
56
- if (result.hits.length === 0) {
57
- console.log(result.synced ? '(同步后仍未找到)' : '(没有匹配)');
78
+ case 'request': {
79
+ console.log(`✓ 已向 ${result.targetAid} 发送加密 friend.invite.v1 加好友申请,message_id=${result.message_id}`);
80
+ console.log('发送成功只表示申请已提交;请等待 Evol App 处理并同步联系人名录,再重试原消息。');
81
+ return;
82
+ }
83
+ case 'list': {
84
+ if (result.entries.length === 0) {
85
+ console.log(result.total === 0 ? '(没有匹配)' : '(这一页没有条目)');
58
86
  return;
59
87
  }
60
- for (const hit of result.hits)
61
- printHit(hit);
62
- if (result.synced)
63
- console.log('(先做了一次同步)');
88
+ for (const entry of result.entries)
89
+ printListRow(entry);
90
+ printPageFooter(result);
91
+ console.log('名录详情:ec directory info <AID>;名片正文:ec aid agentmd get <AID>');
64
92
  return;
65
93
  }
66
- case 'show': {
94
+ case 'info': {
67
95
  // 按名字命中多条时全部列出,先给一行汇总,避免把第一条误当成唯一答案。
96
+ if (result.matchKind === 'fuzzy') {
97
+ console.log('(按名字包含匹配,可能不是同一个人;建议改用 AID 精确查)');
98
+ }
68
99
  if (result.entries.length > 1) {
69
100
  console.log(`按${result.matchedBy === 'name' ? '名字' : 'AID'}命中 ${result.entries.length} 条,逐条列出:`);
70
101
  }
@@ -80,6 +111,8 @@ function output(result, json) {
80
111
  console.log(`(另有 ${result.truncated} 条同名未列出,加 --limit 或按 AID 精确查)`);
81
112
  if (result.synced)
82
113
  console.log('(先做了一次同步)');
114
+ const aid = result.entries.length === 1 ? String(result.entries[0].aid ?? '') : '';
115
+ console.log(`名片正文:ec aid agentmd get ${aid || '<AID>'}`);
83
116
  return;
84
117
  }
85
118
  case 'refresh': {
@@ -98,28 +131,29 @@ function output(result, json) {
98
131
  }
99
132
  return;
100
133
  }
101
- case 'list': {
102
- if (result.entries.length === 0)
103
- console.log('(没有条目)');
104
- for (const entry of result.entries) {
105
- const name = typeof entry.name === 'string' ? entry.name : '';
106
- console.log([name && name !== entry.aid ? name : '', entry.aid, entry.type ?? '', entry.remark ?? '']
107
- .filter(Boolean).join(' | '));
108
- }
109
- return;
110
- }
111
134
  }
112
135
  }
113
- function printHit(hit) {
136
+ /** list 的一行:名字 | AID | type | exttype | 备注名 | 描述 | Owner | 归属。 */
137
+ function printListRow(entry) {
138
+ const text = (value) => (typeof value === 'string' ? value : '');
139
+ const name = text(entry.name);
114
140
  const cells = [
115
- hit.name && hit.name !== hit.aid ? hit.name : '',
116
- hit.aid,
117
- hit.type ?? '',
118
- hit.remark ?? '',
119
- hit.description ?? '',
141
+ name && name !== entry.aid ? name : '',
142
+ text(entry.aid),
143
+ text(entry.type),
144
+ text(entry.exttype),
145
+ text(entry.remark),
146
+ text(entry.description),
147
+ `Owner: ${text(entry.ownerAid) || '(无)'}`,
148
+ `归属: ${text(entry.ownershipStatus) || 'unknown'}${entry.ownershipVerified === true ? ' ✓' : ''}`,
149
+ `内外: ${entry.internal === true ? '内部' : '外部'}`,
120
150
  ].filter(Boolean);
121
- const exact = hit.score >= 1000 ? ' [精确匹配]' : '';
122
- console.log(`${cells.join(' | ')}${exact}`);
151
+ console.log(cells.join(' | '));
152
+ }
153
+ function printPageFooter(result) {
154
+ const pages = Math.max(1, Math.ceil(result.total / result.limit));
155
+ const next = result.hasMore ? ';加 --page ' + (result.page + 1) + ' 看下一页' : '';
156
+ console.log(`(第 ${result.page}/${pages} 页,共 ${result.total} 条${next})`);
123
157
  }
124
158
  async function runManaged(argv, json) {
125
159
  const sessionId = process.env.EVOLCORE_SESSION_ID;
@@ -132,7 +166,7 @@ async function runManaged(argv, json) {
132
166
  argv: ['directory', ...argv],
133
167
  sessionId,
134
168
  delegationToken,
135
- }, 15_000);
169
+ }, argv[0] === 'request' ? 30_000 : 15_000);
136
170
  if (!response) {
137
171
  throw new DirectoryQueryError('DAEMON_UNAVAILABLE', daemonUnavailableMessage(transportError, 'Unable to connect to the evolcore daemon'));
138
172
  }
@@ -144,27 +178,34 @@ async function runManaged(argv, json) {
144
178
  }
145
179
  function printHelp() {
146
180
  console.log(`用法:
147
- ec directory find <query> --self <agent-aid> [--type <type>] [--scope internal|external|all] [--owner <aid|unbound>] [--limit <n>]
148
- ec directory show <contact-aid|名字> --self <agent-aid> [--limit <n>]
149
- ec directory list --self <agent-aid> [--type <type>] [--scope internal|external|all] [--owner <aid|unbound>] [--limit <n>]
150
- ec directory refresh --self <agent-aid>
151
- ec directory blocked --self <agent-aid>
181
+ ec directory list [<关键词>] [--filter '<kw1,kw2>']... [--type <type>] [--scope internal|external|all] [--owner <aid|unbound>] [--limit <n>] [--page <n>]
182
+ ec directory info <contact-aid|名字> [--limit <n>]
183
+ ec directory refresh
184
+ ec directory blocked
185
+ ec directory request <target-aid> [--note <申请介绍>]
186
+
187
+ request:向目标发送 app-v1 friend.invite.v1 加好友申请;介绍默认为“你好,我想添加你为联系人。”。
188
+ 发送成功仅表示申请已提交;须等 Evol App 处理并同步联系人名录后再重试原消息。
152
189
 
153
- find:
154
- 按 AID、名字、备注、描述匹配。查询串按空格切成多个词,要求全部命中。
155
- 默认查全部(含外部条目);--scope internal 只看内部,--scope external 只看外部。
156
- 本地没有匹配时会触发一次有界同步再查一遍(B 方案)。
190
+ list:
191
+ 列举名录;给关键词时按 AID、名字、备注、描述、exttype 做子串匹配(不区分大小写)。
192
+ --filter 与 ec skill list --filter 同语义:组内逗号分隔为 OR,多个 --filter 之间为 AND;
193
+ 位置参数按“多个词同时命中”处理(旧 find 的写法)。
194
+ 默认每页 20 条,--page / --limit 可翻页;输出包含 type、exttype、描述、备注、
195
+ Owner 绑定关系与 Ownership 核验状态。本地备注正文不在 list 展示。
196
+ 旧名 find 等价于 list <关键词>。
157
197
 
158
- show:接受 AID 或名字。按名字匹配显示名、远端备注名与本地称呼(精确等于),
159
- 同名多条时全部列出。返回完整记录(描述不截断)。
160
- list:列出条目,默认只列内部联系人。
161
- --owner <aid|unbound>:find / list 都支持,按条目的归属 Owner 过滤;unbound 只列无归属条目。
198
+ info:
199
+ 接受 AID 或名字。AID 大小写不敏感、可带 @ 前缀;名字先做归一后的精确匹配
200
+ (全角/半角、空格、结尾括号称呼不影响),没命中再按名字包含匹配,结果标
201
+ matchKind=fuzzy。返回完整记录(含本地备注正文)。旧名 show 等价于 info。
162
202
 
163
- refresh:拉一次最新名录并重算 directory.md / identity.json。拉取需要 channel 在线;
164
- 没有连接时只做本地重算——手工改完备注后用它把改动刷进名录。
203
+ refresh:
204
+ 拉一次最新名录并重算 directory.md / identity.json。拉取需要 channel 在线;
205
+ 没有连接时只做本地重算——手工改完备注后用它把改动刷进名录。
165
206
 
166
- blocked:列出被拉黑的主体,合并两个来源——名录的 blocked_aids(Owner 侧,跨 Agent 生效)
167
- 与 peers.json 的 blocked(本端,只对本 agent 生效)。source 字段标明来源。
207
+ blocked:
208
+ 列出被拉黑的主体,合并名录侧(Owner 发布,跨 Agent)与本端(peers.json)两个来源。
168
209
 
169
210
  备注不走命令:直接读写自己目录下的 <agent>/directory/remarks/<联系人AID>.md
170
211
 
@@ -177,7 +218,11 @@ blocked:列出被拉黑的主体,合并两个来源——名录的 blocked_a
177
218
  <正文>
178
219
  文件名必须与 aid 一致;remark 与正文可只写一个。改完调 ec directory refresh。
179
220
 
221
+ 看名片正文(agent.md,下载+验签)用:ec aid agentmd get <AID>
222
+
180
223
  选项:
181
- --self <agent-aid> 目标 Agent,缺省取 EVOLCORE_SELF_AID
182
- --format json 以 JSON 输出`);
224
+ --self <agent-aid> 目标 Agent;托管会话缺省取当前任务所属 Agent(委托凭据),
225
+ 否则取 EVOLCORE_SELF_AID
226
+ --format json 以 JSON 输出;失败时同样输出 { ok: false, code, error }
227
+ --json 等价于 --format json(与 ec skill list 对齐)`);
183
228
  }
package/dist/cli/index.js CHANGED
@@ -56,7 +56,7 @@ AUN:
56
56
  menu-client 向远程 daemon 发送标准 Menu 请求
57
57
  diag 邀请远程诊断 Agent,或 stop 撤销诊断授权
58
58
  peer 联系人黑名单与已登记对端查询
59
- directory 名录查询:按 AID、名字、备注检索联系人
59
+ directory 名录查询与发起加好友申请
60
60
  role 关系角色提升申请与审批
61
61
  net AUN 网络链路诊断
62
62
 
package/dist/cli/peer.js CHANGED
@@ -83,7 +83,8 @@ Options:
83
83
  --format json 输出 JSON
84
84
  --help, -h 显示帮助
85
85
 
86
- 添加联系人、审批联系人申请由 Owner 在 Evol App 名录中完成,Agent 侧不提供入口。`);
86
+ 添加联系人、审批联系人申请由 Evol App 名录流程处理。
87
+ 发起 app-v1 加好友申请:ec directory request <target-aid> --self <agent-aid> [--note <申请介绍>]。`);
87
88
  }
88
89
  function withDefaultSelf(args) {
89
90
  if (args.includes('--self'))
@@ -7,6 +7,7 @@ import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import { readDelegationCredential } from '../core/auth/agent-delegation.js';
9
9
  import { resolveRoot } from '../paths.js';
10
+ import { TEST_TMPDIR_ENV } from '../product.js';
10
11
  export const TASK_RUNTIME_CONTEXT_ENV = 'EVOLCORE_TASK_RUNTIME_CONTEXT';
11
12
  export const SESSION_RUNTIME_DIR_ENV = 'EVOLCORE_SESSION_RUNTIME_DIR';
12
13
  export const DAEMON_RUNTIME_EPOCH_ENV = 'EVOLCORE_DAEMON_RUNTIME_EPOCH';
@@ -189,7 +190,8 @@ function canonicalHome() {
189
190
  return process.platform === 'win32' ? canonical.toLowerCase() : canonical;
190
191
  }
191
192
  function systemTempRoot() {
192
- const testRoot = process.env.EVOLCORE_TEST === '1' && process.env.TMPDIR?.trim();
193
+ const testRoot = process.env.EVOLCORE_TEST === '1'
194
+ && (process.env.TMPDIR || process.env[TEST_TMPDIR_ENV])?.trim();
193
195
  const candidate = testRoot && path.isAbsolute(testRoot)
194
196
  ? testRoot
195
197
  : process.platform === 'win32'
@@ -112,7 +112,6 @@ function assertAccessPolicyWrite(input, agent, policy) {
112
112
  }
113
113
  function clonePolicy(policy) {
114
114
  return {
115
- ...(policy.contactAdmission ? { contactAdmission: policy.contactAdmission } : {}),
116
115
  allowInternalContacts: policy.allowInternalContacts ?? true,
117
116
  allowExternalContacts: policy.allowExternalContacts ?? false,
118
117
  allowAllContacts: policy.allowAllContacts ?? false,
@@ -1,11 +1,11 @@
1
1
  import path from 'path';
2
2
  import { kitsRoleTemplatesDir } from '../paths.js';
3
3
  import { createErrorCapturingReader, fileCache } from '../core/daemon-file-cache.js';
4
- import { normalizeRoleEffortCompat, validateRoleConfig } from './role-schema.js';
4
+ import { normalizeRoleEffortCompat, normalizeRoleGroupChatmodeCompat, validateRoleConfig } from './role-schema.js';
5
5
  import { expectedRoleRank } from './role-ranks.js';
6
6
  export const BUILTIN_ROLE_IDS = ['owner', 'admin', 'member', 'visitor'];
7
7
  export function validateBuiltinRoleTemplateDefinition(roleId, raw) {
8
- const normalizedRaw = normalizeRoleEffortCompat(raw);
8
+ const normalizedRaw = normalizeRoleGroupChatmodeCompat(normalizeRoleEffortCompat(raw));
9
9
  const issues = validateRoleConfig(normalizedRaw);
10
10
  if (issues.length) {
11
11
  return {
@@ -4,6 +4,7 @@ export { expectedRoleRank, ROLE_RANKS } from './role-ranks.js';
4
4
  export const BUILTIN_USER_ROLES = ['member', 'visitor'];
5
5
  export const MANAGEMENT_ROLES = ['owner', 'admin'];
6
6
  export const DAEMON_OWNER_ROLE = 'daemon-owner';
7
+ export const DEFAULT_PA_TEAM_ROLE = 'member';
7
8
  export function isManagementRole(role) {
8
9
  return role === 'owner' || role === 'admin';
9
10
  }
@@ -17,7 +18,7 @@ export function isReservedRoleName(role) {
17
18
  export function getBuiltinRolesConfig() {
18
19
  return {
19
20
  $schema_version: 1,
20
- defaultRoles: { private: null, group: null },
21
+ defaultRoles: { private: null, group: null, paTeam: DEFAULT_PA_TEAM_ROLE },
21
22
  roles: Object.fromEntries(BUILTIN_USER_ROLES.flatMap(roleId => {
22
23
  const definition = readBuiltinRoleTemplate(roleId).definition;
23
24
  return definition ? [[roleId, definition]] : [];
@@ -321,6 +321,11 @@ export function parseConfigFieldValue(fieldPath, rawValue) {
321
321
  ? { ok: true, value: raw }
322
322
  : { ok: false, reason: `Config field ${fieldPath} must be one of ${[...EFFORTS].join(', ')}; use unset for auto` };
323
323
  case 'chatmode':
324
+ if (fieldPath.trim() === 'chatmode.group') {
325
+ return raw === 'proactive'
326
+ ? { ok: true, value: raw }
327
+ : { ok: false, reason: 'Config field chatmode.group is fixed to proactive' };
328
+ }
324
329
  return raw === 'interactive' || raw === 'proactive' || raw === 'paactive'
325
330
  ? { ok: true, value: raw }
326
331
  : { ok: false, reason: `Config field ${fieldPath} must be interactive, proactive, or paactive` };
@@ -28,6 +28,7 @@ import { normalizeAgentLifecycle } from './lifecycle.js';
28
28
  import { isAgentOnlyBaseagentField, isBehaviorConfigFieldPath } from './config-field-policy.js';
29
29
  import { clearRoleStoreCache, isRoleName } from './role-store.js';
30
30
  import { writeRoleDefinition, writeRoleRegistry } from './role-service.js';
31
+ import { normalizeRoleEffortCompat, normalizeRoleGroupChatmodeCompat } from './role-schema.js';
31
32
  import { mutatePeerBookTransactionSync, resolvePeerAidKind } from './peer-book-store.js';
32
33
  import { DAEMON_SCHEMA_NAME } from '../product.js';
33
34
  import { normalizeDaemonServices } from './daemon-services.js';
@@ -661,10 +662,12 @@ export function read(target, sel, opts = {}) {
661
662
  const normalized = target === ConfigTarget.Process
662
663
  ? normalizeProcessConfigCompat(normalizeDaemonServices(migrated))
663
664
  : target === ConfigTarget.Agent
664
- ? normalizeAgentConfigForRead(migrated, sel?.self)
665
+ ? normalizeGroupChatmodeCompat(normalizeAgentConfigForRead(migrated, sel?.self))
665
666
  : target === ConfigTarget.Relation
666
- ? foldLegacyProactiveBlock(migrated)
667
- : migrated;
667
+ ? normalizeGroupChatmodeCompat(foldLegacyProactiveBlock(migrated))
668
+ : target === ConfigTarget.Role
669
+ ? normalizeRoleGroupChatmodeCompat(normalizeRoleEffortCompat(migrated))
670
+ : migrated;
668
671
  // Agent read compatibility may move the legacy top-level `agents` block to
669
672
  // `baseagents`, so canonicalize effort after that structural migration.
670
673
  // config.json 不做 ${VAR} 展开:网关凭证与端点只在 providers.json,那里有独立展开实现。
@@ -879,6 +882,11 @@ function normalizeRelationConfigForWrite(value) {
879
882
  normalizeShowActivitiesCompat(mutable);
880
883
  return mutable;
881
884
  }
885
+ function normalizeGroupChatmodeCompat(value) {
886
+ if (value?.chatmode?.group !== 'interactive')
887
+ return value;
888
+ return { ...value, chatmode: { ...value.chatmode, group: 'proactive' } };
889
+ }
882
890
  function normalizeShowActivitiesCompat(value) {
883
891
  if (value.show_activities === true)
884
892
  value.show_activities = 'all';
@@ -1429,6 +1437,13 @@ export function validateConfigFile(target, sel) {
1429
1437
  catch (error) {
1430
1438
  return { exists: true, errors: [error instanceof Error ? error.message : String(error)] };
1431
1439
  }
1440
+ if ((target === ConfigTarget.Agent || target === ConfigTarget.Relation)
1441
+ && sanitized && typeof sanitized === 'object') {
1442
+ sanitized = normalizeGroupChatmodeCompat(sanitized);
1443
+ }
1444
+ if (target === ConfigTarget.Role) {
1445
+ sanitized = normalizeRoleGroupChatmodeCompat(normalizeRoleEffortCompat(sanitized));
1446
+ }
1432
1447
  return { exists: true, errors: validateConfig(target, sanitized) };
1433
1448
  }
1434
1449
  function fileCacheAvailable() {
@@ -1534,18 +1549,18 @@ function mergeBaseagentBlocks(layers) {
1534
1549
  * the normal agent/relation merge chain without leaking the compatibility
1535
1550
  * container itself into EffectiveAgentConfig.
1536
1551
  *
1537
- * Explicit canonical fields (if a future schema adds them) always win. A
1538
- * single default chat mode applies to the three peer categories because this
1539
- * compatibility field predates the per-category `chatmode` dictionary.
1552
+ * Explicit canonical fields (if a future schema adds them) always win.
1553
+ * Legacy default modes apply to private chats; group delivery is always proactive.
1540
1554
  */
1541
1555
  export function normalizeDefaultsBehaviorCompat(defaults) {
1542
- if (!defaults || !defaults.config || typeof defaults.config !== 'object' || Array.isArray(defaults.config))
1543
- return defaults;
1556
+ if (!defaults || !defaults.config || typeof defaults.config !== 'object' || Array.isArray(defaults.config)) {
1557
+ return defaults ? normalizeGroupChatmodeCompat(defaults) : defaults;
1558
+ }
1544
1559
  const { config, ...rest } = defaults;
1545
1560
  const normalized = { ...rest };
1546
1561
  const chatMode = config.chatMode;
1547
1562
  if (!normalized.chatmode && (chatMode === 'interactive' || chatMode === 'proactive')) {
1548
- normalized.chatmode = { private: chatMode, group: chatMode, nothuman: chatMode };
1563
+ normalized.chatmode = { private: chatMode, group: 'proactive', nothuman: chatMode };
1549
1564
  }
1550
1565
  else if (!normalized.chatmode && chatMode === 'paactive') {
1551
1566
  normalized.chatmode = { private: 'paactive', group: 'proactive', nothuman: 'proactive' };
@@ -1556,7 +1571,7 @@ export function normalizeDefaultsBehaviorCompat(defaults) {
1556
1571
  if (normalized.show_activities === undefined && ['all', 'text', 'none'].includes(config.show_activities)) {
1557
1572
  normalized.show_activities = config.show_activities;
1558
1573
  }
1559
- return normalized;
1574
+ return normalizeGroupChatmodeCompat(normalized);
1560
1575
  }
1561
1576
  function stripStaticOwnerField(config) {
1562
1577
  if (!config)
@@ -13,6 +13,8 @@ import { configuredOwnerList } from './owner-config.js';
13
13
  import { tryParseChannelKey } from '../core/channel-loader.js';
14
14
  import { isValidAid } from '../aun/aid/validation.js';
15
15
  import { getOwners, ownerResolver } from '../core/ownership/owner-resolver.js';
16
+ import { paTeamQualification, paTeamRevision, requiresPaTeamVerification } from '../core/relation/pa-team.js';
17
+ import { readRoleStore } from './role-store.js';
16
18
  export function isAuthenticated(userId) {
17
19
  return isValidAid(String(userId || '').trim());
18
20
  }
@@ -58,7 +60,8 @@ export function getFirstStaticAgentOwner(aid) {
58
60
  }
59
61
  /** Revision for security-sensitive owner/contact/relation authorization inputs. */
60
62
  export function authorizationConfigRevision(aid) {
61
- const fingerprints = [ownerResolver.revision(aid), fileRevision(agentConfig(aid)), fileRevision(agentPeerConfig(aid))];
63
+ const fingerprints = [ownerResolver.revision(aid), paTeamRevision(aid),
64
+ JSON.stringify(readRoleStore(aid)), fileRevision(agentConfig(aid)), fileRevision(agentPeerConfig(aid))];
62
65
  const relations = agentRelationsDir(aid);
63
66
  try {
64
67
  for (const entry of fs.readdirSync(relations, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
@@ -101,6 +104,25 @@ export function resolvePeerRoleDetail(ctx) {
101
104
  candidates.push({ role: 'owner', source: 'agent-owner', sourcePriority: 100 });
102
105
  }
103
106
  const actorRole = resolveActorDirectRole(ctx.selfAid, actor, channelType, operatorId);
107
+ if (channelType === 'aun' && ctx.chatType === 'private' && hasTrustedPrincipal(actor)
108
+ && (paTeamQualification(ctx.selfAid, actor.principalId) === 'matched'
109
+ || requiresPaTeamVerification(ctx.selfAid, actor.principalId))) {
110
+ const ownerCandidate = candidates.find(candidate => candidate.role === 'owner');
111
+ if (ownerCandidate)
112
+ return resultFor('owner', 'agent-owner', actor, ctx.selfAid);
113
+ const relation = read(ConfigTarget.Relation, { self: ctx.selfAid, peerKey: formatPeerKey('aun', actor.principalId) }, { cache: true });
114
+ if (relation?.role !== undefined && relation.role !== null) {
115
+ return resultFor(actorRole, 'relation-actor', actor, ctx.selfAid);
116
+ }
117
+ if (paTeamQualification(ctx.selfAid, actor.principalId) !== 'matched') {
118
+ return resultFor(null, 'none', actor, ctx.selfAid);
119
+ }
120
+ const store = readRoleStore(ctx.selfAid);
121
+ const valid = !store.diagnostics.some(diagnostic => diagnostic.code === 'INVALID_ROLE_REGISTRY'
122
+ || diagnostic.code === 'MISSING_ROLE_REGISTRY');
123
+ const role = valid ? normalizeDefaultRole(store.registry.defaultRoles.paTeam ?? 'member', ctx.selfAid) : null;
124
+ return resultFor(role, 'pa-team-default', actor, ctx.selfAid);
125
+ }
104
126
  if (ctx.chatType === 'private') {
105
127
  if (actorRole)
106
128
  candidates.push({ role: actorRole, source: 'relation-actor', sourcePriority: 80 });
@@ -33,6 +33,30 @@ export function rolePermissionFields() {
33
33
  patterns: field.patterns?.map((pattern) => ({ ...pattern, kind: 'pattern' })),
34
34
  }));
35
35
  }
36
+ /** Read compatibility for policies saved before group delivery became proactive-only. */
37
+ export function normalizeRoleGroupChatmodeCompat(value) {
38
+ if (!isRecord(value) || !isRecord(value.permissions))
39
+ return value;
40
+ const version = value.$schema_version ?? 1;
41
+ if (version !== 1 && version !== 2)
42
+ return value;
43
+ const group = value.permissions['chatmode.group'];
44
+ if (!isRecord(group))
45
+ return value;
46
+ return {
47
+ ...value,
48
+ permissions: {
49
+ ...value.permissions,
50
+ 'chatmode.group': {
51
+ ...group,
52
+ default: group.default === 'interactive' ? 'proactive' : group.default,
53
+ ...(Array.isArray(group.allowedValues) ? {
54
+ allowedValues: [...new Set(group.allowedValues.map(item => item === 'interactive' ? 'proactive' : item))],
55
+ } : {}),
56
+ },
57
+ },
58
+ };
59
+ }
36
60
  function isDescriptor(value) {
37
61
  if (!value || typeof value !== 'object')
38
62
  return false;
@@ -55,10 +79,10 @@ export function rolePermissionFieldPatterns(field) {
55
79
  }
56
80
  /** Shared RoleService/Menu validation backed by the published role schema. */
57
81
  export function validateRoleConfig(value) {
58
- const compatible = normalizeRoleEffortCompat(value);
82
+ const compatible = normalizeRoleGroupChatmodeCompat(normalizeRoleEffortCompat(value));
59
83
  const schema = loadSchema('role-config');
60
84
  const normalized = isRecord(compatible)
61
- && (!Object.hasOwn(compatible, '$schema_version') || compatible.$schema_version === 1)
85
+ && (!Object.hasOwn(compatible, '$schema_version') || compatible.$schema_version === 1 || compatible.$schema_version === 2)
62
86
  ? { ...compatible, $schema_version: schema.version }
63
87
  : compatible;
64
88
  if (!schema.validate(normalized)) {
@@ -5,7 +5,7 @@ import { agentRelationConfig, agentRelationsDir, agentRoleConfig, agentRolesInde
5
5
  import { registerFile, unregisterFile } from '../core/file-integrity/store.js';
6
6
  import { currentVersion, loadSchema } from './schema-registry.js';
7
7
  import { clearRoleStoreCache, getStoredRoleRegistry, isRoleName, readRoleStore, roleRegistryExists, } from './role-store.js';
8
- import { expectedRoleRank, isManagementRole } from './builtin-roles.js';
8
+ import { DEFAULT_PA_TEAM_ROLE, expectedRoleRank, isManagementRole } from './builtin-roles.js';
9
9
  import { readBuiltinRoleTemplate } from './builtin-role-templates.js';
10
10
  import { normalizeRoleEffortCompat, validateRoleConfig } from './role-schema.js';
11
11
  export class RoleServiceError extends Error {
@@ -30,7 +30,7 @@ export function ensureInitialRoleRegistry(selfAid) {
30
30
  writeRoleRegistry(selfAid, {
31
31
  $schema_version: 1,
32
32
  roles: ['owner', 'admin', 'member', 'visitor'],
33
- defaultRoles: { private: null, group: null },
33
+ defaultRoles: { private: null, group: null, paTeam: DEFAULT_PA_TEAM_ROLE },
34
34
  });
35
35
  return true;
36
36
  }
@@ -125,8 +125,11 @@ export function unregisterRole(selfAid, roleId, replacementRoleId) {
125
125
  defaultRoles: {
126
126
  private: registry.defaultRoles.private === roleId ? (replacement ?? null) : registry.defaultRoles.private,
127
127
  group: registry.defaultRoles.group === roleId ? (replacement ?? null) : registry.defaultRoles.group,
128
+ paTeam: (registry.defaultRoles.paTeam ?? DEFAULT_PA_TEAM_ROLE) === roleId
129
+ ? (replacement ?? DEFAULT_PA_TEAM_ROLE) : registry.defaultRoles.paTeam,
128
130
  },
129
131
  };
132
+ validateRegistry(selfAid, nextRegistry);
130
133
  if (hasReplacement) {
131
134
  const relations = agentRelationsDir(selfAid);
132
135
  if (fs.existsSync(relations)) {
@@ -171,8 +174,8 @@ function validateRegistry(selfAid, value) {
171
174
  const registry = normalized;
172
175
  if (!registry.roles.includes('visitor'))
173
176
  throw new RoleServiceError('VISITOR_REQUIRED', 'visitor must remain registered');
174
- for (const role of ['private', 'group']) {
175
- const selected = registry.defaultRoles[role];
177
+ for (const role of ['private', 'group', 'paTeam']) {
178
+ const selected = role === 'paTeam' ? registry.defaultRoles.paTeam ?? DEFAULT_PA_TEAM_ROLE : registry.defaultRoles[role];
176
179
  if (selected !== null && (selected === 'owner' || !registry.roles.includes(selected))) {
177
180
  throw new RoleServiceError('INVALID_DEFAULT_ROLE', `defaultRoles.${role} must reference an assignable registered role`);
178
181
  }
@@ -203,6 +206,8 @@ function findRoleReferences(selfAid, roleId, registry) {
203
206
  references.push('defaultRoles.private');
204
207
  if (registry.defaultRoles.group === roleId)
205
208
  references.push('defaultRoles.group');
209
+ if ((registry.defaultRoles.paTeam ?? DEFAULT_PA_TEAM_ROLE) === roleId)
210
+ references.push('defaultRoles.paTeam');
206
211
  const relations = agentRelationsDir(selfAid);
207
212
  if (!fs.existsSync(relations))
208
213
  return references;