evolcore 0.0.48 → 0.0.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -0
- package/bin/ecmsg.js +9 -4
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +164 -0
- package/dist/ability/caller/contract.js +102 -0
- package/dist/ability/caller/daemon.js +158 -0
- package/dist/ability/caller/service.js +380 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +10 -3
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +173 -1
- package/dist/agent-template/runtime.js +285 -8
- package/dist/agent-template/service.js +1159 -40
- package/dist/agent-template/types.js +2 -1
- package/dist/agents/baseagent-availability.js +27 -3
- package/dist/agents/baseagent-capability-adapter.js +102 -0
- package/dist/agents/baseagent-plugin-descriptor.js +274 -0
- package/dist/agents/baseagent-plugin-loader.js +145 -0
- package/dist/agents/baseagent.js +68 -2
- package/dist/agents/claude-gateway/agent-registration.js +389 -0
- package/dist/agents/claude-gateway/binding.js +96 -0
- package/dist/agents/claude-gateway/inbox.js +138 -0
- package/dist/agents/claude-gateway/index.js +125 -0
- package/dist/agents/claude-gateway/listing.js +330 -0
- package/dist/agents/claude-gateway/router.js +328 -0
- package/dist/agents/claude-gateway/sessions.js +128 -0
- package/dist/agents/claude-gateway/terminal.js +250 -0
- package/dist/agents/claude-gateway/transcript.js +272 -0
- package/dist/agents/claude-gateway/types.js +14 -0
- package/dist/agents/claude-runner.js +6 -10
- package/dist/agents/codex-runner.js +9 -2
- package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
- package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
- package/dist/agents/gemini/index.js +51 -0
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/group/invite-service.js +6 -36
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +31 -2
- package/dist/aun/msg/upload.js +126 -3
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +1175 -457
- package/dist/cli/ability-command.js +42 -0
- package/dist/cli/agent-command.js +20 -1
- package/dist/cli/agent-create.js +78 -18
- package/dist/cli/agent-template.js +5 -3
- package/dist/cli/agent.js +91 -0
- package/dist/cli/aun-commands.js +92 -34
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +245 -101
- package/dist/cli/directory.js +6 -1
- package/dist/cli/ecmsg-gateway.js +11 -9
- package/dist/cli/index.js +30 -5
- package/dist/cli/init.js +39 -63
- package/dist/cli/managed-command-guard.js +3 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/model.js +20 -5
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/quota.js +89 -0
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/role.js +1 -0
- package/dist/cli/services-command.js +12 -9
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +78 -12
- package/dist/config/access-policy.js +16 -3
- package/dist/config/config-field-policy.js +88 -9
- package/dist/config/config-manager.js +97 -47
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +9 -8
- package/dist/config/owner-config.js +0 -16
- package/dist/config/peer-role-resolver.js +1 -7
- package/dist/config/providers-config.js +107 -20
- package/dist/config/providers-management.js +45 -21
- package/dist/config/resolved-config-op.js +4 -44
- package/dist/config/schema-migration.js +78 -5
- package/dist/config/schema-registry.js +52 -7
- package/dist/config-store.js +1309 -17
- package/dist/core/agent-application-service.js +220 -1
- package/dist/core/agent-ipc-registration.js +19 -2
- package/dist/core/agent-reload-coordinator.js +5 -0
- package/dist/core/agent-runtime.js +198 -54
- package/dist/core/auth/agent-delegation.js +14 -0
- package/dist/core/auth/delegation-authorization.js +33 -26
- package/dist/core/auth/operation-authorizer.js +16 -1
- package/dist/core/auth/operation-catalog.js +59 -7
- package/dist/core/baseagent-loader.js +30 -3
- package/dist/core/capability/capability-manager.js +16 -7
- package/dist/core/channel-runtime.js +4 -2
- package/dist/core/command/agent-control.js +20 -2
- package/dist/core/command/agent-template-menu.js +4 -3
- package/dist/core/command/cli-intent-parser.js +28 -0
- package/dist/core/command/command-handler.js +45 -2
- package/dist/core/command/menu-catalog.js +20 -4
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +97 -73
- package/dist/core/command/menu-protocol.js +29 -0
- package/dist/core/command/menu-query-batch.js +2 -2
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/slash-handler.js +17 -26
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/topic-slash.js +7 -1
- package/dist/core/daemon-bootstrap.js +0 -4
- package/dist/core/daemon-control.js +58 -1
- package/dist/core/daemon-lifecycle.js +29 -7
- package/dist/core/evolagent-registry.js +18 -9
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/core/host-snapshot.js +8 -3
- package/dist/core/initialization/service.js +3 -0
- package/dist/core/interaction-router.js +130 -0
- package/dist/core/ipc-registration.js +5 -0
- package/dist/core/memory/consolidation-context.js +2 -1
- package/dist/core/memory/consolidation.js +35 -64
- package/dist/core/message/aun-ipc-sender.js +213 -74
- package/dist/core/message/aun-request-registry.js +31 -0
- 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 +197 -45
- package/dist/core/message/message-log.js +32 -0
- package/dist/core/message/message-queue.js +102 -18
- package/dist/core/message/peer-mode.js +15 -4
- package/dist/core/message/response-engine.js +174 -26
- package/dist/core/message/send-options.js +37 -3
- package/dist/core/message/send-routing.js +11 -7
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-catalog.js +5 -5
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/ownership/owner-resolver.js +12 -86
- package/dist/core/pack-auth.js +7 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +288 -77
- package/dist/core/permission/protected-paths.js +64 -9
- package/dist/core/permission/services-path-acl.js +458 -0
- package/dist/core/permission/tool-policy.js +26 -10
- package/dist/core/relation/peer-identity.js +13 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
- package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
- package/dist/core/session/session-manager.js +47 -10
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/skill/index-generator.js +2 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/task/task-recovery-service.js +1 -0
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +4 -2
- package/dist/core/thread/thread-operation.js +25 -10
- package/dist/core/thread/thread-service.js +294 -55
- package/dist/core/thread/topic-id.js +67 -2
- package/dist/core/thread/types.js +15 -1
- 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 +3 -2
- package/dist/eck/message-renderer.js +28 -5
- package/dist/ecweb/basic-settings-service.js +5 -9
- package/dist/ecweb/providers-service.js +4 -2
- 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 +120 -41
- package/dist/ipc.js +83 -3
- 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/paths.js +48 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +188 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +29 -2
- package/dist/services/dispatcher.js +23 -5
- package/dist/services/host/main.js +388 -0
- package/dist/services/host/protocol.js +118 -0
- package/dist/services/host/resident.js +310 -0
- package/dist/services/host-client.js +386 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +203 -0
- package/dist/services/host-runtime.js +802 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +204 -22
- package/dist/services/ipc-operation.js +288 -44
- package/dist/services/pack-manager.js +1 -0
- package/dist/services/script-runner.js +515 -83
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +109 -4
- 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/application-service.js +6 -4
- package/dist/trigger/local-files.js +19 -9
- package/dist/trigger/scheduler.js +22 -12
- package/dist/trigger/script-sandbox.js +51 -8
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +173 -1
- package/dist/utils/logger.js +2 -2
- package/dist/utils/media-cache.js +190 -43
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/windows-shell-trust.js +7 -3
- package/dist/workbench/service.js +1 -1
- package/kits/docs/INDEX.md +3 -2
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/evolcore/INDEX.md +9 -6
- package/kits/docs/evolcore/agent.md +36 -1
- package/kits/docs/evolcore/aid.md +45 -3
- package/kits/docs/evolcore/config.md +5 -2
- package/kits/docs/evolcore/directory.md +8 -9
- package/kits/docs/evolcore/group.md +2 -1
- package/kits/docs/evolcore/memory-tags.md +2 -0
- package/kits/docs/evolcore/menu-client.md +3 -3
- package/kits/docs/evolcore/menu-protocol.md +7 -0
- package/kits/docs/evolcore/model.md +3 -0
- package/kits/docs/evolcore/msg.md +77 -10
- package/kits/docs/evolcore/pay.md +34 -0
- package/kits/docs/evolcore/provider.md +22 -1
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +3 -0
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/thread-chain.md +2 -0
- package/kits/docs/evolcore/tool-authorization.md +10 -0
- package/kits/docs/evolcore/trigger.md +2 -0
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +7 -0
- package/kits/rules/06-channel.md +3 -3
- package/kits/schemas/_meta.json +38 -5
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/agent-config.schema.21.json +974 -0
- package/kits/schemas/agent-config.schema.22.json +977 -0
- package/kits/schemas/agent-config.schema.23.json +958 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/providers.schema.3.json +18 -2
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +17 -1
- package/kits/skills/ability/SKILL.md +229 -34
- package/kits/skills/ability/STRUCTURE.md +333 -0
- package/kits/skills/ability/references/cli.md +208 -0
- package/kits/skills/ability/references/development.md +107 -37
- package/kits/skills/ability/references/management.md +106 -46
- package/kits/skills/ability/references/runtime-protocol.md +65 -63
- package/kits/skills/agent-output-cards/SKILL.md +64 -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 +3 -3
- package/kits/skills/ec-pay/SKILL.md +101 -0
- package/kits/skills/ec-pay/references/pay-cli.md +110 -0
- package/kits/skills/ec-provider/SKILL.md +58 -9
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +135 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +5 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/reply.md +1 -0
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +27 -128
- package/kits/templates/system-fragments/venue.md +27 -0
- package/package.json +4 -5
- package/scripts/agent-template/inspect.mjs +79 -29
- package/scripts/agent-template/overlay.mjs +20 -2
- package/scripts/agent-template/shared/common.mjs +24 -6
- package/scripts/agent-template/shared/team-schema.json +23 -5
- package/scripts/agent-template/shared/template-contract.mjs +107 -17
- package/scripts/agent-template/shared/template-package.mjs +254 -29
- package/scripts/agent-template/shared/template-runtime.mjs +145 -2
- package/scripts/agent-template/shared/template.mjs +67 -9
- package/scripts/agent-template/team-pack.mjs +132 -41
- package/scripts/agent-template/team-preview.mjs +249 -5
- package/kits/docs/aun/ABILITY_CALLING.md +0 -280
- package/kits/docs/evolcore/ability.md +0 -185
- package/kits/skills/ability/references/calling.md +0 -56
- package/kits/skills/ability/references/contract-checklist.md +0 -37
- package/kits/skills/ability/references/recovery.md +0 -27
- /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
|
@@ -62,6 +62,7 @@ function normalizeTimeoutMs(value) {
|
|
|
62
62
|
export class AunRequestRegistry {
|
|
63
63
|
records = new Map();
|
|
64
64
|
waiters = new Map();
|
|
65
|
+
observers = new Map();
|
|
65
66
|
loaded = new Set();
|
|
66
67
|
appends = new Map();
|
|
67
68
|
key(selfAid, requestId) {
|
|
@@ -165,6 +166,12 @@ export class AunRequestRegistry {
|
|
|
165
166
|
}
|
|
166
167
|
}
|
|
167
168
|
notify(record) {
|
|
169
|
+
if (['completed', 'failed'].includes(record.state)) {
|
|
170
|
+
const key = this.key(record.selfAid, record.requestId);
|
|
171
|
+
for (const observer of this.observers.get(key) ?? [])
|
|
172
|
+
observer(record);
|
|
173
|
+
this.observers.delete(key);
|
|
174
|
+
}
|
|
168
175
|
if (!['completed', 'failed', 'unknown', 'pending'].includes(record.state))
|
|
169
176
|
return;
|
|
170
177
|
const waiters = this.waiters.get(this.key(record.selfAid, record.requestId));
|
|
@@ -394,6 +401,30 @@ export class AunRequestRegistry {
|
|
|
394
401
|
}, waitMs);
|
|
395
402
|
});
|
|
396
403
|
}
|
|
404
|
+
/** Observe late results without extending the original transmission/collection TTL. */
|
|
405
|
+
async observe(selfAid, requestId, timeoutMs) {
|
|
406
|
+
const current = this.get(selfAid, requestId);
|
|
407
|
+
if (!current || ['completed', 'failed'].includes(current.state))
|
|
408
|
+
return current;
|
|
409
|
+
return new Promise(resolve => {
|
|
410
|
+
const key = this.key(selfAid, requestId);
|
|
411
|
+
const waiters = this.observers.get(key) ?? new Set();
|
|
412
|
+
const done = (record) => {
|
|
413
|
+
clearTimeout(timer);
|
|
414
|
+
waiters.delete(callback);
|
|
415
|
+
if (waiters.size === 0)
|
|
416
|
+
this.observers.delete(key);
|
|
417
|
+
resolve(record);
|
|
418
|
+
};
|
|
419
|
+
const callback = (record) => {
|
|
420
|
+
if (['completed', 'failed'].includes(record.state))
|
|
421
|
+
done(record);
|
|
422
|
+
};
|
|
423
|
+
const timer = setTimeout(() => done(this.get(selfAid, requestId)), Math.max(1, Math.min(timeoutMs, 60_000)));
|
|
424
|
+
waiters.add(callback);
|
|
425
|
+
this.observers.set(key, waiters);
|
|
426
|
+
});
|
|
427
|
+
}
|
|
397
428
|
}
|
|
398
429
|
let defaultRegistry;
|
|
399
430
|
export function getAunRequestRegistry() {
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { contactAdmissionDirectory } from '../../directory/contact-admission-paths.js';
|
|
5
|
+
import { atomicWriteJson } from '../../utils/atomic-write.js';
|
|
6
|
+
import { ThreadService } from '../thread/thread-service.js';
|
|
7
|
+
import { ThreadContextStorage } from '../thread/thread-context-storage.js';
|
|
8
|
+
import { isTopicThreadId, normalizeThreadIdForPeer } from '../thread/topic-id.js';
|
|
9
|
+
import { currentContactBinding, sameContactBinding } from './contact-admission.js';
|
|
10
|
+
import { CONTACT_RECEIPT_TTL_MS, readPendingContactInbound } from './contact-pending-inbound.js';
|
|
11
|
+
const PREPARED_TTL_MS = 30_000;
|
|
12
|
+
const MAX_RECORDS = 10_000;
|
|
13
|
+
function file(selfAid, kind, id) {
|
|
14
|
+
if (!/^[a-f0-9]{64}$/.test(id))
|
|
15
|
+
throw new Error('invalid contact thread state key');
|
|
16
|
+
return path.join(contactAdmissionDirectory(selfAid), kind, `${id}.json`);
|
|
17
|
+
}
|
|
18
|
+
function hash(value) { return crypto.createHash('sha256').update(value).digest('hex'); }
|
|
19
|
+
function read(filename) {
|
|
20
|
+
try {
|
|
21
|
+
return JSON.parse(fs.readFileSync(filename, 'utf8'));
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error.code === 'ENOENT')
|
|
25
|
+
return undefined;
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function records(selfAid, kind, prune = false) {
|
|
30
|
+
const directory = path.join(contactAdmissionDirectory(selfAid), kind);
|
|
31
|
+
let names;
|
|
32
|
+
try {
|
|
33
|
+
names = fs.readdirSync(directory);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error.code === 'ENOENT')
|
|
37
|
+
return [];
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
const values = [];
|
|
41
|
+
for (const name of names.filter(name => /^[a-f0-9]{64}\.json$/.test(name))) {
|
|
42
|
+
const filename = path.join(directory, name);
|
|
43
|
+
const value = read(filename);
|
|
44
|
+
if (!value || !Number.isSafeInteger(value.expiresAt))
|
|
45
|
+
throw new Error('invalid contact thread state');
|
|
46
|
+
if (prune && value.expiresAt <= Date.now()) {
|
|
47
|
+
fs.rmSync(filename, { force: true });
|
|
48
|
+
fs.rmSync(filename + '_', { force: true });
|
|
49
|
+
}
|
|
50
|
+
else
|
|
51
|
+
values.push(value);
|
|
52
|
+
}
|
|
53
|
+
return values;
|
|
54
|
+
}
|
|
55
|
+
function activeDelegations(selfAid, binding, peer, threadId) {
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
return records(selfAid, 'thread-delegations').filter(record => record.version === 1 && sameContactBinding(record.binding, binding)
|
|
58
|
+
&& record.targetAid === peer && record.targetThreadId === threadId && record.expiresAt > now);
|
|
59
|
+
}
|
|
60
|
+
function uniqueDelegationOrigin(candidates) {
|
|
61
|
+
const origins = new Map(candidates.map(record => [JSON.stringify([record.originThreadId, record.originSessionId]), record]));
|
|
62
|
+
return origins.size === 1 ? origins.values().next().value : undefined;
|
|
63
|
+
}
|
|
64
|
+
/** Persist before handing the send to a transport, so an immediate reply cannot outrun its provenance. */
|
|
65
|
+
export function prepareContactThreadDelegation(input) {
|
|
66
|
+
const { selfAid, grant, runtime, target } = input;
|
|
67
|
+
const binding = currentContactBinding(selfAid);
|
|
68
|
+
if (!binding || grant.selfAid !== selfAid || grant.actorId !== binding.owner_aid
|
|
69
|
+
|| grant.channelType !== 'aun' || grant.chatType !== 'private' || grant.systemSession
|
|
70
|
+
|| runtime?.selfAid !== selfAid || runtime.channel !== 'aun' || runtime.chatType !== 'private'
|
|
71
|
+
|| runtime.channelId !== binding.owner_aid || grant.peerKey !== `aun#${binding.owner_aid}`
|
|
72
|
+
|| (target.channelType ?? 'aun') !== 'aun' || target.peerKind !== 'private'
|
|
73
|
+
|| target.peer === selfAid || target.peer === binding.owner_aid)
|
|
74
|
+
return undefined;
|
|
75
|
+
const originThreadId = normalizeThreadIdForPeer(runtime.threadId, selfAid, binding.owner_aid);
|
|
76
|
+
const targetThreadId = normalizeThreadIdForPeer(input.targetThreadId, selfAid, target.peer);
|
|
77
|
+
if (!originThreadId || !targetThreadId
|
|
78
|
+
|| normalizeThreadIdForPeer(input.wireThreadId, selfAid, target.peer) !== targetThreadId)
|
|
79
|
+
return undefined;
|
|
80
|
+
const origin = isTopicThreadId(originThreadId)
|
|
81
|
+
? ThreadService.findThreadById(selfAid, originThreadId)
|
|
82
|
+
: ThreadService.findMainSessionEntry(selfAid, binding.owner_aid);
|
|
83
|
+
if (!origin || origin.sessionId !== grant.sessionId || origin.peer !== binding.owner_aid
|
|
84
|
+
|| origin.peerKind !== 'private' || (origin.channelType ?? 'aun') !== 'aun')
|
|
85
|
+
return undefined;
|
|
86
|
+
if (records(selfAid, 'thread-delegations', true).length >= MAX_RECORDS)
|
|
87
|
+
throw new Error('contact delegation capacity reached');
|
|
88
|
+
const id = hash(crypto.randomUUID());
|
|
89
|
+
const createdAt = Date.now();
|
|
90
|
+
const record = { version: 1, id, binding, originThreadId,
|
|
91
|
+
originSessionId: grant.sessionId, targetAid: target.peer, targetThreadId,
|
|
92
|
+
createdAt, expiresAt: createdAt + CONTACT_RECEIPT_TTL_MS, submitted: false };
|
|
93
|
+
atomicWriteJson(file(selfAid, 'thread-delegations', id), record);
|
|
94
|
+
return id;
|
|
95
|
+
}
|
|
96
|
+
export function finishContactThreadDelegation(selfAid, id, messageId) {
|
|
97
|
+
const filename = file(selfAid, 'thread-delegations', id);
|
|
98
|
+
const record = read(filename);
|
|
99
|
+
if (!record)
|
|
100
|
+
return;
|
|
101
|
+
if (!messageId) {
|
|
102
|
+
fs.rmSync(filename, { force: true });
|
|
103
|
+
fs.rmSync(filename + '_', { force: true });
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
atomicWriteJson(filename, { ...record, submitted: true, messageId });
|
|
107
|
+
}
|
|
108
|
+
export function findContactThreadDelegation(selfAid, binding, fromAid, payload, receivedAt) {
|
|
109
|
+
const threadId = normalizeThreadIdForPeer(payload.thread_id, selfAid, fromAid);
|
|
110
|
+
if (!threadId)
|
|
111
|
+
return { defer: false };
|
|
112
|
+
const matches = activeDelegations(selfAid, binding, fromAid, threadId).filter(record => record.createdAt <= receivedAt);
|
|
113
|
+
const submitted = matches.filter(record => record.submitted);
|
|
114
|
+
const ref = typeof payload.ref_message_id === 'string' ? payload.ref_message_id : undefined;
|
|
115
|
+
const exact = ref ? submitted.filter(record => record.messageId === ref) : [];
|
|
116
|
+
// A supplied, unknown reference cannot be used to choose among several origins.
|
|
117
|
+
const candidates = exact.length ? exact : submitted;
|
|
118
|
+
if (!exact.length && matches.some(record => !record.submitted && record.createdAt + PREPARED_TTL_MS > Date.now())) {
|
|
119
|
+
return { defer: true };
|
|
120
|
+
}
|
|
121
|
+
const origin = uniqueDelegationOrigin(candidates);
|
|
122
|
+
if (!origin)
|
|
123
|
+
return { defer: false };
|
|
124
|
+
return { defer: false, origin: { eventId: '', originThreadId: origin.originThreadId, originSessionId: origin.originSessionId } };
|
|
125
|
+
}
|
|
126
|
+
/** Resolve an implicit report to Owner from durable local provenance, never wire topic_source. */
|
|
127
|
+
export function findContactThreadReturn(input) {
|
|
128
|
+
const { selfAid, grant, runtime } = input;
|
|
129
|
+
const binding = currentContactBinding(selfAid);
|
|
130
|
+
const peer = runtime.channelId;
|
|
131
|
+
if (!binding || !peer || peer === selfAid || peer === binding.owner_aid
|
|
132
|
+
|| grant.selfAid !== selfAid || grant.channelType !== 'aun' || grant.chatType !== 'private' || grant.systemSession
|
|
133
|
+
|| runtime.selfAid !== selfAid || runtime.sessionId !== grant.sessionId
|
|
134
|
+
|| runtime.channel !== 'aun' || runtime.chatType !== 'private'
|
|
135
|
+
|| grant.actorId !== peer || grant.peerKey !== `aun#${peer}` || runtime.peerKey !== grant.peerKey)
|
|
136
|
+
return undefined;
|
|
137
|
+
const threadId = normalizeThreadIdForPeer(runtime.threadId, selfAid, peer);
|
|
138
|
+
if (!threadId)
|
|
139
|
+
return undefined;
|
|
140
|
+
const target = isTopicThreadId(threadId)
|
|
141
|
+
? ThreadService.findThreadById(selfAid, threadId) : ThreadService.findMainSessionEntry(selfAid, peer);
|
|
142
|
+
if (!target || target.sessionId !== grant.sessionId || target.peer !== peer
|
|
143
|
+
|| target.peerKind !== 'private' || (target.channelType ?? 'aun') !== 'aun')
|
|
144
|
+
return undefined;
|
|
145
|
+
const record = uniqueDelegationOrigin(activeDelegations(selfAid, binding, peer, threadId).filter(record => record.submitted));
|
|
146
|
+
if (!record)
|
|
147
|
+
return undefined;
|
|
148
|
+
const origin = isTopicThreadId(record.originThreadId)
|
|
149
|
+
? ThreadService.findThreadById(selfAid, record.originThreadId)
|
|
150
|
+
: ThreadService.findMainSessionEntry(selfAid, binding.owner_aid);
|
|
151
|
+
if (!origin || origin.sessionId !== record.originSessionId || origin.peer !== binding.owner_aid
|
|
152
|
+
|| origin.peerKind !== 'private' || (origin.channelType ?? 'aun') !== 'aun'
|
|
153
|
+
|| normalizeThreadIdForPeer(origin.threadId, selfAid, binding.owner_aid) !== record.originThreadId)
|
|
154
|
+
return undefined;
|
|
155
|
+
return { eventId: '', originThreadId: record.originThreadId, originSessionId: record.originSessionId };
|
|
156
|
+
}
|
|
157
|
+
export function isContactApprovalCard(payload) {
|
|
158
|
+
return payload?.type === 'action_card' && payload.card_kind === 'friend_request';
|
|
159
|
+
}
|
|
160
|
+
export function buildContactApprovalCard(request, approval) {
|
|
161
|
+
return {
|
|
162
|
+
type: 'action_card', card_kind: 'friend_request', blocking: false,
|
|
163
|
+
...(isTopicThreadId(approval.originThreadId) ? { thread_id: approval.originThreadId } : {}),
|
|
164
|
+
title: request.reason === 'scope_extension' ? '联系人回复待授权' : '联系人回复待确认',
|
|
165
|
+
text: `您委托联系的 ${request.applicant_aid} 发来消息:\n\n${request.introduction.text}\n\n是否添加好友并允许本 Agent 继续处理?`,
|
|
166
|
+
actions: [
|
|
167
|
+
{ label: request.reason === 'scope_extension' ? '允许本 Agent 并继续' : '添加好友并继续', value: 'approve', behavior: 'reply', style: 'primary' },
|
|
168
|
+
{ label: '拒绝', value: 'reject', behavior: 'reply' },
|
|
169
|
+
],
|
|
170
|
+
friend_request: request,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** Restore provenance even when a review already consumed the original one-shot thread inbox. */
|
|
174
|
+
export function ensureContactApprovalThreadContext(selfAid, pending, sessionId) {
|
|
175
|
+
const approval = pending.approval;
|
|
176
|
+
if (!approval)
|
|
177
|
+
return;
|
|
178
|
+
const messageId = `contact-approval:${approval.eventId}`;
|
|
179
|
+
const storage = new ThreadContextStorage();
|
|
180
|
+
if (storage.readAll(selfAid, sessionId).some(entry => entry.messageId === messageId))
|
|
181
|
+
return;
|
|
182
|
+
storage.append(selfAid, {
|
|
183
|
+
messageId, content: '联系人准入已生效,请继续处理原委托中对方的回复。',
|
|
184
|
+
timestamp: pending.receivedAt, originThreadId: approval.originThreadId,
|
|
185
|
+
originPeer: pending.binding.owner_aid, originSessionId: approval.originSessionId,
|
|
186
|
+
targetSessionId: sessionId,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
/** Durable binding does not depend on the generic interaction router's in-memory callbacks. */
|
|
190
|
+
export function registerContactApprovalCard(selfAid, pendingKey, eventId, messageId) {
|
|
191
|
+
const pending = readPendingContactInbound(selfAid, pendingKey);
|
|
192
|
+
if (!pending?.approval || pending.approval.eventId !== eventId)
|
|
193
|
+
throw new Error('contact approval event mismatch');
|
|
194
|
+
const filename = file(selfAid, 'approval-cards', hash(messageId));
|
|
195
|
+
const previous = read(filename);
|
|
196
|
+
if (previous) {
|
|
197
|
+
if (previous.messageId !== messageId || previous.pendingKey !== pendingKey || previous.eventId !== eventId) {
|
|
198
|
+
throw new Error('contact approval card identity conflict');
|
|
199
|
+
}
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
if (records(selfAid, 'approval-cards', true).length >= MAX_RECORDS)
|
|
203
|
+
throw new Error('contact approval card capacity reached');
|
|
204
|
+
atomicWriteJson(filename, { version: 1, messageId, pendingKey, eventId,
|
|
205
|
+
expiresAt: pending.receivedAt + CONTACT_RECEIPT_TTL_MS });
|
|
206
|
+
}
|
|
207
|
+
export function readContactApprovalCard(selfAid, messageId) {
|
|
208
|
+
const record = read(file(selfAid, 'approval-cards', hash(messageId)));
|
|
209
|
+
if (record && (record.version !== 1 || record.messageId !== messageId))
|
|
210
|
+
throw new Error('invalid contact approval card');
|
|
211
|
+
return record;
|
|
212
|
+
}
|
|
@@ -104,7 +104,34 @@ export class IMRenderer {
|
|
|
104
104
|
return;
|
|
105
105
|
this.recordActivity(item);
|
|
106
106
|
if (!this.suppressProactiveItem(item)) {
|
|
107
|
-
|
|
107
|
+
logger.info(`[IMRenderer] proactive.final.attempt ${JSON.stringify({
|
|
108
|
+
taskId: this.opts.envelope.taskId,
|
|
109
|
+
sessionId: this.opts.envelope.sessionId ?? 'none',
|
|
110
|
+
textLength: item.text.length,
|
|
111
|
+
})}`);
|
|
112
|
+
try {
|
|
113
|
+
await this.sendPayload({ kind: 'activity.batch', items: [item], isFinal: true });
|
|
114
|
+
logger.info(`[IMRenderer] proactive.final.accepted ${JSON.stringify({
|
|
115
|
+
taskId: this.opts.envelope.taskId,
|
|
116
|
+
sessionId: this.opts.envelope.sessionId ?? 'none',
|
|
117
|
+
})}`);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
logger.error(`[IMRenderer] proactive.final.failed ${JSON.stringify({
|
|
121
|
+
taskId: this.opts.envelope.taskId,
|
|
122
|
+
sessionId: this.opts.envelope.sessionId ?? 'none',
|
|
123
|
+
error: error instanceof Error ? error.message : String(error),
|
|
124
|
+
code: error?.code,
|
|
125
|
+
})}`);
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
logger.info(`[IMRenderer] proactive.final.suppressed ${JSON.stringify({
|
|
131
|
+
taskId: this.opts.envelope.taskId,
|
|
132
|
+
sessionId: this.opts.envelope.sessionId ?? 'none',
|
|
133
|
+
reason: 'renderer_policy',
|
|
134
|
+
})}`);
|
|
108
135
|
}
|
|
109
136
|
}
|
|
110
137
|
releaseProactiveFinal() {
|
|
@@ -150,6 +177,18 @@ export class IMRenderer {
|
|
|
150
177
|
async flush(isFinal, attention) {
|
|
151
178
|
await this.activityRecordChain;
|
|
152
179
|
if (this.usesProactiveBehavior()) {
|
|
180
|
+
if (isFinal) {
|
|
181
|
+
logger.info(`[IMRenderer] proactive.flush ${JSON.stringify({
|
|
182
|
+
taskId: this.opts.envelope.taskId,
|
|
183
|
+
sessionId: this.opts.envelope.sessionId ?? 'none',
|
|
184
|
+
activityTransport: this.opts.envelope.activityTransport ?? 'none',
|
|
185
|
+
customFinal: this.usesCustomFinal(),
|
|
186
|
+
deferredTextCount: this.deferredProactiveText.length,
|
|
187
|
+
pendingFinal: !!this.pendingProactiveFinal,
|
|
188
|
+
suppressIntermediateText: this.suppressIntermediateText(),
|
|
189
|
+
suppressActivities: this.suppressActivityItems(),
|
|
190
|
+
})}`);
|
|
191
|
+
}
|
|
153
192
|
if (isFinal === false && this.usesCustomFinal())
|
|
154
193
|
this.releaseProactiveFinal();
|
|
155
194
|
if (isFinal) {
|
|
@@ -2,47 +2,13 @@ import { readAccessPolicy, } from '../../config/access-policy.js';
|
|
|
2
2
|
import { resolvePeerView, resolvePrincipal, } from '../../config/peer-book.js';
|
|
3
3
|
import { isValidAid } from '../../aun/aid/validation.js';
|
|
4
4
|
import { readOwnerDirectoryMembership } from '../../directory/owner-directory-admission.js';
|
|
5
|
-
import { resolveAunPeerKind } from '../relation/peer-identity.js';
|
|
6
5
|
import { evaluateAppContactAdmission } from './contact-admission.js';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* AUN 出站私聊固定使用 app-v1,与入站保持相同的绑定和联系人判定。
|
|
10
|
-
* 群聊的准入单位是群,出站到群不做发言人判定。
|
|
11
|
-
*/
|
|
6
|
+
/** @deprecated Ordinary outbound messages have no contact admission gate. */
|
|
12
7
|
export async function evaluateOutboundContactAdmission(input) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
if (!isValidAid(selfAid) || !isValidAid(targetAid)) {
|
|
16
|
-
return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: 'A valid Agent AID is required for outbound contact admission' };
|
|
17
|
-
}
|
|
18
|
-
// 群目标按群放行。类型无法确认(本地无证据且远端不可达)时不额外阻拦:
|
|
19
|
-
// 这条路径由 IPC 的 callers 选定 msg scope,准入只负责名录三档判定。
|
|
20
|
-
const target = await resolveAunPeerKind(selfAid, targetAid);
|
|
21
|
-
if (target.kind === 'group')
|
|
22
|
-
return { allow: true, status: 'group' };
|
|
23
|
-
let decision;
|
|
24
|
-
try {
|
|
25
|
-
await ownerResolver.refresh(selfAid, { maxAgeMs: OWNERSHIP_CACHE_MAX_AGE_MS, allowTransient: true });
|
|
26
|
-
decision = evaluateAppContactAdmission(selfAid, targetAid);
|
|
27
|
-
}
|
|
28
|
-
catch (error) {
|
|
29
|
-
return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: error instanceof Error ? error.message : String(error) };
|
|
30
|
-
}
|
|
31
|
-
if (decision.allow) {
|
|
32
|
-
if (decision.reason === 'owner')
|
|
33
|
-
return { allow: true, status: 'owner' };
|
|
34
|
-
if (decision.reason === 'temporary')
|
|
35
|
-
return { allow: true, status: 'temporary' };
|
|
36
|
-
if (decision.reason === 'open') {
|
|
37
|
-
const policy = readAccessPolicy(selfAid);
|
|
38
|
-
return { allow: true, status: policy.allowedAids?.includes(targetAid) ? 'allowed_aid' : 'all_contacts' };
|
|
39
|
-
}
|
|
40
|
-
return { allow: true, status: 'contact' };
|
|
8
|
+
if (!isValidAid(input.selfAid) || !isValidAid(input.targetAid)) {
|
|
9
|
+
return { allow: false, code: 'CONTACT_POLICY_INVALID', status: 'absent', error: 'A valid sender and target AID are required' };
|
|
41
10
|
}
|
|
42
|
-
return { allow:
|
|
43
|
-
: decision.reason === 'blocked' ? 'CONTACT_BLOCKED' : 'CONTACT_DENIED',
|
|
44
|
-
status: decision.reason === 'unavailable' ? 'unavailable' : decision.reason === 'blocked' ? 'blocked' : 'denied',
|
|
45
|
-
error: `联系人准入未通过:${decision.reason}` };
|
|
11
|
+
return { allow: true, status: 'unrestricted' };
|
|
46
12
|
}
|
|
47
13
|
export function evaluateInboundAdmissionPreflight(input) {
|
|
48
14
|
const selfAid = String(input.selfAid || '').trim();
|
|
@@ -162,7 +128,7 @@ export function evaluateOwnerDirectoryInboundAdmission(context) {
|
|
|
162
128
|
}
|
|
163
129
|
}
|
|
164
130
|
/**
|
|
165
|
-
*
|
|
131
|
+
* 普通消息入站准入。出站不执行联系人准入。
|
|
166
132
|
*
|
|
167
133
|
* 顺序:可信 handoff → Owner/个人助理 → 群聊(准入单位是整个群)→ 黑名单
|
|
168
134
|
* → `allowAllContacts` 总开关 → 名录不可用 → 白名单 → 名录三档。
|