evolcore 0.0.49 → 0.0.50
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.
- package/CHANGELOG.md +64 -1
- package/bin/ecmsg.js +9 -4
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +164 -0
- package/dist/ability/caller/contract.js +102 -0
- package/dist/ability/caller/daemon.js +158 -0
- package/dist/ability/caller/service.js +380 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +10 -3
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +173 -1
- package/dist/agent-template/runtime.js +280 -6
- package/dist/agent-template/service.js +1159 -40
- package/dist/agent-template/types.js +2 -1
- package/dist/agents/baseagent-availability.js +27 -3
- package/dist/agents/baseagent-capability-adapter.js +102 -0
- package/dist/agents/baseagent-plugin-descriptor.js +274 -0
- package/dist/agents/baseagent-plugin-loader.js +145 -0
- package/dist/agents/baseagent.js +68 -2
- package/dist/agents/claude-gateway/agent-registration.js +389 -0
- package/dist/agents/claude-gateway/binding.js +96 -0
- package/dist/agents/claude-gateway/inbox.js +138 -0
- package/dist/agents/claude-gateway/index.js +125 -0
- package/dist/agents/claude-gateway/listing.js +330 -0
- package/dist/agents/claude-gateway/router.js +328 -0
- package/dist/agents/claude-gateway/sessions.js +128 -0
- package/dist/agents/claude-gateway/terminal.js +250 -0
- package/dist/agents/claude-gateway/transcript.js +272 -0
- package/dist/agents/claude-gateway/types.js +14 -0
- package/dist/agents/claude-runner.js +6 -10
- package/dist/agents/codex-runner.js +4 -1
- package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
- package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
- package/dist/agents/gemini/index.js +51 -0
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/group/invite-service.js +6 -36
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +29 -1
- package/dist/aun/msg/upload.js +126 -3
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +537 -189
- package/dist/cli/ability-command.js +42 -0
- package/dist/cli/agent-command.js +20 -1
- package/dist/cli/agent-create.js +78 -18
- package/dist/cli/agent-template.js +5 -3
- package/dist/cli/agent.js +91 -0
- package/dist/cli/aun-commands.js +92 -34
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +245 -101
- package/dist/cli/ecmsg-gateway.js +11 -9
- package/dist/cli/index.js +23 -4
- package/dist/cli/init.js +39 -63
- package/dist/cli/managed-command-guard.js +1 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/services-command.js +11 -9
- package/dist/cli/thread-command.js +78 -12
- package/dist/config/access-policy.js +16 -3
- package/dist/config/config-field-policy.js +17 -8
- package/dist/config/config-manager.js +86 -46
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +9 -8
- package/dist/config/owner-config.js +0 -16
- package/dist/config/peer-role-resolver.js +1 -7
- package/dist/config/providers-config.js +99 -16
- package/dist/config/providers-management.js +35 -19
- package/dist/config/resolved-config-op.js +1 -42
- package/dist/config/schema-migration.js +78 -5
- package/dist/config/schema-registry.js +52 -7
- package/dist/config-store.js +1309 -17
- package/dist/core/agent-application-service.js +220 -1
- package/dist/core/agent-ipc-registration.js +19 -2
- package/dist/core/agent-reload-coordinator.js +5 -0
- package/dist/core/agent-runtime.js +198 -54
- package/dist/core/auth/agent-delegation.js +14 -0
- package/dist/core/auth/operation-authorizer.js +16 -1
- package/dist/core/auth/operation-catalog.js +50 -7
- package/dist/core/baseagent-loader.js +30 -3
- package/dist/core/capability/capability-manager.js +16 -7
- package/dist/core/channel-runtime.js +4 -2
- package/dist/core/command/agent-control.js +20 -2
- package/dist/core/command/agent-template-menu.js +4 -3
- package/dist/core/command/cli-intent-parser.js +15 -0
- package/dist/core/command/menu-catalog.js +20 -4
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +91 -72
- package/dist/core/command/menu-protocol.js +5 -0
- package/dist/core/command/menu-query-batch.js +2 -2
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/slash-handler.js +17 -26
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/topic-slash.js +7 -1
- package/dist/core/daemon-bootstrap.js +0 -4
- package/dist/core/daemon-control.js +2 -1
- package/dist/core/daemon-lifecycle.js +13 -5
- package/dist/core/evolagent-registry.js +12 -7
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/core/host-snapshot.js +8 -3
- package/dist/core/initialization/service.js +3 -0
- package/dist/core/interaction-router.js +130 -0
- package/dist/core/ipc-registration.js +4 -0
- package/dist/core/memory/consolidation-context.js +2 -1
- package/dist/core/memory/consolidation.js +35 -64
- package/dist/core/message/aun-ipc-sender.js +98 -21
- package/dist/core/message/aun-request-registry.js +31 -0
- package/dist/core/message/message-bridge.js +105 -6
- package/dist/core/message/message-log.js +8 -0
- package/dist/core/message/message-queue.js +5 -3
- package/dist/core/message/peer-mode.js +15 -4
- package/dist/core/message/response-engine.js +23 -8
- package/dist/core/message/send-options.js +37 -3
- package/dist/core/message/send-routing.js +11 -7
- package/dist/core/model/model-catalog.js +5 -5
- package/dist/core/ownership/owner-resolver.js +12 -86
- package/dist/core/pack-auth.js +4 -0
- package/dist/core/permission/ec-command-parser.js +182 -58
- package/dist/core/permission/protected-paths.js +64 -9
- package/dist/core/permission/services-path-acl.js +9 -2
- package/dist/core/permission/tool-policy.js +21 -9
- package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
- package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
- package/dist/core/session/session-manager.js +47 -10
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/skill/index-generator.js +2 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +4 -2
- package/dist/core/thread/thread-operation.js +25 -10
- package/dist/core/thread/thread-service.js +294 -55
- package/dist/core/thread/topic-id.js +52 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/eck/kit-renderer.js +2 -1
- package/dist/ecweb/basic-settings-service.js +5 -9
- package/dist/ecweb/providers-service.js +4 -2
- package/dist/index.js +116 -41
- package/dist/ipc.js +58 -2
- package/dist/paths.js +48 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +188 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +29 -2
- package/dist/services/dispatcher.js +23 -5
- package/dist/services/host/main.js +388 -0
- package/dist/services/host/protocol.js +118 -0
- package/dist/services/host/resident.js +310 -0
- package/dist/services/host-client.js +386 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +203 -0
- package/dist/services/host-runtime.js +802 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +176 -18
- package/dist/services/ipc-operation.js +204 -44
- package/dist/services/script-runner.js +515 -83
- package/dist/services/validation.js +109 -4
- package/dist/trigger/application-service.js +6 -4
- package/dist/trigger/local-files.js +19 -9
- package/dist/trigger/scheduler.js +22 -12
- package/dist/trigger/script-sandbox.js +51 -20
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +73 -0
- package/dist/utils/logger.js +2 -2
- package/dist/utils/media-cache.js +190 -43
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/windows-shell-trust.js +7 -3
- package/kits/docs/INDEX.md +3 -2
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/evolcore/INDEX.md +7 -6
- package/kits/docs/evolcore/agent.md +36 -1
- package/kits/docs/evolcore/aid.md +20 -3
- package/kits/docs/evolcore/config.md +1 -1
- package/kits/docs/evolcore/group.md +2 -1
- package/kits/docs/evolcore/memory-tags.md +2 -0
- package/kits/docs/evolcore/menu-client.md +3 -3
- package/kits/docs/evolcore/menu-protocol.md +7 -0
- package/kits/docs/evolcore/model.md +3 -0
- package/kits/docs/evolcore/msg.md +68 -10
- package/kits/docs/evolcore/pay.md +34 -0
- package/kits/docs/evolcore/provider.md +21 -0
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/thread-chain.md +2 -0
- package/kits/docs/evolcore/tool-authorization.md +10 -0
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +7 -0
- package/kits/rules/06-channel.md +3 -3
- package/kits/schemas/_meta.json +38 -5
- package/kits/schemas/agent-config.schema.21.json +974 -0
- package/kits/schemas/agent-config.schema.22.json +977 -0
- package/kits/schemas/agent-config.schema.23.json +958 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/providers.schema.3.json +18 -2
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +13 -1
- package/kits/skills/ability/SKILL.md +229 -34
- package/kits/skills/ability/STRUCTURE.md +333 -0
- package/kits/skills/ability/references/cli.md +208 -0
- package/kits/skills/ability/references/development.md +107 -37
- package/kits/skills/ability/references/management.md +106 -46
- package/kits/skills/ability/references/runtime-protocol.md +65 -63
- package/kits/skills/agent-output-cards/SKILL.md +12 -5
- package/kits/skills/ec-group/SKILL.md +8 -6
- package/kits/skills/ec-group/TASK.md +186 -0
- package/kits/skills/ec-group/WORKLOG.md +180 -0
- package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
- package/kits/skills/ec-pay/SKILL.md +101 -0
- package/kits/skills/ec-pay/references/pay-cli.md +110 -0
- package/kits/skills/ec-provider/SKILL.md +1 -1
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +135 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/reply.md +1 -0
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +27 -129
- package/kits/templates/system-fragments/venue.md +16 -0
- package/package.json +4 -5
- package/scripts/agent-template/inspect.mjs +37 -23
- package/scripts/agent-template/overlay.mjs +20 -2
- package/scripts/agent-template/shared/common.mjs +16 -4
- package/scripts/agent-template/shared/team-schema.json +20 -4
- package/scripts/agent-template/shared/template-contract.mjs +53 -13
- package/scripts/agent-template/shared/template-package.mjs +90 -26
- package/scripts/agent-template/shared/template-runtime.mjs +111 -1
- package/scripts/agent-template/shared/template.mjs +65 -7
- package/scripts/agent-template/team-pack.mjs +89 -33
- package/scripts/agent-template/team-preview.mjs +249 -5
- package/kits/docs/aun/ABILITY_CALLING.md +0 -280
- package/kits/docs/evolcore/ability.md +0 -185
- package/kits/skills/ability/references/calling.md +0 -56
- package/kits/skills/ability/references/contract-checklist.md +0 -37
- package/kits/skills/ability/references/recovery.md +0 -27
- /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
package/dist/channels/aun.js
CHANGED
|
@@ -15,15 +15,16 @@ import { OWNER_DIRECTORY_SCOPES } from '../directory/owner-directory-cache.js';
|
|
|
15
15
|
import path from 'path';
|
|
16
16
|
import os from 'os';
|
|
17
17
|
import { logger, localTimestamp, logPreview } from '../utils/logger.js';
|
|
18
|
+
import { ensureSessionRuntimeDir } from '../cli/task-context.js';
|
|
18
19
|
import { LogWriter } from '../utils/log-writer.js';
|
|
19
20
|
import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } from '../core/channel-loader.js';
|
|
20
21
|
import { DEFAULT_FLUSH_DELAY_SECONDS } from '../types.js';
|
|
21
|
-
import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath } from '../paths.js';
|
|
22
|
+
import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath, toAttachmentMarkedPath, } from '../paths.js';
|
|
22
23
|
import { getAunRequestRegistry, MAX_AUN_VOLATILE_TTL_SECONDS } from '../core/message/aun-request-registry.js';
|
|
23
24
|
import { AbilityError } from '../ability/types.js';
|
|
24
25
|
import { publishAbilityDocuments } from '../ability/publication.js';
|
|
25
26
|
import { resolveAunSendDevice } from '../aun/ability-device-routing.js';
|
|
26
|
-
import {
|
|
27
|
+
import { saveRelationAttachment, sanitizeFileName, bufferToInboundImage, safeFetch } from '../utils/media-cache.js';
|
|
27
28
|
import { appendAidEvent } from '../utils/instance-registry.js';
|
|
28
29
|
import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInboundEntry, classifyAunPayloadForLog, findLatestMessageLogOperation, findMessageLogOperationMessageId, hasMessageLogOperation } from '../core/message/message-log.js';
|
|
29
30
|
import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
|
|
@@ -37,8 +38,8 @@ import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
|
|
|
37
38
|
import { classifyServicePayloadType, isProjectionServiceResult, getServiceRouter, peekServiceRouter, readLocalSelfIdentity, releaseServiceRouter, } from '../services/index.js';
|
|
38
39
|
import { agentServicesDir } from '../paths.js';
|
|
39
40
|
import { MAX_AUN_ATTACHMENT_SIZE, uploadBufferAndBuildPayload, uploadFileAndBuildPayload } from '../aun/msg/upload.js';
|
|
41
|
+
import { consumePaymentInbound, paymentStore } from '../pay/runtime.js';
|
|
40
42
|
import { loadAgent } from '../config-store.js';
|
|
41
|
-
import { configuredOwnerList, firstConfiguredOwner } from '../config/owner-config.js';
|
|
42
43
|
import { resolvePeerRoleDetail, resolveSenderRelationRole } from '../config/peer-role-resolver.js';
|
|
43
44
|
import { resolveAgentLifecycle } from '../config/lifecycle.js';
|
|
44
45
|
import { resolveEffective } from '../config/config-manager.js';
|
|
@@ -46,6 +47,8 @@ import { isManagementRole } from '../config/builtin-roles.js';
|
|
|
46
47
|
import { normalizeAunMentionMode, normalizeMentionMode } from '../config/mention-mode.js';
|
|
47
48
|
import { getProcessStartTime } from '../utils/process-introspect.js';
|
|
48
49
|
import * as outbox from '../aun/outbox.js';
|
|
50
|
+
import { recordTemplateNoticeReceipt } from '../agent-template/jobs.js';
|
|
51
|
+
import { acceptWidgetCardReply, cancelWidgetCard, readWidgetCard, registerWidgetCard } from '../core/interaction-router.js';
|
|
49
52
|
import { formatSize } from '../utils/media-cache.js';
|
|
50
53
|
import { formatPeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
|
|
51
54
|
import { prepareSameOwnerProof, registerSameOwnerClient, unregisterSameOwnerClient } from '../core/relation/same-owner-proof.js';
|
|
@@ -68,6 +71,14 @@ import { sentReceipt, suppressedReceipt } from '../core/message/send-receipt.js'
|
|
|
68
71
|
export const AUN_HANDOFF_MARKER_FIELD = '_evolcore_handoff_id';
|
|
69
72
|
const AUN_INTERACTION_CARD_TTL_MS = 24 * 60 * 60 * 1000;
|
|
70
73
|
const AUN_INBOUND_DEDUP_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
74
|
+
/**
|
|
75
|
+
* 服务应答的 volatile TTL(秒)。
|
|
76
|
+
*
|
|
77
|
+
* 调用方默认等 12 秒(`SERVICE_CALL_TIMEOUT_MS`),应答发出时它可能只剩几秒
|
|
78
|
+
* 有效期。给 15 秒是留出"脚本在最后一刻跑完、包在路上"的余量:超过这个窗口,
|
|
79
|
+
* 调用方的记录已是终态,投过去也只会被丢弃。
|
|
80
|
+
*/
|
|
81
|
+
const SERVICE_REPLY_TTL_SECONDS = 15;
|
|
71
82
|
const IMAGE_MIME_TYPE = /^image\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/i;
|
|
72
83
|
const AUN_ATTACHMENT_DOWNLOAD_ATTEMPTS = 3;
|
|
73
84
|
const AUN_ATTACHMENT_RETRY_DELAYS_MS = [250, 750];
|
|
@@ -168,7 +179,7 @@ const AUN_MIN_FIELD_SIZE = 1024;
|
|
|
168
179
|
const AUN_SESSION_STATE_PAYLOAD_TYPES = new Set(['text', 'image', 'file', 'video', 'voice', 'audio', 'link']);
|
|
169
180
|
const AUN_TOPIC_NAME_PAYLOAD_TYPES = new Set([
|
|
170
181
|
'text', 'file', 'image', 'audio', 'voice', 'video', 'quote', 'link', 'merge',
|
|
171
|
-
'action_card', 'card', 'notice', 'error', 'activity', 'thought',
|
|
182
|
+
'action_card', 'widget_card', 'card', 'notice', 'error', 'activity', 'thought',
|
|
172
183
|
]);
|
|
173
184
|
/** Automatic PA output shares the activity queue, not the ordinary reply path. */
|
|
174
185
|
function isAgentFinalPayload(payload) {
|
|
@@ -355,18 +366,37 @@ export function echoTraceDirection(text) {
|
|
|
355
366
|
* 正文还没有 trace 行时,回落到首行 `hop=<N>` 参数;都没有则用默认值。
|
|
356
367
|
* 去程返程共用这一个计数器,不重置。
|
|
357
368
|
*/
|
|
358
|
-
export function echoTraceNextHop(text) {
|
|
369
|
+
export function echoTraceNextHop(text, dir = echoTraceDirection(text)) {
|
|
359
370
|
const lines = text.split('\n');
|
|
360
371
|
for (let i = lines.length - 1; i >= 0; i--) {
|
|
361
|
-
const m = /\bhop=(
|
|
362
|
-
if (m)
|
|
363
|
-
|
|
372
|
+
const m = /\bhop=([+-]?\d+)(?=\s|$)/.exec(lines[i]);
|
|
373
|
+
if (m) {
|
|
374
|
+
const hop = Number(m[1]);
|
|
375
|
+
const next = dir === 'ret' || hop < 0 ? hop - 1 : Math.max(0, hop - 1);
|
|
376
|
+
if (!Number.isSafeInteger(hop) || !Number.isSafeInteger(next)) {
|
|
377
|
+
throw new Error('echo hop exceeds JSON safe integer range');
|
|
378
|
+
}
|
|
379
|
+
return next;
|
|
380
|
+
}
|
|
364
381
|
}
|
|
365
|
-
const declared = /\bhop=(\d+)\b/.exec(lines[0] ?? '');
|
|
366
|
-
if (declared)
|
|
367
|
-
return Math.max(0, Number(declared[1]) - 1);
|
|
368
382
|
return ECHO_DEFAULT_HOP - 1;
|
|
369
383
|
}
|
|
384
|
+
/** Restore terminal reply controls when a text outbox entry becomes a wire payload. */
|
|
385
|
+
export function echoTextPayload(text) {
|
|
386
|
+
const payload = { type: 'text', text };
|
|
387
|
+
if (echoProbeKind(text) === null)
|
|
388
|
+
return payload;
|
|
389
|
+
// Only Core's terminal reply trace supplies controls; arbitrary prose and
|
|
390
|
+
// first-line parameters must not turn an ordinary text message into a return.
|
|
391
|
+
const reply = text.split('\n').reverse().find(line => /^\d{2}:\d{2}:\d{2}\.\d{3} \[EvolCore\.reply\] dir=ret hop=/.test(line));
|
|
392
|
+
const hopField = reply && /\bhop=([+-]?\d+)(?=\s|$)/.exec(reply);
|
|
393
|
+
if (!hopField)
|
|
394
|
+
return payload;
|
|
395
|
+
const hop = Number(hopField[1]);
|
|
396
|
+
if (!Number.isSafeInteger(hop))
|
|
397
|
+
throw new Error('echo hop exceeds JSON safe integer range');
|
|
398
|
+
return { ...payload, dir: 'ret', hop };
|
|
399
|
+
}
|
|
370
400
|
/**
|
|
371
401
|
* 组装一行 trace。
|
|
372
402
|
*
|
|
@@ -962,8 +992,6 @@ export class AUNChannel {
|
|
|
962
992
|
&& (!params || !String(payload.type).startsWith('menu.') || params.encrypt === true)
|
|
963
993
|
&& (!params || !permit.device || (params.to_device_id ?? params.device_id) === permit.device));
|
|
964
994
|
}
|
|
965
|
-
// Keep each target's attempt across channel recreation; reset only on process restart.
|
|
966
|
-
static configuredOwnerBindAttempts = new Set();
|
|
967
995
|
managedMenuClient = new ManagedMenuClient((params, beforeSend) => {
|
|
968
996
|
if (!this.connected || !this.client)
|
|
969
997
|
return Promise.reject(new Error('AUN channel is not connected'));
|
|
@@ -988,9 +1016,6 @@ export class AUNChannel {
|
|
|
988
1016
|
} });
|
|
989
1017
|
}
|
|
990
1018
|
client = null;
|
|
991
|
-
configuredOwnerBind;
|
|
992
|
-
configuredOwnerBindEpoch = 0;
|
|
993
|
-
configuredOwnerBindRecheck = false;
|
|
994
1019
|
ownerDirectoryCache;
|
|
995
1020
|
ownerDirectoryWatch;
|
|
996
1021
|
ownerDirectoryFlight;
|
|
@@ -1020,7 +1045,6 @@ export class AUNChannel {
|
|
|
1020
1045
|
/** `topic.renamed` 事件消费器,由 runtime 注入(见 setThreadRenameHandler)。 */
|
|
1021
1046
|
threadRenameHandler = null;
|
|
1022
1047
|
groupInviteHandler;
|
|
1023
|
-
groupInviteConnectedHandler;
|
|
1024
1048
|
groupInviteDeliveryGate;
|
|
1025
1049
|
groupInviteDelivered;
|
|
1026
1050
|
pendingEchoMessages = new Map();
|
|
@@ -1043,7 +1067,7 @@ export class AUNChannel {
|
|
|
1043
1067
|
// 便于 jq 过滤:`jq 'select(.task_id == "task-xxx")'`
|
|
1044
1068
|
const inbound = data && typeof data === 'object' ? data : {};
|
|
1045
1069
|
const isolateTrace = dir === 'IN' && event === 'message.received'
|
|
1046
|
-
&& (!this.config.pureIdentity || inbound.payload?.type === 'action_card_reply');
|
|
1070
|
+
&& (!this.config.pureIdentity || inbound.payload?.type === 'action_card_reply' || inbound.payload?.type === 'widget_card_reply');
|
|
1047
1071
|
const safeData = isolateTrace ? {
|
|
1048
1072
|
message_id: inbound.message_id, seq: inbound.seq,
|
|
1049
1073
|
envelope: { from: inbound.envelope?.from, to: inbound.envelope?.to, encrypted: inbound.envelope?.encrypted },
|
|
@@ -1357,6 +1381,73 @@ export class AUNChannel {
|
|
|
1357
1381
|
logger.info(`${this.logPrefix()} ActionInteraction audit: behavior=${behavior ?? 'reply'} `
|
|
1358
1382
|
+ `cardId=${cardMessageId} interactionId=${interactionId} result=${result} textLength=${textLength}`);
|
|
1359
1383
|
}
|
|
1384
|
+
async handleWidgetCardReply(payload, channelId, senderAid, delivery, messageId, encrypted) {
|
|
1385
|
+
let replyThreadId;
|
|
1386
|
+
try {
|
|
1387
|
+
const binding = typeof payload.card_message_id === 'string'
|
|
1388
|
+
? readWidgetCard(this.config.aid, payload.card_message_id) : undefined;
|
|
1389
|
+
// Group replies are broadcast to every Agent. Like action_card_reply,
|
|
1390
|
+
// a reply to another sender's card is silently ignored by this Agent.
|
|
1391
|
+
if (!binding)
|
|
1392
|
+
return;
|
|
1393
|
+
if (binding?.channelId === channelId && binding.chatType === delivery.chatType && binding.initiatorAid === senderAid) {
|
|
1394
|
+
replyThreadId = binding.threadId;
|
|
1395
|
+
}
|
|
1396
|
+
const outcome = await acceptWidgetCardReply({
|
|
1397
|
+
selfAid: this.config.aid, channelId, senderAid, chatType: delivery.chatType, payload, encrypted,
|
|
1398
|
+
dispatch: async (binding, action, values) => {
|
|
1399
|
+
if (binding.requestId) {
|
|
1400
|
+
const accepted = await this.interactionCallback?.({
|
|
1401
|
+
type: 'interaction.response', id: binding.requestId, action,
|
|
1402
|
+
values, operatorId: senderAid, encrypted,
|
|
1403
|
+
});
|
|
1404
|
+
if (!this.interactionCallback || accepted === false) {
|
|
1405
|
+
await this.invalidateInteraction(binding.requestId, 'backend_rejected');
|
|
1406
|
+
cancelWidgetCard(this.config.aid, binding.messageId);
|
|
1407
|
+
throw Object.assign(new Error('卡片已失效,请重新发起'), { code: 'WIDGET_CARD_EXPIRED' });
|
|
1408
|
+
}
|
|
1409
|
+
this.forgetInteractionCard(binding.messageId, binding.requestId);
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
if (!this.messageHandler)
|
|
1413
|
+
throw new Error('WidgetCard handler is unavailable');
|
|
1414
|
+
if (binding.threadId) {
|
|
1415
|
+
const thread = ThreadService.findThreadById(this.config.aid, binding.threadId);
|
|
1416
|
+
if (!thread || thread.peer !== channelId || thread.topicStatus === 'archived') {
|
|
1417
|
+
throw Object.assign(new Error('原话题已不存在或已归档,请重新发起'), { code: 'WIDGET_CARD_EXPIRED' });
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
const groupRoles = delivery.chatType === 'group' ? await this.resolveGroupMemberRoles(channelId) : undefined;
|
|
1421
|
+
const text = `[WidgetCard 用户${action === 'cancel' ? '取消' : '提交'}]\n${JSON.stringify({
|
|
1422
|
+
title: binding.title, card_message_id: binding.messageId,
|
|
1423
|
+
submission_id: payload.submission_id, action, ...(action === 'submit' ? { values } : {}),
|
|
1424
|
+
})}`;
|
|
1425
|
+
await this.dispatchMessage({
|
|
1426
|
+
channelId, userId: senderAid, chatType: delivery.chatType,
|
|
1427
|
+
...(delivery.chatType === 'group' ? { groupId: channelId,
|
|
1428
|
+
groupRole: groupRoles?.get(senderAid.toLowerCase()),
|
|
1429
|
+
myGroupRole: groupRoles?.get(this.config.aid.toLowerCase()),
|
|
1430
|
+
groupRoles: groupRoles ? Object.fromEntries(groupRoles) : undefined,
|
|
1431
|
+
speakerRelation: resolveSenderRelationRole({ selfAid: this.config.aid,
|
|
1432
|
+
channelKey: `aun#${this.config.aid}#main`, channelType: 'aun', chatType: 'group',
|
|
1433
|
+
senderAid, conversationId: channelId }),
|
|
1434
|
+
} : {}),
|
|
1435
|
+
text, messageId, encrypted, threadId: binding.threadId, source: 'card-trigger', isMentioned: true,
|
|
1436
|
+
msgType: 'widget_card_reply', payloadType: 'widget_card_reply',
|
|
1437
|
+
messageLogContent: '[WidgetCard 回复]', receivedAt: Date.now(), awaitHandler: true,
|
|
1438
|
+
replyContext: { delivery, threadId: binding.threadId,
|
|
1439
|
+
metadata: { encrypted }, replyToMessageId: messageId },
|
|
1440
|
+
});
|
|
1441
|
+
},
|
|
1442
|
+
});
|
|
1443
|
+
logger.info(`${this.logPrefix()} WidgetCard reply ${outcome}: mid=${messageId}`);
|
|
1444
|
+
}
|
|
1445
|
+
catch (error) {
|
|
1446
|
+
const code = error.code ?? 'WIDGET_REPLY_FAILED';
|
|
1447
|
+
logger.warn(`${this.logPrefix()} WidgetCard reply rejected: code=${code} mid=${messageId}`);
|
|
1448
|
+
this.notifyCardActionFailure(channelId, error.code ? error.message : '表单处理失败,请核实任务状态后再操作', senderAid, replyThreadId, delivery);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1360
1451
|
extractTextPayload(payload, channelId, senderAid, delivery, encrypted) {
|
|
1361
1452
|
if (typeof payload === 'string')
|
|
1362
1453
|
return payload;
|
|
@@ -1381,6 +1472,10 @@ export class AUNChannel {
|
|
|
1381
1472
|
?? (savedTopic?.channelId === channelId ? savedTopic?.threadId : undefined)
|
|
1382
1473
|
?? (typeof obj.thread_id === 'string' ? obj.thread_id : undefined);
|
|
1383
1474
|
if (cardInfo) {
|
|
1475
|
+
if (cardInfo.widget) {
|
|
1476
|
+
this.notifyCardActionFailure(channelId || '', '该卡片需要通过 widget_card_reply 提交表单', senderAid, threadId, cardDelivery);
|
|
1477
|
+
return '';
|
|
1478
|
+
}
|
|
1384
1479
|
// compose 按钮由新版客户端在卡片内采集输入;旧版客户端可继续从主编辑器
|
|
1385
1480
|
// 采集。两者最终都回传 action_card_reply{behavior:"compose", text}。
|
|
1386
1481
|
// 映射为 _custom_input + values.custom_text,复用 claude-runner 已有的自定义输入分支
|
|
@@ -1860,7 +1955,6 @@ export class AUNChannel {
|
|
|
1860
1955
|
prepareShutdown() {
|
|
1861
1956
|
this.intentionalDisconnect = true;
|
|
1862
1957
|
this.reconnectGeneration++;
|
|
1863
|
-
this.configuredOwnerBindEpoch++;
|
|
1864
1958
|
this.stopOwnerDirectoryRefresh();
|
|
1865
1959
|
this.stopOutboxTimer();
|
|
1866
1960
|
if (this.reconnectTimer)
|
|
@@ -2611,6 +2705,8 @@ export class AUNChannel {
|
|
|
2611
2705
|
/** 失效可能先于 outbox 卡片投递完成;迟到卡片不得重新启用交互。 */
|
|
2612
2706
|
invalidatedInteractions = new Map();
|
|
2613
2707
|
mentionModeResolver;
|
|
2708
|
+
/** Agent-level private-chat @ policy (`privateMentionMode`); unrelated to group mention policy. */
|
|
2709
|
+
privateMentionModeResolver;
|
|
2614
2710
|
/** Agent-level policy controlling whether group slash commands require structured mentions. */
|
|
2615
2711
|
groupSlashRequireMentionsResolver;
|
|
2616
2712
|
static PROACTIVE_ALLOW_TYPES = new Set([
|
|
@@ -2713,7 +2809,6 @@ export class AUNChannel {
|
|
|
2713
2809
|
if (this.config.pureIdentity && handlers)
|
|
2714
2810
|
return;
|
|
2715
2811
|
this.groupInviteHandler = handlers?.onInvite;
|
|
2716
|
-
this.groupInviteConnectedHandler = handlers?.onConnected;
|
|
2717
2812
|
this.groupInviteDeliveryGate = handlers?.canDeliver;
|
|
2718
2813
|
this.groupInviteDelivered = handlers?.onDelivered;
|
|
2719
2814
|
}
|
|
@@ -2832,7 +2927,6 @@ export class AUNChannel {
|
|
|
2832
2927
|
// An explicit new attempt retires the previous gateway's terminal decision.
|
|
2833
2928
|
this.setAidStatus('reconnecting', { lastAttemptAt: Date.now() });
|
|
2834
2929
|
this.stopOwnerDirectoryRefresh();
|
|
2835
|
-
this.configuredOwnerBindEpoch++;
|
|
2836
2930
|
this.observerGroupMembers.clear();
|
|
2837
2931
|
for (const groupId of new Set([
|
|
2838
2932
|
...this.observerGroupMembershipEpoch.keys(),
|
|
@@ -2902,8 +2996,6 @@ export class AUNChannel {
|
|
|
2902
2996
|
throw this.initializationCancelled();
|
|
2903
2997
|
}
|
|
2904
2998
|
this.client = client;
|
|
2905
|
-
const localConfig = loadAgent(aidName);
|
|
2906
|
-
ownerResolver.setAgentConfiguredOwners(aidName, configuredOwnerList(localConfig));
|
|
2907
2999
|
ownerResolver.attachClient(aidName, client);
|
|
2908
3000
|
registerSameOwnerClient(aidName, client, store);
|
|
2909
3001
|
try {
|
|
@@ -2925,7 +3017,6 @@ export class AUNChannel {
|
|
|
2925
3017
|
store,
|
|
2926
3018
|
aunPath,
|
|
2927
3019
|
cacheRoot: resolveRoot(),
|
|
2928
|
-
ownerAid: this.config.controlOwnerAid,
|
|
2929
3020
|
}).then(result => {
|
|
2930
3021
|
if (!isCurrentClient())
|
|
2931
3022
|
return;
|
|
@@ -3189,7 +3280,6 @@ export class AUNChannel {
|
|
|
3189
3280
|
this.connectedAt = Date.now();
|
|
3190
3281
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
3191
3282
|
completeControlAgentMd();
|
|
3192
|
-
this.reconcileConfiguredOwnerBinding();
|
|
3193
3283
|
// 连接本身**不触发拉取**:名录是懒同步的,只有 `owner.directory.changed` 会写标记。
|
|
3194
3284
|
// 重连很频繁(网络抖动、网关轮换),每次连上都拉一遍会把恢复期变成拉取风暴。
|
|
3195
3285
|
if (!this.config.pureIdentity) {
|
|
@@ -3201,9 +3291,6 @@ export class AUNChannel {
|
|
|
3201
3291
|
catch (error) {
|
|
3202
3292
|
logger.warn(`${this.logPrefix()} Service warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3203
3293
|
}
|
|
3204
|
-
void Promise.resolve(this.groupInviteConnectedHandler?.()).catch(error => {
|
|
3205
|
-
logger.warn(`${this.logPrefix()} Group invitation recovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3206
|
-
});
|
|
3207
3294
|
}
|
|
3208
3295
|
logger.debug(`${this.logPrefix()} connect() completed as ${this._aid}; awaiting connection.state for lifecycle log`);
|
|
3209
3296
|
this.startOwnerDirectoryRefresh();
|
|
@@ -3372,10 +3459,16 @@ export class AUNChannel {
|
|
|
3372
3459
|
const rawAttachments = preCollected ?? this.collectAllAttachments(payload);
|
|
3373
3460
|
const images = [];
|
|
3374
3461
|
let finalText = baseText;
|
|
3462
|
+
let logText = baseText;
|
|
3375
3463
|
if (rawAttachments.length === 0 || !this.client) {
|
|
3376
|
-
return { finalText, images };
|
|
3464
|
+
return { finalText, logText, images };
|
|
3377
3465
|
}
|
|
3466
|
+
// 两套正文:
|
|
3467
|
+
// - finalText:绝对路径。本轮直接给模型用,Read 工具要能立刻读到。
|
|
3468
|
+
// - logText:`$EVOLCORE_HOME/...` 可迁移路径。写进 messages.jsonl,
|
|
3469
|
+
// 换机器/换盘符后仍能被展开成当时的正确绝对路径。
|
|
3378
3470
|
const fileParts = [];
|
|
3471
|
+
const logFileParts = [];
|
|
3379
3472
|
for (const att of rawAttachments) {
|
|
3380
3473
|
const attachmentBuffer = await this.downloadAttachment(att, channelId, delivery);
|
|
3381
3474
|
if (!attachmentBuffer)
|
|
@@ -3390,41 +3483,49 @@ export class AUNChannel {
|
|
|
3390
3483
|
catch { /* read failed, treat as non-image file */ }
|
|
3391
3484
|
if (img) {
|
|
3392
3485
|
try {
|
|
3393
|
-
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), img.mimeType);
|
|
3486
|
+
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), img.mimeType, { filename: name, direction: 'in' });
|
|
3394
3487
|
img = { ...img, attachmentId: attachment.attachmentId, localPath: attachment.filePath };
|
|
3395
|
-
//
|
|
3488
|
+
// 和非图片文件一样,把落盘路径放进消息正文,模型可直接用这个路径读文件或传给命令
|
|
3396
3489
|
fileParts.push(`[图片: ${name} → ${attachment.filePath}]`);
|
|
3490
|
+
logFileParts.push(`[图片: ${name} → ${toAttachmentMarkedPath(this.config.aid, attachment.filePath)}]`);
|
|
3397
3491
|
}
|
|
3398
3492
|
catch (error) {
|
|
3399
3493
|
logger.warn(`${this.logPrefix()} Failed to persist relation attachment for ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3400
3494
|
}
|
|
3401
3495
|
images.push(img);
|
|
3402
|
-
//
|
|
3496
|
+
// 图片已注入视觉通道;落盘路径写进消息正文,模型用该路径读文件或传给命令
|
|
3403
3497
|
}
|
|
3404
3498
|
else {
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
: process.cwd();
|
|
3499
|
+
// 非图片文件同样进关系级附件目录:与图片统一落点,
|
|
3500
|
+
// 换机器时只要搬 $EVOLCORE_HOME,历史里引用的文件都还在。
|
|
3408
3501
|
try {
|
|
3409
|
-
const
|
|
3410
|
-
fileParts.push(`[文件: ${name} → ${
|
|
3502
|
+
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), att.content_type || att.mime_type || 'application/octet-stream', { filename: name, allowAnyExtension: true, direction: 'in' });
|
|
3503
|
+
fileParts.push(`[文件: ${name} → ${attachment.filePath}]`);
|
|
3504
|
+
logFileParts.push(`[文件: ${name} → ${toAttachmentMarkedPath(this.config.aid, attachment.filePath)}]`);
|
|
3411
3505
|
}
|
|
3412
3506
|
catch (error) {
|
|
3413
|
-
logger.warn(`${this.logPrefix()}
|
|
3507
|
+
logger.warn(`${this.logPrefix()} Failed to persist relation file for ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3414
3508
|
}
|
|
3415
3509
|
}
|
|
3416
3510
|
}
|
|
3417
3511
|
const parts = [];
|
|
3418
|
-
|
|
3512
|
+
const logParts = [];
|
|
3513
|
+
if (baseText) {
|
|
3419
3514
|
parts.push(baseText);
|
|
3515
|
+
logParts.push(baseText);
|
|
3516
|
+
}
|
|
3420
3517
|
if (fileParts.length > 0) {
|
|
3421
3518
|
parts.push(...fileParts);
|
|
3422
3519
|
parts.push('请使用 Read 工具读取文件内容。');
|
|
3520
|
+
logParts.push(...logFileParts);
|
|
3521
|
+
logParts.push('请使用 Read 工具读取文件内容。');
|
|
3423
3522
|
}
|
|
3424
3523
|
if (parts.length > 0)
|
|
3425
3524
|
finalText = parts.join('\n\n');
|
|
3525
|
+
if (logParts.length > 0)
|
|
3526
|
+
logText = logParts.join('\n\n');
|
|
3426
3527
|
logger.info(`${this.logPrefix()} [attachments] count=${rawAttachments.length} images=${images.length} files=${fileParts.length}`);
|
|
3427
|
-
return { finalText, images };
|
|
3528
|
+
return { finalText, logText, images };
|
|
3428
3529
|
}
|
|
3429
3530
|
async downloadAttachmentWithRetry(url, filename, source, download) {
|
|
3430
3531
|
const host = attachmentDownloadHost(url);
|
|
@@ -4004,10 +4105,41 @@ export class AUNChannel {
|
|
|
4004
4105
|
logger.debug(`${this.logPrefix()} P2P dropped: pubsub control envelope (mid=${messageId})`);
|
|
4005
4106
|
return;
|
|
4006
4107
|
}
|
|
4108
|
+
// Ability replies belong to an authenticated protocol request, not a
|
|
4109
|
+
// conversation contact. Match them before chat admission/observers;
|
|
4110
|
+
// unmatched or spoofed protocol replies never become model input.
|
|
4111
|
+
const abilityReply = msg.payload && typeof msg.payload === 'object' && !Array.isArray(msg.payload)
|
|
4112
|
+
&& msg.payload.type === 'ability' && ['ack', 'result'].includes(String(msg.payload.role));
|
|
4113
|
+
if (abilityReply) {
|
|
4114
|
+
if (!this.claimInboundMessage('private', messageId, seq))
|
|
4115
|
+
return;
|
|
4116
|
+
const matched = getAunRequestRegistry().resolveIncoming({
|
|
4117
|
+
selfAid: this._aid || this.config.aid, fromAid,
|
|
4118
|
+
fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
|
|
4119
|
+
messageId, payload: msg.payload, encrypted: !!env.encrypted, transport: 'p2p',
|
|
4120
|
+
});
|
|
4121
|
+
if (!matched)
|
|
4122
|
+
logger.debug(`${this.logPrefix()} Unmatched Ability reply: mid=${messageId} from=${fromAid}`);
|
|
4123
|
+
return;
|
|
4124
|
+
}
|
|
4007
4125
|
if (!appOwned && !this.claimInboundMessage('private', messageId, seq))
|
|
4008
4126
|
return;
|
|
4009
4127
|
const protectedHeaders = verifiedProtectedHeaders(msg, env);
|
|
4010
4128
|
const payload = msg.payload ?? '';
|
|
4129
|
+
if (payload && typeof payload === 'object' && payload.type === 'widget_card_reply') {
|
|
4130
|
+
await this.handleWidgetCardReply(payload, fromAid, fromAid, { chatType: 'private' }, messageId, !!env.encrypted);
|
|
4131
|
+
return;
|
|
4132
|
+
}
|
|
4133
|
+
// Payment controls have durable business mappings and must precede the
|
|
4134
|
+
// generic one-shot card consumer, observers, attachments and model input.
|
|
4135
|
+
try {
|
|
4136
|
+
if (!this.config.pureIdentity && await consumePaymentInbound(this.config.aid, fromAid, payload, !!env.encrypted))
|
|
4137
|
+
return;
|
|
4138
|
+
}
|
|
4139
|
+
catch (error) {
|
|
4140
|
+
const code = error?.code ?? 'UNKNOWN';
|
|
4141
|
+
logger.warn(`${this.logPrefix()} Payment inbound isolated: code=${code}; continuing normal message handling`);
|
|
4142
|
+
}
|
|
4011
4143
|
const menuRequest = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
4012
4144
|
&& ['menu.list', 'menu.query', 'menu.options', 'menu.update', 'menu.action', 'menu.token.request'].includes(payload.type)
|
|
4013
4145
|
? payload : undefined;
|
|
@@ -4172,8 +4304,22 @@ export class AUNChannel {
|
|
|
4172
4304
|
// sender omitted payload.mentions; keep that compatibility signal.
|
|
4173
4305
|
mentions.push({ aid: this._aid });
|
|
4174
4306
|
}
|
|
4307
|
+
// 私聊提及标记:结构化 mentions 命中自己或 @all。信封与渲染层据此表达「这条 @ 了我」。
|
|
4308
|
+
// 同 AID 其它设备发来的消息(self-sync)也按已提及处理,与群聊 handoff 的口径一致:
|
|
4309
|
+
// 这类记录不是「别人对我说话」,不该被提及过滤挡掉。
|
|
4310
|
+
const addressedInPrivate = (!!this._aid
|
|
4311
|
+
&& (mentionEntryTargets(mentions).includes(this._aid) || hasMentionAll(mentions)))
|
|
4312
|
+
|| (!!this._aid && fromAid === this._aid);
|
|
4175
4313
|
// Process attachments (顶层 + 嵌套在 merge.items / quote.quote 中的)
|
|
4176
|
-
const { finalText,
|
|
4314
|
+
const { finalText, logText: attachmentLogText, images: inboundImages } = contactControl
|
|
4315
|
+
? { finalText: text, logText: text, images: [] }
|
|
4316
|
+
: await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.attachments', () => this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' }));
|
|
4317
|
+
// 历史记录正文用 logText(`$AGENT_DIR/attachments/...` 别名路径),不用 finalText:
|
|
4318
|
+
// finalText 是本回合给模型的绝对路径,写进历史后换机器/换盘符就失效。
|
|
4319
|
+
// 用 logDescriptor.content 又会把路径丢掉,读历史的一方只能看到 `[image] 文件名`。
|
|
4320
|
+
const loggedContent = logDescriptor.msgType === 'text'
|
|
4321
|
+
? attachmentLogText
|
|
4322
|
+
: (inboundImages.length > 0 || attachmentLogText !== text ? attachmentLogText : logDescriptor.content);
|
|
4177
4323
|
// 私聊 channelId = 对端 AID(不再读 payload.chat_id 含 device 三段式)
|
|
4178
4324
|
// device_id 仅 SDK 内部多实例去重用,evolcore session 层面跨端共享会话
|
|
4179
4325
|
const chatId = fromAid;
|
|
@@ -4282,6 +4428,25 @@ export class AUNChannel {
|
|
|
4282
4428
|
logger.info(`${this.logPrefix()} P2P retained in generic inbound event stream (not Agent chat): type=${p2pPayloadType} from=${shortAid}(${displayName}) mid=${messageId}`);
|
|
4283
4429
|
return;
|
|
4284
4430
|
}
|
|
4431
|
+
// ── 私聊提及模式(privateMentionMode,仅 Agent 级、Owner 可改)──
|
|
4432
|
+
// 判定放在所有控制类 payload 的 return 之后、真正 dispatch 之前:
|
|
4433
|
+
// menu.* / bind.request / observer.inject / event / 白名单外类型都已在上方返回,
|
|
4434
|
+
// 走到这里的一定是普通对话消息。
|
|
4435
|
+
// 与群聊 mentionMode 完全独立:只看 Agent 级 privateMentionMode,
|
|
4436
|
+
// 不读服务器 mention_mode,也不读关系级配置。
|
|
4437
|
+
if (await this.resolvePrivateMentionMode() === 'mention-only'
|
|
4438
|
+
// 联系人补投必须处理。
|
|
4439
|
+
&& !contactDelivery
|
|
4440
|
+
// echo 探针走独立 trace 流程,不参与提及过滤。
|
|
4441
|
+
&& echoProbeKind(text) === null
|
|
4442
|
+
// slash 命令不拦,与群聊 mention-only 的语义保持一致。
|
|
4443
|
+
&& !/^\s*\//.test(text)
|
|
4444
|
+
&& !addressedInPrivate) {
|
|
4445
|
+
// 先落盘再丢弃:写失败必须抛出,绝不能静默吞掉消息。
|
|
4446
|
+
this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq, undefined, undefined, 'filtered-mention-only', loggedContent);
|
|
4447
|
+
logger.info(`${this.logPrefix()} P2P dropped: private mention-only (from=${fromAid} mid=${messageId} textPreview=${JSON.stringify(logPreview(text))})`);
|
|
4448
|
+
return;
|
|
4449
|
+
}
|
|
4285
4450
|
const msgChatmode = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
|
|
4286
4451
|
logger.info(`${this.logPrefix()} message.route: decision=dispatch chatType=private from=${shortAid}(${displayName}) mid=${messageId} payloadType=${p2pPayloadType || 'text'} encrypt=${msgEncrypted} chatmode=${msgChatmode ?? 'none'} textPreview=${JSON.stringify(logPreview(finalText))}`);
|
|
4287
4452
|
appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'message_in', aid: this.config.aid, from: fromAid, msgId: messageId, kind: 'text', len: finalText.length });
|
|
@@ -4296,7 +4461,7 @@ export class AUNChannel {
|
|
|
4296
4461
|
text: this.config.pureIdentity && p2pPayloadType === 'text'
|
|
4297
4462
|
? (typeof payload.text === 'string' ? payload.text : '') : finalText,
|
|
4298
4463
|
chatType: 'private',
|
|
4299
|
-
...(
|
|
4464
|
+
...(p2pPayloadType === 'text' ? {
|
|
4300
4465
|
peerDeviceId: menuSenderDeviceId(msg.sender_device_id),
|
|
4301
4466
|
} : {}),
|
|
4302
4467
|
messageId,
|
|
@@ -4307,6 +4472,8 @@ export class AUNChannel {
|
|
|
4307
4472
|
seq,
|
|
4308
4473
|
threadId,
|
|
4309
4474
|
mentions,
|
|
4475
|
+
// 私聊提及标记:结构化 mentions 命中自己或 @all。信封与渲染层据此表达「这条 @ 了我」。
|
|
4476
|
+
isMentioned: addressedInPrivate,
|
|
4310
4477
|
peerName: displayName || undefined,
|
|
4311
4478
|
peerType: peerIdentity.type,
|
|
4312
4479
|
peerExttype: peerIdentity.exttype,
|
|
@@ -4320,7 +4487,7 @@ export class AUNChannel {
|
|
|
4320
4487
|
msgType: logDescriptor.msgType,
|
|
4321
4488
|
payloadType: logDescriptor.payloadType,
|
|
4322
4489
|
payloadSummary: logDescriptor.payloadSummary,
|
|
4323
|
-
messageLogContent:
|
|
4490
|
+
messageLogContent: loggedContent,
|
|
4324
4491
|
});
|
|
4325
4492
|
if (contactDelivery)
|
|
4326
4493
|
await dispatched;
|
|
@@ -4343,6 +4510,10 @@ export class AUNChannel {
|
|
|
4343
4510
|
const groupId = env.group_id ?? '';
|
|
4344
4511
|
const senderAid = env.from ?? '';
|
|
4345
4512
|
const payload = msg.payload ?? '';
|
|
4513
|
+
if (payload && typeof payload === 'object' && payload.type === 'widget_card_reply') {
|
|
4514
|
+
await this.handleWidgetCardReply(payload, groupId, senderAid, { chatType: 'group', groupId }, messageId, !!env.encrypted);
|
|
4515
|
+
return;
|
|
4516
|
+
}
|
|
4346
4517
|
if (payload && typeof payload === 'object' && payload.type === 'action_card_reply') {
|
|
4347
4518
|
const ref = payload.ref_message_id ?? payload.card_message_id;
|
|
4348
4519
|
const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
|
|
@@ -4499,6 +4670,33 @@ export class AUNChannel {
|
|
|
4499
4670
|
const groupSlashRequireMentions = this.groupSlashRequireMentionsResolver
|
|
4500
4671
|
? await this.groupSlashRequireMentionsResolver().catch(() => undefined) ?? true
|
|
4501
4672
|
: true;
|
|
4673
|
+
// 命令消息:剥离所有 @(多 agent 被 @ 时各自拿到干净的 /status 各自执行);
|
|
4674
|
+
// 普通消息:仅在唯一 @ 是自己时剥离,保留其他 @ 供 agent 感知。
|
|
4675
|
+
const strippedText = isCommandMsg
|
|
4676
|
+
? slashCommandText
|
|
4677
|
+
: this.stripSelfMentionIfOnly(text, this._aid);
|
|
4678
|
+
// Detect attachments before the empty-text guard (顶层 + 嵌套)
|
|
4679
|
+
const rawAttachments = this.collectAllAttachments(payload);
|
|
4680
|
+
const hasAttachments = rawAttachments.length > 0;
|
|
4681
|
+
// Allow through if there's text OR attachments; both-empty messages are silently dropped.
|
|
4682
|
+
// echo 探针即使正文为空也要继续走 trace 流程。
|
|
4683
|
+
if (!strippedText && !hasAttachments && !isEchoMsg) {
|
|
4684
|
+
logger.debug(`${this.logPrefix()} Group dropped: empty text and no attachments (group=${groupId} sender=${senderAid} mid=${messageId})`);
|
|
4685
|
+
return;
|
|
4686
|
+
}
|
|
4687
|
+
// 附件统一「收到就下载」:与私聊同一策略,不等进模型。
|
|
4688
|
+
//
|
|
4689
|
+
// 理由:按需下载听上去省资源,但代价落在使用侧——模型要先跑一次
|
|
4690
|
+
// `ec fs cp` 再读文件,多一轮工具调用和往返延迟;而且跨 AID 读取受
|
|
4691
|
+
// public/ACL 授权约束,取回可能直接失败。下载回来存着,用的时候是
|
|
4692
|
+
// 本地绝对路径,一次 Read 就够。
|
|
4693
|
+
//
|
|
4694
|
+
// 同时保证被提及过滤掉的消息,其历史记录里也带落盘路径(loggedContent)。
|
|
4695
|
+
const { finalText, logText: attachmentLogText, images: inboundImages } = await this.processAttachments(payload, strippedText, groupId, rawAttachments, { chatType: 'group', groupId });
|
|
4696
|
+
// 历史记录用别名路径(logText),不能退回到 `[image] 文件名`,也不能记绝对路径。
|
|
4697
|
+
const loggedContent = logDescriptor.msgType === 'text'
|
|
4698
|
+
? attachmentLogText
|
|
4699
|
+
: (inboundImages.length > 0 || attachmentLogText !== strippedText ? attachmentLogText : logDescriptor.content);
|
|
4502
4700
|
if (isEchoMsg) {
|
|
4503
4701
|
// echo.ask / echo.ecdiag:追加 trace 后继续走 Agent 流程(下面会 dispatch)。
|
|
4504
4702
|
// echo 本身已在快速通道直接回包,不会走到这里。
|
|
@@ -4536,7 +4734,7 @@ export class AUNChannel {
|
|
|
4536
4734
|
if ((commandTargetsAnotherAgent || (enforceMention && !isMentioned)) && !isOwnHandoff) {
|
|
4537
4735
|
try {
|
|
4538
4736
|
if (text.trim() || this.collectAllAttachments(payload).length) {
|
|
4539
|
-
this.appendInboundPayloadJsonl(groupId, senderAid, messageId, msgEncrypted, true, logDescriptor, threadId, receivedAt, seq, isCommandMsg ? 'command' : 'unmentioned', 'filtered');
|
|
4737
|
+
this.appendInboundPayloadJsonl(groupId, senderAid, messageId, msgEncrypted, true, logDescriptor, threadId, receivedAt, seq, isCommandMsg ? 'command' : 'unmentioned', 'filtered', undefined, loggedContent);
|
|
4540
4738
|
}
|
|
4541
4739
|
}
|
|
4542
4740
|
catch (error) {
|
|
@@ -4552,22 +4750,7 @@ export class AUNChannel {
|
|
|
4552
4750
|
return;
|
|
4553
4751
|
}
|
|
4554
4752
|
}
|
|
4555
|
-
// 命令消息:剥离所有 @(多 agent 被 @ 时各自拿到干净的 /status 各自执行);
|
|
4556
|
-
// 普通消息:仅在唯一 @ 是自己时剥离,保留其他 @ 供 agent 感知。
|
|
4557
|
-
const strippedText = isCommandMsg
|
|
4558
|
-
? slashCommandText
|
|
4559
|
-
: this.stripSelfMentionIfOnly(text, this._aid);
|
|
4560
|
-
// Detect attachments before the empty-text guard (顶层 + 嵌套)
|
|
4561
|
-
const rawAttachments = this.collectAllAttachments(payload);
|
|
4562
|
-
const hasAttachments = rawAttachments.length > 0;
|
|
4563
|
-
// Allow through if there's text OR attachments; both-empty messages are silently dropped
|
|
4564
|
-
if (!strippedText && !hasAttachments) {
|
|
4565
|
-
logger.debug(`${this.logPrefix()} Group dropped: empty text and no attachments (group=${groupId} sender=${senderAid} mid=${messageId})`);
|
|
4566
|
-
return;
|
|
4567
|
-
}
|
|
4568
4753
|
const mentions = payloadMentionEntries;
|
|
4569
|
-
// Process attachments
|
|
4570
|
-
const { finalText, images: inboundImages } = await this.processAttachments(payload, strippedText, groupId, rawAttachments, { chatType: 'group', groupId });
|
|
4571
4754
|
const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
|
|
4572
4755
|
const peerIdentity = await PeerIdentityCache.resolve('aun', senderAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
|
|
4573
4756
|
const shortAid = this.getShortAid(senderAid);
|
|
@@ -4648,7 +4831,7 @@ export class AUNChannel {
|
|
|
4648
4831
|
msgType: logDescriptor.msgType,
|
|
4649
4832
|
payloadType: logDescriptor.payloadType,
|
|
4650
4833
|
payloadSummary: logDescriptor.payloadSummary,
|
|
4651
|
-
messageLogContent:
|
|
4834
|
+
messageLogContent: loggedContent,
|
|
4652
4835
|
});
|
|
4653
4836
|
}
|
|
4654
4837
|
dispatchMessage(event) {
|
|
@@ -4777,13 +4960,16 @@ export class AUNChannel {
|
|
|
4777
4960
|
.then(() => handler(inbound))
|
|
4778
4961
|
.catch(err => {
|
|
4779
4962
|
logger.error(`${this.logPrefix()} Message handler error:`, err);
|
|
4780
|
-
if (event.contactDelivery)
|
|
4963
|
+
if (event.contactDelivery || event.awaitHandler)
|
|
4781
4964
|
throw err;
|
|
4782
4965
|
});
|
|
4783
|
-
if (event.contactDelivery)
|
|
4966
|
+
if (event.contactDelivery || event.awaitHandler)
|
|
4784
4967
|
return dispatched;
|
|
4785
4968
|
}
|
|
4786
|
-
appendInboundPayloadJsonl(channelId, fromAid, msgId, encrypt, isGroup, descriptor, threadId, receivedAt, gatewaySeq, groupAttention, groupDelivery) {
|
|
4969
|
+
appendInboundPayloadJsonl(channelId, fromAid, msgId, encrypt, isGroup, descriptor, threadId, receivedAt, gatewaySeq, groupAttention, groupDelivery, privateAttention, contentOverride) {
|
|
4970
|
+
// 私聊过滤记录与群聊过滤记录共用「严格落盘」语义,但使用独立字段,
|
|
4971
|
+
// 避免群历史读取器把私聊记录当成群分类依据。
|
|
4972
|
+
const strict = groupDelivery === 'filtered' || privateAttention !== undefined;
|
|
4787
4973
|
try {
|
|
4788
4974
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', channelId, this.config.aid, this.config.channelName);
|
|
4789
4975
|
const entry = buildInboundEntry({
|
|
@@ -4793,7 +4979,7 @@ export class AUNChannel {
|
|
|
4793
4979
|
chatType: isGroup ? 'group' : 'private',
|
|
4794
4980
|
groupId: isGroup ? channelId : null,
|
|
4795
4981
|
msgId,
|
|
4796
|
-
content: descriptor.content,
|
|
4982
|
+
content: contentOverride ?? descriptor.content,
|
|
4797
4983
|
encrypt,
|
|
4798
4984
|
msgType: descriptor.msgType,
|
|
4799
4985
|
payloadType: descriptor.payloadType,
|
|
@@ -4803,15 +4989,16 @@ export class AUNChannel {
|
|
|
4803
4989
|
gatewaySeq,
|
|
4804
4990
|
groupAttention,
|
|
4805
4991
|
groupDelivery,
|
|
4992
|
+
privateAttention,
|
|
4806
4993
|
});
|
|
4807
|
-
if (
|
|
4994
|
+
if (strict)
|
|
4808
4995
|
appendMessageLogStrict(chatDir, entry, true);
|
|
4809
4996
|
else
|
|
4810
4997
|
appendMessageLog(chatDir, entry);
|
|
4811
4998
|
}
|
|
4812
4999
|
catch (e) {
|
|
4813
5000
|
logger.warn(`${this.logPrefix()} appendInboundPayloadJsonl failed: ${e}`);
|
|
4814
|
-
if (
|
|
5001
|
+
if (strict)
|
|
4815
5002
|
throw e;
|
|
4816
5003
|
}
|
|
4817
5004
|
}
|
|
@@ -5299,7 +5486,7 @@ export class AUNChannel {
|
|
|
5299
5486
|
echoText += `\n${echoTraceLine({
|
|
5300
5487
|
node: 'EvolCore.reply',
|
|
5301
5488
|
dir: 'ret',
|
|
5302
|
-
hop: echoTraceNextHop(echoText),
|
|
5489
|
+
hop: echoTraceNextHop(echoText, 'ret'),
|
|
5303
5490
|
ver,
|
|
5304
5491
|
now: replyTs,
|
|
5305
5492
|
extra: `conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -5418,7 +5605,6 @@ export class AUNChannel {
|
|
|
5418
5605
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
5419
5606
|
this.trace('IN', source, data);
|
|
5420
5607
|
logger.info(`${this.logPrefix()} connection.state: state=connected gateway=${this.gatewayUrl || 'unknown'}`);
|
|
5421
|
-
this.reconcileConfiguredOwnerBinding();
|
|
5422
5608
|
this.startOwnerDirectoryRefresh();
|
|
5423
5609
|
// 不在这里清 flapCount —— 短命连接一上来就会触发本分支,
|
|
5424
5610
|
// 必须等 disconnected 时根据 lifetime 决定是否清零
|
|
@@ -5428,8 +5614,6 @@ export class AUNChannel {
|
|
|
5428
5614
|
const wasConnected = this.connected;
|
|
5429
5615
|
this.connected = false;
|
|
5430
5616
|
this.stopOwnerDirectoryRefresh();
|
|
5431
|
-
if (wasConnected)
|
|
5432
|
-
this.configuredOwnerBindEpoch++;
|
|
5433
5617
|
this.clearQueuedObserverSends(state);
|
|
5434
5618
|
// The nine-state SDK emits standby -> retry_backoff -> reconnecting for
|
|
5435
5619
|
// one reconnect cycle. Count the connected-to-down edge once instead of
|
|
@@ -5483,7 +5667,6 @@ export class AUNChannel {
|
|
|
5483
5667
|
}
|
|
5484
5668
|
else if (state === 'terminal_failed') {
|
|
5485
5669
|
this.stopOwnerDirectoryRefresh();
|
|
5486
|
-
this.configuredOwnerBindEpoch++;
|
|
5487
5670
|
this.connected = false;
|
|
5488
5671
|
this.connectedAt = 0;
|
|
5489
5672
|
this.trace('IN', source, data);
|
|
@@ -5536,95 +5719,6 @@ export class AUNChannel {
|
|
|
5536
5719
|
}
|
|
5537
5720
|
}
|
|
5538
5721
|
}
|
|
5539
|
-
configuredOwnerAid() {
|
|
5540
|
-
const config = loadAgent(this.config.aid);
|
|
5541
|
-
if (!config)
|
|
5542
|
-
return undefined;
|
|
5543
|
-
const lifecycle = resolveAgentLifecycle(config);
|
|
5544
|
-
// Existing active Agents may still carry an unfulfilled configured binding target.
|
|
5545
|
-
if (lifecycle === null)
|
|
5546
|
-
return undefined;
|
|
5547
|
-
return firstConfiguredOwner(config);
|
|
5548
|
-
}
|
|
5549
|
-
reconcileConfiguredOwnerBinding() {
|
|
5550
|
-
const client = this.client;
|
|
5551
|
-
const subjectAid = this.config.aid;
|
|
5552
|
-
const epoch = this.configuredOwnerBindEpoch;
|
|
5553
|
-
if (!client || !this.connected || this.intentionalDisconnect || this.config.pureIdentity)
|
|
5554
|
-
return;
|
|
5555
|
-
if (this.configuredOwnerBind) {
|
|
5556
|
-
if (this.configuredOwnerBind.client !== client || this.configuredOwnerBind.epoch !== epoch) {
|
|
5557
|
-
this.configuredOwnerBindRecheck = true;
|
|
5558
|
-
}
|
|
5559
|
-
return;
|
|
5560
|
-
}
|
|
5561
|
-
// Queue the work after installing the guard; config failures must not fail the channel connection.
|
|
5562
|
-
const promise = Promise.resolve()
|
|
5563
|
-
.then(() => this.submitConfiguredOwnerBinding(subjectAid, client, epoch))
|
|
5564
|
-
.catch(error => {
|
|
5565
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
5566
|
-
logger.warn(`${this.logPrefix()} Configured Owner binding invitation failed: ${reason}`);
|
|
5567
|
-
});
|
|
5568
|
-
const tracked = promise.finally(() => {
|
|
5569
|
-
if (this.configuredOwnerBind?.promise !== tracked)
|
|
5570
|
-
return;
|
|
5571
|
-
this.configuredOwnerBind = undefined;
|
|
5572
|
-
const recheck = this.configuredOwnerBindRecheck;
|
|
5573
|
-
this.configuredOwnerBindRecheck = false;
|
|
5574
|
-
if (recheck)
|
|
5575
|
-
this.reconcileConfiguredOwnerBinding();
|
|
5576
|
-
});
|
|
5577
|
-
this.configuredOwnerBind = { client, epoch, promise: tracked };
|
|
5578
|
-
}
|
|
5579
|
-
isCurrentConfiguredOwnerBind(client, epoch) {
|
|
5580
|
-
return this.client === client && this.configuredOwnerBindEpoch === epoch
|
|
5581
|
-
&& this.connected && !this.intentionalDisconnect;
|
|
5582
|
-
}
|
|
5583
|
-
async submitConfiguredOwnerBinding(subjectAid, client, epoch) {
|
|
5584
|
-
if (!this.isCurrentConfiguredOwnerBind(client, epoch))
|
|
5585
|
-
return;
|
|
5586
|
-
const configuredOwnerAid = this.configuredOwnerAid();
|
|
5587
|
-
if (!configuredOwnerAid
|
|
5588
|
-
|| AUNChannel.configuredOwnerBindAttempts.has(JSON.stringify([subjectAid, configuredOwnerAid]))
|
|
5589
|
-
|| ownerResolver.hasRejectedOwnerBinding(subjectAid, configuredOwnerAid))
|
|
5590
|
-
return;
|
|
5591
|
-
ownerResolver.setConnected(subjectAid, client, true);
|
|
5592
|
-
const current = await ownerResolver.refresh(subjectAid, { force: true, source: 'channel.binding' });
|
|
5593
|
-
if (!this.isCurrentConfiguredOwnerBind(client, epoch))
|
|
5594
|
-
return;
|
|
5595
|
-
// The config may change while the fresh consensus query is in flight.
|
|
5596
|
-
const ownerAid = this.configuredOwnerAid();
|
|
5597
|
-
if (!ownerAid || ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid))
|
|
5598
|
-
return;
|
|
5599
|
-
if (current.task?.operation === 'bind' && current.task.owner_aid === ownerAid
|
|
5600
|
-
&& current.task.status === 'rejected') {
|
|
5601
|
-
return;
|
|
5602
|
-
}
|
|
5603
|
-
if (current.consensusStatus === 'consensus')
|
|
5604
|
-
return;
|
|
5605
|
-
if (!['unbound', 'released', 'single_sided'].includes(current.consensusStatus))
|
|
5606
|
-
return;
|
|
5607
|
-
const attemptKey = JSON.stringify([subjectAid, ownerAid]);
|
|
5608
|
-
if (AUNChannel.configuredOwnerBindAttempts.has(attemptKey))
|
|
5609
|
-
return;
|
|
5610
|
-
// Reserve across channel recreation while preparation is in flight. Only entering
|
|
5611
|
-
// an SDK mutation consumes the attempt; a lost receipt must never release it.
|
|
5612
|
-
AUNChannel.configuredOwnerBindAttempts.add(attemptKey);
|
|
5613
|
-
let submissionStarted = false;
|
|
5614
|
-
try {
|
|
5615
|
-
await ownerResolver.bind(subjectAid, ownerAid, () => this.isCurrentConfiguredOwnerBind(client, epoch) && this.configuredOwnerAid() === ownerAid
|
|
5616
|
-
&& !ownerResolver.hasRejectedOwnerBinding(subjectAid, ownerAid), () => {
|
|
5617
|
-
submissionStarted = true;
|
|
5618
|
-
logger.info(`${this.logPrefix()} Submitting configured Owner binding invitation: `
|
|
5619
|
-
+ `subject=${subjectAid} owner=${ownerAid} consensus=${current.consensusStatus}`);
|
|
5620
|
-
});
|
|
5621
|
-
}
|
|
5622
|
-
catch (error) {
|
|
5623
|
-
if (!submissionStarted)
|
|
5624
|
-
AUNChannel.configuredOwnerBindAttempts.delete(attemptKey);
|
|
5625
|
-
throw error;
|
|
5626
|
-
}
|
|
5627
|
-
}
|
|
5628
5722
|
/** 判断 terminal_failed 的 reason 是否属于"被踢"类 */
|
|
5629
5723
|
isKickReason(reason) {
|
|
5630
5724
|
if (!reason)
|
|
@@ -5819,6 +5913,18 @@ export class AUNChannel {
|
|
|
5819
5913
|
return undefined;
|
|
5820
5914
|
}
|
|
5821
5915
|
},
|
|
5916
|
+
// 常驻宿主的运行目录:与本进程其它 session runtime 同一套(系统临时目录下、
|
|
5917
|
+
// 已做过 ACL 授予)。宿主程序、包脚本快照、调用临时目录都落在这下面。
|
|
5918
|
+
// 取不到时返回 undefined —— 宿主模式会在启动阶段明确拒绝,不静默降级。
|
|
5919
|
+
getRuntimeRoot: () => {
|
|
5920
|
+
try {
|
|
5921
|
+
return ensureSessionRuntimeDir(`services-host:${aid}`);
|
|
5922
|
+
}
|
|
5923
|
+
catch {
|
|
5924
|
+
return undefined;
|
|
5925
|
+
}
|
|
5926
|
+
},
|
|
5927
|
+
onHostLog: line => logger.debug(`[ServicesHost] aid=${aid} ${line}`),
|
|
5822
5928
|
});
|
|
5823
5929
|
this.serviceRouter.ensureStarted(identity);
|
|
5824
5930
|
return this.serviceRouter;
|
|
@@ -5880,6 +5986,9 @@ export class AUNChannel {
|
|
|
5880
5986
|
logger.debug(`${this.logPrefix()} service request without request_id; using message_id ${input.messageId} type=${rawType} from=${input.fromAid}`);
|
|
5881
5987
|
}
|
|
5882
5988
|
const message = {
|
|
5989
|
+
deadlineAt: Number.isSafeInteger(payload.service_deadline_at_ms)
|
|
5990
|
+
? Math.min(payload.service_deadline_at_ms, input.receivedAt + 300_000)
|
|
5991
|
+
: input.receivedAt + 12_000,
|
|
5883
5992
|
type: rawType,
|
|
5884
5993
|
requestId,
|
|
5885
5994
|
requestIdGenerated,
|
|
@@ -5905,6 +6014,9 @@ export class AUNChannel {
|
|
|
5905
6014
|
delivery: { chatType: 'private', service: { type: reply.type, requestId: reply.requestId } },
|
|
5906
6015
|
metadata: { encrypted, source: 'daemon' },
|
|
5907
6016
|
replyToMessageId,
|
|
6017
|
+
// 应答同样只活一个调用窗口:调用方早已超时退出的情况下,回包被持久补投
|
|
6018
|
+
// 没有任何意义,还会在对端留下一条无人认领的消息。
|
|
6019
|
+
ttl: SERVICE_REPLY_TTL_SECONDS,
|
|
5908
6020
|
});
|
|
5909
6021
|
if (!result.ok) {
|
|
5910
6022
|
logger.warn(`${this.logPrefix()} Service reply send failed: type=${reply.type} code=${result.code ?? 'UNKNOWN'} error=${result.error ?? ''}`);
|
|
@@ -5920,6 +6032,29 @@ export class AUNChannel {
|
|
|
5920
6032
|
setMentionModeResolver(resolver) {
|
|
5921
6033
|
this.mentionModeResolver = resolver;
|
|
5922
6034
|
}
|
|
6035
|
+
/**
|
|
6036
|
+
* 私聊 @ 处理策略。与 `mentionModeResolver` 分开:后者是按群的群聊策略,
|
|
6037
|
+
* 本 resolver 只读 Agent 级 `privateMentionMode`,不接收群/对端参数。
|
|
6038
|
+
*/
|
|
6039
|
+
setPrivateMentionModeResolver(resolver) {
|
|
6040
|
+
this.privateMentionModeResolver = resolver;
|
|
6041
|
+
}
|
|
6042
|
+
/**
|
|
6043
|
+
* 读取生效的私聊 @ 处理策略。缺省、解析失败或未装配 resolver 时一律按
|
|
6044
|
+
* `disabled` 处理:任何不确定都退回「处理所有消息」,绝不静默丢消息。
|
|
6045
|
+
*/
|
|
6046
|
+
async resolvePrivateMentionMode() {
|
|
6047
|
+
if (!this.privateMentionModeResolver)
|
|
6048
|
+
return 'disabled';
|
|
6049
|
+
try {
|
|
6050
|
+
const mode = await this.privateMentionModeResolver();
|
|
6051
|
+
return mode === 'mention-only' ? 'mention-only' : 'disabled';
|
|
6052
|
+
}
|
|
6053
|
+
catch (error) {
|
|
6054
|
+
logger.warn(`${this.logPrefix()} privateMentionMode unavailable, treating as disabled: ${error instanceof Error ? error.message : String(error)}`);
|
|
6055
|
+
return 'disabled';
|
|
6056
|
+
}
|
|
6057
|
+
}
|
|
5923
6058
|
setGroupSlashRequireMentionsResolver(resolver) {
|
|
5924
6059
|
this.groupSlashRequireMentionsResolver = resolver;
|
|
5925
6060
|
}
|
|
@@ -6211,6 +6346,8 @@ export class AUNChannel {
|
|
|
6211
6346
|
}
|
|
6212
6347
|
const messageIds = [...(this.interactionCardMessageIds.get(interactionId) ?? [])];
|
|
6213
6348
|
for (const messageId of messageIds) {
|
|
6349
|
+
if (this.cardMessageIdMap.get(messageId)?.widget)
|
|
6350
|
+
cancelWidgetCard(this.config.aid, messageId);
|
|
6214
6351
|
this.forgetInteractionCard(messageId, interactionId);
|
|
6215
6352
|
}
|
|
6216
6353
|
}
|
|
@@ -6311,7 +6448,20 @@ export class AUNChannel {
|
|
|
6311
6448
|
delivery: delivery ?? action.delivery,
|
|
6312
6449
|
replyContext: callbackContext,
|
|
6313
6450
|
sensitive: action.sensitive,
|
|
6451
|
+
widget: action.widget,
|
|
6314
6452
|
});
|
|
6453
|
+
if (action.widget && channelId && (delivery ?? action.delivery)) {
|
|
6454
|
+
const route = (delivery ?? action.delivery);
|
|
6455
|
+
registerWidgetCard(this.config.aid, {
|
|
6456
|
+
version: 1, messageId, channelId, chatType: route.chatType,
|
|
6457
|
+
initiatorAid: route.chatType === 'private' ? channelId : action.initiatorAid,
|
|
6458
|
+
requestId: action.requestId, title: 'WidgetCard', threadId: replyContext?.threadId,
|
|
6459
|
+
expiresAt: action.expiresAt,
|
|
6460
|
+
encrypted: action.sensitive === true || (typeof replyContext?.metadata?.encrypted === 'boolean'
|
|
6461
|
+
? replyContext.metadata.encrypted : this.shouldEncrypt(channelId)),
|
|
6462
|
+
sensitive: action.sensitive, status: 'pending',
|
|
6463
|
+
});
|
|
6464
|
+
}
|
|
6315
6465
|
this.ownedCardMsgIds.add(messageId);
|
|
6316
6466
|
if (typeof replyContext?.threadId === 'string') {
|
|
6317
6467
|
this.ownedCardTopics.set(messageId, { channelId, threadId: replyContext.threadId });
|
|
@@ -6343,12 +6493,32 @@ export class AUNChannel {
|
|
|
6343
6493
|
ownedTimer.unref?.();
|
|
6344
6494
|
const invalidationReason = this.invalidatedInteractions.get(action.requestId);
|
|
6345
6495
|
if (invalidationReason) {
|
|
6496
|
+
if (action.widget)
|
|
6497
|
+
cancelWidgetCard(this.config.aid, messageId);
|
|
6346
6498
|
this.forgetInteractionCard(messageId, action.requestId);
|
|
6347
6499
|
}
|
|
6348
6500
|
}
|
|
6349
6501
|
runPostSend(entry, messageId) {
|
|
6502
|
+
if (entry.dedupeKey?.startsWith('template-update:') && entry.payload?.template_update?.noticeId) {
|
|
6503
|
+
recordTemplateNoticeReceipt(resolvePaths().root, entry.payload.template_update.noticeId, entry.channelId, messageId, entry.id);
|
|
6504
|
+
}
|
|
6350
6505
|
if (!entry.postSend)
|
|
6351
6506
|
return;
|
|
6507
|
+
if (entry.postSend.type === 'register_widget_card') {
|
|
6508
|
+
if (!entry.delivery)
|
|
6509
|
+
throw new Error('WidgetCard delivery route is unavailable');
|
|
6510
|
+
registerWidgetCard(this.config.aid, {
|
|
6511
|
+
version: 1, messageId, channelId: entry.channelId, chatType: entry.delivery.chatType,
|
|
6512
|
+
initiatorAid: entry.postSend.initiatorAid, title: entry.postSend.title,
|
|
6513
|
+
threadId: typeof entry.payload?.thread_id === 'string' ? entry.payload.thread_id : undefined,
|
|
6514
|
+
expiresAt: entry.postSend.expiresAt, encrypted: entry.postSend.encrypted, status: 'pending',
|
|
6515
|
+
});
|
|
6516
|
+
return;
|
|
6517
|
+
}
|
|
6518
|
+
if (entry.postSend.type === 'register_payment_delivery') {
|
|
6519
|
+
paymentStore(this.config.aid).markDelivered(entry.postSend.requestId, entry.postSend.deliveryId, messageId);
|
|
6520
|
+
return;
|
|
6521
|
+
}
|
|
6352
6522
|
if (entry.postSend.type === 'register_contact_approval_card') {
|
|
6353
6523
|
registerContactApprovalCard(this.config.aid, entry.postSend.pendingKey, entry.postSend.eventId, messageId);
|
|
6354
6524
|
return;
|
|
@@ -6411,6 +6581,7 @@ export class AUNChannel {
|
|
|
6411
6581
|
const friendPayload = (typeof payload.type === 'string' && payload.type.startsWith('friend.')) || isContactApprovalCard(payload);
|
|
6412
6582
|
const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
|
|
6413
6583
|
if ((payload.type === 'activity' && truncatedPayload.type !== 'activity')
|
|
6584
|
+
|| (payload.type === 'widget_card' && truncatedPayload.type !== 'widget_card')
|
|
6414
6585
|
|| (isAgentFinalPayload(payload) && !isAgentFinalPayload(truncatedPayload))) {
|
|
6415
6586
|
return {
|
|
6416
6587
|
ok: false, status: 'permanent', code: 'PAYLOAD_TOO_LARGE',
|
|
@@ -6557,8 +6728,33 @@ export class AUNChannel {
|
|
|
6557
6728
|
// intentionally removes undefined array elements, which would otherwise
|
|
6558
6729
|
// turn malformed `mentions: [undefined]` into an apparently valid `[]`.
|
|
6559
6730
|
const finalPayload = this.normalizeAunPayloadMentions(this.applyReplyContextToPayload(validatedPayload, context));
|
|
6731
|
+
if (finalPayload.type === 'widget_card') {
|
|
6732
|
+
if (finalPayload.thread_id !== undefined && !isTopicThreadId(finalPayload.thread_id)) {
|
|
6733
|
+
throw Object.assign(new Error('WidgetCard thread_id must be an existing topic ID'), { code: 'INVALID_WIDGET_CARD' });
|
|
6734
|
+
}
|
|
6735
|
+
const attachments = finalPayload.attachments;
|
|
6736
|
+
const html = Array.isArray(attachments) && attachments.length === 1 ? attachments[0] : undefined;
|
|
6737
|
+
if (!html || typeof html !== 'object' || typeof html.owner_aid !== 'string' || !html.owner_aid
|
|
6738
|
+
|| typeof html.object_key !== 'string' || !html.object_key || html.object_key.includes(':')
|
|
6739
|
+
|| html.object_key.startsWith('/') || html.object_key.split('/').includes('..')
|
|
6740
|
+
|| typeof html.filename !== 'string' || !/\.html?$/i.test(html.filename)
|
|
6741
|
+
|| typeof html.content_type !== 'string' || !/^text\/html(?:\s*;|$)/i.test(html.content_type)) {
|
|
6742
|
+
throw Object.assign(new Error('WidgetCard requires one uploaded HTML attachment with owner_aid and object_key'), { code: 'INVALID_WIDGET_CARD' });
|
|
6743
|
+
}
|
|
6744
|
+
const initiatorAid = delivery.chatType === 'private' ? channelId : finalPayload.initiator;
|
|
6745
|
+
if (typeof initiatorAid !== 'string' || !initiatorAid.trim()) {
|
|
6746
|
+
throw Object.assign(new Error('Group WidgetCard requires an initiator'), { code: 'INVALID_WIDGET_INITIATOR' });
|
|
6747
|
+
}
|
|
6748
|
+
if (opts.postSend?.type !== 'register_interaction_card')
|
|
6749
|
+
opts = { ...opts, postSend: {
|
|
6750
|
+
type: 'register_widget_card', initiatorAid,
|
|
6751
|
+
title: typeof finalPayload.title === 'string' ? finalPayload.title : html.filename,
|
|
6752
|
+
expiresAt: Date.now() + AUN_INTERACTION_CARD_TTL_MS,
|
|
6753
|
+
encrypted: typeof context.metadata?.encrypted === 'boolean' ? context.metadata.encrypted : this.shouldEncrypt(channelId),
|
|
6754
|
+
} };
|
|
6755
|
+
}
|
|
6560
6756
|
const logText = opts.logText ?? this.payloadLogText(finalPayload, opts.contentKind);
|
|
6561
|
-
const expiresAt = opts.postSend?.type === 'register_interaction_card'
|
|
6757
|
+
const expiresAt = opts.postSend?.type === 'register_interaction_card' || opts.postSend?.type === 'register_widget_card'
|
|
6562
6758
|
? opts.postSend.expiresAt
|
|
6563
6759
|
: undefined;
|
|
6564
6760
|
if (typeof expiresAt === 'number' && Number.isFinite(expiresAt) && expiresAt <= Date.now()) {
|
|
@@ -6959,6 +7155,23 @@ export class AUNChannel {
|
|
|
6959
7155
|
return { ok: true, status: 'queued', encrypt: true, outbox_id: sent.outboxId, error: sent.error, code: sent.code };
|
|
6960
7156
|
return { ok: false, status: 'failed', encrypt: true, outbox_id: sent.outboxId, error: sent.error ?? 'friend invite control send failed', code: sent.code };
|
|
6961
7157
|
}
|
|
7158
|
+
if (finalPayload.type === 'widget_card') {
|
|
7159
|
+
if (args.ttl !== undefined || args.deviceId || args.service) {
|
|
7160
|
+
return { ok: false, code: 'INVALID_WIDGET_TARGET', error: 'WidgetCard requires persistent conversation delivery' };
|
|
7161
|
+
}
|
|
7162
|
+
const encrypt = args.encrypt ?? this.shouldEncrypt(args.to);
|
|
7163
|
+
const sent = await this.sendContentPayload(args.to, finalPayload, {
|
|
7164
|
+
contentKind: 'card', context: { delivery: { chatType: 'private' },
|
|
7165
|
+
sessionId: args.log?.sessionId,
|
|
7166
|
+
...(typeof finalPayload.thread_id === 'string' ? { threadId: finalPayload.thread_id } : {}),
|
|
7167
|
+
metadata: { encrypted: encrypt } },
|
|
7168
|
+
});
|
|
7169
|
+
if (sent.messageId)
|
|
7170
|
+
return { ok: true, message_id: sent.messageId, status: 'sent', encrypt };
|
|
7171
|
+
if (sent.queued)
|
|
7172
|
+
return { ok: true, status: 'queued', outbox_id: sent.outboxId, encrypt };
|
|
7173
|
+
return { ok: false, code: sent.code ?? 'WIDGET_CARD_SEND_FAILED', error: sent.error ?? 'WidgetCard send failed', encrypt };
|
|
7174
|
+
}
|
|
6962
7175
|
if (!this.connected || !this.client) {
|
|
6963
7176
|
return { ok: false, error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
6964
7177
|
}
|
|
@@ -7057,6 +7270,9 @@ export class AUNChannel {
|
|
|
7057
7270
|
const selfAddressed = args.to.replace(/^@/, '').toLowerCase() === this.config.aid.replace(/^@/, '').toLowerCase();
|
|
7058
7271
|
if (!selfAddressed && args.log?.content !== undefined) {
|
|
7059
7272
|
const classified = classifyAunPayloadForLog(finalPayload);
|
|
7273
|
+
const logContent = args.log.contentAuthoritative
|
|
7274
|
+
? args.log.content
|
|
7275
|
+
: (classified.content || args.log.content);
|
|
7060
7276
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', args.to, this.config.aid);
|
|
7061
7277
|
fs.mkdirSync(chatDir, { recursive: true });
|
|
7062
7278
|
appendMessageLog(chatDir, buildOutboundEntry({
|
|
@@ -7066,7 +7282,7 @@ export class AUNChannel {
|
|
|
7066
7282
|
threadId: args.log.threadId ?? (typeof finalPayload.thread_id === 'string' ? finalPayload.thread_id : null),
|
|
7067
7283
|
chatType: 'private',
|
|
7068
7284
|
msgId: messageId,
|
|
7069
|
-
content:
|
|
7285
|
+
content: logContent,
|
|
7070
7286
|
encrypt,
|
|
7071
7287
|
chatmode,
|
|
7072
7288
|
msgType: classified.msgType ?? args.log.msgType,
|
|
@@ -7076,7 +7292,7 @@ export class AUNChannel {
|
|
|
7076
7292
|
handoff_trace: args.log.handoffTrace,
|
|
7077
7293
|
transport: this.sendReceiptFromResult(result),
|
|
7078
7294
|
}));
|
|
7079
|
-
this.aidStatsCollector?.recordOutbound(this.config.aid, args.to, Buffer.byteLength(
|
|
7295
|
+
this.aidStatsCollector?.recordOutbound(this.config.aid, args.to, Buffer.byteLength(logContent, 'utf-8'), logContent, false, encrypt, chatmode, 'send');
|
|
7080
7296
|
logWritten = true;
|
|
7081
7297
|
}
|
|
7082
7298
|
return {
|
|
@@ -7099,6 +7315,13 @@ export class AUNChannel {
|
|
|
7099
7315
|
};
|
|
7100
7316
|
}
|
|
7101
7317
|
}
|
|
7318
|
+
/** Reuse the channel-owned storage connection and standard attachment format. */
|
|
7319
|
+
async uploadPaymentImage(data, filename) {
|
|
7320
|
+
if (!this.client || !this.connected)
|
|
7321
|
+
throw new Error('AUN channel is not connected for payment image upload');
|
|
7322
|
+
const uploaded = await uploadBufferAndBuildPayload(this.client, this.config.aid, data, filename, { as: 'image' });
|
|
7323
|
+
return uploaded.attachment;
|
|
7324
|
+
}
|
|
7102
7325
|
/**
|
|
7103
7326
|
* Send an online/offline system notice to the bound Owner as an AUN volatile
|
|
7104
7327
|
* message: nothing is persisted in the outbox or the local message log, and
|
|
@@ -7148,9 +7371,22 @@ export class AUNChannel {
|
|
|
7148
7371
|
contentType: file.contentType,
|
|
7149
7372
|
text: file.text,
|
|
7150
7373
|
transcript: file.transcript,
|
|
7374
|
+
title: file.title,
|
|
7151
7375
|
});
|
|
7152
7376
|
return built.payload;
|
|
7153
7377
|
}
|
|
7378
|
+
/**
|
|
7379
|
+
* 归档 daemon 侧代发的文件(`ec msg send --file` 走这条路径,不经 outbox)。
|
|
7380
|
+
* 与 outbox 投递同一落点与命名规则;归档失败只记日志、返回 null,不阻断发送。
|
|
7381
|
+
* 返回值是写进本地历史的正文:`[文件: 名 → $AGENT_DIR/attachments/…]`。
|
|
7382
|
+
*/
|
|
7383
|
+
archiveDaemonFile(channelId, filePath, as) {
|
|
7384
|
+
const archived = this.archiveOutgoingAttachment(channelId, filePath);
|
|
7385
|
+
if (!archived)
|
|
7386
|
+
return null;
|
|
7387
|
+
const label = as === 'image' ? '图片' : as === 'video' ? '视频' : as === 'voice' ? '语音' : '文件';
|
|
7388
|
+
return `[${label}: ${path.basename(filePath)} → ${toAttachmentMarkedPath(this.config.aid, archived.filePath)}]`;
|
|
7389
|
+
}
|
|
7154
7390
|
/** Daemon-side transport for `ec group send` running inside an agent task. */
|
|
7155
7391
|
async sendDaemonGroupMsg(args) {
|
|
7156
7392
|
if (!args.groupId) {
|
|
@@ -7179,6 +7415,20 @@ export class AUNChannel {
|
|
|
7179
7415
|
else if (payloadMentions !== undefined) {
|
|
7180
7416
|
finalPayload.mentions = payloadMentions;
|
|
7181
7417
|
}
|
|
7418
|
+
if (finalPayload.type === 'widget_card') {
|
|
7419
|
+
const encrypt = args.encrypt ?? this.shouldEncrypt(args.groupId);
|
|
7420
|
+
const sent = await this.sendContentPayload(args.groupId, finalPayload, {
|
|
7421
|
+
contentKind: 'card', context: { delivery: { chatType: 'group', groupId: args.groupId },
|
|
7422
|
+
sessionId: args.log?.sessionId,
|
|
7423
|
+
...(typeof finalPayload.thread_id === 'string' ? { threadId: finalPayload.thread_id } : {}),
|
|
7424
|
+
metadata: { encrypted: encrypt } },
|
|
7425
|
+
});
|
|
7426
|
+
if (sent.messageId)
|
|
7427
|
+
return { ok: true, message_id: sent.messageId, status: 'sent', group_id: args.groupId, encrypt };
|
|
7428
|
+
if (sent.queued)
|
|
7429
|
+
return { ok: true, status: 'queued', outbox_id: sent.outboxId, group_id: args.groupId, encrypt };
|
|
7430
|
+
return { ok: false, code: sent.code ?? 'WIDGET_CARD_SEND_FAILED', error: sent.error ?? 'WidgetCard send failed' };
|
|
7431
|
+
}
|
|
7182
7432
|
if (!this.connected || !this.client) {
|
|
7183
7433
|
return { ok: false, error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
7184
7434
|
}
|
|
@@ -7205,7 +7455,9 @@ export class AUNChannel {
|
|
|
7205
7455
|
let logWritten = false;
|
|
7206
7456
|
if (args.log?.content !== undefined) {
|
|
7207
7457
|
const classified = classifyAunPayloadForLog(finalPayload);
|
|
7208
|
-
const content =
|
|
7458
|
+
const content = args.log.contentAuthoritative
|
|
7459
|
+
? args.log.content
|
|
7460
|
+
: (classified.content || args.log.content);
|
|
7209
7461
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', args.groupId, this.config.aid);
|
|
7210
7462
|
fs.mkdirSync(chatDir, { recursive: true });
|
|
7211
7463
|
appendMessageLog(chatDir, buildOutboundEntry({
|
|
@@ -7307,7 +7559,7 @@ export class AUNChannel {
|
|
|
7307
7559
|
echoText += `\n${echoTraceLine({
|
|
7308
7560
|
node: 'EvolCore.reply',
|
|
7309
7561
|
dir: 'ret',
|
|
7310
|
-
hop: Math.max(0, hop - 1
|
|
7562
|
+
hop: Math.max(0, hop) - 1,
|
|
7311
7563
|
ver,
|
|
7312
7564
|
now: doneTs,
|
|
7313
7565
|
extra: `conn_uptime=${this.connectedAt ? Math.round((doneTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -7392,7 +7644,7 @@ export class AUNChannel {
|
|
|
7392
7644
|
echoText += `\n${echoTraceLine({
|
|
7393
7645
|
node: 'EvolCore.reply',
|
|
7394
7646
|
dir: 'ret',
|
|
7395
|
-
hop: echoTraceNextHop(echoText),
|
|
7647
|
+
hop: echoTraceNextHop(echoText, 'ret'),
|
|
7396
7648
|
ver,
|
|
7397
7649
|
now: replyTs,
|
|
7398
7650
|
extra: `conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -7474,9 +7726,7 @@ export class AUNChannel {
|
|
|
7474
7726
|
const source = context?.metadata?.source ?? 'daemon';
|
|
7475
7727
|
// ext assembly (isFinal, seqInTurn, turnMessageCount, loop, fullaccess) is handled
|
|
7476
7728
|
// centrally by withSessionState → buildWireExt; nothing to pre-merge here.
|
|
7477
|
-
const payload = await this.withSessionState(channelId, withAunAttention(
|
|
7478
|
-
type: 'text', text: finalText,
|
|
7479
|
-
}, context?.attention), context);
|
|
7729
|
+
const payload = await this.withSessionState(channelId, withAunAttention(echoTextPayload(finalText), context?.attention), context);
|
|
7480
7730
|
// sentAt 在每次投递尝试时盖戳(outbox 重发取重发时刻)。服务端会用自己的时间覆盖
|
|
7481
7731
|
// 顶层 timestamp,两者有毫秒级差异,sentAt 只代表本端时钟。
|
|
7482
7732
|
if (context?.debug)
|
|
@@ -7717,6 +7967,37 @@ export class AUNChannel {
|
|
|
7717
7967
|
}
|
|
7718
7968
|
}
|
|
7719
7969
|
async deliverPayloadEntry(entry) {
|
|
7970
|
+
if (!entry.deliveryReceipt && entry.dedupeKey?.startsWith('template-update:')) {
|
|
7971
|
+
const notice = entry.payload?.template_update;
|
|
7972
|
+
if (!notice || entry.dedupeKey !== 'template-update:' + notice.noticeId
|
|
7973
|
+
|| typeof notice.targetAid !== 'string' || !/^[a-z0-9][a-z0-9_-]*(\.[a-z0-9-]+)+$/.test(notice.targetAid)) {
|
|
7974
|
+
return { ok: false, status: 'permanent', code: 'UPDATE_NOTICE_INVALID', error: 'Invalid durable template notice' };
|
|
7975
|
+
}
|
|
7976
|
+
const owner = await ownerResolver.refreshForAuthorization(notice.targetAid);
|
|
7977
|
+
if (owner.refreshFailure || owner.consensusStatus !== 'consensus') {
|
|
7978
|
+
return { ok: false, status: 'retry', code: 'UPDATE_OWNERSHIP_UNAVAILABLE', error: 'Current Agent Owner is unavailable' };
|
|
7979
|
+
}
|
|
7980
|
+
const { TemplateJobs, templateFingerprint, compareTemplateVersions } = await import('../agent-template/jobs.js');
|
|
7981
|
+
const installed = new TemplateJobs(resolvePaths().root).installation(notice.targetAid);
|
|
7982
|
+
const config = loadAgent(notice.targetAid);
|
|
7983
|
+
if (owner.ownerAid !== entry.channelId || config?.update?.mode === 'disabled' || !installed
|
|
7984
|
+
|| installed.ownerAid !== entry.channelId || installed.hostAid !== this.config.aid
|
|
7985
|
+
|| templateFingerprint(installed.source) !== notice.sourceDigest
|
|
7986
|
+
|| installed.release && compareTemplateVersions(installed.release.version, notice.candidateVersion) >= 0) {
|
|
7987
|
+
return { ok: false, status: 'permanent', code: 'UPDATE_NOTICE_STALE', error: 'Owner, source, policy or installed version changed' };
|
|
7988
|
+
}
|
|
7989
|
+
entry.context = { ...entry.context, metadata: { ...entry.context?.metadata, encrypted: true } };
|
|
7990
|
+
}
|
|
7991
|
+
if (!entry.deliveryReceipt && entry.postSend?.type === 'register_payment_delivery') {
|
|
7992
|
+
const record = paymentStore(this.config.aid).read(entry.postSend.requestId);
|
|
7993
|
+
const binding = currentContactBinding(this.config.aid);
|
|
7994
|
+
if (!binding)
|
|
7995
|
+
return { ok: false, status: 'retry', code: 'PAYMENT_OWNERSHIP_UNAVAILABLE', error: 'Payment Owner is not currently verified' };
|
|
7996
|
+
if (!record || !sameContactBinding(record.binding, binding) || entry.channelId !== binding.owner_aid
|
|
7997
|
+
|| entry.delivery?.chatType !== 'private' || entry.payload?.thread_id !== record.threadId) {
|
|
7998
|
+
return { ok: false, status: 'permanent', code: 'PAYMENT_OWNERSHIP_CHANGED', error: 'Payment no longer belongs to this Owner conversation' };
|
|
7999
|
+
}
|
|
8000
|
+
}
|
|
7720
8001
|
if (entry.payload?.type === 'friend.request.v1' && entry.payload.direction === 'outbound') {
|
|
7721
8002
|
return { ok: false, status: 'permanent', code: 'OUTBOUND_APPROVAL_RETIRED', error: 'outbound contact approval is no longer required' };
|
|
7722
8003
|
}
|
|
@@ -7761,7 +8042,7 @@ export class AUNChannel {
|
|
|
7761
8042
|
return { ok: true, status: 'sent' };
|
|
7762
8043
|
}
|
|
7763
8044
|
}
|
|
7764
|
-
const interactionExpiresAt = entry.postSend?.type === 'register_interaction_card'
|
|
8045
|
+
const interactionExpiresAt = entry.postSend?.type === 'register_interaction_card' || entry.postSend?.type === 'register_widget_card'
|
|
7765
8046
|
? entry.postSend.expiresAt
|
|
7766
8047
|
: undefined;
|
|
7767
8048
|
if (typeof interactionExpiresAt === 'number'
|
|
@@ -8035,7 +8316,13 @@ export class AUNChannel {
|
|
|
8035
8316
|
const isOutputServicePayload = delivery.chatType === 'private' && !!delivery.service
|
|
8036
8317
|
&& isProjectionServiceResult(finalPayload.type);
|
|
8037
8318
|
finalPayload = await this.withSessionState(channelId, finalPayload, context);
|
|
8038
|
-
|
|
8319
|
+
// volatile TTL 由调用方按自己的等待期给出;服务应答据此避免在调用方放弃后
|
|
8320
|
+
// 仍被当成持久消息补投一次。
|
|
8321
|
+
const ttl = typeof context?.ttl === 'number' && Number.isInteger(context.ttl)
|
|
8322
|
+
&& context.ttl >= 1 && context.ttl <= MAX_AUN_VOLATILE_TTL_SECONDS
|
|
8323
|
+
? context.ttl
|
|
8324
|
+
: undefined;
|
|
8325
|
+
const params = { payload: finalPayload, encrypt, ...(ttl !== undefined ? { ttl } : {}) };
|
|
8039
8326
|
if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
|
|
8040
8327
|
params.to_device_id = context?.toDeviceId;
|
|
8041
8328
|
if (isMenuPayload && typeof context?.metadata?.menuClientSdkVersion === 'string') {
|
|
@@ -8223,7 +8510,7 @@ export class AUNChannel {
|
|
|
8223
8510
|
else if (result.status === 'permanent')
|
|
8224
8511
|
this.markPermanentOutboxFailure(entry, result);
|
|
8225
8512
|
}
|
|
8226
|
-
async buildUploadedImagePayload(data, mimeType, alt) {
|
|
8513
|
+
async buildUploadedImagePayload(data, mimeType, alt, channelId) {
|
|
8227
8514
|
if (!this.connected || !this.client) {
|
|
8228
8515
|
throw new Error('AUN channel is not connected; image cannot be uploaded');
|
|
8229
8516
|
}
|
|
@@ -8249,9 +8536,23 @@ export class AUNChannel {
|
|
|
8249
8536
|
const digest = crypto.createHash('sha256').update(data).digest('hex').slice(0, 12);
|
|
8250
8537
|
const filename = `image-${digest}.${extension}`;
|
|
8251
8538
|
const built = await uploadBufferAndBuildPayload(this.client, this.config.aid, data, filename, { as: 'image', contentType });
|
|
8539
|
+
// 出站图片同样归档到关系目录(与入站图片、收发文件同一落点)。
|
|
8540
|
+
const archived = channelId
|
|
8541
|
+
? this.archiveOutgoingBuffer(channelId, data, filename, contentType)
|
|
8542
|
+
: null;
|
|
8252
8543
|
const imagePayload = { ...built.payload };
|
|
8253
8544
|
setIfDefined(imagePayload, 'alt', alt);
|
|
8254
|
-
return imagePayload;
|
|
8545
|
+
return { payload: imagePayload, archived };
|
|
8546
|
+
}
|
|
8547
|
+
/** 内存中的出站附件归档(图片走这条:数据不落临时文件)。 */
|
|
8548
|
+
archiveOutgoingBuffer(channelId, data, filename, contentType) {
|
|
8549
|
+
try {
|
|
8550
|
+
return saveRelationAttachment(data, this.config.aid, formatPeerKey('aun', channelId), contentType || 'application/octet-stream', { filename, allowAnyExtension: true, direction: 'out' });
|
|
8551
|
+
}
|
|
8552
|
+
catch (error) {
|
|
8553
|
+
logger.warn(`${this.logPrefix()} Outgoing image archive failed for ${filename}: ${error instanceof Error ? error.message : String(error)}`);
|
|
8554
|
+
return null;
|
|
8555
|
+
}
|
|
8255
8556
|
}
|
|
8256
8557
|
async deliverImageEntry(entry) {
|
|
8257
8558
|
const image = entry.image;
|
|
@@ -8268,11 +8569,14 @@ export class AUNChannel {
|
|
|
8268
8569
|
return { status: 'permanent', error: 'durable image data is invalid', code: 'INVALID_IMAGE_DATA' };
|
|
8269
8570
|
}
|
|
8270
8571
|
try {
|
|
8271
|
-
const imagePayload = await this.buildUploadedImagePayload(data, image.mimeType, image.alt);
|
|
8572
|
+
const { payload: imagePayload, archived } = await this.buildUploadedImagePayload(data, image.mimeType, image.alt, entry.channelId);
|
|
8272
8573
|
entry.type = 'payload';
|
|
8273
8574
|
entry.contentKind = 'image';
|
|
8274
8575
|
entry.payload = this.applyReplyContextToPayload(imagePayload, entry.context);
|
|
8275
|
-
|
|
8576
|
+
// 图片与文件同一规则:历史里记关系目录里的归档路径。
|
|
8577
|
+
entry.logText ??= archived
|
|
8578
|
+
? `[图片: ${image.alt || path.basename(archived.filePath)} → ${toAttachmentMarkedPath(this.config.aid, archived.filePath)}]`
|
|
8579
|
+
: (image.alt ? `[image] ${image.alt}` : '[image]');
|
|
8276
8580
|
delete entry.image;
|
|
8277
8581
|
// Persist the attachment reference before message.send. A failed send then
|
|
8278
8582
|
// retries the compact wire payload without re-uploading the same image.
|
|
@@ -8299,6 +8603,23 @@ export class AUNChannel {
|
|
|
8299
8603
|
return failure;
|
|
8300
8604
|
}
|
|
8301
8605
|
}
|
|
8606
|
+
/**
|
|
8607
|
+
* 出站附件归档:把要发送的文件在关系目录留一份。
|
|
8608
|
+
*
|
|
8609
|
+
* 与入站同一落点(`$RELATIONS_DIR/<peerKey>/attachments/`)、同一命名规则
|
|
8610
|
+
* (原始文件名,重名 `-N`,内容相同则复用)。归档失败只记日志、不阻断发送:
|
|
8611
|
+
* 发送本身是主路径,历史可读性是附带收益。
|
|
8612
|
+
*/
|
|
8613
|
+
archiveOutgoingAttachment(channelId, absPath, contentType) {
|
|
8614
|
+
try {
|
|
8615
|
+
const buffer = fs.readFileSync(absPath);
|
|
8616
|
+
return saveRelationAttachment(buffer, this.config.aid, formatPeerKey('aun', channelId), contentType || 'application/octet-stream', { filename: path.basename(absPath), allowAnyExtension: true, direction: 'out' });
|
|
8617
|
+
}
|
|
8618
|
+
catch (error) {
|
|
8619
|
+
logger.warn(`${this.logPrefix()} Outgoing attachment archive failed for ${absPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
8620
|
+
return null;
|
|
8621
|
+
}
|
|
8622
|
+
}
|
|
8302
8623
|
async deliverFileEntry(entry) {
|
|
8303
8624
|
const channelId = entry.channelId;
|
|
8304
8625
|
if (typeof entry.filePath !== 'string' || !entry.filePath.trim()) {
|
|
@@ -8310,9 +8631,14 @@ export class AUNChannel {
|
|
|
8310
8631
|
const context = this.withDelivery(entry.context, delivery);
|
|
8311
8632
|
const isGroup = delivery.chatType === 'group';
|
|
8312
8633
|
const source = context?.metadata?.source ?? 'daemon';
|
|
8634
|
+
// 归档在两条分支之前做:回执恢复分支也要能引用归档路径。
|
|
8635
|
+
// 该调用是幂等的(同内容复用同一文件,只追加一条元数据),重复执行安全。
|
|
8636
|
+
const fileArchived = this.archiveOutgoingAttachment(channelId, absPath);
|
|
8313
8637
|
if (entry.deliveryReceipt) {
|
|
8314
8638
|
const filename = path.basename(absPath);
|
|
8315
|
-
const logText = entry.logText ??
|
|
8639
|
+
const logText = entry.logText ?? (fileArchived
|
|
8640
|
+
? `[文件: ${filename} → ${toAttachmentMarkedPath(this.config.aid, fileArchived.filePath)}]`
|
|
8641
|
+
: `[file] ${filename}`);
|
|
8316
8642
|
try {
|
|
8317
8643
|
this.appendOutboundJsonl(channelId, {
|
|
8318
8644
|
...classifyAunPayloadForLog({ type: 'file', text: logText }),
|
|
@@ -8338,6 +8664,8 @@ export class AUNChannel {
|
|
|
8338
8664
|
try {
|
|
8339
8665
|
const { attachment } = await uploadFileAndBuildPayload(this.client, this.config.aid, absPath, { as: 'file' });
|
|
8340
8666
|
const { filename, size_bytes: size, content_type: contentType } = attachment;
|
|
8667
|
+
// 归档已在分支之前完成(fileArchived);归档失败不阻断发送,历史里落源路径。
|
|
8668
|
+
const archived = fileArchived;
|
|
8341
8669
|
const filePayload = await this.withSessionState(channelId, buildAunFilePayload({
|
|
8342
8670
|
filename,
|
|
8343
8671
|
size,
|
|
@@ -8440,7 +8768,12 @@ export class AUNChannel {
|
|
|
8440
8768
|
const statsContext = isGroup ? await this.groupStatsContext(channelId) : undefined;
|
|
8441
8769
|
this.aidStatsCollector?.recordOutbound(this.config.aid, channelId, Buffer.byteLength(fileText, 'utf-8'), fileText, false, !!params.encrypt, context?.metadata?.chatmode, 'send', statsContext);
|
|
8442
8770
|
this.appendOutboundJsonl(channelId, {
|
|
8443
|
-
...classifyAunPayloadForLog(filePayload),
|
|
8771
|
+
...classifyAunPayloadForLog(filePayload),
|
|
8772
|
+
// 有归档副本就记归档路径;没有则在正文里补源路径,避免历史只剩文件名。
|
|
8773
|
+
...(archived
|
|
8774
|
+
? { content: `[文件: ${filename} → ${toAttachmentMarkedPath(this.config.aid, archived.filePath)}]` }
|
|
8775
|
+
: { content: `[文件: ${filename} → ${absPath}]` }),
|
|
8776
|
+
msgId: sentMid, encrypt: !!params.encrypt,
|
|
8444
8777
|
context, isGroup, source, transport: this.sendReceiptFromResult(sendResult),
|
|
8445
8778
|
});
|
|
8446
8779
|
if (sendResult)
|
|
@@ -9352,21 +9685,25 @@ export class AUNChannelPlugin {
|
|
|
9352
9685
|
if (req.kind.kind === 'action') {
|
|
9353
9686
|
const isAsyncQuestion = /^aq-[a-f0-9]{40}$/.test(req.id);
|
|
9354
9687
|
const action = req.kind;
|
|
9355
|
-
const aunCard =
|
|
9356
|
-
|
|
9357
|
-
|
|
9358
|
-
|
|
9359
|
-
|
|
9360
|
-
|
|
9361
|
-
|
|
9362
|
-
|
|
9363
|
-
|
|
9364
|
-
|
|
9365
|
-
|
|
9688
|
+
const aunCard = action.widget
|
|
9689
|
+
? withAunAttention(await channel.buildDaemonFilePayload({
|
|
9690
|
+
filePath: action.widget.filePath, as: 'widget_card', title: action.title, text: action.body,
|
|
9691
|
+
}))
|
|
9692
|
+
: withAunAttention({
|
|
9693
|
+
type: 'action_card',
|
|
9694
|
+
title: action.title,
|
|
9695
|
+
...(req.sensitive ? { sensitive: true } : {}),
|
|
9696
|
+
...(req.blocking === true ? { blocking: true } : {}),
|
|
9697
|
+
...(action.recommendedOption ? { recommended_option: action.recommendedOption } : {}),
|
|
9698
|
+
actions: action.buttons.map(btn => ({
|
|
9699
|
+
label: action.recommendedOption === btn.key ? `💡 ${btn.label}` : btn.label,
|
|
9700
|
+
value: btn.key, style: btn.style ?? 'default', behavior: 'reply',
|
|
9701
|
+
})),
|
|
9702
|
+
});
|
|
9366
9703
|
// AUN action_card 以 compose behavior 声明自由文本动作。新版客户端
|
|
9367
9704
|
// 在卡片内采集并确认;旧版客户端可继续从主编辑器采集。两者都结构化
|
|
9368
9705
|
// 回传 action_card_reply{behavior:"compose"},Core 不拦截普通消息队列。
|
|
9369
|
-
if (action.allowCustomInput) {
|
|
9706
|
+
if (!action.widget && action.allowCustomInput) {
|
|
9370
9707
|
aunCard.actions.push({
|
|
9371
9708
|
label: '✏️ 手动输入', style: 'default', behavior: 'compose',
|
|
9372
9709
|
...(req.sensitive ? { sensitive: true } : {}),
|
|
@@ -9377,6 +9714,10 @@ export class AUNChannelPlugin {
|
|
|
9377
9714
|
aunCard.text = action.body;
|
|
9378
9715
|
setIfDefined(aunCard, 'format', action.bodyFormat);
|
|
9379
9716
|
}
|
|
9717
|
+
if (action.widget && req.blocking === true)
|
|
9718
|
+
aunCard.blocking = true;
|
|
9719
|
+
if (action.widget && req.sensitive)
|
|
9720
|
+
aunCard.sensitive = true;
|
|
9380
9721
|
if (req.initiatorId && replyCtx?.delivery?.chatType === 'group')
|
|
9381
9722
|
aunCard.initiator = req.initiatorId;
|
|
9382
9723
|
if (isTopicThreadId(replyCtx?.threadId))
|
|
@@ -9401,6 +9742,7 @@ export class AUNChannelPlugin {
|
|
|
9401
9742
|
initiatorAid: req.initiatorId,
|
|
9402
9743
|
delivery: replyCtx?.delivery,
|
|
9403
9744
|
expiresAt: cardExpiresAt,
|
|
9745
|
+
...(action.widget ? { widget: true } : {}),
|
|
9404
9746
|
},
|
|
9405
9747
|
});
|
|
9406
9748
|
return toInteractionReceipt(result);
|
|
@@ -9578,6 +9920,12 @@ export class AUNChannelPlugin {
|
|
|
9578
9920
|
}, { cache: true }).mentionMode;
|
|
9579
9921
|
});
|
|
9580
9922
|
}
|
|
9923
|
+
if (typeof channel.setPrivateMentionModeResolver === 'function') {
|
|
9924
|
+
// Agent-level only: no peerKey, so a relation-level override cannot leak in.
|
|
9925
|
+
channel.setPrivateMentionModeResolver(async () => {
|
|
9926
|
+
return resolveEffective({ self: aid }, { cache: true }).privateMentionMode;
|
|
9927
|
+
});
|
|
9928
|
+
}
|
|
9581
9929
|
if (typeof channel.setGroupSlashRequireMentionsResolver === 'function') {
|
|
9582
9930
|
channel.setGroupSlashRequireMentionsResolver(async () => {
|
|
9583
9931
|
return resolveEffective({ self: aid }, { cache: true }).groupSlashRequireMentions ?? true;
|