evolcore 0.0.49 → 0.0.51
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 +103 -3
- package/bin/ec-build.mjs +60 -0
- package/bin/ecmsg.js +64 -57
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +173 -0
- package/dist/ability/caller/contract.js +117 -0
- package/dist/ability/caller/credential-files.js +132 -0
- package/dist/ability/caller/daemon.js +183 -0
- package/dist/ability/caller/schema-view.js +157 -0
- package/dist/ability/caller/service.js +519 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +156 -106
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +79 -3
- package/dist/agent-template/runtime.js +459 -47
- package/dist/agent-template/service.js +1242 -198
- package/dist/agent-template/share.js +103 -0
- package/dist/agent-template/tool-runner.js +25 -0
- package/dist/agent-template/types.js +10 -2
- package/dist/agents/claude/availability.js +94 -0
- package/dist/agents/claude/capability-provider.js +154 -0
- package/dist/agents/claude/index.js +145 -0
- package/dist/agents/{claude-runner.js → claude/runner.js} +78 -166
- package/dist/agents/claude/session-file-adapter.js +246 -0
- package/dist/agents/codex/app-server-client.js +90 -10
- package/dist/agents/codex/availability.js +164 -0
- package/dist/agents/codex/capability-provider.js +138 -0
- package/dist/agents/codex/cli.js +38 -0
- package/dist/agents/codex/index.js +345 -0
- package/dist/agents/codex/mcp-elicitation.js +135 -0
- package/dist/agents/{codex-runner.js → codex/runner.js} +652 -383
- package/dist/agents/codex/session-file-adapter.js +834 -0
- package/dist/agents/dsh/availability.js +28 -0
- package/dist/agents/dsh/capability-provider.js +56 -0
- package/dist/agents/dsh/desktop-locations.ps1 +66 -0
- package/dist/agents/dsh/desktop-probe.cjs +37 -0
- package/dist/agents/dsh/index.js +98 -0
- package/dist/agents/dsh/installation.js +400 -0
- package/dist/agents/dsh/resources.js +755 -0
- package/dist/agents/dsh/runner.js +1183 -0
- package/dist/agents/dsh/runtime/README.md +243 -0
- package/dist/agents/dsh/runtime/authorization.js +23 -0
- package/dist/agents/dsh/runtime/bridge.js +837 -0
- package/dist/agents/dsh/runtime/config.js +271 -0
- package/dist/agents/dsh/runtime/entry.js +229 -0
- package/dist/agents/dsh/runtime/session-inspector.js +340 -0
- package/dist/agents/dsh/runtime/tool-policy.js +49 -0
- package/dist/agents/dsh/session-file-adapter.js +145 -0
- package/dist/agents/ecagent/index.js +215 -0
- package/dist/agents/{ecagent-runner.js → ecagent/runner.js} +592 -106
- package/dist/agents/ecagent/session-file-adapter.js +134 -0
- package/dist/agents/gemini/index.js +96 -0
- package/dist/agents/{gemini-runner.js → gemini/runner.js} +18 -23
- package/dist/{core/session/adapters/gemini-session-file-adapter.js → agents/gemini/session-file-adapter.js} +2 -2
- package/dist/aun/ability-device-routing.js +11 -17
- package/dist/aun/aid/agentmd.js +27 -1
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/aid/managed-operation.js +6 -4
- package/dist/aun/group/invite-service.js +7 -37
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/menu/client.js +1 -1
- package/dist/aun/msg/history.js +1 -1
- package/dist/aun/msg/managed-operation.js +93 -21
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +32 -4
- package/dist/aun/msg/upload.js +126 -3
- package/dist/aun/service-proxy.js +1 -1
- package/dist/aun/storage/index.js +242 -0
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +698 -213
- package/dist/channels/daemon.js +3 -2
- package/dist/channels/dingtalk.js +1 -1
- package/dist/channels/feishu.js +9 -9
- package/dist/channels/qqbot.js +1 -1
- package/dist/channels/wechat.js +2 -2
- package/dist/channels/wecom.js +1 -1
- package/dist/claude-gateway/agent-registration.js +389 -0
- package/dist/claude-gateway/binding.js +96 -0
- package/dist/claude-gateway/inbox.js +138 -0
- package/dist/claude-gateway/index.js +125 -0
- package/dist/claude-gateway/listing.js +330 -0
- package/dist/claude-gateway/router.js +328 -0
- package/dist/claude-gateway/sessions.js +128 -0
- package/dist/claude-gateway/terminal.js +250 -0
- package/dist/claude-gateway/transcript.js +272 -0
- package/dist/claude-gateway/types.js +14 -0
- package/dist/cli/ability-command.js +45 -0
- package/dist/cli/ability-output.js +182 -0
- package/dist/cli/agent-command.js +21 -2
- package/dist/cli/agent-create.js +197 -56
- package/dist/cli/agent-template.js +400 -27
- package/dist/cli/agent.js +105 -11
- package/dist/cli/aun-commands.js +237 -123
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +283 -109
- package/dist/cli/data-command.js +1 -1
- package/dist/cli/debug-mode.js +9 -0
- package/dist/cli/directory.js +1 -2
- package/dist/cli/ecmsg-gateway.js +64 -26
- package/dist/cli/fs-command.js +67 -39
- package/dist/cli/index.js +45 -12
- package/dist/cli/init.js +161 -90
- package/dist/cli/managed-command-guard.js +3 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/model.js +1 -1
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/restart-monitor.js +4 -4
- package/dist/cli/services-command.js +35 -10
- package/dist/cli/skill-command.js +4 -4
- package/dist/cli/task-context.js +24 -14
- package/dist/cli/team-workspace-command.js +50 -52
- package/dist/cli/thread-command.js +81 -14
- package/dist/cli/trigger-command.js +47 -12
- package/dist/cli/watch-logs.js +2 -1
- package/dist/config/access-policy.js +16 -3
- package/dist/config/boot-log.js +3 -0
- package/dist/config/builtin-role-templates.js +1 -1
- package/dist/config/config-field-policy.js +26 -13
- package/dist/config/config-manager.js +113 -52
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +29 -44
- package/dist/config/invoke-ipc-service.js +1 -1
- package/dist/config/owner-config.js +5 -19
- package/dist/config/peer-book-store.js +2 -3
- package/dist/config/peer-book.js +2 -2
- package/dist/config/peer-role-resolver.js +3 -9
- package/dist/config/provider-identity-migration.js +24 -105
- package/dist/config/provider-ipc-service.js +13 -3
- package/dist/config/provider-local-sync.js +4 -1
- package/dist/config/provider-menu-request.js +21 -3
- package/dist/config/provider-templates.js +1 -1
- package/dist/config/providers-config.js +138 -31
- package/dist/config/providers-import.js +3 -3
- package/dist/config/providers-management.js +109 -118
- package/dist/config/resolved-config-op.js +1 -42
- package/dist/config/schema-migration.js +254 -15
- package/dist/config/schema-registry.js +53 -8
- package/dist/config-store.js +1343 -63
- package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +228 -9
- package/dist/core/{agent-create-status.js → agent/agent-create-status.js} +112 -4
- package/dist/core/{agent-creation-claim.js → agent/agent-creation-claim.js} +3 -3
- package/dist/core/{agent-ipc-registration.js → agent/agent-ipc-registration.js} +119 -25
- package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +65 -0
- package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +249 -79
- package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +23 -18
- package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
- package/dist/core/auth/agent-delegation.js +15 -8
- package/dist/core/auth/delegation-authorization.js +28 -0
- package/dist/core/auth/operation-authorizer.js +20 -2
- package/dist/core/auth/operation-catalog.js +80 -8
- package/dist/core/baseagent/baseagent-availability.js +197 -0
- package/dist/core/baseagent/baseagent-capability-adapter.js +288 -0
- package/dist/core/baseagent/baseagent-config-shared.js +56 -0
- package/dist/core/baseagent/baseagent-identity.js +68 -0
- package/dist/core/{baseagent-loader.js → baseagent/baseagent-loader.js} +89 -6
- package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
- package/dist/core/baseagent/baseagent-plugin-descriptor.js +357 -0
- package/dist/core/baseagent/baseagent-plugin-loader.js +367 -0
- package/dist/core/baseagent/baseagent.js +157 -0
- package/dist/{agents → core/baseagent}/runner-types.js +36 -4
- package/dist/core/capability/capability-manager.js +91 -33
- package/dist/core/capability/providers/claude-capability-provider.js +2 -154
- package/dist/core/capability/providers/codex-capability-provider.js +2 -136
- package/dist/core/{channel-loader.js → channel/channel-loader.js} +226 -38
- package/dist/core/{channel-runtime.js → channel/channel-runtime.js} +21 -19
- package/dist/core/command/agent-control.js +80 -17
- package/dist/core/command/agent-template-menu.js +23 -10
- package/dist/core/command/agentmd-menu-request.js +19 -8
- package/dist/core/command/agentmd-menu.js +14 -5
- package/dist/core/command/cli-intent-parser.js +15 -0
- package/dist/core/command/command-handler.js +127 -57
- package/dist/core/command/context-policy-menu.js +122 -0
- package/dist/core/command/data-root-resolver.js +157 -20
- package/dist/core/command/memory-slash.js +6 -6
- package/dist/core/command/menu-catalog.js +95 -19
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +392 -93
- package/dist/core/command/menu-protocol.js +47 -8
- package/dist/core/command/menu-query-batch.js +9 -5
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/provider-menu.js +7 -11
- package/dist/core/command/role-menu.js +1 -1
- package/dist/core/command/skill-slash.js +17 -5
- package/dist/core/command/slash-gate.js +2 -4
- package/dist/core/command/slash-handler.js +143 -121
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/team-workspace-team.js +3 -3
- package/dist/core/command/topic-slash.js +16 -10
- package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -18
- package/dist/core/{daemon-control.js → daemon/daemon-control.js} +48 -21
- package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +28 -20
- package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +10 -5
- package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +101 -37
- package/dist/core/{lifecycle-notice.js → daemon/lifecycle-notice.js} +4 -5
- package/dist/core/file-integrity/store.js +1 -1
- package/dist/core/handoff/ipc-registration.js +3 -3
- package/dist/core/handoff/runtime.js +2 -2
- package/dist/{agents → core/inference}/request-identity.js +2 -2
- package/dist/core/inference/text-inference.js +4 -4
- package/dist/core/{bootstrap-messages.js → initialization/bootstrap-messages.js} +10 -10
- package/dist/core/{bootstrap-service.js → initialization/bootstrap-service.js} +24 -23
- package/dist/core/initialization/service.js +57 -9
- package/dist/core/invoke/executors/media.js +1 -1
- package/dist/core/invoke/executors/text.js +1 -1
- package/dist/core/memory/consolidation-context.js +3 -2
- package/dist/core/memory/consolidation-trigger.js +9 -3
- package/dist/core/memory/consolidation.js +39 -68
- package/dist/core/memory/memory-admin.js +6 -6
- package/dist/core/memory/memory-writer.js +1 -1
- package/dist/core/memory/relation-idle-monitor.js +1 -1
- package/dist/core/message/aun-ipc-sender.js +204 -88
- package/dist/core/message/aun-request-registry.js +44 -5
- package/dist/core/message/auto-mention-gate.js +1 -1
- package/dist/core/message/contact-admission.js +1 -1
- package/dist/core/message/im-renderer.js +19 -0
- package/dist/core/{interaction-router.js → message/interaction-router.js} +131 -1
- package/dist/core/message/items-formatter.js +5 -5
- package/dist/core/message/message-admission.js +1 -1
- package/dist/core/message/message-bridge.js +239 -59
- package/dist/core/message/message-log.js +8 -0
- package/dist/core/message/message-queue.js +88 -7
- package/dist/core/message/message-utils.js +1 -1
- package/dist/core/message/peer-mode.js +16 -5
- package/dist/core/message/response-engine.js +351 -152
- package/dist/core/message/send-options.js +44 -7
- package/dist/core/message/send-routing.js +55 -115
- package/dist/core/message/stream-idle-monitor.js +1 -1
- package/dist/core/{data-migration.js → migration/data-migration.js} +29 -1
- package/dist/core/model/catalog-service.js +29 -8
- package/dist/core/model/model-capabilities.js +88 -0
- package/dist/core/model/model-catalog.js +18 -7
- package/dist/core/model/model-diagnostics.js +4 -4
- package/dist/core/ownership/owner-resolver.js +107 -101
- package/dist/core/{pack-auth.js → pack/pack-auth.js} +34 -3
- package/dist/core/{pack-install.js → pack/pack-install.js} +95 -17
- package/dist/core/permission/approval-gateway.js +9 -18
- package/dist/core/permission/ec-command-parser.js +242 -82
- package/dist/core/permission/managed-file.js +234 -0
- package/dist/core/permission/protected-paths.js +120 -9
- package/dist/core/permission/sandbox-runtime.js +267 -3
- package/dist/core/permission/services-path-acl.js +9 -2
- package/dist/core/permission/session-path-grants.js +1 -1
- package/dist/core/permission/shell-environment.js +15 -1
- package/dist/core/permission/tool-policy.js +21 -9
- package/dist/core/plugin/plugin-lifecycle.js +442 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +2 -242
- package/dist/core/session/adapters/codex-session-file-adapter.js +2 -562
- package/dist/core/session/adapters/ecagent-session-file-adapter.js +2 -134
- package/dist/core/{background-session → session/background}/session-cleanup.js +2 -2
- package/dist/core/{background-session → session/background}/types.js +1 -1
- package/dist/core/session/session-file-health.js +2 -272
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +76 -12
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/session/session-terminal.js +185 -0
- package/dist/core/session/session-title.js +8 -11
- package/dist/core/{system-session → session/system}/memory.js +43 -9
- package/dist/core/{system-session → session/system}/registry.js +1 -1
- package/dist/core/{system-session → session/system}/types.js +1 -1
- package/dist/core/skill/index-generator.js +3 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/task/task-activity-store.js +112 -0
- package/dist/core/task/task-recovery-service.js +2 -2
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +6 -4
- package/dist/core/thread/thread-operation.js +27 -11
- package/dist/core/thread/thread-route.js +5 -3
- package/dist/core/thread/thread-service.js +307 -58
- package/dist/core/thread/topic-id.js +52 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/directory/{owner-directory-admission.js → admission.js} +3 -3
- package/dist/directory/{owner-directory-cache.js → cache.js} +90 -8
- package/dist/directory/{owner-directory-markdown.js → markdown.js} +2 -2
- package/dist/directory/{owner-directory-query-operation.js → query-operation.js} +83 -9
- package/dist/directory/{owner-directory-search.js → search.js} +50 -2
- package/dist/directory/{owner-directory-store.js → store.js} +2 -2
- package/dist/eck/kit-renderer.js +3 -2
- package/dist/eck/manifest-engine.js +64 -2
- package/dist/eck/message-renderer.js +35 -0
- package/dist/ecweb/basic-settings-service.js +12 -10
- package/dist/{contracts → ecweb/contracts}/ecweb-service-protocol.js +2 -1
- package/dist/ecweb/dsh-native-service.js +413 -0
- package/dist/ecweb/providers-service.js +5 -3
- package/dist/ecweb/runtime/lifecycle.js +1 -1
- package/dist/ecweb/runtime/supervisor.js +1 -1
- package/dist/event-center/center-config.js +2 -2
- package/dist/event-center/dispatcher.js +1 -1
- package/dist/event-center/ipc-operation.js +12 -3
- package/dist/event-center/pack-loader.js +2 -2
- package/dist/event-center/registry.js +6 -6
- package/dist/event-center/runtime.js +2 -2
- package/dist/index.js +181 -77
- package/dist/ipc.js +161 -12
- package/dist/outputs/authorization.js +27 -0
- package/dist/outputs/events.js +10 -1
- package/dist/outputs/panel-cards.js +960 -0
- package/dist/paths.js +60 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +196 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +30 -3
- package/dist/services/dispatcher.js +25 -7
- package/dist/services/host/main.js +397 -0
- package/dist/services/host/protocol.js +125 -0
- package/dist/services/host/resident.js +347 -0
- package/dist/services/host-client.js +398 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +208 -0
- package/dist/services/host-runtime.js +841 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +258 -36
- package/dist/services/ipc-operation.js +503 -78
- package/dist/services/pack-manager.js +2 -2
- package/dist/services/router.js +43 -3
- package/dist/services/script-runner.js +541 -100
- package/dist/services/service-payload.js +28 -1
- package/dist/services/validation.js +136 -5
- package/dist/stats/context-usage.js +110 -0
- package/dist/stats/model-resolver.js +103 -17
- package/dist/stats/query.js +5 -0
- package/dist/trigger/application-service.js +9 -6
- package/dist/trigger/authorization.js +36 -33
- package/dist/trigger/ipc-service.js +4 -4
- package/dist/trigger/local-files.js +8 -166
- package/dist/trigger/manager.js +2 -2
- package/dist/trigger/parser.js +48 -0
- package/dist/trigger/scheduler.js +35 -13
- package/dist/trigger/script-executor.js +21 -0
- package/dist/trigger/script-sandbox.js +77 -232
- package/dist/trigger/system-definitions.js +25 -0
- package/dist/trigger/validation.js +1 -1
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/atomic-write.js +88 -1
- package/dist/utils/cross-platform.js +4 -42
- package/dist/utils/error-dict.json +22 -1
- package/dist/utils/error-utils.js +193 -6
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +74 -1
- package/dist/utils/logger.js +5 -3
- package/dist/utils/media-cache.js +284 -42
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/startup-trace.js +20 -4
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/welcome.js +64 -20
- package/dist/utils/windows-shell-trust.js +7 -3
- package/ecagent/README.md +35 -0
- package/ecagent/dist/agent-loop.js +80 -30
- package/ecagent/dist/harness/env/nodejs.d.ts +16 -0
- package/ecagent/dist/harness/env/nodejs.js +49 -20
- package/ecagent/dist/harness/messages.js +3 -2
- package/ecagent/dist/harness/types.d.ts +1 -0
- package/ecagent/dist/runtime/types.d.ts +2 -0
- package/ecagent/dist/runtime/utils/validation.d.ts +7 -1
- package/ecagent/dist/runtime/utils/validation.js +42 -0
- package/ecagent/dist/types.d.ts +2 -0
- 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/channels/feishu.md +1 -1
- package/kits/docs/evolcore/INDEX.md +13 -9
- package/kits/docs/evolcore/agent-create.md +2 -0
- package/kits/docs/evolcore/agent.md +133 -11
- package/kits/docs/evolcore/aid.md +39 -6
- package/kits/docs/evolcore/config.md +95 -1
- package/kits/docs/evolcore/ctl.md +2 -1
- package/kits/docs/evolcore/ec-capabilities.md +7 -10
- package/kits/docs/evolcore/ecweb-lifecycle.md +5 -1
- package/kits/docs/evolcore/event.md +1 -1
- package/kits/docs/evolcore/fs.md +49 -3
- package/kits/docs/evolcore/group.md +5 -4
- package/kits/docs/evolcore/memory-consolidation.md +1 -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 +31 -2
- package/kits/docs/evolcore/model.md +12 -1
- package/kits/docs/evolcore/msg.md +96 -36
- package/kits/docs/evolcore/pay.md +22 -0
- package/kits/docs/evolcore/plugin.md +74 -0
- package/kits/docs/evolcore/provider.md +29 -2
- package/kits/docs/evolcore/rpc.md +2 -2
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/skill.md +17 -1
- package/kits/docs/evolcore/stats.md +5 -0
- package/kits/docs/evolcore/storage.md +22 -0
- package/kits/docs/evolcore/thread-chain.md +20 -9
- package/kits/docs/evolcore/tool-authorization.md +14 -0
- package/kits/docs/evolcore/trigger.md +89 -13
- package/kits/docs/identity/AID_PROFILE_SPEC.md +1 -1
- package/kits/docs/venues/feishu-group.md +3 -2
- package/kits/docs/venues/feishu-private.md +3 -2
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +20 -6
- package/kits/rules/06-channel.md +20 -4
- package/kits/schemas/_meta.json +42 -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 +974 -0
- package/kits/schemas/agent-config.schema.24.json +986 -0
- package/kits/schemas/agent-config.schema.25.json +986 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.11.json +487 -0
- package/kits/schemas/daemon.schema.12.json +505 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/defaults.schema.8.json +484 -0
- package/kits/schemas/providers.schema.1.json +1 -1
- package/kits/schemas/providers.schema.2.json +1 -1
- package/kits/schemas/providers.schema.3.json +26 -4
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +17 -1
- package/kits/skills/ability/SKILL.md +395 -33
- package/kits/skills/ability/STRUCTURE.md +338 -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 +80 -37
- package/kits/skills/agent-output-cards/examples/html-surface.json +11 -0
- package/kits/skills/agent-output-cards/examples/meeting-followups.json +16 -0
- package/kits/skills/agent-output-cards/examples/meeting-latest.json +24 -0
- package/kits/skills/agent-output-cards/examples/project-metrics.json +16 -0
- package/kits/skills/agent-output-cards/examples/quick-links.json +18 -0
- package/kits/skills/agent-output-cards/examples/surface.html +8 -0
- package/kits/skills/agent-template-project/SKILL.md +51 -0
- package/kits/skills/agent-template-project/references/01-collect-and-pack.md +174 -0
- package/kits/skills/agent-template-project/references/02-upload-and-share.md +109 -0
- package/kits/skills/agent-template-project/references/03-download-and-install.md +189 -0
- package/kits/skills/agent-template-project/references/04-upgrade-and-recovery.md +74 -0
- package/kits/skills/agent-template-project/references/05-publish-to-platform.md +62 -0
- 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 +5 -5
- package/kits/skills/ec-identity/SKILL.md +9 -6
- package/kits/skills/ec-pay/SKILL.md +223 -0
- package/kits/skills/ec-provider/SKILL.md +6 -6
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +138 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-skill/SKILL.md +25 -9
- package/kits/skills/ec-skill/scripts/cli.mjs +7 -7
- package/kits/skills/ec-skill/scripts/skill.mjs +55 -41
- package/kits/skills/ec-skill/scripts/template/SKILL.md.tmpl +9 -0
- package/kits/skills/ec-trigger/SKILL.md +3 -3
- package/kits/skills/personal-assistant/SKILL.md +22 -22
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +1 -1
- package/kits/skills/scrapling-article-fetch/SKILL.md +5 -5
- package/kits/skills/thread-ops/SKILL.md +19 -9
- package/kits/skills/wechat-article-media-download/SKILL.md +2 -2
- package/kits/skills/wechat-article-reader/SKILL.md +2 -2
- 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 +5 -4
- package/kits/templates/system-fragments/personal-assistant.md +2 -2
- package/kits/templates/system-fragments/reply.md +15 -9
- package/kits/templates/system-fragments/session.md +2 -2
- package/kits/templates/system-fragments/thread.md +30 -127
- package/kits/templates/system-fragments/venue.md +16 -0
- package/package.json +7 -7
- package/scripts/agent-template/index.mjs +7 -1
- package/scripts/agent-template/inspect.mjs +99 -39
- package/scripts/agent-template/overlay.mjs +126 -2
- package/scripts/agent-template/shared/common.mjs +49 -5
- package/scripts/agent-template/shared/plan.mjs +4 -2
- package/scripts/agent-template/shared/service-packs.mjs +104 -0
- package/scripts/agent-template/shared/team-schema.json +468 -39
- package/scripts/agent-template/shared/template-contract.mjs +93 -51
- package/scripts/agent-template/shared/template-package.mjs +225 -44
- package/scripts/agent-template/shared/template-runtime.mjs +137 -15
- package/scripts/agent-template/shared/template.mjs +31 -8
- package/scripts/agent-template/team-pack.mjs +528 -56
- package/scripts/agent-template/team-preview.mjs +102 -9
- package/scripts/aid-batch/identity-batch.mjs +1 -1
- package/dist/agents/baseagent-availability.js +0 -152
- package/dist/agents/baseagent.js +0 -750
- package/dist/agents/codex/catalog.js +0 -80
- package/dist/agents/ecagent-plugin-lazy.js +0 -41
- package/dist/agents/tool-time-context.js +0 -55
- package/dist/core/legacy-rename.js +0 -41
- package/dist/core/plugin-lifecycle.js +0 -137
- package/dist/core/rate-window.js +0 -53
- package/dist/core/runner-reload-transaction.js +0 -60
- package/dist/core/runtime-lock.js +0 -90
- package/dist/core/soul.js +0 -66
- package/dist/core/system-session/grants.js +0 -40
- package/dist/directory/owner-directory-agentmd-sync.js +0 -89
- package/dist/directory/owner-directory-request-operation.js +0 -79
- package/dist/directory/owner-directory-text.js +0 -60
- 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/gemini-capability-provider.js → agents/gemini/capability-provider.js} +0 -0
- /package/dist/core/{system-channels.js → channel/system-channels.js} +0 -0
- /package/dist/core/{daemon-file-cache.js → daemon/daemon-file-cache.js} +0 -0
- /package/dist/core/{event-bus.js → event/event-bus.js} +0 -0
- /package/dist/core/{event-catalog.js → event/event-catalog.js} +0 -0
- /package/dist/core/{pack-ledger.js → pack/pack-ledger.js} +0 -0
- /package/dist/directory/{owner-directory-identity.js → identity.js} +0 -0
- /package/dist/directory/{owner-directory-policy.js → policy.js} +0 -0
- /package/dist/directory/{owner-directory-remarks.js → remarks.js} +0 -0
- /package/dist/directory/{owner-directory-scope.js → scope.js} +0 -0
- /package/dist/{contracts → ecweb/contracts}/ecweb-instance.js +0 -0
- /package/kits/templates/{bootstrap-welcome.md → bootstrap-intro.md} +0 -0
package/dist/channels/aun.js
CHANGED
|
@@ -7,23 +7,22 @@ import crypto from 'crypto';
|
|
|
7
7
|
import { performance } from 'node:perf_hooks';
|
|
8
8
|
import fs from 'fs';
|
|
9
9
|
import { ownerResolver, OWNERSHIP_CACHE_MAX_AGE_MS } from '../core/ownership/owner-resolver.js';
|
|
10
|
-
import { OWNER_DIRECTORY_APPLY_WAIT_MS, OwnerDirectoryCache, parseOwnerDirectoryGrantAbilityResponse } from '../directory/
|
|
11
|
-
import { registerOwnerDirectoryAdmission } from '../directory/
|
|
12
|
-
import {
|
|
13
|
-
import { parseNotificationSnapshots, parseNotificationPublished } from '../directory/owner-directory-store.js';
|
|
14
|
-
import { OWNER_DIRECTORY_SCOPES } from '../directory/owner-directory-cache.js';
|
|
10
|
+
import { OWNER_DIRECTORY_APPLY_WAIT_MS, OwnerDirectoryCache, parseOwnerDirectoryGrantAbilityResponse, OwnerDirectoryAgentMdSync, OWNER_DIRECTORY_SCOPES } from '../directory/cache.js';
|
|
11
|
+
import { registerOwnerDirectoryAdmission } from '../directory/admission.js';
|
|
12
|
+
import { parseNotificationSnapshots, parseNotificationPublished } from '../directory/store.js';
|
|
15
13
|
import path from 'path';
|
|
16
14
|
import os from 'os';
|
|
17
15
|
import { logger, localTimestamp, logPreview } from '../utils/logger.js';
|
|
16
|
+
import { ensureSessionRuntimeDir } from '../cli/task-context.js';
|
|
18
17
|
import { LogWriter } from '../utils/log-writer.js';
|
|
19
|
-
import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } from '../core/channel-loader.js';
|
|
18
|
+
import { middleOutputModePolicy, resolveShowActivities, showActivitiesPolicy } from '../core/channel/channel-loader.js';
|
|
20
19
|
import { DEFAULT_FLUSH_DELAY_SECONDS } from '../types.js';
|
|
21
|
-
import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath } from '../paths.js';
|
|
20
|
+
import { resolvePaths, agentDir as agentDirPath, resolveRoot, channelStatePath, toAttachmentMarkedPath, } from '../paths.js';
|
|
22
21
|
import { getAunRequestRegistry, MAX_AUN_VOLATILE_TTL_SECONDS } from '../core/message/aun-request-registry.js';
|
|
23
22
|
import { AbilityError } from '../ability/types.js';
|
|
24
23
|
import { publishAbilityDocuments } from '../ability/publication.js';
|
|
25
24
|
import { resolveAunSendDevice } from '../aun/ability-device-routing.js';
|
|
26
|
-
import {
|
|
25
|
+
import { saveRelationAttachment, sanitizeFileName, bufferToInboundImage, safeFetch, formatAttachmentMarker } from '../utils/media-cache.js';
|
|
27
26
|
import { appendAidEvent } from '../utils/instance-registry.js';
|
|
28
27
|
import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInboundEntry, classifyAunPayloadForLog, findLatestMessageLogOperation, findMessageLogOperationMessageId, hasMessageLogOperation } from '../core/message/message-log.js';
|
|
29
28
|
import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
|
|
@@ -37,8 +36,8 @@ import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
|
|
|
37
36
|
import { classifyServicePayloadType, isProjectionServiceResult, getServiceRouter, peekServiceRouter, readLocalSelfIdentity, releaseServiceRouter, } from '../services/index.js';
|
|
38
37
|
import { agentServicesDir } from '../paths.js';
|
|
39
38
|
import { MAX_AUN_ATTACHMENT_SIZE, uploadBufferAndBuildPayload, uploadFileAndBuildPayload } from '../aun/msg/upload.js';
|
|
39
|
+
import { consumePaymentInbound, paymentStore } from '../pay/runtime.js';
|
|
40
40
|
import { loadAgent } from '../config-store.js';
|
|
41
|
-
import { configuredOwnerList, firstConfiguredOwner } from '../config/owner-config.js';
|
|
42
41
|
import { resolvePeerRoleDetail, resolveSenderRelationRole } from '../config/peer-role-resolver.js';
|
|
43
42
|
import { resolveAgentLifecycle } from '../config/lifecycle.js';
|
|
44
43
|
import { resolveEffective } from '../config/config-manager.js';
|
|
@@ -46,6 +45,9 @@ import { isManagementRole } from '../config/builtin-roles.js';
|
|
|
46
45
|
import { normalizeAunMentionMode, normalizeMentionMode } from '../config/mention-mode.js';
|
|
47
46
|
import { getProcessStartTime } from '../utils/process-introspect.js';
|
|
48
47
|
import * as outbox from '../aun/outbox.js';
|
|
48
|
+
import { recordTemplateNoticeReceipt } from '../agent-template/jobs.js';
|
|
49
|
+
import { parseTemplateShare, saveTemplateShare, templateShareText, TEMPLATE_SHARE_TYPE } from '../agent-template/share.js';
|
|
50
|
+
import { acceptWidgetCardReply, cancelWidgetCard, readWidgetCard, registerWidgetCard } from '../core/message/interaction-router.js';
|
|
49
51
|
import { formatSize } from '../utils/media-cache.js';
|
|
50
52
|
import { formatPeerKey, PeerIdentityCache } from '../core/relation/peer-identity.js';
|
|
51
53
|
import { prepareSameOwnerProof, registerSameOwnerClient, unregisterSameOwnerClient } from '../core/relation/same-owner-proof.js';
|
|
@@ -58,7 +60,7 @@ import { buildControlAgentName, ensureControlAgentMd } from '../aun/aid/control-
|
|
|
58
60
|
import { errorTextContainsRaw, readInstalledEvolcoreVersion } from '../utils/evolcore-version.js';
|
|
59
61
|
import { ManagedMenuClient, menuSenderDeviceId, menuTransportParams, } from '../aun/menu/index.js';
|
|
60
62
|
import { toolInputForDisplay } from '../utils/tool-summary.js';
|
|
61
|
-
import { bindPostBootstrapWelcomeOutboxSession, hasPendingPostBootstrapWelcomeOutbox, pendingPostBootstrapWelcomeOwners, isPostBootstrapWelcomeOperationId, findPostBootstrapWelcomeOutbox, bootstrapInitialMessageOperationPrefix, postBootstrapWelcomeOperationId, preparePostBootstrapWelcomeOutbox, postBootstrapWelcomeStatus, } from '../core/bootstrap-messages.js';
|
|
63
|
+
import { bindPostBootstrapWelcomeOutboxSession, hasPendingPostBootstrapWelcomeOutbox, pendingPostBootstrapWelcomeOwners, isPostBootstrapWelcomeOperationId, findPostBootstrapWelcomeOutbox, bootstrapInitialMessageOperationPrefix, postBootstrapWelcomeOperationId, preparePostBootstrapWelcomeOutbox, postBootstrapWelcomeStatus, } from '../core/initialization/bootstrap-messages.js';
|
|
62
64
|
import { hasMentionAll, mentionEntryAids, mentionEntryTargets, } from '../core/message/mention-schema.js';
|
|
63
65
|
import { aunOutboundAttention, normalizeAunMentionEntries, parseAunAttention, withAunAttention, } from '../aun/msg/mention-schema.js';
|
|
64
66
|
import { isDeliveryTarget, sameDeliveryTarget } from '../core/message/message-utils.js';
|
|
@@ -68,6 +70,14 @@ import { sentReceipt, suppressedReceipt } from '../core/message/send-receipt.js'
|
|
|
68
70
|
export const AUN_HANDOFF_MARKER_FIELD = '_evolcore_handoff_id';
|
|
69
71
|
const AUN_INTERACTION_CARD_TTL_MS = 24 * 60 * 60 * 1000;
|
|
70
72
|
const AUN_INBOUND_DEDUP_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
73
|
+
/**
|
|
74
|
+
* 服务应答的 volatile TTL(秒)。
|
|
75
|
+
*
|
|
76
|
+
* 调用方默认等 12 秒(`SERVICE_CALL_TIMEOUT_MS`),应答发出时它可能只剩几秒
|
|
77
|
+
* 有效期。给 15 秒是留出"脚本在最后一刻跑完、包在路上"的余量:超过这个窗口,
|
|
78
|
+
* 调用方的记录已是终态,投过去也只会被丢弃。
|
|
79
|
+
*/
|
|
80
|
+
const SERVICE_REPLY_TTL_SECONDS = 15;
|
|
71
81
|
const IMAGE_MIME_TYPE = /^image\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/i;
|
|
72
82
|
const AUN_ATTACHMENT_DOWNLOAD_ATTEMPTS = 3;
|
|
73
83
|
const AUN_ATTACHMENT_RETRY_DELAYS_MS = [250, 750];
|
|
@@ -168,7 +178,7 @@ const AUN_MIN_FIELD_SIZE = 1024;
|
|
|
168
178
|
const AUN_SESSION_STATE_PAYLOAD_TYPES = new Set(['text', 'image', 'file', 'video', 'voice', 'audio', 'link']);
|
|
169
179
|
const AUN_TOPIC_NAME_PAYLOAD_TYPES = new Set([
|
|
170
180
|
'text', 'file', 'image', 'audio', 'voice', 'video', 'quote', 'link', 'merge',
|
|
171
|
-
'action_card', 'card', 'notice', 'error', 'activity', 'thought',
|
|
181
|
+
'action_card', 'widget_card', 'card', 'notice', 'error', 'activity', 'thought',
|
|
172
182
|
]);
|
|
173
183
|
/** Automatic PA output shares the activity queue, not the ordinary reply path. */
|
|
174
184
|
function isAgentFinalPayload(payload) {
|
|
@@ -355,18 +365,37 @@ export function echoTraceDirection(text) {
|
|
|
355
365
|
* 正文还没有 trace 行时,回落到首行 `hop=<N>` 参数;都没有则用默认值。
|
|
356
366
|
* 去程返程共用这一个计数器,不重置。
|
|
357
367
|
*/
|
|
358
|
-
export function echoTraceNextHop(text) {
|
|
368
|
+
export function echoTraceNextHop(text, dir = echoTraceDirection(text)) {
|
|
359
369
|
const lines = text.split('\n');
|
|
360
370
|
for (let i = lines.length - 1; i >= 0; i--) {
|
|
361
|
-
const m = /\bhop=(
|
|
362
|
-
if (m)
|
|
363
|
-
|
|
371
|
+
const m = /\bhop=([+-]?\d+)(?=\s|$)/.exec(lines[i]);
|
|
372
|
+
if (m) {
|
|
373
|
+
const hop = Number(m[1]);
|
|
374
|
+
const next = dir === 'ret' || hop < 0 ? hop - 1 : Math.max(0, hop - 1);
|
|
375
|
+
if (!Number.isSafeInteger(hop) || !Number.isSafeInteger(next)) {
|
|
376
|
+
throw new Error('echo hop exceeds JSON safe integer range');
|
|
377
|
+
}
|
|
378
|
+
return next;
|
|
379
|
+
}
|
|
364
380
|
}
|
|
365
|
-
const declared = /\bhop=(\d+)\b/.exec(lines[0] ?? '');
|
|
366
|
-
if (declared)
|
|
367
|
-
return Math.max(0, Number(declared[1]) - 1);
|
|
368
381
|
return ECHO_DEFAULT_HOP - 1;
|
|
369
382
|
}
|
|
383
|
+
/** Restore terminal reply controls when a text outbox entry becomes a wire payload. */
|
|
384
|
+
export function echoTextPayload(text) {
|
|
385
|
+
const payload = { type: 'text', text };
|
|
386
|
+
if (echoProbeKind(text) === null)
|
|
387
|
+
return payload;
|
|
388
|
+
// Only Core's terminal reply trace supplies controls; arbitrary prose and
|
|
389
|
+
// first-line parameters must not turn an ordinary text message into a return.
|
|
390
|
+
const reply = text.split('\n').reverse().find(line => /^\d{2}:\d{2}:\d{2}\.\d{3} \[EvolCore\.reply\] dir=ret hop=/.test(line));
|
|
391
|
+
const hopField = reply && /\bhop=([+-]?\d+)(?=\s|$)/.exec(reply);
|
|
392
|
+
if (!hopField)
|
|
393
|
+
return payload;
|
|
394
|
+
const hop = Number(hopField[1]);
|
|
395
|
+
if (!Number.isSafeInteger(hop))
|
|
396
|
+
throw new Error('echo hop exceeds JSON safe integer range');
|
|
397
|
+
return { ...payload, dir: 'ret', hop };
|
|
398
|
+
}
|
|
370
399
|
/**
|
|
371
400
|
* 组装一行 trace。
|
|
372
401
|
*
|
|
@@ -962,8 +991,6 @@ export class AUNChannel {
|
|
|
962
991
|
&& (!params || !String(payload.type).startsWith('menu.') || params.encrypt === true)
|
|
963
992
|
&& (!params || !permit.device || (params.to_device_id ?? params.device_id) === permit.device));
|
|
964
993
|
}
|
|
965
|
-
// Keep each target's attempt across channel recreation; reset only on process restart.
|
|
966
|
-
static configuredOwnerBindAttempts = new Set();
|
|
967
994
|
managedMenuClient = new ManagedMenuClient((params, beforeSend) => {
|
|
968
995
|
if (!this.connected || !this.client)
|
|
969
996
|
return Promise.reject(new Error('AUN channel is not connected'));
|
|
@@ -988,9 +1015,6 @@ export class AUNChannel {
|
|
|
988
1015
|
} });
|
|
989
1016
|
}
|
|
990
1017
|
client = null;
|
|
991
|
-
configuredOwnerBind;
|
|
992
|
-
configuredOwnerBindEpoch = 0;
|
|
993
|
-
configuredOwnerBindRecheck = false;
|
|
994
1018
|
ownerDirectoryCache;
|
|
995
1019
|
ownerDirectoryWatch;
|
|
996
1020
|
ownerDirectoryFlight;
|
|
@@ -1020,7 +1044,6 @@ export class AUNChannel {
|
|
|
1020
1044
|
/** `topic.renamed` 事件消费器,由 runtime 注入(见 setThreadRenameHandler)。 */
|
|
1021
1045
|
threadRenameHandler = null;
|
|
1022
1046
|
groupInviteHandler;
|
|
1023
|
-
groupInviteConnectedHandler;
|
|
1024
1047
|
groupInviteDeliveryGate;
|
|
1025
1048
|
groupInviteDelivered;
|
|
1026
1049
|
pendingEchoMessages = new Map();
|
|
@@ -1043,7 +1066,7 @@ export class AUNChannel {
|
|
|
1043
1066
|
// 便于 jq 过滤:`jq 'select(.task_id == "task-xxx")'`
|
|
1044
1067
|
const inbound = data && typeof data === 'object' ? data : {};
|
|
1045
1068
|
const isolateTrace = dir === 'IN' && event === 'message.received'
|
|
1046
|
-
&& (!this.config.pureIdentity || inbound.payload?.type === 'action_card_reply');
|
|
1069
|
+
&& (!this.config.pureIdentity || inbound.payload?.type === 'action_card_reply' || inbound.payload?.type === 'widget_card_reply');
|
|
1047
1070
|
const safeData = isolateTrace ? {
|
|
1048
1071
|
message_id: inbound.message_id, seq: inbound.seq,
|
|
1049
1072
|
envelope: { from: inbound.envelope?.from, to: inbound.envelope?.to, encrypted: inbound.envelope?.encrypted },
|
|
@@ -1087,6 +1110,13 @@ export class AUNChannel {
|
|
|
1087
1110
|
*/
|
|
1088
1111
|
callClient(method, params, lane = 'normal', onStart, onPrepared, beforeSend) {
|
|
1089
1112
|
params = menuTransportParams(method, params);
|
|
1113
|
+
if (method === 'message.send' && typeof params.payload?.type === 'string'
|
|
1114
|
+
&& (params.payload.type === 'menu.response' || params.payload.type === 'menu.event')) {
|
|
1115
|
+
logger.info(`${this.logPrefix()} menu.send prepared type=${params.payload.type} `
|
|
1116
|
+
+ `request_id=${typeof params.payload.id === 'string' ? params.payload.id : '<none>'} `
|
|
1117
|
+
+ `target_device_id=${menuSenderDeviceId(params.to_device_id) ?? '<aid-broadcast>'} `
|
|
1118
|
+
+ `message_class=${params.message_class ?? '<none>'} ttl=${params.ttl ?? 0}`);
|
|
1119
|
+
}
|
|
1090
1120
|
const client = this.client;
|
|
1091
1121
|
const friendPayload = (typeof params.payload?.type === 'string' && params.payload.type.startsWith('friend.'))
|
|
1092
1122
|
|| isContactApprovalCard(params.payload);
|
|
@@ -1357,6 +1387,73 @@ export class AUNChannel {
|
|
|
1357
1387
|
logger.info(`${this.logPrefix()} ActionInteraction audit: behavior=${behavior ?? 'reply'} `
|
|
1358
1388
|
+ `cardId=${cardMessageId} interactionId=${interactionId} result=${result} textLength=${textLength}`);
|
|
1359
1389
|
}
|
|
1390
|
+
async handleWidgetCardReply(payload, channelId, senderAid, delivery, messageId, encrypted) {
|
|
1391
|
+
let replyThreadId;
|
|
1392
|
+
try {
|
|
1393
|
+
const binding = typeof payload.card_message_id === 'string'
|
|
1394
|
+
? readWidgetCard(this.config.aid, payload.card_message_id) : undefined;
|
|
1395
|
+
// Group replies are broadcast to every Agent. Like action_card_reply,
|
|
1396
|
+
// a reply to another sender's card is silently ignored by this Agent.
|
|
1397
|
+
if (!binding)
|
|
1398
|
+
return;
|
|
1399
|
+
if (binding?.channelId === channelId && binding.chatType === delivery.chatType && binding.initiatorAid === senderAid) {
|
|
1400
|
+
replyThreadId = binding.threadId;
|
|
1401
|
+
}
|
|
1402
|
+
const outcome = await acceptWidgetCardReply({
|
|
1403
|
+
selfAid: this.config.aid, channelId, senderAid, chatType: delivery.chatType, payload, encrypted,
|
|
1404
|
+
dispatch: async (binding, action, values) => {
|
|
1405
|
+
if (binding.requestId) {
|
|
1406
|
+
const accepted = await this.interactionCallback?.({
|
|
1407
|
+
type: 'interaction.response', id: binding.requestId, action,
|
|
1408
|
+
values, operatorId: senderAid, encrypted,
|
|
1409
|
+
});
|
|
1410
|
+
if (!this.interactionCallback || accepted === false) {
|
|
1411
|
+
await this.invalidateInteraction(binding.requestId, 'backend_rejected');
|
|
1412
|
+
cancelWidgetCard(this.config.aid, binding.messageId);
|
|
1413
|
+
throw Object.assign(new Error('卡片已失效,请重新发起'), { code: 'WIDGET_CARD_EXPIRED' });
|
|
1414
|
+
}
|
|
1415
|
+
this.forgetInteractionCard(binding.messageId, binding.requestId);
|
|
1416
|
+
return;
|
|
1417
|
+
}
|
|
1418
|
+
if (!this.messageHandler)
|
|
1419
|
+
throw new Error('WidgetCard handler is unavailable');
|
|
1420
|
+
if (binding.threadId) {
|
|
1421
|
+
const thread = ThreadService.findThreadById(this.config.aid, binding.threadId);
|
|
1422
|
+
if (!thread || thread.peer !== channelId || thread.topicStatus === 'archived') {
|
|
1423
|
+
throw Object.assign(new Error('原话题已不存在或已归档,请重新发起'), { code: 'WIDGET_CARD_EXPIRED' });
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
const groupRoles = delivery.chatType === 'group' ? await this.resolveGroupMemberRoles(channelId) : undefined;
|
|
1427
|
+
const text = `[WidgetCard 用户${action === 'cancel' ? '取消' : '提交'}]\n${JSON.stringify({
|
|
1428
|
+
title: binding.title, card_message_id: binding.messageId,
|
|
1429
|
+
submission_id: payload.submission_id, action, ...(action === 'submit' ? { values } : {}),
|
|
1430
|
+
})}`;
|
|
1431
|
+
await this.dispatchMessage({
|
|
1432
|
+
channelId, userId: senderAid, chatType: delivery.chatType,
|
|
1433
|
+
...(delivery.chatType === 'group' ? { groupId: channelId,
|
|
1434
|
+
groupRole: groupRoles?.get(senderAid.toLowerCase()),
|
|
1435
|
+
myGroupRole: groupRoles?.get(this.config.aid.toLowerCase()),
|
|
1436
|
+
groupRoles: groupRoles ? Object.fromEntries(groupRoles) : undefined,
|
|
1437
|
+
speakerRelation: resolveSenderRelationRole({ selfAid: this.config.aid,
|
|
1438
|
+
channelKey: `aun#${this.config.aid}#main`, channelType: 'aun', chatType: 'group',
|
|
1439
|
+
senderAid, conversationId: channelId }),
|
|
1440
|
+
} : {}),
|
|
1441
|
+
text, messageId, encrypted, threadId: binding.threadId, source: 'card-trigger', isMentioned: true,
|
|
1442
|
+
msgType: 'widget_card_reply', payloadType: 'widget_card_reply',
|
|
1443
|
+
messageLogContent: '[WidgetCard 回复]', receivedAt: Date.now(), awaitHandler: true,
|
|
1444
|
+
replyContext: { delivery, threadId: binding.threadId,
|
|
1445
|
+
metadata: { encrypted }, replyToMessageId: messageId },
|
|
1446
|
+
});
|
|
1447
|
+
},
|
|
1448
|
+
});
|
|
1449
|
+
logger.info(`${this.logPrefix()} WidgetCard reply ${outcome}: mid=${messageId}`);
|
|
1450
|
+
}
|
|
1451
|
+
catch (error) {
|
|
1452
|
+
const code = error.code ?? 'WIDGET_REPLY_FAILED';
|
|
1453
|
+
logger.warn(`${this.logPrefix()} WidgetCard reply rejected: code=${code} mid=${messageId}`);
|
|
1454
|
+
this.notifyCardActionFailure(channelId, error.code ? error.message : '表单处理失败,请核实任务状态后再操作', senderAid, replyThreadId, delivery);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1360
1457
|
extractTextPayload(payload, channelId, senderAid, delivery, encrypted) {
|
|
1361
1458
|
if (typeof payload === 'string')
|
|
1362
1459
|
return payload;
|
|
@@ -1381,9 +1478,13 @@ export class AUNChannel {
|
|
|
1381
1478
|
?? (savedTopic?.channelId === channelId ? savedTopic?.threadId : undefined)
|
|
1382
1479
|
?? (typeof obj.thread_id === 'string' ? obj.thread_id : undefined);
|
|
1383
1480
|
if (cardInfo) {
|
|
1481
|
+
if (cardInfo.widget) {
|
|
1482
|
+
this.notifyCardActionFailure(channelId || '', '该卡片需要通过 widget_card_reply 提交表单', senderAid, threadId, cardDelivery);
|
|
1483
|
+
return '';
|
|
1484
|
+
}
|
|
1384
1485
|
// compose 按钮由新版客户端在卡片内采集输入;旧版客户端可继续从主编辑器
|
|
1385
1486
|
// 采集。两者最终都回传 action_card_reply{behavior:"compose", text}。
|
|
1386
|
-
// 映射为 _custom_input + values.custom_text,复用
|
|
1487
|
+
// 映射为 _custom_input + values.custom_text,复用 Claude runner 已有的自定义输入分支
|
|
1387
1488
|
// (原为多选表单提交而设),不需要新增 action 类型,也不必拦截消息队列。
|
|
1388
1489
|
const behaviorRaw = typeof obj.behavior === 'string' ? obj.behavior : undefined;
|
|
1389
1490
|
if (behaviorRaw && behaviorRaw !== 'reply' && behaviorRaw !== 'compose' && behaviorRaw !== 'dismiss') {
|
|
@@ -1489,7 +1590,7 @@ export class AUNChannel {
|
|
|
1489
1590
|
if (this.interactionCallback) {
|
|
1490
1591
|
if (this.interactionActionsInFlight.has(cardMsgId)) {
|
|
1491
1592
|
this.auditActionCardInteraction(behaviorRaw, cardMsgId, cardInfo.requestId, 'rejected_in_flight', text.length);
|
|
1492
|
-
this.notifyCardActionFailure(channelId, '
|
|
1593
|
+
this.notifyCardActionFailure(channelId, '操作正在处理,请勿重复点击', cardClickerAid, threadId, cardDelivery);
|
|
1493
1594
|
return '';
|
|
1494
1595
|
}
|
|
1495
1596
|
this.interactionActionsInFlight.add(cardMsgId);
|
|
@@ -1860,7 +1961,6 @@ export class AUNChannel {
|
|
|
1860
1961
|
prepareShutdown() {
|
|
1861
1962
|
this.intentionalDisconnect = true;
|
|
1862
1963
|
this.reconnectGeneration++;
|
|
1863
|
-
this.configuredOwnerBindEpoch++;
|
|
1864
1964
|
this.stopOwnerDirectoryRefresh();
|
|
1865
1965
|
this.stopOutboxTimer();
|
|
1866
1966
|
if (this.reconnectTimer)
|
|
@@ -2183,7 +2283,7 @@ export class AUNChannel {
|
|
|
2183
2283
|
if (this.intentionalDisconnect || this.client !== client || !this.connected)
|
|
2184
2284
|
return;
|
|
2185
2285
|
const ownerAid = ownerResolver.owner(selfAid);
|
|
2186
|
-
logger.
|
|
2286
|
+
logger.debug(`${this.logPrefix()} ownerResolver result: selfAid=${selfAid}, ownerAid=${ownerAid || 'undefined'}`);
|
|
2187
2287
|
if (ownership.refreshFailure) {
|
|
2188
2288
|
const code = ownership.refreshFailure.code || 'UNKNOWN';
|
|
2189
2289
|
logger.warn(`${this.logPrefix()} Owner relationship refresh failed: status=${ownership.consensusStatus} code=${code}`);
|
|
@@ -2582,6 +2682,8 @@ export class AUNChannel {
|
|
|
2582
2682
|
return this.shouldEncrypt(this.config.aid);
|
|
2583
2683
|
}
|
|
2584
2684
|
_aid;
|
|
2685
|
+
/** Device identity resolved at connect; descriptive metadata for payload.debug only. */
|
|
2686
|
+
deviceInfo;
|
|
2585
2687
|
_selfName; // 本地 agent.md 中的 name,首次 connect 时读取
|
|
2586
2688
|
_chatId = ''; // aid:device_id:slot_id — 多实例回声过滤
|
|
2587
2689
|
/**
|
|
@@ -2611,6 +2713,8 @@ export class AUNChannel {
|
|
|
2611
2713
|
/** 失效可能先于 outbox 卡片投递完成;迟到卡片不得重新启用交互。 */
|
|
2612
2714
|
invalidatedInteractions = new Map();
|
|
2613
2715
|
mentionModeResolver;
|
|
2716
|
+
/** Agent-level private-chat @ policy (`privateMentionMode`); unrelated to group mention policy. */
|
|
2717
|
+
privateMentionModeResolver;
|
|
2614
2718
|
/** Agent-level policy controlling whether group slash commands require structured mentions. */
|
|
2615
2719
|
groupSlashRequireMentionsResolver;
|
|
2616
2720
|
static PROACTIVE_ALLOW_TYPES = new Set([
|
|
@@ -2713,7 +2817,6 @@ export class AUNChannel {
|
|
|
2713
2817
|
if (this.config.pureIdentity && handlers)
|
|
2714
2818
|
return;
|
|
2715
2819
|
this.groupInviteHandler = handlers?.onInvite;
|
|
2716
|
-
this.groupInviteConnectedHandler = handlers?.onConnected;
|
|
2717
2820
|
this.groupInviteDeliveryGate = handlers?.canDeliver;
|
|
2718
2821
|
this.groupInviteDelivered = handlers?.onDelivered;
|
|
2719
2822
|
}
|
|
@@ -2832,7 +2935,6 @@ export class AUNChannel {
|
|
|
2832
2935
|
// An explicit new attempt retires the previous gateway's terminal decision.
|
|
2833
2936
|
this.setAidStatus('reconnecting', { lastAttemptAt: Date.now() });
|
|
2834
2937
|
this.stopOwnerDirectoryRefresh();
|
|
2835
|
-
this.configuredOwnerBindEpoch++;
|
|
2836
2938
|
this.observerGroupMembers.clear();
|
|
2837
2939
|
for (const groupId of new Set([
|
|
2838
2940
|
...this.observerGroupMembershipEpoch.keys(),
|
|
@@ -2902,8 +3004,6 @@ export class AUNChannel {
|
|
|
2902
3004
|
throw this.initializationCancelled();
|
|
2903
3005
|
}
|
|
2904
3006
|
this.client = client;
|
|
2905
|
-
const localConfig = loadAgent(aidName);
|
|
2906
|
-
ownerResolver.setAgentConfiguredOwners(aidName, configuredOwnerList(localConfig));
|
|
2907
3007
|
ownerResolver.attachClient(aidName, client);
|
|
2908
3008
|
registerSameOwnerClient(aidName, client, store);
|
|
2909
3009
|
try {
|
|
@@ -2925,7 +3025,6 @@ export class AUNChannel {
|
|
|
2925
3025
|
store,
|
|
2926
3026
|
aunPath,
|
|
2927
3027
|
cacheRoot: resolveRoot(),
|
|
2928
|
-
ownerAid: this.config.controlOwnerAid,
|
|
2929
3028
|
}).then(result => {
|
|
2930
3029
|
if (!isCurrentClient())
|
|
2931
3030
|
return;
|
|
@@ -3155,7 +3254,7 @@ export class AUNChannel {
|
|
|
3155
3254
|
channelName: this.config.channelName,
|
|
3156
3255
|
});
|
|
3157
3256
|
this.trace('OUT', 'client.connect', { gateway: this.gatewayUrl, extra_info: extraInfo });
|
|
3158
|
-
await client.connect({
|
|
3257
|
+
const connectResult = await client.connect({
|
|
3159
3258
|
// connection_kind 默认 long;slot 已由 AID 携带(evolcore-daemon)
|
|
3160
3259
|
// extra_info:互踢诊断名片(0.4.3 公开 connect 已支持透传)
|
|
3161
3260
|
extra_info: extraInfo,
|
|
@@ -3175,6 +3274,16 @@ export class AUNChannel {
|
|
|
3175
3274
|
this._aid = client.aid ?? undefined;
|
|
3176
3275
|
const deviceId = client.currentAid?.deviceId ?? '';
|
|
3177
3276
|
this._chatId = this._aid ? `${this._aid}:${deviceId}:` : '';
|
|
3277
|
+
// Device identity as the SDK resolved it for this connection. It is
|
|
3278
|
+
// descriptive only — never an authentication or authorization input — and
|
|
3279
|
+
// is attached to `payload.debug` so a receiving peer can tell which device
|
|
3280
|
+
// of this AID sent a message.
|
|
3281
|
+
this.deviceInfo = {
|
|
3282
|
+
deviceId: connectResult?.device_id || deviceId || undefined,
|
|
3283
|
+
deviceIdV2: connectResult?.device_id_v2 || undefined,
|
|
3284
|
+
deviceType: connectResult?.device_type || undefined,
|
|
3285
|
+
deviceName: connectResult?.device_name || undefined,
|
|
3286
|
+
};
|
|
3178
3287
|
// 控制 AID 也有标准 host agent.md。发布在后台执行,短暂的 Name
|
|
3179
3288
|
// Service/Gateway 故障不能把控制通道判定为连接失败。
|
|
3180
3289
|
if (this.config.pureIdentity) {
|
|
@@ -3189,7 +3298,6 @@ export class AUNChannel {
|
|
|
3189
3298
|
this.connectedAt = Date.now();
|
|
3190
3299
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
3191
3300
|
completeControlAgentMd();
|
|
3192
|
-
this.reconcileConfiguredOwnerBinding();
|
|
3193
3301
|
// 连接本身**不触发拉取**:名录是懒同步的,只有 `owner.directory.changed` 会写标记。
|
|
3194
3302
|
// 重连很频繁(网络抖动、网关轮换),每次连上都拉一遍会把恢复期变成拉取风暴。
|
|
3195
3303
|
if (!this.config.pureIdentity) {
|
|
@@ -3201,9 +3309,6 @@ export class AUNChannel {
|
|
|
3201
3309
|
catch (error) {
|
|
3202
3310
|
logger.warn(`${this.logPrefix()} Service warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
3203
3311
|
}
|
|
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
3312
|
}
|
|
3208
3313
|
logger.debug(`${this.logPrefix()} connect() completed as ${this._aid}; awaiting connection.state for lifecycle log`);
|
|
3209
3314
|
this.startOwnerDirectoryRefresh();
|
|
@@ -3372,10 +3477,16 @@ export class AUNChannel {
|
|
|
3372
3477
|
const rawAttachments = preCollected ?? this.collectAllAttachments(payload);
|
|
3373
3478
|
const images = [];
|
|
3374
3479
|
let finalText = baseText;
|
|
3480
|
+
let logText = baseText;
|
|
3375
3481
|
if (rawAttachments.length === 0 || !this.client) {
|
|
3376
|
-
return { finalText, images };
|
|
3482
|
+
return { finalText, logText, images };
|
|
3377
3483
|
}
|
|
3484
|
+
// 两套正文:
|
|
3485
|
+
// - finalText:绝对路径。本轮直接给模型用,Read 工具要能立刻读到。
|
|
3486
|
+
// - logText:`$EVOLCORE_HOME/...` 可迁移路径。写进 messages.jsonl,
|
|
3487
|
+
// 换机器/换盘符后仍能被展开成当时的正确绝对路径。
|
|
3378
3488
|
const fileParts = [];
|
|
3489
|
+
const logFileParts = [];
|
|
3379
3490
|
for (const att of rawAttachments) {
|
|
3380
3491
|
const attachmentBuffer = await this.downloadAttachment(att, channelId, delivery);
|
|
3381
3492
|
if (!attachmentBuffer)
|
|
@@ -3390,41 +3501,49 @@ export class AUNChannel {
|
|
|
3390
3501
|
catch { /* read failed, treat as non-image file */ }
|
|
3391
3502
|
if (img) {
|
|
3392
3503
|
try {
|
|
3393
|
-
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), img.mimeType);
|
|
3504
|
+
const attachment = saveRelationAttachment(attachmentBuffer, this.config.aid, formatPeerKey('aun', channelId), img.mimeType, { filename: name, direction: 'in' });
|
|
3394
3505
|
img = { ...img, attachmentId: attachment.attachmentId, localPath: attachment.filePath };
|
|
3395
|
-
//
|
|
3396
|
-
fileParts.push(
|
|
3506
|
+
// 和非图片文件一样,把落盘路径放进消息正文,模型可直接用这个路径读文件或传给命令
|
|
3507
|
+
fileParts.push(formatAttachmentMarker('图片', name, attachment.filePath, attachment.storage));
|
|
3508
|
+
logFileParts.push(formatAttachmentMarker('图片', name, toAttachmentMarkedPath(this.config.aid, attachment.filePath), attachment.storage));
|
|
3397
3509
|
}
|
|
3398
3510
|
catch (error) {
|
|
3399
3511
|
logger.warn(`${this.logPrefix()} Failed to persist relation attachment for ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3400
3512
|
}
|
|
3401
3513
|
images.push(img);
|
|
3402
|
-
//
|
|
3514
|
+
// 图片已注入视觉通道;落盘路径写进消息正文,模型用该路径读文件或传给命令
|
|
3403
3515
|
}
|
|
3404
3516
|
else {
|
|
3405
|
-
|
|
3406
|
-
|
|
3407
|
-
: process.cwd();
|
|
3517
|
+
// 非图片文件同样进关系级附件目录:与图片统一落点,
|
|
3518
|
+
// 换机器时只要搬 $EVOLCORE_HOME,历史里引用的文件都还在。
|
|
3408
3519
|
try {
|
|
3409
|
-
const
|
|
3410
|
-
fileParts.push(
|
|
3520
|
+
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' });
|
|
3521
|
+
fileParts.push(formatAttachmentMarker('文件', name, attachment.filePath, attachment.storage));
|
|
3522
|
+
logFileParts.push(formatAttachmentMarker('文件', name, toAttachmentMarkedPath(this.config.aid, attachment.filePath), attachment.storage));
|
|
3411
3523
|
}
|
|
3412
3524
|
catch (error) {
|
|
3413
|
-
logger.warn(`${this.logPrefix()}
|
|
3525
|
+
logger.warn(`${this.logPrefix()} Failed to persist relation file for ${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3414
3526
|
}
|
|
3415
3527
|
}
|
|
3416
3528
|
}
|
|
3417
3529
|
const parts = [];
|
|
3418
|
-
|
|
3530
|
+
const logParts = [];
|
|
3531
|
+
if (baseText) {
|
|
3419
3532
|
parts.push(baseText);
|
|
3533
|
+
logParts.push(baseText);
|
|
3534
|
+
}
|
|
3420
3535
|
if (fileParts.length > 0) {
|
|
3421
3536
|
parts.push(...fileParts);
|
|
3422
3537
|
parts.push('请使用 Read 工具读取文件内容。');
|
|
3538
|
+
logParts.push(...logFileParts);
|
|
3539
|
+
logParts.push('请使用 Read 工具读取文件内容。');
|
|
3423
3540
|
}
|
|
3424
3541
|
if (parts.length > 0)
|
|
3425
3542
|
finalText = parts.join('\n\n');
|
|
3543
|
+
if (logParts.length > 0)
|
|
3544
|
+
logText = logParts.join('\n\n');
|
|
3426
3545
|
logger.info(`${this.logPrefix()} [attachments] count=${rawAttachments.length} images=${images.length} files=${fileParts.length}`);
|
|
3427
|
-
return { finalText, images };
|
|
3546
|
+
return { finalText, logText, images };
|
|
3428
3547
|
}
|
|
3429
3548
|
async downloadAttachmentWithRetry(url, filename, source, download) {
|
|
3430
3549
|
const host = attachmentDownloadHost(url);
|
|
@@ -4004,10 +4123,41 @@ export class AUNChannel {
|
|
|
4004
4123
|
logger.debug(`${this.logPrefix()} P2P dropped: pubsub control envelope (mid=${messageId})`);
|
|
4005
4124
|
return;
|
|
4006
4125
|
}
|
|
4126
|
+
// Ability replies belong to an authenticated protocol request, not a
|
|
4127
|
+
// conversation contact. Match them before chat admission/observers;
|
|
4128
|
+
// unmatched or spoofed protocol replies never become model input.
|
|
4129
|
+
const abilityReply = msg.payload && typeof msg.payload === 'object' && !Array.isArray(msg.payload)
|
|
4130
|
+
&& msg.payload.type === 'ability' && ['ack', 'result'].includes(String(msg.payload.role));
|
|
4131
|
+
if (abilityReply) {
|
|
4132
|
+
if (!this.claimInboundMessage('private', messageId, seq))
|
|
4133
|
+
return;
|
|
4134
|
+
const matched = getAunRequestRegistry().resolveIncoming({
|
|
4135
|
+
selfAid: this._aid || this.config.aid, fromAid,
|
|
4136
|
+
fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
|
|
4137
|
+
messageId, payload: msg.payload, encrypted: !!env.encrypted, transport: 'p2p',
|
|
4138
|
+
});
|
|
4139
|
+
if (!matched)
|
|
4140
|
+
logger.debug(`${this.logPrefix()} Unmatched Ability reply: mid=${messageId} from=${fromAid}`);
|
|
4141
|
+
return;
|
|
4142
|
+
}
|
|
4007
4143
|
if (!appOwned && !this.claimInboundMessage('private', messageId, seq))
|
|
4008
4144
|
return;
|
|
4009
4145
|
const protectedHeaders = verifiedProtectedHeaders(msg, env);
|
|
4010
4146
|
const payload = msg.payload ?? '';
|
|
4147
|
+
if (payload && typeof payload === 'object' && payload.type === 'widget_card_reply') {
|
|
4148
|
+
await this.handleWidgetCardReply(payload, fromAid, fromAid, { chatType: 'private' }, messageId, !!env.encrypted);
|
|
4149
|
+
return;
|
|
4150
|
+
}
|
|
4151
|
+
// Payment controls have durable business mappings and must precede the
|
|
4152
|
+
// generic one-shot card consumer, observers, attachments and model input.
|
|
4153
|
+
try {
|
|
4154
|
+
if (!this.config.pureIdentity && await consumePaymentInbound(this.config.aid, fromAid, payload, !!env.encrypted))
|
|
4155
|
+
return;
|
|
4156
|
+
}
|
|
4157
|
+
catch (error) {
|
|
4158
|
+
const code = error?.code ?? 'UNKNOWN';
|
|
4159
|
+
logger.warn(`${this.logPrefix()} Payment inbound isolated: code=${code}; continuing normal message handling`);
|
|
4160
|
+
}
|
|
4011
4161
|
const menuRequest = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
4012
4162
|
&& ['menu.list', 'menu.query', 'menu.options', 'menu.update', 'menu.action', 'menu.token.request'].includes(payload.type)
|
|
4013
4163
|
? payload : undefined;
|
|
@@ -4111,7 +4261,18 @@ export class AUNChannel {
|
|
|
4111
4261
|
? payload._evolcore_causation_ref
|
|
4112
4262
|
: undefined;
|
|
4113
4263
|
const logDescriptor = classifyAunPayloadForLog(payload);
|
|
4114
|
-
|
|
4264
|
+
let templateShare;
|
|
4265
|
+
if (appOwned && payload && typeof payload === 'object' && payload.type === TEMPLATE_SHARE_TYPE) {
|
|
4266
|
+
try {
|
|
4267
|
+
templateShare = parseTemplateShare(payload, this.config.aid);
|
|
4268
|
+
}
|
|
4269
|
+
catch {
|
|
4270
|
+
logger.warn(`${this.logPrefix()} P2P template share rejected: code=INVALID_TEMPLATE_SHARE mid=${messageId}`);
|
|
4271
|
+
return;
|
|
4272
|
+
}
|
|
4273
|
+
}
|
|
4274
|
+
const text = templateShare ? templateShareText(templateShare, fromAid)
|
|
4275
|
+
: this.extractTextPayload(payload, fromAid, fromAid, { chatType: 'private' }, !!env.encrypted);
|
|
4115
4276
|
const threadId = typeof payload === 'object' && payload !== null ? payload.thread_id : undefined;
|
|
4116
4277
|
const refMessageId = typeof payload === 'object' && payload !== null && typeof payload.ref_message_id === 'string'
|
|
4117
4278
|
? payload.ref_message_id
|
|
@@ -4172,8 +4333,24 @@ export class AUNChannel {
|
|
|
4172
4333
|
// sender omitted payload.mentions; keep that compatibility signal.
|
|
4173
4334
|
mentions.push({ aid: this._aid });
|
|
4174
4335
|
}
|
|
4336
|
+
// 私聊提及标记:结构化 mentions 命中自己或 @all。信封与渲染层据此表达「这条 @ 了我」。
|
|
4337
|
+
// 同 AID 其它设备发来的消息(self-sync)也按已提及处理,与群聊 handoff 的口径一致:
|
|
4338
|
+
// 这类记录不是「别人对我说话」,不该被提及过滤挡掉。
|
|
4339
|
+
const addressedInPrivate = (!!this._aid
|
|
4340
|
+
&& (mentionEntryTargets(mentions).includes(this._aid) || hasMentionAll(mentions)))
|
|
4341
|
+
|| (!!this._aid && fromAid === this._aid);
|
|
4175
4342
|
// Process attachments (顶层 + 嵌套在 merge.items / quote.quote 中的)
|
|
4176
|
-
const { finalText,
|
|
4343
|
+
const { finalText, logText: attachmentLogText, images: inboundImages } = templateShare
|
|
4344
|
+
? saveTemplateShare(templateShare, { selfAid: this.config.aid, senderAid: fromAid, messageId, receivedAt })
|
|
4345
|
+
: contactControl
|
|
4346
|
+
? { finalText: text, logText: text, images: [] }
|
|
4347
|
+
: await traceMenuStage(menuRequest, menuContext, menuTiming, 'aun.attachments', () => this.processAttachments(payload, text, fromAid, undefined, { chatType: 'private' }));
|
|
4348
|
+
// 历史记录正文用 logText(`$AGENT_DIR/attachments/...` 别名路径),不用 finalText:
|
|
4349
|
+
// finalText 是本回合给模型的绝对路径,写进历史后换机器/换盘符就失效。
|
|
4350
|
+
// 用 logDescriptor.content 又会把路径丢掉,读历史的一方只能看到 `[image] 文件名`。
|
|
4351
|
+
const loggedContent = logDescriptor.msgType === 'text'
|
|
4352
|
+
? attachmentLogText
|
|
4353
|
+
: (inboundImages.length > 0 || attachmentLogText !== text ? attachmentLogText : logDescriptor.content);
|
|
4177
4354
|
// 私聊 channelId = 对端 AID(不再读 payload.chat_id 含 device 三段式)
|
|
4178
4355
|
// device_id 仅 SDK 内部多实例去重用,evolcore session 层面跨端共享会话
|
|
4179
4356
|
const chatId = fromAid;
|
|
@@ -4277,17 +4454,43 @@ export class AUNChannel {
|
|
|
4277
4454
|
return;
|
|
4278
4455
|
}
|
|
4279
4456
|
// payload 类型白名单:信号类消息(status / event / thought 等)不进 Agent
|
|
4280
|
-
if (p2pPayloadType && !AUNChannel.PROACTIVE_ALLOW_TYPES.has(p2pPayloadType)) {
|
|
4457
|
+
if (p2pPayloadType && !templateShare && !AUNChannel.PROACTIVE_ALLOW_TYPES.has(p2pPayloadType)) {
|
|
4281
4458
|
this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq);
|
|
4282
4459
|
logger.info(`${this.logPrefix()} P2P retained in generic inbound event stream (not Agent chat): type=${p2pPayloadType} from=${shortAid}(${displayName}) mid=${messageId}`);
|
|
4283
4460
|
return;
|
|
4284
4461
|
}
|
|
4462
|
+
// ── 私聊提及模式(privateMentionMode,仅 Agent 级、Owner 可改)──
|
|
4463
|
+
// 判定放在所有控制类 payload 的 return 之后、真正 dispatch 之前:
|
|
4464
|
+
// menu.* / bind.request / observer.inject / event / 白名单外类型都已在上方返回,
|
|
4465
|
+
// 走到这里的一定是普通对话消息。
|
|
4466
|
+
// 与群聊 mentionMode 完全独立:只看 Agent 级 privateMentionMode,
|
|
4467
|
+
// 不读服务器 mention_mode,也不读关系级配置。
|
|
4468
|
+
if (await this.resolvePrivateMentionMode() === 'mention-only'
|
|
4469
|
+
// 联系人补投必须处理。
|
|
4470
|
+
&& !contactDelivery
|
|
4471
|
+
// echo 探针走独立 trace 流程,不参与提及过滤。
|
|
4472
|
+
&& echoProbeKind(text) === null
|
|
4473
|
+
// slash 命令不拦,与群聊 mention-only 的语义保持一致。
|
|
4474
|
+
&& !/^\s*\//.test(text)
|
|
4475
|
+
&& !addressedInPrivate) {
|
|
4476
|
+
// 先落盘再丢弃:写失败必须抛出,绝不能静默吞掉消息。
|
|
4477
|
+
this.appendInboundPayloadJsonl(chatId, fromAid, messageId, msgEncrypted, false, logDescriptor, threadId, receivedAt, seq, undefined, undefined, 'filtered-mention-only', loggedContent);
|
|
4478
|
+
logger.info(`${this.logPrefix()} P2P dropped: private mention-only (from=${fromAid} mid=${messageId} textPreview=${JSON.stringify(logPreview(text))})`);
|
|
4479
|
+
return;
|
|
4480
|
+
}
|
|
4285
4481
|
const msgChatmode = (payload && typeof payload === 'object') ? payload.chatmode : undefined;
|
|
4286
4482
|
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
4483
|
appendAidEvent({ ts: Date.now(), iso: new Date().toISOString(), event: 'message_in', aid: this.config.aid, from: fromAid, msgId: messageId, kind: 'text', len: finalText.length });
|
|
4288
4484
|
const isSystemP2P = p2pPayloadType === 'event';
|
|
4289
4485
|
this.aidStatsCollector?.recordInbound(this.config.aid, fromAid, Buffer.byteLength(finalText, 'utf-8'), finalText, isSystemP2P, msgEncrypted, msgChatmode, isSystemP2P ? 'notify' : 'send');
|
|
4290
4486
|
const replyContext = this.buildPrivateReplyContext(threadId, fromAid, msgEncrypted, messageId, msgChatmode, topicName, refMessageId, readTopicStatus(payload));
|
|
4487
|
+
// 对端发来的 is_stale_interrupt_notice 是旧版「被打断」通知的标记。该通知已不再发送,
|
|
4488
|
+
// 保留入站标记只为兼容仍在运行的旧对端:它进来后按普通消息处理,无需特殊对待。
|
|
4489
|
+
if (payload && typeof payload === 'object' && payload.is_stale_interrupt_notice === true) {
|
|
4490
|
+
if (!replyContext.metadata)
|
|
4491
|
+
replyContext.metadata = {};
|
|
4492
|
+
replyContext.metadata.isStaleInterruptNotice = true;
|
|
4493
|
+
}
|
|
4291
4494
|
const dispatched = this.dispatchMessage({
|
|
4292
4495
|
contactDelivery,
|
|
4293
4496
|
channelId: chatId,
|
|
@@ -4296,7 +4499,7 @@ export class AUNChannel {
|
|
|
4296
4499
|
text: this.config.pureIdentity && p2pPayloadType === 'text'
|
|
4297
4500
|
? (typeof payload.text === 'string' ? payload.text : '') : finalText,
|
|
4298
4501
|
chatType: 'private',
|
|
4299
|
-
...(
|
|
4502
|
+
...(p2pPayloadType === 'text' ? {
|
|
4300
4503
|
peerDeviceId: menuSenderDeviceId(msg.sender_device_id),
|
|
4301
4504
|
} : {}),
|
|
4302
4505
|
messageId,
|
|
@@ -4307,6 +4510,8 @@ export class AUNChannel {
|
|
|
4307
4510
|
seq,
|
|
4308
4511
|
threadId,
|
|
4309
4512
|
mentions,
|
|
4513
|
+
// 私聊提及标记:结构化 mentions 命中自己或 @all。信封与渲染层据此表达「这条 @ 了我」。
|
|
4514
|
+
isMentioned: addressedInPrivate,
|
|
4310
4515
|
peerName: displayName || undefined,
|
|
4311
4516
|
peerType: peerIdentity.type,
|
|
4312
4517
|
peerExttype: peerIdentity.exttype,
|
|
@@ -4320,7 +4525,7 @@ export class AUNChannel {
|
|
|
4320
4525
|
msgType: logDescriptor.msgType,
|
|
4321
4526
|
payloadType: logDescriptor.payloadType,
|
|
4322
4527
|
payloadSummary: logDescriptor.payloadSummary,
|
|
4323
|
-
messageLogContent:
|
|
4528
|
+
messageLogContent: loggedContent,
|
|
4324
4529
|
});
|
|
4325
4530
|
if (contactDelivery)
|
|
4326
4531
|
await dispatched;
|
|
@@ -4343,6 +4548,10 @@ export class AUNChannel {
|
|
|
4343
4548
|
const groupId = env.group_id ?? '';
|
|
4344
4549
|
const senderAid = env.from ?? '';
|
|
4345
4550
|
const payload = msg.payload ?? '';
|
|
4551
|
+
if (payload && typeof payload === 'object' && payload.type === 'widget_card_reply') {
|
|
4552
|
+
await this.handleWidgetCardReply(payload, groupId, senderAid, { chatType: 'group', groupId }, messageId, !!env.encrypted);
|
|
4553
|
+
return;
|
|
4554
|
+
}
|
|
4346
4555
|
if (payload && typeof payload === 'object' && payload.type === 'action_card_reply') {
|
|
4347
4556
|
const ref = payload.ref_message_id ?? payload.card_message_id;
|
|
4348
4557
|
const card = typeof ref === 'string' ? this.cardMessageIdMap.get(ref) : undefined;
|
|
@@ -4499,6 +4708,33 @@ export class AUNChannel {
|
|
|
4499
4708
|
const groupSlashRequireMentions = this.groupSlashRequireMentionsResolver
|
|
4500
4709
|
? await this.groupSlashRequireMentionsResolver().catch(() => undefined) ?? true
|
|
4501
4710
|
: true;
|
|
4711
|
+
// 命令消息:剥离所有 @(多 agent 被 @ 时各自拿到干净的 /status 各自执行);
|
|
4712
|
+
// 普通消息:仅在唯一 @ 是自己时剥离,保留其他 @ 供 agent 感知。
|
|
4713
|
+
const strippedText = isCommandMsg
|
|
4714
|
+
? slashCommandText
|
|
4715
|
+
: this.stripSelfMentionIfOnly(text, this._aid);
|
|
4716
|
+
// Detect attachments before the empty-text guard (顶层 + 嵌套)
|
|
4717
|
+
const rawAttachments = this.collectAllAttachments(payload);
|
|
4718
|
+
const hasAttachments = rawAttachments.length > 0;
|
|
4719
|
+
// Allow through if there's text OR attachments; both-empty messages are silently dropped.
|
|
4720
|
+
// echo 探针即使正文为空也要继续走 trace 流程。
|
|
4721
|
+
if (!strippedText && !hasAttachments && !isEchoMsg) {
|
|
4722
|
+
logger.debug(`${this.logPrefix()} Group dropped: empty text and no attachments (group=${groupId} sender=${senderAid} mid=${messageId})`);
|
|
4723
|
+
return;
|
|
4724
|
+
}
|
|
4725
|
+
// 附件统一「收到就下载」:与私聊同一策略,不等进模型。
|
|
4726
|
+
//
|
|
4727
|
+
// 理由:按需下载听上去省资源,但代价落在使用侧——模型要先跑一次
|
|
4728
|
+
// `ec fs cp` 再读文件,多一轮工具调用和往返延迟;而且跨 AID 读取受
|
|
4729
|
+
// public/ACL 授权约束,取回可能直接失败。下载回来存着,用的时候是
|
|
4730
|
+
// 本地绝对路径,一次 Read 就够。
|
|
4731
|
+
//
|
|
4732
|
+
// 同时保证被提及过滤掉的消息,其历史记录里也带落盘路径(loggedContent)。
|
|
4733
|
+
const { finalText, logText: attachmentLogText, images: inboundImages } = await this.processAttachments(payload, strippedText, groupId, rawAttachments, { chatType: 'group', groupId });
|
|
4734
|
+
// 历史记录用别名路径(logText),不能退回到 `[image] 文件名`,也不能记绝对路径。
|
|
4735
|
+
const loggedContent = logDescriptor.msgType === 'text'
|
|
4736
|
+
? attachmentLogText
|
|
4737
|
+
: (inboundImages.length > 0 || attachmentLogText !== strippedText ? attachmentLogText : logDescriptor.content);
|
|
4502
4738
|
if (isEchoMsg) {
|
|
4503
4739
|
// echo.ask / echo.ecdiag:追加 trace 后继续走 Agent 流程(下面会 dispatch)。
|
|
4504
4740
|
// echo 本身已在快速通道直接回包,不会走到这里。
|
|
@@ -4536,7 +4772,7 @@ export class AUNChannel {
|
|
|
4536
4772
|
if ((commandTargetsAnotherAgent || (enforceMention && !isMentioned)) && !isOwnHandoff) {
|
|
4537
4773
|
try {
|
|
4538
4774
|
if (text.trim() || this.collectAllAttachments(payload).length) {
|
|
4539
|
-
this.appendInboundPayloadJsonl(groupId, senderAid, messageId, msgEncrypted, true, logDescriptor, threadId, receivedAt, seq, isCommandMsg ? 'command' : 'unmentioned', 'filtered');
|
|
4775
|
+
this.appendInboundPayloadJsonl(groupId, senderAid, messageId, msgEncrypted, true, logDescriptor, threadId, receivedAt, seq, isCommandMsg ? 'command' : 'unmentioned', 'filtered', undefined, loggedContent);
|
|
4540
4776
|
}
|
|
4541
4777
|
}
|
|
4542
4778
|
catch (error) {
|
|
@@ -4552,22 +4788,7 @@ export class AUNChannel {
|
|
|
4552
4788
|
return;
|
|
4553
4789
|
}
|
|
4554
4790
|
}
|
|
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
4791
|
const mentions = payloadMentionEntries;
|
|
4569
|
-
// Process attachments
|
|
4570
|
-
const { finalText, images: inboundImages } = await this.processAttachments(payload, strippedText, groupId, rawAttachments, { chatType: 'group', groupId });
|
|
4571
4792
|
const selfAgentDir = path.join(resolvePaths().agentsDir, this.config.aid);
|
|
4572
4793
|
const peerIdentity = await PeerIdentityCache.resolve('aun', senderAid, selfAgentDir, this.store, false, this.config.keystorePath || resolveRoot());
|
|
4573
4794
|
const shortAid = this.getShortAid(senderAid);
|
|
@@ -4648,7 +4869,7 @@ export class AUNChannel {
|
|
|
4648
4869
|
msgType: logDescriptor.msgType,
|
|
4649
4870
|
payloadType: logDescriptor.payloadType,
|
|
4650
4871
|
payloadSummary: logDescriptor.payloadSummary,
|
|
4651
|
-
messageLogContent:
|
|
4872
|
+
messageLogContent: loggedContent,
|
|
4652
4873
|
});
|
|
4653
4874
|
}
|
|
4654
4875
|
dispatchMessage(event) {
|
|
@@ -4777,13 +4998,16 @@ export class AUNChannel {
|
|
|
4777
4998
|
.then(() => handler(inbound))
|
|
4778
4999
|
.catch(err => {
|
|
4779
5000
|
logger.error(`${this.logPrefix()} Message handler error:`, err);
|
|
4780
|
-
if (event.contactDelivery)
|
|
5001
|
+
if (event.contactDelivery || event.awaitHandler)
|
|
4781
5002
|
throw err;
|
|
4782
5003
|
});
|
|
4783
|
-
if (event.contactDelivery)
|
|
5004
|
+
if (event.contactDelivery || event.awaitHandler)
|
|
4784
5005
|
return dispatched;
|
|
4785
5006
|
}
|
|
4786
|
-
appendInboundPayloadJsonl(channelId, fromAid, msgId, encrypt, isGroup, descriptor, threadId, receivedAt, gatewaySeq, groupAttention, groupDelivery) {
|
|
5007
|
+
appendInboundPayloadJsonl(channelId, fromAid, msgId, encrypt, isGroup, descriptor, threadId, receivedAt, gatewaySeq, groupAttention, groupDelivery, privateAttention, contentOverride) {
|
|
5008
|
+
// 私聊过滤记录与群聊过滤记录共用「严格落盘」语义,但使用独立字段,
|
|
5009
|
+
// 避免群历史读取器把私聊记录当成群分类依据。
|
|
5010
|
+
const strict = groupDelivery === 'filtered' || privateAttention !== undefined;
|
|
4787
5011
|
try {
|
|
4788
5012
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', channelId, this.config.aid, this.config.channelName);
|
|
4789
5013
|
const entry = buildInboundEntry({
|
|
@@ -4793,7 +5017,7 @@ export class AUNChannel {
|
|
|
4793
5017
|
chatType: isGroup ? 'group' : 'private',
|
|
4794
5018
|
groupId: isGroup ? channelId : null,
|
|
4795
5019
|
msgId,
|
|
4796
|
-
content: descriptor.content,
|
|
5020
|
+
content: contentOverride ?? descriptor.content,
|
|
4797
5021
|
encrypt,
|
|
4798
5022
|
msgType: descriptor.msgType,
|
|
4799
5023
|
payloadType: descriptor.payloadType,
|
|
@@ -4803,15 +5027,16 @@ export class AUNChannel {
|
|
|
4803
5027
|
gatewaySeq,
|
|
4804
5028
|
groupAttention,
|
|
4805
5029
|
groupDelivery,
|
|
5030
|
+
privateAttention,
|
|
4806
5031
|
});
|
|
4807
|
-
if (
|
|
5032
|
+
if (strict)
|
|
4808
5033
|
appendMessageLogStrict(chatDir, entry, true);
|
|
4809
5034
|
else
|
|
4810
5035
|
appendMessageLog(chatDir, entry);
|
|
4811
5036
|
}
|
|
4812
5037
|
catch (e) {
|
|
4813
5038
|
logger.warn(`${this.logPrefix()} appendInboundPayloadJsonl failed: ${e}`);
|
|
4814
|
-
if (
|
|
5039
|
+
if (strict)
|
|
4815
5040
|
throw e;
|
|
4816
5041
|
}
|
|
4817
5042
|
}
|
|
@@ -5085,6 +5310,38 @@ export class AUNChannel {
|
|
|
5085
5310
|
})
|
|
5086
5311
|
.catch(error => logger.debug(`${this.logPrefix()} observer outbound recipient lookup failed: ${error}`));
|
|
5087
5312
|
}
|
|
5313
|
+
/**
|
|
5314
|
+
* Device metadata for `payload.debug`, sent only to this AID's Owner and to
|
|
5315
|
+
* Agents that share that Owner.
|
|
5316
|
+
*
|
|
5317
|
+
* Device identity is descriptive: it says which device of this AID sent a
|
|
5318
|
+
* message, never who is authorized to do anything. Restricting it keeps a
|
|
5319
|
+
* peer that is unrelated to this AID from learning the sender's device
|
|
5320
|
+
* inventory from ordinary traffic. Relationship facts come from the verified
|
|
5321
|
+
* protocol relation; when there is none, nothing is attached.
|
|
5322
|
+
*/
|
|
5323
|
+
relationshipDebug(recipientAid) {
|
|
5324
|
+
const info = this.deviceInfo;
|
|
5325
|
+
const selfAid = this.getAid();
|
|
5326
|
+
if (!info || !selfAid)
|
|
5327
|
+
return undefined;
|
|
5328
|
+
const toOwner = recipientAid === ownerResolver.owner(selfAid);
|
|
5329
|
+
const sameOwner = !toOwner
|
|
5330
|
+
&& !!ownerResolver.owner(recipientAid)
|
|
5331
|
+
&& ownerResolver.owner(recipientAid) === ownerResolver.owner(selfAid);
|
|
5332
|
+
if (!toOwner && !sameOwner)
|
|
5333
|
+
return undefined;
|
|
5334
|
+
const device = {};
|
|
5335
|
+
if (info.deviceId)
|
|
5336
|
+
device.device_id = info.deviceId;
|
|
5337
|
+
if (info.deviceIdV2)
|
|
5338
|
+
device.device_id_v2 = info.deviceIdV2;
|
|
5339
|
+
if (info.deviceType)
|
|
5340
|
+
device.device_type = info.deviceType;
|
|
5341
|
+
if (info.deviceName)
|
|
5342
|
+
device.device_name = info.deviceName;
|
|
5343
|
+
return Object.keys(device).length > 0 ? device : undefined;
|
|
5344
|
+
}
|
|
5088
5345
|
/**
|
|
5089
5346
|
* 实际投递 observer.forward 给每个 owner,使用 daemon 的全局 AUN 默认加密设置。
|
|
5090
5347
|
* original 为 SDK 给到的原始对象(入站回调 data / 出站 SendResult),整体透传,
|
|
@@ -5299,7 +5556,7 @@ export class AUNChannel {
|
|
|
5299
5556
|
echoText += `\n${echoTraceLine({
|
|
5300
5557
|
node: 'EvolCore.reply',
|
|
5301
5558
|
dir: 'ret',
|
|
5302
|
-
hop: echoTraceNextHop(echoText),
|
|
5559
|
+
hop: echoTraceNextHop(echoText, 'ret'),
|
|
5303
5560
|
ver,
|
|
5304
5561
|
now: replyTs,
|
|
5305
5562
|
extra: `conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -5418,7 +5675,6 @@ export class AUNChannel {
|
|
|
5418
5675
|
this.setAidStatus('connected', { lastConnectedAt: Date.now(), lastError: undefined, gatewayUrl: this.gatewayUrl });
|
|
5419
5676
|
this.trace('IN', source, data);
|
|
5420
5677
|
logger.info(`${this.logPrefix()} connection.state: state=connected gateway=${this.gatewayUrl || 'unknown'}`);
|
|
5421
|
-
this.reconcileConfiguredOwnerBinding();
|
|
5422
5678
|
this.startOwnerDirectoryRefresh();
|
|
5423
5679
|
// 不在这里清 flapCount —— 短命连接一上来就会触发本分支,
|
|
5424
5680
|
// 必须等 disconnected 时根据 lifetime 决定是否清零
|
|
@@ -5428,8 +5684,6 @@ export class AUNChannel {
|
|
|
5428
5684
|
const wasConnected = this.connected;
|
|
5429
5685
|
this.connected = false;
|
|
5430
5686
|
this.stopOwnerDirectoryRefresh();
|
|
5431
|
-
if (wasConnected)
|
|
5432
|
-
this.configuredOwnerBindEpoch++;
|
|
5433
5687
|
this.clearQueuedObserverSends(state);
|
|
5434
5688
|
// The nine-state SDK emits standby -> retry_backoff -> reconnecting for
|
|
5435
5689
|
// one reconnect cycle. Count the connected-to-down edge once instead of
|
|
@@ -5483,7 +5737,6 @@ export class AUNChannel {
|
|
|
5483
5737
|
}
|
|
5484
5738
|
else if (state === 'terminal_failed') {
|
|
5485
5739
|
this.stopOwnerDirectoryRefresh();
|
|
5486
|
-
this.configuredOwnerBindEpoch++;
|
|
5487
5740
|
this.connected = false;
|
|
5488
5741
|
this.connectedAt = 0;
|
|
5489
5742
|
this.trace('IN', source, data);
|
|
@@ -5536,95 +5789,6 @@ export class AUNChannel {
|
|
|
5536
5789
|
}
|
|
5537
5790
|
}
|
|
5538
5791
|
}
|
|
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
5792
|
/** 判断 terminal_failed 的 reason 是否属于"被踢"类 */
|
|
5629
5793
|
isKickReason(reason) {
|
|
5630
5794
|
if (!reason)
|
|
@@ -5802,7 +5966,7 @@ export class AUNChannel {
|
|
|
5802
5966
|
// 与 trigger / 事件中心同源:agent 的工程目录。沙箱要求绝对真实目录,
|
|
5803
5967
|
// 存在性与 H/L 分类由 buildTriggerScriptLaunch 自己校验并明确报错。
|
|
5804
5968
|
getProjectPath: () => this.defaultProjectPath,
|
|
5805
|
-
permissionMode:
|
|
5969
|
+
permissionMode: role => resolveRuntimePermissionMode({ selfAid: aid, role }).effectiveValue,
|
|
5806
5970
|
// bypass + owner 才免沙箱;角色取调用方(service 消息的 from)。解析失败按未知处理。
|
|
5807
5971
|
resolvePeerRole: fromAid => {
|
|
5808
5972
|
try {
|
|
@@ -5819,6 +5983,18 @@ export class AUNChannel {
|
|
|
5819
5983
|
return undefined;
|
|
5820
5984
|
}
|
|
5821
5985
|
},
|
|
5986
|
+
// 常驻宿主的运行目录:与本进程其它 session runtime 同一套(系统临时目录下、
|
|
5987
|
+
// 已做过 ACL 授予)。宿主程序、包脚本快照、调用临时目录都落在这下面。
|
|
5988
|
+
// 取不到时返回 undefined —— 宿主模式会在启动阶段明确拒绝,不静默降级。
|
|
5989
|
+
getRuntimeRoot: () => {
|
|
5990
|
+
try {
|
|
5991
|
+
return ensureSessionRuntimeDir(`services-host:${aid}`);
|
|
5992
|
+
}
|
|
5993
|
+
catch {
|
|
5994
|
+
return undefined;
|
|
5995
|
+
}
|
|
5996
|
+
},
|
|
5997
|
+
onHostLog: line => logger.debug(`[ServicesHost] aid=${aid} ${line}`),
|
|
5822
5998
|
});
|
|
5823
5999
|
this.serviceRouter.ensureStarted(identity);
|
|
5824
6000
|
return this.serviceRouter;
|
|
@@ -5880,6 +6056,9 @@ export class AUNChannel {
|
|
|
5880
6056
|
logger.debug(`${this.logPrefix()} service request without request_id; using message_id ${input.messageId} type=${rawType} from=${input.fromAid}`);
|
|
5881
6057
|
}
|
|
5882
6058
|
const message = {
|
|
6059
|
+
deadlineAt: Number.isSafeInteger(payload.service_deadline_at_ms)
|
|
6060
|
+
? Math.min(payload.service_deadline_at_ms, input.receivedAt + 300_000)
|
|
6061
|
+
: input.receivedAt + 12_000,
|
|
5883
6062
|
type: rawType,
|
|
5884
6063
|
requestId,
|
|
5885
6064
|
requestIdGenerated,
|
|
@@ -5905,6 +6084,9 @@ export class AUNChannel {
|
|
|
5905
6084
|
delivery: { chatType: 'private', service: { type: reply.type, requestId: reply.requestId } },
|
|
5906
6085
|
metadata: { encrypted, source: 'daemon' },
|
|
5907
6086
|
replyToMessageId,
|
|
6087
|
+
// 应答同样只活一个调用窗口:调用方早已超时退出的情况下,回包被持久补投
|
|
6088
|
+
// 没有任何意义,还会在对端留下一条无人认领的消息。
|
|
6089
|
+
ttl: SERVICE_REPLY_TTL_SECONDS,
|
|
5908
6090
|
});
|
|
5909
6091
|
if (!result.ok) {
|
|
5910
6092
|
logger.warn(`${this.logPrefix()} Service reply send failed: type=${reply.type} code=${result.code ?? 'UNKNOWN'} error=${result.error ?? ''}`);
|
|
@@ -5920,6 +6102,29 @@ export class AUNChannel {
|
|
|
5920
6102
|
setMentionModeResolver(resolver) {
|
|
5921
6103
|
this.mentionModeResolver = resolver;
|
|
5922
6104
|
}
|
|
6105
|
+
/**
|
|
6106
|
+
* 私聊 @ 处理策略。与 `mentionModeResolver` 分开:后者是按群的群聊策略,
|
|
6107
|
+
* 本 resolver 只读 Agent 级 `privateMentionMode`,不接收群/对端参数。
|
|
6108
|
+
*/
|
|
6109
|
+
setPrivateMentionModeResolver(resolver) {
|
|
6110
|
+
this.privateMentionModeResolver = resolver;
|
|
6111
|
+
}
|
|
6112
|
+
/**
|
|
6113
|
+
* 读取生效的私聊 @ 处理策略。缺省、解析失败或未装配 resolver 时一律按
|
|
6114
|
+
* `disabled` 处理:任何不确定都退回「处理所有消息」,绝不静默丢消息。
|
|
6115
|
+
*/
|
|
6116
|
+
async resolvePrivateMentionMode() {
|
|
6117
|
+
if (!this.privateMentionModeResolver)
|
|
6118
|
+
return 'disabled';
|
|
6119
|
+
try {
|
|
6120
|
+
const mode = await this.privateMentionModeResolver();
|
|
6121
|
+
return mode === 'mention-only' ? 'mention-only' : 'disabled';
|
|
6122
|
+
}
|
|
6123
|
+
catch (error) {
|
|
6124
|
+
logger.warn(`${this.logPrefix()} privateMentionMode unavailable, treating as disabled: ${error instanceof Error ? error.message : String(error)}`);
|
|
6125
|
+
return 'disabled';
|
|
6126
|
+
}
|
|
6127
|
+
}
|
|
5923
6128
|
setGroupSlashRequireMentionsResolver(resolver) {
|
|
5924
6129
|
this.groupSlashRequireMentionsResolver = resolver;
|
|
5925
6130
|
}
|
|
@@ -6211,6 +6416,8 @@ export class AUNChannel {
|
|
|
6211
6416
|
}
|
|
6212
6417
|
const messageIds = [...(this.interactionCardMessageIds.get(interactionId) ?? [])];
|
|
6213
6418
|
for (const messageId of messageIds) {
|
|
6419
|
+
if (this.cardMessageIdMap.get(messageId)?.widget)
|
|
6420
|
+
cancelWidgetCard(this.config.aid, messageId);
|
|
6214
6421
|
this.forgetInteractionCard(messageId, interactionId);
|
|
6215
6422
|
}
|
|
6216
6423
|
}
|
|
@@ -6311,7 +6518,20 @@ export class AUNChannel {
|
|
|
6311
6518
|
delivery: delivery ?? action.delivery,
|
|
6312
6519
|
replyContext: callbackContext,
|
|
6313
6520
|
sensitive: action.sensitive,
|
|
6521
|
+
widget: action.widget,
|
|
6314
6522
|
});
|
|
6523
|
+
if (action.widget && channelId && (delivery ?? action.delivery)) {
|
|
6524
|
+
const route = (delivery ?? action.delivery);
|
|
6525
|
+
registerWidgetCard(this.config.aid, {
|
|
6526
|
+
version: 1, messageId, channelId, chatType: route.chatType,
|
|
6527
|
+
initiatorAid: route.chatType === 'private' ? channelId : action.initiatorAid,
|
|
6528
|
+
requestId: action.requestId, title: 'WidgetCard', threadId: replyContext?.threadId,
|
|
6529
|
+
expiresAt: action.expiresAt,
|
|
6530
|
+
encrypted: action.sensitive === true || (typeof replyContext?.metadata?.encrypted === 'boolean'
|
|
6531
|
+
? replyContext.metadata.encrypted : this.shouldEncrypt(channelId)),
|
|
6532
|
+
sensitive: action.sensitive, status: 'pending',
|
|
6533
|
+
});
|
|
6534
|
+
}
|
|
6315
6535
|
this.ownedCardMsgIds.add(messageId);
|
|
6316
6536
|
if (typeof replyContext?.threadId === 'string') {
|
|
6317
6537
|
this.ownedCardTopics.set(messageId, { channelId, threadId: replyContext.threadId });
|
|
@@ -6343,12 +6563,32 @@ export class AUNChannel {
|
|
|
6343
6563
|
ownedTimer.unref?.();
|
|
6344
6564
|
const invalidationReason = this.invalidatedInteractions.get(action.requestId);
|
|
6345
6565
|
if (invalidationReason) {
|
|
6566
|
+
if (action.widget)
|
|
6567
|
+
cancelWidgetCard(this.config.aid, messageId);
|
|
6346
6568
|
this.forgetInteractionCard(messageId, action.requestId);
|
|
6347
6569
|
}
|
|
6348
6570
|
}
|
|
6349
6571
|
runPostSend(entry, messageId) {
|
|
6572
|
+
if (entry.dedupeKey?.startsWith('template-update:') && entry.payload?.template_update?.noticeId) {
|
|
6573
|
+
recordTemplateNoticeReceipt(resolvePaths().root, entry.payload.template_update.noticeId, entry.channelId, messageId, entry.id);
|
|
6574
|
+
}
|
|
6350
6575
|
if (!entry.postSend)
|
|
6351
6576
|
return;
|
|
6577
|
+
if (entry.postSend.type === 'register_widget_card') {
|
|
6578
|
+
if (!entry.delivery)
|
|
6579
|
+
throw new Error('WidgetCard delivery route is unavailable');
|
|
6580
|
+
registerWidgetCard(this.config.aid, {
|
|
6581
|
+
version: 1, messageId, channelId: entry.channelId, chatType: entry.delivery.chatType,
|
|
6582
|
+
initiatorAid: entry.postSend.initiatorAid, title: entry.postSend.title,
|
|
6583
|
+
threadId: typeof entry.payload?.thread_id === 'string' ? entry.payload.thread_id : undefined,
|
|
6584
|
+
expiresAt: entry.postSend.expiresAt, encrypted: entry.postSend.encrypted, status: 'pending',
|
|
6585
|
+
});
|
|
6586
|
+
return;
|
|
6587
|
+
}
|
|
6588
|
+
if (entry.postSend.type === 'register_payment_delivery') {
|
|
6589
|
+
paymentStore(this.config.aid).markDelivered(entry.postSend.requestId, entry.postSend.deliveryId, messageId);
|
|
6590
|
+
return;
|
|
6591
|
+
}
|
|
6352
6592
|
if (entry.postSend.type === 'register_contact_approval_card') {
|
|
6353
6593
|
registerContactApprovalCard(this.config.aid, entry.postSend.pendingKey, entry.postSend.eventId, messageId);
|
|
6354
6594
|
return;
|
|
@@ -6411,6 +6651,7 @@ export class AUNChannel {
|
|
|
6411
6651
|
const friendPayload = (typeof payload.type === 'string' && payload.type.startsWith('friend.')) || isContactApprovalCard(payload);
|
|
6412
6652
|
const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
|
|
6413
6653
|
if ((payload.type === 'activity' && truncatedPayload.type !== 'activity')
|
|
6654
|
+
|| (payload.type === 'widget_card' && truncatedPayload.type !== 'widget_card')
|
|
6414
6655
|
|| (isAgentFinalPayload(payload) && !isAgentFinalPayload(truncatedPayload))) {
|
|
6415
6656
|
return {
|
|
6416
6657
|
ok: false, status: 'permanent', code: 'PAYLOAD_TOO_LARGE',
|
|
@@ -6429,6 +6670,12 @@ export class AUNChannel {
|
|
|
6429
6670
|
}
|
|
6430
6671
|
if (encrypt)
|
|
6431
6672
|
params.protected_headers = aunProtectedHeaders(context);
|
|
6673
|
+
// Standalone Owner approvals belong to the persistent application control
|
|
6674
|
+
// stream. Contextual action cards need normal delivery into their topic.
|
|
6675
|
+
if (!isGroup && payload.type === 'friend.request.v1') {
|
|
6676
|
+
params.message_class = 'control';
|
|
6677
|
+
params.protected_headers = { ...params.protected_headers, message_class: 'control' };
|
|
6678
|
+
}
|
|
6432
6679
|
if (isGroup)
|
|
6433
6680
|
params.group_id = delivery.groupId;
|
|
6434
6681
|
else
|
|
@@ -6557,8 +6804,33 @@ export class AUNChannel {
|
|
|
6557
6804
|
// intentionally removes undefined array elements, which would otherwise
|
|
6558
6805
|
// turn malformed `mentions: [undefined]` into an apparently valid `[]`.
|
|
6559
6806
|
const finalPayload = this.normalizeAunPayloadMentions(this.applyReplyContextToPayload(validatedPayload, context));
|
|
6807
|
+
if (finalPayload.type === 'widget_card') {
|
|
6808
|
+
if (finalPayload.thread_id !== undefined && !isTopicThreadId(finalPayload.thread_id)) {
|
|
6809
|
+
throw Object.assign(new Error('WidgetCard thread_id must be an existing topic ID'), { code: 'INVALID_WIDGET_CARD' });
|
|
6810
|
+
}
|
|
6811
|
+
const attachments = finalPayload.attachments;
|
|
6812
|
+
const html = Array.isArray(attachments) && attachments.length === 1 ? attachments[0] : undefined;
|
|
6813
|
+
if (!html || typeof html !== 'object' || typeof html.owner_aid !== 'string' || !html.owner_aid
|
|
6814
|
+
|| typeof html.object_key !== 'string' || !html.object_key || html.object_key.includes(':')
|
|
6815
|
+
|| html.object_key.startsWith('/') || html.object_key.split('/').includes('..')
|
|
6816
|
+
|| typeof html.filename !== 'string' || !/\.html?$/i.test(html.filename)
|
|
6817
|
+
|| typeof html.content_type !== 'string' || !/^text\/html(?:\s*;|$)/i.test(html.content_type)) {
|
|
6818
|
+
throw Object.assign(new Error('WidgetCard requires one uploaded HTML attachment with owner_aid and object_key'), { code: 'INVALID_WIDGET_CARD' });
|
|
6819
|
+
}
|
|
6820
|
+
const initiatorAid = delivery.chatType === 'private' ? channelId : finalPayload.initiator;
|
|
6821
|
+
if (typeof initiatorAid !== 'string' || !initiatorAid.trim()) {
|
|
6822
|
+
throw Object.assign(new Error('Group WidgetCard requires an initiator'), { code: 'INVALID_WIDGET_INITIATOR' });
|
|
6823
|
+
}
|
|
6824
|
+
if (opts.postSend?.type !== 'register_interaction_card')
|
|
6825
|
+
opts = { ...opts, postSend: {
|
|
6826
|
+
type: 'register_widget_card', initiatorAid,
|
|
6827
|
+
title: typeof finalPayload.title === 'string' ? finalPayload.title : html.filename,
|
|
6828
|
+
expiresAt: Date.now() + AUN_INTERACTION_CARD_TTL_MS,
|
|
6829
|
+
encrypted: typeof context.metadata?.encrypted === 'boolean' ? context.metadata.encrypted : this.shouldEncrypt(channelId),
|
|
6830
|
+
} };
|
|
6831
|
+
}
|
|
6560
6832
|
const logText = opts.logText ?? this.payloadLogText(finalPayload, opts.contentKind);
|
|
6561
|
-
const expiresAt = opts.postSend?.type === 'register_interaction_card'
|
|
6833
|
+
const expiresAt = opts.postSend?.type === 'register_interaction_card' || opts.postSend?.type === 'register_widget_card'
|
|
6562
6834
|
? opts.postSend.expiresAt
|
|
6563
6835
|
: undefined;
|
|
6564
6836
|
if (typeof expiresAt === 'number' && Number.isFinite(expiresAt) && expiresAt <= Date.now()) {
|
|
@@ -6883,9 +7155,9 @@ export class AUNChannel {
|
|
|
6883
7155
|
...(result.code !== undefined ? { code: result.code } : {}),
|
|
6884
7156
|
};
|
|
6885
7157
|
}
|
|
6886
|
-
/** Daemon-side transport for `
|
|
7158
|
+
/** Daemon-side transport for `ecmsg send` running inside an agent task. */
|
|
6887
7159
|
/**
|
|
6888
|
-
* Agent 经
|
|
7160
|
+
* Agent 经 ecmsg 委托发送时占用本轮序号,
|
|
6889
7161
|
* 与回复路径共用 sentCount,保证同一轮内 seqInTurn 连续。
|
|
6890
7162
|
*/
|
|
6891
7163
|
nextSeqInTurn(channelId, threadId) {
|
|
@@ -6959,6 +7231,23 @@ export class AUNChannel {
|
|
|
6959
7231
|
return { ok: true, status: 'queued', encrypt: true, outbox_id: sent.outboxId, error: sent.error, code: sent.code };
|
|
6960
7232
|
return { ok: false, status: 'failed', encrypt: true, outbox_id: sent.outboxId, error: sent.error ?? 'friend invite control send failed', code: sent.code };
|
|
6961
7233
|
}
|
|
7234
|
+
if (finalPayload.type === 'widget_card') {
|
|
7235
|
+
if (args.ttl !== undefined || args.deviceId || args.service) {
|
|
7236
|
+
return { ok: false, code: 'INVALID_WIDGET_TARGET', error: 'WidgetCard requires persistent conversation delivery' };
|
|
7237
|
+
}
|
|
7238
|
+
const encrypt = args.encrypt ?? this.shouldEncrypt(args.to);
|
|
7239
|
+
const sent = await this.sendContentPayload(args.to, finalPayload, {
|
|
7240
|
+
contentKind: 'card', context: { delivery: { chatType: 'private' },
|
|
7241
|
+
sessionId: args.log?.sessionId,
|
|
7242
|
+
...(typeof finalPayload.thread_id === 'string' ? { threadId: finalPayload.thread_id } : {}),
|
|
7243
|
+
metadata: { encrypted: encrypt } },
|
|
7244
|
+
});
|
|
7245
|
+
if (sent.messageId)
|
|
7246
|
+
return { ok: true, message_id: sent.messageId, status: 'sent', encrypt };
|
|
7247
|
+
if (sent.queued)
|
|
7248
|
+
return { ok: true, status: 'queued', outbox_id: sent.outboxId, encrypt };
|
|
7249
|
+
return { ok: false, code: sent.code ?? 'WIDGET_CARD_SEND_FAILED', error: sent.error ?? 'WidgetCard send failed', encrypt };
|
|
7250
|
+
}
|
|
6962
7251
|
if (!this.connected || !this.client) {
|
|
6963
7252
|
return { ok: false, error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
6964
7253
|
}
|
|
@@ -7050,13 +7339,16 @@ export class AUNChannel {
|
|
|
7050
7339
|
}
|
|
7051
7340
|
this.forwardOutbound(result, args.debug);
|
|
7052
7341
|
let logWritten = false;
|
|
7053
|
-
// 跨话题自派(`--
|
|
7342
|
+
// 跨话题自派(`--thread T --selfmode`)不写出站日志:chatDir 会按 (to=本端, self=本端) 算成
|
|
7054
7343
|
// 「我↔我」目录,`ThreadService.listPeers` 的磁盘兜底会把它列成真实对端,
|
|
7055
7344
|
// 而话题 T 的历史里也会凭空多出一条「发给本端自己」的出站记录。
|
|
7056
7345
|
// 「自己收到了什么」由本地注入那条入站记录(source='self-address')表达。
|
|
7057
7346
|
const selfAddressed = args.to.replace(/^@/, '').toLowerCase() === this.config.aid.replace(/^@/, '').toLowerCase();
|
|
7058
7347
|
if (!selfAddressed && args.log?.content !== undefined) {
|
|
7059
7348
|
const classified = classifyAunPayloadForLog(finalPayload);
|
|
7349
|
+
const logContent = args.log.contentAuthoritative
|
|
7350
|
+
? args.log.content
|
|
7351
|
+
: (classified.content || args.log.content);
|
|
7060
7352
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', args.to, this.config.aid);
|
|
7061
7353
|
fs.mkdirSync(chatDir, { recursive: true });
|
|
7062
7354
|
appendMessageLog(chatDir, buildOutboundEntry({
|
|
@@ -7066,7 +7358,7 @@ export class AUNChannel {
|
|
|
7066
7358
|
threadId: args.log.threadId ?? (typeof finalPayload.thread_id === 'string' ? finalPayload.thread_id : null),
|
|
7067
7359
|
chatType: 'private',
|
|
7068
7360
|
msgId: messageId,
|
|
7069
|
-
content:
|
|
7361
|
+
content: logContent,
|
|
7070
7362
|
encrypt,
|
|
7071
7363
|
chatmode,
|
|
7072
7364
|
msgType: classified.msgType ?? args.log.msgType,
|
|
@@ -7076,7 +7368,7 @@ export class AUNChannel {
|
|
|
7076
7368
|
handoff_trace: args.log.handoffTrace,
|
|
7077
7369
|
transport: this.sendReceiptFromResult(result),
|
|
7078
7370
|
}));
|
|
7079
|
-
this.aidStatsCollector?.recordOutbound(this.config.aid, args.to, Buffer.byteLength(
|
|
7371
|
+
this.aidStatsCollector?.recordOutbound(this.config.aid, args.to, Buffer.byteLength(logContent, 'utf-8'), logContent, false, encrypt, chatmode, 'send');
|
|
7080
7372
|
logWritten = true;
|
|
7081
7373
|
}
|
|
7082
7374
|
return {
|
|
@@ -7099,6 +7391,13 @@ export class AUNChannel {
|
|
|
7099
7391
|
};
|
|
7100
7392
|
}
|
|
7101
7393
|
}
|
|
7394
|
+
/** Reuse the channel-owned storage connection and standard attachment format. */
|
|
7395
|
+
async uploadPaymentImage(data, filename) {
|
|
7396
|
+
if (!this.client || !this.connected)
|
|
7397
|
+
throw new Error('AUN channel is not connected for payment image upload');
|
|
7398
|
+
const uploaded = await uploadBufferAndBuildPayload(this.client, this.config.aid, data, filename, { as: 'image' });
|
|
7399
|
+
return uploaded.attachment;
|
|
7400
|
+
}
|
|
7102
7401
|
/**
|
|
7103
7402
|
* Send an online/offline system notice to the bound Owner as an AUN volatile
|
|
7104
7403
|
* message: nothing is persisted in the outbox or the local message log, and
|
|
@@ -7148,10 +7447,23 @@ export class AUNChannel {
|
|
|
7148
7447
|
contentType: file.contentType,
|
|
7149
7448
|
text: file.text,
|
|
7150
7449
|
transcript: file.transcript,
|
|
7450
|
+
title: file.title,
|
|
7151
7451
|
});
|
|
7152
7452
|
return built.payload;
|
|
7153
7453
|
}
|
|
7154
|
-
/**
|
|
7454
|
+
/**
|
|
7455
|
+
* 归档 daemon 侧代发的文件(托管 `ecmsg send --file` 走这条路径,不经 outbox)。
|
|
7456
|
+
* 与 outbox 投递同一落点与命名规则;归档失败只记日志、返回 null,不阻断发送。
|
|
7457
|
+
* 返回值是写进本地历史的正文:`[文件: 名 → $AGENT_DIR/attachments/…]`。
|
|
7458
|
+
*/
|
|
7459
|
+
archiveDaemonFile(channelId, filePath, as) {
|
|
7460
|
+
const archived = this.archiveOutgoingAttachment(channelId, filePath);
|
|
7461
|
+
if (!archived)
|
|
7462
|
+
return null;
|
|
7463
|
+
const label = as === 'image' ? '图片' : as === 'video' ? '视频' : as === 'voice' ? '语音' : '文件';
|
|
7464
|
+
return formatAttachmentMarker(label, path.basename(filePath), toAttachmentMarkedPath(this.config.aid, archived.filePath), archived.storage);
|
|
7465
|
+
}
|
|
7466
|
+
/** Daemon-side transport for group `ecmsg send` running inside an agent task. */
|
|
7155
7467
|
async sendDaemonGroupMsg(args) {
|
|
7156
7468
|
if (!args.groupId) {
|
|
7157
7469
|
return { ok: false, error: 'aun group send requires a group target', code: 'UNSUPPORTED_TARGET' };
|
|
@@ -7179,6 +7491,20 @@ export class AUNChannel {
|
|
|
7179
7491
|
else if (payloadMentions !== undefined) {
|
|
7180
7492
|
finalPayload.mentions = payloadMentions;
|
|
7181
7493
|
}
|
|
7494
|
+
if (finalPayload.type === 'widget_card') {
|
|
7495
|
+
const encrypt = args.encrypt ?? this.shouldEncrypt(args.groupId);
|
|
7496
|
+
const sent = await this.sendContentPayload(args.groupId, finalPayload, {
|
|
7497
|
+
contentKind: 'card', context: { delivery: { chatType: 'group', groupId: args.groupId },
|
|
7498
|
+
sessionId: args.log?.sessionId,
|
|
7499
|
+
...(typeof finalPayload.thread_id === 'string' ? { threadId: finalPayload.thread_id } : {}),
|
|
7500
|
+
metadata: { encrypted: encrypt } },
|
|
7501
|
+
});
|
|
7502
|
+
if (sent.messageId)
|
|
7503
|
+
return { ok: true, message_id: sent.messageId, status: 'sent', group_id: args.groupId, encrypt };
|
|
7504
|
+
if (sent.queued)
|
|
7505
|
+
return { ok: true, status: 'queued', outbox_id: sent.outboxId, group_id: args.groupId, encrypt };
|
|
7506
|
+
return { ok: false, code: sent.code ?? 'WIDGET_CARD_SEND_FAILED', error: sent.error ?? 'WidgetCard send failed' };
|
|
7507
|
+
}
|
|
7182
7508
|
if (!this.connected || !this.client) {
|
|
7183
7509
|
return { ok: false, error: 'AUN channel is not connected', code: 'AUN_NOT_CONNECTED' };
|
|
7184
7510
|
}
|
|
@@ -7205,7 +7531,9 @@ export class AUNChannel {
|
|
|
7205
7531
|
let logWritten = false;
|
|
7206
7532
|
if (args.log?.content !== undefined) {
|
|
7207
7533
|
const classified = classifyAunPayloadForLog(finalPayload);
|
|
7208
|
-
const content =
|
|
7534
|
+
const content = args.log.contentAuthoritative
|
|
7535
|
+
? args.log.content
|
|
7536
|
+
: (classified.content || args.log.content);
|
|
7209
7537
|
const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', args.groupId, this.config.aid);
|
|
7210
7538
|
fs.mkdirSync(chatDir, { recursive: true });
|
|
7211
7539
|
appendMessageLog(chatDir, buildOutboundEntry({
|
|
@@ -7307,7 +7635,7 @@ export class AUNChannel {
|
|
|
7307
7635
|
echoText += `\n${echoTraceLine({
|
|
7308
7636
|
node: 'EvolCore.reply',
|
|
7309
7637
|
dir: 'ret',
|
|
7310
|
-
hop: Math.max(0, hop - 1
|
|
7638
|
+
hop: Math.max(0, hop) - 1,
|
|
7311
7639
|
ver,
|
|
7312
7640
|
now: doneTs,
|
|
7313
7641
|
extra: `conn_uptime=${this.connectedAt ? Math.round((doneTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -7392,7 +7720,7 @@ export class AUNChannel {
|
|
|
7392
7720
|
echoText += `\n${echoTraceLine({
|
|
7393
7721
|
node: 'EvolCore.reply',
|
|
7394
7722
|
dir: 'ret',
|
|
7395
|
-
hop: echoTraceNextHop(echoText),
|
|
7723
|
+
hop: echoTraceNextHop(echoText, 'ret'),
|
|
7396
7724
|
ver,
|
|
7397
7725
|
now: replyTs,
|
|
7398
7726
|
extra: `conn_uptime=${this.connectedAt ? Math.round((replyTs - this.connectedAt) / 1000) + 's' : 'unknown'}`,
|
|
@@ -7474,13 +7802,16 @@ export class AUNChannel {
|
|
|
7474
7802
|
const source = context?.metadata?.source ?? 'daemon';
|
|
7475
7803
|
// ext assembly (isFinal, seqInTurn, turnMessageCount, loop, fullaccess) is handled
|
|
7476
7804
|
// 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);
|
|
7805
|
+
const payload = await this.withSessionState(channelId, withAunAttention(echoTextPayload(finalText), context?.attention), context);
|
|
7480
7806
|
// sentAt 在每次投递尝试时盖戳(outbox 重发取重发时刻)。服务端会用自己的时间覆盖
|
|
7481
7807
|
// 顶层 timestamp,两者有毫秒级差异,sentAt 只代表本端时钟。
|
|
7482
|
-
|
|
7483
|
-
|
|
7808
|
+
// Device identity rides along when the recipient is this AID's Owner or a
|
|
7809
|
+
// sibling under the same Owner; other recipients never see it.
|
|
7810
|
+
const deviceDebug = delivery.chatType === 'private' && !delivery.service
|
|
7811
|
+
? this.relationshipDebug(channelId) : undefined;
|
|
7812
|
+
if (context?.debug || deviceDebug) {
|
|
7813
|
+
payload.debug = { ...(context?.debug ?? {}), ...(deviceDebug ?? {}), sentAt: localTimestamp() };
|
|
7814
|
+
}
|
|
7484
7815
|
if (delivery.chatType === 'group') {
|
|
7485
7816
|
const extracted = this.extractMentionEntriesFromText(finalText);
|
|
7486
7817
|
if (extracted.length > 0)
|
|
@@ -7496,6 +7827,9 @@ export class AUNChannel {
|
|
|
7496
7827
|
payload.chatmode = context.metadata.chatmode;
|
|
7497
7828
|
if (context?.metadata?.forkAnchor)
|
|
7498
7829
|
payload.fork_anchor = context.metadata.forkAnchor;
|
|
7830
|
+
// 防 ping-pong 标记:通知对端「我被打断了」时带上,对端收到后不再回发相同通知。
|
|
7831
|
+
if (context?.metadata?.isStaleInterruptNotice)
|
|
7832
|
+
payload.is_stale_interrupt_notice = true;
|
|
7499
7833
|
if (delivery.chatType === 'private' && !delivery.service) {
|
|
7500
7834
|
Object.assign(payload, this.withCurrentTopicName(channelId, payload));
|
|
7501
7835
|
}
|
|
@@ -7717,6 +8051,36 @@ export class AUNChannel {
|
|
|
7717
8051
|
}
|
|
7718
8052
|
}
|
|
7719
8053
|
async deliverPayloadEntry(entry) {
|
|
8054
|
+
if (!entry.deliveryReceipt && entry.dedupeKey?.startsWith('template-update:')) {
|
|
8055
|
+
const notice = entry.payload?.template_update;
|
|
8056
|
+
if (!notice || entry.dedupeKey !== 'template-update:' + notice.noticeId
|
|
8057
|
+
|| typeof notice.targetAid !== 'string' || !/^[a-z0-9][a-z0-9_-]*(\.[a-z0-9-]+)+$/.test(notice.targetAid)) {
|
|
8058
|
+
return { ok: false, status: 'permanent', code: 'UPDATE_NOTICE_INVALID', error: 'Invalid durable template notice' };
|
|
8059
|
+
}
|
|
8060
|
+
const owner = await ownerResolver.refreshForAuthorization(notice.targetAid);
|
|
8061
|
+
if (owner.refreshFailure || owner.consensusStatus !== 'consensus') {
|
|
8062
|
+
return { ok: false, status: 'retry', code: 'UPDATE_OWNERSHIP_UNAVAILABLE', error: 'Current Agent Owner is unavailable' };
|
|
8063
|
+
}
|
|
8064
|
+
const { compareTemplateVersions } = await import('../agent-template/jobs.js');
|
|
8065
|
+
const config = loadAgent(notice.targetAid);
|
|
8066
|
+
if (this.config.aid !== notice.targetAid || owner.ownerAid !== entry.channelId
|
|
8067
|
+
|| !['manual', 'auto'].includes(config?.update?.mode ?? '') || !config?.version
|
|
8068
|
+
|| config.update?.key !== notice.key || config.update?.registryAid !== notice.registryAid
|
|
8069
|
+
|| compareTemplateVersions(config.version, notice.candidateVersion) >= 0) {
|
|
8070
|
+
return { ok: false, status: 'permanent', code: 'UPDATE_NOTICE_STALE', error: 'Owner, source, policy or installed version changed' };
|
|
8071
|
+
}
|
|
8072
|
+
entry.context = { ...entry.context, metadata: { ...entry.context?.metadata, encrypted: true } };
|
|
8073
|
+
}
|
|
8074
|
+
if (!entry.deliveryReceipt && entry.postSend?.type === 'register_payment_delivery') {
|
|
8075
|
+
const record = paymentStore(this.config.aid).read(entry.postSend.requestId);
|
|
8076
|
+
const binding = currentContactBinding(this.config.aid);
|
|
8077
|
+
if (!binding)
|
|
8078
|
+
return { ok: false, status: 'retry', code: 'PAYMENT_OWNERSHIP_UNAVAILABLE', error: 'Payment Owner is not currently verified' };
|
|
8079
|
+
if (!record || !sameContactBinding(record.binding, binding) || entry.channelId !== binding.owner_aid
|
|
8080
|
+
|| entry.delivery?.chatType !== 'private' || entry.payload?.thread_id !== record.threadId) {
|
|
8081
|
+
return { ok: false, status: 'permanent', code: 'PAYMENT_OWNERSHIP_CHANGED', error: 'Payment no longer belongs to this Owner conversation' };
|
|
8082
|
+
}
|
|
8083
|
+
}
|
|
7720
8084
|
if (entry.payload?.type === 'friend.request.v1' && entry.payload.direction === 'outbound') {
|
|
7721
8085
|
return { ok: false, status: 'permanent', code: 'OUTBOUND_APPROVAL_RETIRED', error: 'outbound contact approval is no longer required' };
|
|
7722
8086
|
}
|
|
@@ -7761,7 +8125,7 @@ export class AUNChannel {
|
|
|
7761
8125
|
return { ok: true, status: 'sent' };
|
|
7762
8126
|
}
|
|
7763
8127
|
}
|
|
7764
|
-
const interactionExpiresAt = entry.postSend?.type === 'register_interaction_card'
|
|
8128
|
+
const interactionExpiresAt = entry.postSend?.type === 'register_interaction_card' || entry.postSend?.type === 'register_widget_card'
|
|
7765
8129
|
? entry.postSend.expiresAt
|
|
7766
8130
|
: undefined;
|
|
7767
8131
|
if (typeof interactionExpiresAt === 'number'
|
|
@@ -8021,6 +8385,14 @@ export class AUNChannel {
|
|
|
8021
8385
|
const encrypt = context?.metadata?.encrypted != null
|
|
8022
8386
|
? !!(context.metadata.encrypted)
|
|
8023
8387
|
: this.shouldEncrypt(encryptTarget);
|
|
8388
|
+
// Attach this device's identity when the recipient is this AID's Owner or a
|
|
8389
|
+
// sibling under the same Owner. Group traffic and service replies go to
|
|
8390
|
+
// audiences that are not that relation, so they carry no device metadata.
|
|
8391
|
+
if (!isGroup && !delivery.service) {
|
|
8392
|
+
const device = this.relationshipDebug(targetAid);
|
|
8393
|
+
if (device)
|
|
8394
|
+
finalPayload.debug = { ...(finalPayload.debug ?? {}), ...device };
|
|
8395
|
+
}
|
|
8024
8396
|
if (finalPayload.thread_id === '')
|
|
8025
8397
|
delete finalPayload.thread_id;
|
|
8026
8398
|
// 主话题 id(main:<a>:<b>)是本端身份,不上线;主话题的线上形态就是不带该字段。
|
|
@@ -8035,7 +8407,13 @@ export class AUNChannel {
|
|
|
8035
8407
|
const isOutputServicePayload = delivery.chatType === 'private' && !!delivery.service
|
|
8036
8408
|
&& isProjectionServiceResult(finalPayload.type);
|
|
8037
8409
|
finalPayload = await this.withSessionState(channelId, finalPayload, context);
|
|
8038
|
-
|
|
8410
|
+
// volatile TTL 由调用方按自己的等待期给出;服务应答据此避免在调用方放弃后
|
|
8411
|
+
// 仍被当成持久消息补投一次。
|
|
8412
|
+
const ttl = typeof context?.ttl === 'number' && Number.isInteger(context.ttl)
|
|
8413
|
+
&& context.ttl >= 1 && context.ttl <= MAX_AUN_VOLATILE_TTL_SECONDS
|
|
8414
|
+
? context.ttl
|
|
8415
|
+
: undefined;
|
|
8416
|
+
const params = { payload: finalPayload, encrypt, ...(ttl !== undefined ? { ttl } : {}) };
|
|
8039
8417
|
if (!isGroup && ['menu.response', 'menu.event'].includes(finalPayload.type))
|
|
8040
8418
|
params.to_device_id = context?.toDeviceId;
|
|
8041
8419
|
if (isMenuPayload && typeof context?.metadata?.menuClientSdkVersion === 'string') {
|
|
@@ -8074,7 +8452,12 @@ export class AUNChannel {
|
|
|
8074
8452
|
logger.warn(`${this.logPrefix()} message.send (${payload.type}) returned no message_id; disposition=${failure.status}`);
|
|
8075
8453
|
return { ok: false, ...failure };
|
|
8076
8454
|
}
|
|
8077
|
-
|
|
8455
|
+
const menuRequestId = typeof finalPayload.id === 'string' ? finalPayload.id : '';
|
|
8456
|
+
const menuTargetDeviceId = menuSenderDeviceId(params.to_device_id) ?? '';
|
|
8457
|
+
const menuTransport = isMenuPayload
|
|
8458
|
+
? ` request_id=${menuRequestId || '<none>'} target_device_id=${menuTargetDeviceId || '<aid-broadcast>'}`
|
|
8459
|
+
: '';
|
|
8460
|
+
logger.info(`${this.logPrefix()} message.send (${payload.type}) ok: to=${this.peerLabel(targetAid)} mid=${mid} encrypt=${encrypt}${menuTransport}`);
|
|
8078
8461
|
// 服务回复不进 observer 镜像(回归 13)。
|
|
8079
8462
|
if (!isMenuPayload && !delivery.service)
|
|
8080
8463
|
this.forwardOutbound(result);
|
|
@@ -8223,7 +8606,7 @@ export class AUNChannel {
|
|
|
8223
8606
|
else if (result.status === 'permanent')
|
|
8224
8607
|
this.markPermanentOutboxFailure(entry, result);
|
|
8225
8608
|
}
|
|
8226
|
-
async buildUploadedImagePayload(data, mimeType, alt) {
|
|
8609
|
+
async buildUploadedImagePayload(data, mimeType, alt, channelId) {
|
|
8227
8610
|
if (!this.connected || !this.client) {
|
|
8228
8611
|
throw new Error('AUN channel is not connected; image cannot be uploaded');
|
|
8229
8612
|
}
|
|
@@ -8249,9 +8632,23 @@ export class AUNChannel {
|
|
|
8249
8632
|
const digest = crypto.createHash('sha256').update(data).digest('hex').slice(0, 12);
|
|
8250
8633
|
const filename = `image-${digest}.${extension}`;
|
|
8251
8634
|
const built = await uploadBufferAndBuildPayload(this.client, this.config.aid, data, filename, { as: 'image', contentType });
|
|
8635
|
+
// 出站图片同样归档到关系目录(与入站图片、收发文件同一落点)。
|
|
8636
|
+
const archived = channelId
|
|
8637
|
+
? this.archiveOutgoingBuffer(channelId, data, filename, contentType)
|
|
8638
|
+
: null;
|
|
8252
8639
|
const imagePayload = { ...built.payload };
|
|
8253
8640
|
setIfDefined(imagePayload, 'alt', alt);
|
|
8254
|
-
return imagePayload;
|
|
8641
|
+
return { payload: imagePayload, archived };
|
|
8642
|
+
}
|
|
8643
|
+
/** 内存中的出站附件归档(图片走这条:数据不落临时文件)。 */
|
|
8644
|
+
archiveOutgoingBuffer(channelId, data, filename, contentType) {
|
|
8645
|
+
try {
|
|
8646
|
+
return saveRelationAttachment(data, this.config.aid, formatPeerKey('aun', channelId), contentType || 'application/octet-stream', { filename, allowAnyExtension: true, direction: 'out' });
|
|
8647
|
+
}
|
|
8648
|
+
catch (error) {
|
|
8649
|
+
logger.warn(`${this.logPrefix()} Outgoing image archive failed for ${filename}: ${error instanceof Error ? error.message : String(error)}`);
|
|
8650
|
+
return null;
|
|
8651
|
+
}
|
|
8255
8652
|
}
|
|
8256
8653
|
async deliverImageEntry(entry) {
|
|
8257
8654
|
const image = entry.image;
|
|
@@ -8268,11 +8665,14 @@ export class AUNChannel {
|
|
|
8268
8665
|
return { status: 'permanent', error: 'durable image data is invalid', code: 'INVALID_IMAGE_DATA' };
|
|
8269
8666
|
}
|
|
8270
8667
|
try {
|
|
8271
|
-
const imagePayload = await this.buildUploadedImagePayload(data, image.mimeType, image.alt);
|
|
8668
|
+
const { payload: imagePayload, archived } = await this.buildUploadedImagePayload(data, image.mimeType, image.alt, entry.channelId);
|
|
8272
8669
|
entry.type = 'payload';
|
|
8273
8670
|
entry.contentKind = 'image';
|
|
8274
8671
|
entry.payload = this.applyReplyContextToPayload(imagePayload, entry.context);
|
|
8275
|
-
|
|
8672
|
+
// 图片与文件同一规则:历史里记关系目录里的归档路径。
|
|
8673
|
+
entry.logText ??= archived
|
|
8674
|
+
? formatAttachmentMarker('图片', image.alt || path.basename(archived.filePath), toAttachmentMarkedPath(this.config.aid, archived.filePath), archived.storage)
|
|
8675
|
+
: (image.alt ? `[image] ${image.alt}` : '[image]');
|
|
8276
8676
|
delete entry.image;
|
|
8277
8677
|
// Persist the attachment reference before message.send. A failed send then
|
|
8278
8678
|
// retries the compact wire payload without re-uploading the same image.
|
|
@@ -8299,6 +8699,23 @@ export class AUNChannel {
|
|
|
8299
8699
|
return failure;
|
|
8300
8700
|
}
|
|
8301
8701
|
}
|
|
8702
|
+
/**
|
|
8703
|
+
* 出站附件归档:把要发送的文件在关系目录留一份。
|
|
8704
|
+
*
|
|
8705
|
+
* 与入站同一落点(`$RELATIONS_DIR/<peerKey>/attachments/`)、同一命名规则
|
|
8706
|
+
* (原始文件名,重名 `-N`,内容相同则复用)。归档失败只记日志、不阻断发送:
|
|
8707
|
+
* 发送本身是主路径,历史可读性是附带收益。
|
|
8708
|
+
*/
|
|
8709
|
+
archiveOutgoingAttachment(channelId, absPath, contentType) {
|
|
8710
|
+
try {
|
|
8711
|
+
const buffer = fs.readFileSync(absPath);
|
|
8712
|
+
return saveRelationAttachment(buffer, this.config.aid, formatPeerKey('aun', channelId), contentType || 'application/octet-stream', { filename: path.basename(absPath), allowAnyExtension: true, direction: 'out' });
|
|
8713
|
+
}
|
|
8714
|
+
catch (error) {
|
|
8715
|
+
logger.warn(`${this.logPrefix()} Outgoing attachment archive failed for ${absPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
8716
|
+
return null;
|
|
8717
|
+
}
|
|
8718
|
+
}
|
|
8302
8719
|
async deliverFileEntry(entry) {
|
|
8303
8720
|
const channelId = entry.channelId;
|
|
8304
8721
|
if (typeof entry.filePath !== 'string' || !entry.filePath.trim()) {
|
|
@@ -8310,9 +8727,14 @@ export class AUNChannel {
|
|
|
8310
8727
|
const context = this.withDelivery(entry.context, delivery);
|
|
8311
8728
|
const isGroup = delivery.chatType === 'group';
|
|
8312
8729
|
const source = context?.metadata?.source ?? 'daemon';
|
|
8730
|
+
// 归档在两条分支之前做:回执恢复分支也要能引用归档路径。
|
|
8731
|
+
// 该调用是幂等的(同内容复用同一文件,只追加一条元数据),重复执行安全。
|
|
8732
|
+
const fileArchived = this.archiveOutgoingAttachment(channelId, absPath);
|
|
8313
8733
|
if (entry.deliveryReceipt) {
|
|
8314
8734
|
const filename = path.basename(absPath);
|
|
8315
|
-
const logText = entry.logText ??
|
|
8735
|
+
const logText = entry.logText ?? (fileArchived
|
|
8736
|
+
? formatAttachmentMarker('文件', filename, toAttachmentMarkedPath(this.config.aid, fileArchived.filePath), fileArchived.storage)
|
|
8737
|
+
: `[file] ${filename}`);
|
|
8316
8738
|
try {
|
|
8317
8739
|
this.appendOutboundJsonl(channelId, {
|
|
8318
8740
|
...classifyAunPayloadForLog({ type: 'file', text: logText }),
|
|
@@ -8338,6 +8760,8 @@ export class AUNChannel {
|
|
|
8338
8760
|
try {
|
|
8339
8761
|
const { attachment } = await uploadFileAndBuildPayload(this.client, this.config.aid, absPath, { as: 'file' });
|
|
8340
8762
|
const { filename, size_bytes: size, content_type: contentType } = attachment;
|
|
8763
|
+
// 归档已在分支之前完成(fileArchived);归档失败不阻断发送,历史里落源路径。
|
|
8764
|
+
const archived = fileArchived;
|
|
8341
8765
|
const filePayload = await this.withSessionState(channelId, buildAunFilePayload({
|
|
8342
8766
|
filename,
|
|
8343
8767
|
size,
|
|
@@ -8440,7 +8864,12 @@ export class AUNChannel {
|
|
|
8440
8864
|
const statsContext = isGroup ? await this.groupStatsContext(channelId) : undefined;
|
|
8441
8865
|
this.aidStatsCollector?.recordOutbound(this.config.aid, channelId, Buffer.byteLength(fileText, 'utf-8'), fileText, false, !!params.encrypt, context?.metadata?.chatmode, 'send', statsContext);
|
|
8442
8866
|
this.appendOutboundJsonl(channelId, {
|
|
8443
|
-
...classifyAunPayloadForLog(filePayload),
|
|
8867
|
+
...classifyAunPayloadForLog(filePayload),
|
|
8868
|
+
// 有归档副本就记归档路径;没有则在正文里补源路径,避免历史只剩文件名。
|
|
8869
|
+
...(archived
|
|
8870
|
+
? { content: formatAttachmentMarker('文件', filename, toAttachmentMarkedPath(this.config.aid, archived.filePath), archived.storage) }
|
|
8871
|
+
: { content: `[文件: ${filename} → ${absPath}]` }),
|
|
8872
|
+
msgId: sentMid, encrypt: !!params.encrypt,
|
|
8444
8873
|
context, isGroup, source, transport: this.sendReceiptFromResult(sendResult),
|
|
8445
8874
|
});
|
|
8446
8875
|
if (sendResult)
|
|
@@ -9087,10 +9516,12 @@ export class AUNChannelPlugin {
|
|
|
9087
9516
|
...(dedupeOperationId ? { operationId: dedupeOperationId } : {}),
|
|
9088
9517
|
...(payload.kind === 'result.text' && payload.metadata?.forkAnchor
|
|
9089
9518
|
? { forkAnchor: payload.metadata.forkAnchor } : {}),
|
|
9519
|
+
...(payload.kind === 'result.text' && payload.metadata?.isStaleInterruptNotice
|
|
9520
|
+
? { isStaleInterruptNotice: true } : {}),
|
|
9090
9521
|
},
|
|
9091
9522
|
};
|
|
9092
9523
|
if (payload.kind === 'result.text' && payload.isFinal && delivery.chatType === 'private') {
|
|
9093
|
-
sendCtx.title = '
|
|
9524
|
+
sendCtx.title = '最终回复:';
|
|
9094
9525
|
}
|
|
9095
9526
|
let result;
|
|
9096
9527
|
try {
|
|
@@ -9352,21 +9783,25 @@ export class AUNChannelPlugin {
|
|
|
9352
9783
|
if (req.kind.kind === 'action') {
|
|
9353
9784
|
const isAsyncQuestion = /^aq-[a-f0-9]{40}$/.test(req.id);
|
|
9354
9785
|
const action = req.kind;
|
|
9355
|
-
const aunCard =
|
|
9356
|
-
|
|
9357
|
-
|
|
9358
|
-
|
|
9359
|
-
|
|
9360
|
-
|
|
9361
|
-
|
|
9362
|
-
|
|
9363
|
-
|
|
9364
|
-
|
|
9365
|
-
|
|
9786
|
+
const aunCard = action.widget
|
|
9787
|
+
? withAunAttention(await channel.buildDaemonFilePayload({
|
|
9788
|
+
filePath: action.widget.filePath, as: 'widget_card', title: action.title, text: action.body,
|
|
9789
|
+
}))
|
|
9790
|
+
: withAunAttention({
|
|
9791
|
+
type: 'action_card',
|
|
9792
|
+
title: action.title,
|
|
9793
|
+
...(req.sensitive ? { sensitive: true } : {}),
|
|
9794
|
+
...(req.blocking === true ? { blocking: true } : {}),
|
|
9795
|
+
...(action.recommendedOption ? { recommended_option: action.recommendedOption } : {}),
|
|
9796
|
+
actions: action.buttons.map(btn => ({
|
|
9797
|
+
label: action.recommendedOption === btn.key ? `💡 ${btn.label}` : btn.label,
|
|
9798
|
+
value: btn.key, style: btn.style ?? 'default', behavior: 'reply',
|
|
9799
|
+
})),
|
|
9800
|
+
});
|
|
9366
9801
|
// AUN action_card 以 compose behavior 声明自由文本动作。新版客户端
|
|
9367
9802
|
// 在卡片内采集并确认;旧版客户端可继续从主编辑器采集。两者都结构化
|
|
9368
9803
|
// 回传 action_card_reply{behavior:"compose"},Core 不拦截普通消息队列。
|
|
9369
|
-
if (action.allowCustomInput) {
|
|
9804
|
+
if (!action.widget && action.allowCustomInput) {
|
|
9370
9805
|
aunCard.actions.push({
|
|
9371
9806
|
label: '✏️ 手动输入', style: 'default', behavior: 'compose',
|
|
9372
9807
|
...(req.sensitive ? { sensitive: true } : {}),
|
|
@@ -9377,6 +9812,10 @@ export class AUNChannelPlugin {
|
|
|
9377
9812
|
aunCard.text = action.body;
|
|
9378
9813
|
setIfDefined(aunCard, 'format', action.bodyFormat);
|
|
9379
9814
|
}
|
|
9815
|
+
if (action.widget && req.blocking === true)
|
|
9816
|
+
aunCard.blocking = true;
|
|
9817
|
+
if (action.widget && req.sensitive)
|
|
9818
|
+
aunCard.sensitive = true;
|
|
9380
9819
|
if (req.initiatorId && replyCtx?.delivery?.chatType === 'group')
|
|
9381
9820
|
aunCard.initiator = req.initiatorId;
|
|
9382
9821
|
if (isTopicThreadId(replyCtx?.threadId))
|
|
@@ -9401,6 +9840,7 @@ export class AUNChannelPlugin {
|
|
|
9401
9840
|
initiatorAid: req.initiatorId,
|
|
9402
9841
|
delivery: replyCtx?.delivery,
|
|
9403
9842
|
expiresAt: cardExpiresAt,
|
|
9843
|
+
...(action.widget ? { widget: true } : {}),
|
|
9404
9844
|
},
|
|
9405
9845
|
});
|
|
9406
9846
|
return toInteractionReceipt(result);
|
|
@@ -9470,7 +9910,46 @@ export class AUNChannelPlugin {
|
|
|
9470
9910
|
return suppressedReceipt(envelope, 'empty_interaction');
|
|
9471
9911
|
}
|
|
9472
9912
|
case 'custom': {
|
|
9473
|
-
const
|
|
9913
|
+
const customValue = payload.payload;
|
|
9914
|
+
const customObject = typeof customValue === 'string'
|
|
9915
|
+
? (() => { try {
|
|
9916
|
+
return JSON.parse(customValue);
|
|
9917
|
+
}
|
|
9918
|
+
catch {
|
|
9919
|
+
return undefined;
|
|
9920
|
+
} })()
|
|
9921
|
+
: customValue;
|
|
9922
|
+
if (customObject && typeof customObject === 'object' && !Array.isArray(customObject)
|
|
9923
|
+
&& customObject.type === 'action_card' && customObject.card_kind === 'ownership_bind_request') {
|
|
9924
|
+
const card = customObject;
|
|
9925
|
+
const send = await channel.sendContentPayload(channelId, card, {
|
|
9926
|
+
contentKind: 'card', context: replyCtx, dedupeKey: operationId,
|
|
9927
|
+
logText: '[ownership.bind action_card]',
|
|
9928
|
+
...(typeof card.expires_at_ms === 'number'
|
|
9929
|
+
? { ttl: Math.max(1, card.expires_at_ms - Date.now()) } : {}),
|
|
9930
|
+
});
|
|
9931
|
+
if (send.messageId)
|
|
9932
|
+
return sentReceipt(envelope, [send.messageId], replyCtx?.threadId);
|
|
9933
|
+
if (send.status === 'retry'
|
|
9934
|
+
|| send.status === 'queued' || send.queued) {
|
|
9935
|
+
if (!send.outboxId)
|
|
9936
|
+
return {
|
|
9937
|
+
status: 'failed', operationId, messages: [],
|
|
9938
|
+
error: 'Queued Ownership card is missing its outbox id', code: 'MISSING_OUTBOX_ID',
|
|
9939
|
+
};
|
|
9940
|
+
return { status: 'queued', operationId, messages: [], outboxId: send.outboxId,
|
|
9941
|
+
...(send.error ? { error: send.error } : {}), ...(send.code !== undefined ? { code: send.code } : {}) };
|
|
9942
|
+
}
|
|
9943
|
+
if (send.status === 'permanent' || send.status === 'failed')
|
|
9944
|
+
return {
|
|
9945
|
+
status: 'failed', operationId, messages: [],
|
|
9946
|
+
...(send.outboxId ? { outboxId: send.outboxId } : {}),
|
|
9947
|
+
error: send.error ?? 'Ownership card delivery failed',
|
|
9948
|
+
...(send.code !== undefined ? { code: send.code } : {}),
|
|
9949
|
+
};
|
|
9950
|
+
return suppressedReceipt(envelope, 'ownership_card_not_sent');
|
|
9951
|
+
}
|
|
9952
|
+
const text = typeof customValue === 'string' ? customValue : JSON.stringify(customValue);
|
|
9474
9953
|
await channel.sendCustomPayload(channelId, text, replyCtx);
|
|
9475
9954
|
return;
|
|
9476
9955
|
}
|
|
@@ -9578,6 +10057,12 @@ export class AUNChannelPlugin {
|
|
|
9578
10057
|
}, { cache: true }).mentionMode;
|
|
9579
10058
|
});
|
|
9580
10059
|
}
|
|
10060
|
+
if (typeof channel.setPrivateMentionModeResolver === 'function') {
|
|
10061
|
+
// Agent-level only: no peerKey, so a relation-level override cannot leak in.
|
|
10062
|
+
channel.setPrivateMentionModeResolver(async () => {
|
|
10063
|
+
return resolveEffective({ self: aid }, { cache: true }).privateMentionMode;
|
|
10064
|
+
});
|
|
10065
|
+
}
|
|
9581
10066
|
if (typeof channel.setGroupSlashRequireMentionsResolver === 'function') {
|
|
9582
10067
|
channel.setGroupSlashRequireMentionsResolver(async () => {
|
|
9583
10068
|
return resolveEffective({ self: aid }, { cache: true }).groupSlashRequireMentions ?? true;
|