evolcore 0.0.46 → 0.0.48
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 +93 -0
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +139 -39
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +43 -18
- package/dist/agents/codex/app-server-client.js +32 -23
- package/dist/agents/codex-runner.js +31 -16
- 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/group/fs-download.js +1 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +100 -32
- package/dist/channels/daemon.js +10 -26
- 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 +65 -76
- package/dist/cli/daemon-lifecycle-client.js +17 -3
- package/dist/cli/directory.js +7 -1
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +2 -8
- package/dist/cli/init-channel.js +6 -8
- package/dist/cli/init.js +74 -46
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/restart-monitor.js +104 -28
- package/dist/cli/role.js +61 -17
- package/dist/cli/stats.js +3 -3
- package/dist/cli/task-context.js +83 -15
- package/dist/cli/thread-command.js +16 -51
- package/dist/cli/upgrade-command.js +4 -2
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-manager.js +31 -23
- 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 +59 -218
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +161 -6
- 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 +59 -8
- package/dist/config/providers-management.js +467 -49
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +228 -20
- package/dist/config/schema-registry.js +6 -2
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +10 -5
- package/dist/core/auth/agent-delegation.js +10 -4
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +3 -0
- package/dist/core/auth/delegation-diagnostics.js +56 -15
- package/dist/core/auth/operation-authorizer.js +26 -1
- package/dist/core/auth/operation-catalog.js +28 -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/command-handler.js +81 -85
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +65 -153
- package/dist/core/command/menu-protocol.js +7 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +30 -49
- 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 +19 -10
- package/dist/core/daemon-control.js +8 -10
- package/dist/core/daemon-lifecycle.js +50 -40
- package/dist/core/evolagent-registry.js +22 -3
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/host-snapshot.js +9 -4
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +31 -8
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +6 -4
- package/dist/core/memory/consolidation.js +6 -6
- package/dist/core/message/aun-ipc-sender.js +165 -55
- package/dist/core/message/im-renderer.js +1 -1
- package/dist/core/message/message-bridge.js +51 -334
- package/dist/core/message/message-log.js +5 -0
- package/dist/core/message/message-queue.js +22 -0
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +429 -116
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/ownership/owner-resolver.js +355 -60
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/relation/peer-identity.js +28 -2
- package/dist/core/relation/same-owner-proof.js +81 -111
- package/dist/core/session/adapters/claude-session-file-adapter.js +1 -1
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +49 -14
- 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-image-resources.js +1 -1
- package/dist/core/task/task-recovery-service.js +12 -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/directory/owner-directory-admission.js +1 -1
- package/dist/directory/owner-directory-cache.js +45 -28
- package/dist/directory/owner-directory-markdown.js +13 -1
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/eck/message-renderer.js +84 -24
- 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 +82 -23
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +6 -17
- package/dist/event-center/registry.js +13 -2
- package/dist/event-center/runtime.js +103 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +129 -93
- package/dist/ipc.js +15 -3
- package/dist/outputs/events.js +62 -0
- package/dist/outputs/protocol.js +102 -0
- package/dist/outputs/service.js +279 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +89 -4
- package/dist/services/ipc-operation.js +4 -15
- package/dist/services/pack-manager.js +12 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +1 -1
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +305 -24
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- 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 +11 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +9 -3
- package/dist/trigger/state.js +7 -0
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/aid-bind.js +155 -18
- package/dist/utils/atomic-write.js +3 -3
- package/dist/utils/cross-platform.js +97 -31
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +40 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/instance-registry.js +61 -0
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/process-introspect.js +158 -8
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/upgrade-jobs.js +4 -4
- 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 +2 -2
- package/kits/docs/evolcore/aid.md +3 -1
- package/kits/docs/evolcore/config.md +12 -0
- package/kits/docs/evolcore/directory.md +22 -3
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +133 -5
- package/kits/docs/evolcore/role.md +80 -0
- package/kits/docs/evolcore/services.md +6 -6
- 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 +10 -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/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ability/references/calling.md +1 -1
- 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 +221 -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/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +3 -3
- 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 +6 -5
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +4 -1
- package/scripts/agent-template/shared/common.mjs +2 -3
- package/scripts/agent-template/shared/template-contract.mjs +2 -1
- package/scripts/agent-template/shared/template-package.mjs +9 -2
- package/scripts/agent-template/shared/template-runtime.mjs +20 -5
- package/scripts/agent-template/team-pack.mjs +6 -3
- 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,14 +1,17 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import path from 'path';
|
|
3
|
-
import { randomUUID } from 'crypto';
|
|
4
|
-
import { agentOwnerBindingRejectionPath, resolvePaths } from '../../paths.js';
|
|
3
|
+
import { createHash, randomUUID } from 'crypto';
|
|
4
|
+
import { agentMdPath, agentOwnerBindingRejectionPath, ownershipCachePath, resolvePaths } from '../../paths.js';
|
|
5
5
|
import { isValidAid } from '../../aun/aid/validation.js';
|
|
6
6
|
import { atomicReadJson } from '../../utils/atomic-write.js';
|
|
7
7
|
import { configuredOwnerList as readConfiguredOwnerList } from '../../config/owner-config.js';
|
|
8
8
|
import { logger, logOwnershipEvent, ownershipErrorCode } from '../../utils/logger.js';
|
|
9
9
|
import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
|
|
10
|
+
import { registerContent, verifyFile } from '../file-integrity/store.js';
|
|
11
|
+
import { atomicWrite } from '../../utils/atomic-write.js';
|
|
10
12
|
export const OWNERSHIP_CACHE_MAX_AGE_MS = 30 * 60_000;
|
|
11
|
-
export const OWNERSHIP_AUTHORIZATION_MAX_AGE_MS =
|
|
13
|
+
export const OWNERSHIP_AUTHORIZATION_MAX_AGE_MS = OWNERSHIP_CACHE_MAX_AGE_MS;
|
|
14
|
+
export const OWNERSHIP_RETRY_BASE_MS = 5_000;
|
|
12
15
|
const CREATION_BIND_OPERATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
13
16
|
/** Only use the task returned by this create's bind call. Never select a latest task. */
|
|
14
17
|
export function creationOwnershipBinding(task, subjectAid, ownerAid) {
|
|
@@ -35,15 +38,44 @@ export class OwnershipError extends Error {
|
|
|
35
38
|
this.name = 'OwnershipError';
|
|
36
39
|
}
|
|
37
40
|
}
|
|
41
|
+
/** Shared classification for Ownership and same-Owner authorization evidence. */
|
|
42
|
+
export function isTransientOwnershipRefreshFailure(error) {
|
|
43
|
+
const details = error && typeof error === 'object' ? error : {};
|
|
44
|
+
const code = String(details.code ?? details.stringCode ?? '').toUpperCase();
|
|
45
|
+
const message = error instanceof Error ? error.message
|
|
46
|
+
: typeof details.message === 'string' ? details.message : String(error);
|
|
47
|
+
if (['INVALID', 'CONFLICT', 'FORBIDDEN', 'NOT_APPLICABLE', 'OWNER_LOCKED', 'TASK_MISMATCH',
|
|
48
|
+
'CONSENSUS_MISMATCH', 'UNSUPPORTED_PROTOCOL', 'PERSISTENCE_UNAVAILABLE'].includes(code))
|
|
49
|
+
return false;
|
|
50
|
+
if (/projection.*(?:does not match|conflict)|(?:agent|owner)\.md changed (?:while|during)|NS relation changed .*consensus check|digest does not match authoritative observation|Storage material changed during authoritative read/i.test(message))
|
|
51
|
+
return false;
|
|
52
|
+
if (details.retryable === false)
|
|
53
|
+
return false;
|
|
54
|
+
if (details.retryable === true)
|
|
55
|
+
return true;
|
|
56
|
+
return code === 'TIMEOUT' || code === 'NETWORK_ERROR' || code === 'UNAVAILABLE'
|
|
57
|
+
|| code === 'CLIENT_DISCONNECTED' || code === 'CONNECTION_FAILED'
|
|
58
|
+
|| code === 'GATEWAY_UNAVAILABLE' || code === 'CONNECTION_UNAVAILABLE'
|
|
59
|
+
|| code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ETIMEDOUT'
|
|
60
|
+
|| code === 'ENETUNREACH' || code === 'EAI_AGAIN' || code === 'ENOTFOUND' || code === 'EHOSTUNREACH'
|
|
61
|
+
|| /timed out|timeout|connection reset|connection refused|connection closed|socket hang up|not connected|network error|fetch failed|gateway unavailable|gateway timeout|temporarily unavailable/i.test(message);
|
|
62
|
+
}
|
|
38
63
|
export class OwnerResolver {
|
|
39
64
|
options;
|
|
40
65
|
subjects = new Map();
|
|
66
|
+
authorizationChecks = new Map();
|
|
41
67
|
daemonAid;
|
|
42
68
|
/** Compatibility binding targets loaded from config; never an Owner authorization source. */
|
|
43
69
|
configuredOwners = new Map();
|
|
44
70
|
configuredOwnerFileRevision = new Map();
|
|
45
71
|
listeners = new Set();
|
|
46
72
|
updateListeners = new Set();
|
|
73
|
+
cacheFile;
|
|
74
|
+
rootScope;
|
|
75
|
+
cacheEntries = new Map();
|
|
76
|
+
cacheWriteQueued = false;
|
|
77
|
+
activeQueries = 0;
|
|
78
|
+
queryWaiters = [];
|
|
47
79
|
constructor(options = {}) {
|
|
48
80
|
this.options = options;
|
|
49
81
|
}
|
|
@@ -54,6 +86,170 @@ export class OwnerResolver {
|
|
|
54
86
|
getDaemonAid() {
|
|
55
87
|
return this.daemonAid;
|
|
56
88
|
}
|
|
89
|
+
registerEvidenceClient(subjectAid, client, store) {
|
|
90
|
+
const subject = this.subject(subjectAid);
|
|
91
|
+
if (subject.client && subject.client !== client) {
|
|
92
|
+
subject.generation++;
|
|
93
|
+
subject.epoch++;
|
|
94
|
+
}
|
|
95
|
+
subject.client = client;
|
|
96
|
+
subject.store = store;
|
|
97
|
+
subject.view.connected = client.isReady;
|
|
98
|
+
}
|
|
99
|
+
unregisterEvidenceClient(subjectAid, client) {
|
|
100
|
+
const subject = this.subjects.get(subjectAid);
|
|
101
|
+
if (subject?.client === client) {
|
|
102
|
+
subject.store = undefined;
|
|
103
|
+
this.detachClient(subjectAid, client);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
invalidateEvidence(aid) {
|
|
107
|
+
this.loadCache();
|
|
108
|
+
for (const [subjectAid, cached] of this.cacheEntries) {
|
|
109
|
+
if (subjectAid === aid || cached.ownerAid === aid)
|
|
110
|
+
this.cacheEntries.delete(subjectAid);
|
|
111
|
+
}
|
|
112
|
+
this.writeCache();
|
|
113
|
+
for (const subject of this.subjects.values()) {
|
|
114
|
+
if (subject.view.subjectAid === aid || subject.view.relation?.ownerAid === aid) {
|
|
115
|
+
this.invalidate(subject, 'Ownership material changed; fresh consensus is required');
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async queryConsensus(client, aid) {
|
|
120
|
+
return this.query(() => client.checkOwnershipConsensus(aid, true));
|
|
121
|
+
}
|
|
122
|
+
/** One bounded network budget shared by all subjects and both authorization consumers. */
|
|
123
|
+
async query(operation) {
|
|
124
|
+
const limit = Math.max(1, this.options.queryConcurrency ?? 4);
|
|
125
|
+
if (this.activeQueries >= limit)
|
|
126
|
+
await new Promise(resolve => this.queryWaiters.push(resolve));
|
|
127
|
+
else
|
|
128
|
+
this.activeQueries++;
|
|
129
|
+
try {
|
|
130
|
+
return await operation();
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
const next = this.queryWaiters.shift();
|
|
134
|
+
if (next)
|
|
135
|
+
next();
|
|
136
|
+
else
|
|
137
|
+
this.activeQueries--;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
loadCache() {
|
|
141
|
+
const file = this.options.cachePath?.() ?? ownershipCachePath();
|
|
142
|
+
if (this.cacheFile === file)
|
|
143
|
+
return;
|
|
144
|
+
this.cacheFile = file;
|
|
145
|
+
this.cacheEntries.clear();
|
|
146
|
+
try {
|
|
147
|
+
const checked = verifyFile(file, { requireRegistered: true });
|
|
148
|
+
if (checked.status !== 'verified' || !checked.bytes)
|
|
149
|
+
return;
|
|
150
|
+
const raw = JSON.parse(checked.bytes.toString('utf8'));
|
|
151
|
+
const now = this.now();
|
|
152
|
+
if (raw.schemaVersion !== 1 || !Number.isSafeInteger(raw.savedAt) || raw.savedAt > now
|
|
153
|
+
|| !raw.entries || typeof raw.entries !== 'object' || Array.isArray(raw.entries))
|
|
154
|
+
return;
|
|
155
|
+
for (const [aid, value] of Object.entries(raw.entries)) {
|
|
156
|
+
const view = value;
|
|
157
|
+
if (!view || typeof view !== 'object' || !isValidAid(aid) || view.subjectAid !== aid || view.consensusStatus !== 'consensus'
|
|
158
|
+
|| !view.consensus || view.consensus.sub_aid !== aid || view.consensus.status !== 'consensus'
|
|
159
|
+
|| view.consensus.lock !== 'locked' || !view.ownerAid || !isValidAid(view.ownerAid)
|
|
160
|
+
|| view.ownerAid === aid || view.consensus.owner_aid !== view.ownerAid
|
|
161
|
+
|| !Number.isSafeInteger(view.consensus.relation_version) || view.consensus.relation_version < 1
|
|
162
|
+
|| !/^[a-f0-9]{64}$/.test(view.consensus.agent_md_sha256 ?? '')
|
|
163
|
+
|| !Number.isSafeInteger(view.checkedAt) || view.checkedAt > now
|
|
164
|
+
|| view.checkedAt > raw.savedAt || now - view.checkedAt >= OWNERSHIP_CACHE_MAX_AGE_MS
|
|
165
|
+
|| view.validUntil !== view.checkedAt + OWNERSHIP_CACHE_MAX_AGE_MS
|
|
166
|
+
|| (view.profile && (view.profile.sha256 !== view.consensus.agent_md_sha256
|
|
167
|
+
|| typeof view.profile.type !== 'string')))
|
|
168
|
+
continue;
|
|
169
|
+
this.cacheEntries.set(aid, { ...view, connected: false, refreshFailure: undefined });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
logger.warn(`[ownership] Cache ignored: ${error instanceof Error ? error.message : String(error)}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
restoreCache(subjectAid, subject) {
|
|
177
|
+
this.loadCache();
|
|
178
|
+
if (subject.view.consensus || subject.view.refreshFailure
|
|
179
|
+
|| (subject.view.reason && subject.view.reason !== 'AUN client is unavailable'))
|
|
180
|
+
return;
|
|
181
|
+
const cached = this.cacheEntries.get(subjectAid);
|
|
182
|
+
if (!cached || (cached.validUntil ?? 0) <= this.now() || cached.checkedAt > this.now())
|
|
183
|
+
return;
|
|
184
|
+
// If the SDK has observed a different local card while we were down, do not restore the old proof.
|
|
185
|
+
const cardFile = agentMdPath(subjectAid);
|
|
186
|
+
try {
|
|
187
|
+
if (fs.existsSync(cardFile) && createHash('sha256').update(fs.readFileSync(cardFile)).digest('hex')
|
|
188
|
+
!== cached.consensus?.agent_md_sha256) {
|
|
189
|
+
this.cacheEntries.delete(subjectAid);
|
|
190
|
+
this.writeCache();
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
subject.view = { ...JSON.parse(JSON.stringify(cached)), connected: subject.view.connected };
|
|
198
|
+
this.rememberVerifiedRelation(subject);
|
|
199
|
+
}
|
|
200
|
+
persistCache(subject, invalidate = false) {
|
|
201
|
+
// The daemon is the sole production writer. Short-lived CLI processes may read, never replace its snapshot.
|
|
202
|
+
if (!this.daemonAid && !this.options.cachePath)
|
|
203
|
+
return;
|
|
204
|
+
this.loadCache();
|
|
205
|
+
const view = subject.view;
|
|
206
|
+
if (!invalidate && view.consensusStatus === 'consensus' && view.consensus
|
|
207
|
+
&& Number.isSafeInteger(view.consensus.relation_version)
|
|
208
|
+
&& /^[a-f0-9]{64}$/.test(view.consensus.agent_md_sha256 ?? '')
|
|
209
|
+
&& !view.refreshFailure && view.checkedAt !== undefined) {
|
|
210
|
+
const { subjectAid, ownerAid, consensusStatus, consensus, checkedAt, validUntil, profile, relation } = view;
|
|
211
|
+
this.cacheEntries.set(subjectAid, { subjectAid, ownerAid, consensusStatus, consensus, checkedAt, validUntil,
|
|
212
|
+
profile, relation, authorizationStatus: 'verified', revision: view.revision, connected: false,
|
|
213
|
+
synchronization: { status: 'synced', runtimeOwnerAid: ownerAid } });
|
|
214
|
+
}
|
|
215
|
+
else
|
|
216
|
+
this.cacheEntries.delete(view.subjectAid);
|
|
217
|
+
for (const [aid, cached] of this.cacheEntries) {
|
|
218
|
+
if ((cached.validUntil ?? 0) <= this.now() || cached.checkedAt > this.now())
|
|
219
|
+
this.cacheEntries.delete(aid);
|
|
220
|
+
}
|
|
221
|
+
if (invalidate)
|
|
222
|
+
this.writeCache();
|
|
223
|
+
else if (!this.cacheWriteQueued) {
|
|
224
|
+
const file = this.cacheFile;
|
|
225
|
+
this.cacheWriteQueued = true;
|
|
226
|
+
queueMicrotask(() => {
|
|
227
|
+
if (this.cacheFile !== file || !this.cacheWriteQueued)
|
|
228
|
+
return;
|
|
229
|
+
this.cacheWriteQueued = false;
|
|
230
|
+
this.writeCache();
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
writeCache() {
|
|
235
|
+
if (!this.daemonAid && !this.options.cachePath)
|
|
236
|
+
return;
|
|
237
|
+
const content = JSON.stringify({ schemaVersion: 1, savedAt: this.now(), entries: Object.fromEntries(this.cacheEntries) });
|
|
238
|
+
try {
|
|
239
|
+
// Cache evidence is usable only when the strict integrity registration also succeeds.
|
|
240
|
+
registerContent(this.cacheFile, content);
|
|
241
|
+
atomicWrite(this.cacheFile, content);
|
|
242
|
+
fs.chmodSync(this.cacheFile, 0o600);
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
// Never leave an old usable snapshot behind after a failed revocation write.
|
|
246
|
+
try {
|
|
247
|
+
fs.rmSync(this.cacheFile, { force: true });
|
|
248
|
+
}
|
|
249
|
+
catch { }
|
|
250
|
+
logger.warn(`[ownership] Cache write failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
57
253
|
setConfiguredOwners(subjectAid, owners) {
|
|
58
254
|
this.assertAid(subjectAid);
|
|
59
255
|
const normalized = [...new Set(owners
|
|
@@ -121,6 +317,7 @@ export class OwnerResolver {
|
|
|
121
317
|
this.detachClient(subjectAid);
|
|
122
318
|
const subject = this.subject(subjectAid);
|
|
123
319
|
subject.client = client;
|
|
320
|
+
subject.store = undefined;
|
|
124
321
|
const connectionState = String(client.state ?? '');
|
|
125
322
|
subject.view.connected = connected || client.isReady === true || connectionState === 'ready' || connectionState === 'connected';
|
|
126
323
|
const generation = subject.generation;
|
|
@@ -262,13 +459,15 @@ export class OwnerResolver {
|
|
|
262
459
|
}
|
|
263
460
|
subject.client = undefined;
|
|
264
461
|
subject.view.connected = false;
|
|
265
|
-
|
|
462
|
+
// A transport replacement must not erase a still-valid restart snapshot.
|
|
463
|
+
this.invalidate(subject, 'AUN client is unavailable', false, false);
|
|
266
464
|
}
|
|
267
465
|
owner(subjectAid) {
|
|
268
466
|
if (!subjectAid)
|
|
269
467
|
return undefined;
|
|
270
468
|
const view = this.subjects.get(subjectAid)?.view;
|
|
271
469
|
return view?.consensusStatus === 'consensus'
|
|
470
|
+
&& view.checkedAt !== undefined && view.checkedAt <= this.now()
|
|
272
471
|
&& ((view.validUntil ?? 0) > this.now() || view.refreshFailure?.fallbackUsed === true)
|
|
273
472
|
? view.ownerAid : undefined;
|
|
274
473
|
}
|
|
@@ -345,17 +544,23 @@ export class OwnerResolver {
|
|
|
345
544
|
}
|
|
346
545
|
async refresh(subjectAid, options = {}) {
|
|
347
546
|
const subject = this.subject(subjectAid);
|
|
547
|
+
this.restoreCache(subjectAid, subject);
|
|
348
548
|
this.refreshConfiguredOwnersFromDisk(subjectAid);
|
|
349
549
|
const inFlight = subject.refreshing?.epoch === subject.epoch ? subject.refreshing : undefined;
|
|
350
550
|
const refreshing = inFlight?.promise;
|
|
351
551
|
const initialEpoch = subject.epoch;
|
|
352
552
|
const initialCheckedAt = subject.view.checkedAt;
|
|
353
553
|
const maxAgeMs = options.maxAgeMs ?? this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS;
|
|
354
|
-
const isFresh = () => this.isCacheFresh(subject, maxAgeMs)
|
|
554
|
+
const isFresh = () => this.isCacheFresh(subject, maxAgeMs)
|
|
555
|
+
&& (!options.requireProfile || !!subject.view.profile);
|
|
355
556
|
// A valid cache never schedules a supplementary consensus check; identity
|
|
356
557
|
// verification only runs when the cache is stale or an operation forces it.
|
|
357
558
|
if (!refreshing && !options.force && isFresh())
|
|
358
559
|
return this.snapshot(subjectAid);
|
|
560
|
+
if (!refreshing && !options.force && (subject.retryAt ?? 0) > this.now()) {
|
|
561
|
+
return !options.allowTransient && subject.view.refreshFailure
|
|
562
|
+
? this.unavailableSnapshot(subjectAid, subject.view.refreshFailure) : this.snapshot(subjectAid);
|
|
563
|
+
}
|
|
359
564
|
const attemptId = inFlight?.attemptId ?? ++subject.query;
|
|
360
565
|
const attemptedAt = inFlight?.attemptedAt ?? this.now();
|
|
361
566
|
const caller = new Error().stack?.replace(/\\/g, '/').split('\n')
|
|
@@ -371,10 +576,16 @@ export class OwnerResolver {
|
|
|
371
576
|
firstObservation: !subject.view.consensus, previousConsensusStatus: subject.view.consensusStatus,
|
|
372
577
|
configuredOwnerAid: configuredOwners[0], configuredOwnerCount: configuredOwners.length,
|
|
373
578
|
};
|
|
374
|
-
const promise = refreshing ?? this.refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic);
|
|
579
|
+
const promise = refreshing ?? this.refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic, options);
|
|
375
580
|
subject.refreshing = { epoch: subject.epoch, attemptId, attemptedAt, diagnostic, promise };
|
|
376
581
|
try {
|
|
377
582
|
await promise;
|
|
583
|
+
if (options.requireProfile && !subject.view.profile && !subject.view.refreshFailure
|
|
584
|
+
&& subject.view.consensusStatus === 'consensus' && refreshing) {
|
|
585
|
+
if (subject.refreshing?.promise === refreshing)
|
|
586
|
+
subject.refreshing = undefined;
|
|
587
|
+
return this.refresh(subjectAid, options);
|
|
588
|
+
}
|
|
378
589
|
if (subject.epoch !== initialEpoch && !isFresh()
|
|
379
590
|
&& subject.view.refreshFailure?.attemptId !== attemptId) {
|
|
380
591
|
if (subject.view.connected)
|
|
@@ -398,10 +609,13 @@ export class OwnerResolver {
|
|
|
398
609
|
subject.refreshing = undefined;
|
|
399
610
|
}
|
|
400
611
|
}
|
|
401
|
-
async refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic) {
|
|
612
|
+
async refreshSubject(subjectAid, subject, attemptId, attemptedAt, diagnostic, options) {
|
|
402
613
|
logOwnershipEvent('refresh.started', { subjectAid, ...diagnostic });
|
|
403
|
-
const
|
|
404
|
-
|
|
614
|
+
const observer = options.observerAid ? this.subjects.get(options.observerAid) : undefined;
|
|
615
|
+
const transport = subject.client && subject.view.connected && (!options.requireProfile || subject.store)
|
|
616
|
+
? subject : observer ?? subject;
|
|
617
|
+
const client = transport?.client;
|
|
618
|
+
if (!client || !transport?.view.connected) {
|
|
405
619
|
const reason = 'Subject AID has no connected SDK client';
|
|
406
620
|
this.handleRefreshFailure(subjectAid, subject, { code: 'CLIENT_DISCONNECTED', message: reason }, attemptedAt, attemptId, diagnostic);
|
|
407
621
|
return this.snapshot(subjectAid);
|
|
@@ -409,17 +623,44 @@ export class OwnerResolver {
|
|
|
409
623
|
const generation = subject.generation;
|
|
410
624
|
const epoch = subject.epoch;
|
|
411
625
|
const query = attemptId;
|
|
626
|
+
const transportGeneration = transport.generation;
|
|
627
|
+
const transportEpoch = transport.epoch;
|
|
412
628
|
let timeout;
|
|
413
629
|
try {
|
|
414
|
-
const consensus = await
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
630
|
+
const { consensus, profile } = await this.query(async () => {
|
|
631
|
+
if (subject.generation !== generation || subject.epoch !== epoch || transport.client !== client
|
|
632
|
+
|| transport.generation !== transportGeneration || transport.epoch !== transportEpoch || !transport.view.connected) {
|
|
633
|
+
throw Object.assign(new Error('Ownership transport changed while queued'), { code: 'CLIENT_DISCONNECTED' });
|
|
634
|
+
}
|
|
635
|
+
return await Promise.race([
|
|
636
|
+
(async () => {
|
|
637
|
+
const consensus = await client.checkOwnershipConsensus(subjectAid, true);
|
|
638
|
+
let profile;
|
|
639
|
+
if ((options.requireProfile || transport.store) && consensus.status === 'consensus') {
|
|
640
|
+
if (!transport.store)
|
|
641
|
+
throw Object.assign(new Error('Verified profile transport is unavailable'), { code: 'UNAVAILABLE' });
|
|
642
|
+
const { agentmdGet } = await import('../../aun/aid/agentmd.js');
|
|
643
|
+
const { parseAgentMdFrontmatter } = await import('../relation/peer-identity.js');
|
|
644
|
+
const card = await agentmdGet(subjectAid, { store: transport.store, withVerification: true, remoteOnly: true });
|
|
645
|
+
const identity = parseAgentMdFrontmatter(card.content);
|
|
646
|
+
const sha256 = createHash('sha256').update(card.content, 'utf8').digest('hex');
|
|
647
|
+
if (card.source !== 'remote' || card.verification.status !== 'verified' || identity.aid !== subjectAid
|
|
648
|
+
|| identity.owner !== consensus.owner_aid || sha256 !== consensus.agent_md_sha256) {
|
|
649
|
+
throw Object.assign(new Error('Verified agent.md does not match Ownership consensus'), { code: 'CONSENSUS_MISMATCH' });
|
|
650
|
+
}
|
|
651
|
+
profile = { type: String(identity.type ?? '').trim().toLowerCase(), sha256 };
|
|
652
|
+
}
|
|
653
|
+
return { consensus, profile };
|
|
654
|
+
})(),
|
|
655
|
+
new Promise((_resolve, reject) => {
|
|
656
|
+
timeout = setTimeout(() => reject(new OwnershipError('OWNERSHIP_REFRESH_TIMEOUT', 'Ownership consensus check timed out')), this.options.timeoutMs ?? 8_000);
|
|
657
|
+
timeout.unref?.();
|
|
658
|
+
}),
|
|
659
|
+
]);
|
|
660
|
+
});
|
|
661
|
+
if (subject.generation !== generation || subject.epoch !== epoch
|
|
662
|
+
|| subject.query !== query || transport.client !== client || transport.generation !== transportGeneration
|
|
663
|
+
|| transport.epoch !== transportEpoch || !transport.view.connected) {
|
|
423
664
|
logOwnershipEvent('refresh.discarded', { subjectAid, ...diagnostic,
|
|
424
665
|
durationMs: Math.round(Math.max(0, performance.now() - diagnostic.startedAt)), connected: subject.view.connected,
|
|
425
666
|
});
|
|
@@ -453,6 +694,7 @@ export class OwnerResolver {
|
|
|
453
694
|
authorizationStatus: ownerAid ? 'verified' : 'unavailable',
|
|
454
695
|
consensusStatus: consensus.status,
|
|
455
696
|
consensus: JSON.parse(JSON.stringify(consensus)),
|
|
697
|
+
profile: profile ?? (subject.view.profile?.sha256 === consensus.agent_md_sha256 ? subject.view.profile : undefined),
|
|
456
698
|
checkedAt,
|
|
457
699
|
validUntil: checkedAt + (this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS),
|
|
458
700
|
revision: subject.view.revision + (previousOwner !== ownerAid
|
|
@@ -470,6 +712,9 @@ export class OwnerResolver {
|
|
|
470
712
|
},
|
|
471
713
|
};
|
|
472
714
|
this.rememberVerifiedRelation(subject);
|
|
715
|
+
subject.failures = 0;
|
|
716
|
+
subject.retryAt = undefined;
|
|
717
|
+
this.persistCache(subject);
|
|
473
718
|
this.clearConfirmedRequest(subject, consensus, ownerAid);
|
|
474
719
|
this.clearResolvedRequests(subject, consensus);
|
|
475
720
|
if (previousOwner !== ownerAid || previousStatus !== consensus.status
|
|
@@ -492,7 +737,7 @@ export class OwnerResolver {
|
|
|
492
737
|
this.notifyUpdate(subjectAid);
|
|
493
738
|
}
|
|
494
739
|
catch (error) {
|
|
495
|
-
if (subject.
|
|
740
|
+
if (subject.generation === generation && subject.epoch === epoch && subject.query === query) {
|
|
496
741
|
const reason = error instanceof Error ? error.message : String(error);
|
|
497
742
|
this.handleRefreshFailure(subjectAid, subject, error, attemptedAt, attemptId, diagnostic);
|
|
498
743
|
}
|
|
@@ -513,7 +758,7 @@ export class OwnerResolver {
|
|
|
513
758
|
const reason = error instanceof Error ? error.message
|
|
514
759
|
: typeof details.message === 'string' ? details.message : String(error);
|
|
515
760
|
const code = String(details.stringCode ?? details.code ?? 'OWNERSHIP_REFRESH_FAILED');
|
|
516
|
-
const transient =
|
|
761
|
+
const transient = isTransientOwnershipRefreshFailure(error);
|
|
517
762
|
// Keep the shared cache intact for ordinary callers; strict waiters receive
|
|
518
763
|
// an unavailable view for this attempt and cannot consume the fallback.
|
|
519
764
|
const fallbackUsed = transient && this.canUseTransientAuthorization(subject, attemptedAt);
|
|
@@ -539,6 +784,10 @@ export class OwnerResolver {
|
|
|
539
784
|
subject.view.refreshFailure = {
|
|
540
785
|
kind: transient ? 'transient' : 'permanent', code, reason, attemptedAt, attemptId, fallbackUsed,
|
|
541
786
|
};
|
|
787
|
+
subject.failures = (subject.failures ?? 0) + 1;
|
|
788
|
+
subject.retryAt = transient
|
|
789
|
+
? attemptedAt + Math.min(60_000, OWNERSHIP_RETRY_BASE_MS * 2 ** Math.min(subject.failures - 1, 4))
|
|
790
|
+
: attemptedAt + OWNERSHIP_RETRY_BASE_MS;
|
|
542
791
|
this.notifyUpdate(subjectAid);
|
|
543
792
|
const cause = this.record(details.cause);
|
|
544
793
|
const transportCode = cause?.code ?? details.code;
|
|
@@ -581,27 +830,6 @@ export class OwnerResolver {
|
|
|
581
830
|
? { ownerAid: view.ownerAid, consensus: view.consensus, checkedAt: view.checkedAt, validUntil: view.validUntil }
|
|
582
831
|
: undefined;
|
|
583
832
|
}
|
|
584
|
-
isTransientRefreshFailure(error) {
|
|
585
|
-
const details = error && typeof error === 'object' ? error : {};
|
|
586
|
-
const code = String(details.code ?? details.stringCode ?? '').toUpperCase();
|
|
587
|
-
const message = error instanceof Error ? error.message
|
|
588
|
-
: typeof details.message === 'string' ? details.message : String(error);
|
|
589
|
-
if (['INVALID', 'CONFLICT', 'FORBIDDEN', 'NOT_APPLICABLE', 'OWNER_LOCKED', 'TASK_MISMATCH',
|
|
590
|
-
'CONSENSUS_MISMATCH', 'UNSUPPORTED_PROTOCOL', 'PERSISTENCE_UNAVAILABLE'].includes(code))
|
|
591
|
-
return false;
|
|
592
|
-
if (/projection.*(?:does not match|conflict)|(?:agent|owner)\.md changed (?:while|during)|NS relation changed .*consensus check|digest does not match authoritative observation|Storage material changed during authoritative read/i.test(message))
|
|
593
|
-
return false;
|
|
594
|
-
if (details.retryable === false)
|
|
595
|
-
return false;
|
|
596
|
-
if (details.retryable === true)
|
|
597
|
-
return true;
|
|
598
|
-
return code === 'TIMEOUT' || code === 'NETWORK_ERROR' || code === 'UNAVAILABLE'
|
|
599
|
-
|| code === 'CLIENT_DISCONNECTED' || code === 'CONNECTION_FAILED'
|
|
600
|
-
|| code === 'GATEWAY_UNAVAILABLE' || code === 'CONNECTION_UNAVAILABLE'
|
|
601
|
-
|| code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ETIMEDOUT'
|
|
602
|
-
|| code === 'ENETUNREACH' || code === 'EAI_AGAIN' || code === 'ENOTFOUND' || code === 'EHOSTUNREACH'
|
|
603
|
-
|| /timed out|timeout|connection reset|connection refused|connection closed|socket hang up|not connected|network error|fetch failed|gateway unavailable|gateway timeout|temporarily unavailable/i.test(message);
|
|
604
|
-
}
|
|
605
833
|
hasRejectedOwnerBinding(subjectAid, ownerAid) {
|
|
606
834
|
this.assertAid(subjectAid);
|
|
607
835
|
this.assertAid(ownerAid);
|
|
@@ -646,7 +874,7 @@ export class OwnerResolver {
|
|
|
646
874
|
logger.warn(`[ownership] Failed to persist rejected binding for ${task.sub_aid}: ${reason}`);
|
|
647
875
|
}
|
|
648
876
|
}
|
|
649
|
-
async bind(subjectAid, ownerAid, isCurrent) {
|
|
877
|
+
async bind(subjectAid, ownerAid, isCurrent, onSubmissionStart) {
|
|
650
878
|
this.assertAid(subjectAid);
|
|
651
879
|
this.assertAid(ownerAid);
|
|
652
880
|
if (ownerAid === subjectAid)
|
|
@@ -661,11 +889,22 @@ export class OwnerResolver {
|
|
|
661
889
|
if (subject.binding) {
|
|
662
890
|
if (subject.binding.ownerAid !== ownerAid)
|
|
663
891
|
throw new OwnershipError('BIND_CONFLICT', 'Another owner binding is in progress');
|
|
892
|
+
if (onSubmissionStart) {
|
|
893
|
+
if (subject.binding.submission.started)
|
|
894
|
+
onSubmissionStart();
|
|
895
|
+
else
|
|
896
|
+
subject.binding.submission.listeners.add(onSubmissionStart);
|
|
897
|
+
}
|
|
664
898
|
return subject.binding.promise;
|
|
665
899
|
}
|
|
666
900
|
const previousTask = subject.view.task;
|
|
667
|
-
const
|
|
668
|
-
|
|
901
|
+
const submission = { started: false, listeners: new Set(onSubmissionStart ? [onSubmissionStart] : []) };
|
|
902
|
+
const promise = this.submitBinding(subjectAid, ownerAid, subject, assertCurrent, () => {
|
|
903
|
+
submission.started = true;
|
|
904
|
+
for (const listener of submission.listeners)
|
|
905
|
+
listener();
|
|
906
|
+
});
|
|
907
|
+
subject.binding = { ownerAid, promise, submission };
|
|
669
908
|
try {
|
|
670
909
|
const result = await promise;
|
|
671
910
|
const task = result.task;
|
|
@@ -716,7 +955,7 @@ export class OwnerResolver {
|
|
|
716
955
|
}
|
|
717
956
|
if (subject.transferIntents.has(subAid) || subject.transferTasks.has(subAid)) {
|
|
718
957
|
const generation = subject.generation;
|
|
719
|
-
const current = await this.withSubjectClient(ownerAid, client =>
|
|
958
|
+
const current = await this.withSubjectClient(ownerAid, client => this.queryConsensus(client, subAid));
|
|
720
959
|
if (subject.generation !== generation) {
|
|
721
960
|
throw new OwnershipError('CLIENT_REPLACED', 'Ownership state changed during transfer preflight; retry');
|
|
722
961
|
}
|
|
@@ -847,6 +1086,34 @@ export class OwnerResolver {
|
|
|
847
1086
|
throw error;
|
|
848
1087
|
}
|
|
849
1088
|
}
|
|
1089
|
+
/** Fresh authorization never refreshes unrelated transfers or falls back to an old relation. */
|
|
1090
|
+
async refreshForAuthorization(subjectAid) {
|
|
1091
|
+
const subject = this.subject(subjectAid);
|
|
1092
|
+
if (subject.client && subject.view.connected) {
|
|
1093
|
+
return this.refresh(subjectAid, { force: true, allowTransient: false, source: 'authorization' });
|
|
1094
|
+
}
|
|
1095
|
+
const epoch = subject.epoch;
|
|
1096
|
+
const existing = this.authorizationChecks.get(subjectAid);
|
|
1097
|
+
if (existing?.epoch === epoch)
|
|
1098
|
+
return existing.promise;
|
|
1099
|
+
const generation = subject.generation;
|
|
1100
|
+
const promise = this.withSubjectClient(subjectAid, async (client) => {
|
|
1101
|
+
const consensus = await this.queryConsensus(client, subjectAid);
|
|
1102
|
+
if (subject.generation !== generation || subject.epoch !== epoch) {
|
|
1103
|
+
throw new OwnershipError('CLIENT_REPLACED', 'Subject state changed during authorization; retry');
|
|
1104
|
+
}
|
|
1105
|
+
this.applyConsensus(subjectAid, subject, consensus);
|
|
1106
|
+
return this.snapshot(subjectAid);
|
|
1107
|
+
});
|
|
1108
|
+
this.authorizationChecks.set(subjectAid, { epoch, promise });
|
|
1109
|
+
try {
|
|
1110
|
+
return await promise;
|
|
1111
|
+
}
|
|
1112
|
+
finally {
|
|
1113
|
+
if (this.authorizationChecks.get(subjectAid)?.promise === promise)
|
|
1114
|
+
this.authorizationChecks.delete(subjectAid);
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
850
1117
|
async status(subjectAid, options = {}) {
|
|
851
1118
|
const subject = this.subject(subjectAid);
|
|
852
1119
|
// Status display reuses the resolve snapshot; consensus verification is
|
|
@@ -864,7 +1131,7 @@ export class OwnerResolver {
|
|
|
864
1131
|
}
|
|
865
1132
|
const generation = subject.generation;
|
|
866
1133
|
return this.withSubjectClient(subjectAid, async (client) => {
|
|
867
|
-
const consensus = await
|
|
1134
|
+
const consensus = await this.queryConsensus(client, subjectAid);
|
|
868
1135
|
if (subject.generation !== generation) {
|
|
869
1136
|
throw new OwnershipError('CLIENT_REPLACED', 'Subject state changed during status query; retry');
|
|
870
1137
|
}
|
|
@@ -879,7 +1146,7 @@ export class OwnerResolver {
|
|
|
879
1146
|
const generation = subject.generation;
|
|
880
1147
|
for (const [subAid, task] of [...subject.transferTasks]) {
|
|
881
1148
|
try {
|
|
882
|
-
const consensus = await
|
|
1149
|
+
const consensus = await this.queryConsensus(client, subAid);
|
|
883
1150
|
if ((attached && subject.client !== client) || subject.generation !== generation
|
|
884
1151
|
|| subject.transferTasks.get(subAid)?.operation_id !== task.operation_id)
|
|
885
1152
|
return;
|
|
@@ -942,15 +1209,19 @@ export class OwnerResolver {
|
|
|
942
1209
|
this.subjects.clear();
|
|
943
1210
|
this.configuredOwners.clear();
|
|
944
1211
|
this.configuredOwnerFileRevision.clear();
|
|
1212
|
+
this.authorizationChecks.clear();
|
|
1213
|
+
this.cacheEntries.clear();
|
|
1214
|
+
this.cacheFile = undefined;
|
|
1215
|
+
this.cacheWriteQueued = false;
|
|
945
1216
|
}
|
|
946
|
-
async submitBinding(subjectAid, ownerAid, subject, assertCurrent) {
|
|
1217
|
+
async submitBinding(subjectAid, ownerAid, subject, assertCurrent, onSubmissionStart) {
|
|
947
1218
|
const generation = subject.generation;
|
|
948
1219
|
let replaced = false;
|
|
949
1220
|
subject.view = { ...subject.view, requestedOwnerAid: ownerAid, requestStatus: 'requesting', task: undefined };
|
|
950
1221
|
try {
|
|
951
1222
|
await this.assertAgentOwner(subjectAid, ownerAid);
|
|
952
1223
|
assertCurrent();
|
|
953
|
-
const local = await this.tryLocalBind(subjectAid, ownerAid, assertCurrent);
|
|
1224
|
+
const local = await this.tryLocalBind(subjectAid, ownerAid, assertCurrent, onSubmissionStart);
|
|
954
1225
|
if (local) {
|
|
955
1226
|
if (subject.client && subject.generation !== generation) {
|
|
956
1227
|
throw new OwnershipError('CLIENT_REPLACED', 'Subject SDK client changed during local binding');
|
|
@@ -988,6 +1259,7 @@ export class OwnerResolver {
|
|
|
988
1259
|
}
|
|
989
1260
|
this.applyConsensus(subjectAid, subject, current);
|
|
990
1261
|
assertCurrent();
|
|
1262
|
+
onSubmissionStart?.();
|
|
991
1263
|
const task = this.task(await client.bindOwneraid(ownerAid));
|
|
992
1264
|
if (attached && (subject.client !== client || subject.generation !== generation)) {
|
|
993
1265
|
replaced = true;
|
|
@@ -1333,7 +1605,7 @@ export class OwnerResolver {
|
|
|
1333
1605
|
catch { }
|
|
1334
1606
|
}
|
|
1335
1607
|
}
|
|
1336
|
-
async tryLocalBind(subjectAid, ownerAid, assertCurrent) {
|
|
1608
|
+
async tryLocalBind(subjectAid, ownerAid, assertCurrent, onSubmissionStart) {
|
|
1337
1609
|
let store;
|
|
1338
1610
|
let ownerClient;
|
|
1339
1611
|
let subClient;
|
|
@@ -1352,6 +1624,7 @@ export class OwnerResolver {
|
|
|
1352
1624
|
|| !['agent', 'human'].includes(ownerClient.getType()) || subClient.getType() !== 'agent')
|
|
1353
1625
|
return undefined;
|
|
1354
1626
|
assertCurrent();
|
|
1627
|
+
onSubmissionStart?.();
|
|
1355
1628
|
invoked = true;
|
|
1356
1629
|
const task = this.task(await ownerClient.bindSubaid(subjectAid));
|
|
1357
1630
|
if (!task || task.operation !== 'bind' || task.sub_aid !== subjectAid || task.owner_aid !== ownerAid
|
|
@@ -1420,6 +1693,7 @@ export class OwnerResolver {
|
|
|
1420
1693
|
relation: this.relationAfterConsensus(subject.view.relation, consensus, ownerAid, checkedAt),
|
|
1421
1694
|
authorizationStatus: ownerAid ? 'verified' : 'unavailable', consensusStatus: consensus.status,
|
|
1422
1695
|
consensus: JSON.parse(JSON.stringify(consensus)),
|
|
1696
|
+
profile: subject.view.profile?.sha256 === consensus.agent_md_sha256 ? subject.view.profile : undefined,
|
|
1423
1697
|
checkedAt, validUntil: checkedAt + (this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS),
|
|
1424
1698
|
revision: subject.view.revision + (previousOwner !== ownerAid || subject.view.consensusStatus !== consensus.status
|
|
1425
1699
|
|| subject.view.consensus?.relation_version !== consensus.relation_version
|
|
@@ -1435,6 +1709,9 @@ export class OwnerResolver {
|
|
|
1435
1709
|
},
|
|
1436
1710
|
};
|
|
1437
1711
|
this.rememberVerifiedRelation(subject);
|
|
1712
|
+
this.persistCache(subject);
|
|
1713
|
+
subject.retryAt = undefined;
|
|
1714
|
+
subject.failures = 0;
|
|
1438
1715
|
this.clearConfirmedRequest(subject, consensus, ownerAid);
|
|
1439
1716
|
this.clearResolvedRequests(subject, consensus);
|
|
1440
1717
|
if (previousOwner !== ownerAid || previousStatus !== consensus.status
|
|
@@ -1478,6 +1755,14 @@ export class OwnerResolver {
|
|
|
1478
1755
|
}
|
|
1479
1756
|
subject(subjectAid) {
|
|
1480
1757
|
this.assertAid(subjectAid);
|
|
1758
|
+
const rootScope = this.options.cachePath?.() ?? ownershipCachePath();
|
|
1759
|
+
if (this.rootScope && this.rootScope !== rootScope) {
|
|
1760
|
+
this.subjects.clear();
|
|
1761
|
+
this.configuredOwners.clear();
|
|
1762
|
+
this.configuredOwnerFileRevision.clear();
|
|
1763
|
+
this.authorizationChecks.clear();
|
|
1764
|
+
}
|
|
1765
|
+
this.rootScope = rootScope;
|
|
1481
1766
|
let subject = this.subjects.get(subjectAid);
|
|
1482
1767
|
if (subject)
|
|
1483
1768
|
return subject;
|
|
@@ -1494,7 +1779,7 @@ export class OwnerResolver {
|
|
|
1494
1779
|
this.subjects.set(subjectAid, subject);
|
|
1495
1780
|
return subject;
|
|
1496
1781
|
}
|
|
1497
|
-
invalidate(subject, reason, preserveVerifiedRelation = false) {
|
|
1782
|
+
invalidate(subject, reason, preserveVerifiedRelation = false, persist = true) {
|
|
1498
1783
|
const previousOwner = subject.view.ownerAid;
|
|
1499
1784
|
if (!preserveVerifiedRelation)
|
|
1500
1785
|
subject.verifiedRelation = undefined;
|
|
@@ -1504,7 +1789,11 @@ export class OwnerResolver {
|
|
|
1504
1789
|
...(subject.view.relation ? { relation: { ...subject.view.relation, isCurrent: false } } : {}),
|
|
1505
1790
|
revision: subject.view.revision + 1, reason, refreshFailure: undefined,
|
|
1506
1791
|
synchronization: { status: 'unavailable' },
|
|
1792
|
+
profile: undefined,
|
|
1507
1793
|
};
|
|
1794
|
+
subject.retryAt = undefined;
|
|
1795
|
+
if (persist)
|
|
1796
|
+
this.persistCache(subject, true);
|
|
1508
1797
|
if (previousOwner)
|
|
1509
1798
|
this.notify(subject.view.subjectAid);
|
|
1510
1799
|
this.notifyUpdate(subject.view.subjectAid);
|
|
@@ -1525,15 +1814,19 @@ export class OwnerResolver {
|
|
|
1525
1814
|
}
|
|
1526
1815
|
notify(subjectAid, ownerAid) {
|
|
1527
1816
|
for (const listener of this.listeners) {
|
|
1528
|
-
queueMicrotask(() => {
|
|
1529
|
-
listener
|
|
1530
|
-
|
|
1531
|
-
|
|
1817
|
+
queueMicrotask(() => {
|
|
1818
|
+
if (!this.listeners.has(listener))
|
|
1819
|
+
return;
|
|
1820
|
+
try {
|
|
1821
|
+
listener(subjectAid, ownerAid);
|
|
1822
|
+
}
|
|
1823
|
+
catch { }
|
|
1824
|
+
});
|
|
1532
1825
|
}
|
|
1533
1826
|
}
|
|
1534
1827
|
invalidateRelatedSubjects(changedAid, targetAid) {
|
|
1535
1828
|
for (const [subjectAid, subject] of this.subjects) {
|
|
1536
|
-
if (
|
|
1829
|
+
if (targetAid && targetAid !== subjectAid)
|
|
1537
1830
|
continue;
|
|
1538
1831
|
const ownerAid = subject.view.relation?.ownerAid;
|
|
1539
1832
|
if ((!targetAid && changedAid === subjectAid) || changedAid === ownerAid
|
|
@@ -1724,15 +2017,17 @@ export async function refreshOwnershipForAuthorization(subjectAid, options = {})
|
|
|
1724
2017
|
return views;
|
|
1725
2018
|
}
|
|
1726
2019
|
export async function assertOwnershipAuthorization(context) {
|
|
2020
|
+
await context?.revalidateExecutionIdentity?.();
|
|
1727
2021
|
if (context?.internalContactAuthorization && context.selfAid && context.actor?.principalId) {
|
|
1728
|
-
const {
|
|
1729
|
-
const { resolvePeerRoleDetail } = await import('../../config/peer-role-resolver.js');
|
|
2022
|
+
const { resolveFreshPeerRoleDetail } = await import('../../config/peer-role-resolver.js');
|
|
1730
2023
|
const { getRoleDefinition } = await import('../../config/roles.js');
|
|
1731
|
-
await
|
|
1732
|
-
const current = resolvePeerRoleDetail({
|
|
2024
|
+
const current = await resolveFreshPeerRoleDetail({
|
|
1733
2025
|
selfAid: context.selfAid, channelKey: context.actor.operatorChannelKey, channelType: 'aun',
|
|
1734
2026
|
chatType: 'private', actorId: context.actor.principalId, conversationId: context.actor.principalId,
|
|
1735
2027
|
});
|
|
2028
|
+
if (current.authorizationFailure) {
|
|
2029
|
+
throw Object.assign(new OwnershipError('INTERNAL_CONTACT_AUTHORIZATION_UNAVAILABLE', current.authorizationFailure.reason), { retryable: current.authorizationFailure.retryable });
|
|
2030
|
+
}
|
|
1736
2031
|
if (!current.allowAccess || current.effectiveRole !== context.role
|
|
1737
2032
|
|| (context.internalContactDefaultRole && current.source !== 'internal-contact-default')
|
|
1738
2033
|
|| (context.internalContactPolicy !== undefined && context.internalContactPolicy !== JSON.stringify(getRoleDefinition(context.role ?? '', context.selfAid)))) {
|