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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/README.md +22 -0
  3. package/dist/agents/claude-runner.js +26 -2
  4. package/dist/agents/codex/app-server-client.js +12 -0
  5. package/dist/agents/codex-runner.js +49 -8
  6. package/dist/agents/ecagent-runner.js +39 -15
  7. package/dist/agents/gemini-runner.js +15 -12
  8. package/dist/agents/tool-time-context.js +55 -0
  9. package/dist/aun/aid/agentmd.js +21 -1
  10. package/dist/aun/menu/client.js +1 -1
  11. package/dist/aun/model-headers.js +17 -0
  12. package/dist/aun/msg/p2p.js +7 -2
  13. package/dist/channels/aun.js +522 -50
  14. package/dist/channels/builtin-plugins.js +16 -11
  15. package/dist/channels/daemon.js +4 -0
  16. package/dist/channels/dingtalk.js +83 -31
  17. package/dist/channels/feishu.js +29 -13
  18. package/dist/channels/qqbot.js +32 -11
  19. package/dist/channels/wechat.js +13 -3
  20. package/dist/channels/wecom.js +67 -27
  21. package/dist/cli/agent-command.js +3 -86
  22. package/dist/cli/agent-create.js +20 -6
  23. package/dist/cli/agent.js +1 -79
  24. package/dist/cli/aun-commands.js +18 -19
  25. package/dist/cli/config.js +1 -1
  26. package/dist/cli/daemon-commands.js +47 -2
  27. package/dist/cli/data-command.js +9 -1
  28. package/dist/cli/debug-mode.js +1 -1
  29. package/dist/cli/diag.js +1 -1
  30. package/dist/cli/directory.js +149 -91
  31. package/dist/cli/getmeta-command.js +1 -1
  32. package/dist/cli/index.js +79 -22
  33. package/dist/cli/init.js +1 -23
  34. package/dist/cli/link-rules.js +1 -1
  35. package/dist/cli/managed-command-guard.js +0 -1
  36. package/dist/cli/pa-workspace-command.js +36 -2
  37. package/dist/cli/peer.js +3 -2
  38. package/dist/cli/restart-monitor.js +17 -3
  39. package/dist/cli/role.js +1 -1
  40. package/dist/cli/session-command.js +1 -1
  41. package/dist/cli/stats.js +2 -2
  42. package/dist/cli/task-context.js +3 -1
  43. package/dist/cli/thread-command.js +1 -1
  44. package/dist/cli/watch-msg.js +1 -1
  45. package/dist/config/builtin-role-templates.js +2 -2
  46. package/dist/config/builtin-roles.js +2 -1
  47. package/dist/config/config-field-policy.js +7 -2
  48. package/dist/config/config-manager.js +32 -10
  49. package/dist/config/peer-role-resolver.js +23 -1
  50. package/dist/config/role-schema.js +29 -4
  51. package/dist/config/role-service.js +12 -7
  52. package/dist/config/role-store.js +30 -8
  53. package/dist/config-store.js +75 -4
  54. package/dist/core/agent-ipc-registration.js +16 -59
  55. package/dist/core/auth/auth-gateway.js +14 -4
  56. package/dist/core/auth/authorization-audit.js +52 -14
  57. package/dist/core/auth/operation-authorizer.js +17 -11
  58. package/dist/core/auth/operation-catalog.js +5 -13
  59. package/dist/core/channel-loader.js +152 -16
  60. package/dist/core/channel-runtime.js +5 -0
  61. package/dist/core/command/agent-control.js +2 -1
  62. package/dist/core/command/agentmd-menu-request.js +50 -0
  63. package/dist/core/command/agentmd-menu.js +156 -0
  64. package/dist/core/command/cli-intent-parser.js +0 -8
  65. package/dist/core/command/command-handler.js +47 -40
  66. package/dist/core/command/connect-menu.js +7 -3
  67. package/dist/core/command/menu-catalog.js +16 -2
  68. package/dist/core/command/menu-handler.js +107 -14
  69. package/dist/core/command/menu-protocol.js +28 -0
  70. package/dist/core/command/role-menu.js +23 -9
  71. package/dist/core/command/slash-handler.js +139 -51
  72. package/dist/core/daemon-file-cache.js +3 -3
  73. package/dist/core/daemon-lifecycle.js +9 -1
  74. package/dist/core/evolagent-registry.js +5 -4
  75. package/dist/core/evolagent.js +10 -12
  76. package/dist/core/handoff/argv-parse.js +115 -0
  77. package/dist/core/handoff/ipc-registration.js +1 -1
  78. package/dist/core/ipc-registration.js +19 -2
  79. package/dist/core/lifecycle-notice.js +185 -0
  80. package/dist/core/memory/consolidation.js +8 -1
  81. package/dist/core/memory/relation-sweep.js +20 -8
  82. package/dist/core/message/aun-ipc-sender.js +35 -2
  83. package/dist/core/message/contact-admission.js +530 -0
  84. package/dist/core/message/im-renderer.js +111 -16
  85. package/dist/core/message/message-admission.js +29 -54
  86. package/dist/core/message/message-bridge.js +62 -8
  87. package/dist/core/message/message-utils.js +9 -5
  88. package/dist/core/message/peer-mode.js +55 -13
  89. package/dist/core/message/response-engine.js +298 -78
  90. package/dist/core/message/retry-scheduler.js +4 -0
  91. package/dist/core/ownership/owner-resolver.js +72 -34
  92. package/dist/core/permission/ec-command-parser.js +25 -38
  93. package/dist/core/permission/readonly-shell-query.js +34 -8
  94. package/dist/core/permission/tool-policy.js +50 -5
  95. package/dist/core/relation/pa-team.js +127 -0
  96. package/dist/core/role/runtime-policy.js +18 -5
  97. package/dist/core/session/session-manager.js +9 -1
  98. package/dist/core/soul.js +66 -0
  99. package/dist/core/system-session/memory.js +2 -2
  100. package/dist/core/thread/thread-service.js +6 -4
  101. package/dist/directory/contact-admission-paths.js +9 -0
  102. package/dist/directory/owner-directory-admission.js +125 -29
  103. package/dist/directory/owner-directory-cache.js +554 -58
  104. package/dist/directory/owner-directory-identity.js +60 -0
  105. package/dist/directory/owner-directory-markdown.js +154 -58
  106. package/dist/directory/owner-directory-policy.js +108 -0
  107. package/dist/directory/owner-directory-query-operation.js +399 -90
  108. package/dist/directory/owner-directory-remarks.js +29 -2
  109. package/dist/directory/owner-directory-request-operation.js +76 -0
  110. package/dist/directory/owner-directory-scope.js +35 -4
  111. package/dist/directory/owner-directory-search.js +118 -33
  112. package/dist/directory/owner-directory-store.js +117 -30
  113. package/dist/directory/owner-directory-text.js +60 -0
  114. package/dist/eck/kit-renderer.js +18 -8
  115. package/dist/eck/manifest-engine.js +55 -6
  116. package/dist/ecweb/basic-settings-service.js +2 -2
  117. package/dist/ecweb/message-context-service.js +28 -16
  118. package/dist/index.js +20 -5
  119. package/dist/ipc.js +1 -1
  120. package/dist/paths.js +29 -1
  121. package/dist/product.js +1 -0
  122. package/dist/response-system/config-resolver.js +1 -1
  123. package/dist/response-system/engines/v1/index.js +2 -1
  124. package/dist/response-system/modes/single-session/index.js +7 -2
  125. package/dist/trigger/scheduler.js +7 -4
  126. package/dist/trigger/validation.js +4 -0
  127. package/dist/utils/error-utils.js +12 -7
  128. package/dist/utils/logger.js +13 -4
  129. package/dist/utils/npm-ops.js +2 -2
  130. package/dist/utils/windows-autostart.js +1 -1
  131. package/ecagent/README.md +18 -0
  132. package/ecagent/dist/agent-loop.js +43 -1
  133. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  134. package/ecagent/dist/harness/agent-harness.js +24 -8
  135. package/ecagent/dist/harness/compaction/compaction.js +3 -0
  136. package/ecagent/dist/harness/types.d.ts +1 -0
  137. package/kits/docs/INDEX.md +1 -0
  138. package/kits/docs/channels/aun.md +1 -1
  139. package/kits/docs/context-assembly.md +21 -6
  140. package/kits/docs/eck_templates/INDEX.template.md +1 -2
  141. package/kits/docs/evolcore/INDEX.md +4 -1
  142. package/kits/docs/evolcore/agent-create.md +5 -5
  143. package/kits/docs/evolcore/agent.md +4 -9
  144. package/kits/docs/evolcore/directory.md +227 -0
  145. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  146. package/kits/docs/evolcore/file-navigation.md +265 -0
  147. package/kits/docs/evolcore/menu-protocol.md +55 -0
  148. package/kits/docs/evolcore/msg.md +1 -0
  149. package/kits/docs/evolcore/peer.md +2 -1
  150. package/kits/docs/evolcore/response.md +7 -1
  151. package/kits/docs/evolcore/task.md +2 -0
  152. package/kits/docs/evolcore/tool-authorization.md +1 -1
  153. package/kits/docs/evolcore/trigger.md +4 -0
  154. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  155. package/kits/docs/prompt-loading-architecture.md +6 -2
  156. package/kits/eck_manifest.auxiliary.json +1 -0
  157. package/kits/eck_manifest.json +64 -7
  158. package/kits/eck_manifest.memory.json +93 -4
  159. package/kits/rules/01-overview.md +2 -2
  160. package/kits/rules/03-identity.md +10 -9
  161. package/kits/rules/05-venue.md +2 -4
  162. package/kits/rules/06-channel.md +1 -1
  163. package/kits/schemas/_meta.json +44 -3
  164. package/kits/schemas/agent-config.schema.18.json +5 -0
  165. package/kits/schemas/agent-config.schema.19.json +924 -0
  166. package/kits/schemas/agent-config.schema.20.json +925 -0
  167. package/kits/schemas/relation-config.schema.12.json +289 -0
  168. package/kits/schemas/relation-config.schema.13.json +289 -0
  169. package/kits/schemas/role-config.schema.2.json +215 -0
  170. package/kits/schemas/role-config.schema.3.json +1038 -0
  171. package/kits/schemas/role-registry.schema.1.json +3 -2
  172. package/kits/skills/ec-skill/scripts/cli.mjs +3 -2
  173. package/kits/skills/ec-trigger/SKILL.md +4 -4
  174. package/kits/skills/personal-assistant/SKILL.md +109 -53
  175. package/kits/skills/personal-assistant/references/02-bootstrap.md +73 -30
  176. package/kits/skills/personal-assistant/scripts/clean.mjs +35 -18
  177. package/kits/skills/personal-assistant/scripts/init.mjs +41 -2
  178. package/kits/skills/personal-assistant/scripts/lib/persona.mjs +185 -0
  179. package/kits/skills/personal-assistant/scripts/migrate.mjs +55 -4
  180. package/kits/skills/personal-assistant/scripts/pa.mjs +173 -0
  181. package/kits/skills/personal-assistant/scripts/uninstall.mjs +130 -0
  182. package/kits/skills/personal-assistant/templates/persona-section.md +3 -3
  183. package/kits/templates/message-fragments/handoff-request-to-target.md +1 -1
  184. package/kits/templates/soul/00-GUIDE.md +39 -0
  185. package/kits/templates/soul/01-identity.md +5 -0
  186. package/kits/templates/soul/02-persona.md +11 -0
  187. package/kits/templates/soul/03-duties.md +5 -0
  188. package/kits/templates/soul/04-working-style.md +5 -0
  189. package/kits/templates/system-fragments/bootstrap.md +7 -7
  190. package/kits/templates/system-fragments/channel.md +2 -2
  191. package/kits/templates/system-fragments/commands.md +3 -2
  192. package/kits/templates/system-fragments/directory-contacts.md +9 -0
  193. package/kits/templates/system-fragments/memory.md +1 -1
  194. package/kits/templates/system-fragments/personal-assistant.md +50 -0
  195. package/kits/templates/system-fragments/reply.md +7 -0
  196. package/kits/templates/system-fragments/session.md +6 -2
  197. package/package.json +3 -2
  198. package/dist/cli/handoff-command.js +0 -353
  199. package/dist/directory/owner-directory-remark-operation.js +0 -147
  200. package/kits/docs/evolcore/self-summary.md +0 -29
@@ -1,7 +1,6 @@
1
- import path from 'path';
2
1
  import { formatChannelKey, tryParseChannelKey } from './channel-loader.js';
3
- import { agentPersonalDir } from '../paths.js';
4
2
  import { fileCache } from './daemon-file-cache.js';
3
+ import { readSoulContent } from './soul.js';
5
4
  import { ConfigTarget, assertAgentModelConfigured, read as cfgRead, write as cfgWrite, ensureFile as cfgEnsure, resolveEffective } from '../config/config-manager.js';
6
5
  import { withLifecycleForWrite } from '../config/lifecycle.js';
7
6
  import { isStaticAgentAdmin, isStaticAgentOwner } from '../config/peer-role-resolver.js';
@@ -270,14 +269,12 @@ export class EvolAgent {
270
269
  return `agent-files:${this.aid}`;
271
270
  }
272
271
  /**
273
- * 读取 personal/persona.md 内容。走 fileCache(mtime 门控):persona 可由
274
- * `ec agent persona` 或 agent 自己更新,与 working memory 一样改了即应生效,
275
- * 故每次读 stat 比对、变了自动重读。文件不存在返回 null。
272
+ * 读取 soul 目录里的自我定义内容(`personal/soul/*.md`,按文件名排序)。
273
+ * 具体过滤规则见 `readSoulContent`:跳过机制指南与空文件,剥掉 HTML 注释后判空。
274
+ * 走 fileCache 的 mtime 策略,改了下一轮即生效。
276
275
  */
277
276
  getPersona() {
278
- const personaPath = path.join(agentPersonalDir(this.aid), 'persona.md');
279
- const raw = fileCache.getText(personaPath, { policy: 'mtime', group: this.agentFilesGroup() });
280
- return raw === null ? null : (raw.trim() || null);
277
+ return readSoulContent(this.aid);
281
278
  }
282
279
  /** 清除本 agent 身份层缓存(reload 后重新读取)。只失效自己的文件组,不波及他人。 */
283
280
  invalidatePersonaCache() {
@@ -297,10 +294,11 @@ export class EvolAgent {
297
294
  };
298
295
  }
299
296
  resolveChatMode(chatType, globalChatmode) {
300
- const key = chatType === 'group' ? 'group' : 'private';
301
- return (this.merged.chatmode?.[key]
302
- ?? globalChatmode?.[key]
303
- ?? (key === 'group' ? 'proactive' : 'interactive'));
297
+ if (chatType === 'group')
298
+ return 'proactive';
299
+ return (this.merged.chatmode?.private
300
+ ?? globalChatmode?.private
301
+ ?? 'interactive');
304
302
  }
305
303
  // ── Reload 支持:替换 in-memory config 并复用 channels Map ───────────
306
304
  /** 用新的 raw + merged 替换 in-memory 状态。channels 由调用方决定如何 reconcile。 */
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Handoff argv 解析。
3
+ *
4
+ * `ec handoff` 命令入口已移除,但 daemon 侧仍通过 IPC 接收 handoff 报文
5
+ * (`handoff-return` / `handoff-recover-return` / `handoff-status` /
6
+ * `handoff-list` / `handoff-trace`),需要在 core 层解析这些 argv。
7
+ * 这里只放纯解析逻辑,不做任何 IPC 或输出。
8
+ */
9
+ import fs from 'fs';
10
+ import { HANDOFF_QUERY_DEFAULT_LIMIT, HANDOFF_QUERY_MAX_LIMIT, HANDOFF_STATES } from './types.js';
11
+ import { HANDOFF_ID_RE } from './store.js';
12
+ import { canonicalizeEvolcoreCommandArgv } from '../permission/ec-command-parser.js';
13
+ import { MAIN_CLI_BIN } from '../../product.js';
14
+ function parseLimit(value) {
15
+ const limit = Number(value);
16
+ if (!value || !Number.isInteger(limit) || limit < 1 || limit > HANDOFF_QUERY_MAX_LIMIT) {
17
+ throw new Error('INVALID_HANDOFF_LIMIT');
18
+ }
19
+ return limit;
20
+ }
21
+ export function parseList(args) {
22
+ const parsed = { limit: HANDOFF_QUERY_DEFAULT_LIMIT };
23
+ for (let index = 0; index < args.length; index++) {
24
+ const arg = args[index];
25
+ const value = args[index + 1];
26
+ if (arg === '--state') {
27
+ if (!value || !HANDOFF_STATES.includes(value))
28
+ throw new Error('INVALID_HANDOFF_STATE');
29
+ parsed.state = value;
30
+ index++;
31
+ }
32
+ else if (arg === '--session') {
33
+ if (!value)
34
+ throw new Error('HANDOFF_SESSION_REQUIRED');
35
+ parsed.sessionId = value;
36
+ index++;
37
+ }
38
+ else if (arg === '--agent') {
39
+ if (!value)
40
+ throw new Error('HANDOFF_AGENT_REQUIRED');
41
+ parsed.agent = value;
42
+ index++;
43
+ }
44
+ else if (arg === '--limit') {
45
+ parsed.limit = parseLimit(value);
46
+ index++;
47
+ }
48
+ else {
49
+ throw new Error(`UNKNOWN_HANDOFF_OPTION:${arg}`);
50
+ }
51
+ }
52
+ return parsed;
53
+ }
54
+ export function parseTrace(args) {
55
+ const handoffId = args[0];
56
+ if (!handoffId || !HANDOFF_ID_RE.test(handoffId))
57
+ throw new Error('INVALID_HANDOFF_ID');
58
+ const parsed = { handoffId, limit: HANDOFF_QUERY_DEFAULT_LIMIT };
59
+ for (let index = 1; index < args.length; index++) {
60
+ const arg = args[index];
61
+ const value = args[index + 1];
62
+ if (arg === '--agent') {
63
+ if (!value)
64
+ throw new Error('HANDOFF_AGENT_REQUIRED');
65
+ parsed.agent = value;
66
+ index++;
67
+ }
68
+ else if (arg === '--limit') {
69
+ parsed.limit = parseLimit(value);
70
+ index++;
71
+ }
72
+ else {
73
+ throw new Error(`UNKNOWN_HANDOFF_OPTION:${arg}`);
74
+ }
75
+ }
76
+ return parsed;
77
+ }
78
+ export function parseReturn(args, options = {}) {
79
+ if (!options.canonical)
80
+ args = canonicalizeEvolcoreCommandArgv([MAIN_CLI_BIN, 'handoff', 'return', ...args]).slice(3);
81
+ const dash = args.indexOf('--');
82
+ if (dash >= 0) {
83
+ const beforeDash = args.slice(0, dash);
84
+ const first = beforeDash[0];
85
+ if (first?.startsWith('h-') && !HANDOFF_ID_RE.test(first))
86
+ throw new Error(`INVALID_HANDOFF_ID:${first}`);
87
+ const handoffId = first && HANDOFF_ID_RE.test(first) ? first : undefined;
88
+ if (beforeDash.length > (handoffId ? 1 : 0))
89
+ throw new Error('HANDOFF_CONTENT_DELIMITER_CONFLICT');
90
+ return { handoffId, content: args.slice(dash + 1).join(' ') };
91
+ }
92
+ const fileIndex = args.indexOf('--text-from-file');
93
+ const filePath = fileIndex >= 0 ? args[fileIndex + 1] : undefined;
94
+ if (fileIndex >= 0 && !filePath)
95
+ throw new Error('HANDOFF_CONTENT_FILE_READ_FAILED');
96
+ const positional = args.filter((_, index) => fileIndex < 0 || (index !== fileIndex && index !== fileIndex + 1));
97
+ const first = positional[0];
98
+ if (first?.startsWith('h-') && !HANDOFF_ID_RE.test(first))
99
+ throw new Error(`INVALID_HANDOFF_ID:${first}`);
100
+ const handoffId = first && HANDOFF_ID_RE.test(first) ? first : undefined;
101
+ const contentArgs = handoffId ? positional.slice(1) : positional;
102
+ if (filePath && contentArgs.length > 0)
103
+ throw new Error('HANDOFF_CONTENT_FILE_CONFLICT');
104
+ if (filePath) {
105
+ if (options.deferFileRead)
106
+ return { handoffId, content: '' };
107
+ try {
108
+ return { handoffId, content: options.readFile ? options.readFile(filePath) : fs.readFileSync(filePath, 'utf8') };
109
+ }
110
+ catch {
111
+ throw new Error('HANDOFF_CONTENT_FILE_READ_FAILED');
112
+ }
113
+ }
114
+ return { handoffId, content: contentArgs.join(' ') };
115
+ }
@@ -2,7 +2,7 @@ import { isManagementRole } from '../../config/builtin-roles.js';
2
2
  import { hasTrustedFullAccessDelegation, trustedExecutionIdentityInput, } from '../auth/agent-delegation.js';
3
3
  import { authorizeFreshOperation as authorizeOperation, buildAuthSubject } from '../auth/auth-gateway.js';
4
4
  import { parsePeerKey } from '../relation/peer-identity.js';
5
- import { parseReturn } from '../../cli/handoff-command.js';
5
+ import { parseReturn } from './argv-parse.js';
6
6
  import { readTriggerLocalFile } from '../../trigger/local-files.js';
7
7
  export function registerHandoffIpc({ ipcServer, agentDelegationRegistry, responseEngine, sessionManager, agentRegistry, handoffRuntime, getProcessOwners, }) {
8
8
  const resolveManagedHandoffScope = async (params, operation) => {
@@ -313,15 +313,31 @@ export function createIpcStatusProvider(dependencies) {
313
313
  return () => {
314
314
  const channels = {};
315
315
  const channelsByType = {};
316
+ const channelRuntime = dependencies.getChannelRuntimeSnapshot?.();
316
317
  for (const instance of dependencies.channelInstances) {
317
318
  const name = instance.adapter.channelName;
318
- const status = instance.channel.getStatus?.() ?? { connected: true };
319
319
  const channelType = instance.channelType || name;
320
- channels[name] = { ...status, channelType };
320
+ try {
321
+ const status = instance.channel.getStatus?.() ?? { connected: false };
322
+ channels[name] = { ...status, channelType };
323
+ }
324
+ catch {
325
+ channels[name] = { connected: false, channelType, status: 'failed', reason: { code: 'STATUS_FAILED', message: '渠道状态读取失败' } };
326
+ }
321
327
  if (!channelsByType[channelType])
322
328
  channelsByType[channelType] = [];
323
329
  channelsByType[channelType].push(name);
324
330
  }
331
+ for (const instance of channelRuntime?.instances ?? []) {
332
+ const { channelName, channelType, status, reason, agentAid } = instance;
333
+ channels[channelName] = {
334
+ ...channels[channelName], channelType, agentAid, status, connected: status === 'connected',
335
+ ...(reason ? { reason } : {}),
336
+ };
337
+ const names = channelsByType[channelType] ??= [];
338
+ if (!names.includes(channelName))
339
+ names.push(channelName);
340
+ }
325
341
  const snapshot = dependencies.statsCollector.getSnapshot();
326
342
  const agents = dependencies.agentRegistry.list();
327
343
  const runtimeError = dependencies.getAgentRuntimeError();
@@ -361,6 +377,7 @@ export function createIpcStatusProvider(dependencies) {
361
377
  } : {}),
362
378
  channels,
363
379
  channelsByType,
380
+ ...(channelRuntime ? { channelRuntime } : {}),
364
381
  queue: { pending: dependencies.messageQueue.getGlobalQueueLength(), processing: dependencies.messageQueue.getGlobalProcessingCount() },
365
382
  ...(dependencies.getTriggerSummary ? { triggers: dependencies.getTriggerSummary() } : {}),
366
383
  ...(dependencies.getStatusSnapshot ? dependencies.getStatusSnapshot() : {}),
@@ -0,0 +1,185 @@
1
+ import { ownerResolver } from './ownership/owner-resolver.js';
2
+ import { resolveAgentDisplayName } from '../aun/aid/agentmd.js';
3
+ import { isValidAid } from '../aun/aid/validation.js';
4
+ import { logger } from '../utils/logger.js';
5
+ /** AUN volatile TTL for online/offline notices; the gateway caps this at 3600s. */
6
+ export const LIFECYCLE_NOTICE_TTL_SECONDS = 1_800;
7
+ /** Owner consensus checks are retried at these offsets after a channel connects. */
8
+ export const ONLINE_OWNER_RETRY_DELAYS_MS = [0, 2_000, 6_000];
9
+ /** Shutdown is time-boxed: a missed offline notice is acceptable, a hung exit is not. */
10
+ export const OFFLINE_SINGLE_SEND_MS = 1_200;
11
+ export const OFFLINE_TOTAL_BUDGET_MS = 1_500;
12
+ function normalizeAid(value) {
13
+ const aid = String(value ?? '').trim();
14
+ return aid.startsWith('@') ? aid.slice(1) : aid;
15
+ }
16
+ function confirmedOwner(view) {
17
+ if (!view || view.consensusStatus !== 'consensus')
18
+ return undefined;
19
+ const owner = normalizeAid(view.ownerAid);
20
+ return isValidAid(owner) ? owner : undefined;
21
+ }
22
+ function channelInstanceAid(instance, agent) {
23
+ const channel = instance.channel;
24
+ return normalizeAid(channel?.getAid?.() ?? agent?.aid);
25
+ }
26
+ function isAun(instance) {
27
+ return instance.channelType === 'aun';
28
+ }
29
+ function sleep(ms) {
30
+ if (ms <= 0)
31
+ return Promise.resolve();
32
+ return new Promise(resolve => {
33
+ const timer = setTimeout(resolve, ms);
34
+ timer.unref?.();
35
+ });
36
+ }
37
+ /** Await a promise at most `ms`, swallowing both timeout and rejection. */
38
+ async function settleWithin(promise, ms) {
39
+ let timer;
40
+ try {
41
+ await Promise.race([
42
+ promise.then(() => undefined, () => undefined),
43
+ new Promise(resolve => {
44
+ timer = setTimeout(resolve, ms);
45
+ timer.unref?.();
46
+ }),
47
+ ]);
48
+ }
49
+ finally {
50
+ if (timer)
51
+ clearTimeout(timer);
52
+ }
53
+ }
54
+ export function createLifecycleNoticeService(deps) {
55
+ const log = deps.log ?? logger;
56
+ const retryDelaysMs = deps.timing?.retryDelaysMs ?? ONLINE_OWNER_RETRY_DELAYS_MS;
57
+ const onlineSendMs = deps.timing?.onlineSendMs ?? OFFLINE_SINGLE_SEND_MS;
58
+ const offlineSingleMs = deps.timing?.offlineSingleMs ?? OFFLINE_SINGLE_SEND_MS;
59
+ const offlineTotalMs = deps.timing?.offlineTotalMs ?? OFFLINE_TOTAL_BUDGET_MS;
60
+ const lookup = deps.ownerLookup ?? {
61
+ refreshOwner: aid => ownerResolver.refresh(aid, {
62
+ force: true,
63
+ source: 'daemon.lifecycle.online',
64
+ }),
65
+ owner: aid => ownerResolver.owner(aid),
66
+ onChange: listener => ownerResolver.onChange(listener),
67
+ };
68
+ /**
69
+ * SIGINT/SIGTERM 会先跑 `onShutdown(() => ownerResolver.stop())`,进入 daemon
70
+ * shutdown 时共识缓存已被清空。上下线通知都依赖这份进程内缓存。
71
+ */
72
+ const confirmedOwners = new Map();
73
+ const onlineInFlight = new Set();
74
+ let onlineStopped = false;
75
+ let offlineSent = false;
76
+ const unsubscribe = lookup.onChange((subjectAid, ownerAid) => {
77
+ const aid = normalizeAid(subjectAid);
78
+ const owner = normalizeAid(ownerAid);
79
+ if (aid && owner && isValidAid(owner) && owner !== aid)
80
+ confirmedOwners.set(aid, owner);
81
+ else if (aid)
82
+ confirmedOwners.delete(aid);
83
+ });
84
+ const agentNameFor = (selfAid) => resolveAgentDisplayName(selfAid) || selfAid.split('.')[0] || selfAid;
85
+ async function sendOne(instance, selfAid, ownerAid, online) {
86
+ const channel = instance.channel;
87
+ if (typeof channel?.sendLifecycleNotice !== 'function') {
88
+ log.warn(`[Lifecycle] AUN channel for ${selfAid} does not expose sendLifecycleNotice`);
89
+ return;
90
+ }
91
+ try {
92
+ const result = await channel.sendLifecycleNotice({
93
+ to: ownerAid,
94
+ agentName: agentNameFor(selfAid),
95
+ online,
96
+ ttlSeconds: LIFECYCLE_NOTICE_TTL_SECONDS,
97
+ });
98
+ if (result?.ok !== true) {
99
+ log.warn(`[Lifecycle] ${online ? 'online' : 'offline'} notice ${selfAid} -> ${ownerAid} failed: `
100
+ + `${result?.code ?? ''} ${result?.error ?? ''}`.trim());
101
+ }
102
+ }
103
+ catch (error) {
104
+ log.warn(`[Lifecycle] ${online ? 'online' : 'offline'} notice ${selfAid} -> ${ownerAid} failed: `
105
+ + `${error instanceof Error ? error.message : String(error)}`);
106
+ }
107
+ }
108
+ async function runOnline(instance, selfAid) {
109
+ for (const delay of retryDelaysMs) {
110
+ if (delay > 0)
111
+ await sleep(delay);
112
+ if (onlineStopped)
113
+ return;
114
+ let owner;
115
+ try {
116
+ owner = confirmedOwner(await lookup.refreshOwner(selfAid));
117
+ }
118
+ catch (error) {
119
+ log.debug(`[Lifecycle] ownership refresh for ${selfAid} failed: `
120
+ + `${error instanceof Error ? error.message : String(error)}`);
121
+ }
122
+ if (!owner || owner === selfAid)
123
+ continue;
124
+ confirmedOwners.set(selfAid, owner);
125
+ await settleWithin(sendOne(instance, selfAid, owner, true), onlineSendMs);
126
+ return;
127
+ }
128
+ log.info(`[Lifecycle] ${selfAid} has no Ownership consensus; online notice skipped`);
129
+ }
130
+ function online(instance) {
131
+ if (onlineStopped || !isAun(instance))
132
+ return;
133
+ const agent = deps.resolveAgent(instance.adapter.channelKey, instance.adapter.channelName);
134
+ if (!agent)
135
+ return;
136
+ const selfAid = channelInstanceAid(instance, agent);
137
+ if (!selfAid || onlineInFlight.has(selfAid))
138
+ return;
139
+ onlineInFlight.add(selfAid);
140
+ void runOnline(instance, selfAid)
141
+ .catch(error => log.warn(`[Lifecycle] online notice for ${selfAid} failed: `
142
+ + `${error instanceof Error ? error.message : String(error)}`))
143
+ .finally(() => onlineInFlight.delete(selfAid));
144
+ }
145
+ function beginShutdown() {
146
+ onlineStopped = true;
147
+ unsubscribe();
148
+ }
149
+ async function sendOffline(signal) {
150
+ if (offlineSent)
151
+ return;
152
+ offlineSent = true;
153
+ const seen = new Set();
154
+ const jobs = [];
155
+ for (const instance of deps.channelInstances) {
156
+ if (!isAun(instance))
157
+ continue;
158
+ const agent = deps.resolveAgent(instance.adapter.channelKey, instance.adapter.channelName);
159
+ const selfAid = channelInstanceAid(instance, agent);
160
+ if (!selfAid || seen.has(selfAid))
161
+ continue;
162
+ seen.add(selfAid);
163
+ const owner = confirmedOwners.get(selfAid) ?? confirmedOwnerFromResolver(selfAid);
164
+ if (!owner) {
165
+ log.debug(`[Lifecycle] ${selfAid} has no confirmed Owner; offline notice skipped`);
166
+ continue;
167
+ }
168
+ jobs.push(settleWithin(sendOne(instance, selfAid, owner, false), offlineSingleMs));
169
+ }
170
+ if (jobs.length === 0)
171
+ return;
172
+ log.info(`[Lifecycle] sending ${jobs.length} offline notice(s) (signal=${signal ?? 'unknown'})`);
173
+ await settleWithin(Promise.allSettled(jobs), offlineTotalMs);
174
+ }
175
+ function confirmedOwnerFromResolver(selfAid) {
176
+ try {
177
+ const owner = normalizeAid(lookup.owner(selfAid));
178
+ return owner && isValidAid(owner) && owner !== selfAid ? owner : undefined;
179
+ }
180
+ catch {
181
+ return undefined;
182
+ }
183
+ }
184
+ return { online, beginShutdown, sendOffline };
185
+ }
@@ -828,13 +828,16 @@ export function createConsolidationSessionFinalizer({ sessionManager, getAgent,
828
828
  // 读不到会话或批次目录时也要通知一次(只带 sessionId,链按它认领),否则链只能干等看门狗
829
829
  finalizedInfo = { sessionId, success, touchedPeerKeys: [] };
830
830
  const session = await sessionManager.getSessionById(sessionId);
831
- if (!session)
831
+ if (!session) {
832
+ success = false;
832
833
  return;
834
+ }
833
835
  const meta = (session.metadata ?? {});
834
836
  if (typeof meta.relationSweepId === 'string')
835
837
  finalizedInfo.relationSweepId = meta.relationSweepId;
836
838
  const batchDir = (meta.consolidationBatchDir ?? meta.consolidationLogBase);
837
839
  if (!batchDir) {
840
+ success = false;
838
841
  // 没有批次目录就没有流水可写;这是链路级的断裂,至少要能在日志里对上层
839
842
  logger.warn(`[Memory] 整理会话缺少批次目录,跳过收尾(session=${sessionId},`
840
843
  + `hasSession=${!!session},metadata 键=${Object.keys(meta).join(',') || '<空>'})`);
@@ -1113,6 +1116,7 @@ export function createConsolidationSessionFinalizer({ sessionManager, getAgent,
1113
1116
  }
1114
1117
  }
1115
1118
  catch (error) {
1119
+ success = false;
1116
1120
  logger.warn(`[Memory] 整理收尾失败(session=${sessionId}): ${error?.message}`);
1117
1121
  // 收尾本身抛错:批次目录可能已进入中间状态,把错误码与栈留在流水里
1118
1122
  if (batchDirForLog) {
@@ -1127,6 +1131,9 @@ export function createConsolidationSessionFinalizer({ sessionManager, getAgent,
1127
1131
  releaseSlot(releaseAid, sessionId);
1128
1132
  // 槽位释放之后再通知:链的下一步入队时,本 agent 的串行队列已经空出来
1129
1133
  if (finalizedInfo && onSessionFinalized) {
1134
+ finalizedInfo.success = success;
1135
+ if (!success)
1136
+ finalizedInfo.touchedPeerKeys = [];
1130
1137
  try {
1131
1138
  onSessionFinalized(finalizedInfo);
1132
1139
  }
@@ -22,7 +22,7 @@ import { logger } from '../../utils/logger.js';
22
22
  import { RELATION_SWEEP_ORDER, judgeRelationMode } from './consolidation-trigger.js';
23
23
  import { taskContextOfRoute } from './relation-idle-monitor.js';
24
24
  import { parsePeerKey } from '../relation/peer-identity.js';
25
- /** 单步整理会话迟迟不收尾时,链最多等这么久就放弃(整理会话自身 15 分钟超时,留余量)。 */
25
+ /** 单步整理会话迟迟不收尾时,链最多等这么久;队列自身 15 分钟超时后留出收尾余量。 */
26
26
  const DEFAULT_STEP_WATCHDOG_MS = 30 * 60_000;
27
27
  /**
28
28
  * 写进会话 metadata 的 relationSweepId 带上步骤序号:`<链 id>#<步骤序号>`。
@@ -77,8 +77,11 @@ export class RelationSweepRunner {
77
77
  if (peerKey !== state.request.peerKey)
78
78
  state.touched.add(peerKey);
79
79
  }
80
- if (!info.success)
80
+ if (!info.success) {
81
81
  state.failed = true;
82
+ this.stop(state);
83
+ return;
84
+ }
82
85
  this.stepDone(state);
83
86
  }
84
87
  /** 排队后拉起失败的通知(来自 ConsolidationQueue.setLaunchFailedListener)。 */
@@ -87,7 +90,7 @@ export class RelationSweepRunner {
87
90
  if (!state)
88
91
  return;
89
92
  state.failed = true;
90
- this.stepDone(state);
93
+ this.stop(state);
91
94
  }
92
95
  /** 回调对应的是某条链**正在等的那一步**时返回该链;过期步骤、无关会话返回 undefined。 */
93
96
  currentStep(tag, sessionId) {
@@ -121,6 +124,15 @@ export class RelationSweepRunner {
121
124
  state.waitingSessionId = undefined;
122
125
  void this.advance(state);
123
126
  }
127
+ stop(state) {
128
+ if (state.watchdog)
129
+ clearTimeout(state.watchdog);
130
+ state.watchdog = undefined;
131
+ state.waiting = undefined;
132
+ state.waitingSessionId = undefined;
133
+ state.remaining = [];
134
+ this.finish(state);
135
+ }
124
136
  async advance(state) {
125
137
  const { selfAid, peerKey, route, force } = state.request;
126
138
  while (state.remaining.length > 0) {
@@ -177,18 +189,18 @@ export class RelationSweepRunner {
177
189
  return;
178
190
  }
179
191
  if (!launched) {
180
- // 立即拉起失败:这一步作废,继续下一步
181
- state.waiting = undefined;
192
+ // 立即拉起失败:依赖当前步骤的后续步骤不再运行
182
193
  state.failed = true;
183
- continue;
194
+ this.stop(state);
195
+ return;
184
196
  }
185
197
  state.ran.push(mode);
186
198
  if (launched.executionSessionId)
187
199
  state.waitingSessionId = launched.executionSessionId;
188
200
  state.watchdog = setTimeout(() => {
189
- logger.warn(`[Memory] 关系整理链等待收尾超时,跳过该步(peerKey=${peerKey},mode=${mode})`);
201
+ logger.warn(`[Memory] 关系整理链等待收尾超时,停止后续步骤(peerKey=${peerKey},mode=${mode})`);
190
202
  state.failed = true;
191
- this.stepDone(state);
203
+ this.stop(state);
192
204
  }, this.stepWatchdogMs);
193
205
  state.watchdog.unref?.();
194
206
  return;
@@ -7,6 +7,7 @@ import { classifyAunPayloadForLog } from './message-log.js';
7
7
  import { isValidAunDeliveryForChannel } from './outbound.js';
8
8
  import { isHClassPath } from '../permission/protected-paths.js';
9
9
  import { evaluateOutboundContactAdmission } from './message-admission.js';
10
+ import { contactIntroductionText, evaluateAppContactAdmission, parseFriendInvite } from './contact-admission.js';
10
11
  import { normalizeAunMentionEntries, withAunAttention } from '../../aun/msg/mention-schema.js';
11
12
  import { resolveManagedSendArgv } from '../../cli/aun-commands.js';
12
13
  import { readTriggerLocalFile, resolveAttachmentLocalPath } from '../../trigger/local-files.js';
@@ -68,6 +69,7 @@ export function createAunHandoffSender(sessionManager, channelInstances, getOutb
68
69
  encrypt: handoff.request.encrypt,
69
70
  causation: handoff.causation,
70
71
  debug,
72
+ model: typeof debug?.model === 'string' ? debug.model : undefined,
71
73
  log,
72
74
  })
73
75
  : { ok: false, error: 'AUN channel does not support daemon group sends' }
@@ -78,6 +80,7 @@ export function createAunHandoffSender(sessionManager, channelInstances, getOutb
78
80
  encrypt: handoff.request.encrypt,
79
81
  causation: handoff.causation,
80
82
  debug,
83
+ model: typeof debug?.model === 'string' ? debug.model : undefined,
81
84
  log,
82
85
  })
83
86
  : { ok: false, error: 'AUN channel does not support daemon private sends' };
@@ -391,7 +394,35 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
391
394
  if (params.scope === 'msg') {
392
395
  const admission = await evaluateOutboundContactAdmission({ selfAid: params.aid, targetAid: params.to });
393
396
  if (!admission.allow) {
394
- return { ok: false, error: admission.error, code: admission.code };
397
+ const decision = evaluateAppContactAdmission(params.aid, params.to);
398
+ const friendInvite = params.rawPayload === true && params.encrypt === true
399
+ && parseFriendInvite(params.payload, params.aid, params.to);
400
+ const inviteMayRequestContact = !!friendInvite
401
+ && (decision?.reason === 'not_in_contacts' || admission.code === 'CONTACT_ALL_CONTACTS_DISABLED');
402
+ if (!inviteMayRequestContact) {
403
+ const canRequestOwner = !!decision && (decision.reason === 'not_in_contacts' || decision.reason === 'scope_extension')
404
+ && !params.file && params.returnPolicy !== 'required' && contactIntroductionText(params.payload) !== undefined;
405
+ if (!canRequestOwner || typeof ch.requestOutboundContact !== 'function') {
406
+ return { ok: false, error: admission.error, code: admission.code, sent: false };
407
+ }
408
+ try {
409
+ // Retries of the same task message share an event; never queue the original peer send.
410
+ const sourceMessageId = 'outbound-' + crypto.createHash('sha256').update(JSON.stringify([
411
+ params.originSessionId, params.originMessageId, params.to, contactIntroductionText(params.payload),
412
+ ])).digest('hex');
413
+ const request = await ch.requestOutboundContact({ to: params.to, payload: params.payload, sourceMessageId });
414
+ if (!request.ok)
415
+ return { ok: false, code: request.code, error: request.error, sent: false };
416
+ const receipt = request.receipt;
417
+ return { ok: false, code: 'CONTACT_APPROVAL_REQUIRED', sent: false, retryable: false,
418
+ error: `目标 ${params.to} 未准入,${receipt.status === 'sent' ? '已向' : '已排队向'}本端 Owner ${receipt.owner_aid} 提交联系申请,等待审批;原消息未发送`,
419
+ contact_request: receipt };
420
+ }
421
+ catch (error) {
422
+ return { ok: false, code: 'CONTACT_OWNER_REQUEST_FAILED', sent: false,
423
+ error: `向本端 Owner 提交联系申请失败:${error instanceof Error ? error.message : String(error)};原消息未发送` };
424
+ }
425
+ }
395
426
  }
396
427
  }
397
428
  // The IPC command already carries the caller-selected transport scope.
@@ -399,7 +430,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
399
430
  // look group-like and a group identifier may use a future format.
400
431
  const encrypt = typeof params.encrypt === 'boolean'
401
432
  ? params.encrypt
402
- : (typeof ch.getDefaultEncrypt === 'function' ? ch.getDefaultEncrypt() : true);
433
+ : (typeof ch.getDefaultEncrypt === 'function' ? ch.getDefaultEncrypt() : false);
403
434
  let payload = params.payload;
404
435
  if (params.file) {
405
436
  if (isHClassPath(params.file.filePath) && !fullAccess) {
@@ -591,6 +622,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
591
622
  mentions: params.mentions,
592
623
  encrypt,
593
624
  debug,
625
+ model: typeof debug?.model === 'string' ? debug.model : undefined,
594
626
  log: params.log ? { ...params.log, sessionId: targetSessionId ?? params.log.sessionId } : undefined,
595
627
  });
596
628
  if (params.thread && params.checkEveryMs !== undefined && sent.ok && sent.message_id && threadRoute) {
@@ -629,6 +661,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
629
661
  encrypt,
630
662
  causation: runtimeCausation,
631
663
  debug,
664
+ model: typeof debug?.model === 'string' ? debug.model : undefined,
632
665
  log: params.log ? { ...params.log, sessionId: targetSessionId ?? params.log.sessionId } : undefined,
633
666
  });
634
667
  if (preparedRequest) {