evolcore 0.0.43-test.4 → 0.0.43-test.5
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 +46 -0
- package/bin/ecmsg.js +354 -91
- package/dist/agents/codex-runner.js +12 -17
- package/dist/aun/aid/agentmd.js +25 -0
- package/dist/aun/aid/control-aid.js +15 -0
- package/dist/aun/aid/identity.js +8 -0
- package/dist/aun/aid/ownership-operation.js +12 -3
- package/dist/channels/aun.js +30 -17
- package/dist/channels/daemon.js +2 -2
- package/dist/cli/agent-create.js +4 -2
- package/dist/cli/aid-bind-command.js +3 -0
- package/dist/cli/aun-commands.js +10 -3
- package/dist/cli/code-stats.js +451 -213
- package/dist/cli/ctl-command.js +1 -3
- package/dist/cli/daemon-commands.js +12 -3
- package/dist/cli/directory.js +3 -1
- package/dist/cli/ecmsg-gateway.js +204 -0
- package/dist/cli/index.js +6 -0
- package/dist/cli/init.js +45 -13
- package/dist/cli/provider-command.js +82 -5
- package/dist/cli/restart-monitor.js +11 -19
- package/dist/cli/stats.js +8 -1
- package/dist/cli/task-context.js +3 -0
- package/dist/config/boot-log.js +12 -1
- package/dist/config/config-manager.js +4 -13
- package/dist/config/daemon-services.js +1 -0
- package/dist/config/peer-role-resolver.js +5 -5
- package/dist/config/provider-identity-migration.js +202 -0
- package/dist/config/provider-identity.js +37 -0
- package/dist/config/provider-ipc-service.js +40 -3
- package/dist/config/provider-local-sync.js +153 -0
- package/dist/config/providers-config.js +32 -4
- package/dist/config/providers-management.js +144 -68
- package/dist/config/providers.js +4 -1
- package/dist/config/schema-migration.js +67 -3
- package/dist/core/agent-runtime.js +4 -2
- package/dist/core/auth/auth-gateway.js +5 -3
- package/dist/core/auth/delegation-diagnostics.js +6 -2
- package/dist/core/auth/operation-authorizer.js +3 -1
- package/dist/core/auth/operation-catalog.js +6 -4
- package/dist/core/command/cli-intent-parser.js +2 -1
- package/dist/core/command/command-handler.js +11 -6
- package/dist/core/command/menu-protocol.js +4 -2
- package/dist/core/command/provider-menu.js +4 -2
- package/dist/core/command/role-menu.js +2 -2
- package/dist/core/command/slash-handler.js +52 -16
- package/dist/core/handoff/runtime.js +9 -3
- package/dist/core/initialization/service.js +4 -3
- package/dist/core/message/aun-ipc-sender.js +81 -3
- package/dist/core/message/message-admission.js +2 -0
- package/dist/core/message/response-engine.js +23 -23
- package/dist/core/message/send-options.js +40 -0
- package/dist/core/message/send-routing.js +310 -0
- package/dist/core/ownership/owner-resolver.js +111 -8
- package/dist/core/permission/ec-command-parser.js +148 -15
- package/dist/core/permission/readonly-shell-query.js +66 -7
- package/dist/core/permission/tool-error-code.js +13 -1
- package/dist/core/permission/tool-policy.js +74 -20
- package/dist/core/relation/same-owner-proof.js +131 -0
- package/dist/core/session/session-idle-monitor.js +94 -16
- package/dist/core/session/session-manager.js +69 -16
- package/dist/core/thread/thread-route.js +5 -2
- package/dist/directory/owner-directory-cache.js +686 -97
- package/dist/directory/owner-directory-markdown.js +146 -36
- package/dist/directory/owner-directory-query-operation.js +2 -2
- package/dist/directory/owner-directory-scope.js +12 -0
- package/dist/directory/owner-directory-search.js +5 -1
- package/dist/directory/owner-directory-store.js +28 -0
- package/dist/ecweb/basic-settings-service.js +15 -1
- package/dist/ecweb/message-context-service.js +2 -2
- package/dist/ecweb/providers-service.js +3 -1
- package/dist/ecweb/runtime/lifecycle.js +18 -9
- package/dist/ecweb/runtime/supervisor.js +76 -24
- package/dist/index.js +4 -0
- package/dist/paths.js +2 -1
- package/dist/proxy/manager.js +2 -0
- package/dist/proxy/service-supervisor.js +2 -2
- package/dist/response-system/engines/v1/proactive-flow.js +4 -0
- package/dist/trigger/application-service.js +1 -0
- package/dist/trigger/event-source.js +4 -0
- package/dist/trigger/feedback.js +26 -2
- package/dist/trigger/scheduler.js +3 -3
- package/dist/trigger/system-definitions.js +2 -2
- package/dist/trigger/validation.js +4 -0
- package/dist/utils/autostart.js +2 -2
- package/dist/utils/cross-platform.js +36 -8
- package/dist/utils/public-suffix.js +5811 -0
- package/dist/utils/windows-autostart.js +41 -7
- package/ecagent/dist/harness/env/nodejs.js +46 -2
- package/kits/docs/aun/ABILITY_CALLING.md +3 -3
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/channels/feishu.md +2 -2
- package/kits/docs/context-assembly.md +20 -4
- package/kits/docs/evolcore/INDEX.md +2 -1
- package/kits/docs/evolcore/agent.md +2 -2
- package/kits/docs/evolcore/aid.md +8 -2
- package/kits/docs/evolcore/ctl.md +13 -4
- package/kits/docs/evolcore/directory.md +48 -15
- package/kits/docs/evolcore/group.md +6 -6
- package/kits/docs/evolcore/memory-consolidation.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +32 -3
- package/kits/docs/evolcore/msg.md +28 -27
- package/kits/docs/evolcore/provider.md +39 -5
- package/kits/docs/evolcore/response.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +11 -13
- package/kits/docs/evolcore/tool-authorization.md +17 -0
- package/kits/docs/evolcore/trigger.md +2 -2
- package/kits/docs/identity/ROLE_DETAIL.md +1 -1
- package/kits/docs/prompt-loading-architecture.md +30 -20
- package/kits/eck_manifest.auxiliary.json +5 -5
- package/kits/eck_manifest.json +28 -28
- package/kits/eck_manifest.memory.json +18 -18
- package/kits/rules/01-overview.md +1 -1
- package/kits/rules/06-channel.md +3 -3
- package/kits/schemas/_meta.json +7 -1
- package/kits/schemas/providers.schema.2.json +74 -0
- package/kits/schemas/role-registry.schema.1.json +1 -1
- package/kits/skills/ec-agent-create/SKILL.md +1 -0
- package/kits/skills/ec-service-proxy/SKILL.md +3 -10
- package/kits/skills/ec-trigger/SKILL.md +5 -5
- package/kits/skills/ec-trigger/references/examples.md +1 -1
- package/kits/templates/system-fragments/channel.md +5 -5
- package/kits/templates/system-fragments/commands.md +3 -2
- package/kits/templates/system-fragments/directory-contacts.md +10 -3
- package/kits/templates/system-fragments/personal-assistant.md +22 -3
- package/kits/templates/system-fragments/reply.md +47 -28
- package/kits/templates/system-fragments/session.md +2 -9
- package/kits/templates/system-fragments/thread.md +5 -5
- package/package.json +2 -3
|
@@ -10,7 +10,7 @@ import { loadedBaseagentIds } from '../../agents/baseagent-availability.js';
|
|
|
10
10
|
import { isDiagnosticSessionActive } from '../command/diag-service.js';
|
|
11
11
|
import { evaluateInboundAdmissionPreflight, evaluateOrdinaryInboundAdmission } from './message-admission.js';
|
|
12
12
|
import { authorizeAccess, authorizeOperation, buildAuthSubject } from '../auth/auth-gateway.js';
|
|
13
|
-
import {
|
|
13
|
+
import { prepareSameOwnerProof, sameOwnerQualification, requiresSameOwnerProof } from '../relation/same-owner-proof.js';
|
|
14
14
|
import { getRoleDefinition } from '../../config/roles.js';
|
|
15
15
|
import { buildTaskRuntimeEnv, ensureRuntimeLockDir, ensureSessionRuntimeDir } from '../../cli/task-context.js';
|
|
16
16
|
import { BUILTIN_SESSION_PATH_GRANTS, mergeRuntimeGrantsForSession, resolveGrantedReadRoots, } from '../permission/session-path-grants.js';
|
|
@@ -28,7 +28,7 @@ import { logger } from '../../utils/logger.js';
|
|
|
28
28
|
import { isHostChinese } from '../../utils/locale.js';
|
|
29
29
|
import { ExecutionTimeoutError, OrphanedTargetSessionError, UnattendedInputRequiredError, isExecutionFailure, getErrorMessage, getErrorRawText, getToolResultErrorText, classifyError, normalizeCoreErrorReason, normalizeCoreErrorSubtype, ErrorType, ERROR_PREFIX, isInfraError, isAbortTerminalReason, prefixErrorType, isRetryableError, isContextTooLongText, isPolicyRejectedError } from '../../utils/error-utils.js';
|
|
30
30
|
import { readEvolcoreRuntimeFlavor, tagErrorTextWithEvolcoreVersion } from '../../utils/evolcore-version.js';
|
|
31
|
-
import { describeProactiveSendCommandFailure, isExactEvolcoreSendCommandForSession, isThreadRoutedEvolcoreSendCommand, parseCodexToolCommand, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from '../permission/ec-command-parser.js';
|
|
31
|
+
import { describeProactiveSendCommandFailure, isExactEvolcoreSendCommandForSession, isReadOnlyEcCommand, isThreadRoutedEvolcoreSendCommand, parseCodexToolCommand, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from '../permission/ec-command-parser.js';
|
|
32
32
|
import { resolveThreadRouteTarget } from '../thread/thread-route.js';
|
|
33
33
|
import { isMainSession, isTopicSession, isTopicThreadId, sessionLocalTopicId, sessionTopicThreadId } from '../thread/topic-id.js';
|
|
34
34
|
import { summarizeToolInputForDisplay, toolInputForDisplay } from '../../utils/tool-summary.js';
|
|
@@ -1087,21 +1087,16 @@ function wasRetryInputAlreadySubmitted(error) {
|
|
|
1087
1087
|
return !!(error && typeof error === 'object' && error[RETRY_INPUT_ALREADY_SUBMITTED_MARK] === true);
|
|
1088
1088
|
}
|
|
1089
1089
|
function formatRetryInputAlreadySubmittedMessage(error) {
|
|
1090
|
-
const raw = getErrorRawText(error);
|
|
1091
1090
|
const record = error && typeof error === 'object' ? error : undefined;
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
const statusCode = raw?.match(/\b([45]\d{2})\b/)?.[1];
|
|
1095
|
-
if (retryCount !== undefined && statusCode) {
|
|
1096
|
-
return `⚠️ Codex 已重连 ${retryCount} 次模型服务后仍失败(${statusCode})。本次执行已停止。`;
|
|
1097
|
-
}
|
|
1098
|
-
if (retryCount !== undefined) {
|
|
1099
|
-
return `⚠️ Codex 已重连 ${retryCount} 次模型服务后仍失败。本次执行已停止。`;
|
|
1091
|
+
if (record?.codexExecutionOutcome !== 'failed') {
|
|
1092
|
+
return '⚠️ 本轮执行已中断,暂无法确认执行结果。为避免重复执行,系统未重新提交输入。';
|
|
1100
1093
|
}
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1094
|
+
const retryCount = typeof record.codexRetryCount === 'number'
|
|
1095
|
+
&& Number.isSafeInteger(record.codexRetryCount)
|
|
1096
|
+
&& record.codexRetryCount > 0
|
|
1097
|
+
? record.codexRetryCount : undefined;
|
|
1098
|
+
const message = '⚠️ 模型服务请求失败,本次执行已停止。';
|
|
1099
|
+
return retryCount === undefined ? message : `${message}Codex 已重连 ${retryCount} 次。`;
|
|
1105
1100
|
}
|
|
1106
1101
|
function isNonErrorInterruptReason(reason) {
|
|
1107
1102
|
return reason === 'new_message'
|
|
@@ -3027,15 +3022,15 @@ export class ResponseEngine {
|
|
|
3027
3022
|
const selfAidForAccess = accessAdapterSelfAid || message.selfAID || session.selfAID || undefined;
|
|
3028
3023
|
if (message.source === 'trigger' && message.triggerMeta?.originChannelType === 'aun'
|
|
3029
3024
|
&& message.triggerMeta.originChatType !== 'group') {
|
|
3030
|
-
await
|
|
3025
|
+
await prepareSameOwnerProof(selfAidForAccess, message.triggerMeta.originPeerId);
|
|
3031
3026
|
}
|
|
3032
3027
|
if (message.source === 'handoff' && message.handoffDelivery?.direction === 'origin'
|
|
3033
3028
|
&& message.handoffDelivery.originAuthorization?.channelType === 'aun'
|
|
3034
3029
|
&& message.handoffDelivery.originAuthorization.chatType === 'private') {
|
|
3035
|
-
await
|
|
3030
|
+
await prepareSameOwnerProof(selfAidForAccess, message.handoffDelivery.originAuthorization.actorId);
|
|
3036
3031
|
}
|
|
3037
3032
|
if ((message.channelType || accessChannelKey.split('#')[0]) === 'aun' && message.chatType !== 'group') {
|
|
3038
|
-
await
|
|
3033
|
+
await prepareSameOwnerProof(selfAidForAccess, message.peerId);
|
|
3039
3034
|
}
|
|
3040
3035
|
await refreshOwnershipForAuthorization(selfAidForAccess, {
|
|
3041
3036
|
maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS,
|
|
@@ -3664,12 +3659,12 @@ export class ResponseEngine {
|
|
|
3664
3659
|
const peerIdRaw = message.peerId;
|
|
3665
3660
|
if (message.source === 'trigger' && message.triggerMeta?.originChannelType === 'aun'
|
|
3666
3661
|
&& message.triggerMeta.originChatType !== 'group') {
|
|
3667
|
-
await
|
|
3662
|
+
await prepareSameOwnerProof(selfAid, message.triggerMeta.originPeerId);
|
|
3668
3663
|
}
|
|
3669
3664
|
if (message.handoffDelivery?.direction === 'origin'
|
|
3670
3665
|
&& message.handoffDelivery.originAuthorization?.channelType === 'aun'
|
|
3671
3666
|
&& message.handoffDelivery.originAuthorization.chatType === 'private') {
|
|
3672
|
-
await
|
|
3667
|
+
await prepareSameOwnerProof(selfAid, message.handoffDelivery.originAuthorization.actorId);
|
|
3673
3668
|
}
|
|
3674
3669
|
const triggerExecutionIdentity = this.resolveTriggerExecutionIdentity(message, selfAid);
|
|
3675
3670
|
const authorizationIdentity = triggerExecutionIdentity
|
|
@@ -3694,7 +3689,7 @@ export class ResponseEngine {
|
|
|
3694
3689
|
: undefined);
|
|
3695
3690
|
const peerType = message.peerType ?? session.metadata?.peerType;
|
|
3696
3691
|
if (configChannelType === 'aun' && configChatType === 'private') {
|
|
3697
|
-
await
|
|
3692
|
+
await prepareSameOwnerProof(selfAid, configActorId);
|
|
3698
3693
|
}
|
|
3699
3694
|
const peerRoleDetail = authorizationIdentity ? undefined : (() => {
|
|
3700
3695
|
try {
|
|
@@ -3871,6 +3866,8 @@ export class ResponseEngine {
|
|
|
3871
3866
|
: undefined,
|
|
3872
3867
|
previousTurnState: this.turnCoordinator.current(session),
|
|
3873
3868
|
isSendCommand: (toolName, toolInput) => isExactEvolcoreSendCommandForSession(toolName, toolInput, session.channelId, chatType, selfAid) || isThreadRoutedSendForSelf(toolName, toolInput, selfAid),
|
|
3869
|
+
// 只读命令(--help / 查询类)不参与意图表达门禁,避免"查语法"被判违规。
|
|
3870
|
+
isReadOnlyCommand: (toolName, toolInput) => isReadOnlyEcCommand(toolName, toolInput),
|
|
3874
3871
|
describeSendCommandFailure: (toolName, toolInput) => describeProactiveSendCommandFailure(toolName, toolInput, {
|
|
3875
3872
|
selfAid,
|
|
3876
3873
|
channelId: session.channelId,
|
|
@@ -4642,8 +4639,8 @@ export class ResponseEngine {
|
|
|
4642
4639
|
// 系统会话没有角色
|
|
4643
4640
|
role: systemSessionMarker ? undefined : peerRole,
|
|
4644
4641
|
internalContactAuthorization: !systemSessionMarker && configChannelType === 'aun' && configChatType === 'private'
|
|
4645
|
-
&& !!selfAid && !!configActorId && (
|
|
4646
|
-
||
|
|
4642
|
+
&& !!selfAid && !!configActorId && (sameOwnerQualification(selfAid, configActorId) === 'matched'
|
|
4643
|
+
|| requiresSameOwnerProof(selfAid, configActorId)),
|
|
4647
4644
|
internalContactDefaultRole: peerRoleDetail?.source === 'internal-contact-default'
|
|
4648
4645
|
|| (authorizationIdentity?.role === peerRole && configChannelType === 'aun'
|
|
4649
4646
|
&& configChatType === 'private' && !!selfAid && !!configActorId
|
|
@@ -5718,6 +5715,9 @@ export class ResponseEngine {
|
|
|
5718
5715
|
} : {}),
|
|
5719
5716
|
daemonRuntimeEpoch: this.agentDelegationRegistry?.getRuntimeEpoch(),
|
|
5720
5717
|
threadId: sessionTopicThreadId(session),
|
|
5718
|
+
// 仅观测:入站消息的加密状态,供 ecmsg 的 --encrypt auto 沿用。
|
|
5719
|
+
...(message.replyContext?.metadata?.encrypted != null
|
|
5720
|
+
? { inboundEncrypted: !!(message.replyContext.metadata.encrypted) } : {}),
|
|
5721
5721
|
sessionRuntimeDir,
|
|
5722
5722
|
runtimeLockDir: ensureRuntimeLockDir(sessionRuntimeDir),
|
|
5723
5723
|
handoffIds: v2HandoffIds.length > 0 && v2HandoffDirection === 'target' ? v2HandoffIds : undefined,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 托管发送的选项表——**唯一事实源**。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成一个模块:这些选项原本在 `aun-commands.ts` 的 `resolveManagedSendArgv`
|
|
5
|
+
* 里内联定义,`ecmsg` 网关又维护了一份自己的表。两份表一旦漂移,就会出现
|
|
6
|
+
* "某个参数在一边能过、在另一边被当成正文"的静默错误。
|
|
7
|
+
*
|
|
8
|
+
* 本模块无任何依赖,`ecmsg` 可以安全引用(它刻意避免加载 aun-commands 那套重模块)。
|
|
9
|
+
*/
|
|
10
|
+
/** 取一个值的选项(`ec msg|group send` 的权威列表)。 */
|
|
11
|
+
export const MANAGED_SEND_VALUE_FLAGS = [
|
|
12
|
+
'--format', '--file', '--payload', '--payload-file', '--text-from-file',
|
|
13
|
+
'--link', '--title', '--description', '--as', '--content-type', '--text',
|
|
14
|
+
'--transcript', '--thread', '--check-every', '--trigger-prompt',
|
|
15
|
+
'--return', '--timeout', '--handoff-context', '--mention', '--self', '--device-id',
|
|
16
|
+
];
|
|
17
|
+
/** 布尔选项。 */
|
|
18
|
+
export const MANAGED_SEND_BOOLEAN_FLAGS = [
|
|
19
|
+
'--encrypt', '--no-encrypt', '--mention-all',
|
|
20
|
+
];
|
|
21
|
+
/**
|
|
22
|
+
* 网关自己消费、不向下游透传的选项。
|
|
23
|
+
*
|
|
24
|
+
* 注意 `--encrypt` / `--no-encrypt` 在网关侧语义不同:网关接受
|
|
25
|
+
* `--encrypt yes|no|auto`(三态),解析后向下游下发二态。
|
|
26
|
+
*/
|
|
27
|
+
export const GATEWAY_ROUTE_VALUE_FLAGS = [
|
|
28
|
+
'--thread', '--to', '--from', '--check-every', '--encrypt', '--format',
|
|
29
|
+
];
|
|
30
|
+
/** 只有网关认识、`ec msg send` 不认识的选项。 */
|
|
31
|
+
export const GATEWAY_ONLY_VALUE_FLAGS = ['--to', '--from'];
|
|
32
|
+
/** 网关的别名映射:`--self` 与 `--from` 等价(托管发送里本端恒为会话本端)。 */
|
|
33
|
+
export const GATEWAY_FLAG_ALIASES = {
|
|
34
|
+
'--self': '--from',
|
|
35
|
+
};
|
|
36
|
+
/** 下游允许的选项总数,用于漂移自检。 */
|
|
37
|
+
export const MANAGED_SEND_KNOWN_FLAGS = [
|
|
38
|
+
...MANAGED_SEND_VALUE_FLAGS,
|
|
39
|
+
...MANAGED_SEND_BOOLEAN_FLAGS,
|
|
40
|
+
];
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 统一发送路由 —— 目标三元组解析(纯函数)
|
|
3
|
+
*
|
|
4
|
+
* 设计依据:`docs/send-routing/unified-send-routing-plan.md`
|
|
5
|
+
*
|
|
6
|
+
* 本模块只做**判定**,不做任何 IO:
|
|
7
|
+
* - 话题索引查询由调用方通过 `resolveThread` 注入
|
|
8
|
+
* - `--to` 的渠道/类型解析由调用方通过 `resolveTarget` 注入
|
|
9
|
+
* - 群 AID 的精确归一由调用方通过 `normalizeGroupId` 注入
|
|
10
|
+
*
|
|
11
|
+
* 之所以抽成纯函数:CLI(ecmsg 网关)、daemon(发送通道)、门禁(意图表达判定)
|
|
12
|
+
* 三处必须用**同一份**判定逻辑。历史上"文档一套、代码一套"的分裂正是在这里产生的。
|
|
13
|
+
*
|
|
14
|
+
* 核心不变量:
|
|
15
|
+
* I2 本端恒等于当前会话本端;`from` 出现且不等 → 立即失败
|
|
16
|
+
* I3 目标由 (self, peer, threadId) 唯一确定
|
|
17
|
+
* I4 跨话题 ⇔ threadId 不同 或 peer 不同
|
|
18
|
+
* I5 跨话题必有复查周期(缺省补默认);同话题永不建复查
|
|
19
|
+
* I6 加密默认 auto;只有目标对端是 AUN 时才能加密
|
|
20
|
+
*/
|
|
21
|
+
import { canonicalizeMainTopicId, formatMainTopicId, isMainTopicId, mainTopicPeer, normalizeTopicAid, } from '../thread/topic-id.js';
|
|
22
|
+
// ── 常量 ────────────────────────────────────────────────────────────────
|
|
23
|
+
/** 跨话题缺省复查周期(plan 假设 A1)。改这里即可调整全局节奏。 */
|
|
24
|
+
export const DEFAULT_CROSS_TOPIC_CHECK_EVERY = '20m';
|
|
25
|
+
export const DEFAULT_CROSS_TOPIC_CHECK_EVERY_MS = 20 * 60_000;
|
|
26
|
+
/**
|
|
27
|
+
* 话题 id 形态:`thread-<ms>-<4位序号>-<4位hex>`。
|
|
28
|
+
*
|
|
29
|
+
* 与 `thread-service.ts` 的 THREAD_ID_RE 保持一致(那个常量未导出,且该模块
|
|
30
|
+
* 依赖 fs,不能被纯函数引用)。两侧改动必须同步。
|
|
31
|
+
*/
|
|
32
|
+
const THREAD_TOPIC_ID_RE = /^thread-[0-9]+-[0-9a-f]{4}-[0-9a-f]{4}$/;
|
|
33
|
+
/** 时长语法:`<正整数><d|h|m|s>`。与 trigger/parser.ts 的 parseDuration 同口径。 */
|
|
34
|
+
const DURATION_RE = /^([1-9]\d*)([dhms])$/;
|
|
35
|
+
// ── 基础工具 ────────────────────────────────────────────────────────────
|
|
36
|
+
/** 解析时长;格式非法返回 null。 */
|
|
37
|
+
export function parseDurationToMs(value) {
|
|
38
|
+
const match = DURATION_RE.exec(String(value ?? '').trim().toLowerCase());
|
|
39
|
+
if (!match)
|
|
40
|
+
return null;
|
|
41
|
+
const amount = Number(match[1]);
|
|
42
|
+
const unit = match[2];
|
|
43
|
+
const multiplier = unit === 'd' ? 86_400_000
|
|
44
|
+
: unit === 'h' ? 3_600_000
|
|
45
|
+
: unit === 'm' ? 60_000 : 1_000;
|
|
46
|
+
return amount * multiplier;
|
|
47
|
+
}
|
|
48
|
+
/** 是否为独立话题 id(`thread-…`)。 */
|
|
49
|
+
export function isThreadTopicId(value) {
|
|
50
|
+
return typeof value === 'string' && THREAD_TOPIC_ID_RE.test(value);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* 对端等值判定的规范形态。
|
|
54
|
+
*
|
|
55
|
+
* - AUN 私聊:去 `@`、转小写(AID 大小写不敏感)
|
|
56
|
+
* - AUN 群:去 `@`、转小写,并可经 `normalizeGroupId` 处理 base 简写
|
|
57
|
+
* - 非 AUN:仅 trim,**保持大小写**(`ou_xxx` 一类原生 ID 大小写敏感)
|
|
58
|
+
*/
|
|
59
|
+
export function canonicalPeerKey(peer, deps = {}) {
|
|
60
|
+
const isAun = peer.channelType === 'aun';
|
|
61
|
+
let id = isAun
|
|
62
|
+
? normalizeTopicAid(peer.id).toLowerCase()
|
|
63
|
+
: String(peer.id ?? '').trim();
|
|
64
|
+
if (isAun && peer.peerKind === 'group' && deps.normalizeGroupId) {
|
|
65
|
+
id = deps.normalizeGroupId(id);
|
|
66
|
+
}
|
|
67
|
+
return `${peer.channelType}|${peer.peerKind}|${id}`;
|
|
68
|
+
}
|
|
69
|
+
/** 两个对端是否指向同一目标。必须带 peerKind 与 channelType,否则不算同一个。 */
|
|
70
|
+
export function sameRoutePeer(a, b, deps = {}) {
|
|
71
|
+
return canonicalPeerKey(a, deps) === canonicalPeerKey(b, deps);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 当前会话的规范话题标识。
|
|
75
|
+
*
|
|
76
|
+
* 独立话题直接用它自己的 id;主会话用 `main:<self>:<peer>`(字典序规范形态)。
|
|
77
|
+
* 非 AUN 的原生 ID 拼不出主话题 id,此时返回空串,语义是"该渠道的主会话"。
|
|
78
|
+
*/
|
|
79
|
+
export function currentTopicThreadId(session) {
|
|
80
|
+
if (session.threadId)
|
|
81
|
+
return session.threadId;
|
|
82
|
+
try {
|
|
83
|
+
return formatMainTopicId(session.selfAid, session.peerId);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return '';
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* 解析 `--thread`,只接受两种形态:`thread-…` 与 `main:<a>:<b>`。
|
|
91
|
+
*
|
|
92
|
+
* 明确拒绝:裸 `main`、`<peer>/main`、`<peer>/<id>`、裸对端 AID、`current`。
|
|
93
|
+
* 裸对端 AID 虽然能被 `resolveThreadRef` 宽松展开成主话题,但那是历史写法;
|
|
94
|
+
* 网关要求参数形态与实际语义一一对应,避免"看起来像对端其实是话题"的歧义。
|
|
95
|
+
*/
|
|
96
|
+
function resolveThreadOption(raw, self, deps) {
|
|
97
|
+
const value = String(raw ?? '').trim();
|
|
98
|
+
const hint = (example) => `当前是回复本会话,可直接省略;指定话题请写 ${example}`;
|
|
99
|
+
if (!value) {
|
|
100
|
+
return fail('INVALID_THREAD_REF', '--thread 不能为空', hint('thread-… 或 main:<aidA>:<aidB>'));
|
|
101
|
+
}
|
|
102
|
+
if (value === 'current') {
|
|
103
|
+
return fail('INVALID_THREAD_REF', '--thread 不接受 current', '回复当前会话请直接省略 --thread');
|
|
104
|
+
}
|
|
105
|
+
if (isMainTopicId(value)) {
|
|
106
|
+
const peerId = mainTopicPeer(value, self);
|
|
107
|
+
if (!peerId) {
|
|
108
|
+
return fail('IDENTITY_MISMATCH', `主话题 ${value} 不属于当前本端 ${self}——主话题 id 由本端与对端共同构成`);
|
|
109
|
+
}
|
|
110
|
+
const threadId = canonicalizeMainTopicId(value) ?? value;
|
|
111
|
+
return { peer: { channelType: 'aun', peerKind: 'private', id: peerId }, threadId };
|
|
112
|
+
}
|
|
113
|
+
if (isThreadTopicId(value)) {
|
|
114
|
+
const info = deps.resolveThread?.(value);
|
|
115
|
+
if (!info) {
|
|
116
|
+
return fail('TOPIC_NOT_FOUND', `话题 ${value} 不存在于本端索引`, '用 ec thread list <对端AID> 查看可用话题');
|
|
117
|
+
}
|
|
118
|
+
if (normalizeTopicAid(info.selfAid) !== normalizeTopicAid(self)) {
|
|
119
|
+
return fail('IDENTITY_MISMATCH', `话题 ${value} 的本端是 ${info.selfAid},不是当前会话本端 ${self}`);
|
|
120
|
+
}
|
|
121
|
+
return { peer: info.peer, threadId: value };
|
|
122
|
+
}
|
|
123
|
+
return fail('INVALID_THREAD_REF', `--thread 只接受 thread-… 或 main:<aidA>:<aidB>,收到 "${value}"`, '裸对端 AID 不是话题 id;要指定对端请用 --to');
|
|
124
|
+
}
|
|
125
|
+
function fail(code, message, hint) {
|
|
126
|
+
return { ok: false, code, message, ...(hint ? { hint } : {}) };
|
|
127
|
+
}
|
|
128
|
+
// ── 主流程 ──────────────────────────────────────────────────────────────
|
|
129
|
+
/**
|
|
130
|
+
* 解析一次发送的目标三元组与派生约束。
|
|
131
|
+
*
|
|
132
|
+
* 判定顺序(与 plan 4.3 一致,失败即返回,异常均在发送前产生):
|
|
133
|
+
* 1. from 身份校验
|
|
134
|
+
* 2. --thread 形态与归属校验
|
|
135
|
+
* 3. --thread 与 --to 冲突校验
|
|
136
|
+
* 4. 跨话题判定
|
|
137
|
+
* 5. 复查周期
|
|
138
|
+
* 6. 加密模式
|
|
139
|
+
*/
|
|
140
|
+
export function resolveSendRoute(input, session, deps = {}) {
|
|
141
|
+
const self = normalizeTopicAid(session.selfAid);
|
|
142
|
+
if (!self) {
|
|
143
|
+
return fail('IDENTITY_MISMATCH', '当前会话本端未知,无法确定发送者');
|
|
144
|
+
}
|
|
145
|
+
// 1. from 只允许等于会话本端
|
|
146
|
+
if (input.from !== undefined) {
|
|
147
|
+
const from = normalizeTopicAid(input.from);
|
|
148
|
+
if (from !== self) {
|
|
149
|
+
return fail('IDENTITY_MISMATCH', `from 必须是当前会话本端 ${self},收到 ${input.from}`, '托管会话里 from 恒等于本端,通常不需要写;若要联系其他对象请用 --to');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const currentPeer = {
|
|
153
|
+
channelType: session.channelType,
|
|
154
|
+
peerKind: session.chatType,
|
|
155
|
+
id: session.peerId,
|
|
156
|
+
};
|
|
157
|
+
const currentThread = currentTopicThreadId(session);
|
|
158
|
+
// 2. 目标解析:--thread > --to > 当前会话
|
|
159
|
+
let peer;
|
|
160
|
+
let threadId;
|
|
161
|
+
let source;
|
|
162
|
+
if (input.thread !== undefined) {
|
|
163
|
+
const resolved = resolveThreadOption(input.thread, self, deps);
|
|
164
|
+
if ('ok' in resolved)
|
|
165
|
+
return resolved;
|
|
166
|
+
peer = resolved.peer;
|
|
167
|
+
threadId = resolved.threadId;
|
|
168
|
+
source = { peer: 'thread', thread: 'thread' };
|
|
169
|
+
}
|
|
170
|
+
else if (input.to !== undefined) {
|
|
171
|
+
const targetId = String(input.to ?? '').trim();
|
|
172
|
+
if (!targetId) {
|
|
173
|
+
return fail('INVALID_ARGUMENT', '--to 不能为空', '省略 --to 表示发给当前会话对端');
|
|
174
|
+
}
|
|
175
|
+
const resolvedPeer = deps.resolveTarget?.(targetId) ?? {
|
|
176
|
+
channelType: session.channelType,
|
|
177
|
+
peerKind: session.chatType,
|
|
178
|
+
id: targetId,
|
|
179
|
+
};
|
|
180
|
+
if (!resolvedPeer.id) {
|
|
181
|
+
return fail('TARGET_UNRESOLVED', `无法解析 --to ${targetId}`);
|
|
182
|
+
}
|
|
183
|
+
peer = resolvedPeer;
|
|
184
|
+
const samePeer = sameRoutePeer(peer, currentPeer, deps);
|
|
185
|
+
if (samePeer) {
|
|
186
|
+
threadId = currentThread;
|
|
187
|
+
source = { peer: 'to', thread: 'session' };
|
|
188
|
+
}
|
|
189
|
+
else {
|
|
190
|
+
const derived = deriveMainTopicId(self, peer);
|
|
191
|
+
if (derived === undefined) {
|
|
192
|
+
return fail('TOPIC_REQUIRED', `--to ${targetId} 与当前对端不同,且该渠道的原生 ID 无法构成主话题`, '跨渠道发送请显式指定 --thread <话题id>(先用 ec thread list 查看或创建)');
|
|
193
|
+
}
|
|
194
|
+
threadId = derived;
|
|
195
|
+
source = { peer: 'to', thread: 'derived' };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
peer = currentPeer;
|
|
200
|
+
threadId = currentThread;
|
|
201
|
+
source = { peer: 'session', thread: 'session' };
|
|
202
|
+
}
|
|
203
|
+
// 3. --thread 与 --to 同时给出:对端必须一致
|
|
204
|
+
if (input.thread !== undefined && input.to !== undefined) {
|
|
205
|
+
const targetId = String(input.to ?? '').trim();
|
|
206
|
+
const explicitPeer = deps.resolveTarget?.(targetId) ?? {
|
|
207
|
+
channelType: session.channelType,
|
|
208
|
+
peerKind: session.chatType,
|
|
209
|
+
id: targetId,
|
|
210
|
+
};
|
|
211
|
+
if (!sameRoutePeer(explicitPeer, peer, deps)) {
|
|
212
|
+
return fail('TOPIC_CONFLICT', `--thread 指向 ${peer.id},--to 指向 ${explicitPeer.id},两者冲突`, '一次发送只能有一个目标:保留 --thread 或 --to 其中之一');
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// 4. 跨话题判定
|
|
216
|
+
const crossTopic = !sameRoutePeer(peer, currentPeer, deps) || threadId !== currentThread;
|
|
217
|
+
// 5. 复查周期
|
|
218
|
+
let checkEveryMs;
|
|
219
|
+
let checkEveryDefaulted = false;
|
|
220
|
+
let checkEveryIgnored = false;
|
|
221
|
+
if (crossTopic) {
|
|
222
|
+
if (input.checkEvery === undefined) {
|
|
223
|
+
checkEveryMs = DEFAULT_CROSS_TOPIC_CHECK_EVERY_MS;
|
|
224
|
+
checkEveryDefaulted = true;
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
const parsed = parseDurationToMs(input.checkEvery);
|
|
228
|
+
if (parsed === null) {
|
|
229
|
+
return fail('INVALID_ARGUMENT', `--check-every 时长非法:${input.checkEvery}`, '合法格式:5m、30m、2h、1d');
|
|
230
|
+
}
|
|
231
|
+
checkEveryMs = parsed;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
else if (input.checkEvery !== undefined) {
|
|
235
|
+
// 同话题永不建复查:忽略而不是失败,回执里说明
|
|
236
|
+
checkEveryIgnored = true;
|
|
237
|
+
}
|
|
238
|
+
// 6. 加密
|
|
239
|
+
let encrypt = 'auto';
|
|
240
|
+
if (input.noEncrypt === true && input.encrypt !== undefined && input.encrypt !== 'no') {
|
|
241
|
+
return fail('INVALID_ARGUMENT', '--no-encrypt 与 --encrypt 互斥');
|
|
242
|
+
}
|
|
243
|
+
if (input.noEncrypt === true)
|
|
244
|
+
encrypt = 'no';
|
|
245
|
+
else if (input.encrypt !== undefined) {
|
|
246
|
+
if (!['yes', 'no', 'auto'].includes(input.encrypt)) {
|
|
247
|
+
return fail('INVALID_ARGUMENT', `--encrypt 只接受 yes|no|auto,收到 ${input.encrypt}`);
|
|
248
|
+
}
|
|
249
|
+
encrypt = input.encrypt;
|
|
250
|
+
}
|
|
251
|
+
if (peer.channelType !== 'aun' && encrypt === 'yes') {
|
|
252
|
+
return fail('ENCRYPT_UNSUPPORTED', `目标对端 ${peer.id} 不在 AUN 网络上(channel=${peer.channelType}),无法端到端加密`, '去掉 --encrypt 或改用 --encrypt no');
|
|
253
|
+
}
|
|
254
|
+
const encryptResolved = encrypt === 'auto' && peer.channelType === 'aun'
|
|
255
|
+
? (input.inboundTriggered === true ? input.inboundEncrypted === true : false)
|
|
256
|
+
: encrypt === 'yes';
|
|
257
|
+
return {
|
|
258
|
+
ok: true,
|
|
259
|
+
self,
|
|
260
|
+
peer,
|
|
261
|
+
threadId,
|
|
262
|
+
crossTopic,
|
|
263
|
+
...(checkEveryMs !== undefined ? { checkEveryMs } : {}),
|
|
264
|
+
checkEveryDefaulted,
|
|
265
|
+
checkEveryIgnored,
|
|
266
|
+
encrypt,
|
|
267
|
+
encryptResolved,
|
|
268
|
+
source,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* 由 (本端, 对端) 推导主话题 id。
|
|
273
|
+
*
|
|
274
|
+
* 只有能构成合法 AID 段时才返回;非 AUN 原生 ID(`ou_xxx`)返回 undefined,
|
|
275
|
+
* 由调用方要求显式 `--thread`。
|
|
276
|
+
*/
|
|
277
|
+
function deriveMainTopicId(self, peer) {
|
|
278
|
+
try {
|
|
279
|
+
return formatMainTopicId(self, peer.id);
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
// 非 AUN 原生 ID(`ou_xxx` / `wxid_xxx`)不是合法 AID 段,拼不出主话题。
|
|
283
|
+
// 这类目标必须显式给 --thread。
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
// ── 回执渲染 ────────────────────────────────────────────────────────────
|
|
288
|
+
/** 来源标注:让调用方分辨哪些值是系统补的。 */
|
|
289
|
+
function sourceLabel(source, field) {
|
|
290
|
+
const value = field === 'peer' ? source.peer : source.thread;
|
|
291
|
+
return value === 'session' ? '会话'
|
|
292
|
+
: value === 'thread' ? '传入'
|
|
293
|
+
: value === 'to' ? '传入'
|
|
294
|
+
: value === 'derived' ? '推导' : value;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* 回执里的路由前缀(plan 9.1)。
|
|
298
|
+
*
|
|
299
|
+
* 格式:`from=<self> to=<id>(<来源>) thread=<threadId>(<来源>) chatType=<kind>`
|
|
300
|
+
* 推断补全的值标来源,全部为归一化后的实际生效值,不是输入原文。
|
|
301
|
+
*/
|
|
302
|
+
export function formatRouteReceipt(route) {
|
|
303
|
+
const threadLabel = route.threadId ? route.threadId : 'main';
|
|
304
|
+
return [
|
|
305
|
+
`from=${route.self}`,
|
|
306
|
+
`to=${route.peer.id}(${sourceLabel(route.source, 'peer')})`,
|
|
307
|
+
`thread=${threadLabel}(${sourceLabel(route.source, 'thread')})`,
|
|
308
|
+
`chatType=${route.peer.peerKind}`,
|
|
309
|
+
].join(' ');
|
|
310
|
+
}
|
|
@@ -67,9 +67,10 @@ export class OwnerResolver {
|
|
|
67
67
|
else
|
|
68
68
|
this.configuredOwners.delete(subjectAid);
|
|
69
69
|
const subject = this.subjects.get(subjectAid);
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
70
|
+
// Retiring compatibility targets must not invalidate the freshly verified protocol Owner.
|
|
71
|
+
const removesConfirmedTargets = normalized.length === 0 && subject?.view.consensusStatus === 'consensus'
|
|
72
|
+
&& this.isCacheFresh(subject, OWNERSHIP_AUTHORIZATION_MAX_AGE_MS);
|
|
73
|
+
if (subject && !removesConfirmedTargets) {
|
|
73
74
|
this.invalidate(subject, 'Configured Owners changed; fresh consensus is required', true);
|
|
74
75
|
}
|
|
75
76
|
}
|
|
@@ -606,6 +607,29 @@ export class OwnerResolver {
|
|
|
606
607
|
this.assertAid(ownerAid);
|
|
607
608
|
return fs.existsSync(agentOwnerBindingRejectionPath(subjectAid, ownerAid));
|
|
608
609
|
}
|
|
610
|
+
/** Explicit local reset; never submits a bind or resets the channel's per-process attempts. */
|
|
611
|
+
resetRejectedOwnerBinding(subjectAid, ownerAid) {
|
|
612
|
+
this.assertAid(subjectAid);
|
|
613
|
+
this.assertAid(ownerAid);
|
|
614
|
+
let cleared = false;
|
|
615
|
+
try {
|
|
616
|
+
fs.unlinkSync(agentOwnerBindingRejectionPath(subjectAid, ownerAid));
|
|
617
|
+
cleared = true;
|
|
618
|
+
}
|
|
619
|
+
catch (error) {
|
|
620
|
+
if (error.code !== 'ENOENT')
|
|
621
|
+
throw error;
|
|
622
|
+
}
|
|
623
|
+
const subject = this.subject(subjectAid);
|
|
624
|
+
if (subject.view.task?.operation === 'bind' && subject.view.task.owner_aid === ownerAid
|
|
625
|
+
&& subject.view.task.status === 'rejected') {
|
|
626
|
+
subject.view.task = undefined;
|
|
627
|
+
subject.view.requestStatus = undefined;
|
|
628
|
+
subject.view.requestedOwnerAid = undefined;
|
|
629
|
+
}
|
|
630
|
+
logOwnershipEvent('rejection.reset', { subjectAid, ownerAid });
|
|
631
|
+
return { ...this.snapshot(subjectAid), rejectionReset: { ownerAid, cleared } };
|
|
632
|
+
}
|
|
609
633
|
rememberRejectedOwnerBinding(task) {
|
|
610
634
|
const file = agentOwnerBindingRejectionPath(task.sub_aid, task.owner_aid);
|
|
611
635
|
try {
|
|
@@ -768,7 +792,14 @@ export class OwnerResolver {
|
|
|
768
792
|
return await this.withSubjectClient(subjectAid, async (client, attached) => {
|
|
769
793
|
// SDK 0.5.24 can recover an authenticated request from message history;
|
|
770
794
|
// this in-memory projection is only used to detect mismatched results.
|
|
771
|
-
const request = subject.requests.get(operationId) ?? subject.decisionTasks.get(operationId)
|
|
795
|
+
const request = subject.requests.get(operationId) ?? subject.decisionTasks.get(operationId)
|
|
796
|
+
?? (decision === 'accept' ? await this.readDecisionPreflight(subjectAid, client, operationId) : undefined);
|
|
797
|
+
if (decision === 'accept' && request) {
|
|
798
|
+
await this.assertAgentOwner(request.sub_aid, request.new_owner_aid ?? request.owner_aid);
|
|
799
|
+
}
|
|
800
|
+
if (subject.generation !== generation || (attached && subject.client !== client)) {
|
|
801
|
+
throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during approval preparation');
|
|
802
|
+
}
|
|
772
803
|
const result = decision === 'accept'
|
|
773
804
|
? await client.acceptOwnershipRequest(operationId)
|
|
774
805
|
: await client.rejectOwnershipRequest(operationId, reason);
|
|
@@ -917,6 +948,8 @@ export class OwnerResolver {
|
|
|
917
948
|
let replaced = false;
|
|
918
949
|
subject.view = { ...subject.view, requestedOwnerAid: ownerAid, requestStatus: 'requesting', task: undefined };
|
|
919
950
|
try {
|
|
951
|
+
await this.assertAgentOwner(subjectAid, ownerAid);
|
|
952
|
+
assertCurrent();
|
|
920
953
|
const local = await this.tryLocalBind(subjectAid, ownerAid, assertCurrent);
|
|
921
954
|
if (local) {
|
|
922
955
|
if (subject.client && subject.generation !== generation) {
|
|
@@ -1004,6 +1037,8 @@ export class OwnerResolver {
|
|
|
1004
1037
|
targetConsensus = current;
|
|
1005
1038
|
subject.view.targetConsensus = current;
|
|
1006
1039
|
assertCurrent();
|
|
1040
|
+
await this.assertAgentOwner(subAid, newOwnerAid);
|
|
1041
|
+
assertCurrent();
|
|
1007
1042
|
const local = await this.tryLocalTransfer(ownerAid, subAid, newOwnerAid, current, assertCurrent);
|
|
1008
1043
|
if (local) {
|
|
1009
1044
|
subject.view.task = local.task;
|
|
@@ -1153,6 +1188,73 @@ export class OwnerResolver {
|
|
|
1153
1188
|
throw new OwnershipError('INVALID_OWNER', 'The new Owner must differ from the current Owner');
|
|
1154
1189
|
}
|
|
1155
1190
|
}
|
|
1191
|
+
async assertAgentOwner(subjectAid, ownerAid) {
|
|
1192
|
+
if (subjectAid === this.daemonAid)
|
|
1193
|
+
return;
|
|
1194
|
+
const { loadAgent } = await import('../../config-store.js');
|
|
1195
|
+
const client = this.subjects.get(subjectAid)?.client;
|
|
1196
|
+
if (!loadAgent(subjectAid) && client?.getType && client.getType() !== 'agent')
|
|
1197
|
+
return;
|
|
1198
|
+
const { assertHumanAgentOwner } = await import('../../aun/aid/agentmd.js');
|
|
1199
|
+
await assertHumanAgentOwner(ownerAid);
|
|
1200
|
+
}
|
|
1201
|
+
/** Only identifies the human-type preflight target. The SDK still authenticates the original request. */
|
|
1202
|
+
async readDecisionPreflight(subjectAid, client, operationId) {
|
|
1203
|
+
const query = { filter: 'all', limit: 200 };
|
|
1204
|
+
const tokens = new Set();
|
|
1205
|
+
for (;;) {
|
|
1206
|
+
const catalog = await client.call('message.peers', query);
|
|
1207
|
+
for (const peer of Array.isArray(catalog.peers) ? catalog.peers : []) {
|
|
1208
|
+
const sender = String(peer.sender_aid ?? '');
|
|
1209
|
+
const head = Number(peer.head_seq);
|
|
1210
|
+
const snapshot = Number.isSafeInteger(head) && head > 0 && head < Number.MAX_SAFE_INTEGER
|
|
1211
|
+
? { snapshot_head_seq: head } : {};
|
|
1212
|
+
let before = snapshot.snapshot_head_seq === undefined ? Number.MAX_SAFE_INTEGER : head + 1;
|
|
1213
|
+
for (;;) {
|
|
1214
|
+
const history = await client.call('message.history', {
|
|
1215
|
+
sender_aid: sender, before_seq: before, ...snapshot, limit: 200,
|
|
1216
|
+
});
|
|
1217
|
+
for (const row of Array.isArray(history.messages) ? history.messages : []) {
|
|
1218
|
+
let value = row.payload ?? row;
|
|
1219
|
+
try {
|
|
1220
|
+
if (value?.type === 'text' && typeof value.text === 'string')
|
|
1221
|
+
value = JSON.parse(value.text);
|
|
1222
|
+
if (typeof value === 'string')
|
|
1223
|
+
value = JSON.parse(value);
|
|
1224
|
+
}
|
|
1225
|
+
catch {
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
if (value?.type !== 'aun.ownership.sdk.v1' || value.operation_id !== operationId
|
|
1229
|
+
|| !['bind.request', 'transfer.request'].includes(value.action))
|
|
1230
|
+
continue;
|
|
1231
|
+
const task = this.bindingTask({ ...value, status: 'pending', step: 'approval' });
|
|
1232
|
+
if (!task || String(row.from_aid ?? row.from ?? row.sender_aid ?? '') !== sender
|
|
1233
|
+
|| ![task.sub_aid, task.owner_aid, task.new_owner_aid].includes(subjectAid)) {
|
|
1234
|
+
throw new OwnershipError('TASK_MISMATCH', 'Ownership history preflight does not match the local subject');
|
|
1235
|
+
}
|
|
1236
|
+
return task;
|
|
1237
|
+
}
|
|
1238
|
+
if (history.has_older !== true)
|
|
1239
|
+
break;
|
|
1240
|
+
const next = Number(history.next_before_seq);
|
|
1241
|
+
if (!Number.isSafeInteger(next) || next <= 0 || next >= before) {
|
|
1242
|
+
throw new OwnershipError('REQUEST_NOT_FOUND', 'Ownership history pagination did not advance');
|
|
1243
|
+
}
|
|
1244
|
+
before = next;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
if (catalog.has_more !== true)
|
|
1248
|
+
break;
|
|
1249
|
+
const token = catalog.next_page_token;
|
|
1250
|
+
if (typeof token !== 'string' || !token || tokens.has(token)) {
|
|
1251
|
+
throw new OwnershipError('REQUEST_NOT_FOUND', 'Ownership peer pagination did not advance');
|
|
1252
|
+
}
|
|
1253
|
+
tokens.add(token);
|
|
1254
|
+
query.page_token = token;
|
|
1255
|
+
}
|
|
1256
|
+
throw new OwnershipError('REQUEST_NOT_FOUND', 'Cannot identify the Owner of the original ownership request');
|
|
1257
|
+
}
|
|
1156
1258
|
async tryLocalTransfer(ownerAid, subAid, newOwnerAid, current, assertCurrent) {
|
|
1157
1259
|
let store;
|
|
1158
1260
|
let ownerClient;
|
|
@@ -1173,7 +1275,8 @@ export class OwnerResolver {
|
|
|
1173
1275
|
ownerClient = await sdkStore.loadClient(store, ownerAid);
|
|
1174
1276
|
subClient = await sdkStore.loadClient(store, subAid);
|
|
1175
1277
|
newOwnerClient = await sdkStore.loadClient(store, newOwnerAid);
|
|
1176
|
-
if (
|
|
1278
|
+
if (!['agent', 'human'].includes(ownerClient.getType()) || subClient.getType() !== 'agent'
|
|
1279
|
+
|| !['agent', 'human'].includes(newOwnerClient.getType())
|
|
1177
1280
|
|| typeof ownerClient.transferLocalSubaid !== 'function')
|
|
1178
1281
|
return undefined;
|
|
1179
1282
|
assertCurrent();
|
|
@@ -1246,7 +1349,7 @@ export class OwnerResolver {
|
|
|
1246
1349
|
ownerClient = await sdkStore.loadClient(store, ownerAid);
|
|
1247
1350
|
subClient = await sdkStore.loadClient(store, subjectAid);
|
|
1248
1351
|
if (typeof ownerClient.bindSubaid !== 'function'
|
|
1249
|
-
|| ownerClient.getType()
|
|
1352
|
+
|| !['agent', 'human'].includes(ownerClient.getType()) || subClient.getType() !== 'agent')
|
|
1250
1353
|
return undefined;
|
|
1251
1354
|
assertCurrent();
|
|
1252
1355
|
invoked = true;
|
|
@@ -1614,10 +1717,10 @@ export async function refreshOwnershipForAuthorization(subjectAid, options = {})
|
|
|
1614
1717
|
}
|
|
1615
1718
|
export async function assertOwnershipAuthorization(context) {
|
|
1616
1719
|
if (context?.internalContactAuthorization && context.selfAid && context.actor?.principalId) {
|
|
1617
|
-
const {
|
|
1720
|
+
const { prepareSameOwnerProof } = await import('../relation/same-owner-proof.js');
|
|
1618
1721
|
const { resolvePeerRoleDetail } = await import('../../config/peer-role-resolver.js');
|
|
1619
1722
|
const { getRoleDefinition } = await import('../../config/roles.js');
|
|
1620
|
-
await
|
|
1723
|
+
await prepareSameOwnerProof(context.selfAid, context.actor.principalId);
|
|
1621
1724
|
const current = resolvePeerRoleDetail({
|
|
1622
1725
|
selfAid: context.selfAid, channelKey: context.actor.operatorChannelKey, channelType: 'aun',
|
|
1623
1726
|
chatType: 'private', actorId: context.actor.principalId, conversationId: context.actor.principalId,
|