evolcore 0.0.40 → 0.0.41-test.1

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.
Files changed (226) hide show
  1. package/CHANGELOG.md +94 -1
  2. package/bin/codex-managed-hook.mjs +11 -0
  3. package/bin/ec-safe-output.js +11 -1
  4. package/dist/agents/baseagent-availability.js +1 -1
  5. package/dist/agents/baseagent.js +20 -43
  6. package/dist/agents/claude-runner.js +197 -197
  7. package/dist/agents/codex-runner.js +535 -259
  8. package/dist/agents/ecagent-runner.js +31 -12
  9. package/dist/agents/gemini-runner.js +27 -7
  10. package/dist/agents/runner-types.js +11 -3
  11. package/dist/aun/ability-device-routing.js +26 -0
  12. package/dist/aun/aid/client.js +1 -1
  13. package/dist/aun/group/fs-download.js +39 -0
  14. package/dist/aun/group/identity.js +36 -13
  15. package/dist/aun/group/operations.js +5 -0
  16. package/dist/aun/msg/managed-operation.js +72 -11
  17. package/dist/aun/msg/p2p.js +32 -7
  18. package/dist/aun/service-proxy.js +36 -12
  19. package/dist/aun/storage/download.js +30 -0
  20. package/dist/aun/storage/index.js +14 -6
  21. package/dist/channels/aun.js +367 -24
  22. package/dist/channels/daemon.js +39 -5
  23. package/dist/cli/agent-command.js +2 -0
  24. package/dist/cli/agent-create.js +98 -19
  25. package/dist/cli/agent.js +10 -3
  26. package/dist/cli/aun-commands.js +85 -41
  27. package/dist/cli/daemon-commands.js +678 -688
  28. package/dist/cli/fs-command.js +64 -2
  29. package/dist/cli/index.js +48 -4
  30. package/dist/cli/managed-command-guard.js +4 -0
  31. package/dist/cli/model.js +40 -40
  32. package/dist/cli/proxy-command.js +92 -0
  33. package/dist/cli/restart-monitor.js +17 -0
  34. package/dist/cli/role.js +85 -0
  35. package/dist/cli/session-command.js +128 -13
  36. package/dist/cli/stats.js +60 -4
  37. package/dist/cli/trigger-command.js +2 -2
  38. package/dist/config/access-policy.js +8 -1
  39. package/dist/config/boot-log.js +38 -1
  40. package/dist/config/config-field-policy.js +5 -32
  41. package/dist/config/config-manager.js +46 -39
  42. package/dist/config/config-operation-service.js +8 -11
  43. package/dist/config/contact-book-store.js +47 -21
  44. package/dist/config/contact-book.js +18 -12
  45. package/dist/config/contact-operation-service.js +3 -4
  46. package/dist/config/contact-request-service.js +11 -0
  47. package/dist/config/daemon-services.js +11 -0
  48. package/dist/config/gateway-config.js +89 -595
  49. package/dist/config/peer-role-resolver.js +15 -11
  50. package/dist/config/providers-config.js +12 -7
  51. package/dist/config/providers-import.js +3 -21
  52. package/dist/config/resolved-config-op.js +3 -0
  53. package/dist/config/role-command-service.js +166 -0
  54. package/dist/config/role-request-service.js +193 -0
  55. package/dist/config/schema-migration.js +686 -25
  56. package/dist/config-store.js +79 -3
  57. package/dist/contracts/ecweb-instance.js +41 -0
  58. package/dist/contracts/ecweb-service-protocol.js +3 -1
  59. package/dist/core/agent-application-service.js +11 -1
  60. package/dist/core/agent-ipc-registration.js +4 -0
  61. package/dist/core/agent-runtime.js +1 -1
  62. package/dist/core/auth/agent-delegation.js +82 -6
  63. package/dist/core/auth/auth-gateway.js +1 -1
  64. package/dist/core/auth/authorization-audit.js +37 -9
  65. package/dist/core/auth/delegation-authorization.js +3 -1
  66. package/dist/core/auth/operation-authorizer.js +15 -0
  67. package/dist/core/auth/operation-catalog.js +39 -6
  68. package/dist/core/command/agent-control.js +94 -19
  69. package/dist/core/command/agent-storage-menu.js +5 -3
  70. package/dist/core/command/cli-intent-parser.js +2 -1
  71. package/dist/core/command/command-handler.js +105 -145
  72. package/dist/core/command/connect-menu.js +31 -2
  73. package/dist/core/command/data-root-resolver.js +5 -4
  74. package/dist/core/command/memory-slash.js +16 -8
  75. package/dist/core/command/menu-catalog.js +6 -6
  76. package/dist/core/command/menu-handler.js +87 -163
  77. package/dist/core/command/menu-protocol.js +9 -2
  78. package/dist/core/command/role-menu.js +148 -30
  79. package/dist/core/command/slash-gate.js +13 -10
  80. package/dist/core/command/slash-handler.js +157 -352
  81. package/dist/core/daemon-control.js +8 -14
  82. package/dist/core/event-catalog.js +15 -0
  83. package/dist/core/evolagent-registry.js +4 -4
  84. package/dist/core/evolagent.js +2 -2
  85. package/dist/core/inference/text-inference.js +31 -40
  86. package/dist/core/ipc-registration.js +24 -3
  87. package/dist/core/memory/consolidation-context.js +51 -5
  88. package/dist/core/memory/consolidation-ops-records.js +1 -1
  89. package/dist/core/memory/consolidation-trigger.js +190 -190
  90. package/dist/core/memory/consolidation.js +316 -29
  91. package/dist/core/memory/forget-log.js +96 -0
  92. package/dist/core/memory/index-manager.js +27 -5
  93. package/dist/core/memory/memory-admin.js +45 -5
  94. package/dist/core/memory/memory-writer.js +163 -18
  95. package/dist/core/memory/relation-idle-monitor.js +119 -58
  96. package/dist/core/memory/relation-sweep.js +44 -39
  97. package/dist/core/message/aun-ipc-sender.js +34 -7
  98. package/dist/core/message/aun-request-registry.js +97 -3
  99. package/dist/core/message/im-renderer.js +11 -4
  100. package/dist/core/message/message-admission.js +97 -8
  101. package/dist/core/message/message-bridge.js +71 -24
  102. package/dist/core/message/message-log.js +55 -0
  103. package/dist/core/message/message-queue.js +5 -5
  104. package/dist/core/message/response-engine.js +387 -144
  105. package/dist/core/model/catalog-service.js +4 -2
  106. package/dist/core/model/config-scope.js +24 -64
  107. package/dist/core/model/field-scope.js +1 -1
  108. package/dist/core/model/model-catalog.js +37 -47
  109. package/dist/core/model/model-diagnostics.js +4 -3
  110. package/dist/core/model/model-fallback.js +10 -7
  111. package/dist/core/model/model-permission.js +3 -2
  112. package/dist/core/ownership/owner-resolver.js +25 -23
  113. package/dist/core/permission/ec-command-parser.js +138 -5
  114. package/dist/core/permission/sandbox-runtime.js +18 -1
  115. package/dist/core/permission/tool-policy.js +42 -10
  116. package/dist/core/relation/peer-identity.js +64 -1
  117. package/dist/core/role/runtime-policy.js +72 -13
  118. package/dist/core/session/session-capsule.js +197 -0
  119. package/dist/core/session/session-idle-monitor.js +1 -1
  120. package/dist/core/session/session-manager.js +168 -14
  121. package/dist/core/session/session-mapper.js +2 -0
  122. package/dist/core/session/session-renew.js +3 -3
  123. package/dist/core/skill/index-generator.js +15 -5
  124. package/dist/core/system-session/memory.js +6 -1
  125. package/dist/core/thread/thread-service.js +19 -6
  126. package/dist/directory/owner-directory-admission.js +95 -0
  127. package/dist/directory/owner-directory-authorization.js +309 -0
  128. package/dist/directory/owner-directory-cache.js +635 -0
  129. package/dist/eck/kit-renderer.js +2 -2
  130. package/dist/ecweb/basic-settings-service.js +33 -40
  131. package/dist/ecweb/message-context-service.js +110 -0
  132. package/dist/index.js +79 -17
  133. package/dist/ipc.js +189 -17
  134. package/dist/paths.js +4 -0
  135. package/dist/proxy/command.js +122 -0
  136. package/dist/proxy/ipc-service.js +68 -0
  137. package/dist/proxy/manager.js +485 -0
  138. package/dist/proxy/service-supervisor.js +603 -0
  139. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  140. package/dist/stats/budget.js +1 -1
  141. package/dist/stats/db.js +15 -0
  142. package/dist/stats/index.js +2 -2
  143. package/dist/stats/price-resolver.js +304 -5
  144. package/dist/stats/query.js +82 -3
  145. package/dist/stats/writer.js +38 -5
  146. package/dist/trigger/feedback.js +18 -7
  147. package/dist/trigger/manager.js +20 -3
  148. package/dist/trigger/parser.js +6 -3
  149. package/dist/trigger/patch.js +1 -1
  150. package/dist/trigger/system-definitions.js +43 -7
  151. package/dist/trigger/validation.js +13 -5
  152. package/dist/utils/cross-platform.js +14 -0
  153. package/dist/utils/ecweb-supervisor.js +258 -83
  154. package/dist/utils/error-utils.js +16 -2
  155. package/dist/utils/logger.js +24 -5
  156. package/dist/utils/npm-ops.js +2 -1
  157. package/dist/utils/package-version-info.js +5 -3
  158. package/dist/utils/upgrade-jobs.js +45 -5
  159. package/kits/docs/INDEX.md +1 -1
  160. package/kits/docs/aun/ABILITY_CALLING.md +20 -2
  161. package/kits/docs/channels/aun.md +9 -0
  162. package/kits/docs/evolcore/INDEX.md +2 -1
  163. package/kits/docs/evolcore/agent-create.md +3 -2
  164. package/kits/docs/evolcore/agent.md +1 -1
  165. package/kits/docs/evolcore/config.md +18 -7
  166. package/kits/docs/evolcore/contact.md +3 -0
  167. package/kits/docs/evolcore/event.md +1 -0
  168. package/kits/docs/evolcore/fs.md +16 -0
  169. package/kits/docs/evolcore/memory-architecture.md +2 -2
  170. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  171. package/kits/docs/evolcore/memory.md +1 -1
  172. package/kits/docs/evolcore/menu-protocol.md +36 -0
  173. package/kits/docs/evolcore/model.md +23 -20
  174. package/kits/docs/evolcore/msg.md +21 -8
  175. package/kits/docs/evolcore/session.md +14 -0
  176. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  177. package/kits/schemas/_meta.json +37 -4
  178. package/kits/schemas/agent-config.schema.13.json +23 -3
  179. package/kits/schemas/agent-config.schema.16.json +891 -0
  180. package/kits/schemas/daemon.schema.9.json +366 -0
  181. package/kits/schemas/defaults.schema.5.json +406 -127
  182. package/kits/schemas/relation-config.schema.11.json +260 -0
  183. package/kits/schemas/role-config.schema.1.json +7 -7
  184. package/kits/skills/.switches.json +3 -7
  185. package/kits/skills/aid-ability/SKILL.md +35 -6
  186. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  187. package/kits/skills/ec-trigger/SKILL.md +13 -5
  188. package/kits/skills/personal-assistant/SKILL.md +176 -0
  189. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  190. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  191. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  192. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  193. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  194. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  195. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  196. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  197. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  198. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  199. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  200. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  201. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  202. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  203. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  204. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  205. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  206. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  207. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  208. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  209. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  210. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  211. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  212. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  213. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  214. package/kits/templates/memory-consolidation/forget.md +19 -6
  215. package/kits/templates/memory-consolidation/notes.md +1 -1
  216. package/kits/templates/memory-consolidation/profile.md +2 -2
  217. package/kits/templates/memory-consolidation/promote.md +20 -3
  218. package/kits/templates/roles/member.json +8 -1
  219. package/kits/templates/session-capsule/recovery.md +5 -0
  220. package/kits/templates/session-capsule/renew.md +5 -0
  221. package/kits/templates/system-fragments/baseagent.md +2 -2
  222. package/kits/templates/system-fragments/bootstrap.md +6 -6
  223. package/kits/templates/system-fragments/channel.md +1 -1
  224. package/kits/templates/system-fragments/memory.md +4 -4
  225. package/package.json +7 -3
  226. package/dist/stats/billing.js +0 -215
@@ -0,0 +1,485 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import chokidar from 'chokidar';
5
+ import { DEFAULT_ECWEB_PORT, serviceRuntimeMode } from '../config/daemon-services.js';
6
+ import { ConfigTarget, mutateConfig, onConfigWrite } from '../config/config-manager.js';
7
+ import { loadDaemonConfig } from '../config-store.js';
8
+ import { resolvePaths } from '../paths.js';
9
+ import { atomicWriteJson } from '../utils/atomic-write.js';
10
+ import { logger as defaultLogger } from '../utils/logger.js';
11
+ import { startServiceProxy } from '../aun/service-proxy.js';
12
+ import { ServiceSupervisor } from './service-supervisor.js';
13
+ const MUTATIONS = new Set([
14
+ 'build', 'update', 'apply', 'publish', 'unpublish', 'remove', 'start', 'stop',
15
+ 'restart', 'reload', 'reset-failure',
16
+ ]);
17
+ function stable(value) {
18
+ if (Array.isArray(value))
19
+ return '[' + value.map(stable).join(',') + ']';
20
+ if (value && typeof value === 'object') {
21
+ return '{' + Object.entries(value)
22
+ .filter(([, item]) => item !== undefined)
23
+ .sort(([a], [b]) => a.localeCompare(b))
24
+ .map(([key, item]) => JSON.stringify(key) + ':' + stable(item))
25
+ .join(',') + '}';
26
+ }
27
+ return JSON.stringify(value);
28
+ }
29
+ function hash(value) {
30
+ return 'sha256:' + crypto.createHash('sha256').update(stable(value)).digest('hex');
31
+ }
32
+ function operationStorePath() {
33
+ return path.join(resolvePaths().proxyDir, 'operations.json');
34
+ }
35
+ function readOperationStore() {
36
+ try {
37
+ const value = JSON.parse(fs.readFileSync(operationStorePath(), 'utf8'));
38
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
39
+ }
40
+ catch {
41
+ return {};
42
+ }
43
+ }
44
+ function writeOperationStore(value) {
45
+ fs.mkdirSync(resolvePaths().proxyDir, { recursive: true });
46
+ atomicWriteJson(operationStorePath(), value);
47
+ }
48
+ function serviceRevision(service) {
49
+ return service ? hash(service) : 'absent';
50
+ }
51
+ function findService(services, name) {
52
+ return services.find(service => service.name === name);
53
+ }
54
+ function validateOperationId(value) {
55
+ if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) {
56
+ throw Object.assign(new Error('operationId must contain 1-128 safe characters'), { code: 'INVALID_ARGUMENT' });
57
+ }
58
+ return value;
59
+ }
60
+ export class ServiceProxyManager {
61
+ options;
62
+ supervisor;
63
+ removeConfigListener;
64
+ activeProxy = null;
65
+ activeProxySignature = '';
66
+ activeProxyNames = [];
67
+ applyQueue = Promise.resolve();
68
+ stopped = false;
69
+ instanceWatcher;
70
+ instanceApplyTimer;
71
+ proxyTransport = {
72
+ state: 'unpublished',
73
+ gatewayRegistered: false,
74
+ proxyServer: 'unknown',
75
+ updatedAt: Date.now(),
76
+ error: undefined,
77
+ };
78
+ inflight = new Map();
79
+ constructor(options) {
80
+ this.options = options;
81
+ this.supervisor = new ServiceSupervisor(defaultLogger);
82
+ }
83
+ async start() {
84
+ this.stopped = false;
85
+ this.removeConfigListener = onConfigWrite(({ target }) => {
86
+ if (target === ConfigTarget.Process)
87
+ void this.scheduleApply().catch(error => {
88
+ defaultLogger.warn('[ServiceProxy] hot apply failed: ' + (error instanceof Error ? error.message : String(error)));
89
+ });
90
+ });
91
+ fs.mkdirSync(resolvePaths().instanceDir, { recursive: true });
92
+ this.instanceWatcher = chokidar.watch(resolvePaths().instanceDir, { ignoreInitial: true, depth: 0 });
93
+ this.instanceWatcher.on('all', (_event, filePath) => {
94
+ const basename = path.basename(filePath);
95
+ const configured = loadDaemonConfig().services ?? [];
96
+ if (!configured.some(service => service.proxy?.enabled === true
97
+ && service.proxy.source === 'instance'
98
+ && basename.startsWith(service.name + '-')))
99
+ return;
100
+ const serviceName = configured.find(service => service.proxy?.enabled === true
101
+ && service.proxy.source === 'instance'
102
+ && basename.startsWith(service.name + '-'))?.name;
103
+ if (this.proxyTransport.proxyServer !== 'unconfirmed')
104
+ return;
105
+ if (this.instanceApplyTimer)
106
+ clearTimeout(this.instanceApplyTimer);
107
+ this.instanceApplyTimer = setTimeout(() => {
108
+ this.instanceApplyTimer = undefined;
109
+ const activeProxyConfig = this.activeProxyNames
110
+ .map(name => findService(loadDaemonConfig().services ?? [], name))
111
+ .filter((service) => !!service);
112
+ const dirtySnapshot = activeProxyConfig.map(service => service.name === serviceName
113
+ ? { ...service, runtime: { ...service.runtime, generation: Date.now() } }
114
+ : service);
115
+ this.activeProxySignature = hash(dirtySnapshot);
116
+ void this.scheduleApply().catch(error => {
117
+ defaultLogger.warn('[ServiceProxy] instance change apply failed: ' + (error instanceof Error ? error.message : String(error)));
118
+ });
119
+ }, 250);
120
+ this.instanceApplyTimer.unref?.();
121
+ });
122
+ await this.supervisor.start(loadDaemonConfig().services ?? []);
123
+ void this.scheduleApply().catch(error => {
124
+ defaultLogger.warn('[ServiceProxy] initial apply failed: ' + (error instanceof Error ? error.message : String(error)));
125
+ });
126
+ }
127
+ async stop() {
128
+ if (this.stopped)
129
+ return;
130
+ this.stopped = true;
131
+ this.removeConfigListener?.();
132
+ this.removeConfigListener = undefined;
133
+ if (this.instanceApplyTimer)
134
+ clearTimeout(this.instanceApplyTimer);
135
+ this.instanceApplyTimer = undefined;
136
+ await this.instanceWatcher?.close();
137
+ this.instanceWatcher = undefined;
138
+ await this.applyQueue.catch(() => { });
139
+ this.activeProxy?.stop();
140
+ this.activeProxy = null;
141
+ await this.supervisor.stop();
142
+ }
143
+ async execute(request) {
144
+ if (!request || typeof request !== 'object' || !request.operation) {
145
+ throw Object.assign(new Error('operation is required'), { code: 'INVALID_ARGUMENT' });
146
+ }
147
+ if (!MUTATIONS.has(request.operation))
148
+ return this.executeRead(request);
149
+ if (request.dryRun)
150
+ return this.dryRun(request);
151
+ const operationId = validateOperationId(request.operationId);
152
+ const inputFingerprint = hash({ ...request, operationId: undefined, dryRun: undefined });
153
+ const previous = readOperationStore()[operationId];
154
+ if (previous) {
155
+ if (previous.fingerprint !== inputFingerprint) {
156
+ throw Object.assign(new Error('operationId was already used with different input'), { code: 'IDEMPOTENCY_CONFLICT' });
157
+ }
158
+ if (previous.result.ok === false)
159
+ throw Object.assign(new Error(String(previous.result.error)), { code: String(previous.result.code ?? 'OPERATION_FAILED'), data: previous.result.data });
160
+ return { ...previous.result, replayed: true };
161
+ }
162
+ const pending = this.inflight.get(operationId);
163
+ if (pending)
164
+ return await pending;
165
+ const run = this.executeMutation(request, operationId).then(result => {
166
+ const store = readOperationStore();
167
+ store[operationId] = { fingerprint: inputFingerprint, result, completedAt: Date.now() };
168
+ const retained = Object.entries(store).sort((a, b) => b[1].completedAt - a[1].completedAt).slice(0, 500);
169
+ writeOperationStore(Object.fromEntries(retained));
170
+ return result;
171
+ }).catch(error => {
172
+ const store = readOperationStore();
173
+ store[operationId] = {
174
+ fingerprint: inputFingerprint,
175
+ result: { ok: false, code: String(error?.code ?? 'OPERATION_FAILED'), error: error instanceof Error ? error.message : String(error) },
176
+ completedAt: Date.now(),
177
+ };
178
+ writeOperationStore(store);
179
+ throw error;
180
+ }).finally(() => this.inflight.delete(operationId));
181
+ this.inflight.set(operationId, run);
182
+ return await run;
183
+ }
184
+ async executeRead(request) {
185
+ const config = loadDaemonConfig();
186
+ const services = config.services ?? [];
187
+ const service = request.name ? findService(services, request.name) : undefined;
188
+ if (request.name && !service && request.operation !== 'job') {
189
+ throw Object.assign(new Error('service not found: ' + request.name), { code: 'NOT_FOUND' });
190
+ }
191
+ if (request.operation === 'job') {
192
+ const jobId = request.jobId ?? request.name;
193
+ if (!jobId)
194
+ throw Object.assign(new Error('jobId is required'), { code: 'INVALID_ARGUMENT' });
195
+ const record = readOperationStore()[jobId];
196
+ if (!record)
197
+ throw Object.assign(new Error('operation result not found: ' + jobId), { code: 'NOT_FOUND' });
198
+ return { ok: true, jobId, state: 'completed', completedAt: record.completedAt, result: record.result };
199
+ }
200
+ if (request.operation === 'access') {
201
+ return {
202
+ ok: true,
203
+ providerAid: this.options.providerAid,
204
+ service: this.describe(service),
205
+ accessState: 'unresolved',
206
+ url: null,
207
+ };
208
+ }
209
+ if (request.operation === 'show')
210
+ return { ok: true, configRev: serviceRevision(service), service: this.describe(service) };
211
+ if (request.operation === 'options') {
212
+ return { ok: true, operations: [...MUTATIONS], reloadByMode: { managed: 'restart', external: 'unmanaged' } };
213
+ }
214
+ if (request.operation === 'list' || request.operation === 'status') {
215
+ return {
216
+ ok: true,
217
+ providerAid: this.options.providerAid,
218
+ services: services.map(item => ({
219
+ ...this.describe(item),
220
+ configRev: serviceRevision(item),
221
+ runtime: (item.name === 'ecweb' && serviceRuntimeMode(item) === 'managed' ? this.options.ecwebSupervisor?.status() : undefined)
222
+ ?? this.supervisor.snapshot(item.name)[0] ?? {
223
+ name: item.name, state: item.enabled ? 'unknown' : 'disabled',
224
+ failureCount: 0, restartCount: 0, generation: 0,
225
+ managed: serviceRuntimeMode(item) === 'managed',
226
+ },
227
+ })),
228
+ proxy: { ...this.proxyTransport },
229
+ };
230
+ }
231
+ throw Object.assign(new Error('unsupported read operation: ' + request.operation), { code: 'NOT_SUPPORTED' });
232
+ }
233
+ dryRun(request) {
234
+ const services = loadDaemonConfig().services ?? [];
235
+ const current = request.name ? findService(services, request.name) : undefined;
236
+ if (request.operation === 'build' && request.service) {
237
+ if (current && request.ifRev !== serviceRevision(current))
238
+ throw Object.assign(new Error('config revision changed'), { code: 'CONFLICT', data: { currentRev: serviceRevision(current) } });
239
+ if (!current && request.ifRev !== 'absent')
240
+ throw Object.assign(new Error('new services require ifRev=absent'), { code: 'CONFLICT', data: { currentRev: 'absent' } });
241
+ return { ok: true, dryRun: true, changed: !current || stable(current) !== stable(request.service), configRev: serviceRevision(request.service), plan: 'save service definition and apply' };
242
+ }
243
+ if (!current)
244
+ throw Object.assign(new Error('service not found: ' + request.name), { code: 'NOT_FOUND' });
245
+ if (request.ifRev !== serviceRevision(current))
246
+ throw Object.assign(new Error('config revision changed'), { code: 'CONFLICT', data: { currentRev: serviceRevision(current) } });
247
+ return { ok: true, dryRun: true, changed: true, configRev: serviceRevision(current), plan: request.operation + ' service ' + current.name };
248
+ }
249
+ async executeMutation(request, operationId) {
250
+ if (request.operation === 'apply') {
251
+ await this.scheduleApply();
252
+ return { ok: true, changed: false, operationId, jobId: operationId, state: 'completed', proxy: { ...this.proxyTransport } };
253
+ }
254
+ if (request.operation === 'build') {
255
+ if (!request.service)
256
+ throw Object.assign(new Error('service is required'), { code: 'INVALID_ARGUMENT' });
257
+ const name = request.service.name;
258
+ if (!name)
259
+ throw Object.assign(new Error('service.name is required'), { code: 'INVALID_ARGUMENT' });
260
+ const result = this.mutateService(name, request.ifRev, current => {
261
+ if (current)
262
+ return { ...request.service };
263
+ return { ...request.service };
264
+ }, true);
265
+ await this.scheduleApply();
266
+ return { ok: true, ...result, operationId, jobId: operationId, state: 'completed' };
267
+ }
268
+ const name = request.name;
269
+ if (!name)
270
+ throw Object.assign(new Error('service name is required'), { code: 'INVALID_ARGUMENT' });
271
+ if (request.operation === 'update') {
272
+ if (!request.patch)
273
+ throw Object.assign(new Error('patch is required'), { code: 'INVALID_ARGUMENT' });
274
+ if (request.patch.name !== undefined && request.patch.name !== name) {
275
+ throw Object.assign(new Error('service name cannot be changed'), { code: 'INVALID_ARGUMENT' });
276
+ }
277
+ const result = this.mutateService(name, request.ifRev, current => ({ ...current, ...request.patch,
278
+ ...(current?.proxy || request.patch?.proxy ? { proxy: { ...(current?.proxy ?? {}), ...(request.patch?.proxy ?? {}) } } : {}),
279
+ ...(current?.runtime || request.patch?.runtime ? { runtime: { ...(current?.runtime ?? {}), ...(request.patch?.runtime ?? {}) } } : {}), }));
280
+ await this.scheduleApply();
281
+ return { ok: true, ...result, operationId, jobId: operationId, state: 'completed' };
282
+ }
283
+ const current = findService(loadDaemonConfig().services ?? [], name);
284
+ if (!current)
285
+ throw Object.assign(new Error('service not found: ' + name), { code: 'NOT_FOUND' });
286
+ if (request.ifRev !== serviceRevision(current)) {
287
+ throw Object.assign(new Error('config revision changed'), { code: 'CONFLICT', data: { currentRev: serviceRevision(current) } });
288
+ }
289
+ if (request.operation === 'remove') {
290
+ if (current.enabled || current.proxy?.enabled)
291
+ throw Object.assign(new Error('unpublish and stop the service before removal'), { code: 'SERVICE_BUSY' });
292
+ const result = this.mutateService(name, request.ifRev, () => undefined);
293
+ await this.scheduleApply();
294
+ return { ok: true, ...result, operationId, jobId: operationId, state: 'completed' };
295
+ }
296
+ if (request.operation === 'publish' || request.operation === 'unpublish') {
297
+ if (request.operation === 'publish' && current.enabled !== true)
298
+ throw Object.assign(new Error('service must be enabled before publish'), { code: 'SERVICE_NOT_ENABLED' });
299
+ const result = this.mutateService(name, request.ifRev, service => ({
300
+ ...service,
301
+ proxy: { ...(service?.proxy ?? {}), enabled: request.operation === 'publish' },
302
+ }));
303
+ await this.scheduleApply();
304
+ return { ok: true, ...result, operationId, jobId: operationId, state: 'completed', proxy: { ...this.proxyTransport } };
305
+ }
306
+ if (request.operation === 'start' || request.operation === 'stop') {
307
+ if (serviceRuntimeMode(current) === 'external')
308
+ throw Object.assign(new Error('external services cannot be started or stopped by EvolCore'), { code: 'EXTERNAL_SERVICE_UNMANAGED' });
309
+ if (name === 'ecweb' && this.options.ecwebSupervisor) {
310
+ const result = this.mutateService(name, request.ifRev, service => ({ ...service, enabled: request.operation === 'start' }));
311
+ await this.scheduleApply();
312
+ await this.options.ecwebSupervisor.configure({
313
+ enabled: request.operation === 'start',
314
+ port: current.port ?? DEFAULT_ECWEB_PORT,
315
+ runtimeMode: 'managed',
316
+ restart: current.runtime?.restart,
317
+ });
318
+ return { ok: true, ...result, operationId, jobId: operationId, state: 'completed', runtime: this.options.ecwebSupervisor.status() };
319
+ }
320
+ if (name === 'ecweb')
321
+ throw Object.assign(new Error('ECWeb internal adapter is unavailable'), { code: 'SERVICE_UNAVAILABLE' });
322
+ const result = this.mutateService(name, request.ifRev, service => ({ ...service, enabled: request.operation === 'start' }));
323
+ await this.scheduleApply();
324
+ if (request.operation === 'start')
325
+ await this.supervisor.startService(name);
326
+ if (request.operation === 'stop')
327
+ await this.supervisor.stopService(name);
328
+ return { ok: true, ...result, operationId, jobId: operationId, state: 'completed', runtime: this.supervisor.snapshot(name)[0] };
329
+ }
330
+ if (request.operation === 'restart' || request.operation === 'reload') {
331
+ if (current.enabled !== true)
332
+ throw Object.assign(new Error('disabled service cannot be reloaded'), { code: 'SERVICE_NOT_ENABLED' });
333
+ if (serviceRuntimeMode(current) === 'external')
334
+ throw Object.assign(new Error('external service lifecycle is not managed'), { code: 'EXTERNAL_SERVICE_UNMANAGED' });
335
+ if (name === 'ecweb' && this.options.ecwebSupervisor) {
336
+ await this.options.ecwebSupervisor.restart();
337
+ await this.scheduleApply();
338
+ return { ok: true, changed: true, configRev: serviceRevision(current), operationId, jobId: operationId, state: 'completed', runtime: this.options.ecwebSupervisor.status() };
339
+ }
340
+ if (name === 'ecweb')
341
+ throw Object.assign(new Error('ECWeb internal adapter is unavailable'), { code: 'SERVICE_UNAVAILABLE' });
342
+ const runtime = request.operation === 'restart'
343
+ ? await this.supervisor.restartService(name)
344
+ : await this.supervisor.reload(name);
345
+ await this.scheduleApply();
346
+ return { ok: true, changed: true, configRev: serviceRevision(current), operationId, jobId: operationId, state: 'completed', runtime };
347
+ }
348
+ if (request.operation === 'reset-failure') {
349
+ if (serviceRuntimeMode(current) === 'external')
350
+ throw Object.assign(new Error('external service lifecycle is not managed'), { code: 'EXTERNAL_SERVICE_UNMANAGED' });
351
+ if (name === 'ecweb' && this.options.ecwebSupervisor) {
352
+ await this.options.ecwebSupervisor.resetFailure();
353
+ return { ok: true, changed: true, configRev: serviceRevision(current), operationId, jobId: operationId, state: 'completed', runtime: this.options.ecwebSupervisor.status() };
354
+ }
355
+ const runtime = await this.supervisor.clearFailure(name);
356
+ return { ok: true, changed: true, configRev: serviceRevision(current), operationId, jobId: operationId, state: 'completed', runtime };
357
+ }
358
+ throw Object.assign(new Error('unsupported operation: ' + request.operation), { code: 'NOT_SUPPORTED' });
359
+ }
360
+ mutateService(name, ifRev, mutate, allowCreate = false) {
361
+ const result = mutateConfig(ConfigTarget.Process, undefined, config => {
362
+ const services = Array.isArray(config.services) ? config.services : [];
363
+ const current = findService(services, name);
364
+ const currentRev = serviceRevision(current);
365
+ if (ifRev !== currentRev) {
366
+ throw Object.assign(new Error('config revision changed'), { code: 'CONFLICT', data: { currentRev } });
367
+ }
368
+ if (!current && !allowCreate && mutate !== undefined) {
369
+ throw Object.assign(new Error('service not found: ' + name), { code: 'NOT_FOUND' });
370
+ }
371
+ const updated = mutate(current);
372
+ config.services = updated
373
+ ? current ? services.map(item => item.name === name ? updated : item) : [...services, updated]
374
+ : services.filter(item => item.name !== name);
375
+ return updated;
376
+ });
377
+ const service = result.value;
378
+ return { changed: result.changed, configRev: serviceRevision(service), ...(service ? { service: this.describe(service) } : {}) };
379
+ }
380
+ async scheduleApply() {
381
+ this.applyQueue = this.applyQueue.then(() => this.applyFromConfig(), () => this.applyFromConfig());
382
+ return this.applyQueue;
383
+ }
384
+ async applyFromConfig() {
385
+ if (this.stopped)
386
+ return;
387
+ const services = loadDaemonConfig().services ?? [];
388
+ const ecweb = findService(services, 'ecweb');
389
+ await this.options.ecwebSupervisor?.configure({
390
+ enabled: ecweb?.enabled === true,
391
+ port: ecweb?.port ?? DEFAULT_ECWEB_PORT,
392
+ runtimeMode: ecweb ? serviceRuntimeMode(ecweb) : 'managed',
393
+ restart: ecweb?.runtime?.restart,
394
+ });
395
+ await this.supervisor.reconcile(services);
396
+ if (this.stopped)
397
+ return;
398
+ const desired = services.filter(service => service.enabled === true && service.proxy?.enabled === true);
399
+ const signature = hash(desired);
400
+ if (signature === this.activeProxySignature)
401
+ return;
402
+ const oldNames = this.activeProxy ? (this.activeProxySignature ? this.readActiveProxyNames() : []) : [];
403
+ const nextNames = desired.map(service => service.name);
404
+ if (this.activeProxy) {
405
+ const removed = oldNames.filter(name => !nextNames.includes(name));
406
+ try {
407
+ await this.activeProxy.unregister(removed);
408
+ }
409
+ catch (error) {
410
+ this.proxyTransport.state = 'degraded';
411
+ this.proxyTransport.error = 'withdrawal pending: ' + (error instanceof Error ? error.message : String(error));
412
+ }
413
+ this.activeProxy.stop();
414
+ this.activeProxy = null;
415
+ }
416
+ this.activeProxySignature = signature;
417
+ this.activeProxyNames = nextNames;
418
+ this.proxyTransport.updatedAt = Date.now();
419
+ this.proxyTransport.gatewayRegistered = false;
420
+ this.proxyTransport.proxyServer = 'unknown';
421
+ if (desired.length === 0) {
422
+ if (!this.proxyTransport.error)
423
+ this.proxyTransport.state = 'unpublished';
424
+ return;
425
+ }
426
+ this.proxyTransport.error = undefined;
427
+ this.proxyTransport.state = 'starting';
428
+ const handle = startServiceProxy(this.options.controlChannel, this.options.providerAid, desired);
429
+ if (!handle) {
430
+ this.proxyTransport.state = 'unpublished';
431
+ return;
432
+ }
433
+ this.activeProxy = handle;
434
+ try {
435
+ const result = await handle.ready;
436
+ if (this.activeProxy !== handle)
437
+ return;
438
+ this.proxyTransport.gatewayRegistered = result.gatewayRegistered;
439
+ this.proxyTransport.proxyServer = 'unconfirmed';
440
+ if (result.registered === 0) {
441
+ handle.stop();
442
+ this.activeProxy = null;
443
+ this.activeProxySignature = '';
444
+ this.proxyTransport.state = 'degraded';
445
+ this.proxyTransport.error = 'no local service endpoint is ready yet';
446
+ const timer = setTimeout(() => {
447
+ void this.scheduleApply().catch(error => defaultLogger.warn('[ServiceProxy] endpoint retry failed: ' + String(error)));
448
+ }, 1000);
449
+ timer.unref?.();
450
+ return;
451
+ }
452
+ this.proxyTransport.state = result.gatewayRegistered ? 'active' : 'degraded';
453
+ this.proxyTransport.error = result.gatewayRegistered ? undefined : 'Gateway registration has not been confirmed';
454
+ }
455
+ catch (error) {
456
+ if (this.activeProxy !== handle)
457
+ return;
458
+ this.proxyTransport.state = 'degraded';
459
+ this.proxyTransport.error = error instanceof Error ? error.message : String(error);
460
+ }
461
+ }
462
+ readActiveProxyNames() {
463
+ return [...this.activeProxyNames];
464
+ }
465
+ describe(service) {
466
+ return {
467
+ name: service.name,
468
+ enabled: service.enabled === true,
469
+ ...(service.port === undefined ? {} : { port: service.port }),
470
+ runtimeMode: serviceRuntimeMode(service),
471
+ restart: { enabled: serviceRuntimeMode(service) === 'managed' && service.runtime?.restart?.enabled !== false },
472
+ ...(service.health ? { health: service.health } : {}),
473
+ proxy: service.proxy
474
+ ? {
475
+ enabled: service.proxy.enabled === true,
476
+ source: service.proxy.source,
477
+ serviceType: service.proxy.serviceType,
478
+ visibility: service.proxy.visibility,
479
+ metadata: service.proxy.metadata ?? {},
480
+ }
481
+ : { enabled: false },
482
+ configRev: serviceRevision(service),
483
+ };
484
+ }
485
+ }