evolcore 0.0.43-test.2 → 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 (110) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist/agents/ecagent-runner.js +13 -6
  3. package/dist/aun/aid/agentmd.js +21 -1
  4. package/dist/aun/msg/p2p.js +4 -2
  5. package/dist/channels/aun.js +79 -48
  6. package/dist/channels/daemon.js +4 -0
  7. package/dist/cli/agent-create.js +3 -5
  8. package/dist/cli/aun-commands.js +17 -19
  9. package/dist/cli/directory.js +101 -56
  10. package/dist/cli/index.js +1 -1
  11. package/dist/cli/peer.js +2 -1
  12. package/dist/cli/task-context.js +3 -1
  13. package/dist/config/access-policy.js +0 -1
  14. package/dist/config/builtin-role-templates.js +2 -2
  15. package/dist/config/builtin-roles.js +2 -1
  16. package/dist/config/config-field-policy.js +5 -0
  17. package/dist/config/config-manager.js +25 -10
  18. package/dist/config/peer-role-resolver.js +23 -1
  19. package/dist/config/role-schema.js +26 -2
  20. package/dist/config/role-service.js +9 -4
  21. package/dist/config/role-store.js +30 -8
  22. package/dist/core/auth/auth-gateway.js +14 -4
  23. package/dist/core/auth/operation-authorizer.js +17 -0
  24. package/dist/core/auth/operation-catalog.js +12 -2
  25. package/dist/core/channel-runtime.js +5 -0
  26. package/dist/core/command/agent-control.js +1 -1
  27. package/dist/core/command/agentmd-menu-request.js +50 -0
  28. package/dist/core/command/agentmd-menu.js +156 -0
  29. package/dist/core/command/command-handler.js +39 -3
  30. package/dist/core/command/menu-catalog.js +13 -0
  31. package/dist/core/command/menu-handler.js +59 -9
  32. package/dist/core/command/menu-protocol.js +8 -0
  33. package/dist/core/command/role-menu.js +23 -9
  34. package/dist/core/command/slash-handler.js +48 -21
  35. package/dist/core/daemon-lifecycle.js +9 -1
  36. package/dist/core/evolagent.js +5 -4
  37. package/dist/core/lifecycle-notice.js +185 -0
  38. package/dist/core/message/aun-ipc-sender.js +30 -24
  39. package/dist/core/message/contact-admission.js +1 -19
  40. package/dist/core/message/im-renderer.js +64 -28
  41. package/dist/core/message/message-admission.js +15 -65
  42. package/dist/core/message/message-bridge.js +18 -5
  43. package/dist/core/message/message-utils.js +9 -0
  44. package/dist/core/message/peer-mode.js +16 -8
  45. package/dist/core/message/response-engine.js +56 -35
  46. package/dist/core/ownership/owner-resolver.js +72 -34
  47. package/dist/core/permission/ec-command-parser.js +24 -10
  48. package/dist/core/relation/pa-team.js +127 -0
  49. package/dist/core/role/runtime-policy.js +4 -3
  50. package/dist/core/thread/thread-service.js +6 -4
  51. package/dist/directory/owner-directory-admission.js +0 -3
  52. package/dist/directory/owner-directory-cache.js +197 -15
  53. package/dist/directory/owner-directory-markdown.js +44 -21
  54. package/dist/directory/owner-directory-policy.js +1 -1
  55. package/dist/directory/owner-directory-query-operation.js +219 -97
  56. package/dist/directory/owner-directory-request-operation.js +76 -0
  57. package/dist/directory/owner-directory-scope.js +35 -4
  58. package/dist/directory/owner-directory-search.js +76 -23
  59. package/dist/directory/owner-directory-store.js +5 -38
  60. package/dist/directory/owner-directory-text.js +60 -0
  61. package/dist/eck/kit-renderer.js +6 -3
  62. package/dist/eck/message-renderer.js +2 -5
  63. package/dist/ecweb/message-context-service.js +4 -0
  64. package/dist/index.js +11 -0
  65. package/dist/paths.js +4 -2
  66. package/dist/product.js +1 -0
  67. package/dist/response-system/engines/v1/index.js +2 -4
  68. package/dist/response-system/modes/single-session/index.js +1 -1
  69. package/dist/trigger/scheduler.js +8 -3
  70. package/dist/utils/error-utils.js +7 -5
  71. package/ecagent/README.md +18 -0
  72. package/ecagent/dist/harness/agent-harness.d.ts +2 -0
  73. package/ecagent/dist/harness/agent-harness.js +24 -8
  74. package/ecagent/dist/harness/compaction/compaction.js +3 -0
  75. package/ecagent/dist/harness/types.d.ts +1 -0
  76. package/kits/docs/channels/aun.md +1 -1
  77. package/kits/docs/context-assembly.md +1 -1
  78. package/kits/docs/evolcore/INDEX.md +4 -1
  79. package/kits/docs/evolcore/directory.md +125 -35
  80. package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
  81. package/kits/docs/evolcore/file-navigation.md +265 -0
  82. package/kits/docs/evolcore/msg.md +1 -0
  83. package/kits/docs/evolcore/peer.md +2 -1
  84. package/kits/docs/evolcore/response.md +2 -2
  85. package/kits/docs/evolcore/task.md +2 -0
  86. package/kits/docs/evolcore/tool-authorization.md +1 -1
  87. package/kits/docs/identity/ROLE_DETAIL.md +2 -0
  88. package/kits/eck_manifest.json +7 -3
  89. package/kits/eck_manifest.memory.json +26 -1
  90. package/kits/schemas/_meta.json +16 -3
  91. package/kits/schemas/agent-config.schema.20.json +925 -0
  92. package/kits/schemas/relation-config.schema.13.json +289 -0
  93. package/kits/schemas/role-config.schema.3.json +1038 -0
  94. package/kits/schemas/role-registry.schema.1.json +3 -2
  95. package/kits/templates/soul/00-GUIDE.md +20 -42
  96. package/kits/templates/system-fragments/channel.md +2 -2
  97. package/kits/templates/system-fragments/commands.md +1 -1
  98. package/kits/templates/system-fragments/directory-contacts.md +1 -1
  99. package/kits/templates/system-fragments/personal-assistant.md +2 -17
  100. package/kits/templates/system-fragments/reply.md +7 -0
  101. package/kits/templates/system-fragments/session.md +6 -2
  102. package/package.json +2 -2
  103. package/dist/eck/paactive-context.js +0 -45
  104. package/dist/response-system/engines/v1/paactive-flow.js +0 -18
  105. package/kits/eck_manifest.paactive.json +0 -528
  106. package/kits/eck_message_manifest.paactive.json +0 -233
  107. package/kits/templates/message-fragments/paactive/item.md +0 -3
  108. package/kits/templates/system-fragments/paactive/channel.md +0 -25
  109. package/kits/templates/system-fragments/paactive/reply.md +0 -25
  110. package/kits/templates/system-fragments/paactive/session.md +0 -32
@@ -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
+ }
@@ -7,7 +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 { appContactAdmissionActive, contactIntroductionText, evaluateAppContactAdmission } from './contact-admission.js';
10
+ import { contactIntroductionText, evaluateAppContactAdmission, parseFriendInvite } from './contact-admission.js';
11
11
  import { normalizeAunMentionEntries, withAunAttention } from '../../aun/msg/mention-schema.js';
12
12
  import { resolveManagedSendArgv } from '../../cli/aun-commands.js';
13
13
  import { readTriggerLocalFile, resolveAttachmentLocalPath } from '../../trigger/local-files.js';
@@ -394,28 +394,34 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
394
394
  if (params.scope === 'msg') {
395
395
  const admission = await evaluateOutboundContactAdmission({ selfAid: params.aid, targetAid: params.to });
396
396
  if (!admission.allow) {
397
- const decision = appContactAdmissionActive(params.aid) ? evaluateAppContactAdmission(params.aid, params.to) : undefined;
398
- const canRequestOwner = !!decision && (decision.reason === 'not_in_contacts' || decision.reason === 'scope_extension')
399
- && !params.file && params.returnPolicy !== 'required' && contactIntroductionText(params.payload) !== undefined;
400
- if (!canRequestOwner || typeof ch.requestOutboundContact !== 'function') {
401
- return { ok: false, error: admission.error, code: admission.code, sent: false };
402
- }
403
- try {
404
- // Retries of the same task message share an event; never queue the original peer send.
405
- const sourceMessageId = 'outbound-' + crypto.createHash('sha256').update(JSON.stringify([
406
- params.originSessionId, params.originMessageId, params.to, contactIntroductionText(params.payload),
407
- ])).digest('hex');
408
- const request = await ch.requestOutboundContact({ to: params.to, payload: params.payload, sourceMessageId });
409
- if (!request.ok)
410
- return { ok: false, code: request.code, error: request.error, sent: false };
411
- const receipt = request.receipt;
412
- return { ok: false, code: 'CONTACT_APPROVAL_REQUIRED', sent: false, retryable: false,
413
- error: `目标 ${params.to} 未准入,${receipt.status === 'sent' ? '已向' : '已排队向'}本端 Owner ${receipt.owner_aid} 提交联系申请,等待审批;原消息未发送`,
414
- contact_request: receipt };
415
- }
416
- catch (error) {
417
- return { ok: false, code: 'CONTACT_OWNER_REQUEST_FAILED', sent: false,
418
- error: `向本端 Owner 提交联系申请失败:${error instanceof Error ? error.message : String(error)};原消息未发送` };
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
+ }
419
425
  }
420
426
  }
421
427
  }
@@ -424,7 +430,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
424
430
  // look group-like and a group identifier may use a future format.
425
431
  const encrypt = typeof params.encrypt === 'boolean'
426
432
  ? params.encrypt
427
- : (typeof ch.getDefaultEncrypt === 'function' ? ch.getDefaultEncrypt() : true);
433
+ : (typeof ch.getDefaultEncrypt === 'function' ? ch.getDefaultEncrypt() : false);
428
434
  let payload = params.payload;
429
435
  if (params.file) {
430
436
  if (isHClassPath(params.file.filePath) && !fullAccess) {
@@ -101,24 +101,6 @@ export function saveIsolatedContactSource(selfAid, aid, mid, source) {
101
101
  export function contactSourceDigest(payload) {
102
102
  return crypto.createHash('sha256').update(JSON.stringify(payload) ?? 'undefined').digest('hex');
103
103
  }
104
- export function appContactAdmissionEnabled(selfAid) {
105
- return readAccessPolicy(selfAid).contactAdmission === 'app-v1';
106
- }
107
- /**
108
- * app-v1 是否真正生效:配置已开启**且**当前 Ownership 能给出共识绑定。
109
- *
110
- * app-v1 的判定全部建立在 relation_version 之上;没有绑定(单边关系、未签署声明、
111
- * Ownership 暂不可用)时无法判定,此时必须退回 legacy 规则,而不是把所有人判成
112
- * unavailable 后静默丢信。旧格式授权由 OwnerDirectoryCache 的兼容读取放行,
113
- * 因此 legacy 规则对既有授权仍然有效。
114
- *
115
- * 绑定新鲜度不参与这里的判定:准入链路上反复核验 Ownership 既昂贵又会把健康关系
116
- * 误判成不可用。共识只在显式事件(ownership 变更、agent.md/owner.md 变化、配置
117
- * Owner 变化、断线过期)到达时被 invalidate,届时绑定自然消失并回退 legacy。
118
- */
119
- export function appContactAdmissionActive(selfAid) {
120
- return appContactAdmissionEnabled(selfAid) && !!currentContactBinding(selfAid);
121
- }
122
104
  /**
123
105
  * 当前生效的共识绑定,不要求授权处在 5 分钟窗口内。
124
106
  *
@@ -449,7 +431,7 @@ export function parseFriendInvite(payload, senderAid, selfAid) {
449
431
  if (!Number.isSafeInteger(value.created_at_ms) || value.created_at_ms <= 0
450
432
  || value.expires_at_ms !== value.created_at_ms + FRIEND_INVITE_TTL_MS)
451
433
  return undefined;
452
- if (typeof value.introduction !== 'string' || !value.introduction.trim())
434
+ if (typeof value.introduction !== 'string' || !value.introduction.trim() || value.introduction.includes('\0'))
453
435
  return undefined;
454
436
  return { invite_id: value.invite_id, applicant_aid: senderAid, target_aid: selfAid,
455
437
  created_at_ms: value.created_at_ms, expires_at_ms: value.expires_at_ms, introduction: value.introduction };
@@ -6,6 +6,7 @@ import { tagErrorTextWithEvolcoreVersion } from '../../utils/evolcore-version.js
6
6
  import { DEFAULT_FLUSH_DELAY_MS } from '../../types.js';
7
7
  import { classifyAunToolErrorCode, normalizeToolErrorClassification } from '../permission/tool-error-code.js';
8
8
  import { foldSubtaskTerminal } from './subtask-tool-projection.js';
9
+ import { isNoopText, mayBeNoopText } from './message-utils.js';
9
10
  function toolApprovalMetadata(event) {
10
11
  if (!event || event.executed !== false || !event.decisionSource || event.decisionSource === 'runner')
11
12
  return {};
@@ -117,7 +118,7 @@ export class IMRenderer {
117
118
  if (isFinal) {
118
119
  const pending = this.deferredProactiveText;
119
120
  this.deferredProactiveText = [];
120
- if (pending.map(item => item.text).join('').trim() !== this.opts.noopSentinel) {
121
+ if (!isNoopText(pending.map(item => item.text).join(''), this.opts.noopSentinel || undefined)) {
121
122
  for (const item of pending) {
122
123
  this.recordActivity(item);
123
124
  await this.sendPayload({ kind: 'activity.batch', items: [item] });
@@ -139,11 +140,11 @@ export class IMRenderer {
139
140
  }
140
141
  /** 是否有 pending 内容 */
141
142
  hasContent() {
142
- return this.textBuffer.length > 0 || this.deferredProactiveText.length > 0 || this.itemsQueue.some(it => it.kind !== 'text') || this.hasHeldToolResults();
143
+ return !!this.pendingAutomaticText || this.textBuffer.length > 0 || this.deferredProactiveText.length > 0 || this.itemsQueue.some(it => it.kind !== 'text') || this.hasHeldToolResults();
143
144
  }
144
145
  /** 是否有会抑制兜底错误消息的正文/过程内容;lifecycle 边界不算。 */
145
146
  hasNonLifecycleContent() {
146
- return this.textBuffer.trim().length > 0 || this.hasHeldToolResults() || this.itemsQueue.some(it => {
147
+ return !!this.pendingAutomaticText || this.textBuffer.trim().length > 0 || this.hasHeldToolResults() || this.itemsQueue.some(it => {
147
148
  if (it.kind === 'text')
148
149
  return it.text.trim().length > 0;
149
150
  if (this.subtaskItems.has(it))
@@ -159,12 +160,14 @@ export class IMRenderer {
159
160
  }
160
161
  /** 是否有待发送的文本 */
161
162
  hasTextPending() {
162
- return this.textBuffer.length > 0;
163
+ return !!this.pendingAutomaticText || this.textBuffer.length > 0;
163
164
  }
164
165
  /** flush 当前 textBuffer 作为独立的 result.text(非 final),然后清空 buffer */
165
166
  async flushText() {
166
167
  if (this.opts.envelope.chatmode === 'proactive')
167
168
  return;
169
+ if (this.pendingAutomaticText)
170
+ await this.retryAutomaticText();
168
171
  if (this.textBuffer.length === 0)
169
172
  return;
170
173
  // 文件标记过滤后若只剩空白,应立即消费;尤其避免 final-only
@@ -186,6 +189,8 @@ export class IMRenderer {
186
189
  this.itemsQueue = this.itemsQueue.filter(it => it.kind !== 'text');
187
190
  return;
188
191
  }
192
+ if (mayBeNoopText(rawText, this.opts.noopSentinel || undefined))
193
+ return;
189
194
  if (this.timer) {
190
195
  clearTimeout(this.timer);
191
196
  this.timer = undefined;
@@ -205,7 +210,8 @@ export class IMRenderer {
205
210
  }
206
211
  catch (error) {
207
212
  // A failed durable enqueue must remain retryable by the final flush.
208
- this.textBuffer = rawText + this.textBuffer;
213
+ if (this.opts.envelope.chatmode !== 'paactive')
214
+ this.textBuffer = rawText + this.textBuffer;
209
215
  throw error;
210
216
  }
211
217
  this.lastFlush = Date.now();
@@ -229,6 +235,7 @@ export class IMRenderer {
229
235
  this.textBuffer = '';
230
236
  this.allText = '';
231
237
  this.deferredProactiveText = [];
238
+ this.pendingAutomaticText = undefined;
232
239
  }
233
240
  /** 仅丢弃尚未发送的正文,保留 notice/tool 等活动项。 */
234
241
  discardPendingText() {
@@ -239,10 +246,11 @@ export class IMRenderer {
239
246
  this.itemsQueue = this.itemsQueue.filter(it => it.kind !== 'text');
240
247
  this.textBuffer = '';
241
248
  this.deferredProactiveText = [];
249
+ this.pendingAutomaticText = undefined;
242
250
  }
243
251
  /** 当前 buffer 中尚未 flush 的文本 */
244
252
  getRemainingText() {
245
- return this.textBuffer;
253
+ return (this.pendingAutomaticText?.item.text ?? '') + this.textBuffer;
246
254
  }
247
255
  // ── 文本/活动注入(替代 StreamFlusher.addText/addActivity)──
248
256
  /** 添加文本片段(流式 text) */
@@ -711,29 +719,46 @@ export class IMRenderer {
711
719
  * Explicit sends, command receipts and interaction fallbacks bypass it.
712
720
  */
713
721
  async sendAutomaticText(payload) {
722
+ if (isNoopText(payload.text, this.opts.noopSentinel || undefined))
723
+ return;
714
724
  if (this.opts.envelope.chatmode !== 'paactive')
715
725
  return this.sendPayload(payload);
716
- const signature = JSON.stringify([
717
- payload.text,
718
- payload.metadata?.forkAnchor?.assistantMessageId,
719
- ]);
720
- const pending = this.pendingAutomaticText?.signature === signature
721
- ? this.pendingAutomaticText
722
- : undefined;
723
- const item = pending?.item ?? {
726
+ try {
727
+ // Another flush may have started while this one awaited a tool batch.
728
+ // Never replace its in-flight or failed text item with this payload.
729
+ while (this.pendingAutomaticText)
730
+ await this.retryAutomaticText();
731
+ }
732
+ catch (error) {
733
+ // This payload has not been recorded yet; preserve it behind the older
734
+ // pending item so a later flush can retry both without loss or overlap.
735
+ this.textBuffer = payload.text + this.textBuffer;
736
+ throw error;
737
+ }
738
+ const item = {
724
739
  kind: 'text',
725
740
  text: payload.text,
726
741
  ...(payload.metadata?.forkAnchor ? { forkAnchor: payload.metadata.forkAnchor } : {}),
727
742
  };
728
- const activityId = pending?.activityId
729
- ?? `activity-${randomUUID().replace(/-/g, '')}`;
730
- if (!pending) {
731
- this.recordActivity(item, activityId);
732
- this.pendingAutomaticText = { signature, item, activityId };
743
+ this.recordActivity(item, `activity-${randomUUID().replace(/-/g, '')}`);
744
+ this.pendingAutomaticText = { item };
745
+ await this.retryAutomaticText();
746
+ }
747
+ /** Keep a failed, already-recorded text item separate from newly buffered text. */
748
+ retryAutomaticText() {
749
+ const pending = this.pendingAutomaticText;
750
+ if (!pending)
751
+ return Promise.resolve();
752
+ if (!pending.delivery) {
753
+ pending.delivery = this.sendPayload({ kind: 'activity.batch', items: [pending.item] }).then(() => {
754
+ if (this.pendingAutomaticText === pending)
755
+ this.pendingAutomaticText = undefined;
756
+ }, error => {
757
+ pending.delivery = undefined;
758
+ throw error;
759
+ });
733
760
  }
734
- await this.sendPayload({ kind: 'activity.batch', items: [item] });
735
- if (this.pendingAutomaticText?.activityId === activityId)
736
- this.pendingAutomaticText = undefined;
761
+ return pending.delivery;
737
762
  }
738
763
  scheduleFlush() {
739
764
  if (this.timer) {
@@ -780,6 +805,8 @@ export class IMRenderer {
780
805
  const nonThinking = this.itemsQueue.filter(it => it.kind !== 'text');
781
806
  if (nonThinking.length === 0)
782
807
  return;
808
+ if (this.pendingAutomaticText)
809
+ await this.retryAutomaticText();
783
810
  if (this.timer) {
784
811
  clearTimeout(this.timer);
785
812
  this.timer = undefined;
@@ -814,6 +841,8 @@ export class IMRenderer {
814
841
  clearTimeout(this.timer);
815
842
  this.timer = undefined;
816
843
  }
844
+ if (this.pendingAutomaticText)
845
+ await this.retryAutomaticText();
817
846
  // 显式 flush(轮次结束、出错收尾)时放出被扣住的后台占位结果;定时 flush 不放,
818
847
  // 否则长时间后台任务会在终态到达前就把占位结果发出去。放出的结果随本次 flush 一起发,
819
848
  // 不需要它重新挂上的定时器。
@@ -835,7 +864,7 @@ export class IMRenderer {
835
864
  item.text = item.text.replace(this.opts.fileMarkerPattern, '');
836
865
  }
837
866
  }
838
- if (isFinal && this.textBuffer.trim() === this.opts.noopSentinel) {
867
+ if (isFinal && isNoopText(this.textBuffer, this.opts.noopSentinel || undefined)) {
839
868
  this.discardPendingText();
840
869
  }
841
870
  else if (!this.hasSendableText(this.textBuffer, isFinal ? 'final' : 'flush')) {
@@ -883,6 +912,8 @@ export class IMRenderer {
883
912
  if (!isFinal && this.textBuffer.length > 0) {
884
913
  if (this.suppressIntermediateText())
885
914
  return;
915
+ if (mayBeNoopText(this.textBuffer, this.opts.noopSentinel || undefined))
916
+ return;
886
917
  // A timer cannot decide whether this is the final answer. Keep it for
887
918
  // an explicit boundary; known commentary can still be sent immediately.
888
919
  if (scheduled && this.opts.deferTextUntilBoundary && this.currentTextPhase !== 'commentary')
@@ -900,7 +931,8 @@ export class IMRenderer {
900
931
  await this.sendAutomaticText(payload);
901
932
  }
902
933
  catch (error) {
903
- this.textBuffer = text + this.textBuffer;
934
+ if (this.opts.envelope.chatmode !== 'paactive')
935
+ this.textBuffer = text + this.textBuffer;
904
936
  throw error;
905
937
  }
906
938
  this.lastFlush = Date.now();
@@ -921,7 +953,8 @@ export class IMRenderer {
921
953
  await this.sendAutomaticText(payload);
922
954
  }
923
955
  catch (error) {
924
- this.textBuffer = finalText + this.textBuffer;
956
+ if (this.opts.envelope.chatmode !== 'paactive')
957
+ this.textBuffer = finalText + this.textBuffer;
925
958
  throw error;
926
959
  }
927
960
  this.lastFlush = Date.now();
@@ -1020,9 +1053,12 @@ export class IMRenderer {
1020
1053
  }
1021
1054
  /** proactive:单个 ThoughtItem 包成 activity.batch[1] 发出。 */
1022
1055
  emitProactiveItem(item) {
1023
- if (this.opts.noopSentinel && (item.kind === 'text' || (item.kind === 'summary' && !item.is_error))) {
1024
- this.deferredProactiveText.push(item);
1025
- return;
1056
+ if (item.kind === 'text' || (item.kind === 'summary' && !item.is_error)) {
1057
+ if (this.opts.noopSentinel || this.deferredProactiveText.length > 0
1058
+ || mayBeNoopText(item.text)) {
1059
+ this.deferredProactiveText.push(item);
1060
+ return;
1061
+ }
1026
1062
  }
1027
1063
  this.recordActivity(item);
1028
1064
  const evolCommand = item.kind === 'tool_call' ? item.evolCommand : undefined;
@@ -3,12 +3,9 @@ import { resolvePeerView, resolvePrincipal, } from '../../config/peer-book.js';
3
3
  import { isValidAid } from '../../aun/aid/validation.js';
4
4
  import { readOwnerDirectoryMembership } from '../../directory/owner-directory-admission.js';
5
5
  import { resolveAunPeerKind } from '../relation/peer-identity.js';
6
- import { appContactAdmissionActive, evaluateAppContactAdmission } from './contact-admission.js';
6
+ import { evaluateAppContactAdmission } from './contact-admission.js';
7
7
  /**
8
- * 出站私聊准入:与入站使用同一套判定,保证双向对称。
9
- *
10
- * 顺序与入站一致:本地拉黑 → Owner/个人助理 → 黑名单 → 白名单
11
- * → `allowAllContacts` 总开关 → 名录内部/外部档。
8
+ * AUN 出站私聊固定使用 app-v1,与入站保持相同的绑定和联系人判定。
12
9
  * 群聊的准入单位是群,出站到群不做发言人判定。
13
10
  */
14
11
  export async function evaluateOutboundContactAdmission(input) {
@@ -22,67 +19,19 @@ export async function evaluateOutboundContactAdmission(input) {
22
19
  const target = await resolveAunPeerKind(selfAid, targetAid);
23
20
  if (target.kind === 'group')
24
21
  return { allow: true, status: 'group' };
25
- let policy;
26
- try {
27
- policy = readAccessPolicy(selfAid);
28
- }
29
- catch (error) {
30
- return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: error instanceof Error ? error.message : String(error) };
31
- }
32
- if (policy.contactAdmission === 'app-v1' && appContactAdmissionActive(selfAid)) {
33
- const decision = evaluateAppContactAdmission(selfAid, targetAid);
34
- if (decision.allow)
35
- return { allow: true, status: decision.reason === 'owner' ? 'owner' : decision.reason === 'temporary' ? 'temporary' : 'contact' };
36
- return { allow: false, code: decision.reason === 'unavailable' ? 'CONTACT_DIRECTORY_UNAVAILABLE'
37
- : decision.reason === 'blocked' ? 'CONTACT_BLOCKED' : 'CONTACT_DENIED',
38
- status: decision.reason === 'unavailable' ? 'unavailable' : decision.reason === 'blocked' ? 'blocked' : 'denied',
39
- error: `联系人准入未通过:${decision.reason}` };
40
- }
41
- let view;
22
+ let decision;
42
23
  try {
43
- view = resolvePeerView(selfAid, targetAid);
24
+ decision = evaluateAppContactAdmission(selfAid, targetAid);
44
25
  }
45
26
  catch (error) {
46
27
  return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: error instanceof Error ? error.message : String(error) };
47
28
  }
48
- if (view.blocked) {
49
- return { allow: false, code: 'CONTACT_BLOCKED', status: 'blocked', error: `目标 ${targetAid} 已被本端拉黑。请先解除拉黑:ec peer unblock ${targetAid} --self ${selfAid}` };
50
- }
51
- if (view.isOwner)
52
- return { allow: true, status: 'owner' };
53
- if (policy.deniedAids?.includes(targetAid)) {
54
- return { allow: false, code: 'CONTACT_DENIED', status: 'denied', error: `目标 ${targetAid} 在 Owner 配置的黑名单 deniedAids 中,当前无法联系` };
55
- }
56
- if (policy.allowedAids?.includes(targetAid))
57
- return { allow: true, status: 'allowed_aid' };
58
- // 总开关:压过名录三档(含名录不可用)。拉黑与 deniedAids 已在本行之前判定。
59
- if (policy.allowAllContacts === true)
60
- return { allow: true, status: 'all_contacts' };
61
- const membership = readOwnerDirectoryMembership(selfAid, targetAid);
62
- switch (membership?.category) {
63
- case 'unavailable':
64
- return { allow: false, code: 'CONTACT_DIRECTORY_UNAVAILABLE', status: 'unavailable', error: 'Owner 名录当前不可用,无法确认目标身份,已拒绝发送;如需无条件联系请开启 allowAllContacts' };
65
- case 'owner':
66
- return { allow: true, status: 'owner' };
67
- case 'assistant':
68
- return { allow: true, status: 'internal' };
69
- case 'agent':
70
- case 'human':
71
- case 'other': {
72
- if (membership.internal) {
73
- return policy.allowInternalContacts !== false
74
- ? { allow: true, status: 'internal' }
75
- : { allow: false, code: 'CONTACT_INTERNAL_DISABLED', status: 'disabled', error: '当前 Agent 不接受内部联系,Owner 未开启 allowInternalContacts 与 allowAllContacts' };
76
- }
77
- // 与入站同一判据:个人助理未显式配置时默认可以联系外部。
78
- return membership.effectiveAllowExternalContacts === true
79
- ? { allow: true, status: 'external' }
80
- : { allow: false, code: 'CONTACT_EXTERNAL_DISABLED', status: 'disabled', error: '当前 Agent 不接受外部联系,Owner 未开启 allowExternalContacts 与 allowAllContacts' };
81
- }
82
- case 'not_found':
83
- default:
84
- return { allow: false, code: 'CONTACT_ALL_CONTACTS_DISABLED', status: 'disabled', error: `目标 ${targetAid} 不在当前 Agent 的 Owner 名录中,Owner 未开启 allowAllContacts` };
85
- }
29
+ if (decision.allow)
30
+ return { allow: true, status: decision.reason === 'owner' ? 'owner' : decision.reason === 'temporary' ? 'temporary' : 'contact' };
31
+ return { allow: false, code: decision.reason === 'unavailable' ? 'CONTACT_DIRECTORY_UNAVAILABLE'
32
+ : decision.reason === 'blocked' ? 'CONTACT_BLOCKED' : 'CONTACT_DENIED',
33
+ status: decision.reason === 'unavailable' ? 'unavailable' : decision.reason === 'blocked' ? 'blocked' : 'denied',
34
+ error: `联系人准入未通过:${decision.reason}` };
86
35
  }
87
36
  export function evaluateInboundAdmissionPreflight(input) {
88
37
  const selfAid = String(input.selfAid || '').trim();
@@ -166,7 +115,7 @@ export function evaluateInboundAdmissionPreflight(input) {
166
115
  * 拒绝发生在业务路由之前,被拒的名录发送者不会收到自动回复。
167
116
  */
168
117
  export function evaluateOwnerDirectoryInboundAdmission(context) {
169
- if (context.channelType === 'aun' && context.policy?.contactAdmission === 'app-v1' && appContactAdmissionActive(context.selfAid))
118
+ if (context.channelType === 'aun')
170
119
  return undefined;
171
120
  if (context.trustedHandoffEcho || context.isOwner || !context.primaryId || !context.policy)
172
121
  return undefined;
@@ -226,10 +175,11 @@ function evaluateOrdinaryAdmission(context) {
226
175
  return { allow: true, reason: 'owner', context };
227
176
  return { allow: true, reason: 'group_channel_allowed', context };
228
177
  }
229
- // Owner 恒放行,不查名录也不看三个开关。
230
- if (context.isOwner)
178
+ // Non-AUN channels retain their Owner shortcut; AUN Owner admission comes
179
+ // from the current app-v1 relation binding below.
180
+ if (context.isOwner && context.channelType !== 'aun')
231
181
  return { allow: true, reason: 'owner', context };
232
- if (context.channelType === 'aun' && policy.contactAdmission === 'app-v1' && appContactAdmissionActive(context.selfAid)) {
182
+ if (context.channelType === 'aun') {
233
183
  const decision = evaluateAppContactAdmission(context.selfAid, context.primaryId ?? context.actorId);
234
184
  if (decision.allow)
235
185
  return { allow: true, reason: decision.reason === 'owner' ? 'owner'