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,12 +1,23 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { isValidAid } from '../aun/aid/validation.js';
|
|
3
4
|
import { agentConfig } from '../paths.js';
|
|
5
|
+
import { isManagementRole } from './builtin-roles.js';
|
|
6
|
+
import { isRoleName } from './role-store.js';
|
|
7
|
+
import { roleMenuQuery, roleMenuUpdate } from '../core/command/role-menu.js';
|
|
8
|
+
import { getRoleBudgetStatus, resolveRoleUsageLimits } from '../stats/role-budget.js';
|
|
9
|
+
import { resolveRoot } from '../paths.js';
|
|
10
|
+
import { authorizeFreshOperation, buildAuthSubject } from '../core/auth/auth-gateway.js';
|
|
11
|
+
import { ownerResolver, refreshOwnershipForAuthorization } from '../core/ownership/owner-resolver.js';
|
|
12
|
+
import { logger } from '../utils/logger.js';
|
|
4
13
|
import { listRoleRequests, reviewRoleRequest, submitRoleRequest, } from './role-request-service.js';
|
|
5
14
|
export function resolveRoleCommand(argv) {
|
|
6
15
|
const args = argv[0] === 'role' ? argv.slice(1) : [...argv];
|
|
7
16
|
const selfAid = String(argValue(args, '--self') || '').trim();
|
|
8
17
|
if (!isValidAid(selfAid))
|
|
9
18
|
return invalid('INVALID_SELF', '--self must be a valid Agent AID');
|
|
19
|
+
if (args[0] === 'quota')
|
|
20
|
+
return resolveQuotaCommand(args, selfAid);
|
|
10
21
|
const positional = stripOptions(args);
|
|
11
22
|
const [command, subcommand, ...extra] = positional;
|
|
12
23
|
if (extra.length > 0)
|
|
@@ -61,10 +72,61 @@ export function resolveRoleCommand(argv) {
|
|
|
61
72
|
}
|
|
62
73
|
return invalid('UNKNOWN_COMMAND', `Unknown role command: ${positional.join(' ')}`);
|
|
63
74
|
}
|
|
64
|
-
export async function executeResolvedRoleCommand(command, actorAid, apply) {
|
|
75
|
+
export async function executeResolvedRoleCommand(command, actorAid, apply, context) {
|
|
65
76
|
if (!fs.existsSync(agentConfig(command.selfAid))) {
|
|
66
77
|
return { ok: false, code: 'AGENT_NOT_FOUND', error: `Agent does not exist: ${command.selfAid}` };
|
|
67
78
|
}
|
|
79
|
+
if (command.kind === 'quota') {
|
|
80
|
+
if (!context || context.self !== command.selfAid) {
|
|
81
|
+
return { ok: false, code: 'PERMISSION_DENIED', error: 'Role quota operations require an authorized Agent context' };
|
|
82
|
+
}
|
|
83
|
+
const current = await roleMenuQuery(context, { self: command.selfAid, view: 'role', roleId: command.roleId });
|
|
84
|
+
let result = current;
|
|
85
|
+
if (command.action !== 'show') {
|
|
86
|
+
if (isManagementRole(command.roleId)) {
|
|
87
|
+
return { ok: false, code: 'NOT_SUPPORTED', error: 'Owner and admin are exempt from role usage limits' };
|
|
88
|
+
}
|
|
89
|
+
const updateArgs = {
|
|
90
|
+
self: command.selfAid,
|
|
91
|
+
resource: 'definition',
|
|
92
|
+
roleId: command.roleId,
|
|
93
|
+
expectedPolicyRevision: current.policyRevision,
|
|
94
|
+
};
|
|
95
|
+
if (command.action === 'inherit') {
|
|
96
|
+
updateArgs.remove = { usageLimits: true };
|
|
97
|
+
result = await roleMenuUpdate(context, updateArgs, '{}');
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
const inheritedLimits = resolveRoleUsageLimits(command.roleId, command.selfAid);
|
|
101
|
+
const usageLimits = {
|
|
102
|
+
...inheritedLimits,
|
|
103
|
+
...current.definition.usageLimits,
|
|
104
|
+
...command.patch,
|
|
105
|
+
};
|
|
106
|
+
if (command.patch.enabled === undefined) {
|
|
107
|
+
usageLimits.enabled = current.definition.usageLimits?.enabled ?? inheritedLimits?.enabled ?? false;
|
|
108
|
+
}
|
|
109
|
+
if (usageLimits.enabled === true && usageLimits.limitAmount === undefined) {
|
|
110
|
+
return { ok: false, code: 'INVALID_ARGUMENT', error: 'Enabling a quota requires --limit <amount|unlimited>' };
|
|
111
|
+
}
|
|
112
|
+
result = await roleMenuUpdate(context, updateArgs, JSON.stringify({ usageLimits }));
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const effectiveUsageLimits = resolveRoleUsageLimits(command.roleId, command.selfAid);
|
|
116
|
+
return {
|
|
117
|
+
ok: true,
|
|
118
|
+
operation: 'quota',
|
|
119
|
+
selfAid: command.selfAid,
|
|
120
|
+
roleId: command.roleId,
|
|
121
|
+
changed: result.changed === true,
|
|
122
|
+
applicable: !isManagementRole(command.roleId),
|
|
123
|
+
enforced: !isManagementRole(command.roleId)
|
|
124
|
+
&& effectiveUsageLimits?.enabled !== false
|
|
125
|
+
&& typeof effectiveUsageLimits?.limitAmount === 'number',
|
|
126
|
+
usageLimits: result.definition.usageLimits ?? null,
|
|
127
|
+
effectiveUsageLimits,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
68
130
|
if (command.kind === 'request') {
|
|
69
131
|
const submission = await submitRoleRequest({
|
|
70
132
|
selfAid: command.selfAid,
|
|
@@ -124,6 +186,191 @@ export async function executeResolvedRoleCommand(command, actorAid, apply) {
|
|
|
124
186
|
requests: listRoleRequests({ selfAid: command.selfAid, status: command.status }),
|
|
125
187
|
};
|
|
126
188
|
}
|
|
189
|
+
/** The daemon asks its authenticated Owner; the exhausted Agent never approves its own quota. */
|
|
190
|
+
export class RoleQuotaQuestions {
|
|
191
|
+
router;
|
|
192
|
+
pending = new Map();
|
|
193
|
+
constructor(router) {
|
|
194
|
+
this.router = router;
|
|
195
|
+
}
|
|
196
|
+
async present(input) {
|
|
197
|
+
const self = input.request.selfAid;
|
|
198
|
+
if (!self)
|
|
199
|
+
return false;
|
|
200
|
+
const budget = getRoleBudgetStatus(resolveRoot(), input.request);
|
|
201
|
+
if (!budget.hard_blocked)
|
|
202
|
+
return false;
|
|
203
|
+
await refreshOwnershipForAuthorization(input.daemonAid, { includeDaemon: true, allowTransient: false });
|
|
204
|
+
const ownerAid = ownerResolver.owner(input.daemonAid);
|
|
205
|
+
if (!ownerAid)
|
|
206
|
+
return false;
|
|
207
|
+
const authorize = async () => {
|
|
208
|
+
const subject = buildAuthSubject({ selfAid: self, actorId: ownerAid,
|
|
209
|
+
channel: input.transport.channelKey, channelType: 'aun', channelId: ownerAid,
|
|
210
|
+
chatType: 'private', fromControlChannel: true, peerType: 'human' });
|
|
211
|
+
const decision = await authorizeFreshOperation({ source: 'menu', subject,
|
|
212
|
+
intent: { operation: 'role.policy.write', scope: 'agent', source: 'menu',
|
|
213
|
+
args: { self, targetAgentAid: self, roleId: budget.role } } });
|
|
214
|
+
return decision.allow && ownerResolver.owner(input.daemonAid) === ownerAid;
|
|
215
|
+
};
|
|
216
|
+
if (!(await authorize()))
|
|
217
|
+
return false;
|
|
218
|
+
const context = { self, actorRole: 'none', actorAid: ownerAid,
|
|
219
|
+
isDaemonOwner: true, fromControlChannel: true, chatType: 'private' };
|
|
220
|
+
const policy = await roleMenuQuery(context, { self, view: 'role', roleId: budget.role });
|
|
221
|
+
// A quota change applies to the whole role, so one pending request covers
|
|
222
|
+
// all exhausted subjects of that role under this policy and reset period.
|
|
223
|
+
const key = JSON.stringify([self, budget.role, budget.period_start_ts, policy.policyRevision, ownerAid]);
|
|
224
|
+
for (const [oldKey, entry] of this.pending) {
|
|
225
|
+
if (entry.expiresAt <= Date.now()) {
|
|
226
|
+
this.pending.delete(oldKey);
|
|
227
|
+
await this.router.cancel(entry.id, 'expired');
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const previous = this.pending.get(key);
|
|
231
|
+
if (previous)
|
|
232
|
+
return (await previous.delivery ?? false) && previous.open;
|
|
233
|
+
const id = `rqq-${randomUUID()}`;
|
|
234
|
+
const expiresAt = Date.now() + 15 * 60_000;
|
|
235
|
+
const entry = { id, expiresAt, open: true };
|
|
236
|
+
this.pending.set(key, entry);
|
|
237
|
+
const close = () => { entry.open = false; };
|
|
238
|
+
const isCurrent = async () => {
|
|
239
|
+
if (!entry.open || Date.now() >= expiresAt || !(await authorize()))
|
|
240
|
+
return false;
|
|
241
|
+
const current = getRoleBudgetStatus(resolveRoot(), input.request);
|
|
242
|
+
if (!current.hard_blocked || current.period_start_ts !== budget.period_start_ts)
|
|
243
|
+
return false;
|
|
244
|
+
const latest = await roleMenuQuery(context, { self, view: 'role', roleId: budget.role });
|
|
245
|
+
return entry.open && latest.policyRevision === policy.policyRevision;
|
|
246
|
+
};
|
|
247
|
+
const notice = (text) => input.transport.notice(ownerAid, text);
|
|
248
|
+
this.router.register(id, `role-quota:${self}`, async (action, values) => {
|
|
249
|
+
if (action === 'reject' || action === 'dismiss' || values?.behavior === 'dismiss') {
|
|
250
|
+
close();
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
if (!(await isCurrent())) {
|
|
254
|
+
await this.router.cancel(id, 'quota_or_owner_changed');
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
const raw = action === '_custom_input' && typeof values?.custom_text === 'string'
|
|
258
|
+
? values.custom_text.trim() : '';
|
|
259
|
+
const amount = Number(raw);
|
|
260
|
+
if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/u.test(raw) || !Number.isFinite(amount)
|
|
261
|
+
|| amount <= getRoleBudgetStatus(resolveRoot(), input.request).used_amount) {
|
|
262
|
+
await notice('请输入高于当前已用金额的新额度上限,币种保持不变。');
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
try {
|
|
266
|
+
await roleMenuUpdate(context, { self, resource: 'definition', roleId: budget.role,
|
|
267
|
+
expectedPolicyRevision: policy.policyRevision }, JSON.stringify({ usageLimits: {
|
|
268
|
+
...resolveRoleUsageLimits(budget.role, self), limitAmount: amount,
|
|
269
|
+
} }));
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
await this.router.cancel(id, 'quota_changed');
|
|
273
|
+
await notice('额度未修改,角色配置或权限已变化,请重新申请。');
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
close();
|
|
277
|
+
await notice(`${self} 的 ${budget.role} 角色额度已调整为 ${budget.currency} ${amount}。请在原会话重试。`)
|
|
278
|
+
.catch(error => logger.warn(`[RoleQuota] Quota saved but confirmation failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
279
|
+
return true;
|
|
280
|
+
}, { blocking: false, retainOnRejected: true, requireEncrypted: true,
|
|
281
|
+
initiatorId: ownerAid, initiatorChannelKey: input.transport.channelKey,
|
|
282
|
+
timeoutMs: 15 * 60_000,
|
|
283
|
+
onCancel: async () => { close(); await input.transport.invalidate(id); } });
|
|
284
|
+
try {
|
|
285
|
+
entry.delivery = input.transport.send(ownerAid, {
|
|
286
|
+
type: 'interaction', id, sessionId: `role-quota:${self}`, channelId: ownerAid,
|
|
287
|
+
initiatorId: ownerAid, blocking: false, sensitive: true, expiresAt,
|
|
288
|
+
kind: { kind: 'action', title: '申请调整角色额度', allowCustomInput: true,
|
|
289
|
+
body: `Agent:${self}\n角色:${budget.role}\n已用 / 上限:${budget.currency} ${budget.used_amount} / ${budget.limit_amount}`
|
|
290
|
+
+ `\n计费对象:${budget.usage_subject_key}\n请输入新的金额上限;这会修改该角色所有关系使用的额度配置。`,
|
|
291
|
+
buttons: [{ key: 'reject', label: '暂不调整' }] },
|
|
292
|
+
}).catch(() => false);
|
|
293
|
+
const sent = await entry.delivery;
|
|
294
|
+
if (sent)
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
catch { /* Delivery failure must leave the next blocked request retryable. */ }
|
|
298
|
+
this.pending.delete(key);
|
|
299
|
+
await this.router.cancel(id, 'delivery_failed');
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function resolveQuotaCommand(args, selfAid) {
|
|
304
|
+
const fields = new Map([
|
|
305
|
+
['--enabled', 'enabled'], ['--limit', 'limitAmount'], ['--currency', 'currency'],
|
|
306
|
+
['--reset', 'resetMode'], ['--cost-basis', 'costBasis'], ['--scope', 'scope'],
|
|
307
|
+
]);
|
|
308
|
+
const options = new Map();
|
|
309
|
+
const positional = [];
|
|
310
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
311
|
+
const token = args[index];
|
|
312
|
+
if (!token.startsWith('-')) {
|
|
313
|
+
positional.push(token);
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (!fields.has(token) && !['--self', '--format'].includes(token)) {
|
|
317
|
+
return invalid('INVALID_ARGUMENT', `Unknown quota option: ${token}`);
|
|
318
|
+
}
|
|
319
|
+
if (options.has(token))
|
|
320
|
+
return invalid('INVALID_ARGUMENT', `Duplicate option: ${token}`);
|
|
321
|
+
const value = args[++index];
|
|
322
|
+
if (!value || value.startsWith('--'))
|
|
323
|
+
return invalid('INVALID_ARGUMENT', `${token} requires a value`);
|
|
324
|
+
options.set(token, value);
|
|
325
|
+
}
|
|
326
|
+
const [, action, roleId, ...extra] = positional;
|
|
327
|
+
if (!['show', 'set', 'disable', 'inherit'].includes(action) || !isRoleName(roleId) || extra.length) {
|
|
328
|
+
return invalid('INVALID_ARGUMENT', 'Expected role quota show|set|disable|inherit <role-id>');
|
|
329
|
+
}
|
|
330
|
+
if (options.has('--format') && options.get('--format') !== 'json') {
|
|
331
|
+
return invalid('INVALID_ARGUMENT', '--format only supports json');
|
|
332
|
+
}
|
|
333
|
+
const patch = {};
|
|
334
|
+
for (const [flag, field] of fields) {
|
|
335
|
+
const value = options.get(flag);
|
|
336
|
+
if (value === undefined)
|
|
337
|
+
continue;
|
|
338
|
+
if (action !== 'set')
|
|
339
|
+
return invalid('INVALID_ARGUMENT', `${flag} is only supported by quota set`);
|
|
340
|
+
if (field === 'enabled') {
|
|
341
|
+
if (value !== 'true' && value !== 'false')
|
|
342
|
+
return invalid('INVALID_ARGUMENT', '--enabled must be true or false');
|
|
343
|
+
patch.enabled = value === 'true';
|
|
344
|
+
}
|
|
345
|
+
else if (field === 'limitAmount') {
|
|
346
|
+
if (value === 'unlimited')
|
|
347
|
+
patch.limitAmount = null;
|
|
348
|
+
else if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value) || !Number.isFinite(Number(value))) {
|
|
349
|
+
return invalid('INVALID_ARGUMENT', '--limit must be a non-negative amount or unlimited');
|
|
350
|
+
}
|
|
351
|
+
else
|
|
352
|
+
patch.limitAmount = Number(value);
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
const choices = {
|
|
356
|
+
currency: ['CNY', 'USD'], resetMode: ['never', 'daily', 'weekly', 'monthly'],
|
|
357
|
+
costBasis: ['gateway', 'official'], scope: ['subject', 'role'],
|
|
358
|
+
};
|
|
359
|
+
if (!choices[field].includes(value))
|
|
360
|
+
return invalid('INVALID_ARGUMENT', `${flag} must be ${choices[field].join('|')}`);
|
|
361
|
+
Object.assign(patch, { [field]: value });
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (action === 'set' && !Object.keys(patch).length) {
|
|
365
|
+
return invalid('INVALID_ARGUMENT', 'quota set requires at least one quota option');
|
|
366
|
+
}
|
|
367
|
+
if (action === 'disable')
|
|
368
|
+
patch.enabled = false;
|
|
369
|
+
return { ok: true, command: {
|
|
370
|
+
kind: 'quota', action: action, selfAid, roleId, patch,
|
|
371
|
+
canonicalArgv: canonicalArgv(['role', ...args]),
|
|
372
|
+
} };
|
|
373
|
+
}
|
|
127
374
|
function parseStatus(value) {
|
|
128
375
|
return value === 'pending' || value === 'approved' || value === 'rejected' || value === 'expired'
|
|
129
376
|
? value
|
|
@@ -6,9 +6,13 @@ import { resolvePaths } from '../paths.js';
|
|
|
6
6
|
import { acquireConfigMutationLock, ConfigError } from './config-manager.js';
|
|
7
7
|
import { firstConfiguredOwner } from './owner-config.js';
|
|
8
8
|
import { currentVersion, loadSchema } from './schema-registry.js';
|
|
9
|
-
import { planProviderIdentityMigration } from './provider-identity-migration.js';
|
|
9
|
+
import { planProviderIdentityMigration, validateProviderIdentityMigrationPlan } from './provider-identity-migration.js';
|
|
10
10
|
import { providerIdentity } from './provider-identity.js';
|
|
11
11
|
import { snapshot } from './snapshot.js';
|
|
12
|
+
import { logger } from '../utils/logger.js';
|
|
13
|
+
import { parseContactAlias } from './peer-alias.js';
|
|
14
|
+
import { recoverAllPeerBookMutationsSync } from './peer-book-store.js';
|
|
15
|
+
import { atomicReplaceFile } from '../utils/atomic-write.js';
|
|
12
16
|
const MIGRATION_KIND = {
|
|
13
17
|
'auxiliary-model-v1': 'auxiliary-model',
|
|
14
18
|
'agent-only-model-v1': 'agent-only-model',
|
|
@@ -20,6 +24,7 @@ const MIGRATION_KIND = {
|
|
|
20
24
|
'legacy-model-selection-v1': 'agent-only-model',
|
|
21
25
|
'access-policy-v17-v1': 'agent-only-model',
|
|
22
26
|
'peer-file-v1': 'agent-only-model',
|
|
27
|
+
'peer-state-v4': 'agent-only-model',
|
|
23
28
|
};
|
|
24
29
|
const SUPPORTED_BASEAGENTS = new Set(['claude', 'codex', 'gemini', 'ecagent']);
|
|
25
30
|
const BASEAGENT_ALIASES = new Map([
|
|
@@ -42,20 +47,24 @@ function hasOwn(value, field) {
|
|
|
42
47
|
return Object.prototype.hasOwnProperty.call(value, field);
|
|
43
48
|
}
|
|
44
49
|
let startupReadCache = null;
|
|
50
|
+
let startupRelationFiles = null;
|
|
45
51
|
/**
|
|
46
52
|
* 在这个作用域内共享配置读取结果。
|
|
47
53
|
*
|
|
48
54
|
* 只能包住「只读规划」阶段:一旦有迁移落盘,缓存里的内容就过期了。
|
|
49
|
-
*
|
|
55
|
+
* 配置文本与关系文件列表共用作用域,结束后自动失效。
|
|
50
56
|
*/
|
|
51
57
|
export async function withMigrationReadCache(run) {
|
|
52
58
|
const previous = startupReadCache;
|
|
59
|
+
const previousRelations = startupRelationFiles;
|
|
53
60
|
startupReadCache = new Map();
|
|
61
|
+
startupRelationFiles = new Map();
|
|
54
62
|
try {
|
|
55
63
|
return await run();
|
|
56
64
|
}
|
|
57
65
|
finally {
|
|
58
66
|
startupReadCache = previous;
|
|
67
|
+
startupRelationFiles = previousRelations;
|
|
59
68
|
}
|
|
60
69
|
}
|
|
61
70
|
/**
|
|
@@ -68,6 +77,7 @@ export async function withMigrationReadCache(run) {
|
|
|
68
77
|
*/
|
|
69
78
|
export function invalidateMigrationReadCache() {
|
|
70
79
|
startupReadCache?.clear();
|
|
80
|
+
startupRelationFiles?.clear();
|
|
71
81
|
}
|
|
72
82
|
function readJson(file) {
|
|
73
83
|
if (startupReadCache) {
|
|
@@ -374,6 +384,9 @@ function migrateConfig(input, file, parentContext) {
|
|
|
374
384
|
};
|
|
375
385
|
}
|
|
376
386
|
function walkRelationConfigs(dir) {
|
|
387
|
+
const cached = startupRelationFiles?.get(dir);
|
|
388
|
+
if (cached)
|
|
389
|
+
return cached;
|
|
377
390
|
if (!fs.existsSync(dir))
|
|
378
391
|
return [];
|
|
379
392
|
const files = [];
|
|
@@ -386,6 +399,7 @@ function walkRelationConfigs(dir) {
|
|
|
386
399
|
else if (entry.isFile() && entry.name === 'config.json')
|
|
387
400
|
files.push(full);
|
|
388
401
|
}
|
|
402
|
+
startupRelationFiles?.set(dir, files);
|
|
389
403
|
return files;
|
|
390
404
|
}
|
|
391
405
|
function planConfigFile(file, parentContext, changes, summary) {
|
|
@@ -525,10 +539,55 @@ function acquireLock(home, id) {
|
|
|
525
539
|
}
|
|
526
540
|
function atomicWrite(file, content) {
|
|
527
541
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
528
|
-
const
|
|
542
|
+
const exists = fs.existsSync(file);
|
|
543
|
+
const mode = exists ? fs.statSync(file).mode & 0o777 : 0o600;
|
|
544
|
+
const windows = process.platform === 'win32';
|
|
545
|
+
const readonly = windows && exists && (mode & 0o200) === 0;
|
|
529
546
|
const temp = `${file}.schema-migration-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
530
|
-
|
|
531
|
-
|
|
547
|
+
let restoreReadonly = false;
|
|
548
|
+
let failure;
|
|
549
|
+
let failed = false;
|
|
550
|
+
try {
|
|
551
|
+
// A Windows readonly temporary file cannot be safely cleaned up on failure.
|
|
552
|
+
fs.writeFileSync(temp, content, { mode: windows ? mode | 0o200 : mode, flag: 'wx' });
|
|
553
|
+
if (readonly) {
|
|
554
|
+
fs.chmodSync(file, mode | 0o200);
|
|
555
|
+
restoreReadonly = true;
|
|
556
|
+
}
|
|
557
|
+
// Migration journals restore complete files; never truncate the live file
|
|
558
|
+
// as a fallback when Windows refuses to replace its directory entry.
|
|
559
|
+
atomicReplaceFile(temp, file, { allowInPlaceFallback: false });
|
|
560
|
+
}
|
|
561
|
+
catch (error) {
|
|
562
|
+
failed = true;
|
|
563
|
+
failure = error;
|
|
564
|
+
}
|
|
565
|
+
finally {
|
|
566
|
+
if (restoreReadonly) {
|
|
567
|
+
try {
|
|
568
|
+
fs.chmodSync(file, mode);
|
|
569
|
+
}
|
|
570
|
+
catch (error) {
|
|
571
|
+
failure = failed ? migrationRecoveryFailure(failure, error, 'Restoring readonly attribute failed') : error;
|
|
572
|
+
failed = true;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
try {
|
|
576
|
+
fs.rmSync(temp, { force: true });
|
|
577
|
+
}
|
|
578
|
+
catch (error) {
|
|
579
|
+
logger.warn(`[config] Could not remove migration temporary file ${temp}: ${error}`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
if (failed)
|
|
583
|
+
throw failure;
|
|
584
|
+
}
|
|
585
|
+
function migrationRecoveryFailure(original, recovery, step) {
|
|
586
|
+
const detail = (error) => error instanceof Error ? error.message : String(error);
|
|
587
|
+
const error = new AggregateError([original, recovery], `${detail(original)}; ${step}: ${detail(recovery)}`, {
|
|
588
|
+
cause: original,
|
|
589
|
+
});
|
|
590
|
+
return Object.assign(error, isRecord(original) && typeof original.code === 'string' ? { code: original.code } : {});
|
|
532
591
|
}
|
|
533
592
|
function journalPath(home, id) {
|
|
534
593
|
return path.join(home, 'data', `${id}-migration.json`);
|
|
@@ -538,7 +597,11 @@ function writeJournal(plan, state, id) {
|
|
|
538
597
|
schemaVersion: 1,
|
|
539
598
|
state,
|
|
540
599
|
home: plan.home,
|
|
541
|
-
changes: plan.changes
|
|
600
|
+
changes: plan.changes.map(item => ({
|
|
601
|
+
...item,
|
|
602
|
+
...(process.platform === 'win32' && item.before !== null
|
|
603
|
+
? { mode: fs.statSync(item.file).mode & 0o777 } : {}),
|
|
604
|
+
})),
|
|
542
605
|
};
|
|
543
606
|
atomicWrite(journalPath(plan.home, id), jsonText(journal));
|
|
544
607
|
}
|
|
@@ -563,7 +626,8 @@ function readJournal(home, id) {
|
|
|
563
626
|
const changes = [];
|
|
564
627
|
for (const item of raw.changes) {
|
|
565
628
|
if (!isRecord(item) || typeof item.file !== 'string' || typeof item.after !== 'string'
|
|
566
|
-
|| (item.before !== null && typeof item.before !== 'string')
|
|
629
|
+
|| (item.before !== null && typeof item.before !== 'string')
|
|
630
|
+
|| (item.mode !== undefined && (!Number.isInteger(item.mode) || Number(item.mode) < 0 || Number(item.mode) > 0o777))) {
|
|
567
631
|
throw new Error(`Migration journal contains an unsafe change: ${file}`);
|
|
568
632
|
}
|
|
569
633
|
const target = path.resolve(item.file);
|
|
@@ -575,6 +639,7 @@ function readJournal(home, id) {
|
|
|
575
639
|
kind: MIGRATION_KIND[id],
|
|
576
640
|
before: item.before,
|
|
577
641
|
after: item.after,
|
|
642
|
+
...(typeof item.mode === 'number' ? { mode: item.mode } : {}),
|
|
578
643
|
});
|
|
579
644
|
}
|
|
580
645
|
return {
|
|
@@ -592,8 +657,27 @@ function recoverJournal(home, id) {
|
|
|
592
657
|
for (const item of [...journal.changes].reverse()) {
|
|
593
658
|
if (item.before === null)
|
|
594
659
|
fs.rmSync(item.file, { force: true });
|
|
595
|
-
else
|
|
596
|
-
|
|
660
|
+
else {
|
|
661
|
+
// A failed first replacement may leave the original already intact.
|
|
662
|
+
// Replacing it again can repeat the same Windows access error forever.
|
|
663
|
+
let current;
|
|
664
|
+
try {
|
|
665
|
+
current = fs.readFileSync(item.file, 'utf8');
|
|
666
|
+
}
|
|
667
|
+
catch (error) {
|
|
668
|
+
if (!isRecord(error) || error.code !== 'ENOENT')
|
|
669
|
+
throw error;
|
|
670
|
+
current = null;
|
|
671
|
+
}
|
|
672
|
+
if (current !== item.before)
|
|
673
|
+
atomicWrite(item.file, item.before);
|
|
674
|
+
// Also restore readonly after a crash between chmod and replacement,
|
|
675
|
+
// including when the original bytes were never changed.
|
|
676
|
+
if (process.platform === 'win32' && item.mode !== undefined
|
|
677
|
+
&& (fs.statSync(item.file).mode & 0o200) !== (item.mode & 0o200)) {
|
|
678
|
+
fs.chmodSync(item.file, item.mode);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
597
681
|
}
|
|
598
682
|
}
|
|
599
683
|
fs.rmSync(journalPath(home, id), { force: true });
|
|
@@ -633,7 +717,12 @@ function applyMigration(plan, id) {
|
|
|
633
717
|
fs.rmSync(journalPath(plan.home, id), { force: true });
|
|
634
718
|
}
|
|
635
719
|
catch (error) {
|
|
636
|
-
|
|
720
|
+
try {
|
|
721
|
+
recoverJournal(plan.home, id);
|
|
722
|
+
}
|
|
723
|
+
catch (recovery) {
|
|
724
|
+
throw migrationRecoveryFailure(error, recovery, 'Migration rollback failed');
|
|
725
|
+
}
|
|
637
726
|
throw error;
|
|
638
727
|
}
|
|
639
728
|
return backup;
|
|
@@ -1303,16 +1392,17 @@ function planAgentModelProviderMigration(home) {
|
|
|
1303
1392
|
value.$schema_version = AGENT_CONFIG_RESTAMP.to;
|
|
1304
1393
|
}
|
|
1305
1394
|
summary.gatewayFieldsRemoved += removed.length;
|
|
1306
|
-
|
|
1307
|
-
if (nextText === entry.text)
|
|
1395
|
+
if (isDeepStrictEqual(value, entry.value))
|
|
1308
1396
|
continue;
|
|
1397
|
+
const nextText = jsonText(value);
|
|
1309
1398
|
changes.push({ file, kind: 'agent-only-model', before: entry.text, after: nextText });
|
|
1310
1399
|
details.push({ file: path.relative(home, file), removed });
|
|
1311
1400
|
summary.filesChanged += 1;
|
|
1312
1401
|
}
|
|
1313
1402
|
if (Object.keys(providers).length > 0) {
|
|
1314
|
-
const
|
|
1315
|
-
if (
|
|
1403
|
+
const nextRegistry = { $schema_version: 1, ...providerRegistry, providers };
|
|
1404
|
+
if (!isDeepStrictEqual(nextRegistry, providerRegistry)) {
|
|
1405
|
+
const nextText = jsonText(nextRegistry);
|
|
1316
1406
|
changes.push({ file: providersFile, kind: 'agent-only-model', before: providersBefore, after: nextText });
|
|
1317
1407
|
details.push({ file: 'providers.json', removed: [] });
|
|
1318
1408
|
summary.filesChanged += 1;
|
|
@@ -1420,7 +1510,14 @@ export function runProviderIdentitySchemaMigration(options = {}) {
|
|
|
1420
1510
|
try {
|
|
1421
1511
|
assertDaemonStopped(home);
|
|
1422
1512
|
recoverJournal(home, id);
|
|
1423
|
-
|
|
1513
|
+
let plan;
|
|
1514
|
+
try {
|
|
1515
|
+
plan = planProviderIdentityMigration(home, undefined, { cleanupAliases: true });
|
|
1516
|
+
}
|
|
1517
|
+
catch (error) {
|
|
1518
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1519
|
+
throw new ConfigError('PROVIDER_IDENTITY_PLAN_FAILED', `Provider identity migration planning failed: ${detail}`, { cause: error });
|
|
1520
|
+
}
|
|
1424
1521
|
const backup = options.apply ? commitProviderSyncMigration(plan, true) : null;
|
|
1425
1522
|
return { ok: true, mode: options.apply ? 'applied' : 'dry-run',
|
|
1426
1523
|
home, changedFiles: plan.changes.length, backup, summary: plan.summary, pending: plan.pending };
|
|
@@ -1435,7 +1532,19 @@ export async function ensureProviderIdentityMigrationOnStartup() {
|
|
|
1435
1532
|
return result.changedFiles === 0 && result.pending.length === 0 ? null : result;
|
|
1436
1533
|
}
|
|
1437
1534
|
catch (error) {
|
|
1438
|
-
|
|
1535
|
+
if (!(error instanceof ConfigError) || error.code !== 'PROVIDER_IDENTITY_PLAN_FAILED') {
|
|
1536
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1537
|
+
throw new ConfigError('PROVIDER_IDENTITY_MIGRATION_FAILED', `Automatic Provider identity migration failed: ${detail}`, { cause: error });
|
|
1538
|
+
}
|
|
1539
|
+
const cause = isRecord(error.data) ? error.data.cause : error;
|
|
1540
|
+
const code = isRecord(cause) && typeof cause.code === 'string'
|
|
1541
|
+
? cause.code : 'PROVIDER_IDENTITY_PLAN_FAILED';
|
|
1542
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
1543
|
+
const message = `[config] Automatic Provider identity migration skipped [${code}]: ${detail}; `
|
|
1544
|
+
+ 'continuing startup with existing configuration';
|
|
1545
|
+
logger.warn(message);
|
|
1546
|
+
console.error(`⚠ ${message}`);
|
|
1547
|
+
return null;
|
|
1439
1548
|
}
|
|
1440
1549
|
}
|
|
1441
1550
|
export function commitProviderSyncMigration(plan, migrationLocked = false) {
|
|
@@ -1464,6 +1573,7 @@ export function commitProviderSyncMigration(plan, migrationLocked = false) {
|
|
|
1464
1573
|
throw Object.assign(new Error('Configuration changed during Provider sync; retry after reviewing the current configuration'), { code: 'CONFLICT' });
|
|
1465
1574
|
}
|
|
1466
1575
|
}
|
|
1576
|
+
validateProviderIdentityMigrationPlan(plan);
|
|
1467
1577
|
return applyMigration(plan, id);
|
|
1468
1578
|
}
|
|
1469
1579
|
finally {
|
|
@@ -1969,8 +2079,8 @@ export async function ensureAccessPolicyMigrationOnStartup() {
|
|
|
1969
2079
|
* `contact.json` 只承载本 Agent 的身份映射、displayName 与本地拉黑,和 Owner 名录副本
|
|
1970
2080
|
* `contacts.json` 名字太近。v17 起改称 `peers.json`,这里把既有文件搬过去。
|
|
1971
2081
|
*
|
|
1972
|
-
*
|
|
1973
|
-
*
|
|
2082
|
+
* 有身份绑定或本地拉黑时搬移;只有已退役数据时归档,不创建 peers.json。
|
|
2083
|
+
* 目标已存在时保留目标、把旧文件留在原地由 Owner 复核。
|
|
1974
2084
|
*/
|
|
1975
2085
|
function planPeerFileRename(home) {
|
|
1976
2086
|
const changes = [];
|
|
@@ -1996,9 +2106,25 @@ function planPeerFileRename(home) {
|
|
|
1996
2106
|
continue;
|
|
1997
2107
|
}
|
|
1998
2108
|
const text = fs.readFileSync(legacy, 'utf8');
|
|
1999
|
-
|
|
2109
|
+
const value = JSON.parse(text);
|
|
2110
|
+
if (!isRecord(value) || !isRecord(value.contacts)
|
|
2111
|
+
|| ![1, 2, 3].includes(Number(value.$schema_version))
|
|
2112
|
+
|| !loadSchema('contact-book', Number(value.$schema_version)).validate(value)) {
|
|
2113
|
+
throw new Error(`Invalid legacy peer state: ${legacy}`);
|
|
2114
|
+
}
|
|
2115
|
+
const useful = Object.values(value.contacts).some(contact => isRecord(contact)
|
|
2116
|
+
&& ((Array.isArray(contact.aliases) && contact.aliases.length > 0)
|
|
2117
|
+
|| contact.status === 'blocked' || contact.blocked === true));
|
|
2118
|
+
const destination = useful ? target : `${legacy}.migrated`;
|
|
2119
|
+
const before = fs.existsSync(destination) ? fs.readFileSync(destination, 'utf8') : null;
|
|
2120
|
+
if (before !== null && before !== text) {
|
|
2121
|
+
throw new Error(`Legacy peer archive conflicts with existing data: ${destination}`);
|
|
2122
|
+
}
|
|
2123
|
+
if (before !== text)
|
|
2124
|
+
changes.push({ file: destination, kind: 'agent-only-model', before, after: text });
|
|
2000
2125
|
legacyFiles.push(legacy);
|
|
2001
|
-
details.push({ file: path.relative(home, legacy), removed: ['contact.json'],
|
|
2126
|
+
details.push({ file: path.relative(home, legacy), removed: ['contact.json'],
|
|
2127
|
+
migrated: [useful ? '→peers.json' : '→contact.json.migrated (no peer state needed)'] });
|
|
2002
2128
|
summary.filesChanged += 1;
|
|
2003
2129
|
}
|
|
2004
2130
|
return { home, changes, summary, details, legacyFiles };
|
|
@@ -2058,3 +2184,85 @@ export async function ensurePeerFileRenameOnStartup() {
|
|
|
2058
2184
|
throw new ConfigError('PEER_FILE_RENAME_MIGRATION_FAILED', `Automatic peer file rename migration failed: ${detail}`, { cause: error });
|
|
2059
2185
|
}
|
|
2060
2186
|
}
|
|
2187
|
+
/** One-time retirement of contact membership, display names and management projections. */
|
|
2188
|
+
export function runPeerStateMigration(options = {}) {
|
|
2189
|
+
const id = 'peer-state-v4';
|
|
2190
|
+
const home = path.resolve(options.home || resolvePaths().root);
|
|
2191
|
+
const release = acquireLock(home, id);
|
|
2192
|
+
try {
|
|
2193
|
+
assertDaemonStopped(home);
|
|
2194
|
+
recoverJournal(home, id);
|
|
2195
|
+
const changes = [];
|
|
2196
|
+
const root = path.join(home, 'agents');
|
|
2197
|
+
const entries = fs.existsSync(root) ? fs.readdirSync(root, { withFileTypes: true }) : [];
|
|
2198
|
+
const schema = loadSchema('contact-book', 4);
|
|
2199
|
+
for (const entry of entries) {
|
|
2200
|
+
if (!entry.isDirectory() || !validAid(entry.name))
|
|
2201
|
+
continue;
|
|
2202
|
+
const file = path.join(root, entry.name, 'peers.json');
|
|
2203
|
+
if (!fs.existsSync(file))
|
|
2204
|
+
continue;
|
|
2205
|
+
const configFile = path.join(root, entry.name, 'config.json');
|
|
2206
|
+
if (!fs.existsSync(configFile))
|
|
2207
|
+
continue;
|
|
2208
|
+
const agent = JSON.parse(fs.readFileSync(configFile, 'utf8'));
|
|
2209
|
+
const channelKeys = new Set((Array.isArray(agent.channels) ? agent.channels : [])
|
|
2210
|
+
.filter((channel) => channel && channel.type !== 'aun' && typeof channel.name === 'string')
|
|
2211
|
+
.map((channel) => channel.type + '#' + entry.name + '#' + channel.name));
|
|
2212
|
+
const before = fs.readFileSync(file, 'utf8');
|
|
2213
|
+
const old = JSON.parse(before);
|
|
2214
|
+
if (!isRecord(old) || !isRecord(old.contacts)
|
|
2215
|
+
|| ![1, 2, 3, 4].includes(Number(old.$schema_version))) {
|
|
2216
|
+
throw new Error('Invalid peer state: ' + file);
|
|
2217
|
+
}
|
|
2218
|
+
if (!loadSchema('contact-book', Number(old.$schema_version)).validate(old)) {
|
|
2219
|
+
throw new Error('Invalid legacy peer state: ' + file);
|
|
2220
|
+
}
|
|
2221
|
+
if (old.$schema_version === 4) {
|
|
2222
|
+
if (!schema.validate(old))
|
|
2223
|
+
throw new Error('Invalid peer state: ' + file);
|
|
2224
|
+
continue;
|
|
2225
|
+
}
|
|
2226
|
+
const contacts = {};
|
|
2227
|
+
const aliases = new Set();
|
|
2228
|
+
for (const [aid, value] of Object.entries(old.contacts)) {
|
|
2229
|
+
if (!validAid(aid) || !isRecord(value))
|
|
2230
|
+
throw new Error('Invalid peer entry: ' + file);
|
|
2231
|
+
const kept = {};
|
|
2232
|
+
if (value.aliases !== undefined) {
|
|
2233
|
+
if (!Array.isArray(value.aliases))
|
|
2234
|
+
throw new Error('Invalid peer aliases: ' + file);
|
|
2235
|
+
for (const alias of value.aliases) {
|
|
2236
|
+
const parsed = parseContactAlias(alias, entry.name);
|
|
2237
|
+
if (!parsed || !channelKeys.has(parsed.channelKey) || aliases.has(alias)) {
|
|
2238
|
+
throw new Error('Invalid or conflicting peer alias: ' + file);
|
|
2239
|
+
}
|
|
2240
|
+
aliases.add(alias);
|
|
2241
|
+
}
|
|
2242
|
+
if (value.aliases.length)
|
|
2243
|
+
kept.aliases = [...value.aliases];
|
|
2244
|
+
}
|
|
2245
|
+
if (value.status === 'blocked' || value.blocked === true)
|
|
2246
|
+
kept.status = 'blocked';
|
|
2247
|
+
if (kept.aliases || kept.status)
|
|
2248
|
+
contacts[aid] = kept;
|
|
2249
|
+
}
|
|
2250
|
+
const next = { $schema_version: 4, contacts };
|
|
2251
|
+
if (!schema.validate(next))
|
|
2252
|
+
throw new Error('Invalid migrated peer state: ' + file);
|
|
2253
|
+
changes.push({ file, kind: 'agent-only-model', before, after: jsonText(next) });
|
|
2254
|
+
}
|
|
2255
|
+
const plan = { home, changes, summary: { filesChanged: changes.length } };
|
|
2256
|
+
const backup = options.apply ? applyMigration(plan, id) : null;
|
|
2257
|
+
return { changedFiles: changes.length, backup };
|
|
2258
|
+
}
|
|
2259
|
+
finally {
|
|
2260
|
+
release();
|
|
2261
|
+
}
|
|
2262
|
+
}
|
|
2263
|
+
export async function ensurePeerStateOnStartup() {
|
|
2264
|
+
recoverAllPeerBookMutationsSync();
|
|
2265
|
+
const result = runPeerStateMigration({ apply: true });
|
|
2266
|
+
if (result.changedFiles)
|
|
2267
|
+
logger.info('[peers] Retired contact membership in ' + result.changedFiles + ' peer state files');
|
|
2268
|
+
}
|