evolcore 0.0.43-test.1 → 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 (200) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/README.md +22 -0
  3. package/dist/agents/claude-runner.js +26 -2
  4. package/dist/agents/codex/app-server-client.js +12 -0
  5. package/dist/agents/codex-runner.js +49 -8
  6. package/dist/agents/ecagent-runner.js +39 -15
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/aid/agentmd.js +21 -1
  10. package/dist/aun/menu/client.js +1 -1
  11. package/dist/aun/model-headers.js +17 -0
  12. package/dist/aun/msg/p2p.js +7 -2
  13. package/dist/channels/aun.js +522 -50
  14. package/dist/channels/builtin-plugins.js +16 -11
  15. package/dist/channels/daemon.js +4 -0
  16. package/dist/channels/dingtalk.js +83 -31
  17. package/dist/channels/feishu.js +29 -13
  18. package/dist/channels/qqbot.js +32 -11
  19. package/dist/channels/wechat.js +13 -3
  20. package/dist/channels/wecom.js +67 -27
  21. package/dist/cli/agent-command.js +3 -86
  22. package/dist/cli/agent-create.js +20 -6
  23. package/dist/cli/agent.js +1 -79
  24. package/dist/cli/aun-commands.js +18 -19
  25. package/dist/cli/config.js +1 -1
  26. package/dist/cli/daemon-commands.js +47 -2
  27. package/dist/cli/data-command.js +9 -1
  28. package/dist/cli/debug-mode.js +1 -1
  29. package/dist/cli/diag.js +1 -1
  30. package/dist/cli/directory.js +149 -91
  31. package/dist/cli/getmeta-command.js +1 -1
  32. package/dist/cli/index.js +79 -22
  33. package/dist/cli/init.js +1 -23
  34. package/dist/cli/link-rules.js +1 -1
  35. package/dist/cli/managed-command-guard.js +0 -1
  36. package/dist/cli/pa-workspace-command.js +36 -2
  37. package/dist/cli/peer.js +3 -2
  38. package/dist/cli/restart-monitor.js +17 -3
  39. package/dist/cli/role.js +1 -1
  40. package/dist/cli/session-command.js +1 -1
  41. package/dist/cli/stats.js +2 -2
  42. package/dist/cli/task-context.js +3 -1
  43. package/dist/cli/thread-command.js +1 -1
  44. package/dist/cli/watch-msg.js +1 -1
  45. package/dist/config/builtin-role-templates.js +2 -2
  46. package/dist/config/builtin-roles.js +2 -1
  47. package/dist/config/config-field-policy.js +7 -2
  48. package/dist/config/config-manager.js +32 -10
  49. package/dist/config/peer-role-resolver.js +23 -1
  50. package/dist/config/role-schema.js +29 -4
  51. package/dist/config/role-service.js +12 -7
  52. package/dist/config/role-store.js +30 -8
  53. package/dist/config-store.js +75 -4
  54. package/dist/core/agent-ipc-registration.js +16 -59
  55. package/dist/core/auth/auth-gateway.js +14 -4
  56. package/dist/core/auth/authorization-audit.js +52 -14
  57. package/dist/core/auth/operation-authorizer.js +17 -11
  58. package/dist/core/auth/operation-catalog.js +5 -13
  59. package/dist/core/channel-loader.js +152 -16
  60. package/dist/core/channel-runtime.js +5 -0
  61. package/dist/core/command/agent-control.js +2 -1
  62. package/dist/core/command/agentmd-menu-request.js +50 -0
  63. package/dist/core/command/agentmd-menu.js +156 -0
  64. package/dist/core/command/cli-intent-parser.js +0 -8
  65. package/dist/core/command/command-handler.js +47 -40
  66. package/dist/core/command/connect-menu.js +7 -3
  67. package/dist/core/command/menu-catalog.js +16 -2
  68. package/dist/core/command/menu-handler.js +107 -14
  69. package/dist/core/command/menu-protocol.js +28 -0
  70. package/dist/core/command/role-menu.js +23 -9
  71. package/dist/core/command/slash-handler.js +139 -51
  72. package/dist/core/daemon-file-cache.js +3 -3
  73. package/dist/core/daemon-lifecycle.js +9 -1
  74. package/dist/core/evolagent-registry.js +5 -4
  75. package/dist/core/evolagent.js +10 -12
  76. package/dist/core/handoff/argv-parse.js +115 -0
  77. package/dist/core/handoff/ipc-registration.js +1 -1
  78. package/dist/core/ipc-registration.js +19 -2
  79. package/dist/core/lifecycle-notice.js +185 -0
  80. package/dist/core/memory/consolidation.js +8 -1
  81. package/dist/core/memory/relation-sweep.js +20 -8
  82. package/dist/core/message/aun-ipc-sender.js +35 -2
  83. package/dist/core/message/contact-admission.js +530 -0
  84. package/dist/core/message/im-renderer.js +111 -16
  85. package/dist/core/message/message-admission.js +29 -54
  86. package/dist/core/message/message-bridge.js +62 -8
  87. package/dist/core/message/message-utils.js +9 -5
  88. package/dist/core/message/peer-mode.js +55 -13
  89. package/dist/core/message/response-engine.js +298 -78
  90. package/dist/core/message/retry-scheduler.js +4 -0
  91. package/dist/core/ownership/owner-resolver.js +72 -34
  92. package/dist/core/permission/ec-command-parser.js +25 -38
  93. package/dist/core/permission/readonly-shell-query.js +34 -8
  94. package/dist/core/permission/tool-policy.js +50 -5
  95. package/dist/core/relation/pa-team.js +127 -0
  96. package/dist/core/role/runtime-policy.js +18 -5
  97. package/dist/core/session/session-manager.js +9 -1
  98. package/dist/core/soul.js +66 -0
  99. package/dist/core/system-session/memory.js +2 -2
  100. package/dist/core/thread/thread-service.js +6 -4
  101. package/dist/directory/contact-admission-paths.js +9 -0
  102. package/dist/directory/owner-directory-admission.js +125 -29
  103. package/dist/directory/owner-directory-cache.js +554 -58
  104. package/dist/directory/owner-directory-identity.js +60 -0
  105. package/dist/directory/owner-directory-markdown.js +154 -58
  106. package/dist/directory/owner-directory-policy.js +108 -0
  107. package/dist/directory/owner-directory-query-operation.js +399 -90
  108. package/dist/directory/owner-directory-remarks.js +29 -2
  109. package/dist/directory/owner-directory-request-operation.js +76 -0
  110. package/dist/directory/owner-directory-scope.js +35 -4
  111. package/dist/directory/owner-directory-search.js +118 -33
  112. package/dist/directory/owner-directory-store.js +117 -30
  113. package/dist/directory/owner-directory-text.js +60 -0
  114. package/dist/eck/kit-renderer.js +18 -8
  115. package/dist/eck/manifest-engine.js +55 -6
  116. package/dist/ecweb/basic-settings-service.js +2 -2
  117. package/dist/ecweb/message-context-service.js +28 -16
  118. package/dist/index.js +20 -5
  119. package/dist/ipc.js +1 -1
  120. package/dist/paths.js +29 -1
  121. package/dist/product.js +1 -0
  122. package/dist/response-system/config-resolver.js +1 -1
  123. package/dist/response-system/engines/v1/index.js +2 -1
  124. package/dist/response-system/modes/single-session/index.js +7 -2
  125. package/dist/trigger/scheduler.js +7 -4
  126. package/dist/trigger/validation.js +4 -0
  127. package/dist/utils/error-utils.js +12 -7
  128. package/dist/utils/logger.js +13 -4
  129. package/dist/utils/npm-ops.js +2 -2
  130. package/dist/utils/windows-autostart.js +1 -1
  131. package/ecagent/README.md +18 -0
  132. package/ecagent/dist/agent-loop.js +43 -1
  133. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  134. package/ecagent/dist/harness/agent-harness.js +24 -8
  135. package/ecagent/dist/harness/compaction/compaction.js +3 -0
  136. package/ecagent/dist/harness/types.d.ts +1 -0
  137. package/kits/docs/INDEX.md +1 -0
  138. package/kits/docs/channels/aun.md +1 -1
  139. package/kits/docs/context-assembly.md +21 -6
  140. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  141. package/kits/docs/evolcore/INDEX.md +4 -1
  142. package/kits/docs/evolcore/agent-create.md +5 -5
  143. package/kits/docs/evolcore/agent.md +4 -9
  144. package/kits/docs/evolcore/directory.md +227 -0
  145. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  146. package/kits/docs/evolcore/file-navigation.md +265 -0
  147. package/kits/docs/evolcore/menu-protocol.md +55 -0
  148. package/kits/docs/evolcore/msg.md +1 -0
  149. package/kits/docs/evolcore/peer.md +2 -1
  150. package/kits/docs/evolcore/response.md +7 -1
  151. package/kits/docs/evolcore/task.md +2 -0
  152. package/kits/docs/evolcore/tool-authorization.md +1 -1
  153. package/kits/docs/evolcore/trigger.md +4 -0
  154. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  155. package/kits/docs/prompt-loading-architecture.md +6 -2
  156. package/kits/eck_manifest.auxiliary.json +1 -0
  157. package/kits/eck_manifest.json +64 -7
  158. package/kits/eck_manifest.memory.json +93 -4
  159. package/kits/rules/01-overview.md +2 -2
  160. package/kits/rules/03-identity.md +10 -9
  161. package/kits/rules/05-venue.md +2 -4
  162. package/kits/rules/06-channel.md +1 -1
  163. package/kits/schemas/_meta.json +44 -3
  164. package/kits/schemas/agent-config.schema.18.json +5 -0
  165. package/kits/schemas/agent-config.schema.19.json +924 -0
  166. package/kits/schemas/agent-config.schema.20.json +925 -0
  167. package/kits/schemas/relation-config.schema.12.json +289 -0
  168. package/kits/schemas/relation-config.schema.13.json +289 -0
  169. package/kits/schemas/role-config.schema.2.json +215 -0
  170. package/kits/schemas/role-config.schema.3.json +1038 -0
  171. package/kits/schemas/role-registry.schema.1.json +3 -2
  172. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  173. package/kits/skills/ec-trigger/SKILL.md +4 -4
  174. package/kits/skills/personal-assistant/SKILL.md +109 -53
  175. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  176. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  177. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  178. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  179. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  180. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  181. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  182. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  183. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  184. package/kits/templates/soul/00-GUIDE.md +39 -0
  185. package/kits/templates/soul/01-identity.md +5 -0
  186. package/kits/templates/soul/02-persona.md +11 -0
  187. package/kits/templates/soul/03-duties.md +5 -0
  188. package/kits/templates/soul/04-working-style.md +5 -0
  189. package/kits/templates/system-fragments/bootstrap.md +7 -7
  190. package/kits/templates/system-fragments/channel.md +2 -2
  191. package/kits/templates/system-fragments/commands.md +3 -2
  192. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  193. package/kits/templates/system-fragments/memory.md +1 -1
  194. package/kits/templates/system-fragments/personal-assistant.md +50 -0
  195. package/kits/templates/system-fragments/reply.md +7 -0
  196. package/kits/templates/system-fragments/session.md +6 -2
  197. package/package.json +3 -2
  198. package/dist/cli/handoff-command.js +0 -353
  199. package/dist/directory/owner-directory-remark-operation.js +0 -147
  200. package/kits/docs/evolcore/self-summary.md +0 -29
@@ -1,13 +1,14 @@
1
1
  /**
2
- * `ec directory find|show|list`:查名录。
2
+ * `ec directory list|info`:查名录(旧名 `find` → `list`,`show` → `info`)。
3
3
  *
4
+ * 命令面与 `ec skill` 对齐:`list` 列举/过滤(`--filter` + 分页),`info` 看单条详情。
4
5
  * 和 `directory.md` 的分工:注入内容给的是截断后的概览(描述 100 字、名字 32 字,
5
- * 外部组还可能整组不注入),命令给的是完整记录和精确查找。两类使用场景:
6
+ * 不可信条目只留名字),命令给的是完整记录和精确查找。两类使用场景:
6
7
  *
7
8
  * - 按描述找能力:模型已经知道大致有什么人,需要完整描述判断能不能用。
8
9
  * - 按名字找 AID:Owner 或 PA 说"联系张三",把名字落成 AID。
9
10
  *
10
- * `find` 未命中时会触发一次有界同步(和准入路径共用 `lookupByAid` 与模块级单飞),
11
+ * 关键词不命中时会触发一次有界同步(和准入路径共用 `lookupByAid` 与模块级单飞),
11
12
  * 同步完再查一次——"本地没有"通常意味着"刚更新还没拉下来",而不是"没有这个人"。
12
13
  */
13
14
  import fs from 'node:fs';
@@ -15,11 +16,21 @@ import path from 'node:path';
15
16
  import { agentDir } from '../paths.js';
16
17
  import { isValidAid } from '../aun/aid/validation.js';
17
18
  import { OwnerDirectoryCache, OWNER_DIRECTORY_SCOPES } from './owner-directory-cache.js';
18
- import { readAllRemarks, readRemark } from './owner-directory-remarks.js';
19
- import { describeEntry, searchDirectory, } from './owner-directory-search.js';
19
+ import { readAllRemarks } from './owner-directory-remarks.js';
20
+ import { describeEntry, filterDirectory, } from './owner-directory-search.js';
20
21
  import { isInternalEntry, ownerRefAid } from './owner-directory-scope.js';
22
+ import { editDistance, normalizeDirectoryText, sameDirectoryName, stripTrailingParenthetical, } from './owner-directory-text.js';
21
23
  import { ownerResolver } from '../core/ownership/owner-resolver.js';
22
- import { resolveAllowExternalContacts, syncOwnerDirectoryForLookup } from './owner-directory-admission.js';
24
+ import { authorizedOwnerAid, refreshOwnerDirectory, syncOwnerDirectoryForLookup } from './owner-directory-admission.js';
25
+ import { getPeerSnapshot } from '../config/peer-book.js';
26
+ import { resolveEntryContactable } from './owner-directory-policy.js';
27
+ /** 旧命令名 → 新命令。`find` 合入 `list --filter`,`show` 改名为 `info`。 */
28
+ const LEGACY_ACTIONS = { find: 'list', show: 'info' };
29
+ /** `info` 按名字命中时的默认上限。 */
30
+ const INFO_NAME_MATCH_LIMIT = 20;
31
+ /** `list` 的分页默认值与上限;与 `ec skill list` 的默认 20 条一致。 */
32
+ const LIST_DEFAULT_LIMIT = 20;
33
+ const LIST_MAX_LIMIT = 100;
23
34
  export class DirectoryQueryError extends Error {
24
35
  code;
25
36
  constructor(code, message) {
@@ -28,11 +39,13 @@ export class DirectoryQueryError extends Error {
28
39
  this.name = 'DirectoryQueryError';
29
40
  }
30
41
  }
31
- /** 解析 `ec directory <find|show|list> ...` 之后的 argv。 */
42
+ /** 解析 `ec directory <list|info|refresh|blocked> ...` 之后的 argv。 */
32
43
  export function resolveDirectoryQueryCommand(argv) {
33
- const [action, ...rest] = argv;
34
- if (action !== 'find' && action !== 'show' && action !== 'list') {
35
- throw new DirectoryQueryError('INVALID_ACTION', 'directory requires one of: find, show, list');
44
+ const [rawAction, ...rest] = argv;
45
+ const action = LEGACY_ACTIONS[rawAction] ?? rawAction;
46
+ if (action !== 'list' && action !== 'info'
47
+ && action !== 'refresh' && action !== 'blocked') {
48
+ throw new DirectoryQueryError('INVALID_ACTION', 'directory requires one of: list, info, refresh, blocked');
36
49
  }
37
50
  const selfAid = takeFlag(rest, '--self') ?? process.env.EVOLCORE_SELF_AID?.trim();
38
51
  if (!selfAid)
@@ -42,24 +55,45 @@ export function resolveDirectoryQueryCommand(argv) {
42
55
  const scope = parseScope(takeFlag(rest, '--scope'));
43
56
  const type = takeFlag(rest, '--type')?.trim() || undefined;
44
57
  const limit = parseLimit(takeFlag(rest, '--limit'));
58
+ const page = parsePage(takeFlag(rest, '--page'));
59
+ const ownerAid = parseOwnerFilter(takeFlag(rest, '--owner'));
45
60
  const positional = takePositional(rest);
46
- if (action === 'find') {
47
- const query = positional.join(' ').trim();
48
- if (!query)
49
- throw new DirectoryQueryError('INVALID_ARGUMENT', 'find requires a query');
50
- return { action, selfAid, query, ...(type ? { type } : {}), ...(scope ? { scope } : {}), ...(limit ? { limit } : {}) };
51
- }
52
- if (action === 'show') {
53
- const aid = positional[0];
54
- if (!aid)
55
- throw new DirectoryQueryError('INVALID_ARGUMENT', 'show requires a contact AID');
56
- if (!isValidAid(aid))
57
- throw new DirectoryQueryError('INVALID_ARGUMENT', `invalid contact AID: ${aid}`);
58
- return { action, selfAid, aid };
59
- }
60
- if (positional.length > 0)
61
- throw new DirectoryQueryError('INVALID_ARGUMENT', 'list takes no positional argument');
62
- return { action, selfAid, ...(type ? { type } : {}), ...(scope ? { scope } : {}), ...(limit ? { limit } : {}) };
61
+ if (action === 'info') {
62
+ const target = positional.join(' ').trim();
63
+ if (!target)
64
+ throw new DirectoryQueryError('INVALID_ARGUMENT', 'info requires a contact AID or name');
65
+ // 名字里可能有空格(备注名/显示名允许),所以拼起来整体作为 target;
66
+ // 是不是 AID 由执行层判定,参数层不做格式假设。
67
+ return {
68
+ action, selfAid, target,
69
+ ...(limit ? { limit } : {}),
70
+ };
71
+ }
72
+ if (action === 'list') {
73
+ // `--filter 'a,b' --filter 'c'`:组内 OR、组间 AND。
74
+ const filterGroups = takeFlags(rest, '--filter')
75
+ .map(value => value.split(',').map(item => item.trim()).filter(Boolean))
76
+ .filter(group => group.length > 0);
77
+ // 位置参数是老 `find` 的写法:多个词要求同时命中 → 每个词一组(AND)。
78
+ const positionalGroups = positional
79
+ .map(token => token.trim()).filter(Boolean)
80
+ .map(token => [token]);
81
+ const filters = [...filterGroups, ...positionalGroups];
82
+ return {
83
+ action, selfAid,
84
+ ...(filters.length > 0 ? { filters } : {}),
85
+ ...(type ? { type } : {}), ...(scope ? { scope } : {}),
86
+ ...(ownerAid ? { ownerAid } : {}), ...(limit ? { limit } : {}), ...(page ? { page } : {}),
87
+ };
88
+ }
89
+ if (positional.length > 0) {
90
+ throw new DirectoryQueryError('INVALID_ARGUMENT', `${action} takes no positional argument`);
91
+ }
92
+ return {
93
+ action, selfAid,
94
+ ...(type ? { type } : {}), ...(scope ? { scope } : {}),
95
+ ...(ownerAid ? { ownerAid } : {}),
96
+ };
63
97
  }
64
98
  /**
65
99
  * 执行查询。
@@ -72,89 +106,318 @@ export async function executeDirectoryQueryCommand(command) {
72
106
  if (!fs.existsSync(agentDir(command.selfAid))) {
73
107
  return { ok: false, code: 'AGENT_NOT_FOUND', error: `agent ${command.selfAid} does not exist` };
74
108
  }
75
- const ownerAid = ownerResolver.owner(command.selfAid) ?? ownerResolver.knownOwner(command.selfAid);
109
+ // ownerAid 必须与磁盘上的授权一致:离线时 `ownerResolver` 只能给出 known owner,
110
+ // 可能与 authorization.json 里的 Owner 不同,那样 `scopeAccess` 会判成未授权。
111
+ const ownerAid = authorizedOwnerAid(directory, command.selfAid);
76
112
  if (!ownerAid) {
77
- return { ok: false, code: 'OWNER_UNKNOWN', error: `agent ${command.selfAid} has no Owner` };
113
+ return { ok: false, code: 'NOT_AUTHORIZED', error: 'directory is not authorized for this agent' };
78
114
  }
79
115
  const cache = new OwnerDirectoryCache({ selfAid: command.selfAid, ownerAid, directory });
80
116
  const scope = OWNER_DIRECTORY_SCOPES[0];
81
117
  if (cache.scopeAccess(scope) !== 'authorized') {
82
118
  return { ok: false, code: 'NOT_AUTHORIZED', error: 'directory is not authorized for this agent' };
83
119
  }
84
- let snapshot = cache.readSnapshot(scope);
120
+ // refresh 要在快照判空之前处理:它存在的意义正是"本地没有或太旧,去拉一次"。
121
+ if (command.action === 'refresh') {
122
+ const result = await refreshOwnerDirectory(command.selfAid);
123
+ // 拉取需要连接,重算不需要:只要本地重算成功就算成功,
124
+ // `pulled: false` 只表示"没有拉到新内容",不是失败。
125
+ if (!result.pulled && !result.regenerated) {
126
+ return { ok: false, code: 'REFRESH_UNAVAILABLE', error: 'directory is not available for this agent' };
127
+ }
128
+ return { ok: true, action: 'refresh', ...result };
129
+ }
130
+ if (command.action === 'blocked') {
131
+ return directoryBlockedEntries(command, directory, ownerAid, cache, scope);
132
+ }
133
+ // Owner 与个人助理是顶层身份块,不在 `entries` 里;但注入的 directory.md 把
134
+ // 他们列在最上面,也提示了「用 ec directory info 查详情」。查询必须能查到。
135
+ let snapshot = withIdentityEntries(cache.readSnapshot(scope));
85
136
  if (!snapshot) {
86
137
  return { ok: false, code: 'NO_SNAPSHOT', error: 'directory snapshot is not available yet' };
87
138
  }
88
- const ownerRef = ownerRefAid(snapshot, ownerAid);
89
139
  const contactable = resolveContactable(command.selfAid, cache);
90
- const remarks = readAllRemarks(directory);
91
- if (command.action === 'find') {
92
- let hits = searchDirectory(snapshot, ownerAid, remarks, {
93
- query: command.query,
94
- ...(command.type ? { type: command.type } : {}),
95
- ...(command.scope ? { scope: command.scope } : {}),
96
- ...(command.limit ? { limit: command.limit } : {}),
97
- });
140
+ if (command.action === 'info') {
141
+ const target = command.target ?? '';
142
+ const lookup = (snap) => infoTarget(snap, target, ownerAid, directory, contactable, command.limit);
143
+ let hit = lookup(snapshot);
98
144
  let synced = false;
99
- if (hits.length === 0) {
145
+ if (hit.entries.length === 0) {
100
146
  // 未命中通常是"刚更新还没拉下来":触发一次有界同步再看一遍。
101
147
  synced = await syncOnce(command.selfAid);
102
- snapshot = cache.readSnapshot(scope);
103
- if (snapshot) {
104
- hits = searchDirectory(snapshot, ownerAid, readAllRemarks(directory), {
105
- query: command.query,
106
- ...(command.type ? { type: command.type } : {}),
107
- ...(command.scope ? { scope: command.scope } : {}),
108
- ...(command.limit ? { limit: command.limit } : {}),
109
- });
110
- }
148
+ const refreshed = withIdentityEntries(cache.readSnapshot(scope));
149
+ if (refreshed)
150
+ hit = lookup(refreshed);
111
151
  }
112
- return { ok: true, action: 'find', hits, synced };
113
- }
114
- if (command.action === 'show') {
115
- const entry = snapshot.entries.find(item => item.aid === command.aid);
116
- if (!entry) {
117
- const synced = await syncOnce(command.selfAid);
118
- const refreshed = cache.readSnapshot(scope);
119
- const found = refreshed?.entries.find(item => item.aid === command.aid);
120
- if (!found) {
121
- return {
122
- ok: false, code: 'NOT_FOUND',
123
- error: `${command.aid} is not in the directory${synced ? ' (after a sync attempt)' : ''}`,
124
- };
125
- }
126
- const ref = ownerRefAid(refreshed, ownerAid);
127
- return { ok: true, action: 'show', entry: describeEntry(found, ref, readRemark(directory, found.aid), contactable) };
152
+ if (hit.entries.length === 0) {
153
+ const close = hit.suggestions?.length
154
+ ? `; close matches: ${hit.suggestions.map(item => `${item.name}(${item.aid})`).join(', ')}`
155
+ : '';
156
+ return {
157
+ ok: false, code: 'NOT_FOUND',
158
+ error: `${target} is not in the directory${synced ? ' (after a sync attempt)' : ''}${close}`,
159
+ };
160
+ }
161
+ return {
162
+ ok: true, action: 'info',
163
+ entries: hit.entries,
164
+ ...(hit.entries.length === 1 ? { entry: hit.entries[0] } : {}),
165
+ matchedBy: hit.matchedBy,
166
+ ...(hit.matchKind ? { matchKind: hit.matchKind } : {}),
167
+ ...(hit.truncated ? { truncated: hit.truncated } : {}),
168
+ synced,
169
+ };
170
+ }
171
+ // list:过滤后分页。过滤条件为空时就是全量列举。
172
+ let filtered = filterDirectory(snapshot, ownerAid, readAllRemarks(directory), {
173
+ ...(command.filters ? { filters: command.filters } : {}),
174
+ ...(command.type ? { type: command.type } : {}),
175
+ ...(command.scope ? { scope: command.scope } : {}),
176
+ ...(command.ownerAid ? { ownerAid: command.ownerAid } : {}),
177
+ });
178
+ let synced = false;
179
+ if (filtered.length === 0 && command.filters?.length) {
180
+ // 不命中时才做一次有界同步:全量列举不需要网络。
181
+ synced = await syncOnce(command.selfAid);
182
+ const refreshed = withIdentityEntries(cache.readSnapshot(scope));
183
+ if (refreshed) {
184
+ snapshot = refreshed;
185
+ filtered = filterDirectory(snapshot, ownerAid, readAllRemarks(directory), {
186
+ ...(command.filters ? { filters: command.filters } : {}),
187
+ ...(command.type ? { type: command.type } : {}),
188
+ ...(command.scope ? { scope: command.scope } : {}),
189
+ ...(command.ownerAid ? { ownerAid: command.ownerAid } : {}),
190
+ });
128
191
  }
129
- return { ok: true, action: 'show', entry: describeEntry(entry, ownerRef, remarks.get(entry.aid), contactable) };
130
- }
131
- const typeFilter = command.type?.trim().toLowerCase();
132
- const scopeFilter = command.scope ?? 'internal';
133
- const entries = snapshot.entries
134
- .filter(entry => {
135
- const internal = isInternalEntry(entry, ownerRef);
136
- if (scopeFilter === 'internal' && !internal)
137
- return false;
138
- if (scopeFilter === 'external' && internal)
139
- return false;
140
- if (typeFilter && (entry.type ?? '').toLowerCase() !== typeFilter)
141
- return false;
142
- return true;
143
- })
144
- .map(entry => describeEntry(entry, ownerRef, remarks.get(entry.aid), contactable));
145
- return { ok: true, action: 'list', entries };
192
+ }
193
+ const limit = Math.min(command.limit ?? LIST_DEFAULT_LIMIT, LIST_MAX_LIMIT);
194
+ const page = command.page ?? 1;
195
+ const total = filtered.length;
196
+ const start = (page - 1) * limit;
197
+ const ownerRef = ownerRefAid(snapshot, ownerAid);
198
+ const remarks = readAllRemarks(directory);
199
+ const entries = filtered.slice(start, start + limit)
200
+ // 检索结果不带本地备注正文:要看正文用 `ec directory info <AID>`。
201
+ .map(entry => describeEntry(entry, ownerRef, remarks.get(entry.aid), contactable, {
202
+ includeLocalRemark: false,
203
+ }));
204
+ return {
205
+ ok: true, action: 'list', entries, page, limit, total, hasMore: start + entries.length < total,
206
+ };
207
+ }
208
+ /**
209
+ * `ec directory blocked`:列出被拉黑的主体,两个来源合并。
210
+ *
211
+ * - `contacts.json` 的 `blocked_aids`:Owner 侧发布的拉黑,跨 Agent 生效;
212
+ * - `peers.json` 的 `blocked`:本端自己拉的,只对本 agent 生效。
213
+ *
214
+ * 两者都会让消息被拒,但语义不同,所以输出里标 `source`。名录里有这个 AID 时
215
+ * 补上名字,没在名录里也要列出来——拉黑的对象不一定还在名录里。
216
+ */
217
+ function directoryBlockedEntries(command, directory, ownerAid, cache, scope) {
218
+ const snapshot = cache.readSnapshot(scope);
219
+ const ownerRef = ownerRefAid(snapshot, ownerAid);
220
+ const remarks = readAllRemarks(directory);
221
+ const contactable = resolveContactable(command.selfAid, cache);
222
+ const sources = new Map();
223
+ for (const aid of readBlockedAidsFromSnapshot(directory)) {
224
+ if (!sources.has(aid))
225
+ sources.set(aid, new Set());
226
+ sources.get(aid).add('owner');
227
+ }
228
+ try {
229
+ for (const aid of getPeerSnapshot(command.selfAid).blockedIndex) {
230
+ if (!aid)
231
+ continue;
232
+ if (!sources.has(aid))
233
+ sources.set(aid, new Set());
234
+ sources.get(aid).add('local');
235
+ }
236
+ }
237
+ catch {
238
+ // peers.json 坏了不影响名录侧的拉黑:能列多少列多少。
239
+ }
240
+ const entries = [...sources.entries()].map(([aid, sourceSet]) => {
241
+ const entry = snapshot?.entries.find(item => item.aid === aid);
242
+ const name = entry?.name ?? null;
243
+ return {
244
+ aid,
245
+ name,
246
+ ...(entry?.type !== undefined ? { type: entry.type } : {}),
247
+ ...(entry ? { internal: isInternalEntry(entry, ownerRef) } : {}),
248
+ inDirectory: !!entry,
249
+ source: [...sourceSet].sort().join(','),
250
+ // 黑名单条目一律不可联系;这里给的是"名录层面的可联系性",两者取与。
251
+ contactable: false,
252
+ ...(entry ? { contactableForEntry: contactable(entry) } : {}),
253
+ };
254
+ }).sort((a, b) => a.aid.localeCompare(b.aid));
255
+ return { ok: true, action: 'blocked', entries };
256
+ }
257
+ /**
258
+ * 读本地快照文件里的 `blocked_aids`。
259
+ *
260
+ * 快照对象(`OwnerDirectorySnapshot`)不保留这一项——准入只关心条目,拉黑
261
+ * 走的是另一条判据;这里为 `ec directory blocked` 直接读原始文件。格式按协议是
262
+ * `{ target_type: 'aid'|'group', target_id }`,也容忍纯字符串数组。
263
+ */
264
+ function readBlockedAidsFromSnapshot(directory) {
265
+ try {
266
+ const raw = JSON.parse(fs.readFileSync(path.join(directory, 'contacts.json'), 'utf8'));
267
+ const list = raw?.blockedAids
268
+ ?? raw?.blocked_aids;
269
+ if (!Array.isArray(list))
270
+ return [];
271
+ const aids = [];
272
+ for (const item of list) {
273
+ const aid = typeof item === 'string'
274
+ ? item
275
+ : (item && typeof item === 'object' && typeof item.target_id === 'string'
276
+ ? String(item.target_id) : '');
277
+ if (aid && isValidAid(aid))
278
+ aids.push(aid);
279
+ }
280
+ return aids;
281
+ }
282
+ catch {
283
+ return [];
284
+ }
285
+ }
286
+ /**
287
+ * 把快照顶层的 `owner` / `personal_assistant` 身份块补成可查询条目。
288
+ *
289
+ * 这两个身份块按协议**不属于** `entries`(`personal_assistant` 是身份元数据),
290
+ * 但注入的 `directory.md` 把 Owner 和个人助理列在最上面,并提示用
291
+ * `ec directory info <名字>` 看详情。只查 `entries` 会让最该查到的两个人查不到。
292
+ * 与已有条目同 AID 时以条目为准,避免同一个人出现两次。
293
+ *
294
+ * 两者在快照解析阶段已经和 `authorization.json` 的授权 Owner 做过一致性校验,
295
+ * 所以补成条目时按“已核验”处理,否则他们会被自己的归属门禁判成外部。
296
+ */
297
+ function withIdentityEntries(snapshot) {
298
+ if (!snapshot)
299
+ return undefined;
300
+ const known = new Set(snapshot.entries.map(entry => entry.aid));
301
+ const ownerRef = snapshot.owner?.aid ?? snapshot.ownerAid;
302
+ const extra = [];
303
+ for (const field of [snapshot.owner, snapshot.personalAssistant]) {
304
+ if (!field?.aid || known.has(field.aid))
305
+ continue;
306
+ known.add(field.aid);
307
+ extra.push(identityEntry(field, ownerRef));
308
+ }
309
+ return extra.length > 0 ? { ...snapshot, entries: [...extra, ...snapshot.entries] } : snapshot;
310
+ }
311
+ function identityEntry(field, ownerAid) {
312
+ return {
313
+ aid: field.aid,
314
+ name: field.name || field.aid,
315
+ ownerAid,
316
+ ownership_status: 'owned',
317
+ ...(field.agent_md_signed_at !== undefined ? { agent_md_signed_at: field.agent_md_signed_at } : {}),
318
+ };
146
319
  }
147
320
  /**
148
- * 一次有界同步(B 方案):用 channel 注册着的活缓存触发,和准入路径共用
149
- * 模块级单飞。查询用的只读实例没有网络能力——没有活缓存时返回 false,
150
- * 按未命中处理。
321
+ * `show` 的目标解析:合法 AID 精确匹配;否则当名字匹配,分两级——
322
+ * 归一后精确相等(全角/空格/结尾括号称呼不影响),没命中再按名字包含放宽。
323
+ * 两级都不碰描述字段:描述里提到某人(「李文江的助理」)不代表那条就是某人。
324
+ *
325
+ * 备注名优先级与渲染一致:本地备注 > 远端 remark > 远端 name。
151
326
  */
327
+ function infoTarget(snapshot, target, ownerAid, directory, contactable,
328
+ /** 同名多条时的上限;不传按 20 条封顶,防止一个常见名字把上下文灌满。 */
329
+ limit) {
330
+ const ownerRef = ownerRefAid(snapshot, ownerAid);
331
+ const remarks = readAllRemarks(directory);
332
+ // 兼容 `@aid` 写法(与 daemon 里委托凭据的处理一致),AID 大小写不敏感。
333
+ const bareTarget = target.trim().replace(/^@/, '');
334
+ if (isValidAid(bareTarget)) {
335
+ const wantedAid = normalizeDirectoryText(bareTarget);
336
+ const entry = snapshot.entries.find((item) => normalizeDirectoryText(item.aid) === wantedAid);
337
+ return {
338
+ matchedBy: 'aid',
339
+ entries: entry ? [describeEntry(entry, ownerRef, remarks.get(entry.aid), contactable)] : [],
340
+ };
341
+ }
342
+ const wanted = normalizeDirectoryText(target);
343
+ const namesOf = (entry) => {
344
+ const remark = remarks.get(entry.aid);
345
+ // 所有叫法都参与:名录名、Owner 的备注名、本地记的每一个称呼。
346
+ return [entry.name, entry.remark, ...(remark?.aliases ?? (remark?.remark ? [remark.remark] : []))]
347
+ .map(value => (typeof value === 'string' ? value : ''))
348
+ .filter(Boolean);
349
+ };
350
+ const exact = snapshot.entries.filter((entry) => namesOf(entry).some(name => sameDirectoryName(name, wanted)));
351
+ const matched = exact.length > 0
352
+ ? { entries: exact, kind: 'exact' }
353
+ // 精确没命中才放宽到包含:中文名很少误伤,但绝不能回落到描述——
354
+ // 「李文江的助理」不是李文江本人。
355
+ : { entries: fuzzyNameMatches(snapshot, wanted, namesOf), kind: 'fuzzy' };
356
+ const cap = limit ?? INFO_NAME_MATCH_LIMIT;
357
+ const result = {
358
+ matchedBy: 'name',
359
+ entries: matched.entries.slice(0, cap).map((entry) => describeEntry(entry, ownerRef, remarks.get(entry.aid), contactable)),
360
+ ...(matched.entries.length > 0 ? { matchKind: matched.kind } : {}),
361
+ ...(matched.entries.length > cap ? { truncated: matched.entries.length - cap } : {}),
362
+ };
363
+ if (matched.entries.length === 0) {
364
+ result.suggestions = nearestNames(snapshot, wanted, namesOf);
365
+ }
366
+ return result;
367
+ }
368
+ /** 名字/称呼包含查询串。长度小于 2 的查询串不做放宽,否则单个字会命中一大片。 */
369
+ function fuzzyNameMatches(snapshot, wanted, namesOf) {
370
+ if (wanted.length < 2)
371
+ return [];
372
+ return snapshot.entries.filter((entry) => namesOf(entry).some(name => {
373
+ const normalized = normalizeDirectoryText(name);
374
+ const base = normalizeDirectoryText(stripTrailingParenthetical(normalized));
375
+ return normalized.includes(wanted) || base.includes(wanted);
376
+ }));
377
+ }
378
+ /** 拼错/叫法差异时的兜底提示:按编辑距离找最多 3 个最近的名字。 */
379
+ function nearestNames(snapshot, wanted, namesOf) {
380
+ if (wanted.length < 2)
381
+ return [];
382
+ const scored = [];
383
+ for (const entry of snapshot.entries) {
384
+ let best = Number.POSITIVE_INFINITY;
385
+ let closest = entry.name;
386
+ for (const name of namesOf(entry)) {
387
+ const normalized = normalizeDirectoryText(stripTrailingParenthetical(normalizeDirectoryText(name)));
388
+ if (!normalized)
389
+ continue;
390
+ const distance = editDistance(normalized, wanted);
391
+ if (distance < best) {
392
+ best = distance;
393
+ closest = name;
394
+ }
395
+ }
396
+ const threshold = wanted.length >= 5 ? 2 : 1;
397
+ if (best <= threshold)
398
+ scored.push({ aid: entry.aid, name: closest, distance: best });
399
+ }
400
+ return scored.sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name))
401
+ .slice(0, 3)
402
+ .map(({ aid, name }) => ({ aid, name }));
403
+ }
152
404
  async function syncOnce(selfAid) {
153
405
  return syncOwnerDirectoryForLookup(selfAid);
154
406
  }
155
- /** 这个人现在能不能联系:外部条目取决于 `allowExternalContacts`。 */
407
+ /**
408
+ * 这条名录条目现在能不能联系。
409
+ *
410
+ * 逐条判定而不是整份一个布尔:内部条目看内部档,外部条目看外部档,白名单与
411
+ * 黑名单各自优先。只算一次 `allowExternalContacts` 就套给所有条目,会把
412
+ * 内部联系人一起标成"不可联系"。
413
+ */
156
414
  function resolveContactable(selfAid, cache) {
157
- return resolveAllowExternalContacts(selfAid, cache.readSnapshot(OWNER_DIRECTORY_SCOPES[0]));
415
+ const snapshot = cache.readSnapshot(OWNER_DIRECTORY_SCOPES[0]);
416
+ const ownerRef = ownerRefAid(snapshot, ownerResolver.owner(selfAid) ?? '');
417
+ return entry => resolveEntryContactable(selfAid, snapshot, {
418
+ aid: entry.aid,
419
+ internal: isInternalEntry(entry, ownerRef),
420
+ });
158
421
  }
159
422
  function takeFlag(args, flag) {
160
423
  const index = args.indexOf(flag);
@@ -166,15 +429,35 @@ function takeFlag(args, flag) {
166
429
  }
167
430
  return value;
168
431
  }
432
+ /** 可重复的标志:`--filter 'a,b' --filter c`。 */
433
+ function takeFlags(args, flag) {
434
+ const values = [];
435
+ for (let index = 0; index < args.length; index++) {
436
+ if (args[index] !== flag)
437
+ continue;
438
+ const value = args[index + 1];
439
+ if (value === undefined || value.startsWith('--')) {
440
+ throw new DirectoryQueryError('INVALID_ARGUMENT', `${flag} requires a value`);
441
+ }
442
+ values.push(value);
443
+ index++;
444
+ }
445
+ return values;
446
+ }
447
+ /** 带值的标志;其余 `--xxx` 视为布尔标志(如 `--json`),不能吃掉后面的位置参数。 */
448
+ const VALUED_FLAGS = new Set([
449
+ '--self', '--type', '--scope', '--owner', '--limit', '--page', '--filter', '--format',
450
+ ]);
169
451
  function takePositional(args) {
170
452
  const result = [];
171
453
  for (let index = 0; index < args.length; index++) {
172
454
  const arg = args[index];
173
- if (arg.startsWith('--')) {
174
- index++;
455
+ if (!arg.startsWith('--')) {
456
+ result.push(arg);
175
457
  continue;
176
458
  }
177
- result.push(arg);
459
+ if (VALUED_FLAGS.has(arg))
460
+ index++;
178
461
  }
179
462
  return result;
180
463
  }
@@ -185,6 +468,24 @@ function parseScope(value) {
185
468
  return value;
186
469
  throw new DirectoryQueryError('INVALID_ARGUMENT', '--scope must be internal, external or all');
187
470
  }
471
+ /**
472
+ * `--owner <aid|unbound>`:按条目归属过滤。
473
+ *
474
+ * `unbound` 是保留值,表示"名录里没有 owner_aid 的条目"——那批人内外判断不了,
475
+ * 列出来通常是排查用。其余值必须是合法 AID。
476
+ */
477
+ function parseOwnerFilter(value) {
478
+ if (value === undefined)
479
+ return undefined;
480
+ const trimmed = value.trim();
481
+ if (!trimmed)
482
+ throw new DirectoryQueryError('INVALID_ARGUMENT', '--owner requires a value');
483
+ if (trimmed === 'unbound')
484
+ return trimmed;
485
+ if (!isValidAid(trimmed))
486
+ throw new DirectoryQueryError('INVALID_ARGUMENT', `invalid --owner AID: ${trimmed}`);
487
+ return trimmed;
488
+ }
188
489
  function parseLimit(value) {
189
490
  if (value === undefined)
190
491
  return undefined;
@@ -193,3 +494,11 @@ function parseLimit(value) {
193
494
  }
194
495
  return Number(value);
195
496
  }
497
+ function parsePage(value) {
498
+ if (value === undefined)
499
+ return undefined;
500
+ if (!/^\d+$/.test(value) || Number(value) <= 0) {
501
+ throw new DirectoryQueryError('INVALID_ARGUMENT', '--page must be a positive integer');
502
+ }
503
+ return Number(value);
504
+ }
@@ -57,15 +57,37 @@ export function parseRemarkFile(text, expectedAid) {
57
57
  const declaredAid = fields.aid;
58
58
  if (!declaredAid || declaredAid !== expectedAid)
59
59
  return undefined;
60
- const remark = fields.remark || undefined;
60
+ // 称呼可以有多个:`remark: 蒋总, 老蒋`。统一按中英文逗号、顿号与空白切分。
61
+ const aliases = splitAliases(fields.remark);
62
+ const remark = aliases.length > 0 ? fields.remark : undefined;
61
63
  const updatedAt = /^\d+$/.test(fields.updated_at ?? '') ? Number(fields.updated_at) : undefined;
62
64
  return {
63
65
  aid: declaredAid,
64
66
  ...(remark !== undefined ? { remark } : {}),
67
+ ...(aliases.length > 0 ? { aliases } : {}),
65
68
  ...(body ? { body } : {}),
66
69
  ...(updatedAt !== undefined ? { updatedAt } : {}),
67
70
  };
68
71
  }
72
+ /**
73
+ * 拆分称呼:中英文逗号、顿号、分号与空白都算分隔符,去重保序。
74
+ *
75
+ * 只写一个称呼时行为与以前完全一致(返回单元素数组)。
76
+ */
77
+ export function splitAliases(value) {
78
+ if (!value)
79
+ return [];
80
+ const seen = new Set();
81
+ const out = [];
82
+ for (const part of String(value).split(/[,,、;;\s]+/)) {
83
+ const alias = part.trim();
84
+ if (!alias || seen.has(alias))
85
+ continue;
86
+ seen.add(alias);
87
+ out.push(alias);
88
+ }
89
+ return out;
90
+ }
69
91
  export function serializeRemarkFile(remark) {
70
92
  const lines = ['---', `aid: ${remark.aid}`];
71
93
  if (remark.remark)
@@ -138,8 +160,13 @@ export function removeRemark(directory, aid) {
138
160
  atomicRemove(file);
139
161
  return true;
140
162
  }
163
+ /** 备注清单。`remark` 是称呼、`body` 是正文,两者可独立存在。 */
141
164
  export function listRemarks(directory) {
142
165
  return [...readAllRemarks(directory).values()]
143
- .map(({ aid, remark }) => ({ aid, ...(remark !== undefined ? { remark } : {}) }))
166
+ .map(({ aid, remark, body }) => ({
167
+ aid,
168
+ ...(remark !== undefined ? { remark } : {}),
169
+ ...(body !== undefined ? { body } : {}),
170
+ }))
144
171
  .sort((a, b) => a.aid.localeCompare(b.aid));
145
172
  }