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
package/CHANGELOG.md CHANGED
@@ -14,14 +14,20 @@
14
14
  - 修复创建 Agent 时指定人格文本与 Soul 占位模板冲突的问题,保留对已有设定的覆盖保护。
15
15
  - 新增 App 联系人准入协议,按当前 Owner 共识和名录范围处理陌生消息、临时授权和黑名单;未准入的出站联系仅向本端 Owner 申请。
16
16
  - 完善 Owner 名录授权范围、缓存同步、查询、搜索和未知字段保留;名录备注支持直接编辑文件。
17
+ - 新增同 Owner PA 团队默认角色,缺省为 `member`;按双方签名名片和当前 Ownership 核验资格,变化后使授权缓存失效,并在执行前重新核验。
18
+ - 名录查询统一为 `ec directory list/info`,保留 `find/show` 别名;支持分页、结构化错误和加好友申请,Agent 条目增加双边归属核验。
19
+ - 新增加密 AUN 名片编辑与发布 Menu,仅允许当前协议 Owner 操作,保护身份、Ownership 字段及远端版本。
17
20
 
18
21
  ### 对话、任务与自动化
19
22
 
20
- - 新增 `paactive` 模式,用于已激活 AUN Agent 与人类 Owner/Admin 的私聊主会话,通过独立上下文和可靠 activity 投递展示助理活动。
23
+ - 新增 `paactive` 模式,用于已激活 AUN Agent 与人类 Owner 的私聊主会话及话题,复用 interactive 执行流和共享 ECK 上下文,通过可靠 activity 投递展示助理活动。
24
+ - 群聊固定使用 `proactive`;兼容读取旧 `interactive` 配置,新写入按当前模式约束校验。PA activity 串行重试并保留待发文本,避免重复记录或丢失。
21
25
  - AUN 消息增加受保护模型信息和模型切换通知;Slash 正常回执改用 notice,并新增 Slash 指令清单 Menu 查询。
22
26
  - Trigger 成功结果以 `[[NOOP]]` 开头时静默处理,支持前导空白和流式拆分,同时保留原始执行记录。
23
27
  - 完善 Fullaccess 提示范围、工具授权审计和只读命令解析;取消任务后停止后续模型请求,记忆整理失败时停止后续步骤并回报失败。
24
28
  - 将网关请求超时、输入未消费和空成功协议故障纳入可恢复错误处理。
29
+ - 修正 ecagent 压缩后的上下文用量,按末次模型调用报告当前占用;补齐百万上下文模型窗口,明确超限错误不再进入通用或传输重试。
30
+ - 手动压缩增加结构化进度通知,会话状态明确 Fullaccess 作用域和空闲触发状态;话题改名确认会话更新成功后才保存索引。
25
31
 
26
32
  ### 渠道、安装与管理
27
33
 
@@ -29,6 +35,7 @@
29
35
  - 修复 EC Web 脱管进程恢复、Provider 操作入口及受管服务运行信息校验;npm 元数据查询优先联网刷新。
30
36
  - 完善 Windows 安装器中文编码、Node.js 安装后的 PATH 刷新和初始化检查,并明确计划任务权限不足时的自启动回退提示。
31
37
  - 裸跑 `ec` 改为显示帮助;移除 `ec handoff` CLI 入口,跨话题协作继续使用话题与消息命令。
38
+ - 新增面向已确认 Owner 的 Agent 上下线通知;主动 AUN 发送默认明文,显式加密或渠道配置仍优先生效。
32
39
 
33
40
  ### AUN SDK
34
41
 
@@ -13,7 +13,7 @@ import { requestDangerousCommandPermission } from '../core/permission/approval-g
13
13
  import { normalizeExecutionPermissionMode, normalizePermissionMode } from '../core/permission/mode.js';
14
14
  import { checkBashDescription, checkDangerousCommand, checkReadonly, evaluateToolPreflight } from '../core/permission/tool-policy.js';
15
15
  import { logger } from '../utils/logger.js';
16
- import { ErrorType } from '../utils/error-utils.js';
16
+ import { ErrorType, getErrorRawText, isContextTooLongText } from '../utils/error-utils.js';
17
17
  import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
18
18
  import { appendToolTimeToMessages } from './tool-time-context.js';
19
19
  import { auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
@@ -23,7 +23,7 @@ import { buildModelRequestHeaders } from './request-identity.js';
23
23
  import { getGatewayPricing as getSharedGatewayPricing, resolveModelSpec } from '../stats/price-resolver.js';
24
24
  import { appendRequestPath } from './request-identity.js';
25
25
  import { getManagedTaskTempDir } from '../cli/task-context.js';
26
- import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext } from './runner-types.js';
26
+ import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext, isOneMillionContextModel, autoCompactWindowForModel, sdkAutoCompactWindowForModel } from './runner-types.js';
27
27
  const PROVIDER_ID = 'evolcore-gateway';
28
28
  const DEFAULT_SYSTEM_PROMPT = `You are ecagent, the coding agent built into EvolCore.
29
29
  Work directly in the current project. Inspect relevant files before changing them, keep edits scoped, and verify the result.
@@ -305,6 +305,7 @@ function createOpenAiTransport(config) {
305
305
  const retryableHttp = response === undefined || status === 429 || (status !== undefined && status >= 500);
306
306
  const retryable = !aborted
307
307
  && retryableHttp
308
+ && !isContextTooLongText(getErrorRawText(error))
308
309
  && !(error instanceof Error && /\[auth\]/.test(error.message));
309
310
  if (retryable && attempt + 1 < attempts) {
310
311
  retryScheduled = true;
@@ -459,8 +460,8 @@ function createModel(id, baseUrl) {
459
460
  const modelId = stripContextWindowSuffix(id);
460
461
  const isClaude = modelId.toLowerCase().startsWith('claude-');
461
462
  const fallback = isClaude
462
- ? { context_window: 200_000, max_output_tokens: 8_192 }
463
- : { context_window: 128_000, max_output_tokens: 16_384 };
463
+ ? { context_window: isOneMillionContextModel(id) ? 1_000_000 : 200_000, max_output_tokens: 8_192 }
464
+ : { context_window: isOneMillionContextModel(id) ? 1_000_000 : 128_000, max_output_tokens: 16_384 };
464
465
  const spec = resolveModelSpec(resolveRoot(), id, undefined, fallback);
465
466
  return {
466
467
  id: modelId,
@@ -749,7 +750,7 @@ function errorType(message) {
749
750
  return ErrorType.SESSION_UNAVAILABLE;
750
751
  if (normalized.includes('[auth]') || normalized.includes('401') || normalized.includes('403'))
751
752
  return 'auth';
752
- if (normalized.includes('context') && (normalized.includes('long') || normalized.includes('length')))
753
+ if (isContextTooLongText(message))
753
754
  return 'context_too_long';
754
755
  if (normalized.includes('[network]') || normalized.includes('fetch') || normalized.includes('timeout') || normalized.includes('gateway'))
755
756
  return 'network';
@@ -1003,6 +1004,7 @@ export class EcagentRunner {
1003
1004
  models,
1004
1005
  model,
1005
1006
  thinkingLevel: normalizeThinkingLevel(effort),
1007
+ autoCompactWindow: sdkAutoCompactWindowForModel(modelId, model.contextWindow),
1006
1008
  tools: createTools(nodeEnv, request.projectPath, request.runtimeEnv, request.modelOverride?.bootstrapAgentMdPath, fullaccess, request.modelOverride?.personalSoulDir, this.permissionContexts.get(request.sessionId)?.systemSessionGrants),
1007
1009
  systemPrompt: [DEFAULT_SYSTEM_PROMPT, request.systemPromptAppend].filter(Boolean).join('\n\n'),
1008
1010
  streamOptions: {
@@ -1012,6 +1014,10 @@ export class EcagentRunner {
1012
1014
  },
1013
1015
  });
1014
1016
  runtime.harness = harness;
1017
+ harness.on('session_before_compact', () => {
1018
+ this.onCompactStart?.(request.sessionId);
1019
+ return undefined;
1020
+ });
1015
1021
  if (this.pendingInterrupts.get(request.sessionId) === queue) {
1016
1022
  this.pendingInterrupts.delete(request.sessionId);
1017
1023
  await harness.abort();
@@ -1123,7 +1129,7 @@ export class EcagentRunner {
1123
1129
  sessionTitle: title,
1124
1130
  numTurns: stats.numTurns,
1125
1131
  tokenUsage: stats.usage,
1126
- contextUsage: this.contextUsage(model, stats.usage, effort),
1132
+ contextUsage: stats.modelCalls.at(-1)?.contextUsage,
1127
1133
  lastModelCall: stats.modelCalls.at(-1),
1128
1134
  modelCalls: stats.modelCalls,
1129
1135
  });
@@ -1333,6 +1339,7 @@ export class EcagentRunner {
1333
1339
  return {
1334
1340
  totalTokens, maxTokens: model.contextWindow,
1335
1341
  percentage: model.contextWindow > 0 ? totalTokens / model.contextWindow * 100 : 0,
1342
+ autoCompactTokens: autoCompactWindowForModel(model.id),
1336
1343
  model: model.id, effort,
1337
1344
  };
1338
1345
  }
@@ -766,7 +766,7 @@ async function publishAgentMd(content, opts) {
766
766
  }
767
767
  const r = await store.uploadAgentMd(opts.aid, content);
768
768
  if (!r.ok)
769
- throw new Error(`upload agent.md failed for ${opts.aid}: ${r.error.message}`);
769
+ throw Object.assign(new Error(`upload agent.md failed for ${opts.aid}: ${r.error.message}`), { code: r.error.code });
770
770
  invalidateAgentDisplayName(opts.aid, aunPath);
771
771
  const remoteVersion = normalizeRemoteVersion({ exists: true, etag: r.data?.etag, last_modified: r.data?.last_modified ?? r.data?.lastModified });
772
772
  return {
@@ -789,6 +789,26 @@ export async function agentmdPut(content, opts) {
789
789
  const lockKey = `${path.resolve(aunPath)}\u0000${opts.aid.toLowerCase()}`;
790
790
  return withAgentMdWriteLock(lockKey, () => publishAgentMd(content, opts));
791
791
  }
792
+ /** Read, validate and replace a remote card in the same lock as CLI/profile writes. */
793
+ export async function agentmdUpdate(aid, update, opts = {}) {
794
+ const aunPath = resolveAgentMdAunPath(opts);
795
+ const lockKey = `${path.resolve(aunPath)}\u0000${aid.toLowerCase()}`;
796
+ return withAgentMdWriteLock(lockKey, async () => {
797
+ const store = opts.store ?? await getAidStore({ slotId: SLOT.cli, aunPath });
798
+ try {
799
+ const current = await agentmdGet(aid, { store, aunPath, withVerification: true, remoteOnly: true });
800
+ const content = await update(current);
801
+ return await publishAgentMd(content, { aid, store, aunPath, expectedRemoteVersion: current.remoteVersion });
802
+ }
803
+ finally {
804
+ if (!opts.store)
805
+ try {
806
+ store.close();
807
+ }
808
+ catch { /* ignore */ }
809
+ }
810
+ });
811
+ }
792
812
  /**
793
813
  * Apply a profile to an SDK-owned card. Ownership declarations are SDK output:
794
814
  * never reconstruct them from the form or replace the owned card with an
@@ -44,7 +44,8 @@ export function daemonTaskSendIpcTimeoutMs(file = false, requestTimeoutMs) {
44
44
  export function resolveAunMessageEncrypt(explicit) {
45
45
  if (typeof explicit === 'boolean')
46
46
  return explicit;
47
- return readDaemonConfigForSend().aun?.defaultEncrypt ?? true;
47
+ // 默认明文:只有显式 --encrypt 或 daemon.json 配置 aun.defaultEncrypt 才加密。
48
+ return readDaemonConfigForSend().aun?.defaultEncrypt ?? false;
48
49
  }
49
50
  function buildSimplePayload(body) {
50
51
  switch (body.mode) {
@@ -187,7 +188,8 @@ async function daemonMsgSendResult(args, payload, runtimeContext, daemonResult)
187
188
  }
188
189
  const sent = {
189
190
  ok: true,
190
- message_id: daemonResult.message_id || daemonResult.handoff_id || '',
191
+ // handoff_id 是内部投递实例,不再冒充 message_id 回给调用方。
192
+ message_id: daemonResult.message_id || '',
191
193
  handoff_id: daemonResult.handoff_id,
192
194
  target_session_id: daemonResult.target_session_id,
193
195
  seq: daemonResult.seq,
@@ -1,7 +1,6 @@
1
1
  import { E2EEError, validateAIDFormat } from '@agentunion/fastaun';
2
2
  import { sanitizeMenuLogValue } from '../core/command/menu-protocol.js';
3
- import { appContactAdmissionEnabled, appContactAdmissionActive, buildContactRequest, contactIntroductionText, consumeContactIntroductionBudget, currentContactBinding, verifiedContactBinding, evaluateAppContactAdmission, executeContactGrant, isContactControlPayload, reconcileTemporaryContactGrants, sameContactBinding, isolatedContactSource, saveIsolatedContactSource, contactSourceDigest, CONTACT_EVENT_TTL_MS, FRIEND_INVITE_TYPE, FRIEND_INVITE_RESULT_TYPE, isFriendInvitePayload, parseFriendInvite, recordedFriendInviteDecision, decideFriendInvite, markFriendInviteWelcomed, buildFriendInviteResult, friendPayloadRouteValid, friendInviteWelcomeText } from '../core/message/contact-admission.js';
4
- import { evaluateOutboundContactAdmission } from '../core/message/message-admission.js';
3
+ import { buildContactRequest, contactIntroductionText, consumeContactIntroductionBudget, currentContactBinding, verifiedContactBinding, evaluateAppContactAdmission, executeContactGrant, isContactControlPayload, reconcileTemporaryContactGrants, sameContactBinding, isolatedContactSource, saveIsolatedContactSource, contactSourceDigest, CONTACT_EVENT_TTL_MS, FRIEND_INVITE_TYPE, FRIEND_INVITE_RESULT_TYPE, isFriendInvitePayload, parseFriendInvite, recordedFriendInviteDecision, decideFriendInvite, markFriendInviteWelcomed, buildFriendInviteResult, friendPayloadRouteValid, friendInviteWelcomeText } from '../core/message/contact-admission.js';
5
4
  import crypto from 'crypto';
6
5
  import { performance } from 'node:perf_hooks';
7
6
  import fs from 'fs';
@@ -45,6 +44,7 @@ import * as outbox from '../aun/outbox.js';
45
44
  import { aunProtectedHeaders } from '../aun/model-headers.js';
46
45
  import { formatSize } from '../utils/media-cache.js';
47
46
  import { formatPeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
47
+ import { preparePaTeamQualification, registerPaTeamClient, unregisterPaTeamClient } from '../core/relation/pa-team.js';
48
48
  import { isHClassPath } from '../core/permission/protected-paths.js';
49
49
  import { consumeAunCausation, registerAunCausation } from '../core/causation/aun-association.js';
50
50
  import { deriveCausation, normalizeCausation } from '../core/causation/context.js';
@@ -72,6 +72,8 @@ const OBSERVER_GROUP_MEMBERS_PAGE_SIZE = 200;
72
72
  const OBSERVER_GROUP_MEMBERS_MAX_PAGES = 100;
73
73
  const AUN_SEND_LOG_TEXT_MAX_LENGTH = 60;
74
74
  const AUN_MAX_PAYLOAD_SIZE = 512 * 1024;
75
+ /** AUN volatile TTL for online/offline lifecycle notices (gateway cap is 3600s). */
76
+ export const DEFAULT_LIFECYCLE_NOTICE_TTL_SECONDS = 1_800;
75
77
  const OWNER_DIRECTORY_ACK_TTL_SECONDS = 30;
76
78
  const OWNER_DIRECTORY_RETRY_BASE_MS = 1_000;
77
79
  const OWNER_DIRECTORY_RETRY_MAX_MS = 60_000;
@@ -587,6 +589,22 @@ function sentOutboxResult(messageId) {
587
589
  ? { status: 'sent', messageId }
588
590
  : { status: 'permanent', error: 'AUN send completed without a remote message_id', code: 'MISSING_MESSAGE_ID' };
589
591
  }
592
+ /**
593
+ * Wire contract for agent online/offline notices. Kept in one place so EvolApp
594
+ * and tests can rely on the same field names.
595
+ */
596
+ export function buildAunLifecycleNoticePayload(args) {
597
+ const name = args.agentName.trim() || args.selfAid;
598
+ return {
599
+ type: 'notice',
600
+ subtype: args.online ? 'agent.online' : 'agent.offline',
601
+ severity: 'info',
602
+ text: `${name} ${args.online ? '已上线' : '已下线'}`,
603
+ agent_aid: args.selfAid,
604
+ agent_name: name,
605
+ sent_at: args.sentAt ?? Date.now(),
606
+ };
607
+ }
590
608
  function setIfDefined(target, key, value) {
591
609
  if (value !== undefined)
592
610
  target[key] = value;
@@ -765,7 +783,7 @@ export class AUNChannel {
765
783
  if (options.targetAid !== target || JSON.stringify(options.request) !== request || Date.now() >= expires) {
766
784
  throw Object.assign(new Error('Managed Menu operation changed or expired'), { code: 'CONTACT_DENIED' });
767
785
  }
768
- if (!this.config.pureIdentity && appContactAdmissionActive(this.config.aid)
786
+ if (!this.config.pureIdentity
769
787
  && (!binding || !sameContactBinding(binding, currentContactBinding(this.config.aid)))) {
770
788
  throw Object.assign(new Error('Managed Menu Owner relation unavailable or changed'), { code: 'CONTACT_OWNERSHIP_UNAVAILABLE' });
771
789
  }
@@ -810,8 +828,7 @@ export class AUNChannel {
810
828
  // 自动从 data 推断顶层字段(self_aid / peer_aid / group_id / task_id / chatmode),
811
829
  // 便于 jq 过滤:`jq 'select(.task_id == "task-xxx")'`
812
830
  const inbound = data && typeof data === 'object' ? data : {};
813
- const isolateTrace = dir === 'IN' && event === 'message.received'
814
- && !this.config.pureIdentity && appContactAdmissionEnabled(this.config.aid);
831
+ const isolateTrace = dir === 'IN' && event === 'message.received' && !this.config.pureIdentity;
815
832
  const safeData = isolateTrace ? {
816
833
  message_id: inbound.message_id, seq: inbound.seq,
817
834
  envelope: { from: inbound.envelope?.from, to: inbound.envelope?.to, encrypted: inbound.envelope?.encrypted },
@@ -856,7 +873,7 @@ export class AUNChannel {
856
873
  callClient(method, params, lane = 'normal', onStart, onPrepared, beforeSend) {
857
874
  params = menuTransportParams(method, params);
858
875
  const client = this.client;
859
- const appOwned = !this.config.pureIdentity && appContactAdmissionActive(this.config.aid);
876
+ const appOwned = !this.config.pureIdentity;
860
877
  const friendPayload = typeof params.payload?.type === 'string' && params.payload.type.startsWith('friend.');
861
878
  const binding = appOwned || friendPayload ? currentContactBinding(this.config.aid) : undefined;
862
879
  onPrepared?.(params);
@@ -1746,10 +1763,8 @@ export class AUNChannel {
1746
1763
  // Let Core and the SDK reuse valid consensus; explicit authorization/bind operations
1747
1764
  // own their fresh checks. Material changes invalidate the SDK cache themselves.
1748
1765
  const ownership = await ownerResolver.refresh(selfAid, { allowTransient: true, source: 'directory.runtime' });
1749
- // Fall back to configured owner for agents created before the ownership consensus protocol,
1750
- // which may not yet have a consensus result but do have owners in config.json.
1751
- const ownerAid = ownerResolver.owner(selfAid) ?? ownerResolver.knownOwner(selfAid);
1752
- logger.info(`${this.logPrefix()} ownerResolver result: selfAid=${selfAid}, ownerAid=${ownerAid || 'undefined'} (protocol=${ownerResolver.owner(selfAid) || 'none'}, known=${ownerResolver.knownOwner(selfAid) || 'none'})`);
1766
+ const ownerAid = ownerResolver.owner(selfAid);
1767
+ logger.info(`${this.logPrefix()} ownerResolver result: selfAid=${selfAid}, ownerAid=${ownerAid || 'undefined'}`);
1753
1768
  if (ownership.refreshFailure) {
1754
1769
  const code = ownership.refreshFailure.code || 'UNKNOWN';
1755
1770
  logger.warn(`${this.logPrefix()} Owner relationship refresh failed: status=${ownership.consensusStatus} code=${code}`);
@@ -1761,9 +1776,8 @@ export class AUNChannel {
1761
1776
  logger.debug(`${this.logPrefix()} Owner directory unavailable: owner=${ownerAid ? 'known' : 'unknown'}, connectionChanged=${this.client !== client || !this.connected}`);
1762
1777
  return;
1763
1778
  }
1764
- const appOwned = appContactAdmissionActive(selfAid);
1765
- const relationVersion = appOwned ? currentContactBinding(selfAid)?.relation_version : undefined;
1766
- if (appOwned && !relationVersion)
1779
+ const relationVersion = currentContactBinding(selfAid)?.relation_version;
1780
+ if (!relationVersion)
1767
1781
  return;
1768
1782
  if (this.ownerDirectoryCache?.client !== client || this.ownerDirectoryCache.ownerAid !== ownerAid
1769
1783
  || this.ownerDirectoryRelationVersion !== relationVersion) {
@@ -1771,7 +1785,7 @@ export class AUNChannel {
1771
1785
  // the new cache implementation own storage and event synchronization.
1772
1786
  const directory = path.join(this.agentDir, 'directory');
1773
1787
  const cache = new OwnerDirectoryCache({
1774
- onSnapshotApplying: snapshot => { if (appOwned && isCurrent())
1788
+ onSnapshotApplying: snapshot => { if (isCurrent())
1775
1789
  reconcileTemporaryContactGrants(selfAid, snapshot); },
1776
1790
  relationVersion,
1777
1791
  isCurrent: () => isCurrent(),
@@ -1789,8 +1803,8 @@ export class AUNChannel {
1789
1803
  });
1790
1804
  const isCurrent = () => this.client === client && this.connected
1791
1805
  && this.ownerDirectoryCache?.cache === cache
1792
- && (ownerResolver.owner(selfAid) ?? (appOwned ? undefined : ownerResolver.knownOwner(selfAid))) === ownerAid
1793
- && (!appOwned || currentContactBinding(selfAid)?.relation_version === relationVersion);
1806
+ && ownerResolver.owner(selfAid) === ownerAid
1807
+ && currentContactBinding(selfAid)?.relation_version === relationVersion;
1794
1808
  const agentMd = new OwnerDirectoryAgentMdSync({
1795
1809
  selfAid,
1796
1810
  aunPath: this.config.keystorePath || resolveRoot(),
@@ -1884,7 +1898,7 @@ export class AUNChannel {
1884
1898
  const view = await ownerResolver.refresh(this.config.aid, { maxAgeMs: 0, source: 'directory.authorization' });
1885
1899
  const binding = verifiedContactBinding(this.config.aid, view);
1886
1900
  if (!binding || senderAid !== binding.owner_aid || grant.owner_aid !== senderAid || grant.grantee_aid !== this.config.aid
1887
- || (appContactAdmissionEnabled(this.config.aid) && grant.relation_version !== binding.relation_version))
1901
+ || grant.relation_version !== binding.relation_version)
1888
1902
  return;
1889
1903
  const runtime = await this.getOwnerDirectoryRuntime();
1890
1904
  if (!runtime)
@@ -1963,7 +1977,7 @@ export class AUNChannel {
1963
1977
  const view = await ownerResolver.refresh(selfAid, { maxAgeMs: 0, source: 'directory.grant' });
1964
1978
  const binding = verifiedContactBinding(selfAid, view);
1965
1979
  if (!binding || senderAid !== binding.owner_aid || parsed.owner_aid !== senderAid || parsed.grantee_aid !== selfAid
1966
- || (appContactAdmissionEnabled(selfAid) && parsed.relation_version !== binding.relation_version)) {
1980
+ || parsed.relation_version !== binding.relation_version) {
1967
1981
  logger.warn(`${this.logPrefix()} owner.directory.grant ignored: sender or relation binding is not verified`);
1968
1982
  return;
1969
1983
  }
@@ -1982,7 +1996,7 @@ export class AUNChannel {
1982
1996
  // 不再等"下一条入站消息"——那条消息可能几小时后才来。
1983
1997
  await runtime.cache.handleOwnerChangedEvent(senderAid);
1984
1998
  try {
1985
- await runtime.cache.processPendingIfNeeded();
1999
+ await runtime.cache.processPendingIfNeeded('grant');
1986
2000
  await runtime.cache.applyFromSharedCache();
1987
2001
  logger.info(`${this.logPrefix()} owner.directory.grant: pulled and applied after authorization (total=${runtime.cache.readSnapshot('contacts')?.total ?? 'none'})`);
1988
2002
  }
@@ -2119,7 +2133,8 @@ export class AUNChannel {
2119
2133
  }
2120
2134
  }
2121
2135
  shouldEncrypt(_peerId) {
2122
- return this.config.defaultEncrypt ?? true;
2136
+ // 默认明文:只有显式 --encrypt 或 daemon.json 配置 aun.defaultEncrypt 才加密。
2137
+ return this.config.defaultEncrypt ?? false;
2123
2138
  }
2124
2139
  /** Effective channel default for callers that must persist a concrete transport choice. */
2125
2140
  getDefaultEncrypt() {
@@ -2337,6 +2352,7 @@ export class AUNChannel {
2337
2352
  this.observerGroupMemberFetches.clear();
2338
2353
  // Clean up existing client if any
2339
2354
  if (this.client) {
2355
+ unregisterPaTeamClient(this.config.aid, this.client);
2340
2356
  ownerResolver.detachClient(this.config.aid, this.client);
2341
2357
  this.trace('OUT', 'client.close', { reason: 'initClient' });
2342
2358
  try {
@@ -2378,6 +2394,7 @@ export class AUNChannel {
2378
2394
  const localConfig = loadAgent(aidName);
2379
2395
  ownerResolver.setAgentConfiguredOwners(aidName, configuredOwnerList(localConfig));
2380
2396
  ownerResolver.attachClient(aidName, client);
2397
+ registerPaTeamClient(aidName, client, store);
2381
2398
  try {
2382
2399
  await this.config.onClientReady?.(client);
2383
2400
  }
@@ -2446,7 +2463,7 @@ export class AUNChannel {
2446
2463
  if (data && typeof data === 'object') {
2447
2464
  const d = data;
2448
2465
  const payloadType = d.payload?.type ?? d.envelope?.type ?? '';
2449
- if (payloadType === 'text' && (this.config.pureIdentity || !appContactAdmissionEnabled(this.config.aid))) {
2466
+ if (payloadType === 'text' && this.config.pureIdentity) {
2450
2467
  const msgId = d.message_id ?? d.id ?? '';
2451
2468
  const from = d.from ?? d.envelope?.from ?? '';
2452
2469
  const to = d.to ?? d.envelope?.to ?? this.config.aid ?? '';
@@ -3201,22 +3218,13 @@ export class AUNChannel {
3201
3218
  }
3202
3219
  }
3203
3220
  /**
3204
- * The same rules this Agent applies to ordinary private messages. app-v1 agents are judged by the
3205
- * versioned Owner snapshot; legacy agents by deniedAids / allowedAids / allowAllContacts / directory tiers.
3221
+ * Friend invites use the same app-v1 decision as ordinary private messages.
3206
3222
  */
3207
3223
  async judgeFriendInvite(selfAid, applicantAid) {
3208
- if (appContactAdmissionActive(selfAid)) {
3209
- const decision = evaluateAppContactAdmission(selfAid, applicantAid);
3210
- if (decision.allow)
3211
- return { kind: decision.reason === 'temporary' ? 'owner' : 'accept', reason: decision.reason };
3212
- return { kind: decision.reason === 'blocked' || decision.reason === 'unavailable' ? 'silent' : 'owner', reason: decision.reason };
3213
- }
3214
- const decision = await evaluateOutboundContactAdmission({ selfAid, targetAid: applicantAid });
3224
+ const decision = evaluateAppContactAdmission(selfAid, applicantAid);
3215
3225
  if (decision.allow)
3216
- return { kind: decision.status === 'temporary' || decision.status === 'group' ? 'owner' : 'accept', reason: decision.status };
3217
- const silent = decision.code === 'CONTACT_BLOCKED' || decision.code === 'CONTACT_DENIED'
3218
- || decision.code === 'CONTACT_DIRECTORY_UNAVAILABLE' || decision.code === 'CONTACT_POLICY_INVALID';
3219
- return { kind: silent ? 'silent' : 'owner', reason: decision.code };
3226
+ return { kind: decision.reason === 'temporary' ? 'owner' : 'accept', reason: decision.reason };
3227
+ return { kind: decision.reason === 'blocked' || decision.reason === 'unavailable' ? 'silent' : 'owner', reason: decision.reason };
3220
3228
  }
3221
3229
  async sendFriendInviteResult(invite, decision, inboundMessageId) {
3222
3230
  const result = buildFriendInviteResult(this.config.aid, invite, decision);
@@ -3264,16 +3272,7 @@ export class AUNChannel {
3264
3272
  }
3265
3273
  return;
3266
3274
  }
3267
- const appOwned = !this.config.pureIdentity && appContactAdmissionActive(this.config.aid);
3268
- if (!appOwned && !this.config.pureIdentity) {
3269
- try {
3270
- if (isolatedContactSource(this.config.aid, fromAid, messageId))
3271
- return;
3272
- }
3273
- catch {
3274
- return;
3275
- }
3276
- }
3275
+ const appOwned = !this.config.pureIdentity;
3277
3276
  if (!appOwned && !this.claimInboundMessage('private', messageId, seq))
3278
3277
  return;
3279
3278
  const protectedHeaders = verifiedProtectedHeaders(msg, env);
@@ -3403,6 +3402,7 @@ export class AUNChannel {
3403
3402
  // 解析对端身份(30天缓存)
3404
3403
  const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
3405
3404
  const peerIdentity = await PeerIdentityCache.resolve('aun', fromAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
3405
+ await preparePaTeamQualification(this.config.aid, fromAid);
3406
3406
  const shortAid = this.getShortAid(fromAid);
3407
3407
  const displayName = peerIdentity.name || shortAid;
3408
3408
  // 详细 dispatch 决策日志:记录消息为何被路由到 agent
@@ -4744,6 +4744,7 @@ export class AUNChannel {
4744
4744
  }
4745
4745
  // Force close SDK client,中断它内部的重连循环
4746
4746
  if (this.client) {
4747
+ unregisterPaTeamClient(this.config.aid, this.client);
4747
4748
  ownerResolver.detachClient(this.config.aid, this.client);
4748
4749
  this.trace('OUT', 'client.close', { reason: `takeover_${reason}` });
4749
4750
  this.client.close().catch(() => { });
@@ -4770,6 +4771,7 @@ export class AUNChannel {
4770
4771
  logger.debug(`${this.logPrefix()} TS-layer reconnect (${reason}) succeeded but generation stale, closing stale client`);
4771
4772
  this.stopOwnerDirectoryRefresh();
4772
4773
  if (this.client) {
4774
+ unregisterPaTeamClient(this.config.aid, this.client);
4773
4775
  ownerResolver.detachClient(this.config.aid, this.client);
4774
4776
  this.client.close().catch(() => { });
4775
4777
  this.client = null;
@@ -5282,10 +5284,13 @@ export class AUNChannel {
5282
5284
  }
5283
5285
  }
5284
5286
  appContactOutboundBlock(channelId, delivery, payload, params) {
5285
- if (delivery.chatType === 'group' || this.config.pureIdentity || !appContactAdmissionActive(this.config.aid)
5287
+ if (delivery.chatType === 'group' || this.config.pureIdentity
5286
5288
  || this.hasContactControlPermit(channelId, payload, params))
5287
5289
  return undefined;
5288
5290
  const decision = evaluateAppContactAdmission(this.config.aid, channelId);
5291
+ if (params?.encrypt === true && params?.rawPayload === true && parseFriendInvite(payload, this.config.aid, channelId)
5292
+ && decision.reason === 'not_in_contacts')
5293
+ return undefined;
5289
5294
  if (decision.allow)
5290
5295
  return undefined;
5291
5296
  return { status: decision.reason === 'unavailable' ? 'retry' : 'permanent',
@@ -5805,7 +5810,7 @@ export class AUNChannel {
5805
5810
  async requestOutboundContact(args) {
5806
5811
  const selfAid = this.config.aid;
5807
5812
  const binding = currentContactBinding(selfAid);
5808
- if (!appContactAdmissionActive(selfAid) || !binding) {
5813
+ if (!binding) {
5809
5814
  return { ok: false, code: 'CONTACT_DIRECTORY_UNAVAILABLE', error: '本端 Owner 关系不可用,未发送申请或原消息' };
5810
5815
  }
5811
5816
  const decision = evaluateAppContactAdmission(selfAid, args.to);
@@ -5886,7 +5891,7 @@ export class AUNChannel {
5886
5891
  code: 'INVALID_REQUEST_TTL',
5887
5892
  };
5888
5893
  }
5889
- const contactBlock = this.appContactOutboundBlock(args.to, { chatType: 'private' }, finalPayload);
5894
+ const contactBlock = this.appContactOutboundBlock(args.to, { chatType: 'private' }, finalPayload, { encrypt: args.encrypt, rawPayload: preserveRawPayload });
5890
5895
  if (contactBlock)
5891
5896
  return { ok: false, code: contactBlock.code, error: contactBlock.error };
5892
5897
  if (preserveRawPayload && jsonUtf8Size(finalPayload) > AUN_MAX_PAYLOAD_SIZE) {
@@ -5906,6 +5911,7 @@ export class AUNChannel {
5906
5911
  let peerRole = null;
5907
5912
  try {
5908
5913
  const { resolvePeerRoleDetail } = await import('../config/peer-role-resolver.js');
5914
+ await preparePaTeamQualification(this.config.aid, args.to);
5909
5915
  peerRole = resolvePeerRoleDetail({
5910
5916
  selfAid: this.config.aid,
5911
5917
  channelKey: `aun#${this.config.aid}#main`,
@@ -6012,6 +6018,29 @@ export class AUNChannel {
6012
6018
  };
6013
6019
  }
6014
6020
  }
6021
+ /**
6022
+ * Send an online/offline system notice to the bound Owner as an AUN volatile
6023
+ * message: nothing is persisted in the outbox or the local message log, and
6024
+ * the gateway drops it after the TTL. Best-effort by design.
6025
+ */
6026
+ async sendLifecycleNotice(args) {
6027
+ const requested = Math.trunc(args.ttlSeconds ?? DEFAULT_LIFECYCLE_NOTICE_TTL_SECONDS);
6028
+ const ttl = Number.isFinite(requested)
6029
+ ? Math.min(MAX_AUN_VOLATILE_TTL_SECONDS, Math.max(1, requested))
6030
+ : DEFAULT_LIFECYCLE_NOTICE_TTL_SECONDS;
6031
+ return this.sendDaemonMsg({
6032
+ to: args.to,
6033
+ payload: buildAunLifecycleNoticePayload({
6034
+ selfAid: this.getAid() || this.config.aid,
6035
+ agentName: args.agentName,
6036
+ online: args.online,
6037
+ sentAt: args.now?.() ?? Date.now(),
6038
+ }),
6039
+ // Preserve the notice verbatim: no session state, topic name or mentions.
6040
+ rawPayload: true,
6041
+ ttl,
6042
+ });
6043
+ }
6015
6044
  /** Public contracts use this AID's existing authenticated storage connection. */
6016
6045
  get abilityPublisherAid() { return this._aid || this.config.aid; }
6017
6046
  async publishAbilityDocuments(documents, expectedIndexes = []) {
@@ -7453,8 +7482,10 @@ export class AUNChannel {
7453
7482
  async disconnect() {
7454
7483
  this.stopOwnerDirectoryRefresh();
7455
7484
  this.configuredOwnerBindEpoch++;
7456
- if (this.client)
7485
+ if (this.client) {
7486
+ unregisterPaTeamClient(this.config.aid, this.client);
7457
7487
  ownerResolver.detachClient(this.config.aid, this.client);
7488
+ }
7458
7489
  this.managedMenuClient.close();
7459
7490
  this.intentionalDisconnect = true;
7460
7491
  if (this.reconnectTimer) {
@@ -3,6 +3,7 @@ import { ExecutionTimeoutError } from '../utils/error-utils.js';
3
3
  import { logger } from '../utils/logger.js';
4
4
  import { normalizeExecutionMode } from '../trigger/validation.js';
5
5
  import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
6
+ import { preparePaTeamQualification } from '../core/relation/pa-team.js';
6
7
  import { assertSystemSessionLaunchable } from '../core/system-session/registry.js';
7
8
  import { sessionTopicThreadId } from '../core/thread/topic-id.js';
8
9
  const DEFAULT_WATCHDOG_MS = 11 * 60 * 1000;
@@ -146,6 +147,9 @@ export class DaemonChannel {
146
147
  }
147
148
  if (ctx.signal?.aborted)
148
149
  onAbort();
150
+ if (message.triggerMeta?.originChannelType === 'aun' && message.triggerMeta.originChatType !== 'group') {
151
+ await preparePaTeamQualification(ctx.trigger.agentAid, message.triggerMeta.originPeerId);
152
+ }
149
153
  if (!slot?.terminalClaim) {
150
154
  void this.messageQueue.enqueue(ctx.session.id, message, ctx.projectPath, {
151
155
  interruptible: false,
@@ -238,11 +238,9 @@ function saveInitialBehavior(aid, baseagent) {
238
238
  };
239
239
  const sel = { self: aid };
240
240
  const existingBehavior = cfgRead(ConfigTarget.Agent, sel) || {};
241
- // 新建 Agent 默认开启 app-v1 联系人准入:陌生人纯文本转成 friend.request.v1
242
- // 交 Owner 审核,而不是静默丢弃。已有的 access 策略(含 --force 重建)原样保留。
241
+ // New agents use app-v1 in code; these values control only explicit openness rules.
243
242
  if (!existingBehavior.access) {
244
243
  behavior.access = {
245
- contactAdmission: 'app-v1',
246
244
  allowInternalContacts: true,
247
245
  allowExternalContacts: false,
248
246
  allowAllContacts: false,
@@ -1107,8 +1105,8 @@ export function validateInitializationPlan(plan) {
1107
1105
  if (plan.chatmode !== undefined) {
1108
1106
  if (!plan.chatmode || typeof plan.chatmode !== 'object' || Array.isArray(plan.chatmode)
1109
1107
  || Object.entries(plan.chatmode).some(([scope, value]) => !['private', 'group', 'nothuman'].includes(scope)
1110
- || !['interactive', 'proactive', ...(scope === 'private' ? ['paactive'] : [])].includes(value))) {
1111
- failure('INVALID_ARGS', 'chatmode must contain private/group/nothuman values; paactive is private AUN only');
1108
+ || !(scope === 'group' ? ['proactive'] : ['interactive', 'proactive', ...(scope === 'private' ? ['paactive'] : [])]).includes(value))) {
1109
+ failure('INVALID_ARGS', 'chatmode.group must be proactive; paactive is private AUN only');
1112
1110
  }
1113
1111
  }
1114
1112
  if (plan.avatarFile !== undefined && plan.avatarUrl !== undefined)
@@ -197,6 +197,16 @@ async function runManagedAid(args, formatJson) {
197
197
  console.log(`✓ 头像已更新${response.result.avatar ? `: ${response.result.avatar}` : ''}${response.result.sha256 ? ` (sha256: ${response.result.sha256})` : ''}`);
198
198
  }
199
199
  }
200
+ /**
201
+ * handoff 只是内部投递实例,不属于对外回执。回执与 JSON 结果统一剥掉该字段,
202
+ * 调用方只看 message_id;需要排查时查运行日志。
203
+ */
204
+ function stripHandoff(result) {
205
+ if (!result || typeof result !== 'object' || !('handoff_id' in result))
206
+ return result;
207
+ const { handoff_id: _handoffId, ...rest } = result;
208
+ return rest;
209
+ }
200
210
  function failManagedGroup(formatJson, code, error, details = {}) {
201
211
  if (formatJson)
202
212
  console.log(JSON.stringify({ ok: false, code, error, ...details }));
@@ -2368,15 +2378,10 @@ Options:
2368
2378
  console.log(`request_id=${result.request_id} state=${result.request_state ?? '-'} message_id=${result.message_id ?? '-'}`);
2369
2379
  }
2370
2380
  else if (formatJson) {
2371
- console.log(JSON.stringify(result));
2381
+ console.log(JSON.stringify(stripHandoff(result)));
2372
2382
  }
2373
2383
  else {
2374
- if (result.handoff_id && result.status === 'delivered')
2375
- console.log(`✓ handoff ${result.handoff_id} 已投递 ${result.message_id ?? ''}`.trimEnd());
2376
- else if (result.handoff_id)
2377
- console.log(`✓ 已排队 handoff ${result.handoff_id}(尚未投递)`);
2378
- else
2379
- console.log(`✓ 已发送 ${result.message_id ?? ''} seq=${result.seq ?? '-'} status=${result.status ?? '-'}`);
2384
+ console.log(`✓ 已发送 message_id=${result.message_id ?? '-'} seq=${result.seq ?? '-'} status=${result.status ?? '-'}`);
2380
2385
  }
2381
2386
  return;
2382
2387
  }
@@ -2782,7 +2787,7 @@ g- 是名称的一部分,会完整保留;默认命名格式为 g-10000 至 g
2782
2787
  const outputResult = (result, successHuman) => {
2783
2788
  if (!result.ok) {
2784
2789
  if (formatJson) {
2785
- console.log(JSON.stringify(result));
2790
+ console.log(JSON.stringify(stripHandoff(result)));
2786
2791
  }
2787
2792
  else {
2788
2793
  console.error(`❌ ${result.error}`);
@@ -2790,7 +2795,7 @@ g- 是名称的一部分,会完整保留;默认命名格式为 g-10000 至 g
2790
2795
  process.exit(1);
2791
2796
  }
2792
2797
  if (formatJson) {
2793
- console.log(JSON.stringify(result));
2798
+ console.log(JSON.stringify(stripHandoff(result)));
2794
2799
  }
2795
2800
  else {
2796
2801
  successHuman();
@@ -3036,12 +3041,7 @@ g- 是名称的一部分,会完整保留;默认命名格式为 g-10000 至 g
3036
3041
  }
3037
3042
  outputResult(result, () => {
3038
3043
  const r = result;
3039
- if (r.handoff_id && r.status === 'delivered')
3040
- console.log(`✓ handoff ${r.handoff_id} 已投递 ${r.message_id ?? ''}`.trimEnd());
3041
- else if (r.handoff_id)
3042
- console.log(`✓ 已排队 handoff ${r.handoff_id}(尚未投递)`);
3043
- else
3044
- console.log(`✓ 已发送 message_id=${r.message_id ?? r.message?.message_id ?? '-'} seq=${r.message?.seq ?? '-'}`);
3044
+ console.log(`✓ 已发送 message_id=${r.message_id ?? r.message?.message_id ?? '-'} seq=${r.message?.seq ?? '-'}`);
3045
3045
  });
3046
3046
  return;
3047
3047
  }
@@ -3568,13 +3568,11 @@ async function runManagedSend(argv, formatJson) {
3568
3568
  ...(result.contact_request ? { contact_request: result.contact_request } : {}),
3569
3569
  });
3570
3570
  if (formatJson)
3571
- console.log(JSON.stringify(result));
3572
- else if (result.handoff_id)
3573
- console.log(`✓ handoff ${result.handoff_id} ${result.status === 'delivered' ? '已投递' : '已排队'} ${result.message_id ?? ''}`.trimEnd());
3571
+ console.log(JSON.stringify(stripHandoff(result)));
3574
3572
  else if (result.request_id)
3575
3573
  console.log(`sent message_id=${result.message_id ?? '-'} request_id=${result.request_id} state=${result.request_state ?? '-'}`);
3576
3574
  else
3577
- console.log(`✓ 已发送 message_id=${result.message_id ?? '-'} seq=${result.seq ?? result.message?.seq ?? '-'}`);
3575
+ console.log(`✓ 已发送 message_id=${result.message_id ?? '-'} seq=${result.seq ?? result.message?.seq ?? '-'} status=${result.status ?? '-'}`);
3578
3576
  // 复查 Trigger 结果必须可见:消息已发出所以不改退出码(避免调用方重发),
3579
3577
  // 但没建成要明说,别让调用方以为"N 分钟后会自动复查"。
3580
3578
  if (!formatJson) {