evolcore 0.0.43-test.4 → 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 (129) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/bin/ecmsg.js +354 -91
  3. package/dist/agents/codex-runner.js +12 -17
  4. package/dist/aun/aid/agentmd.js +25 -0
  5. package/dist/aun/aid/control-aid.js +15 -0
  6. package/dist/aun/aid/identity.js +8 -0
  7. package/dist/aun/aid/ownership-operation.js +12 -3
  8. package/dist/channels/aun.js +30 -17
  9. package/dist/channels/daemon.js +2 -2
  10. package/dist/cli/agent-create.js +4 -2
  11. package/dist/cli/aid-bind-command.js +3 -0
  12. package/dist/cli/aun-commands.js +10 -3
  13. package/dist/cli/code-stats.js +451 -213
  14. package/dist/cli/ctl-command.js +1 -3
  15. package/dist/cli/daemon-commands.js +12 -3
  16. package/dist/cli/directory.js +3 -1
  17. package/dist/cli/ecmsg-gateway.js +204 -0
  18. package/dist/cli/index.js +6 -0
  19. package/dist/cli/init.js +45 -13
  20. package/dist/cli/provider-command.js +82 -5
  21. package/dist/cli/restart-monitor.js +11 -19
  22. package/dist/cli/stats.js +8 -1
  23. package/dist/cli/task-context.js +3 -0
  24. package/dist/config/boot-log.js +12 -1
  25. package/dist/config/config-manager.js +4 -13
  26. package/dist/config/daemon-services.js +1 -0
  27. package/dist/config/peer-role-resolver.js +5 -5
  28. package/dist/config/provider-identity-migration.js +202 -0
  29. package/dist/config/provider-identity.js +37 -0
  30. package/dist/config/provider-ipc-service.js +40 -3
  31. package/dist/config/provider-local-sync.js +153 -0
  32. package/dist/config/providers-config.js +32 -4
  33. package/dist/config/providers-management.js +144 -68
  34. package/dist/config/providers.js +4 -1
  35. package/dist/config/schema-migration.js +67 -3
  36. package/dist/core/agent-runtime.js +4 -2
  37. package/dist/core/auth/auth-gateway.js +5 -3
  38. package/dist/core/auth/delegation-diagnostics.js +6 -2
  39. package/dist/core/auth/operation-authorizer.js +3 -1
  40. package/dist/core/auth/operation-catalog.js +6 -4
  41. package/dist/core/command/cli-intent-parser.js +2 -1
  42. package/dist/core/command/command-handler.js +11 -6
  43. package/dist/core/command/menu-protocol.js +4 -2
  44. package/dist/core/command/provider-menu.js +4 -2
  45. package/dist/core/command/role-menu.js +2 -2
  46. package/dist/core/command/slash-handler.js +52 -16
  47. package/dist/core/handoff/runtime.js +9 -3
  48. package/dist/core/initialization/service.js +4 -3
  49. package/dist/core/message/aun-ipc-sender.js +81 -3
  50. package/dist/core/message/message-admission.js +2 -0
  51. package/dist/core/message/response-engine.js +23 -23
  52. package/dist/core/message/send-options.js +40 -0
  53. package/dist/core/message/send-routing.js +310 -0
  54. package/dist/core/ownership/owner-resolver.js +111 -8
  55. package/dist/core/permission/ec-command-parser.js +148 -15
  56. package/dist/core/permission/readonly-shell-query.js +66 -7
  57. package/dist/core/permission/tool-error-code.js +13 -1
  58. package/dist/core/permission/tool-policy.js +74 -20
  59. package/dist/core/relation/same-owner-proof.js +131 -0
  60. package/dist/core/session/session-idle-monitor.js +94 -16
  61. package/dist/core/session/session-manager.js +69 -16
  62. package/dist/core/thread/thread-route.js +5 -2
  63. package/dist/directory/owner-directory-cache.js +686 -97
  64. package/dist/directory/owner-directory-markdown.js +146 -36
  65. package/dist/directory/owner-directory-query-operation.js +2 -2
  66. package/dist/directory/owner-directory-scope.js +12 -0
  67. package/dist/directory/owner-directory-search.js +5 -1
  68. package/dist/directory/owner-directory-store.js +28 -0
  69. package/dist/ecweb/basic-settings-service.js +15 -1
  70. package/dist/ecweb/message-context-service.js +2 -2
  71. package/dist/ecweb/providers-service.js +3 -1
  72. package/dist/ecweb/runtime/lifecycle.js +18 -9
  73. package/dist/ecweb/runtime/supervisor.js +76 -24
  74. package/dist/index.js +4 -0
  75. package/dist/paths.js +2 -1
  76. package/dist/proxy/manager.js +2 -0
  77. package/dist/proxy/service-supervisor.js +2 -2
  78. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  79. package/dist/trigger/application-service.js +1 -0
  80. package/dist/trigger/event-source.js +4 -0
  81. package/dist/trigger/feedback.js +26 -2
  82. package/dist/trigger/scheduler.js +3 -3
  83. package/dist/trigger/system-definitions.js +2 -2
  84. package/dist/trigger/validation.js +4 -0
  85. package/dist/utils/autostart.js +2 -2
  86. package/dist/utils/cross-platform.js +36 -8
  87. package/dist/utils/public-suffix.js +5811 -0
  88. package/dist/utils/windows-autostart.js +41 -7
  89. package/ecagent/dist/harness/env/nodejs.js +46 -2
  90. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  91. package/kits/docs/channels/aun.md +1 -1
  92. package/kits/docs/channels/feishu.md +2 -2
  93. package/kits/docs/context-assembly.md +20 -4
  94. package/kits/docs/evolcore/INDEX.md +2 -1
  95. package/kits/docs/evolcore/agent.md +2 -2
  96. package/kits/docs/evolcore/aid.md +8 -2
  97. package/kits/docs/evolcore/ctl.md +13 -4
  98. package/kits/docs/evolcore/directory.md +48 -15
  99. package/kits/docs/evolcore/group.md +6 -6
  100. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  101. package/kits/docs/evolcore/menu-protocol.md +32 -3
  102. package/kits/docs/evolcore/msg.md +28 -27
  103. package/kits/docs/evolcore/provider.md +39 -5
  104. package/kits/docs/evolcore/response.md +1 -1
  105. package/kits/docs/evolcore/thread-chain.md +11 -13
  106. package/kits/docs/evolcore/tool-authorization.md +17 -0
  107. package/kits/docs/evolcore/trigger.md +2 -2
  108. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  109. package/kits/docs/prompt-loading-architecture.md +30 -20
  110. package/kits/eck_manifest.auxiliary.json +5 -5
  111. package/kits/eck_manifest.json +28 -28
  112. package/kits/eck_manifest.memory.json +18 -18
  113. package/kits/rules/01-overview.md +1 -1
  114. package/kits/rules/06-channel.md +3 -3
  115. package/kits/schemas/_meta.json +7 -1
  116. package/kits/schemas/providers.schema.2.json +74 -0
  117. package/kits/schemas/role-registry.schema.1.json +1 -1
  118. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  119. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  120. package/kits/skills/ec-trigger/SKILL.md +5 -5
  121. package/kits/skills/ec-trigger/references/examples.md +1 -1
  122. package/kits/templates/system-fragments/channel.md +5 -5
  123. package/kits/templates/system-fragments/commands.md +3 -2
  124. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  125. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  126. package/kits/templates/system-fragments/reply.md +47 -28
  127. package/kits/templates/system-fragments/session.md +2 -9
  128. package/kits/templates/system-fragments/thread.md +5 -5
  129. package/package.json +2 -3
@@ -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
+ }
@@ -10,6 +10,20 @@ import { createRootCausation } from '../causation/context.js';
10
10
  export const DEFAULT_SESSION_LOOP_SECONDS = 300;
11
11
  export const MIN_SESSION_LOOP_SECONDS = 30;
12
12
  export const MAX_SESSION_LOOP_SECONDS = 86400;
13
+ export const MAX_SESSION_LOOP_PROMPT_LENGTH = 4096;
14
+ export function normalizeSessionLoopOnceConfig(value) {
15
+ if (!value || typeof value !== 'object' || Array.isArray(value))
16
+ return undefined;
17
+ const raw = value;
18
+ if (Object.keys(raw).some(key => key !== 'idleSeconds' && key !== 'prompt'))
19
+ return undefined;
20
+ if (!isValidIdleSeconds(raw.idleSeconds) || typeof raw.prompt !== 'string')
21
+ return undefined;
22
+ const prompt = raw.prompt.trim();
23
+ if (!prompt || prompt.length > MAX_SESSION_LOOP_PROMPT_LENGTH)
24
+ return undefined;
25
+ return { idleSeconds: raw.idleSeconds, prompt };
26
+ }
13
27
  export function normalizeSessionLoopConfig(value) {
14
28
  if (!value || typeof value !== 'object' || Array.isArray(value))
15
29
  return undefined;
@@ -64,6 +78,16 @@ export function readSessionLoopConfigForSession(session) {
64
78
  const target = resolveSessionLoopTarget(session);
65
79
  return target ? readSessionLoopConfig(target) : undefined;
66
80
  }
81
+ export function readSessionLoopOnceConfig(session) {
82
+ const request = session.metadata?.sessionLoopOnce;
83
+ if (!request || typeof request.requestId !== 'string' || !request.requestId.trim()
84
+ || typeof request.peerId !== 'string' || !request.peerId.trim()
85
+ || !Number.isFinite(request.requestedAt))
86
+ return undefined;
87
+ const config = normalizeSessionLoopOnceConfig({ idleSeconds: request.idleSeconds, prompt: request.prompt });
88
+ return config ? { ...config, requestId: request.requestId, requestedAt: request.requestedAt, peerId: request.peerId,
89
+ ...(typeof request.encrypted === 'boolean' ? { encrypted: request.encrypted } : {}) } : undefined;
90
+ }
67
91
  export function updateRelationSessionLoop(session, config) {
68
92
  const target = resolveSessionLoopTarget(session);
69
93
  if (!target || target.level !== 'relation-main')
@@ -117,11 +141,19 @@ export function writeSessionLoopConfig(store, target, config) {
117
141
  }
118
142
  export function sessionLoopPayload(target) {
119
143
  const config = readSessionLoopConfig(target);
144
+ const once = readSessionLoopOnceConfig(target.session);
120
145
  return {
121
146
  target: { level: target.level, sessionId: target.session.id },
122
147
  sessionId: target.session.id,
123
148
  value: config?.enabled === true,
124
149
  ...(config?.enabled ? { idleSeconds: config.idleSeconds } : {}),
150
+ ...(once ? {
151
+ once: {
152
+ pending: true,
153
+ idleSeconds: once.idleSeconds,
154
+ promptPreview: once.prompt.replace(/\s+/g, ' ').slice(0, 120),
155
+ },
156
+ } : {}),
125
157
  };
126
158
  }
127
159
  export function sessionLoopError(code, message) {
@@ -159,7 +191,8 @@ export class SessionIdleMonitor {
159
191
  return;
160
192
  this.refreshSessionIdleTriggerIds();
161
193
  const triggerPath = event.causation?.trigger?.path ?? [];
162
- if (triggerPath.some(node => this.knownSessionIdleTriggerIds.has(node.triggerId))) {
194
+ if (triggerPath.some(node => this.knownSessionIdleTriggerIds.has(node.triggerId))
195
+ && this.sessions.get(event.sessionId)?.emitted !== false) {
163
196
  this.taskEncryption.delete(event.sessionId);
164
197
  return;
165
198
  }
@@ -176,6 +209,8 @@ export class SessionIdleMonitor {
176
209
  onTaskStarted = (event) => {
177
210
  if (event.type !== 'task:started' || !event.sessionId)
178
211
  return;
212
+ this.clearTimers(event.sessionId);
213
+ this.generations.set(event.sessionId, (this.generations.get(event.sessionId) ?? 0) + 1);
179
214
  if (typeof event.encrypt === 'boolean')
180
215
  this.taskEncryption.set(event.sessionId, event.encrypt);
181
216
  else
@@ -199,7 +234,7 @@ export class SessionIdleMonitor {
199
234
  };
200
235
  onSessionLoopChanged = (event) => {
201
236
  if (event.type === 'session:loop-changed')
202
- void this.refreshSession(event.sessionId, event.timestamp);
237
+ void this.refreshSession(event.sessionId, event.timestamp, true);
203
238
  };
204
239
  constructor(options) {
205
240
  this.options = options;
@@ -226,7 +261,20 @@ export class SessionIdleMonitor {
226
261
  this.active = true;
227
262
  this.refreshSessionIdleTriggerIds();
228
263
  for (const sessionId of this.sessions.keys())
264
+ void this.restorePendingSession(sessionId);
265
+ }
266
+ async restorePendingSession(sessionId) {
267
+ try {
268
+ const session = await this.options.getSessionById(sessionId);
269
+ const state = this.sessions.get(sessionId);
270
+ const pending = session && readSessionLoopOnceConfig(session);
271
+ if (state && pending && state.onceRequestId === pending.requestId)
272
+ state.emitted = false;
229
273
  this.scheduleSession(sessionId);
274
+ }
275
+ catch (error) {
276
+ this.warn(`Failed to restore pending idle check for ${sessionId}`, error);
277
+ }
230
278
  }
231
279
  /**
232
280
  * 重新采集 session:idle trigger 身份。
@@ -238,6 +286,11 @@ export class SessionIdleMonitor {
238
286
  refreshTriggerIdentities() {
239
287
  this.refreshSessionIdleTriggerIds();
240
288
  }
289
+ isCurrentLoopOnceEvent(sessionId, requestId, generation) {
290
+ const state = this.sessions.get(sessionId);
291
+ return this.active && state?.emitted === true && state.onceRequestId === requestId
292
+ && (this.generations.get(sessionId) ?? 0) === generation;
293
+ }
241
294
  /** Re-read relation configuration and re-arm every restored/current session. */
242
295
  refresh() {
243
296
  if (!this.active)
@@ -248,10 +301,15 @@ export class SessionIdleMonitor {
248
301
  this.scheduleSession(sessionId);
249
302
  }
250
303
  }
251
- async refreshSession(sessionId, changedAt = this.now()) {
252
- const state = this.sessions.get(sessionId);
253
- if (!state || !this.active)
254
- return;
304
+ async refreshSession(sessionId, changedAt = this.now(), force = false) {
305
+ let state = this.sessions.get(sessionId);
306
+ if (!state) {
307
+ state = { lastEndedAt: changedAt, armedAt: changedAt, emitted: false };
308
+ this.sessions.set(sessionId, state);
309
+ this.persistState();
310
+ }
311
+ this.clearTimers(sessionId);
312
+ this.generations.set(sessionId, (this.generations.get(sessionId) ?? 0) + 1);
255
313
  const generation = this.generations.get(sessionId) ?? 0;
256
314
  try {
257
315
  const session = await this.options.getSessionById(sessionId);
@@ -260,13 +318,14 @@ export class SessionIdleMonitor {
260
318
  const seconds = await this.readIdleSeconds(session);
261
319
  if (this.sessions.get(sessionId) !== state || (this.generations.get(sessionId) ?? 0) !== generation)
262
320
  return;
263
- if (state.idleSeconds === seconds)
264
- return;
265
- this.clearTimers(sessionId);
266
- this.generations.set(sessionId, generation + 1);
321
+ const pending = readSessionLoopOnceConfig(session);
322
+ const changed = force || state.idleSeconds !== seconds || state.onceRequestId !== pending?.requestId;
267
323
  state.idleSeconds = seconds;
268
- state.armedAt = changedAt;
269
- state.emitted = false;
324
+ state.onceRequestId = pending?.requestId;
325
+ if (changed) {
326
+ state.armedAt = changedAt;
327
+ state.emitted = false;
328
+ }
270
329
  this.persistState();
271
330
  if (seconds !== undefined && !await this.options.isSessionBusy(sessionId))
272
331
  this.scheduleSession(sessionId);
@@ -366,6 +425,7 @@ export class SessionIdleMonitor {
366
425
  return;
367
426
  const idleMs = toIdleMs(idleSeconds);
368
427
  state.idleSeconds = idleSeconds;
428
+ state.onceRequestId = readSessionLoopOnceConfig(session)?.requestId;
369
429
  this.persistState();
370
430
  if (idleMs === undefined)
371
431
  return;
@@ -435,12 +495,24 @@ export class SessionIdleMonitor {
435
495
  this.clearSession(sessionId);
436
496
  return;
437
497
  }
498
+ try {
499
+ session = await this.options.getSessionById(sessionId);
500
+ }
501
+ catch (error) {
502
+ this.warn(`Failed to revalidate idle session ${sessionId}`, error);
503
+ return;
504
+ }
505
+ if (!session?.selfAID || !this.isEligibleSession(session) || !this.isCurrentCycle(sessionId, lastEndedAt, generation))
506
+ return;
438
507
  const state = this.sessions.get(sessionId);
439
508
  if (!state || state.emitted)
440
509
  return;
510
+ const once = readSessionLoopOnceConfig(session);
441
511
  state.emitted = true;
442
- if (!this.persistState())
512
+ if (!this.persistState()) {
513
+ state.emitted = false;
443
514
  return;
515
+ }
444
516
  const topicThreadId = sessionTopicThreadId(session);
445
517
  this.options.eventBus.publish({
446
518
  type: 'session:idle',
@@ -451,12 +523,13 @@ export class SessionIdleMonitor {
451
523
  channelId: session.channelId,
452
524
  chatType: session.chatType,
453
525
  ...(topicThreadId ? { threadId: topicThreadId } : {}),
454
- ...(session.metadata?.peerId || session.channelId ? { peerId: session.metadata?.peerId || session.channelId } : {}),
455
- ...(typeof state.encrypted === 'boolean'
456
- ? { encrypted: state.encrypted }
526
+ peerId: once?.peerId ?? session.metadata?.peerId ?? session.channelId,
527
+ ...(typeof (once?.encrypted ?? state.encrypted) === 'boolean'
528
+ ? { encrypted: once?.encrypted ?? state.encrypted }
457
529
  : typeof session.metadata?.replyContext?.metadata?.encrypted === 'boolean'
458
530
  ? { encrypted: session.metadata.replyContext.metadata.encrypted }
459
531
  : {}),
532
+ ...(once ? { loopPrompt: once.prompt, loopOnceRequestId: once.requestId, loopIdleGeneration: generation } : {}),
460
533
  idleMs,
461
534
  lastEndedAt,
462
535
  timestamp: this.now(),
@@ -493,6 +566,9 @@ export class SessionIdleMonitor {
493
566
  }
494
567
  }
495
568
  async readIdleSeconds(session) {
569
+ const once = readSessionLoopOnceConfig(session);
570
+ if (once)
571
+ return once.idleSeconds;
496
572
  try {
497
573
  return await this.options.getSessionIdleSeconds(session);
498
574
  }
@@ -568,6 +644,7 @@ export class SessionIdleMonitor {
568
644
  ...(typeof rawState.encrypted === 'boolean' ? { encrypted: rawState.encrypted } : {}),
569
645
  ...(typeof rawState.armedAt === 'number' && Number.isFinite(rawState.armedAt) ? { armedAt: rawState.armedAt } : {}),
570
646
  ...(typeof rawState.idleSeconds === 'number' ? { idleSeconds: rawState.idleSeconds } : {}),
647
+ ...(typeof rawState.onceRequestId === 'string' ? { onceRequestId: rawState.onceRequestId } : {}),
571
648
  });
572
649
  }
573
650
  }
@@ -584,6 +661,7 @@ export class SessionIdleMonitor {
584
661
  ...(typeof state.encrypted === 'boolean' ? { encrypted: state.encrypted } : {}),
585
662
  ...(state.armedAt !== undefined ? { armedAt: state.armedAt } : {}),
586
663
  ...(state.idleSeconds !== undefined ? { idleSeconds: state.idleSeconds } : {}),
664
+ ...(state.onceRequestId ? { onceRequestId: state.onceRequestId } : {}),
587
665
  };
588
666
  }
589
667
  try {