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
@@ -1,12 +1,14 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { spawn } from 'child_process';
4
- import { getPackageRoot, isDevMode, resolvePaths } from '../paths.js';
4
+ import { isDevMode, resolvePaths } from '../paths.js';
5
+ import { SERVICE_HEALTH_INTERVALS, SERVICE_RESTART_BACKOFF_MS, SERVICE_RESTART_MAX_ATTEMPTS, SERVICE_RESTART_WINDOW_MS, } from '../config/daemon-services.js';
5
6
  import { WEB_PACKAGE_NAME } from '../product.js';
6
7
  import { resolveGlobalPkg } from './npm-ops.js';
7
8
  import { ecwebVersionRequirementError, resolveEcwebLaunchCommand } from './ecweb-utils.js';
8
9
  import * as platform from './cross-platform.js';
9
- import { getProcessStartTime } from './process-introspect.js';
10
+ import { getProcessStartTime, startTimeMatches } from './process-introspect.js';
11
+ import { matchesEcwebInstanceHealth, parseEcwebInstanceRecord } from '../contracts/ecweb-instance.js';
10
12
  const INSTANCE_FILE_RE = /^(?:ecweb|watch-web)-\d+\.json$/;
11
13
  function sleep(ms) {
12
14
  return new Promise(resolve => setTimeout(resolve, ms));
@@ -37,17 +39,9 @@ function readEntries() {
37
39
  continue;
38
40
  const filePath = path.join(dir, file);
39
41
  try {
40
- const value = JSON.parse(fs.readFileSync(filePath, 'utf8'));
41
- if (Number.isInteger(value.pid) && value.pid > 0) {
42
- entries.push({
43
- filePath,
44
- record: {
45
- pid: value.pid,
46
- port: Number.isInteger(value.port) ? value.port : 42705,
47
- ...(typeof value.startedAt === 'number' ? { startedAt: value.startedAt } : {}),
48
- },
49
- });
50
- }
42
+ const record = parseEcwebInstanceRecord(JSON.parse(fs.readFileSync(filePath, 'utf8')), resolvePaths().root, file);
43
+ if (record)
44
+ entries.push({ filePath, record });
51
45
  }
52
46
  catch {
53
47
  // A partially-written instance file is ignored until the next check.
@@ -67,17 +61,14 @@ function removeEntriesForPid(pid) {
67
61
  removeEntry(entry);
68
62
  }
69
63
  }
70
- async function probe(port) {
64
+ async function probe(record) {
71
65
  try {
72
- const response = await fetch(`http://127.0.0.1:${port}/api/health`, {
66
+ const response = await fetch(`http://127.0.0.1:${record.port}/api/health`, {
73
67
  signal: AbortSignal.timeout(1500),
74
68
  });
75
69
  if (!response.ok)
76
70
  return false;
77
- const health = await response.json();
78
- return health.ok === true
79
- && health.service === 'ecweb'
80
- && health.daemonProtocolCompatible === true;
71
+ return matchesEcwebInstanceHealth(await response.json(), record);
81
72
  }
82
73
  catch {
83
74
  return false;
@@ -93,15 +84,29 @@ async function probe(port) {
93
84
  */
94
85
  export function createEcwebSupervisor(options) {
95
86
  const failureThreshold = Math.max(1, options.failureThreshold ?? 3);
96
- const checkIntervalMs = Math.max(1000, options.checkIntervalMs ?? 5000);
87
+ let desiredPort = options.port;
88
+ let desiredEnabled = options.enabled ?? true;
89
+ let runtimeMode = options.runtimeMode ?? 'managed';
90
+ let restartConfig = options.restart;
97
91
  let active = null;
98
92
  let child = null;
99
93
  let logFd = null;
100
94
  let timer = null;
101
95
  let failureCount = 0;
96
+ let healthy = false;
102
97
  let startInFlight = null;
103
98
  let childStartedAt = 0;
104
99
  let stopping = false;
100
+ let checkInFlight = null;
101
+ let startup = null;
102
+ let restartInFlight = null;
103
+ let recoveryTimer = null;
104
+ let recoveryAttempts = [];
105
+ let recoveryExhausted = false;
106
+ let intentionalStop = false;
107
+ let launchRequested = false;
108
+ let hasBeenReady = false;
109
+ let configureQueue = Promise.resolve();
105
110
  const logFile = path.join(resolvePaths().logs, 'ecweb-daemon.log');
106
111
  const setActiveFromEntry = (entry, owned) => {
107
112
  active = {
@@ -120,7 +125,15 @@ export function createEcwebSupervisor(options) {
120
125
  removeEntry(entry);
121
126
  continue;
122
127
  }
123
- if (await probe(entry.record.port))
128
+ const actual = getProcessStartTime(entry.record.pid);
129
+ if (actual !== null && entry.record.startedAt !== undefined
130
+ && (entry.record.schemaVersion === 1 ? Math.abs(actual - entry.record.startedAt) >= 2000 : actual - entry.record.startedAt > 2000)) {
131
+ removeEntry(entry);
132
+ continue;
133
+ }
134
+ if (entry.record.port !== desiredPort)
135
+ continue;
136
+ if (await probe(entry.record))
124
137
  return entry;
125
138
  }
126
139
  return null;
@@ -133,7 +146,7 @@ export function createEcwebSupervisor(options) {
133
146
  return found;
134
147
  if (Date.now() >= deadline)
135
148
  break;
136
- await sleep(250);
149
+ await sleep(SERVICE_HEALTH_INTERVALS.http.startup);
137
150
  } while (!stopping);
138
151
  return null;
139
152
  };
@@ -147,6 +160,7 @@ export function createEcwebSupervisor(options) {
147
160
  logFd = null;
148
161
  };
149
162
  const killActive = async () => {
163
+ intentionalStop = true;
150
164
  const current = active;
151
165
  if (!current) {
152
166
  // During the short window between spawn() and ECWeb writing its
@@ -160,15 +174,15 @@ export function createEcwebSupervisor(options) {
160
174
  catch { }
161
175
  await platform.waitForProcessExit(pendingPid, 5000);
162
176
  }
177
+ child = null;
178
+ healthy = false;
163
179
  return;
164
180
  }
165
181
  const actual = getProcessStartTime(current.pid);
166
182
  // Never kill a reused PID. `startedAt` was captured from the live process
167
183
  // when it was adopted/spawned, so this remains safe even for legacy records
168
184
  // whose on-disk timestamp used a different clock.
169
- const sameProcess = current.startedAt !== null && actual !== null
170
- ? current.startedAt === actual
171
- : false;
185
+ const sameProcess = current.startedAt !== null && startTimeMatches(current.startedAt, actual);
172
186
  if (sameProcess && platform.isProcessRunning(current.pid)) {
173
187
  try {
174
188
  platform.killProcess(current.pid, true);
@@ -178,12 +192,16 @@ export function createEcwebSupervisor(options) {
178
192
  }
179
193
  removeEntriesForPid(current.pid);
180
194
  active = null;
195
+ child = null;
196
+ healthy = false;
181
197
  };
182
198
  const spawnEcweb = async () => {
199
+ intentionalStop = false;
200
+ hasBeenReady = false;
183
201
  const root = resolvePaths().root;
184
202
  const localEntry = path.join(root, 'ecweb', 'dist', 'index.js');
185
203
  const globalPkg = resolveGlobalPkg(WEB_PACKAGE_NAME);
186
- let launch = resolveEcwebLaunchCommand(['--home', root, '--port', String(options.port)], {
204
+ let launch = resolveEcwebLaunchCommand(['--home', root, '--port', String(desiredPort)], {
187
205
  installedPkg: globalPkg,
188
206
  });
189
207
  let cwd = root;
@@ -194,7 +212,7 @@ export function createEcwebSupervisor(options) {
194
212
  if (!launch && isDevMode() && fs.existsSync(localEntry)) {
195
213
  launch = {
196
214
  command: process.execPath,
197
- args: [localEntry, '--home', root, '--port', String(options.port)],
215
+ args: [localEntry, '--home', root, '--port', String(desiredPort)],
198
216
  entry: localEntry,
199
217
  source: 'package-bin',
200
218
  };
@@ -206,11 +224,15 @@ export function createEcwebSupervisor(options) {
206
224
  }
207
225
  if (!launch) {
208
226
  options.logger.warn('ECWeb 启动入口不存在,请重新安装包含匹配 ECWeb 的 EvolCore 版本。');
227
+ failureCount = failureThreshold;
228
+ scheduleRecovery();
209
229
  return;
210
230
  }
211
231
  const versionError = ecwebVersionRequirementError(version);
212
232
  if (versionError) {
213
233
  options.logger.error(`ECWeb 未启动: ${versionError}`);
234
+ failureCount = failureThreshold;
235
+ scheduleRecovery();
214
236
  return;
215
237
  }
216
238
  fs.mkdirSync(resolvePaths().logs, { recursive: true });
@@ -227,14 +249,9 @@ export function createEcwebSupervisor(options) {
227
249
  detached: true,
228
250
  stdio: ['ignore', childLogFd, childLogFd],
229
251
  windowsHide: platform.isWindows,
230
- // Keep the runtime home and package root aligned with this daemon.
231
- // The service protocol is the runtime boundary; package-root pinning
232
- // remains useful for development-only compatibility code and static
233
- // asset resolution.
234
252
  env: {
235
253
  ...process.env,
236
254
  EVOLCORE_HOME: root,
237
- EVOLCORE_PACKAGE_ROOT: getPackageRoot(),
238
255
  EVOLCORE_ECWEB_SUPERVISED: '1',
239
256
  },
240
257
  });
@@ -242,6 +259,8 @@ export function createEcwebSupervisor(options) {
242
259
  catch (error) {
243
260
  closeLogStream();
244
261
  options.logger.error(`ECWeb 子进程创建失败: ${error?.message || error}`);
262
+ failureCount = failureThreshold;
263
+ scheduleRecovery();
245
264
  return;
246
265
  }
247
266
  closeLogStream();
@@ -249,16 +268,23 @@ export function createEcwebSupervisor(options) {
249
268
  childStartedAt = Date.now();
250
269
  spawned.once('error', (error) => {
251
270
  options.logger.error(`ECWeb 子进程创建失败: ${error.message}`);
271
+ if (child !== spawned || intentionalStop || stopping)
272
+ return;
273
+ failureCount = failureThreshold;
274
+ scheduleRecovery();
252
275
  });
253
276
  spawned.once('exit', (code, signal) => {
254
277
  options.logger.warn(`ECWeb 进程退出 (PID: ${spawned.pid ?? 'unknown'}, code=${code ?? 'null'}, signal=${signal ?? 'null'})`);
255
278
  if (child === spawned) {
256
279
  child = null;
257
280
  childStartedAt = 0;
258
- }
259
- if (!stopping) {
260
- active = null;
261
- failureCount = failureThreshold;
281
+ healthy = false;
282
+ if (!stopping && !intentionalStop) {
283
+ if (active?.pid === spawned.pid)
284
+ active = null;
285
+ failureCount = failureThreshold;
286
+ scheduleRecovery();
287
+ }
262
288
  }
263
289
  closeLogStream();
264
290
  });
@@ -275,79 +301,228 @@ export function createEcwebSupervisor(options) {
275
301
  // latency while ServiceProxy continues to wait for the instance file.
276
302
  };
277
303
  const ensureRunning = async () => {
278
- if (stopping || startInFlight)
304
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed' || startInFlight)
279
305
  return;
280
- // A supervised ECWeb waits for daemon IPC before it binds and writes its
281
- // instance record. Do not mistake that startup window for a crashed
282
- // service and spawn a second child. The child is still subject to a hard
283
- // timeout so a permanently stuck handshake is eventually replaced.
284
- if (child?.pid && platform.isProcessRunning(child.pid)) {
285
- if (Date.now() - childStartedAt < 45_000)
286
- return;
287
- }
288
- const healthy = await findHealthyInstance();
289
- if (healthy) {
290
- const changed = !active || active.pid !== healthy.record.pid || active.port !== healthy.record.port;
291
- setActiveFromEntry(healthy, active?.pid === healthy.record.pid ? active.owned : false);
306
+ // Allow the child to bind and publish its instance record before treating
307
+ // it as crashed. Daemon readiness is not required for HTTP liveness.
308
+ const instance = await findHealthyInstance();
309
+ healthy = instance !== null;
310
+ if (instance) {
311
+ launchRequested = false;
312
+ cancelRecovery();
313
+ const changed = !active || active.pid !== instance.record.pid || active.port !== instance.record.port;
314
+ setActiveFromEntry(instance, active?.pid === instance.record.pid ? active.owned : false);
292
315
  failureCount = 0;
316
+ hasBeenReady = true;
293
317
  if (changed)
294
- options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${healthy.record.pid}, 端口: ${healthy.record.port})`);
318
+ options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${instance.record.pid}, 端口: ${instance.record.port})`);
319
+ return;
320
+ }
321
+ if (!launchRequested && !hasBeenReady && child?.pid && platform.isProcessRunning(child.pid)
322
+ && Date.now() - childStartedAt < 45_000)
323
+ return;
324
+ if (launchRequested) {
325
+ launchRequested = false;
326
+ startInFlight = (async () => {
327
+ await killActive();
328
+ await spawnEcweb();
329
+ })().finally(() => { startInFlight = null; });
330
+ await startInFlight;
295
331
  return;
296
332
  }
297
333
  failureCount += 1;
298
334
  if (failureCount < failureThreshold)
299
335
  return;
300
- // A manual `ec watch web` may be between killing the old process and
301
- // registering the replacement. Re-scan immediately before spawning.
302
- const replacement = await waitForHealthyInstance(1500);
303
- if (replacement) {
304
- setActiveFromEntry(replacement, false);
305
- failureCount = 0;
336
+ scheduleRecovery();
337
+ };
338
+ const check = () => {
339
+ if (checkInFlight)
340
+ return checkInFlight;
341
+ checkInFlight = ensureRunning().finally(() => { checkInFlight = null; });
342
+ return checkInFlight;
343
+ };
344
+ const cancelRecovery = () => {
345
+ if (recoveryTimer)
346
+ clearTimeout(recoveryTimer);
347
+ recoveryTimer = null;
348
+ };
349
+ const scheduleRecovery = () => {
350
+ if (stopping || intentionalStop || !desiredEnabled || runtimeMode !== 'managed'
351
+ || restartConfig?.enabled === false || recoveryTimer || recoveryExhausted)
352
+ return;
353
+ const now = Date.now();
354
+ recoveryAttempts = recoveryAttempts.filter(timestamp => now - timestamp <= SERVICE_RESTART_WINDOW_MS);
355
+ if (recoveryAttempts.length >= SERVICE_RESTART_MAX_ATTEMPTS) {
356
+ recoveryExhausted = true;
357
+ options.logger.error('ECWeb 自动恢复已达到 15 分钟内 3 次上限,请修复后 reset-failure');
306
358
  return;
307
359
  }
308
- startInFlight = (async () => {
360
+ recoveryAttempts.push(now);
361
+ const delay = (restartConfig?.backoffMs ?? SERVICE_RESTART_BACKOFF_MS) * (2 ** (recoveryAttempts.length - 1));
362
+ recoveryTimer = setTimeout(() => {
363
+ recoveryTimer = null;
364
+ if (stopping || !desiredEnabled || runtimeMode !== 'managed' || restartConfig?.enabled === false)
365
+ return;
366
+ launchRequested = true;
367
+ void check().catch(error => options.logger.error('ECWeb 自动恢复失败: ' + String(error)));
368
+ }, delay);
369
+ recoveryTimer.unref?.();
370
+ };
371
+ const restart = async () => {
372
+ if (runtimeMode !== 'managed')
373
+ throw Object.assign(new Error('ECWeb is external'), { code: 'EXTERNAL_SERVICE_UNMANAGED' });
374
+ if (!desiredEnabled || stopping)
375
+ throw Object.assign(new Error('ECWeb is disabled'), { code: 'SERVICE_NOT_ENABLED' });
376
+ if (restartInFlight)
377
+ return restartInFlight;
378
+ restartInFlight = (async () => {
379
+ cancelRecovery();
380
+ if (checkInFlight)
381
+ await checkInFlight.catch(() => { });
382
+ if (startInFlight)
383
+ await startInFlight.catch(() => { });
309
384
  await killActive();
310
- await spawnEcweb();
311
- failureCount = 0;
312
- })().finally(() => { startInFlight = null; });
313
- await startInFlight;
385
+ failureCount = failureThreshold;
386
+ launchRequested = true;
387
+ await check();
388
+ })().finally(() => { restartInFlight = null; });
389
+ return restartInFlight;
390
+ };
391
+ const scheduleCheck = () => {
392
+ if (stopping)
393
+ return;
394
+ const interval = active || hasBeenReady ? SERVICE_HEALTH_INTERVALS.http.running : SERVICE_HEALTH_INTERVALS.http.startup;
395
+ timer = setTimeout(() => {
396
+ timer = null;
397
+ void check().catch((error) => {
398
+ options.logger.error(`ECWeb watchdog 检查失败: ${error?.message || error}`);
399
+ }).finally(scheduleCheck);
400
+ }, desiredEnabled && runtimeMode === 'managed' ? interval : SERVICE_HEALTH_INTERVALS.http.running);
401
+ timer.unref?.();
402
+ };
403
+ const start = async () => {
404
+ if (stopping)
405
+ return;
406
+ if (!desiredEnabled || runtimeMode !== 'managed') {
407
+ scheduleCheck();
408
+ return;
409
+ }
410
+ // Give an independently started ECWeb time to publish its instance record.
411
+ const existing = await waitForHealthyInstance(1_500);
412
+ if (stopping)
413
+ return;
414
+ if (existing) {
415
+ healthy = true;
416
+ hasBeenReady = true;
417
+ setActiveFromEntry(existing, false);
418
+ options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${existing.record.pid}, 端口: ${existing.record.port})`);
419
+ }
420
+ else {
421
+ failureCount = failureThreshold;
422
+ launchRequested = true;
423
+ await check();
424
+ }
425
+ if (stopping)
426
+ return;
427
+ scheduleCheck();
428
+ };
429
+ const configure = async (config) => {
430
+ if (stopping)
431
+ return;
432
+ const portChanged = config.port !== desiredPort;
433
+ const enabledChanged = config.enabled !== desiredEnabled;
434
+ const nextMode = config.runtimeMode ?? 'managed';
435
+ const modeChanged = nextMode !== runtimeMode;
436
+ const recoveryChanged = JSON.stringify(config.restart) !== JSON.stringify(restartConfig);
437
+ desiredEnabled = config.enabled;
438
+ desiredPort = config.port;
439
+ runtimeMode = nextMode;
440
+ restartConfig = config.restart;
441
+ if (!enabledChanged && !portChanged && !modeChanged && !recoveryChanged)
442
+ return;
443
+ cancelRecovery();
444
+ if (checkInFlight)
445
+ await checkInFlight.catch(() => { });
446
+ if (startInFlight)
447
+ await startInFlight.catch(() => { });
448
+ if (restartInFlight)
449
+ await restartInFlight.catch(() => { });
450
+ if (stopping)
451
+ return;
452
+ if (runtimeMode === 'external') {
453
+ child?.removeAllListeners();
454
+ child = null;
455
+ active = null;
456
+ healthy = false;
457
+ }
458
+ else if (enabledChanged || portChanged || modeChanged) {
459
+ await killActive();
460
+ recoveryAttempts = [];
461
+ recoveryExhausted = false;
462
+ failureCount = desiredEnabled ? failureThreshold : 0;
463
+ launchRequested = desiredEnabled;
464
+ if (desiredEnabled && !stopping)
465
+ await check();
466
+ }
467
+ else if (restartConfig?.enabled !== false && !healthy && failureCount >= failureThreshold) {
468
+ intentionalStop = false;
469
+ scheduleRecovery();
470
+ }
471
+ if (timer)
472
+ clearTimeout(timer);
473
+ timer = null;
474
+ scheduleCheck();
314
475
  };
315
476
  return {
316
- async start() {
317
- if (stopping)
318
- return;
319
- // CLI/restart-monitor writes the instance record before the daemon is
320
- // ready. Give that process enough time to bind before launching another.
321
- const existing = await waitForHealthyInstance(1_500);
322
- if (existing) {
323
- setActiveFromEntry(existing, false);
324
- options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${existing.record.pid}, 端口: ${existing.record.port})`);
325
- }
326
- else {
327
- failureCount = failureThreshold;
328
- await ensureRunning();
329
- }
330
- timer = setInterval(() => {
331
- void ensureRunning().catch((error) => {
332
- options.logger.error(`ECWeb watchdog 检查失败: ${error?.message || error}`);
333
- });
334
- }, checkIntervalMs);
335
- timer.unref?.();
477
+ start() {
478
+ if (!startup)
479
+ startup = start();
480
+ return startup;
481
+ },
482
+ configure(config) {
483
+ configureQueue = configureQueue.then(() => configure(config), () => configure(config));
484
+ return configureQueue;
485
+ },
486
+ restart,
487
+ async resetFailure() {
488
+ recoveryAttempts = [];
489
+ recoveryExhausted = false;
490
+ if (!healthy)
491
+ await restart();
492
+ },
493
+ status() {
494
+ const running = active && platform.isProcessRunning(active.pid);
495
+ const ready = running && healthy && active.port === desiredPort;
496
+ return {
497
+ enabled: desiredEnabled,
498
+ port: desiredPort,
499
+ state: !desiredEnabled ? 'disabled' : ready ? 'ready' : failureCount >= failureThreshold ? 'failed' : 'starting',
500
+ ...(running ? { pid: active.pid } : {}),
501
+ };
336
502
  },
337
503
  async stop() {
338
504
  if (stopping)
339
505
  return;
340
506
  stopping = true;
507
+ cancelRecovery();
341
508
  if (timer)
342
- clearInterval(timer);
509
+ clearTimeout(timer);
343
510
  timer = null;
511
+ if (startup)
512
+ await startup.catch(() => { });
513
+ if (checkInFlight)
514
+ await checkInFlight.catch(() => { });
515
+ if (restartInFlight)
516
+ await restartInFlight.catch(() => { });
517
+ await configureQueue.catch(() => { });
344
518
  if (startInFlight) {
345
519
  try {
346
520
  await startInFlight;
347
521
  }
348
522
  catch { }
349
523
  }
350
- await killActive();
524
+ if (runtimeMode === 'managed')
525
+ await killActive();
351
526
  if (child) {
352
527
  try {
353
528
  child.removeAllListeners();
@@ -565,11 +565,11 @@ function sandboxInitializationErrorMessage(error, prefix) {
565
565
  || /codex_sandbox_userns_disabled_by_apparmor/i.test(String(error?.message ?? ''))
566
566
  || (isCodexSandboxUserNamespaceFailure({ message: error?.message, stderr })
567
567
  && /apparmor_restrict_unprivileged_userns\s*=\s*1|apparmor/i.test([error?.message ?? '', ...stderr].join('\n')))) {
568
- return `${prefix}Codex Linux 沙箱无法创建 user namespace(${CODEX_SANDBOX_USER_NAMESPACE_DISABLED_BY_APPARMOR}),当前操作未执行;请让宿主为该 EvolCore/Codex 服务配置受限的 AppArmor 允许规则,或使用等价隔离后端。不要关闭沙箱或自动降级为全权限,并运行 ec diagnose 获取探针结果`;
568
+ return `${prefix}Codex Linux 内层沙箱无法创建 user namespace(${CODEX_SANDBOX_USER_NAMESPACE_DISABLED_BY_APPARMOR});已尝试保留 EvolCore 外层隔离重试,但重试仍未成功。请让宿主为该 EvolCore/Codex 服务配置受限的 AppArmor 允许规则,或运行 ec diagnose 获取探针结果`;
569
569
  }
570
570
  if (error?.code === CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE
571
571
  || isCodexSandboxUserNamespaceFailure({ message: error?.message, stderr })) {
572
- return `${prefix}Codex Linux 沙箱无法创建 user namespace(${CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE}),当前操作未执行;请检查内核/AppArmor/容器策略并运行 ec diagnose。不会关闭沙箱或自动降级为全权限`;
572
+ return `${prefix}Codex Linux 内层沙箱无法创建 user namespace(${CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE});已尝试保留 EvolCore 外层隔离重试,但重试仍未成功。请检查内核/AppArmor/容器策略并运行 ec diagnose`;
573
573
  }
574
574
  if (diagnostic) {
575
575
  const target = /mkdir parents for/i.test(diagnostic) ? '挂载目标的父目录' : '挂载目标';
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import { resolvePaths } from '../paths.js';
3
3
  import { LogWriter } from './log-writer.js';
4
4
  import { normalizeToolErrorClassification } from '../core/permission/tool-error-code.js';
5
- import { normalizePermissionMode } from '../core/permission/mode.js';
5
+ import { normalizeExecutionPermissionMode } from '../core/permission/mode.js';
6
6
  import { buildToolLifecycleEventKey, normalizeToolCorrelation } from '../core/audit/event-key.js';
7
7
  let currentLevel = process.env.LOG_LEVEL || 'INFO';
8
8
  const LEVELS = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3 };
@@ -116,7 +116,7 @@ export function normalizeStructuredLog(data) {
116
116
  // `unknown` marker for records that genuinely arrived without context.
117
117
  const permissionMode = typeof rawPermissionMode === 'string'
118
118
  && rawPermissionMode !== 'unknown'
119
- ? normalizePermissionMode(rawPermissionMode).mode
119
+ ? normalizeExecutionPermissionMode(rawPermissionMode)
120
120
  : rawPermissionMode;
121
121
  const toolName = data.toolName ?? data.tool ?? data.name ?? nested?.toolName ?? nested?.name;
122
122
  const isError = data.isError ?? data.is_error ?? (data.ok === false ? true : undefined)
@@ -197,13 +197,32 @@ export function normalizeStructuredLog(data) {
197
197
  ...(missingContextFields.length > 0 ? { contextMissing: missingContextFields } : {}),
198
198
  };
199
199
  }
200
- export function localTimestamp() {
201
- const d = new Date();
200
+ export function localTimestamp(at = new Date()) {
201
+ const d = at;
202
202
  const pad = (n) => String(n).padStart(2, '0');
203
203
  const offset = -d.getTimezoneOffset();
204
204
  const zone = `${offset >= 0 ? '+' : '-'}${pad(Math.floor(Math.abs(offset) / 60))}:${pad(Math.abs(offset) % 60)}`;
205
205
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${String(d.getMilliseconds()).padStart(3, '0')}${zone}`;
206
206
  }
207
+ /**
208
+ * Give event logs one canonical record time. `ts` and `timestamp` are both
209
+ * the log write time; `eventTimestamp` preserves the producer's business
210
+ * timestamp when it was supplied, and `loggedAt` provides the numeric form.
211
+ */
212
+ export function normalizeEventLog(data, loggedAt = Date.now()) {
213
+ const normalized = normalizeStructuredLog(data);
214
+ const eventTimestamp = typeof normalized?.timestamp === 'number'
215
+ && Number.isFinite(normalized.timestamp)
216
+ ? normalized.timestamp
217
+ : undefined;
218
+ return {
219
+ ...normalized,
220
+ timestamp: loggedAt,
221
+ ts: localTimestamp(new Date(loggedAt)),
222
+ loggedAt,
223
+ ...(eventTimestamp !== undefined ? { eventTimestamp } : {}),
224
+ };
225
+ }
207
226
  function log(level, ...args) {
208
227
  if (!shouldLog(level))
209
228
  return;
@@ -238,7 +257,7 @@ export const logger = {
238
257
  const writer = getWriters().event;
239
258
  if (!writer)
240
259
  return;
241
- writer.write(JSON.stringify({ ts: localTimestamp(), ...normalizeStructuredLog(data) }));
260
+ writer.write(JSON.stringify(normalizeEventLog(data)));
242
261
  },
243
262
  menu: (data) => {
244
263
  // Menu has a deliberately compact domain schema. Do not expand it with
@@ -8,7 +8,8 @@ import { atomicReplaceJson, withFileLock } from './atomic-write.js';
8
8
  import { loadDaemonConfig } from '../config-store.js';
9
9
  export const VERSION_INFO_TTL_MS = 24 * 60 * 60 * 1000;
10
10
  export const VERSION_INFO_SCHEMA_VERSION = 2;
11
- export const VERSION_INFO_PACKAGES = [MAIN_PACKAGE_NAME, WEB_PACKAGE_NAME, '@agentunion/fastaun'];
11
+ const FASTAUN_PACKAGE_NAME = '@agentunion/fastaun';
12
+ export const VERSION_INFO_PACKAGES = [MAIN_PACKAGE_NAME, WEB_PACKAGE_NAME, FASTAUN_PACKAGE_NAME];
12
13
  export const AUTO_UPGRADE_PACKAGES = [MAIN_PACKAGE_NAME];
13
14
  export function resolveUpgradeDistTag() {
14
15
  return loadDaemonConfig().upgrade?.testPackages === true ? 'test' : 'latest';
@@ -157,7 +158,8 @@ async function checkPackage(name, force, options) {
157
158
  throw new Error('Unmanaged package');
158
159
  const now = options.now ?? Date.now();
159
160
  const at = new Date(now).toISOString();
160
- const distTag = options.distTag ?? resolveUpgradeDistTag();
161
+ const requestedDistTag = options.distTag ?? resolveUpgradeDistTag();
162
+ const distTag = name === FASTAUN_PACKAGE_NAME ? 'latest' : requestedDistTag;
161
163
  const selection = options.selection ?? (isLinkedInstall() && !options.includeUninstalled
162
164
  ? linkedInstallSelection
163
165
  : await resolveUpgradeRegistry(options.signal));
@@ -63,6 +63,15 @@ AUN keystore seed 由 EvolCore 使用固定应用值管理,不再提供配置
63
63
  - **群 @ 处理策略**:`mention_mode=disabled|mention-only` 是群级配置,只决定哪些群消息进入 Agent LLM 上下文,不影响 AUN 协议层投递;被过滤消息仍应本地存档。
64
64
  - **身份体系**:对端以 AID 标识,关系层 peerKey 形如 `aun#alice.aid.pub`。
65
65
 
66
+ ### 对端类型判定
67
+
68
+ 群与个人 AID 使用相同语法;数字、`g-`、`group.` 前缀都不证明主体类型。
69
+ 核心代码统一使用 `resolveAunTargetKind`,由可信会话路由、relation `targetKind`、同 AID 验签通过的
70
+ 名片类型提供证据。结果为 `private` / `group` / `unknown`,同时保留来源及缺失、冲突等原因。
71
+ 关系层 `readAunPeerKind` 只读取本地证据;`resolveAunPeerKind` 在缺少证据时拉取并验签名片。
72
+ 缺少或冲突的类型证据不能用于新增联系人或授予权限。迁移缺少类型证据且不涉及旧角色时会保留为 dormant 联系人;
73
+ 角色迁移或冲突类型缺少证据时会停止。任何情况下都不会按 AID 外形删除条目。
74
+
66
75
  ### 私聊最终回复标题
67
76
 
68
77
  AUN 私聊中,`result.text` 的 `isFinal=true` 会在 `payload.text` 正文前添加 `✅ 最终回复:`。AUN 文本客户端按正文展示,标题随 outbox 上下文持久化,断线恢复发送时仍保留。群聊、中间文本、命令回执及错误消息不自动添加该标题。
@@ -105,7 +105,7 @@ ec agent delete <aid> [--purge]
105
105
  - `ec agent welcome --text <text>` 用于保存 Bootstrap 中 Agent 自主准备的完整正式文案,不要求 Owner 起草、审稿或确认;命令固定写入当前 Agent 的 `$PERSONAL_DIR/welcome.md`,不接受自定义路径。`welcome show` 读取该文件。
106
106
  - welcome 托管写入要求当前 Agent 私聊 Owner;admin 仅可读。模板上限 4 KiB,渲染上限 8 KiB;变量为 `agentName`、`agentDescription`、`agentAid`、`agentTags`、`agentTagsText`、`ownerName`、`ownerAid`、`channel`,支持标签循环和真值条件。写入保留原始文本,投递不附加额外文案。
107
107
  - `agent show <target-aid>` 与 `agent get <target-aid> <key>` 的跨 Agent 读取对 owner/admin 开放,但普通 Agent 角色只获得安全摘要;敏感配置值和物理路径仅对 DaemonOwner 返回原值。跨 Agent 写入、启停、删除和 reload 仍遵循各自的目标与 DaemonOwner 权限边界。
108
- - Agent 配置可包含 `fullaccess.enabled`(默认关闭)。Menu 写入要求请求者同时是目标 Agent Owner 与 daemon Owner。私聊中 `/fa` 查询、`/fa on|off` 管理当前 EC 会话:主会话写 Agent 级开关,话题会话写自身 session metadata;`/fa <任务信息>` 或 `/fullaccess <任务信息>` 则由 daemon Owner 发起一次性 fullaccess 任务,不改变会话开关。群聊不支持。实际运行时逐次复核相应 Owner 授权、会话绑定和 Runner fullaccess 能力;Trigger 不会因该开关自动提权。
108
+ - Agent 配置可包含 `fullaccess.enabled`(默认关闭),作为全局开关;开启后对符合条件的私聊直接生效,局部 `/fa on|off` 不改变全局授权。Menu 写入全局开关要求请求者同时是目标 Agent Owner 与 daemon Owner。关闭全局开关时,私聊 `/fa on|off` 管理当前作用域:主会话写 relation 配置并跨 EC session/backend 续接保留,话题会话写自身 session metadata;`/fa <任务信息>` 或 `/fullaccess <任务信息>` 则由 daemon Owner 发起一次性 fullaccess 任务,不改变会话开关。群聊不支持。实际运行时逐次复核相应 Owner 授权、会话绑定和 Runner fullaccess 能力;Trigger 不会因该开关自动提权。
109
109
 
110
110
  ## 创建 Agent
111
111