evolcore 0.0.43-test.2 → 0.0.43-test.4

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 (173) hide show
  1. package/CHANGELOG.md +44 -1
  2. package/bin/ecmsg.js +229 -0
  3. package/bin/install-codex-managed-hooks.mjs +130 -8
  4. package/dist/ability/application-service.js +37 -0
  5. package/dist/ability/resources.js +28 -0
  6. package/dist/ability/runtime.js +6 -1
  7. package/dist/agents/claude-runner.js +7 -5
  8. package/dist/agents/codex/app-server-client.js +0 -12
  9. package/dist/agents/codex-runner.js +0 -37
  10. package/dist/agents/ecagent-runner.js +138 -36
  11. package/dist/aun/aid/agentmd.js +52 -13
  12. package/dist/aun/menu/client.js +8 -7
  13. package/dist/aun/menu/index.js +1 -1
  14. package/dist/aun/menu/transport.js +8 -5
  15. package/dist/aun/msg/p2p.js +4 -2
  16. package/dist/aun/service-proxy.js +3 -0
  17. package/dist/channels/aun.js +105 -53
  18. package/dist/channels/daemon.js +14 -2
  19. package/dist/cli/agent-command.js +5 -0
  20. package/dist/cli/agent-create.js +31 -11
  21. package/dist/cli/agent.js +9 -3
  22. package/dist/cli/aun-commands.js +19 -21
  23. package/dist/cli/daemon-commands.js +30 -18
  24. package/dist/cli/directory.js +98 -56
  25. package/dist/cli/getmeta-command.js +2 -1
  26. package/dist/cli/index.js +1 -1
  27. package/dist/cli/init.js +13 -5
  28. package/dist/cli/peer.js +2 -1
  29. package/dist/cli/task-context.js +3 -1
  30. package/dist/cli/trigger-command.js +20 -14
  31. package/dist/config/access-policy.js +0 -1
  32. package/dist/config/boot-log.js +12 -2
  33. package/dist/config/builtin-role-templates.js +2 -2
  34. package/dist/config/builtin-roles.js +2 -1
  35. package/dist/config/config-field-policy.js +7 -0
  36. package/dist/config/config-manager.js +30 -10
  37. package/dist/config/peer-role-resolver.js +23 -1
  38. package/dist/config/role-schema.js +25 -1
  39. package/dist/config/role-service.js +9 -4
  40. package/dist/config/role-store.js +30 -8
  41. package/dist/config/schema-migration.js +121 -0
  42. package/dist/core/agent-application-service.js +11 -0
  43. package/dist/core/agent-ipc-registration.js +2 -0
  44. package/dist/core/agent-runtime.js +41 -9
  45. package/dist/core/auth/auth-gateway.js +14 -4
  46. package/dist/core/auth/operation-authorizer.js +19 -1
  47. package/dist/core/auth/operation-catalog.js +12 -2
  48. package/dist/core/baseagent-loader.js +11 -3
  49. package/dist/core/bootstrap-service.js +8 -0
  50. package/dist/core/channel-loader.js +61 -23
  51. package/dist/core/channel-runtime.js +5 -0
  52. package/dist/core/command/agent-control.js +5 -2
  53. package/dist/core/command/agentmd-menu-request.js +50 -0
  54. package/dist/core/command/agentmd-menu.js +156 -0
  55. package/dist/core/command/chatmode-config.js +46 -0
  56. package/dist/core/command/command-handler.js +44 -17
  57. package/dist/core/command/daemon-diagnostics.js +2 -1
  58. package/dist/core/command/menu-catalog.js +14 -1
  59. package/dist/core/command/menu-handler.js +74 -24
  60. package/dist/core/command/menu-protocol.js +8 -0
  61. package/dist/core/command/role-menu.js +23 -9
  62. package/dist/core/command/slash-handler.js +52 -47
  63. package/dist/core/daemon-lifecycle.js +43 -17
  64. package/dist/core/event-catalog.js +19 -0
  65. package/dist/core/evolagent-registry.js +3 -0
  66. package/dist/core/evolagent.js +5 -4
  67. package/dist/core/ipc-registration.js +6 -0
  68. package/dist/core/lifecycle-notice.js +185 -0
  69. package/dist/core/message/aun-ipc-sender.js +30 -24
  70. package/dist/core/message/contact-admission.js +1 -19
  71. package/dist/core/message/im-renderer.js +81 -40
  72. package/dist/core/message/message-admission.js +21 -62
  73. package/dist/core/message/message-bridge.js +18 -5
  74. package/dist/core/message/message-utils.js +9 -0
  75. package/dist/core/message/peer-mode.js +16 -8
  76. package/dist/core/message/response-engine.js +67 -47
  77. package/dist/core/model/model-capabilities.js +37 -0
  78. package/dist/core/model/model-catalog.js +6 -2
  79. package/dist/core/ownership/owner-resolver.js +74 -36
  80. package/dist/core/permission/ec-command-parser.js +62 -13
  81. package/dist/core/plugin-lifecycle.js +6 -2
  82. package/dist/core/relation/pa-team.js +132 -0
  83. package/dist/core/role/runtime-policy.js +4 -3
  84. package/dist/core/thread/thread-service.js +6 -4
  85. package/dist/directory/owner-directory-admission.js +0 -3
  86. package/dist/directory/owner-directory-cache.js +201 -17
  87. package/dist/directory/owner-directory-markdown.js +44 -21
  88. package/dist/directory/owner-directory-policy.js +1 -1
  89. package/dist/directory/owner-directory-query-operation.js +218 -98
  90. package/dist/directory/owner-directory-request-operation.js +76 -0
  91. package/dist/directory/owner-directory-scope.js +35 -4
  92. package/dist/directory/owner-directory-search.js +76 -23
  93. package/dist/directory/owner-directory-store.js +5 -38
  94. package/dist/directory/owner-directory-text.js +60 -0
  95. package/dist/eck/kit-renderer.js +6 -3
  96. package/dist/eck/message-renderer.js +2 -5
  97. package/dist/ecweb/message-context-service.js +4 -0
  98. package/dist/ecweb/runtime/lifecycle.js +29 -5
  99. package/dist/ecweb/runtime/supervisor.js +83 -27
  100. package/dist/index.js +209 -38
  101. package/dist/paths.js +4 -2
  102. package/dist/product.js +1 -0
  103. package/dist/proxy/service-supervisor.js +377 -141
  104. package/dist/response-system/engines/v1/index.js +2 -4
  105. package/dist/response-system/modes/single-session/index.js +1 -1
  106. package/dist/trigger/audit.js +3 -2
  107. package/dist/trigger/authorization.js +2 -3
  108. package/dist/trigger/history.js +4 -3
  109. package/dist/trigger/ipc-service.js +24 -19
  110. package/dist/trigger/manager.js +3 -5
  111. package/dist/trigger/parser.js +4 -21
  112. package/dist/trigger/patch.js +3 -15
  113. package/dist/trigger/scheduler.js +53 -13
  114. package/dist/trigger/validation.js +0 -13
  115. package/dist/utils/error-utils.js +15 -5
  116. package/dist/utils/macos-autostart.js +31 -0
  117. package/dist/utils/model-prices.jsonl +15 -8
  118. package/dist/utils/process-introspect.js +21 -1
  119. package/dist/utils/startup-trace.js +7 -1
  120. package/dist/utils/windows-autostart.js +1 -0
  121. package/ecagent/README.md +18 -0
  122. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  123. package/ecagent/dist/harness/agent-harness.js +24 -8
  124. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  125. package/ecagent/dist/harness/compaction/compaction.js +7 -4
  126. package/ecagent/dist/harness/types.d.ts +1 -0
  127. package/kits/docs/channels/aun.md +1 -1
  128. package/kits/docs/context-assembly.md +1 -1
  129. package/kits/docs/evolcore/INDEX.md +5 -2
  130. package/kits/docs/evolcore/directory.md +125 -35
  131. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  132. package/kits/docs/evolcore/file-navigation.md +279 -0
  133. package/kits/docs/evolcore/menu-protocol.md +1 -0
  134. package/kits/docs/evolcore/model.md +5 -3
  135. package/kits/docs/evolcore/msg.md +1 -0
  136. package/kits/docs/evolcore/peer.md +2 -1
  137. package/kits/docs/evolcore/response.md +4 -2
  138. package/kits/docs/evolcore/task.md +2 -0
  139. package/kits/docs/evolcore/thread-chain.md +1 -1
  140. package/kits/docs/evolcore/tool-authorization.md +4 -1
  141. package/kits/docs/evolcore/trigger.md +10 -7
  142. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  143. package/kits/eck_manifest.json +6 -23
  144. package/kits/eck_manifest.memory.json +26 -1
  145. package/kits/rules/01-overview.md +42 -44
  146. package/kits/rules/02-navigation.md +44 -53
  147. package/kits/rules/03-identity.md +21 -25
  148. package/kits/rules/04-relation.md +23 -33
  149. package/kits/rules/05-venue.md +24 -25
  150. package/kits/schemas/_meta.json +10 -10
  151. package/kits/schemas/agent-config.schema.19.json +10 -6
  152. package/kits/schemas/relation-config.schema.12.json +2 -2
  153. package/kits/schemas/role-config.schema.2.json +5 -5
  154. package/kits/schemas/role-registry.schema.1.json +3 -2
  155. package/kits/skills/ec-service-proxy/SKILL.md +10 -0
  156. package/kits/skills/ec-trigger/SKILL.md +1 -1
  157. package/kits/templates/soul/00-GUIDE.md +20 -42
  158. package/kits/templates/system-fragments/channel.md +2 -2
  159. package/kits/templates/system-fragments/commands.md +1 -1
  160. package/kits/templates/system-fragments/directory-contacts.md +1 -1
  161. package/kits/templates/system-fragments/identity.md +0 -1
  162. package/kits/templates/system-fragments/personal-assistant.md +2 -17
  163. package/kits/templates/system-fragments/reply.md +7 -0
  164. package/kits/templates/system-fragments/session.md +6 -2
  165. package/package.json +18 -13
  166. package/dist/eck/paactive-context.js +0 -45
  167. package/dist/response-system/engines/v1/paactive-flow.js +0 -18
  168. package/kits/eck_manifest.paactive.json +0 -528
  169. package/kits/eck_message_manifest.paactive.json +0 -233
  170. package/kits/templates/message-fragments/paactive/item.md +0 -3
  171. package/kits/templates/system-fragments/paactive/channel.md +0 -25
  172. package/kits/templates/system-fragments/paactive/reply.md +0 -25
  173. package/kits/templates/system-fragments/paactive/session.md +0 -32
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import path from 'node:path';
6
6
  import { clearRuntimeBaseagentModelDefaults } from '../../agents/baseagent.js';
7
+ import { buildModelRequestHeaders } from '../../agents/request-identity.js';
7
8
  import { activeBaseagent } from './config-scope.js';
8
9
  import { resolveEffective } from '../../config/config-manager.js';
9
10
  import { readRuntimeEnvironmentVariable } from '../../config/runtime-env.js';
@@ -137,7 +138,8 @@ export function resolveCatalogContext(self, ba) {
137
138
  if (envBaseUrl) {
138
139
  const envApiKey = readRuntimeEnvironmentVariable('ANTHROPIC_AUTH_TOKEN', self).value
139
140
  ?? readRuntimeEnvironmentVariable('ANTHROPIC_API_KEY', self).value;
140
- return { ...context, baseUrl: envBaseUrl, apiKey: envApiKey, style: 'claude' };
141
+ return { ...context, baseUrl: envBaseUrl, apiKey: envApiKey, style: 'claude',
142
+ headers: buildModelRequestHeaders({ baseagent: 'claude', baseUrl: envBaseUrl, agentAid: self }) };
141
143
  }
142
144
  }
143
145
  // 模型选择只在 Agent 级且必须指向 provider;没有 provider 就没有目录可查。
@@ -152,7 +154,9 @@ export function resolveCatalogContext(self, ba) {
152
154
  style: provider.style,
153
155
  baseUrl: provider.baseUrl,
154
156
  apiKey: provider.apiKey,
155
- headers: provider.headers,
157
+ headers: baseagent === 'claude' || baseagent === 'codex' || baseagent === 'ecagent'
158
+ ? buildModelRequestHeaders({ baseagent, baseUrl: provider.baseUrl, agentAid: self, configuredHeaders: provider.headers })
159
+ : provider.headers,
156
160
  queryParams: provider.queryParams,
157
161
  modelOverrides: provider.modelOverrides,
158
162
  });
@@ -425,7 +425,7 @@ export class OwnerResolver {
425
425
  return this.snapshot(subjectAid);
426
426
  }
427
427
  const ownerAid = consensus.status === 'consensus' && consensus.sub_aid === subjectAid
428
- && typeof consensus.owner_aid === 'string' && isValidAid(consensus.owner_aid)
428
+ && typeof consensus.owner_aid === 'string' && isValidAid(consensus.owner_aid) && consensus.owner_aid !== subjectAid
429
429
  ? consensus.owner_aid : undefined;
430
430
  if (consensus.sub_aid !== subjectAid || (consensus.status === 'consensus' && !ownerAid)) {
431
431
  throw new Error('Ownership consensus contains a mismatched subject or invalid owner');
@@ -913,13 +913,13 @@ export class OwnerResolver {
913
913
  this.configuredOwnerFileRevision.clear();
914
914
  }
915
915
  async submitBinding(subjectAid, ownerAid, subject, assertCurrent) {
916
- const client = subject.client;
917
916
  const generation = subject.generation;
917
+ let replaced = false;
918
918
  subject.view = { ...subject.view, requestedOwnerAid: ownerAid, requestStatus: 'requesting', task: undefined };
919
919
  try {
920
920
  const local = await this.tryLocalBind(subjectAid, ownerAid, assertCurrent);
921
921
  if (local) {
922
- if (client && (subject.client !== client || subject.generation !== generation)) {
922
+ if (subject.client && subject.generation !== generation) {
923
923
  throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during local binding');
924
924
  }
925
925
  subject.view.task = local.task;
@@ -928,40 +928,63 @@ export class OwnerResolver {
928
928
  subject.view.reason = undefined;
929
929
  return this.snapshot(subjectAid);
930
930
  }
931
- if (!client || !subject.view.connected)
932
- throw new OwnershipError('SUBJECT_UNAVAILABLE', 'Subject AID SDK client is not ready');
933
- const current = await this.refresh(subjectAid, { force: true, source: 'ownership.bind' });
934
- if (current.consensusStatus === 'consensus') {
935
- if (current.ownerAid === ownerAid)
936
- return current;
937
- throw new OwnershipError('OWNER_ALREADY_BOUND', 'Subject already has a protocol owner; transfer is not supported');
938
- }
939
- if (!['unbound', 'released', 'single_sided'].includes(current.consensusStatus)) {
940
- throw new OwnershipError('CONSENSUS_REQUIRED', 'Binding requires a fresh readable ownership baseline');
941
- }
942
- assertCurrent();
943
- const task = this.task(await client.bindOwneraid(ownerAid));
944
- if (subject.client !== client || subject.generation !== generation) {
945
- throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during binding; the request may have been submitted');
946
- }
947
- if (!task || task.sub_aid !== subjectAid || task.owner_aid !== ownerAid || task.operation !== 'bind') {
948
- throw new OwnershipError('TASK_MISMATCH', 'SDK returned a binding result for a different subject or owner');
949
- }
950
- subject.view.task = task;
951
- subject.view.requestStatus = task.status === 'error' ? 'error' : 'submitted';
952
- subject.view.reason = task.reason;
953
- if (task.status === 'rejected')
954
- this.rememberRejectedOwnerBinding(task);
955
- if (task.status === 'error' || task.status === 'rejected' || task.status === 'stopped') {
956
- throw Object.assign(new OwnershipError(task.code ?? 'BIND_FAILED', task.reason ?? `Binding ended with ${task.status}`), {
957
- retryable: task.retryable,
958
- });
959
- }
960
- this.invalidate(subject, 'Binding submitted; waiting for explicit owner approval and fresh consensus', true);
961
- return this.snapshot(subjectAid);
931
+ // 尚无已加载渠道 client 的主体(典型是初始化停在 ownerpending、审批前不会
932
+ // hotLoad 的 Agent)也必须能在共识成立前换绑。withSubjectClient 在没有
933
+ // 已连接 client 时会退化为独立 slot 的临时短连接,与 submitTransfer /
934
+ // decide / status 的取用方式一致。
935
+ return await this.withSubjectClient(subjectAid, async (client, attached) => {
936
+ if (attached && (subject.client !== client || subject.generation !== generation)) {
937
+ throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed before binding');
938
+ }
939
+ assertCurrent();
940
+ const current = await client.checkOwnershipConsensus(subjectAid, true);
941
+ if (current.sub_aid !== subjectAid) {
942
+ throw new OwnershipError('TASK_MISMATCH', 'Ownership consensus returned a different subject');
943
+ }
944
+ if (current.status === 'unavailable' || current.status === 'invalid' || current.status === 'not_applicable') {
945
+ throw new OwnershipError(current.code ?? 'CONSENSUS_REQUIRED', current.reason ?? 'Binding requires a fresh readable ownership baseline');
946
+ }
947
+ if (current.status === 'consensus') {
948
+ this.applyConsensus(subjectAid, subject, current);
949
+ if (current.owner_aid === ownerAid)
950
+ return this.snapshot(subjectAid);
951
+ throw new OwnershipError('OWNER_ALREADY_BOUND', 'Subject already has a protocol owner; transfer is not supported');
952
+ }
953
+ if (!['unbound', 'released', 'single_sided'].includes(current.status)) {
954
+ throw new OwnershipError('CONSENSUS_REQUIRED', 'Binding requires a fresh readable ownership baseline');
955
+ }
956
+ this.applyConsensus(subjectAid, subject, current);
957
+ assertCurrent();
958
+ const task = this.task(await client.bindOwneraid(ownerAid));
959
+ if (attached && (subject.client !== client || subject.generation !== generation)) {
960
+ replaced = true;
961
+ throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during binding; the request may have been submitted');
962
+ }
963
+ if (!task || task.sub_aid !== subjectAid || task.owner_aid !== ownerAid || task.operation !== 'bind') {
964
+ throw new OwnershipError('TASK_MISMATCH', 'SDK returned a binding result for a different subject or owner');
965
+ }
966
+ subject.view.task = task;
967
+ subject.view.requestStatus = task.status === 'error' ? 'error' : 'submitted';
968
+ subject.view.reason = task.reason;
969
+ if (task.status === 'rejected')
970
+ this.rememberRejectedOwnerBinding(task);
971
+ if (task.status === 'error' || task.status === 'rejected' || task.status === 'stopped') {
972
+ throw Object.assign(new OwnershipError(task.code ?? 'BIND_FAILED', task.reason ?? `Binding ended with ${task.status}`), {
973
+ retryable: task.retryable,
974
+ });
975
+ }
976
+ const submittedReason = 'Binding submitted; waiting for explicit owner approval and fresh consensus';
977
+ // 提交后旧共识必然过期(名片已写入新声明),invalidate 会清空 ownerAid 与
978
+ // consensusStatus;但"已提交、待审批"是调用方唯一能据以推进的事实,
979
+ // 必须留在视图里,否则上层只会看到 unavailable 而分不清是失败还是等待。
980
+ this.invalidate(subject, submittedReason, true);
981
+ subject.view.requestStatus = 'submitted';
982
+ subject.view.reason = submittedReason;
983
+ return this.snapshot(subjectAid);
984
+ });
962
985
  }
963
986
  catch (error) {
964
- if (!client || (subject.client === client && subject.generation === generation)) {
987
+ if (!replaced) {
965
988
  subject.view.requestStatus = 'interrupted';
966
989
  subject.view.reason = error instanceof Error ? error.message : String(error);
967
990
  }
@@ -1275,7 +1298,7 @@ export class OwnerResolver {
1275
1298
  throw new OwnershipError('TASK_MISMATCH', 'Ownership consensus subject does not match');
1276
1299
  }
1277
1300
  const ownerAid = consensus.status === 'consensus' && typeof consensus.owner_aid === 'string'
1278
- && isValidAid(consensus.owner_aid) ? consensus.owner_aid : undefined;
1301
+ && isValidAid(consensus.owner_aid) && consensus.owner_aid !== subjectAid ? consensus.owner_aid : undefined;
1279
1302
  if (consensus.status === 'consensus' && !ownerAid) {
1280
1303
  this.invalidate(subject, 'Ownership consensus owner is invalid');
1281
1304
  throw new OwnershipError('TASK_MISMATCH', 'Ownership consensus owner is invalid');
@@ -1590,6 +1613,21 @@ export async function refreshOwnershipForAuthorization(subjectAid, options = {})
1590
1613
  }
1591
1614
  }
1592
1615
  export async function assertOwnershipAuthorization(context) {
1616
+ if (context?.internalContactAuthorization && context.selfAid && context.actor?.principalId) {
1617
+ const { preparePaTeamQualification } = await import('../relation/pa-team.js');
1618
+ const { resolvePeerRoleDetail } = await import('../../config/peer-role-resolver.js');
1619
+ const { getRoleDefinition } = await import('../../config/roles.js');
1620
+ await preparePaTeamQualification(context.selfAid, context.actor.principalId);
1621
+ const current = resolvePeerRoleDetail({
1622
+ selfAid: context.selfAid, channelKey: context.actor.operatorChannelKey, channelType: 'aun',
1623
+ chatType: 'private', actorId: context.actor.principalId, conversationId: context.actor.principalId,
1624
+ });
1625
+ if (!current.allowAccess || current.effectiveRole !== context.role
1626
+ || (context.internalContactDefaultRole && current.source !== 'internal-contact-default')
1627
+ || (context.internalContactPolicy !== undefined && context.internalContactPolicy !== JSON.stringify(getRoleDefinition(context.role ?? '', context.selfAid)))) {
1628
+ throw new OwnershipError('INTERNAL_CONTACT_AUTHORIZATION_CHANGED', 'Internal-contact authorization changed; start a new task with the current role');
1629
+ }
1630
+ }
1593
1631
  const authorization = context?.executionPermission;
1594
1632
  const ownerRole = context?.role === 'owner' && context.actor?.operatorChannelType !== 'daemon';
1595
1633
  const ownerActor = hasTrustedPrincipal(context?.actor) ? context.actor.principalId : undefined;
@@ -328,6 +328,16 @@ const CODEX_POWERSHELL_INERT_SWITCHES = new Set([
328
328
  // intentionally not treated as a trusted Codex carrier.
329
329
  const CODEX_CMD_INERT_SWITCHES = new Set(['/d', '/s', '/q', '/a', '/u']);
330
330
  const EVOLCORE_EXECUTABLE_ALIASES = new Set(['ec', 'ec.cmd', 'ec.exe', 'ec.ps1']);
331
+ /**
332
+ * 轻量发送入口 `ecmsg` 的前缀映射:`ecmsg <args...>` 等价于 `ec msg <args...>`。
333
+ *
334
+ * 必须在这里归一,不能只做一个独立脚本——委托审批是按规范化 argv 的哈希
335
+ * arm 的(codex-runner 的 armApprovedDelegationCommand)。若 `ecmsg` 不归一到
336
+ * `['ec','msg',...]`,策略层会把它当普通命令(kind: 'none'),既不 arm 审批,
337
+ * daemon 侧也算不出匹配的哈希,最终必然 INVALID_DELEGATION;更糟的是它会绕过
338
+ * ec_shell_composite_command 与会话身份绑定,成为冒充发送的后门。
339
+ */
340
+ const EVOLCORE_MSG_ENTRY_ALIASES = new Set(['ecmsg', 'ecmsg.cmd', 'ecmsg.exe', 'ecmsg.ps1']);
331
341
  const EVOLCORE_NODE_EXECUTABLES = new Set(['node', 'node.exe']);
332
342
  const APPLY_PATCH_EXECUTABLE_BASENAMES = new Set([
333
343
  'apply_patch',
@@ -439,6 +449,10 @@ function hasEcCommandPrefix(command) {
439
449
  continue;
440
450
  if (boundary && /^ec(?:\.cmd|\.exe|\.ps1)?(?=$|\s|[;&|`()<>])/i.test(command.slice(index)))
441
451
  return true;
452
+ // `ecmsg` 是 `ec msg` 的同义词,同样算 EC 命令边界——否则
453
+ // `ecmsg ... && rm -rf /` 会落成 kind:'none',绕过复合命令拦截。
454
+ if (boundary && /^ecmsg(?:\.cmd|\.exe|\.ps1)?(?=$|\s|[;&|`()<>])/i.test(command.slice(index)))
455
+ return true;
442
456
  boundary = false;
443
457
  }
444
458
  return false;
@@ -694,6 +708,17 @@ function hasCarrierEcCommandPrefix(command, dialect) {
694
708
  return /^\s*ec(?:\.cmd|\.exe|\.ps1)?(?:\s|$)/i.test(inner);
695
709
  }
696
710
  /** Normalize the Windows npm shims to the canonical EvolCore CLI name. */
711
+ /**
712
+ * 取可执行名的 basename(小写)。与 hasEcCommandPrefix 里的算法一致:
713
+ * 兼容 `C:\path\ecmsg.cmd` 与 `./ecmsg` 这类调用形态。
714
+ */
715
+ function executableBasename(value) {
716
+ if (!value)
717
+ return undefined;
718
+ const normalized = value.replaceAll('\\', '/');
719
+ const base = normalized.slice(normalized.lastIndexOf('/') + 1).toLowerCase();
720
+ return base || undefined;
721
+ }
697
722
  export function normalizeEvolcoreCommandArgv(argv) {
698
723
  if (argv.length === 0)
699
724
  return [];
@@ -702,6 +727,12 @@ export function normalizeEvolcoreCommandArgv(argv) {
702
727
  if (typeof executable === 'string' && EVOLCORE_EXECUTABLE_ALIASES.has(executable.toLowerCase())) {
703
728
  return ['ec', ...materialized.slice(1)];
704
729
  }
730
+ // `ecmsg` 是 `ec msg` 的同义词:归一到 EC 命令族,才能进入同一条
731
+ // 审批、委托与复合命令拦截链路(见 EVOLCORE_MSG_ENTRY_ALIASES 注释)。
732
+ const entryAlias = executableBasename(executable);
733
+ if (entryAlias && EVOLCORE_MSG_ENTRY_ALIASES.has(entryAlias)) {
734
+ return ['ec', 'msg', ...materialized.slice(1)];
735
+ }
705
736
  if (typeof executable === 'string' && isNodeExecutable(executable) && materialized.length >= 2
706
737
  && typeof materialized[1] === 'string' && normalizeNodeWrapperPath(materialized[1])) {
707
738
  return ['ec', ...materialized.slice(2)];
@@ -1552,23 +1583,38 @@ function resolveCodexCmdCarrierString(command) {
1552
1583
  */
1553
1584
  function resolveCodexPowerShellCarrierString(command) {
1554
1585
  const input = trimShellSpacing(command);
1555
- const match = input.match(/^(?:"([^"\r\n]+)"|(\S+))((?:[ \t]+-[A-Za-z]+)+)[ \t]+(.+)$/);
1586
+ const match = input.match(/^(?:"([^"\r\n]+)"|(\S+))((?:[ \t]+-[A-Za-z]+)+)[ \t]+(.+)$/s);
1556
1587
  if (!match)
1557
1588
  return undefined;
1558
- const executable = match[1] ?? match[2];
1589
+ let executable = match[1] ?? match[2];
1590
+ if (match[1] !== undefined) {
1591
+ const parsedExecutable = parseLiteralShellCommand(`"${match[1]}"`, { dialect: 'posix' });
1592
+ if (!parsedExecutable.ok || parsedExecutable.argv.length !== 1)
1593
+ return undefined;
1594
+ executable = parsedExecutable.argv[0];
1595
+ }
1559
1596
  if (!isCodexPowerShellExecutable(executable))
1560
1597
  return undefined;
1561
- // A string-form carrier has one additional command-line quoting layer. The
1562
- // command argument is commonly serialized as `"ec ..."`; remove exactly
1563
- // that outer pair and leave quotes belonging to EC arguments intact.
1564
1598
  let nested = match[4].trim();
1565
- if (nested.length >= 2
1566
- && ((nested.startsWith('"') && nested.endsWith('"'))
1567
- || (nested.startsWith("'") && nested.endsWith("'")))) {
1568
- nested = nested.slice(1, -1);
1599
+ let failure;
1600
+ if (nested.startsWith('"') || nested.startsWith("'")) {
1601
+ // The outer `-Command` argument is a PowerShell string literal. Strip
1602
+ // that one transport-level pair without tokenizing the body as POSIX
1603
+ // shell: doing so removes the `$env:` assignment marker and collapses
1604
+ // doubled single quotes around the credential token before the
1605
+ // PowerShell credential-prefix parser sees them.
1606
+ const quote = nested[0];
1607
+ if (nested.length >= 2 && nested.endsWith(quote)) {
1608
+ nested = nested.slice(1, -1);
1609
+ }
1610
+ else {
1611
+ failure = parseFailure('invalid-quote', nested, 0, 0, 'powershell');
1612
+ nested = nested.slice(1);
1613
+ }
1569
1614
  }
1570
1615
  const switches = match[3].trim().split(/[ \t]+/);
1571
- return resolveCodexPowerShellCarrierArgv([executable, ...switches, nested]);
1616
+ const carrier = resolveCodexPowerShellCarrierArgv([executable, ...switches, nested]);
1617
+ return carrier && failure ? { ...carrier, parseFailure: failure } : carrier;
1572
1618
  }
1573
1619
  /** Resolve a POSIX shell carrier when app-server provides only a string. */
1574
1620
  function resolveCodexPosixShellCarrierString(command) {
@@ -2951,12 +2997,15 @@ export function parseCdPrefixedEcCommand(input) {
2951
2997
  */
2952
2998
  function parseEcTail(segment) {
2953
2999
  const literal = parseLiteralShellArgv(segment);
3000
+ // 归一化后再判首元素:`ecmsg ...` 等价于 `ec msg ...`,必须与 ec 同权进审批链。
3001
+ // 返回的 argv 也必须是归一化后的形态,否则审批哈希与 daemon 侧解析会错位。
2954
3002
  if (literal && literal.length > 0 && normalizeEvolcoreCommandArgv(literal)[0] === 'ec') {
2955
- return { argv: literal, mergeStderr: false };
3003
+ return { argv: normalizeEvolcoreCommandArgv(literal), mergeStderr: false };
2956
3004
  }
2957
3005
  const bounded = parseBoundedOutputShellCommand(segment);
2958
- if (bounded && bounded.argv[0] === 'ec')
2959
- return bounded;
3006
+ if (bounded && normalizeEvolcoreCommandArgv(bounded.argv)[0] === 'ec') {
3007
+ return { ...bounded, argv: normalizeEvolcoreCommandArgv(bounded.argv) };
3008
+ }
2960
3009
  return null;
2961
3010
  }
2962
3011
  /**
@@ -97,7 +97,11 @@ export class PluginHandle {
97
97
  this.timeouts.set(timer, release);
98
98
  return timer;
99
99
  }
100
- dispose() {
100
+ /**
101
+ * `options.teardownBudgetMs` 只给进程退出路径用,透传给 teardown(目前只有 AUN 渠道
102
+ * 的 `client.close()` 关心):daemon 反正马上 `exit(0)`,等不满的网络握手没有意义。
103
+ */
104
+ dispose(options = {}) {
101
105
  if (this.disposal)
102
106
  return this.disposal;
103
107
  this.currentState = 'disposing';
@@ -118,7 +122,7 @@ export class PluginHandle {
118
122
  ...pending.map(([operation, label]) => cleanup(operation, label)),
119
123
  ]);
120
124
  try {
121
- await this.teardown?.();
125
+ await this.teardown?.(options.teardownBudgetMs);
122
126
  }
123
127
  catch (cause) {
124
128
  errors.push(new Error(`Plugin ${this.owner}: teardown`, { cause }));
@@ -0,0 +1,132 @@
1
+ import { createHash } from 'crypto';
2
+ import { agentmdGet } from '../../aun/aid/agentmd.js';
3
+ import { isValidAid } from '../../aun/aid/validation.js';
4
+ import { parseAgentMdFrontmatter } from './peer-identity.js';
5
+ export const PA_TEAM_MAX_AGE_MS = 30_000;
6
+ const PA_TEAM_TIMEOUT_MS = 8_000;
7
+ const runtimes = new Map();
8
+ const knownTeams = new Map();
9
+ let revision = 0;
10
+ export function registerPaTeamClient(selfAid, client, store) {
11
+ unregisterPaTeamClient(selfAid);
12
+ const peers = knownTeams.get(selfAid) ?? new Set();
13
+ knownTeams.set(selfAid, peers);
14
+ const runtime = { client, store, generation: 0, entries: new Map(), pending: new Map(), knownTeams: peers, subscriptions: [] };
15
+ runtimes.set(selfAid, runtime);
16
+ const invalidate = () => {
17
+ if (runtimes.get(selfAid) !== runtime)
18
+ return;
19
+ runtime.generation++;
20
+ runtime.entries.clear();
21
+ runtime.pending.clear();
22
+ revision++;
23
+ };
24
+ for (const event of ['agentmd.changed', 'storage.object_changed', 'ownership.completed', 'ownership.rejected',
25
+ 'ownership.stopped', 'ownership.error', 'disconnected']) {
26
+ runtime.subscriptions.push(client.on(event, invalidate));
27
+ }
28
+ }
29
+ export function unregisterPaTeamClient(selfAid, client) {
30
+ const runtime = runtimes.get(selfAid);
31
+ if (!runtime || (client && runtime.client !== client))
32
+ return;
33
+ runtimes.delete(selfAid);
34
+ revision++;
35
+ for (const subscription of runtime.subscriptions)
36
+ subscription.unsubscribe();
37
+ }
38
+ export function paTeamQualification(selfAid, peerAid) {
39
+ const runtime = runtimes.get(selfAid);
40
+ const entry = runtime?.entries.get(peerAid);
41
+ return runtime?.client.isReady && entry && entry.expiresAt > Date.now()
42
+ ? entry.qualification : 'unavailable';
43
+ }
44
+ export function paTeamRevision(selfAid) {
45
+ const runtime = runtimes.get(selfAid);
46
+ const entries = [...(runtime?.entries ?? [])].map(([peerAid, entry]) => [peerAid, entry.revision, entry.expiresAt > Date.now()]);
47
+ return JSON.stringify([revision, runtime?.client.isReady === true, entries]);
48
+ }
49
+ export function requiresPaTeamVerification(selfAid, peerAid) {
50
+ return knownTeams.get(selfAid)?.has(peerAid) === true;
51
+ }
52
+ export async function preparePaTeamQualification(selfAid, peerAid) {
53
+ if (!selfAid || !peerAid || selfAid === peerAid || !isValidAid(selfAid) || !isValidAid(peerAid))
54
+ return;
55
+ const runtime = runtimes.get(selfAid);
56
+ if (!runtime?.client.isReady)
57
+ return;
58
+ const cached = runtime.entries.get(peerAid);
59
+ if (cached && cached.expiresAt > Date.now())
60
+ return;
61
+ const pending = runtime.pending.get(peerAid);
62
+ if (pending)
63
+ return pending;
64
+ const generation = runtime.generation;
65
+ const startedAt = Date.now();
66
+ const query = async () => {
67
+ const cards = await Promise.all([selfAid, peerAid].map(aid => agentmdGet(aid, { store: runtime.store, withVerification: true, remoteOnly: true })));
68
+ const profiles = cards.map((card, index) => {
69
+ if (card.source !== 'remote' || card.verification.status !== 'verified')
70
+ throw new Error('Unverified PA profile');
71
+ const profile = parseAgentMdFrontmatter(card.content);
72
+ if (profile.aid !== [selfAid, peerAid][index])
73
+ throw new Error('Mismatched PA profile');
74
+ return profile;
75
+ });
76
+ // The same-owner proof is now the internal-agent qualification. Keep the
77
+ // pa-team API names for registry/config compatibility, but do not require
78
+ // an exttype prefix: non-PA agents owned by the same Owner are internal
79
+ // contacts as well. Human/service/device identities do not participate in
80
+ // this automatic role because they cannot provide the required agent.md
81
+ // ownership statement used by the protocol consensus check.
82
+ if (!profiles.every(profile => String(profile.type || '').trim().toLowerCase() === 'agent'))
83
+ return 'unmatched';
84
+ const consensuses = await Promise.all([selfAid, peerAid].map(aid => runtime.client.checkOwnershipConsensus(aid, true)));
85
+ for (const [index, consensus] of consensuses.entries()) {
86
+ const digest = createHash('sha256').update(cards[index].content, 'utf8').digest('hex');
87
+ if (consensus.status !== 'consensus' || consensus.sub_aid !== [selfAid, peerAid][index]
88
+ || consensus.lock !== 'locked' || !consensus.owner_aid || !isValidAid(consensus.owner_aid)
89
+ || !Number.isSafeInteger(consensus.relation_version) || consensus.relation_version < 1
90
+ || consensus.agent_md_sha256 !== digest
91
+ || profiles[index].owner !== consensus.owner_aid)
92
+ return 'unavailable';
93
+ }
94
+ return consensuses[0].owner_aid === consensuses[1].owner_aid ? 'matched' : 'unmatched';
95
+ };
96
+ const task = (async () => {
97
+ let timeout;
98
+ let qualification = 'unavailable';
99
+ try {
100
+ qualification = await Promise.race([query(), new Promise(resolve => {
101
+ timeout = setTimeout(() => resolve('unavailable'), PA_TEAM_TIMEOUT_MS);
102
+ timeout.unref?.();
103
+ })]);
104
+ }
105
+ catch {
106
+ qualification = 'unavailable';
107
+ }
108
+ finally {
109
+ if (timeout)
110
+ clearTimeout(timeout);
111
+ }
112
+ if (runtimes.get(selfAid) !== runtime || runtime.generation !== generation || !runtime.client.isReady)
113
+ return;
114
+ if (qualification === 'matched')
115
+ runtime.knownTeams.add(peerAid);
116
+ if (qualification === 'unmatched')
117
+ runtime.knownTeams.delete(peerAid);
118
+ runtime.entries.set(peerAid, {
119
+ qualification,
120
+ expiresAt: startedAt + (qualification === 'unavailable' ? 2_000 : PA_TEAM_MAX_AGE_MS),
121
+ revision: ++revision,
122
+ });
123
+ })();
124
+ runtime.pending.set(peerAid, task);
125
+ try {
126
+ await task;
127
+ }
128
+ finally {
129
+ if (runtime.pending.get(peerAid) === task)
130
+ runtime.pending.delete(peerAid);
131
+ }
132
+ }
@@ -170,7 +170,8 @@ export function sessionFullAccessStatus(session, principalId) {
170
170
  // takes precedence over any per-main-session or per-topic /fa state.
171
171
  const override = readSessionFullAccessOverride(session);
172
172
  const localEnabled = override?.enabled === true;
173
- const scope = isTopicSession(session) ? 'session' : 'relation';
173
+ const source = isTopicSession(session) ? 'session' : 'relation';
174
+ const scope = source === 'session' ? 'topic-session' : 'relation-main';
174
175
  if (agentStatus.enabled) {
175
176
  return {
176
177
  ...agentStatus, effective: agentStatus.effective && session.chatType === 'private',
@@ -180,7 +181,7 @@ export function sessionFullAccessStatus(session, principalId) {
180
181
  if (!override) {
181
182
  return {
182
183
  enabled: false, eligible: agentStatus.eligible, effective: false,
183
- inherited: false, globalEnabled: false, localEnabled: false, scope, source: scope, mutable: true,
184
+ inherited: false, globalEnabled: false, localEnabled: false, scope, source, mutable: true,
184
185
  };
185
186
  }
186
187
  const eligible = !!session.selfAID && isAgentFullAccessOwner(session.selfAID, principalId);
@@ -193,7 +194,7 @@ export function sessionFullAccessStatus(session, principalId) {
193
194
  globalEnabled: false,
194
195
  localEnabled,
195
196
  scope,
196
- source: scope,
197
+ source,
197
198
  mutable: true,
198
199
  authorizedBy: override.authorizedBy,
199
200
  };
@@ -332,15 +332,17 @@ export class ThreadService {
332
332
  if (entry.name === sanitized)
333
333
  return { changed: false, name: sanitized };
334
334
  const nameUpdatedAt = Math.max(Date.now(), Number(entry.nameUpdatedAt ?? entry.createdAt ?? 0) + 1);
335
+ const session = await this.sessionManager.getThreadSession(entryChannelType(entry), entry.peer, threadId, selfAid);
336
+ if (session) {
337
+ const renamed = await this.sessionManager.renameSession(session.id, sanitized, nameUpdatedAt);
338
+ if (!renamed)
339
+ throw new ThreadServiceError(`话题会话改名失败: ${session.id}`, 'RENAME_FAILED');
340
+ }
335
341
  entry.name = sanitized;
336
342
  entry.nameUpdatedAt = nameUpdatedAt;
337
343
  entry.lastActiveAt = nameUpdatedAt;
338
344
  this.writeThreadIndex(selfAid, index);
339
345
  this.appendThreadSnapshot(selfAid, entry);
340
- const session = await this.sessionManager.getThreadSession(entryChannelType(entry), entry.peer, threadId, selfAid);
341
- if (session) {
342
- await this.sessionManager.renameSession(session.id, sanitized, nameUpdatedAt);
343
- }
344
346
  return { changed: true, name: sanitized, nameUpdatedAt, peerKind: entry.peerKind };
345
347
  }
346
348
  /**
@@ -4,7 +4,6 @@ import { agentDir } from '../paths.js';
4
4
  import { existsAtomic } from '../utils/atomic-write.js';
5
5
  import { ownerResolver } from '../core/ownership/owner-resolver.js';
6
6
  import { logger } from '../utils/logger.js';
7
- import { readAccessPolicy } from '../config/access-policy.js';
8
7
  import { isInternalEntry, ownerRefAid } from './owner-directory-scope.js';
9
8
  import { isPersonalAssistantSnapshot, resolveAllowExternalContacts } from './owner-directory-policy.js';
10
9
  import { OwnerDirectoryCache, OWNER_DIRECTORY_INITIAL_WAIT_MS, OWNER_DIRECTORY_SCOPES, } from './owner-directory-cache.js';
@@ -157,8 +156,6 @@ export async function syncOwnerDirectoryForLookup(selfAid) {
157
156
  }
158
157
  /** Cache misses get one bounded synchronization attempt before admission, using the live channel. */
159
158
  export async function prepareOwnerDirectoryAdmission(selfAid, aid) {
160
- if (readAccessPolicy(selfAid).contactAdmission === 'app-v1')
161
- return;
162
159
  const live = liveDirectories.get(selfAid);
163
160
  if (!live)
164
161
  return;