evolcore 0.0.40 → 0.0.41-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 (100) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/claude-runner.js +21 -106
  5. package/dist/agents/codex-runner.js +451 -231
  6. package/dist/agents/ecagent-runner.js +30 -11
  7. package/dist/agents/gemini-runner.js +26 -6
  8. package/dist/agents/runner-types.js +11 -3
  9. package/dist/aun/ability-device-routing.js +26 -0
  10. package/dist/aun/aid/client.js +1 -1
  11. package/dist/aun/group/identity.js +8 -0
  12. package/dist/aun/msg/managed-operation.js +4 -4
  13. package/dist/aun/msg/p2p.js +27 -7
  14. package/dist/aun/storage/download.js +30 -0
  15. package/dist/aun/storage/index.js +14 -6
  16. package/dist/channels/aun.js +33 -4
  17. package/dist/channels/daemon.js +24 -4
  18. package/dist/cli/agent-command.js +2 -0
  19. package/dist/cli/agent-create.js +98 -19
  20. package/dist/cli/agent.js +10 -3
  21. package/dist/cli/aun-commands.js +82 -22
  22. package/dist/cli/daemon-commands.js +19 -10
  23. package/dist/cli/index.js +1 -1
  24. package/dist/cli/restart-monitor.js +17 -0
  25. package/dist/cli/session-command.js +128 -13
  26. package/dist/cli/stats.js +60 -4
  27. package/dist/cli/trigger-command.js +2 -2
  28. package/dist/config/access-policy.js +2 -0
  29. package/dist/config/config-operation-service.js +17 -6
  30. package/dist/config/gateway-config.js +1 -1
  31. package/dist/config/peer-role-resolver.js +10 -8
  32. package/dist/core/agent-application-service.js +11 -1
  33. package/dist/core/agent-ipc-registration.js +4 -0
  34. package/dist/core/auth/agent-delegation.js +80 -5
  35. package/dist/core/auth/authorization-audit.js +20 -3
  36. package/dist/core/auth/operation-catalog.js +8 -0
  37. package/dist/core/command/agent-control.js +91 -12
  38. package/dist/core/command/command-handler.js +57 -46
  39. package/dist/core/command/connect-menu.js +23 -2
  40. package/dist/core/command/menu-catalog.js +1 -0
  41. package/dist/core/command/menu-handler.js +38 -101
  42. package/dist/core/command/menu-protocol.js +9 -2
  43. package/dist/core/command/role-menu.js +7 -6
  44. package/dist/core/command/slash-gate.js +13 -10
  45. package/dist/core/command/slash-handler.js +34 -98
  46. package/dist/core/event-catalog.js +15 -0
  47. package/dist/core/ipc-registration.js +18 -1
  48. package/dist/core/memory/consolidation-trigger.js +1 -1
  49. package/dist/core/message/aun-ipc-sender.js +26 -5
  50. package/dist/core/message/aun-request-registry.js +97 -3
  51. package/dist/core/message/im-renderer.js +4 -0
  52. package/dist/core/message/message-admission.js +8 -4
  53. package/dist/core/message/message-bridge.js +40 -6
  54. package/dist/core/message/message-log.js +55 -0
  55. package/dist/core/message/message-queue.js +5 -5
  56. package/dist/core/message/response-engine.js +310 -136
  57. package/dist/core/model/model-catalog.js +7 -6
  58. package/dist/core/ownership/owner-resolver.js +2 -2
  59. package/dist/core/permission/ec-command-parser.js +110 -5
  60. package/dist/core/permission/tool-policy.js +28 -7
  61. package/dist/core/session/session-capsule.js +197 -0
  62. package/dist/core/session/session-manager.js +148 -14
  63. package/dist/core/session/session-mapper.js +2 -0
  64. package/dist/index.js +3 -3
  65. package/dist/ipc.js +22 -8
  66. package/dist/stats/budget.js +1 -1
  67. package/dist/stats/db.js +15 -0
  68. package/dist/stats/index.js +2 -2
  69. package/dist/stats/price-resolver.js +304 -5
  70. package/dist/stats/query.js +82 -3
  71. package/dist/stats/writer.js +38 -5
  72. package/dist/trigger/feedback.js +18 -7
  73. package/dist/trigger/manager.js +20 -3
  74. package/dist/trigger/parser.js +6 -3
  75. package/dist/trigger/patch.js +1 -1
  76. package/dist/trigger/system-definitions.js +43 -7
  77. package/dist/trigger/validation.js +13 -5
  78. package/dist/utils/error-utils.js +14 -0
  79. package/dist/utils/npm-ops.js +2 -1
  80. package/dist/utils/package-version-info.js +1 -1
  81. package/dist/utils/upgrade-jobs.js +45 -5
  82. package/kits/docs/INDEX.md +1 -1
  83. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  84. package/kits/docs/evolcore/INDEX.md +2 -1
  85. package/kits/docs/evolcore/agent-create.md +3 -2
  86. package/kits/docs/evolcore/agent.md +1 -1
  87. package/kits/docs/evolcore/config.md +1 -1
  88. package/kits/docs/evolcore/event.md +1 -0
  89. package/kits/docs/evolcore/fs.md +5 -0
  90. package/kits/docs/evolcore/menu-protocol.md +32 -0
  91. package/kits/docs/evolcore/msg.md +17 -1
  92. package/kits/docs/evolcore/session.md +14 -0
  93. package/kits/schemas/agent-config.schema.13.json +15 -0
  94. package/kits/skills/aid-ability/SKILL.md +35 -6
  95. package/kits/templates/session-capsule/recovery.md +5 -0
  96. package/kits/templates/session-capsule/renew.md +5 -0
  97. package/kits/templates/system-fragments/bootstrap.md +6 -6
  98. package/kits/templates/system-fragments/channel.md +1 -1
  99. package/package.json +3 -3
  100. package/dist/stats/billing.js +0 -215
@@ -367,8 +367,9 @@ function buildAuditRecord(event) {
367
367
  : undefined;
368
368
  const errorCode = classification?.errorCode;
369
369
  const ecwebRequestId = event.source === 'ecweb' ? event.ecwebRequestId : undefined;
370
- const requestId = event.requestId ?? ecwebRequestId;
371
- const correlationId = event.correlationId ?? event.callId ?? requestId;
370
+ const sourceRequestId = event.requestId ?? ecwebRequestId;
371
+ const requestId = namespaceAuditRequestId(event.source, event.sessionId, sourceRequestId);
372
+ const correlationId = event.correlationId ?? event.callId ?? sourceRequestId;
372
373
  return {
373
374
  type: 'authorization:audit',
374
375
  ts: event.ts,
@@ -380,13 +381,14 @@ function buildAuditRecord(event) {
380
381
  sessionId: event.sessionId,
381
382
  callId: event.callId,
382
383
  correlationId,
383
- requestId,
384
+ requestId: sourceRequestId,
384
385
  operation: event.operation,
385
386
  })),
386
387
  eventPhase: event.eventPhase,
387
388
  callId: event.callId,
388
389
  correlationId,
389
390
  requestId,
391
+ sourceRequestId,
390
392
  sessionId: event.sessionId,
391
393
  ...(event.source === 'ecweb' && !event.sessionId ? { sessionScope: 'not_applicable' } : {}),
392
394
  agentAid: redactIdentifier(event.agentAid ?? event.selfAid),
@@ -438,6 +440,15 @@ function buildAuditRecord(event) {
438
440
  exitCode: event.exitCode,
439
441
  };
440
442
  }
443
+ function namespaceAuditRequestId(source, sessionId, sourceRequestId) {
444
+ if (sourceRequestId === undefined)
445
+ return undefined;
446
+ const namespace = source === 'ecweb' && !sessionId ? [source] : [source, sessionId ?? 'unknown'];
447
+ // JSON escaping also preserves unpaired UTF-16 surrogates from source IDs;
448
+ // encodeURIComponent alone would throw and interrupt authorization auditing.
449
+ const parts = [...namespace, sourceRequestId].map(part => encodeURIComponent(JSON.stringify(part).slice(1, -1)));
450
+ return `audit:v1:${parts.join(':')}`;
451
+ }
441
452
  function resolveAgentName(event) {
442
453
  const displayName = typeof event.agentName === 'string' ? event.agentName.trim() : '';
443
454
  if (displayName && !isUnknownAgentLabel(displayName))
@@ -493,6 +504,7 @@ function logAuditEvent(record) {
493
504
  record.taskId ? `task=${record.taskId}` : null,
494
505
  record.messageId ? `message=${record.messageId}` : null,
495
506
  record.requestId ? `request=${record.requestId}` : null,
507
+ record.sourceRequestId ? `sourceRequest=${JSON.stringify(record.sourceRequestId)}` : null,
496
508
  record.callId ? `call=${record.callId}` : null,
497
509
  record.correlationId ? `correlation=${record.correlationId}` : null,
498
510
  record.eventKey ? `eventKey=${record.eventKey}` : null,
@@ -601,6 +613,11 @@ function summarizeAuthorizationArgs(operation, args) {
601
613
  ? Math.max(0, Math.floor(diagnostic.inputLength)) : undefined;
602
614
  if (issue && offset !== undefined && tokenIndex !== undefined && dialect && inputLength !== undefined) {
603
615
  summary.parseFailure = { issue, offset, tokenIndex, dialect, inputLength };
616
+ for (const field of ['canonicalizationStage', 'wrapper', 'redirectDetected', 'managedTempPath', 'managedTempResolved']) {
617
+ if (typeof diagnostic[field] === 'string' || typeof diagnostic[field] === 'boolean') {
618
+ summary.parseFailure[field] = diagnostic[field];
619
+ }
620
+ }
604
621
  }
605
622
  continue;
606
623
  }
@@ -1046,6 +1046,14 @@ const OPERATIONS = [
1046
1046
  description: '删除云存储对象',
1047
1047
  sources: ['menu.cli', 'agent-tool', 'control'],
1048
1048
  },
1049
+ {
1050
+ id: 'storage.get_by_share',
1051
+ category: 'write-agent',
1052
+ dangerous: true,
1053
+ defaultScopes: ['agent', 'control'],
1054
+ description: '通过分享短码从云存储下载文件',
1055
+ sources: ['menu.cli', 'agent-tool', 'control'],
1056
+ },
1049
1057
  // ── Gateway & Config Operations ──
1050
1058
  {
1051
1059
  id: 'gateway.read',
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import { ownerResolver } from '../ownership/owner-resolver.js';
3
3
  import { agentFullAccessStatus, agentFullAccessWriteError } from '../role/runtime-policy.js';
4
- import { initializationSummary } from '../../cli/agent-create.js';
4
+ import { initializationSummary, validateInitializationModelArgs } from '../../cli/agent-create.js';
5
5
  import { agentDelete, agentEnable, agentDisable, agentList, agentShow, agentSet, agentReload, } from '../../cli/agent.js';
6
6
  import { agentCreateNonInteractive } from '../../cli/agent-create.js';
7
7
  import { logger } from '../../utils/logger.js';
@@ -546,18 +546,78 @@ export async function execAgentAction(action, args, peerId, eventBus, service, s
546
546
  if (action === 'initialize') {
547
547
  if (!service?.initialization)
548
548
  return { error: '初始化服务不可用', code: 'NOT_CONFIGURED' };
549
- const plan = a.plan && typeof a.plan === 'object' ? a.plan : {
550
- aid: a.aid,
551
- project: typeof a.project === 'string' ? a.project : '',
552
- baseagent: a.baseagent,
553
- owners: Array.isArray(a.owners) ? a.owners : (a.owner ? [a.owner] : []),
554
- name: a.name,
555
- description: a.description,
556
- type: a.type || 'agent',
557
- tags: a.tags,
558
- ...(typeof a.persona === 'string' ? { persona: a.persona } : {}),
549
+ if (!peerId)
550
+ return { error: '缺少发起者 AID', code: 'INVALID_ARGS' };
551
+ if (a.resume !== undefined && typeof a.resume !== 'boolean') {
552
+ return { error: 'resume 必须是布尔值', code: 'INVALID_ARGS' };
553
+ }
554
+ if (a.resume === true) {
555
+ const aid = typeof a.aid === 'string' ? a.aid.trim() : '';
556
+ if (!aid || !isValidAid(aid))
557
+ return { error: 'resume 需要有效的 aid', code: 'INVALID_ARGS' };
558
+ if (Object.keys(a).some(key => !['aid', 'resume', 'context'].includes(key))) {
559
+ return { error: '恢复请求不能携带新的初始化计划', code: 'INVALID_ARGS' };
560
+ }
561
+ try {
562
+ return { data: service.initialization.resume(aid, peerId) };
563
+ }
564
+ catch (error) {
565
+ return { error: error instanceof Error ? error.message : String(error), code: error.code || 'INITIALIZE_FAILED' };
566
+ }
567
+ }
568
+ if (a.plan !== undefined && (!a.plan || typeof a.plan !== 'object' || Array.isArray(a.plan))) {
569
+ return { error: 'plan 必须是对象', code: 'INVALID_ARGS' };
570
+ }
571
+ const supplied = a.plan && typeof a.plan === 'object' && !Array.isArray(a.plan) ? a.plan : {};
572
+ if (a.project !== undefined && supplied.project !== undefined
573
+ && typeof a.project === 'string' && typeof supplied.project === 'string'
574
+ && a.project.trim() && supplied.project.trim()
575
+ && a.project.trim() !== supplied.project.trim()) {
576
+ return { error: 'project 与 plan.project 必须一致', code: 'INVALID_ARGS' };
577
+ }
578
+ const aid = supplied.aid ?? a.aid;
579
+ if (typeof aid !== 'string' || !isValidAid(aid))
580
+ return { error: '无效 Agent AID', code: 'INVALID_ARGS' };
581
+ if (a.aid !== undefined && a.aid !== aid) {
582
+ return { error: 'aid 与 plan.aid 必须一致', code: 'INVALID_ARGS' };
583
+ }
584
+ for (const owners of [supplied.owners, a.owners]) {
585
+ if (owners !== undefined && (!Array.isArray(owners) || owners.length !== 1)) {
586
+ return { error: '初始化必须指定一位 Owner', code: 'INVALID_ARGS' };
587
+ }
588
+ }
589
+ const ownerAid = supplied.ownerAid ?? supplied.owner
590
+ ?? a.ownerAid ?? a.owner
591
+ ?? (Array.isArray(supplied.owners) ? supplied.owners[0] : undefined)
592
+ ?? (Array.isArray(a.owners) ? a.owners[0] : undefined);
593
+ const rawModel = supplied.model ?? a.model;
594
+ const rawEffort = supplied.effort ?? a.effort;
595
+ for (const [field, value] of [['model', rawModel], ['effort', rawEffort]]) {
596
+ if (value !== undefined && typeof value !== 'string') {
597
+ return { error: `${field} 必须是字符串`, code: 'INVALID_ARGS' };
598
+ }
599
+ }
600
+ const effort = typeof rawEffort === 'string' && rawEffort.trim() && rawEffort.trim() !== 'auto'
601
+ ? rawEffort.trim() : undefined;
602
+ const plan = {
603
+ aid,
604
+ project: supplied.project ?? a.project ?? '',
605
+ baseagent: supplied.baseagent ?? a.baseagent,
606
+ ...(typeof rawModel === 'string' && rawModel.trim() ? { model: rawModel.trim() } : {}),
607
+ ...(effort ? { effort } : {}),
608
+ ownerAid,
609
+ name: supplied.name ?? a.name,
610
+ description: supplied.description ?? a.description,
611
+ type: supplied.type ?? a.type ?? 'agent',
612
+ tags: supplied.tags ?? a.tags,
613
+ ...(typeof (supplied.persona ?? a.persona) === 'string' ? { persona: supplied.persona ?? a.persona } : {}),
614
+ ...(typeof (supplied.avatarFile ?? a.avatarFile) === 'string' ? { avatarFile: supplied.avatarFile ?? a.avatarFile } : {}),
615
+ ...(typeof (supplied.avatarUrl ?? a.avatarUrl) === 'string' ? { avatarUrl: supplied.avatarUrl ?? a.avatarUrl } : {}),
559
616
  };
560
617
  try {
618
+ const modelError = await validateInitializationModelArgs(plan);
619
+ if (modelError)
620
+ return modelError;
561
621
  return { data: service.initialization.start(plan, peerId, a.dryRun === true) };
562
622
  }
563
623
  catch (error) {
@@ -865,13 +925,31 @@ export async function execAgentQuery(args, service, subject) {
865
925
  const agentDir = path.join(resolvePaths().agentsDir, aid);
866
926
  const progress = readCreateStatus(agentDir);
867
927
  const initialization = initializationSummary(aid);
928
+ let usable;
929
+ if (initialization && service?.initialization) {
930
+ try {
931
+ const state = service.initialization.status(aid);
932
+ if (typeof state.usable === 'boolean')
933
+ usable = state.usable;
934
+ }
935
+ catch {
936
+ usable = false;
937
+ }
938
+ }
868
939
  const res = service
869
940
  ? await service.show(aid)
870
941
  : await agentShow(aid);
871
942
  if (!('ok' in res) || res.ok !== true) {
872
943
  const code = classifyError(res.error);
873
944
  if (code === 'NOT_FOUND' && initialization)
874
- return { data: { aid, lifecycle: service?.readConfig(aid)?.lifecycle ?? null, initialization } };
945
+ return {
946
+ data: {
947
+ aid,
948
+ lifecycle: service?.readConfig(aid)?.lifecycle ?? null,
949
+ initialization,
950
+ ...(usable === undefined ? {} : { usable }),
951
+ },
952
+ };
875
953
  if (code === 'NOT_FOUND' && progress)
876
954
  return { data: buildCreateProgressOnlyAgent(aid, progress) };
877
955
  return { error: res.error, code };
@@ -884,6 +962,7 @@ export async function execAgentQuery(args, service, subject) {
884
962
  const data = {
885
963
  ...res,
886
964
  ...(initialization ? { initialization } : {}),
965
+ ...(usable === undefined ? {} : { usable }),
887
966
  config: {
888
967
  ...(res.config ?? {}),
889
968
  active_baseagent: safeAgentConfig.active_baseagent ?? res.config?.baseagent ?? null,
@@ -804,7 +804,7 @@ export class CommandHandler {
804
804
  reliability: {
805
805
  concurrency: 'forbid',
806
806
  missedPolicy: 'run_once',
807
- retry: { maxAttempts: 0, backoffMs: 30_000 },
807
+ retry: { maxAttempts: 1, backoffMs: 30_000 },
808
808
  },
809
809
  limits: this.limitsFromParsed(parsed),
810
810
  };
@@ -2742,21 +2742,49 @@ export class CommandHandler {
2742
2742
  if (sessionSelfAid && sessionSelfAid !== actorAid) {
2743
2743
  return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation self agent does not match the active session' };
2744
2744
  }
2745
- const isSelfPersonalTarget = parsed.command.targetAid === actorAid;
2746
- let currentPrivatePeer;
2747
- let currentGroup;
2748
- if (grant.channelType === 'aun' && grant.chatType === 'private') {
2745
+ let relationId;
2746
+ try {
2747
+ const relation = parsePeerKey(grant.peerKey);
2748
+ if (relation.channelType !== grant.channelType)
2749
+ throw new Error('relation channel mismatch');
2750
+ relationId = relation.channelId;
2751
+ }
2752
+ catch {
2753
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation contains an invalid relation key' };
2754
+ }
2755
+ const isSelfTarget = parsed.command.targetAid === actorAid;
2756
+ const isCurrentPrivatePeerCat = grant.channelType === 'aun'
2757
+ && grant.chatType === 'private'
2758
+ && parsed.command.kind === 'cat'
2759
+ && parsed.command.targetAid === relationId;
2760
+ let storageBackend;
2761
+ if (isSelfTarget) {
2762
+ storageBackend = 'personal';
2763
+ }
2764
+ else {
2765
+ let targetType;
2749
2766
  try {
2750
- currentPrivatePeer = parsePeerKey(grant.peerKey).channelId;
2767
+ const card = await agentmdGet(parsed.command.targetAid, { withVerification: true, remoteOnly: true });
2768
+ if (card.verification.status !== 'verified') {
2769
+ return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md verification did not succeed' };
2770
+ }
2771
+ const frontmatter = card.content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
2772
+ const document = frontmatter ? parseDocument(frontmatter) : undefined;
2773
+ const rawTargetType = document && document.errors.length === 0
2774
+ ? document.toJS()?.type
2775
+ : undefined;
2776
+ targetType = typeof rawTargetType === 'string' ? rawTargetType.trim().toLowerCase() : undefined;
2777
+ if (!targetType) {
2778
+ return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md has no valid type' };
2779
+ }
2751
2780
  }
2752
2781
  catch {
2753
- return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation contains an invalid relation key' };
2782
+ return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md could not be verified' };
2754
2783
  }
2784
+ storageBackend = targetType === 'group' ? 'group' : 'personal';
2755
2785
  }
2756
- const isCurrentPrivatePeerCat = parsed.command.kind === 'cat'
2757
- && currentPrivatePeer !== undefined
2758
- && parsed.command.targetAid === currentPrivatePeer;
2759
- if (isSelfPersonalTarget) {
2786
+ let currentGroup;
2787
+ if (storageBackend === 'personal' && isSelfTarget) {
2760
2788
  if (grant.issuedRole !== 'owner' && !hasTrustedFullAccessDelegation(grant)) {
2761
2789
  return { ok: false, code: 'NO_PERMISSION', error: 'Managed personal storage requires the current Agent owner relation' };
2762
2790
  }
@@ -2764,56 +2792,39 @@ export class CommandHandler {
2764
2792
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Only the current Agent can access its personal storage' };
2765
2793
  }
2766
2794
  }
2767
- else if (isCurrentPrivatePeerCat) {
2795
+ else if (storageBackend === 'personal' && isCurrentPrivatePeerCat) {
2768
2796
  if (parsed.command.actorAid && parsed.command.actorAid !== actorAid) {
2769
2797
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Managed fs cannot switch the execution identity with --as' };
2770
2798
  }
2771
2799
  }
2772
- else {
2773
- const trustedFullAccess = hasTrustedFullAccessDelegation(grant);
2774
- if (trustedFullAccess) {
2775
- let targetType;
2776
- try {
2777
- const card = await agentmdGet(parsed.command.targetAid, { withVerification: true, remoteOnly: true });
2778
- if (card.verification.status !== 'verified') {
2779
- return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md verification did not succeed' };
2780
- }
2781
- const frontmatter = card.content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];
2782
- const document = frontmatter ? parseDocument(frontmatter) : undefined;
2783
- targetType = document && document.errors.length === 0
2784
- ? String(document.toJS()?.type ?? '').trim().toLowerCase()
2785
- : undefined;
2786
- }
2787
- catch {
2788
- return { ok: false, code: 'INVALID_TARGET', error: 'Target AID agent.md could not be verified' };
2789
- }
2790
- if (targetType !== 'group') {
2791
- return { ok: false, code: 'INVALID_TARGET', error: 'Managed group storage requires a verified group AID' };
2792
- }
2793
- }
2800
+ else if (storageBackend === 'group') {
2794
2801
  if (!hasTrustedFullAccessDelegation(grant) && (grant.channelType !== 'aun' || grant.chatType !== 'group')) {
2795
- return { ok: false, code: 'SCOPE_MISMATCH', error: 'Managed group fs operations require the current AUN group relation' };
2796
- }
2797
- try {
2798
- currentGroup = parsePeerKey(grant.peerKey).channelId;
2799
- }
2800
- catch {
2801
- return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation contains an invalid relation key' };
2802
+ return { ok: false, code: 'SCOPE_MISMATCH', error: 'Group storage requires the current AUN group relation' };
2802
2803
  }
2804
+ if (grant.channelType === 'aun' && grant.chatType === 'group')
2805
+ currentGroup = relationId;
2803
2806
  if (parsed.command.actorAid && parsed.command.actorAid !== actorAid) {
2804
2807
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Managed fs cannot switch the execution identity with --as' };
2805
2808
  }
2806
2809
  if (!hasTrustedFullAccessDelegation(grant)
2807
- && !sameGroupAid(parsed.command.targetAid, currentGroup)) {
2810
+ && (!currentGroup || !sameGroupAid(parsed.command.targetAid, currentGroup))) {
2808
2811
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Only the current AUN group can be targeted' };
2809
2812
  }
2810
2813
  }
2814
+ else {
2815
+ return {
2816
+ ok: false,
2817
+ code: 'SCOPE_MISMATCH',
2818
+ error: 'Managed personal storage is limited to the current Agent and cat of the current AUN private peer',
2819
+ };
2820
+ }
2811
2821
  const resolvedCommand = parsed.command;
2812
- resolvedCommand.storageBackend = isSelfPersonalTarget || isCurrentPrivatePeerCat ? 'personal' : 'group';
2813
- resolvedCommand.actorAid = hasTrustedFullAccessDelegation(grant) && !isSelfPersonalTarget && !isCurrentPrivatePeerCat
2822
+ resolvedCommand.storageBackend = storageBackend;
2823
+ resolvedCommand.actorAid = hasTrustedFullAccessDelegation(grant) && !isSelfTarget && !isCurrentPrivatePeerCat
2814
2824
  ? (resolvedCommand.actorAid ?? actorAid)
2815
2825
  : actorAid;
2816
- const relationTarget = currentPrivatePeer ?? currentGroup;
2826
+ const relationTarget = currentGroup
2827
+ ?? (grant.channelType === 'aun' && grant.chatType === 'private' ? relationId : undefined);
2817
2828
  const subject = buildAuthSubject({
2818
2829
  selfAid: grant.selfAid,
2819
2830
  actorId: grant.actorId,
@@ -2846,7 +2857,7 @@ export class CommandHandler {
2846
2857
  subject,
2847
2858
  intent: {
2848
2859
  operation: parsed.command.operationId,
2849
- scope: isSelfPersonalTarget ? 'agent' : 'relation',
2860
+ scope: isSelfTarget ? 'agent' : 'relation',
2850
2861
  source: 'agent-tool',
2851
2862
  args: intentArgs,
2852
2863
  },
@@ -3,6 +3,7 @@ import { getContactSnapshot, resolveContactView } from '../../config/contact-boo
3
3
  import { mutateAccessPolicy, readAccessPolicySnapshot, } from '../../config/access-policy.js';
4
4
  import { expirePendingContactRequests, addContact, mutateContactWithOperation, reviewContactRequest, } from '../../config/contact-request-service.js';
5
5
  import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
6
+ import { isValidAid } from '../../aun/aid/validation.js';
6
7
  /**
7
8
  * Connect Menu — 联系人与关系管理协议
8
9
  *
@@ -31,7 +32,7 @@ export function connectMenuOperation(kind, args, value) {
31
32
  if (kind === 'action')
32
33
  return 'connect.write';
33
34
  const resource = String(args?.resource ?? '');
34
- if (resource === 'policyMode' || resource === 'requestLimit') {
35
+ if (isAccessUpdateResource(resource)) {
35
36
  return 'connect.access.write';
36
37
  }
37
38
  if (resource === 'admin')
@@ -100,7 +101,7 @@ async function handleOptions(self, args, context) {
100
101
  {
101
102
  option: 'access',
102
103
  label: '访问设置',
103
- description: '设置消息准入模式和准入控制消息限额',
104
+ description: '设置外部联系开关、指定 AID 名单、消息准入模式和准入控制消息限额',
104
105
  },
105
106
  ],
106
107
  });
@@ -265,6 +266,8 @@ async function handleAction(req, self, context) {
265
266
  }
266
267
  function isAccessUpdateResource(resource) {
267
268
  return resource === 'policyMode'
269
+ || resource === 'allowExternalContacts'
270
+ || resource === 'allowedAids'
268
271
  || resource === 'requestLimit';
269
272
  }
270
273
  function updateAccessResource(req, context, resource) {
@@ -281,6 +284,18 @@ function updateAccessResource(req, context, resource) {
281
284
  return fail('INVALID_ARGUMENT', 'policyMode must be open, contacts, or owners');
282
285
  }
283
286
  }
287
+ else if (resource === 'allowExternalContacts') {
288
+ if (typeof decoded !== 'boolean') {
289
+ return fail('INVALID_ARGUMENT', 'allowExternalContacts must be a JSON boolean');
290
+ }
291
+ }
292
+ else if (resource === 'allowedAids') {
293
+ if (!Array.isArray(decoded)
294
+ || decoded.some(aid => typeof aid !== 'string' || !isValidAid(aid))
295
+ || new Set(decoded).size !== decoded.length) {
296
+ return fail('INVALID_ARGUMENT', 'allowedAids must be a JSON array of unique valid AIDs');
297
+ }
298
+ }
284
299
  else {
285
300
  const requestLimit = decoded;
286
301
  if (!requestLimit || typeof requestLimit !== 'object' || Array.isArray(requestLimit)
@@ -534,6 +549,12 @@ function accessPolicyWithUpdate(current, resource, decoded) {
534
549
  if (resource === 'policyMode') {
535
550
  return { ...current, policyMode: decoded };
536
551
  }
552
+ if (resource === 'allowExternalContacts') {
553
+ return { ...current, allowExternalContacts: decoded };
554
+ }
555
+ if (resource === 'allowedAids') {
556
+ return { ...current, allowedAids: [...decoded] };
557
+ }
537
558
  const requestLimit = decoded;
538
559
  return {
539
560
  ...current,
@@ -121,6 +121,7 @@ const ENTRIES = [
121
121
  { id: 'system.paircode', type: 'action', contexts: ['process'], name: 'system', label: '获取配对码', section: 'process', order: 35, action: { cmd: '/system', action: 'paircode', operation: 'system.paircode', scope: 'process' } },
122
122
  { id: 'agent.list', type: 'list', contexts: ['process'], name: 'agent', label: 'Agent 列表', section: 'process', order: 40, options: { cmd: '/agent', args: { options: 'all' }, operation: 'agent.list', scope: 'control', mode: 'dynamic' }, control: 'list' },
123
123
  { id: 'agent.create', type: 'action', contexts: ['process'], name: 'agent', label: '创建 Agent', section: 'process', order: 50, action: { cmd: '/agent', action: 'create', operation: 'agent.create', scope: 'control' } },
124
+ { id: 'agent.initialize', type: 'action', contexts: ['process'], name: 'agent', label: '初始化 Agent', section: 'process', order: 55, action: { cmd: '/agent', action: 'initialize', operation: 'agent.initialize', scope: 'control' } },
124
125
  { id: 'agent.reload', type: 'action', contexts: ['process'], name: 'agent', label: '重载 Agent', section: 'process', order: 60, action: { cmd: '/agent', action: 'reload', operation: 'agent.reload', scope: 'control' } },
125
126
  { id: 'agent.delete', type: 'action', contexts: ['process'], name: 'agent', label: '删除 Agent', section: 'process', order: 70, action: { cmd: '/agent', action: 'delete', operation: 'agent.delete', scope: 'control' } },
126
127
  ];
@@ -26,6 +26,8 @@ import { loadDefaults, loadDaemonConfig } from '../../config-store.js';
26
26
  import { WEB_PACKAGE_NAME, RESTART_REQUEST_ID_ENV, RUNTIME_HOME_ENV, SESSION_ID_ENV } from '../../product.js';
27
27
  import { read as cfgRead, resolveEffective, resolveEffectiveFieldWithSource, routeFieldPath, write as cfgWrite, ConfigTarget, } from '../../config/config-manager.js';
28
28
  import { execAgentAction, execAgentQuery, execAgentOptions, execAidAvatar, resolveProjectPath } from './agent-control.js';
29
+ import { readInitialization } from '../../cli/agent-create.js';
30
+ import { isValidAid } from '../../aun/aid/validation.js';
29
31
  import { gatewayList, gatewayUpdate, gatewayDelete, gatewayTest, gatewayModels, gatewaySetPrice, gatewaySyncEnv } from '../../config/gateway-config.js';
30
32
  import { displaySessionTitle } from '../session/session-title.js';
31
33
  import { buildTranscriptTurns } from '../session/session-transcript.js';
@@ -3229,113 +3231,20 @@ export async function execMenuUpdate(cmd, value, channel, channelId, userId, ove
3229
3231
  return { error: `无效 baseagent: ${arg},可选: ${valid.join(' / ')}`, code: 'INVALID_VALUE' };
3230
3232
  }
3231
3233
  const previousBaseagent = evolagent.baseagent;
3232
- const sessionTopicId = sessionTopicThreadId(session);
3233
- if (session && sessionTopicId) {
3234
- if (transportReplyContext?.threadId !== sessionTopicId) {
3235
- return { error: '话题路由上下文不匹配,拒绝切换', code: 'THREAD_CONTEXT_MISMATCH' };
3236
- }
3237
- if (typeof this.messageQueue.withSessionBarrier !== 'function') {
3238
- return { error: '当前运行环境不支持安全话题切换', code: 'NOT_SUPPORTED' };
3239
- }
3240
- const sessionKey = this.getQueueKey(session, channel, channelId);
3241
- const currentAgent = this.getAgent(channel, session.baseagent);
3242
- const outcome = await this.messageQueue.withSessionBarrier(sessionKey, async (snapshot) => {
3243
- const latest = await this.sessionManager.getSessionById?.(session.id);
3244
- if (!latest || sessionTopicThreadId(latest) !== sessionTopicId) {
3245
- return { error: '话题会话不存在或归属已变化', code: 'NOT_FOUND' };
3246
- }
3247
- const busy = !!latest.processingState
3248
- || !!latest.metadata?.turnState?.active
3249
- || snapshot.active
3250
- || snapshot.queued > 0
3251
- || snapshot.dispatching
3252
- || this.messageQueue.isProcessing?.(sessionKey)
3253
- || (this.messageQueue.getQueueLength?.(sessionKey) ?? 0) > 0
3254
- || currentAgent.hasActiveStream(sessionKey);
3255
- if (busy) {
3256
- return { error: '当前话题会话忙碌,无法切换 baseagent', code: 'BUSY' };
3257
- }
3258
- try {
3259
- evolagent.setActiveBaseagent(arg);
3260
- await this.sessionManager.rotateTopicBackend({
3261
- sessionId: latest.id,
3262
- expectedThreadId: sessionTopicId,
3263
- baseagent: arg,
3264
- });
3265
- return { ok: true };
3266
- }
3267
- catch (error) {
3268
- try {
3269
- evolagent.setActiveBaseagent(previousBaseagent);
3270
- }
3271
- catch { }
3272
- return { error: error instanceof Error ? error.message : String(error), code: 'EXEC_FAILED' };
3273
- }
3274
- });
3275
- if ('error' in outcome)
3276
- return outcome;
3277
- this.eventBus.publish({
3278
- type: 'agent:baseagent-changed',
3279
- aid: evolagent.aid,
3280
- baseagent: arg,
3281
- previousBaseagent,
3282
- scope: 'agent',
3283
- timestamp: Date.now(),
3284
- });
3285
- return { data: {
3286
- baseagent: arg,
3287
- previousBaseagent,
3288
- baseagentChanged: previousBaseagent !== arg,
3289
- scope: 'agent',
3290
- sessionId: session.id,
3291
- threadId: sessionTopicId,
3292
- sessionIdChanged: false,
3293
- notice: '已切换 Baseagent: ' + previousBaseagent + ' → ' + arg + ',话题会话 ID 保持不变',
3294
- } };
3295
- }
3296
3234
  try {
3297
3235
  evolagent.setActiveBaseagent(arg);
3298
3236
  }
3299
3237
  catch (error) {
3300
3238
  return { error: error instanceof Error ? error.message : String(error), code: 'INVALID_VALUE' };
3301
3239
  }
3302
- try {
3303
- const newSession = await this.sessionManager.createNewSession(channel, channelId, evolagent.projectPath, undefined, arg, session?.metadata, { previousBaseagent, baseagentChanged: previousBaseagent !== arg });
3304
- if (session) {
3305
- try {
3306
- const previousAgent = this.getAgent(channel, session.baseagent);
3307
- await previousAgent.clearSession(session.id, session.agentSessionId || '', session.projectPath);
3308
- await previousAgent.closeSession(session.id);
3309
- }
3310
- catch (error) {
3311
- // The new Evolcore session is already active; backend cleanup is best effort.
3312
- logger.warn(`[Menu] baseagent switch cleanup failed: session=${session.id}: ${error instanceof Error ? error.message : String(error)}`);
3313
- }
3314
- }
3315
- this.eventBus.publish({
3316
- type: 'agent:baseagent-changed',
3317
- aid: evolagent.aid,
3318
- baseagent: arg,
3319
- previousBaseagent,
3320
- scope: 'agent',
3321
- timestamp: Date.now(),
3322
- });
3323
- return { data: {
3324
- baseagent: arg,
3325
- previousBaseagent,
3326
- baseagentChanged: previousBaseagent !== arg,
3327
- scope: 'agent',
3328
- sessionId: newSession.id,
3329
- notice: `已切换 Baseagent: ${previousBaseagent} → ${arg},已创建新的主会话`,
3330
- } };
3331
- }
3332
- catch (error) {
3333
- try {
3334
- evolagent.setActiveBaseagent(previousBaseagent);
3335
- }
3336
- catch { }
3337
- return { error: `创建新会话失败:${error instanceof Error ? error.message : String(error)}`, code: 'EXEC_FAILED' };
3338
- }
3240
+ this.eventBus.publish({ type: 'agent:baseagent-changed', aid: evolagent.aid,
3241
+ baseagent: arg, previousBaseagent, scope: 'agent', timestamp: Date.now() });
3242
+ return { data: {
3243
+ baseagent: arg, previousBaseagent, baseagentChanged: previousBaseagent !== arg, scope: 'agent',
3244
+ sessionId: session?.id, sessionIdChanged: false,
3245
+ notice: `新会话默认 Baseagent: ${previousBaseagent} → ${arg}`
3246
+ + (session ? `,当前会话继续使用 ${session.baseagent}` : ''),
3247
+ } };
3339
3248
  }
3340
3249
  if (cmdBase === '/model') {
3341
3250
  const target = resolveMenuModelTarget.call(this, {
@@ -3767,6 +3676,34 @@ export async function execMenuAction(cmd, action, args, channel, channelId, user
3767
3676
  if (action === 'create') {
3768
3677
  a.project = resolveProjectPath(a.project, a.aid ?? '', loadDefaults());
3769
3678
  }
3679
+ else if (action === 'initialize' && a.resume !== true) {
3680
+ const suppliedPlan = a.plan && typeof a.plan === 'object' && !Array.isArray(a.plan) ? a.plan : undefined;
3681
+ const aid = suppliedPlan?.aid ?? a.aid ?? '';
3682
+ if (typeof aid !== 'string' || !isValidAid(aid))
3683
+ return { error: '无效 Agent AID', code: 'INVALID_ARGS' };
3684
+ if ([suppliedPlan?.project, a.project].some(project => project !== undefined && typeof project !== 'string')) {
3685
+ return { error: 'project 必须是字符串', code: 'INVALID_ARGS' };
3686
+ }
3687
+ const explicitProject = typeof suppliedPlan?.project === 'string' && suppliedPlan.project.trim()
3688
+ ? suppliedPlan.project
3689
+ : typeof a.project === 'string' && a.project.trim()
3690
+ ? a.project
3691
+ : undefined;
3692
+ let previousProject;
3693
+ if (!explicitProject) {
3694
+ try {
3695
+ previousProject = readInitialization(aid)?.plan.project;
3696
+ }
3697
+ catch {
3698
+ return { error: '初始化状态无效', code: 'INITIALIZE_STATE_INVALID' };
3699
+ }
3700
+ }
3701
+ const project = previousProject ?? resolveProjectPath(explicitProject, aid, loadDefaults());
3702
+ if (suppliedPlan)
3703
+ a.plan = { ...suppliedPlan, project };
3704
+ else
3705
+ a.project = project;
3706
+ }
3770
3707
  // queue-clear:清空指定 agent 的待处理消息(不影响处理中),直接走 messageQueue。
3771
3708
  if (action === 'queue-clear') {
3772
3709
  if (!a.aid)
@@ -31,7 +31,8 @@ export function parseMenuEvent(value) {
31
31
  export function buildMenuClientProtectedHeaders(input) {
32
32
  const clientName = input.clientName ?? 'evol';
33
33
  if (clientName === 'ec-menu-client') {
34
- const clientVersion = input.clientVersion?.trim();
34
+ // Menu compatibility uses the base version; installed/logged versions retain the test suffix.
35
+ const clientVersion = input.clientVersion?.trim().replace(/-test\.(0|[1-9]\d*)$/, '');
35
36
  if (!parseStableSemver(clientVersion)) {
36
37
  throw Object.assign(new Error('ec-menu-client requires a stable X.Y.Z client version'), { code: 'INVALID_CLIENT' });
37
38
  }
@@ -498,7 +499,7 @@ const INVALID_ARGUMENT_CODES = new Set([
498
499
  'ARGUMENT_MISMATCH', 'INVALID_ARGS', 'INVALID_DELEGATION',
499
500
  'INVALID_FIELD', 'INVALID_REVISION', 'INVALID_SCOPE', 'INVALID_TYPE', 'INVALID_VALUE', 'MISSING_AID',
500
501
  'MISSING_ARGV', 'MISSING_BASEAGENT', 'MISSING_CMD', 'MISSING_PEER', 'MISSING_VALUE',
501
- 'REVISION_REQUIRED', 'ROLE_VIOLATION',
502
+ 'REVISION_REQUIRED', 'ROLE_VIOLATION', 'INITIALIZE_FIELDS_REQUIRED',
502
503
  ]);
503
504
  const STABLE_CODES = new Set([
504
505
  'ROLE_ACCESS_DENIED', 'PERMISSION_DENIED', 'UNAUTHORIZED', 'FORBIDDEN',
@@ -515,6 +516,12 @@ const STABLE_CODES = new Set([
515
516
  'LOOP_TRIGGER_NOT_FOUND', 'LOOP_TRIGGER_DISABLED', 'LOOP_TRIGGER_INVALID',
516
517
  'ROOT_NOT_FOUND', 'ROOT_FORBIDDEN', 'ROOT_EXPIRED', 'ROOT_SCOPE_MISMATCH', 'ROOT_PEER_MISMATCH',
517
518
  'INVALID_ROOT_ID', 'MISSING_ROOT_ID', 'INVALID_ROOT_PATH', 'NOT_A_DIRECTORY', 'FILE_TOO_LARGE',
519
+ // Agent initialization uses these codes to distinguish a retryable failure,
520
+ // an actor mismatch, and a plan/state conflict at the App boundary.
521
+ 'INITIALIZE_PLAN_CONFLICT', 'INITIALIZE_OWNER_MISMATCH', 'INITIALIZE_CANCELLED',
522
+ 'INITIALIZE_STATE_INVALID', 'INITIALIZE_TARGET_CHANGED', 'INITIALIZE_TARGET_EXISTS',
523
+ 'INITIALIZE_AGENTMD_VERIFY_FAILED', 'INITIALIZE_OWNER_CONFLICT', 'INITIALIZE_AVATAR_FAILED',
524
+ 'INITIALIZE_FAILED', 'MODEL_UNAVAILABLE',
518
525
  ]);
519
526
  export function normalizeMenuError(error) {
520
527
  const source = error && typeof error === 'object' ? error : {};