evolcore 0.0.43-test.3 → 0.0.43-test.5

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 (192) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/bin/ecmsg.js +492 -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 +12 -54
  10. package/dist/agents/ecagent-runner.js +130 -35
  11. package/dist/aun/aid/agentmd.js +56 -12
  12. package/dist/aun/aid/control-aid.js +15 -0
  13. package/dist/aun/aid/identity.js +8 -0
  14. package/dist/aun/aid/ownership-operation.js +12 -3
  15. package/dist/aun/menu/client.js +8 -7
  16. package/dist/aun/menu/index.js +1 -1
  17. package/dist/aun/menu/transport.js +8 -5
  18. package/dist/aun/service-proxy.js +3 -0
  19. package/dist/channels/aun.js +56 -22
  20. package/dist/channels/daemon.js +12 -4
  21. package/dist/cli/agent-command.js +5 -0
  22. package/dist/cli/agent-create.js +32 -8
  23. package/dist/cli/agent.js +9 -3
  24. package/dist/cli/aid-bind-command.js +3 -0
  25. package/dist/cli/aun-commands.js +12 -5
  26. package/dist/cli/code-stats.js +451 -213
  27. package/dist/cli/ctl-command.js +1 -3
  28. package/dist/cli/daemon-commands.js +42 -21
  29. package/dist/cli/directory.js +7 -8
  30. package/dist/cli/ecmsg-gateway.js +204 -0
  31. package/dist/cli/getmeta-command.js +2 -1
  32. package/dist/cli/index.js +6 -0
  33. package/dist/cli/init.js +58 -18
  34. package/dist/cli/provider-command.js +82 -5
  35. package/dist/cli/restart-monitor.js +11 -19
  36. package/dist/cli/stats.js +8 -1
  37. package/dist/cli/task-context.js +3 -0
  38. package/dist/cli/trigger-command.js +20 -14
  39. package/dist/config/boot-log.js +23 -2
  40. package/dist/config/config-field-policy.js +2 -0
  41. package/dist/config/config-manager.js +13 -17
  42. package/dist/config/daemon-services.js +1 -0
  43. package/dist/config/peer-role-resolver.js +6 -6
  44. package/dist/config/provider-identity-migration.js +202 -0
  45. package/dist/config/provider-identity.js +37 -0
  46. package/dist/config/provider-ipc-service.js +40 -3
  47. package/dist/config/provider-local-sync.js +153 -0
  48. package/dist/config/providers-config.js +32 -4
  49. package/dist/config/providers-management.js +144 -68
  50. package/dist/config/providers.js +4 -1
  51. package/dist/config/role-schema.js +3 -3
  52. package/dist/config/schema-migration.js +188 -3
  53. package/dist/core/agent-application-service.js +11 -0
  54. package/dist/core/agent-ipc-registration.js +2 -0
  55. package/dist/core/agent-runtime.js +45 -11
  56. package/dist/core/auth/auth-gateway.js +8 -6
  57. package/dist/core/auth/delegation-diagnostics.js +6 -2
  58. package/dist/core/auth/operation-authorizer.js +5 -2
  59. package/dist/core/auth/operation-catalog.js +6 -4
  60. package/dist/core/baseagent-loader.js +11 -3
  61. package/dist/core/bootstrap-service.js +8 -0
  62. package/dist/core/channel-loader.js +61 -23
  63. package/dist/core/command/agent-control.js +4 -1
  64. package/dist/core/command/chatmode-config.js +46 -0
  65. package/dist/core/command/cli-intent-parser.js +2 -1
  66. package/dist/core/command/command-handler.js +16 -20
  67. package/dist/core/command/daemon-diagnostics.js +2 -1
  68. package/dist/core/command/menu-catalog.js +1 -1
  69. package/dist/core/command/menu-handler.js +16 -16
  70. package/dist/core/command/menu-protocol.js +4 -2
  71. package/dist/core/command/provider-menu.js +4 -2
  72. package/dist/core/command/role-menu.js +2 -2
  73. package/dist/core/command/slash-handler.js +56 -42
  74. package/dist/core/daemon-lifecycle.js +35 -17
  75. package/dist/core/event-catalog.js +19 -0
  76. package/dist/core/evolagent-registry.js +3 -0
  77. package/dist/core/handoff/runtime.js +9 -3
  78. package/dist/core/initialization/service.js +4 -3
  79. package/dist/core/ipc-registration.js +6 -0
  80. package/dist/core/message/aun-ipc-sender.js +81 -3
  81. package/dist/core/message/im-renderer.js +24 -19
  82. package/dist/core/message/message-admission.js +13 -2
  83. package/dist/core/message/response-engine.js +40 -41
  84. package/dist/core/message/send-options.js +40 -0
  85. package/dist/core/message/send-routing.js +310 -0
  86. package/dist/core/model/model-capabilities.js +37 -0
  87. package/dist/core/model/model-catalog.js +6 -2
  88. package/dist/core/ownership/owner-resolver.js +117 -14
  89. package/dist/core/permission/ec-command-parser.js +195 -27
  90. package/dist/core/permission/readonly-shell-query.js +66 -7
  91. package/dist/core/permission/tool-error-code.js +13 -1
  92. package/dist/core/permission/tool-policy.js +74 -20
  93. package/dist/core/plugin-lifecycle.js +6 -2
  94. package/dist/core/relation/pa-team.js +7 -2
  95. package/dist/core/relation/same-owner-proof.js +131 -0
  96. package/dist/core/session/session-idle-monitor.js +94 -16
  97. package/dist/core/session/session-manager.js +69 -16
  98. package/dist/core/thread/thread-route.js +5 -2
  99. package/dist/directory/owner-directory-cache.js +690 -99
  100. package/dist/directory/owner-directory-markdown.js +146 -36
  101. package/dist/directory/owner-directory-query-operation.js +7 -9
  102. package/dist/directory/owner-directory-scope.js +12 -0
  103. package/dist/directory/owner-directory-search.js +5 -1
  104. package/dist/directory/owner-directory-store.js +28 -0
  105. package/dist/ecweb/basic-settings-service.js +15 -1
  106. package/dist/ecweb/message-context-service.js +2 -2
  107. package/dist/ecweb/providers-service.js +3 -1
  108. package/dist/ecweb/runtime/lifecycle.js +38 -5
  109. package/dist/ecweb/runtime/supervisor.js +157 -49
  110. package/dist/index.js +202 -38
  111. package/dist/paths.js +2 -1
  112. package/dist/proxy/manager.js +2 -0
  113. package/dist/proxy/service-supervisor.js +379 -143
  114. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  115. package/dist/trigger/application-service.js +1 -0
  116. package/dist/trigger/audit.js +3 -2
  117. package/dist/trigger/authorization.js +2 -3
  118. package/dist/trigger/event-source.js +4 -0
  119. package/dist/trigger/feedback.js +26 -2
  120. package/dist/trigger/history.js +4 -3
  121. package/dist/trigger/ipc-service.js +24 -19
  122. package/dist/trigger/manager.js +3 -5
  123. package/dist/trigger/parser.js +4 -21
  124. package/dist/trigger/patch.js +3 -15
  125. package/dist/trigger/scheduler.js +48 -13
  126. package/dist/trigger/system-definitions.js +2 -2
  127. package/dist/trigger/validation.js +4 -13
  128. package/dist/utils/autostart.js +2 -2
  129. package/dist/utils/cross-platform.js +36 -8
  130. package/dist/utils/error-utils.js +8 -0
  131. package/dist/utils/macos-autostart.js +31 -0
  132. package/dist/utils/model-prices.jsonl +15 -8
  133. package/dist/utils/process-introspect.js +21 -1
  134. package/dist/utils/public-suffix.js +5811 -0
  135. package/dist/utils/startup-trace.js +7 -1
  136. package/dist/utils/windows-autostart.js +42 -7
  137. package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
  138. package/ecagent/dist/harness/compaction/compaction.js +4 -4
  139. package/ecagent/dist/harness/env/nodejs.js +46 -2
  140. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  141. package/kits/docs/channels/aun.md +1 -1
  142. package/kits/docs/channels/feishu.md +2 -2
  143. package/kits/docs/context-assembly.md +20 -4
  144. package/kits/docs/evolcore/INDEX.md +3 -2
  145. package/kits/docs/evolcore/agent.md +2 -2
  146. package/kits/docs/evolcore/aid.md +8 -2
  147. package/kits/docs/evolcore/ctl.md +13 -4
  148. package/kits/docs/evolcore/directory.md +48 -15
  149. package/kits/docs/evolcore/file-navigation.md +63 -49
  150. package/kits/docs/evolcore/group.md +6 -6
  151. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  152. package/kits/docs/evolcore/menu-protocol.md +33 -3
  153. package/kits/docs/evolcore/model.md +5 -3
  154. package/kits/docs/evolcore/msg.md +28 -27
  155. package/kits/docs/evolcore/provider.md +39 -5
  156. package/kits/docs/evolcore/response.md +3 -1
  157. package/kits/docs/evolcore/thread-chain.md +12 -14
  158. package/kits/docs/evolcore/tool-authorization.md +21 -1
  159. package/kits/docs/evolcore/trigger.md +12 -9
  160. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  161. package/kits/docs/prompt-loading-architecture.md +30 -20
  162. package/kits/eck_manifest.auxiliary.json +5 -5
  163. package/kits/eck_manifest.json +28 -49
  164. package/kits/eck_manifest.memory.json +18 -18
  165. package/kits/rules/01-overview.md +43 -45
  166. package/kits/rules/02-navigation.md +44 -53
  167. package/kits/rules/03-identity.md +21 -25
  168. package/kits/rules/04-relation.md +23 -33
  169. package/kits/rules/05-venue.md +24 -25
  170. package/kits/rules/06-channel.md +3 -3
  171. package/kits/schemas/_meta.json +20 -27
  172. package/kits/schemas/agent-config.schema.19.json +10 -6
  173. package/kits/schemas/providers.schema.2.json +74 -0
  174. package/kits/schemas/relation-config.schema.12.json +2 -2
  175. package/kits/schemas/role-config.schema.2.json +5 -5
  176. package/kits/schemas/role-registry.schema.1.json +1 -1
  177. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  178. package/kits/skills/ec-service-proxy/SKILL.md +3 -0
  179. package/kits/skills/ec-trigger/SKILL.md +4 -4
  180. package/kits/skills/ec-trigger/references/examples.md +1 -1
  181. package/kits/templates/system-fragments/channel.md +5 -5
  182. package/kits/templates/system-fragments/commands.md +3 -2
  183. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  184. package/kits/templates/system-fragments/identity.md +0 -1
  185. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  186. package/kits/templates/system-fragments/reply.md +47 -28
  187. package/kits/templates/system-fragments/session.md +2 -9
  188. package/kits/templates/system-fragments/thread.md +5 -5
  189. package/package.json +17 -13
  190. package/kits/schemas/agent-config.schema.20.json +0 -925
  191. package/kits/schemas/relation-config.schema.13.json +0 -289
  192. package/kits/schemas/role-config.schema.3.json +0 -1038
@@ -5,6 +5,7 @@ const MAX_PIPELINE_STAGES = 3;
5
5
  const SUPPORTED_EXECUTABLES = new Set([
6
6
  'echo', 'pwd', 'ls', 'cat', 'grep', 'rg', 'find', 'sed', 'head', 'tail', 'sort', 'uniq', 'git', 'wc', 'stat', 'lstat', 'awk',
7
7
  'bash', 'sh',
8
+ 'ps', 'pgrep', 'env',
8
9
  ]);
9
10
  const FIND_MUTATING_PRIMARY_RE = /^-(?:delete|exec|execdir|ok|okdir|fprint|fprint0|fprintf|fls)$/;
10
11
  const RG_PROCESS_SPAWNING_OPTION_RE = /^(?:--pre|--hostname-bin|--pre-glob|--search-zip)(?:=|$)/;
@@ -279,6 +280,8 @@ function analyzeGrep(args) {
279
280
  return paths;
280
281
  }
281
282
  function analyzeRg(args, hasPipelineInput = false) {
283
+ if (args.length === 1 && ['--help', '-h', '--version', '-V', '--type-list'].includes(args[0]))
284
+ return [];
282
285
  if (args.some(argument => RG_PROCESS_SPAWNING_OPTION_RE.test(argument)
283
286
  || argument === '--follow'
284
287
  // `-z` is the short form of `--search-zip`; it may also appear in a
@@ -367,15 +370,64 @@ function analyzeRg(args, hasPipelineInput = false) {
367
370
  }
368
371
  if (!filesMode && !hasExplicitPattern && !implicitPatternSeen)
369
372
  return null;
370
- // Enumeration modes ignore the incoming stream and are never stdin filters.
371
- if (hasPipelineInput && filesMode)
372
- return null;
373
373
  // Without an explicit path, ripgrep reads stdin when used after a pipe.
374
374
  // Standalone searches and `--files` still default to the current directory.
375
- if (!inputOperandSeen && !hasPipelineInput)
376
- paths.push(recursive('.'));
375
+ if (!inputOperandSeen && (!hasPipelineInput || filesMode))
376
+ paths.push({ ...recursive('.'), implicit: true });
377
377
  return paths;
378
378
  }
379
+ /** Process/environment queries have no filesystem operands or child command. */
380
+ function analyzeProcessQuery(executable, args) {
381
+ if (executable === 'env') {
382
+ // `env NAME=value command`, -S and -C can execute/change scope. Only
383
+ // printing the current environment is a passthrough query.
384
+ return args.every(arg => ['-0', '--null'].includes(arg)) ? [] : null;
385
+ }
386
+ if (executable === 'ps') {
387
+ const flags = new Set(['-e', '-A', '-a', '-x', '-f', '-l', '-w', '-ww', '--no-headers', '--headers', '--forest']);
388
+ const values = new Set(['-o', '-eo', '-efo', '--format', '-p', '--pid', '--ppid', '-u', '--user', '-U', '--User', '-C', '--sort']);
389
+ for (let index = 0; index < args.length; index++) {
390
+ const arg = args[index];
391
+ const option = arg.split('=', 1)[0];
392
+ if (values.has(option)) {
393
+ const value = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++index];
394
+ if (!value || value.startsWith('-'))
395
+ return null;
396
+ }
397
+ else if (!flags.has(arg) && !/^-[eAaxflw]+$/.test(arg) && !/^[auxflw]+$/.test(arg))
398
+ return null;
399
+ }
400
+ return [];
401
+ }
402
+ // pgrep -F/--pidfile and --logpidfile read files; -L depends on them.
403
+ // Keep only process selectors and one literal matching expression.
404
+ let pattern = false;
405
+ let optionsEnded = false;
406
+ const values = new Set(['-P', '--parent', '-u', '--euid', '-U', '--uid', '-g', '--pgroup', '-s', '--session', '-t', '--terminal', '-d', '--delimiter', '-r', '--runstates']);
407
+ const flags = new Set(['--full', '--list-full', '--list-name', '--count', '--exact', '--ignore-case', '--newest', '--oldest', '--inverse']);
408
+ for (let index = 0; index < args.length; index++) {
409
+ const arg = args[index];
410
+ if (!optionsEnded && arg === '--') {
411
+ optionsEnded = true;
412
+ continue;
413
+ }
414
+ const option = arg.split('=', 1)[0];
415
+ if (!optionsEnded && values.has(option)) {
416
+ const value = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : args[++index];
417
+ if (!value || value.startsWith('-'))
418
+ return null;
419
+ }
420
+ else if (!optionsEnded && (flags.has(arg) || /^-[aflcxinov]+$/.test(arg))) {
421
+ continue;
422
+ }
423
+ else {
424
+ if ((!optionsEnded && arg.startsWith('-')) || pattern)
425
+ return null;
426
+ pattern = true;
427
+ }
428
+ }
429
+ return pattern ? [] : null;
430
+ }
379
431
  function analyzeFind(args) {
380
432
  if (args.some(argument => FIND_MUTATING_PRIMARY_RE.test(argument)))
381
433
  return null;
@@ -859,6 +911,12 @@ function analyzeCommand(argv, hasPipelineInput = false) {
859
911
  let accessKind = 'content';
860
912
  let purpose = 'unknown';
861
913
  switch (executable) {
914
+ case 'ps':
915
+ case 'pgrep':
916
+ case 'env':
917
+ pathOperands = analyzeProcessQuery(executable, args);
918
+ purpose = 'passthrough';
919
+ break;
862
920
  case 'echo':
863
921
  pathOperands = [];
864
922
  purpose = 'passthrough';
@@ -940,7 +998,8 @@ function analyzeCommand(argv, hasPipelineInput = false) {
940
998
  // 无路径操作数的命令是纯 stdin→stdout 变换,可安全出现在管道任意位置。
941
999
  // 对于 sort/wc/awk/grep/head/tail/sed:有路径参数时读文件,无路径参数时为 stdin 变换。
942
1000
  const stdinTransform = pathOperands.length === 0
943
- && ['sort', 'uniq', 'wc', 'awk', 'grep', 'rg', 'head', 'tail', 'sed'].includes(executable);
1001
+ && ['sort', 'uniq', 'wc', 'awk', 'grep', 'rg', 'head', 'tail', 'sed'].includes(executable)
1002
+ && !(executable === 'rg' && args.some(arg => ['--files', '--type-list', '--help', '-h', '--version', '-V'].includes(arg)));
944
1003
  // 修正 purpose:stdin 变换时统一标记,避免 'metadata-read'/'content-read' 歧义
945
1004
  const resolvedPurpose = stdinTransform ? 'stdin-transform' : purpose;
946
1005
  return {
@@ -966,7 +1025,7 @@ export function analyzeReadonlyShellQuery(command, options = {}) {
966
1025
  const argv = parseStageArgv(stages[index], options);
967
1026
  if (!argv)
968
1027
  return { kind: 'unproven', reason: 'non-literal-command' };
969
- const analyzed = analyzeCommand(argv, index > 0);
1028
+ const analyzed = analyzeCommand(argv, index > 0 || options.hasPipelineInput === true);
970
1029
  if (!analyzed)
971
1030
  return { kind: 'unproven', reason: 'unsupported-command-or-option' };
972
1031
  if (index > 0) {
@@ -44,12 +44,19 @@ const PERMISSION_ERROR_CODES = new Set([
44
44
  'APPROVAL_TIMEOUT',
45
45
  'DELEGATION_FAILED',
46
46
  ]);
47
+ const INVALID_ARGUMENT_POLICY_CODES = new Set([
48
+ 'apply_patch_invalid_argument',
49
+ 'apply_patch_unparseable',
50
+ 'file_change_invalid_argument',
51
+ ]);
47
52
  const DETAIL_CODE_BY_POLICY_CODE = {
48
53
  h_class_protection: 'H_CLASS_PROTECTION',
54
+ shell_implicit_cwd: 'IMPLICIT_CWD',
49
55
  l_class_protection: 'L_CLASS_PROTECTION',
50
56
  native_file_change_required: 'NATIVE_FILE_CHANGE_REQUIRED',
51
57
  apply_patch_invalid_argument: 'INVALID_ARGUMENT',
52
58
  apply_patch_unparseable: 'APPLY_PATCH_UNPARSEABLE',
59
+ file_change_invalid_argument: 'INVALID_ARGUMENT',
53
60
  apply_patch_workspace_escape: 'APPLY_PATCH_WORKSPACE_ESCAPE',
54
61
  ec_shell_invalid_quote: 'INVALID_QUOTE',
55
62
  ec_command_not_canonical: 'INVALID_ARGUMENT',
@@ -121,7 +128,12 @@ export function normalizeToolErrorClassification(input) {
121
128
  if (explicitPermission && facts.started)
122
129
  classificationConflict = true;
123
130
  let errorCode;
124
- if (explicitPermission) {
131
+ if (decisionSource === 'policy' && facts.blocked && !facts.started
132
+ && typeof input.policyCode === 'string' && INVALID_ARGUMENT_POLICY_CODES.has(input.policyCode)
133
+ && (explicit === undefined || explicit === 'POLICY_DENIED' || explicit === 'INVALID_ARGUMENT')) {
134
+ errorCode = 'INVALID_ARGUMENT';
135
+ }
136
+ else if (explicitPermission) {
125
137
  errorCode = exactPermissionBlock && !facts.started
126
138
  ? explicit
127
139
  : 'EXECUTION_FAILED';
@@ -43,6 +43,26 @@ export function expandManagedTempPath(value, options = {}) {
43
43
  }
44
44
  const WRITE_INTENT_RE = /(?:^|[\s;&|])(?:mkdir|mktemp|touch|tee|cp|mv|install|chmod|chown|ln|rm)(?:[\s;&|]|$)|(?:^|[\s])(?:\d>>?|>>?)\s*/i;
45
45
  const TEMP_TOKEN_RE = /(?:\$TMPDIR|\$\{TMPDIR\}|\/(?:[^\s'";&|<>)]*\/)?(?:tmp|var\/tmp|dev\/shm)(?:\/|$))[^\s'";&|<>)]*/g;
46
+ /** Strip only literal trailing output redirects from a proven query. */
47
+ function readonlyStageWriteTargets(stage, managedTempDir) {
48
+ let query = stage.text;
49
+ const targets = [];
50
+ const options = { managedTempDir, hasPipelineInput: stage.hasPipelineInput };
51
+ while (true) {
52
+ if (analyzeReadonlyShellQuery(query, options).kind === 'proven-readonly')
53
+ return targets;
54
+ const match = query.match(/^(.*?)[ \t]+(?:[012])?>>?[ \t]*("[^"\r\n]*"|'[^'\r\n]*'|[^\s'"<>;&|]+)[ \t]*$/);
55
+ if (!match)
56
+ return undefined;
57
+ const argv = parseLiteralShellArgv(match[2], managedTempDir
58
+ ? { allowManagedTmpDir: true, managedTempDir } : undefined);
59
+ if (argv?.length !== 1)
60
+ return undefined;
61
+ if (argv[0] !== '/dev/null')
62
+ targets.push(argv[0]);
63
+ query = match[1];
64
+ }
65
+ }
46
66
  function windowsTempRoots(options) {
47
67
  if (process.platform !== 'win32')
48
68
  return [];
@@ -60,7 +80,15 @@ export function checkManagedTempShellCommand(command, options = {}) {
60
80
  if (!WRITE_INTENT_RE.test(command))
61
81
  return { kind: 'none' };
62
82
  const root = resolveManagedTempDir(options.env);
63
- const normalized = substituteTmpDir(command, root);
83
+ // Inspect each stage independently. A readonly query's path/pattern
84
+ // operands are not write targets, even when another stage writes output.
85
+ // The query parser only permits the inert stderr sink `2>/dev/null`.
86
+ const writeOperands = splitShellCommandStages(command).flatMap(stage => {
87
+ if (!WRITE_INTENT_RE.test(stage.text))
88
+ return [];
89
+ return readonlyStageWriteTargets(stage, root) ?? [stage.text];
90
+ });
91
+ const normalized = substituteTmpDir(writeOperands.join('; '), root);
64
92
  const candidates = [...normalized.matchAll(TEMP_TOKEN_RE)].map(match => match[0].replace(/[.,:]+$/, ''));
65
93
  // Windows has no portable `/tmp` spelling. Treat absolute paths below the
66
94
  // host temporary roots as temporary operands too, so a sibling session
@@ -397,14 +425,18 @@ const DANGEROUS_PATTERNS = [
397
425
  { kind: 'reg-delete', pattern: /\breg\s+delete/i, reason: '删除注册表项(Windows 系统配置)', approvalScope: 'request' },
398
426
  ];
399
427
  function splitShellCommandSegments(command) {
428
+ return splitShellCommandStages(command).map(stage => stage.text);
429
+ }
430
+ function splitShellCommandStages(command) {
400
431
  const segments = [];
432
+ let hasPipelineInput = false;
401
433
  let segment = '';
402
434
  let quote = null;
403
435
  let escaped = false;
404
436
  let substitutionDepth = 0;
405
437
  const finish = () => {
406
438
  if (segment.trim())
407
- segments.push(segment.trim());
439
+ segments.push({ text: segment.trim(), hasPipelineInput });
408
440
  segment = '';
409
441
  };
410
442
  for (let index = 0; index < command.length; index++) {
@@ -449,6 +481,7 @@ function splitShellCommandSegments(command) {
449
481
  }
450
482
  if (substitutionDepth === 0 && (char === ';' || char === '\n' || char === '|' || char === '&')) {
451
483
  finish();
484
+ hasPipelineInput = char === '|' && command[index + 1] !== '|';
452
485
  if ((char === '|' || char === '&') && command[index + 1] === char)
453
486
  index++;
454
487
  continue;
@@ -1194,21 +1227,27 @@ function literalScriptFilesystemOperands(argv) {
1194
1227
  * explicit literal path in an otherwise unsupported command.
1195
1228
  */
1196
1229
  function literalProtectedShellOperand(command, className, options, depth = 0) {
1197
- for (const segment of splitShellCommandSegments(command)) {
1230
+ let implicitMatch;
1231
+ for (const stage of splitShellCommandStages(command)) {
1232
+ const segment = stage.text;
1198
1233
  for (const value of literalShellRedirectOperands(segment)) {
1199
1234
  const matched = protectedClassPath(value, className, options);
1200
1235
  if (matched)
1201
- return matched;
1236
+ return { path: matched };
1202
1237
  }
1203
1238
  // A segment that is itself a proven readonly query already has precise
1204
1239
  // path operands. Reusing that IR avoids treating patterns/revisions as
1205
1240
  // paths and also lets a valid segment coexist with a protected one.
1206
- const segmentAnalysis = analyzeReadonlyShellQuery(segment);
1241
+ const segmentAnalysis = analyzeReadonlyShellQuery(segment, { hasPipelineInput: stage.hasPipelineInput });
1207
1242
  if (segmentAnalysis.kind === 'proven-readonly') {
1208
1243
  for (const operand of queryPathOperands(segmentAnalysis)) {
1209
1244
  const matched = shellOperandMatchesClass(operand.operand, className, options, operand.accessKind);
1210
- if (matched)
1211
- return matched;
1245
+ if (matched) {
1246
+ if (operand.operand.implicit)
1247
+ implicitMatch = { path: resolveProtectedCandidate('.', options.cwd), implicitCwd: true };
1248
+ else
1249
+ return { path: matched };
1250
+ }
1212
1251
  }
1213
1252
  continue;
1214
1253
  }
@@ -1218,12 +1257,12 @@ function literalProtectedShellOperand(command, className, options, depth = 0) {
1218
1257
  for (const value of literalMutationOperands(argv)) {
1219
1258
  const matched = protectedClassPath(value, className, options);
1220
1259
  if (matched)
1221
- return matched;
1260
+ return { path: matched };
1222
1261
  }
1223
1262
  for (const value of literalReadonlyOperands(argv)) {
1224
1263
  const matched = protectedClassPath(value, className, options);
1225
1264
  if (matched)
1226
- return matched;
1265
+ return { path: matched };
1227
1266
  if (className === 'h' && commandName(argv[0]) === 'rg'
1228
1267
  && hClassReadScopeIncludesProtectedPath(value, options)) {
1229
1268
  const root = resolveProtectedCandidate(options.root ?? resolveRoot());
@@ -1231,13 +1270,13 @@ function literalProtectedShellOperand(command, className, options, depth = 0) {
1231
1270
  const target = getExistingHClassMaskTargets(root, { selfAid: options.selfAid })
1232
1271
  .find(candidate => isSameOrDescendant(candidate.path, scope));
1233
1272
  if (target)
1234
- return target.path;
1273
+ return { path: target.path };
1235
1274
  }
1236
1275
  }
1237
1276
  for (const value of literalScriptFilesystemOperands(argv)) {
1238
1277
  const matched = protectedClassPath(value, className, options);
1239
1278
  if (matched)
1240
- return matched;
1279
+ return { path: matched };
1241
1280
  }
1242
1281
  // Explicit nested shell carriers are parsed recursively. A nested query
1243
1282
  // still goes through the same segment-aware rules; arbitrary unsupported
@@ -1249,13 +1288,15 @@ function literalProtectedShellOperand(command, className, options, depth = 0) {
1249
1288
  const nested = commandIndex >= 0 ? argv[commandIndex + 1] : undefined;
1250
1289
  if (nested) {
1251
1290
  const matched = literalProtectedShellOperand(nested, className, options, depth + 1);
1252
- if (matched)
1291
+ if (matched?.implicitCwd)
1292
+ implicitMatch = { path: matched.path, implicitCwd: true };
1293
+ else if (matched)
1253
1294
  return matched;
1254
1295
  }
1255
1296
  }
1256
1297
  }
1257
1298
  }
1258
- return undefined;
1299
+ return implicitMatch;
1259
1300
  }
1260
1301
  function shellOperandMatchesClass(operand, className, options, accessKind = operand.access === 'recursive' ? 'enumerate' : 'content') {
1261
1302
  // `$TMPDIR` is a private session namespace, so names such as `CA` or
@@ -1372,8 +1413,9 @@ function analyzeShellProtectedOperands(command, options) {
1372
1413
  analysis,
1373
1414
  hClass: !!hClassPath,
1374
1415
  lClass: !!lClassPath,
1375
- hClassPath,
1376
- lClassPath,
1416
+ hClassPath: hClassPath?.path,
1417
+ lClassPath: lClassPath?.path,
1418
+ implicitCwd: hClassPath?.implicitCwd,
1377
1419
  };
1378
1420
  }
1379
1421
  const operands = analysis.ir.pipelines.flatMap(pipeline => pipeline.flatMap(query => {
@@ -1383,7 +1425,11 @@ function analyzeShellProtectedOperands(command, options) {
1383
1425
  accessKind: query.accessKind ?? (operand.access === 'recursive' ? 'enumerate' : 'content'),
1384
1426
  }));
1385
1427
  }));
1386
- const hClassPath = operands.map(({ operand, accessKind }) => shellOperandMatchesClass(operand, 'h', analyzedOptions, accessKind)).find(Boolean);
1428
+ const hMatches = operands.map(({ operand, accessKind }) => ({ operand,
1429
+ path: shellOperandMatchesClass(operand, 'h', analyzedOptions, accessKind) })).filter(item => item.path);
1430
+ const hMatch = hMatches.find(item => !item.operand.implicit) ?? hMatches[0];
1431
+ const hClassPath = hMatch?.operand.implicit
1432
+ ? resolveProtectedCandidate('.', analyzedOptions.cwd) : hMatch?.path;
1387
1433
  const lClassPath = operands.map(({ operand, accessKind }) => shellOperandMatchesClass(operand, 'l', analyzedOptions, accessKind)).find(Boolean);
1388
1434
  if (logDiagnosticRoot && operands.some(({ operand }) => !isSameOrDescendant(resolveProtectedCandidate(operand.value, analyzedOptions.cwd), logDiagnosticRoot))) {
1389
1435
  analysis = { kind: 'unproven', reason: 'log-diagnostic-scope-escape' };
@@ -1394,6 +1440,7 @@ function analyzeShellProtectedOperands(command, options) {
1394
1440
  lClass: !!lClassPath,
1395
1441
  hClassPath,
1396
1442
  lClassPath,
1443
+ implicitCwd: hMatch?.operand.implicit,
1397
1444
  };
1398
1445
  }
1399
1446
  function protectedReadToolPaths(toolName, input) {
@@ -1720,6 +1767,9 @@ export function checkReadonly(toolName, input, projectPath, context) {
1720
1767
  }
1721
1768
  if (protectedOperands.hClass) {
1722
1769
  logger.warn(`[ReadonlyCheck] 🔒 H-class path blocked in readonly shell: cmd="${cmd}" session=${context?.sessionId} channel=${context?.channel} peer=${context?.peerId} role=${context?.role}`);
1770
+ if (protectedOperands.implicitCwd) {
1771
+ return { behavior: 'deny', message: IMPLICIT_CWD_SEARCH_NOTICE, policyCode: 'shell_implicit_cwd', matchedPath: protectedOperands.hClassPath };
1772
+ }
1723
1773
  if (protectedOperands.analysis.kind === 'proven-readonly') {
1724
1774
  return { behavior: 'deny', message: '🔒 只读模式:不允许读取 H 类受保护路径', policyCode: 'readonly_h_class_read', matchedPath: protectedOperands.hClassPath };
1725
1775
  }
@@ -1944,6 +1994,8 @@ function requestsFilesystemRoot(value) {
1944
1994
  const PROTECTED_READ_SEARCH_HINT = '\n\n💡 只读检索请显式指定普通源码目录,例如:' +
1945
1995
  "\n rg -n -g '!*.json_' -g '!*.json.migrated' -- '<关键词>' src tests kits docs" +
1946
1996
  '\n 不要把项目根目录作为递归搜索范围;若子目录仍含受保护文件,请继续缩小到明确文件。';
1997
+ const IMPLICIT_CWD_SEARCH_NOTICE = '🔒 查询未指定文件路径,默认递归扫描当前目录;该范围可能包含受保护路径,已拒绝。' +
1998
+ PROTECTED_READ_SEARCH_HINT;
1947
1999
  export function checkHClassWrite(toolName, input, context) {
1948
2000
  const paths = [];
1949
2001
  const grantPaths = [];
@@ -2012,10 +2064,12 @@ export function checkHClassWrite(toolName, input, context) {
2012
2064
  `session=${context?.sessionId} channel=${context?.channel} peer=${context?.peerId} role=${context?.role}`);
2013
2065
  return {
2014
2066
  behavior: 'deny',
2015
- message: '🔒 Shell 命令涉及受保护的 H 类配置/证书/快照路径,agent 不可直接操作' +
2016
- (protectedOperands.analysis.kind === 'proven-readonly' ? PROTECTED_READ_SEARCH_HINT : ''),
2067
+ message: protectedOperands.implicitCwd ? IMPLICIT_CWD_SEARCH_NOTICE
2068
+ : '🔒 Shell 命令涉及受保护的 H 类配置/证书/快照路径,agent 不可直接操作' +
2069
+ (protectedOperands.analysis.kind === 'proven-readonly' ? PROTECTED_READ_SEARCH_HINT : ''),
2017
2070
  matchedPath: protectedOperands.hClassPath,
2018
- matchedRule: protectedOperands.hClassPath ? 'h-class-shell-operand' : 'h-class-shell-unproven',
2071
+ matchedRule: protectedOperands.implicitCwd ? 'implicit-cwd'
2072
+ : protectedOperands.hClassPath ? 'h-class-shell-operand' : 'h-class-shell-unproven',
2019
2073
  };
2020
2074
  }
2021
2075
  collectFilesystemGrantPaths(input.additionalPermissions, grantPaths, projectRootGrantSubpaths);
@@ -2753,7 +2807,7 @@ export function evaluateToolPreflight(toolName, input, context) {
2753
2807
  allowProtectedMetadata: context.allowProtectedMetadata,
2754
2808
  });
2755
2809
  if (hClass.behavior === 'deny') {
2756
- return { behavior: 'deny', input: checkedInput, message: `${hClass.message}${hClass.matchedRule ? ` (matchedRule=${hClass.matchedRule})` : ''}`, policyCode: 'h_class_protection', matchedPath: hClass.matchedPath, matchedRule: hClass.matchedRule };
2810
+ return { behavior: 'deny', input: checkedInput, message: `${hClass.message}${hClass.matchedRule ? ` (matchedRule=${hClass.matchedRule})` : ''}`, policyCode: hClass.matchedRule === 'implicit-cwd' ? 'shell_implicit_cwd' : 'h_class_protection', matchedPath: hClass.matchedPath, matchedRule: hClass.matchedRule };
2757
2811
  }
2758
2812
  const lClass = checkLClassWrite(policyToolName, protectedPolicyInput, {
2759
2813
  sessionId: context.sessionId,
@@ -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 }));
@@ -73,8 +73,13 @@ export async function preparePaTeamQualification(selfAid, peerAid) {
73
73
  throw new Error('Mismatched PA profile');
74
74
  return profile;
75
75
  });
76
- if (!profiles.every(profile => profile.type === 'agent'
77
- && typeof profile.exttype === 'string' && /^pa\.[^\s.][^\s]*$/i.test(profile.exttype.trim())))
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'))
78
83
  return 'unmatched';
79
84
  const consensuses = await Promise.all([selfAid, peerAid].map(aid => runtime.client.checkOwnershipConsensus(aid, true)));
80
85
  for (const [index, consensus] of consensuses.entries()) {
@@ -0,0 +1,131 @@
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 SAME_OWNER_MAX_AGE_MS = 30_000;
6
+ const SAME_OWNER_TIMEOUT_MS = 8_000;
7
+ const runtimes = new Map();
8
+ const knownTeams = new Map();
9
+ let revision = 0;
10
+ export function registerSameOwnerClient(selfAid, client, store) {
11
+ unregisterSameOwnerClient(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 unregisterSameOwnerClient(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 sameOwnerQualification(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 sameOwnerRevision(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 requiresSameOwnerProof(selfAid, peerAid) {
50
+ return knownTeams.get(selfAid)?.has(peerAid) === true;
51
+ }
52
+ export async function prepareSameOwnerProof(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 agent profile');
71
+ const profile = parseAgentMdFrontmatter(card.content);
72
+ if (profile.aid !== [selfAid, peerAid][index])
73
+ throw new Error('Mismatched agent profile');
74
+ return profile;
75
+ });
76
+ // 这里证明的是「同一个 Owner 名下的内部 agent」,**不是** PA Team 成员关系:
77
+ // 团队归属由 contacts.json 的 open_pa_context 决定(见 owner-directory-scope.ts
78
+ // 的 isInPaTeam),本模块不读那份名单。判据也不看 exttype 前缀——同 Owner 的
79
+ // 非 PA agent 同样是内部联系人。human/service/device 不参与:它们拿不到
80
+ // agent.md 里协议共识校验所需的 ownership statement。
81
+ if (!profiles.every(profile => String(profile.type || '').trim().toLowerCase() === 'agent'))
82
+ return 'unmatched';
83
+ const consensuses = await Promise.all([selfAid, peerAid].map(aid => runtime.client.checkOwnershipConsensus(aid, true)));
84
+ for (const [index, consensus] of consensuses.entries()) {
85
+ const digest = createHash('sha256').update(cards[index].content, 'utf8').digest('hex');
86
+ if (consensus.status !== 'consensus' || consensus.sub_aid !== [selfAid, peerAid][index]
87
+ || consensus.lock !== 'locked' || !consensus.owner_aid || !isValidAid(consensus.owner_aid)
88
+ || !Number.isSafeInteger(consensus.relation_version) || consensus.relation_version < 1
89
+ || consensus.agent_md_sha256 !== digest
90
+ || profiles[index].owner !== consensus.owner_aid)
91
+ return 'unavailable';
92
+ }
93
+ return consensuses[0].owner_aid === consensuses[1].owner_aid ? 'matched' : 'unmatched';
94
+ };
95
+ const task = (async () => {
96
+ let timeout;
97
+ let qualification = 'unavailable';
98
+ try {
99
+ qualification = await Promise.race([query(), new Promise(resolve => {
100
+ timeout = setTimeout(() => resolve('unavailable'), SAME_OWNER_TIMEOUT_MS);
101
+ timeout.unref?.();
102
+ })]);
103
+ }
104
+ catch {
105
+ qualification = 'unavailable';
106
+ }
107
+ finally {
108
+ if (timeout)
109
+ clearTimeout(timeout);
110
+ }
111
+ if (runtimes.get(selfAid) !== runtime || runtime.generation !== generation || !runtime.client.isReady)
112
+ return;
113
+ if (qualification === 'matched')
114
+ runtime.knownTeams.add(peerAid);
115
+ if (qualification === 'unmatched')
116
+ runtime.knownTeams.delete(peerAid);
117
+ runtime.entries.set(peerAid, {
118
+ qualification,
119
+ expiresAt: startedAt + (qualification === 'unavailable' ? 2_000 : SAME_OWNER_MAX_AGE_MS),
120
+ revision: ++revision,
121
+ });
122
+ })();
123
+ runtime.pending.set(peerAid, task);
124
+ try {
125
+ await task;
126
+ }
127
+ finally {
128
+ if (runtime.pending.get(peerAid) === task)
129
+ runtime.pending.delete(peerAid);
130
+ }
131
+ }