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
@@ -0,0 +1,76 @@
1
+ import fs from 'node:fs';
2
+ import crypto from 'node:crypto';
3
+ import { agentConfig } from '../paths.js';
4
+ import { isValidAid } from '../aun/aid/validation.js';
5
+ import { FRIEND_INVITE_TTL_MS } from '../core/message/contact-admission.js';
6
+ import { DirectoryQueryError } from './owner-directory-query-operation.js';
7
+ /** Submit the App-owned invitation protocol without mutating the directory or access policy. */
8
+ export function resolveDirectoryRequestCommand(argv) {
9
+ if (argv[0] !== 'request')
10
+ throw new DirectoryQueryError('INVALID_ACTION', 'directory request is required');
11
+ const values = new Map();
12
+ const positionals = [];
13
+ for (let index = 1; index < argv.length; index++) {
14
+ const token = argv[index];
15
+ if (!token.startsWith('-')) {
16
+ positionals.push(token);
17
+ continue;
18
+ }
19
+ if (!['--self', '--note', '--format'].includes(token)) {
20
+ throw new DirectoryQueryError('INVALID_ARGUMENT', `未知 request 参数: ${token}`);
21
+ }
22
+ const value = argv[++index];
23
+ if (values.has(token) || !value?.trim() || value.startsWith('--')) {
24
+ throw new DirectoryQueryError('INVALID_ARGUMENT', `${token} 必须提供非空值,且不能重复`);
25
+ }
26
+ values.set(token, value.trim());
27
+ }
28
+ const selfAid = values.get('--self') ?? process.env.EVOLCORE_SELF_AID?.trim();
29
+ if (!selfAid || !isValidAid(selfAid)) {
30
+ throw new DirectoryQueryError('INVALID_ARGUMENT', '--self <agent-aid> 必须是有效的本端 Agent AID');
31
+ }
32
+ if (positionals.length !== 1 || !isValidAid(positionals[0])) {
33
+ throw new DirectoryQueryError('INVALID_ARGUMENT', '用法: ec directory request <target-aid> --self <agent-aid> [--note <申请说明>]');
34
+ }
35
+ if (positionals[0] === selfAid) {
36
+ throw new DirectoryQueryError('INVALID_ARGUMENT', '不能向本 Agent 自己发送好友申请');
37
+ }
38
+ const format = values.get('--format');
39
+ if (format !== undefined && format !== 'json' && format !== 'text') {
40
+ throw new DirectoryQueryError('INVALID_ARGUMENT', '--format 仅支持 text|json');
41
+ }
42
+ const note = values.get('--note');
43
+ if (note?.includes('\0')) {
44
+ throw new DirectoryQueryError('INVALID_ARGUMENT', '申请说明不能包含 NUL');
45
+ }
46
+ return { action: 'request', selfAid, targetAid: positionals[0], ...(note ? { note } : {}) };
47
+ }
48
+ export async function executeDirectoryRequestCommand(command, send) {
49
+ if (!fs.existsSync(agentConfig(command.selfAid))) {
50
+ return { ok: false, code: 'AGENT_NOT_FOUND', error: `Agent 不存在: ${command.selfAid}` };
51
+ }
52
+ const createdAt = Date.now();
53
+ const payload = {
54
+ type: 'friend.invite.v1',
55
+ schema_version: 1,
56
+ invite_id: `friend-invite-${crypto.randomUUID()}`,
57
+ applicant_aid: command.selfAid,
58
+ target_aid: command.targetAid,
59
+ created_at_ms: createdAt,
60
+ expires_at_ms: createdAt + FRIEND_INVITE_TTL_MS,
61
+ introduction: command.note ?? '你好,我想添加你为联系人。',
62
+ };
63
+ try {
64
+ const result = await send({ from: command.selfAid, to: command.targetAid, payload, encrypt: true });
65
+ if (!result.ok || !result.message_id) {
66
+ return { ok: false, code: String(result.code ?? 'FRIEND_INVITE_FAILED'),
67
+ error: `向目标 ${command.targetAid} 发送加好友申请失败:${result.error ?? '未获得消息发送回执'}` };
68
+ }
69
+ return { ok: true, action: 'request', selfAid: command.selfAid, targetAid: command.targetAid,
70
+ status: 'sent', message_id: result.message_id };
71
+ }
72
+ catch (error) {
73
+ return { ok: false, code: 'FRIEND_INVITE_FAILED',
74
+ error: `向目标 ${command.targetAid} 发送加好友申请失败:${error instanceof Error ? error.message : String(error)}` };
75
+ }
76
+ }
@@ -40,6 +40,27 @@ export function isMessagingType(type) {
40
40
  export function ownerRefAid(snapshot, fallbackOwnerAid) {
41
41
  return snapshot?.owner?.aid ?? fallbackOwnerAid;
42
42
  }
43
+ /**
44
+ * 归属是否经过双边核验。
45
+ *
46
+ * 协议里 `ownership_status` 只有 `owned` / `unknown`:`owned` 表示 Owner 侧已经
47
+ * 通过 Ownership 共识确认了这条与自己的绑定关系,`unknown`(以及缺字段)都表示
48
+ * **没能确认**。内外判定和注入都只认 `owned`——否则一个 Agent 只要在名录里
49
+ * 把 `owner_aid` 写成我们的 Owner,就能拿到内部联系人的默认放行。
50
+ */
51
+ export function isOwnershipVerified(entry) {
52
+ return (entry.ownership_status ?? '').trim().toLowerCase() === 'owned';
53
+ }
54
+ /**
55
+ * 这条主体要不要过双边归属门禁。
56
+ *
57
+ * 只对 `type=agent` 生效:会自称“我是某某的 Agent”并据此索取内部待遇的是 Agent,
58
+ * 双边核验要拦的也是它。人类联系人由 Owner 在名录里直接维护,`owner_aid` 本身
59
+ * 就是 Owner 的明确指派;其余非消息类型(host/device/service…)不参与消息准入。
60
+ */
61
+ function requiresOwnershipVerification(entry) {
62
+ return (entry.type ?? '').trim().toLowerCase() === 'agent';
63
+ }
43
64
  /** 条目的 Owner AID;缺失返回 undefined。 */
44
65
  export function entryOwnerAid(entry) {
45
66
  const value = entry.ownerAid?.trim();
@@ -64,11 +85,21 @@ export function classifyEntry(entry, ownerRef) {
64
85
  const owner = entryOwnerAid(entry);
65
86
  if (owner === undefined)
66
87
  return type === 'agent' ? 'unbound_agent' : 'external_human';
67
- if (owner === ownerRef)
68
- return 'internal';
88
+ if (owner === ownerRef) {
89
+ const verified = !requiresOwnershipVerification(entry) || isOwnershipVerified(entry);
90
+ return verified ? 'internal' : 'unverified';
91
+ }
69
92
  return type === 'agent' ? 'external_agent' : 'external_human';
70
93
  }
71
- /** 条目是否属于本 Owner(内部联系人)。没有 `owner_aid` 的条目不算内部。 */
94
+ /**
95
+ * 条目是否属于本 Owner(内部联系人)。
96
+ *
97
+ * agent 类型必须同时满足 `owner_aid` 匹配与双边核验;只看 `owner_aid` 会让一条
98
+ * 自称归属、实际未核验的 Agent 拿到内部联系人的默认放行。人类与其他非消息类型
99
+ * 以 `owner_aid` 为准(见 `requiresOwnershipVerification`)。
100
+ */
72
101
  export function isInternalEntry(entry, ownerRef) {
73
- return entryOwnerAid(entry) === ownerRef;
102
+ if (entryOwnerAid(entry) !== ownerRef)
103
+ return false;
104
+ return !requiresOwnershipVerification(entry) || isOwnershipVerified(entry);
74
105
  }
@@ -8,7 +8,8 @@
8
8
  * 中文没有词边界,一律按子串匹配,不做分词。查询串按空白切成 token,
9
9
  * **所有 token 都要命中**(AND),总分是每个 token 最佳命中字段的分数之和。
10
10
  */
11
- import { isInternalEntry, ownerRefAid } from './owner-directory-scope.js';
11
+ import { isInternalEntry, isOwnershipVerified, ownerRefAid, } from './owner-directory-scope.js';
12
+ import { normalizeDirectoryText, stripTrailingParenthetical, } from './owner-directory-text.js';
12
13
  const DEFAULT_LIMIT = 5;
13
14
  const MAX_LIMIT = 50;
14
15
  /** 各命中方式的权重。分数用于排序,不承诺对外稳定,调用方只看相对顺序。 */
@@ -23,10 +24,6 @@ const WEIGHT = {
23
24
  descriptionContains: 150,
24
25
  exactType: 100,
25
26
  };
26
- /** 这个人就是当前 agent 的个人助理。 */
27
- export function isPersonalAssistantSnapshot(selfAid, snapshot) {
28
- return !!snapshot?.personalAssistant?.aid && snapshot.personalAssistant.aid === selfAid;
29
- }
30
27
  export function searchDirectory(snapshot, ownerAid, remarks, options) {
31
28
  if (!snapshot)
32
29
  return [];
@@ -38,6 +35,7 @@ export function searchDirectory(snapshot, ownerAid, remarks, options) {
38
35
  // 默认查全部:注入里的外部条目只有名字,模型要靠 find 才能拿到 AID。
39
36
  const scope = options.scope ?? 'all';
40
37
  const typeFilter = options.type?.trim().toLowerCase();
38
+ const ownerFilter = options.ownerAid?.trim().toLowerCase();
41
39
  const hits = [];
42
40
  for (const entry of snapshot.entries) {
43
41
  const internal = isInternalEntry(entry, ownerRef);
@@ -47,15 +45,21 @@ export function searchDirectory(snapshot, ownerAid, remarks, options) {
47
45
  continue;
48
46
  if (typeFilter && (entry.type ?? '').toLowerCase() !== typeFilter)
49
47
  continue;
50
- // 本地备注是"这个 agent 自己怎么看这个人",搜索优先用它。
48
+ if (ownerFilter) {
49
+ const entryOwner = (entry.ownerAid ?? '').trim().toLowerCase();
50
+ if (ownerFilter === 'unbound' ? entryOwner !== '' : entryOwner !== ownerFilter)
51
+ continue;
52
+ }
53
+ // 三段叫法**同时参与搜索**:名录名、Owner 写的备注名、自己记的称呼。
54
+ // 谁都不顶替谁——Owner 口语里任何一个叫法落到这里都必须能搜到,否则下一次
55
+ // 他换一种叫法提到同一个人,就又得重新翻一遍。
51
56
  const remark = remarks?.get(entry.aid);
52
- const effectiveRemark = remark?.remark ?? entry.remark;
53
- const effectiveDescription = remark?.body ?? entry.description;
57
+ const localNote = remark?.body;
54
58
  let score = 0;
55
59
  const matched = new Set();
56
60
  let allTokensHit = true;
57
61
  for (const token of tokens) {
58
- const best = scoreToken(token, entry, effectiveRemark, effectiveDescription);
62
+ const best = scoreToken(token, entry, remark, localNote);
59
63
  if (best.score === 0) {
60
64
  allTokensHit = false;
61
65
  break;
@@ -71,8 +75,13 @@ export function searchDirectory(snapshot, ownerAid, remarks, options) {
71
75
  ...(entry.type !== undefined ? { type: entry.type } : {}),
72
76
  ...(entry.exttype !== undefined ? { exttype: entry.exttype } : {}),
73
77
  ...(entry.baseagent !== undefined ? { baseagent: entry.baseagent } : {}),
74
- ...(effectiveRemark !== undefined ? { remark: effectiveRemark } : {}),
75
- ...(effectiveDescription !== undefined ? { description: effectiveDescription } : {}),
78
+ ...(remark?.remark !== undefined
79
+ ? { remark: remark.remark }
80
+ : entry.remark !== undefined ? { remark: entry.remark } : {}),
81
+ ...(remark?.aliases !== undefined ? { aliases: remark.aliases } : {}),
82
+ ...(entry.remark !== undefined ? { ownerRemark: entry.remark } : {}),
83
+ ...(entry.description !== undefined ? { description: entry.description } : {}),
84
+ ...(localNote !== undefined ? { localRemark: localNote } : {}),
76
85
  internal,
77
86
  matched: [...matched],
78
87
  score,
@@ -85,21 +94,32 @@ export function searchDirectory(snapshot, ownerAid, remarks, options) {
85
94
  || a.aid.localeCompare(b.aid));
86
95
  return hits.slice(0, limit);
87
96
  }
88
- function scoreToken(token, entry, remark, description) {
89
- const aid = entry.aid.toLowerCase();
90
- const name = entry.name.toLowerCase();
91
- const exttype = (entry.exttype ?? '').toLowerCase();
92
- const type = (entry.type ?? '').toLowerCase();
93
- const baseagent = (entry.baseagent ?? '').toLowerCase();
97
+ function scoreToken(token, entry, remark, localNote) {
98
+ const aid = normalizeDirectoryText(entry.aid);
99
+ const rawName = normalizeDirectoryText(entry.name);
100
+ // 名字比较忽略结尾括号称呼:`李文江(研发)` 与 `李文江` 是同一个人。
101
+ const name = normalizeDirectoryText(stripTrailingParenthetical(rawName));
102
+ const exttype = normalizeDirectoryText(entry.exttype ?? '');
103
+ const type = normalizeDirectoryText(entry.type ?? '');
104
+ const baseagent = normalizeDirectoryText(entry.baseagent ?? '');
94
105
  if (aid === token)
95
106
  return { score: WEIGHT.exactAid, field: 'aid' };
96
- if (name === token)
107
+ if (name === token || rawName === token)
97
108
  return { score: WEIGHT.exactName, field: 'name' };
98
109
  if (aid.startsWith(token) || name.startsWith(token))
99
110
  return { score: WEIGHT.prefix, field: 'prefix' };
100
- if (remark && remark.toLowerCase() === token)
111
+ // 任何叫法精确命中都算:名录名、Owner 写的备注名、自己记的每一个称呼。
112
+ const localAliases = (remark?.aliases ?? (remark?.remark ? [remark.remark] : []))
113
+ .map(alias => normalizeDirectoryText(alias));
114
+ if (localAliases.some(alias => alias === token || normalizeDirectoryText(stripTrailingParenthetical(alias)) === token)) {
101
115
  return { score: WEIGHT.exactRemark, field: 'remark' };
102
- // AID 的域段先于普通包含判定:`find agentid.cn` 是"列出这个域",不是"名字里有这段字"。
116
+ }
117
+ const ownerRemark = normalizeDirectoryText(entry.remark ?? '');
118
+ if (ownerRemark && (ownerRemark === token || normalizeDirectoryText(stripTrailingParenthetical(ownerRemark)) === token)) {
119
+ return { score: WEIGHT.exactRemark, field: 'ownerRemark' };
120
+ }
121
+ // AID 的域段先于普通包含判定:`list --filter agentid.cn` 是"列出这个域",
122
+ // 不是"名字里有这段字"。
103
123
  const domain = aid.slice(aid.indexOf('.') + 1);
104
124
  if (domain.includes(token))
105
125
  return { score: WEIGHT.domainContains, field: 'domain' };
@@ -107,39 +127,104 @@ function scoreToken(token, entry, remark, description) {
107
127
  return { score: WEIGHT.contains, field: 'name' };
108
128
  if (exttype === token || baseagent === token)
109
129
  return { score: WEIGHT.exactExttype, field: 'exttype' };
110
- if (description && description.toLowerCase().includes(token)) {
130
+ if (entry.description && normalizeDirectoryText(entry.description).includes(token)) {
111
131
  return { score: WEIGHT.descriptionContains, field: 'description' };
112
132
  }
113
- if (remark && remark.toLowerCase().includes(token)) {
133
+ // 本地备注正文与远端描述并列参与:它是 PA 自己记的"什么事该找他",是找人的主要线索之一。
134
+ if (localNote && normalizeDirectoryText(localNote).includes(token)) {
135
+ return { score: WEIGHT.descriptionContains, field: 'localNote' };
136
+ }
137
+ if (localAliases.some(alias => alias.includes(token))) {
114
138
  return { score: WEIGHT.descriptionContains, field: 'remark' };
115
139
  }
140
+ if (ownerRemark.includes(token)) {
141
+ return { score: WEIGHT.descriptionContains, field: 'ownerRemark' };
142
+ }
116
143
  if (type === token)
117
144
  return { score: WEIGHT.exactType, field: 'type' };
118
145
  return { score: 0, field: '' };
119
146
  }
120
- /** 单个条目的完整记录,用于 `show`。描述与备注不截断。 */
121
- export function describeEntry(entry, ownerRef, remark, contactable) {
147
+ /**
148
+ * `list` 的过滤:组间 AND、组内 OR。
149
+ *
150
+ * 与 `ec skill list --filter` 同一套语义(逗号分隔为 OR,多个 `--filter` 之间
151
+ * 为 AND),区别只是匹配字段:技能匹配名称+描述,名录还匹配 AID、备注、exttype。
152
+ * 组为空表示不过滤。
153
+ */
154
+ export function filterDirectory(snapshot, ownerAid, remarks, options = {}) {
155
+ if (!snapshot)
156
+ return [];
157
+ const ownerRef = ownerRefAid(snapshot, ownerAid);
158
+ const groups = (options.filters ?? [])
159
+ .map(group => group.map(keyword => normalizeDirectoryText(keyword)).filter(Boolean))
160
+ .filter(group => group.length > 0);
161
+ const scope = options.scope ?? 'all';
162
+ const typeFilter = normalizeDirectoryText(options.type ?? '');
163
+ const ownerFilter = normalizeDirectoryText(options.ownerAid ?? '');
164
+ return snapshot.entries
165
+ .filter(entry => {
166
+ const internal = isInternalEntry(entry, ownerRef);
167
+ if (scope === 'internal' && !internal)
168
+ return false;
169
+ if (scope === 'external' && internal)
170
+ return false;
171
+ if (typeFilter && normalizeDirectoryText(entry.type ?? '') !== typeFilter)
172
+ return false;
173
+ if (ownerFilter) {
174
+ const entryOwner = normalizeDirectoryText(entry.ownerAid ?? '');
175
+ if (ownerFilter === 'unbound' ? entryOwner !== '' : entryOwner !== ownerFilter)
176
+ return false;
177
+ }
178
+ if (groups.length === 0)
179
+ return true;
180
+ const remark = remarks?.get(entry.aid);
181
+ return groups.every(group => group.some(keyword => scoreToken(keyword, entry, remark, remark?.body).score > 0));
182
+ })
183
+ .sort((a, b) => Number(isInternalEntry(b, ownerRef)) - Number(isInternalEntry(a, ownerRef))
184
+ || normalizeDirectoryText(a.name).localeCompare(normalizeDirectoryText(b.name))
185
+ || a.aid.localeCompare(b.aid));
186
+ }
187
+ /**
188
+ * 单个条目的完整记录,用于 `show`。描述与备注不截断。
189
+ *
190
+ * `contactable` 传的是"这条目能不能联系"的判定函数,不是统一布尔:内部与外部
191
+ * 受不同开关约束,白名单与黑名单又各自优先,算一次再套给所有条目必然错。
192
+ * 传布尔时按原样使用(老调用方与单测)。
193
+ */
194
+ export function describeEntry(entry, ownerRef, remark, contactable,
195
+ /**
196
+ * `includeLocalRemark` 只在详情(`info`)里打开。`list` 是检索结果,
197
+ * 本地备注正文可能很长,按口径不展示——要看正文用 `ec directory info <AID>`。
198
+ */
199
+ options = {}) {
200
+ const internal = isInternalEntry(entry, ownerRef);
201
+ const contactableValue = typeof contactable === 'function' ? contactable(entry) : contactable;
122
202
  return {
123
203
  aid: entry.aid,
124
204
  name: entry.name,
125
205
  type: entry.type ?? null,
126
206
  exttype: entry.exttype ?? null,
127
207
  baseagent: entry.baseagent ?? null,
128
- remark: remark?.remark ?? entry.remark ?? null,
129
- description: remark?.body ?? entry.description ?? null,
208
+ // Owner 绑定关系与核验状态要单独给出:list 的用途就是让调用方看清
209
+ // "这条到底归谁、这个归属是不是经过双边确认的"。
210
+ ownerAid: entry.ownerAid ?? null,
130
211
  ownershipStatus: entry.ownership_status ?? null,
212
+ ownershipVerified: isOwnershipVerified(entry),
213
+ ownershipCheckedAt: entry.ownership_checked_at_ms ?? null,
214
+ // 远端字段与本地备注并列返回,不互相覆盖:调用方要判断"对方本来是什么样"
215
+ // 和"我记了什么"是两件事。要在渲染里二选一由调用方决定。
216
+ remark: remark?.remark ?? entry.remark ?? null,
217
+ aliases: remark?.aliases ?? null,
218
+ description: entry.description ?? null,
219
+ ...(options.includeLocalRemark !== false ? { localRemark: remark?.body ?? null } : {}),
131
220
  agentMdSignedAt: entry.agent_md_signed_at ?? null,
132
- internal: isInternalEntry(entry, ownerRef),
133
- contactable,
221
+ internal,
222
+ contactable: contactableValue,
134
223
  remarkSource: remark ? 'local' : 'remote',
135
224
  };
136
225
  }
137
226
  function tokenize(query) {
138
- return String(query ?? '')
139
- .toLowerCase()
140
- .split(/\s+/)
141
- .map(token => token.trim())
142
- .filter(Boolean);
227
+ return normalizeDirectoryText(query).split(/\s+/).filter(Boolean);
143
228
  }
144
229
  function clampLimit(limit) {
145
230
  if (!Number.isSafeInteger(limit) || limit <= 0)
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { atomicWriteJson } from '../utils/atomic-write.js';
4
4
  import { logger } from '../utils/logger.js';
5
+ import { changedEntryFields } from './owner-directory-cache.js';
5
6
  import { OWNER_DIRECTORY_SCOPES } from './owner-directory-scope.js';
6
7
  // ── content_digest helpers ────────────────────────────────────────────────────
7
8
  const CONTENT_DIGEST_RE = /^[a-f0-9]{64}$/;
@@ -45,10 +46,9 @@ function archiveFileName(scope, now) {
45
46
  function changesDir(directory) {
46
47
  return path.join(directory, 'changes');
47
48
  }
48
- function changesFile(directory, now) {
49
- const y = now.getUTCFullYear();
50
- const m = String(now.getUTCMonth() + 1).padStart(2, '0');
51
- return path.join(changesDir(directory), `${y}-${m}.jsonl`);
49
+ function changesFile(directory, year, month) {
50
+ const m = String(month).padStart(2, '0');
51
+ return path.join(changesDir(directory), `${year}-${m}.jsonl`);
52
52
  }
53
53
  function changesIndexFile(directory) {
54
54
  return path.join(changesDir(directory), 'index.json');
@@ -84,7 +84,7 @@ function entryChangeKind(entry) {
84
84
  /**
85
85
  * 比较新旧两份快照,生成变更行列表。
86
86
  * 无旧快照时写一行 baseline(不展开差集)。
87
- * owner / personal_assistant 字段的 agent_md_signed_at 变化也纳入比对。
87
+ * owner / personal_assistant 身份块的变化单独产出 `identity_changed` 行。
88
88
  */
89
89
  export function diffSnapshots(scope, next, prev, nextMeta, prevMeta) {
90
90
  const now = next.fetchedAt;
@@ -109,8 +109,13 @@ export function diffSnapshots(scope, next, prev, nextMeta, prevMeta) {
109
109
  lines.push({ at: now, scope, type: 'host_added', aid, contentDigest, prevContentDigest: prevDigest, from: null, to: entry });
110
110
  }
111
111
  }
112
- else if (entryChanged(old, entry)) {
113
- lines.push({ at: now, scope, type: 'entry_changed', aid, contentDigest, prevContentDigest: prevDigest, from: old, to: entry });
112
+ else {
113
+ // 运行期自检:只有真正存在差异字段才记 `entry_changed`。
114
+ // 上游若换一种序列化(缺失 / "" / null 互换),这里不会再刷出噪音行。
115
+ const fields = changedEntryFields(old, entry);
116
+ if (fields.length === 0)
117
+ continue;
118
+ lines.push({ at: now, scope, type: 'entry_changed', aid, contentDigest, prevContentDigest: prevDigest, from: old, to: entry, fields });
114
119
  const wasHost = isHost(old), nowHost = isHost(entry);
115
120
  if (!wasHost && nowHost)
116
121
  lines.push({ at: now, scope, type: 'host_added', aid, contentDigest, prevContentDigest: prevDigest, from: old, to: entry });
@@ -127,21 +132,40 @@ export function diffSnapshots(scope, next, prev, nextMeta, prevMeta) {
127
132
  }
128
133
  }
129
134
  }
135
+ // 身份块(owner / personal_assistant)不属于 entries,但它的 agent_md_signed_at 决定
136
+ // agent.md 是否需要重拉。不单独记行的话,"换了 owner / personal assistant"这件事
137
+ // 在变更日志里完全不可见。
138
+ for (const slot of ['owner', 'personalAssistant']) {
139
+ const before = prevMeta?.[slot], after = nextMeta?.[slot];
140
+ if (!identityChanged(before, after))
141
+ continue;
142
+ lines.push({
143
+ at: now, scope, type: 'identity_changed', identity: slot,
144
+ aid: after?.aid ?? before?.aid ?? '',
145
+ contentDigest, prevContentDigest: prevDigest,
146
+ from: before ?? null, to: after ?? null,
147
+ });
148
+ }
130
149
  return lines;
131
150
  }
132
151
  /**
133
- * 条目内容是否变化。比较全部内容字段;`ownership_checked_at_ms` 是探测时间而不是
134
- * 内容,单独变化不记变更行。
152
+ * 身份块(`owner` / `personal_assistant`)是否变化。
153
+ *
154
+ * 身份块的 `agent_md_signed_at` 决定 agent.md 是否需要重新拉取,改了就值得记一行,
155
+ * 否则"换了 owner 或 personal assistant"这件事在变更日志里完全不可见。
156
+ * 两侧都缺失时不算变更(老快照没有身份块是常态,不是事件)。
135
157
  */
136
- function entryChanged(a, b) {
137
- return a.name !== b.name
138
- || a.remark !== b.remark
139
- || a.description !== b.description
140
- || a.type !== b.type
141
- || a.exttype !== b.exttype
142
- || a.baseagent !== b.baseagent
143
- || a.ownership_status !== b.ownership_status
144
- || a.agent_md_signed_at !== b.agent_md_signed_at;
158
+ function text(value) {
159
+ return value ?? '';
160
+ }
161
+ function identityChanged(a, b) {
162
+ if (!a && !b)
163
+ return false;
164
+ if (!a || !b)
165
+ return true;
166
+ return a.aid !== b.aid
167
+ || text(a.name) !== text(b.name)
168
+ || (a.agent_md_signed_at ?? 0) !== (b.agent_md_signed_at ?? 0);
145
169
  }
146
170
  /**
147
171
  * 收集需要刷新 agent.md 的 AID:
@@ -162,6 +186,12 @@ export function collectAgentMdRefreshAids(lines, nextMeta, prevMeta, nextSnapsho
162
186
  continue;
163
187
  if (!line.aid)
164
188
  continue;
189
+ if (line.type === 'identity_changed') {
190
+ // 身份块的刷新对象不是 name 字段,而是 aid 本身。
191
+ if (line.to?.aid)
192
+ aids.add(line.to.aid);
193
+ continue;
194
+ }
165
195
  const isAdd = line.type === 'agent_added' || line.type === 'contact_added';
166
196
  const signedAtChanged = line.from?.agent_md_signed_at !== line.to?.agent_md_signed_at;
167
197
  if (isAdd || signedAtChanged)
@@ -185,23 +215,81 @@ export function collectAgentMdRefreshAids(lines, nextMeta, prevMeta, nextSnapsho
185
215
  }
186
216
  /**
187
217
  * 将变更行追加到 changes/<YYYY-MM>.jsonl,并更新 index.json。
188
- * 无变更时跳过。失败只记日志,不影响调用方。
218
+ *
219
+ * 无变更时跳过。**失败会抛出**:调用方必须在覆盖本地快照之前调用它,
220
+ * 这样写日志失败时整次同步失败、下次重试,而不是"快照前进了、日志缺一块"。
221
+ * 吞掉异常会让这条链永久缺环,事后无法从日志补回。
189
222
  */
190
223
  export function appendChanges(directory, lines, now = new Date()) {
191
224
  if (lines.length === 0)
192
225
  return;
226
+ const cDir = changesDir(directory);
227
+ fs.mkdirSync(cDir, { recursive: true, mode: 0o700 });
228
+ const jsonl = lines.map(l => JSON.stringify(l)).join('\n') + '\n';
229
+ // 月份由变更行自己的 `at` 决定,不由写盘那一刻的墙钟决定。
230
+ // 服务端时间与本机时间不一致、或月末跨零点时,否则会出现"写着 10 月的记录躺在
231
+ // 11 月文件里"这种按文件找、按时间戳找都对不上的孤儿行。
232
+ const { year, month } = changesMonth(lines);
233
+ const target = changesFile(directory, year, month);
234
+ if (alreadyAppended(target, lines)) {
235
+ logger.debug(`[OwnerDirectoryStore] ${path.basename(target)} already ends with this batch; skipping duplicate append`);
236
+ return;
237
+ }
238
+ fs.appendFileSync(target, jsonl, 'utf-8');
239
+ updateChangesIndex(directory, lines, year, month);
240
+ }
241
+ /**
242
+ * 这一批是否已经写过了。
243
+ *
244
+ * 调用方先写日志、后覆盖快照,所以"日志写成功但快照没写成"会触发重试;
245
+ * 重试时 diff 结果与上一批完全相同,这里比对末尾那行的 digest 对就能识别,
246
+ * 避免同一批变更落两份。
247
+ *
248
+ * 判据:最后一行与这一批的首行共享 `contentDigest` + `prevContentDigest`。
249
+ * 一整批共用同一个 digest 对(见 diffSnapshots),所以只比首行就够。
250
+ * 文件里最后一行解析失败时按"没写过"处理——宁可重复,不能漏记。
251
+ */
252
+ function alreadyAppended(file, lines) {
253
+ if (lines.length === 0)
254
+ return false;
255
+ let tail;
256
+ try {
257
+ const size = fs.statSync(file).size;
258
+ if (size === 0)
259
+ return false;
260
+ // 只需最后一行:连同换行符读尾部 8KB,足够覆盖单行(条目字段有截断上限)。
261
+ const length = Math.min(size, 8192);
262
+ const fd = fs.openSync(file, 'r');
263
+ try {
264
+ const buffer = Buffer.alloc(length);
265
+ fs.readSync(fd, buffer, 0, length, size - length);
266
+ tail = buffer.toString('utf-8');
267
+ }
268
+ finally {
269
+ fs.closeSync(fd);
270
+ }
271
+ }
272
+ catch {
273
+ return false;
274
+ }
275
+ const lastLine = tail.split('\n').filter(line => line.trim()).pop();
276
+ if (!lastLine)
277
+ return false;
193
278
  try {
194
- const cDir = changesDir(directory);
195
- fs.mkdirSync(cDir, { recursive: true, mode: 0o700 });
196
- const jsonl = lines.map(l => JSON.stringify(l)).join('\n') + '\n';
197
- fs.appendFileSync(changesFile(directory, now), jsonl, 'utf-8');
198
- updateChangesIndex(directory, lines, now);
279
+ const last = JSON.parse(lastLine);
280
+ return last.contentDigest === lines[0].contentDigest
281
+ && last.prevContentDigest === lines[0].prevContentDigest;
199
282
  }
200
- catch (error) {
201
- logger.warn(`[OwnerDirectoryStore] appendChanges failed: ${error instanceof Error ? error.message : String(error)}`);
283
+ catch {
284
+ return false;
202
285
  }
203
286
  }
204
- function updateChangesIndex(directory, lines, now) {
287
+ function changesMonth(lines) {
288
+ // `at` 是该行所属快照的 fetchedAt;同一批共用一个 `at`,取最早的即可。
289
+ const stamp = new Date(lines[0].at);
290
+ return { year: stamp.getUTCFullYear(), month: stamp.getUTCMonth() + 1 };
291
+ }
292
+ function updateChangesIndex(directory, lines, year, month) {
205
293
  const indexPath = changesIndexFile(directory);
206
294
  let index = [];
207
295
  try {
@@ -210,8 +298,7 @@ function updateChangesIndex(directory, lines, now) {
210
298
  index = raw;
211
299
  }
212
300
  catch { /* fresh */ }
213
- const y = now.getUTCFullYear(), m = now.getUTCMonth() + 1;
214
- const existing = index.find(e => e.year === y && e.month === m);
301
+ const existing = index.find(e => e.year === year && e.month === month);
215
302
  const ats = lines.map(l => l.at);
216
303
  const minAt = Math.min(...ats), maxAt = Math.max(...ats);
217
304
  if (existing) {
@@ -220,7 +307,7 @@ function updateChangesIndex(directory, lines, now) {
220
307
  existing.lastAt = Math.max(existing.lastAt, maxAt);
221
308
  }
222
309
  else {
223
- index.push({ year: y, month: m, count: lines.length, firstAt: minAt, lastAt: maxAt });
310
+ index.push({ year, month, count: lines.length, firstAt: minAt, lastAt: maxAt });
224
311
  index.sort((a, b) => a.year !== b.year ? a.year - b.year : a.month - b.month);
225
312
  }
226
313
  atomicWriteJson(indexPath, index);
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 名录里的名字/关键词归一。
3
+ *
4
+ * `list`、`info`(旧 `find` / `show`)必须用同一套比较规则,否则同一个名字在
5
+ * 不同命令里的命中结果会不一致:
6
+ *
7
+ * - NFKC:全角字母/数字/空格 → 半角;
8
+ * - 去掉零宽字符:从聊天窗口复制名字时经常带进来;
9
+ * - 空白折叠为单个空格;
10
+ * - 大小写不敏感(AID 和英文名都不该区分大小写)。
11
+ */
12
+ /** 归一后的比较基串。 */
13
+ export function normalizeDirectoryText(value) {
14
+ return String(value ?? '')
15
+ .normalize('NFKC')
16
+ .replace(/[\u200B-\u200D\uFEFF]/g, '')
17
+ .replace(/\s+/g, ' ')
18
+ .trim()
19
+ .toLowerCase();
20
+ }
21
+ /** 去掉名字结尾括号里的称呼:`李文江(研发)` → `李文江`。 */
22
+ export function stripTrailingParenthetical(value) {
23
+ return value.replace(/\s*[((][^()()]*[))]\s*$/, '').trim();
24
+ }
25
+ /**
26
+ * 两个名字是否算同一个人:
27
+ * - 归一后完全相等;
28
+ * - 忽略结尾括号里的称呼;
29
+ * - 忽略名字内部的空格。
30
+ */
31
+ export function sameDirectoryName(candidate, wanted) {
32
+ const right = normalizeDirectoryText(wanted);
33
+ if (!right)
34
+ return false;
35
+ const left = normalizeDirectoryText(candidate);
36
+ if (left === right)
37
+ return true;
38
+ const leftBase = normalizeDirectoryText(stripTrailingParenthetical(left));
39
+ const rightBase = normalizeDirectoryText(stripTrailingParenthetical(right));
40
+ return leftBase === rightBase
41
+ || leftBase.replace(/ /g, '') === rightBase.replace(/ /g, '');
42
+ }
43
+ /** 编辑距离,用于“可能打错字/叫法接近”的提示。 */
44
+ export function editDistance(left, right) {
45
+ if (left === right)
46
+ return 0;
47
+ if (!left.length)
48
+ return right.length;
49
+ if (!right.length)
50
+ return left.length;
51
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
52
+ for (let row = 1; row <= left.length; row++) {
53
+ const current = [row];
54
+ for (let column = 1; column <= right.length; column++) {
55
+ current[column] = Math.min(previous[column] + 1, current[column - 1] + 1, previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1));
56
+ }
57
+ previous = current;
58
+ }
59
+ return previous[right.length];
60
+ }