evolcore 0.0.41-test.0 → 0.0.41-test.2
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 +62 -0
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/baseagent.js +88 -49
- package/dist/agents/claude-runner.js +177 -92
- package/dist/agents/codex-runner.js +146 -71
- package/dist/agents/ecagent-runner.js +1 -1
- package/dist/agents/gemini-runner.js +1 -1
- package/dist/aun/aid/agentmd.js +98 -11
- package/dist/aun/aid/client.js +1 -1
- package/dist/aun/aid/control-aid.js +26 -2
- package/dist/aun/aid/identity.js +91 -0
- package/dist/aun/aid/index.js +1 -1
- package/dist/aun/aid/managed-operation.js +1 -1
- package/dist/aun/aid/ownership-operation.js +23 -22
- package/dist/aun/group/fs-download.js +39 -0
- package/dist/aun/group/identity.js +36 -21
- package/dist/aun/group/operations.js +5 -0
- package/dist/aun/menu/client.js +27 -0
- package/dist/aun/msg/managed-operation.js +68 -7
- package/dist/aun/msg/p2p.js +8 -8
- package/dist/aun/service-proxy.js +53 -12
- package/dist/channels/aun.js +633 -32
- package/dist/channels/daemon.js +15 -1
- package/dist/cli/agent-command.js +5 -2
- package/dist/cli/agent-create.js +991 -233
- package/dist/cli/agent.js +49 -10
- package/dist/cli/aid-bind-command.js +48 -19
- package/dist/cli/aun-commands.js +48 -36
- package/dist/cli/daemon-commands.js +679 -697
- package/dist/cli/fs-command.js +64 -2
- package/dist/cli/index.js +72 -5
- package/dist/cli/init-channel.js +1 -1
- package/dist/cli/init.js +75 -1
- package/dist/cli/managed-command-guard.js +17 -1
- package/dist/cli/model.js +40 -40
- package/dist/cli/provider-command.js +57 -0
- package/dist/cli/proxy-command.js +92 -0
- package/dist/cli/restart-monitor.js +4 -2
- package/dist/cli/role.js +85 -0
- package/dist/cli/stats.js +10 -3
- package/dist/cli/task-context.js +19 -0
- package/dist/config/access-policy.js +7 -2
- package/dist/config/boot-log.js +39 -1
- package/dist/config/config-field-policy.js +17 -39
- package/dist/config/config-manager.js +183 -44
- package/dist/config/config-operation-service.js +5 -19
- package/dist/config/contact-book-store.js +47 -21
- package/dist/config/contact-book.js +18 -12
- package/dist/config/contact-operation-service.js +3 -4
- package/dist/config/contact-request-service.js +11 -0
- package/dist/config/daemon-services.js +11 -0
- package/dist/config/gateway-config.js +88 -594
- package/dist/config/owner-config.js +2 -2
- package/dist/config/peer-role-resolver.js +15 -12
- package/dist/config/provider-ipc-service.js +132 -0
- package/dist/config/provider-menu-request.js +58 -0
- package/dist/config/providers-config.js +12 -7
- package/dist/config/providers-import.js +3 -21
- package/dist/config/providers-management.js +78 -5
- package/dist/config/resolved-config-op.js +11 -1
- package/dist/config/role-command-service.js +166 -0
- package/dist/config/role-request-service.js +193 -0
- package/dist/config/schema-migration.js +1000 -25
- package/dist/config-store.js +89 -4
- package/dist/contracts/ecweb-instance.js +41 -0
- package/dist/contracts/ecweb-service-protocol.js +4 -1
- package/dist/core/agent-application-service.js +60 -11
- package/dist/core/agent-create-status.js +203 -0
- package/dist/core/agent-creation-claim.js +177 -0
- package/dist/core/agent-ipc-registration.js +39 -18
- package/dist/core/agent-runtime.js +194 -24
- package/dist/core/auth/agent-delegation.js +6 -3
- package/dist/core/auth/auth-gateway.js +67 -2
- package/dist/core/auth/authorization-audit.js +58 -11
- package/dist/core/auth/delegation-authorization.js +5 -2
- package/dist/core/auth/operation-authorizer.js +43 -6
- package/dist/core/auth/operation-catalog.js +45 -7
- package/dist/core/channel-loader.js +2 -0
- package/dist/core/command/agent-control.js +260 -21
- package/dist/core/command/agent-storage-menu.js +5 -3
- package/dist/core/command/cli-intent-parser.js +8 -3
- package/dist/core/command/command-handler.js +112 -154
- package/dist/core/command/connect-menu.js +11 -3
- package/dist/core/command/data-root-resolver.js +5 -4
- package/dist/core/command/memory-slash.js +16 -8
- package/dist/core/command/menu-catalog.js +10 -6
- package/dist/core/command/menu-handler.js +106 -73
- package/dist/core/command/menu-protocol.js +15 -1
- package/dist/core/command/provider-menu.js +46 -0
- package/dist/core/command/role-menu.js +147 -30
- package/dist/core/command/slash-handler.js +125 -255
- package/dist/core/daemon-control.js +26 -27
- package/dist/core/event-catalog.js +10 -0
- package/dist/core/evolagent-registry.js +7 -5
- package/dist/core/evolagent.js +10 -8
- package/dist/core/file-integrity/store.js +11 -0
- package/dist/core/handoff/ipc-registration.js +3 -0
- package/dist/core/inference/text-inference.js +31 -40
- package/dist/core/initialization/service.js +491 -0
- package/dist/core/ipc-registration.js +40 -24
- package/dist/core/memory/consolidation-context.js +51 -5
- package/dist/core/memory/consolidation-ops-records.js +96 -1
- package/dist/core/memory/consolidation-trigger.js +208 -191
- package/dist/core/memory/consolidation.js +333 -35
- package/dist/core/memory/index-manager.js +27 -5
- package/dist/core/memory/memory-admin.js +45 -5
- package/dist/core/memory/memory-writer.js +163 -18
- package/dist/core/memory/relation-idle-monitor.js +119 -58
- package/dist/core/memory/relation-sweep.js +55 -45
- package/dist/core/message/aun-ipc-sender.js +81 -69
- package/dist/core/message/im-renderer.js +25 -4
- package/dist/core/message/message-admission.js +89 -4
- package/dist/core/message/message-bridge.js +66 -21
- package/dist/core/message/response-engine.js +108 -35
- package/dist/core/model/catalog-service.js +5 -3
- package/dist/core/model/config-scope.js +29 -71
- package/dist/core/model/field-scope.js +1 -1
- package/dist/core/model/model-catalog.js +30 -41
- package/dist/core/model/model-diagnostics.js +4 -3
- package/dist/core/model/model-fallback.js +10 -7
- package/dist/core/model/model-permission.js +3 -2
- package/dist/core/ownership/owner-resolver.js +772 -158
- package/dist/core/permission/approval-gateway.js +103 -403
- package/dist/core/permission/ec-command-parser.js +62 -6
- package/dist/core/permission/index.js +1 -0
- package/dist/core/permission/permission-result.js +78 -0
- package/dist/core/permission/sandbox-runtime.js +18 -1
- package/dist/core/permission/tool-policy.js +21 -46
- package/dist/core/relation/peer-identity.js +64 -1
- package/dist/core/role/runtime-policy.js +72 -13
- package/dist/core/session/session-capsule.js +1 -1
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +20 -0
- package/dist/core/session/session-renew.js +3 -3
- package/dist/core/skill/index-generator.js +15 -5
- package/dist/core/system-session/memory.js +43 -8
- package/dist/core/thread/thread-service.js +19 -6
- package/dist/directory/owner-directory-admission.js +95 -0
- package/dist/directory/owner-directory-authorization.js +309 -0
- package/dist/directory/owner-directory-cache.js +635 -0
- package/dist/eck/kit-renderer.js +2 -2
- package/dist/ecweb/basic-settings-service.js +33 -40
- package/dist/ecweb/init-menu.js +32 -0
- package/dist/ecweb/message-context-service.js +110 -0
- package/dist/index.js +93 -19
- package/dist/ipc.js +247 -29
- package/dist/paths.js +7 -0
- package/dist/proxy/command.js +122 -0
- package/dist/proxy/ipc-service.js +68 -0
- package/dist/proxy/manager.js +484 -0
- package/dist/proxy/service-supervisor.js +603 -0
- package/dist/response-system/engines/v1/proactive-flow.js +16 -6
- package/dist/trigger/authorization.js +27 -17
- package/dist/trigger/feedback.js +2 -3
- package/dist/trigger/ipc-service.js +105 -78
- package/dist/trigger/local-files.js +2 -1
- package/dist/trigger/manager.js +5 -3
- package/dist/trigger/scheduler.js +88 -6
- package/dist/utils/atomic-write.js +28 -0
- package/dist/utils/cross-platform.js +14 -0
- package/dist/utils/ecweb-supervisor.js +258 -83
- package/dist/utils/error-utils.js +26 -2
- package/dist/utils/logger.js +92 -6
- package/dist/utils/package-version-info.js +4 -2
- package/dist/utils/welcome.js +1 -1
- package/kits/docs/INDEX.md +1 -0
- package/kits/docs/aun/SDK.md +4 -1
- package/kits/docs/channels/aun.md +9 -0
- package/kits/docs/evolcore/INDEX.md +1 -0
- package/kits/docs/evolcore/agent.md +8 -1
- package/kits/docs/evolcore/aid.md +67 -17
- package/kits/docs/evolcore/config.md +28 -7
- package/kits/docs/evolcore/contact.md +3 -0
- package/kits/docs/evolcore/fs.md +11 -0
- package/kits/docs/evolcore/group.md +1 -1
- package/kits/docs/evolcore/memory-architecture.md +2 -2
- package/kits/docs/evolcore/memory-consolidation.md +32 -8
- package/kits/docs/evolcore/memory.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +4 -0
- package/kits/docs/evolcore/model.md +23 -20
- package/kits/docs/evolcore/msg.md +4 -7
- package/kits/docs/evolcore/provider.md +50 -0
- package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
- package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
- package/kits/rules/01-overview.md +3 -0
- package/kits/rules/04-relation.md +1 -1
- package/kits/schemas/_meta.json +37 -4
- package/kits/schemas/agent-config.schema.13.json +8 -3
- package/kits/schemas/agent-config.schema.16.json +891 -0
- package/kits/schemas/daemon.schema.9.json +366 -0
- package/kits/schemas/defaults.schema.5.json +406 -127
- package/kits/schemas/relation-config.schema.11.json +277 -0
- package/kits/schemas/role-config.schema.1.json +7 -7
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ec-agent-create/SKILL.md +3 -0
- package/kits/skills/ec-identity/SKILL.md +2 -2
- package/kits/skills/ec-service-proxy/SKILL.md +118 -0
- package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
- package/kits/skills/personal-assistant/SKILL.md +176 -0
- package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
- package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
- package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
- package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
- package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
- package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
- package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
- package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
- package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
- package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
- package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
- package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
- package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
- package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
- package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
- package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
- package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
- package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
- package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
- package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
- package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
- package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
- package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
- package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
- package/kits/skills/thread-ops/SKILL.md +5 -0
- package/kits/templates/memory-consolidation/forget.md +19 -6
- package/kits/templates/memory-consolidation/notes.md +1 -1
- package/kits/templates/memory-consolidation/profile.md +2 -2
- package/kits/templates/memory-consolidation/promote.md +20 -3
- package/kits/templates/roles/member.json +8 -1
- package/kits/templates/system-fragments/baseagent.md +2 -2
- package/kits/templates/system-fragments/memory.md +4 -4
- package/kits/templates/system-fragments/venue.md +1 -1
- package/package.json +7 -3
- package/dist/core/message/create-status.js +0 -96
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { resolvePaths } from '../../paths.js';
|
|
6
|
+
import { atomicReadJson, atomicWriteJson } from '../../utils/atomic-write.js';
|
|
7
|
+
import { loadDaemonConfig } from '../../config-store.js';
|
|
8
|
+
import { ConfigTarget, mutateConfig } from '../../config/config-manager.js';
|
|
9
|
+
import { getBaseagentSnapshot } from '../../agents/baseagent-availability.js';
|
|
10
|
+
import { isValidAid } from '../../aun/aid/validation.js';
|
|
11
|
+
import { listBaseagentImportSources, providerFromBaseagent } from '../../config/providers-import.js';
|
|
12
|
+
import { importOrMergeBaseagentProvider, readProvidersSnapshot } from '../../config/providers-management.js';
|
|
13
|
+
import { readInstalledEvolcoreVersion } from '../../utils/evolcore-version.js';
|
|
14
|
+
import { defaultProjectsRoot } from '../../utils/project-path.js';
|
|
15
|
+
import { resolveControlAidDomain } from '../../aun/aid/control-aid.js';
|
|
16
|
+
import { validateInitializationModelArgs } from '../../cli/agent-create.js';
|
|
17
|
+
import { isHClassPath, isLClassPath } from '../permission/protected-paths.js';
|
|
18
|
+
import { normalizeAvatarImage } from '../../utils/avatar-upload.js';
|
|
19
|
+
const require = createRequire(import.meta.url);
|
|
20
|
+
const TTL = 10 * 60 * 1000;
|
|
21
|
+
const steps = new Set(['welcome', 'binding', 'configuration', 'agent', 'ready']);
|
|
22
|
+
function record(value) {
|
|
23
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
24
|
+
}
|
|
25
|
+
function fail(code, message, statusCode = 400) {
|
|
26
|
+
throw Object.assign(new Error(message), { code, statusCode });
|
|
27
|
+
}
|
|
28
|
+
function qrSvg(payload) {
|
|
29
|
+
const QRCode = require('qrcode-terminal/vendor/QRCode');
|
|
30
|
+
const qr = new QRCode(-1, 1);
|
|
31
|
+
qr.addData(JSON.stringify(payload));
|
|
32
|
+
qr.make();
|
|
33
|
+
const count = qr.getModuleCount();
|
|
34
|
+
const cells = [];
|
|
35
|
+
for (let row = 0; row < count; row++) {
|
|
36
|
+
for (let column = 0; column < count; column++) {
|
|
37
|
+
if (qr.isDark(row, column))
|
|
38
|
+
cells.push('M' + (column + 4) + ' ' + (row + 4) + 'h1v1h-1z');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + (count + 8) + ' ' + (count + 8)
|
|
42
|
+
+ '" shape-rendering="crispEdges"><path fill="white" d="M0 0h' + (count + 8) + 'v' + (count + 8)
|
|
43
|
+
+ 'H0z"/><path fill="black" d="' + cells.join('') + '"/></svg>';
|
|
44
|
+
}
|
|
45
|
+
export class EcwebInitializationService {
|
|
46
|
+
deps;
|
|
47
|
+
agentInitializer;
|
|
48
|
+
queue = Promise.resolve();
|
|
49
|
+
constructor(deps = {}) {
|
|
50
|
+
this.deps = deps;
|
|
51
|
+
}
|
|
52
|
+
setAgentInitializer(service) { this.agentInitializer = service; }
|
|
53
|
+
exclusive(action) {
|
|
54
|
+
const result = this.queue.then(action);
|
|
55
|
+
this.queue = result.catch(() => undefined);
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
root() { return this.deps.root?.() ?? resolvePaths().root; }
|
|
59
|
+
now() { return this.deps.now?.() ?? Date.now(); }
|
|
60
|
+
file() { return path.join(this.root(), 'data', 'ecweb', 'init-state.json'); }
|
|
61
|
+
save(state) {
|
|
62
|
+
state.updatedAt = this.now();
|
|
63
|
+
atomicWriteJson(this.file(), state);
|
|
64
|
+
for (const file of [this.file(), `${this.file()}_`])
|
|
65
|
+
if (fs.existsSync(file))
|
|
66
|
+
fs.chmodSync(file, 0o600);
|
|
67
|
+
}
|
|
68
|
+
read() {
|
|
69
|
+
const aid = this.deps.controlAid ? this.deps.controlAid() : loadDaemonConfig().aid;
|
|
70
|
+
if (!aid || !isValidAid(aid))
|
|
71
|
+
fail('CONTROL_AID_NOT_READY', '主机身份尚未就绪,请先运行 ec init --web', 409);
|
|
72
|
+
let state;
|
|
73
|
+
try {
|
|
74
|
+
state = atomicReadJson(this.file());
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return fail('INIT_STATE_INVALID', '初始化状态无法读取,请检查数据文件', 409);
|
|
78
|
+
}
|
|
79
|
+
if (state && (!record(state) || state.version !== 1 || !steps.has(state.step) || !isValidAid(state.controlAid) || !Number.isFinite(state.updatedAt)
|
|
80
|
+
|| (state.binding && (!isValidAid(state.controlAid) || typeof state.binding.id !== 'string'
|
|
81
|
+
|| !/^[A-Za-z0-9_-]{43}$/.test(state.binding.token) || !Number.isFinite(state.binding.expiresAt)
|
|
82
|
+
|| !['created', 'pending', 'unknown', 'bound', 'expired'].includes(state.binding.status))))) {
|
|
83
|
+
fail('INIT_STATE_INVALID', '初始化状态无效,不能继续绑定', 409);
|
|
84
|
+
}
|
|
85
|
+
if (!state || state.controlAid !== aid)
|
|
86
|
+
return { version: 1, controlAid: aid, step: 'welcome', updatedAt: this.now() };
|
|
87
|
+
if (state.binding?.status === 'created' && state.binding.expiresAt <= this.now()) {
|
|
88
|
+
state.binding.status = 'expired';
|
|
89
|
+
this.save(state);
|
|
90
|
+
}
|
|
91
|
+
return state;
|
|
92
|
+
}
|
|
93
|
+
async ownership(aid, force = true, source = 'initialization.operation') {
|
|
94
|
+
if (this.deps.refreshOwner)
|
|
95
|
+
return this.deps.refreshOwner(aid, { force });
|
|
96
|
+
const { ownerResolver, OWNERSHIP_AUTHORIZATION_MAX_AGE_MS } = await import('../ownership/owner-resolver.js');
|
|
97
|
+
return ownerResolver.refresh(aid, { force, maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, allowTransient: !force, source });
|
|
98
|
+
}
|
|
99
|
+
async bind(aid, owner) {
|
|
100
|
+
if (this.deps.bindOwner)
|
|
101
|
+
return this.deps.bindOwner(aid, owner);
|
|
102
|
+
const { ownerResolver } = await import('../ownership/owner-resolver.js');
|
|
103
|
+
return ownerResolver.bind(aid, owner);
|
|
104
|
+
}
|
|
105
|
+
async verifiedOwner(state, force = true, source = 'initialization.operation') {
|
|
106
|
+
const view = await this.ownership(state.controlAid, force, source);
|
|
107
|
+
const owner = view.consensusStatus === 'consensus' && view.ownerAid && isValidAid(view.ownerAid)
|
|
108
|
+
&& view.ownerAid !== state.controlAid ? view.ownerAid : undefined;
|
|
109
|
+
if (owner && state.ownerAid && state.ownerAid !== owner)
|
|
110
|
+
fail('OWNER_CHANGED', '主机 Owner 已变更,请重新核对初始化状态', 409);
|
|
111
|
+
if (owner && state.ownerAid !== owner) {
|
|
112
|
+
state.ownerAid = owner;
|
|
113
|
+
this.save(state);
|
|
114
|
+
}
|
|
115
|
+
if (owner && state.binding?.ownerAid === owner && state.binding.status !== 'bound') {
|
|
116
|
+
state.binding.status = 'bound';
|
|
117
|
+
state.step = 'configuration';
|
|
118
|
+
this.save(state);
|
|
119
|
+
}
|
|
120
|
+
return owner;
|
|
121
|
+
}
|
|
122
|
+
async view(state) {
|
|
123
|
+
if (state.creation && !state.agent) {
|
|
124
|
+
const { aid, name, project } = state.creation.plan;
|
|
125
|
+
state.agent = { aid, name, project };
|
|
126
|
+
this.save(state);
|
|
127
|
+
}
|
|
128
|
+
if (state.step === 'agent' && state.agent && this.agentInitializer) {
|
|
129
|
+
const result = this.agentInitializer.status(state.agent.aid);
|
|
130
|
+
if (result.complete === true && result.usable === true) {
|
|
131
|
+
state.step = 'ready';
|
|
132
|
+
this.save(state);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const bindingPending = !!state.binding?.ownerAid && ['pending', 'unknown'].includes(state.binding.status);
|
|
136
|
+
const ownerAid = await this.verifiedOwner(state, bindingPending, bindingPending ? 'initialization.binding' : 'initialization.view');
|
|
137
|
+
const binding = state.binding;
|
|
138
|
+
const scannable = binding?.status === 'created' && binding.expiresAt > this.now();
|
|
139
|
+
return {
|
|
140
|
+
status: state.step === 'ready' ? 'completed' : state.step === 'welcome' ? 'pending' : 'in_progress',
|
|
141
|
+
step: ownerAid ? state.step === 'welcome' || state.step === 'binding' ? 'configuration' : state.step : state.step === 'welcome' ? 'welcome' : 'binding',
|
|
142
|
+
controlAid: state.controlAid, ownerAid: ownerAid ?? null, updatedAt: state.updatedAt,
|
|
143
|
+
binding: binding ? {
|
|
144
|
+
id: binding.id, status: binding.status === 'bound' && !ownerAid ? 'unknown' : binding.status,
|
|
145
|
+
expiresAt: binding.expiresAt,
|
|
146
|
+
qrSvg: scannable ? qrSvg({
|
|
147
|
+
type: 'evolcore.bind', version: readInstalledEvolcoreVersion(),
|
|
148
|
+
platform: process.platform === 'win32' ? 'windows' : process.platform,
|
|
149
|
+
bindType: 'daemon', subjectAid: state.controlAid,
|
|
150
|
+
token: binding.token, expiresAt: binding.expiresAt,
|
|
151
|
+
}) : null,
|
|
152
|
+
} : null,
|
|
153
|
+
...(state.agent ? { agent: state.agent } : {}),
|
|
154
|
+
...(state.agent && this.agentInitializer ? { creation: this.agentInitializer.status(state.agent.aid) } : {}),
|
|
155
|
+
...(state.creation ? { agentConfiguration: {
|
|
156
|
+
baseagent: state.creation.plan.baseagent, provider: state.creation.plan.provider ?? null,
|
|
157
|
+
model: state.creation.plan.model ?? 'auto', effort: state.creation.plan.effort ?? 'auto',
|
|
158
|
+
} } : {}),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
generatedAgentAid(name, controlAid) {
|
|
162
|
+
const slug = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 30) || 'agent';
|
|
163
|
+
const domain = controlAid.split('.').slice(1).join('.') || resolveControlAidDomain();
|
|
164
|
+
return `${slug}-${crypto.randomBytes(4).toString('hex')}.${domain}`;
|
|
165
|
+
}
|
|
166
|
+
async submitOwner(ownerValue, sessionId, token) {
|
|
167
|
+
return this.exclusive(() => this.submitOwnerUnlocked(ownerValue, sessionId, token));
|
|
168
|
+
}
|
|
169
|
+
async handleAppBindRequest(payload, senderAid, encrypted) {
|
|
170
|
+
if (payload.type !== 'bind.request' || payload.bindType !== 'daemon')
|
|
171
|
+
return null;
|
|
172
|
+
const creationId = payload.creationId;
|
|
173
|
+
let state;
|
|
174
|
+
try {
|
|
175
|
+
state = this.read();
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
return { type: 'bind.response', ...(typeof creationId === 'string' ? { creationId } : {}), bindType: 'daemon', success: false,
|
|
179
|
+
error: { code: error.code ?? 'INIT_UNAVAILABLE', message: '主机初始化服务暂不可用' } };
|
|
180
|
+
}
|
|
181
|
+
const response = (success, status, code, message) => ({
|
|
182
|
+
type: 'bind.response',
|
|
183
|
+
...(typeof creationId === 'string' && creationId.trim() ? { creationId } : {}),
|
|
184
|
+
bindType: 'daemon',
|
|
185
|
+
success,
|
|
186
|
+
subjectAid: state.controlAid,
|
|
187
|
+
...(isValidAid(senderAid) ? { ownerAid: senderAid.toLowerCase() } : {}),
|
|
188
|
+
...(status ? { status } : {}),
|
|
189
|
+
...(code ? { error: { code, message: message ?? '绑定请求无效' } } : {}),
|
|
190
|
+
});
|
|
191
|
+
if (!encrypted)
|
|
192
|
+
return response(false, undefined, 'ENCRYPTION_REQUIRED', '绑定请求必须使用加密身份消息');
|
|
193
|
+
if (typeof creationId !== 'string' || !creationId.trim() || creationId.length > 128) {
|
|
194
|
+
return response(false, undefined, 'INVALID_CREATION_ID', '缺少有效的 creationId');
|
|
195
|
+
}
|
|
196
|
+
if (!isValidAid(senderAid))
|
|
197
|
+
return response(false, undefined, 'INVALID_SENDER', '无法确认请求发送方身份');
|
|
198
|
+
if (!state.binding || typeof payload.token !== 'string' || payload.token.length !== state.binding.token.length
|
|
199
|
+
|| !crypto.timingSafeEqual(Buffer.from(payload.token), Buffer.from(state.binding.token))) {
|
|
200
|
+
return response(false, undefined, 'BIND_SESSION_INVALID', '绑定会话无效,请刷新二维码');
|
|
201
|
+
}
|
|
202
|
+
if (payload.timestamp !== undefined && (typeof payload.timestamp !== 'number' || !Number.isFinite(payload.timestamp)
|
|
203
|
+
|| Math.abs(this.now() - payload.timestamp) > TTL)) {
|
|
204
|
+
return response(false, undefined, 'REQUEST_EXPIRED', '绑定请求已过期,请重新扫描二维码');
|
|
205
|
+
}
|
|
206
|
+
const fingerprint = crypto.createHash('sha256').update(JSON.stringify({
|
|
207
|
+
bindType: payload.bindType, token: payload.token, senderAid: senderAid.toLowerCase(),
|
|
208
|
+
clientName: payload.clientName, deviceName: payload.deviceName, platform: payload.platform,
|
|
209
|
+
appVersion: payload.appVersion, timestamp: payload.timestamp,
|
|
210
|
+
})).digest('hex');
|
|
211
|
+
try {
|
|
212
|
+
const activeBinding = state.binding;
|
|
213
|
+
const result = await this.exclusive(() => this.submitOwnerUnlocked(senderAid, activeBinding.id, payload.token, creationId, fingerprint));
|
|
214
|
+
const binding = result.binding;
|
|
215
|
+
const ownerAid = result.ownerAid;
|
|
216
|
+
return response(true, ownerAid === senderAid.toLowerCase() ? 'bound' : binding?.status ?? 'pending');
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
const details = error;
|
|
220
|
+
const messages = {
|
|
221
|
+
BIND_SESSION_INVALID: '绑定会话无效,请刷新二维码',
|
|
222
|
+
BIND_SESSION_EXPIRED: '二维码已过期,请刷新',
|
|
223
|
+
BIND_CONFLICT: '绑定请求冲突,请刷新页面核对状态',
|
|
224
|
+
OWNER_ALREADY_BOUND: '主机已绑定其他 Owner',
|
|
225
|
+
OWNERSHIP_UNAVAILABLE: '暂时无法确认主机归属,请稍后重试',
|
|
226
|
+
};
|
|
227
|
+
return response(false, undefined, details.code ?? 'BIND_FAILED', messages[details.code ?? ''] ?? '绑定请求未能受理,请查询状态后重试');
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
async submitOwnerUnlocked(ownerValue, sessionId, token, creationId, requestFingerprint) {
|
|
231
|
+
const state = this.read();
|
|
232
|
+
const binding = state.binding;
|
|
233
|
+
if (!binding || (sessionId !== undefined && binding.id !== sessionId) || typeof token !== 'string' || token.length !== binding.token.length
|
|
234
|
+
|| !crypto.timingSafeEqual(Buffer.from(token), Buffer.from(binding.token)))
|
|
235
|
+
fail('BIND_SESSION_INVALID', '绑定会话无效', 403);
|
|
236
|
+
if (typeof ownerValue !== 'string' || !isValidAid(ownerValue) || ownerValue.toLowerCase() === state.controlAid.toLowerCase()) {
|
|
237
|
+
fail('INVALID_OWNER', '请输入有效且不同于主机的 Owner AID');
|
|
238
|
+
}
|
|
239
|
+
const owner = ownerValue.toLowerCase();
|
|
240
|
+
if (binding.ownerAid) {
|
|
241
|
+
if (binding.ownerAid !== owner)
|
|
242
|
+
fail('BIND_CONFLICT', '本次会话已有其他绑定请求', 409);
|
|
243
|
+
if (creationId && (binding.creationId !== creationId || binding.requestFingerprint !== requestFingerprint)) {
|
|
244
|
+
fail('BIND_CONFLICT', 'creationId 已用于不同的绑定请求', 409);
|
|
245
|
+
}
|
|
246
|
+
return this.view(state);
|
|
247
|
+
}
|
|
248
|
+
if (binding.status !== 'created' || binding.expiresAt <= this.now())
|
|
249
|
+
fail('BIND_SESSION_EXPIRED', '二维码已过期,请刷新', 409);
|
|
250
|
+
const baseline = await this.ownership(state.controlAid);
|
|
251
|
+
if (baseline.consensusStatus === 'consensus' && baseline.ownerAid?.toLowerCase() !== owner)
|
|
252
|
+
fail('OWNER_ALREADY_BOUND', '主机已绑定其他 Owner', 409);
|
|
253
|
+
if (!['consensus', 'unbound', 'released', 'single_sided'].includes(baseline.consensusStatus)) {
|
|
254
|
+
fail('OWNERSHIP_UNAVAILABLE', '暂时无法确认主机归属,请稍后重试', 503);
|
|
255
|
+
}
|
|
256
|
+
const latest = this.read();
|
|
257
|
+
if (latest.binding?.id !== binding.id || latest.binding.ownerAid || latest.binding.expiresAt <= this.now()) {
|
|
258
|
+
fail('BIND_CONFLICT', '绑定会话已变更,请刷新页面', 409);
|
|
259
|
+
}
|
|
260
|
+
binding.ownerAid = owner;
|
|
261
|
+
binding.status = 'pending';
|
|
262
|
+
if (creationId) {
|
|
263
|
+
binding.creationId = creationId;
|
|
264
|
+
binding.requestFingerprint = requestFingerprint;
|
|
265
|
+
}
|
|
266
|
+
this.save(state);
|
|
267
|
+
try {
|
|
268
|
+
const result = await this.bind(state.controlAid, owner);
|
|
269
|
+
binding.operationId = result.task?.operation_id;
|
|
270
|
+
this.save(state);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
binding.status = 'unknown';
|
|
274
|
+
this.save(state);
|
|
275
|
+
}
|
|
276
|
+
return this.view(state);
|
|
277
|
+
}
|
|
278
|
+
async handle(input) {
|
|
279
|
+
return this.exclusive(() => this.handleUnlocked(input));
|
|
280
|
+
}
|
|
281
|
+
async handleUnlocked(input) {
|
|
282
|
+
try {
|
|
283
|
+
if (!record(input) || typeof input.method !== 'string' || typeof input.pathname !== 'string') {
|
|
284
|
+
fail('INVALID_REQUEST', '初始化请求格式无效');
|
|
285
|
+
}
|
|
286
|
+
const pathname = input.pathname.replace(/\/+$/u, '');
|
|
287
|
+
const body = record(input.body) ? input.body : {};
|
|
288
|
+
const state = this.read();
|
|
289
|
+
if (input.method === 'GET' && pathname === '/api/init/state')
|
|
290
|
+
return { status: 200, body: { success: true, data: await this.view(state) } };
|
|
291
|
+
if (input.method === 'POST' && pathname === '/api/init/start') {
|
|
292
|
+
if (state.step === 'welcome') {
|
|
293
|
+
state.step = 'binding';
|
|
294
|
+
this.save(state);
|
|
295
|
+
}
|
|
296
|
+
return { status: 200, body: { success: true, data: await this.view(state) } };
|
|
297
|
+
}
|
|
298
|
+
const bindingMatch = /^\/api\/init\/binding-sessions\/([^/]+)$/u.exec(pathname);
|
|
299
|
+
if (input.method === 'GET' && bindingMatch) {
|
|
300
|
+
if (!state.binding || state.binding.id !== decodeURIComponent(bindingMatch[1])) {
|
|
301
|
+
fail('BIND_SESSION_INVALID', '绑定会话不存在', 404);
|
|
302
|
+
}
|
|
303
|
+
return { status: 200, body: { success: true, data: await this.view(state) } };
|
|
304
|
+
}
|
|
305
|
+
if (input.method === 'POST' && (pathname === '/api/init/binding-sessions' || pathname === '/api/init/binding-sessions/refresh')) {
|
|
306
|
+
if (await this.verifiedOwner(state))
|
|
307
|
+
return { status: 200, body: { success: true, data: await this.view(state) } };
|
|
308
|
+
if (state.binding?.ownerAid)
|
|
309
|
+
fail('BIND_PENDING', '绑定已提交,请先在 EVOL APP 确认并查询结果,不能重复创建', 409);
|
|
310
|
+
if (pathname.endsWith('/refresh') || !state.binding || state.binding.expiresAt <= this.now()) {
|
|
311
|
+
state.binding = { id: crypto.randomUUID(), token: crypto.randomBytes(32).toString('base64url'), status: 'created', expiresAt: this.now() + TTL };
|
|
312
|
+
state.step = 'binding';
|
|
313
|
+
this.save(state);
|
|
314
|
+
}
|
|
315
|
+
return { status: 201, body: { success: true, data: await this.view(state) } };
|
|
316
|
+
}
|
|
317
|
+
if (input.method === 'POST' && pathname === '/api/init/binding-sessions/manual') {
|
|
318
|
+
if (!state.binding)
|
|
319
|
+
fail('BIND_SESSION_INVALID', '请先开始绑定', 409);
|
|
320
|
+
return { status: 202, body: { success: true, data: await this.submitOwnerUnlocked(body.ownerAid, state.binding.id, state.binding.token) } };
|
|
321
|
+
}
|
|
322
|
+
if (input.method === 'GET' && pathname === '/api/init/configuration') {
|
|
323
|
+
const owner = await this.verifiedOwner(state);
|
|
324
|
+
if (!owner)
|
|
325
|
+
fail('OWNERSHIP_REQUIRED', '请先完成主机 Owner 绑定', 409);
|
|
326
|
+
const providers = readProvidersSnapshot();
|
|
327
|
+
return { status: 200, body: { success: true, data: {
|
|
328
|
+
baseagents: await getBaseagentSnapshot(), providers,
|
|
329
|
+
sources: listBaseagentImportSources(),
|
|
330
|
+
providersRevision: providers.revision,
|
|
331
|
+
defaultProjectPath: defaultProjectsRoot(this.root()),
|
|
332
|
+
defaultBaseagent: state.baseagent ?? null,
|
|
333
|
+
} } };
|
|
334
|
+
}
|
|
335
|
+
if (input.method === 'POST' && pathname === '/api/init/configuration') {
|
|
336
|
+
const owner = await this.verifiedOwner(state);
|
|
337
|
+
if (!owner)
|
|
338
|
+
fail('OWNERSHIP_REQUIRED', '请先完成主机 Owner 绑定', 409);
|
|
339
|
+
if (state.creation)
|
|
340
|
+
fail('CREATE_CONFLICT', '创建任务已提交,请先查看创建进度', 409);
|
|
341
|
+
const inventory = await getBaseagentSnapshot();
|
|
342
|
+
if (typeof body.baseagent !== 'string' || !inventory.baseagents.some(item => item.id === body.baseagent && item.detected)) {
|
|
343
|
+
fail('INVALID_BASEAGENT', '请选择可用的默认 Base Agent');
|
|
344
|
+
}
|
|
345
|
+
mutateConfig(ConfigTarget.Defaults, undefined, config => { config.active_baseagent = body.baseagent; });
|
|
346
|
+
state.baseagent = body.baseagent;
|
|
347
|
+
state.ownerAid = owner;
|
|
348
|
+
state.step = 'agent';
|
|
349
|
+
this.save(state);
|
|
350
|
+
return { status: 200, body: { success: true, data: await this.view(state) } };
|
|
351
|
+
}
|
|
352
|
+
if (input.method === 'POST' && pathname === '/api/init/providers/import') {
|
|
353
|
+
const owner = await this.verifiedOwner(state);
|
|
354
|
+
if (!owner)
|
|
355
|
+
fail('OWNERSHIP_REQUIRED', '请先完成主机 Owner 绑定', 409);
|
|
356
|
+
if (state.creation)
|
|
357
|
+
fail('CREATE_CONFLICT', '创建任务已提交,不能再导入初始化配置', 409);
|
|
358
|
+
if (typeof body.revision !== 'string' || body.source !== 'baseagent')
|
|
359
|
+
fail('INVALID_REQUEST', '当前仅支持导入本机 Base Agent 配置');
|
|
360
|
+
let provider;
|
|
361
|
+
if (typeof body.id === 'string') {
|
|
362
|
+
try {
|
|
363
|
+
provider = providerFromBaseagent(body.id);
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
return fail('INVALID_SOURCE', '本机 Provider 配置不可导入');
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
else
|
|
370
|
+
return fail('INVALID_SOURCE', 'Provider 来源无效');
|
|
371
|
+
try {
|
|
372
|
+
const data = await importOrMergeBaseagentProvider({ revision: body.revision, value: provider });
|
|
373
|
+
return { status: 200, body: { success: true, data } };
|
|
374
|
+
}
|
|
375
|
+
catch (error) {
|
|
376
|
+
if (error.statusCode === 409)
|
|
377
|
+
fail('REVISION_CONFLICT', '配置已变更,请刷新预览后重新确认', 409);
|
|
378
|
+
return fail('PROVIDER_IMPORT_FAILED', 'Provider 导入失败,未返回凭据详情');
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
if (input.method === 'POST' && pathname === '/api/init/agent') {
|
|
382
|
+
const owner = await this.verifiedOwner(state);
|
|
383
|
+
if (!owner)
|
|
384
|
+
fail('OWNERSHIP_REQUIRED', '请先完成主机 Owner 绑定', 409);
|
|
385
|
+
if (!this.agentInitializer)
|
|
386
|
+
fail('INIT_UNAVAILABLE', 'Agent 初始化服务尚未就绪', 503);
|
|
387
|
+
if (typeof body.operationId !== 'string' || !/^[A-Za-z0-9_-]{8,80}$/u.test(body.operationId))
|
|
388
|
+
fail('INVALID_ARGS', '缺少创建操作 ID');
|
|
389
|
+
const fingerprint = crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
|
|
390
|
+
if (state.creation) {
|
|
391
|
+
if (state.creation.operationId !== body.operationId || state.creation.fingerprint !== fingerprint)
|
|
392
|
+
fail('CREATE_CONFLICT', '已有首个 Agent 创建请求,请查询进度', 409);
|
|
393
|
+
this.agentInitializer.start(state.creation.plan, 'local-control');
|
|
394
|
+
return { status: 200, body: { success: true, data: await this.view(state) } };
|
|
395
|
+
}
|
|
396
|
+
if (state.step !== 'configuration' && state.step !== 'agent')
|
|
397
|
+
fail('INVALID_STEP', '当前不能创建 Agent', 409);
|
|
398
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
399
|
+
if (typeof body.project !== 'string' || !path.isAbsolute(body.project))
|
|
400
|
+
fail('INVALID_ARGS', '项目目录必须使用绝对路径');
|
|
401
|
+
const project = path.resolve(body.project);
|
|
402
|
+
if (isHClassPath(project) || isLClassPath(project))
|
|
403
|
+
fail('INVALID_ARGS', '不能使用受保护目录作为项目目录');
|
|
404
|
+
const baseagent = typeof body.baseagent === 'string' ? body.baseagent.trim() : '';
|
|
405
|
+
const inventory = await getBaseagentSnapshot();
|
|
406
|
+
if (!inventory.baseagents.some(item => item.id === baseagent && item.detected)) {
|
|
407
|
+
fail('INVALID_BASEAGENT', '请选择可用的 Base Agent');
|
|
408
|
+
}
|
|
409
|
+
const aid = typeof body.aid === 'string' && body.aid.trim() ? body.aid.trim().toLowerCase() : this.generatedAgentAid(name, state.controlAid);
|
|
410
|
+
if (!name || !project || !baseagent)
|
|
411
|
+
fail('INVALID_ARGS', '昵称、项目目录和 Base Agent 不能为空');
|
|
412
|
+
const plan = {
|
|
413
|
+
aid, project, baseagent,
|
|
414
|
+
...(typeof body.model === 'string' && body.model.trim() && body.model.trim() !== 'auto' ? { model: body.model.trim() } : {}),
|
|
415
|
+
...(typeof body.effort === 'string' && body.effort.trim() && body.effort.trim() !== 'auto' ? { effort: body.effort.trim() } : {}),
|
|
416
|
+
ownerAid: typeof body.ownerAid === 'string' && body.ownerAid.trim() ? body.ownerAid.trim().toLowerCase() : owner,
|
|
417
|
+
name, description: `${name},由 ECweb 创建的 Agent`, type: 'agent', tags: ['assistant'],
|
|
418
|
+
...(typeof body.provider === 'string' && body.provider ? { provider: body.provider } : {}),
|
|
419
|
+
...(state.avatar && body.avatarId === state.avatar.id ? { avatarFile: state.avatar.file } : {}),
|
|
420
|
+
};
|
|
421
|
+
if (body.avatarId && (!state.avatar || body.avatarId !== state.avatar.id))
|
|
422
|
+
fail('INVALID_AVATAR', '请重新上传头像');
|
|
423
|
+
const modelError = await validateInitializationModelArgs({ plan });
|
|
424
|
+
if (modelError)
|
|
425
|
+
fail(modelError.code, modelError.error);
|
|
426
|
+
const { validateInitializationPlan } = await import('../../cli/agent-create.js');
|
|
427
|
+
try {
|
|
428
|
+
validateInitializationPlan(plan);
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
fail('INVALID_ARGS', 'Agent 参数无效,请检查 AID、项目目录及 Provider 配置');
|
|
432
|
+
}
|
|
433
|
+
state.creation = { operationId: body.operationId, fingerprint, plan };
|
|
434
|
+
state.step = 'agent';
|
|
435
|
+
this.save(state);
|
|
436
|
+
const result = this.agentInitializer.start(plan, 'local-control');
|
|
437
|
+
state.agent = { aid, name, project, ...(typeof result.operationId === 'string' ? { operationId: result.operationId } : {}) };
|
|
438
|
+
state.step = 'agent';
|
|
439
|
+
this.save(state);
|
|
440
|
+
return { status: 202, body: { success: true, data: await this.view(state) } };
|
|
441
|
+
}
|
|
442
|
+
if (input.method === 'POST' && pathname === '/api/init/agent/resume') {
|
|
443
|
+
if (!await this.verifiedOwner(state))
|
|
444
|
+
fail('OWNERSHIP_REQUIRED', '请先完成主机 Owner 绑定', 409);
|
|
445
|
+
if (!state.agent || !this.agentInitializer)
|
|
446
|
+
fail('NOT_FOUND', '没有可恢复的创建任务', 404);
|
|
447
|
+
const current = this.agentInitializer.status(state.agent.aid);
|
|
448
|
+
if (current.code === 'NOT_FOUND' && state.creation)
|
|
449
|
+
this.agentInitializer.start(state.creation.plan, 'local-control');
|
|
450
|
+
else
|
|
451
|
+
this.agentInitializer.resume(state.agent.aid, 'local-control');
|
|
452
|
+
return { status: 202, body: { success: true, data: await this.view(state) } };
|
|
453
|
+
}
|
|
454
|
+
if (input.method === 'POST' && pathname === '/api/init/avatar') {
|
|
455
|
+
if (!await this.verifiedOwner(state))
|
|
456
|
+
fail('OWNERSHIP_REQUIRED', '请先完成主机 Owner 绑定', 409);
|
|
457
|
+
if (state.creation)
|
|
458
|
+
fail('CREATE_CONFLICT', '创建任务已提交,不能再修改头像', 409);
|
|
459
|
+
if (typeof body.data !== 'string' || !/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u.test(body.data))
|
|
460
|
+
fail('INVALID_AVATAR', '请选择 PNG、JPEG 或 WebP 图片');
|
|
461
|
+
const bytes = Buffer.from(body.data.slice(body.data.indexOf(',') + 1), 'base64');
|
|
462
|
+
if (bytes.length > 700 * 1024)
|
|
463
|
+
fail('INVALID_AVATAR', '头像不能超过 700 KiB');
|
|
464
|
+
let avatar;
|
|
465
|
+
try {
|
|
466
|
+
avatar = (await normalizeAvatarImage(bytes)).buffer;
|
|
467
|
+
}
|
|
468
|
+
catch {
|
|
469
|
+
fail('INVALID_AVATAR', '头像图片无效,请换一张图片重试');
|
|
470
|
+
}
|
|
471
|
+
const id = crypto.randomUUID();
|
|
472
|
+
const avatarRoot = path.join(this.root(), 'data', 'ecweb', 'avatars');
|
|
473
|
+
fs.mkdirSync(avatarRoot, { recursive: true });
|
|
474
|
+
const file = path.join(avatarRoot, `${id}.jpg`);
|
|
475
|
+
fs.writeFileSync(file, avatar, { flag: 'wx', mode: 0o600 });
|
|
476
|
+
state.avatar = { id, file };
|
|
477
|
+
this.save(state);
|
|
478
|
+
return { status: 201, body: { success: true, data: { id } } };
|
|
479
|
+
}
|
|
480
|
+
return { status: 404, body: { success: false, code: 'NOT_FOUND', error: '初始化接口不存在' } };
|
|
481
|
+
}
|
|
482
|
+
catch (error) {
|
|
483
|
+
const details = error;
|
|
484
|
+
return { status: details.statusCode ?? 503, body: { success: false, code: details.code ?? 'INIT_UNAVAILABLE', error: details.code && error instanceof Error ? error.message : '初始化服务暂时不可用' } };
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
export const ecwebInitializationService = new EcwebInitializationService();
|
|
489
|
+
export async function handleInitService(input) {
|
|
490
|
+
return ecwebInitializationService.handle(input);
|
|
491
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ecwebInitializationService } from './initialization/service.js';
|
|
1
2
|
import { TriggerDefinitionManager } from '../trigger/manager.js';
|
|
2
3
|
import { ensureSessionRuntimeDir } from '../cli/task-context.js';
|
|
3
4
|
import { logger } from '../utils/logger.js';
|
|
@@ -10,6 +11,7 @@ import { resolveStorageCommandArgv } from '../aun/storage/index.js';
|
|
|
10
11
|
import { agentDir } from '../paths.js';
|
|
11
12
|
import { parsePeerKey } from './relation/peer-identity.js';
|
|
12
13
|
import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
|
|
14
|
+
import { createEcwebMessageContextProvider } from '../ecweb/message-context-service.js';
|
|
13
15
|
import { buildDebugTaskContext } from './auth/debug-context.js';
|
|
14
16
|
import { loadAgent } from '../config-store.js';
|
|
15
17
|
import { executeLocalInitializationCommand, hasSuppliedInitialization } from '../cli/agent-create.js';
|
|
@@ -20,11 +22,12 @@ import { registerAgentOperationExecutor } from './agent-ipc-registration.js';
|
|
|
20
22
|
import { registerHandoffIpc } from './handoff/ipc-registration.js';
|
|
21
23
|
import { registerAunIpcSender } from './message/aun-ipc-sender.js';
|
|
22
24
|
import { registerConsolidationCheckExecutor, registerConsolidationLaunchExecutor, } from './memory/consolidation.js';
|
|
23
|
-
import { createTriggerBaseagentResolver, registerTriggerIpcExecutor } from '../trigger/ipc-service.js';
|
|
25
|
+
import { createManagedCrossThreadReviewTrigger, createTriggerBaseagentResolver, registerTriggerIpcExecutor, } from '../trigger/ipc-service.js';
|
|
24
26
|
import { createThreadOperationExecutor } from './thread/ipc-operation.js';
|
|
25
27
|
import { isLinkedInstall } from '../utils/npm-ops.js';
|
|
26
28
|
import { buildSystemSessionContext, getSystemSessionModule } from './system-session/registry.js';
|
|
27
|
-
export function registerDaemonIpc({ ipcServer, agentRegistry, agentDelegationRegistry, sessionManager, statsCollector, aidStatsCollector, responseEngine, messageQueue, agentMap, commandHandler, channelInstances, eventBus, handoffRuntime, reloadCoordinator, agentApplicationService, agentInitializationService, enqueueConsolidation,
|
|
29
|
+
export function registerDaemonIpc({ ipcServer, agentRegistry, agentDelegationRegistry, sessionManager, statsCollector, aidStatsCollector, responseEngine, messageQueue, agentMap, commandHandler, channelInstances, eventBus, handoffRuntime, reloadCoordinator, agentApplicationService, agentInitializationService, enqueueConsolidation, getRelationRoute, isConsolidationPending, completeAgentBootstrap, contactBinds, bindService, diagService, getProcessOwners, getControlAidState, daemonAid, triggerControlToken, triggerSchedulers, daemonTriggerOwner, primaryAgent, triggerAuthorization, }) {
|
|
30
|
+
ecwebInitializationService.setAgentInitializer(agentInitializationService);
|
|
28
31
|
const authorizeManagedAgentOperation = createDelegationAuthorizer({
|
|
29
32
|
agentDelegationRegistry,
|
|
30
33
|
sessionManager,
|
|
@@ -58,6 +61,7 @@ export function registerDaemonIpc({ ipcServer, agentRegistry, agentDelegationReg
|
|
|
58
61
|
agentMap,
|
|
59
62
|
isLinkedInstall: isLinkedInstall(),
|
|
60
63
|
});
|
|
64
|
+
ipcServer.setEcwebMessageContextProvider(createEcwebMessageContextProvider(sessionManager));
|
|
61
65
|
if (process.env.EVOLCORE_DEBUG_MODE === '1') {
|
|
62
66
|
ipcServer.setDebugIssueTokenExecutor(async ({ sessionId }) => {
|
|
63
67
|
try {
|
|
@@ -226,9 +230,32 @@ export function registerDaemonIpc({ ipcServer, agentRegistry, agentDelegationReg
|
|
|
226
230
|
handoffRuntime,
|
|
227
231
|
getProcessOwners,
|
|
228
232
|
});
|
|
229
|
-
|
|
233
|
+
const triggerIpcDependencies = {
|
|
234
|
+
daemonTriggerOwnerAid: daemonTriggerOwner.aid,
|
|
235
|
+
daemonTriggerBaseagent: daemonTriggerOwner.baseagent,
|
|
236
|
+
getScheduler: agentAid => triggerSchedulers.get(agentAid),
|
|
237
|
+
hasAgent: agentAid => !!agentRegistry.get(agentAid),
|
|
238
|
+
getAgentBaseagent: agentAid => agentRegistry.get(agentAid)?.baseagent,
|
|
239
|
+
getAvailableBaseagents: createTriggerBaseagentResolver({
|
|
240
|
+
daemonTriggerOwnerAid: daemonTriggerOwner.aid,
|
|
241
|
+
getAgentName: agentAid => agentRegistry.get(agentAid)?.name,
|
|
242
|
+
getDaemonAgentName: () => primaryAgent?.name,
|
|
243
|
+
agentMap,
|
|
244
|
+
}),
|
|
245
|
+
getSessionById: sessionId => sessionManager.getSessionById(sessionId),
|
|
246
|
+
...triggerAuthorization,
|
|
247
|
+
};
|
|
248
|
+
registerAunIpcSender({
|
|
249
|
+
ipcServer,
|
|
250
|
+
channelInstances,
|
|
251
|
+
agentDelegationRegistry,
|
|
252
|
+
responseEngine,
|
|
253
|
+
handoffRuntime,
|
|
254
|
+
sessionManager,
|
|
255
|
+
createCrossThreadReviewTrigger: input => createManagedCrossThreadReviewTrigger(input, triggerIpcDependencies),
|
|
256
|
+
});
|
|
230
257
|
ipcServer.setAgentReloadExecutor((aid, options) => reloadCoordinator.reload(aid, options));
|
|
231
|
-
registerConsolidationCheckExecutor({ ipcServer, agentRegistry, enqueueConsolidation,
|
|
258
|
+
registerConsolidationCheckExecutor({ ipcServer, agentRegistry, enqueueConsolidation, getRelationRoute, isConsolidationPending });
|
|
232
259
|
ipcServer.setInitializationExecutor(async (command) => executeLocalInitializationCommand(agentInitializationService, command));
|
|
233
260
|
ipcServer.setAgentApplicationService(agentApplicationService);
|
|
234
261
|
registerQueueIpcProviders({ ipcServer, statsCollector, agentRegistry, messageQueue });
|
|
@@ -252,21 +279,7 @@ export function registerDaemonIpc({ ipcServer, agentRegistry, agentDelegationReg
|
|
|
252
279
|
recoverTask: request => responseEngine.recoverTask(request),
|
|
253
280
|
});
|
|
254
281
|
registerConsolidationLaunchExecutor({ ipcServer, sessionManager, enqueueConsolidation });
|
|
255
|
-
registerTriggerIpcExecutor(ipcServer,
|
|
256
|
-
daemonTriggerOwnerAid: daemonTriggerOwner.aid,
|
|
257
|
-
daemonTriggerBaseagent: daemonTriggerOwner.baseagent,
|
|
258
|
-
getScheduler: agentAid => triggerSchedulers.get(agentAid),
|
|
259
|
-
hasAgent: agentAid => !!agentRegistry.get(agentAid),
|
|
260
|
-
getAgentBaseagent: agentAid => agentRegistry.get(agentAid)?.baseagent,
|
|
261
|
-
getAvailableBaseagents: createTriggerBaseagentResolver({
|
|
262
|
-
daemonTriggerOwnerAid: daemonTriggerOwner.aid,
|
|
263
|
-
getAgentName: agentAid => agentRegistry.get(agentAid)?.name,
|
|
264
|
-
getDaemonAgentName: () => primaryAgent?.name,
|
|
265
|
-
agentMap,
|
|
266
|
-
}),
|
|
267
|
-
getSessionById: sessionId => sessionManager.getSessionById(sessionId),
|
|
268
|
-
...triggerAuthorization,
|
|
269
|
-
});
|
|
282
|
+
registerTriggerIpcExecutor(ipcServer, triggerIpcDependencies);
|
|
270
283
|
}
|
|
271
284
|
export function createIpcStatusProvider(dependencies) {
|
|
272
285
|
return () => {
|
|
@@ -323,6 +336,7 @@ export function createIpcStatusProvider(dependencies) {
|
|
|
323
336
|
queue: { pending: dependencies.messageQueue.getGlobalQueueLength(), processing: dependencies.messageQueue.getGlobalProcessingCount() },
|
|
324
337
|
...(dependencies.getTriggerSummary ? { triggers: dependencies.getTriggerSummary() } : {}),
|
|
325
338
|
...(dependencies.getStatusSnapshot ? dependencies.getStatusSnapshot() : {}),
|
|
339
|
+
...(dependencies.getServiceProxySnapshot ? { serviceProxy: dependencies.getServiceProxySnapshot() } : {}),
|
|
326
340
|
stats: {
|
|
327
341
|
received: snapshot.lastHour.received,
|
|
328
342
|
sent: snapshot.lastHour.sent,
|
|
@@ -555,9 +569,10 @@ export function registerCommandIpcProviders({ ipcServer, agentRegistry, triggerC
|
|
|
555
569
|
ipcServer.setWecomContactBindExecutor(contactBinds.wecom);
|
|
556
570
|
ipcServer.setWechatContactBindExecutor(contactBinds.wechat);
|
|
557
571
|
ipcServer.setMenuExecutor((payload, auth) => cmdHandler.execMenuForEcweb(payload, auth));
|
|
558
|
-
ipcServer.setConfigOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleConfigOperation(argv, sessionId, delegationToken, delegationCommandHash));
|
|
572
|
+
ipcServer.setConfigOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, requestId) => cmdHandler.handleConfigOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId));
|
|
559
573
|
ipcServer.setContactOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleContactOperation(argv, sessionId, delegationToken, delegationCommandHash));
|
|
560
|
-
ipcServer.
|
|
574
|
+
ipcServer.setRoleOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleRoleOperation(argv, sessionId, delegationToken, delegationCommandHash));
|
|
575
|
+
ipcServer.setAidOperationExecutor((argv, sessionId, delegationToken, delegationCommandHash, requestId) => cmdHandler.handleAidOperation(argv, sessionId, delegationToken, delegationCommandHash, requestId));
|
|
561
576
|
ipcServer.setAidOwnershipExecutor((argv, sessionId, delegationToken, delegationCommandHash) => cmdHandler.handleOwnershipOperation(argv, sessionId, delegationToken, delegationCommandHash));
|
|
562
577
|
ipcServer.setDiagExecutor(command => executeDiag(command));
|
|
563
578
|
ipcServer.setMenuClientExecutor(async (command) => {
|
|
@@ -686,7 +701,7 @@ export function registerOperationIpcProviders({ ipcServer, sessionManager, messa
|
|
|
686
701
|
parent = path.dirname(parent);
|
|
687
702
|
const realParent = fs.realpathSync(parent);
|
|
688
703
|
if (!roots.some(root => isSameOrDescendant(destination, root) && isSameOrDescendant(realParent, root))
|
|
689
|
-
|| isHClassPath(destination) || isLClassPath(destination)
|
|
704
|
+
|| (!authorization.fullAccess && (isHClassPath(destination) || isLClassPath(destination)))
|
|
690
705
|
|| (fs.existsSync(destination) && (!fs.lstatSync(destination).isFile() || fs.lstatSync(destination).isSymbolicLink()))) {
|
|
691
706
|
return { ok: false, code: 'INVALID_LOCAL_PATH', error: 'Download destination must be an unprotected project/TMPDIR file' };
|
|
692
707
|
}
|
|
@@ -700,7 +715,7 @@ export function registerOperationIpcProviders({ ipcServer, sessionManager, messa
|
|
|
700
715
|
parent = path.dirname(parent);
|
|
701
716
|
const realParent = fs.realpathSync(parent);
|
|
702
717
|
if (!roots.some(root => isSameOrDescendant(destination, root) && isSameOrDescendant(realParent, root))
|
|
703
|
-
|| isHClassPath(destination) || isLClassPath(destination)
|
|
718
|
+
|| (!authorization.fullAccess && (isHClassPath(destination) || isLClassPath(destination)))
|
|
704
719
|
|| (fs.existsSync(destination) && (!fs.lstatSync(destination).isFile() || fs.lstatSync(destination).isSymbolicLink()))) {
|
|
705
720
|
return { ok: false, code: 'INVALID_LOCAL_PATH', error: 'Download destination must be an unprotected project/TMPDIR file' };
|
|
706
721
|
}
|
|
@@ -739,7 +754,8 @@ export function registerOperationIpcProviders({ ipcServer, sessionManager, messa
|
|
|
739
754
|
const stat = fs.lstatSync(localFile);
|
|
740
755
|
const inProject = isSameOrDescendant(localFile, projectPath);
|
|
741
756
|
const inRuntime = authorization.sessionRuntimeDir && isSameOrDescendant(localFile, fs.realpathSync(authorization.sessionRuntimeDir));
|
|
742
|
-
if ((!inProject && !inRuntime)
|
|
757
|
+
if ((!inProject && !inRuntime)
|
|
758
|
+
|| (!authorization.fullAccess && (isHClassPath(localFile) || isLClassPath(localFile)))) {
|
|
743
759
|
return { ok: false, code: 'INVALID_LOCAL_PATH', error: 'Upload source must be an unprotected file inside the current session project' };
|
|
744
760
|
}
|
|
745
761
|
if (!stat.isFile() || stat.isSymbolicLink()) {
|