evolcore 0.0.43-test.1 → 0.0.43-test.3

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 (200) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/README.md +22 -0
  3. package/dist/agents/claude-runner.js +26 -2
  4. package/dist/agents/codex/app-server-client.js +12 -0
  5. package/dist/agents/codex-runner.js +49 -8
  6. package/dist/agents/ecagent-runner.js +39 -15
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/aid/agentmd.js +21 -1
  10. package/dist/aun/menu/client.js +1 -1
  11. package/dist/aun/model-headers.js +17 -0
  12. package/dist/aun/msg/p2p.js +7 -2
  13. package/dist/channels/aun.js +522 -50
  14. package/dist/channels/builtin-plugins.js +16 -11
  15. package/dist/channels/daemon.js +4 -0
  16. package/dist/channels/dingtalk.js +83 -31
  17. package/dist/channels/feishu.js +29 -13
  18. package/dist/channels/qqbot.js +32 -11
  19. package/dist/channels/wechat.js +13 -3
  20. package/dist/channels/wecom.js +67 -27
  21. package/dist/cli/agent-command.js +3 -86
  22. package/dist/cli/agent-create.js +20 -6
  23. package/dist/cli/agent.js +1 -79
  24. package/dist/cli/aun-commands.js +18 -19
  25. package/dist/cli/config.js +1 -1
  26. package/dist/cli/daemon-commands.js +47 -2
  27. package/dist/cli/data-command.js +9 -1
  28. package/dist/cli/debug-mode.js +1 -1
  29. package/dist/cli/diag.js +1 -1
  30. package/dist/cli/directory.js +149 -91
  31. package/dist/cli/getmeta-command.js +1 -1
  32. package/dist/cli/index.js +79 -22
  33. package/dist/cli/init.js +1 -23
  34. package/dist/cli/link-rules.js +1 -1
  35. package/dist/cli/managed-command-guard.js +0 -1
  36. package/dist/cli/pa-workspace-command.js +36 -2
  37. package/dist/cli/peer.js +3 -2
  38. package/dist/cli/restart-monitor.js +17 -3
  39. package/dist/cli/role.js +1 -1
  40. package/dist/cli/session-command.js +1 -1
  41. package/dist/cli/stats.js +2 -2
  42. package/dist/cli/task-context.js +3 -1
  43. package/dist/cli/thread-command.js +1 -1
  44. package/dist/cli/watch-msg.js +1 -1
  45. package/dist/config/builtin-role-templates.js +2 -2
  46. package/dist/config/builtin-roles.js +2 -1
  47. package/dist/config/config-field-policy.js +7 -2
  48. package/dist/config/config-manager.js +32 -10
  49. package/dist/config/peer-role-resolver.js +23 -1
  50. package/dist/config/role-schema.js +29 -4
  51. package/dist/config/role-service.js +12 -7
  52. package/dist/config/role-store.js +30 -8
  53. package/dist/config-store.js +75 -4
  54. package/dist/core/agent-ipc-registration.js +16 -59
  55. package/dist/core/auth/auth-gateway.js +14 -4
  56. package/dist/core/auth/authorization-audit.js +52 -14
  57. package/dist/core/auth/operation-authorizer.js +17 -11
  58. package/dist/core/auth/operation-catalog.js +5 -13
  59. package/dist/core/channel-loader.js +152 -16
  60. package/dist/core/channel-runtime.js +5 -0
  61. package/dist/core/command/agent-control.js +2 -1
  62. package/dist/core/command/agentmd-menu-request.js +50 -0
  63. package/dist/core/command/agentmd-menu.js +156 -0
  64. package/dist/core/command/cli-intent-parser.js +0 -8
  65. package/dist/core/command/command-handler.js +47 -40
  66. package/dist/core/command/connect-menu.js +7 -3
  67. package/dist/core/command/menu-catalog.js +16 -2
  68. package/dist/core/command/menu-handler.js +107 -14
  69. package/dist/core/command/menu-protocol.js +28 -0
  70. package/dist/core/command/role-menu.js +23 -9
  71. package/dist/core/command/slash-handler.js +139 -51
  72. package/dist/core/daemon-file-cache.js +3 -3
  73. package/dist/core/daemon-lifecycle.js +9 -1
  74. package/dist/core/evolagent-registry.js +5 -4
  75. package/dist/core/evolagent.js +10 -12
  76. package/dist/core/handoff/argv-parse.js +115 -0
  77. package/dist/core/handoff/ipc-registration.js +1 -1
  78. package/dist/core/ipc-registration.js +19 -2
  79. package/dist/core/lifecycle-notice.js +185 -0
  80. package/dist/core/memory/consolidation.js +8 -1
  81. package/dist/core/memory/relation-sweep.js +20 -8
  82. package/dist/core/message/aun-ipc-sender.js +35 -2
  83. package/dist/core/message/contact-admission.js +530 -0
  84. package/dist/core/message/im-renderer.js +111 -16
  85. package/dist/core/message/message-admission.js +29 -54
  86. package/dist/core/message/message-bridge.js +62 -8
  87. package/dist/core/message/message-utils.js +9 -5
  88. package/dist/core/message/peer-mode.js +55 -13
  89. package/dist/core/message/response-engine.js +298 -78
  90. package/dist/core/message/retry-scheduler.js +4 -0
  91. package/dist/core/ownership/owner-resolver.js +72 -34
  92. package/dist/core/permission/ec-command-parser.js +25 -38
  93. package/dist/core/permission/readonly-shell-query.js +34 -8
  94. package/dist/core/permission/tool-policy.js +50 -5
  95. package/dist/core/relation/pa-team.js +127 -0
  96. package/dist/core/role/runtime-policy.js +18 -5
  97. package/dist/core/session/session-manager.js +9 -1
  98. package/dist/core/soul.js +66 -0
  99. package/dist/core/system-session/memory.js +2 -2
  100. package/dist/core/thread/thread-service.js +6 -4
  101. package/dist/directory/contact-admission-paths.js +9 -0
  102. package/dist/directory/owner-directory-admission.js +125 -29
  103. package/dist/directory/owner-directory-cache.js +554 -58
  104. package/dist/directory/owner-directory-identity.js +60 -0
  105. package/dist/directory/owner-directory-markdown.js +154 -58
  106. package/dist/directory/owner-directory-policy.js +108 -0
  107. package/dist/directory/owner-directory-query-operation.js +399 -90
  108. package/dist/directory/owner-directory-remarks.js +29 -2
  109. package/dist/directory/owner-directory-request-operation.js +76 -0
  110. package/dist/directory/owner-directory-scope.js +35 -4
  111. package/dist/directory/owner-directory-search.js +118 -33
  112. package/dist/directory/owner-directory-store.js +117 -30
  113. package/dist/directory/owner-directory-text.js +60 -0
  114. package/dist/eck/kit-renderer.js +18 -8
  115. package/dist/eck/manifest-engine.js +55 -6
  116. package/dist/ecweb/basic-settings-service.js +2 -2
  117. package/dist/ecweb/message-context-service.js +28 -16
  118. package/dist/index.js +20 -5
  119. package/dist/ipc.js +1 -1
  120. package/dist/paths.js +29 -1
  121. package/dist/product.js +1 -0
  122. package/dist/response-system/config-resolver.js +1 -1
  123. package/dist/response-system/engines/v1/index.js +2 -1
  124. package/dist/response-system/modes/single-session/index.js +7 -2
  125. package/dist/trigger/scheduler.js +7 -4
  126. package/dist/trigger/validation.js +4 -0
  127. package/dist/utils/error-utils.js +12 -7
  128. package/dist/utils/logger.js +13 -4
  129. package/dist/utils/npm-ops.js +2 -2
  130. package/dist/utils/windows-autostart.js +1 -1
  131. package/ecagent/README.md +18 -0
  132. package/ecagent/dist/agent-loop.js +43 -1
  133. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  134. package/ecagent/dist/harness/agent-harness.js +24 -8
  135. package/ecagent/dist/harness/compaction/compaction.js +3 -0
  136. package/ecagent/dist/harness/types.d.ts +1 -0
  137. package/kits/docs/INDEX.md +1 -0
  138. package/kits/docs/channels/aun.md +1 -1
  139. package/kits/docs/context-assembly.md +21 -6
  140. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  141. package/kits/docs/evolcore/INDEX.md +4 -1
  142. package/kits/docs/evolcore/agent-create.md +5 -5
  143. package/kits/docs/evolcore/agent.md +4 -9
  144. package/kits/docs/evolcore/directory.md +227 -0
  145. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  146. package/kits/docs/evolcore/file-navigation.md +265 -0
  147. package/kits/docs/evolcore/menu-protocol.md +55 -0
  148. package/kits/docs/evolcore/msg.md +1 -0
  149. package/kits/docs/evolcore/peer.md +2 -1
  150. package/kits/docs/evolcore/response.md +7 -1
  151. package/kits/docs/evolcore/task.md +2 -0
  152. package/kits/docs/evolcore/tool-authorization.md +1 -1
  153. package/kits/docs/evolcore/trigger.md +4 -0
  154. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  155. package/kits/docs/prompt-loading-architecture.md +6 -2
  156. package/kits/eck_manifest.auxiliary.json +1 -0
  157. package/kits/eck_manifest.json +64 -7
  158. package/kits/eck_manifest.memory.json +93 -4
  159. package/kits/rules/01-overview.md +2 -2
  160. package/kits/rules/03-identity.md +10 -9
  161. package/kits/rules/05-venue.md +2 -4
  162. package/kits/rules/06-channel.md +1 -1
  163. package/kits/schemas/_meta.json +44 -3
  164. package/kits/schemas/agent-config.schema.18.json +5 -0
  165. package/kits/schemas/agent-config.schema.19.json +924 -0
  166. package/kits/schemas/agent-config.schema.20.json +925 -0
  167. package/kits/schemas/relation-config.schema.12.json +289 -0
  168. package/kits/schemas/relation-config.schema.13.json +289 -0
  169. package/kits/schemas/role-config.schema.2.json +215 -0
  170. package/kits/schemas/role-config.schema.3.json +1038 -0
  171. package/kits/schemas/role-registry.schema.1.json +3 -2
  172. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  173. package/kits/skills/ec-trigger/SKILL.md +4 -4
  174. package/kits/skills/personal-assistant/SKILL.md +109 -53
  175. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  176. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  177. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  178. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  179. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  180. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  181. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  182. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  183. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  184. package/kits/templates/soul/00-GUIDE.md +39 -0
  185. package/kits/templates/soul/01-identity.md +5 -0
  186. package/kits/templates/soul/02-persona.md +11 -0
  187. package/kits/templates/soul/03-duties.md +5 -0
  188. package/kits/templates/soul/04-working-style.md +5 -0
  189. package/kits/templates/system-fragments/bootstrap.md +7 -7
  190. package/kits/templates/system-fragments/channel.md +2 -2
  191. package/kits/templates/system-fragments/commands.md +3 -2
  192. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  193. package/kits/templates/system-fragments/memory.md +1 -1
  194. package/kits/templates/system-fragments/personal-assistant.md +50 -0
  195. package/kits/templates/system-fragments/reply.md +7 -0
  196. package/kits/templates/system-fragments/session.md +6 -2
  197. package/package.json +3 -2
  198. package/dist/cli/handoff-command.js +0 -353
  199. package/dist/directory/owner-directory-remark-operation.js +0 -147
  200. package/kits/docs/evolcore/self-summary.md +0 -29
@@ -4,6 +4,10 @@
4
4
  */
5
5
  export const API_RETRY_DELAYS_MS = [5_000, 10_000, 30_000];
6
6
  export const MAX_PROTOCOL_REPLAY_ATTEMPTS = 1;
7
+ export function isRecoverableProtocolFailure(subtype, reason) {
8
+ return subtype === 'protocol_incomplete'
9
+ && (reason === 'input_not_consumed' || reason === 'empty_success');
10
+ }
7
11
  export class RetryScheduler {
8
12
  resolveModelId;
9
13
  currentProvider;
@@ -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
  }
@@ -1590,6 +1613,21 @@ export async function refreshOwnershipForAuthorization(subjectAid, options = {})
1590
1613
  }
1591
1614
  }
1592
1615
  export async function assertOwnershipAuthorization(context) {
1616
+ if (context?.paTeamAuthorization && 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.paTeamDefaultRole && current.source !== 'pa-team-default')
1627
+ || (context.paTeamPolicy !== undefined && context.paTeamPolicy !== JSON.stringify(getRoleDefinition(context.role ?? '', context.selfAid)))) {
1628
+ throw new OwnershipError('PA_TEAM_AUTHORIZATION_CHANGED', 'PA team 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;
@@ -338,7 +338,7 @@ const APPLY_PATCH_EXECUTABLE_BASENAMES = new Set([
338
338
  ]);
339
339
  const EVOLCORE_SUBCOMMANDS = new Set([
340
340
  'ability', 'agent', 'aid', 'bench', 'config', 'peer', 'ctl', 'data', 'diag', 'diagnose',
341
- 'fs', 'gateway', 'group', 'handoff', 'init', 'link-rules', 'logs', 'menu-client',
341
+ 'fs', 'gateway', 'group', 'init', 'link-rules', 'logs', 'menu-client',
342
342
  'mode', 'model', 'msg', 'mv', 'net', 'queue', 'response', 'restart',
343
343
  'restart-monitor', 'rpc', 'start', 'stats', 'status', 'stop', 'storage', 'task',
344
344
  'trigger', 'proxy', 'version', 'watch', 'session', 'pa-workspace', 'upgrade', 'update',
@@ -762,7 +762,6 @@ function materializeEvolcoreCmdShimArgv(argv) {
762
762
  }
763
763
  const INLINE_TEXT_FLAGS = {
764
764
  agentNew: new Set(['--description', '--persona-text', '--handoff']),
765
- agentPersona: new Set(['--text']),
766
765
  agentWelcome: new Set(['--text']),
767
766
  msgSend: new Set(['--description', '--text', '--transcript', '--handoff-context']),
768
767
  groupSend: new Set(['--text', '--transcript']),
@@ -899,27 +898,6 @@ function canonicalizeCommaOnlyFlags(argv, flags) {
899
898
  index++;
900
899
  }
901
900
  }
902
- function canonicalizeHandoffText(argv) {
903
- const action = argv[2];
904
- if (action !== 'return' && action !== 'recover-return')
905
- return;
906
- const delimiter = argv.indexOf('--', 2);
907
- if (delimiter >= 0) {
908
- for (let index = delimiter + 1; index < argv.length; index++) {
909
- argv[index] = decodeEvolcoreInlineText(argv[index]);
910
- }
911
- return;
912
- }
913
- const fileIndex = argv.indexOf('--text-from-file', 2);
914
- for (let index = 2; index < argv.length; index++) {
915
- if (index === fileIndex) {
916
- index++;
917
- continue;
918
- }
919
- if (!argv[index].startsWith('--'))
920
- argv[index] = decodeEvolcoreInlineText(argv[index]);
921
- }
922
- }
923
901
  const LOCAL_FILE_VALUE_FLAGS = new Set(['--file', '--text-from-file', '--payload-file']);
924
902
  function normalizeWindowsFilePath(value) {
925
903
  if (process.platform !== 'win32' || !/^[A-Za-z]:[\\/]/u.test(value))
@@ -959,8 +937,6 @@ export function canonicalizeEvolcoreCommandArgv(argv) {
959
937
  if (command === 'agent') {
960
938
  if (subcommand === 'new')
961
939
  decodeInlineFlags(result, INLINE_TEXT_FLAGS.agentNew);
962
- else if (subcommand === 'persona')
963
- decodeInlineFlags(result, INLINE_TEXT_FLAGS.agentPersona);
964
940
  else if (subcommand === 'welcome')
965
941
  decodeInlineFlags(result, INLINE_TEXT_FLAGS.agentWelcome);
966
942
  }
@@ -992,9 +968,6 @@ export function canonicalizeEvolcoreCommandArgv(argv) {
992
968
  else if (subcommand === 'update')
993
969
  decodeInlineFlags(result, INLINE_TEXT_FLAGS.triggerUpdate);
994
970
  }
995
- else if (command === 'handoff') {
996
- canonicalizeHandoffText(result);
997
- }
998
971
  else if (command === 'memory') {
999
972
  canonicalizeListFlags(result, MEMORY_LIST_FLAGS);
1000
973
  canonicalizeCommaOnlyFlags(result, MEMORY_COMMA_ONLY_FLAGS);
@@ -1579,23 +1552,37 @@ function resolveCodexCmdCarrierString(command) {
1579
1552
  */
1580
1553
  function resolveCodexPowerShellCarrierString(command) {
1581
1554
  const input = trimShellSpacing(command);
1582
- const match = input.match(/^(?:"([^"\r\n]+)"|(\S+))((?:[ \t]+-[A-Za-z]+)+)[ \t]+(.+)$/);
1555
+ const match = input.match(/^(?:"([^"\r\n]+)"|(\S+))((?:[ \t]+-[A-Za-z]+)+)[ \t]+(.+)$/s);
1583
1556
  if (!match)
1584
1557
  return undefined;
1585
- const executable = match[1] ?? match[2];
1558
+ let executable = match[1] ?? match[2];
1559
+ if (match[1] !== undefined) {
1560
+ const parsedExecutable = parseLiteralShellCommand(`"${match[1]}"`, { dialect: 'posix' });
1561
+ if (!parsedExecutable.ok || parsedExecutable.argv.length !== 1)
1562
+ return undefined;
1563
+ executable = parsedExecutable.argv[0];
1564
+ }
1586
1565
  if (!isCodexPowerShellExecutable(executable))
1587
1566
  return undefined;
1588
- // A string-form carrier has one additional command-line quoting layer. The
1589
- // command argument is commonly serialized as `"ec ..."`; remove exactly
1590
- // that outer pair and leave quotes belonging to EC arguments intact.
1591
1567
  let nested = match[4].trim();
1592
- if (nested.length >= 2
1593
- && ((nested.startsWith('"') && nested.endsWith('"'))
1594
- || (nested.startsWith("'") && nested.endsWith("'")))) {
1595
- nested = nested.slice(1, -1);
1568
+ let failure;
1569
+ if (nested.startsWith('"') || nested.startsWith("'")) {
1570
+ const parsed = parseLiteralShellCommand(nested, { dialect: 'posix' });
1571
+ if (parsed.ok && parsed.argv.length === 1) {
1572
+ nested = parsed.argv[0];
1573
+ }
1574
+ else {
1575
+ failure = parsed.ok
1576
+ ? parseFailure('shell-composition', nested, 0, 0, 'powershell')
1577
+ : { ...parsed, dialect: 'powershell' };
1578
+ nested = nested.length > 1 && nested.endsWith(nested[0])
1579
+ ? nested.slice(1, -1)
1580
+ : nested.slice(1);
1581
+ }
1596
1582
  }
1597
1583
  const switches = match[3].trim().split(/[ \t]+/);
1598
- return resolveCodexPowerShellCarrierArgv([executable, ...switches, nested]);
1584
+ const carrier = resolveCodexPowerShellCarrierArgv([executable, ...switches, nested]);
1585
+ return carrier && failure ? { ...carrier, parseFailure: failure } : carrier;
1599
1586
  }
1600
1587
  /** Resolve a POSIX shell carrier when app-server provides only a string. */
1601
1588
  function resolveCodexPosixShellCarrierString(command) {
@@ -3,7 +3,7 @@ import { parseLiteralShellArgv } from './ec-command-parser.js';
3
3
  const MAX_QUERY_LISTS = 8;
4
4
  const MAX_PIPELINE_STAGES = 3;
5
5
  const SUPPORTED_EXECUTABLES = new Set([
6
- 'echo', 'pwd', 'ls', 'cat', 'grep', 'rg', 'find', 'sed', 'head', 'tail', 'sort', 'git', 'wc', 'stat', 'lstat', 'awk',
6
+ 'echo', 'pwd', 'ls', 'cat', 'grep', 'rg', 'find', 'sed', 'head', 'tail', 'sort', 'uniq', 'git', 'wc', 'stat', 'lstat', 'awk',
7
7
  'bash', 'sh',
8
8
  ]);
9
9
  const FIND_MUTATING_PRIMARY_RE = /^-(?:delete|exec|execdir|ok|okdir|fprint|fprint0|fprintf|fls)$/;
@@ -278,7 +278,7 @@ function analyzeGrep(args) {
278
278
  paths.push(recursive('.'));
279
279
  return paths;
280
280
  }
281
- function analyzeRg(args) {
281
+ function analyzeRg(args, hasPipelineInput = false) {
282
282
  if (args.some(argument => RG_PROCESS_SPAWNING_OPTION_RE.test(argument)
283
283
  || argument === '--follow'
284
284
  // `-z` is the short form of `--search-zip`; it may also appear in a
@@ -316,7 +316,7 @@ function analyzeRg(args) {
316
316
  }
317
317
  if (!optionsEnded && argument.startsWith('-') && argument !== '-') {
318
318
  const option = argument.split('=', 1)[0];
319
- if (['--files', '--files-with-matches', '--files-without-match', '--type-list'].includes(option))
319
+ if (option === '--files' || option === '--type-list')
320
320
  filesMode = true;
321
321
  const inlineShort = !argument.startsWith('--') && argument.length > 2
322
322
  && (argument[1] === 'e' || argument[1] === 'f' || argument[1] === 'g');
@@ -367,7 +367,12 @@ function analyzeRg(args) {
367
367
  }
368
368
  if (!filesMode && !hasExplicitPattern && !implicitPatternSeen)
369
369
  return null;
370
- if (!inputOperandSeen)
370
+ // Enumeration modes ignore the incoming stream and are never stdin filters.
371
+ if (hasPipelineInput && filesMode)
372
+ return null;
373
+ // Without an explicit path, ripgrep reads stdin when used after a pipe.
374
+ // Standalone searches and `--files` still default to the current directory.
375
+ if (!inputOperandSeen && !hasPipelineInput)
371
376
  paths.push(recursive('.'));
372
377
  return paths;
373
378
  }
@@ -493,6 +498,23 @@ function analyzeSort(args) {
493
498
  }
494
499
  return paths;
495
500
  }
501
+ function analyzeUniq(args) {
502
+ const valueOptions = new Set(['-f', '-s', '-w', '--skip-fields', '--skip-chars', '--check-chars']);
503
+ const allowedFlags = new Set(['-c', '-d', '-D', '-u', '-i', '--count', '--repeated', '--all-repeated', '--unique', '--ignore-case']);
504
+ for (let index = 0; index < args.length; index++) {
505
+ const argument = args[index];
506
+ const option = argument.split('=', 1)[0];
507
+ if (valueOptions.has(option)) {
508
+ const value = argument.includes('=') ? argument.slice(argument.indexOf('=') + 1) : args[++index];
509
+ if (!value || !/^\d+$/.test(value))
510
+ return null;
511
+ }
512
+ else if (!allowedFlags.has(argument)) {
513
+ return null;
514
+ }
515
+ }
516
+ return [];
517
+ }
496
518
  /**
497
519
  * Git metadata queries do not expose file contents and their output paths are
498
520
  * controlled by the repository, not by arbitrary shell operands. Keep this
@@ -828,7 +850,7 @@ function analyzeShellSyntaxCheck(args) {
828
850
  }
829
851
  return paths;
830
852
  }
831
- function analyzeCommand(argv) {
853
+ function analyzeCommand(argv, hasPipelineInput = false) {
832
854
  const executable = normalizeExecutable(argv[0]);
833
855
  if (!executable)
834
856
  return null;
@@ -858,7 +880,7 @@ function analyzeCommand(argv) {
858
880
  purpose = 'search';
859
881
  break;
860
882
  case 'rg':
861
- pathOperands = analyzeRg(args);
883
+ pathOperands = analyzeRg(args, hasPipelineInput);
862
884
  purpose = 'search';
863
885
  break;
864
886
  case 'find':
@@ -882,6 +904,10 @@ function analyzeCommand(argv) {
882
904
  // sort 有路径参数时是文件读取,无路径参数时是纯 stdin 排序
883
905
  purpose = 'stdin-transform';
884
906
  break;
907
+ case 'uniq':
908
+ pathOperands = analyzeUniq(args);
909
+ purpose = 'stdin-transform';
910
+ break;
885
911
  case 'git':
886
912
  pathOperands = analyzeGit(args);
887
913
  purpose = 'vcs-query';
@@ -914,7 +940,7 @@ function analyzeCommand(argv) {
914
940
  // 无路径操作数的命令是纯 stdin→stdout 变换,可安全出现在管道任意位置。
915
941
  // 对于 sort/wc/awk/grep/head/tail/sed:有路径参数时读文件,无路径参数时为 stdin 变换。
916
942
  const stdinTransform = pathOperands.length === 0
917
- && ['sort', 'wc', 'awk', 'grep', 'rg', 'head', 'tail', 'sed'].includes(executable);
943
+ && ['sort', 'uniq', 'wc', 'awk', 'grep', 'rg', 'head', 'tail', 'sed'].includes(executable);
918
944
  // 修正 purpose:stdin 变换时统一标记,避免 'metadata-read'/'content-read' 歧义
919
945
  const resolvedPurpose = stdinTransform ? 'stdin-transform' : purpose;
920
946
  return {
@@ -940,7 +966,7 @@ export function analyzeReadonlyShellQuery(command, options = {}) {
940
966
  const argv = parseStageArgv(stages[index], options);
941
967
  if (!argv)
942
968
  return { kind: 'unproven', reason: 'non-literal-command' };
943
- const analyzed = analyzeCommand(argv);
969
+ const analyzed = analyzeCommand(argv, index > 0);
944
970
  if (!analyzed)
945
971
  return { kind: 'unproven', reason: 'unsupported-command-or-option' };
946
972
  if (index > 0) {
@@ -1337,7 +1337,33 @@ function hClassReadScopeIncludesProtectedPath(value, options) {
1337
1337
  return getExistingHClassMaskTargets(root, { selfAid: options.selfAid }).some(target => isSameOrDescendant(target.path, scope));
1338
1338
  }
1339
1339
  function analyzeShellProtectedOperands(command, options) {
1340
- const analysis = analyzeReadonlyShellQuery(command, { managedTempDir: options.managedTempDir });
1340
+ let analyzedOptions = options;
1341
+ let logDiagnosticRoot;
1342
+ let analysis = analyzeReadonlyShellQuery(command, { managedTempDir: options.managedTempDir });
1343
+ const cdPrefix = command.match(/^\s*cd\s+("(?:[^"\\]|\\.)*"|'[^']*'|[^\s;&|]+)\s*&&\s*([\s\S]+)$/);
1344
+ if (cdPrefix) {
1345
+ const cdArgv = parseLiteralShellArgv(`cd ${cdPrefix[1]}`);
1346
+ const nestedAnalysis = analyzeReadonlyShellQuery(cdPrefix[2], { managedTempDir: options.managedTempDir });
1347
+ const logRoot = resolveProtectedCandidate(path.join(options.root ?? resolveRoot(), 'logs'));
1348
+ if (cdArgv?.length === 2 && !cdArgv[1].startsWith('-') && nestedAnalysis.kind === 'proven-readonly'
1349
+ && isSameOrDescendant(resolveProtectedCandidate(cdArgv[1], options.cwd), logRoot)) {
1350
+ const cwd = resolveProtectedCandidate(cdArgv[1], options.cwd);
1351
+ analyzedOptions = { ...options, cwd };
1352
+ logDiagnosticRoot = logRoot;
1353
+ const pipelines = nestedAnalysis.ir.pipelines.map(pipeline => pipeline.map(query => ({
1354
+ ...query,
1355
+ pathOperands: query.pathOperands.map(operand => ({
1356
+ ...operand,
1357
+ value: resolveProtectedCandidate(operand.value, cwd),
1358
+ })),
1359
+ })));
1360
+ pipelines.unshift([{
1361
+ executable: 'cd', argv: cdArgv, pathOperands: [{ value: cwd, access: 'exact' }],
1362
+ stdinTransform: false, purpose: 'metadata-read', accessKind: 'metadata',
1363
+ }]);
1364
+ analysis = { kind: 'proven-readonly', ir: { pipelines, pathOperands: pipelines.flatMap(pipeline => pipeline.flatMap(query => query.pathOperands)) } };
1365
+ }
1366
+ }
1341
1367
  if (analysis.kind === 'unproven') {
1342
1368
  const pathOptions = { cwd: options.cwd, root: options.root, selfAid: options.selfAid };
1343
1369
  const hClassPath = literalProtectedShellOperand(command, 'h', pathOptions);
@@ -1351,14 +1377,17 @@ function analyzeShellProtectedOperands(command, options) {
1351
1377
  };
1352
1378
  }
1353
1379
  const operands = analysis.ir.pipelines.flatMap(pipeline => pipeline.flatMap(query => {
1354
- const scopes = boundedRgSourceScopes(query, options);
1380
+ const scopes = boundedRgSourceScopes(query, analyzedOptions);
1355
1381
  return (scopes ?? query.pathOperands).map(operand => ({
1356
1382
  operand,
1357
1383
  accessKind: query.accessKind ?? (operand.access === 'recursive' ? 'enumerate' : 'content'),
1358
1384
  }));
1359
1385
  }));
1360
- const hClassPath = operands.map(({ operand, accessKind }) => shellOperandMatchesClass(operand, 'h', options, accessKind)).find(Boolean);
1361
- const lClassPath = operands.map(({ operand, accessKind }) => shellOperandMatchesClass(operand, 'l', options, accessKind)).find(Boolean);
1386
+ const hClassPath = operands.map(({ operand, accessKind }) => shellOperandMatchesClass(operand, 'h', analyzedOptions, accessKind)).find(Boolean);
1387
+ const lClassPath = operands.map(({ operand, accessKind }) => shellOperandMatchesClass(operand, 'l', analyzedOptions, accessKind)).find(Boolean);
1388
+ if (logDiagnosticRoot && operands.some(({ operand }) => !isSameOrDescendant(resolveProtectedCandidate(operand.value, analyzedOptions.cwd), logDiagnosticRoot))) {
1389
+ analysis = { kind: 'unproven', reason: 'log-diagnostic-scope-escape' };
1390
+ }
1362
1391
  return {
1363
1392
  analysis,
1364
1393
  hClass: !!hClassPath,
@@ -2250,6 +2279,14 @@ function managedTempOptions(context) {
2250
2279
  : process.env,
2251
2280
  };
2252
2281
  }
2282
+ function summarizeShellSegments(command) {
2283
+ const safeExecutables = new Set(['ec', 'head', 'tail', 'echo', 'rg', 'grep', 'sort', 'uniq', 'cut', 'wc', 'tr', 'pwd', 'cd']);
2284
+ return splitShellCommandSegments(command).slice(0, 8).map((segment, index) => {
2285
+ const words = parseShellWords(segment);
2286
+ const executable = safeExecutables.has(words[0]) ? words[0] : 'unknown';
2287
+ return `${index + 1}:${executable}/${Math.max(0, words.length - 1)}`;
2288
+ });
2289
+ }
2253
2290
  /**
2254
2291
  * 校验 `cd <dir> && ec ...` 白名单里的目录。
2255
2292
  *
@@ -2482,6 +2519,7 @@ export function evaluateToolPreflight(toolName, input, context) {
2482
2519
  message: '🔒 文件修改目标必须位于当前 workspace 或会话 $TMPDIR 内',
2483
2520
  policyCode: fileMutation.source === 'file-change' ? 'file_change_workspace_escape' : 'apply_patch_workspace_escape',
2484
2521
  errorDetailCode: 'APPLY_PATCH_WORKSPACE_ESCAPE', matchedPath: escapedPath,
2522
+ matchedRule: 'file-mutation-workspace-boundary',
2485
2523
  };
2486
2524
  }
2487
2525
  for (const candidate of fileMutation.paths) {
@@ -2611,7 +2649,12 @@ export function evaluateToolPreflight(toolName, input, context) {
2611
2649
  if (ecCommand.kind === 'cd-prefixed') {
2612
2650
  const cwdError = validateCdPrefixedCwd(ecCommand.cwd, context);
2613
2651
  if (cwdError) {
2614
- return { behavior: 'deny', input, message: cwdError, policyCode: 'ec_shell_composite_command' };
2652
+ return {
2653
+ behavior: 'deny', input, message: cwdError, policyCode: 'ec_shell_composite_command',
2654
+ matchedPath: resolveProtectedCandidate(ecCommand.cwd, context.projectPath),
2655
+ matchedRule: 'ec-cwd-outside-workspace',
2656
+ parsedSegments: summarizeShellSegments(policyCommand),
2657
+ };
2615
2658
  }
2616
2659
  return prepareBoundedOutputInput(input, ecCommand.command, 'ec', context);
2617
2660
  }
@@ -2666,6 +2709,8 @@ export function evaluateToolPreflight(toolName, input, context) {
2666
2709
  input,
2667
2710
  message,
2668
2711
  policyCode: 'ec_shell_composite_command',
2712
+ matchedRule: `ec-shell-${ecCommand.issue}`,
2713
+ parsedSegments: summarizeShellSegments(policyCommand),
2669
2714
  };
2670
2715
  }
2671
2716
  const boundedOutput = parseBoundedOutputShellCommand(command);
@@ -0,0 +1,127 @@
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
+ if (!profiles.every(profile => profile.type === 'agent'
77
+ && typeof profile.exttype === 'string' && /^pa\.[^\s.][^\s]*$/i.test(profile.exttype.trim())))
78
+ return 'unmatched';
79
+ const consensuses = await Promise.all([selfAid, peerAid].map(aid => runtime.client.checkOwnershipConsensus(aid, true)));
80
+ for (const [index, consensus] of consensuses.entries()) {
81
+ const digest = createHash('sha256').update(cards[index].content, 'utf8').digest('hex');
82
+ if (consensus.status !== 'consensus' || consensus.sub_aid !== [selfAid, peerAid][index]
83
+ || consensus.lock !== 'locked' || !consensus.owner_aid || !isValidAid(consensus.owner_aid)
84
+ || !Number.isSafeInteger(consensus.relation_version) || consensus.relation_version < 1
85
+ || consensus.agent_md_sha256 !== digest
86
+ || profiles[index].owner !== consensus.owner_aid)
87
+ return 'unavailable';
88
+ }
89
+ return consensuses[0].owner_aid === consensuses[1].owner_aid ? 'matched' : 'unmatched';
90
+ };
91
+ const task = (async () => {
92
+ let timeout;
93
+ let qualification = 'unavailable';
94
+ try {
95
+ qualification = await Promise.race([query(), new Promise(resolve => {
96
+ timeout = setTimeout(() => resolve('unavailable'), PA_TEAM_TIMEOUT_MS);
97
+ timeout.unref?.();
98
+ })]);
99
+ }
100
+ catch {
101
+ qualification = 'unavailable';
102
+ }
103
+ finally {
104
+ if (timeout)
105
+ clearTimeout(timeout);
106
+ }
107
+ if (runtimes.get(selfAid) !== runtime || runtime.generation !== generation || !runtime.client.isReady)
108
+ return;
109
+ if (qualification === 'matched')
110
+ runtime.knownTeams.add(peerAid);
111
+ if (qualification === 'unmatched')
112
+ runtime.knownTeams.delete(peerAid);
113
+ runtime.entries.set(peerAid, {
114
+ qualification,
115
+ expiresAt: startedAt + (qualification === 'unavailable' ? 2_000 : PA_TEAM_MAX_AGE_MS),
116
+ revision: ++revision,
117
+ });
118
+ })();
119
+ runtime.pending.set(peerAid, task);
120
+ try {
121
+ await task;
122
+ }
123
+ finally {
124
+ if (runtime.pending.get(peerAid) === task)
125
+ runtime.pending.delete(peerAid);
126
+ }
127
+ }