evolcore 0.0.41 → 0.0.42-test.0

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 (190) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/bin/codex-managed-hook.mjs +9 -5
  3. package/dist/agents/baseagent.js +156 -16
  4. package/dist/agents/claude-runner.js +10 -3
  5. package/dist/agents/codex/catalog.js +8 -4
  6. package/dist/agents/codex-runner.js +236 -59
  7. package/dist/agents/ecagent-runner.js +82 -13
  8. package/dist/aun/aid/agentmd.js +106 -27
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +65 -13
  11. package/dist/aun/aid/identity.js +70 -4
  12. package/dist/aun/aid/index.js +2 -2
  13. package/dist/aun/service-proxy.js +25 -1
  14. package/dist/channels/aun.js +242 -209
  15. package/dist/channels/dingtalk.js +1 -1
  16. package/dist/channels/feishu.js +1 -1
  17. package/dist/channels/qqbot.js +1 -1
  18. package/dist/channels/wechat.js +1 -1
  19. package/dist/channels/wecom.js +1 -1
  20. package/dist/cli/agent-command.js +183 -3
  21. package/dist/cli/agent-create.js +92 -86
  22. package/dist/cli/agent.js +136 -1
  23. package/dist/cli/aun-commands.js +137 -35
  24. package/dist/cli/bench.js +8 -2
  25. package/dist/cli/command-log.js +1 -1
  26. package/dist/cli/daemon-commands.js +235 -51
  27. package/dist/cli/debug-mode.js +1 -1
  28. package/dist/cli/directory.js +170 -0
  29. package/dist/cli/index.js +40 -30
  30. package/dist/cli/init-channel.js +4 -4
  31. package/dist/cli/init.js +47 -32
  32. package/dist/cli/managed-command-guard.js +4 -1
  33. package/dist/cli/model.js +27 -18
  34. package/dist/cli/pa-workspace-command.js +191 -0
  35. package/dist/cli/{contact.js → peer.js} +19 -25
  36. package/dist/cli/restart-monitor.js +11 -4
  37. package/dist/cli/thread-command.js +47 -18
  38. package/dist/cli/version.js +18 -18
  39. package/dist/config/access-policy.js +29 -12
  40. package/dist/config/boot-log.js +65 -10
  41. package/dist/config/builtin-roles.js +2 -4
  42. package/dist/config/config-field-policy.js +3 -0
  43. package/dist/config/config-manager.js +28 -20
  44. package/dist/config/{contact-bind-code.js → peer-bind-code.js} +6 -6
  45. package/dist/config/{contact-book-store.js → peer-book-store.js} +75 -75
  46. package/dist/config/{contact-book-v2-startup.js → peer-book-v2-startup.js} +2 -2
  47. package/dist/config/{contact-book.js → peer-book.js} +47 -47
  48. package/dist/config/peer-operation-service.js +132 -0
  49. package/dist/config/{contact-request-service.js → peer-request-service.js} +90 -90
  50. package/dist/config/peer-role-resolver.js +3 -3
  51. package/dist/config/providers-config.js +17 -8
  52. package/dist/config/providers.js +1 -1
  53. package/dist/config/schema-migration.js +336 -39
  54. package/dist/core/agent-application-service.js +8 -2
  55. package/dist/core/agent-create-status.js +4 -5
  56. package/dist/core/agent-ipc-registration.js +5 -4
  57. package/dist/core/agent-runtime.js +30 -17
  58. package/dist/core/auth/operation-authorizer.js +0 -24
  59. package/dist/core/auth/operation-catalog.js +4 -20
  60. package/dist/core/baseagent-loader.js +27 -3
  61. package/dist/core/bootstrap-service.js +5 -22
  62. package/dist/core/capability/capability-manager.js +52 -35
  63. package/dist/core/channel-loader.js +43 -2
  64. package/dist/core/channel-runtime.js +2 -2
  65. package/dist/core/command/agent-control.js +54 -18
  66. package/dist/core/command/command-handler.js +92 -72
  67. package/dist/core/command/connect-menu.js +35 -42
  68. package/dist/core/command/daemon-diagnostics.js +41 -5
  69. package/dist/core/command/data-root-error.js +10 -0
  70. package/dist/core/command/data-root-resolver.js +53 -13
  71. package/dist/core/command/menu-catalog.js +1 -0
  72. package/dist/core/command/menu-handler.js +163 -65
  73. package/dist/core/command/menu-protocol.js +52 -0
  74. package/dist/core/command/pa-workspace-calendar.js +223 -0
  75. package/dist/core/command/pa-workspace-store.js +459 -0
  76. package/dist/core/command/role-menu.js +2 -2
  77. package/dist/core/command/slash-gate.js +1 -1
  78. package/dist/core/command/slash-handler.js +57 -41
  79. package/dist/core/daemon-lifecycle.js +90 -31
  80. package/dist/core/evolagent.js +6 -10
  81. package/dist/core/handoff/runtime.js +11 -4
  82. package/dist/core/host-snapshot.js +208 -0
  83. package/dist/core/initialization/service.js +152 -20
  84. package/dist/core/ipc-registration.js +33 -4
  85. package/dist/core/memory/batch-meta.js +27 -0
  86. package/dist/core/memory/consolidation-ops-records.js +44 -1
  87. package/dist/core/memory/consolidation.js +169 -27
  88. package/dist/core/message/aun-ipc-sender.js +2 -8
  89. package/dist/core/message/im-renderer.js +56 -3
  90. package/dist/core/message/message-admission.js +121 -124
  91. package/dist/core/message/message-bridge.js +38 -54
  92. package/dist/core/message/message-queue.js +7 -0
  93. package/dist/core/message/outbound.js +34 -9
  94. package/dist/core/message/response-engine.js +154 -73
  95. package/dist/core/model/catalog-service.js +1 -1
  96. package/dist/core/model/config-scope.js +2 -2
  97. package/dist/core/model/model-catalog.js +5 -4
  98. package/dist/core/model/model-diagnostics.js +6 -5
  99. package/dist/core/model/model-fallback.js +3 -6
  100. package/dist/core/model/model-permission.js +1 -1
  101. package/dist/core/ownership/owner-resolver.js +9 -9
  102. package/dist/core/permission/approval-gateway.js +1 -1
  103. package/dist/core/permission/ec-command-parser.js +2 -2
  104. package/dist/core/permission/tool-canonical.js +96 -46
  105. package/dist/core/permission/tool-error-code.js +41 -0
  106. package/dist/core/permission/tool-policy.js +71 -47
  107. package/dist/core/role/runtime-policy.js +1 -1
  108. package/dist/core/session/session-idle-monitor.js +10 -0
  109. package/dist/core/session/session-manager.js +2 -4
  110. package/dist/core/session/session-title.js +36 -8
  111. package/dist/core/system-session/memory.js +2 -7
  112. package/dist/core/thread/command-parser.js +6 -2
  113. package/dist/core/thread/ipc-operation.js +51 -36
  114. package/dist/core/thread/thread-operation.js +29 -61
  115. package/dist/core/thread/thread-service.js +57 -13
  116. package/dist/directory/canonical-digest.js +54 -0
  117. package/dist/directory/owner-directory-admission.js +114 -43
  118. package/dist/directory/owner-directory-agentmd-sync.js +89 -0
  119. package/dist/directory/owner-directory-cache.js +847 -459
  120. package/dist/directory/owner-directory-markdown.js +272 -0
  121. package/dist/directory/owner-directory-query-operation.js +195 -0
  122. package/dist/directory/owner-directory-remark-operation.js +147 -0
  123. package/dist/directory/owner-directory-remarks.js +145 -0
  124. package/dist/directory/owner-directory-scope.js +55 -0
  125. package/dist/directory/owner-directory-search.js +148 -0
  126. package/dist/directory/owner-directory-store.js +227 -0
  127. package/dist/eck/kit-renderer.js +1 -0
  128. package/dist/ecweb/basic-settings-service.js +4 -1
  129. package/dist/ecweb/message-context-service.js +13 -9
  130. package/dist/index.js +195 -37
  131. package/dist/ipc.js +86 -22
  132. package/dist/paths.js +11 -8
  133. package/dist/product.js +2 -0
  134. package/dist/proxy/manager.js +13 -2
  135. package/dist/proxy/service-supervisor.js +8 -1
  136. package/dist/trigger/history.js +23 -0
  137. package/dist/trigger/scheduler.js +3 -0
  138. package/dist/utils/atomic-write.js +21 -0
  139. package/dist/utils/cross-platform.js +35 -0
  140. package/dist/utils/ecweb-supervisor.js +42 -0
  141. package/dist/utils/error-utils.js +2 -1
  142. package/dist/utils/evolcore-version.js +19 -0
  143. package/dist/utils/host-info.js +242 -5
  144. package/dist/utils/instance-registry.js +28 -6
  145. package/dist/utils/logger.js +59 -14
  146. package/dist/utils/machine-info.js +46 -0
  147. package/dist/utils/process-introspect.js +166 -2
  148. package/dist/utils/startup-trace.js +245 -0
  149. package/ecagent/dist/agent-loop.js +27 -13
  150. package/ecagent/dist/harness/agent-harness.js +3 -3
  151. package/ecagent/dist/harness/types.d.ts +1 -0
  152. package/ecagent/dist/types.d.ts +1 -0
  153. package/kits/docs/INDEX.md +1 -1
  154. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +72 -0
  155. package/kits/docs/evolcore/INDEX.md +3 -2
  156. package/kits/docs/evolcore/agent-create.md +17 -27
  157. package/kits/docs/evolcore/agent.md +4 -1
  158. package/kits/docs/evolcore/aid.md +3 -1
  159. package/kits/docs/evolcore/config.md +16 -5
  160. package/kits/docs/evolcore/ctl.md +9 -0
  161. package/kits/docs/evolcore/ec-capabilities.md +19 -0
  162. package/kits/docs/evolcore/memory-consolidation-batches.md +79 -5
  163. package/kits/docs/evolcore/menu-exec-schema-commands.md +2 -1
  164. package/kits/docs/evolcore/menu-protocol.md +1 -0
  165. package/kits/docs/evolcore/model.md +13 -4
  166. package/kits/docs/evolcore/msg.md +1 -1
  167. package/kits/docs/evolcore/pa-workspace.md +51 -0
  168. package/kits/docs/evolcore/peer.md +73 -0
  169. package/kits/docs/evolcore/thread-chain.md +4 -1
  170. package/kits/eck_manifest.json +21 -0
  171. package/kits/rules/06-channel.md +1 -1
  172. package/kits/schemas/_meta.json +12 -1
  173. package/kits/schemas/agent-config.schema.16.json +6 -0
  174. package/kits/schemas/agent-config.schema.17.json +897 -0
  175. package/kits/schemas/daemon.schema.9.json +8 -1
  176. package/kits/skills/ec-agent-create/SKILL.md +2 -2
  177. package/kits/skills/ec-identity/SKILL.md +45 -27
  178. package/kits/skills/ec-service-proxy/SKILL.md +7 -2
  179. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +4 -5
  180. package/kits/skills/thread-ops/SKILL.md +11 -11
  181. package/kits/templates/bootstrap-welcome.md +3 -15
  182. package/kits/templates/message-fragments/item.md +1 -1
  183. package/kits/templates/system-fragments/bootstrap.md +24 -23
  184. package/kits/templates/system-fragments/commands.md +12 -5
  185. package/kits/templates/system-fragments/thread.md +18 -3
  186. package/package.json +6 -4
  187. package/dist/config/contact-operation-service.js +0 -235
  188. package/dist/directory/owner-directory-authorization.js +0 -309
  189. package/kits/docs/evolcore/contact.md +0 -78
  190. /package/dist/config/{contact-alias.js → peer-alias.js} +0 -0
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 本地备注:`$AGENT_DIR/directory/remarks/<aid>.md`。
3
+ *
4
+ * 备注描述的是"这个 agent 自己怎么看这个人",和 Owner 侧发布的远端条目不是
5
+ * 一回事,所以存在本地、由个人助理通过 `ec directory remark` 命令维护,
6
+ * 引擎只读。渲染目录时按 AID 覆盖远端的 `description`(正文)和 `remark`
7
+ * (frontmatter)。
8
+ *
9
+ * 文件格式:
10
+ *
11
+ * ```markdown
12
+ * ---
13
+ * aid: zhang.agentid.cn
14
+ * remark: 合作方技术负责人
15
+ * updated_at: 1793253085
16
+ * ---
17
+ *
18
+ * 正文替代描述。
19
+ * ```
20
+ */
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { atomicRemove, atomicWrite } from '../utils/atomic-write.js';
24
+ import { logger } from '../utils/logger.js';
25
+ import { isValidAid } from '../aun/aid/validation.js';
26
+ export const OWNER_DIRECTORY_REMARKS_DIR = 'remarks';
27
+ const REMARK_MAX_BYTES = 64 * 1024;
28
+ function remarksDir(directory) {
29
+ return path.join(directory, OWNER_DIRECTORY_REMARKS_DIR);
30
+ }
31
+ export function remarkPath(directory, aid) {
32
+ return path.join(remarksDir(directory), `${aid}.md`);
33
+ }
34
+ /**
35
+ * 解析备注文件。frontmatter 只认 `aid` / `remark` / `updated_at` 三个键,
36
+ * 其余忽略。正文与 frontmatter 之间以一个空行分隔。
37
+ *
38
+ * 返回 undefined 表示这个文件不该生效(aid 不合法、与文件名不一致、格式坏)。
39
+ * 调用方据此回落到远端字段——宁可少注一条备注,也不能把备注挂到别人头上。
40
+ */
41
+ export function parseRemarkFile(text, expectedAid) {
42
+ const normalized = text.replace(/\r\n/g, '\n');
43
+ if (!normalized.startsWith('---\n'))
44
+ return undefined;
45
+ const end = normalized.indexOf('\n---', 3);
46
+ if (end < 0)
47
+ return undefined;
48
+ const header = normalized.slice(4, end);
49
+ const body = normalized.slice(end + 4).replace(/^\n+/, '').trim();
50
+ const fields = {};
51
+ for (const line of header.split('\n')) {
52
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/.exec(line.trim());
53
+ if (!match)
54
+ continue;
55
+ fields[match[1]] = match[2].trim();
56
+ }
57
+ const declaredAid = fields.aid;
58
+ if (!declaredAid || declaredAid !== expectedAid)
59
+ return undefined;
60
+ const remark = fields.remark || undefined;
61
+ const updatedAt = /^\d+$/.test(fields.updated_at ?? '') ? Number(fields.updated_at) : undefined;
62
+ return {
63
+ aid: declaredAid,
64
+ ...(remark !== undefined ? { remark } : {}),
65
+ ...(body ? { body } : {}),
66
+ ...(updatedAt !== undefined ? { updatedAt } : {}),
67
+ };
68
+ }
69
+ export function serializeRemarkFile(remark) {
70
+ const lines = ['---', `aid: ${remark.aid}`];
71
+ if (remark.remark)
72
+ lines.push(`remark: ${remark.remark.replace(/\n/g, ' ')}`);
73
+ lines.push(`updated_at: ${remark.updatedAt ?? Math.floor(Date.now() / 1000)}`);
74
+ lines.push('---', '');
75
+ if (remark.body)
76
+ lines.push(remark.body.trim(), '');
77
+ return lines.join('\n');
78
+ }
79
+ /** 读取单个备注。文件不存在、超限或格式非法都返回 undefined。 */
80
+ export function readRemark(directory, aid) {
81
+ if (!isValidAid(aid))
82
+ return undefined;
83
+ const file = remarkPath(directory, aid);
84
+ try {
85
+ const stat = fs.statSync(file);
86
+ if (!stat.isFile() || stat.size > REMARK_MAX_BYTES)
87
+ return undefined;
88
+ const parsed = parseRemarkFile(fs.readFileSync(file, 'utf8'), aid);
89
+ return parsed ? { ...parsed, mtimeMs: stat.mtimeMs } : undefined;
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
95
+ /**
96
+ * 读取目录下全部备注,按 AID 建索引。
97
+ *
98
+ * 坏文件跳过并记一条 warn:一个格式写错的备注不该让整份目录注入失败。
99
+ */
100
+ export function readAllRemarks(directory) {
101
+ const result = new Map();
102
+ let names;
103
+ try {
104
+ names = fs.readdirSync(remarksDir(directory));
105
+ }
106
+ catch {
107
+ return result;
108
+ }
109
+ for (const name of names) {
110
+ if (!name.endsWith('.md'))
111
+ continue;
112
+ const aid = name.slice(0, -3);
113
+ if (!isValidAid(aid))
114
+ continue;
115
+ const remark = readRemark(directory, aid);
116
+ if (remark)
117
+ result.set(aid, remark);
118
+ else
119
+ logger.warn(`[OwnerDirectoryRemarks] Ignored malformed remark file: ${name}`);
120
+ }
121
+ return result;
122
+ }
123
+ export function writeRemark(directory, remark) {
124
+ if (!isValidAid(remark.aid))
125
+ throw new TypeError('remark requires a valid AID');
126
+ atomicWrite(remarkPath(directory, remark.aid), serializeRemarkFile(remark));
127
+ try {
128
+ fs.chmodSync(remarkPath(directory, remark.aid), 0o600);
129
+ }
130
+ catch { /* best effort */ }
131
+ }
132
+ export function removeRemark(directory, aid) {
133
+ if (!isValidAid(aid))
134
+ return false;
135
+ const file = remarkPath(directory, aid);
136
+ if (!fs.existsSync(file))
137
+ return false;
138
+ atomicRemove(file);
139
+ return true;
140
+ }
141
+ export function listRemarks(directory) {
142
+ return [...readAllRemarks(directory).values()]
143
+ .map(({ aid, remark }) => ({ aid, ...(remark !== undefined ? { remark } : {}) }))
144
+ .sort((a, b) => a.aid.localeCompare(b.aid));
145
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 名录范围。
3
+ *
4
+ * 只有一份 contacts.json:agents 已经并入其中(条目用 `owner_aid` 分内外、
5
+ * 用 `type` 分主体类型),不再有独立的 agents 文件。保留 scope 这一层是因为
6
+ * 授权结果、pending 标记和通知摘要都按 scope 组织。
7
+ *
8
+ * 单独成文件是为了让 store 和 cache 都能引用,而不形成循环依赖。
9
+ */
10
+ export const OWNER_DIRECTORY_SCOPES = ['contacts'];
11
+ export function isOwnerDirectoryScope(value) {
12
+ return value === 'contacts';
13
+ }
14
+ /**
15
+ * 内外判据的唯一来源:条目的 `owner_aid` 是否等于 Owner 身份块里的 `aid`。
16
+ *
17
+ * 身份块缺失时才回落到根 `owner_aid`——协议要求 `owner.aid === owner_aid`,
18
+ * 所以正常情况下两者等价。
19
+ */
20
+ export function ownerRefAid(snapshot, fallbackOwnerAid) {
21
+ return snapshot?.owner?.aid ?? fallbackOwnerAid;
22
+ }
23
+ /** 条目的 Owner AID;缺失返回 undefined。 */
24
+ export function entryOwnerAid(entry) {
25
+ const value = entry.ownerAid?.trim();
26
+ return value ? value : undefined;
27
+ }
28
+ /**
29
+ * 分组判据。
30
+ *
31
+ * 内外只看 `owner_aid` 是否等于 `owner.aid`;没有 `owner_aid` 就无法判断内外,
32
+ * 按类型落到 `unbound_agent`(agent)或 `external_human`(其余)。
33
+ */
34
+ export function classifyEntry(entry, ownerRef) {
35
+ const type = (entry.type ?? '').toLowerCase();
36
+ const owner = entryOwnerAid(entry);
37
+ if (owner === undefined) {
38
+ // 群不依赖 owner_aid 判定——群本身就是外部主体,有没有 Owner 记录都该进群分组。
39
+ // 其余无 owner 的条目按类型落到 unbound_agent / external_human。
40
+ if (type === 'group')
41
+ return 'group';
42
+ return type === 'agent' ? 'unbound_agent' : 'external_human';
43
+ }
44
+ if (owner === ownerRef)
45
+ return 'internal';
46
+ if (type === 'group')
47
+ return 'group';
48
+ if (type === 'agent')
49
+ return 'external_agent';
50
+ return 'external_human';
51
+ }
52
+ /** 条目是否属于本 Owner(内部联系人)。没有 `owner_aid` 的条目不算内部。 */
53
+ export function isInternalEntry(entry, ownerRef) {
54
+ return entryOwnerAid(entry) === ownerRef;
55
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * 名录检索。
3
+ *
4
+ * 两种使用场景:
5
+ * - 按描述找能力:注入里已有截断后的描述,命令补的是完整记录和注入里看不到的条目。
6
+ * - 按名字找 AID:Owner 或 PA 说"联系张三",要落到具体 AID。
7
+ *
8
+ * 中文没有词边界,一律按子串匹配,不做分词。查询串按空白切成 token,
9
+ * **所有 token 都要命中**(AND),总分是每个 token 最佳命中字段的分数之和。
10
+ */
11
+ import { isInternalEntry, ownerRefAid } from './owner-directory-scope.js';
12
+ const DEFAULT_LIMIT = 5;
13
+ const MAX_LIMIT = 50;
14
+ /** 各命中方式的权重。分数用于排序,不承诺对外稳定,调用方只看相对顺序。 */
15
+ const WEIGHT = {
16
+ exactAid: 1000,
17
+ exactName: 1000,
18
+ prefix: 600,
19
+ exactRemark: 500,
20
+ contains: 300,
21
+ domainContains: 250,
22
+ exactExttype: 200,
23
+ descriptionContains: 150,
24
+ exactType: 100,
25
+ };
26
+ /** 这个人就是当前 agent 的个人助理。 */
27
+ export function isPersonalAssistantSnapshot(selfAid, snapshot) {
28
+ return !!snapshot?.personalAssistant?.aid && snapshot.personalAssistant.aid === selfAid;
29
+ }
30
+ export function searchDirectory(snapshot, ownerAid, remarks, options) {
31
+ if (!snapshot)
32
+ return [];
33
+ const ownerRef = ownerRefAid(snapshot, ownerAid);
34
+ const tokens = tokenize(options.query);
35
+ if (tokens.length === 0)
36
+ return [];
37
+ const limit = clampLimit(options.limit);
38
+ // 默认查全部:注入里的外部条目只有名字,模型要靠 find 才能拿到 AID。
39
+ const scope = options.scope ?? 'all';
40
+ const typeFilter = options.type?.trim().toLowerCase();
41
+ const hits = [];
42
+ for (const entry of snapshot.entries) {
43
+ const internal = isInternalEntry(entry, ownerRef);
44
+ if (scope === 'internal' && !internal)
45
+ continue;
46
+ if (scope === 'external' && internal)
47
+ continue;
48
+ if (typeFilter && (entry.type ?? '').toLowerCase() !== typeFilter)
49
+ continue;
50
+ // 本地备注是"这个 agent 自己怎么看这个人",搜索优先用它。
51
+ const remark = remarks?.get(entry.aid);
52
+ const effectiveRemark = remark?.remark ?? entry.remark;
53
+ const effectiveDescription = remark?.body ?? entry.description;
54
+ let score = 0;
55
+ const matched = new Set();
56
+ let allTokensHit = true;
57
+ for (const token of tokens) {
58
+ const best = scoreToken(token, entry, effectiveRemark, effectiveDescription);
59
+ if (best.score === 0) {
60
+ allTokensHit = false;
61
+ break;
62
+ }
63
+ score += best.score;
64
+ matched.add(best.field);
65
+ }
66
+ if (!allTokensHit)
67
+ continue;
68
+ hits.push({
69
+ aid: entry.aid,
70
+ name: entry.name,
71
+ ...(entry.type !== undefined ? { type: entry.type } : {}),
72
+ ...(entry.exttype !== undefined ? { exttype: entry.exttype } : {}),
73
+ ...(entry.baseagent !== undefined ? { baseagent: entry.baseagent } : {}),
74
+ ...(effectiveRemark !== undefined ? { remark: effectiveRemark } : {}),
75
+ ...(effectiveDescription !== undefined ? { description: effectiveDescription } : {}),
76
+ internal,
77
+ matched: [...matched],
78
+ score,
79
+ });
80
+ }
81
+ // 同分时内部优先,再按名称、AID 排,保证结果稳定。
82
+ hits.sort((a, b) => b.score - a.score
83
+ || Number(b.internal) - Number(a.internal)
84
+ || a.name.localeCompare(b.name)
85
+ || a.aid.localeCompare(b.aid));
86
+ return hits.slice(0, limit);
87
+ }
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();
94
+ if (aid === token)
95
+ return { score: WEIGHT.exactAid, field: 'aid' };
96
+ if (name === token)
97
+ return { score: WEIGHT.exactName, field: 'name' };
98
+ if (aid.startsWith(token) || name.startsWith(token))
99
+ return { score: WEIGHT.prefix, field: 'prefix' };
100
+ if (remark && remark.toLowerCase() === token)
101
+ return { score: WEIGHT.exactRemark, field: 'remark' };
102
+ // AID 的域段先于普通包含判定:`find agentid.cn` 是"列出这个域",不是"名字里有这段字"。
103
+ const domain = aid.slice(aid.indexOf('.') + 1);
104
+ if (domain.includes(token))
105
+ return { score: WEIGHT.domainContains, field: 'domain' };
106
+ if (aid.includes(token) || name.includes(token))
107
+ return { score: WEIGHT.contains, field: 'name' };
108
+ if (exttype === token || baseagent === token)
109
+ return { score: WEIGHT.exactExttype, field: 'exttype' };
110
+ if (description && description.toLowerCase().includes(token)) {
111
+ return { score: WEIGHT.descriptionContains, field: 'description' };
112
+ }
113
+ if (remark && remark.toLowerCase().includes(token)) {
114
+ return { score: WEIGHT.descriptionContains, field: 'remark' };
115
+ }
116
+ if (type === token)
117
+ return { score: WEIGHT.exactType, field: 'type' };
118
+ return { score: 0, field: '' };
119
+ }
120
+ /** 单个条目的完整记录,用于 `show`。描述与备注不截断。 */
121
+ export function describeEntry(entry, ownerRef, remark, contactable) {
122
+ return {
123
+ aid: entry.aid,
124
+ name: entry.name,
125
+ type: entry.type ?? null,
126
+ exttype: entry.exttype ?? null,
127
+ baseagent: entry.baseagent ?? null,
128
+ remark: remark?.remark ?? entry.remark ?? null,
129
+ description: remark?.body ?? entry.description ?? null,
130
+ ownershipStatus: entry.ownership_status ?? null,
131
+ agentMdSignedAt: entry.agent_md_signed_at ?? null,
132
+ internal: isInternalEntry(entry, ownerRef),
133
+ contactable,
134
+ remarkSource: remark ? 'local' : 'remote',
135
+ };
136
+ }
137
+ function tokenize(query) {
138
+ return String(query ?? '')
139
+ .toLowerCase()
140
+ .split(/\s+/)
141
+ .map(token => token.trim())
142
+ .filter(Boolean);
143
+ }
144
+ function clampLimit(limit) {
145
+ if (!Number.isSafeInteger(limit) || limit <= 0)
146
+ return DEFAULT_LIMIT;
147
+ return Math.min(MAX_LIMIT, limit);
148
+ }
@@ -0,0 +1,227 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { atomicWriteJson } from '../utils/atomic-write.js';
4
+ import { logger } from '../utils/logger.js';
5
+ import { OWNER_DIRECTORY_SCOPES } from './owner-directory-scope.js';
6
+ // ── content_digest helpers ────────────────────────────────────────────────────
7
+ const CONTENT_DIGEST_RE = /^[a-f0-9]{64}$/;
8
+ export function isValidContentDigest(v) {
9
+ return typeof v === 'string' && CONTENT_DIGEST_RE.test(v);
10
+ }
11
+ /**
12
+ * 解析 v2 通知 data.digests 字段。
13
+ * 老格式(无 digests)或字段缺失时返回空对象,接收端回退到无条件拉取。
14
+ *
15
+ * 只认 OWNER_DIRECTORY_SCOPES:App 若还发 `digests.agents`(agents.json 时代的
16
+ * 残留),这里直接忽略,结果为空 → 退化成无条件拉取,不会卡住同步。
17
+ */
18
+ export function parseNotificationSnapshots(data) {
19
+ if (!data || typeof data !== 'object' || Array.isArray(data))
20
+ return {};
21
+ const raw = data['digests'];
22
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
23
+ return {};
24
+ const result = {};
25
+ for (const scope of OWNER_DIRECTORY_SCOPES) {
26
+ const entry = raw[scope];
27
+ if (!entry || typeof entry !== 'string')
28
+ continue;
29
+ if (!isValidContentDigest(entry))
30
+ continue;
31
+ result[scope] = { content_digest: entry };
32
+ }
33
+ return result;
34
+ }
35
+ // ── 路径 helpers ──────────────────────────────────────────────────────────────
36
+ function archiveDir(directory, now) {
37
+ const y = now.getUTCFullYear();
38
+ const m = String(now.getUTCMonth() + 1).padStart(2, '0');
39
+ return path.join(directory, 'archive', `${y}-${m}`);
40
+ }
41
+ function archiveFileName(scope, now) {
42
+ const iso = now.toISOString().replace(/[-:.]/g, '').slice(0, 15) + 'Z';
43
+ return `${scope}-${iso}.json`;
44
+ }
45
+ function changesDir(directory) {
46
+ return path.join(directory, 'changes');
47
+ }
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`);
52
+ }
53
+ function changesIndexFile(directory) {
54
+ return path.join(changesDir(directory), 'index.json');
55
+ }
56
+ // ── 归档 ───────────────────────────────────────────────────────────────────────
57
+ /**
58
+ * 把旧快照文件复制到 archive/ 子目录,全量保留不清理。
59
+ * 旧文件不存在时静默跳过,内部 catch 不向上抛。
60
+ */
61
+ export function archiveSnapshot(directory, scope, now = new Date()) {
62
+ const src = path.join(directory, `${scope}.json`);
63
+ if (!fs.existsSync(src))
64
+ return;
65
+ try {
66
+ const aDir = archiveDir(directory, now);
67
+ fs.mkdirSync(aDir, { recursive: true, mode: 0o700 });
68
+ const dest = path.join(aDir, archiveFileName(scope, now));
69
+ fs.copyFileSync(src, dest);
70
+ logger.debug(`[OwnerDirectoryStore] Archived ${scope} → ${dest}`);
71
+ }
72
+ catch (error) {
73
+ logger.warn(`[OwnerDirectoryStore] Archive failed for ${scope}: ${error instanceof Error ? error.message : String(error)}`);
74
+ }
75
+ }
76
+ // ── 变更记录 ──────────────────────────────────────────────────────────────────
77
+ function isHost(entry) {
78
+ return entry.type === 'host';
79
+ }
80
+ /** 条目类别:变更记录的 added/removed 前缀按这个走,不再由文件 scope 决定。 */
81
+ function entryChangeKind(entry) {
82
+ return entry.type === 'agent' ? 'agent' : 'contact';
83
+ }
84
+ /**
85
+ * 比较新旧两份快照,生成变更行列表。
86
+ * 无旧快照时写一行 baseline(不展开差集)。
87
+ * owner / personal_assistant 字段的 agent_md_signed_at 变化也纳入比对。
88
+ */
89
+ export function diffSnapshots(scope, next, prev, nextMeta, prevMeta) {
90
+ const now = next.fetchedAt;
91
+ const contentDigest = next.contentDigest ?? '';
92
+ const prevDigest = prev?.contentDigest ?? '';
93
+ if (!prev) {
94
+ return [{
95
+ at: now, scope, type: 'baseline', aid: '',
96
+ contentDigest, prevContentDigest: '',
97
+ from: null, to: null,
98
+ }];
99
+ }
100
+ const prevMap = new Map(prev.entries.map(e => [e.aid, e]));
101
+ const nextMap = new Map(next.entries.map(e => [e.aid, e]));
102
+ const lines = [];
103
+ for (const [aid, entry] of nextMap) {
104
+ const old = prevMap.get(aid);
105
+ if (!old) {
106
+ const kind = entryChangeKind(entry);
107
+ lines.push({ at: now, scope, type: kind === 'agent' ? 'agent_added' : 'contact_added', aid, contentDigest, prevContentDigest: prevDigest, from: null, to: entry });
108
+ if (isHost(entry)) {
109
+ lines.push({ at: now, scope, type: 'host_added', aid, contentDigest, prevContentDigest: prevDigest, from: null, to: entry });
110
+ }
111
+ }
112
+ else if (entryChanged(old, entry)) {
113
+ lines.push({ at: now, scope, type: 'entry_changed', aid, contentDigest, prevContentDigest: prevDigest, from: old, to: entry });
114
+ const wasHost = isHost(old), nowHost = isHost(entry);
115
+ if (!wasHost && nowHost)
116
+ lines.push({ at: now, scope, type: 'host_added', aid, contentDigest, prevContentDigest: prevDigest, from: old, to: entry });
117
+ if (wasHost && !nowHost)
118
+ lines.push({ at: now, scope, type: 'host_removed', aid, contentDigest, prevContentDigest: prevDigest, from: old, to: entry });
119
+ }
120
+ }
121
+ for (const [aid, entry] of prevMap) {
122
+ if (!nextMap.has(aid)) {
123
+ const kind = entryChangeKind(entry);
124
+ lines.push({ at: now, scope, type: kind === 'agent' ? 'agent_removed' : 'contact_removed', aid, contentDigest, prevContentDigest: prevDigest, from: entry, to: null });
125
+ if (isHost(entry)) {
126
+ lines.push({ at: now, scope, type: 'host_removed', aid, contentDigest, prevContentDigest: prevDigest, from: entry, to: null });
127
+ }
128
+ }
129
+ }
130
+ return lines;
131
+ }
132
+ /**
133
+ * 条目内容是否变化。比较全部内容字段;`ownership_checked_at_ms` 是探测时间而不是
134
+ * 内容,单独变化不记变更行。
135
+ */
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;
145
+ }
146
+ /**
147
+ * 收集需要刷新 agent.md 的 AID:
148
+ * - 新增条目
149
+ * - agent_md_signed_at 变化的条目
150
+ * - 根对象 `owner` / `personal_assistant` 的 agent_md_signed_at 变化
151
+ */
152
+ export function collectAgentMdRefreshAids(lines, nextMeta, prevMeta, nextSnapshot) {
153
+ const aids = new Set();
154
+ // baseline = first-ever pull; refresh all entries in the new snapshot
155
+ if (lines.some(l => l.type === 'baseline') && nextSnapshot) {
156
+ for (const entry of nextSnapshot.entries)
157
+ aids.add(entry.aid);
158
+ }
159
+ else {
160
+ for (const line of lines) {
161
+ if (line.type === 'baseline' || line.type === 'host_added' || line.type === 'host_removed')
162
+ continue;
163
+ if (!line.aid)
164
+ continue;
165
+ const isAdd = line.type === 'agent_added' || line.type === 'contact_added';
166
+ const signedAtChanged = line.from?.agent_md_signed_at !== line.to?.agent_md_signed_at;
167
+ if (isAdd || signedAtChanged)
168
+ aids.add(line.aid);
169
+ }
170
+ }
171
+ // owner / personal_assistant fields
172
+ if (nextMeta?.owner?.aid) {
173
+ const prev = prevMeta?.owner?.agent_md_signed_at ?? 0;
174
+ const next = nextMeta.owner.agent_md_signed_at ?? 0;
175
+ if (next > prev)
176
+ aids.add(nextMeta.owner.aid);
177
+ }
178
+ if (nextMeta?.personalAssistant?.aid) {
179
+ const prev = prevMeta?.personalAssistant?.agent_md_signed_at ?? 0;
180
+ const next = nextMeta.personalAssistant.agent_md_signed_at ?? 0;
181
+ if (next > prev)
182
+ aids.add(nextMeta.personalAssistant.aid);
183
+ }
184
+ return [...aids];
185
+ }
186
+ /**
187
+ * 将变更行追加到 changes/<YYYY-MM>.jsonl,并更新 index.json。
188
+ * 无变更时跳过。失败只记日志,不影响调用方。
189
+ */
190
+ export function appendChanges(directory, lines, now = new Date()) {
191
+ if (lines.length === 0)
192
+ return;
193
+ 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);
199
+ }
200
+ catch (error) {
201
+ logger.warn(`[OwnerDirectoryStore] appendChanges failed: ${error instanceof Error ? error.message : String(error)}`);
202
+ }
203
+ }
204
+ function updateChangesIndex(directory, lines, now) {
205
+ const indexPath = changesIndexFile(directory);
206
+ let index = [];
207
+ try {
208
+ const raw = JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
209
+ if (Array.isArray(raw))
210
+ index = raw;
211
+ }
212
+ catch { /* fresh */ }
213
+ const y = now.getUTCFullYear(), m = now.getUTCMonth() + 1;
214
+ const existing = index.find(e => e.year === y && e.month === m);
215
+ const ats = lines.map(l => l.at);
216
+ const minAt = Math.min(...ats), maxAt = Math.max(...ats);
217
+ if (existing) {
218
+ existing.count += lines.length;
219
+ existing.firstAt = Math.min(existing.firstAt, minAt);
220
+ existing.lastAt = Math.max(existing.lastAt, maxAt);
221
+ }
222
+ else {
223
+ index.push({ year: y, month: m, count: lines.length, firstAt: minAt, lastAt: maxAt });
224
+ index.sort((a, b) => a.year !== b.year ? a.year - b.year : a.month - b.month);
225
+ }
226
+ atomicWriteJson(indexPath, index);
227
+ }
@@ -237,6 +237,7 @@ const PARAM_DESCRIPTIONS = {
237
237
  isBootstrapping: '当前 agent 是否处于 bootstrap 首次设定阶段',
238
238
  hasPersona: '是否有 persona 内容',
239
239
  hasWorkingMemory: '是否有 working memory',
240
+ hasOwnerDirectory: '是否有 Owner 名录注入文件($AGENT_DIR/directory/directory.md)',
240
241
  peerId: '对端在该渠道的原生 ID',
241
242
  peerKey: '对端跨渠道唯一标识(channel#urlEncode(peerId))',
242
243
  peerName: '对端显示名',
@@ -1,6 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import path from 'node:path';
3
3
  import { ConfigTarget, mutateConfig, read, validateConfig, } from '../config/config-manager.js';
4
+ import { LOG_LEVELS } from '../utils/logger.js';
4
5
  const BASEAGENTS = ['claude', 'codex', 'gemini', 'ecagent'];
5
6
  const BASEAGENT_SET = new Set(BASEAGENTS);
6
7
  const EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
@@ -33,6 +34,7 @@ const DAEMON_EXACT_PATHS = new Set([
33
34
  'debug.aunSdkLog',
34
35
  'debug.upmsg',
35
36
  'debug.eckSnapshots',
37
+ 'debug.channelLogs',
36
38
  ]);
37
39
  const DEFAULTS_EXACT_PATHS = new Set([
38
40
  'active_baseagent',
@@ -99,6 +101,7 @@ const BOOLEAN_PATHS = new Set([
99
101
  'debug.aunSdkLog',
100
102
  'debug.upmsg',
101
103
  'debug.eckSnapshots',
104
+ 'debug.channelLogs',
102
105
  'responseModeParams.single-session.pre_tool_1stmsgchk',
103
106
  'responseModeParams.single-session.tool_use_reminder',
104
107
  'session_renew.enabled',
@@ -410,7 +413,7 @@ function validateDaemonValue(fieldPath, value) {
410
413
  return;
411
414
  }
412
415
  if (fieldPath === 'debug.logLevel') {
413
- if (!['DEBUG', 'INFO', 'WARN', 'ERROR'].includes(String(value)))
416
+ if (!LOG_LEVELS.includes(String(value)))
414
417
  throw makeError(`${fieldPath} is invalid`, 'INVALID_SETTINGS_VALUE');
415
418
  return;
416
419
  }
@@ -1,5 +1,5 @@
1
1
  import { isValidAid } from '../aun/aid/validation.js';
2
- import { resolvePeerDisplayLabel } from '../config/contact-book.js';
2
+ import { resolvePeerDisplayLabel } from '../config/peer-book.js';
3
3
  import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
4
4
  import { resolveChatMode } from '../core/message/peer-mode.js';
5
5
  import { resolvePermissionMode } from '../core/model/config-scope.js';
@@ -58,7 +58,7 @@ function displayLabels(value) {
58
58
  }
59
59
  });
60
60
  }
61
- export function createEcwebMessageContextProvider(sessionManager) {
61
+ export function createEcwebMessageContextProvider(sessionManager, resolveRuntimeStatus) {
62
62
  return async (request) => {
63
63
  for (const field of Object.keys(request)) {
64
64
  if (!REQUEST_FIELDS.has(field))
@@ -95,14 +95,18 @@ export function createEcwebMessageContextProvider(sessionManager) {
95
95
  const session = await sessionManager.getSessionById(sessionId);
96
96
  if (session?.selfAID === identity.selfAid
97
97
  && session.channelType === identity.channelType
98
- && session.channelId === conversationId
99
- && session.agentSessionId && session.projectPath && session.baseagent) {
100
- try {
101
- const fileInfo = sessionManager.getSessionFileInfo(session.projectPath, session.agentSessionId, session.baseagent, session.selfAID);
102
- if (Number.isFinite(fileInfo.turns) && fileInfo.turns > 0)
103
- result.turns = fileInfo.turns;
98
+ && session.channelId === conversationId) {
99
+ const status = resolveRuntimeStatus?.(session);
100
+ if (status)
101
+ result.status = status;
102
+ if (session.agentSessionId && session.projectPath && session.baseagent) {
103
+ try {
104
+ const fileInfo = sessionManager.getSessionFileInfo(session.projectPath, session.agentSessionId, session.baseagent, session.selfAID);
105
+ if (Number.isFinite(fileInfo.turns) && fileInfo.turns > 0)
106
+ result.turns = fileInfo.turns;
107
+ }
108
+ catch { }
104
109
  }
105
- catch { }
106
110
  }
107
111
  }
108
112
  return result;