evolcore 0.0.47 → 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 +90 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +143 -40
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +34 -17
- package/dist/agents/codex-runner.js +36 -17
- package/dist/agents/ecagent-runner.js +7 -4
- package/dist/agents/gemini-runner.js +5 -2
- package/dist/agents/runner-types.js +5 -21
- package/dist/aun/aid/agentmd.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +722 -295
- package/dist/channels/daemon.js +9 -25
- package/dist/cli/aun-commands.js +86 -51
- package/dist/cli/code-stats.js +19 -8
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +44 -43
- package/dist/cli/directory.js +13 -2
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +9 -9
- package/dist/cli/init-channel.js +4 -6
- package/dist/cli/init.js +72 -50
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +62 -17
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/stats.js +3 -3
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +16 -51
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +13 -7
- package/dist/config/daemon-services.js +30 -3
- package/dist/config/gateway-config.js +2 -2
- package/dist/config/invoke-ipc-service.js +6 -4
- package/dist/config/peer-bind-code.js +3 -4
- package/dist/config/peer-book-store.js +62 -229
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +4 -1
- package/dist/config/provider-ipc-service.js +56 -11
- package/dist/config/provider-menu-request.js +24 -5
- package/dist/config/provider-templates.js +127 -0
- package/dist/config/providers-config.js +67 -12
- package/dist/config/providers-management.js +477 -51
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +105 -4
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +4 -0
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +36 -26
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +37 -64
- package/dist/core/capability/providers/codex-capability-provider.js +7 -8
- package/dist/core/channel-loader.js +18 -0
- package/dist/core/command/agent-control.js +32 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +126 -87
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +67 -150
- package/dist/core/command/menu-protocol.js +31 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +26 -43
- package/dist/core/command/team-workspace-items.js +81 -12
- package/dist/core/command/team-workspace-team.js +9 -71
- package/dist/core/command/topic-slash.js +9 -30
- package/dist/core/daemon-bootstrap.js +8 -1
- package/dist/core/daemon-control.js +64 -8
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +20 -3
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +11 -6
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +3 -1
- package/dist/core/message/aun-ipc-sender.js +279 -107
- 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 +41 -2
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +140 -370
- package/dist/core/message/message-log.js +29 -0
- package/dist/core/message/message-queue.js +119 -15
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +580 -134
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- 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 +328 -50
- 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/protected-paths.js +6 -6
- 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 +36 -1
- package/dist/core/relation/same-owner-proof.js +81 -112
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +13 -7
- package/dist/core/session/session-fs-store.js +91 -35
- package/dist/core/session/session-manager.js +68 -24
- package/dist/core/session/session-mapper.js +14 -34
- package/dist/core/session/session-transcript.js +5 -1
- package/dist/core/task/task-activity-store.js +84 -0
- package/dist/core/task/task-recovery-service.js +13 -0
- package/dist/core/thread/command-parser.js +7 -12
- package/dist/core/thread/thread-context-storage.js +3 -2
- package/dist/core/thread/thread-operation.js +2 -13
- package/dist/core/thread/thread-service.js +15 -46
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +12 -9
- package/dist/directory/owner-directory-cache.js +64 -28
- package/dist/directory/owner-directory-markdown.js +14 -2
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +112 -29
- package/dist/ecweb/basic-settings-service.js +3 -1
- package/dist/ecweb/message-context-service.js +1 -1
- package/dist/ecweb/pairing.js +4 -3
- package/dist/ecweb/providers-service.js +26 -1
- package/dist/ecweb/runtime/lifecycle.js +18 -8
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +36 -6
- 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 +29 -3
- package/dist/event-center/runtime.js +106 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +96 -59
- package/dist/ipc.js +38 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +63 -0
- package/dist/outputs/protocol.js +103 -0
- package/dist/outputs/service.js +266 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +114 -5
- package/dist/services/ipc-operation.js +88 -15
- package/dist/services/pack-manager.js +13 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +2 -2
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/quota-query.js +95 -0
- package/dist/stats/role-budget.js +5 -2
- package/dist/stats/writer.js +10 -6
- package/dist/trigger/audit.js +7 -0
- package/dist/trigger/authorization.js +105 -11
- package/dist/trigger/feedback.js +10 -0
- package/dist/trigger/history.js +37 -11
- package/dist/trigger/ipc-service.js +12 -1
- package/dist/trigger/manager.js +1 -0
- package/dist/trigger/scheduler.js +7 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +21 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/cross-platform.js +73 -26
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +27 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/process-introspect.js +12 -7
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/windows-shell-trust.js +2 -0
- package/dist/workbench/protocol.js +80 -0
- package/dist/workbench/service.js +359 -0
- package/ecagent/dist/types.d.ts +6 -2
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +4 -2
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +16 -1
- package/kits/docs/evolcore/directory.md +30 -12
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +124 -4
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +83 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +14 -15
- package/kits/docs/evolcore/tool-authorization.md +5 -0
- package/kits/docs/evolcore/trigger.md +12 -0
- package/kits/eck_message_manifest.json +12 -0
- package/kits/provider-templates.json +1213 -0
- package/kits/rules/04-relation.md +3 -3
- package/kits/schemas/_meta.json +14 -2
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +8 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-group/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +19 -72
- package/kits/skills/ec-provider/SKILL.md +270 -0
- package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/skills/thread-ops/SKILL.md +34 -21
- package/kits/templates/message-fragments/group-batch-item.md +1 -1
- package/kits/templates/message-fragments/group-batch.md +1 -1
- package/kits/templates/message-fragments/inject-default.md +1 -1
- package/kits/templates/message-fragments/interrupt-insert.md +1 -0
- package/kits/templates/message-fragments/item-group.md +1 -1
- package/kits/templates/message-fragments/item-private.md +1 -1
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/message-fragments/trigger-session.md +1 -1
- package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
- package/kits/templates/roles/admin.json +2 -19
- package/kits/templates/roles/member.json +0 -3
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +1 -1
- package/kits/templates/system-fragments/thread.md +7 -5
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +50 -11
- package/scripts/agent-template/shared/common.mjs +11 -6
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +62 -11
- package/scripts/agent-template/shared/template-package.mjs +189 -21
- package/scripts/agent-template/shared/template-runtime.mjs +54 -6
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +52 -14
- package/dist/cli/peer.js +0 -127
- package/dist/config/peer-operation-service.js +0 -132
- package/dist/config/peer-request-service.js +0 -532
- package/dist/core/command/connect-menu.js +0 -624
|
@@ -1,532 +0,0 @@
|
|
|
1
|
-
import crypto from 'crypto';
|
|
2
|
-
import fs from 'fs';
|
|
3
|
-
import { isValidAid } from '../aun/aid/validation.js';
|
|
4
|
-
import { recordAunPeerRoute, resolveAunPeerKind } from '../core/relation/peer-identity.js';
|
|
5
|
-
import { agentPeerOperations } from '../paths.js';
|
|
6
|
-
import { listStaticAgentAdmins, listStaticAgentOwners } from './peer-role-resolver.js';
|
|
7
|
-
import { listAgentOwners } from './access-policy.js';
|
|
8
|
-
import { PeerMutationError, mutatePeerBookPrepared, } from './peer-book-store.js';
|
|
9
|
-
export const PEER_REQUEST_TTL_MS = 20 * 60 * 1000;
|
|
10
|
-
export const PEER_REQUEST_WINDOW_MS = 60 * 60 * 1000;
|
|
11
|
-
export const PEER_REQUEST_MAX_PER_WINDOW = 3;
|
|
12
|
-
export const PEER_REQUEST_MAX_PENDING = 100;
|
|
13
|
-
export const PEER_REQUEST_MAX_RETAINED = 1000;
|
|
14
|
-
export const PEER_REQUEST_NOTE_MAX_LENGTH = 500;
|
|
15
|
-
export const PEER_REQUEST_ID_MAX_LENGTH = 128;
|
|
16
|
-
export async function mutatePeerWithOperation(input) {
|
|
17
|
-
const at = new Date(input.now ?? Date.now()).toISOString();
|
|
18
|
-
const logFile = agentPeerOperations(input.selfAid);
|
|
19
|
-
const result = await mutatePeerBookPrepared(input.selfAid, ({ peerRevision }) => {
|
|
20
|
-
if (input.expectedContactRevision !== undefined && input.expectedContactRevision !== peerRevision) {
|
|
21
|
-
throw new PeerMutationError('CONFLICT', 'Contact book changed since it was read', {
|
|
22
|
-
expectedContactRevision: input.expectedContactRevision,
|
|
23
|
-
peerRevision,
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
return {
|
|
27
|
-
mutation: input.mutation,
|
|
28
|
-
actor: input.actorId,
|
|
29
|
-
value: undefined,
|
|
30
|
-
beforeCommit: ({ peerRevision: nextRevision }) => operationLogChange(logFile, [operationRecord({
|
|
31
|
-
at,
|
|
32
|
-
op: input.operation,
|
|
33
|
-
primaryId: input.primaryId,
|
|
34
|
-
actorId: input.actorId,
|
|
35
|
-
peerRevision: nextRevision,
|
|
36
|
-
})]),
|
|
37
|
-
};
|
|
38
|
-
});
|
|
39
|
-
const { value: _value, ...mutationResult } = result;
|
|
40
|
-
return mutationResult;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* Add a canonical AUN contact as active through the Contact Book transaction.
|
|
44
|
-
* Existing pending/declined entries are intentionally promoted here, while a
|
|
45
|
-
* blocked entry remains a hard stop and must be explicitly unblocked first.
|
|
46
|
-
*/
|
|
47
|
-
export async function addPeer(input) {
|
|
48
|
-
const primaryId = String(input.primaryId || '').trim();
|
|
49
|
-
if (!isValidAid(primaryId)) {
|
|
50
|
-
throw new PeerMutationError('INVALID_AID', `Invalid contact AID: ${primaryId}`);
|
|
51
|
-
}
|
|
52
|
-
const identity = await resolveAunPeerKind(input.selfAid, primaryId);
|
|
53
|
-
if (identity.kind !== 'private') {
|
|
54
|
-
throw new PeerMutationError(identity.kind === 'group' ? 'INVALID_AID' : 'CONTACT_TYPE_UNKNOWN', identity.kind === 'group' ? `Contact Book does not support group AID: ${primaryId}`
|
|
55
|
-
: `Cannot establish private contact type (${identity.reason}): ${primaryId}`);
|
|
56
|
-
}
|
|
57
|
-
const at = new Date(input.now ?? Date.now()).toISOString();
|
|
58
|
-
const logFile = agentPeerOperations(input.selfAid);
|
|
59
|
-
const result = await mutatePeerBookPrepared(input.selfAid, ({ contact, peerRevision }) => {
|
|
60
|
-
if (input.expectedContactRevision !== undefined && input.expectedContactRevision !== peerRevision) {
|
|
61
|
-
throw new PeerMutationError('CONFLICT', 'Contact book changed since it was read', {
|
|
62
|
-
expectedContactRevision: input.expectedContactRevision,
|
|
63
|
-
peerRevision,
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
if (contact.contacts[primaryId]?.status === 'blocked') {
|
|
67
|
-
throw new PeerMutationError('CONTACT_BLOCKED', `Contact is blocked: ${primaryId}`);
|
|
68
|
-
}
|
|
69
|
-
const mutations = [
|
|
70
|
-
{ type: 'set-status', primaryId, status: 'active' },
|
|
71
|
-
];
|
|
72
|
-
if (input.displayName !== undefined) {
|
|
73
|
-
mutations.push({ type: 'set-display-name', primaryId, displayName: input.displayName });
|
|
74
|
-
}
|
|
75
|
-
return {
|
|
76
|
-
mutation: mutations.length === 1 ? mutations[0] : { type: 'batch', mutations },
|
|
77
|
-
actor: input.actorId,
|
|
78
|
-
value: undefined,
|
|
79
|
-
beforeCommit: ({ peerRevision: nextRevision }) => operationLogChange(logFile, [operationRecord({
|
|
80
|
-
at,
|
|
81
|
-
op: 'manual-add',
|
|
82
|
-
primaryId,
|
|
83
|
-
actorId: input.actorId,
|
|
84
|
-
peerRevision: nextRevision,
|
|
85
|
-
})]),
|
|
86
|
-
};
|
|
87
|
-
});
|
|
88
|
-
const { value: _value, ...mutationResult } = result;
|
|
89
|
-
return mutationResult;
|
|
90
|
-
}
|
|
91
|
-
export async function submitPeerRequest(input) {
|
|
92
|
-
const applicantAid = String(input.applicantAid || '').trim();
|
|
93
|
-
const owners = listAgentOwners(input.selfAid);
|
|
94
|
-
if (!isValidAid(applicantAid)) {
|
|
95
|
-
return { code: 'invalid-applicant', peerRevision: '' };
|
|
96
|
-
}
|
|
97
|
-
if (owners.includes(applicantAid)) {
|
|
98
|
-
return { code: 'owner', peerRevision: '' };
|
|
99
|
-
}
|
|
100
|
-
if (owners.length === 0) {
|
|
101
|
-
return { code: 'no-owner', peerRevision: '' };
|
|
102
|
-
}
|
|
103
|
-
const identity = input.routeKind
|
|
104
|
-
? recordAunPeerRoute(input.selfAid, applicantAid, input.routeKind)
|
|
105
|
-
: await resolveAunPeerKind(input.selfAid, applicantAid);
|
|
106
|
-
if (identity.kind !== 'private')
|
|
107
|
-
return { code: 'invalid-applicant', peerRevision: '' };
|
|
108
|
-
const note = normalizeNote(input.note);
|
|
109
|
-
if (note === null) {
|
|
110
|
-
return { code: 'invalid-note', peerRevision: '' };
|
|
111
|
-
}
|
|
112
|
-
const nowMs = input.now ?? Date.now();
|
|
113
|
-
const nowIso = new Date(nowMs).toISOString();
|
|
114
|
-
const logFile = agentPeerOperations(input.selfAid);
|
|
115
|
-
const result = await mutatePeerBookPrepared(input.selfAid, ({ contact }) => {
|
|
116
|
-
const expiration = collectExpiredMutations(contact, nowMs);
|
|
117
|
-
const effectiveEntry = effectiveEntryAfterExpirations(contact.contacts[applicantAid], nowMs);
|
|
118
|
-
if (effectiveEntry?.status === 'blocked') {
|
|
119
|
-
return preparedWithExpirations(expiration, { code: 'blocked', peerRevision: '' }, logFile);
|
|
120
|
-
}
|
|
121
|
-
if (effectiveEntry && (effectiveEntry.status === undefined || effectiveEntry.status === 'active')) {
|
|
122
|
-
return preparedWithExpirations(expiration, { code: 'already-contact', peerRevision: '' }, logFile);
|
|
123
|
-
}
|
|
124
|
-
const operations = readOperationLog(logFile);
|
|
125
|
-
const windowStart = nowMs - PEER_REQUEST_WINDOW_MS;
|
|
126
|
-
const recentCount = operations.filter(record => (record.primaryId === applicantAid
|
|
127
|
-
&& (record.op === 'request' || record.op === 'resubmit')
|
|
128
|
-
&& Date.parse(record.at) > windowStart
|
|
129
|
-
&& Date.parse(record.at) <= nowMs)).length;
|
|
130
|
-
if (recentCount >= PEER_REQUEST_MAX_PER_WINDOW) {
|
|
131
|
-
return preparedWithExpirations(expiration, {
|
|
132
|
-
code: 'rate-limited',
|
|
133
|
-
...(effectiveEntry?.status === 'pending' && effectiveEntry.pendingRequest
|
|
134
|
-
? {
|
|
135
|
-
requestId: effectiveEntry.pendingRequest.id,
|
|
136
|
-
submittedAt: effectiveEntry.pendingRequest.submittedAt,
|
|
137
|
-
expiresAt: effectiveEntry.pendingRequest.expiresAt,
|
|
138
|
-
}
|
|
139
|
-
: {}),
|
|
140
|
-
peerRevision: '',
|
|
141
|
-
}, logFile);
|
|
142
|
-
}
|
|
143
|
-
const counts = countRequestRecordsAfterExpirations(contact, nowMs);
|
|
144
|
-
const isExistingPending = effectiveEntry?.status === 'pending';
|
|
145
|
-
if (!isExistingPending && (counts.pending >= PEER_REQUEST_MAX_PENDING
|
|
146
|
-
|| counts.retained >= PEER_REQUEST_MAX_RETAINED)) {
|
|
147
|
-
return preparedWithExpirations(expiration, { code: 'capacity', peerRevision: '' }, logFile);
|
|
148
|
-
}
|
|
149
|
-
const requestId = `creq_${crypto.randomUUID().replace(/-/g, '')}`;
|
|
150
|
-
const expiresAt = new Date(nowMs + PEER_REQUEST_TTL_MS).toISOString();
|
|
151
|
-
const op = isExistingPending ? 'resubmit' : 'request';
|
|
152
|
-
const value = {
|
|
153
|
-
code: isExistingPending ? 'resubmitted' : 'submitted',
|
|
154
|
-
requestId,
|
|
155
|
-
submittedAt: nowIso,
|
|
156
|
-
expiresAt,
|
|
157
|
-
peerRevision: '',
|
|
158
|
-
};
|
|
159
|
-
const mutations = [
|
|
160
|
-
...expiration.mutations,
|
|
161
|
-
{
|
|
162
|
-
type: 'set-request',
|
|
163
|
-
primaryId: applicantAid,
|
|
164
|
-
request: { id: requestId, submittedAt: nowIso, expiresAt },
|
|
165
|
-
},
|
|
166
|
-
];
|
|
167
|
-
return {
|
|
168
|
-
mutation: { type: 'batch', mutations },
|
|
169
|
-
actor: applicantAid,
|
|
170
|
-
value,
|
|
171
|
-
beforeCommit: ({ peerRevision }) => operationLogChange(logFile, [
|
|
172
|
-
...expiration.events.map(event => ({ ...event, peerRevision })),
|
|
173
|
-
operationRecord({
|
|
174
|
-
at: nowIso,
|
|
175
|
-
op,
|
|
176
|
-
primaryId: applicantAid,
|
|
177
|
-
requestId,
|
|
178
|
-
expiresAt,
|
|
179
|
-
sourceChannelKey: input.sourceChannelKey,
|
|
180
|
-
...(note ? { note } : {}),
|
|
181
|
-
peerRevision,
|
|
182
|
-
}),
|
|
183
|
-
]),
|
|
184
|
-
};
|
|
185
|
-
});
|
|
186
|
-
return { ...result.value, peerRevision: result.peerRevision };
|
|
187
|
-
}
|
|
188
|
-
export async function reviewPeerRequest(input) {
|
|
189
|
-
const nowMs = input.now ?? Date.now();
|
|
190
|
-
const nowIso = new Date(nowMs).toISOString();
|
|
191
|
-
const logFile = agentPeerOperations(input.selfAid);
|
|
192
|
-
try {
|
|
193
|
-
const result = await mutatePeerBookPrepared(input.selfAid, ({ contact, peerRevision }) => {
|
|
194
|
-
const owners = listStaticAgentOwners(input.selfAid, { fresh: true });
|
|
195
|
-
const admins = listStaticAgentAdmins(input.selfAid, { fresh: true });
|
|
196
|
-
const selectedManager = input.reviewerRole === undefined
|
|
197
|
-
&& input.actorId === input.approverId
|
|
198
|
-
&& (owners.includes(input.approverId) || admins.includes(input.approverId));
|
|
199
|
-
const managementReviewer = input.actorId === input.approverId
|
|
200
|
-
&& ((input.reviewerRole === 'admin' && admins.includes(input.actorId))
|
|
201
|
-
|| (input.reviewerRole === 'owner' && owners.includes(input.actorId)));
|
|
202
|
-
if (!selectedManager && !managementReviewer) {
|
|
203
|
-
return preparedNoop({ code: 'forbidden', peerRevision });
|
|
204
|
-
}
|
|
205
|
-
if (peerRevision !== input.expectedContactRevision) {
|
|
206
|
-
return preparedNoop({ code: 'revision-conflict', peerRevision });
|
|
207
|
-
}
|
|
208
|
-
const entry = contact.contacts[input.primaryId];
|
|
209
|
-
if (!entry || entry.status !== 'pending' || entry.pendingRequest?.id !== input.requestId) {
|
|
210
|
-
return preparedNoop({ code: 'request-stale', peerRevision });
|
|
211
|
-
}
|
|
212
|
-
const requestMetadata = {
|
|
213
|
-
requestId: entry.pendingRequest.id,
|
|
214
|
-
expiresAt: entry.pendingRequest.expiresAt,
|
|
215
|
-
};
|
|
216
|
-
if (Date.parse(entry.pendingRequest.expiresAt) <= nowMs) {
|
|
217
|
-
const mutation = {
|
|
218
|
-
type: 'expire-request',
|
|
219
|
-
primaryId: input.primaryId,
|
|
220
|
-
requestId: input.requestId,
|
|
221
|
-
now: nowIso,
|
|
222
|
-
};
|
|
223
|
-
return {
|
|
224
|
-
mutation,
|
|
225
|
-
actor: input.actorId,
|
|
226
|
-
value: { code: 'request-expired', peerRevision, ...requestMetadata },
|
|
227
|
-
beforeCommit: ({ peerRevision: nextRevision }) => operationLogChange(logFile, [operationRecord({
|
|
228
|
-
at: nowIso,
|
|
229
|
-
op: 'expire',
|
|
230
|
-
primaryId: input.primaryId,
|
|
231
|
-
requestId: input.requestId,
|
|
232
|
-
peerRevision: nextRevision,
|
|
233
|
-
})]),
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
const code = input.decision === 'approve'
|
|
237
|
-
? 'approved'
|
|
238
|
-
: input.decision === 'reject'
|
|
239
|
-
? 'rejected'
|
|
240
|
-
: 'blocked';
|
|
241
|
-
return {
|
|
242
|
-
mutation: {
|
|
243
|
-
type: 'review-request',
|
|
244
|
-
primaryId: input.primaryId,
|
|
245
|
-
requestId: input.requestId,
|
|
246
|
-
decision: input.decision,
|
|
247
|
-
now: nowIso,
|
|
248
|
-
},
|
|
249
|
-
actor: input.actorId,
|
|
250
|
-
value: { code, peerRevision, ...requestMetadata },
|
|
251
|
-
beforeCommit: ({ peerRevision: nextRevision }) => operationLogChange(logFile, [operationRecord({
|
|
252
|
-
at: nowIso,
|
|
253
|
-
op: input.decision === 'approve' ? 'approve' : input.decision === 'reject' ? 'reject' : 'block',
|
|
254
|
-
primaryId: input.primaryId,
|
|
255
|
-
requestId: input.requestId,
|
|
256
|
-
actorId: input.actorId,
|
|
257
|
-
peerRevision: nextRevision,
|
|
258
|
-
})]),
|
|
259
|
-
};
|
|
260
|
-
});
|
|
261
|
-
return { ...result.value, peerRevision: result.peerRevision };
|
|
262
|
-
}
|
|
263
|
-
catch (error) {
|
|
264
|
-
if (error instanceof PeerMutationError && error.code === 'REQUEST_EXPIRED') {
|
|
265
|
-
return { code: 'request-expired', peerRevision: input.expectedContactRevision };
|
|
266
|
-
}
|
|
267
|
-
throw error;
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
export async function expirePendingPeerRequests(selfAid, now = Date.now()) {
|
|
271
|
-
const nowIso = new Date(now).toISOString();
|
|
272
|
-
const logFile = agentPeerOperations(selfAid);
|
|
273
|
-
const result = await mutatePeerBookPrepared(selfAid, ({ contact }) => {
|
|
274
|
-
const expiration = collectExpiredMutations(contact, now);
|
|
275
|
-
if (expiration.mutations.length === 0)
|
|
276
|
-
return preparedNoop(0);
|
|
277
|
-
return {
|
|
278
|
-
mutation: { type: 'batch', mutations: expiration.mutations },
|
|
279
|
-
actor: 'contact-request-expiry',
|
|
280
|
-
value: expiration.mutations.length,
|
|
281
|
-
beforeCommit: ({ peerRevision }) => operationLogChange(logFile, expiration.events.map(event => ({ ...event, peerRevision }))),
|
|
282
|
-
};
|
|
283
|
-
});
|
|
284
|
-
return result.value;
|
|
285
|
-
}
|
|
286
|
-
export async function listPendingPeerRequests(selfAid, now = Date.now()) {
|
|
287
|
-
await expirePendingPeerRequests(selfAid, now);
|
|
288
|
-
const result = await mutatePeerBookPrepared(selfAid, ({ contact, peerRevision }) => preparedNoop(Object.entries(contact.contacts)
|
|
289
|
-
.filter(([, entry]) => entry.status === 'pending' && entry.pendingRequest)
|
|
290
|
-
.map(([primaryId, entry]) => ({
|
|
291
|
-
primaryId,
|
|
292
|
-
requestId: entry.pendingRequest.id,
|
|
293
|
-
submittedAt: entry.pendingRequest.submittedAt,
|
|
294
|
-
expiresAt: entry.pendingRequest.expiresAt,
|
|
295
|
-
peerRevision,
|
|
296
|
-
}))));
|
|
297
|
-
return result.value;
|
|
298
|
-
}
|
|
299
|
-
/** Return only the authenticated applicant's own admission/request state. */
|
|
300
|
-
export async function queryOwnPeerRequestStatus(input) {
|
|
301
|
-
const applicantAid = String(input.applicantAid || '').trim();
|
|
302
|
-
if (!isValidAid(applicantAid))
|
|
303
|
-
return protocolResult('NOT_ALLOWED');
|
|
304
|
-
const now = input.now ?? Date.now();
|
|
305
|
-
const rawRequestId = input.requestId;
|
|
306
|
-
if (rawRequestId !== undefined && typeof rawRequestId !== 'string')
|
|
307
|
-
return protocolResult('NOT_ALLOWED');
|
|
308
|
-
const requestedRequestId = rawRequestId?.trim();
|
|
309
|
-
if (requestedRequestId !== undefined
|
|
310
|
-
&& (!requestedRequestId || requestedRequestId.length > PEER_REQUEST_ID_MAX_LENGTH)) {
|
|
311
|
-
return protocolResult('NOT_ALLOWED');
|
|
312
|
-
}
|
|
313
|
-
const owners = listAgentOwners(input.selfAid);
|
|
314
|
-
const result = await mutatePeerBookPrepared(input.selfAid, ({ contact }) => {
|
|
315
|
-
const logFile = agentPeerOperations(input.selfAid);
|
|
316
|
-
const expiration = collectExpiredMutations(contact, now);
|
|
317
|
-
const entry = effectiveEntryAfterExpirations(contact.contacts[applicantAid], now);
|
|
318
|
-
const operations = readOperationLog(logFile).filter(record => record.primaryId === applicantAid);
|
|
319
|
-
const latestRequestOperation = [...operations].reverse().find(record => (!!record.requestId
|
|
320
|
-
&& (record.op === 'request' || record.op === 'resubmit' || record.op === 'approve'
|
|
321
|
-
|| record.op === 'reject' || record.op === 'expire' || record.op === 'block')));
|
|
322
|
-
if (requestedRequestId !== undefined && latestRequestOperation?.requestId !== requestedRequestId) {
|
|
323
|
-
return preparedNoop(protocolResult('NOT_ALLOWED'));
|
|
324
|
-
}
|
|
325
|
-
const requestMetadata = requestMetadataFor(operations, latestRequestOperation?.requestId);
|
|
326
|
-
let value;
|
|
327
|
-
if (owners.includes(applicantAid)
|
|
328
|
-
|| (entry && (entry.status === undefined || entry.status === 'active'))) {
|
|
329
|
-
value = protocolResult('APPROVED', requestMetadata);
|
|
330
|
-
}
|
|
331
|
-
else if (entry?.status === 'blocked') {
|
|
332
|
-
value = protocolResult('NOT_ALLOWED');
|
|
333
|
-
}
|
|
334
|
-
else if (entry?.status === 'pending' && entry.pendingRequest) {
|
|
335
|
-
value = protocolResult('PENDING', {
|
|
336
|
-
requestId: entry.pendingRequest.id,
|
|
337
|
-
expiresAt: entry.pendingRequest.expiresAt,
|
|
338
|
-
});
|
|
339
|
-
}
|
|
340
|
-
else if (entry?.status === 'declined') {
|
|
341
|
-
value = protocolResult('EXPIRED', {
|
|
342
|
-
requestId: latestRequestOperation?.op === 'expire' ? latestRequestOperation.requestId : requestMetadata.requestId,
|
|
343
|
-
expiresAt: entry.declinedAt ?? requestMetadata.expiresAt,
|
|
344
|
-
});
|
|
345
|
-
}
|
|
346
|
-
else if (latestRequestOperation?.op === 'reject') {
|
|
347
|
-
value = protocolResult('REJECTED', requestMetadata);
|
|
348
|
-
}
|
|
349
|
-
else if (latestRequestOperation?.op === 'expire') {
|
|
350
|
-
value = protocolResult('EXPIRED', requestMetadata);
|
|
351
|
-
}
|
|
352
|
-
else if (owners.length === 0) {
|
|
353
|
-
value = protocolResult('NOT_ALLOWED');
|
|
354
|
-
}
|
|
355
|
-
else {
|
|
356
|
-
value = protocolResult('CONTACT_REQUIRED');
|
|
357
|
-
}
|
|
358
|
-
if (expiration.mutations.length === 0)
|
|
359
|
-
return preparedNoop(value);
|
|
360
|
-
return {
|
|
361
|
-
mutation: { type: 'batch', mutations: expiration.mutations },
|
|
362
|
-
actor: 'contact-request-expiry',
|
|
363
|
-
value,
|
|
364
|
-
beforeCommit: ({ peerRevision }) => operationLogChange(logFile, expiration.events.map(event => ({ ...event, peerRevision }))),
|
|
365
|
-
};
|
|
366
|
-
});
|
|
367
|
-
return result.value;
|
|
368
|
-
}
|
|
369
|
-
export function peerRequestSubmissionProtocolResult(result) {
|
|
370
|
-
const metadata = { requestId: result.requestId, expiresAt: result.expiresAt };
|
|
371
|
-
switch (result.code) {
|
|
372
|
-
case 'submitted':
|
|
373
|
-
case 'resubmitted':
|
|
374
|
-
return protocolResult('SUBMITTED', metadata);
|
|
375
|
-
case 'already-contact':
|
|
376
|
-
case 'owner':
|
|
377
|
-
return protocolResult('APPROVED', metadata);
|
|
378
|
-
case 'rate-limited':
|
|
379
|
-
return protocolResult('RATE_LIMITED', metadata);
|
|
380
|
-
default:
|
|
381
|
-
return protocolResult('NOT_ALLOWED', metadata);
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
export function findPeerRequestNote(selfAid, requestId) {
|
|
385
|
-
const records = readOperationLog(agentPeerOperations(selfAid));
|
|
386
|
-
return [...records].reverse().find(record => (record.requestId === requestId
|
|
387
|
-
&& (record.op === 'request' || record.op === 'resubmit')))?.note;
|
|
388
|
-
}
|
|
389
|
-
function normalizeNote(value) {
|
|
390
|
-
const note = String(value ?? '').trim();
|
|
391
|
-
if (note.length > PEER_REQUEST_NOTE_MAX_LENGTH)
|
|
392
|
-
return null;
|
|
393
|
-
return note;
|
|
394
|
-
}
|
|
395
|
-
function requestMetadataFor(operations, requestId) {
|
|
396
|
-
if (!requestId)
|
|
397
|
-
return {};
|
|
398
|
-
const submitted = [...operations].reverse().find(record => (record.requestId === requestId && (record.op === 'request' || record.op === 'resubmit')));
|
|
399
|
-
const submittedAt = submitted ? Date.parse(submitted.at) : Number.NaN;
|
|
400
|
-
return {
|
|
401
|
-
requestId,
|
|
402
|
-
expiresAt: submitted?.expiresAt
|
|
403
|
-
?? (Number.isFinite(submittedAt) ? new Date(submittedAt + PEER_REQUEST_TTL_MS).toISOString() : undefined),
|
|
404
|
-
};
|
|
405
|
-
}
|
|
406
|
-
function protocolResult(status, metadata = {}) {
|
|
407
|
-
return {
|
|
408
|
-
status,
|
|
409
|
-
requestId: metadata.requestId ?? null,
|
|
410
|
-
expiresAt: metadata.expiresAt ?? null,
|
|
411
|
-
};
|
|
412
|
-
}
|
|
413
|
-
function collectExpiredMutations(book, now) {
|
|
414
|
-
const mutations = [];
|
|
415
|
-
const events = [];
|
|
416
|
-
for (const [primaryId, entry] of Object.entries(book.contacts)) {
|
|
417
|
-
if (entry.status !== 'pending' || !entry.pendingRequest)
|
|
418
|
-
continue;
|
|
419
|
-
if (Date.parse(entry.pendingRequest.expiresAt) > now)
|
|
420
|
-
continue;
|
|
421
|
-
mutations.push({
|
|
422
|
-
type: 'expire-request',
|
|
423
|
-
primaryId,
|
|
424
|
-
requestId: entry.pendingRequest.id,
|
|
425
|
-
now: new Date(now).toISOString(),
|
|
426
|
-
});
|
|
427
|
-
events.push(operationRecord({
|
|
428
|
-
at: new Date(now).toISOString(),
|
|
429
|
-
op: 'expire',
|
|
430
|
-
primaryId,
|
|
431
|
-
requestId: entry.pendingRequest.id,
|
|
432
|
-
peerRevision: '',
|
|
433
|
-
}));
|
|
434
|
-
}
|
|
435
|
-
return { mutations, events };
|
|
436
|
-
}
|
|
437
|
-
function effectiveEntryAfterExpirations(entry, now) {
|
|
438
|
-
if (entry?.status === 'pending' && entry.pendingRequest && Date.parse(entry.pendingRequest.expiresAt) <= now) {
|
|
439
|
-
return { ...entry, status: 'declined', pendingRequest: undefined, declinedAt: entry.pendingRequest.expiresAt };
|
|
440
|
-
}
|
|
441
|
-
return entry;
|
|
442
|
-
}
|
|
443
|
-
function countRequestRecordsAfterExpirations(book, now) {
|
|
444
|
-
let pending = 0;
|
|
445
|
-
let declined = 0;
|
|
446
|
-
for (const entry of Object.values(book.contacts)) {
|
|
447
|
-
const effective = effectiveEntryAfterExpirations(entry, now);
|
|
448
|
-
if (effective?.status === 'pending')
|
|
449
|
-
pending += 1;
|
|
450
|
-
else if (effective?.status === 'declined')
|
|
451
|
-
declined += 1;
|
|
452
|
-
}
|
|
453
|
-
return { pending, retained: pending + declined };
|
|
454
|
-
}
|
|
455
|
-
function preparedWithExpirations(expiration, value, logFile) {
|
|
456
|
-
if (expiration.mutations.length === 0)
|
|
457
|
-
return preparedNoop(value);
|
|
458
|
-
return {
|
|
459
|
-
mutation: { type: 'batch', mutations: expiration.mutations },
|
|
460
|
-
actor: 'contact-request-expiry',
|
|
461
|
-
value,
|
|
462
|
-
beforeCommit: ({ peerRevision }) => operationLogChange(logFile, expiration.events.map(event => ({ ...event, peerRevision }))),
|
|
463
|
-
};
|
|
464
|
-
}
|
|
465
|
-
function preparedNoop(value) {
|
|
466
|
-
return { value };
|
|
467
|
-
}
|
|
468
|
-
function readOperationLog(file) {
|
|
469
|
-
let raw;
|
|
470
|
-
try {
|
|
471
|
-
raw = fs.readFileSync(file, 'utf8');
|
|
472
|
-
}
|
|
473
|
-
catch (error) {
|
|
474
|
-
if (error?.code === 'ENOENT')
|
|
475
|
-
return [];
|
|
476
|
-
throw new PeerMutationError('CONTACT_OPERATION_LOG_INVALID', `Cannot read contact operation log: ${error instanceof Error ? error.message : String(error)}`);
|
|
477
|
-
}
|
|
478
|
-
const records = [];
|
|
479
|
-
for (const [index, line] of raw.split('\n').entries()) {
|
|
480
|
-
if (!line.trim())
|
|
481
|
-
continue;
|
|
482
|
-
try {
|
|
483
|
-
const record = JSON.parse(line);
|
|
484
|
-
if (!record || typeof record !== 'object' || typeof record.at !== 'string'
|
|
485
|
-
|| !Number.isFinite(Date.parse(record.at)) || typeof record.op !== 'string'
|
|
486
|
-
|| !['request', 'resubmit', 'approve', 'reject', 'expire', 'block', 'unblock', 'manual-add'].includes(record.op)
|
|
487
|
-
|| typeof record.primaryId !== 'string' || !isValidAid(record.primaryId)
|
|
488
|
-
|| (record.requestId !== undefined && typeof record.requestId !== 'string')
|
|
489
|
-
|| (record.expiresAt !== undefined && (!isValidIsoDate(record.expiresAt)))
|
|
490
|
-
|| (record.actorId !== undefined && typeof record.actorId !== 'string')
|
|
491
|
-
|| (record.sourceChannelKey !== undefined && typeof record.sourceChannelKey !== 'string')
|
|
492
|
-
|| (record.note !== undefined && (typeof record.note !== 'string' || record.note.length > PEER_REQUEST_NOTE_MAX_LENGTH))
|
|
493
|
-
|| typeof record.peerRevision !== 'string')
|
|
494
|
-
throw new Error('invalid record');
|
|
495
|
-
records.push(record);
|
|
496
|
-
}
|
|
497
|
-
catch (error) {
|
|
498
|
-
throw new PeerMutationError('CONTACT_OPERATION_LOG_INVALID', `Invalid contact operation log record at line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`);
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
return records;
|
|
502
|
-
}
|
|
503
|
-
function isValidIsoDate(value) {
|
|
504
|
-
return Number.isFinite(Date.parse(value));
|
|
505
|
-
}
|
|
506
|
-
function operationLogChange(file, records) {
|
|
507
|
-
if (records.length === 0)
|
|
508
|
-
return undefined;
|
|
509
|
-
// Validate the existing log while the Contact Book lock is held. The log is
|
|
510
|
-
// part of the same journal transaction as contact.json, so a malformed log
|
|
511
|
-
// must fail closed before either file is changed.
|
|
512
|
-
readOperationLog(file);
|
|
513
|
-
let before;
|
|
514
|
-
try {
|
|
515
|
-
before = fs.readFileSync(file, 'utf8');
|
|
516
|
-
}
|
|
517
|
-
catch (error) {
|
|
518
|
-
if (error?.code === 'ENOENT')
|
|
519
|
-
before = null;
|
|
520
|
-
else
|
|
521
|
-
throw error;
|
|
522
|
-
}
|
|
523
|
-
const prefix = before && !before.endsWith('\n') ? `${before}\n` : (before ?? '');
|
|
524
|
-
return {
|
|
525
|
-
file,
|
|
526
|
-
before,
|
|
527
|
-
after: `${prefix}${records.map(record => JSON.stringify(record)).join('\n')}\n`,
|
|
528
|
-
};
|
|
529
|
-
}
|
|
530
|
-
function operationRecord(input) {
|
|
531
|
-
return { id: `evt_${crypto.randomUUID().replace(/-/g, '')}`, ...input };
|
|
532
|
-
}
|