evolcore 0.0.48 → 0.0.49
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 +34 -0
- package/dist/agent-template/runtime.js +5 -2
- package/dist/agents/codex-runner.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +643 -273
- package/dist/cli/directory.js +6 -1
- package/dist/cli/index.js +7 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +1 -0
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +11 -1
- package/dist/config/providers-config.js +8 -4
- package/dist/config/providers-management.js +11 -3
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/core/auth/delegation-authorization.js +33 -26
- package/dist/core/auth/operation-catalog.js +9 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +45 -2
- package/dist/core/command/menu-handler.js +6 -1
- package/dist/core/command/menu-protocol.js +24 -0
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/daemon-control.js +57 -1
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +6 -2
- package/dist/core/ipc-registration.js +1 -0
- package/dist/core/message/aun-ipc-sender.js +118 -56
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +40 -1
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +92 -39
- package/dist/core/message/message-log.js +24 -0
- package/dist/core/message/message-queue.js +97 -15
- package/dist/core/message/response-engine.js +151 -18
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/pack-auth.js +3 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +106 -19
- package/dist/core/permission/services-path-acl.js +451 -0
- package/dist/core/permission/tool-policy.js +5 -1
- package/dist/core/relation/peer-identity.js +13 -0
- package/dist/core/task/task-recovery-service.js +1 -0
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +11 -8
- package/dist/directory/owner-directory-cache.js +19 -0
- package/dist/directory/owner-directory-markdown.js +1 -1
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +28 -5
- package/dist/ecweb/runtime/supervisor.js +36 -8
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +20 -5
- package/dist/event-center/runtime.js +10 -7
- package/dist/index.js +4 -0
- package/dist/ipc.js +25 -1
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +3 -2
- package/dist/outputs/protocol.js +1 -0
- package/dist/outputs/service.js +2 -15
- package/dist/services/index.js +29 -5
- package/dist/services/ipc-operation.js +84 -0
- package/dist/services/pack-manager.js +1 -0
- package/dist/services/service-payload.js +13 -7
- package/dist/stats/budget.js +1 -1
- package/dist/stats/model-resolver.js +2 -2
- package/dist/stats/quota-query.js +95 -0
- package/dist/trigger/script-sandbox.js +12 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/npm-ops.js +43 -8
- package/dist/workbench/service.js +1 -1
- package/kits/docs/evolcore/INDEX.md +2 -0
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +4 -1
- package/kits/docs/evolcore/directory.md +8 -9
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/provider.md +1 -1
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +3 -0
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/trigger.md +2 -0
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-provider/SKILL.md +57 -8
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/commands.md +1 -0
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/thread.md +1 -0
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +2 -2
- package/scripts/agent-template/inspect.mjs +46 -10
- package/scripts/agent-template/shared/common.mjs +9 -3
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +60 -10
- package/scripts/agent-template/shared/template-package.mjs +182 -21
- package/scripts/agent-template/shared/template-runtime.mjs +35 -2
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +46 -11
|
@@ -467,8 +467,17 @@ export async function recoverStartupObserverHints(options) {
|
|
|
467
467
|
}
|
|
468
468
|
catch (error) {
|
|
469
469
|
attempts++;
|
|
470
|
+
// 一个永久失败的 Agent 不能无限期占住它自己的输入,更不能拖住宿主的总就绪
|
|
471
|
+
// 判定(`startupRecoveryPending` 会一直不清)。到上限后按降级放行,
|
|
472
|
+
// 并把被跳过的提示作为显式错误报出来,而不是静默丢弃。
|
|
473
|
+
if (attempts >= MAX_OBSERVER_HINT_ATTEMPTS) {
|
|
474
|
+
options.trace?.addSpan('daemon.observerHints', started, Date.now(), `${aid}; giving up after ${attempts} attempts`);
|
|
475
|
+
logger.error(`[startup] observer hint registration gave up for ${aid} after ${attempts} attempts; pending hints in this Agent are not restored: ${error}`);
|
|
476
|
+
options.onAgentHintsRecovered(aid);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
470
479
|
options.trace?.addSpan('daemon.observerHints', started, Date.now(), `${aid}; retry pending`);
|
|
471
|
-
logger.warn(`[startup] observer hint registration waits for ${aid} (attempt ${attempts}): ${error}`);
|
|
480
|
+
logger.warn(`[startup] observer hint registration waits for ${aid} (attempt ${attempts}/${MAX_OBSERVER_HINT_ATTEMPTS}): ${error}`);
|
|
472
481
|
await recoveryRetryDelay();
|
|
473
482
|
}
|
|
474
483
|
}
|
|
@@ -481,6 +490,8 @@ export async function recoverStartupObserverHints(options) {
|
|
|
481
490
|
function recoveryRetryDelay() {
|
|
482
491
|
return new Promise(resolve => { const timer = setTimeout(resolve, 1_000); timer.unref?.(); });
|
|
483
492
|
}
|
|
493
|
+
/** Observer hint 注册的连续失败上限:超过即降级放行,避免单个 Agent 拖住整个宿主就绪。 */
|
|
494
|
+
const MAX_OBSERVER_HINT_ATTEMPTS = 30;
|
|
484
495
|
/**
|
|
485
496
|
* Background recovery never gates Ready. Until an Agent's scan completes its
|
|
486
497
|
* inputs stay queued; afterwards only sessions referenced by unfinished
|
|
@@ -499,8 +510,11 @@ export class StartupHandoffRecovery {
|
|
|
499
510
|
const state = this.states.get(aid);
|
|
500
511
|
if (!state || state.phase === 'ready')
|
|
501
512
|
return;
|
|
513
|
+
// 扫描尚未产出结论时不阻塞:没有证据说明这个会话受任何未完成的 Handoff 影响,
|
|
514
|
+
// 退回 'startup Handoff scan' 会把该 Agent 的每个会话都挂在一次可能永远
|
|
515
|
+
// 等不到结果的后台扫描后面(与类注释的「后台恢复永不 gate Ready」矛盾)。
|
|
502
516
|
if (!state.sessions)
|
|
503
|
-
return
|
|
517
|
+
return;
|
|
504
518
|
if (state.sessions.has(sessionId))
|
|
505
519
|
return 'session Handoff recovery';
|
|
506
520
|
}
|
|
@@ -704,8 +704,12 @@ function safeInfoValue(fn, fallback) {
|
|
|
704
704
|
function findInstanceByKey(raw, agent, channelKey) {
|
|
705
705
|
return raw.channels.find(c => agent.effectiveChannelName(c.type, c.name) === channelKey) ?? null;
|
|
706
706
|
}
|
|
707
|
-
/**
|
|
708
|
-
|
|
707
|
+
/**
|
|
708
|
+
* active Agent 只有本地私钥和证书齐全,才参与启动编排。
|
|
709
|
+
*
|
|
710
|
+
* 纯本地文件判定(不读注册表状态),导出以便单测直接覆盖各 lifecycle / 文件组合。
|
|
711
|
+
*/
|
|
712
|
+
export function precheckAgentConfig(aid, config) {
|
|
709
713
|
if (resolveAgentLifecycle(config) !== 'active')
|
|
710
714
|
return null;
|
|
711
715
|
const directory = aidLocalDir(aid);
|
|
@@ -667,6 +667,7 @@ export function registerCommandIpcProviders({ lifecycle, ipcServer, agentRegistr
|
|
|
667
667
|
ipcServer.setConfigOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, requestId) => cmdHandler.handleConfigOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId));
|
|
668
668
|
ipcServer.setPeerOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleContactOperation(argv, sessionId, delegationToken, delegationCommandHash));
|
|
669
669
|
ipcServer.setRoleOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, localControl) => cmdHandler.handleRoleOperation(argv, sessionId, delegationToken, delegationCommandHash, localControl));
|
|
670
|
+
ipcServer.setQuotaOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, localControl) => cmdHandler.handleQuotaOperation(argv, sessionId, delegationToken, delegationCommandHash, localControl));
|
|
670
671
|
ipcServer.setDirectoryOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleDirectoryOperation(argv, sessionId, delegationToken, delegationCommandHash));
|
|
671
672
|
ipcServer.setAidOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, requestId) => cmdHandler.handleAidOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId));
|
|
672
673
|
ipcServer.setAidOwnershipExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleOwnershipOperation(argv, sessionId, delegationToken, delegationCommandHash));
|
|
@@ -7,15 +7,13 @@ import { AUN_HANDOFF_MARKER_FIELD } from '../../channels/aun.js';
|
|
|
7
7
|
import { classifyAunPayloadForLog } from './message-log.js';
|
|
8
8
|
import { isValidAunDeliveryForChannel } from './outbound.js';
|
|
9
9
|
import { isHClassPath } from '../permission/protected-paths.js';
|
|
10
|
-
import { evaluateOutboundContactAdmission } from './message-admission.js';
|
|
11
|
-
import { contactIntroductionText, evaluateAppContactAdmission, parseFriendInvite } from './contact-admission.js';
|
|
12
10
|
import { normalizeAunMentionEntries, withAunAttention } from '../../aun/msg/mention-schema.js';
|
|
13
11
|
import { resolveManagedSendArgv } from '../../cli/aun-commands.js';
|
|
14
12
|
import { readTriggerLocalFile, resolveAttachmentLocalPath } from '../../trigger/local-files.js';
|
|
15
13
|
import { TriggerDefinitionManager } from '../../trigger/manager.js';
|
|
16
14
|
import { normalizeGroupAid, sameGroupAid } from '../../aun/group/identity.js';
|
|
17
15
|
import { resolveThreadRouteTarget } from '../thread/thread-route.js';
|
|
18
|
-
import { isTopicThreadId, parseMainTopicId, safeFormatMainTopicId, sessionLocalTopicId } from '../thread/topic-id.js';
|
|
16
|
+
import { isMainSessionThreadId, isTopicThreadId, parseMainTopicId, safeFormatMainTopicId, sessionLocalTopicId, } from '../thread/topic-id.js';
|
|
19
17
|
import { ThreadService } from '../thread/thread-service.js';
|
|
20
18
|
import { diagLog } from '../../utils/msg-diag.js';
|
|
21
19
|
import { buildEnvelope, DEFAULT_NOOP_SENTINEL } from './message-utils.js';
|
|
@@ -29,7 +27,45 @@ import { buildDownstreamArgv, expandGroupBase, parseGatewayArgs } from '../../cl
|
|
|
29
27
|
import { resolveSendRoute } from './send-routing.js';
|
|
30
28
|
import { agentDir } from '../../paths.js';
|
|
31
29
|
import { chatDirPath, readAllJsonlLines } from '../session/session-fs-store.js';
|
|
30
|
+
import { prepareContactThreadDelegation, finishContactThreadDelegation, findContactThreadReturn } from './contact-thread-approval.js';
|
|
31
|
+
import { currentContactBinding } from './contact-admission.js';
|
|
32
32
|
const TASK_ID_MESSAGE_PAYLOAD_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file']);
|
|
33
|
+
const TOPIC_SOURCE_MESSAGE_TYPES = new Set(['text', 'link', 'image', 'video', 'voice', 'file', 'action_card']);
|
|
34
|
+
/** Stamp the actual runtime source before handoff/outbox persistence, including retries. */
|
|
35
|
+
export function withAunTopicSource(payload, input) {
|
|
36
|
+
// A caller's payload can be copied from another message. Its old provenance
|
|
37
|
+
// must not survive a new managed send or mark an ordinary reply cross-topic.
|
|
38
|
+
const result = { ...payload };
|
|
39
|
+
delete result.topic_source;
|
|
40
|
+
const runtime = input.runtime;
|
|
41
|
+
if (!TOPIC_SOURCE_MESSAGE_TYPES.has(String(payload.type)) || runtime?.channel !== 'aun'
|
|
42
|
+
|| runtime.selfAid !== input.selfAid
|
|
43
|
+
|| (runtime.chatType !== 'private' && runtime.chatType !== 'group'))
|
|
44
|
+
return result;
|
|
45
|
+
// channelId is the conversation peer; peerId in a group is the speaker.
|
|
46
|
+
const peer = runtime.channelId?.trim() ?? '';
|
|
47
|
+
if (!safeFormatMainTopicId(input.selfAid, peer))
|
|
48
|
+
return result;
|
|
49
|
+
const threadId = isTopicThreadId(runtime.threadId) ? runtime.threadId : '';
|
|
50
|
+
if (!isMainSessionThreadId(runtime.threadId) && !/^thread-[a-zA-Z0-9-]+$/.test(threadId))
|
|
51
|
+
return result;
|
|
52
|
+
const targetThreadId = isTopicThreadId(input.targetThreadId) ? input.targetThreadId : '';
|
|
53
|
+
if (peer.toLowerCase() === input.targetPeer.trim().toLowerCase()
|
|
54
|
+
&& runtime.chatType === input.targetChatType && threadId === targetThreadId)
|
|
55
|
+
return result;
|
|
56
|
+
const source = {
|
|
57
|
+
version: 1, agent_aid: input.selfAid, peer_id: peer,
|
|
58
|
+
chat_type: runtime.chatType, thread_id: threadId,
|
|
59
|
+
};
|
|
60
|
+
// An absent/deleted index entry must never prevent the message being sent.
|
|
61
|
+
try {
|
|
62
|
+
const name = input.resolveName?.(source)?.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 256);
|
|
63
|
+
if (name && name !== '话题会话' && name !== '默认会话')
|
|
64
|
+
source.name = name;
|
|
65
|
+
}
|
|
66
|
+
catch { /* the coordinates still identify the source */ }
|
|
67
|
+
return { ...result, topic_source: source };
|
|
68
|
+
}
|
|
33
69
|
function normalizeAid(value) {
|
|
34
70
|
return String(value ?? '').trim().replace(/^@/, '').toLowerCase();
|
|
35
71
|
}
|
|
@@ -510,6 +546,18 @@ async function resolveGatewaySend(argv, grant, runtime, session) {
|
|
|
510
546
|
|| (currentChatType !== 'private' && currentChatType !== 'group')) {
|
|
511
547
|
throw Object.assign(new Error('Current AUN conversation route is unavailable'), { code: 'AUN_OUTBOUND_ROUTE_REQUIRED' });
|
|
512
548
|
}
|
|
549
|
+
// An unqualified report to Owner continues its unique originating delegation.
|
|
550
|
+
// Explicit --thread always wins; unrelated conversations keep normal routing.
|
|
551
|
+
let returningToOrigin = false;
|
|
552
|
+
if (options.thread === undefined && options.to
|
|
553
|
+
&& normalizeAid(options.to) === currentContactBinding(grant.selfAid)?.owner_aid) {
|
|
554
|
+
const origin = findContactThreadReturn({ selfAid: grant.selfAid, grant, runtime });
|
|
555
|
+
if (origin) {
|
|
556
|
+
options.thread = origin.originThreadId;
|
|
557
|
+
options.checkEvery ??= 'none';
|
|
558
|
+
returningToOrigin = true;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
513
561
|
const resolveKind = async (target) => {
|
|
514
562
|
if (normalizeAid(target) === normalizeAid(currentPeer))
|
|
515
563
|
return currentChatType;
|
|
@@ -563,6 +611,8 @@ async function resolveGatewaySend(argv, grant, runtime, session) {
|
|
|
563
611
|
}, deps);
|
|
564
612
|
if (!route.ok)
|
|
565
613
|
throw Object.assign(new Error(route.message), { code: route.code });
|
|
614
|
+
if (returningToOrigin)
|
|
615
|
+
route.source.thread = 'derived';
|
|
566
616
|
return { route, argv: buildDownstreamArgv(route, text, passthrough) };
|
|
567
617
|
}
|
|
568
618
|
export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegationRegistry, responseEngine, handoffRuntime, sessionManager, messageQueue, createCrossThreadReviewTrigger, }) {
|
|
@@ -701,13 +751,15 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
701
751
|
}
|
|
702
752
|
// Topic lookup also restores the current topic; cross-topic side effects
|
|
703
753
|
// must follow the verified route rather than the presence of a topic ID.
|
|
704
|
-
|
|
754
|
+
// First-contact gateway sends omit --thread until handoff creates the main
|
|
755
|
+
// session. They still cross topics and must retain their delegation/inbox.
|
|
756
|
+
const threadRouted = gatewayRoute?.crossTopic ?? !!threadRoute;
|
|
705
757
|
// 规范目标 id:话题保留原 id;主话题用双方拼出的规范形态(用于 Trigger 标签与通知)。
|
|
706
758
|
const targetTopicId = threadRoute
|
|
707
759
|
? (isTopicThreadId(threadRef)
|
|
708
760
|
? threadRef
|
|
709
761
|
: (safeFormatMainTopicId(params.aid, threadRoute.peer) ?? threadRef))
|
|
710
|
-
:
|
|
762
|
+
: gatewayRoute?.threadId;
|
|
711
763
|
const isSystemEvent = params.trustedSystemEvent === true
|
|
712
764
|
&& params.payload?.type === 'event' && params.payload.event === 'topic.renamed';
|
|
713
765
|
// 非托管跨话题自派:调用方没有委托凭证,用本机 controlToken 证明「本机控制面调用」。
|
|
@@ -829,43 +881,6 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
829
881
|
if (!ch) {
|
|
830
882
|
return { ok: false, error: `AUN channel not found for ${params.aid}`, code: 'AUN_CHANNEL_NOT_FOUND' };
|
|
831
883
|
}
|
|
832
|
-
// 跨话题自派(`--to <本端AID>`):收件人就是自己,不属于跨主体通讯,跳过联系人准入。
|
|
833
|
-
// 不放进 evaluateAppContactAdmission 内部:那是通用准入判定,其它调用方
|
|
834
|
-
// (入站、handoff 等)也用它,在函数内开口子会扩散到所有路径。
|
|
835
|
-
if (params.scope === 'msg' && !isSelfAidTarget(params.aid, params.to)) {
|
|
836
|
-
const admission = await evaluateOutboundContactAdmission({ selfAid: params.aid, targetAid: params.to });
|
|
837
|
-
if (!admission.allow) {
|
|
838
|
-
const decision = evaluateAppContactAdmission(params.aid, params.to);
|
|
839
|
-
const friendInvite = params.rawPayload === true && params.encrypt === true
|
|
840
|
-
&& parseFriendInvite(params.payload, params.aid, params.to);
|
|
841
|
-
const inviteMayRequestContact = !!friendInvite
|
|
842
|
-
&& (decision?.reason === 'not_in_contacts' || admission.code === 'CONTACT_ALL_CONTACTS_DISABLED');
|
|
843
|
-
if (!inviteMayRequestContact) {
|
|
844
|
-
const canRequestOwner = !!decision && (decision.reason === 'not_in_contacts' || decision.reason === 'scope_extension')
|
|
845
|
-
&& !params.file && params.returnPolicy !== 'required' && contactIntroductionText(params.payload) !== undefined;
|
|
846
|
-
if (!canRequestOwner || typeof ch.requestOutboundContact !== 'function') {
|
|
847
|
-
return { ok: false, error: admission.error, code: admission.code, sent: false };
|
|
848
|
-
}
|
|
849
|
-
try {
|
|
850
|
-
// Retries of the same task message share an event; never queue the original peer send.
|
|
851
|
-
const sourceMessageId = 'outbound-' + crypto.createHash('sha256').update(JSON.stringify([
|
|
852
|
-
params.originSessionId, params.originMessageId, params.to, contactIntroductionText(params.payload),
|
|
853
|
-
])).digest('hex');
|
|
854
|
-
const request = await ch.requestOutboundContact({ to: params.to, payload: params.payload, sourceMessageId });
|
|
855
|
-
if (!request.ok)
|
|
856
|
-
return { ok: false, code: request.code, error: request.error, sent: false };
|
|
857
|
-
const receipt = request.receipt;
|
|
858
|
-
return { ok: false, code: 'CONTACT_APPROVAL_REQUIRED', sent: false, retryable: false,
|
|
859
|
-
error: `目标 ${params.to} 未准入,${receipt.status === 'sent' ? '已向' : '已排队向'}本端 Owner ${receipt.owner_aid} 提交联系申请,等待审批;原消息未发送`,
|
|
860
|
-
contact_request: receipt };
|
|
861
|
-
}
|
|
862
|
-
catch (error) {
|
|
863
|
-
return { ok: false, code: 'CONTACT_OWNER_REQUEST_FAILED', sent: false,
|
|
864
|
-
error: `向本端 Owner 提交联系申请失败:${error instanceof Error ? error.message : String(error)};原消息未发送` };
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
}
|
|
868
|
-
}
|
|
869
884
|
// The IPC command already carries the caller-selected transport scope.
|
|
870
885
|
// Never reclassify the target by parsing its AID string: a private AID may
|
|
871
886
|
// look group-like and a group identifier may use a future format.
|
|
@@ -941,6 +956,21 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
941
956
|
if (params.rawPayload !== true && isTopicThreadId(params.thread) && typeof payload.thread_id !== 'string') {
|
|
942
957
|
payload = { ...payload, thread_id: params.thread };
|
|
943
958
|
}
|
|
959
|
+
if (params.rawPayload !== true) {
|
|
960
|
+
payload = withAunTopicSource(payload, {
|
|
961
|
+
selfAid: params.aid,
|
|
962
|
+
runtime,
|
|
963
|
+
targetPeer: threadRoute?.peer ?? params.to,
|
|
964
|
+
targetChatType: params.scope === 'group' ? 'group' : 'private',
|
|
965
|
+
targetThreadId: params.thread,
|
|
966
|
+
resolveName: source => {
|
|
967
|
+
const entry = source.thread_id
|
|
968
|
+
? ThreadService.findThreadById(params.aid, source.thread_id)
|
|
969
|
+
: ThreadService.findMainSessionEntry(params.aid, source.peer_id);
|
|
970
|
+
return entry?.peer === source.peer_id ? entry.name : undefined;
|
|
971
|
+
},
|
|
972
|
+
});
|
|
973
|
+
}
|
|
944
974
|
// 跨话题自派:在线上载荷显式打标。客户端(尤其观察者转发/入站解析)不必只靠
|
|
945
975
|
// `from == to` 推断,可直接认这个字段;同 AID 的其它设备也据此区分「自己派给自己」。
|
|
946
976
|
if (selfAddressed && params.rawPayload !== true) {
|
|
@@ -979,7 +1009,35 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
979
1009
|
payload = preparedRequest.payload;
|
|
980
1010
|
getAunRequestRegistry().markSending(params.aid, preparedRequest.requestId);
|
|
981
1011
|
}
|
|
982
|
-
let
|
|
1012
|
+
let contactDelegationId;
|
|
1013
|
+
const contactTarget = threadRoute ?? (gatewayRoute ? {
|
|
1014
|
+
peer: gatewayRoute.peer.id, peerKind: gatewayRoute.peer.peerKind, channelType: gatewayRoute.peer.channelType,
|
|
1015
|
+
} : undefined);
|
|
1016
|
+
if (!selfAddressed && !preparedRequest && params.scope === 'msg' && threadRouted && contactTarget && targetTopicId && delegation.grant) {
|
|
1017
|
+
try {
|
|
1018
|
+
contactDelegationId = prepareContactThreadDelegation({
|
|
1019
|
+
selfAid: params.aid, grant: delegation.grant, runtime, target: contactTarget,
|
|
1020
|
+
targetThreadId: targetTopicId, wireThreadId: payload.thread_id,
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
catch (error) {
|
|
1024
|
+
logger.warn(`[AUN] Could not persist contact delegation: ${error instanceof Error ? error.message : String(error)}`);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
const finishContactDelegation = (messageId) => {
|
|
1028
|
+
if (!contactDelegationId)
|
|
1029
|
+
return;
|
|
1030
|
+
try {
|
|
1031
|
+
finishContactThreadDelegation(params.aid, contactDelegationId, messageId);
|
|
1032
|
+
}
|
|
1033
|
+
catch (error) {
|
|
1034
|
+
logger.warn(`[AUN] Could not settle contact delegation: ${error instanceof Error ? error.message : String(error)}`);
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
// Topic effects need the destination even when handoff is bypassed. Keep
|
|
1038
|
+
// the legacy log override separate: only handoff resolves that session.
|
|
1039
|
+
const targetSessionId = threadRoute?.sessionId;
|
|
1040
|
+
let handoffSessionId;
|
|
983
1041
|
// 跨话题自派一律跳过 handoff:目标会话是按话题索引解析出的 (自端, 对端) 会话,
|
|
984
1042
|
// 而 handoff 用 `to`(=本端)作为 channelId 去 getOrCreateSession,会建出
|
|
985
1043
|
// 「我↔我」的错误会话目录。话题内与跨话题同此处理(D14)。
|
|
@@ -1029,8 +1087,9 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
1029
1087
|
},
|
|
1030
1088
|
causation: runtimeCausation,
|
|
1031
1089
|
});
|
|
1032
|
-
|
|
1090
|
+
handoffSessionId = created.targetSession.id;
|
|
1033
1091
|
if (created.crossSession && created.handoff) {
|
|
1092
|
+
finishContactDelegation(created.handoff.target_message_id ?? created.handoff.handoff_id);
|
|
1034
1093
|
const response = {
|
|
1035
1094
|
ok: true,
|
|
1036
1095
|
status: created.handoff.state === 'target_sent' ? 'delivered' : 'queued',
|
|
@@ -1055,12 +1114,12 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
1055
1114
|
}
|
|
1056
1115
|
// 排队未投递(无 message_id)时也要写 inbox + 建复查:handoff 已不再
|
|
1057
1116
|
// 承载目标侧上下文,跳过这里就会丢上下文。
|
|
1058
|
-
if (threadRouted &&
|
|
1117
|
+
if (threadRouted && targetTopicId) {
|
|
1059
1118
|
const effects = await applyManagedCrossThreadSendEffects({
|
|
1060
1119
|
runtime,
|
|
1061
1120
|
selfAid: params.aid,
|
|
1062
|
-
targetThreadId: targetTopicId
|
|
1063
|
-
targetSessionId:
|
|
1121
|
+
targetThreadId: targetTopicId,
|
|
1122
|
+
targetSessionId: created.targetSession.id,
|
|
1064
1123
|
targetChannelId: params.to,
|
|
1065
1124
|
feedbackChatType: params.scope === 'group' ? 'group' : 'private',
|
|
1066
1125
|
messageId: response.message_id ?? created.handoff.handoff_id,
|
|
@@ -1084,6 +1143,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
1084
1143
|
}
|
|
1085
1144
|
}
|
|
1086
1145
|
catch (error) {
|
|
1146
|
+
finishContactDelegation();
|
|
1087
1147
|
const code = error?.code;
|
|
1088
1148
|
const handoffId = error?.handoffId
|
|
1089
1149
|
?? error?.blockingHandoffId;
|
|
@@ -1119,14 +1179,14 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
1119
1179
|
encrypt,
|
|
1120
1180
|
debug,
|
|
1121
1181
|
model: typeof debug?.model === 'string' ? debug.model : undefined,
|
|
1122
|
-
log: params.log ? { ...params.log, sessionId:
|
|
1182
|
+
log: params.log ? { ...params.log, sessionId: handoffSessionId ?? params.log.sessionId } : undefined,
|
|
1123
1183
|
});
|
|
1124
|
-
if (threadRouted &&
|
|
1184
|
+
if (threadRouted && targetTopicId && sent.ok && sent.message_id && targetSessionId) {
|
|
1125
1185
|
const effects = await applyManagedCrossThreadSendEffects({
|
|
1126
1186
|
runtime,
|
|
1127
1187
|
selfAid: params.aid,
|
|
1128
|
-
targetThreadId:
|
|
1129
|
-
targetSessionId
|
|
1188
|
+
targetThreadId: targetTopicId,
|
|
1189
|
+
targetSessionId,
|
|
1130
1190
|
targetChannelId: params.to,
|
|
1131
1191
|
feedbackChatType: 'group',
|
|
1132
1192
|
messageId: sent.message_id,
|
|
@@ -1148,6 +1208,7 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
1148
1208
|
return sent;
|
|
1149
1209
|
}
|
|
1150
1210
|
if (typeof ch.sendDaemonMsg !== 'function') {
|
|
1211
|
+
finishContactDelegation();
|
|
1151
1212
|
return { ok: false, error: 'AUN channel does not support daemon private sends', code: 'AUN_MSG_UNSUPPORTED' };
|
|
1152
1213
|
}
|
|
1153
1214
|
diagLog('aun_out', diagCommon);
|
|
@@ -1161,8 +1222,9 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
1161
1222
|
causation: runtimeCausation,
|
|
1162
1223
|
debug,
|
|
1163
1224
|
model: typeof debug?.model === 'string' ? debug.model : undefined,
|
|
1164
|
-
log: params.log ? { ...params.log, sessionId:
|
|
1165
|
-
});
|
|
1225
|
+
log: params.log ? { ...params.log, sessionId: handoffSessionId ?? params.log.sessionId } : undefined,
|
|
1226
|
+
}).catch((error) => { finishContactDelegation(); throw error; });
|
|
1227
|
+
finishContactDelegation(sent.ok ? sent.message_id : undefined);
|
|
1166
1228
|
// send_ok 只看网关是否返回 message_id,与 aun_out 的差值即发送失败次数;
|
|
1167
1229
|
// 放在各个 return 分支之前,request / self-addressed 路径也不会漏记。
|
|
1168
1230
|
if (sent.ok && sent.message_id)
|
|
@@ -1213,12 +1275,12 @@ export function registerAunIpcSender({ ipcServer, channelInstances, agentDelegat
|
|
|
1213
1275
|
sent.self_session_id = delivered.sessionId;
|
|
1214
1276
|
return sent;
|
|
1215
1277
|
}
|
|
1216
|
-
if (threadRouted &&
|
|
1278
|
+
if (threadRouted && targetTopicId && sent.ok && sent.message_id && targetSessionId) {
|
|
1217
1279
|
const effects = await applyManagedCrossThreadSendEffects({
|
|
1218
1280
|
runtime,
|
|
1219
1281
|
selfAid: params.aid,
|
|
1220
|
-
targetThreadId:
|
|
1221
|
-
targetSessionId
|
|
1282
|
+
targetThreadId: targetTopicId,
|
|
1283
|
+
targetSessionId,
|
|
1222
1284
|
targetChannelId: params.to,
|
|
1223
1285
|
feedbackChatType: 'private',
|
|
1224
1286
|
messageId: sent.message_id,
|
|
@@ -24,8 +24,12 @@ function readState(file) {
|
|
|
24
24
|
throw error;
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
|
+
/** Stable source identity shared by isolation tombstones and pending inbound storage. */
|
|
28
|
+
export function contactInboundKey(selfAid, fromAid, messageId) {
|
|
29
|
+
return crypto.createHash('sha256').update(JSON.stringify([selfAid, fromAid, messageId])).digest('hex');
|
|
30
|
+
}
|
|
27
31
|
function sourceFile(selfAid, aid, mid) {
|
|
28
|
-
const key =
|
|
32
|
+
const key = contactInboundKey(selfAid, aid, mid);
|
|
29
33
|
return path.join(contactAdmissionDirectory(selfAid), 'isolated-sources', key.slice(0, 2), key + '.json');
|
|
30
34
|
}
|
|
31
35
|
const failedIsolationStores = new Set();
|
|
@@ -57,7 +61,8 @@ export function saveIsolatedContactSource(selfAid, aid, mid, source) {
|
|
|
57
61
|
const previous = JSON.parse(existing);
|
|
58
62
|
if (previous.digest !== source.digest)
|
|
59
63
|
return previous;
|
|
60
|
-
source = { ...previous, ...(source.notified ? { notified: true } : {})
|
|
64
|
+
source = { ...previous, ...(source.notified ? { notified: true } : {}),
|
|
65
|
+
...(source.notificationReady ? { notificationReady: true } : {}) };
|
|
61
66
|
}
|
|
62
67
|
fs.writeFileSync(barrier, 'incomplete', { mode: 0o600 });
|
|
63
68
|
if (!existing) {
|
|
@@ -414,12 +419,26 @@ function executeContactGrantLocked(selfAid, senderAid, payload, encrypted, now,
|
|
|
414
419
|
// ---------------------------------------------------------------------------
|
|
415
420
|
export const FRIEND_INVITE_TYPE = 'friend.invite.v1';
|
|
416
421
|
export const FRIEND_INVITE_RESULT_TYPE = 'friend.invite.result.v1';
|
|
422
|
+
export const FRIEND_INVITE_PROOF_TYPE = 'friend.invite.proof.v1';
|
|
417
423
|
/** Contract 08: expires_at_ms must equal created_at_ms + three days exactly. */
|
|
418
424
|
export const FRIEND_INVITE_TTL_MS = 3 * 24 * 60 * 60 * 1000;
|
|
419
425
|
const MAX_FRIEND_INVITE_DECISIONS = 10000;
|
|
426
|
+
const QR_PROOF_TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
420
427
|
export function isFriendInvitePayload(payload) {
|
|
421
428
|
return !!payload && typeof payload === 'object' && !Array.isArray(payload) && payload.type === FRIEND_INVITE_TYPE;
|
|
422
429
|
}
|
|
430
|
+
export function isFriendInviteProofPayload(payload) {
|
|
431
|
+
return !!payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
432
|
+
&& payload.type === FRIEND_INVITE_PROOF_TYPE;
|
|
433
|
+
}
|
|
434
|
+
function parseFriendInviteQrProof(value) {
|
|
435
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
436
|
+
return undefined;
|
|
437
|
+
const proof = value;
|
|
438
|
+
if (proof.version !== 1 || typeof proof.token !== 'string' || !QR_PROOF_TOKEN_RE.test(proof.token))
|
|
439
|
+
return undefined;
|
|
440
|
+
return { version: 1, token: proof.token };
|
|
441
|
+
}
|
|
423
442
|
/** The authenticated envelope decides identity; payload AIDs must match it exactly. */
|
|
424
443
|
export function parseFriendInvite(payload, senderAid, selfAid) {
|
|
425
444
|
if (!isFriendInvitePayload(payload))
|
|
@@ -437,13 +456,69 @@ export function parseFriendInvite(payload, senderAid, selfAid) {
|
|
|
437
456
|
return undefined;
|
|
438
457
|
if (typeof value.introduction !== 'string' || !value.introduction.trim() || value.introduction.includes('\0'))
|
|
439
458
|
return undefined;
|
|
459
|
+
let qrProof;
|
|
460
|
+
if (value.qr_proof !== undefined) {
|
|
461
|
+
qrProof = parseFriendInviteQrProof(value.qr_proof);
|
|
462
|
+
if (!qrProof)
|
|
463
|
+
return undefined;
|
|
464
|
+
}
|
|
440
465
|
return { invite_id: value.invite_id, applicant_aid: senderAid, target_aid: selfAid,
|
|
441
|
-
created_at_ms: value.created_at_ms, expires_at_ms: value.expires_at_ms, introduction: value.introduction
|
|
466
|
+
created_at_ms: value.created_at_ms, expires_at_ms: value.expires_at_ms, introduction: value.introduction,
|
|
467
|
+
...(qrProof ? { qr_proof: qrProof } : {}) };
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Parse the durable QR proof control package. Core authenticates the AUN
|
|
471
|
+
* sender and target and preserves the proof, but deliberately does not verify
|
|
472
|
+
* the token itself; the Owner-side App performs that decision.
|
|
473
|
+
*/
|
|
474
|
+
export function parseFriendInviteProof(payload, senderAid, selfAid) {
|
|
475
|
+
if (!isFriendInviteProofPayload(payload))
|
|
476
|
+
return undefined;
|
|
477
|
+
const value = payload;
|
|
478
|
+
if (value.schema_version !== 1 || typeof value.proof_id !== 'string'
|
|
479
|
+
|| !/^[a-zA-Z0-9_.:-]{1,256}$/.test(value.proof_id))
|
|
480
|
+
return undefined;
|
|
481
|
+
const invite = parseFriendInvite(value.invite, senderAid, selfAid);
|
|
482
|
+
if (!invite)
|
|
483
|
+
return undefined;
|
|
484
|
+
// The wrapper always carries the fresh proof used for this retry. It may
|
|
485
|
+
// intentionally differ from an old proof retained inside the original
|
|
486
|
+
// invite; that original invite is an immutable business record.
|
|
487
|
+
const outer = parseFriendInviteQrProof(value.qr_proof);
|
|
488
|
+
if (!outer)
|
|
489
|
+
return undefined;
|
|
490
|
+
return { proof_id: value.proof_id, invite, qr_proof: outer };
|
|
491
|
+
}
|
|
492
|
+
/** Canonical wire shape used when Core forwards a validated invite. */
|
|
493
|
+
export function serializeFriendInvite(invite) {
|
|
494
|
+
return {
|
|
495
|
+
type: FRIEND_INVITE_TYPE,
|
|
496
|
+
schema_version: 1,
|
|
497
|
+
invite_id: invite.invite_id,
|
|
498
|
+
applicant_aid: invite.applicant_aid,
|
|
499
|
+
target_aid: invite.target_aid,
|
|
500
|
+
created_at_ms: invite.created_at_ms,
|
|
501
|
+
expires_at_ms: invite.expires_at_ms,
|
|
502
|
+
introduction: invite.introduction,
|
|
503
|
+
...(invite.qr_proof ? { qr_proof: { version: 1, token: invite.qr_proof.token } } : {}),
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
export function serializeFriendInviteProof(proof) {
|
|
507
|
+
return {
|
|
508
|
+
type: FRIEND_INVITE_PROOF_TYPE,
|
|
509
|
+
schema_version: 1,
|
|
510
|
+
proof_id: proof.proof_id,
|
|
511
|
+
invite: serializeFriendInvite(proof.invite),
|
|
512
|
+
qr_proof: { version: 1, token: proof.qr_proof.token },
|
|
513
|
+
};
|
|
442
514
|
}
|
|
443
515
|
export function friendInviteDigest(invite) {
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
516
|
+
const identity = [invite.applicant_aid, invite.target_aid, invite.created_at_ms, invite.expires_at_ms, invite.introduction];
|
|
517
|
+
// Keep the legacy digest byte-for-byte stable for invites that predate QR
|
|
518
|
+
// proofs; only proof-bearing invites add the new identity fields.
|
|
519
|
+
if (invite.qr_proof)
|
|
520
|
+
identity.push(invite.qr_proof.version, invite.qr_proof.token);
|
|
521
|
+
return crypto.createHash('sha256').update(JSON.stringify(identity)).digest('hex');
|
|
447
522
|
}
|
|
448
523
|
function inviteDecisionPath(selfAid) { return path.join(contactAdmissionDirectory(selfAid), 'friend-invite-decisions.json'); }
|
|
449
524
|
function inviteDecisionKey(binding, inviteId) {
|
|
@@ -521,6 +596,16 @@ export function buildFriendInviteResult(selfAid, invite, decision) {
|
|
|
521
596
|
export function friendPayloadRouteValid(payload, to, encrypt, binding) {
|
|
522
597
|
if (encrypt !== true)
|
|
523
598
|
return false;
|
|
599
|
+
if (payload.type === FRIEND_INVITE_TYPE || payload.type === FRIEND_INVITE_PROOF_TYPE) {
|
|
600
|
+
// Outbound App requests originate from the target Agent itself and go to
|
|
601
|
+
// the requested peer. They are not Owner-directed friend controls.
|
|
602
|
+
const invite = payload.type === FRIEND_INVITE_TYPE ? payload : payload.invite;
|
|
603
|
+
const parsed = payload.type === FRIEND_INVITE_TYPE
|
|
604
|
+
? parseFriendInvite(payload, binding.target_agent_aid, invite?.target_aid)
|
|
605
|
+
: parseFriendInviteProof(payload, binding.target_agent_aid, invite?.target_aid)?.invite;
|
|
606
|
+
return !!invite && !!parsed && invite.applicant_aid === binding.target_agent_aid
|
|
607
|
+
&& isValidAid(invite.target_aid) && to === invite.target_aid && to !== binding.target_agent_aid;
|
|
608
|
+
}
|
|
524
609
|
if (payload.type === FRIEND_INVITE_RESULT_TYPE) {
|
|
525
610
|
return payload.target_aid === binding.target_agent_aid && payload.responder_aid === binding.target_agent_aid
|
|
526
611
|
&& payload.relation_version === binding.relation_version && isValidAid(payload.applicant_aid) && to === payload.applicant_aid;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { contactAdmissionDirectory } from '../../directory/contact-admission-paths.js';
|
|
4
|
+
import { atomicReplaceJsonSync } from '../../utils/atomic-write.js';
|
|
5
|
+
import { CONTACT_EVENT_TTL_MS, contactInboundKey, contactSourceDigest } from './contact-admission.js';
|
|
6
|
+
export { contactInboundKey } from './contact-admission.js';
|
|
7
|
+
const MAX_RECORDS = 10_000;
|
|
8
|
+
const MAX_BYTES = 64 * 1024 * 1024;
|
|
9
|
+
export const CONTACT_RECEIPT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
10
|
+
const deliveries = new WeakSet();
|
|
11
|
+
export function createContactInboundDelivery(value) {
|
|
12
|
+
deliveries.add(value);
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
export function trustedContactInboundDelivery(value) {
|
|
16
|
+
return value && typeof value === 'object' && deliveries.has(value)
|
|
17
|
+
? value : undefined;
|
|
18
|
+
}
|
|
19
|
+
function directory(selfAid) {
|
|
20
|
+
return path.join(contactAdmissionDirectory(selfAid), 'pending-inbound');
|
|
21
|
+
}
|
|
22
|
+
function filename(selfAid, key) {
|
|
23
|
+
if (!/^[a-f0-9]{64}$/.test(key))
|
|
24
|
+
throw new Error('invalid pending contact key');
|
|
25
|
+
return path.join(directory(selfAid), `${key}.json`);
|
|
26
|
+
}
|
|
27
|
+
function commit(record) {
|
|
28
|
+
const file = filename(record.selfAid, record.key);
|
|
29
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
30
|
+
// No hot backup: a completed/expired record must not retain a second plaintext copy.
|
|
31
|
+
atomicReplaceJsonSync(file, record);
|
|
32
|
+
}
|
|
33
|
+
export function readPendingContactInbound(selfAid, key) {
|
|
34
|
+
let raw;
|
|
35
|
+
try {
|
|
36
|
+
raw = fs.readFileSync(filename(selfAid, key), 'utf8');
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error.code === 'ENOENT')
|
|
40
|
+
return undefined;
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
const record = JSON.parse(raw);
|
|
44
|
+
if (record.version !== 1 || record.selfAid !== selfAid || record.key !== key
|
|
45
|
+
|| contactInboundKey(selfAid, record.fromAid, record.messageId) !== key
|
|
46
|
+
|| !Number.isFinite(record.receivedAt) || record.expiresAt !== record.receivedAt + CONTACT_EVENT_TTL_MS
|
|
47
|
+
|| !Number.isSafeInteger(record.order) || record.binding?.target_agent_aid !== selfAid
|
|
48
|
+
|| !['waiting', 'transferring', 'accepted', 'expired', 'blocked', 'binding_changed', 'rejected'].includes(record.state)
|
|
49
|
+
|| (record.message && (record.message.message_id !== record.messageId
|
|
50
|
+
|| record.message.envelope?.from?.trim() !== record.fromAid
|
|
51
|
+
|| contactSourceDigest(record.message.payload) !== record.digest))) {
|
|
52
|
+
throw new Error('invalid pending contact record');
|
|
53
|
+
}
|
|
54
|
+
return record;
|
|
55
|
+
}
|
|
56
|
+
export function listPendingContactInbound(selfAid, includeTerminal = false) {
|
|
57
|
+
let names;
|
|
58
|
+
try {
|
|
59
|
+
names = fs.readdirSync(directory(selfAid));
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code === 'ENOENT')
|
|
63
|
+
return [];
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
// Synchronous commits cannot overlap in this daemon. These are interrupted
|
|
67
|
+
// rewrites, never committed sources; do not leave plaintext outside retention.
|
|
68
|
+
for (const name of names.filter(name => /^[a-f0-9]{64}\.json\.pending$/.test(name))) {
|
|
69
|
+
fs.rmSync(path.join(directory(selfAid), name), { force: true });
|
|
70
|
+
}
|
|
71
|
+
const records = names.filter(name => /^[a-f0-9]{64}\.json$/.test(name))
|
|
72
|
+
.map(name => readPendingContactInbound(selfAid, name.slice(0, -5)))
|
|
73
|
+
.filter(record => includeTerminal || record.state === 'waiting' || record.state === 'transferring');
|
|
74
|
+
return records.sort((a, b) => a.order - b.order || a.key.localeCompare(b.key));
|
|
75
|
+
}
|
|
76
|
+
export function savePendingContactInbound(input) {
|
|
77
|
+
const key = contactInboundKey(input.selfAid, input.fromAid, input.messageId);
|
|
78
|
+
const previous = readPendingContactInbound(input.selfAid, key);
|
|
79
|
+
const digest = contactSourceDigest(input.message.payload);
|
|
80
|
+
if (previous) {
|
|
81
|
+
if (previous.digest !== digest)
|
|
82
|
+
throw new Error('pending contact content conflict');
|
|
83
|
+
return previous;
|
|
84
|
+
}
|
|
85
|
+
const records = listPendingContactInbound(input.selfAid, true);
|
|
86
|
+
for (const record of records) {
|
|
87
|
+
if (!record.message && record.receivedAt + CONTACT_RECEIPT_TTL_MS <= Date.now()) {
|
|
88
|
+
fs.unlinkSync(filename(input.selfAid, record.key));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const retained = records.filter(record => record.message || record.receivedAt + CONTACT_RECEIPT_TTL_MS > Date.now());
|
|
92
|
+
const bytes = retained.reduce((n, record) => n + Buffer.byteLength(JSON.stringify(record)), 0);
|
|
93
|
+
const record = {
|
|
94
|
+
version: 1, key, selfAid: input.selfAid, fromAid: input.fromAid, messageId: input.messageId,
|
|
95
|
+
binding: input.binding, digest, receivedAt: input.receivedAt,
|
|
96
|
+
expiresAt: input.receivedAt + CONTACT_EVENT_TTL_MS,
|
|
97
|
+
order: Math.max(Date.now(), ...retained.map(record => record.order + 1)),
|
|
98
|
+
state: 'waiting', message: JSON.parse(JSON.stringify(input.message)),
|
|
99
|
+
};
|
|
100
|
+
if (retained.length >= MAX_RECORDS || bytes + Buffer.byteLength(JSON.stringify(record)) > MAX_BYTES) {
|
|
101
|
+
throw new Error('pending contact storage capacity exceeded');
|
|
102
|
+
}
|
|
103
|
+
commit(record);
|
|
104
|
+
return record;
|
|
105
|
+
}
|
|
106
|
+
export function updatePendingContactInbound(record) { commit(record); }
|
|
107
|
+
export function finishPendingContactInbound(record, state) {
|
|
108
|
+
const terminal = { ...record, state };
|
|
109
|
+
delete terminal.message;
|
|
110
|
+
commit(terminal);
|
|
111
|
+
// Remove an interrupted rewrite, which may still contain the original plaintext.
|
|
112
|
+
fs.rmSync(filename(record.selfAid, record.key) + '.pending', { force: true });
|
|
113
|
+
}
|