evolcore 0.0.41-test.2 → 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 +38 -2
  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
@@ -1,235 +0,0 @@
1
- import fs from 'fs';
2
- import { isValidAid } from '../aun/aid/validation.js';
3
- import { agentConfig } from '../paths.js';
4
- import { getContactSnapshot, resolveContactView } from './contact-book.js';
5
- import { ContactMutationError } from './contact-book-store.js';
6
- import { addContact, mutateContactWithOperation } from './contact-request-service.js';
7
- import { expirePendingContactRequests, reviewContactRequest } from './contact-request-service.js';
8
- import { listStaticAgentOwners } from './peer-role-resolver.js';
9
- export function resolveContactCommand(argv) {
10
- const args = argv[0] === 'contact' ? argv.slice(1) : [...argv];
11
- const selfAid = String(argValue(args, '--self') || '').trim();
12
- if (!isValidAid(selfAid))
13
- return invalid('INVALID_SELF', '--self must be a valid Agent AID');
14
- const positional = stripOptions(args);
15
- const [command, subcommand, ...extra] = positional;
16
- if (extra.length > 0)
17
- return invalid('INVALID_ARGUMENT', `Unexpected contact arguments: ${extra.join(' ')}`);
18
- if (command === 'list') {
19
- if (subcommand !== undefined) {
20
- return invalid('INVALID_ARGUMENT', 'contact list does not accept a positional argument');
21
- }
22
- const filter = args.includes('--blocked')
23
- ? 'blocked'
24
- : args.includes('--pending')
25
- ? 'pending'
26
- : args.includes('--all') ? 'all' : undefined;
27
- if (!filter)
28
- return invalid('INVALID_ARGUMENT', 'contact list requires --blocked, --pending, or --all');
29
- return {
30
- ok: true,
31
- command: { kind: 'list-blocked', operationId: 'contact.read', selfAid, filter, canonicalArgv: canonicalArgv(argv) },
32
- };
33
- }
34
- if (command === 'approve' || command === 'reject' || command === 'block-request') {
35
- if (!isValidAid(subcommand || '')) {
36
- return invalid('INVALID_AID', 'primaryId must be a valid individual AID');
37
- }
38
- const requestId = String(argValue(args, '--request-id') || '').trim();
39
- if (!requestId)
40
- return invalid('INVALID_ARGUMENT', `${command} requires --request-id <request-id>`);
41
- const expectedContactRevision = argValue(args, '--contact-revision')?.trim() || undefined;
42
- return {
43
- ok: true,
44
- command: {
45
- kind: 'review-request',
46
- operationId: 'contact.review',
47
- selfAid,
48
- primaryId: subcommand,
49
- requestId,
50
- decision: command === 'approve' ? 'approve' : command === 'reject' ? 'reject' : 'block',
51
- expectedContactRevision,
52
- canonicalArgv: canonicalArgv(argv),
53
- },
54
- };
55
- }
56
- if (command === 'block' || command === 'unblock') {
57
- if (!isValidAid(subcommand || '')) {
58
- return invalid('INVALID_AID', 'primaryId must be a valid individual AID');
59
- }
60
- return {
61
- ok: true,
62
- command: {
63
- kind: 'set-blocked',
64
- operationId: 'contact.block',
65
- selfAid,
66
- primaryId: subcommand,
67
- blocked: command === 'block',
68
- canonicalArgv: canonicalArgv(argv),
69
- },
70
- };
71
- }
72
- if (command === 'add') {
73
- if (!isValidAid(subcommand || '')) {
74
- return invalid('INVALID_AID', 'primaryId must be a valid individual AID');
75
- }
76
- return {
77
- ok: true,
78
- command: {
79
- kind: 'add',
80
- operationId: 'contact.add',
81
- selfAid,
82
- primaryId: subcommand,
83
- canonicalArgv: canonicalArgv(argv),
84
- },
85
- };
86
- }
87
- return invalid('UNKNOWN_COMMAND', `Unknown contact command: ${positional.join(' ')}`);
88
- }
89
- export async function executeResolvedContactCommand(command, actor = 'local-cli') {
90
- if (!fs.existsSync(agentConfig(command.selfAid))) {
91
- return { ok: false, code: 'AGENT_NOT_FOUND', error: `Agent does not exist: ${command.selfAid}` };
92
- }
93
- try {
94
- if (command.kind === 'list-blocked') {
95
- await expirePendingContactRequests(command.selfAid);
96
- const snapshot = getContactSnapshot(command.selfAid);
97
- const ids = command.filter === 'blocked'
98
- ? [...snapshot.blockedIndex]
99
- : [...snapshot.contacts.entries()]
100
- .filter(([, entry]) => command.filter === 'all' || entry.status === 'pending')
101
- .map(([id]) => id);
102
- const items = ids.sort().map(id => contactItem(command.selfAid, id));
103
- if (command.filter === 'blocked') {
104
- return {
105
- ok: true,
106
- operation: 'list-blocked',
107
- selfAid: command.selfAid,
108
- contactRevision: snapshot.contactRevision,
109
- items,
110
- };
111
- }
112
- return {
113
- ok: true,
114
- operation: 'list-contacts',
115
- selfAid: command.selfAid,
116
- filter: command.filter,
117
- contactRevision: snapshot.contactRevision,
118
- items,
119
- };
120
- }
121
- if (command.kind === 'review-request') {
122
- const expectedContactRevision = command.expectedContactRevision ?? getContactSnapshot(command.selfAid).contactRevision;
123
- const reviewerAid = actor === 'local-cli'
124
- ? listStaticAgentOwners(command.selfAid)[0]
125
- : actor;
126
- if (!reviewerAid) {
127
- return { ok: false, code: 'NO_OWNER', error: `Agent has no owner: ${command.selfAid}` };
128
- }
129
- const reviewed = await reviewContactRequest({
130
- selfAid: command.selfAid,
131
- primaryId: command.primaryId,
132
- requestId: command.requestId,
133
- expectedContactRevision,
134
- approverId: reviewerAid,
135
- actorId: reviewerAid,
136
- decision: command.decision,
137
- });
138
- if (reviewed.code !== 'approved' && reviewed.code !== 'rejected' && reviewed.code !== 'blocked') {
139
- const code = reviewed.code === 'request-expired' ? 'REQUEST_EXPIRED'
140
- : reviewed.code === 'revision-conflict' ? 'CONFLICT'
141
- : reviewed.code === 'forbidden' ? 'PERMISSION_DENIED' : 'REQUEST_STALE';
142
- return { ok: false, code, error: reviewed.code, data: { contactRevision: reviewed.contactRevision } };
143
- }
144
- return {
145
- ok: true,
146
- operation: 'review-request',
147
- selfAid: command.selfAid,
148
- primaryId: command.primaryId,
149
- requestId: command.requestId,
150
- result: reviewed.code,
151
- contactRevision: reviewed.contactRevision,
152
- };
153
- }
154
- if (command.kind === 'set-blocked') {
155
- if (!getContactSnapshot(command.selfAid).contacts.has(command.primaryId)) {
156
- return { ok: false, code: 'NOT_FOUND', error: `Contact was not found: ${command.primaryId}` };
157
- }
158
- const result = await mutateContactWithOperation({
159
- selfAid: command.selfAid,
160
- actorId: actor,
161
- operation: command.blocked ? 'block' : 'unblock',
162
- primaryId: command.primaryId,
163
- mutation: {
164
- type: 'set-status',
165
- primaryId: command.primaryId,
166
- status: command.blocked ? 'blocked' : 'active',
167
- },
168
- });
169
- return {
170
- ok: true,
171
- operation: 'set-blocked',
172
- selfAid: command.selfAid,
173
- primaryId: command.primaryId,
174
- blocked: command.blocked,
175
- changed: result.changed,
176
- contactRevision: result.contactRevision,
177
- };
178
- }
179
- if (command.kind === 'add') {
180
- const result = await addContact({
181
- selfAid: command.selfAid,
182
- primaryId: command.primaryId,
183
- actorId: actor,
184
- });
185
- return {
186
- ok: true,
187
- operation: 'add',
188
- selfAid: command.selfAid,
189
- primaryId: command.primaryId,
190
- status: 'active',
191
- changed: result.changed,
192
- contactRevision: result.contactRevision,
193
- };
194
- }
195
- return { ok: false, code: 'CONTACT_OPERATION_FAILED', error: 'Unsupported contact operation' };
196
- }
197
- catch (error) {
198
- if (error instanceof ContactMutationError) {
199
- return { ok: false, code: error.code, error: error.message, ...(error.data ? { data: error.data } : {}) };
200
- }
201
- return { ok: false, code: 'CONTACT_OPERATION_FAILED', error: error instanceof Error ? error.message : String(error) };
202
- }
203
- }
204
- function argValue(args, flag) {
205
- const index = args.indexOf(flag);
206
- return index >= 0 ? args[index + 1] : undefined;
207
- }
208
- function stripOptions(args) {
209
- const result = [];
210
- for (let index = 0; index < args.length; index += 1) {
211
- const arg = args[index];
212
- if (arg === '--self' || arg === '--format' || arg === '--request-id' || arg === '--contact-revision') {
213
- index += 1;
214
- continue;
215
- }
216
- if (arg === '--blocked' || arg === '--pending' || arg === '--all')
217
- continue;
218
- result.push(arg);
219
- }
220
- return result;
221
- }
222
- function contactItem(selfAid, primaryId) {
223
- const view = resolveContactView(selfAid, primaryId);
224
- const entry = getContactSnapshot(selfAid).contacts.get(primaryId);
225
- return {
226
- ...view,
227
- ...(entry?.pendingRequest ? { pendingRequest: { ...entry.pendingRequest } } : {}),
228
- };
229
- }
230
- function canonicalArgv(argv) {
231
- return argv[0] === 'contact' ? [...argv] : ['contact', ...argv];
232
- }
233
- function invalid(code, reason) {
234
- return { ok: false, code, reason };
235
- }
@@ -1,309 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { randomUUID } from 'node:crypto';
4
- import Ajv from 'ajv';
5
- import { readAuthoritativePersonalFsObject } from '../aun/group/fs-download.js';
6
- import { atomicReadJson, atomicWriteJson } from '../utils/atomic-write.js';
7
- import { getAunRequestRegistry } from '../core/message/aun-request-registry.js';
8
- import { parseOwnerDirectoryGrantAbilityResponse } from './owner-directory-cache.js';
9
- import { logger } from '../utils/logger.js';
10
- const ABILITY_PATH = 'directory/access';
11
- const DEFINITION_ID = 'evol-directory-access-v1';
12
- const REQUEST_TTL_SECONDS = 60;
13
- const REQUEST_PARAMS = {
14
- action: 'request', scopes: ['agents'], valid_for_seconds: 2_592_000,
15
- purpose: '同步 Owner 的 Agent 名录,识别并联系同属 Owner 的 Agent',
16
- };
17
- /** Startup/Owner-message retries, with a durable stop only for a correlated Owner refusal. */
18
- export class OwnerDirectoryAuthorization {
19
- options;
20
- inFlight;
21
- retryTimer;
22
- registry;
23
- now;
24
- constructor(options) {
25
- this.options = options;
26
- this.registry = options.registry ?? getAunRequestRegistry();
27
- this.now = options.now ?? Date.now;
28
- }
29
- ensureAuthorization() {
30
- if (this.inFlight) {
31
- logger.debug(`[OwnerDirectory] Authorization request already in flight for ${this.options.selfAid} -> ${this.options.ownerAid}`);
32
- return this.inFlight;
33
- }
34
- logger.info(`[OwnerDirectory] Starting authorization check: selfAid=${this.options.selfAid}, Owner=${this.options.ownerAid}`);
35
- const task = this.requestIfNeeded().finally(() => {
36
- if (this.inFlight === task)
37
- this.inFlight = undefined;
38
- });
39
- this.inFlight = task;
40
- return task;
41
- }
42
- dispose() {
43
- if (this.retryTimer)
44
- clearTimeout(this.retryTimer);
45
- this.retryTimer = undefined;
46
- }
47
- scheduleCheck(at) {
48
- this.dispose();
49
- this.retryTimer = setTimeout(() => {
50
- this.retryTimer = undefined;
51
- if (!this.options.isCurrent())
52
- return;
53
- void this.ensureAuthorization().catch(() => {
54
- if (this.options.isCurrent())
55
- this.scheduleCheck(this.now() + 5_000);
56
- });
57
- }, Math.max(1, at - this.now()));
58
- this.retryTimer.unref();
59
- }
60
- ownsRequest(record) {
61
- return record.selfAid === this.options.selfAid && record.targetAid === this.options.ownerAid
62
- && record.requestId.startsWith('owner-directory-auto-');
63
- }
64
- /** Called only after the channel refreshes Ownership and the registry verifies the sender/device. */
65
- async acceptResponse(record) {
66
- const attempt = this.readAttempt();
67
- const response = record.responsePayload;
68
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Received authorization response from ${record.targetAid}, state: ${record.state}, hasAttempt=${!!attempt}, hasResponse=${!!response}`);
69
- if (response) {
70
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Response payload summary: type=${response.type}, role=${response.role}, ok=${response.ok}, ability_path=${response.ability_path}, definition_id=${response.definition_id}, call_id=${response.call_id}, operation_id=${response.operation_id}, error=${JSON.stringify(response.error)}`);
71
- }
72
- if (!this.options.isCurrent()) {
73
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - connection no longer current`);
74
- return;
75
- }
76
- if (!attempt) {
77
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - no local attempt on disk`);
78
- return;
79
- }
80
- if (!this.ownsRequest(record)) {
81
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - record not owned by this attempt (requestId=${record.requestId}, selfAid=${record.selfAid}, targetAid=${record.targetAid})`);
82
- return;
83
- }
84
- if (record.state !== 'completed') {
85
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - record.state=${record.state} (not completed)`);
86
- return;
87
- }
88
- if (!record.targetDeviceId || record.responseDeviceId !== record.targetDeviceId) {
89
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - device mismatch: target=${record.targetDeviceId}, response=${record.responseDeviceId}`);
90
- return;
91
- }
92
- if (!response || response.type !== 'ability' || response.role !== 'result'
93
- || response.call_id !== record.requestId || response.operation_id !== attempt.operationId
94
- || response.ability_path !== ABILITY_PATH || response.definition_id !== DEFINITION_ID) {
95
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: acceptResponse skipped - response validation failed. matches: type=${response?.type === 'ability'}, role=${response?.role === 'result'}, call_id=${response?.call_id === record.requestId}, operation_id=${response?.operation_id === attempt.operationId}, ability_path=${response?.ability_path === ABILITY_PATH}, definition_id=${response?.definition_id === DEFINITION_ID}`);
96
- return;
97
- }
98
- // An absent grant, an ACK, a timeout or a storage/transport error is not an Owner refusal.
99
- if (response.ok === false && isRecord(response.error)
100
- && ['user_denied', 'permission_denied'].includes(String(response.error.code))) {
101
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: Authorization explicitly denied by Owner: ${response.error.code}, message=${response.error.message}`);
102
- this.dispose();
103
- this.writeAttempt({ ...attempt, status: 'denied' });
104
- return;
105
- }
106
- if (response.ok === false) {
107
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: Authorization request failed (retryable): ${JSON.stringify(response.error)}`);
108
- this.writeAttempt({ ...attempt, status: 'retryable' });
109
- if (attempt.action === 'status')
110
- this.scheduleCheck(this.now() + 5_000);
111
- return;
112
- }
113
- const grant = parseOwnerDirectoryGrantAbilityResponse(response);
114
- if (!grant || grant.owner_aid !== this.options.ownerAid || grant.grantee_aid !== this.options.selfAid) {
115
- logger.warn(`[OwnerDirectory] Authorization response validation failed or identity mismatch`);
116
- return;
117
- }
118
- logger.info(`[OwnerDirectory] Received valid authorization grant: status=${grant.status}, scopes=${JSON.stringify(grant.active_scopes)}`);
119
- this.options.cache.saveAuthorization(grant);
120
- const result = response.result;
121
- if (this.options.cache.scopeAccess('agents') !== 'authorized' && isRecord(result)
122
- && result.status === 'sync_pending' && ['initializing', 'syncing'].includes(String(result.readiness))
123
- && isRecord(result.retry_request) && result.retry_request.action === 'status') {
124
- const hint = result.retry_after_seconds;
125
- const delay = typeof hint === 'number' && Number.isFinite(hint) ? Math.min(300, Math.max(1, hint)) : 5;
126
- const retryAt = this.now() + Math.ceil(delay * 1_000);
127
- logger.info(`[OwnerDirectory] Owner directory is ${result.readiness}, will check status in ${delay}s`);
128
- this.writeAttempt({ ...attempt, status: 'initializing', action: 'status', retryAt });
129
- this.scheduleCheck(retryAt);
130
- return;
131
- }
132
- this.dispose();
133
- const finalStatus = this.options.cache.scopeAccess('agents') === 'authorized' ? 'granted' : 'retryable';
134
- logger.info(`[OwnerDirectory] Authorization completed with status: ${finalStatus}`);
135
- this.writeAttempt({ ...attempt, action: 'request', retryAt: undefined, status: finalStatus });
136
- logger.info(`[OwnerDirectory] Triggering directory cache refresh after authorization`);
137
- await this.options.cache.handleOwnerChangedEvent(this.options.ownerAid);
138
- }
139
- async requestIfNeeded() {
140
- if (!this.options.isCurrent()) {
141
- logger.debug(`[OwnerDirectory] Authorization check skipped - connection no longer current for ${this.options.selfAid}`);
142
- return;
143
- }
144
- let previous = this.readAttempt();
145
- const scopeAccess = this.options.cache.scopeAccess('agents');
146
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Scope 'agents' access status: ${scopeAccess}, previous status: ${previous?.status || 'none'}`);
147
- if (scopeAccess === 'authorized') {
148
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Already authorized for Owner ${this.options.ownerAid}, skipping request`);
149
- this.dispose();
150
- // A later valid grant supersedes an earlier refusal, including grants requested manually.
151
- if (previous?.status === 'denied')
152
- this.writeAttempt({ ...previous, status: 'granted' });
153
- return;
154
- }
155
- if (previous?.status === 'denied') {
156
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: Authorization previously denied by Owner ${this.options.ownerAid}, not retrying`);
157
- this.dispose();
158
- return;
159
- }
160
- if (previous?.status === 'pending') {
161
- const record = this.registry.get(this.options.selfAid, previous.callId);
162
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: found pending attempt, callId=${previous.callId.slice(0, 24)}..., record=${record ? `state=${record.state}` : 'not found'}, deadlineAt=${new Date(previous.deadlineAt).toISOString()}, expired=${previous.deadlineAt <= this.now()}`);
163
- if (record?.state === 'completed') {
164
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: processing completed record`);
165
- await this.acceptResponse(record);
166
- previous = this.readAttempt();
167
- if (previous?.status === 'denied' || this.options.cache.scopeAccess('agents') === 'authorized')
168
- return;
169
- }
170
- else if (previous.deadlineAt > this.now() && record && !['failed', 'unknown'].includes(record.state)) {
171
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: pending request still within deadline, skipping (record.state=${record.state})`);
172
- return;
173
- }
174
- else {
175
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: pending request expired or failed, will retry (record=${record ? `state=${record.state}` : 'not found'})`);
176
- }
177
- }
178
- if (previous?.status === 'initializing' && (previous.retryAt ?? 0) > this.now()) {
179
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: initializing, retryAt=${new Date(previous.retryAt).toISOString()}, waiting`);
180
- this.scheduleCheck(previous.retryAt);
181
- return;
182
- }
183
- const action = previous?.action === 'status' ? 'status' : 'request';
184
- const params = action === 'status' ? { action: 'status' } : REQUEST_PARAMS;
185
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Discovering device for Owner ${this.options.ownerAid}, action: ${action}`);
186
- let deviceId;
187
- try {
188
- deviceId = await this.discoverDevice(previous?.deviceId, params);
189
- }
190
- catch (error) {
191
- logger.warn(`[OwnerDirectory] Agent ${this.options.selfAid}: Device discovery failed: ${error instanceof Error ? error.message : String(error)}`);
192
- throw error;
193
- }
194
- logger.info(`[OwnerDirectory] Agent ${this.options.selfAid}: Selected device: ${deviceId}`);
195
- if (!this.options.isCurrent() || this.options.cache.scopeAccess('agents') === 'authorized'
196
- || this.readAttempt()?.status === 'denied')
197
- return;
198
- // Retain the logical operation across unanswered attempts for Provider idempotency.
199
- const operationId = previous?.status === 'pending' ? previous.operationId : `directory-${randomUUID()}`;
200
- const callId = `owner-directory-auto-${randomUUID()}`;
201
- logger.info(`[OwnerDirectory] Sending authorization ${action} to Owner ${this.options.ownerAid}, operation: ${operationId.slice(0, 16)}..., call: ${callId.slice(0, 24)}...`);
202
- const prepared = this.registry.prepare({
203
- selfAid: this.options.selfAid, targetAid: this.options.ownerAid, targetDeviceId: deviceId,
204
- timeoutMs: REQUEST_TTL_SECONDS * 1_000,
205
- payload: { type: 'ability', role: 'call', call_id: callId, operation_id: operationId,
206
- ability_path: ABILITY_PATH, definition_id: DEFINITION_ID, params,
207
- ttl: REQUEST_TTL_SECONDS, async: false },
208
- });
209
- this.writeAttempt({ schemaVersion: 1, selfAid: this.options.selfAid, ownerAid: this.options.ownerAid,
210
- operationId, callId, deviceId, action, deadlineAt: this.now() + REQUEST_TTL_SECONDS * 1_000, status: 'pending' });
211
- if (action === 'status')
212
- this.scheduleCheck(this.now() + REQUEST_TTL_SECONDS * 1_000);
213
- this.registry.markSending(this.options.selfAid, callId);
214
- try {
215
- const sent = await this.options.send(prepared.payload, deviceId, REQUEST_TTL_SECONDS);
216
- if (!sent.ok || !sent.message_id) {
217
- logger.error(`[OwnerDirectory] Authorization request not accepted: ${sent.error}`);
218
- throw new Error(sent.error ?? 'directory authorization request was not accepted');
219
- }
220
- logger.info(`[OwnerDirectory] Authorization request sent successfully, message_id: ${sent.message_id}`);
221
- this.registry.markTransportAccepted(this.options.selfAid, callId, sent.message_id, sent.status);
222
- }
223
- catch (error) {
224
- logger.error(`[OwnerDirectory] Authorization request failed: ${error instanceof Error ? error.message : String(error)}`);
225
- this.registry.markFailed(this.options.selfAid, callId, error instanceof Error ? error.message : String(error));
226
- throw error;
227
- }
228
- }
229
- async discoverDevice(preferred, params) {
230
- logger.info(`[OwnerDirectory] discoverDevice: reading ability/index.json from Owner ${this.options.ownerAid}`);
231
- let index;
232
- try {
233
- index = await this.readPublishedJson('/ability/index.json', 128 * 1024);
234
- }
235
- catch (error) {
236
- logger.warn(`[OwnerDirectory] discoverDevice: failed to read ability/index.json: ${error instanceof Error ? error.message : String(error)}`);
237
- throw error;
238
- }
239
- const capabilities = Array.isArray(index.capabilities) ? index.capabilities : [];
240
- logger.info(`[OwnerDirectory] discoverDevice: ability/index.json has ${capabilities.length} capabilities`);
241
- const entry = capabilities.find(value => isRecord(value)
242
- && value.path === ABILITY_PATH && value.definition_id === DEFINITION_ID);
243
- if (!isRecord(entry) || !Array.isArray(entry.devices) || !entry.devices.length
244
- || entry.devices.some(device => typeof device !== 'string' || !device.trim())
245
- || typeof entry.detail_ref !== 'string') {
246
- logger.warn(`[OwnerDirectory] discoverDevice: Owner has no valid directory/access entry. entry=${JSON.stringify(entry)}`);
247
- throw new Error('Owner has no published directory/access device/contract');
248
- }
249
- logger.info(`[OwnerDirectory] discoverDevice: found entry, devices=${JSON.stringify(entry.devices)}, detail_ref=${entry.detail_ref}`);
250
- const prefix = `${this.options.ownerAid}:/`;
251
- if (!entry.detail_ref.startsWith(prefix)) {
252
- logger.warn(`[OwnerDirectory] discoverDevice: detail_ref does not start with owner prefix: ${entry.detail_ref}`);
253
- throw new Error('Owner directory contract must belong to the same Owner');
254
- }
255
- const contractPath = entry.detail_ref.slice(this.options.ownerAid.length + 1);
256
- logger.info(`[OwnerDirectory] discoverDevice: reading contract at ${contractPath}`);
257
- let contract;
258
- try {
259
- contract = await this.readPublishedJson(contractPath, 24 * 1024);
260
- }
261
- catch (error) {
262
- logger.warn(`[OwnerDirectory] discoverDevice: failed to read contract: ${error instanceof Error ? error.message : String(error)}`);
263
- throw error;
264
- }
265
- if (contract.path !== ABILITY_PATH || contract.definition_id !== DEFINITION_ID
266
- || contract.idempotency !== 'keyed' || contract.require_confirm !== entry.require_confirm
267
- || contract.auth_required !== entry.auth_required || !isRecord(contract.params_schema)
268
- || JSON.stringify(contract.effects) !== JSON.stringify(entry.effects)) {
269
- logger.warn(`[OwnerDirectory] discoverDevice: contract mismatch. contract.path=${contract.path}, contract.idempotency=${contract.idempotency}, require_confirm=${contract.require_confirm}/${entry.require_confirm}, auth_required=${contract.auth_required}/${entry.auth_required}, effects_match=${JSON.stringify(contract.effects) === JSON.stringify(entry.effects)}`);
270
- throw new Error('Owner directory index and contract do not match');
271
- }
272
- const validate = new Ajv({ strict: false }).compile(contract.params_schema);
273
- if (!validate(params)) {
274
- logger.warn(`[OwnerDirectory] discoverDevice: params schema validation failed: ${JSON.stringify(validate.errors)}`);
275
- throw new Error('Owner directory contract does not accept the authorization parameters');
276
- }
277
- const devices = entry.devices;
278
- const selected = preferred && devices.includes(preferred) ? preferred : [...devices].sort()[0];
279
- logger.info(`[OwnerDirectory] discoverDevice: selected device=${selected}`);
280
- return selected;
281
- }
282
- async readPublishedJson(remotePath, maxBytes) {
283
- const { bytes } = await readAuthoritativePersonalFsObject(this.options.client, remotePath, this.options.ownerAid, maxBytes);
284
- const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes).replace(/^\uFEFF/, ''));
285
- if (!isRecord(value))
286
- throw new Error('Owner ability document must be a JSON object');
287
- return value;
288
- }
289
- readAttempt() {
290
- const value = atomicReadJson(this.statePath());
291
- if (!isRecord(value) || value.schemaVersion !== 1 || value.selfAid !== this.options.selfAid
292
- || value.ownerAid !== this.options.ownerAid || typeof value.operationId !== 'string'
293
- || typeof value.callId !== 'string' || typeof value.deviceId !== 'string' || !Number.isSafeInteger(value.deadlineAt)
294
- || !['pending', 'initializing', 'retryable', 'denied', 'granted'].includes(String(value.status))
295
- || (value.action !== undefined && !['request', 'status'].includes(String(value.action)))
296
- || (value.retryAt !== undefined && !Number.isSafeInteger(value.retryAt)))
297
- return undefined;
298
- return value;
299
- }
300
- writeAttempt(attempt) {
301
- fs.mkdirSync(this.options.directory, { recursive: true, mode: 0o700 });
302
- atomicWriteJson(this.statePath(), attempt);
303
- fs.chmodSync(this.statePath(), 0o600);
304
- }
305
- statePath() { return path.join(this.options.directory, 'authorization-request.json'); }
306
- }
307
- function isRecord(value) {
308
- return value !== null && typeof value === 'object' && !Array.isArray(value);
309
- }
@@ -1,78 +0,0 @@
1
- # ec contact — Agent 联系人与访问控制
2
-
3
- `ec contact` 管理指定 Agent 的 Contact Book v3。它只接受 AUN AID 主键;拉黑的是该 canonical AID,
4
- 因此会拒绝它在 AUN 以及所有已绑定外部渠道中的私聊入站。角色统一由 relation `config.json role` 管理。
5
-
6
- ## 命令
7
-
8
- ```bash
9
- ec contact add <aid> --self <agent-aid>
10
- ec contact block <aid> --self <agent-aid>
11
- ec contact unblock <aid> --self <agent-aid>
12
- ec contact list --blocked [--self <agent-aid>]
13
- ec contact list --pending [--self <agent-aid>]
14
- ec contact list --all [--self <agent-aid>]
15
- ec contact approve <aid> --request-id <id> [--self <agent-aid>]
16
- ec contact reject <aid> --request-id <id> [--self <agent-aid>]
17
- ec contact block-request <aid> --request-id <id> [--self <agent-aid>]
18
- ```
19
-
20
- 支持 `--format json`。本机 `list` 省略 `--self` 时聚合全部 Agent;写操作在仅有一个 Agent 时可自动推断,多 Agent 环境必须显式指定,避免误操作错误 Agent。
21
-
22
- ## 约束
23
-
24
- - `<aid>` 和 `--self` 必须是合法 AID。
25
- - 新增或恢复 active 联系人前,必须确认对端为 `private`:依据明确的关系类型或验签名片;缺少证据时先查验名片,
26
- 未验证、未知、群类型或证据冲突都会拒绝。数字开头的 AID 适用相同规则。
27
- - 删除角色关系或撤销 Owner 后,既有联系人元数据和拉黑状态仍保留;缺少类型证据的旧条目不能据此授予权限。
28
- - Agent 托管会话中的 `add` 只能针对当前 AUN 私聊对端;它创建/更新 `pending`,并向本 Agent Owner 发送审核卡片。
29
- - `add` 复用 `/request` 的联系人申请额度、过期和请求版本校验;已有 `pending`/`declined` 条目会重新走申请流程。
30
- - Owner 在审核卡片点击“通过”后才变为 active;`blocked` 必须先执行 `unblock`。
31
- - `list --pending` 可查看仍待审核的申请及其 `requestId`;卡片过期或投递失败时,Owner 可用 `approve/reject/block-request` 通过 requestId 处理当前申请,过期申请需申请方重新提交。
32
- - 直接从本机终端执行 `add` 属于本地管理操作,会直接创建或恢复 active 联系人;Connect `action=add` 同样是管理端直接操作。
33
- - 写入 Agent Owner 时,系统会自动创建该 Owner 的 active 联系人记录。
34
- - `block/unblock` 只接受已存在的联系人;不存在时返回 `NOT_FOUND`。
35
- - `block/unblock` 至少改变本 Agent 的入站接收策略;托管任务的普通私聊 `ec msg send` 对 blocked 目标也会在 daemon 侧被拒绝。非托管 AUN CLI 发送不读取本地联系人簿。不代表对端也拉黑了本 Agent。
36
- - Agent owner 不能被拉黑。
37
- - `list --blocked` 只列出 blocked contact;`list --pending` 只列出待审申请;`list --all` 列出联系人全状态。指定 `--self` 时返回该 Agent 的 `contactRevision`,本机省略 `--self` 时按 Agent 聚合。
38
-
39
- ## 权限边界
40
-
41
- 直接从本机终端运行时,这是本地管理命令。
42
-
43
- 从 Agent 活动任务执行时,CLI 不直接写文件,而是携带当前 session delegation token 调用 daemon `contact.op`:
44
-
45
- | 操作 | owner | admin | 普通角色 |
46
- |---|---:|---:|---:|
47
- | `list --blocked/--pending/--all` | 允许 | 允许 | 拒绝 |
48
- | Agent 会话 `add` 当前私聊对端 | 允许 | 允许 | 由当前关系授权,受 AUN 私聊和申请限制 |
49
- | `block` / `unblock` | 允许 | 拒绝 | 拒绝 |
50
- | `approve/reject/block-request` | 允许 | 允许 | 拒绝 |
51
-
52
- 缺少、伪造、撤销或跨会话 delegation token 时失败关闭。托管调用省略 `--self` 时使用 delegation 中的当前 Agent;显式 `--self` 必须等于当前任务所属 Agent。
53
-
54
- 角色管理使用 Role Menu relation assignment;admin 的授予和撤销必须由 owner 执行。
55
-
56
- ## JSON 输出
57
-
58
- 拉黑成功:
59
-
60
- ```json
61
- {
62
- "ok": true,
63
- "operation": "set-blocked",
64
- "selfAid": "bot.agentid.pub",
65
- "primaryId": "peer.agentid.pub",
66
- "blocked": true,
67
- "changed": true,
68
- "contactRevision": "..."
69
- }
70
- ```
71
-
72
- ## 拉黑后的消息行为
73
-
74
- - AUN 和已绑定外部私聊身份的入站在 MessageBridge 业务入口被拦截,不进入 menu/auth/command/session/queue/LLM。
75
- - 群聊不按成员的联系人状态过滤;`open` 对所有已配置渠道的群聊入站开放,`contacts` 将 Agent 已加入并
76
- 接收到的群聊视为授权,`owners` 仅 Owner 消息开放。
77
- - 对 `ai`、`bot`、`agent`、`service` 类型的私聊对端,可限频返回 `[rejection] Not accepting messages from you.`。
78
- - 入站正文中的 `[rejection]` 没有协议控制语义。发送者未被本 Agent 拉黑时,该文本正常进入响应式会话。
File without changes