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
@@ -19,8 +19,8 @@ import { auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
19
19
  import { resolveEcagentConfig } from './baseagent.js';
20
20
  import { resolveProviderServiceForBaseagent } from '../config/providers.js';
21
21
  import { buildModelRequestHeaders } from './request-identity.js';
22
+ import { getGatewayPricing as getSharedGatewayPricing, resolveModelSpec } from '../stats/price-resolver.js';
22
23
  import { appendRequestPath } from './request-identity.js';
23
- import { resolveModelSpec } from '../stats/billing.js';
24
24
  import { getManagedTaskTempDir } from '../cli/task-context.js';
25
25
  import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext } from './runner-types.js';
26
26
  const PROVIDER_ID = 'evolcore-gateway';
@@ -795,6 +795,12 @@ export class EcagentRunner {
795
795
  setSendPrompt(fn) { this.sendPromptFn = fn; }
796
796
  setPermissionContext(sessionId, context) { this.permissionContexts.set(sessionId, context); }
797
797
  setCompactStartCallback(callback) { this.onCompactStart = callback; }
798
+ /** 返回当前网关 /v1/models 的价格缓存(1h TTL,stale-while-revalidate)。
799
+ * 缺失/过期时异步触发刷新,本轮先返回旧值或 undefined(回退本地价表)。 */
800
+ getGatewayPricing() {
801
+ const conn = this.currentProviderConfig();
802
+ return getSharedGatewayPricing(conn.baseUrl, conn.apiKey, conn.headers);
803
+ }
798
804
  currentProviderConfig(providerOverride) {
799
805
  const providerId = providerOverride ?? this.config.providerId;
800
806
  if (!providerId)
@@ -925,7 +931,13 @@ export class EcagentRunner {
925
931
  const connection = this.currentProviderConfig(request.modelOverride?.provider);
926
932
  await fs.promises.mkdir(request.projectPath, { recursive: true });
927
933
  const previousRuntime = this.runtimes.get(request.sessionId);
928
- const runtime = await this.getOrCreateRuntime(request.sessionId, request.projectPath, request.initialAgentSessionId, request.modelOverride);
934
+ const runtime = await this.getOrCreateRuntime(request.sessionId, request.projectPath, request.initialAgentSessionId, request.modelOverride, async (oldId) => {
935
+ if (!request.modelOverride?.capsule)
936
+ return;
937
+ const recovered = await request.modelOverride.capsule.recover(oldId, request.prompt, request.systemPromptAppend);
938
+ request.prompt = recovered.prompt;
939
+ request.systemPromptAppend = recovered.systemPrompt;
940
+ });
929
941
  if (lifecycle.cancelled)
930
942
  throw new Error('ecagent run interrupted');
931
943
  if (previousRuntime !== runtime) {
@@ -989,13 +1001,20 @@ export class EcagentRunner {
989
1001
  const decision = await this.authorizeTool(request.sessionId, request.projectPath, permissionMode, event.toolName, event.input, stats.numTurns + 1);
990
1002
  return lifecycle.cancelled || signal?.aborted ? { block: true, reason: '工具调用已取消' } : decision;
991
1003
  });
992
- const unsubscribe = harness.subscribe(event => this.mapHarnessEvent(queue, event, stats, model, effort));
1004
+ let inputAccepted = false;
1005
+ const unsubscribe = harness.subscribe(event => {
1006
+ // The harness persists a user message before publishing message_end.
1007
+ // Failures in createTurnState/before_agent_start must leave context pending.
1008
+ if (!inputAccepted && event.type === 'message_end' && event.message.role === 'user') {
1009
+ inputAccepted = true;
1010
+ if (request.modelOverride?.turn?.inputId) {
1011
+ queue.push({ type: 'input_accepted', inputId: request.modelOverride.turn.inputId });
1012
+ }
1013
+ }
1014
+ this.mapHarnessEvent(queue, event, stats, model, effort);
1015
+ });
993
1016
  queue.push({ type: 'state_changed', state: 'running' });
994
1017
  queue.push({ type: 'status', subtype: 'started', message: `ecagent is using ${modelId}` });
995
- // Ecagent 输入在 harness.prompt 调用时提交,在此前报告
996
- if (request.modelOverride?.turn?.inputId) {
997
- queue.push({ type: 'input_accepted', inputId: request.modelOverride.turn.inputId });
998
- }
999
1018
  const ecImages = request.images?.map(image => ({
1000
1019
  type: 'image', data: image.data, mimeType: image.mimeType || 'image/png',
1001
1020
  }));
@@ -1071,7 +1090,7 @@ export class EcagentRunner {
1071
1090
  queue.end();
1072
1091
  }
1073
1092
  }
1074
- async getOrCreateRuntime(sessionId, projectPath, requestedId, modelOverride) {
1093
+ async getOrCreateRuntime(sessionId, projectPath, requestedId, modelOverride, recover) {
1075
1094
  const current = this.runtimes.get(sessionId);
1076
1095
  const topicBinding = modelOverride?.backend?.kind === 'topic';
1077
1096
  const requestedTopicAgentSessionId = topicBinding
@@ -1086,6 +1105,7 @@ export class EcagentRunner {
1086
1105
  }
1087
1106
  if (current && !recoverySessionId
1088
1107
  && current.projectPath === projectPath
1108
+ && !!this.resolveSessionFile(current.agentSessionId, projectPath)
1089
1109
  && (!targetId || current.agentSessionId === targetId)
1090
1110
  && (!topicBinding || (!!targetId && current.agentSessionId === targetId)))
1091
1111
  return current;
@@ -1104,6 +1124,7 @@ export class EcagentRunner {
1104
1124
  throw error;
1105
1125
  }
1106
1126
  logger.warn(`[EcagentRunner] backing session ${targetId} was not found; creating a new session`);
1127
+ await recover?.(targetId);
1107
1128
  session = await repo.create({ cwd: projectPath });
1108
1129
  }
1109
1130
  else
@@ -1113,9 +1134,7 @@ export class EcagentRunner {
1113
1134
  // Topic UNBOUND is an explicit backend boundary. Let ecagent allocate a
1114
1135
  // fresh provider ID; reusing the EvolCore Session ID would make every
1115
1136
  // /renew cycle reopen the same provider session under a new filename.
1116
- session = topicBinding
1117
- ? await repo.create({ cwd: projectPath })
1118
- : await repo.create({ cwd: projectPath, id: sessionId });
1137
+ session = await repo.create({ cwd: projectPath });
1119
1138
  }
1120
1139
  const metadata = await session.getMetadata();
1121
1140
  if (recoverySessionId && metadata.id !== recoverySessionId) {
@@ -26,6 +26,7 @@ import { GeminiSessionFileAdapter } from '../core/session/adapters/gemini-sessio
26
26
  import { logger } from '../utils/logger.js';
27
27
  import { normalizeExecutionPermissionMode, normalizePermissionMode } from '../core/permission/mode.js';
28
28
  import { resolveRoot } from '../paths.js';
29
+ import { getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
29
30
  import { workspaceContainsHClassPaths } from '../core/permission/protected-paths.js';
30
31
  import { buildBubblewrapCommand } from '../core/permission/sandbox-runtime.js';
31
32
  import { getManagedTaskTempDir } from '../cli/task-context.js';
@@ -337,6 +338,12 @@ export class GeminiRunner {
337
338
  // ── ModelSwitcher ──
338
339
  setModel(model) { this.model = stripContextWindowSuffix(model); }
339
340
  getModel() { return this.model; }
341
+ /** 返回当前网关 /v1/models 的价格缓存(1h TTL,stale-while-revalidate)。
342
+ * 缺失/过期时异步触发刷新,本轮先返回旧值或 undefined(回退本地价表)。 */
343
+ getGatewayPricing() {
344
+ const conn = this.currentProviderConfig();
345
+ return getSharedGatewayPricing(conn.baseUrl, conn.apiKey, conn.headers);
346
+ }
340
347
  getModelCatalog() {
341
348
  return getRunnerCatalog('gemini', this.agentAid, this.currentProviderConfig());
342
349
  }
@@ -413,6 +420,18 @@ export class GeminiRunner {
413
420
  let geminiSessionId = topicBinding
414
421
  ? (topicAgentSessionId || undefined)
415
422
  : initialAgentSessionId || cachedSessionId;
423
+ if (!topicBinding && !initialAgentSessionId && typeof sessionManager?.getSessionById === 'function') {
424
+ const latest = await sessionManager.getSessionById(sessionId);
425
+ geminiSessionId = latest?.agentSessionId || undefined;
426
+ }
427
+ if (!topicBinding && geminiSessionId && modelOverride?.capsule
428
+ && !this.resolveSessionFile(geminiSessionId, projectPath)) {
429
+ const recovered = await modelOverride.capsule.recover(geminiSessionId, prompt, systemPromptAppend);
430
+ prompt = recovered.prompt;
431
+ systemPromptAppend = recovered.systemPrompt;
432
+ this.activeSessions.delete(sessionId);
433
+ geminiSessionId = undefined;
434
+ }
416
435
  // per-call 权限模式/模型:优先 override,缺省回落实例级(多会话并发互不污染)
417
436
  const requestedPermissionMode = modelOverride?.permissionMode || this.currentMode;
418
437
  const executionPermissionMode = normalizeExecutionPermissionMode(requestedPermissionMode);
@@ -539,10 +558,7 @@ export class GeminiRunner {
539
558
  const pendingToolNames = new Map(); // toolId → toolName
540
559
  const recordedDeniedToolIds = new Set();
541
560
  const startTime = Date.now();
542
- // Gemini 走 spawn + argv,输入在 spawn 时已提交;在第一个业务事件前报告
543
- if (turn?.inputId) {
544
- yield { type: 'input_accepted', inputId: turn.inputId };
545
- }
561
+ let inputAccepted = false;
546
562
  const rl = createInterface({ input: child.stdout });
547
563
  // Build async queue from readline
548
564
  const queue = [];
@@ -631,9 +647,13 @@ export class GeminiRunner {
631
647
  break;
632
648
  }
633
649
  case 'message': {
634
- // Skip user message echo
635
- if (event.role === 'user')
650
+ if (event.role === 'user') {
651
+ if (!inputAccepted && turn?.inputId) {
652
+ inputAccepted = true;
653
+ yield { type: 'input_accepted', inputId: turn.inputId };
654
+ }
636
655
  break;
656
+ }
637
657
  // Assistant message (delta=true → streaming)
638
658
  // Accumulate into textBuffer; will flush on boundary event
639
659
  if (event.role === 'assistant' && event.content) {
@@ -119,20 +119,28 @@ export function hasClearSession(agent) {
119
119
  export function numericToken(value) {
120
120
  return typeof value === 'number' && Number.isFinite(value) ? value : 0;
121
121
  }
122
- export function contextTokensForUsage(usage, isClaudeModel) {
122
+ export function contextTokensForUsage(usage, model) {
123
123
  if (!usage)
124
124
  return 0;
125
- if (!isClaudeModel)
125
+ // GPT keeps its reported input count; other models report cache separately.
126
+ if (isGptContextUsageModel(model))
126
127
  return numericToken(usage.input_tokens);
127
128
  return numericToken(usage.input_tokens)
129
+ + numericToken(usage.output_tokens)
128
130
  + numericToken(usage.cache_creation_input_tokens)
129
131
  + numericToken(usage.cache_read_input_tokens);
130
132
  }
131
133
  export function usageForContext(usage) {
132
134
  const iterations = Array.isArray(usage?.iterations) ? usage.iterations : undefined;
133
- const lastIteration = iterations?.slice().reverse().find(it => contextTokensForUsage(it, true) > 0);
135
+ const lastIteration = iterations?.slice().reverse().find(it => contextTokensForUsage(it) > 0);
134
136
  return lastIteration ?? usage;
135
137
  }
138
+ export function isGptContextUsageModel(model) {
139
+ if (!model)
140
+ return false;
141
+ const modelId = stripContextWindowSuffix(model).trim().split(/[/:]/).at(-1) ?? '';
142
+ return /^(?:gpt|chatgpt|o[134])(?:[-.]|$)/i.test(modelId);
143
+ }
136
144
  /** Models whose base ID uses a 1M context window when sent to the SDK with [1m]. */
137
145
  export const ONE_M_CONTEXT_MODEL_PREFIXES = ['claude-opus-5', 'claude-opus-4-8', 'claude-sonnet-4-6'];
138
146
  const ONE_M_CONTEXT_MODEL_ALIASES = ['opus', 'sonnet'];
@@ -0,0 +1,26 @@
1
+ /** Only this read-only query collects responses from every online device. */
2
+ export function isAidWideDeviceStatusQuery(payload) {
3
+ const params = payload?.params;
4
+ return payload?.type === 'ability' && payload.role === 'call'
5
+ && payload.ability_path === 'device/status'
6
+ && !!params && typeof params === 'object' && !Array.isArray(params)
7
+ && params.action === 'read';
8
+ }
9
+ /** Device routing belongs to message.send, never to the Ability payload. */
10
+ export function resolveAunSendDevice(deviceId, scope, payload) {
11
+ if (deviceId !== undefined && (scope !== 'msg' || typeof deviceId !== 'string'
12
+ || !deviceId || deviceId.length > 256 || /[\s\x00-\x1f\x7f]/.test(deviceId))) {
13
+ throw Object.assign(new Error('--device-id requires a nonempty private target device ID'), { code: 'INVALID_DEVICE_ID' });
14
+ }
15
+ if (isAidWideDeviceStatusQuery(payload)) {
16
+ if (scope !== 'msg' || deviceId !== undefined) {
17
+ throw Object.assign(new Error('device/status queries the AID online devices; omit --device-id and use a private AID target'), { code: 'ABILITY_DEVICE_NOT_ALLOWED' });
18
+ }
19
+ return undefined;
20
+ }
21
+ if (payload?.type === 'ability' && payload.role === 'call'
22
+ && payload.ability_path !== 'protocol/discover' && !deviceId) {
23
+ throw Object.assign(new Error('Select a device from the Provider ability index and pass --device-id; business Ability calls cannot broadcast to every device'), { code: 'ABILITY_DEVICE_REQUIRED' });
24
+ }
25
+ return deviceId;
26
+ }
@@ -39,7 +39,7 @@ export function suppressSdkLogs() {
39
39
  };
40
40
  }
41
41
  // ==================== SDK package ====================
42
- export const MIN_AUN_CORE_SDK = [0, 5, 25];
42
+ export const MIN_AUN_CORE_SDK = [0, 5, 26];
43
43
  export const AUN_CORE_SDK_PKG = '@agentunion/fastaun';
44
44
  function compareVersion(a, min) {
45
45
  const parts = a.split('.').map(n => parseInt(n, 10));
@@ -41,3 +41,11 @@ export function isExplicitGroupId(value) {
41
41
  || /^grp_[a-z0-9_-]+$/i.test(id)
42
42
  || /^g-[a-z0-9_-]+(?:[.@][a-z0-9.-]+)?$/i.test(id);
43
43
  }
44
+ /** Legacy named-group hint for generic relation data without authoritative type metadata. */
45
+ export function isLegacyNamedGroupIdHint(value) {
46
+ const id = value.trim();
47
+ if (!id)
48
+ return false;
49
+ return /^grp_[a-z0-9_-]+$/i.test(id)
50
+ || /^g-[a-z0-9_-]+(?:[.@][a-z0-9.-]+)?$/i.test(id);
51
+ }
@@ -825,7 +825,7 @@ function parseRemote(value, allowEmpty) {
825
825
  return failFs('INVALID_ARGUMENT', 'missing remote storage path');
826
826
  const separator = value.indexOf(':');
827
827
  if (separator <= 0)
828
- return failFs('INVALID_PATH', 'remote path must use <group-aid>:<absolute-path>');
828
+ return failFs('INVALID_PATH', 'remote path must use <AID>:<absolute-path>');
829
829
  let targetAid;
830
830
  const remotePath = value.slice(separator + 1);
831
831
  const rawId = value.slice(0, separator).trim();
@@ -834,7 +834,7 @@ function parseRemote(value, allowEmpty) {
834
834
  }
835
835
  catch (error) {
836
836
  if (!isValidAid(rawId))
837
- return failFs('INVALID_GROUP', `invalid group AID: ${error.message}`);
837
+ return failFs('INVALID_AID', `invalid AID: ${error.message}`);
838
838
  targetAid = rawId;
839
839
  }
840
840
  if (remotePath === '' && allowEmpty)
@@ -960,7 +960,7 @@ export function resolveManagedFsOperation(argv) {
960
960
  if (source && !('targetAid' in source))
961
961
  return source;
962
962
  if (source && source.targetAid !== destination.targetAid)
963
- return failFs('INVALID_GROUP', 'managed cp cannot cross targets');
963
+ return failFs('INVALID_ARGUMENT', 'managed cp cannot cross targets');
964
964
  const kind = source ? 'copy' : 'upload';
965
965
  return { ok: true, command: {
966
966
  kind, operationId: `ec.fs.${kind}`, canonicalArgv: ['fs', 'cp', positionals[0], positionals[1], ...(actorAid ? ['--as', actorAid] : [])],
@@ -976,7 +976,7 @@ export function resolveManagedFsOperation(argv) {
976
976
  if (!('targetAid' in destination))
977
977
  return destination;
978
978
  if (source.targetAid !== destination.targetAid)
979
- return failFs('INVALID_GROUP', 'managed mv cannot cross targets');
979
+ return failFs('INVALID_ARGUMENT', 'managed mv cannot cross targets');
980
980
  return { ok: true, command: {
981
981
  kind: 'move', operationId: 'ec.fs.move', canonicalArgv: ['fs', 'mv', positionals[0], positionals[1], ...(actorAid ? ['--as', actorAid] : [])],
982
982
  actorAid, targetAid: destination.targetAid, remotePath: destination.remotePath, destinationPath: destination.remotePath,
@@ -13,6 +13,7 @@ import { loadDaemonConfig } from '../../config-store.js';
13
13
  import { formatPeerKey } from '../../core/relation/peer-identity.js';
14
14
  import { normalizeAunMentionEntries, withAunAttention } from './mention-schema.js';
15
15
  import { isTopicThreadId } from '../../core/thread/topic-id.js';
16
+ import { resolveAunSendDevice } from '../ability-device-routing.js';
16
17
  const DAEMON_SEND_TIMEOUT_GRACE_MS = 10_000;
17
18
  const DEFAULT_IDLE_TIMEOUT_MS = 120_000;
18
19
  const MAX_TIMER_MS = 2_147_483_647;
@@ -98,7 +99,9 @@ function msgSendLogMetadata(args, payload, runtimeContext) {
98
99
  const isInSession = !!process.env.EVOLCORE_SESSION_ID || !!runtimeContext;
99
100
  const source = isInSession ? 'msg' : 'cli';
100
101
  const classified = payload === undefined ? undefined : classifyAunPayloadForLog(payload);
101
- const threadId = msgSendThreadId(args, payload && typeof payload === 'object' ? payload : undefined, runtimeContext);
102
+ const threadId = args.body.mode === 'payload'
103
+ ? args.thread
104
+ : msgSendThreadId(args, payload && typeof payload === 'object' ? payload : undefined, runtimeContext);
102
105
  const sessionId = runtimeContext?.channel === 'aun'
103
106
  && runtimeContext.chatType === 'private'
104
107
  && runtimeContext.selfAid === args.from
@@ -132,12 +135,15 @@ async function tryDaemonMsgSend(args, payload, runtimeContext, file) {
132
135
  if (args.slotId || args.aunPath) {
133
136
  return { ok: false, code: 'INVALID_DELEGATION', error: 'Task sends cannot override the daemon AUN connection' };
134
137
  }
135
- const thread = msgSendThreadId(args, payload, runtimeContext);
138
+ const thread = args.body.mode === 'payload'
139
+ ? args.thread
140
+ : msgSendThreadId(args, payload, runtimeContext);
136
141
  const response = await ipcQuery(resolvePaths().socket, {
137
142
  type: 'aun-msg-send',
138
143
  aid: args.from,
139
144
  to: args.to,
140
145
  scope: 'msg',
146
+ deviceId: args.deviceId,
141
147
  ...(payload ? { payload } : { file }),
142
148
  rawPayload: args.body.mode === 'payload',
143
149
  encrypt: args.encrypt,
@@ -169,8 +175,9 @@ async function daemonMsgSendResult(args, payload, runtimeContext, daemonResult)
169
175
  };
170
176
  }
171
177
  const completedRequest = args.returnPolicy === 'required' && !!daemonResult.request_id
172
- && daemonResult.request_state === 'completed' && !!daemonResult.response
173
- && typeof daemonResult.response === 'object' && !Array.isArray(daemonResult.response);
178
+ && daemonResult.request_state === 'completed'
179
+ && ((!!daemonResult.response && typeof daemonResult.response === 'object' && !Array.isArray(daemonResult.response))
180
+ || (Array.isArray(daemonResult.responses) && daemonResult.responses.length > 0));
174
181
  if (!daemonResult.message_id && !daemonResult.handoff_id && !completedRequest) {
175
182
  return { ok: false, error: 'daemon AUN message send returned no message_id' };
176
183
  }
@@ -186,6 +193,8 @@ async function daemonMsgSendResult(args, payload, runtimeContext, daemonResult)
186
193
  request_id: daemonResult.request_id,
187
194
  request_state: daemonResult.request_state,
188
195
  response: daemonResult.response,
196
+ responses: daemonResult.responses,
197
+ request_diagnostics: daemonResult.request_diagnostics,
189
198
  transport_error: daemonResult.transport_error,
190
199
  };
191
200
  if (sent.message_id && !daemonResult.handoff_id && !daemonResult.log_written) {
@@ -232,6 +241,12 @@ async function appendMsgSendOutboundLog(args, result, opts) {
232
241
  catch { /* daemon 不在或 IPC 失败都忽略 */ }
233
242
  }
234
243
  export async function msgSend(args) {
244
+ try {
245
+ resolveAunSendDevice(args.deviceId, 'msg', args.body.mode === 'payload' ? args.body.payload : undefined);
246
+ }
247
+ catch (error) {
248
+ return { ok: false, code: error.code, error: error.message };
249
+ }
235
250
  if (args.handoffContext !== undefined && (!process.env.EVOLCORE_SESSION_ID
236
251
  || !args.handoffContext.trim() || args.handoffContext.length > 64 * 1024)) {
237
252
  return { ok: false, code: 'INVALID_HANDOFF_CONTEXT', error: 'handoff context requires a managed session and 1–65536 characters' };
@@ -252,7 +267,9 @@ export async function msgSend(args) {
252
267
  if (args.body.mode !== 'payload' && Object.prototype.hasOwnProperty.call(payload, 'mentions')) {
253
268
  payload.mentions = normalizeAunMentionEntries(payload.mentions);
254
269
  }
255
- applyRoutingPayloadFields(payload, args, runtimeContext, false);
270
+ if (args.body.mode !== 'payload') {
271
+ applyRoutingPayloadFields(payload, args, runtimeContext, false);
272
+ }
256
273
  const daemonResult = await tryDaemonMsgSend(args, payload, runtimeContext);
257
274
  if (daemonResult)
258
275
  return daemonMsgSendResult(args, payload, runtimeContext, daemonResult);
@@ -336,14 +353,17 @@ export async function msgSend(args) {
336
353
  if (args.body.mode !== 'payload')
337
354
  payload.chatmode = chatmode;
338
355
  // 5. 写入 payload.thread_id/ref_message_id(如果指定)
339
- applyRoutingPayloadFields(payload, args, runtimeContext, args.body.mode !== 'payload');
356
+ if (args.body.mode !== 'payload') {
357
+ applyRoutingPayloadFields(payload, args, runtimeContext);
358
+ }
340
359
  if (args.body.mode !== 'payload' && Object.prototype.hasOwnProperty.call(payload, 'mentions')) {
341
360
  payload.mentions = normalizeAunMentionEntries(payload.mentions);
342
361
  }
343
362
  const encrypt = resolveAunMessageEncrypt(args.encrypt);
344
363
  if (args.body.mode !== 'payload')
345
364
  payload = withAunAttention(payload);
346
- const sendParams = { to: args.to, payload, encrypt };
365
+ const sendParams = { to: args.to, payload, encrypt,
366
+ ...(args.deviceId ? { device_id: args.deviceId } : {}) };
347
367
  const result = await conn.call('message.send', sendParams);
348
368
  const messageId = typeof result?.message_id === 'string' && result.message_id.trim()
349
369
  ? result.message_id
@@ -27,3 +27,33 @@ export async function storageDownload(aid, url, localPath, opts) {
27
27
  fs.writeFileSync(outPath, buffer);
28
28
  return { ok: true, localPath: outPath, size: buffer.length };
29
29
  }
30
+ export async function storageGetByShare(aid, shareId, localPath, opts) {
31
+ const shareResult = await rpcCall(aid, 'storage.get_by_share', { share_id: shareId }, { aunPath: opts?.aunPath });
32
+ if (!shareResult.ok) {
33
+ return { ok: false, localPath: '', size: 0, error: JSON.stringify(shareResult.error) };
34
+ }
35
+ const res = shareResult.result;
36
+ const objectKey = typeof res.object_key === 'string' ? res.object_key : '';
37
+ const contentType = typeof res.content_type === 'string' ? res.content_type : undefined;
38
+ const sha256 = typeof res.sha256 === 'string' ? res.sha256 : undefined;
39
+ // Small object: content is inlined as base64
40
+ if (typeof res.content === 'string') {
41
+ const buffer = Buffer.from(res.content, 'base64');
42
+ const outPath = localPath ?? (objectKey ? path.basename(objectKey) : `share-${shareId}`);
43
+ fs.writeFileSync(outPath, buffer);
44
+ return { ok: true, localPath: outPath, size: buffer.length, objectKey, contentType, sha256 };
45
+ }
46
+ // Large object: download_url provided
47
+ const downloadUrl = typeof res.download_url === 'string' ? res.download_url : undefined;
48
+ if (!downloadUrl) {
49
+ return { ok: false, localPath: '', size: 0, error: 'storage.get_by_share returned neither content nor download_url' };
50
+ }
51
+ const resp = await fetch(downloadUrl);
52
+ if (!resp.ok) {
53
+ return { ok: false, localPath: '', size: 0, error: `HTTP GET failed: ${resp.status}` };
54
+ }
55
+ const buffer = Buffer.from(await resp.arrayBuffer());
56
+ const outPath = localPath ?? (objectKey ? path.basename(objectKey) : `share-${shareId}`);
57
+ fs.writeFileSync(outPath, buffer);
58
+ return { ok: true, localPath: outPath, size: buffer.length, objectKey, contentType, sha256 };
59
+ }
@@ -1,5 +1,5 @@
1
1
  export { storageUpload, storageUploadBuffer, storageLs, storageRm, storageQuota } from './client.js';
2
- export { storageDownload } from './download.js';
2
+ export { storageDownload, storageGetByShare } from './download.js';
3
3
  import { isValidAid } from '../aid/validation.js';
4
4
  export function resolveStorageCommandArgv(argv) {
5
5
  if (argv[0] !== 'storage')
@@ -18,14 +18,22 @@ export function resolveStorageCommandArgv(argv) {
18
18
  positionals.push(value);
19
19
  }
20
20
  const [sub, aid, source, destination] = positionals;
21
- const operation = { upload: 'storage.upload', download: 'storage.download', ls: 'storage.list', rm: 'storage.delete', quota: 'storage.quota' }[sub];
21
+ const operation = {
22
+ upload: 'storage.upload', download: 'storage.download', ls: 'storage.list',
23
+ rm: 'storage.delete', quota: 'storage.quota', 'get-by-share': 'storage.get_by_share',
24
+ }[sub];
22
25
  if (!operation || !aid || !isValidAid(aid))
23
26
  throw new Error('Invalid storage command or AID');
24
- const counts = { upload: [4], download: [3, 4], ls: [2, 3], rm: [3], quota: [2] };
27
+ const counts = {
28
+ upload: [4], download: [3, 4], ls: [2, 3], rm: [3], quota: [2], 'get-by-share': [3, 4],
29
+ };
25
30
  if (!counts[sub].includes(positionals.length) || (isPublic && sub !== 'upload'))
26
31
  throw new Error('Invalid storage arguments');
27
- return { sub, aid, operation, isPublic, localFile: sub === 'upload' ? source : undefined,
32
+ return { sub, aid, operation, isPublic,
33
+ localFile: sub === 'upload' ? source : undefined,
28
34
  remotePath: sub === 'upload' ? destination : sub === 'rm' ? source : undefined,
29
- url: sub === 'download' ? source : undefined, localPath: sub === 'download' ? destination : undefined,
30
- prefix: sub === 'ls' ? source ?? '' : undefined };
35
+ url: sub === 'download' ? source : undefined,
36
+ localPath: sub === 'download' ? destination : sub === 'get-by-share' ? destination : undefined,
37
+ prefix: sub === 'ls' ? source ?? '' : undefined,
38
+ shareId: sub === 'get-by-share' ? source : undefined };
31
39
  }
@@ -12,6 +12,7 @@ import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } f
12
12
  import { DEFAULT_FLUSH_DELAY_SECONDS } from '../types.js';
13
13
  import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath } from '../paths.js';
14
14
  import { getAunRequestRegistry, MAX_AUN_VOLATILE_TTL_SECONDS } from '../core/message/aun-request-registry.js';
15
+ import { resolveAunSendDevice } from '../aun/ability-device-routing.js';
15
16
  import { saveToUploads, saveRelationAttachment, sanitizeFileName, bufferToInboundImage, safeFetch } from '../utils/media-cache.js';
16
17
  import { appendAidEvent } from '../utils/instance-registry.js';
17
18
  import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInboundEntry, classifyAunPayloadForLog, findLatestMessageLogOperation, findMessageLogOperationMessageId, hasMessageLogOperation } from '../core/message/message-log.js';
@@ -581,6 +582,24 @@ function appendRawErrorText(text, raw) {
581
582
  return text;
582
583
  return `${text}\n原因:${rawText}`;
583
584
  }
585
+ function structuredErrorSendReceipt(envelope, result, threadId) {
586
+ if (result.messageId)
587
+ return sentReceipt(envelope, [result.messageId], threadId);
588
+ const operationId = envelope.operationId ?? envelope.taskId;
589
+ if ((result.status === 'retry' || result.queued) && result.outboxId) {
590
+ return {
591
+ status: 'queued', operationId, messages: [], outboxId: result.outboxId,
592
+ ...(result.error !== undefined ? { error: result.error } : {}),
593
+ ...(result.code !== undefined ? { code: result.code } : {}),
594
+ };
595
+ }
596
+ return {
597
+ status: 'failed', operationId, messages: [],
598
+ ...(result.outboxId !== undefined ? { outboxId: result.outboxId } : {}),
599
+ error: result.error ?? 'AUN structured error send returned no delivery receipt',
600
+ code: result.code ?? 'MISSING_SEND_RECEIPT',
601
+ };
602
+ }
584
603
  /**
585
604
  * 把 AUNChannel 投递的 opts 映射成渠道无关的 InboundMessage。
586
605
  *
@@ -2534,6 +2553,7 @@ export class AUNChannel {
2534
2553
  const responseRecord = getAunRequestRegistry().resolveIncoming({
2535
2554
  selfAid: this._aid || this.config.aid,
2536
2555
  fromAid,
2556
+ fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
2537
2557
  messageId,
2538
2558
  payload,
2539
2559
  });
@@ -2758,6 +2778,7 @@ export class AUNChannel {
2758
2778
  const responseRecord = getAunRequestRegistry().resolveIncoming({
2759
2779
  selfAid: this._aid || this.config.aid,
2760
2780
  fromAid: senderAid,
2781
+ fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
2761
2782
  messageId,
2762
2783
  payload,
2763
2784
  });
@@ -4802,6 +4823,12 @@ export class AUNChannel {
4802
4823
  return seqInTurn;
4803
4824
  }
4804
4825
  async sendDaemonMsg(args) {
4826
+ try {
4827
+ resolveAunSendDevice(args.deviceId, 'msg', args.payload);
4828
+ }
4829
+ catch (error) {
4830
+ return { ok: false, code: error.code, error: error.message };
4831
+ }
4805
4832
  if (!args.to) {
4806
4833
  return { ok: false, error: 'aun-msg-send requires a private target', code: 'UNSUPPORTED_TARGET' };
4807
4834
  }
@@ -4887,6 +4914,7 @@ export class AUNChannel {
4887
4914
  to: args.to,
4888
4915
  payload: preserveRawPayload ? finalPayload : this.truncatePayloadIfNeeded(finalPayload, 'msg-send-ipc'),
4889
4916
  encrypt,
4917
+ ...(args.deviceId ? { device_id: args.deviceId } : {}),
4890
4918
  ...(args.ttl !== undefined ? { ttl: args.ttl } : {}),
4891
4919
  };
4892
4920
  try {
@@ -6723,8 +6751,8 @@ export class AUNChannelPlugin {
6723
6751
  ...(payload.reason !== undefined ? { reason: payload.reason } : {}),
6724
6752
  ...(payload.recoverable !== undefined ? { recoverable: payload.recoverable } : {}),
6725
6753
  };
6726
- await channel.sendReliableStructured(channelId, errorPayload, { ...(replyCtx ?? {}), suppressPeerMention: true }, payload.text);
6727
- return;
6754
+ const result = await channel.sendReliableStructured(channelId, errorPayload, { ...(replyCtx ?? {}), suppressPeerMention: true }, payload.text);
6755
+ return structuredErrorSendReceipt(envelope, result, replyCtx?.threadId);
6728
6756
  }
6729
6757
  case 'result.error': {
6730
6758
  const raw = rawErrorText(payload.raw) ?? payload.text;
@@ -6736,8 +6764,9 @@ export class AUNChannelPlugin {
6736
6764
  };
6737
6765
  setIfDefined(errorPayload, 'subtype', payload.subtype);
6738
6766
  setIfDefined(errorPayload, 'reason', payload.reason);
6739
- await channel.sendReliableStructured(channelId, errorPayload, { ...(replyCtx ?? {}), suppressPeerMention: true }, payload.text);
6740
- return;
6767
+ setIfDefined(errorPayload, 'recoverable', payload.recoverable);
6768
+ const result = await channel.sendReliableStructured(channelId, errorPayload, { ...(replyCtx ?? {}), suppressPeerMention: true }, payload.text);
6769
+ return structuredErrorSendReceipt(envelope, result, replyCtx?.threadId);
6741
6770
  }
6742
6771
  case 'result.file': {
6743
6772
  const fileCtx = payload.correlationId
@@ -187,11 +187,11 @@ export class DaemonChannel {
187
187
  slot.acc.files.push({ path: payload.filePath, name: payload.fileName });
188
188
  break;
189
189
  case 'result.error':
190
- slot.acc.error = { reason: payload.reason, text: payload.text, recoverable: payload.recoverable };
190
+ slot.acc.error = { reason: payload.reason, subtype: payload.subtype, text: payload.text, raw: payload.raw, recoverable: payload.recoverable };
191
191
  this.finish(runId, 'error', { errorType: payload.reason ?? 'result_error' });
192
192
  break;
193
193
  case 'system.error':
194
- slot.acc.error = { reason: payload.subtype, text: payload.text, recoverable: payload.recoverable };
194
+ slot.acc.error = { reason: payload.reason ?? payload.subtype, subtype: payload.subtype, text: payload.text, raw: payload.raw, recoverable: payload.recoverable };
195
195
  this.finish(runId, 'error', { errorType: payload.subtype });
196
196
  break;
197
197
  case 'status.progress':
@@ -221,8 +221,10 @@ export class DaemonChannel {
221
221
  case 'status.error':
222
222
  if (payload.metadata?.message) {
223
223
  slot.acc.error = {
224
- reason: payload.metadata.errorType ?? 'status_error',
224
+ reason: payload.metadata.reason ?? payload.metadata.errorType ?? 'status_error',
225
+ subtype: payload.metadata.errorType,
225
226
  text: payload.metadata.message,
227
+ raw: payload.metadata.raw,
226
228
  recoverable: payload.metadata.recoverable,
227
229
  };
228
230
  }
@@ -236,6 +238,16 @@ export class DaemonChannel {
236
238
  this.finish(runId, 'interrupted', payload.metadata);
237
239
  break;
238
240
  case 'status.timeout':
241
+ slot.acc.error = {
242
+ reason: payload.metadata?.reason ?? payload.metadata?.errorType ?? 'timeout',
243
+ subtype: payload.metadata?.errorType,
244
+ text: payload.metadata?.message
245
+ ?? (payload.metadata?.idleSec
246
+ ? `任务超时(${payload.metadata.idleSec}秒无响应),已自动中断`
247
+ : '任务超时,已自动中断'),
248
+ recoverable: payload.metadata?.recoverable,
249
+ raw: payload.metadata?.raw,
250
+ };
239
251
  this.finish(runId, 'timeout', payload.metadata);
240
252
  break;
241
253
  }
@@ -424,9 +436,13 @@ export class DaemonChannel {
424
436
  slot.acc.error = {
425
437
  reason: 'daemon_watchdog_timeout',
426
438
  text: `daemon conversation watchdog timed out after ${this.watchdogMs}ms`,
439
+ recoverable: true,
427
440
  };
428
- if (!this.claimTerminal(slot, 'error', {
441
+ if (!this.claimTerminal(slot, 'timeout', {
429
442
  errorType: 'daemon_watchdog_timeout',
443
+ reason: 'daemon_watchdog_timeout',
444
+ message: slot.acc.error.text,
445
+ recoverable: true,
430
446
  watchdogMs: this.watchdogMs,
431
447
  }))
432
448
  return;
@@ -448,9 +464,13 @@ export class DaemonChannel {
448
464
  slot.acc.error = {
449
465
  reason: 'daemon_total_execution_timeout',
450
466
  text: `daemon conversation exceeded total execution limit of ${totalExecutionMs}ms`,
467
+ recoverable: true,
451
468
  };
452
469
  if (!this.claimTerminal(slot, 'timeout', {
453
470
  errorType: 'daemon_total_execution_timeout',
471
+ reason: 'daemon_total_execution_timeout',
472
+ message: slot.acc.error.text,
473
+ recoverable: true,
454
474
  totalExecutionMs,
455
475
  }))
456
476
  return;
@@ -82,6 +82,8 @@ function printAgentNewHelp() {
82
82
  --project <path> 默认: 当前目录
83
83
  --baseagent <claude|codex|gemini|ecagent>
84
84
  默认: defaults 配置,否则检测本机可用基座
85
+ --model <id> 初始化可选;须在主机当前基座的可见模型目录中
86
+ --effort <level> 初始化可选;需同时指定 model,auto 使用默认强度
85
87
  --owner <aid> 必填;初始协议 Owner 绑定意图
86
88
  --name <display-name> 初始化必填;Bootstrap 默认取项目名称
87
89
  --description <text> 初始化必填;Bootstrap 默认取项目描述