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
package/dist/cli/agent.js CHANGED
@@ -4,7 +4,7 @@ import path from 'path';
4
4
  import { SESSION_ID_ENV } from '../product.js';
5
5
  import { resolvePaths, agentMdPath as getAgentMdPathFromPaths, agentPersonalDir, agentWelcomePath, aunPath as defaultAunPath } from '../paths.js';
6
6
  import { loadDefaults, loadAllAgents, loadAgent, saveAgent, ensureAgentDirSkeleton } from '../config-store.js';
7
- import { initConfigManager } from '../config/config-manager.js';
7
+ import { assertAgentAidAvailable, assertAgentModelConfigured, initConfigManager } from '../config/config-manager.js';
8
8
  import { resolveConfigCommand } from '../config/resolved-config-op.js';
9
9
  import { executeResolvedConfigCommandAsync } from '../config/config-operation-service.js';
10
10
  import { ipcQuery, IpcTransportError } from '../ipc.js';
@@ -21,6 +21,7 @@ import { resolveAgentLifecycle } from '../config/lifecycle.js';
21
21
  import { initializationSummary } from './agent-create.js';
22
22
  import { parseAgentWelcomeMetadata, readAgentWelcomeTemplate, renderPostBootstrapWelcomeMessage, saveAgentWelcomeTemplate, validateWelcomeTemplate } from '../utils/welcome.js';
23
23
  import { RUNTIME_ENVIRONMENT_NAMES } from '../config/runtime-env.js';
24
+ import { removeAgentFiles } from '../core/agent-create-status.js';
24
25
  export { agentCreateInteractive, agentCreateNonInteractive, parseAgentOwnerArgs, resolveAgentCreatePlan, validateAgentCreatePlan, validateAgentOwnerOptions, } from './agent-create.js';
25
26
  /** Route agent lifecycle commands from a managed task through daemon IPC. */
26
27
  export async function runManagedAgentOperation(argv, timeoutMs = 60_000) {
@@ -364,6 +365,14 @@ export async function agentDisable(aid, options = {}) {
364
365
  return agentSetEnabled(aid, false, options);
365
366
  }
366
367
  async function agentSetEnabled(aid, enabled, options = {}) {
368
+ if (enabled) {
369
+ try {
370
+ assertAgentAidAvailable(aid);
371
+ }
372
+ catch (error) {
373
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
374
+ }
375
+ }
367
376
  const p = resolvePaths();
368
377
  let config;
369
378
  try {
@@ -375,6 +384,14 @@ async function agentSetEnabled(aid, enabled, options = {}) {
375
384
  if (!config) {
376
385
  return { ok: false, error: `Agent "${aid}" not found` };
377
386
  }
387
+ if (enabled) {
388
+ try {
389
+ assertAgentModelConfigured(aid);
390
+ }
391
+ catch (error) {
392
+ return { ok: false, code: error.code ?? 'CONFIG_ERROR', error: error.message ?? String(error) };
393
+ }
394
+ }
378
395
  const previousEnabled = config.enabled;
379
396
  config.enabled = enabled;
380
397
  saveAgent(config);
@@ -516,6 +533,12 @@ function readPersonaSource(file) {
516
533
  }
517
534
  /** Read or replace the current Agent's personal/persona.md. */
518
535
  export async function agentPersona(aid, options = {}) {
536
+ try {
537
+ assertAgentAidAvailable(aid);
538
+ }
539
+ catch (error) {
540
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
541
+ }
519
542
  if (options.text !== undefined && options.file !== undefined)
520
543
  return { ok: false, code: 'INVALID_ARGS', error: '--text 与 --file 不能同时使用' };
521
544
  const managedSession = !!process.env.EVOLCORE_SESSION_ID && !options.trustedLocal;
@@ -562,6 +585,12 @@ export async function agentPersona(aid, options = {}) {
562
585
  }
563
586
  /** Read or replace the current Agent's self-prepared Bootstrap welcome template. */
564
587
  export async function agentWelcome(aid, options = {}) {
588
+ try {
589
+ assertAgentAidAvailable(aid);
590
+ }
591
+ catch (error) {
592
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
593
+ }
565
594
  if (!isValidAid(aid))
566
595
  return { ok: false, code: 'INVALID_ARGS', error: 'Invalid Agent AID' };
567
596
  if (options.text !== undefined) {
@@ -645,6 +674,12 @@ export async function agentWelcome(aid, options = {}) {
645
674
  * running or reload fails, returns reloaded:false (no error).
646
675
  */
647
676
  export async function agentChannelUpsert(opts) {
677
+ try {
678
+ assertAgentAidAvailable(opts.aid);
679
+ }
680
+ catch (error) {
681
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
682
+ }
648
683
  const p = resolvePaths();
649
684
  const SUPPORTED_TYPES = new Set(['feishu', 'wechat', 'dingtalk', 'qqbot', 'wecom']);
650
685
  if (opts.channel.type === 'aun') {
@@ -710,15 +745,7 @@ export async function agentDelete(aid, purge = false) {
710
745
  stopped = !!result?.ok;
711
746
  }
712
747
  catch { }
713
- if (purge) {
714
- fs.rmSync(agentDir, { recursive: true, force: true });
715
- }
716
- else {
717
- fs.unlinkSync(configPath);
718
- // 清理构建进度文件(非 purge 删除只移除 config.json,需显式清理 create-status.json)
719
- const { removeCreateStatus } = await import('../core/message/create-status.js');
720
- removeCreateStatus(agentDir);
721
- }
748
+ await removeAgentFiles(aid, purge);
722
749
  // Trigger resync so daemon drops the agent
723
750
  try {
724
751
  await ipcQuery(p.socket, { type: 'evolagent.resync' });
@@ -728,6 +755,12 @@ export async function agentDelete(aid, purge = false) {
728
755
  }
729
756
  // ==================== agentRename ====================
730
757
  export async function agentRename(aid, name) {
758
+ try {
759
+ assertAgentAidAvailable(aid);
760
+ }
761
+ catch (error) {
762
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
763
+ }
731
764
  const config = loadAgent(aid);
732
765
  if (!config) {
733
766
  return { ok: false, error: `Agent "${aid}" not found` };
@@ -757,6 +790,12 @@ export async function agentRename(aid, name) {
757
790
  }
758
791
  // ==================== agentReady ====================
759
792
  export async function agentReady(aid, commandArgs) {
793
+ try {
794
+ assertAgentAidAvailable(aid);
795
+ }
796
+ catch (error) {
797
+ return { ok: false, code: 'CONTROL_AID_RESERVED', error: error.message };
798
+ }
760
799
  const managedSessionId = process.env.EVOLCORE_SESSION_ID;
761
800
  const taskSelfAid = managedSessionId ? readTaskRuntimeContextFromEnv()?.selfAid : undefined;
762
801
  if (taskSelfAid && taskSelfAid.replace(/^@/, '') !== aid.replace(/^@/, '')) {
@@ -1,29 +1,48 @@
1
- import { ipcQuery } from '../ipc.js';
1
+ import { ipcHostQuery, ipcQuery } from '../ipc.js';
2
2
  import { resolvePaths } from '../paths.js';
3
3
  import { parseOwnershipCommand, ownershipFailure } from '../aun/aid/ownership-operation.js';
4
- import { readDelegationCredential } from '../core/auth/agent-delegation.js';
5
- import { MAIN_CLI_BIN } from '../product.js';
4
+ import { AGENT_DELEGATION_TOKEN_ENV, CODEX_SESSION_TOKEN_ENV, readDelegationCredential } from '../core/auth/agent-delegation.js';
5
+ import { MAIN_CLI_BIN, SESSION_ID_ENV } from '../product.js';
6
6
  export async function cmdAidBind(args) {
7
7
  if (args.includes('--help') || args.includes('-h')) {
8
8
  console.log([
9
9
  `用法: ${MAIN_CLI_BIN} aid bind <ownerAid> [--subject <subjectAid>] [--format json]`,
10
- `${MAIN_CLI_BIN} aid bind status [--subject <subjectAid>] [--format json]`,
10
+ `用法: ${MAIN_CLI_BIN} aid transfer <subAid> <newOwnerAid> --subject <currentOwnerAid> [--format json]`,
11
+ `${MAIN_CLI_BIN} aid bind status [--refresh] [--subject <subjectAid>] [--format json]`,
11
12
  `${MAIN_CLI_BIN} aid bind accept <operationId> [--subject <subjectAid>] [--format json]`,
12
13
  `${MAIN_CLI_BIN} aid bind reject <operationId> [--reason <text>] [--subject <subjectAid>] [--format json]`,
14
+ '宿主 CLI 可显式加 --local-control 选择本地控制,并持有本地控制凭据;TTY 不授予权限。',
15
+ '同一 OS 用户可读取控制凭据,fullaccess 与宿主共用该信任边界。',
13
16
  ].join('\n'));
14
17
  return;
15
18
  }
16
19
  const formatJson = args.includes('--format') && args[args.indexOf('--format') + 1] === 'json';
17
20
  try {
18
- parseOwnershipCommand(['bind', ...args]);
19
- const sessionId = process.env.EVOLCORE_SESSION_ID;
20
- const delegationToken = sessionId ? readDelegationCredential() : undefined;
21
- if (sessionId && !delegationToken)
22
- throw Object.assign(new Error('Active task delegation is required'), { code: 'DELEGATION_REQUIRED' });
23
- const isDecision = args[0] === 'accept' || args[0] === 'reject';
24
- const response = await ipcQuery(resolvePaths().socket, {
25
- type: 'aid.ownership', argv: ['aid', 'bind', ...args],
26
- ...(sessionId ? { sessionId, delegationToken } : {}),
21
+ const requestedLocalControl = args.includes('--local-control');
22
+ if (args.filter(arg => arg === '--local-control').length > 1) {
23
+ throw Object.assign(new Error('Duplicate --local-control option'), { code: 'INVALID_ARGUMENT' });
24
+ }
25
+ const commandArgs = args.filter(arg => arg !== '--local-control');
26
+ const ownershipArgv = commandArgs[0] === 'transfer' ? commandArgs : ['bind', ...commandArgs];
27
+ const command = parseOwnershipCommand(ownershipArgv);
28
+ const sessionId = process.env[SESSION_ID_ENV];
29
+ const delegationToken = readDelegationCredential();
30
+ const managedContext = [SESSION_ID_ENV, AGENT_DELEGATION_TOKEN_ENV, CODEX_SESSION_TOKEN_ENV]
31
+ .some(key => process.env[key] !== undefined);
32
+ if (requestedLocalControl && managedContext) {
33
+ throw Object.assign(new Error('Task delegation cannot select host control authentication'), { code: 'INVALID_DELEGATION' });
34
+ }
35
+ // A clean standalone CLI keeps the historical syntax. Any managed marker,
36
+ // including a delegation token after session tampering, forces delegation.
37
+ const localControl = requestedLocalControl || !managedContext;
38
+ if (!localControl && (!sessionId?.trim() || !delegationToken)) {
39
+ throw Object.assign(new Error('Valid task delegation is required; host CLI must explicitly use --local-control'), { code: 'DELEGATION_REQUIRED' });
40
+ }
41
+ const isDecision = command.action === 'accept' || command.action === 'reject';
42
+ const query = localControl ? ipcHostQuery : ipcQuery;
43
+ const response = await query(resolvePaths().socket, {
44
+ type: 'aid.ownership', argv: ['aid', ...ownershipArgv],
45
+ ...(localControl ? { authMode: 'local-control' } : { sessionId, delegationToken }),
27
46
  }, isDecision ? 150_000 : 30_000);
28
47
  if (!response?.ok)
29
48
  throw Object.assign(new Error(response?.error ?? 'daemon 未运行或 IPC 不可用'), { code: response?.code, retryable: response?.retryable });
@@ -32,17 +51,27 @@ export async function cmdAidBind(args) {
32
51
  else {
33
52
  const state = response.state;
34
53
  console.log(`主体 AID: ${state.subjectAid}`);
35
- console.log(`协议 Owner: ${state.ownerAid ?? '未确认'}`);
36
- console.log(`共识状态: ${state.consensusStatus}`);
37
- if (state.consensus)
38
- console.log(`协议关系版本: ${state.consensus.relation_version}`);
54
+ console.log(`当前协议 Owner: ${state.ownerAid ?? '未确认'}`);
55
+ console.log(`当前共识状态: ${state.consensusStatus}`);
56
+ if (state.consensus && state.consensusStatus !== 'unavailable') {
57
+ console.log(`当前观察关系版本: ${state.consensus.relation_version}`);
58
+ }
59
+ if (state.relation && !state.relation.isCurrent) {
60
+ console.log(`最近已确认关系(历史快照): ${state.relation.consensusStatus} (owner=${state.relation.ownerAid ?? '-'}, version=${state.relation.relationVersion})`);
61
+ }
39
62
  console.log(`运行态同步: ${state.synchronization.status}`);
40
63
  if (state.task)
41
- console.log(`绑定任务: ${state.task.operation_id} (${state.task.status}/${state.task.step})`);
64
+ console.log(`SDK 动作记录(不代表绑定结论): ${state.task.operation_id} (${state.task.status}/${state.task.step})`);
42
65
  if (state.decisionTask)
43
- console.log(`审批任务: ${state.decisionTask.operation_id} (${state.decisionTask.status}/${state.decisionTask.step})`);
66
+ console.log(`审批 SDK 动作记录(不代表关系已成立): ${state.decisionTask.operation_id} (${state.decisionTask.status}/${state.decisionTask.step})`);
44
67
  if (state.decisionConsensus)
45
68
  console.log(`审批目标共识: ${state.decisionConsensus.status} (owner=${state.decisionConsensus.owner_aid ?? '-'}, version=${state.decisionConsensus.relation_version}, lock=${state.decisionConsensus.lock})`);
69
+ if (state.targetConsensus)
70
+ console.log(`转让目标共识: ${state.targetConsensus.status} (sub=${state.targetConsensus.sub_aid}, owner=${state.targetConsensus.owner_aid ?? '-'}, version=${state.targetConsensus.relation_version}, lock=${state.targetConsensus.lock})`);
71
+ for (const transfer of state.transfers ?? []) {
72
+ const consensus = transfer.consensus;
73
+ console.log(`Owner 转让: sub=${transfer.task.sub_aid}, newOwner=${transfer.task.new_owner_aid}, operation=${transfer.task.operation_id} (${transfer.task.status}/${transfer.task.step})${consensus ? `, 共识=${consensus.status}/${consensus.relation_version}/${consensus.lock}` : ''}`);
74
+ }
46
75
  for (const request of state.requests ?? []) {
47
76
  console.log(`待确认邀约: ${request.operation_id} (sub=${request.sub_aid}, owner=${request.owner_aid}, 本端=${request.local_role})`);
48
77
  }
@@ -472,7 +472,8 @@ Commands:
472
472
  agentmd set <aid> <field> <value> 修改一个字段并签名上传
473
473
  avatar <aid> --file <path> | --url <https-url> 上传头像并更新 agent.md
474
474
  bind <ownerAid> [--subject <subjectAid>] 发起 Ownership 2.1 绑定
475
- bind status [--subject <subjectAid>] 核验协议 Owner、任务和同步状态
475
+ transfer <subAid> <newOwnerAid> --subject <currentOwnerAid> 发起 Ownership 2.1 转让
476
+ bind status [--refresh] [--subject <subjectAid>] 核验协议 Owner、任务和同步状态(--refresh 强制重新查询)
476
477
  bind accept <operationId> [--subject <subjectAid>] 接受绑定邀约
477
478
  bind reject <operationId> [--reason <text>] [--subject <subjectAid>] 拒绝绑定邀约
478
479
 
@@ -495,9 +496,9 @@ Options:
495
496
  ec aid agentmd set mybot.agentid.pub description "A helpful agent"`);
496
497
  return;
497
498
  }
498
- if (sub === 'bind') {
499
+ if (sub === 'bind' || sub === 'transfer') {
499
500
  const { cmdAidBind } = await import('./aid-bind-command.js');
500
- await cmdAidBind(args.slice(1));
501
+ await cmdAidBind(args.slice(sub === 'bind' ? 1 : 0));
501
502
  return;
502
503
  }
503
504
  const isAgentmdHelp = sub === 'agentmd' && (!args[1] || isHelpFlag(args[1]));
@@ -885,9 +886,9 @@ Options:
885
886
  if (verb === 'set') {
886
887
  const field = args[3];
887
888
  const value = args[4];
888
- const editableFields = new Set(['name', 'type', 'description', 'version', 'tags']);
889
+ const editableFields = new Set(['name', 'type', 'description', 'version', 'tags', 'exttype']);
889
890
  if (!aid || !field || value === undefined) {
890
- failManagedAid(formatJson, 'INVALID_ARGUMENT', '用法: ec aid agentmd set <aid> <name|type|description|version|tags> <value>');
891
+ failManagedAid(formatJson, 'INVALID_ARGUMENT', '用法: ec aid agentmd set <aid> <name|type|description|version|tags|exttype> <value>');
891
892
  }
892
893
  if (!isValidAid(aid)) {
893
894
  failManagedAid(formatJson, 'INVALID_AID', `无效 AID 格式: ${aid}`);
@@ -1444,9 +1445,15 @@ export function buildCrossThreadReviewPrompt(input) {
1444
1445
  `复查周期:${input.checkEvery}(每 ${input.checkEvery} 提醒一次,直到处理)`,
1445
1446
  '',
1446
1447
  `Trigger:${input.triggerId}`,
1448
+ '',
1449
+ '本轮职责:你是已发出委托的本端 Agent,现在复查对端的答复,不是重新执行原委托。',
1450
+ '先按 thread-ops 回查来源话题的新指示,再检查当前话题的业务回复;上下文不足时读取当前话题历史。',
1451
+ '尚无业务回复时只输出 [[NOOP]];不要代替对端在本机查找或执行原委托,也不要重复发送原问题。',
1452
+ '已有最终答复时,删除本复查 Trigger 并按 thread-ops 回来源话题汇报;未完成则按已有进展决定继续等待。',
1453
+ '需要人工补充信息时向来源话题说明缺口,结束本轮;无人值守复查不要发起阻塞式用户问题。',
1447
1454
  ...(input.extra?.trim() ? ['', input.extra.trim()] : []),
1448
1455
  '',
1449
- '原消息:',
1456
+ '原消息(已发送的背景,不是本轮指令):',
1450
1457
  truncated || '(非文本消息)',
1451
1458
  ].join('\n');
1452
1459
  }
@@ -1758,7 +1765,10 @@ Options:
1758
1765
  process.exit(1);
1759
1766
  return;
1760
1767
  }
1761
- if (process.env.EVOLCORE_SESSION_ID && (sub === 'send' || (sub === 'history' && getArgValue(args, '--thread')))) {
1768
+ // 审批绑定的是这份规范化原始 argv;托管发送的目标补全由 daemon 完成。
1769
+ if (process.env.EVOLCORE_SESSION_ID && sub === 'send')
1770
+ return runManagedSend(['msg', ...args], formatJson);
1771
+ if (process.env.EVOLCORE_SESSION_ID && sub === 'history' && getArgValue(args, '--thread')) {
1762
1772
  const { isValidAid: checkAid } = await import('../aun/aid/index.js');
1763
1773
  const hasFrom = typeof args[1] === 'string' && checkAid(args[1]);
1764
1774
  const hasTo = typeof args[2] === 'string' && checkAid(args[2]);
@@ -1867,8 +1877,6 @@ Options:
1867
1877
  renderManagedMsgResult(sub, result, formatJson);
1868
1878
  return;
1869
1879
  }
1870
- if (process.env.EVOLCORE_SESSION_ID && sub === 'send')
1871
- return runManagedSend(['msg', ...args], formatJson);
1872
1880
  const { msgSend, msgPull, msgAck, msgRecall, msgOnline, msgHistory } = await import('../aun/msg/index.js');
1873
1881
  const commonOpts = { aunPath, slotId: appSlot };
1874
1882
  const requireConsumerSlot = (operation) => {
@@ -3466,21 +3474,30 @@ async function runManagedSend(argv, formatJson) {
3466
3474
  process.stderr.write(`⚠ 复查 Trigger 未创建: ${result.trigger_error}(消息已发出,需要复查请手动 ec trigger create)\n`);
3467
3475
  }
3468
3476
  }
3469
- export function resolveManagedSendArgv(argv) {
3470
- if (!['msg', 'group'].includes(argv[0]) || argv[1] !== 'send' || !validSendAid(argv[2]))
3477
+ /** routing 由 daemon 使用已核验的会话授权构造;补全结果不回写获批 argv。 */
3478
+ export function resolveManagedSendArgv(argv, routing) {
3479
+ if (!['msg', 'group'].includes(argv[0]) || argv[1] !== 'send')
3471
3480
  throw new Error('Invalid managed send command');
3472
3481
  const scope = argv[0];
3473
- const aid = argv[2];
3474
- const to = scope === 'group' ? normalizeGroupAid(argv[3], aid.slice(aid.indexOf('.') + 1)) : argv[3];
3475
- if (!to || !validSendAid(to))
3476
- throw new Error('Invalid send target');
3482
+ const hasFrom = validSendAid(argv[2]);
3483
+ const hasTo = hasFrom && (scope === 'group' || validSendAid(argv[3]));
3484
+ const canInferRoute = scope === 'msg' && routing !== undefined;
3485
+ if (!hasFrom && !canInferRoute)
3486
+ throw new Error('Invalid managed send command');
3487
+ const aid = hasFrom ? argv[2] : routing.selfAid;
3488
+ if (!validSendAid(aid))
3489
+ throw new Error('Invalid managed send command');
3490
+ if (canInferRoute && !hasTo && aid !== routing.selfAid) {
3491
+ throw new Error(`当前会话的本端是 ${routing.selfAid},无法为 ${aid} 补全发送目标`);
3492
+ }
3493
+ const bodyStart = hasFrom ? (hasTo ? 4 : 3) : 2;
3477
3494
  const values = new Map();
3478
3495
  const booleans = new Set();
3479
3496
  const text = [];
3480
3497
  const mentions = [];
3481
3498
  const valueFlags = new Set(['--format', '--file', '--payload', '--payload-file', '--text-from-file', '--link', '--title', '--description', '--as', '--content-type', '--text', '--transcript', '--thread', '--check-every', '--trigger-prompt', '--return', '--timeout', '--handoff-context', '--mention', '--self', '--device-id']);
3482
3499
  const booleanFlags = new Set(['--encrypt', '--no-encrypt', '--mention-all']);
3483
- for (let index = 4; index < argv.length; index++) {
3500
+ for (let index = bodyStart; index < argv.length; index++) {
3484
3501
  const flag = argv[index];
3485
3502
  if (flag === '--') {
3486
3503
  text.push(...argv.slice(index + 1));
@@ -3540,6 +3557,17 @@ export function resolveManagedSendArgv(argv) {
3540
3557
  throw new Error(`--self ${declaredSelf} 与当前会话本端 ${aid} 不一致`);
3541
3558
  }
3542
3559
  const thread = values.get('--thread');
3560
+ const inferredTarget = !hasTo && canInferRoute
3561
+ ? thread ? routing.resolveThreadPeer(thread) : routing.peerId
3562
+ : undefined;
3563
+ if (thread && !hasTo && canInferRoute && !inferredTarget) {
3564
+ throw Object.assign(new Error(`话题不存在或不属于当前本端: ${thread}`), { code: 'TOPIC_NOT_FOUND' });
3565
+ }
3566
+ const to = scope === 'group'
3567
+ ? normalizeGroupAid(argv[3], aid.slice(aid.indexOf('.') + 1))
3568
+ : hasTo ? argv[3] : inferredTarget;
3569
+ if (!to || !validSendAid(to))
3570
+ throw new Error('Invalid send target');
3543
3571
  const checkEvery = values.get('--check-every');
3544
3572
  const triggerPromptExtra = values.get('--trigger-prompt');
3545
3573
  if (!thread && (checkEvery !== undefined || triggerPromptExtra !== undefined))
@@ -232,6 +232,7 @@ function buildDaemonEnv(p, opts) {
232
232
  EVENT_LOG: process.env.EVENT_LOG || 'true',
233
233
  ...(opts.diagnose ? { EVOLCORE_DIAGNOSE: '1' } : {}),
234
234
  ...(opts.bindBootstrap ? { EVOLCORE_BIND_BOOTSTRAP: '1' } : {}),
235
+ ...(opts.webInit ? { EVOLCORE_WEB_INIT: '1' } : {}),
235
236
  ...(opts.debug ? { EVOLCORE_DEBUG_MODE: '1' } : {}),
236
237
  };
237
238
  }
package/dist/cli/index.js CHANGED
@@ -59,6 +59,7 @@ AUN:
59
59
 
60
60
  配置与诊断:
61
61
  config 读取、修改和检查分层配置
62
+ provider 管理 daemon 级 Provider 注册表与 JSON 导入
62
63
  stats Token 用量与费用统计
63
64
  diagnose 检查启动环境
64
65
  version 显示组件版本
@@ -111,7 +112,7 @@ export async function main(args) {
111
112
  // 注入完成后剥除 --as-session <sessionId> 两个参数,避免子命令把它们当作未知参数
112
113
  const strippedArgs = stripAsSessionArgs(args);
113
114
  try {
114
- assertManagedTopLevelCommandAllowed(cmd, strippedArgs);
115
+ await assertManagedTopLevelCommandAllowed(cmd, strippedArgs);
115
116
  }
116
117
  catch (error) {
117
118
  if (!(error instanceof ManagedCommandNotAllowedError))
@@ -143,6 +144,10 @@ export async function main(args) {
143
144
  --baseagent <claude|codex|gemini|ecagent> 默认: PATH 中第一个可用项;ecagent 需显式选择
144
145
  --force 已存在 defaults.json 时覆盖
145
146
 
147
+ 通过 EC Web 完成首次初始化:
148
+ ec init --web 启动初始化所需服务并输出 EC Web 入口地址
149
+ 默认 ec init 行为保持不变
150
+
146
151
  云部署非交互式初始化(结构化 JSON 输出):
147
152
  ec init --non-interactive --owner <aid> [--format json] [选项]
148
153
  --owner <aid> 必填。控制 AID 创建后的 Owner 邀约目标,不等待审批
@@ -195,6 +200,19 @@ export async function main(args) {
195
200
  process.exit(1);
196
201
  }
197
202
  else {
203
+ if (strippedArgs.includes("--web")) {
204
+ if (strippedArgs.length !== 2) {
205
+ console.error("❌ ec init --web 不能与其他初始化参数组合使用");
206
+ process.exitCode = 1;
207
+ break;
208
+ }
209
+ const { suppressSdkLogs } = await import("../aun/aid/index.js");
210
+ suppressSdkLogs();
211
+ const initialized = await cmdInit({ web: true });
212
+ if (!initialized && process.exitCode == null)
213
+ process.exitCode = 1;
214
+ break;
215
+ }
198
216
  const { suppressSdkLogs } = await import('../aun/aid/index.js');
199
217
  suppressSdkLogs();
200
218
  const nonInteractive = strippedArgs.includes('--non-interactive');
@@ -521,6 +539,11 @@ export async function main(args) {
521
539
  await cmdResponse(strippedArgs.slice(1));
522
540
  break;
523
541
  }
542
+ case 'provider': {
543
+ const { cmdProvider } = await import('./provider-command.js');
544
+ await cmdProvider(strippedArgs.slice(1));
545
+ break;
546
+ }
524
547
  case 'config': {
525
548
  const { cmdConfig } = await import('./config.js');
526
549
  await cmdConfig(strippedArgs.slice(1));
@@ -696,7 +696,7 @@ export async function cmdInitWechat() {
696
696
  // ==================== AUN ====================
697
697
  export async function cmdInitAun() {
698
698
  console.log('AUN 协议 Owner 统一使用 ec aid bind <ownerAid> [--subject <subjectAid>]');
699
- console.log(`状态查询: ${MAIN_CLI_BIN} aid bind status [--subject <subjectAid>];邀约审批: ${MAIN_CLI_BIN} aid bind accept|reject <operationId>。`);
699
+ console.log(`状态查询: ${MAIN_CLI_BIN} aid bind status [--refresh] [--subject <subjectAid>];转让: ${MAIN_CLI_BIN} aid transfer <subAid> <newOwnerAid> --subject <currentOwnerAid>;邀约审批: ${MAIN_CLI_BIN} aid bind accept|reject <operationId>。`);
700
700
  }
701
701
  async function pickAunOwnerBindTarget(rl, daemonAid) {
702
702
  const { agents } = loadAllAgents();
package/dist/cli/init.js CHANGED
@@ -6,7 +6,7 @@ import { resolvePaths, ensureDataDirs } from '../paths.js';
6
6
  import { commandExists } from '../utils/cross-platform.js';
7
7
  import { scanInstances } from '../utils/instance-registry.js';
8
8
  import { saveDefaultsSafe, loadAllAgents, loadDaemonConfig, saveDaemonConfig } from '../config-store.js';
9
- import { ecwebService, setEcwebEnabled } from '../config/daemon-services.js';
9
+ import { DEFAULT_ECWEB_PORT, ecwebService, setEcwebEnabled } from '../config/daemon-services.js';
10
10
  import { ensureControlAgentMd, generateControlAid, resolveControlAidDomain, submitControlAidRegistration, } from '../aun/aid/control-aid.js';
11
11
  import { isValidAid } from '../aun/aid/validation.js';
12
12
  import { getCodexAppServerAvailability } from '../agents/codex-runner.js';
@@ -161,8 +161,82 @@ export async function ensureEcwebInstalledForInit(options = {}) {
161
161
  return { ok: false, error };
162
162
  }
163
163
  }
164
+ export async function cmdInitWeb(dependencies = {}) {
165
+ const p = resolvePaths();
166
+ ensureDataDirs();
167
+ const daemonRunning = dependencies.isDaemonRunning?.()
168
+ ?? scanInstances().mains.some(instance => instance.alive);
169
+ if (daemonRunning && !(dependencies.loadConfig ?? loadDaemonConfig)().aid) {
170
+ console.error("❌ EvolCore 正在运行但未配置控制 AID;请先停止服务后重试。");
171
+ return false;
172
+ }
173
+ const install = await (dependencies.ensureEcwebInstalled ?? ensureEcwebInstalledForInit)();
174
+ if (!install.ok)
175
+ return false;
176
+ let config = (dependencies.loadConfig ?? loadDaemonConfig)();
177
+ if (!config.aid) {
178
+ try {
179
+ const aidDomain = resolveControlAidDomain(config.aun?.defaultAidDomain);
180
+ const { aid } = await (dependencies.generateAid ?? generateControlAid)(aidDomain);
181
+ config = { ...config, $schema_version: config.$schema_version ?? 1, aid };
182
+ (dependencies.saveConfig ?? saveDaemonConfig)(config);
183
+ console.log(`✓ 已生成主机控制 AID: ${aid}`);
184
+ }
185
+ catch (error) {
186
+ console.error(`❌ 主机控制 AID 准备失败: ${installErrorMessage(error)}`);
187
+ return false;
188
+ }
189
+ }
190
+ const controlAid = config.aid;
191
+ if (!controlAid) {
192
+ console.error("❌ 主机控制 AID 未配置。");
193
+ return false;
194
+ }
195
+ try {
196
+ await (dependencies.ensureAgentMd ?? ensureControlAgentMd)(controlAid);
197
+ }
198
+ catch (error) {
199
+ console.warn(`⚠️ 主机控制 AID 名片暂未发布,将由 daemon 后续重试: ${installErrorMessage(error)}`);
200
+ }
201
+ if (ecwebService(config.services)?.enabled !== true) {
202
+ config = { ...config, services: setEcwebEnabled(config.services, true) };
203
+ try {
204
+ (dependencies.saveConfig ?? saveDaemonConfig)(config);
205
+ }
206
+ catch (error) {
207
+ console.error(`❌ 启用 ECWeb 失败: ${installErrorMessage(error)}`);
208
+ return false;
209
+ }
210
+ }
211
+ try {
212
+ if (!daemonRunning && dependencies.startDaemon) {
213
+ await dependencies.startDaemon();
214
+ }
215
+ else if (!daemonRunning) {
216
+ const { cmdStart } = await import("./daemon-commands.js");
217
+ await cmdStart({ bindBootstrap: true, webInit: true });
218
+ }
219
+ const started = dependencies.startEcweb
220
+ ? await dependencies.startEcweb()
221
+ : await (await import("./daemon-commands.js")).startEcwebIfEnabled(p);
222
+ if (!started) {
223
+ console.error("❌ ECWeb 未能启动;可稍后运行 ec watch web 重试。");
224
+ return false;
225
+ }
226
+ }
227
+ catch (error) {
228
+ console.error(`❌ 启动 ECweb 初始化环境失败: ${installErrorMessage(error)}`);
229
+ return false;
230
+ }
231
+ const currentConfig = (dependencies.loadConfig ?? loadDaemonConfig)();
232
+ const port = ecwebService(currentConfig.services)?.port ?? DEFAULT_ECWEB_PORT;
233
+ console.log(`\nECweb 初始化: http://localhost:${port}/init`);
234
+ return true;
235
+ }
164
236
  // ==================== Main ====================
165
237
  export async function cmdInit(options) {
238
+ if (options?.web)
239
+ return cmdInitWeb();
166
240
  // 云部署非交互式路径:当带 --owner 或 --format json 时走结构化分支,与交互式 tail 完全隔离。
167
241
  // 预留方案 B:当 daemon 支持 Control Plane 无 agent 启动时,可在此分支跳过 agent new 预创建。
168
242
  if (options?.nonInteractive && (options.owner || options.format === 'json' || options.projectpath || options.ecweb)) {
@@ -1,4 +1,5 @@
1
1
  import { isHelpFlag, wantsHelp } from './help.js';
2
+ import { isTrustedFullAccessRuntimeContext, readVerifiedTaskRuntimeContext } from './task-context.js';
2
3
  const MANAGED_TASK_COMMANDS = new Set([
3
4
  'aid',
4
5
  'agent',
@@ -17,6 +18,7 @@ const MANAGED_TASK_COMMANDS = new Set([
17
18
  'model',
18
19
  'msg',
19
20
  'proxy',
21
+ 'provider',
20
22
  'queue',
21
23
  'response',
22
24
  // `role` 提交/审批关系角色提升申请,通过 role.op IPC 鉴权;
@@ -49,6 +51,7 @@ const MANAGED_TASK_COMMANDS = new Set([
49
51
  '-V',
50
52
  '--version',
51
53
  ]);
54
+ const SELF_PROTECTED_LIFECYCLE_COMMANDS = new Set(['start', 'stop', 'restart', 'restart-monitor']);
52
55
  export class ManagedCommandNotAllowedError extends Error {
53
56
  command;
54
57
  code = 'NOT_ALLOWED';
@@ -62,9 +65,18 @@ export class ManagedCommandNotAllowedError extends Error {
62
65
  * Local maintenance commands do not have daemon authorization entrypoints.
63
66
  * Keep them outside managed tasks so they cannot read or mutate host state.
64
67
  */
65
- export function assertManagedTopLevelCommandAllowed(command, args, env = process.env) {
68
+ export async function assertManagedTopLevelCommandAllowed(command, args, env = process.env) {
66
69
  if (!env.EVOLCORE_SESSION_ID || isHelpFlag(command) || wantsHelp(args.slice(1)))
67
70
  return;
71
+ // A trusted fullaccess task may enter any implemented CLI command. The
72
+ // command's own daemon/operation handler still performs its normal checks.
73
+ const verified = await readVerifiedTaskRuntimeContext(env);
74
+ if (isTrustedFullAccessRuntimeContext(verified)) {
75
+ if (SELF_PROTECTED_LIFECYCLE_COMMANDS.has(command)) {
76
+ throw new ManagedCommandNotAllowedError(command);
77
+ }
78
+ return;
79
+ }
68
80
  if (!MANAGED_TASK_COMMANDS.has(command))
69
81
  throw new ManagedCommandNotAllowedError(command);
70
82
  }
@@ -0,0 +1,57 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { resolvePaths } from '../paths.js';
4
+ import { readDelegationCredential, hashCurrentDelegatedCommand } from '../core/auth/agent-delegation.js';
5
+ import { parseProviderCommand } from '../config/provider-ipc-service.js';
6
+ import { queryDaemon, daemonUnavailableMessage, wantsHelp } from './help.js';
7
+ export async function cmdProvider(args) {
8
+ if (!args.length || wantsHelp(args)) {
9
+ console.log('用法: ec provider <命令> [--format json]\n\n'
10
+ + ' list\n show <provider-id>\n create --file <path>\n import --file <path>\n'
11
+ + ' update <provider-id> --file <path>\n delete <provider-id>\n\n'
12
+ + '只允许宿主控制终端管理 process 级 Provider。文件必须为 UTF-8,最大 1 MiB。\n'
13
+ + 'import 接受单 Provider 对象、单项映射或 providers 包装,始终创建新 ID。\n'
14
+ + 'update 替换完整对象;<redacted> 保留原密钥。输出始终脱敏。');
15
+ return;
16
+ }
17
+ const json = args.some((value, index) => value === '--format=json' || (value === '--format' && args[index + 1] === 'json'));
18
+ try {
19
+ const parsed = parseProviderCommand(['provider', ...args]);
20
+ const argv = ['provider', parsed.operation,
21
+ ...(parsed.providerId ? [parsed.providerId] : []),
22
+ ...(parsed.file ? ['--file', path.resolve(parsed.file)] : []),
23
+ ...(parsed.json ? ['--format', 'json'] : [])];
24
+ const sessionId = process.env.EVOLCORE_SESSION_ID;
25
+ const delegationToken = readDelegationCredential();
26
+ let controlToken;
27
+ if (!sessionId && !delegationToken) {
28
+ try {
29
+ controlToken = fs.readFileSync(resolvePaths().controlToken, 'utf8').trim();
30
+ }
31
+ catch { }
32
+ }
33
+ const { response, transportError } = await queryDaemon(resolvePaths().socket, {
34
+ type: 'provider.op', argv,
35
+ ...(sessionId || delegationToken ? { sessionId, delegationToken, delegationCommandHash: hashCurrentDelegatedCommand() } : { controlToken }),
36
+ }, 30_000);
37
+ if (!response)
38
+ throw Object.assign(new Error(daemonUnavailableMessage(transportError, '无法连接 EvolCore daemon')), { code: 'DAEMON_UNAVAILABLE' });
39
+ if (json)
40
+ console.log(JSON.stringify(response, null, 2));
41
+ else if (response.ok === false)
42
+ console.error(response.error + ' (' + response.code + ')');
43
+ else
44
+ console.log(JSON.stringify(response.data, null, 2));
45
+ if (response.ok === false)
46
+ process.exitCode = 1;
47
+ }
48
+ catch (error) {
49
+ const failure = error;
50
+ const result = { ok: false, code: failure.code ?? 'INVALID_ARGUMENT', error: failure.message ?? 'Provider command failed' };
51
+ if (json)
52
+ console.log(JSON.stringify(result, null, 2));
53
+ else
54
+ console.error(result.error);
55
+ process.exitCode = 1;
56
+ }
57
+ }
@@ -1,5 +1,5 @@
1
1
  import fs from 'fs';
2
- import { ipcQuery } from '../ipc.js';
2
+ import { ipcHostQuery } from '../ipc.js';
3
3
  import path from 'path';
4
4
  import { spawn, execFile } from 'child_process';
5
5
  import { promisify } from 'util';
@@ -1234,7 +1234,9 @@ async function notifyDaemonOwners(p, message, log) {
1234
1234
  log(`Daemon owner notification skipped: invalid daemon.json.aid ${daemonAid}`);
1235
1235
  return;
1236
1236
  }
1237
- const response = await ipcQuery(p.socket, { type: 'aid.ownership', argv: ['aid', 'bind', 'status'] }, OWNER_NOTIFICATION_TIMEOUT_MS).catch(() => null);
1237
+ const response = await ipcHostQuery(p.socket, {
1238
+ type: 'aid.ownership', authMode: 'local-control', argv: ['aid', 'bind', 'status'],
1239
+ }, OWNER_NOTIFICATION_TIMEOUT_MS).catch(() => null);
1238
1240
  const state = response?.ok ? response.state : undefined;
1239
1241
  const owners = state?.subjectAid === daemonAid && state?.consensusStatus === 'consensus'
1240
1242
  && typeof state.ownerAid === 'string' && isValidAid(state.ownerAid) ? [state.ownerAid] : [];