evolcore 0.0.43-test.4 → 0.0.43-test.6

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 (186) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ecmsg.js +437 -91
  3. package/dist/agents/baseagent-availability.js +19 -4
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +14 -3
  7. package/dist/agents/codex-runner.js +18 -23
  8. package/dist/aun/aid/agentmd.js +25 -0
  9. package/dist/aun/aid/control-aid.js +15 -0
  10. package/dist/aun/aid/identity.js +8 -0
  11. package/dist/aun/aid/ownership-operation.js +12 -3
  12. package/dist/aun/group/invite-service.js +3 -2
  13. package/dist/aun/service-proxy.js +18 -6
  14. package/dist/channels/aun.js +99 -23
  15. package/dist/channels/daemon.js +2 -2
  16. package/dist/cli/agent-create.js +19 -7
  17. package/dist/cli/aid-bind-command.js +3 -0
  18. package/dist/cli/aun-commands.js +19 -4
  19. package/dist/cli/code-stats.js +451 -213
  20. package/dist/cli/ctl-command.js +1 -3
  21. package/dist/cli/daemon-commands.js +42 -4
  22. package/dist/cli/directory.js +3 -1
  23. package/dist/cli/ecmsg-gateway.js +206 -0
  24. package/dist/cli/index.js +6 -0
  25. package/dist/cli/init.js +120 -13
  26. package/dist/cli/provider-command.js +82 -5
  27. package/dist/cli/restart-monitor.js +35 -24
  28. package/dist/cli/stats.js +8 -1
  29. package/dist/cli/task-context.js +41 -1
  30. package/dist/cli/watch-logs.js +6 -4
  31. package/dist/config/boot-log.js +16 -3
  32. package/dist/config/builtin-roles.js +2 -2
  33. package/dist/config/config-manager.js +5 -14
  34. package/dist/config/daemon-services.js +1 -0
  35. package/dist/config/peer-role-resolver.js +6 -6
  36. package/dist/config/provider-identity-migration.js +277 -0
  37. package/dist/config/provider-identity.js +37 -0
  38. package/dist/config/provider-ipc-service.js +40 -3
  39. package/dist/config/provider-local-sync.js +155 -0
  40. package/dist/config/providers-config.js +45 -4
  41. package/dist/config/providers-management.js +242 -76
  42. package/dist/config/providers.js +4 -1
  43. package/dist/config/role-service.js +8 -8
  44. package/dist/config/role-store.js +22 -22
  45. package/dist/config/schema-migration.js +143 -86
  46. package/dist/config/snapshot.js +70 -41
  47. package/dist/core/agent-runtime.js +48 -9
  48. package/dist/core/auth/auth-gateway.js +5 -3
  49. package/dist/core/auth/delegation-diagnostics.js +6 -2
  50. package/dist/core/auth/operation-authorizer.js +3 -1
  51. package/dist/core/auth/operation-catalog.js +6 -4
  52. package/dist/core/baseagent-loader.js +114 -11
  53. package/dist/core/channel-loader.js +36 -13
  54. package/dist/core/channel-runtime.js +112 -42
  55. package/dist/core/command/cli-intent-parser.js +2 -1
  56. package/dist/core/command/command-handler.js +16 -11
  57. package/dist/core/command/menu-handler.js +8 -3
  58. package/dist/core/command/menu-protocol.js +80 -7
  59. package/dist/core/command/provider-menu.js +4 -2
  60. package/dist/core/command/role-menu.js +29 -17
  61. package/dist/core/command/slash-handler.js +52 -16
  62. package/dist/core/daemon-control.js +42 -15
  63. package/dist/core/daemon-lifecycle.js +411 -67
  64. package/dist/core/handoff/dispatcher.js +9 -3
  65. package/dist/core/handoff/runtime.js +139 -45
  66. package/dist/core/handoff/store.js +190 -2
  67. package/dist/core/handoff/types.js +5 -0
  68. package/dist/core/initialization/service.js +7 -6
  69. package/dist/core/ipc-registration.js +5 -4
  70. package/dist/core/lifecycle-notice.js +10 -4
  71. package/dist/core/message/aun-ipc-sender.js +83 -5
  72. package/dist/core/message/message-admission.js +2 -0
  73. package/dist/core/message/message-bridge.js +53 -4
  74. package/dist/core/message/message-queue.js +46 -4
  75. package/dist/core/message/pending-hints.js +4 -10
  76. package/dist/core/message/response-engine.js +33 -25
  77. package/dist/core/message/send-options.js +40 -0
  78. package/dist/core/message/send-routing.js +320 -0
  79. package/dist/core/ownership/owner-resolver.js +112 -8
  80. package/dist/core/permission/ec-command-parser.js +159 -16
  81. package/dist/core/permission/readonly-shell-query.js +66 -7
  82. package/dist/core/permission/tool-error-code.js +13 -1
  83. package/dist/core/permission/tool-policy.js +74 -20
  84. package/dist/core/relation/same-owner-proof.js +131 -0
  85. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  86. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  87. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  88. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  89. package/dist/core/session/session-fs-store.js +164 -3
  90. package/dist/core/session/session-idle-monitor.js +103 -17
  91. package/dist/core/session/session-manager.js +105 -18
  92. package/dist/core/thread/thread-route.js +5 -2
  93. package/dist/directory/owner-directory-admission.js +26 -1
  94. package/dist/directory/owner-directory-cache.js +739 -109
  95. package/dist/directory/owner-directory-markdown.js +146 -36
  96. package/dist/directory/owner-directory-query-operation.js +6 -3
  97. package/dist/directory/owner-directory-scope.js +12 -0
  98. package/dist/directory/owner-directory-search.js +5 -1
  99. package/dist/directory/owner-directory-store.js +28 -0
  100. package/dist/ecweb/basic-settings-service.js +15 -1
  101. package/dist/ecweb/message-context-service.js +2 -2
  102. package/dist/ecweb/providers-service.js +3 -1
  103. package/dist/ecweb/runtime/lifecycle.js +26 -15
  104. package/dist/ecweb/runtime/supervisor.js +120 -51
  105. package/dist/index.js +551 -250
  106. package/dist/paths.js +2 -1
  107. package/dist/proxy/manager.js +40 -17
  108. package/dist/proxy/service-supervisor.js +67 -33
  109. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  110. package/dist/trigger/application-service.js +4 -1
  111. package/dist/trigger/audit.js +19 -4
  112. package/dist/trigger/authorization.js +14 -5
  113. package/dist/trigger/event-source.js +4 -0
  114. package/dist/trigger/feedback.js +26 -2
  115. package/dist/trigger/history.js +176 -7
  116. package/dist/trigger/manager.js +1 -3
  117. package/dist/trigger/scheduler.js +81 -8
  118. package/dist/trigger/system-definitions.js +2 -2
  119. package/dist/trigger/validation.js +4 -0
  120. package/dist/utils/autostart.js +2 -2
  121. package/dist/utils/cross-platform.js +188 -12
  122. package/dist/utils/host-info.js +11 -8
  123. package/dist/utils/npm-ops.js +48 -0
  124. package/dist/utils/process-introspect.js +64 -1
  125. package/dist/utils/public-suffix.js +5811 -0
  126. package/dist/utils/startup-trace.js +160 -19
  127. package/dist/utils/windows-autostart.js +41 -7
  128. package/ecagent/dist/harness/env/nodejs.js +46 -2
  129. package/kits/docs/aun/ABILITY_CALLING.md +6 -6
  130. package/kits/docs/channels/aun.md +1 -1
  131. package/kits/docs/channels/feishu.md +2 -2
  132. package/kits/docs/context-assembly.md +20 -4
  133. package/kits/docs/evolcore/INDEX.md +5 -3
  134. package/kits/docs/evolcore/agent.md +2 -2
  135. package/kits/docs/evolcore/aid.md +8 -2
  136. package/kits/docs/evolcore/ctl.md +15 -5
  137. package/kits/docs/evolcore/directory.md +48 -15
  138. package/kits/docs/evolcore/group.md +8 -8
  139. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  140. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  141. package/kits/docs/evolcore/menu-protocol.md +32 -3
  142. package/kits/docs/evolcore/msg.md +38 -30
  143. package/kits/docs/evolcore/provider.md +57 -5
  144. package/kits/docs/evolcore/response.md +2 -2
  145. package/kits/docs/evolcore/thread-chain.md +11 -13
  146. package/kits/docs/evolcore/tool-authorization.md +17 -0
  147. package/kits/docs/evolcore/trigger.md +2 -2
  148. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  149. package/kits/docs/prompt-loading-architecture.md +30 -20
  150. package/kits/eck_manifest.auxiliary.json +5 -5
  151. package/kits/eck_manifest.json +44 -32
  152. package/kits/eck_manifest.memory.json +18 -18
  153. package/kits/eck_message_manifest.json +3 -3
  154. package/kits/rules/01-overview.md +1 -1
  155. package/kits/rules/06-channel.md +7 -8
  156. package/kits/schemas/_meta.json +7 -1
  157. package/kits/schemas/daemon.schema.1.json +5 -0
  158. package/kits/schemas/daemon.schema.2.json +5 -0
  159. package/kits/schemas/daemon.schema.3.json +2 -1
  160. package/kits/schemas/daemon.schema.4.json +2 -1
  161. package/kits/schemas/daemon.schema.5.json +2 -1
  162. package/kits/schemas/daemon.schema.6.json +1 -1
  163. package/kits/schemas/daemon.schema.7.json +1 -1
  164. package/kits/schemas/daemon.schema.8.json +2 -1
  165. package/kits/schemas/daemon.schema.9.json +2 -1
  166. package/kits/schemas/providers.schema.2.json +74 -0
  167. package/kits/schemas/role-registry.schema.1.json +2 -2
  168. package/kits/schemas/single-session.schema.1.json +1 -1
  169. package/kits/schemas/single-session.schema.2.json +1 -1
  170. package/kits/schemas/single-session.schema.3.json +1 -1
  171. package/kits/skills/aid-ability/SKILL.md +7 -7
  172. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  173. package/kits/skills/ec-group/SKILL.md +8 -5
  174. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  175. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  176. package/kits/skills/ec-trigger/SKILL.md +9 -9
  177. package/kits/skills/ec-trigger/references/examples.md +1 -1
  178. package/kits/skills/thread-ops/SKILL.md +10 -10
  179. package/kits/templates/system-fragments/channel.md +5 -5
  180. package/kits/templates/system-fragments/commands.md +7 -6
  181. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  182. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  183. package/kits/templates/system-fragments/reply.md +48 -28
  184. package/kits/templates/system-fragments/session.md +3 -10
  185. package/kits/templates/system-fragments/thread.md +5 -5
  186. package/package.json +4 -4
@@ -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,
@@ -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
+ }
@@ -11,6 +11,7 @@ import { buildCliSessionPreview } from '../session-title.js';
11
11
  import path from 'path';
12
12
  import fs from 'fs';
13
13
  import os from 'os';
14
+ import { visitSessionHistory } from '../session-fs-store.js';
14
15
  export class ClaudeSessionFileAdapter {
15
16
  baseagent = 'claude';
16
17
  getSessionFilePath(projectPath, agentSessionId) {
@@ -60,6 +61,29 @@ export class ClaudeSessionFileAdapter {
60
61
  return null;
61
62
  return this.readSessionPreview(sessionFile).title;
62
63
  }
64
+ async readMenuSummary(projectPath, agentSessionId) {
65
+ let turns = 0;
66
+ let validInfo = true;
67
+ const messages = [];
68
+ try {
69
+ await visitSessionHistory(this.getSessionFilePath(projectPath, agentSessionId), event => {
70
+ if (event?.type !== 'user' || event.message?.role !== 'user')
71
+ return;
72
+ const content = event.message.content;
73
+ if (!(Array.isArray(content) && content.every((part) => part.type === 'tool_result')))
74
+ turns++;
75
+ const text = this.extractRawUserText(content);
76
+ if (text)
77
+ messages.push(text);
78
+ }, () => { validInfo = false; });
79
+ return { turns: validInfo ? turns : 0, firstMessage: buildCliSessionPreview(messages, 'claude').title };
80
+ }
81
+ catch (error) {
82
+ if (error.code !== 'ENOENT')
83
+ logger.warn('[ClaudeAdapter] Failed to read menu summary', error);
84
+ return { turns: 0, firstMessage: null };
85
+ }
86
+ }
63
87
  /**
64
88
  * 单遍扫描会话文件,返回预览标题及是否含真人消息。
65
89
  * - title:第一条真人消息(跳过脚手架 prompt);全是脚手架时退回首条脚手架文本作兜底
@@ -15,6 +15,7 @@ import { logger } from '../../../utils/logger.js';
15
15
  import path from 'path';
16
16
  import fs from 'fs';
17
17
  import os from 'os';
18
+ import { visitSessionHistory } from '../session-fs-store.js';
18
19
  const requireFromHere = createRequire(import.meta.url);
19
20
  let sqliteModule; // undefined = not tried, null = unavailable
20
21
  export const sanitizeCodexThreadTitle = sanitizeSessionTitle;
@@ -37,6 +38,7 @@ export class CodexSessionFileAdapter {
37
38
  db = null;
38
39
  dbInitialized = false;
39
40
  rolloutPathCache = new Map();
41
+ rolloutFilesScan;
40
42
  constructor(codexHome = path.join(os.homedir(), '.codex')) {
41
43
  this.codexHome = codexHome;
42
44
  }
@@ -235,6 +237,84 @@ export class CodexSessionFileAdapter {
235
237
  return null;
236
238
  return this.readUserMessageFromRollout(rolloutPath, 'first');
237
239
  }
240
+ async findRolloutFileAsync(agentSessionId, preferred) {
241
+ for (const candidate of [preferred, this.rolloutPathCache.get(agentSessionId)]) {
242
+ if (typeof candidate !== 'string' || !candidate)
243
+ continue;
244
+ try {
245
+ await fs.promises.access(candidate);
246
+ return candidate;
247
+ }
248
+ catch { /* Rescan moved rollouts. */ }
249
+ }
250
+ this.rolloutPathCache.delete(agentSessionId);
251
+ const scan = async (dir) => {
252
+ const files = [];
253
+ let entries;
254
+ try {
255
+ entries = await fs.promises.readdir(dir, { withFileTypes: true });
256
+ }
257
+ catch {
258
+ return files;
259
+ }
260
+ for (const entry of entries) {
261
+ const file = path.join(dir, entry.name);
262
+ if (entry.isDirectory())
263
+ files.push(...await scan(file));
264
+ else if (entry.name.endsWith('.jsonl')) {
265
+ files.push(file);
266
+ const id = /([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.jsonl$/i.exec(entry.name)?.[1];
267
+ if (id && !this.rolloutPathCache.has(id))
268
+ this.rolloutPathCache.set(id, file);
269
+ }
270
+ }
271
+ return files;
272
+ };
273
+ // Concurrent topic reads share discovery. Misses are never cached across scans.
274
+ const pending = this.rolloutFilesScan ??= scan(path.join(this.codexHome, 'sessions'));
275
+ try {
276
+ const file = (await pending).find(file => path.basename(file).includes(agentSessionId)) ?? null;
277
+ if (file)
278
+ this.rolloutPathCache.set(agentSessionId, file);
279
+ return file;
280
+ }
281
+ finally {
282
+ if (this.rolloutFilesScan === pending)
283
+ this.rolloutFilesScan = undefined;
284
+ }
285
+ }
286
+ async readMenuSummary(_projectPath, agentSessionId) {
287
+ let row;
288
+ try {
289
+ row = this.getDb()?.prepare('SELECT first_user_message, rollout_path FROM threads WHERE id = ?').get(agentSessionId);
290
+ }
291
+ catch (error) {
292
+ logger.warn('[CodexAdapter] menu summary DB query failed:', error);
293
+ }
294
+ const rollout = await this.findRolloutFileAsync(agentSessionId, row?.rollout_path);
295
+ let turns = 0;
296
+ let rolloutRead = false;
297
+ const messages = [];
298
+ if (rollout) {
299
+ try {
300
+ await visitSessionHistory(rollout, event => {
301
+ if (event?.type === 'turn_context')
302
+ turns++;
303
+ if (event?.type === 'event_msg' && event.payload?.type === 'user_message' && event.payload.message) {
304
+ messages.push(String(event.payload.message));
305
+ }
306
+ });
307
+ rolloutRead = true;
308
+ }
309
+ catch {
310
+ turns = 0;
311
+ messages.length = 0;
312
+ }
313
+ }
314
+ const initial = buildCliSessionPreview([row?.first_user_message], 'codex');
315
+ return { turns, firstMessage: row && (initial.hasReal || !rollout || !rolloutRead)
316
+ ? initial.title : buildCliSessionPreview(messages, 'codex').title };
317
+ }
238
318
  readLastUserMessage(projectPath, agentSessionId) {
239
319
  // 1. 优先查 state DB 获取 rollout_path
240
320
  const db = this.getDb();
@@ -1,5 +1,6 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
+ import { visitSessionHistory } from '../session-fs-store.js';
3
4
  import { agentSessionsDir } from '../../../paths.js';
4
5
  function projectDirectory(projectPath, agentAid) {
5
6
  if (!agentAid?.trim())
@@ -72,6 +73,27 @@ export class EcagentSessionFileAdapter {
72
73
  .find(item => item.type === 'message' && item.message?.role === 'user');
73
74
  return preview(messageText(entry?.message?.content));
74
75
  }
76
+ async readMenuSummary(projectPath, agentSessionId, agentAid) {
77
+ let turns = 0;
78
+ let firstMessage = null;
79
+ const dir = projectDirectory(projectPath, agentAid);
80
+ if (!dir)
81
+ return { turns, firstMessage };
82
+ try {
83
+ const name = (await fs.promises.readdir(dir)).find(name => name.endsWith(`_${agentSessionId}.jsonl`));
84
+ if (name)
85
+ await visitSessionHistory(path.join(dir, name), (entry, line) => {
86
+ if (line === 0 || entry?.type !== 'message' || entry.message?.role !== 'user')
87
+ return;
88
+ if (turns++ === 0)
89
+ firstMessage = preview(messageText(entry.message.content));
90
+ });
91
+ return { turns, firstMessage };
92
+ }
93
+ catch {
94
+ return { turns: 0, firstMessage: null };
95
+ }
96
+ }
75
97
  readLastUserMessage(projectPath, agentSessionId, agentAid) {
76
98
  const entries = this.readEntries(projectPath, agentSessionId, agentAid)
77
99
  .filter(item => item.type === 'message' && item.message?.role === 'user');
@@ -120,6 +120,45 @@ export class GeminiSessionFileAdapter {
120
120
  readFirstMessage(projectPath, agentSessionId) {
121
121
  return this.readUserMessage(projectPath, agentSessionId, 'first');
122
122
  }
123
+ async readMenuSummary(projectPath, agentSessionId) {
124
+ const home = this.getGeminiHome();
125
+ let projectKey;
126
+ try {
127
+ const data = JSON.parse(await fs.promises.readFile(path.join(home, 'projects.json'), 'utf8'));
128
+ const mapped = data?.projects?.[projectPath];
129
+ if (typeof mapped === 'string' && mapped.trim())
130
+ projectKey = mapped;
131
+ }
132
+ catch { /* Match the existing project-root fallback. */ }
133
+ if (!projectKey) {
134
+ try {
135
+ for (const entry of await fs.promises.readdir(path.join(home, 'tmp'), { withFileTypes: true })) {
136
+ if (!entry.isDirectory())
137
+ continue;
138
+ try {
139
+ if ((await fs.promises.readFile(path.join(home, 'tmp', entry.name, '.project_root'), 'utf8')).trim() === projectPath) {
140
+ projectKey = entry.name;
141
+ break;
142
+ }
143
+ }
144
+ catch { /* Ignore broken project roots. */ }
145
+ }
146
+ }
147
+ catch { /* Use the basename fallback. */ }
148
+ }
149
+ const dir = path.join(home, 'tmp', projectKey ?? path.basename(projectPath), 'chats');
150
+ try {
151
+ const name = (await fs.promises.readdir(dir)).find(name => name.includes(agentSessionId.slice(0, 8)) && name.endsWith('.json'));
152
+ if (!name)
153
+ return { turns: 0, firstMessage: null };
154
+ const data = JSON.parse(await fs.promises.readFile(path.join(dir, name), 'utf8'));
155
+ return { turns: (data.messages || []).filter((message) => message.type === 'user').length,
156
+ firstMessage: this.buildSessionPreview(data).title };
157
+ }
158
+ catch {
159
+ return { turns: 0, firstMessage: null };
160
+ }
161
+ }
123
162
  readLastUserMessage(projectPath, agentSessionId) {
124
163
  return this.readUserMessage(projectPath, agentSessionId, 'last');
125
164
  }