evolcore 0.0.40 → 0.0.41-test.1

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 (226) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/baseagent-availability.js +1 -1
  5. package/dist/agents/baseagent.js +20 -43
  6. package/dist/agents/claude-runner.js +197 -197
  7. package/dist/agents/codex-runner.js +535 -259
  8. package/dist/agents/ecagent-runner.js +31 -12
  9. package/dist/agents/gemini-runner.js +27 -7
  10. package/dist/agents/runner-types.js +11 -3
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/group/fs-download.js +39 -0
  14. package/dist/aun/group/identity.js +36 -13
  15. package/dist/aun/group/operations.js +5 -0
  16. package/dist/aun/msg/managed-operation.js +72 -11
  17. package/dist/aun/msg/p2p.js +32 -7
  18. package/dist/aun/service-proxy.js +36 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +367 -24
  22. package/dist/channels/daemon.js +39 -5
  23. package/dist/cli/agent-command.js +2 -0
  24. package/dist/cli/agent-create.js +98 -19
  25. package/dist/cli/agent.js +10 -3
  26. package/dist/cli/aun-commands.js +85 -41
  27. package/dist/cli/daemon-commands.js +678 -688
  28. package/dist/cli/fs-command.js +64 -2
  29. package/dist/cli/index.js +48 -4
  30. package/dist/cli/managed-command-guard.js +4 -0
  31. package/dist/cli/model.js +40 -40
  32. package/dist/cli/proxy-command.js +92 -0
  33. package/dist/cli/restart-monitor.js +17 -0
  34. package/dist/cli/role.js +85 -0
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/trigger-command.js +2 -2
  38. package/dist/config/access-policy.js +8 -1
  39. package/dist/config/boot-log.js +38 -1
  40. package/dist/config/config-field-policy.js +5 -32
  41. package/dist/config/config-manager.js +46 -39
  42. package/dist/config/config-operation-service.js +8 -11
  43. package/dist/config/contact-book-store.js +47 -21
  44. package/dist/config/contact-book.js +18 -12
  45. package/dist/config/contact-operation-service.js +3 -4
  46. package/dist/config/contact-request-service.js +11 -0
  47. package/dist/config/daemon-services.js +11 -0
  48. package/dist/config/gateway-config.js +89 -595
  49. package/dist/config/peer-role-resolver.js +15 -11
  50. package/dist/config/providers-config.js +12 -7
  51. package/dist/config/providers-import.js +3 -21
  52. package/dist/config/resolved-config-op.js +3 -0
  53. package/dist/config/role-command-service.js +166 -0
  54. package/dist/config/role-request-service.js +193 -0
  55. package/dist/config/schema-migration.js +686 -25
  56. package/dist/config-store.js +79 -3
  57. package/dist/contracts/ecweb-instance.js +41 -0
  58. package/dist/contracts/ecweb-service-protocol.js +3 -1
  59. package/dist/core/agent-application-service.js +11 -1
  60. package/dist/core/agent-ipc-registration.js +4 -0
  61. package/dist/core/agent-runtime.js +1 -1
  62. package/dist/core/auth/agent-delegation.js +82 -6
  63. package/dist/core/auth/auth-gateway.js +1 -1
  64. package/dist/core/auth/authorization-audit.js +37 -9
  65. package/dist/core/auth/delegation-authorization.js +3 -1
  66. package/dist/core/auth/operation-authorizer.js +15 -0
  67. package/dist/core/auth/operation-catalog.js +39 -6
  68. package/dist/core/command/agent-control.js +94 -19
  69. package/dist/core/command/agent-storage-menu.js +5 -3
  70. package/dist/core/command/cli-intent-parser.js +2 -1
  71. package/dist/core/command/command-handler.js +105 -145
  72. package/dist/core/command/connect-menu.js +31 -2
  73. package/dist/core/command/data-root-resolver.js +5 -4
  74. package/dist/core/command/memory-slash.js +16 -8
  75. package/dist/core/command/menu-catalog.js +6 -6
  76. package/dist/core/command/menu-handler.js +87 -163
  77. package/dist/core/command/menu-protocol.js +9 -2
  78. package/dist/core/command/role-menu.js +148 -30
  79. package/dist/core/command/slash-gate.js +13 -10
  80. package/dist/core/command/slash-handler.js +157 -352
  81. package/dist/core/daemon-control.js +8 -14
  82. package/dist/core/event-catalog.js +15 -0
  83. package/dist/core/evolagent-registry.js +4 -4
  84. package/dist/core/evolagent.js +2 -2
  85. package/dist/core/inference/text-inference.js +31 -40
  86. package/dist/core/ipc-registration.js +24 -3
  87. package/dist/core/memory/consolidation-context.js +51 -5
  88. package/dist/core/memory/consolidation-ops-records.js +1 -1
  89. package/dist/core/memory/consolidation-trigger.js +190 -190
  90. package/dist/core/memory/consolidation.js +316 -29
  91. package/dist/core/memory/forget-log.js +96 -0
  92. package/dist/core/memory/index-manager.js +27 -5
  93. package/dist/core/memory/memory-admin.js +45 -5
  94. package/dist/core/memory/memory-writer.js +163 -18
  95. package/dist/core/memory/relation-idle-monitor.js +119 -58
  96. package/dist/core/memory/relation-sweep.js +44 -39
  97. package/dist/core/message/aun-ipc-sender.js +34 -7
  98. package/dist/core/message/aun-request-registry.js +97 -3
  99. package/dist/core/message/im-renderer.js +11 -4
  100. package/dist/core/message/message-admission.js +97 -8
  101. package/dist/core/message/message-bridge.js +71 -24
  102. package/dist/core/message/message-log.js +55 -0
  103. package/dist/core/message/message-queue.js +5 -5
  104. package/dist/core/message/response-engine.js +387 -144
  105. package/dist/core/model/catalog-service.js +4 -2
  106. package/dist/core/model/config-scope.js +24 -64
  107. package/dist/core/model/field-scope.js +1 -1
  108. package/dist/core/model/model-catalog.js +37 -47
  109. package/dist/core/model/model-diagnostics.js +4 -3
  110. package/dist/core/model/model-fallback.js +10 -7
  111. package/dist/core/model/model-permission.js +3 -2
  112. package/dist/core/ownership/owner-resolver.js +25 -23
  113. package/dist/core/permission/ec-command-parser.js +138 -5
  114. package/dist/core/permission/sandbox-runtime.js +18 -1
  115. package/dist/core/permission/tool-policy.js +42 -10
  116. package/dist/core/relation/peer-identity.js +64 -1
  117. package/dist/core/role/runtime-policy.js +72 -13
  118. package/dist/core/session/session-capsule.js +197 -0
  119. package/dist/core/session/session-idle-monitor.js +1 -1
  120. package/dist/core/session/session-manager.js +168 -14
  121. package/dist/core/session/session-mapper.js +2 -0
  122. package/dist/core/session/session-renew.js +3 -3
  123. package/dist/core/skill/index-generator.js +15 -5
  124. package/dist/core/system-session/memory.js +6 -1
  125. package/dist/core/thread/thread-service.js +19 -6
  126. package/dist/directory/owner-directory-admission.js +95 -0
  127. package/dist/directory/owner-directory-authorization.js +309 -0
  128. package/dist/directory/owner-directory-cache.js +635 -0
  129. package/dist/eck/kit-renderer.js +2 -2
  130. package/dist/ecweb/basic-settings-service.js +33 -40
  131. package/dist/ecweb/message-context-service.js +110 -0
  132. package/dist/index.js +79 -17
  133. package/dist/ipc.js +189 -17
  134. package/dist/paths.js +4 -0
  135. package/dist/proxy/command.js +122 -0
  136. package/dist/proxy/ipc-service.js +68 -0
  137. package/dist/proxy/manager.js +485 -0
  138. package/dist/proxy/service-supervisor.js +603 -0
  139. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  140. package/dist/stats/budget.js +1 -1
  141. package/dist/stats/db.js +15 -0
  142. package/dist/stats/index.js +2 -2
  143. package/dist/stats/price-resolver.js +304 -5
  144. package/dist/stats/query.js +82 -3
  145. package/dist/stats/writer.js +38 -5
  146. package/dist/trigger/feedback.js +18 -7
  147. package/dist/trigger/manager.js +20 -3
  148. package/dist/trigger/parser.js +6 -3
  149. package/dist/trigger/patch.js +1 -1
  150. package/dist/trigger/system-definitions.js +43 -7
  151. package/dist/trigger/validation.js +13 -5
  152. package/dist/utils/cross-platform.js +14 -0
  153. package/dist/utils/ecweb-supervisor.js +258 -83
  154. package/dist/utils/error-utils.js +16 -2
  155. package/dist/utils/logger.js +24 -5
  156. package/dist/utils/npm-ops.js +2 -1
  157. package/dist/utils/package-version-info.js +5 -3
  158. package/dist/utils/upgrade-jobs.js +45 -5
  159. package/kits/docs/INDEX.md +1 -1
  160. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  161. package/kits/docs/channels/aun.md +9 -0
  162. package/kits/docs/evolcore/INDEX.md +2 -1
  163. package/kits/docs/evolcore/agent-create.md +3 -2
  164. package/kits/docs/evolcore/agent.md +1 -1
  165. package/kits/docs/evolcore/config.md +18 -7
  166. package/kits/docs/evolcore/contact.md +3 -0
  167. package/kits/docs/evolcore/event.md +1 -0
  168. package/kits/docs/evolcore/fs.md +16 -0
  169. package/kits/docs/evolcore/memory-architecture.md +2 -2
  170. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  171. package/kits/docs/evolcore/memory.md +1 -1
  172. package/kits/docs/evolcore/menu-protocol.md +36 -0
  173. package/kits/docs/evolcore/model.md +23 -20
  174. package/kits/docs/evolcore/msg.md +21 -8
  175. package/kits/docs/evolcore/session.md +14 -0
  176. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  177. package/kits/schemas/_meta.json +37 -4
  178. package/kits/schemas/agent-config.schema.13.json +23 -3
  179. package/kits/schemas/agent-config.schema.16.json +891 -0
  180. package/kits/schemas/daemon.schema.9.json +366 -0
  181. package/kits/schemas/defaults.schema.5.json +406 -127
  182. package/kits/schemas/relation-config.schema.11.json +260 -0
  183. package/kits/schemas/role-config.schema.1.json +7 -7
  184. package/kits/skills/.switches.json +3 -7
  185. package/kits/skills/aid-ability/SKILL.md +35 -6
  186. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  187. package/kits/skills/ec-trigger/SKILL.md +13 -5
  188. package/kits/skills/personal-assistant/SKILL.md +176 -0
  189. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  190. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  191. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  192. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  193. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  194. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  195. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  196. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  197. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  198. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  199. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  200. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  201. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  202. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  203. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  204. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  205. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  206. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  207. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  208. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  209. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  210. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  211. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  212. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  213. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  214. package/kits/templates/memory-consolidation/forget.md +19 -6
  215. package/kits/templates/memory-consolidation/notes.md +1 -1
  216. package/kits/templates/memory-consolidation/profile.md +2 -2
  217. package/kits/templates/memory-consolidation/promote.md +20 -3
  218. package/kits/templates/roles/member.json +8 -1
  219. package/kits/templates/session-capsule/recovery.md +5 -0
  220. package/kits/templates/session-capsule/renew.md +5 -0
  221. package/kits/templates/system-fragments/baseagent.md +2 -2
  222. package/kits/templates/system-fragments/bootstrap.md +6 -6
  223. package/kits/templates/system-fragments/channel.md +1 -1
  224. package/kits/templates/system-fragments/memory.md +4 -4
  225. package/package.json +7 -3
  226. package/dist/stats/billing.js +0 -215
@@ -210,7 +210,11 @@ export class ThreadService {
210
210
  topicStatus: last.topicStatus ?? 'pending',
211
211
  createdAt: last.createdAt ?? 0,
212
212
  lastActiveAt: last.updatedAt ?? 0,
213
- ...(last.nameUpdatedAt !== undefined ? { nameUpdatedAt: last.nameUpdatedAt } : {}),
213
+ ...(typeof last.metadata?.nameUpdatedAt === 'number'
214
+ ? { nameUpdatedAt: last.metadata.nameUpdatedAt }
215
+ : typeof last.nameUpdatedAt === 'number'
216
+ ? { nameUpdatedAt: last.nameUpdatedAt }
217
+ : {}),
214
218
  };
215
219
  }
216
220
  catch {
@@ -253,7 +257,7 @@ export class ThreadService {
253
257
  peer, // channelId
254
258
  '', // defaultProjectPath — threads are not bound to a project
255
259
  threadId, // threadId
256
- { peerName: peer }, // metadata
260
+ { peerName: peer, nameUpdatedAt: now }, // metadata
257
261
  sanitized, // name
258
262
  undefined, // userId
259
263
  peerKind === 'group' ? 'group' : 'private', // chatType
@@ -271,6 +275,7 @@ export class ThreadService {
271
275
  channelType: 'aun',
272
276
  peerKind,
273
277
  name: sanitized,
278
+ nameUpdatedAt: now,
274
279
  label: label ?? null,
275
280
  topicStatus: topicStatus ?? 'pending',
276
281
  createdAt: now,
@@ -321,7 +326,7 @@ export class ThreadService {
321
326
  throw new ThreadServiceError(`话题不存在: ${threadId}`, 'TOPIC_NOT_FOUND');
322
327
  if (entry.name === sanitized)
323
328
  return { changed: false, name: sanitized };
324
- const nameUpdatedAt = Date.now();
329
+ const nameUpdatedAt = Math.max(Date.now(), Number(entry.nameUpdatedAt ?? entry.createdAt ?? 0) + 1);
325
330
  entry.name = sanitized;
326
331
  entry.nameUpdatedAt = nameUpdatedAt;
327
332
  entry.lastActiveAt = nameUpdatedAt;
@@ -330,7 +335,7 @@ export class ThreadService {
330
335
  // Sync to session
331
336
  const session = await this.sessionManager.getThreadSession(entryChannelType(entry), entry.peer, threadId, selfAid);
332
337
  if (session) {
333
- await this.sessionManager.renameSession(session.id, sanitized);
338
+ await this.sessionManager.renameSession(session.id, sanitized, nameUpdatedAt);
334
339
  }
335
340
  return { changed: true, name: sanitized, nameUpdatedAt, peerKind: entry.peerKind };
336
341
  }
@@ -390,7 +395,7 @@ export class ThreadService {
390
395
  this.appendThreadSnapshot(input.selfAid, entry);
391
396
  const session = await this.sessionManager.getThreadSession(entryChannelType(entry), entry.peer, input.threadId, input.selfAid);
392
397
  if (session)
393
- await this.sessionManager.renameSession(session.id, sanitized);
398
+ await this.sessionManager.renameSession(session.id, sanitized, input.nameUpdatedAt);
394
399
  return { applied: true };
395
400
  }
396
401
  // ── P1a.1.6: 话题标签 ──
@@ -790,6 +795,11 @@ export class ThreadService {
790
795
  channelType: parsedDir?.channelType ?? 'aun',
791
796
  peerKind: last.chatType === 'group' ? 'group' : 'private',
792
797
  name: last.name ?? last.threadId,
798
+ ...(typeof last.metadata?.nameUpdatedAt === 'number'
799
+ ? { nameUpdatedAt: last.metadata.nameUpdatedAt }
800
+ : typeof last.nameUpdatedAt === 'number'
801
+ ? { nameUpdatedAt: last.nameUpdatedAt }
802
+ : {}),
793
803
  label: last.label ?? null,
794
804
  topicStatus: last.topicStatus ?? 'pending',
795
805
  createdAt: last.createdAt ?? 0,
@@ -973,7 +983,10 @@ export class ThreadService {
973
983
  id: latest.id ?? entry.sessionId,
974
984
  projectPath: latest.projectPath ?? '',
975
985
  chatType: entry.peerKind === 'group' ? 'group' : 'private',
976
- metadata: latest.metadata ?? {},
986
+ metadata: {
987
+ ...(latest.metadata ?? {}),
988
+ ...(entry.nameUpdatedAt !== undefined ? { nameUpdatedAt: entry.nameUpdatedAt } : {}),
989
+ },
977
990
  // topic metadata — updated values
978
991
  threadId: entry.threadId,
979
992
  channelIdAlias: entry.peer,
@@ -0,0 +1,95 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { agentDir } from '../paths.js';
4
+ import { ownerResolver } from '../core/ownership/owner-resolver.js';
5
+ import { OwnerDirectoryCache, OWNER_DIRECTORY_INITIAL_WAIT_MS, OWNER_DIRECTORY_SCOPES, } from './owner-directory-cache.js';
6
+ const liveDirectories = new Map();
7
+ // Coalesce negative lookups from unrelated senders as well as concurrent calls.
8
+ const MISS_REFRESH_INTERVAL_MS = 60_000;
9
+ /** Register only the channel's existing client-backed cache; no SDK connections are created here. */
10
+ export function registerOwnerDirectoryAdmission(input) {
11
+ const current = liveDirectories.get(input.selfAid);
12
+ if (current?.cache === input.cache)
13
+ return;
14
+ liveDirectories.set(input.selfAid, { ...input, missAttemptAt: {} });
15
+ }
16
+ /** Cache misses get one bounded synchronization attempt before admission, using the live channel. */
17
+ export async function prepareOwnerDirectoryAdmission(selfAid, aid) {
18
+ const live = liveDirectories.get(selfAid);
19
+ if (!live)
20
+ return;
21
+ if (!live.isCurrent()) {
22
+ liveDirectories.delete(selfAid);
23
+ return;
24
+ }
25
+ if (ownerResolver.owner(selfAid) !== live.ownerAid)
26
+ return;
27
+ const agents = live.cache.readSnapshot('agents');
28
+ if (agents?.entries.some(entry => entry.aid === aid)) {
29
+ // The higher-priority Agent category is already known. Only its stale refresh may run.
30
+ void live.cache.lookupByAid('agents', aid).catch(() => { });
31
+ return;
32
+ }
33
+ const contacts = live.cache.readSnapshot('contacts');
34
+ if (contacts?.entries.some(entry => entry.aid === aid)
35
+ && (agents || live.cache.scopeAccess('agents') === 'not_authorized')) {
36
+ void live.cache.refreshIfNeeded().catch(() => { });
37
+ return;
38
+ }
39
+ const tasks = [];
40
+ for (const scope of OWNER_DIRECTORY_SCOPES) {
41
+ if (live.cache.scopeAccess(scope) !== 'authorized')
42
+ continue;
43
+ const found = live.cache.readSnapshot(scope)?.entries.some(entry => entry.aid === aid);
44
+ const now = Date.now();
45
+ if (!found) {
46
+ if (now - (live.missAttemptAt[scope] ?? 0) < MISS_REFRESH_INTERVAL_MS)
47
+ continue;
48
+ live.missAttemptAt[scope] = now;
49
+ }
50
+ tasks.push(live.cache.lookupByAid(scope, aid));
51
+ }
52
+ if (tasks.length === 0)
53
+ return;
54
+ let timer;
55
+ try {
56
+ await Promise.race([
57
+ Promise.allSettled(tasks),
58
+ new Promise(resolve => { timer = setTimeout(resolve, OWNER_DIRECTORY_INITIAL_WAIT_MS); }),
59
+ ]);
60
+ }
61
+ finally {
62
+ if (timer)
63
+ clearTimeout(timer);
64
+ }
65
+ }
66
+ /** Local-only classification. A stale or changed Owner can never authorize an old snapshot. */
67
+ export function readOwnerDirectoryMembership(selfAid, aid) {
68
+ const directory = path.join(agentDir(selfAid), 'directory');
69
+ const configured = ['authorization.json', 'authorization.json_', 'agents.json', 'contacts.json']
70
+ .some(name => fs.existsSync(path.join(directory, name)));
71
+ if (!configured)
72
+ return undefined;
73
+ const unknown = { agents: 'unavailable', contacts: 'unavailable' };
74
+ const ownerAid = ownerResolver.owner(selfAid);
75
+ if (!ownerAid)
76
+ return unknown;
77
+ try {
78
+ const cache = new OwnerDirectoryCache({ selfAid, ownerAid, directory });
79
+ const membership = { ...unknown };
80
+ for (const scope of OWNER_DIRECTORY_SCOPES) {
81
+ const access = cache.scopeAccess(scope);
82
+ if (access === 'not_authorized')
83
+ membership[scope] = 'not_authorized';
84
+ else if (access === 'authorized') {
85
+ const snapshot = cache.readSnapshot(scope);
86
+ if (snapshot)
87
+ membership[scope] = snapshot.entries.some(entry => entry.aid === aid) ? 'found' : 'not_found';
88
+ }
89
+ }
90
+ return membership;
91
+ }
92
+ catch {
93
+ return unknown;
94
+ }
95
+ }
@@ -0,0 +1,309 @@
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
+ }