evolcore 0.0.41-test.0 → 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 (177) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +20 -43
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +84 -28
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/group/fs-download.js +39 -0
  9. package/dist/aun/group/identity.js +36 -21
  10. package/dist/aun/group/operations.js +5 -0
  11. package/dist/aun/msg/managed-operation.js +68 -7
  12. package/dist/aun/msg/p2p.js +5 -0
  13. package/dist/aun/service-proxy.js +36 -12
  14. package/dist/channels/aun.js +334 -20
  15. package/dist/channels/daemon.js +15 -1
  16. package/dist/cli/aun-commands.js +4 -20
  17. package/dist/cli/daemon-commands.js +678 -697
  18. package/dist/cli/fs-command.js +64 -2
  19. package/dist/cli/index.js +48 -4
  20. package/dist/cli/managed-command-guard.js +4 -0
  21. package/dist/cli/model.js +40 -40
  22. package/dist/cli/proxy-command.js +92 -0
  23. package/dist/cli/role.js +85 -0
  24. package/dist/config/access-policy.js +7 -2
  25. package/dist/config/boot-log.js +38 -1
  26. package/dist/config/config-field-policy.js +5 -32
  27. package/dist/config/config-manager.js +46 -39
  28. package/dist/config/config-operation-service.js +5 -19
  29. package/dist/config/contact-book-store.js +47 -21
  30. package/dist/config/contact-book.js +18 -12
  31. package/dist/config/contact-operation-service.js +3 -4
  32. package/dist/config/contact-request-service.js +11 -0
  33. package/dist/config/daemon-services.js +11 -0
  34. package/dist/config/gateway-config.js +88 -594
  35. package/dist/config/peer-role-resolver.js +13 -11
  36. package/dist/config/providers-config.js +12 -7
  37. package/dist/config/providers-import.js +3 -21
  38. package/dist/config/resolved-config-op.js +3 -0
  39. package/dist/config/role-command-service.js +166 -0
  40. package/dist/config/role-request-service.js +193 -0
  41. package/dist/config/schema-migration.js +686 -25
  42. package/dist/config-store.js +79 -3
  43. package/dist/contracts/ecweb-instance.js +41 -0
  44. package/dist/contracts/ecweb-service-protocol.js +3 -1
  45. package/dist/core/agent-runtime.js +1 -1
  46. package/dist/core/auth/agent-delegation.js +2 -1
  47. package/dist/core/auth/auth-gateway.js +1 -1
  48. package/dist/core/auth/authorization-audit.js +17 -6
  49. package/dist/core/auth/delegation-authorization.js +3 -1
  50. package/dist/core/auth/operation-authorizer.js +15 -0
  51. package/dist/core/auth/operation-catalog.js +31 -6
  52. package/dist/core/command/agent-control.js +3 -7
  53. package/dist/core/command/agent-storage-menu.js +5 -3
  54. package/dist/core/command/cli-intent-parser.js +2 -1
  55. package/dist/core/command/command-handler.js +48 -99
  56. package/dist/core/command/connect-menu.js +11 -3
  57. package/dist/core/command/data-root-resolver.js +5 -4
  58. package/dist/core/command/memory-slash.js +16 -8
  59. package/dist/core/command/menu-catalog.js +5 -6
  60. package/dist/core/command/menu-handler.js +49 -62
  61. package/dist/core/command/role-menu.js +147 -30
  62. package/dist/core/command/slash-handler.js +123 -254
  63. package/dist/core/daemon-control.js +8 -14
  64. package/dist/core/evolagent-registry.js +4 -4
  65. package/dist/core/evolagent.js +2 -2
  66. package/dist/core/inference/text-inference.js +31 -40
  67. package/dist/core/ipc-registration.js +6 -2
  68. package/dist/core/memory/consolidation-context.js +51 -5
  69. package/dist/core/memory/consolidation-ops-records.js +1 -1
  70. package/dist/core/memory/consolidation-trigger.js +189 -189
  71. package/dist/core/memory/consolidation.js +316 -29
  72. package/dist/core/memory/forget-log.js +96 -0
  73. package/dist/core/memory/index-manager.js +27 -5
  74. package/dist/core/memory/memory-admin.js +45 -5
  75. package/dist/core/memory/memory-writer.js +163 -18
  76. package/dist/core/memory/relation-idle-monitor.js +119 -58
  77. package/dist/core/memory/relation-sweep.js +44 -39
  78. package/dist/core/message/aun-ipc-sender.js +8 -2
  79. package/dist/core/message/im-renderer.js +7 -4
  80. package/dist/core/message/message-admission.js +89 -4
  81. package/dist/core/message/message-bridge.js +31 -18
  82. package/dist/core/message/response-engine.js +77 -8
  83. package/dist/core/model/catalog-service.js +4 -2
  84. package/dist/core/model/config-scope.js +24 -64
  85. package/dist/core/model/field-scope.js +1 -1
  86. package/dist/core/model/model-catalog.js +30 -41
  87. package/dist/core/model/model-diagnostics.js +4 -3
  88. package/dist/core/model/model-fallback.js +10 -7
  89. package/dist/core/model/model-permission.js +3 -2
  90. package/dist/core/ownership/owner-resolver.js +23 -21
  91. package/dist/core/permission/ec-command-parser.js +30 -2
  92. package/dist/core/permission/sandbox-runtime.js +18 -1
  93. package/dist/core/permission/tool-policy.js +14 -3
  94. package/dist/core/relation/peer-identity.js +64 -1
  95. package/dist/core/role/runtime-policy.js +72 -13
  96. package/dist/core/session/session-capsule.js +1 -1
  97. package/dist/core/session/session-idle-monitor.js +1 -1
  98. package/dist/core/session/session-manager.js +20 -0
  99. package/dist/core/session/session-renew.js +3 -3
  100. package/dist/core/skill/index-generator.js +15 -5
  101. package/dist/core/system-session/memory.js +6 -1
  102. package/dist/core/thread/thread-service.js +19 -6
  103. package/dist/directory/owner-directory-admission.js +95 -0
  104. package/dist/directory/owner-directory-authorization.js +309 -0
  105. package/dist/directory/owner-directory-cache.js +635 -0
  106. package/dist/eck/kit-renderer.js +2 -2
  107. package/dist/ecweb/basic-settings-service.js +33 -40
  108. package/dist/ecweb/message-context-service.js +110 -0
  109. package/dist/index.js +76 -14
  110. package/dist/ipc.js +170 -12
  111. package/dist/paths.js +4 -0
  112. package/dist/proxy/command.js +122 -0
  113. package/dist/proxy/ipc-service.js +68 -0
  114. package/dist/proxy/manager.js +485 -0
  115. package/dist/proxy/service-supervisor.js +603 -0
  116. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  117. package/dist/utils/cross-platform.js +14 -0
  118. package/dist/utils/ecweb-supervisor.js +258 -83
  119. package/dist/utils/error-utils.js +2 -2
  120. package/dist/utils/logger.js +24 -5
  121. package/dist/utils/package-version-info.js +4 -2
  122. package/kits/docs/channels/aun.md +9 -0
  123. package/kits/docs/evolcore/agent.md +1 -1
  124. package/kits/docs/evolcore/config.md +17 -6
  125. package/kits/docs/evolcore/contact.md +3 -0
  126. package/kits/docs/evolcore/fs.md +11 -0
  127. package/kits/docs/evolcore/memory-architecture.md +2 -2
  128. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  129. package/kits/docs/evolcore/memory.md +1 -1
  130. package/kits/docs/evolcore/menu-protocol.md +4 -0
  131. package/kits/docs/evolcore/model.md +23 -20
  132. package/kits/docs/evolcore/msg.md +4 -7
  133. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  134. package/kits/schemas/_meta.json +37 -4
  135. package/kits/schemas/agent-config.schema.13.json +8 -3
  136. package/kits/schemas/agent-config.schema.16.json +891 -0
  137. package/kits/schemas/daemon.schema.9.json +366 -0
  138. package/kits/schemas/defaults.schema.5.json +406 -127
  139. package/kits/schemas/relation-config.schema.11.json +260 -0
  140. package/kits/schemas/role-config.schema.1.json +7 -7
  141. package/kits/skills/.switches.json +3 -7
  142. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  143. package/kits/skills/ec-trigger/SKILL.md +13 -5
  144. package/kits/skills/personal-assistant/SKILL.md +176 -0
  145. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  146. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  147. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  148. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  149. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  150. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  151. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  152. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  153. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  154. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  155. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  156. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  157. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  158. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  159. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  160. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  161. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  162. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  163. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  164. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  165. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  166. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  167. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  168. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  169. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  170. package/kits/templates/memory-consolidation/forget.md +19 -6
  171. package/kits/templates/memory-consolidation/notes.md +1 -1
  172. package/kits/templates/memory-consolidation/profile.md +2 -2
  173. package/kits/templates/memory-consolidation/promote.md +20 -3
  174. package/kits/templates/roles/member.json +8 -1
  175. package/kits/templates/system-fragments/baseagent.md +2 -2
  176. package/kits/templates/system-fragments/memory.md +4 -4
  177. package/package.json +6 -2
@@ -0,0 +1,603 @@
1
+ import fs from 'node:fs';
2
+ import net from 'node:net';
3
+ import path from 'node:path';
4
+ import { spawn } from 'node:child_process';
5
+ import crypto from 'node:crypto';
6
+ import { resolvePaths } from '../paths.js';
7
+ import { SERVICE_HEALTH_INTERVALS, SERVICE_RESTART_BACKOFF_MS, SERVICE_RESTART_MAX_ATTEMPTS, SERVICE_RESTART_WINDOW_MS, serviceRuntimeMode, } from '../config/daemon-services.js';
8
+ import { getProcessStartTime, startTimeMatches } from '../utils/process-introspect.js';
9
+ import * as platform from '../utils/cross-platform.js';
10
+ import { logger as defaultLogger } from '../utils/logger.js';
11
+ import { atomicWriteJson } from '../utils/atomic-write.js';
12
+ function sleep(ms) {
13
+ return new Promise(resolve => setTimeout(resolve, ms));
14
+ }
15
+ function stableHash(value) {
16
+ return crypto.createHash('sha256').update(JSON.stringify(value) ?? 'null').digest('hex');
17
+ }
18
+ function recordPath(name, pid) {
19
+ return path.join(resolvePaths().instanceDir, name + '-' + pid + '.json');
20
+ }
21
+ function serviceConfigHash(service) {
22
+ const { restart: _restart, ...runtime } = service.runtime ?? {};
23
+ return stableHash({ runtime, health: service.health, port: service.port });
24
+ }
25
+ function readInstanceRecords(name) {
26
+ const dir = resolvePaths().instanceDir;
27
+ let files;
28
+ try {
29
+ files = fs.readdirSync(dir);
30
+ }
31
+ catch {
32
+ return [];
33
+ }
34
+ const escapedName = name.replace(/[^a-z0-9_-]/gi, '');
35
+ const pattern = new RegExp('^' + escapedName + '-(\\d+)\\.json$');
36
+ const output = [];
37
+ for (const file of files) {
38
+ const match = file.match(pattern);
39
+ if (!match)
40
+ continue;
41
+ const filePath = path.join(dir, file);
42
+ try {
43
+ const record = JSON.parse(fs.readFileSync(filePath, 'utf8'));
44
+ if (record.owner !== 'evolcore-service-supervisor'
45
+ || record.pid !== Number(match[1])
46
+ || typeof record.startedAt !== 'number'
47
+ || !Number.isInteger(record.port))
48
+ continue;
49
+ output.push({
50
+ pid: record.pid,
51
+ startedAt: record.startedAt,
52
+ port: record.port,
53
+ ...(typeof record.configHash === 'string' ? { configHash: record.configHash } : {}),
54
+ filePath,
55
+ });
56
+ }
57
+ catch {
58
+ // Ignore partially written records until the next reconciliation.
59
+ }
60
+ }
61
+ return output;
62
+ }
63
+ async function tcpReady(port, timeoutMs) {
64
+ return await new Promise(resolve => {
65
+ const socket = net.createConnection({ host: '127.0.0.1', port });
66
+ const done = (ready) => {
67
+ socket.removeAllListeners();
68
+ socket.destroy();
69
+ resolve(ready);
70
+ };
71
+ const timer = setTimeout(() => done(false), timeoutMs);
72
+ timer.unref?.();
73
+ socket.once('connect', () => { clearTimeout(timer); done(true); });
74
+ socket.once('error', () => { clearTimeout(timer); done(false); });
75
+ });
76
+ }
77
+ async function checkHealth(service, pid) {
78
+ if (pid > 0 && !platform.isProcessRunning(pid))
79
+ return false;
80
+ if (!service.port)
81
+ return pid > 0;
82
+ if (pid > 0) {
83
+ const listeners = platform.findProcessByPort(service.port);
84
+ if (listeners.length > 0 && !listeners.includes(pid))
85
+ return false;
86
+ }
87
+ const health = service.health;
88
+ const timeoutMs = health?.timeoutMs ?? 1500;
89
+ if (health?.type === 'http') {
90
+ try {
91
+ const response = await fetch('http://127.0.0.1:' + service.port + (health.path ?? '/'), {
92
+ signal: AbortSignal.timeout(timeoutMs),
93
+ });
94
+ return response.ok;
95
+ }
96
+ catch {
97
+ return false;
98
+ }
99
+ }
100
+ return tcpReady(service.port, timeoutMs);
101
+ }
102
+ export class ServiceSupervisor {
103
+ log;
104
+ active = new Map();
105
+ desired = new Map();
106
+ stopped = false;
107
+ constructor(log = defaultLogger) {
108
+ this.log = log;
109
+ }
110
+ async start(services) {
111
+ this.stopped = false;
112
+ await this.reconcile(services);
113
+ }
114
+ async reconcile(services) {
115
+ if (this.stopped)
116
+ return;
117
+ const next = new Map(services.map(service => [service.name, service]));
118
+ for (const [name, active] of this.active) {
119
+ const desired = next.get(name);
120
+ if (!desired || desired.enabled !== true
121
+ || (desired.name === 'ecweb' && serviceRuntimeMode(desired) === 'managed')
122
+ || serviceRuntimeMode(desired) !== serviceRuntimeMode(active.config)) {
123
+ await this.stopEntry(active, true);
124
+ this.active.delete(name);
125
+ }
126
+ else if (serviceConfigHash(desired) !== active.configHash) {
127
+ active.config = desired;
128
+ active.configHash = serviceConfigHash(desired);
129
+ active.generation += 1;
130
+ if (serviceRuntimeMode(desired) === 'managed')
131
+ await this.restartEntry(active, 'service configuration changed');
132
+ else {
133
+ if (active.healthTimer)
134
+ clearTimeout(active.healthTimer);
135
+ active.healthTimer = undefined;
136
+ active.state = desired.port ? 'starting' : 'unknown';
137
+ void this.monitorHealth(active).finally(() => this.scheduleHealthCheck(active));
138
+ }
139
+ }
140
+ else {
141
+ const recoveryChanged = stableHash(active.config.runtime?.restart) !== stableHash(desired.runtime?.restart);
142
+ active.config = desired;
143
+ if (recoveryChanged && serviceRuntimeMode(desired) === 'managed') {
144
+ if (active.restartTimer)
145
+ clearTimeout(active.restartTimer);
146
+ active.restartTimer = undefined;
147
+ if (active.state === 'backoff')
148
+ active.state = 'failed';
149
+ if (active.state === 'failed')
150
+ this.scheduleRestart(active);
151
+ this.scheduleHealthCheck(active);
152
+ }
153
+ }
154
+ }
155
+ this.desired.clear();
156
+ for (const service of services)
157
+ this.desired.set(service.name, service);
158
+ for (const service of services) {
159
+ if (service.enabled !== true || this.active.has(service.name))
160
+ continue;
161
+ if (service.name === 'ecweb' && serviceRuntimeMode(service) === 'managed')
162
+ continue;
163
+ if (serviceRuntimeMode(service) === 'external') {
164
+ const active = {
165
+ config: service, process: null, pid: 0, startedAt: 0, recordPath: '',
166
+ configHash: serviceConfigHash(service), generation: 1, state: service.port ? 'starting' : 'unknown',
167
+ failureCount: 0, restartCount: 0, failures: [], healthFailures: 0, healthCheckInFlight: false,
168
+ intentionalStop: false, stopping: false,
169
+ };
170
+ this.active.set(service.name, active);
171
+ void this.monitorHealth(active).finally(() => this.scheduleHealthCheck(active));
172
+ continue;
173
+ }
174
+ const active = this.adoptOrCreate(service);
175
+ this.active.set(service.name, active);
176
+ if (active.state !== 'ready') {
177
+ void this.startEntry(active).catch(() => { });
178
+ }
179
+ else if (!active.healthy) {
180
+ void this.verifyAdopted(active);
181
+ }
182
+ }
183
+ }
184
+ async reload(name) {
185
+ return this.restartService(name);
186
+ }
187
+ async restartService(name) {
188
+ const active = this.active.get(name);
189
+ if (!active)
190
+ throw Object.assign(new Error('managed service is not running: ' + name), { code: 'SERVICE_NOT_RUNNING' });
191
+ if (active.config.runtime?.mode !== 'managed') {
192
+ throw Object.assign(new Error('external service lifecycle is not managed: ' + name), { code: 'EXTERNAL_SERVICE_UNMANAGED' });
193
+ }
194
+ await this.restartEntry(active, 'manual restart');
195
+ return this.snapshotOne(active);
196
+ }
197
+ async startService(name) {
198
+ const service = this.desired.get(name);
199
+ if (!service || service.runtime?.mode !== 'managed') {
200
+ throw Object.assign(new Error('service is not configured as managed: ' + name), { code: 'EXTERNAL_SERVICE_UNMANAGED' });
201
+ }
202
+ service.enabled = true;
203
+ this.desired.set(name, service);
204
+ let active = this.active.get(name);
205
+ if (!active) {
206
+ active = this.adoptOrCreate(service);
207
+ this.active.set(name, active);
208
+ }
209
+ await this.startEntry(active);
210
+ return this.snapshotOne(active);
211
+ }
212
+ async stopService(name) {
213
+ const active = this.active.get(name);
214
+ if (!active)
215
+ return { name, state: 'disabled', failureCount: 0, restartCount: 0, generation: 0, managed: false };
216
+ if (active.config.runtime?.mode !== 'managed') {
217
+ throw Object.assign(new Error('external service lifecycle is not managed: ' + name), { code: 'EXTERNAL_SERVICE_UNMANAGED' });
218
+ }
219
+ await this.stopEntry(active, true);
220
+ await active.startPromise?.catch(() => { });
221
+ this.active.delete(name);
222
+ return this.snapshotOne(active);
223
+ }
224
+ snapshot(name) {
225
+ return [...this.active.values()]
226
+ .filter(active => !name || active.config.name === name)
227
+ .map(active => this.snapshotOne(active))
228
+ .sort((a, b) => a.name.localeCompare(b.name));
229
+ }
230
+ async stop() {
231
+ if (this.stopped)
232
+ return;
233
+ this.stopped = true;
234
+ for (const active of [...this.active.values()]) {
235
+ await this.stopEntry(active, true);
236
+ await active.startPromise?.catch(() => { });
237
+ }
238
+ this.active.clear();
239
+ }
240
+ async clearFailure(name) {
241
+ const active = this.active.get(name);
242
+ if (!active)
243
+ throw Object.assign(new Error('managed service not found: ' + name), { code: 'NOT_FOUND' });
244
+ if (active.config.runtime?.mode !== 'managed') {
245
+ throw Object.assign(new Error('external service lifecycle is not managed: ' + name), { code: 'EXTERNAL_SERVICE_UNMANAGED' });
246
+ }
247
+ active.failures = [];
248
+ active.failureCount = 0;
249
+ active.retryExhausted = false;
250
+ active.lastError = undefined;
251
+ if (active.config.enabled === true && active.state !== 'ready')
252
+ await this.restartEntry(active, 'failure reset');
253
+ return this.snapshotOne(active);
254
+ }
255
+ async verifyAdopted(active) {
256
+ if (active.state !== 'starting' || !active.pid || !platform.isProcessRunning(active.pid))
257
+ return;
258
+ const generation = active.generation;
259
+ const healthy = await checkHealth(active.config, active.pid);
260
+ if (generation !== active.generation || active.stopping || this.stopped)
261
+ return;
262
+ active.checkedAt = Date.now();
263
+ active.healthy = healthy;
264
+ active.state = healthy ? 'ready' : 'failed';
265
+ if (!healthy) {
266
+ active.lastError = 'adopted service failed health check';
267
+ this.scheduleRestart(active);
268
+ }
269
+ else
270
+ this.scheduleHealthCheck(active);
271
+ }
272
+ adoptOrCreate(service) {
273
+ const hash = serviceConfigHash(service);
274
+ const records = readInstanceRecords(service.name);
275
+ const adopted = records
276
+ .filter(record => platform.isProcessRunning(record.pid)
277
+ && startTimeMatches(record.startedAt, getProcessStartTime(record.pid))
278
+ && record.configHash === hash)
279
+ .sort((a, b) => b.startedAt - a.startedAt)[0];
280
+ if (adopted) {
281
+ return {
282
+ config: service, process: null, pid: adopted.pid, startedAt: adopted.startedAt,
283
+ recordPath: adopted.filePath, configHash: hash, generation: 1, state: 'starting',
284
+ failureCount: 0, restartCount: 0, failures: [],
285
+ healthFailures: 0, healthCheckInFlight: false,
286
+ intentionalStop: false, stopping: false,
287
+ };
288
+ }
289
+ for (const record of records) {
290
+ if (platform.isProcessRunning(record.pid)
291
+ && startTimeMatches(record.startedAt, getProcessStartTime(record.pid))) {
292
+ this.log.warn('[ServiceSupervisor] refusing to adopt a managed process with a stale config hash: service=' + service.name);
293
+ try {
294
+ platform.killProcess(record.pid, true);
295
+ }
296
+ catch { }
297
+ try {
298
+ fs.unlinkSync(record.filePath);
299
+ }
300
+ catch { }
301
+ }
302
+ else {
303
+ try {
304
+ fs.unlinkSync(record.filePath);
305
+ }
306
+ catch { }
307
+ }
308
+ }
309
+ return {
310
+ config: service, process: null, pid: 0, startedAt: 0,
311
+ recordPath: '', configHash: hash, generation: 0, state: 'disabled',
312
+ failureCount: 0, restartCount: 0, failures: [],
313
+ healthFailures: 0, healthCheckInFlight: false,
314
+ intentionalStop: false, stopping: false,
315
+ };
316
+ }
317
+ async startEntry(active) {
318
+ if (this.stopped || active.stopping || active.startPromise)
319
+ return active.startPromise;
320
+ if (active.pid && platform.isProcessRunning(active.pid)) {
321
+ if (startTimeMatches(active.startedAt, getProcessStartTime(active.pid))) {
322
+ const healthy = await checkHealth(active.config, active.pid);
323
+ active.checkedAt = Date.now();
324
+ active.healthy = healthy;
325
+ if (healthy) {
326
+ active.state = 'ready';
327
+ this.scheduleHealthCheck(active);
328
+ return;
329
+ }
330
+ }
331
+ await this.stopEntry(active, false);
332
+ }
333
+ const command = active.config.runtime?.command;
334
+ if (!command)
335
+ throw Object.assign(new Error('managed service has no command: ' + active.config.name), { code: 'INVALID_CONFIG' });
336
+ if (active.config.name === 'evolcore'
337
+ || (command.file === process.execPath && process.argv[1]
338
+ && (command.args ?? []).some(argument => path.resolve(command.cwd ?? process.cwd(), argument) === path.resolve(process.argv[1])))) {
339
+ throw Object.assign(new Error('the current EvolCore daemon cannot be managed as a ServiceProxy service'), { code: 'SERVICE_PROTECTED' });
340
+ }
341
+ active.intentionalStop = false;
342
+ active.state = 'starting';
343
+ active.lastError = undefined;
344
+ const run = async () => {
345
+ const logDir = path.join(resolvePaths().logs, 'services');
346
+ fs.mkdirSync(logDir, { recursive: true });
347
+ const logPath = path.join(logDir, active.config.name + '.log');
348
+ const fd = fs.openSync(logPath, 'a');
349
+ let child;
350
+ try {
351
+ child = spawn(command.file, command.args ?? [], {
352
+ cwd: command.cwd,
353
+ detached: true,
354
+ stdio: ['ignore', fd, fd],
355
+ windowsHide: platform.isWindows,
356
+ env: { ...process.env },
357
+ });
358
+ }
359
+ catch (error) {
360
+ fs.closeSync(fd);
361
+ throw error;
362
+ }
363
+ fs.closeSync(fd);
364
+ active.process = child;
365
+ child.once('error', error => {
366
+ if (active.process !== child)
367
+ return;
368
+ active.lastError = error.message;
369
+ active.state = 'failed';
370
+ });
371
+ const pid = child.pid;
372
+ if (!pid)
373
+ throw Object.assign(new Error('failed to obtain PID for ' + active.config.name), { code: 'PROCESS_START_FAILED' });
374
+ active.pid = pid;
375
+ active.startedAt = getProcessStartTime(pid) ?? Date.now();
376
+ active.recordPath = recordPath(active.config.name, pid);
377
+ active.generation += 1;
378
+ child.once('exit', (code, signal) => {
379
+ if (active.process !== child)
380
+ return;
381
+ active.process = null;
382
+ try {
383
+ fs.unlinkSync(active.recordPath);
384
+ }
385
+ catch { }
386
+ active.pid = 0;
387
+ active.startedAt = 0;
388
+ if (active.healthTimer)
389
+ clearTimeout(active.healthTimer);
390
+ active.healthTimer = undefined;
391
+ active.healthy = false;
392
+ if (active.intentionalStop || active.stopping || this.stopped) {
393
+ active.state = 'disabled';
394
+ return;
395
+ }
396
+ active.lastError = 'process exited (code=' + (code ?? 'null') + ', signal=' + (signal ?? 'null') + ')';
397
+ active.state = 'failed';
398
+ this.scheduleRestart(active);
399
+ });
400
+ child.unref();
401
+ await this.waitForHealth(active);
402
+ if (active.stopping || this.stopped || !platform.isProcessRunning(pid))
403
+ return;
404
+ fs.mkdirSync(resolvePaths().instanceDir, { recursive: true });
405
+ atomicWriteJson(active.recordPath, {
406
+ owner: 'evolcore-service-supervisor',
407
+ pid,
408
+ startedAt: active.startedAt,
409
+ port: active.config.port ?? 0,
410
+ configHash: active.configHash,
411
+ });
412
+ active.state = 'ready';
413
+ this.scheduleHealthCheck(active);
414
+ this.log.info('[ServiceSupervisor] ready service=' + active.config.name + ' pid=' + pid);
415
+ };
416
+ active.startPromise = run().catch(async (error) => {
417
+ if (active.intentionalStop || this.stopped || error?.code === 'SERVICE_START_CANCELLED')
418
+ throw error;
419
+ active.lastError = error instanceof Error ? error.message : String(error);
420
+ if (!active.restartTimer)
421
+ active.state = 'failed';
422
+ this.log.warn('[ServiceSupervisor] start failed service=' + active.config.name + ': ' + active.lastError);
423
+ if (active.process?.pid)
424
+ await this.stopEntry(active, false);
425
+ this.scheduleRestart(active);
426
+ throw error;
427
+ }).finally(() => { active.startPromise = undefined; });
428
+ return active.startPromise;
429
+ }
430
+ async waitForHealth(active) {
431
+ const deadline = Date.now() + (active.config.health?.startupTimeoutMs ?? 45000);
432
+ const interval = SERVICE_HEALTH_INTERVALS[active.config.health?.type ?? 'tcp'].startup;
433
+ const generation = active.generation;
434
+ do {
435
+ if (generation !== active.generation || active.intentionalStop || this.stopped) {
436
+ throw Object.assign(new Error('service start cancelled: ' + active.config.name), { code: 'SERVICE_START_CANCELLED' });
437
+ }
438
+ if (active.stopping || this.stopped || !platform.isProcessRunning(active.pid)) {
439
+ throw Object.assign(new Error('service exited before ready: ' + active.config.name), { code: 'READINESS_TIMEOUT' });
440
+ }
441
+ if (active.config.port) {
442
+ const listeners = platform.findProcessByPort(active.config.port);
443
+ if (listeners.length > 0 && !listeners.includes(active.pid)) {
444
+ throw Object.assign(new Error('configured service port is owned by another process: ' + active.config.port), { code: 'PORT_IN_USE' });
445
+ }
446
+ }
447
+ const healthy = await checkHealth(active.config, active.pid);
448
+ if (generation !== active.generation || active.intentionalStop || this.stopped) {
449
+ throw Object.assign(new Error('service start cancelled: ' + active.config.name), { code: 'SERVICE_START_CANCELLED' });
450
+ }
451
+ if (healthy) {
452
+ active.healthy = true;
453
+ active.checkedAt = Date.now();
454
+ active.healthFailures = 0;
455
+ return;
456
+ }
457
+ await sleep(interval);
458
+ } while (Date.now() < deadline);
459
+ throw Object.assign(new Error('service readiness timed out: ' + active.config.name), { code: 'READINESS_TIMEOUT' });
460
+ }
461
+ async restartEntry(active, reason) {
462
+ active.generation += 1;
463
+ active.state = 'reloading';
464
+ this.log.info('[ServiceSupervisor] restart service=' + active.config.name + ' reason=' + reason);
465
+ await this.stopEntry(active, false);
466
+ await active.startPromise?.catch(() => { });
467
+ active.stopping = false;
468
+ await this.startEntry(active);
469
+ }
470
+ async stopEntry(active, intentional) {
471
+ active.intentionalStop = intentional;
472
+ active.stopping = true;
473
+ active.generation += 1;
474
+ active.state = 'stopping';
475
+ if (active.healthTimer)
476
+ clearTimeout(active.healthTimer);
477
+ active.healthTimer = undefined;
478
+ if (active.restartTimer)
479
+ clearTimeout(active.restartTimer);
480
+ active.restartTimer = undefined;
481
+ const pid = active.pid;
482
+ const expectedStartedAt = active.startedAt;
483
+ if (pid > 0 && platform.isProcessRunning(pid) && startTimeMatches(expectedStartedAt, getProcessStartTime(pid))) {
484
+ try {
485
+ platform.killProcessTree(pid, false);
486
+ }
487
+ catch { }
488
+ const exited = await platform.waitForProcessExit(pid, active.config.runtime?.stopTimeoutMs ?? 10000);
489
+ if (!exited && startTimeMatches(expectedStartedAt, getProcessStartTime(pid))) {
490
+ try {
491
+ platform.killProcessTree(pid, true);
492
+ }
493
+ catch { }
494
+ await platform.waitForProcessExit(pid, 5000);
495
+ }
496
+ }
497
+ if (active.recordPath) {
498
+ try {
499
+ fs.unlinkSync(active.recordPath);
500
+ }
501
+ catch { }
502
+ }
503
+ active.process = null;
504
+ active.pid = 0;
505
+ active.startedAt = 0;
506
+ active.healthy = false;
507
+ active.stopping = false;
508
+ active.state = intentional ? 'disabled' : 'starting';
509
+ }
510
+ scheduleRestart(active) {
511
+ if (this.stopped || active.intentionalStop || active.restartTimer || active.config.enabled !== true
512
+ || active.config.runtime?.mode !== 'managed')
513
+ return;
514
+ const restart = active.config.runtime?.restart;
515
+ if (restart?.enabled === false)
516
+ return;
517
+ if (active.retryExhausted)
518
+ return;
519
+ const now = Date.now();
520
+ active.failures = active.failures.filter(timestamp => now - timestamp <= SERVICE_RESTART_WINDOW_MS);
521
+ if (active.failures.length >= SERVICE_RESTART_MAX_ATTEMPTS) {
522
+ active.retryExhausted = true;
523
+ active.state = 'failed';
524
+ active.lastError = 'restart limit reached; use reset-failure before retrying';
525
+ this.log.error('[ServiceSupervisor] restart limit reached service=' + active.config.name);
526
+ return;
527
+ }
528
+ active.failures.push(now);
529
+ const base = restart?.backoffMs ?? SERVICE_RESTART_BACKOFF_MS;
530
+ const delay = base * (2 ** (active.failures.length - 1));
531
+ active.state = 'backoff';
532
+ active.failureCount = active.failures.length;
533
+ active.restartTimer = setTimeout(() => {
534
+ active.restartTimer = undefined;
535
+ active.restartCount += 1;
536
+ void this.restartEntry(active, 'automatic recovery').catch(() => { });
537
+ }, delay);
538
+ active.restartTimer.unref?.();
539
+ }
540
+ scheduleHealthCheck(active) {
541
+ if (this.stopped || active.intentionalStop || (!active.pid && serviceRuntimeMode(active.config) !== 'external') || active.healthTimer
542
+ || (active.state !== 'ready' && active.state !== 'failed'
543
+ && !(active.state === 'starting' && serviceRuntimeMode(active.config) === 'external')))
544
+ return;
545
+ const interval = SERVICE_HEALTH_INTERVALS[active.config.health?.type ?? 'tcp'].running;
546
+ active.healthTimer = setTimeout(() => {
547
+ active.healthTimer = undefined;
548
+ void this.monitorHealth(active).catch(error => {
549
+ this.log.warn('[ServiceSupervisor] health check failed service=' + active.config.name + ': ' + String(error));
550
+ }).finally(() => this.scheduleHealthCheck(active));
551
+ }, interval);
552
+ active.healthTimer.unref?.();
553
+ }
554
+ async monitorHealth(active) {
555
+ if (this.stopped || active.stopping || active.healthCheckInFlight
556
+ || (active.state !== 'ready' && active.state !== 'failed'
557
+ && !(active.state === 'starting' && serviceRuntimeMode(active.config) === 'external')))
558
+ return;
559
+ active.healthCheckInFlight = true;
560
+ const generation = active.generation;
561
+ try {
562
+ const healthy = (serviceRuntimeMode(active.config) === 'external'
563
+ || startTimeMatches(active.startedAt, getProcessStartTime(active.pid)))
564
+ && await checkHealth(active.config, active.pid);
565
+ if (generation !== active.generation || active.stopping || this.stopped)
566
+ return;
567
+ active.healthy = healthy;
568
+ active.checkedAt = Date.now();
569
+ if (active.healthy) {
570
+ active.healthFailures = 0;
571
+ active.state = 'ready';
572
+ return;
573
+ }
574
+ active.healthFailures += 1;
575
+ const threshold = active.config.health?.failureThreshold ?? 3;
576
+ if (active.healthFailures < threshold)
577
+ return;
578
+ if (!active.retryExhausted)
579
+ active.lastError = 'health check failed ' + active.healthFailures + ' consecutive times';
580
+ active.state = 'failed';
581
+ this.scheduleRestart(active);
582
+ }
583
+ finally {
584
+ active.healthCheckInFlight = false;
585
+ }
586
+ }
587
+ snapshotOne(active) {
588
+ return {
589
+ name: active.config.name,
590
+ state: active.state,
591
+ ...(active.pid ? { pid: active.pid } : {}),
592
+ ...(active.config.port ? { port: active.config.port } : {}),
593
+ ...(active.startedAt ? { startedAt: active.startedAt } : {}),
594
+ ...(active.healthy === undefined ? {} : { healthy: active.healthy }),
595
+ ...(active.checkedAt ? { checkedAt: active.checkedAt } : {}),
596
+ failureCount: active.failureCount,
597
+ restartCount: active.restartCount,
598
+ ...(active.lastError ? { lastError: active.lastError } : {}),
599
+ generation: active.generation,
600
+ managed: active.config.runtime?.mode === 'managed',
601
+ };
602
+ }
603
+ }
@@ -152,6 +152,14 @@ function settleRound(state) {
152
152
  state.roundPending = 0;
153
153
  state.roundCounter = state.roundHasIntentSuccess ? 0 : state.roundCounter + 1;
154
154
  }
155
+ /** 每个模型返回最多计一次熔断违规;同轮的批量工具拒绝共享这次计数。 */
156
+ function recordRoundViolation(state) {
157
+ if (!state.roundViolationCounted) {
158
+ state.roundViolationCounted = true;
159
+ state.violationCount++;
160
+ }
161
+ return state.violationCount;
162
+ }
155
163
  /**
156
164
  * 进入一轮。turn 为 runner 提供的模型返回序号:
157
165
  * - 有 turn:同一 turn 视为同一轮;turn 变化时先结算上一轮
@@ -179,6 +187,7 @@ function beginRound(state, turn) {
179
187
  state.roundHasIntentAttempt = false;
180
188
  state.roundHasIntentSuccess = false;
181
189
  state.roundWarned = false;
190
+ state.roundViolationCounted = false;
182
191
  }
183
192
  /** 新输入(新消息、插入消息、队列合并、续跑、任务恢复)到来:计数重置为初值 */
184
193
  export function resetIntentCounter(state) {
@@ -222,6 +231,7 @@ function buildState(message, cfg) {
222
231
  roundHasIntentAttempt: false,
223
232
  roundHasIntentSuccess: false,
224
233
  roundWarned: false,
234
+ roundViolationCounted: false,
225
235
  };
226
236
  }
227
237
  function normalizedThread(threadId) {
@@ -371,9 +381,9 @@ export const proactiveFlow = {
371
381
  // 非 send 命令:先检查格式是否"像 send 但解析失败"(F2修复:计入违规)
372
382
  const sendFailure = ctx.describeSendCommandFailure?.(toolName, toolInput);
373
383
  if (sendFailure) {
374
- state.violationCount++;
375
- if (state.violationCount >= VIOLATION_CIRCUIT_BREAK_THRESHOLD) {
376
- return { block: true, policyCode: 'proactive_circuit_break', reason: `连续违规 ${state.violationCount} 次,任务已中断,请重新描述需求` };
384
+ const violationCount = recordRoundViolation(state);
385
+ if (violationCount >= VIOLATION_CIRCUIT_BREAK_THRESHOLD) {
386
+ return { block: true, policyCode: 'proactive_circuit_break', reason: `连续违规 ${violationCount} 次,任务已中断,请重新描述需求` };
377
387
  }
378
388
  return { block: true, policyCode: 'proactive_send_invalid', reason: sendFailure };
379
389
  }
@@ -391,9 +401,9 @@ export const proactiveFlow = {
391
401
  return undefined;
392
402
  }
393
403
  // 计数 ≥ 16:只放行意图表达,其他调用全部拒绝
394
- state.violationCount++;
395
- if (state.violationCount >= VIOLATION_CIRCUIT_BREAK_THRESHOLD) {
396
- return { block: true, policyCode: 'proactive_circuit_break', reason: `连续违规 ${state.violationCount} 次,任务已中断,请重新描述需求` };
404
+ const violationCount = recordRoundViolation(state);
405
+ if (violationCount >= VIOLATION_CIRCUIT_BREAK_THRESHOLD) {
406
+ return { block: true, policyCode: 'proactive_circuit_break', reason: `连续违规 ${violationCount} 次,任务已中断,请重新描述需求` };
397
407
  }
398
408
  return {
399
409
  block: true,
@@ -723,6 +723,20 @@ export function killProcess(pid, force = false) {
723
723
  return !isProcessRunning(pid);
724
724
  }
725
725
  }
726
+ /** Terminate a detached process group where supported, falling back to one PID. */
727
+ export function killProcessTree(pid, force = false) {
728
+ if (!Number.isInteger(pid) || pid <= 0)
729
+ return false;
730
+ if (isWindows)
731
+ return killProcess(pid, force);
732
+ try {
733
+ process.kill(-pid, force ? 'SIGKILL' : 'SIGTERM');
734
+ return true;
735
+ }
736
+ catch {
737
+ return killProcess(pid, force);
738
+ }
739
+ }
726
740
  /** Wait until a process has really disappeared from the host process table. */
727
741
  export async function waitForProcessExit(pid, timeoutMs = 10_000, intervalMs = 250) {
728
742
  const deadline = Date.now() + timeoutMs;