evolcore 0.0.41 → 0.0.42

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 (190) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/bin/codex-managed-hook.mjs +9 -5
  3. package/dist/agents/baseagent.js +156 -16
  4. package/dist/agents/claude-runner.js +10 -3
  5. package/dist/agents/codex/catalog.js +8 -4
  6. package/dist/agents/codex-runner.js +236 -59
  7. package/dist/agents/ecagent-runner.js +82 -13
  8. package/dist/aun/aid/agentmd.js +106 -27
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +65 -13
  11. package/dist/aun/aid/identity.js +70 -4
  12. package/dist/aun/aid/index.js +2 -2
  13. package/dist/aun/service-proxy.js +25 -1
  14. package/dist/channels/aun.js +242 -209
  15. package/dist/channels/dingtalk.js +1 -1
  16. package/dist/channels/feishu.js +1 -1
  17. package/dist/channels/qqbot.js +1 -1
  18. package/dist/channels/wechat.js +1 -1
  19. package/dist/channels/wecom.js +1 -1
  20. package/dist/cli/agent-command.js +183 -3
  21. package/dist/cli/agent-create.js +92 -86
  22. package/dist/cli/agent.js +136 -1
  23. package/dist/cli/aun-commands.js +137 -35
  24. package/dist/cli/bench.js +8 -2
  25. package/dist/cli/command-log.js +1 -1
  26. package/dist/cli/daemon-commands.js +235 -51
  27. package/dist/cli/debug-mode.js +1 -1
  28. package/dist/cli/directory.js +170 -0
  29. package/dist/cli/index.js +40 -30
  30. package/dist/cli/init-channel.js +4 -4
  31. package/dist/cli/init.js +47 -32
  32. package/dist/cli/managed-command-guard.js +4 -1
  33. package/dist/cli/model.js +27 -18
  34. package/dist/cli/pa-workspace-command.js +191 -0
  35. package/dist/cli/{contact.js → peer.js} +19 -25
  36. package/dist/cli/restart-monitor.js +11 -4
  37. package/dist/cli/thread-command.js +47 -18
  38. package/dist/cli/version.js +18 -18
  39. package/dist/config/access-policy.js +29 -12
  40. package/dist/config/boot-log.js +65 -10
  41. package/dist/config/builtin-roles.js +2 -4
  42. package/dist/config/config-field-policy.js +3 -0
  43. package/dist/config/config-manager.js +28 -20
  44. package/dist/config/{contact-bind-code.js → peer-bind-code.js} +6 -6
  45. package/dist/config/{contact-book-store.js → peer-book-store.js} +75 -75
  46. package/dist/config/{contact-book-v2-startup.js → peer-book-v2-startup.js} +2 -2
  47. package/dist/config/{contact-book.js → peer-book.js} +47 -47
  48. package/dist/config/peer-operation-service.js +132 -0
  49. package/dist/config/{contact-request-service.js → peer-request-service.js} +90 -90
  50. package/dist/config/peer-role-resolver.js +3 -3
  51. package/dist/config/providers-config.js +17 -8
  52. package/dist/config/providers.js +1 -1
  53. package/dist/config/schema-migration.js +336 -39
  54. package/dist/core/agent-application-service.js +8 -2
  55. package/dist/core/agent-create-status.js +4 -5
  56. package/dist/core/agent-ipc-registration.js +5 -4
  57. package/dist/core/agent-runtime.js +30 -17
  58. package/dist/core/auth/operation-authorizer.js +0 -24
  59. package/dist/core/auth/operation-catalog.js +4 -20
  60. package/dist/core/baseagent-loader.js +27 -3
  61. package/dist/core/bootstrap-service.js +5 -22
  62. package/dist/core/capability/capability-manager.js +52 -35
  63. package/dist/core/channel-loader.js +43 -2
  64. package/dist/core/channel-runtime.js +2 -2
  65. package/dist/core/command/agent-control.js +54 -18
  66. package/dist/core/command/command-handler.js +92 -72
  67. package/dist/core/command/connect-menu.js +35 -42
  68. package/dist/core/command/daemon-diagnostics.js +41 -5
  69. package/dist/core/command/data-root-error.js +10 -0
  70. package/dist/core/command/data-root-resolver.js +53 -13
  71. package/dist/core/command/menu-catalog.js +1 -0
  72. package/dist/core/command/menu-handler.js +163 -65
  73. package/dist/core/command/menu-protocol.js +52 -0
  74. package/dist/core/command/pa-workspace-calendar.js +223 -0
  75. package/dist/core/command/pa-workspace-store.js +459 -0
  76. package/dist/core/command/role-menu.js +2 -2
  77. package/dist/core/command/slash-gate.js +1 -1
  78. package/dist/core/command/slash-handler.js +57 -41
  79. package/dist/core/daemon-lifecycle.js +90 -31
  80. package/dist/core/evolagent.js +6 -10
  81. package/dist/core/handoff/runtime.js +11 -4
  82. package/dist/core/host-snapshot.js +208 -0
  83. package/dist/core/initialization/service.js +152 -20
  84. package/dist/core/ipc-registration.js +33 -4
  85. package/dist/core/memory/batch-meta.js +27 -0
  86. package/dist/core/memory/consolidation-ops-records.js +44 -1
  87. package/dist/core/memory/consolidation.js +169 -27
  88. package/dist/core/message/aun-ipc-sender.js +2 -8
  89. package/dist/core/message/im-renderer.js +56 -3
  90. package/dist/core/message/message-admission.js +121 -124
  91. package/dist/core/message/message-bridge.js +38 -54
  92. package/dist/core/message/message-queue.js +7 -0
  93. package/dist/core/message/outbound.js +34 -9
  94. package/dist/core/message/response-engine.js +154 -73
  95. package/dist/core/model/catalog-service.js +1 -1
  96. package/dist/core/model/config-scope.js +2 -2
  97. package/dist/core/model/model-catalog.js +5 -4
  98. package/dist/core/model/model-diagnostics.js +6 -5
  99. package/dist/core/model/model-fallback.js +3 -6
  100. package/dist/core/model/model-permission.js +1 -1
  101. package/dist/core/ownership/owner-resolver.js +9 -9
  102. package/dist/core/permission/approval-gateway.js +1 -1
  103. package/dist/core/permission/ec-command-parser.js +2 -2
  104. package/dist/core/permission/tool-canonical.js +96 -46
  105. package/dist/core/permission/tool-error-code.js +41 -0
  106. package/dist/core/permission/tool-policy.js +71 -47
  107. package/dist/core/role/runtime-policy.js +1 -1
  108. package/dist/core/session/session-idle-monitor.js +10 -0
  109. package/dist/core/session/session-manager.js +2 -4
  110. package/dist/core/session/session-title.js +36 -8
  111. package/dist/core/system-session/memory.js +2 -7
  112. package/dist/core/thread/command-parser.js +6 -2
  113. package/dist/core/thread/ipc-operation.js +51 -36
  114. package/dist/core/thread/thread-operation.js +29 -61
  115. package/dist/core/thread/thread-service.js +57 -13
  116. package/dist/directory/canonical-digest.js +54 -0
  117. package/dist/directory/owner-directory-admission.js +114 -43
  118. package/dist/directory/owner-directory-agentmd-sync.js +89 -0
  119. package/dist/directory/owner-directory-cache.js +847 -459
  120. package/dist/directory/owner-directory-markdown.js +272 -0
  121. package/dist/directory/owner-directory-query-operation.js +195 -0
  122. package/dist/directory/owner-directory-remark-operation.js +147 -0
  123. package/dist/directory/owner-directory-remarks.js +145 -0
  124. package/dist/directory/owner-directory-scope.js +55 -0
  125. package/dist/directory/owner-directory-search.js +148 -0
  126. package/dist/directory/owner-directory-store.js +227 -0
  127. package/dist/eck/kit-renderer.js +1 -0
  128. package/dist/ecweb/basic-settings-service.js +4 -1
  129. package/dist/ecweb/message-context-service.js +13 -9
  130. package/dist/index.js +195 -37
  131. package/dist/ipc.js +86 -22
  132. package/dist/paths.js +11 -8
  133. package/dist/product.js +2 -0
  134. package/dist/proxy/manager.js +13 -2
  135. package/dist/proxy/service-supervisor.js +8 -1
  136. package/dist/trigger/history.js +23 -0
  137. package/dist/trigger/scheduler.js +3 -0
  138. package/dist/utils/atomic-write.js +21 -0
  139. package/dist/utils/cross-platform.js +35 -0
  140. package/dist/utils/ecweb-supervisor.js +42 -0
  141. package/dist/utils/error-utils.js +2 -1
  142. package/dist/utils/evolcore-version.js +19 -0
  143. package/dist/utils/host-info.js +242 -5
  144. package/dist/utils/instance-registry.js +28 -6
  145. package/dist/utils/logger.js +59 -14
  146. package/dist/utils/machine-info.js +46 -0
  147. package/dist/utils/process-introspect.js +166 -2
  148. package/dist/utils/startup-trace.js +245 -0
  149. package/ecagent/dist/agent-loop.js +27 -13
  150. package/ecagent/dist/harness/agent-harness.js +3 -3
  151. package/ecagent/dist/harness/types.d.ts +1 -0
  152. package/ecagent/dist/types.d.ts +1 -0
  153. package/kits/docs/INDEX.md +1 -1
  154. package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +72 -0
  155. package/kits/docs/evolcore/INDEX.md +3 -2
  156. package/kits/docs/evolcore/agent-create.md +17 -27
  157. package/kits/docs/evolcore/agent.md +4 -1
  158. package/kits/docs/evolcore/aid.md +3 -1
  159. package/kits/docs/evolcore/config.md +16 -5
  160. package/kits/docs/evolcore/ctl.md +9 -0
  161. package/kits/docs/evolcore/ec-capabilities.md +19 -0
  162. package/kits/docs/evolcore/memory-consolidation-batches.md +79 -5
  163. package/kits/docs/evolcore/menu-exec-schema-commands.md +2 -1
  164. package/kits/docs/evolcore/menu-protocol.md +1 -0
  165. package/kits/docs/evolcore/model.md +13 -4
  166. package/kits/docs/evolcore/msg.md +1 -1
  167. package/kits/docs/evolcore/pa-workspace.md +51 -0
  168. package/kits/docs/evolcore/peer.md +73 -0
  169. package/kits/docs/evolcore/thread-chain.md +4 -1
  170. package/kits/eck_manifest.json +21 -0
  171. package/kits/rules/06-channel.md +1 -1
  172. package/kits/schemas/_meta.json +12 -1
  173. package/kits/schemas/agent-config.schema.16.json +6 -0
  174. package/kits/schemas/agent-config.schema.17.json +897 -0
  175. package/kits/schemas/daemon.schema.9.json +8 -1
  176. package/kits/skills/ec-agent-create/SKILL.md +2 -2
  177. package/kits/skills/ec-identity/SKILL.md +45 -27
  178. package/kits/skills/ec-service-proxy/SKILL.md +7 -2
  179. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +4 -5
  180. package/kits/skills/thread-ops/SKILL.md +11 -11
  181. package/kits/templates/bootstrap-welcome.md +3 -15
  182. package/kits/templates/message-fragments/item.md +1 -1
  183. package/kits/templates/system-fragments/bootstrap.md +24 -23
  184. package/kits/templates/system-fragments/commands.md +12 -5
  185. package/kits/templates/system-fragments/thread.md +18 -3
  186. package/package.json +6 -4
  187. package/dist/config/contact-operation-service.js +0 -235
  188. package/dist/directory/owner-directory-authorization.js +0 -309
  189. package/kits/docs/evolcore/contact.md +0 -78
  190. /package/dist/config/{contact-alias.js → peer-alias.js} +0 -0
@@ -7,7 +7,7 @@ import { ensureSessionRuntimeDir } from '../../cli/task-context.js';
7
7
  import { renderCommandCardAsText } from '../interaction-router.js';
8
8
  import { buildEnvelope, deliveryTargetFromSession, isInteractionSendAccepted, replyContextFromSession, sendInteractionPayload } from '../message/message-utils.js';
9
9
  import { sessionTopicThreadId } from '../thread/topic-id.js';
10
- import { resolvePaths, getPackageRoot } from '../../paths.js';
10
+ import { resolvePaths, getPackageRoot, resolveRoot } from '../../paths.js';
11
11
  import { loadDaemonConfig } from '../../config-store.js';
12
12
  import { parseOwnershipCommand, executeOwnershipCommand, ownershipFailure } from '../../aun/aid/ownership-operation.js';
13
13
  import { ownerResolver, refreshOwnershipForAuthorization } from '../ownership/owner-resolver.js';
@@ -36,15 +36,17 @@ import { parseTimeArg, TIME_ARG_FORMATS, splitConfigBatchGetArgv } from '../../c
36
36
  import { auditCommandAuthorization, auditFullAccessEvent, hashArgv } from '../auth/authorization-audit.js';
37
37
  import { ResponseModeRegistry } from '../../response-system/registry.js';
38
38
  import { registerBuiltinModes } from '../../response-system/modes/index.js';
39
+ import { DirectoryRemarkError, executeDirectoryRemarkCommand, resolveDirectoryRemarkCommand, } from '../../directory/owner-directory-remark-operation.js';
40
+ import { DirectoryQueryError, executeDirectoryQueryCommand, resolveDirectoryQueryCommand, } from '../../directory/owner-directory-query-operation.js';
39
41
  import { executeResolvedRoleCommand, resolveRoleCommand } from '../../config/role-command-service.js';
40
42
  import { applyApprovedRoleAssignment } from './role-menu.js';
41
- import { executeResolvedContactCommand, resolveContactCommand } from '../../config/contact-operation-service.js';
43
+ import { executeResolvedPeerCommand, resolvePeerCommand } from '../../config/peer-operation-service.js';
42
44
  import { hasTrustedFullAccessDelegation, trustedExecutionIdentityInput } from '../auth/agent-delegation.js';
43
45
  import { executeManagedAidOperation, ManagedAidOperationError, managedAidShowViewForRole, resolveManagedAidOperation, } from '../../aun/aid/managed-operation.js';
44
46
  import { MAX_AVATAR_SOURCE_BYTES } from '../../utils/avatar-upload.js';
45
47
  import { executeManagedGroupOperation, isManagedGroupRelationRead, isManagedGroupRelationWrite, ManagedGroupOperationError, resolveManagedGroupOperation, executeManagedMsgOperation, ManagedMsgOperationError, resolveManagedMsgOperation, executeManagedFsOperation, ManagedFsOperationError, resolveManagedFsOperation, } from '../../aun/msg/managed-operation.js';
46
48
  import { authorizeFreshOperation, buildAuthSubject, executeAuditedOperation } from '../auth/auth-gateway.js';
47
- import { isHClassPath, isLClassPath, isSameOrDescendant } from '../permission/protected-paths.js';
49
+ import { getExistingRelationAttachmentDirs, isHClassPath, isLClassPath, isSameOrDescendant } from '../permission/protected-paths.js';
48
50
  import { validateModelSelectionForRole } from '../model/model-permission.js';
49
51
  import { getModelInfo } from '../model/model-catalog.js';
50
52
  import { constrainRuntimePermissionMode, resolveRuntimePermissionMode, validateRuntimeStringFieldOverride } from '../role/runtime-policy.js';
@@ -113,6 +115,7 @@ export class CommandHandler {
113
115
  daemonTriggerChannel = 'daemon';
114
116
  daemonStatusProvider;
115
117
  daemonMonitorProvider;
118
+ daemonHostProvider;
116
119
  agentDelegationRegistry;
117
120
  threadSystemMsgSender;
118
121
  handoffRuntime;
@@ -182,7 +185,6 @@ export class CommandHandler {
182
185
  return { ok: false, code: error.code ?? 'MENU_REQUEST_FAILED', error: error.message };
183
186
  }
184
187
  }
185
- contactRequestSubmitter;
186
188
  /**
187
189
  * Get the runner for a (channel, baseagent) pair.
188
190
  *
@@ -332,6 +334,9 @@ export class CommandHandler {
332
334
  setDaemonMonitorProvider(provider) {
333
335
  this.daemonMonitorProvider = provider;
334
336
  }
337
+ setDaemonHostProvider(provider) {
338
+ this.daemonHostProvider = provider;
339
+ }
335
340
  /** 返回管理当前通道的 EvolAgent,无则返回 null */
336
341
  getOwningAgent(channel) {
337
342
  if (!this.agentRegistry)
@@ -907,10 +912,6 @@ export class CommandHandler {
907
912
  setInteractionRouter(router) {
908
913
  this.interactionRouter = router;
909
914
  }
910
- /** Inject the daemon-owned contact request/card workflow for Agent self-service. */
911
- setContactRequestSubmitter(submitter) {
912
- this.contactRequestSubmitter = submitter;
913
- }
914
915
  setStatsCollector(collector) {
915
916
  this.statsCollector = collector;
916
917
  }
@@ -2000,22 +2001,13 @@ export class CommandHandler {
2000
2001
  return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation contains an invalid relation key' };
2001
2002
  }
2002
2003
  const resolvedArgv = argv.includes('--self') ? argv : [...argv, '--self', grant.selfAid];
2003
- const resolved = resolveContactCommand(resolvedArgv);
2004
+ const resolved = resolvePeerCommand(resolvedArgv);
2004
2005
  if (!resolved.ok)
2005
2006
  return { ok: false, code: resolved.code, error: resolved.reason };
2006
2007
  if (resolved.command.selfAid !== grant.selfAid && !hasTrustedFullAccessDelegation(grant)) {
2007
2008
  return { ok: false, code: 'SCOPE_MISMATCH', error: 'Only the current Agent contact book can be targeted' };
2008
2009
  }
2009
- const selfServiceAdd = resolved.command.kind === 'add';
2010
2010
  const primaryId = 'primaryId' in resolved.command ? resolved.command.primaryId : undefined;
2011
- if (selfServiceAdd && !hasTrustedFullAccessDelegation(grant)) {
2012
- if (grant.channelType !== 'aun' || grant.chatType !== 'private') {
2013
- return { ok: false, code: 'SCOPE_MISMATCH', error: 'contact add requires the current AUN private relation' };
2014
- }
2015
- if (primaryId !== conversationId) {
2016
- return { ok: false, code: 'SCOPE_MISMATCH', error: 'contact add may only target the current private peer' };
2017
- }
2018
- }
2019
2011
  const subject = buildAuthSubject({
2020
2012
  selfAid: grant.selfAid,
2021
2013
  actorId: grant.actorId,
@@ -2032,18 +2024,11 @@ export class CommandHandler {
2032
2024
  subject,
2033
2025
  intent: {
2034
2026
  operation: resolved.command.operationId,
2035
- scope: selfServiceAdd ? 'relation' : 'agent',
2027
+ scope: 'agent',
2036
2028
  source: 'agent-tool',
2037
2029
  args: {
2038
2030
  self: resolved.command.selfAid,
2039
2031
  ...(primaryId ? { primaryId } : {}),
2040
- ...(selfServiceAdd
2041
- ? {
2042
- targetId: primaryId,
2043
- peer: primaryId,
2044
- peerKey: `aun#${primaryId}`,
2045
- }
2046
- : {}),
2047
2032
  },
2048
2033
  },
2049
2034
  auditMetadata: {
@@ -2054,48 +2039,7 @@ export class CommandHandler {
2054
2039
  });
2055
2040
  if (!decision.allow)
2056
2041
  return { ok: false, code: decision.code, error: decision.reason };
2057
- if (selfServiceAdd) {
2058
- if (!this.contactRequestSubmitter) {
2059
- return { ok: false, code: 'CONTACT_REQUEST_UNAVAILABLE', error: 'Contact request workflow is not configured' };
2060
- }
2061
- try {
2062
- const submission = await this.contactRequestSubmitter({
2063
- selfAid: grant.selfAid,
2064
- applicantAid: primaryId,
2065
- sourceChannelKey: grant.channel,
2066
- });
2067
- if (submission.code === 'blocked') {
2068
- return {
2069
- ok: false,
2070
- code: 'CONTACT_BLOCKED',
2071
- error: `目标联系人 ${primaryId} 已被拉黑。请先解除拉黑:ec contact unblock ${primaryId} --self ${grant.selfAid}`,
2072
- };
2073
- }
2074
- return {
2075
- ok: true,
2076
- result: {
2077
- ok: true,
2078
- operation: 'add',
2079
- selfAid: grant.selfAid,
2080
- primaryId: primaryId,
2081
- status: submission.code,
2082
- changed: submission.code === 'submitted' || submission.code === 'resubmitted',
2083
- requestId: submission.requestId,
2084
- expiresAt: submission.expiresAt,
2085
- contactRevision: submission.contactRevision,
2086
- reviewCardSent: submission.reviewCardSent === true,
2087
- },
2088
- };
2089
- }
2090
- catch (error) {
2091
- return {
2092
- ok: false,
2093
- code: error?.code ?? 'CONTACT_REQUEST_FAILED',
2094
- error: error instanceof Error ? error.message : String(error),
2095
- };
2096
- }
2097
- }
2098
- const result = await executeResolvedContactCommand(resolved.command, grant.actorId);
2042
+ const result = await executeResolvedPeerCommand(resolved.command, grant.actorId);
2099
2043
  return result.ok
2100
2044
  ? { ok: true, result }
2101
2045
  : { ok: false, code: result.code, error: result.error, ...(result.data ? { data: result.data } : {}) };
@@ -2195,6 +2139,70 @@ export class CommandHandler {
2195
2139
  return { ok: false, code: 'ROLE_OPERATION_FAILED', error: error?.message ?? String(error) };
2196
2140
  }
2197
2141
  }
2142
+ /**
2143
+ * `ec directory remark ...`
2144
+ *
2145
+ * 备注写的是**目标 Agent** 的目录,不是调用方自己的目录——个人助理要维护
2146
+ * 别的 agent 的名录备注,沙箱权限写不进去,所以统一由 daemon 落盘。
2147
+ *
2148
+ * 权限边界:目标 Agent 必须是调用方自身,或者与调用方同属一个 Owner。
2149
+ * 这条限制防止一个 agent 借命令去改无关 Agent 的注入内容。
2150
+ */
2151
+ async handleDirectoryOperation(argv, sessionId, delegationToken, delegationCommandHash) {
2152
+ if (!this.agentDelegationRegistry) {
2153
+ return { ok: false, code: 'DELEGATION_REQUIRED', error: 'Task delegation is not configured' };
2154
+ }
2155
+ const delegation = this.agentDelegationRegistry.validate(delegationToken, sessionId, delegationCommandHash);
2156
+ if (!delegation.ok)
2157
+ return { ok: false, code: delegation.code, error: delegation.reason };
2158
+ const session = await this.sessionManager.getSessionById(sessionId);
2159
+ if (!session)
2160
+ return { ok: false, code: 'INVALID_SESSION', error: 'Invalid session' };
2161
+ // argv 形如 ['directory', '<sub>', ...]:remark 是写操作,其余是读查询。
2162
+ const isRemark = argv[1] === 'remark';
2163
+ const subArgv = argv.slice(2);
2164
+ let command;
2165
+ try {
2166
+ command = isRemark
2167
+ ? resolveDirectoryRemarkCommand(subArgv)
2168
+ : resolveDirectoryQueryCommand(subArgv);
2169
+ }
2170
+ catch (error) {
2171
+ const known = error instanceof DirectoryRemarkError || error instanceof DirectoryQueryError;
2172
+ return {
2173
+ ok: false,
2174
+ code: known ? error.code : 'INVALID_ARGUMENT',
2175
+ error: error instanceof Error ? error.message : String(error),
2176
+ };
2177
+ }
2178
+ const grantSelfAid = delegation.grant.selfAid.replace(/^@/, '');
2179
+ const sessionSelfAid = session.selfAID?.replace(/^@/, '');
2180
+ if (sessionSelfAid && sessionSelfAid !== grantSelfAid) {
2181
+ return { ok: false, code: 'INVALID_DELEGATION', error: 'Delegation self agent does not match the active session' };
2182
+ }
2183
+ if (!this.canMaintainDirectory(grantSelfAid, command.selfAid)) {
2184
+ return { ok: false, code: 'SCOPE_MISMATCH', error: 'Only your own Agent or an Agent under the same Owner can be accessed' };
2185
+ }
2186
+ if (isRemark) {
2187
+ const result = executeDirectoryRemarkCommand(command);
2188
+ return result.ok
2189
+ ? { ok: true, result }
2190
+ : { ok: false, code: result.code, error: result.error };
2191
+ }
2192
+ const result = await executeDirectoryQueryCommand(command);
2193
+ return result.ok
2194
+ ? { ok: true, result }
2195
+ : { ok: false, code: result.code, error: result.error };
2196
+ }
2197
+ canMaintainDirectory(callerAid, targetAid) {
2198
+ if (callerAid === targetAid)
2199
+ return true;
2200
+ const callerOwner = ownerResolver.owner(callerAid) ?? ownerResolver.knownOwner(callerAid);
2201
+ if (!callerOwner)
2202
+ return false;
2203
+ const targetOwner = ownerResolver.owner(targetAid) ?? ownerResolver.knownOwner(targetAid);
2204
+ return !!targetOwner && targetOwner === callerOwner;
2205
+ }
2198
2206
  async handleAidOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId) {
2199
2207
  if (!this.agentDelegationRegistry) {
2200
2208
  return { ok: false, code: 'DELEGATION_REQUIRED', error: 'Task delegation is not configured' };
@@ -2260,6 +2268,7 @@ export class CommandHandler {
2260
2268
  }, onExecutionStarted => this.executeAuthorizedAidOperation(parsed.command, session, subject, delegation.grant, onExecutionStarted));
2261
2269
  }
2262
2270
  async executeAuthorizedAidOperation(command, session, subject, grant, onExecutionStarted) {
2271
+ const grantSelfAid = grant.selfAid.replace(/^@/, '');
2263
2272
  let avatarBuffer;
2264
2273
  if (command.kind === 'avatar' && command.filePath) {
2265
2274
  const filePath = String(command.filePath || '').trim();
@@ -2269,9 +2278,12 @@ export class CommandHandler {
2269
2278
  const projectPath = path.resolve(session.projectPath);
2270
2279
  const managedTempPath = this.getManagedSessionTempDir(session);
2271
2280
  const resolvedPath = path.isAbsolute(filePath) ? path.resolve(filePath) : path.resolve(projectPath, filePath);
2272
- const allowedRoots = [projectPath, managedTempPath].filter((value) => !!value);
2281
+ // 对端发来的图片按原有机制落在本 Agent 的关系附件目录;直接引用原文件,
2282
+ // 不要求先复制到项目里。只放开本 Agent 自己的目录,其它 Agent 的不在其中。
2283
+ const relationAttachmentRoots = getExistingRelationAttachmentDirs(resolveRoot(), { selfAid: grantSelfAid });
2284
+ const allowedRoots = [projectPath, managedTempPath, ...relationAttachmentRoots].filter((value) => !!value);
2273
2285
  if (!filePath || !allowedRoots.some(root => isSameOrDescendant(resolvedPath, root))) {
2274
- return { ok: false, code: 'INVALID_AVATAR_PATH', error: 'Avatar file must be inside the current session project or managed TMPDIR' };
2286
+ return { ok: false, code: 'INVALID_AVATAR_PATH', error: "Avatar file must be inside the current session project, this Agent's incoming attachment folders, or managed TMPDIR" };
2275
2287
  }
2276
2288
  if (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(resolvedPath) || isLClassPath(resolvedPath))) {
2277
2289
  return { ok: false, code: 'PROTECTED_AVATAR_PATH', error: 'Avatar file cannot be read from a protected EvolCore path' };
@@ -2285,9 +2297,17 @@ export class CommandHandler {
2285
2297
  realManagedTempPath = managedTempPath ? fs.realpathSync(managedTempPath) : undefined;
2286
2298
  }
2287
2299
  catch { }
2288
- const realAllowedRoots = [realProjectPath, realManagedTempPath].filter((value) => !!value);
2300
+ const realRelationRoots = relationAttachmentRoots
2301
+ .map(root => { try {
2302
+ return fs.realpathSync(root);
2303
+ }
2304
+ catch {
2305
+ return undefined;
2306
+ } })
2307
+ .filter((value) => !!value);
2308
+ const realAllowedRoots = [realProjectPath, realManagedTempPath, ...realRelationRoots].filter((value) => !!value);
2289
2309
  if (!realAllowedRoots.some(root => isSameOrDescendant(realPath, root))) {
2290
- return { ok: false, code: 'INVALID_AVATAR_PATH', error: 'Avatar file resolves outside the current session project or managed TMPDIR' };
2310
+ return { ok: false, code: 'INVALID_AVATAR_PATH', error: "Avatar file resolves outside the current session project, this Agent's incoming attachment folders, or managed TMPDIR" };
2291
2311
  }
2292
2312
  if (!hasTrustedFullAccessDelegation(grant) && (isHClassPath(realPath) || isLClassPath(realPath))) {
2293
2313
  return { ok: false, code: 'PROTECTED_AVATAR_PATH', error: 'Avatar file cannot be read from a protected EvolCore path' };
@@ -1,7 +1,7 @@
1
1
  import { roleMenuQuery, roleMenuGroupCount, roleMenuUpdate, } from './role-menu.js';
2
- import { getContactSnapshot, resolveContactView } from '../../config/contact-book.js';
2
+ import { getPeerSnapshot, resolvePeerView } from '../../config/peer-book.js';
3
3
  import { mutateAccessPolicy, readAccessPolicySnapshot, } from '../../config/access-policy.js';
4
- import { expirePendingContactRequests, addContact, mutateContactWithOperation, reviewContactRequest, } from '../../config/contact-request-service.js';
4
+ import { expirePendingPeerRequests, addPeer, mutatePeerWithOperation, reviewPeerRequest, } from '../../config/peer-request-service.js';
5
5
  import { formatPeerKey, parsePeerKey } from '../relation/peer-identity.js';
6
6
  import { isValidAid } from '../../aun/aid/validation.js';
7
7
  /**
@@ -73,8 +73,8 @@ async function handleOptions(self, args, context) {
73
73
  if (option) {
74
74
  return fail('NOT_SUPPORTED', `Unknown connect option: ${option}`);
75
75
  }
76
- await expirePendingContactRequests(self);
77
- const snapshot = getContactSnapshot(self);
76
+ await expirePendingPeerRequests(self);
77
+ const snapshot = getPeerSnapshot(self);
78
78
  const contactCount = snapshot.contacts.size;
79
79
  const blockedCount = snapshot.blockedIndex.size;
80
80
  const pendingCount = [...snapshot.contacts.values()].filter(entry => entry.status === 'pending').length;
@@ -163,33 +163,33 @@ function queryAccess(self) {
163
163
  });
164
164
  }
165
165
  async function queryContacts(args, self) {
166
- await expirePendingContactRequests(self);
167
- const snapshot = getContactSnapshot(self);
166
+ await expirePendingPeerRequests(self);
167
+ const snapshot = getPeerSnapshot(self);
168
168
  const page = paginate([...snapshot.contacts.keys()].sort(), args, self, primaryId => primaryId);
169
169
  const items = page.items.map(primaryId => contactItem(self, primaryId));
170
170
  return ok({
171
171
  self,
172
172
  view: 'contacts',
173
173
  items,
174
- contactRevision: snapshot.contactRevision,
174
+ peerRevision: snapshot.peerRevision,
175
175
  pendingCount: [...snapshot.contacts.values()].filter(entry => entry.status === 'pending').length,
176
176
  nextCursor: page.nextCursor,
177
177
  dataSource: { kind: 'contact-book', authoritative: true, complete: true },
178
178
  });
179
179
  }
180
180
  async function queryContact(req, self) {
181
- await expirePendingContactRequests(self);
181
+ await expirePendingPeerRequests(self);
182
182
  const primaryId = String(req.args?.primaryId ?? '').trim();
183
183
  if (!primaryId)
184
184
  return fail('INVALID_ARGUMENT', 'primaryId is required');
185
- const snapshot = getContactSnapshot(self);
185
+ const snapshot = getPeerSnapshot(self);
186
186
  if (!snapshot.contacts.has(primaryId))
187
187
  return fail('NOT_FOUND', `Contact was not found: ${primaryId}`);
188
- return ok({ self, view: 'contact', ...contactItem(self, primaryId), contactRevision: snapshot.contactRevision });
188
+ return ok({ self, view: 'contact', ...contactItem(self, primaryId), peerRevision: snapshot.peerRevision });
189
189
  }
190
190
  function contactItem(self, primaryId) {
191
- const view = resolveContactView(self, primaryId);
192
- const pendingRequest = getContactSnapshot(self).contacts.get(primaryId)?.pendingRequest;
191
+ const view = resolvePeerView(self, primaryId);
192
+ const pendingRequest = getPeerSnapshot(self).contacts.get(primaryId)?.pendingRequest;
193
193
  return {
194
194
  primaryId,
195
195
  displayName: view.displayName ?? null,
@@ -265,11 +265,11 @@ async function handleAction(req, self, context) {
265
265
  return fail('NOT_SUPPORTED', `Unknown action: ${String(action)}`);
266
266
  }
267
267
  function isAccessUpdateResource(resource) {
268
- return resource === 'policyMode'
269
- || resource === 'allowOwnerDirectoryContacts'
270
- || resource === 'allowOwnerAgentDirectory'
268
+ return resource === 'allowInternalContacts'
271
269
  || resource === 'allowExternalContacts'
270
+ || resource === 'allowStrangerContacts'
272
271
  || resource === 'allowedAids'
272
+ || resource === 'deniedAids'
273
273
  || resource === 'requestLimit';
274
274
  }
275
275
  function updateAccessResource(req, context, resource) {
@@ -281,21 +281,16 @@ function updateAccessResource(req, context, resource) {
281
281
  const self = context.self;
282
282
  const expectedAccessRevision = requireAccessRevision(args);
283
283
  const decoded = decodeAccessUpdateValue(req.value);
284
- if (resource === 'policyMode') {
285
- if (typeof decoded !== 'string' || !['open', 'contacts', 'owners'].includes(decoded)) {
286
- return fail('INVALID_ARGUMENT', 'policyMode must be open, contacts, or owners');
287
- }
288
- }
289
- else if (resource === 'allowOwnerDirectoryContacts' || resource === 'allowOwnerAgentDirectory' || resource === 'allowExternalContacts') {
284
+ if (resource === 'allowInternalContacts' || resource === 'allowExternalContacts' || resource === 'allowStrangerContacts') {
290
285
  if (typeof decoded !== 'boolean') {
291
286
  return fail('INVALID_ARGUMENT', `${resource} must be a JSON boolean`);
292
287
  }
293
288
  }
294
- else if (resource === 'allowedAids') {
289
+ else if (resource === 'allowedAids' || resource === 'deniedAids') {
295
290
  if (!Array.isArray(decoded)
296
291
  || decoded.some(aid => typeof aid !== 'string' || !isValidAid(aid))
297
292
  || new Set(decoded).size !== decoded.length) {
298
- return fail('INVALID_ARGUMENT', 'allowedAids must be a JSON array of unique valid AIDs');
293
+ return fail('INVALID_ARGUMENT', `${resource} must be a JSON array of unique valid AIDs`);
299
294
  }
300
295
  }
301
296
  else {
@@ -338,7 +333,7 @@ async function actionReviewRequest(req, self, context, decision) {
338
333
  requireAdminContext(context);
339
334
  const expectedContactRevision = requireContactRevision(args);
340
335
  const actorId = String(context.actorAid || '').trim();
341
- const reviewed = await reviewContactRequest({
336
+ const reviewed = await reviewPeerRequest({
342
337
  selfAid: self,
343
338
  primaryId,
344
339
  requestId,
@@ -370,14 +365,14 @@ async function actionReviewRequest(req, self, context, decision) {
370
365
  primaryId,
371
366
  requestId,
372
367
  result: reviewed.code,
373
- contactRevision: reviewed.contactRevision,
368
+ peerRevision: reviewed.peerRevision,
374
369
  });
375
370
  }
376
371
  const code = reviewed.code === 'forbidden' ? 'PERMISSION_DENIED'
377
372
  : reviewed.code === 'revision-conflict' ? 'CONFLICT'
378
373
  : reviewed.code === 'request-expired' ? 'EXPIRED'
379
374
  : 'NOT_FOUND';
380
- return fail(code, reviewed.code.replace(/-/g, ' '), { contactRevision: reviewed.contactRevision });
375
+ return fail(code, reviewed.code.replace(/-/g, ' '), { peerRevision: reviewed.peerRevision });
381
376
  }
382
377
  async function actionAdd(req, self, context) {
383
378
  requireAdminContext(context);
@@ -390,9 +385,9 @@ async function actionAdd(req, self, context) {
390
385
  if (hasDisplayName && args.displayName !== null && typeof args.displayName !== 'string') {
391
386
  return fail('INVALID_ARGUMENT', 'displayName must be a string or null');
392
387
  }
393
- const current = getContactSnapshot(self).contacts.get(primaryId);
388
+ const current = getPeerSnapshot(self).contacts.get(primaryId);
394
389
  const displayName = hasDisplayName ? args.displayName : current?.displayName ?? null;
395
- const result = await addContact({
390
+ const result = await addPeer({
396
391
  selfAid: self,
397
392
  actorId: context.actorAid ?? 'connect-menu',
398
393
  expectedContactRevision,
@@ -406,7 +401,7 @@ async function actionAdd(req, self, context) {
406
401
  primaryId,
407
402
  displayName: storedDisplayName,
408
403
  changed: result.changed,
409
- contactRevision: result.contactRevision,
404
+ peerRevision: result.peerRevision,
410
405
  });
411
406
  }
412
407
  async function actionSetStatus(req, self, context, blocked) {
@@ -416,10 +411,10 @@ async function actionSetStatus(req, self, context, blocked) {
416
411
  if (!primaryId)
417
412
  return fail('INVALID_ARGUMENT', 'primaryId is required');
418
413
  const expectedContactRevision = requireContactRevision(args);
419
- if (!getContactSnapshot(self).contacts.has(primaryId)) {
414
+ if (!getPeerSnapshot(self).contacts.has(primaryId)) {
420
415
  return fail('NOT_FOUND', `Contact was not found: ${primaryId}`);
421
416
  }
422
- const result = await mutateContactWithOperation({
417
+ const result = await mutatePeerWithOperation({
423
418
  selfAid: self,
424
419
  actorId: context.actorAid ?? 'connect-menu',
425
420
  operation: blocked ? 'block' : 'unblock',
@@ -432,7 +427,7 @@ async function actionSetStatus(req, self, context, blocked) {
432
427
  action: blocked ? 'block' : 'unblock',
433
428
  primaryId,
434
429
  changed: result.changed,
435
- contactRevision: result.contactRevision,
430
+ peerRevision: result.peerRevision,
436
431
  });
437
432
  }
438
433
  // ── Helpers ──
@@ -473,8 +468,6 @@ function errorCode(error) {
473
468
  return 'CONFLICT';
474
469
  if (code === 'access_policy_temporarily_unavailable')
475
470
  return 'TEMPORARILY_UNAVAILABLE';
476
- if (code === 'restricted_mode_without_owner')
477
- return 'NOT_ALLOWED';
478
471
  if (code === 'invalid_access_policy')
479
472
  return 'INTERNAL_ERROR';
480
473
  return typeof code === 'string' ? code : 'INTERNAL_ERROR';
@@ -548,21 +541,21 @@ function normalizeAssignmentUpdate(data) {
548
541
  };
549
542
  }
550
543
  function accessPolicyWithUpdate(current, resource, decoded) {
551
- if (resource === 'policyMode') {
552
- return { ...current, policyMode: decoded };
553
- }
554
- if (resource === 'allowOwnerDirectoryContacts') {
555
- return { ...current, allowOwnerDirectoryContacts: decoded };
556
- }
557
- if (resource === 'allowOwnerAgentDirectory') {
558
- return { ...current, allowOwnerAgentDirectory: decoded };
544
+ if (resource === 'allowInternalContacts') {
545
+ return { ...current, allowInternalContacts: decoded };
559
546
  }
560
547
  if (resource === 'allowExternalContacts') {
561
548
  return { ...current, allowExternalContacts: decoded };
562
549
  }
550
+ if (resource === 'allowStrangerContacts') {
551
+ return { ...current, allowStrangerContacts: decoded };
552
+ }
563
553
  if (resource === 'allowedAids') {
564
554
  return { ...current, allowedAids: [...decoded] };
565
555
  }
556
+ if (resource === 'deniedAids') {
557
+ return { ...current, deniedAids: [...decoded] };
558
+ }
566
559
  const requestLimit = decoded;
567
560
  return {
568
561
  ...current,
@@ -3,6 +3,33 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { resolvePaths } from '../../paths.js';
5
5
  import { isValidAid } from '../../aun/aid/validation.js';
6
+ import { LOG_LEVELS as LOGGER_LEVELS } from '../../utils/logger.js';
7
+ export function parseManagedDaemonLogArgv(argv) {
8
+ if (argv[0] !== 'logs')
9
+ throw { code: 'INVALID_ARGUMENT', message: 'Expected ec logs command' };
10
+ const query = { view: 'logs', source: 'daemon', limit: 50 };
11
+ for (let index = 1; index < argv.length; index += 1) {
12
+ const flag = argv[index];
13
+ if (flag === '--raw') {
14
+ throw { code: 'NOT_ALLOWED', message: '--raw is unavailable in managed tasks; use it from the host terminal' };
15
+ }
16
+ if (flag === '--no-color')
17
+ continue;
18
+ if (flag !== '--level' && flag !== '--module') {
19
+ throw { code: 'INVALID_ARGUMENT', message: `Unsupported managed logs option: ${flag}` };
20
+ }
21
+ const value = argv[index + 1];
22
+ if (!value || value.startsWith('--')) {
23
+ throw { code: 'INVALID_ARGUMENT', message: `${flag} requires a value` };
24
+ }
25
+ if (flag === '--level')
26
+ query.level = value;
27
+ else
28
+ query.module = value;
29
+ index += 1;
30
+ }
31
+ return query;
32
+ }
6
33
  function diagnosticPaths(overrides) {
7
34
  if (overrides)
8
35
  return overrides;
@@ -33,7 +60,7 @@ const LOG_SOURCES = [
33
60
  { id: 'delegation-audit', label: 'Delegation audit', pattern: /^delegation-audit(?:-.+)?\.log$/ },
34
61
  { id: 'role-mutations', label: 'Role mutations', pattern: /^role-mutations(?:-.+)?\.log$/ },
35
62
  ];
36
- const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
63
+ const LOG_LEVELS = LOGGER_LEVELS.map(level => level.toLowerCase());
37
64
  const LEVEL_RANK = new Map(LOG_LEVELS.map((level, index) => [level, index]));
38
65
  const DEFAULT_LOG_LIMIT = 200;
39
66
  const MAX_LOG_LIMIT = 1_000;
@@ -128,6 +155,8 @@ function parseLine(rawLine, file) {
128
155
  : value?.status === 'completed' ? 'info'
129
156
  : value?.status === 'started' ? 'debug' : undefined;
130
157
  const level = (explicitLevel || (textLevel === 'warning' ? 'warn' : textLevel) || inferred || null);
158
+ const textModule = raw.match(/^\[[^\]]+\]\s+\[(?:TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\]\s+((?:\[[^\]]+\]\s*)+)/i)?.[1]
159
+ ?.replace(/[\[\]]/g, '').trim();
131
160
  const scalar = (item) => typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean' ? String(item) : null;
132
161
  const fields = [];
133
162
  const excluded = new Set(['ts', 'timestamp', 'level', 'message', 'msg', 'text', 'event', 'type', 'status', 'error']);
@@ -144,7 +173,8 @@ function parseLine(rawLine, file) {
144
173
  : typeof value?.type === 'string' ? value.type
145
174
  : typeof value?.status === 'string' ? value.status : null;
146
175
  const module = typeof value?.module === 'string' ? value.module
147
- : event ? event.split(/[.:]/)[0] : null;
176
+ : event ? event.split(/[.:]/)[0]
177
+ : textModule || null;
148
178
  const actor = typeof value?.actor === 'string' ? value.actor
149
179
  : typeof value?.aid === 'string' ? value.aid
150
180
  : typeof value?.selfAid === 'string' ? value.selfAid : null;
@@ -239,7 +269,7 @@ export function listDiagnosticLogOptions(pathOverrides) {
239
269
  }
240
270
  export function queryDiagnosticLogs(args, requester, pathOverrides) {
241
271
  const startedAt = Date.now();
242
- const allowed = new Set(['view', 'source', 'since', 'until', 'level', 'limit', 'cursor']);
272
+ const allowed = new Set(['view', 'source', 'since', 'until', 'level', 'module', 'limit', 'cursor']);
243
273
  const unknown = Object.keys(args).find(key => !allowed.has(key));
244
274
  if (unknown)
245
275
  throw { code: 'INVALID_ARGUMENT', message: `Unsupported logs argument: ${unknown}` };
@@ -266,6 +296,10 @@ export function queryDiagnosticLogs(args, requester, pathOverrides) {
266
296
  if (level !== undefined && !LEVEL_RANK.has(level)) {
267
297
  throw { code: 'INVALID_ARGUMENT', message: `Unsupported log level: ${level}` };
268
298
  }
299
+ if (args.module !== undefined && (typeof args.module !== 'string' || !args.module.trim() || args.module.length > 128)) {
300
+ throw { code: 'INVALID_ARGUMENT', message: 'module must be a non-empty string of at most 128 characters' };
301
+ }
302
+ const module = typeof args.module === 'string' ? args.module.trim().toLowerCase() : undefined;
269
303
  const now = Date.now();
270
304
  const since = timeBoundary(args.since, now);
271
305
  const until = timeBoundary(args.until, now);
@@ -274,7 +308,7 @@ export function queryDiagnosticLogs(args, requester, pathOverrides) {
274
308
  }
275
309
  const matching = files.filter(file => source.pattern.test(file.name)).sort((a, b) => a.mtimeMs - b.mtimeMs);
276
310
  const fingerprint = resourceFingerprint({
277
- source: sourceId, level, since: args.since ?? null, until: args.until ?? null,
311
+ source: sourceId, level, module, since: args.since ?? null, until: args.until ?? null,
278
312
  files: matching.map(file => [file.name, file.size, file.mtimeMs]),
279
313
  });
280
314
  const offset = decodeCursor(args.cursor, { kind: 'logs', requester, fingerprint });
@@ -297,6 +331,8 @@ export function queryDiagnosticLogs(args, requester, pathOverrides) {
297
331
  if (rowRank === undefined || rowRank < LEVEL_RANK.get(level))
298
332
  return false;
299
333
  }
334
+ if (module && !row.module?.toLowerCase().includes(module))
335
+ return false;
300
336
  return true;
301
337
  });
302
338
  const newestFirst = rows.reverse();
@@ -319,7 +355,7 @@ export function queryDiagnosticLogs(args, requester, pathOverrides) {
319
355
  }
320
356
  return {
321
357
  source: sourceId,
322
- filters: { since: since ?? null, until: until ?? null, level: level ?? null },
358
+ filters: { since: since ?? null, until: until ?? null, level: level ?? null, module: module ?? null },
323
359
  limit,
324
360
  lines: page.reverse(),
325
361
  nextCursor: nextOffset < newestFirst.length
@@ -0,0 +1,10 @@
1
+ export class DataRootError extends Error {
2
+ code;
3
+ data;
4
+ constructor(code, message, data) {
5
+ super(message);
6
+ this.name = 'DataRootError';
7
+ this.code = code;
8
+ this.data = data;
9
+ }
10
+ }