evolcore 0.0.43-test.0 → 0.0.43-test.2

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 (172) hide show
  1. package/CHANGELOG.md +31 -2
  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 +26 -9
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/aid/client.js +1 -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 +3 -0
  13. package/dist/channels/aun.js +484 -43
  14. package/dist/channels/builtin-plugins.js +16 -11
  15. package/dist/channels/dingtalk.js +83 -31
  16. package/dist/channels/feishu.js +29 -13
  17. package/dist/channels/qqbot.js +32 -11
  18. package/dist/channels/wechat.js +13 -3
  19. package/dist/channels/wecom.js +67 -27
  20. package/dist/cli/agent-command.js +3 -86
  21. package/dist/cli/agent-create.js +22 -6
  22. package/dist/cli/agent.js +1 -79
  23. package/dist/cli/aun-commands.js +1 -0
  24. package/dist/cli/config.js +1 -1
  25. package/dist/cli/daemon-commands.js +47 -2
  26. package/dist/cli/data-command.js +9 -1
  27. package/dist/cli/debug-mode.js +1 -1
  28. package/dist/cli/diag.js +1 -1
  29. package/dist/cli/directory.js +77 -64
  30. package/dist/cli/getmeta-command.js +1 -1
  31. package/dist/cli/index.js +79 -22
  32. package/dist/cli/init.js +1 -23
  33. package/dist/cli/link-rules.js +1 -1
  34. package/dist/cli/managed-command-guard.js +0 -1
  35. package/dist/cli/pa-workspace-command.js +36 -2
  36. package/dist/cli/peer.js +1 -1
  37. package/dist/cli/restart-monitor.js +17 -3
  38. package/dist/cli/role.js +1 -1
  39. package/dist/cli/session-command.js +1 -1
  40. package/dist/cli/stats.js +2 -2
  41. package/dist/cli/thread-command.js +1 -1
  42. package/dist/cli/watch-msg.js +1 -1
  43. package/dist/config/access-policy.js +1 -0
  44. package/dist/config/config-field-policy.js +2 -2
  45. package/dist/config/config-manager.js +7 -0
  46. package/dist/config/role-schema.js +4 -3
  47. package/dist/config/role-service.js +3 -3
  48. package/dist/config-store.js +75 -4
  49. package/dist/core/agent-ipc-registration.js +16 -59
  50. package/dist/core/agent-runtime.js +2 -1
  51. package/dist/core/auth/authorization-audit.js +52 -14
  52. package/dist/core/auth/operation-authorizer.js +0 -11
  53. package/dist/core/auth/operation-catalog.js +0 -18
  54. package/dist/core/channel-loader.js +152 -16
  55. package/dist/core/command/agent-control.js +2 -1
  56. package/dist/core/command/cli-intent-parser.js +0 -8
  57. package/dist/core/command/command-handler.js +17 -46
  58. package/dist/core/command/connect-menu.js +7 -3
  59. package/dist/core/command/menu-catalog.js +3 -2
  60. package/dist/core/command/menu-handler.js +51 -8
  61. package/dist/core/command/menu-protocol.js +20 -0
  62. package/dist/core/command/slash-handler.js +101 -40
  63. package/dist/core/daemon-file-cache.js +3 -3
  64. package/dist/core/evolagent-registry.js +5 -4
  65. package/dist/core/evolagent.js +5 -8
  66. package/dist/core/handoff/argv-parse.js +115 -0
  67. package/dist/core/handoff/ipc-registration.js +1 -1
  68. package/dist/core/ipc-registration.js +19 -2
  69. package/dist/core/memory/consolidation.js +8 -1
  70. package/dist/core/memory/relation-sweep.js +20 -8
  71. package/dist/core/message/aun-ipc-sender.js +28 -1
  72. package/dist/core/message/contact-admission.js +548 -0
  73. package/dist/core/message/im-renderer.js +69 -10
  74. package/dist/core/message/message-admission.js +28 -3
  75. package/dist/core/message/message-bridge.js +46 -5
  76. package/dist/core/message/message-utils.js +0 -5
  77. package/dist/core/message/peer-mode.js +44 -10
  78. package/dist/core/message/response-engine.js +268 -69
  79. package/dist/core/message/retry-scheduler.js +4 -0
  80. package/dist/core/permission/ec-command-parser.js +1 -28
  81. package/dist/core/permission/readonly-shell-query.js +34 -8
  82. package/dist/core/permission/tool-policy.js +50 -5
  83. package/dist/core/role/runtime-policy.js +14 -2
  84. package/dist/core/session/session-manager.js +9 -1
  85. package/dist/core/soul.js +66 -0
  86. package/dist/core/system-session/memory.js +2 -2
  87. package/dist/directory/contact-admission-paths.js +9 -0
  88. package/dist/directory/owner-directory-admission.js +128 -29
  89. package/dist/directory/owner-directory-cache.js +364 -50
  90. package/dist/directory/owner-directory-identity.js +60 -0
  91. package/dist/directory/owner-directory-markdown.js +120 -47
  92. package/dist/directory/owner-directory-policy.js +108 -0
  93. package/dist/directory/owner-directory-query-operation.js +219 -32
  94. package/dist/directory/owner-directory-remarks.js +29 -2
  95. package/dist/directory/owner-directory-search.js +50 -18
  96. package/dist/directory/owner-directory-store.js +150 -30
  97. package/dist/eck/kit-renderer.js +12 -5
  98. package/dist/eck/manifest-engine.js +55 -6
  99. package/dist/eck/message-renderer.js +5 -2
  100. package/dist/eck/paactive-context.js +45 -0
  101. package/dist/ecweb/basic-settings-service.js +2 -2
  102. package/dist/ecweb/message-context-service.js +24 -16
  103. package/dist/index.js +9 -5
  104. package/dist/ipc.js +1 -1
  105. package/dist/paths.js +26 -0
  106. package/dist/response-system/config-resolver.js +1 -1
  107. package/dist/response-system/engines/v1/index.js +4 -1
  108. package/dist/response-system/engines/v1/paactive-flow.js +18 -0
  109. package/dist/response-system/modes/single-session/index.js +7 -2
  110. package/dist/trigger/scheduler.js +3 -5
  111. package/dist/trigger/validation.js +4 -0
  112. package/dist/utils/error-utils.js +5 -2
  113. package/dist/utils/logger.js +13 -4
  114. package/dist/utils/npm-ops.js +2 -2
  115. package/dist/utils/windows-autostart.js +1 -1
  116. package/ecagent/dist/agent-loop.js +43 -1
  117. package/kits/docs/INDEX.md +1 -0
  118. package/kits/docs/context-assembly.md +21 -6
  119. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  120. package/kits/docs/evolcore/INDEX.md +1 -1
  121. package/kits/docs/evolcore/agent-create.md +5 -5
  122. package/kits/docs/evolcore/agent.md +4 -9
  123. package/kits/docs/evolcore/directory.md +137 -0
  124. package/kits/docs/evolcore/menu-protocol.md +55 -0
  125. package/kits/docs/evolcore/response.md +7 -1
  126. package/kits/docs/evolcore/tool-authorization.md +1 -1
  127. package/kits/docs/evolcore/trigger.md +4 -0
  128. package/kits/docs/prompt-loading-architecture.md +6 -2
  129. package/kits/eck_manifest.auxiliary.json +1 -0
  130. package/kits/eck_manifest.json +57 -4
  131. package/kits/eck_manifest.memory.json +67 -3
  132. package/kits/eck_manifest.paactive.json +528 -0
  133. package/kits/eck_message_manifest.paactive.json +233 -0
  134. package/kits/rules/01-overview.md +2 -2
  135. package/kits/rules/03-identity.md +10 -9
  136. package/kits/rules/05-venue.md +2 -4
  137. package/kits/rules/06-channel.md +1 -1
  138. package/kits/schemas/_meta.json +31 -3
  139. package/kits/schemas/agent-config.schema.18.json +5 -0
  140. package/kits/schemas/agent-config.schema.19.json +924 -0
  141. package/kits/schemas/relation-config.schema.12.json +289 -0
  142. package/kits/schemas/role-config.schema.2.json +215 -0
  143. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  144. package/kits/skills/ec-trigger/SKILL.md +4 -4
  145. package/kits/skills/personal-assistant/SKILL.md +109 -53
  146. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  147. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  148. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  149. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  150. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  151. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  152. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  153. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  154. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  155. package/kits/templates/message-fragments/paactive/item.md +3 -0
  156. package/kits/templates/soul/00-GUIDE.md +61 -0
  157. package/kits/templates/soul/01-identity.md +5 -0
  158. package/kits/templates/soul/02-persona.md +11 -0
  159. package/kits/templates/soul/03-duties.md +5 -0
  160. package/kits/templates/soul/04-working-style.md +5 -0
  161. package/kits/templates/system-fragments/bootstrap.md +7 -7
  162. package/kits/templates/system-fragments/commands.md +3 -2
  163. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  164. package/kits/templates/system-fragments/memory.md +1 -1
  165. package/kits/templates/system-fragments/paactive/channel.md +25 -0
  166. package/kits/templates/system-fragments/paactive/reply.md +25 -0
  167. package/kits/templates/system-fragments/paactive/session.md +32 -0
  168. package/kits/templates/system-fragments/personal-assistant.md +65 -0
  169. package/package.json +4 -3
  170. package/dist/cli/handoff-command.js +0 -353
  171. package/dist/directory/owner-directory-remark-operation.js +0 -147
  172. package/kits/docs/evolcore/self-summary.md +0 -29
@@ -0,0 +1,548 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { contactAdmissionDirectory } from '../../directory/contact-admission-paths.js';
6
+ import { atomicWriteJson } from '../../utils/atomic-write.js';
7
+ import { isValidAid } from '../../aun/aid/validation.js';
8
+ import { readAccessPolicy } from '../../config/access-policy.js';
9
+ import { resolvePeerView } from '../../config/peer-book.js';
10
+ import { readOwnerDirectoryMembership } from '../../directory/owner-directory-admission.js';
11
+ import { ownerResolver } from '../ownership/owner-resolver.js';
12
+ import { isProcessRunning } from '../../utils/cross-platform.js';
13
+ export const CONTACT_EVENT_TTL_MS = 3 * 24 * 60 * 60 * 1000;
14
+ const GRANT_DURATION_MS = 30 * 60 * 1000;
15
+ const MAX_ISOLATED_CONTACT_SOURCES = 10000;
16
+ // Read-only probes must never delete an atomic writer's __ file or restore its backup.
17
+ function readState(file) {
18
+ try {
19
+ return fs.readFileSync(file, 'utf8');
20
+ }
21
+ catch (error) {
22
+ if (error.code === 'ENOENT')
23
+ return undefined;
24
+ throw error;
25
+ }
26
+ }
27
+ function sourceFile(selfAid, aid, mid) {
28
+ const key = crypto.createHash('sha256').update(JSON.stringify([selfAid, aid, mid])).digest('hex');
29
+ return path.join(contactAdmissionDirectory(selfAid), 'isolated-sources', key.slice(0, 2), key + '.json');
30
+ }
31
+ const failedIsolationStores = new Set();
32
+ export function isolatedContactSource(selfAid, aid, mid) {
33
+ if (failedIsolationStores.has(selfAid) || ['isolation-incomplete', 'isolation-failed'].some(name => fs.existsSync(path.join(contactAdmissionDirectory(selfAid), name)))) {
34
+ throw new Error('contact isolation store requires recovery');
35
+ }
36
+ const raw = readState(sourceFile(selfAid, aid, mid));
37
+ if (raw === undefined)
38
+ return undefined;
39
+ const source = JSON.parse(raw);
40
+ if (!source || !Number.isSafeInteger(source.at) || source.at < 0 || typeof source.digest !== 'string'
41
+ || !/^[a-f0-9]{64}$/.test(source.digest))
42
+ throw new Error('invalid contact isolation source');
43
+ return source;
44
+ }
45
+ /** A source tombstone is independent of Owner/version and never contains message text. */
46
+ export function saveIsolatedContactSource(selfAid, aid, mid, source) {
47
+ const barrier = path.join(contactAdmissionDirectory(selfAid), 'isolation-incomplete');
48
+ try {
49
+ return withContactStateLock(selfAid, 'sources', () => {
50
+ const file = sourceFile(selfAid, aid, mid);
51
+ try {
52
+ if (failedIsolationStores.has(selfAid) || fs.existsSync(barrier)
53
+ || fs.existsSync(path.join(contactAdmissionDirectory(selfAid), 'isolation-failed')))
54
+ throw new Error('contact isolation store requires recovery');
55
+ const existing = readState(file);
56
+ if (existing) {
57
+ const previous = JSON.parse(existing);
58
+ if (previous.digest !== source.digest)
59
+ return previous;
60
+ source = { ...previous, ...(source.notified ? { notified: true } : {}) };
61
+ }
62
+ fs.writeFileSync(barrier, 'incomplete', { mode: 0o600 });
63
+ if (!existing) {
64
+ const countFile = path.join(contactAdmissionDirectory(selfAid), 'isolated-source-count.json');
65
+ const countRaw = readState(countFile);
66
+ let count;
67
+ if (countRaw)
68
+ count = JSON.parse(countRaw).count;
69
+ else {
70
+ const directory = path.dirname(path.dirname(file));
71
+ count = fs.existsSync(directory) ? fs.readdirSync(directory, { withFileTypes: true }).filter(item => item.isDirectory())
72
+ .reduce((total, item) => total + fs.readdirSync(path.join(directory, item.name)).filter(name => name.endsWith('.json')).length, 0) : 0;
73
+ }
74
+ if (!Number.isSafeInteger(count) || count < 0 || count >= MAX_ISOLATED_CONTACT_SOURCES)
75
+ throw new Error('contact source capacity reached');
76
+ atomicWriteJson(countFile, { count: count + 1 });
77
+ }
78
+ fs.mkdirSync(path.dirname(file), { recursive: true });
79
+ // Persist only source identity, binding and event metadata, never introduction text.
80
+ atomicWriteJson(file, source);
81
+ fs.unlinkSync(barrier);
82
+ return source;
83
+ }
84
+ catch (error) {
85
+ failedIsolationStores.add(selfAid);
86
+ throw error;
87
+ }
88
+ });
89
+ }
90
+ catch (error) {
91
+ failedIsolationStores.add(selfAid);
92
+ // Even a lock failure cannot allow a later restart to reinterpret the source.
93
+ try {
94
+ fs.mkdirSync(path.dirname(barrier), { recursive: true });
95
+ fs.writeFileSync(path.join(path.dirname(barrier), 'isolation-failed'), 'recovery required', { mode: 0o600 });
96
+ }
97
+ catch { /* disk unavailable: remain closed in memory */ }
98
+ throw error;
99
+ }
100
+ }
101
+ export function contactSourceDigest(payload) {
102
+ return crypto.createHash('sha256').update(JSON.stringify(payload) ?? 'undefined').digest('hex');
103
+ }
104
+ export function appContactAdmissionEnabled(selfAid) {
105
+ return readAccessPolicy(selfAid).contactAdmission === 'app-v1';
106
+ }
107
+ /**
108
+ * app-v1 是否真正生效:配置已开启**且**当前 Ownership 能给出共识绑定。
109
+ *
110
+ * app-v1 的判定全部建立在 relation_version 之上;没有绑定(单边关系、未签署声明、
111
+ * Ownership 暂不可用)时无法判定,此时必须退回 legacy 规则,而不是把所有人判成
112
+ * unavailable 后静默丢信。旧格式授权由 OwnerDirectoryCache 的兼容读取放行,
113
+ * 因此 legacy 规则对既有授权仍然有效。
114
+ *
115
+ * 绑定新鲜度不参与这里的判定:准入链路上反复核验 Ownership 既昂贵又会把健康关系
116
+ * 误判成不可用。共识只在显式事件(ownership 变更、agent.md/owner.md 变化、配置
117
+ * Owner 变化、断线过期)到达时被 invalidate,届时绑定自然消失并回退 legacy。
118
+ */
119
+ export function appContactAdmissionActive(selfAid) {
120
+ return appContactAdmissionEnabled(selfAid) && !!currentContactBinding(selfAid);
121
+ }
122
+ /**
123
+ * 当前生效的共识绑定,不要求授权处在 5 分钟窗口内。
124
+ *
125
+ * 用于准入、传输校验等高频路径:它们只需要"身份与版本仍由已观测到的共识支撑",
126
+ * 5 分钟授权窗口是敏感操作(ability、执行授权)的判据,见 verifiedContactBinding。
127
+ */
128
+ export function currentContactBinding(selfAid) {
129
+ return consensusContactBinding(selfAid, ownerResolver.snapshot(selfAid));
130
+ }
131
+ /** 只要求当前观测到的共识:身份、锁和关系版本一致即可,不看授权时效。 */
132
+ export function consensusContactBinding(selfAid, view) {
133
+ const consensus = view.consensus;
134
+ const owner = view.ownerAid;
135
+ const version = consensus?.relation_version;
136
+ if (view.subjectAid !== selfAid
137
+ || view.consensusStatus !== 'consensus' || consensus?.status !== 'consensus' || consensus.lock !== 'locked'
138
+ || !owner || !isValidAid(owner) || consensus?.owner_aid !== owner || consensus.sub_aid !== selfAid
139
+ || !Number.isSafeInteger(version) || (version ?? 0) <= 0)
140
+ return undefined;
141
+ return { owner_aid: owner, target_agent_aid: selfAid, relation_version: version };
142
+ }
143
+ /** Consume the actual strict refresh result, never a transient shared fallback. */
144
+ export function verifiedContactBinding(selfAid, view) {
145
+ if (view.authorizationStatus !== 'verified' || view.refreshFailure?.fallbackUsed
146
+ || (view.validUntil !== undefined && view.validUntil <= Date.now()))
147
+ return undefined;
148
+ return consensusContactBinding(selfAid, view);
149
+ }
150
+ export function sameContactBinding(value, binding) {
151
+ return !!binding && value.owner_aid === binding.owner_aid
152
+ && value.target_agent_aid === binding.target_agent_aid && value.relation_version === binding.relation_version;
153
+ }
154
+ /** Existing protocol handlers must still authenticate each operation. Classification never grants rights. */
155
+ export function isContactControlPayload(payload) {
156
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
157
+ return false;
158
+ const value = payload;
159
+ const type = typeof value.type === 'string' ? value.type : '';
160
+ return type.startsWith('menu.') || type.startsWith('observer.') || type.startsWith('friend.')
161
+ || type === 'event' || type === 'bind.request' || type === 'bind.response' || type === 'ability' || type === 'error'
162
+ || (type === 'text' && typeof value.text === 'string' && /^\s*\/bind(?:\s|$)/i.test(value.text));
163
+ }
164
+ /** Synchronous transitions cannot interleave in one process; a lock excludes other daemons. */
165
+ function withContactStateLock(selfAid, name, action) {
166
+ const directory = contactAdmissionDirectory(selfAid);
167
+ fs.mkdirSync(directory, { recursive: true });
168
+ const file = path.join(directory, `${name}.lock`);
169
+ const token = crypto.randomUUID();
170
+ const identity = JSON.stringify({ pid: process.pid, host: os.hostname(), token });
171
+ let descriptor;
172
+ try {
173
+ descriptor = fs.openSync(file, 'wx', 0o600);
174
+ }
175
+ catch (error) {
176
+ if (error.code !== 'EEXIST')
177
+ throw error;
178
+ const raw = fs.readFileSync(file, 'utf8');
179
+ let previous;
180
+ try {
181
+ previous = JSON.parse(raw);
182
+ }
183
+ catch {
184
+ throw new Error('contact execution state is busy');
185
+ }
186
+ if (previous.host !== os.hostname() || !Number.isSafeInteger(previous.pid) || previous.pid <= 0 || isProcessRunning(previous.pid)
187
+ || fs.readFileSync(file, 'utf8') !== raw)
188
+ throw new Error('contact execution state is busy');
189
+ fs.unlinkSync(file);
190
+ descriptor = fs.openSync(file, 'wx', 0o600);
191
+ }
192
+ try {
193
+ fs.writeFileSync(descriptor, identity);
194
+ return action();
195
+ }
196
+ finally {
197
+ fs.closeSync(descriptor);
198
+ if (fs.readFileSync(file, 'utf8') === identity)
199
+ fs.unlinkSync(file);
200
+ }
201
+ }
202
+ /** The successful snapshot is read once; allow flags cannot bypass scope or denial. */
203
+ export function evaluateAppContactAdmission(selfAid, aid, now = Date.now()) {
204
+ if (!isValidAid(selfAid) || !isValidAid(aid))
205
+ return { allow: false, reason: 'unavailable' };
206
+ const binding = currentContactBinding(selfAid);
207
+ if (!binding)
208
+ return { allow: false, reason: 'unavailable' };
209
+ if (aid === binding.owner_aid)
210
+ return { allow: true, reason: 'owner' };
211
+ const policy = readAccessPolicy(selfAid);
212
+ const member = readOwnerDirectoryMembership(selfAid, aid, true);
213
+ if (!member || member.category === 'unavailable')
214
+ return { allow: false, reason: 'unavailable' };
215
+ if (member.blocked || policy.deniedAids?.includes(aid) || resolvePeerView(selfAid, aid).blocked) {
216
+ invalidateGrants(selfAid, binding, aid);
217
+ return { allow: false, reason: 'blocked' };
218
+ }
219
+ if (member.scopeExcluded) {
220
+ invalidateGrants(selfAid, binding, aid);
221
+ return { allow: false, reason: 'scope_extension' };
222
+ }
223
+ if (hasTemporaryContactGrant(selfAid, aid, binding, now))
224
+ return { allow: true, reason: 'temporary' };
225
+ if (member.entry)
226
+ return { allow: true, reason: 'contact' };
227
+ // 未命中名录的陌生人不属于内外部联系人,只接受总开关或单独授权。
228
+ if (policy.allowAllContacts || policy.allowedAids?.includes(aid)) {
229
+ return { allow: true, reason: 'open' };
230
+ }
231
+ return { allow: false, reason: 'not_in_contacts' };
232
+ }
233
+ /** No nested file/quote/merge, no executable fields disguised as a text. */
234
+ export function contactIntroductionText(payload) {
235
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
236
+ return undefined;
237
+ const value = payload;
238
+ if (value.type !== 'text' || typeof value.text !== 'string' || !value.text.trim())
239
+ return undefined;
240
+ if (['file', 'files', 'image', 'images', 'attachments', 'items', 'quote', 'url', 'action', 'actions'].some(key => key in value))
241
+ return undefined;
242
+ return value.text;
243
+ }
244
+ /** `eventKey` defaults to the source message; invite-driven requests pass the invite ID so retries share one event. */
245
+ export function buildContactRequest(binding, applicantAid, sourceMessageId, receivedAt, text, reason, eventKey) {
246
+ return withContactStateLock(binding.target_agent_aid, 'receipts', () => buildContactRequestLocked(binding, applicantAid, sourceMessageId, receivedAt, text, reason, eventKey ?? sourceMessageId));
247
+ }
248
+ function buildContactRequestLocked(binding, applicantAid, sourceMessageId, receivedAt, text, reason, eventKey) {
249
+ const eventId = 'friend-' + crypto.createHash('sha256').update(JSON.stringify([
250
+ binding.owner_aid, binding.target_agent_aid, binding.relation_version, applicantAid, eventKey,
251
+ ])).digest('hex');
252
+ // Transport receipt metadata only: no introduction or App request state.
253
+ const receiptPath = path.join(contactAdmissionDirectory(binding.target_agent_aid), 'contact-event-receipts.json');
254
+ const raw = readState(receiptPath);
255
+ const receipts = raw ? JSON.parse(raw) : {};
256
+ const digest = crypto.createHash('sha256').update(text).digest('hex');
257
+ const previous = receipts[eventId];
258
+ if (previous && previous.digest !== digest)
259
+ throw new Error('contact source message identity conflict');
260
+ if (previous) {
261
+ receivedAt = previous.at;
262
+ reason = previous.reason ?? reason;
263
+ }
264
+ else {
265
+ // Never forget a source ID and later turn a historical replay into a fresh introduction.
266
+ if (Object.keys(receipts).length >= 10000)
267
+ throw new Error('contact event receipt capacity reached');
268
+ receipts[eventId] = { at: receivedAt, digest, reason };
269
+ atomicWriteJson(receiptPath, receipts);
270
+ }
271
+ return { type: 'friend.request.v1', schema_version: 1, ...binding, event_id: eventId,
272
+ applicant_aid: applicantAid, source_message_id: sourceMessageId, received_at_ms: receivedAt,
273
+ reason, introduction: { payload_type: 'text', text } };
274
+ }
275
+ // Rate limiting is transport protection, independent of App rejection/cooldown state.
276
+ const introductionBuckets = new Map();
277
+ export function consumeContactIntroductionBudget(selfAid, aid, now = Date.now()) {
278
+ const policy = readAccessPolicy(selfAid);
279
+ const window = policy.requestLimit.coolDown * 1000;
280
+ const keys = [`${selfAid}:all`, `${selfAid}:${aid}`];
281
+ // App owns the rolling three introductions; transport must allow a fourth to replace the oldest.
282
+ const limits = [policy.requestLimit.maxTimes, policy.requestLimit.maxTimes];
283
+ const buckets = keys.map(key => {
284
+ const old = introductionBuckets.get(key);
285
+ return old && now - old.start < window ? old : { start: now, count: 0 };
286
+ });
287
+ if (buckets.some((bucket, i) => bucket.count >= limits[i]))
288
+ return false;
289
+ for (let i = 0; i < keys.length; i++)
290
+ introductionBuckets.set(keys[i], { start: buckets[i].start, count: buckets[i].count + 1 });
291
+ // Bounded metadata; do not accumulate identities from rejected floods.
292
+ if (introductionBuckets.size > 4096) {
293
+ for (const [key, bucket] of introductionBuckets)
294
+ if (now - bucket.start >= window)
295
+ introductionBuckets.delete(key);
296
+ while (introductionBuckets.size > 4096)
297
+ introductionBuckets.delete(introductionBuckets.keys().next().value);
298
+ }
299
+ return true;
300
+ }
301
+ function grantPath(selfAid) { return path.join(contactAdmissionDirectory(selfAid), 'temporary-contact-grants.json'); }
302
+ function readGrants(selfAid) {
303
+ const raw = readState(grantPath(selfAid));
304
+ if (!raw)
305
+ return {};
306
+ const parsed = JSON.parse(raw);
307
+ if (parsed.schema_version !== 1 || !Array.isArray(parsed.records))
308
+ throw new Error('invalid temporary contact grant store');
309
+ return Object.fromEntries(parsed.records.map((record) => [grantKey(record.command), record]));
310
+ }
311
+ function grantKey(command) {
312
+ return JSON.stringify([command.owner_aid, command.target_agent_aid, command.relation_version, command.grant_id]);
313
+ }
314
+ function writeGrants(selfAid, records) {
315
+ atomicWriteJson(grantPath(selfAid), { schema_version: 1, records: Object.values(records) });
316
+ }
317
+ function hasTemporaryContactGrant(selfAid, aid, binding, now) {
318
+ return Object.values(readGrants(selfAid)).some(record => sameContactBinding(record.command, binding)
319
+ && record.command.applicant_aid === aid && !record.revoked && record.result.status === 'applied'
320
+ && record.result.granted_at_ms <= now && record.result.expires_at_ms > now);
321
+ }
322
+ function invalidateGrants(selfAid, binding, aid) {
323
+ withContactStateLock(selfAid, 'grants', () => invalidateGrantsLocked(selfAid, binding, aid));
324
+ }
325
+ function invalidateGrantsLocked(selfAid, binding, aid) {
326
+ const records = readGrants(selfAid);
327
+ let changed = false;
328
+ for (const record of Object.values(records)) {
329
+ if (sameContactBinding(record.command, binding) && record.command.applicant_aid === aid && !record.revoked) {
330
+ record.revoked = true;
331
+ changed = true;
332
+ }
333
+ }
334
+ if (changed)
335
+ writeGrants(selfAid, records);
336
+ }
337
+ /** A subsequently removed denial must not revive an earlier temporary grant. */
338
+ export function reconcileTemporaryContactGrants(selfAid, snapshot) {
339
+ withContactStateLock(selfAid, 'grants', () => reconcileGrantsLocked(selfAid, snapshot));
340
+ }
341
+ function reconcileGrantsLocked(selfAid, snapshot) {
342
+ const records = readGrants(selfAid);
343
+ let changed = false;
344
+ for (const record of Object.values(records)) {
345
+ const entry = snapshot.entries.find(value => value.aid === record.command.applicant_aid);
346
+ if (!record.revoked && (record.command.owner_aid !== snapshot.ownerAid
347
+ || record.command.relation_version !== snapshot.relationVersion
348
+ || snapshot.blockedAids?.includes(record.command.applicant_aid)
349
+ || (entry?.agent_scope?.mode === 'selected' && !entry.agent_scope.agent_aids.includes(selfAid)))) {
350
+ record.revoked = true;
351
+ changed = true;
352
+ }
353
+ }
354
+ if (changed)
355
+ writeGrants(selfAid, records);
356
+ }
357
+ /** Only authenticated E2EE Owner commands reach the state mutation. No App approval state is stored. */
358
+ export function executeContactGrant(selfAid, senderAid, payload, encrypted, now = Date.now(), binding = currentContactBinding(selfAid)) {
359
+ if (!binding || !sameContactBinding(binding, currentContactBinding(selfAid)))
360
+ return undefined;
361
+ return withContactStateLock(selfAid, 'grants', () => executeContactGrantLocked(selfAid, senderAid, payload, encrypted, now, binding));
362
+ }
363
+ function executeContactGrantLocked(selfAid, senderAid, payload, encrypted, now, binding) {
364
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
365
+ return undefined;
366
+ const command = payload;
367
+ const revoke = command.type === 'friend.grant.revoke.v1';
368
+ if (command.type !== 'friend.grant.v1' && !revoke)
369
+ return undefined;
370
+ // Never respond to unauthenticated callers or reflect arbitrary payload addresses.
371
+ if (!encrypted || !sameContactBinding(binding, currentContactBinding(selfAid)) || senderAid !== binding.owner_aid)
372
+ return undefined;
373
+ const base = { type: revoke ? 'friend.grant.revoke.result.v1' : 'friend.grant.result.v1', schema_version: 1,
374
+ ...binding, applicant_aid: command.applicant_aid, grant_id: command.grant_id,
375
+ granted_at_ms: null, expires_at_ms: null };
376
+ const reject = (error) => ({ ...base, status: 'rejected', error_code: error });
377
+ if (!sameContactBinding(command, binding))
378
+ return reject('ownership_changed');
379
+ if (command.schema_version !== 1 || typeof command.grant_id !== 'string'
380
+ || !/^[a-zA-Z0-9_.:-]{1,256}$/.test(command.grant_id) || !isValidAid(command.applicant_aid))
381
+ return reject('invalid_payload');
382
+ const records = readGrants(selfAid);
383
+ const key = grantKey(command);
384
+ const previous = records[key];
385
+ if (previous && previous.command.applicant_aid !== command.applicant_aid)
386
+ return reject('idempotency_conflict');
387
+ if (revoke) {
388
+ if (!previous && Object.keys(records).length >= 10000)
389
+ return reject('grant_capacity');
390
+ records[key] = previous ? { ...previous, revoked: true } : { command: { ...command }, result: {}, revoked: true };
391
+ writeGrants(selfAid, records);
392
+ return { ...base, status: 'revoked', error_code: null };
393
+ }
394
+ if (command.duration_seconds !== 1800 || !Number.isSafeInteger(command.activate_before_ms))
395
+ return reject('invalid_payload');
396
+ if (previous?.revoked)
397
+ return reject('revoked');
398
+ if (previous) {
399
+ if (previous.command.duration_seconds !== command.duration_seconds || previous.command.activate_before_ms !== command.activate_before_ms)
400
+ return reject('idempotency_conflict');
401
+ return previous.result;
402
+ }
403
+ let result;
404
+ const member = readOwnerDirectoryMembership(selfAid, command.applicant_aid, true);
405
+ const policy = readAccessPolicy(selfAid);
406
+ if (command.activate_before_ms <= now)
407
+ result = reject('activation_expired');
408
+ else if (!member || member.category === 'unavailable')
409
+ return reject('directory_unavailable');
410
+ else if (member.blocked || policy.deniedAids?.includes(command.applicant_aid) || resolvePeerView(selfAid, command.applicant_aid).blocked)
411
+ result = reject('blocked');
412
+ else if (member.scopeExcluded)
413
+ result = reject('scope_excluded');
414
+ else
415
+ result = { ...base, status: 'applied', granted_at_ms: now, expires_at_ms: now + GRANT_DURATION_MS, error_code: null };
416
+ // Keep bounded durable metadata; never evict a revocation or reuse a grant ID to activate again.
417
+ if (Object.keys(records).length >= 10000)
418
+ return reject('grant_capacity');
419
+ records[key] = { command: { ...command }, result };
420
+ writeGrants(selfAid, records);
421
+ return result;
422
+ }
423
+ // ---------------------------------------------------------------------------
424
+ // friend.invite.v1:App 主动添加联系人(evol_app 契约 08 统一好友申请)。
425
+ // 按 Owner 配置的准入策略已放行的申请人由本 Agent 直接回 accepted 并发一条欢迎语,
426
+ // 不转交 Owner;其余按契约转成带原 invite 的 friend.request.v1 交 Owner 决定。
427
+ // 决定按「关系版本 + invite_id」持久化:重投只重发原结果,欢迎语只发一次。
428
+ // ---------------------------------------------------------------------------
429
+ export const FRIEND_INVITE_TYPE = 'friend.invite.v1';
430
+ export const FRIEND_INVITE_RESULT_TYPE = 'friend.invite.result.v1';
431
+ /** Contract 08: expires_at_ms must equal created_at_ms + three days exactly. */
432
+ export const FRIEND_INVITE_TTL_MS = 3 * 24 * 60 * 60 * 1000;
433
+ const MAX_FRIEND_INVITE_DECISIONS = 10000;
434
+ export function isFriendInvitePayload(payload) {
435
+ return !!payload && typeof payload === 'object' && !Array.isArray(payload) && payload.type === FRIEND_INVITE_TYPE;
436
+ }
437
+ /** The authenticated envelope decides identity; payload AIDs must match it exactly. */
438
+ export function parseFriendInvite(payload, senderAid, selfAid) {
439
+ if (!isFriendInvitePayload(payload))
440
+ return undefined;
441
+ const value = payload;
442
+ if (value.schema_version !== 1)
443
+ return undefined;
444
+ if (typeof value.invite_id !== 'string' || !/^[a-zA-Z0-9_.:-]{1,256}$/.test(value.invite_id))
445
+ return undefined;
446
+ if (!isValidAid(senderAid) || !isValidAid(selfAid) || senderAid === selfAid
447
+ || value.applicant_aid !== senderAid || value.target_aid !== selfAid)
448
+ return undefined;
449
+ if (!Number.isSafeInteger(value.created_at_ms) || value.created_at_ms <= 0
450
+ || value.expires_at_ms !== value.created_at_ms + FRIEND_INVITE_TTL_MS)
451
+ return undefined;
452
+ if (typeof value.introduction !== 'string' || !value.introduction.trim())
453
+ return undefined;
454
+ return { invite_id: value.invite_id, applicant_aid: senderAid, target_aid: selfAid,
455
+ created_at_ms: value.created_at_ms, expires_at_ms: value.expires_at_ms, introduction: value.introduction };
456
+ }
457
+ export function friendInviteDigest(invite) {
458
+ return crypto.createHash('sha256').update(JSON.stringify([
459
+ invite.applicant_aid, invite.target_aid, invite.created_at_ms, invite.expires_at_ms, invite.introduction,
460
+ ])).digest('hex');
461
+ }
462
+ function inviteDecisionPath(selfAid) { return path.join(contactAdmissionDirectory(selfAid), 'friend-invite-decisions.json'); }
463
+ function inviteDecisionKey(binding, inviteId) {
464
+ return JSON.stringify([binding.owner_aid, binding.target_agent_aid, binding.relation_version, inviteId]);
465
+ }
466
+ function readInviteDecisions(selfAid) {
467
+ const raw = readState(inviteDecisionPath(selfAid));
468
+ if (!raw)
469
+ return {};
470
+ const parsed = JSON.parse(raw);
471
+ if (parsed.schema_version !== 1 || !parsed.records || typeof parsed.records !== 'object' || Array.isArray(parsed.records)) {
472
+ throw new Error('invalid friend invite decision store');
473
+ }
474
+ return parsed.records;
475
+ }
476
+ function writeInviteDecisions(selfAid, records) {
477
+ atomicWriteJson(inviteDecisionPath(selfAid), { schema_version: 1, records });
478
+ }
479
+ /** A decision belongs to one Owner relation; the same invite ID with a different body is a conflict, never a replacement. */
480
+ export function recordedFriendInviteDecision(selfAid, binding, invite) {
481
+ const previous = readInviteDecisions(selfAid)[inviteDecisionKey(binding, invite.invite_id)];
482
+ if (!previous)
483
+ return { conflict: false };
484
+ return previous.digest === friendInviteDigest(invite) ? { decision: previous, conflict: false } : { conflict: true };
485
+ }
486
+ export function decideFriendInvite(selfAid, binding, invite, status, now = Date.now()) {
487
+ return withContactStateLock(selfAid, 'invites', () => {
488
+ const records = readInviteDecisions(selfAid);
489
+ const key = inviteDecisionKey(binding, invite.invite_id);
490
+ const digest = friendInviteDigest(invite);
491
+ const previous = records[key];
492
+ if (previous) {
493
+ if (previous.digest !== digest)
494
+ throw new Error('friend invite identity conflict');
495
+ return previous;
496
+ }
497
+ if (Object.keys(records).length >= MAX_FRIEND_INVITE_DECISIONS) {
498
+ // Only invites past their own protocol expiry may be forgotten; a live decision is never evicted.
499
+ for (const [name, record] of Object.entries(records))
500
+ if (record.expires_at_ms <= now)
501
+ delete records[name];
502
+ if (Object.keys(records).length >= MAX_FRIEND_INVITE_DECISIONS)
503
+ throw new Error('friend invite decision capacity reached');
504
+ }
505
+ const decision = {
506
+ invite_id: invite.invite_id, applicant_aid: invite.applicant_aid, digest, status,
507
+ decision_id: 'friend-decision-' + crypto.createHash('sha256').update(JSON.stringify([
508
+ binding.owner_aid, binding.target_agent_aid, binding.relation_version, invite.invite_id,
509
+ ])).digest('hex'),
510
+ decided_at_ms: now, relation_version: binding.relation_version, expires_at_ms: invite.expires_at_ms,
511
+ };
512
+ records[key] = decision;
513
+ writeInviteDecisions(selfAid, records);
514
+ return decision;
515
+ });
516
+ }
517
+ export function markFriendInviteWelcomed(selfAid, binding, inviteId) {
518
+ withContactStateLock(selfAid, 'invites', () => {
519
+ const records = readInviteDecisions(selfAid);
520
+ const key = inviteDecisionKey(binding, inviteId);
521
+ const record = records[key];
522
+ if (!record || record.welcomed)
523
+ return;
524
+ records[key] = { ...record, welcomed: true };
525
+ writeInviteDecisions(selfAid, records);
526
+ });
527
+ }
528
+ /** responder_aid is this Agent: acceptance follows the Owner's configured policy rather than an Owner decision. */
529
+ export function buildFriendInviteResult(selfAid, invite, decision) {
530
+ return { type: FRIEND_INVITE_RESULT_TYPE, schema_version: 1, invite_id: invite.invite_id,
531
+ applicant_aid: invite.applicant_aid, target_aid: selfAid, responder_aid: selfAid, status: decision.status,
532
+ decision_id: decision.decision_id, decided_at_ms: decision.decided_at_ms, relation_version: decision.relation_version };
533
+ }
534
+ /** friend.* transport routes: requests and grant results go to the Owner; an invite result goes back to its applicant. */
535
+ export function friendPayloadRouteValid(payload, to, encrypt, binding) {
536
+ if (encrypt !== true)
537
+ return false;
538
+ if (payload.type === FRIEND_INVITE_RESULT_TYPE) {
539
+ return payload.target_aid === binding.target_agent_aid && payload.responder_aid === binding.target_agent_aid
540
+ && payload.relation_version === binding.relation_version && isValidAid(payload.applicant_aid) && to === payload.applicant_aid;
541
+ }
542
+ return sameContactBinding(payload, binding) && to === binding.owner_aid;
543
+ }
544
+ /** Fixed template; no model turn and no applicant-controlled text is echoed back. */
545
+ export function friendInviteWelcomeText(agentName, selfAid) {
546
+ const name = agentName?.trim() || selfAid;
547
+ return `你好,我是 ${name}。已通过你的好友申请,现在可以直接给我发消息。`;
548
+ }