evolcore 0.0.41-test.1 → 0.0.41-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 (127) hide show
  1. package/CHANGELOG.md +49 -36
  2. package/dist/agents/baseagent.js +68 -6
  3. package/dist/agents/codex-runner.js +62 -43
  4. package/dist/aun/aid/agentmd.js +98 -11
  5. package/dist/aun/aid/client.js +1 -1
  6. package/dist/aun/aid/control-aid.js +26 -2
  7. package/dist/aun/aid/identity.js +91 -0
  8. package/dist/aun/aid/index.js +1 -1
  9. package/dist/aun/aid/managed-operation.js +1 -1
  10. package/dist/aun/aid/ownership-operation.js +23 -22
  11. package/dist/aun/menu/client.js +27 -0
  12. package/dist/aun/msg/p2p.js +3 -8
  13. package/dist/aun/service-proxy.js +17 -0
  14. package/dist/channels/aun.js +321 -34
  15. package/dist/cli/agent-command.js +5 -2
  16. package/dist/cli/agent-create.js +991 -233
  17. package/dist/cli/agent.js +49 -10
  18. package/dist/cli/aid-bind-command.js +48 -19
  19. package/dist/cli/aun-commands.js +44 -16
  20. package/dist/cli/daemon-commands.js +1 -0
  21. package/dist/cli/index.js +24 -1
  22. package/dist/cli/init-channel.js +1 -1
  23. package/dist/cli/init.js +75 -1
  24. package/dist/cli/managed-command-guard.js +13 -1
  25. package/dist/cli/provider-command.js +57 -0
  26. package/dist/cli/restart-monitor.js +4 -2
  27. package/dist/cli/stats.js +10 -3
  28. package/dist/cli/task-context.js +19 -0
  29. package/dist/config/boot-log.js +3 -2
  30. package/dist/config/config-field-policy.js +12 -7
  31. package/dist/config/config-manager.js +138 -6
  32. package/dist/config/owner-config.js +2 -2
  33. package/dist/config/peer-role-resolver.js +2 -1
  34. package/dist/config/provider-ipc-service.js +132 -0
  35. package/dist/config/provider-menu-request.js +58 -0
  36. package/dist/config/providers-management.js +78 -5
  37. package/dist/config/resolved-config-op.js +8 -1
  38. package/dist/config/schema-migration.js +322 -8
  39. package/dist/config-store.js +10 -1
  40. package/dist/contracts/ecweb-service-protocol.js +2 -1
  41. package/dist/core/agent-application-service.js +60 -11
  42. package/dist/core/agent-create-status.js +203 -0
  43. package/dist/core/agent-creation-claim.js +177 -0
  44. package/dist/core/agent-ipc-registration.js +39 -18
  45. package/dist/core/agent-runtime.js +193 -23
  46. package/dist/core/auth/agent-delegation.js +4 -2
  47. package/dist/core/auth/auth-gateway.js +66 -1
  48. package/dist/core/auth/authorization-audit.js +41 -5
  49. package/dist/core/auth/delegation-authorization.js +2 -1
  50. package/dist/core/auth/operation-authorizer.js +28 -6
  51. package/dist/core/auth/operation-catalog.js +14 -1
  52. package/dist/core/channel-loader.js +2 -0
  53. package/dist/core/command/agent-control.js +257 -14
  54. package/dist/core/command/cli-intent-parser.js +6 -2
  55. package/dist/core/command/command-handler.js +64 -55
  56. package/dist/core/command/memory-slash.js +1 -1
  57. package/dist/core/command/menu-catalog.js +5 -0
  58. package/dist/core/command/menu-handler.js +64 -18
  59. package/dist/core/command/menu-protocol.js +15 -1
  60. package/dist/core/command/provider-menu.js +46 -0
  61. package/dist/core/command/slash-handler.js +2 -1
  62. package/dist/core/daemon-control.js +18 -13
  63. package/dist/core/event-catalog.js +10 -0
  64. package/dist/core/evolagent-registry.js +3 -1
  65. package/dist/core/evolagent.js +8 -6
  66. package/dist/core/file-integrity/store.js +11 -0
  67. package/dist/core/handoff/ipc-registration.js +3 -0
  68. package/dist/core/initialization/service.js +491 -0
  69. package/dist/core/ipc-registration.js +34 -22
  70. package/dist/core/memory/consolidation-ops-records.js +95 -0
  71. package/dist/core/memory/consolidation-trigger.js +19 -2
  72. package/dist/core/memory/consolidation.js +19 -8
  73. package/dist/core/memory/memory-admin.js +1 -1
  74. package/dist/core/memory/relation-sweep.js +11 -6
  75. package/dist/core/message/aun-ipc-sender.js +73 -67
  76. package/dist/core/message/im-renderer.js +18 -0
  77. package/dist/core/message/message-bridge.js +35 -3
  78. package/dist/core/message/response-engine.js +32 -28
  79. package/dist/core/model/catalog-service.js +1 -1
  80. package/dist/core/model/config-scope.js +5 -7
  81. package/dist/core/ownership/owner-resolver.js +755 -143
  82. package/dist/core/permission/approval-gateway.js +103 -403
  83. package/dist/core/permission/ec-command-parser.js +32 -4
  84. package/dist/core/permission/index.js +1 -0
  85. package/dist/core/permission/permission-result.js +78 -0
  86. package/dist/core/permission/tool-policy.js +7 -43
  87. package/dist/core/system-session/memory.js +37 -7
  88. package/dist/directory/owner-directory-cache.js +2 -2
  89. package/dist/ecweb/init-menu.js +32 -0
  90. package/dist/index.js +17 -5
  91. package/dist/ipc.js +85 -25
  92. package/dist/paths.js +3 -0
  93. package/dist/proxy/manager.js +6 -7
  94. package/dist/trigger/authorization.js +27 -17
  95. package/dist/trigger/feedback.js +2 -3
  96. package/dist/trigger/ipc-service.js +105 -78
  97. package/dist/trigger/local-files.js +2 -1
  98. package/dist/trigger/manager.js +5 -3
  99. package/dist/trigger/scheduler.js +88 -6
  100. package/dist/utils/atomic-write.js +28 -0
  101. package/dist/utils/error-utils.js +24 -0
  102. package/dist/utils/logger.js +68 -1
  103. package/dist/utils/welcome.js +1 -1
  104. package/kits/docs/INDEX.md +1 -0
  105. package/kits/docs/aun/SDK.md +4 -1
  106. package/kits/docs/evolcore/INDEX.md +1 -0
  107. package/kits/docs/evolcore/agent.md +8 -1
  108. package/kits/docs/evolcore/aid.md +67 -17
  109. package/kits/docs/evolcore/config.md +11 -1
  110. package/kits/docs/evolcore/group.md +1 -1
  111. package/kits/docs/evolcore/provider.md +50 -0
  112. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  113. package/kits/rules/01-overview.md +3 -0
  114. package/kits/rules/04-relation.md +1 -1
  115. package/kits/schemas/_meta.json +2 -2
  116. package/kits/schemas/agent-config.schema.16.json +3 -3
  117. package/kits/schemas/relation-config.schema.11.json +17 -0
  118. package/kits/skills/.switches.json +8 -0
  119. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  120. package/kits/skills/ec-identity/SKILL.md +2 -2
  121. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  122. package/kits/skills/ec-trigger/SKILL.md +5 -13
  123. package/kits/skills/thread-ops/SKILL.md +5 -0
  124. package/kits/templates/system-fragments/venue.md +1 -1
  125. package/package.json +3 -3
  126. package/dist/core/memory/forget-log.js +0 -96
  127. package/dist/core/message/create-status.js +0 -96
@@ -2,19 +2,21 @@ import crypto from 'crypto';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { parseDocument } from 'yaml';
5
+ import { validateAgentMdDocument } from '@agentunion/fastaun';
5
6
  import { getAidStore, loadAid, SLOT } from './store.js';
6
7
  import { agentMdPath, aidLocalDir, resolveRoot } from '../../paths.js';
7
8
  export const DEFAULT_AGENT_DESCRIPTION = 'EvolCore AI agent.';
8
9
  /**
9
- * AUN 主体类型白名单。没有 `ai` / `codeagent` 这类取值:使用大模型且没有
10
- * 专用主体类型的服务程序默认归为 `agent`。新建 AID 未指定类型时使用 DEFAULT_AGENT_TYPE。
10
+ * AUN 主体类型已知预设值列表。`type` 是可扩展字符串,协议允许应用自定义值;
11
+ * 此列表用于 CLI 创建/set 时的归一化,未知类型原样透传(协议层不拦截)。
12
+ * 新建 AID 未指定类型时使用 DEFAULT_AGENT_TYPE。
11
13
  */
12
- export const AGENT_TYPES = ['human', 'agent', 'group', 'service', 'device', 'org', 'host'];
14
+ export const AGENT_TYPES = ['human', 'agent', 'group', 'service', 'device', 'org', 'host', 'custom'];
13
15
  export const DEFAULT_AGENT_TYPE = 'agent';
14
16
  /**
15
- * 归一化主体类型:大小写不敏感,统一收敛为白名单里的小写形式。
16
- * `--type AGENT` / `Agent` 都接受,最终写进 agent.md 的一律是小写 `agent`。
17
- * 返回 undefined 表示输入不是可识别的类型(交由 validateAgentType 报错)。
17
+ * 归一化主体类型:大小写不敏感,对已知预设值统一收敛为小写形式。
18
+ * `--type AGENT` / `Agent` 都接受,最终写进 agent.md 的预设值一律是小写。
19
+ * 未知的扩展类型返回 undefined——由调用方决定是否透传或报错。
18
20
  */
19
21
  export function normalizeAgentType(type) {
20
22
  if (typeof type !== 'string')
@@ -26,8 +28,6 @@ export function normalizeAgentType(type) {
26
28
  export function validateAgentType(type) {
27
29
  if (typeof type !== 'string' || !type.trim())
28
30
  return 'must be a non-empty string';
29
- if (!normalizeAgentType(type))
30
- return `must be one of ${AGENT_TYPES.join(', ')}`;
31
31
  return null;
32
32
  }
33
33
  /**
@@ -42,8 +42,6 @@ export const AGENT_AVATAR_MAX_LENGTH = 256;
42
42
  function codePointLength(value) {
43
43
  return Array.from(value).length;
44
44
  }
45
- export const AGENT_TAG_MIN_COUNT = 3;
46
- export const AGENT_TAG_MAX_COUNT = 6;
47
45
  export const AGENT_TAG_MAX_LENGTH = 50;
48
46
  const AGENT_TAG_PATTERN = /^[\p{L}\p{N}-]+$/u;
49
47
  /** Return a human-readable validation error for one tag, or null when valid. */
@@ -500,7 +498,7 @@ export function updateAgentMdFrontmatterFieldValue(content, field, value) {
500
498
  const error = validateAgentType(normalized);
501
499
  if (error)
502
500
  throw new Error(`agent.md type ${error}`);
503
- return updateAgentMdFrontmatterField(content, field, normalizeAgentType(normalized), 'aid');
501
+ return updateAgentMdFrontmatterField(content, field, normalizeAgentType(normalized) ?? normalized, 'aid');
504
502
  }
505
503
  if (field === 'version' && !/^\d+\.\d+\.\d+$/.test(normalized)) {
506
504
  throw new Error('agent.md version must use major.minor.patch format');
@@ -615,6 +613,37 @@ export async function agentmdGet(aid, opts) {
615
613
  catch { /* ignore */ }
616
614
  }
617
615
  }
616
+ /** Check an existing identity before Agent creation can overwrite its signed card. */
617
+ export async function assertAgentIdentityReusable(aid, opts = {}) {
618
+ let card;
619
+ try {
620
+ card = await agentmdGet(aid, { ...opts, withVerification: true, remoteOnly: true });
621
+ }
622
+ catch (error) {
623
+ if (error.code === 'AGENTMD_NOT_FOUND')
624
+ return;
625
+ throw error;
626
+ }
627
+ assertAgentCardReusable(aid, card);
628
+ }
629
+ /** The caller supplies a card whose verification came from the SDK, never raw YAML alone. */
630
+ export function assertAgentCardReusable(aid, card) {
631
+ if (card.verification.status !== 'verified') {
632
+ throw Object.assign(new Error(`Cannot verify the existing identity for ${aid}`), { code: 'AGENT_IDENTITY_UNVERIFIED' });
633
+ }
634
+ const frontmatter = card.content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
635
+ const document = parseDocument(frontmatter ?? '');
636
+ const fields = document.toJS();
637
+ if (document.errors.length > 0 || !fields || typeof fields !== 'object' || Array.isArray(fields)
638
+ || typeof fields.aid !== 'string' || fields.aid.toLowerCase() !== aid.toLowerCase()) {
639
+ throw Object.assign(new Error(`Invalid existing identity for ${aid}`), { code: 'AGENT_IDENTITY_UNVERIFIED' });
640
+ }
641
+ if (typeof fields.type === 'string' && fields.type.trim().toLowerCase() === 'host') {
642
+ throw Object.assign(new Error(`AID "${aid}" belongs to a host and cannot be reused as an Agent`), {
643
+ code: 'HOST_AID_RESERVED',
644
+ });
645
+ }
646
+ }
618
647
  /**
619
648
  * Validate and upload agent.md. The SDK signs the payload and persists its
620
649
  * signed local cache only after the remote upload succeeds.
@@ -687,6 +716,64 @@ export async function agentmdPut(content, opts) {
687
716
  const lockKey = `${path.resolve(aunPath)}\u0000${opts.aid.toLowerCase()}`;
688
717
  return withAgentMdWriteLock(lockKey, () => publishAgentMd(content, opts));
689
718
  }
719
+ /**
720
+ * Apply the creation form's profile to the card produced by the SDK's initial
721
+ * Owner binding. Ownership declarations are SDK output: never reconstruct them
722
+ * from the form or replace the owned card with an unowned initial template.
723
+ */
724
+ export async function agentmdPutInitializationProfile(content, opts) {
725
+ const validation = validateAgentMdFrontmatter(content, opts.aid);
726
+ if (!validation.valid) {
727
+ throw new Error(`invalid agent.md frontmatter: ${validation.errors.join('; ')}`);
728
+ }
729
+ const profileFrontmatter = stripAgentMdSignature(content).match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)[1];
730
+ const profile = parseDocument(profileFrontmatter).toJS();
731
+ const aunPath = resolveAgentMdAunPath(opts);
732
+ const lockKey = `${path.resolve(aunPath)}\u0000${opts.aid.toLowerCase()}`;
733
+ return withAgentMdWriteLock(lockKey, async () => {
734
+ const store = opts.store ?? await getAidStore({ slotId: SLOT.cli, aunPath });
735
+ const ownStore = !opts.store;
736
+ try {
737
+ const current = await agentmdGet(opts.aid, { store, aunPath, withVerification: true, remoteOnly: true });
738
+ if (current.source !== 'remote' || current.verification.status !== 'verified') {
739
+ throw Object.assign(new Error('Initial owned agent.md must be verified remotely'), { code: 'INITIALIZE_REMOTE_UNVERIFIED' });
740
+ }
741
+ const payload = stripAgentMdSignature(current.content);
742
+ // Use the SDK's upload schema as well as signature verification. Download
743
+ // compatibility alone also accepts historical cards without Ownership 2.1.
744
+ const { frontmatter } = validateAgentMdDocument(payload, { expectedAid: opts.aid, forUpload: true });
745
+ const ownership = frontmatter.ownership;
746
+ const statement = ownership?.statement;
747
+ if (frontmatter.owner !== opts.ownerAid || statement?.owner_aid !== opts.ownerAid
748
+ || statement.sub_aid !== opts.aid || statement.relation_version !== 1) {
749
+ throw Object.assign(new Error('Initial agent.md ownership no longer matches the creation'), { code: 'INITIALIZE_OWNER_CONFLICT' });
750
+ }
751
+ const version = current.remoteVersion;
752
+ if (!version?.etag && !version?.lastModified) {
753
+ throw new AgentMdVersionUnavailableError('初始归属名片缺少远端版本,已拒绝覆盖发布');
754
+ }
755
+ if (opts.expectedRemoteVersion && !remoteVersionsEqual(opts.expectedRemoteVersion, version)) {
756
+ throw new AgentMdVersionConflictError(opts.expectedRemoteVersion, version);
757
+ }
758
+ const match = payload.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
759
+ const document = parseDocument(match[1]);
760
+ for (const field of ['name', 'type', 'description', 'tags']) {
761
+ if (Object.hasOwn(profile, field))
762
+ document.set(field, profile[field]);
763
+ }
764
+ const updated = `---\n${document.toString({ lineWidth: 0 })}---\n${payload.slice(match[0].length)}`;
765
+ validateAgentMdDocument(updated, { expectedAid: opts.aid, forUpload: true });
766
+ return await publishAgentMd(updated, { ...opts, store, aunPath, expectedRemoteVersion: version });
767
+ }
768
+ finally {
769
+ if (ownStore)
770
+ try {
771
+ store.close();
772
+ }
773
+ catch { /* ignore */ }
774
+ }
775
+ });
776
+ }
690
777
  export async function agentmdSet(aid, field, value, opts = {}) {
691
778
  const aunPath = resolveAgentMdAunPath(opts);
692
779
  const lockKey = `${path.resolve(aunPath)}\u0000${aid.toLowerCase()}`;
@@ -39,7 +39,7 @@ export function suppressSdkLogs() {
39
39
  };
40
40
  }
41
41
  // ==================== SDK package ====================
42
- export const MIN_AUN_CORE_SDK = [0, 5, 26];
42
+ export const MIN_AUN_CORE_SDK = [0, 5, 28];
43
43
  export const AUN_CORE_SDK_PKG = '@agentunion/fastaun';
44
44
  function compareVersion(a, min) {
45
45
  const parts = a.split('.').map(n => parseInt(n, 10));
@@ -11,7 +11,7 @@ import { isValidAid } from './validation.js';
11
11
  import { agentMdPath, resolvePaths } from '../../paths.js';
12
12
  import { PeerIdentityCache } from '../../core/relation/peer-identity.js';
13
13
  import { agentmdPut, buildInitialAgentMd, invalidateAgentDisplayName, stripAgentMdSignature } from './agentmd.js';
14
- import { logger } from '../../utils/logger.js';
14
+ import { logger, logOwnershipEvent } from '../../utils/logger.js';
15
15
  const MAX_ATTEMPTS = 5;
16
16
  export { DEFAULT_AID_DOMAIN } from './domain.js';
17
17
  /** Human-facing platform label used in the control AID's agent.md name. */
@@ -135,7 +135,30 @@ export async function ensureControlAgentMd(aid, opts = {}) {
135
135
  catch { /* missing */ }
136
136
  const metadata = readJsonFile(metadataPath);
137
137
  const remoteMissing = String(metadata?.remote_status ?? '').trim().toLowerCase() === 'missing';
138
- const needsPublish = !existing || !hasCanonicalControlFrontmatter(existing, normalizedAid, name, aunRoot) || remoteMissing;
138
+ const canonical = !!existing && hasCanonicalControlFrontmatter(existing, normalizedAid, name, aunRoot);
139
+ const needsPublish = !canonical || remoteMissing;
140
+ let hadOwnershipFields;
141
+ if (existing) {
142
+ try {
143
+ const frontmatter = stripAgentMdSignature(existing).match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
144
+ if (frontmatter) {
145
+ const document = parseDocument(frontmatter);
146
+ if (document.errors.length === 0) {
147
+ const fields = document.toJS();
148
+ if (fields && typeof fields === 'object' && !Array.isArray(fields)) {
149
+ hadOwnershipFields = Object.hasOwn(fields, 'owner') || Object.hasOwn(fields, 'ownership');
150
+ }
151
+ }
152
+ }
153
+ }
154
+ catch { }
155
+ }
156
+ const diagnostic = {
157
+ subjectAid: normalizedAid, processId: process.pid, publicationRequired: needsPublish,
158
+ publicationReason: !existing ? 'missing' : !canonical ? 'noncanonical' : remoteMissing ? 'remote_missing' : 'current',
159
+ hadOwnershipFields,
160
+ };
161
+ logOwnershipEvent('control.card.checked', diagnostic);
139
162
  if (!needsPublish)
140
163
  return { aid: normalizedAid, name, published: false };
141
164
  const content = buildInitialAgentMd({
@@ -147,6 +170,7 @@ export async function ensureControlAgentMd(aid, opts = {}) {
147
170
  });
148
171
  try {
149
172
  await agentmdPut(content, { aid: normalizedAid, store: opts.store, aunPath: aunRoot });
173
+ logOwnershipEvent('control.card.published', diagnostic);
150
174
  }
151
175
  catch (error) {
152
176
  // agentmdPut intentionally keeps edits to an existing card on failure;
@@ -3,6 +3,7 @@ import path from 'path';
3
3
  import crypto from 'crypto';
4
4
  import { getAidStore, loadAid, loadClient, AidLoadError, SLOT } from './store.js';
5
5
  import { downloadCaRoot } from './client.js';
6
+ import { AUN_KEYSTORE_ENCRYPTION_SEED } from './encryption-seed-policy.js';
6
7
  import { resolvePaths, agentMdPath, aunPath as defaultAunPath } from '../../paths.js';
7
8
  // ==================== Validation ====================
8
9
  export function isValidAid(name) {
@@ -263,6 +264,96 @@ export async function aidCreate(aid, opts) {
263
264
  throw e;
264
265
  }
265
266
  }
267
+ /**
268
+ * Bootstrap an agent's PKI identity without publishing agent.md or binding an
269
+ * Owner. One-shot initialization performs those operations separately and must
270
+ * retain the operation ID returned by its explicit Owner bind.
271
+ *
272
+ * RegisterFlow keeps the SDK's existing-key and pending-registration recovery;
273
+ * unlike the legacy force path, this entry point never deletes a local key.
274
+ * The caller owns the returned client and store and must close them in order.
275
+ */
276
+ export async function aidCreateIdentityOnly(aid, opts) {
277
+ const target = aid.trim();
278
+ const aunPath = opts?.aunPath ?? defaultAunPath();
279
+ const { RegisterFlow, LocalIdentityStore, CryptoProvider, GatewayDiscovery } = await import('@agentunion/fastaun');
280
+ RegisterFlow.validateAidName(target);
281
+ const alreadyExisted = fs.existsSync(path.join(aunPath, 'AIDs', target, 'private'));
282
+ const authenticate = async (gateway = '') => {
283
+ // Recreate through the common factory after registration/CA download so
284
+ // slot, encryption seed, SSL verification and the current CA all agree.
285
+ const store = await getAidStore({ slotId: SLOT.cli, aunPath });
286
+ let client;
287
+ try {
288
+ client = await loadClient(store, target);
289
+ const auth = await client.authenticate();
290
+ return { aid: target, alreadyExisted, gateway: String(auth?.gateway ?? gateway), client, store };
291
+ }
292
+ catch (error) {
293
+ // Closing must not hide the registration/authentication failure.
294
+ try {
295
+ await client?.close();
296
+ }
297
+ catch { /* preserve original error */ }
298
+ try {
299
+ store.close();
300
+ }
301
+ catch { /* preserve original error */ }
302
+ throw error;
303
+ }
304
+ };
305
+ if (alreadyExisted && (await verifySignAbility(target, { aunPath })).ok) {
306
+ // A network/auth failure here is not permission to register again.
307
+ return authenticate();
308
+ }
309
+ let gateway = '';
310
+ const keystore = new LocalIdentityStore(aunPath, { encryptionSeed: AUN_KEYSTORE_ENCRYPTION_SEED });
311
+ let registrationCompleted = false;
312
+ try {
313
+ const discovery = new GatewayDiscovery({ verifySsl: true });
314
+ const issuer = target.slice(target.indexOf('.') + 1);
315
+ let discoveryError;
316
+ // Match AIDStore's discovery fallback for an AID that is not registered yet.
317
+ for (const url of [
318
+ `https://${target}/.well-known/aun-gateway`,
319
+ `https://gateway.${issuer}/.well-known/aun-gateway`,
320
+ ]) {
321
+ try {
322
+ gateway = await discovery.discover(url);
323
+ break;
324
+ }
325
+ catch (error) {
326
+ discoveryError = error;
327
+ }
328
+ }
329
+ if (!gateway)
330
+ throw discoveryError instanceof Error ? discoveryError : new Error(String(discoveryError));
331
+ const flow = new RegisterFlow({ keystore, crypto: new CryptoProvider(), verifySsl: true });
332
+ keystore.saveMetadata(target, { identity_type: 'agent', identity_exttype: '' });
333
+ const registered = await flow.registerAid(gateway, target);
334
+ // Follow AIDStore.register's public persistence contract. In particular,
335
+ // registerAid can return a recovered certificate for an existing keypair.
336
+ if (registered.cert)
337
+ keystore.saveCert(target, registered.cert);
338
+ keystore.saveKeyPair(target, {
339
+ private_key_pem: registered.private_key_pem,
340
+ public_key_der_b64: registered.public_key_der_b64,
341
+ curve: registered.curve,
342
+ });
343
+ registrationCompleted = true;
344
+ }
345
+ finally {
346
+ try {
347
+ keystore.close();
348
+ }
349
+ catch (error) {
350
+ if (registrationCompleted)
351
+ throw error;
352
+ }
353
+ }
354
+ await downloadCaRoot(aunPath, gateway, '', opts?.silent === true);
355
+ return authenticate(gateway);
356
+ }
266
357
  // ==================== Show ====================
267
358
  export async function aidShow(aid, opts) {
268
359
  const aunPath = opts?.aunPath ?? defaultAunPath();
@@ -1,5 +1,5 @@
1
1
  export { AgentMdVersionUnavailableError, AgentMdVersionConflictError } from './agentmd.js';
2
- export { AGENT_TAG_MIN_COUNT, AGENT_TAG_MAX_COUNT, AGENT_TAG_MAX_LENGTH, validateAgentTag, validateAgentTags, } from './agentmd.js';
2
+ export { AGENT_TAG_MAX_LENGTH, validateAgentTag, validateAgentTags, } from './agentmd.js';
3
3
  export { isValidAid, aidList, aidListVerified, aidCreate, aidShow, aidDelete, aidLookup, verifySignAbility, probePkiRecoverability, appendAidLifecycle, readAidLifecycle } from './identity.js';
4
4
  export { AGENT_TYPES, DEFAULT_AGENT_DESCRIPTION, DEFAULT_AGENT_TYPE, normalizeAgentType, validateAgentType, buildInitialAgentMd, validateAgentMdFrontmatter, agentmdGet, agentmdPut, agentmdSet, agentmdSync, invalidateAgentDisplayName, parseAgentDisplayName, refreshAgentDisplayName, resolveAgentDisplayName, stripAgentMdSignature, updateAgentMdFrontmatterAvatar, updateAgentMdFrontmatterFieldValue, updateAgentMdFrontmatterName, } from './agentmd.js';
5
5
  export { MIN_AUN_CORE_SDK, AUN_CORE_SDK_PKG, isAunSdkVersionOk, resolveAunCoreSdkPkg, ensureAunSdk, isAunSdkReady, downloadCaRoot, suppressSdkLogs, } from './client.js';
@@ -55,7 +55,7 @@ function parseAvatar(args) {
55
55
  },
56
56
  };
57
57
  }
58
- const AGENTMD_EDITABLE_FIELDS = new Set(['name', 'type', 'description', 'version', 'tags']);
58
+ const AGENTMD_EDITABLE_FIELDS = new Set(['name', 'type', 'description', 'version', 'tags', 'exttype']);
59
59
  function parseAgentmdSet(args) {
60
60
  const aidResult = parseAid(args[2]);
61
61
  if (!aidResult.ok)
@@ -1,6 +1,5 @@
1
1
  import { isValidAid } from './validation.js';
2
2
  import { ownerResolver, OwnershipError } from '../../core/ownership/owner-resolver.js';
3
- import { logger } from '../../utils/logger.js';
4
3
  import { MAIN_CLI_BIN } from '../../product.js';
5
4
  const OWNERSHIP_OPERATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6
5
  export function ownershipFailure(error) {
@@ -15,21 +14,31 @@ export function ownershipFailure(error) {
15
14
  }
16
15
  export function parseOwnershipCommand(argv) {
17
16
  const args = argv[0] === 'aid' ? argv.slice(1) : [...argv];
18
- if (args[0] !== 'bind' || !args[1]) {
19
- throw new OwnershipError('INVALID_ARGUMENT', `Use ${MAIN_CLI_BIN} aid bind <ownerAid>, status, accept, or reject`);
17
+ if (!args[0] || !args[1] || !['bind', 'transfer'].includes(args[0])) {
18
+ throw new OwnershipError('INVALID_ARGUMENT', `Use ${MAIN_CLI_BIN} aid bind <ownerAid>, transfer <subAid> <newOwnerAid>, status, accept, or reject`);
20
19
  }
21
- const action = ['status', 'accept', 'reject'].includes(args[1]) ? args[1] : 'bind';
20
+ const action = args[0] === 'transfer' ? 'transfer'
21
+ : ['status', 'accept', 'reject'].includes(args[1]) ? args[1] : 'bind';
22
22
  if (action === 'bind' && !isValidAid(args[1]))
23
23
  throw new OwnershipError('INVALID_AID', 'A valid owner AID is required');
24
+ if (action === 'transfer' && (!isValidAid(args[1]) || !isValidAid(args[2] ?? ''))) {
25
+ throw new OwnershipError('INVALID_AID', 'Valid sub and new owner AIDs are required');
26
+ }
24
27
  if ((action === 'accept' || action === 'reject') && !OWNERSHIP_OPERATION_ID.test(args[2] ?? '')) {
25
28
  throw new OwnershipError('INVALID_OPERATION', 'A valid ownership operation ID is required');
26
29
  }
27
30
  let subjectAid;
28
31
  let reason;
32
+ let refresh = false;
29
33
  let formatSeen = false;
30
34
  const positionalEnd = action === 'bind' || action === 'status' ? 2 : 3;
31
- for (let index = positionalEnd; index < args.length; index += 2) {
35
+ for (let index = positionalEnd; index < args.length;) {
32
36
  const flag = args[index];
37
+ if (flag === '--refresh' && action === 'status' && !refresh) {
38
+ refresh = true;
39
+ index += 1;
40
+ continue;
41
+ }
33
42
  const value = args[index + 1];
34
43
  if (flag === '--subject' && !subjectAid && isValidAid(value ?? '')) {
35
44
  subjectAid = value;
@@ -42,11 +51,14 @@ export function parseOwnershipCommand(argv) {
42
51
  reason = value;
43
52
  }
44
53
  else {
45
- throw new OwnershipError('INVALID_ARGUMENT', 'Supported options are --subject <subjectAid>, --reason <text>, and --format json');
54
+ throw new OwnershipError('INVALID_ARGUMENT', 'Supported options are --subject <subjectAid>, --reason <text>, --refresh (status only), and --format json');
46
55
  }
56
+ index += 2;
47
57
  }
48
58
  if (action === 'status')
49
- return { action, subjectAid };
59
+ return { action, subjectAid, ...(refresh ? { refresh } : {}) };
60
+ if (action === 'transfer')
61
+ return { action, subAid: args[1], newOwnerAid: args[2], subjectAid };
50
62
  if (action === 'accept')
51
63
  return { action, operationId: args[2], subjectAid };
52
64
  if (action === 'reject')
@@ -58,24 +70,13 @@ export async function executeOwnershipCommand(command, defaultSubjectAid) {
58
70
  if (!subjectAid)
59
71
  throw new OwnershipError('SUBJECT_REQUIRED', 'No local subject AID is available');
60
72
  if (command.action === 'status') {
61
- return ownerResolver.status(subjectAid);
73
+ return ownerResolver.status(subjectAid, { force: command.refresh === true });
62
74
  }
63
75
  if (command.action === 'accept' || command.action === 'reject') {
64
76
  return ownerResolver.decide(subjectAid, command.operationId, command.action, command.action === 'reject' ? command.reason : undefined);
65
77
  }
66
- logger.info(`[ownership] bind requested subject=${subjectAid} owner=${command.ownerAid}`);
67
- try {
68
- const result = await ownerResolver.bind(subjectAid, command.ownerAid);
69
- const task = result.task;
70
- const log = task && ['rejected', 'stopped', 'error'].includes(task.status) ? logger.warn : logger.info;
71
- log(`[ownership] bind result ${JSON.stringify({ subjectAid, ownerAid: command.ownerAid, operationId: task?.operation_id,
72
- taskStatus: task?.status, step: task?.step, consensusStatus: result.consensusStatus, requestStatus: result.requestStatus,
73
- code: task?.code, reason: task?.reason })}`);
74
- return result;
75
- }
76
- catch (error) {
77
- const details = ownershipFailure(error);
78
- logger.warn(`[ownership] bind failed subject=${subjectAid} owner=${command.ownerAid} code=${details.code} error=${JSON.stringify(details.error)}`);
79
- throw error;
78
+ if (command.action === 'transfer') {
79
+ return ownerResolver.transfer(subjectAid, command.subAid, command.newOwnerAid);
80
80
  }
81
+ return ownerResolver.bind(subjectAid, command.ownerAid);
81
82
  }
@@ -13,6 +13,8 @@ const MAX_TIMEOUT_MS = 120_000;
13
13
  const POLL_INTERVAL_MS = 200;
14
14
  const PULL_LIMIT = 50;
15
15
  const LOCK_STALE_MS = 5 * 60_000;
16
+ const DENIAL_CACHE_TTL_MS = 30 * 60_000;
17
+ const DENIAL_CACHE_LIMIT = 128;
16
18
  export class MenuClientError extends Error {
17
19
  code;
18
20
  data;
@@ -28,6 +30,7 @@ export class ManagedMenuClient {
28
30
  send;
29
31
  pending = new Map();
30
32
  eventHandlers = new Map();
33
+ deniedQueries = new Map();
31
34
  constructor(send) {
32
35
  this.send = send;
33
36
  }
@@ -68,6 +71,7 @@ export class ManagedMenuClient {
68
71
  for (const entry of this.eventHandlers.values())
69
72
  clearTimeout(entry.timer);
70
73
  this.eventHandlers.clear();
74
+ this.deniedQueries.clear();
71
75
  }
72
76
  async request(options) {
73
77
  if (!isValidAid(options.fromAid) || !isValidAid(options.targetAid))
@@ -85,6 +89,23 @@ export class ManagedMenuClient {
85
89
  if (this.pending.has(key))
86
90
  throw new MenuClientError('CLIENT_BUSY', 'Request ID is already in flight for this daemon');
87
91
  const headers = buildMenuClientProtectedHeaders({ clientName: 'ec-menu-client', clientVersion: readInstalledEvolcoreVersion(), remoteAccessToken: options.remoteAccessToken ?? options.ecwebToken });
92
+ const denialKey = request.type === 'menu.query' || request.type === 'menu.options'
93
+ ? crypto.createHash('sha256').update(JSON.stringify([
94
+ options.fromAid, options.targetAid, headers,
95
+ Object.fromEntries(Object.entries(request).filter(([field]) => field !== 'id')),
96
+ ])).digest('hex')
97
+ : undefined;
98
+ for (const [cachedKey, expires] of this.deniedQueries) {
99
+ if (expires <= Date.now())
100
+ this.deniedQueries.delete(cachedKey);
101
+ }
102
+ if (denialKey && this.deniedQueries.has(denialKey)) {
103
+ options.beforeSend?.();
104
+ return {
105
+ type: 'menu.response', id: request.id, name: request.name,
106
+ error: { code: 'NOT_ALLOWED', message: 'Remote query was denied; authorization denial cached for up to 30 minutes or until reconnect.' },
107
+ };
108
+ }
88
109
  if (options.onEvent && request.type === 'menu.action' && request.action === 'upgrade' && request.args?.mode === 'update') {
89
110
  const existing = this.eventHandlers.get(key);
90
111
  if (existing)
@@ -112,6 +133,12 @@ export class ManagedMenuClient {
112
133
  });
113
134
  try {
114
135
  const [, value] = await Promise.all([sent, response]);
136
+ if (denialKey && value.error?.code === 'NOT_ALLOWED') {
137
+ if (this.deniedQueries.size >= DENIAL_CACHE_LIMIT) {
138
+ this.deniedQueries.delete(this.deniedQueries.keys().next().value);
139
+ }
140
+ this.deniedQueries.set(denialKey, Date.now() + DENIAL_CACHE_TTL_MS);
141
+ }
115
142
  if (value.error || !(value.data && typeof value.data === 'object' && typeof value.data.jobId === 'string')) {
116
143
  const handler = this.eventHandlers.get(key);
117
144
  if (handler) {
@@ -104,9 +104,7 @@ function msgSendLogMetadata(args, payload, runtimeContext) {
104
104
  const isInSession = !!process.env.EVOLCORE_SESSION_ID || !!runtimeContext;
105
105
  const source = isInSession ? 'msg' : 'cli';
106
106
  const classified = payload === undefined ? undefined : classifyAunPayloadForLog(payload);
107
- const threadId = args.body.mode === 'payload'
108
- ? args.thread
109
- : msgSendThreadId(args, payload && typeof payload === 'object' ? payload : undefined, runtimeContext);
107
+ const threadId = msgSendThreadId(args, payload && typeof payload === 'object' ? payload : undefined, runtimeContext);
110
108
  const sessionId = runtimeContext?.channel === 'aun'
111
109
  && runtimeContext.chatType === 'private'
112
110
  && runtimeContext.selfAid === args.from
@@ -140,9 +138,7 @@ async function tryDaemonMsgSend(args, payload, runtimeContext, file) {
140
138
  if (args.slotId || args.aunPath) {
141
139
  return { ok: false, code: 'INVALID_DELEGATION', error: 'Task sends cannot override the daemon AUN connection' };
142
140
  }
143
- const thread = args.body.mode === 'payload'
144
- ? args.thread
145
- : msgSendThreadId(args, payload, runtimeContext);
141
+ const thread = args.body.mode === 'payload' ? undefined : msgSendThreadId(args, payload, runtimeContext);
146
142
  const response = await ipcQuery(resolvePaths().socket, {
147
143
  type: 'aun-msg-send',
148
144
  aid: args.from,
@@ -272,9 +268,8 @@ export async function msgSend(args) {
272
268
  if (args.body.mode !== 'payload' && Object.prototype.hasOwnProperty.call(payload, 'mentions')) {
273
269
  payload.mentions = normalizeAunMentionEntries(payload.mentions);
274
270
  }
275
- if (args.body.mode !== 'payload') {
271
+ if (args.body.mode !== 'payload')
276
272
  applyRoutingPayloadFields(payload, args, runtimeContext, false);
277
- }
278
273
  const daemonResult = await tryDaemonMsgSend(args, payload, runtimeContext);
279
274
  if (daemonResult)
280
275
  return daemonMsgSendResult(args, payload, runtimeContext, daemonResult);
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import fs from 'fs';
18
18
  import path from 'path';
19
+ import { setTimeout as delay } from 'node:timers/promises';
19
20
  import { ServiceProxyClient, EndpointPolicy } from '@agentunion/fastaun';
20
21
  import { resolvePaths } from '../paths.js';
21
22
  import { logger } from '../utils/logger.js';
@@ -24,6 +25,7 @@ import { getProcessStartTime, startTimeMatches } from '../utils/process-introspe
24
25
  const LOG = '[ServiceProxy]';
25
26
  const INSTANCE_DISCOVERY_TIMEOUT_MS = 10_000;
26
27
  const INSTANCE_DISCOVERY_INTERVAL_MS = 250;
28
+ const CONTROL_CONNECTION_INTERVAL_MS = 250;
27
29
  function sleep(ms) {
28
30
  return new Promise(resolve => setTimeout(resolve, ms));
29
31
  }
@@ -138,8 +140,18 @@ export function startServiceProxy(controlChannel, providerAid, configuredService
138
140
  }
139
141
  let stopped = false;
140
142
  let proxyClient = null;
143
+ const startupAbort = new AbortController();
141
144
  const run = async () => {
142
145
  try {
146
+ // 控制 AID 与本地服务并行启动;等待认证连接完成,避免把正常启动阶段当作隧道故障。
147
+ if (!controlChannel.isConnected()) {
148
+ logger.info(`${LOG} 等待 AUN 控制通道就绪后启动代理`);
149
+ }
150
+ while (!stopped && !controlChannel.isConnected()) {
151
+ await delay(CONTROL_CONNECTION_INTERVAL_MS, undefined, { signal: startupAbort.signal, ref: false });
152
+ }
153
+ if (stopped)
154
+ return { registered: 0, gatewayRegistered: false };
143
155
  // 动态解引用 facade:每次访问都读 channel 当前 client,规避重连换 client 的死引用问题。
144
156
  const aunFacade = {
145
157
  call: (method, params) => {
@@ -221,6 +233,8 @@ export function startServiceProxy(controlChannel, providerAid, configuredService
221
233
  catch (e) {
222
234
  logger.warn(`${LOG} Gateway 登记暂不可用,隧道后台继续重试: ${e?.message || e}`);
223
235
  }
236
+ if (stopped)
237
+ return { registered: 0, gatewayRegistered: false };
224
238
  // 常驻持久隧道(内部自带指数退避重连 + client 缺失时自动等待)。
225
239
  // 不 await:后台运行,不阻塞 daemon 启动。
226
240
  proxyClient
@@ -235,6 +249,8 @@ export function startServiceProxy(controlChannel, providerAid, configuredService
235
249
  return { registered, gatewayRegistered };
236
250
  }
237
251
  catch (e) {
252
+ if (stopped)
253
+ return { registered: 0, gatewayRegistered: false };
238
254
  logger.warn(`${LOG} 启动失败(不影响 daemon 主流程): ${e?.message || e}`);
239
255
  throw e;
240
256
  }
@@ -250,6 +266,7 @@ export function startServiceProxy(controlChannel, providerAid, configuredService
250
266
  },
251
267
  stop: () => {
252
268
  stopped = true;
269
+ startupAbort.abort();
253
270
  try {
254
271
  proxyClient?.stop();
255
272
  }