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
@@ -22,6 +22,7 @@ import { uploadAvatarFile, uploadAvatarUrl } from '../utils/avatar-upload.js';
22
22
  import { readTaskRuntimeContextFromEnv } from './task-context.js';
23
23
  import { logger } from '../utils/logger.js';
24
24
  import { creationOwnershipBinding } from '../core/ownership/owner-resolver.js';
25
+ import { getCatalog, resolveCatalogModel, catalogEfforts, assertCatalogSelectable } from '../core/model/model-catalog.js';
25
26
  /** Select the creation lifecycle independently of --non-interactive. */
26
27
  export function resolveAgentCreateMode(args) {
27
28
  if (args.includes('--initialize') && args.includes('--bootstrap')) {
@@ -697,23 +698,32 @@ export function initializationPath(aid) {
697
698
  return path.join(agentDataDir(aid), 'initialization.json');
698
699
  }
699
700
  export function initializationFingerprint(plan) {
700
- return createHash('sha256').update(JSON.stringify([
701
+ const values = [
701
702
  plan.aid, plan.project, plan.baseagent, plan.ownerAid, plan.name,
702
703
  plan.description, plan.type, plan.tags, plan.persona ?? null,
703
704
  plan.avatarFile ?? null, plan.avatarUrl ?? null,
704
- ])).digest('hex');
705
+ ...(plan.model !== undefined || plan.effort !== undefined
706
+ ? [{ model: plan.model ?? null, effort: plan.effort ?? null }]
707
+ : []),
708
+ ];
709
+ return createHash('sha256').update(JSON.stringify(values)).digest('hex');
705
710
  }
706
711
  export function readInitialization(aid) {
707
712
  const file = initializationPath(aid);
708
713
  if (!fs.existsSync(file))
709
714
  return null;
710
- const record = JSON.parse(fs.readFileSync(file, 'utf8'));
711
- if (record.version !== 1 || record.plan?.aid !== aid || !/^init-[a-f0-9]{24}$/.test(record.operationId)
712
- || !['in_progress', 'failed', 'complete', 'cancelled'].includes(record.status)
713
- || initializationFingerprint(record.plan) !== record.fingerprint) {
714
- throw new Error('INITIALIZE_STATE_INVALID');
715
+ try {
716
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'));
717
+ if (record.version !== 1 || record.plan?.aid !== aid || !/^init-[a-f0-9]{24}$/.test(record.operationId)
718
+ || !['in_progress', 'failed', 'complete', 'cancelled'].includes(record.status)
719
+ || initializationFingerprint(record.plan) !== record.fingerprint) {
720
+ failure('INITIALIZE_STATE_INVALID');
721
+ }
722
+ return record;
723
+ }
724
+ catch {
725
+ failure('INITIALIZE_STATE_INVALID');
715
726
  }
716
- return record;
717
727
  }
718
728
  export function saveInitialization(record) {
719
729
  const file = initializationPath(record.plan.aid);
@@ -734,8 +744,8 @@ export function initializationSummary(aid) {
734
744
  return {
735
745
  mode: 'supplied', operationId: r.operationId, fingerprint: r.fingerprint,
736
746
  status: r.status, phase: r.phase, complete: r.status === 'complete',
737
- code: r.code, error: r.error, retryable: r.status === 'failed',
738
- nextStep: r.status === 'failed' ? `ec agent initialize ${aid} --resume` : undefined,
747
+ code: r.code ?? null, error: r.error ?? null, retryable: r.status === 'failed',
748
+ nextStep: r.status === 'failed' ? `ec agent initialize ${aid} --resume` : null,
739
749
  agentmd: { published: r.published === true, verified: r.verified === true },
740
750
  persona: { provided: r.plan.persona !== undefined },
741
751
  avatar: { requested: r.plan.avatarFile !== undefined || r.plan.avatarUrl !== undefined, uploaded: r.avatarUploaded === true },
@@ -743,7 +753,10 @@ export function initializationSummary(aid) {
743
753
  };
744
754
  }
745
755
  catch {
746
- return { mode: 'supplied', status: 'failed', complete: false, code: 'INITIALIZE_STATE_INVALID' };
756
+ return {
757
+ mode: 'supplied', status: 'failed', phase: 'unknown', complete: false,
758
+ code: 'INITIALIZE_STATE_INVALID', error: 'Initialization state is invalid', retryable: false,
759
+ };
747
760
  }
748
761
  }
749
762
  /** Persistent guard also covers a removed/tampered config marker. */
@@ -767,13 +780,21 @@ function failure(code, error = code) {
767
780
  throw Object.assign(new Error(error), { code });
768
781
  }
769
782
  export function validateInitializationPlan(plan) {
770
- if (!plan.name?.trim() || !plan.description?.trim() || !Array.isArray(plan.tags) || !plan.ownerAid?.trim()) {
783
+ if (typeof plan.name !== 'string' || !plan.name.trim()
784
+ || typeof plan.description !== 'string' || !plan.description.trim()
785
+ || !Array.isArray(plan.tags) || typeof plan.ownerAid !== 'string' || !plan.ownerAid.trim()) {
771
786
  failure('INITIALIZE_FIELDS_REQUIRED', 'Explicit name, description, tags and one Owner AID are required');
772
787
  }
773
788
  if (!isValidAid(plan.ownerAid))
774
789
  failure('INVALID_ARGS', 'Owner must be a valid AID');
775
790
  if (plan.type !== 'agent')
776
791
  failure('INVALID_ARGS', 'Initialized targets must have type=agent');
792
+ if (plan.model !== undefined && (typeof plan.model !== 'string' || !plan.model.trim() || plan.model.length > 512)) {
793
+ failure('INVALID_ARGS', 'model must be a non-empty string of at most 512 characters');
794
+ }
795
+ if (plan.effort !== undefined && (typeof plan.effort !== 'string' || !plan.effort.trim() || plan.effort.length > 64)) {
796
+ failure('INVALID_ARGS', 'effort must be a non-empty string of at most 64 characters');
797
+ }
777
798
  if (plan.avatarFile !== undefined && plan.avatarUrl !== undefined)
778
799
  failure('INVALID_ARGS', 'avatar-file and avatar-url are mutually exclusive');
779
800
  const error = validateAgentCreatePlan({
@@ -782,8 +803,9 @@ export function validateInitializationPlan(plan) {
782
803
  });
783
804
  if (error)
784
805
  failure('INVALID_ARGS', error);
785
- if (!path.isAbsolute(plan.project))
806
+ if (typeof plan.project !== 'string' || !path.isAbsolute(plan.project)) {
786
807
  failure('INVALID_ARGS', 'project must be an absolute path');
808
+ }
787
809
  if (fs.existsSync(plan.project) && !fs.statSync(plan.project).isDirectory())
788
810
  failure('INVALID_ARGS', 'project is not a directory');
789
811
  const card = validateAgentMdFrontmatter(buildInitialAgentMd(plan), plan.aid);
@@ -797,6 +819,44 @@ export function validateInitializationPlan(plan) {
797
819
  failure('INVALID_ARGS', personaError);
798
820
  }
799
821
  }
822
+ export async function validateInitializationModelArgs(args) {
823
+ const plan = args.plan && typeof args.plan === 'object' && !Array.isArray(args.plan) ? args.plan : args;
824
+ const modelValue = plan.model ?? args.model;
825
+ const effortValue = plan.effort ?? args.effort;
826
+ if (modelValue !== undefined && typeof modelValue !== 'string') {
827
+ return { error: 'model 必须是字符串', code: 'INVALID_ARGS' };
828
+ }
829
+ if (effortValue !== undefined && typeof effortValue !== 'string') {
830
+ return { error: 'effort 必须是字符串', code: 'INVALID_ARGS' };
831
+ }
832
+ const model = typeof modelValue === 'string' ? modelValue.trim() : '';
833
+ const effort = typeof effortValue === 'string' ? effortValue.trim() : '';
834
+ if (!model && (!effort || effort === 'auto'))
835
+ return undefined;
836
+ if (!model && effort && effort !== 'auto') {
837
+ return { error: '设置 effort 时必须同时指定 model', code: 'INVALID_ARGS' };
838
+ }
839
+ const baseagentValue = plan.baseagent ?? args.baseagent;
840
+ const baseagent = typeof baseagentValue === 'string' ? baseagentValue.trim() : '';
841
+ if (!baseagent)
842
+ return { error: '指定 model/effort 时必须提供 baseagent', code: 'INVALID_ARGS' };
843
+ try {
844
+ const catalog = await getCatalog(undefined, baseagent);
845
+ assertCatalogSelectable(catalog);
846
+ const modelIds = catalog.models.map(entry => entry.id);
847
+ const resolvedModel = resolveCatalogModel(catalog, model);
848
+ if (!modelIds.includes(model) && !modelIds.includes(resolvedModel)) {
849
+ return { error: `模型不在当前主机 ${baseagent} 的可见目录中: ${model}`, code: 'INVALID_ARGS' };
850
+ }
851
+ if (effort && effort !== 'auto' && !catalogEfforts(catalog, resolvedModel, baseagent).includes(effort)) {
852
+ return { error: `模型 ${model} 不支持推理强度: ${effort}`, code: 'INVALID_ARGS' };
853
+ }
854
+ }
855
+ catch (error) {
856
+ return { error: error instanceof Error ? error.message : String(error), code: 'MODEL_UNAVAILABLE' };
857
+ }
858
+ return undefined;
859
+ }
800
860
  function cardHash(content) {
801
861
  return createHash('sha256').update(content).digest('hex');
802
862
  }
@@ -859,6 +919,8 @@ export class AgentInitializationService {
859
919
  resume(aid, actor) {
860
920
  if (this.deps.authorize && !this.deps.authorize(actor))
861
921
  failure('NOT_ALLOWED');
922
+ if (!isValidAid(aid))
923
+ failure('INVALID_ARGS', 'Invalid initialization AID');
862
924
  const r = readInitialization(aid);
863
925
  if (!r)
864
926
  failure('NOT_FOUND');
@@ -952,8 +1014,11 @@ export class AgentInitializationService {
952
1014
  const config = loadAgent(r.plan.aid);
953
1015
  if (r.configSaved && (!config || config.enabled === false))
954
1016
  failure('INITIALIZE_TARGET_CHANGED');
1017
+ const baseagentConfig = config?.baseagents?.[r.plan.baseagent];
955
1018
  if (config && (config.initialization?.operationId !== r.operationId
956
- || config.active_baseagent !== r.plan.baseagent || config.projects?.defaultPath !== r.plan.project)) {
1019
+ || config.active_baseagent !== r.plan.baseagent || config.projects?.defaultPath !== r.plan.project
1020
+ || baseagentConfig?.model !== r.plan.model
1021
+ || baseagentConfig?.effort !== r.plan.effort)) {
957
1022
  failure('INITIALIZE_TARGET_CHANGED');
958
1023
  }
959
1024
  }
@@ -973,7 +1038,12 @@ export class AgentInitializationService {
973
1038
  $schema_version: CONFIG_SCHEMA_VERSION, aid: p.aid, enabled: true, lifecycle: 'created',
974
1039
  initialization: { mode: 'supplied', operationId: r.operationId }, channels: [],
975
1040
  projects: { defaultPath: p.project }, active_baseagent: p.baseagent,
976
- baseagents: { [p.baseagent]: {} }, chatmode: { private: 'interactive', group: 'proactive', nothuman: 'proactive' },
1041
+ baseagents: {
1042
+ [p.baseagent]: {
1043
+ ...(p.model ? { model: p.model } : {}),
1044
+ ...(p.effort ? { effort: p.effort } : {}),
1045
+ },
1046
+ }, chatmode: { private: 'interactive', group: 'proactive', nothuman: 'proactive' },
977
1047
  });
978
1048
  }
979
1049
  r.configSaved = true;
@@ -1100,7 +1170,7 @@ export class AgentInitializationService {
1100
1170
  }
1101
1171
  }
1102
1172
  /** Called only after the IPC adapter has validated the local control token. */
1103
- export function executeLocalInitializationCommand(service, command) {
1173
+ export async function executeLocalInitializationCommand(service, command) {
1104
1174
  try {
1105
1175
  if (!Array.isArray(command.argv) || command.argv.some(value => typeof value !== 'string')) {
1106
1176
  return { ok: false, code: 'INVALID_ARGS', error: 'argv required' };
@@ -1115,7 +1185,11 @@ export function executeLocalInitializationCommand(service, command) {
1115
1185
  return { ok: false, code: 'NOT_FOUND', error: 'No initialization record' };
1116
1186
  return service.resume(parsed.aid, record.actor);
1117
1187
  }
1118
- return service.start(resolveInitializationPlan(argv), 'local-control', parsed.dryRun);
1188
+ const plan = resolveInitializationPlan(argv);
1189
+ const modelError = await validateInitializationModelArgs(plan);
1190
+ if (modelError)
1191
+ return { ok: false, ...modelError };
1192
+ return service.start(plan, 'local-control', parsed.dryRun);
1119
1193
  }
1120
1194
  catch (error) {
1121
1195
  return {
@@ -1134,7 +1208,7 @@ export function parseInitializationArgs(args) {
1134
1208
  throw new Error('--bootstrap cannot initialize an agent');
1135
1209
  const booleans = new Set(resume ? ['--resume'] : ['--initialize', '--non-interactive', '--dry-run']);
1136
1210
  const strings = new Set(resume ? ['--wait', '--format'] : [
1137
- '--project', '--baseagent', '--owner', '--name', '--description', '--tags', '--type', '--avatar-file', '--avatar-url',
1211
+ '--project', '--baseagent', '--model', '--effort', '--owner', '--name', '--description', '--tags', '--type', '--avatar-file', '--avatar-url',
1138
1212
  '--persona-file', '--persona-text', '--wait', '--format',
1139
1213
  ]);
1140
1214
  const seen = new Set();
@@ -1187,8 +1261,13 @@ export function resolveInitializationPlan(args, context) {
1187
1261
  avatarFile: v['--avatar-file'], avatarUrl: v['--avatar-url'],
1188
1262
  name: v['--name'], description: v['--description'], tags: parseAgentTags(v['--tags']), type: v['--type'],
1189
1263
  }, context?.projectCwd);
1264
+ const model = v['--model']?.trim();
1265
+ const effort = v['--effort']?.trim();
1190
1266
  return {
1191
- aid: p.aid, project: p.project, baseagent: p.baseagent ?? '', ownerAid: p.owner ?? '',
1267
+ aid: p.aid, project: p.project, baseagent: p.baseagent ?? '',
1268
+ ...(model ? { model } : {}),
1269
+ ...(effort && effort !== 'auto' ? { effort } : {}),
1270
+ ownerAid: p.owner ?? '',
1192
1271
  name: p.name, description: p.description, tags: p.tags, type: p.type,
1193
1272
  ...(persona !== undefined ? { persona } : {}),
1194
1273
  ...(v['--avatar-file'] !== undefined ? { avatarFile: v['--avatar-file'] } : {}),
package/dist/cli/agent.js CHANGED
@@ -167,14 +167,16 @@ export async function agentShow(aid) {
167
167
  if (!agent) {
168
168
  const init = initializationSummary(aid);
169
169
  if (init) {
170
+ const lifecycle = loadAgent(aid)?.lifecycle ?? null;
170
171
  return {
171
172
  ok: true,
172
173
  aid,
173
174
  status: 'initializing',
174
- lifecycle: loadAgent(aid)?.lifecycle ?? null,
175
+ lifecycle,
175
176
  identity: { name: null, description: null },
176
177
  config: { baseagent: null, model: null, effort: null, chatmode: null, channels: [] },
177
178
  connection: null,
179
+ usable: false,
178
180
  sessions: { active: 0, last_activity: null },
179
181
  paths: {
180
182
  config: toPosix(path.join(p.agentsDir, aid, 'config.json')),
@@ -207,11 +209,13 @@ export async function agentShow(aid) {
207
209
  }
208
210
  const identity = readAgentMdIdentity(aid);
209
211
  const agentMdPath = getAgentMdPath(aid);
212
+ const lifecycle = loadAgent(aid)?.lifecycle ?? null;
213
+ const initializationState = initializationSummary(aid);
210
214
  return {
211
215
  ok: true,
212
216
  aid,
213
217
  status: agentInfo.status || 'unknown',
214
- lifecycle: loadAgent(aid)?.lifecycle ?? null,
218
+ lifecycle,
215
219
  identity,
216
220
  config: {
217
221
  baseagent: agentInfo.baseagent || null,
@@ -221,6 +225,10 @@ export async function agentShow(aid) {
221
225
  channels: agentInfo.channels || [],
222
226
  },
223
227
  connection: connectionInfo,
228
+ ...(initializationState ? {
229
+ initialization: initializationState,
230
+ usable: initializationState.complete === true && lifecycle === 'active' && connectionInfo?.status === 'connected',
231
+ } : {}),
224
232
  sessions: {
225
233
  active: agentInfo.activeSessions || 0,
226
234
  last_activity: agentInfo.lastActivity ? new Date(agentInfo.lastActivity).toISOString() : null,
@@ -231,7 +239,6 @@ export async function agentShow(aid) {
231
239
  project: toPosix(agentInfo.projectPath || null),
232
240
  data: toPosix(path.join(p.agentsDir, aid, 'data')),
233
241
  },
234
- ...(initializationSummary(aid) ? { initialization: initializationSummary(aid) } : {}),
235
242
  ...(stale ? { stale: true } : {}),
236
243
  };
237
244
  }
@@ -15,6 +15,7 @@ import { ManagedGroupOperationError } from '../aun/msg/managed-operation.js';
15
15
  import { parseDuration } from '../trigger/parser.js';
16
16
  import { isTopicThreadId, safeFormatMainTopicId } from '../core/thread/topic-id.js';
17
17
  import { parseJsonObjectArgument } from '../core/permission/ec-command-parser.js';
18
+ import { resolveAunSendDevice } from '../aun/ability-device-routing.js';
18
19
  // ==================== AID ====================
19
20
  function resolveAunPath(args) {
20
21
  const idx = args.indexOf('--aun-path');
@@ -1119,6 +1120,7 @@ export async function cmdStorage(args) {
1119
1120
  Commands:
1120
1121
  upload <aid> <local-file> <remote-path> [--public] 上传文件(默认私有)
1121
1122
  download <aid> <url> [local-path] 下载文件
1123
+ get-by-share <aid> <share-id> [local-path] 通过分享短码下载文件
1122
1124
  ls <aid> [prefix] 列文件
1123
1125
  rm <aid> <remote-path> 删文件
1124
1126
  quota <aid> 查配额
@@ -1135,6 +1137,7 @@ Options:
1135
1137
  ec storage upload myaid.agentid.pub ./pic.png images/pic.png --public
1136
1138
  ec storage download myaid.agentid.pub myaid.agentid.pub/notes/doc.txt ./doc.txt
1137
1139
  ec storage download myaid.agentid.pub bob.agentid.pub/public/file.pdf ./file.pdf
1140
+ ec storage get-by-share myaid.agentid.pub <share-id> ./output.json
1138
1141
  ec storage ls myaid.agentid.pub notes/
1139
1142
  ec storage rm myaid.agentid.pub notes/doc.txt
1140
1143
  ec storage quota myaid.agentid.pub`);
@@ -1151,7 +1154,7 @@ Options:
1151
1154
  process.exit(1);
1152
1155
  }
1153
1156
  if (process.env.EVOLCORE_SESSION_ID) {
1154
- const operation = { ls: 'storage.list', quota: 'storage.quota', upload: 'storage.upload', download: 'storage.download', rm: 'storage.delete' }[sub];
1157
+ const operation = { ls: 'storage.list', quota: 'storage.quota', upload: 'storage.upload', download: 'storage.download', rm: 'storage.delete', 'get-by-share': 'storage.get_by_share' }[sub];
1155
1158
  if (!operation)
1156
1159
  failManagedGroup(formatJson, 'NOT_ALLOWED', `unsupported managed storage command: ${sub}`);
1157
1160
  const delegationToken = readDelegationCredential();
@@ -1209,11 +1212,13 @@ Options:
1209
1212
  console.log(JSON.stringify(authorization));
1210
1213
  else if (sub === 'download')
1211
1214
  console.log(`✓ 已下载: ${authorization.localPath} (${authorization.size} bytes)`);
1215
+ else if (sub === 'get-by-share')
1216
+ console.log(`✓ 已下载: ${authorization.localPath} (${authorization.size} bytes)`);
1212
1217
  else
1213
1218
  console.log(`✓ 已删除: ${authorization.objectKey}`);
1214
1219
  return;
1215
1220
  }
1216
- const { storageUpload, storageDownload, storageLs, storageRm, storageQuota } = await import('../aun/storage/index.js');
1221
+ const { storageUpload, storageDownload, storageGetByShare, storageLs, storageRm, storageQuota } = await import('../aun/storage/index.js');
1217
1222
  if (sub === 'upload') {
1218
1223
  const localFile = args[2];
1219
1224
  const remotePath = args[3];
@@ -1251,6 +1256,31 @@ Options:
1251
1256
  }
1252
1257
  return;
1253
1258
  }
1259
+ if (sub === 'get-by-share') {
1260
+ const shareId = args[2];
1261
+ const localPath = args[3];
1262
+ if (!shareId) {
1263
+ console.error('用法: ec storage get-by-share <aid> <share-id> [local-path]');
1264
+ process.exit(1);
1265
+ }
1266
+ const result = await storageGetByShare(aid, shareId, localPath, { aunPath });
1267
+ if (!result.ok) {
1268
+ if (formatJson) {
1269
+ console.log(JSON.stringify({ ok: false, error: result.error }));
1270
+ }
1271
+ else {
1272
+ console.error(`❌ 下载失败: ${result.error}`);
1273
+ }
1274
+ process.exit(1);
1275
+ }
1276
+ if (formatJson) {
1277
+ console.log(JSON.stringify({ ok: true, localPath: result.localPath, size: result.size, objectKey: result.objectKey ?? null, sha256: result.sha256 ?? null }));
1278
+ }
1279
+ else {
1280
+ console.log(`✓ 已下载: ${result.localPath} (${result.size} bytes)`);
1281
+ }
1282
+ return;
1283
+ }
1254
1284
  if (sub === 'download') {
1255
1285
  const url = args[2];
1256
1286
  const localPath = args[3];
@@ -1382,7 +1412,7 @@ export function buildThreadCheckTrigger(input) {
1382
1412
  chatType: input.feedbackChatType ?? 'private',
1383
1413
  },
1384
1414
  },
1385
- reliability: { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 0, backoffMs: 30_000 } },
1415
+ reliability: { concurrency: 'forbid', missedPolicy: 'run_once', retry: { maxAttempts: 1, backoffMs: 30_000 } },
1386
1416
  };
1387
1417
  }
1388
1418
  /**
@@ -1589,6 +1619,7 @@ Commands:
1589
1619
  send <from> <to> --file <path> [--as <type>] 发送文件(image|video|voice|file)
1590
1620
  send <from> <to> --link <url> [--title T] 发送链接卡片
1591
1621
  send <from> <to> --payload <json> 发送自定义 payload
1622
+ send <from> <to> --payload-file <path> 从 UTF-8 文件读取自定义 payload
1592
1623
  request get <self-aid> <request-id> 查询已登记请求状态
1593
1624
  pull <from> [--after-seq N] [--limit N] --app <name> 拉取收件箱(必须使用独立 slot)
1594
1625
  ack <from> <seq> [--app <name>] 确认已读
@@ -1607,7 +1638,9 @@ Options:
1607
1638
  --aun-path <path> 指定 AUN keystore 根
1608
1639
  --format json 输出 JSON 格式
1609
1640
  --payload '<json>' 发送任意 JSON payload,不添加聊天字段
1641
+ --payload-file <path> 从 UTF-8 文件读取 JSON payload(与 --payload 互斥)
1610
1642
  --return none|required 是否等待关联响应(required 建立请求记录)
1643
+ --device-id <id> 定向到能力目录中的一台设备(device/status 查询不指定;其他业务能力必填,不写入 payload)
1611
1644
  --timeout <duration> required 的等待期限和 AUN volatile TTL,如 30s、60s、2m(默认 60s,最大 3600s)
1612
1645
  --encrypt 强制端到端加密(未指定时使用 daemon 默认值)
1613
1646
  --no-encrypt 强制明文发送(优先于 --encrypt)
@@ -1711,8 +1744,16 @@ Options:
1711
1744
  console.log(JSON.stringify(result));
1712
1745
  else if (!result.ok)
1713
1746
  console.error(`request query failed: ${result.error}`);
1714
- else
1715
- console.log(`request_id=${requestId} state=${result.request?.state ?? 'unknown'} message_id=${result.request?.outboundMessageId ?? '-'}`);
1747
+ else {
1748
+ const request = result.request ?? {};
1749
+ const ignored = request.lastIgnoredResponse;
1750
+ const reason = (request.state !== 'completed' && request.state !== 'failed' ? ignored?.reason : undefined)
1751
+ ?? (request.state === 'pending' && request.ackMessageId ? 'provider_ack_without_final_result' : undefined)
1752
+ ?? (request.state === 'pending' ? 'no_final_response_before_deadline' : undefined);
1753
+ console.log(`request_id=${requestId} state=${request.state ?? 'unknown'} message_id=${request.outboundMessageId ?? '-'}`
1754
+ + ` target_device_id=${request.targetDeviceId ?? '-'} response_device_id=${request.responseDeviceId ?? '-'}`
1755
+ + ` ack=${request.ackMessageId ? 'received' : 'none'}${reason ? ` reason=${reason}` : ''}`);
1756
+ }
1716
1757
  if (!result.ok)
1717
1758
  process.exit(1);
1718
1759
  return;
@@ -1985,11 +2026,12 @@ Options:
1985
2026
  const textFromFileVal = getArgValue(args, '--text-from-file');
1986
2027
  const linkVal = getArgValue(args, '--link');
1987
2028
  const payloadVal = getArgValue(args, '--payload');
2029
+ const payloadFileVal = getArgValue(args, '--payload-file');
1988
2030
  let body;
1989
2031
  // 检查互斥参数
1990
- const exclusiveModes = [fileVal, textFromFileVal, linkVal, payloadVal].filter(Boolean);
2032
+ const exclusiveModes = [fileVal, textFromFileVal, linkVal, payloadVal, payloadFileVal].filter(Boolean);
1991
2033
  if (exclusiveModes.length > 1) {
1992
- console.error('❌ --file, --text-from-file, --link, --payload 互斥,只能指定一个');
2034
+ console.error('❌ --file, --text-from-file, --link, --payload, --payload-file 互斥,只能指定一个');
1993
2035
  process.exit(1);
1994
2036
  }
1995
2037
  if (fileVal) {
@@ -2042,10 +2084,21 @@ Options:
2042
2084
  }
2043
2085
  body = { mode: 'payload', payload: parsed };
2044
2086
  }
2087
+ else if (payloadFileVal) {
2088
+ let parsed;
2089
+ try {
2090
+ parsed = parseJsonObjectArgument(fs.readFileSync(payloadFileVal, 'utf-8'), '--payload-file');
2091
+ }
2092
+ catch (e) {
2093
+ console.error(`--payload-file parse failed: ${e.message}`);
2094
+ process.exit(1);
2095
+ }
2096
+ body = { mode: 'payload', payload: parsed };
2097
+ }
2045
2098
  else {
2046
2099
  const text = collectPositional(args, 3).join(' ');
2047
2100
  if (!text) {
2048
- console.error('❌ 缺少消息内容(文本或 --file/--text-from-file/--link/--payload)');
2101
+ console.error('❌ 缺少消息内容(文本或 --file/--text-from-file/--link/--payload/--payload-file)');
2049
2102
  process.exit(1);
2050
2103
  }
2051
2104
  body = { mode: 'text', text };
@@ -2137,7 +2190,7 @@ Options:
2137
2190
  };
2138
2191
  // `--thread` 的原文只用于解析;发出的必须是规范 id(历史写法 `<peer>/<id>`
2139
2192
  // 若原样上线,对端会把它当成一个不存在的话题 id)。
2140
- const result = await msgSend({ from, to, body, encrypt, thread: thread ? threadTopicId : undefined, returnPolicy: returnPolicyRaw, timeoutMs, handoffContext: getArgValue(args, '--handoff-context'), onUploadProgress, ...commonOpts });
2193
+ const result = await msgSend({ from, to, body, encrypt, deviceId: getArgValue(args, '--device-id'), thread: thread ? threadTopicId : undefined, returnPolicy: returnPolicyRaw, timeoutMs, handoffContext: getArgValue(args, '--handoff-context'), onUploadProgress, ...commonOpts });
2141
2194
  if (!result.ok) {
2142
2195
  if (formatJson) {
2143
2196
  console.log(JSON.stringify(result));
@@ -2726,8 +2779,9 @@ g- 是名称的一部分,会完整保留;默认命名格式为 g-10000 至 g
2726
2779
  const getSendArgValue = (flag) => getArgValue(optionArgs, flag);
2727
2780
  const fileVal = getSendArgValue('--file');
2728
2781
  const payloadVal = getSendArgValue('--payload');
2782
+ const payloadFileVal = getSendArgValue('--payload-file');
2729
2783
  const bodyPositionals = collectPositional(args, 3);
2730
- const bodyFlags = ['--file', '--payload', '--as', '--content-type', '--text', '--transcript', '--thread', '--check-every', '--trigger-prompt'];
2784
+ const bodyFlags = ['--file', '--payload', '--payload-file', '--as', '--content-type', '--text', '--transcript', '--thread', '--check-every', '--trigger-prompt'];
2731
2785
  for (let index = 3; index < args.length; index++) {
2732
2786
  const flag = args[index];
2733
2787
  if (flag === '--')
@@ -2742,11 +2796,14 @@ g- 是名称的一部分,会完整保留;默认命名格式为 g-10000 至 g
2742
2796
  if (optionArgs.includes('--encrypt') && optionArgs.includes('--no-encrypt')) {
2743
2797
  failManagedGroup(formatJson, 'INVALID_ARGUMENT', '--encrypt 与 --no-encrypt 不能同时使用');
2744
2798
  }
2745
- if (fileVal && payloadVal) {
2746
- failManagedGroup(formatJson, 'INVALID_ARGUMENT', '--file and --payload are mutually exclusive');
2799
+ if ([fileVal, payloadVal, payloadFileVal].filter(Boolean).length > 1) {
2800
+ failManagedGroup(formatJson, 'INVALID_ARGUMENT', '--file, --payload and --payload-file are mutually exclusive');
2801
+ }
2802
+ if (payloadFileVal) {
2803
+ failManagedGroup(formatJson, 'INVALID_ARGUMENT', '--payload-file is supported for private msg sends only');
2747
2804
  }
2748
- if ((fileVal || payloadVal) && bodyPositionals.length > 0) {
2749
- failManagedGroup(formatJson, 'INVALID_ARGUMENT', '文本正文不能与 --file 或 --payload 同时使用');
2805
+ if ((fileVal || payloadVal || payloadFileVal) && bodyPositionals.length > 0) {
2806
+ failManagedGroup(formatJson, 'INVALID_ARGUMENT', '文本正文不能与 --file、--payload 或 --payload-file 同时使用');
2750
2807
  }
2751
2808
  let body;
2752
2809
  if (fileVal) {
@@ -2789,7 +2846,7 @@ g- 是名称的一部分,会完整保留;默认命名格式为 g-10000 至 g
2789
2846
  }
2790
2847
  const text = collectPositional(args, 3).join(' ');
2791
2848
  if (!text) {
2792
- console.error('❌ 缺少消息内容(文本或 --file/--payload)');
2849
+ console.error('❌ 缺少消息内容(文本或 --file/--payload/--payload-file)');
2793
2850
  process.exit(1);
2794
2851
  }
2795
2852
  body = { mode: 'text', text };
@@ -3437,7 +3494,7 @@ export function resolveManagedSendArgv(argv) {
3437
3494
  const booleans = new Set();
3438
3495
  const text = [];
3439
3496
  const mentions = [];
3440
- const valueFlags = new Set(['--format', '--file', '--payload', '--text-from-file', '--link', '--title', '--description', '--as', '--content-type', '--text', '--transcript', '--thread', '--check-every', '--trigger-prompt', '--return', '--timeout', '--handoff-context', '--mention', '--self']);
3497
+ 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']);
3441
3498
  const booleanFlags = new Set(['--encrypt', '--no-encrypt', '--mention-all']);
3442
3499
  for (let index = 4; index < argv.length; index++) {
3443
3500
  const flag = argv[index];
@@ -3514,13 +3571,14 @@ export function resolveManagedSendArgv(argv) {
3514
3571
  }
3515
3572
  if (scope === 'msg' && (mentions.length || booleans.has('--mention-all')))
3516
3573
  throw new Error('Mentions require a group send');
3517
- if (scope === 'group' && (values.has('--link') || values.has('--text-from-file')))
3574
+ if (scope === 'group' && (values.has('--link') || values.has('--text-from-file') || values.has('--payload-file')))
3518
3575
  throw new Error('Unsupported group send body');
3519
- const modes = ['--file', '--payload', '--text-from-file', '--link'].filter(flag => values.has(flag));
3576
+ const modes = ['--file', '--payload', '--payload-file', '--text-from-file', '--link'].filter(flag => values.has(flag));
3520
3577
  if (modes.length > 1 || (modes.length && text.length))
3521
3578
  throw new Error('Message body modes are mutually exclusive');
3522
3579
  let payload;
3523
3580
  let file;
3581
+ const payloadFile = values.get('--payload-file');
3524
3582
  if (values.has('--file')) {
3525
3583
  const as = values.get('--as');
3526
3584
  if (as && !['image', 'video', 'voice', 'file'].includes(as))
@@ -3537,7 +3595,7 @@ export function resolveManagedSendArgv(argv) {
3537
3595
  payload = { type: 'link', url: values.get('--link'), ...(values.get('--title') ? { title: values.get('--title') } : {}),
3538
3596
  ...(values.get('--description') ? { description: values.get('--description') } : {}) };
3539
3597
  }
3540
- else if (!values.has('--text-from-file')) {
3598
+ else if (!values.has('--text-from-file') && !payloadFile) {
3541
3599
  if (!text.join(' '))
3542
3600
  throw new Error('Message content is required');
3543
3601
  payload = { type: 'text', text: text.join(' ') };
@@ -3546,7 +3604,9 @@ export function resolveManagedSendArgv(argv) {
3546
3604
  throw new Error('Attachment options require --file');
3547
3605
  if (booleans.has('--mention-all'))
3548
3606
  mentions.push({ scope: 'all' });
3549
- return { aid, to, scope, payload, rawPayload: values.has('--payload'), file, textFile: values.get('--text-from-file'),
3607
+ const deviceId = resolveAunSendDevice(values.get('--device-id'), scope, payload);
3608
+ return { aid, to, scope, payload, rawPayload: values.has('--payload') || values.has('--payload-file'), file, textFile: values.get('--text-from-file'), payloadFile,
3609
+ deviceId,
3550
3610
  encrypt: booleans.has('--no-encrypt') ? false : booleans.has('--encrypt') ? true : undefined,
3551
3611
  thread, checkEvery, checkEveryMs: checkEveryMs ?? undefined, triggerPromptExtra, returnPolicy: returnPolicy, timeoutMs, handoffContext,
3552
3612
  mentions: mentions.length ? mentions : undefined };
@@ -3566,12 +3626,12 @@ export function resolveManagedSendArgv(argv) {
3566
3626
  */
3567
3627
  const VALUE_FLAGS = new Set([
3568
3628
  '--format', '--app', '--after-seq', '--limit', '--file', '--link',
3569
- '--payload', '--title', '--description', '--text', '--transcript',
3629
+ '--payload', '--payload-file', '--title', '--description', '--text', '--transcript',
3570
3630
  '--as', '--content-type', '--mention', '--visibility', '--join-mode',
3571
3631
  '--group-id', '--name', '--message', '--answer', '--page', '--size',
3572
3632
  '--member-type',
3573
3633
  '--aun-path', '--thread', '--handoff-context', '--self',
3574
- '--return', '--timeout',
3634
+ '--return', '--timeout', '--device-id',
3575
3635
  // 跨话题发送的复查参数:漏登记会让 collectPositional 把它们当正文(正文污染)
3576
3636
  '--check-every', '--trigger-prompt',
3577
3637
  ]);
@@ -1572,26 +1572,35 @@ export async function cmdStatus(options = {}) {
1572
1572
  // 实例副本在唯一的当前实例已存在时属于迁移来源,不应误报。
1573
1573
  let orphanCount = 0;
1574
1574
  try {
1575
- const { agents } = loadAllAgents();
1575
+ // When the daemon is reachable, use its loaded Agent view instead of
1576
+ // reopening protected defaults.json and daemon.json from the CLI.
1577
+ const [agentResponse, liveStatus] = await Promise.all([agentsPromise, statusPromise]);
1578
+ if (!agentResponse?.ok || !Array.isArray(agentResponse.agents))
1579
+ throw new Error('Agent list unavailable');
1576
1580
  const configChannelNames = new Set();
1577
1581
  const configuredByAgentType = new Map();
1578
- for (const cfg of agents) {
1582
+ for (const cfg of agentResponse.agents) {
1583
+ if (typeof cfg.aid !== 'string' || !cfg.aid)
1584
+ continue;
1579
1585
  // AUN 是从 agent 自身 AID 隐式派生的内建通道,不出现在 cfg.channels 里。
1580
1586
  // 不补这条,所有 aun#<aid>#main 会话都会被误判成 orphan。
1581
1587
  configChannelNames.add(`aun#${cfg.aid}#main`);
1582
- for (const inst of cfg.channels) {
1583
- // effective key: <type>#<selfAID>#<name>
1584
- const channelKey = `${inst.type}#${cfg.aid}#${inst.name}`;
1588
+ for (const channelKey of Array.isArray(cfg.channels) ? cfg.channels : []) {
1589
+ if (typeof channelKey !== 'string')
1590
+ continue;
1585
1591
  configChannelNames.add(channelKey);
1586
- const identity = `${inst.type}\0${cfg.aid}`;
1592
+ const [type, aid] = channelKey.split('#');
1593
+ if (!type || !aid)
1594
+ continue;
1595
+ const identity = `${type}\0${aid}`;
1587
1596
  configuredByAgentType.set(identity, [...(configuredByAgentType.get(identity) ?? []), channelKey]);
1588
1597
  }
1589
1598
  }
1590
1599
  // The daemon control identity owns AUN transcripts but deliberately
1591
1600
  // has no Agent config, so include it explicitly in route validity.
1592
- const daemonConfig = readJsonFile(p.daemonConfig);
1593
- if (daemonConfig?.aid)
1594
- configChannelNames.add(`aun#${daemonConfig.aid}#main`);
1601
+ const controlAid = liveStatus?.controlAid?.aid;
1602
+ if (typeof controlAid === 'string' && controlAid)
1603
+ configChannelNames.add(`aun#${controlAid}#main`);
1595
1604
  for (const chat of chatDirs) {
1596
1605
  const channelKey = chat.channelKey;
1597
1606
  if (!channelKey || configChannelNames.has(channelKey) || isNonAgentSessionChannel(channelKey))
@@ -1712,7 +1721,7 @@ export async function cmdStatus(options = {}) {
1712
1721
  console.log(` Build ID: runtime=unavailable (daemon 未提供 build identity) dist=${computeBuildId(path.join(getPackageRoot(), 'dist')) ?? '?'}`);
1713
1722
  console.log(' ⚠ 当前 daemon 未提供 build ID;请重启到包含 build identity 的版本后再判断源码行为。');
1714
1723
  }
1715
- if (!showLiveChannels(statusResponse)) {
1724
+ if (!statusResponse) {
1716
1725
  const config = readStatusDefaultsConfig(p.defaultsConfig);
1717
1726
  if (config) {
1718
1727
  console.log('🔌 Channels (live status unavailable; configuration is stale):');
package/dist/cli/index.js CHANGED
@@ -281,7 +281,7 @@ export async function main(args) {
281
281
  const sessionId = process.env.EVOLCORE_SESSION_ID;
282
282
  const delegationToken = readDelegationCredential();
283
283
  const result = await ipcQuery(resolvePaths().socket, {
284
- type: 'status.auth', sessionId, delegationToken,
284
+ type: 'status.auth', sessionId, delegationToken, argv: ['status', ...statusArgs],
285
285
  });
286
286
  if (!result?.ok) {
287
287
  console.error(`❌ ${result?.error || 'status is not allowed in this task'}`);
@@ -234,6 +234,23 @@ export async function cmdRestartMonitor() {
234
234
  process.exitCode = 2;
235
235
  return;
236
236
  }
237
+ if (upgradeJob?.distTag === 'stable') {
238
+ let enabled = false;
239
+ try {
240
+ enabled = loadDaemonConfig().upgrade?.autoOnStart !== false;
241
+ }
242
+ catch { }
243
+ if (!enabled) {
244
+ log('Automatic stable upgrade disabled before restart; leaving the daemon running');
245
+ updateUpgradeJob(upgradeJob.jobId, {
246
+ status: 'failed', success: false, released: true, code: 'AUTO_UPGRADE_DISABLED',
247
+ reason: 'Automatic stable upgrades disabled by autoOnStart',
248
+ }, '自动更新已关闭,未执行重启');
249
+ cleanupPendingFile(pendingFile, log, hasCorrelatedRequest ? requestId : undefined);
250
+ process.exitCode = 2;
251
+ return;
252
+ }
253
+ }
237
254
  if (hasCorrelatedRequest) {
238
255
  if (upgradeJob && (readUpgradeJob(upgradeJob.jobId)?.status !== 'running' || upgradeJob.deadline <= Date.now())) {
239
256
  cleanupPendingFile(pendingFile, log, requestId);