evolcore 0.0.43-test.4 → 0.0.43-test.5

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 (129) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/bin/ecmsg.js +354 -91
  3. package/dist/agents/codex-runner.js +12 -17
  4. package/dist/aun/aid/agentmd.js +25 -0
  5. package/dist/aun/aid/control-aid.js +15 -0
  6. package/dist/aun/aid/identity.js +8 -0
  7. package/dist/aun/aid/ownership-operation.js +12 -3
  8. package/dist/channels/aun.js +30 -17
  9. package/dist/channels/daemon.js +2 -2
  10. package/dist/cli/agent-create.js +4 -2
  11. package/dist/cli/aid-bind-command.js +3 -0
  12. package/dist/cli/aun-commands.js +10 -3
  13. package/dist/cli/code-stats.js +451 -213
  14. package/dist/cli/ctl-command.js +1 -3
  15. package/dist/cli/daemon-commands.js +12 -3
  16. package/dist/cli/directory.js +3 -1
  17. package/dist/cli/ecmsg-gateway.js +204 -0
  18. package/dist/cli/index.js +6 -0
  19. package/dist/cli/init.js +45 -13
  20. package/dist/cli/provider-command.js +82 -5
  21. package/dist/cli/restart-monitor.js +11 -19
  22. package/dist/cli/stats.js +8 -1
  23. package/dist/cli/task-context.js +3 -0
  24. package/dist/config/boot-log.js +12 -1
  25. package/dist/config/config-manager.js +4 -13
  26. package/dist/config/daemon-services.js +1 -0
  27. package/dist/config/peer-role-resolver.js +5 -5
  28. package/dist/config/provider-identity-migration.js +202 -0
  29. package/dist/config/provider-identity.js +37 -0
  30. package/dist/config/provider-ipc-service.js +40 -3
  31. package/dist/config/provider-local-sync.js +153 -0
  32. package/dist/config/providers-config.js +32 -4
  33. package/dist/config/providers-management.js +144 -68
  34. package/dist/config/providers.js +4 -1
  35. package/dist/config/schema-migration.js +67 -3
  36. package/dist/core/agent-runtime.js +4 -2
  37. package/dist/core/auth/auth-gateway.js +5 -3
  38. package/dist/core/auth/delegation-diagnostics.js +6 -2
  39. package/dist/core/auth/operation-authorizer.js +3 -1
  40. package/dist/core/auth/operation-catalog.js +6 -4
  41. package/dist/core/command/cli-intent-parser.js +2 -1
  42. package/dist/core/command/command-handler.js +11 -6
  43. package/dist/core/command/menu-protocol.js +4 -2
  44. package/dist/core/command/provider-menu.js +4 -2
  45. package/dist/core/command/role-menu.js +2 -2
  46. package/dist/core/command/slash-handler.js +52 -16
  47. package/dist/core/handoff/runtime.js +9 -3
  48. package/dist/core/initialization/service.js +4 -3
  49. package/dist/core/message/aun-ipc-sender.js +81 -3
  50. package/dist/core/message/message-admission.js +2 -0
  51. package/dist/core/message/response-engine.js +23 -23
  52. package/dist/core/message/send-options.js +40 -0
  53. package/dist/core/message/send-routing.js +310 -0
  54. package/dist/core/ownership/owner-resolver.js +111 -8
  55. package/dist/core/permission/ec-command-parser.js +148 -15
  56. package/dist/core/permission/readonly-shell-query.js +66 -7
  57. package/dist/core/permission/tool-error-code.js +13 -1
  58. package/dist/core/permission/tool-policy.js +74 -20
  59. package/dist/core/relation/same-owner-proof.js +131 -0
  60. package/dist/core/session/session-idle-monitor.js +94 -16
  61. package/dist/core/session/session-manager.js +69 -16
  62. package/dist/core/thread/thread-route.js +5 -2
  63. package/dist/directory/owner-directory-cache.js +686 -97
  64. package/dist/directory/owner-directory-markdown.js +146 -36
  65. package/dist/directory/owner-directory-query-operation.js +2 -2
  66. package/dist/directory/owner-directory-scope.js +12 -0
  67. package/dist/directory/owner-directory-search.js +5 -1
  68. package/dist/directory/owner-directory-store.js +28 -0
  69. package/dist/ecweb/basic-settings-service.js +15 -1
  70. package/dist/ecweb/message-context-service.js +2 -2
  71. package/dist/ecweb/providers-service.js +3 -1
  72. package/dist/ecweb/runtime/lifecycle.js +18 -9
  73. package/dist/ecweb/runtime/supervisor.js +76 -24
  74. package/dist/index.js +4 -0
  75. package/dist/paths.js +2 -1
  76. package/dist/proxy/manager.js +2 -0
  77. package/dist/proxy/service-supervisor.js +2 -2
  78. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  79. package/dist/trigger/application-service.js +1 -0
  80. package/dist/trigger/event-source.js +4 -0
  81. package/dist/trigger/feedback.js +26 -2
  82. package/dist/trigger/scheduler.js +3 -3
  83. package/dist/trigger/system-definitions.js +2 -2
  84. package/dist/trigger/validation.js +4 -0
  85. package/dist/utils/autostart.js +2 -2
  86. package/dist/utils/cross-platform.js +36 -8
  87. package/dist/utils/public-suffix.js +5811 -0
  88. package/dist/utils/windows-autostart.js +41 -7
  89. package/ecagent/dist/harness/env/nodejs.js +46 -2
  90. package/kits/docs/aun/ABILITY_CALLING.md +3 -3
  91. package/kits/docs/channels/aun.md +1 -1
  92. package/kits/docs/channels/feishu.md +2 -2
  93. package/kits/docs/context-assembly.md +20 -4
  94. package/kits/docs/evolcore/INDEX.md +2 -1
  95. package/kits/docs/evolcore/agent.md +2 -2
  96. package/kits/docs/evolcore/aid.md +8 -2
  97. package/kits/docs/evolcore/ctl.md +13 -4
  98. package/kits/docs/evolcore/directory.md +48 -15
  99. package/kits/docs/evolcore/group.md +6 -6
  100. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  101. package/kits/docs/evolcore/menu-protocol.md +32 -3
  102. package/kits/docs/evolcore/msg.md +28 -27
  103. package/kits/docs/evolcore/provider.md +39 -5
  104. package/kits/docs/evolcore/response.md +1 -1
  105. package/kits/docs/evolcore/thread-chain.md +11 -13
  106. package/kits/docs/evolcore/tool-authorization.md +17 -0
  107. package/kits/docs/evolcore/trigger.md +2 -2
  108. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  109. package/kits/docs/prompt-loading-architecture.md +30 -20
  110. package/kits/eck_manifest.auxiliary.json +5 -5
  111. package/kits/eck_manifest.json +28 -28
  112. package/kits/eck_manifest.memory.json +18 -18
  113. package/kits/rules/01-overview.md +1 -1
  114. package/kits/rules/06-channel.md +3 -3
  115. package/kits/schemas/_meta.json +7 -1
  116. package/kits/schemas/providers.schema.2.json +74 -0
  117. package/kits/schemas/role-registry.schema.1.json +1 -1
  118. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  119. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  120. package/kits/skills/ec-trigger/SKILL.md +5 -5
  121. package/kits/skills/ec-trigger/references/examples.md +1 -1
  122. package/kits/templates/system-fragments/channel.md +5 -5
  123. package/kits/templates/system-fragments/commands.md +3 -2
  124. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  125. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  126. package/kits/templates/system-fragments/reply.md +47 -28
  127. package/kits/templates/system-fragments/session.md +2 -9
  128. package/kits/templates/system-fragments/thread.md +5 -5
  129. package/package.json +2 -3
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { spawn } from 'child_process';
4
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
+ import { SERVICE_HEALTH_INTERVALS, SERVICE_RESTART_BACKOFF_MS, SERVICE_RESTART_MAX_ATTEMPTS, SERVICE_RESTART_WINDOW_MS, SERVICE_STARTUP_TIMEOUT_MS, } from '../../config/daemon-services.js';
6
6
  import { WEB_PACKAGE_NAME } from '../../product.js';
7
7
  import { resolveGlobalPkg } from '../../utils/npm-ops.js';
8
8
  import { ecwebVersionRequirementError, resolveEcwebLaunchCommand } from './launch.js';
@@ -100,17 +100,20 @@ function removeEntriesForPid(pid) {
100
100
  removeEntry(entry);
101
101
  }
102
102
  }
103
- async function probe(record) {
103
+ async function probe(record, timeoutMs) {
104
+ const signal = AbortSignal.timeout(timeoutMs);
104
105
  try {
105
106
  const response = await fetch(`http://127.0.0.1:${record.port}/api/health`, {
106
- signal: AbortSignal.timeout(1500),
107
+ signal,
107
108
  });
108
109
  if (!response.ok)
109
- return false;
110
- return matchesEcwebInstanceHealth(await response.json(), record);
110
+ return { healthy: false, reason: `HTTP ${response.status}` };
111
+ return matchesEcwebInstanceHealth(await response.json(), record)
112
+ ? { healthy: true }
113
+ : { healthy: false, reason: '健康响应或实例身份不匹配' };
111
114
  }
112
115
  catch {
113
- return false;
116
+ return { healthy: false, reason: signal.aborted ? `健康请求超时 (${timeoutMs}ms)` : '健康请求失败或响应 JSON 无效' };
114
117
  }
115
118
  }
116
119
  /**
@@ -122,7 +125,8 @@ async function probe(record) {
122
125
  * ECWeb's own stale-instance cleanup, and daemon startup.
123
126
  */
124
127
  export function createEcwebSupervisor(options) {
125
- const failureThreshold = Math.max(1, options.failureThreshold ?? 3);
128
+ let healthConfig = options.health;
129
+ let failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
126
130
  let desiredPort = options.port;
127
131
  let desiredEnabled = options.enabled ?? true;
128
132
  let runtimeMode = options.runtimeMode ?? 'managed';
@@ -132,6 +136,7 @@ export function createEcwebSupervisor(options) {
132
136
  let logFd = null;
133
137
  let timer = null;
134
138
  let failureCount = 0;
139
+ let lastHealthFailure = '未发现有效的 ECWeb 实例注册';
135
140
  let healthy = false;
136
141
  let startInFlight = null;
137
142
  let childStartedAt = 0;
@@ -147,6 +152,7 @@ export function createEcwebSupervisor(options) {
147
152
  let recoveryAttempts = [];
148
153
  let recoveryExhausted = false;
149
154
  let intentionalStop = false;
155
+ const expectedChildExits = new WeakSet();
150
156
  let launchRequested = false;
151
157
  let hasBeenReady = false;
152
158
  let configureQueue = Promise.resolve();
@@ -172,21 +178,28 @@ export function createEcwebSupervisor(options) {
172
178
  };
173
179
  };
174
180
  const findHealthyInstance = async () => {
181
+ lastHealthFailure = '未发现有效的 ECWeb 实例注册';
175
182
  for (const entry of readEntries()) {
176
183
  if (!isAlive(entry.record)) {
184
+ lastHealthFailure = '实例进程不存在';
177
185
  removeEntry(entry);
178
186
  continue;
179
187
  }
180
188
  const actual = getProcessStartTime(entry.record.pid);
181
189
  if (actual !== null && entry.record.startedAt !== undefined
182
190
  && (entry.record.schemaVersion === 1 ? Math.abs(actual - entry.record.startedAt) >= 2000 : actual - entry.record.startedAt > 2000)) {
191
+ lastHealthFailure = '实例 PID 启动时间不匹配';
183
192
  removeEntry(entry);
184
193
  continue;
185
194
  }
186
- if (entry.record.port !== desiredPort)
195
+ if (entry.record.port !== desiredPort) {
196
+ lastHealthFailure = `实例端口与配置不匹配 (期望: ${desiredPort})`;
187
197
  continue;
188
- if (await probe(entry.record))
198
+ }
199
+ const result = await probe(entry.record, healthConfig?.timeoutMs ?? 1500);
200
+ if (result.healthy)
189
201
  return entry;
202
+ lastHealthFailure = result.reason;
190
203
  }
191
204
  return null;
192
205
  };
@@ -211,23 +224,44 @@ export function createEcwebSupervisor(options) {
211
224
  catch { }
212
225
  logFd = null;
213
226
  };
227
+ const stopTrackedProcess = (identity, onTiming) => {
228
+ const target = child?.pid === identity.pid ? child : null;
229
+ const requestShutdown = target?.connected ? () => {
230
+ try {
231
+ if (!target.connected)
232
+ return false;
233
+ // The callback handles an asynchronously closed channel without an
234
+ // unhandled child 'error' event. Exit confirmation remains separate.
235
+ target.send({ type: 'ecweb.shutdown' }, () => { });
236
+ return true;
237
+ }
238
+ catch {
239
+ return false;
240
+ }
241
+ } : undefined;
242
+ return stopEcwebProcess(identity, undefined, onTiming, requestShutdown);
243
+ };
214
244
  const killActive = async (onTiming) => {
215
245
  intentionalStop = true;
216
246
  const current = active;
247
+ // Keep stop intent with the child: its exit event may arrive after a
248
+ // replacement has reset the supervisor's intentionalStop flag.
249
+ if (child && (!current || child.pid === current.pid))
250
+ expectedChildExits.add(child);
217
251
  if (!current) {
218
252
  // During the short window between spawn() and ECWeb writing its
219
253
  // instance record there is no `active` entry yet, but the daemon still
220
254
  // owns the child and must not leave it behind on shutdown.
221
255
  const pendingPid = child?.pid;
222
256
  if (pendingPid && platform.isProcessRunning(pendingPid)) {
223
- await stopEcwebProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, undefined, onTiming);
257
+ await stopTrackedProcess({ pid: pendingPid, startedAt: childIdentityStartedAt }, onTiming);
224
258
  }
225
259
  child = null;
226
260
  childIdentityStartedAt = null;
227
261
  healthy = false;
228
262
  return;
229
263
  }
230
- await stopEcwebProcess({ pid: current.pid, startedAt: current.startedAt }, undefined, onTiming);
264
+ await stopTrackedProcess({ pid: current.pid, startedAt: current.startedAt }, onTiming);
231
265
  removeEntriesForPid(current.pid);
232
266
  active = null;
233
267
  child = null;
@@ -239,6 +273,7 @@ export function createEcwebSupervisor(options) {
239
273
  return;
240
274
  intentionalStop = false;
241
275
  hasBeenReady = false;
276
+ failureCount = 0;
242
277
  const root = resolvePaths().root;
243
278
  const localEntry = path.join(root, 'ecweb', 'dist', 'index.js');
244
279
  const globalPkg = resolveGlobalPkg(WEB_PACKAGE_NAME);
@@ -296,7 +331,7 @@ export function createEcwebSupervisor(options) {
296
331
  spawned = spawn(launch.command, launch.args, {
297
332
  cwd,
298
333
  detached: true,
299
- stdio: ['ignore', childLogFd, childLogFd],
334
+ stdio: ['ignore', childLogFd, childLogFd, 'ipc'],
300
335
  windowsHide: platform.isWindows,
301
336
  env: {
302
337
  ...process.env,
@@ -324,8 +359,13 @@ export function createEcwebSupervisor(options) {
324
359
  scheduleRecovery();
325
360
  });
326
361
  spawned.once('exit', (code, signal) => {
327
- options.logger.warn(`ECWeb 进程退出 (PID: ${spawned.pid ?? 'unknown'}, code=${code ?? 'null'}, signal=${signal ?? 'null'})`);
328
- const diagnostics = child === spawned ? readExitDiagnostics(logFile, childLogStartOffset) : undefined;
362
+ const expectedExit = stopping || expectedChildExits.has(spawned);
363
+ const exitMessage = `ECWeb 进程退出 (PID: ${spawned.pid ?? 'unknown'}, code=${code ?? 'null'}, signal=${signal ?? 'null'})`;
364
+ if (expectedExit)
365
+ options.logger.info(`${exitMessage},主动停止`);
366
+ else
367
+ options.logger.warn(exitMessage);
368
+ const diagnostics = !expectedExit && child === spawned ? readExitDiagnostics(logFile, childLogStartOffset) : undefined;
329
369
  if (diagnostics)
330
370
  options.logger.warn(`ECWeb 退出诊断(最近日志,含异常栈如有):\n${diagnostics}`);
331
371
  if (child === spawned) {
@@ -333,7 +373,7 @@ export function createEcwebSupervisor(options) {
333
373
  childStartedAt = 0;
334
374
  childIdentityStartedAt = null;
335
375
  healthy = false;
336
- if (!stopping && !intentionalStop) {
376
+ if (!expectedExit) {
337
377
  if (active?.pid === spawned.pid)
338
378
  active = null;
339
379
  failureCount = failureThreshold;
@@ -350,6 +390,7 @@ export function createEcwebSupervisor(options) {
350
390
  closeLogStream();
351
391
  });
352
392
  spawned.unref();
393
+ spawned.channel?.unref();
353
394
  if (!spawned.pid) {
354
395
  closeLogStream();
355
396
  options.logger.warn('ECWeb 启动失败:未取得子进程 PID');
@@ -388,9 +429,15 @@ export function createEcwebSupervisor(options) {
388
429
  return;
389
430
  }
390
431
  if (!launchRequested && !hasBeenReady && child?.pid && platform.isProcessRunning(child.pid)
391
- && Date.now() - childStartedAt < 45_000)
432
+ && Date.now() - childStartedAt < (healthConfig?.startupTimeoutMs ?? SERVICE_STARTUP_TIMEOUT_MS))
392
433
  return;
393
434
  if (launchRequested) {
435
+ // A successful probe above cancels recovery without spending a retry.
436
+ // Charge the allowance only when an automatic restart actually begins.
437
+ if (launchRequested === 'recovery') {
438
+ recoveryAttempts.push(Date.now());
439
+ options.logger.warn(`ECWeb 自动恢复执行 (尝试: ${recoveryAttempts.length}/${SERVICE_RESTART_MAX_ATTEMPTS}, PID: ${active?.pid ?? child?.pid ?? 'unknown'})`);
440
+ }
394
441
  launchRequested = false;
395
442
  startInFlight = (async () => {
396
443
  await killActive();
@@ -402,6 +449,8 @@ export function createEcwebSupervisor(options) {
402
449
  failureCount += 1;
403
450
  if (failureCount < failureThreshold)
404
451
  return;
452
+ if (failureCount === failureThreshold)
453
+ options.logger.warn(`ECWeb 健康检查未通过 (PID: ${active?.pid ?? child?.pid ?? 'unknown'}, 连续失败: ${failureCount}, 启动后: ${childStartedAt ? Date.now() - childStartedAt : 0}ms, 原因: ${lastHealthFailure})`);
405
454
  scheduleRecovery();
406
455
  };
407
456
  const check = () => {
@@ -417,7 +466,7 @@ export function createEcwebSupervisor(options) {
417
466
  };
418
467
  const scheduleRecovery = () => {
419
468
  if (stopping || intentionalStop || !desiredEnabled || runtimeMode !== 'managed'
420
- || restartConfig?.enabled === false || recoveryTimer || recoveryExhausted)
469
+ || restartConfig?.enabled === false || recoveryTimer || launchRequested || recoveryExhausted)
421
470
  return;
422
471
  const now = Date.now();
423
472
  recoveryAttempts = recoveryAttempts.filter(timestamp => now - timestamp <= SERVICE_RESTART_WINDOW_MS);
@@ -426,13 +475,13 @@ export function createEcwebSupervisor(options) {
426
475
  options.logger.error('ECWeb 自动恢复已达到 15 分钟内 3 次上限,请修复后 reset-failure');
427
476
  return;
428
477
  }
429
- recoveryAttempts.push(now);
430
- const delay = (restartConfig?.backoffMs ?? SERVICE_RESTART_BACKOFF_MS) * (2 ** (recoveryAttempts.length - 1));
478
+ const delay = (restartConfig?.backoffMs ?? SERVICE_RESTART_BACKOFF_MS) * (2 ** recoveryAttempts.length);
479
+ options.logger.warn(`ECWeb 自动恢复排期 (尝试: ${recoveryAttempts.length + 1}/${SERVICE_RESTART_MAX_ATTEMPTS}, 退避: ${delay}ms)`);
431
480
  recoveryTimer = setTimeout(() => {
432
481
  recoveryTimer = null;
433
482
  if (stopping || !desiredEnabled || runtimeMode !== 'managed' || restartConfig?.enabled === false)
434
483
  return;
435
- launchRequested = true;
484
+ launchRequested = 'recovery';
436
485
  void check().catch(error => options.logger.error('ECWeb 自动恢复失败: ' + String(error)));
437
486
  }, delay);
438
487
  recoveryTimer.unref?.();
@@ -456,7 +505,7 @@ export function createEcwebSupervisor(options) {
456
505
  if (stopping)
457
506
  return;
458
507
  failureCount = failureThreshold;
459
- launchRequested = true;
508
+ launchRequested = 'manual';
460
509
  await check();
461
510
  })().finally(() => { restartInFlight = null; });
462
511
  return restartInFlight;
@@ -495,7 +544,7 @@ export function createEcwebSupervisor(options) {
495
544
  }
496
545
  else {
497
546
  failureCount = failureThreshold;
498
- launchRequested = true;
547
+ launchRequested = 'manual';
499
548
  await check();
500
549
  }
501
550
  if (stopping)
@@ -510,11 +559,14 @@ export function createEcwebSupervisor(options) {
510
559
  const nextMode = config.runtimeMode ?? 'managed';
511
560
  const modeChanged = nextMode !== runtimeMode;
512
561
  const recoveryChanged = JSON.stringify(config.restart) !== JSON.stringify(restartConfig);
562
+ const healthChanged = JSON.stringify(config.health) !== JSON.stringify(healthConfig);
513
563
  desiredEnabled = config.enabled;
514
564
  desiredPort = config.port;
515
565
  runtimeMode = nextMode;
516
566
  restartConfig = config.restart;
517
- if (!enabledChanged && !portChanged && !modeChanged && !recoveryChanged)
567
+ healthConfig = config.health;
568
+ failureThreshold = Math.max(1, healthConfig?.failureThreshold ?? options.failureThreshold ?? 3);
569
+ if (!enabledChanged && !portChanged && !modeChanged && !recoveryChanged && !healthChanged)
518
570
  return;
519
571
  cancelRecovery();
520
572
  if (checkInFlight)
@@ -536,7 +588,7 @@ export function createEcwebSupervisor(options) {
536
588
  recoveryAttempts = [];
537
589
  recoveryExhausted = false;
538
590
  failureCount = desiredEnabled ? failureThreshold : 0;
539
- launchRequested = desiredEnabled;
591
+ launchRequested = desiredEnabled ? 'manual' : false;
540
592
  if (desiredEnabled && !stopping)
541
593
  await check();
542
594
  }
package/dist/index.js CHANGED
@@ -254,6 +254,7 @@ async function main() {
254
254
  enabled: ecwebConfig?.enabled === true,
255
255
  runtimeMode: ecwebConfig ? serviceRuntimeMode(ecwebConfig) : 'managed',
256
256
  restart: ecwebConfig?.runtime?.restart,
257
+ health: ecwebConfig?.health,
257
258
  logger,
258
259
  });
259
260
  onShutdown(() => ecwebSupervisor?.stop());
@@ -267,6 +268,7 @@ async function main() {
267
268
  port: service?.port ?? DEFAULT_ECWEB_PORT,
268
269
  runtimeMode: service ? serviceRuntimeMode(service) : 'managed',
269
270
  restart: service?.runtime?.restart,
271
+ health: service?.health,
270
272
  }).catch((error) => logger.warn(`ECWeb 配置热应用失败: ${error?.message || error}`));
271
273
  }
272
274
  catch (error) {
@@ -760,6 +762,8 @@ async function main() {
760
762
  messageQueue,
761
763
  responseEngine,
762
764
  sessionManager,
765
+ canDispatchSessionLoopOnce: (sessionId, requestId, generation) => (sessionIdleMonitor.isCurrentLoopOnceEvent(sessionId, requestId, generation)
766
+ && !messageQueue.isProcessing(sessionId) && messageQueue.getQueueLength(sessionId) === 0),
763
767
  targetSessionLocks,
764
768
  triggerAudit,
765
769
  triggerScriptExecutor,
package/dist/paths.js CHANGED
@@ -56,7 +56,8 @@ export function resolvePaths() {
56
56
  providersConfig: path.join(root, 'providers.json'),
57
57
  logs: path.join(root, 'logs'),
58
58
  agentsDir,
59
- lineStats: path.join(root, 'logs', 'line-stats.log'),
59
+ lineStats: path.join(root, 'logs', 'code-stats.json'),
60
+ lineStatsCache: path.join(root, 'logs', 'code-stats-cache.json'),
60
61
  readySignal: path.join(root, 'data', 'instance', 'ready.signal'),
61
62
  controlToken: path.join(root, 'data', 'instance', 'control.token'),
62
63
  /** 启动/停止阶段埋点记录(CLI 与 daemon 各写一行,按 traceId 关联) */
@@ -325,6 +325,7 @@ export class ServiceProxyManager {
325
325
  port: current.port ?? DEFAULT_ECWEB_PORT,
326
326
  runtimeMode: 'managed',
327
327
  restart: current.runtime?.restart,
328
+ health: current.health,
328
329
  });
329
330
  return { ok: true, ...result, operationId, jobId: operationId, state: 'completed', runtime: this.options.ecwebSupervisor.status() };
330
331
  }
@@ -402,6 +403,7 @@ export class ServiceProxyManager {
402
403
  port: ecweb?.port ?? DEFAULT_ECWEB_PORT,
403
404
  runtimeMode: ecweb ? serviceRuntimeMode(ecweb) : 'managed',
404
405
  restart: ecweb?.runtime?.restart,
406
+ health: ecweb?.health,
405
407
  });
406
408
  await this.supervisor.reconcile(services);
407
409
  if (this.stopped)
@@ -4,7 +4,7 @@ import path from 'node:path';
4
4
  import { spawn } from 'node:child_process';
5
5
  import crypto from 'node:crypto';
6
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';
7
+ import { SERVICE_HEALTH_INTERVALS, SERVICE_RESTART_BACKOFF_MS, SERVICE_RESTART_MAX_ATTEMPTS, SERVICE_RESTART_WINDOW_MS, SERVICE_STARTUP_TIMEOUT_MS, serviceRuntimeMode, } from '../config/daemon-services.js';
8
8
  import { getProcessStartTime, startTimeMatches } from '../utils/process-introspect.js';
9
9
  import * as platform from '../utils/cross-platform.js';
10
10
  import { logger as defaultLogger } from '../utils/logger.js';
@@ -587,7 +587,7 @@ export class ServiceSupervisor {
587
587
  await run();
588
588
  }
589
589
  async waitForHealth(active) {
590
- const deadline = Date.now() + (active.config.health?.startupTimeoutMs ?? 45000);
590
+ const deadline = Date.now() + (active.config.health?.startupTimeoutMs ?? SERVICE_STARTUP_TIMEOUT_MS);
591
591
  const interval = SERVICE_HEALTH_INTERVALS[active.config.health?.type ?? 'tcp'].startup;
592
592
  const generation = active.generation;
593
593
  do {
@@ -378,6 +378,10 @@ export const proactiveFlow = {
378
378
  state.roundHasIntentAttempt = true;
379
379
  return undefined;
380
380
  }
381
+ // 只读命令(--help 等)不受门禁限制:门禁防的是"光看不发",
382
+ // 查语法正是为了学会怎么发。拦它只会让模型反复试错直到熔断。
383
+ if (ctx.isReadOnlyCommand?.(toolName, toolInput))
384
+ return undefined;
381
385
  // 非 send 命令:先检查格式是否"像 send 但解析失败"(F2修复:计入违规)
382
386
  const sendFailure = ctx.describeSendCommandFailure?.(toolName, toolInput);
383
387
  if (sendFailure) {
@@ -113,6 +113,7 @@ export function buildTriggerScheduler(owner, dependencies, options = {}) {
113
113
  getChannel: dependencies.getTriggerChannel,
114
114
  sessionManager: dependencies.sessionManager,
115
115
  messageQueue: dependencies.messageQueue,
116
+ canDispatchSessionLoopOnce: dependencies.canDispatchSessionLoopOnce,
116
117
  recoverTask: request => dependencies.responseEngine.recoverTask(request),
117
118
  inspectTargetExecution: (sessionId, attemptId, selfAid) => (dependencies.responseEngine.inspectTargetExecution(sessionId, attemptId, selfAid)),
118
119
  eventBus: dependencies.eventBus,
@@ -38,6 +38,10 @@ export class TriggerEventSource {
38
38
  return;
39
39
  if (event.type.startsWith('trigger:') && event.originTriggerId === trigger.id)
40
40
  return;
41
+ if (event.type === 'session:idle' && event.loopOnceRequestId
42
+ && (trigger.id !== '__session-idle-check' || !isDaemonEventSessionTrigger(trigger)
43
+ || trigger.execution.type !== 'target_session'))
44
+ return;
41
45
  // Dynamic routing is agent-local for ordinary Agent Triggers. A
42
46
  // daemon-origin event_session Trigger is explicitly allowed to route
43
47
  // the event to the owning Agent discovered from the payload.
@@ -4,6 +4,7 @@ import { isDaemonEventSessionTrigger } from './event-source.js';
4
4
  import { TASK_RECOVERY_PROMPT } from '../core/task/task-recovery-service.js';
5
5
  import { ExecutionTimeoutError, OrphanedTargetSessionError, isRetryableError } from '../utils/error-utils.js';
6
6
  import { isTopicThreadId, sessionThreadKind, sessionTopicThreadId } from '../core/thread/topic-id.js';
7
+ import { readSessionLoopOnceConfig, resolveSessionLoopTarget } from '../core/session/session-idle-monitor.js';
7
8
  const FEEDBACK_DEADLINE_MS = 30_000;
8
9
  const TARGET_SESSION_CANCEL_GRACE_MS = 1_000;
9
10
  const TARGET_SESSION_OUTCOME_GRACE_MS = 5_000;
@@ -115,7 +116,17 @@ export class TriggerFeedbackDispatcher {
115
116
  || !Number.isSafeInteger(input.sourcePayload.generation))) {
116
117
  return this.failed(feedback, [], 'recovery_event_invalid', 'task:error must identify the original task and generation');
117
118
  }
118
- const prompt = isTaskErrorRecovery ? TASK_RECOVERY_PROMPT : input.prompt;
119
+ const loopOnceRequestId = input.sourcePayload?.type === 'session:idle'
120
+ && typeof input.sourcePayload.loopOnceRequestId === 'string'
121
+ ? input.sourcePayload.loopOnceRequestId : undefined;
122
+ const pendingLoop = eventSession && readSessionLoopOnceConfig(eventSession);
123
+ if (loopOnceRequestId && (!pendingLoop || pendingLoop.requestId !== loopOnceRequestId
124
+ || pendingLoop.peerId !== input.sourcePayload?.peerId
125
+ || (pendingLoop.encrypted !== undefined && pendingLoop.encrypted !== input.sourcePayload?.encrypted)
126
+ || input.trigger.id !== '__session-idle-check' || !isDaemonEventSessionTrigger(input.trigger))) {
127
+ return { status: 'skipped', reason: 'loop_once_stale', feedback, effects: [], error: null };
128
+ }
129
+ const prompt = isTaskErrorRecovery ? TASK_RECOVERY_PROMPT : loopOnceRequestId ? pendingLoop.prompt : input.prompt;
119
130
  const targetAgentAid = eventSession?.selfAID ?? input.trigger.agentAid;
120
131
  feedback.target = target;
121
132
  feedback.renderedTextHash = sha256(prompt);
@@ -276,7 +287,7 @@ export class TriggerFeedbackDispatcher {
276
287
  boundSessionId: session.id,
277
288
  modelOverride: input.trigger.execution.model,
278
289
  effortOverride: input.trigger.execution.effort,
279
- permissionModeOverride: input.trigger.execution.permissionMode,
290
+ permissionModeOverride: loopOnceRequestId ? undefined : input.trigger.execution.permissionMode,
280
291
  originPeerId: eventSession ? input.sourcePayload.peerId : input.trigger.origin?.peerId,
281
292
  originChannelKey: eventSession ? target.channelKey : input.trigger.origin?.channelKey,
282
293
  originChannelType: eventSession ? channelType : input.trigger.origin?.channelType
@@ -388,6 +399,19 @@ export class TriggerFeedbackDispatcher {
388
399
  enqueuePromise = recovery.completion;
389
400
  }
390
401
  else {
402
+ if (loopOnceRequestId) {
403
+ const latest = await this.deps.sessionManager.getSessionById(session.id);
404
+ const currentMain = sessionThreadKind(session).kind === 'main'
405
+ ? this.deps.sessionManager.getActiveSessionSync(session.channel, session.channelId) : undefined;
406
+ if (delivery.signal.aborted)
407
+ throw delivery.signal.reason;
408
+ if (!latest || !resolveSessionLoopTarget(latest) || latest.selfAID !== targetAgentAid
409
+ || (sessionThreadKind(session).kind === 'main' && currentMain?.id !== session.id)
410
+ || !this.deps.canDispatchSessionLoopOnce?.(session.id, loopOnceRequestId, input.sourcePayload?.loopIdleGeneration)
411
+ || !this.deps.sessionManager.consumeSessionLoopOnce(session.id, loopOnceRequestId)) {
412
+ return { status: 'skipped', reason: 'loop_once_stale', feedback, effects: [], error: null };
413
+ }
414
+ }
391
415
  enqueuePromise = this.deps.messageQueue.enqueue(session.id, message, session.projectPath, {
392
416
  interruptible: false,
393
417
  agentName: binding.agentName,
@@ -4,7 +4,7 @@ import { CronExpressionParser } from 'cron-parser';
4
4
  import { logger } from '../utils/logger.js';
5
5
  import { isNoopText } from '../core/message/message-utils.js';
6
6
  import { matchTriggerEvent, TriggerEventSource } from './event-source.js';
7
- import { definitionRevision, executionTimeoutMs, parseDurationMs, previewText, renderTemplate, resolveScriptPath, sha256, validateConcurrencyCombination, } from './validation.js';
7
+ import { definitionRevision, executionTimeoutMs, parseDurationMs, previewText, renderTemplate, sessionIdlePromptOverride, resolveScriptPath, sha256, validateConcurrencyCombination, } from './validation.js';
8
8
  import { TargetSessionLockRegistry } from './session-lock.js';
9
9
  import { enterTrigger, formatTriggerPath } from '../core/causation/context.js';
10
10
  import { createRootCausation } from '../core/causation/context.js';
@@ -936,7 +936,7 @@ export class TriggerRuntimeScheduler {
936
936
  : {}),
937
937
  },
938
938
  };
939
- const originalPrompt = renderTemplate(definition.execution.prompt ?? '', {
939
+ const originalPrompt = sessionIdlePromptOverride(sourcePayload) ?? renderTemplate(definition.execution.prompt ?? '', {
940
940
  trigger: triggerView,
941
941
  timestamp: firedAt,
942
942
  event: sourcePayload,
@@ -1266,7 +1266,7 @@ export class TriggerRuntimeScheduler {
1266
1266
  let anomalies = [];
1267
1267
  let incomplete;
1268
1268
  try {
1269
- const originalPrompt = renderTemplate(definition.execution.prompt ?? '', {
1269
+ const originalPrompt = sessionIdlePromptOverride(source.payload) ?? renderTemplate(definition.execution.prompt ?? '', {
1270
1270
  trigger: definition,
1271
1271
  timestamp: source.firedAt,
1272
1272
  event: source.payload,
@@ -157,7 +157,7 @@ export function seedTaskRecoveryTrigger(manager, owner) {
157
157
  atomicWriteJson(manager.definitionPath(definition.id), definition);
158
158
  fs.rmSync(manager.activePath(definition.id), { force: true });
159
159
  }
160
- const SESSION_IDLE_CHECK_PROMPT = `本会话已闲置一段时间。请依据你的职责执行一次例行巡检:
160
+ const DEFAULT_SESSION_IDLE_PROMPT = `本会话已闲置一段时间。请依据你的职责执行一次例行巡检:
161
161
  1. 检查当前会话中未完成却停滞的事项。私聊检查自己承诺或正在推进的任务;群聊还需检查成员长时间无进展、被点名未回应、承诺后失联等情况。有,则在既有授权和职责内推进一次,或向相关成员催促一次并说明停滞事项,随后即止;无,则不做任何动作。不要自行新增任务,正常推进或无待办时保持沉默。
162
162
  2. 巡检优先基于已有上下文判断,确需补充背景再查询历史,并遵守会话自身的发送规范。
163
163
  3. 判定无需任何对外动作时,本轮只输出 [[NOOP]],不发送任何消息、不发布巡检结论。注意:最终对外输出必须是且仅是 [[NOOP]] 这一行——不要在输出它之前先发送任何说明文字或巡检判定,判定过程仅在内部完成。
@@ -188,7 +188,7 @@ export function seedSessionIdleCheckTrigger(manager, owner) {
188
188
  },
189
189
  execution: {
190
190
  type: 'target_session',
191
- prompt: SESSION_IDLE_CHECK_PROMPT,
191
+ prompt: DEFAULT_SESSION_IDLE_PROMPT,
192
192
  onError: 'retry',
193
193
  noopSentinel: '[[NOOP]]',
194
194
  },
@@ -9,6 +9,10 @@ const MAX_EXECUTION_TIMEOUT_MS = 2_147_483_647;
9
9
  export const TRIGGER_SCHEMA_VERSION = 3.1;
10
10
  const LEGACY_TRIGGER_SCHEMA_VERSION = 4;
11
11
  const DEFAULT_NOOP_SENTINEL = '[[NOOP]]';
12
+ export function sessionIdlePromptOverride(event) {
13
+ return event?.type === 'session:idle' && typeof event.loopOnceRequestId === 'string'
14
+ && typeof event.loopPrompt === 'string' ? event.loopPrompt : undefined;
15
+ }
12
16
  /** Only a leading sentinel controls delivery; later mentions are ordinary prose. */
13
17
  export function isTriggerNoopText(text, sentinel) {
14
18
  return !!sentinel && text.trimStart().startsWith(sentinel);
@@ -7,9 +7,9 @@ export function autostartInstalled() {
7
7
  return macosAutostartInstalled();
8
8
  return false;
9
9
  }
10
- export function configureAutostart(enabled, runtimeRoot) {
10
+ export function configureAutostart(enabled, runtimeRoot, options = {}) {
11
11
  if (process.platform === 'win32')
12
- return configureWindowsAutostart(enabled, runtimeRoot);
12
+ return configureWindowsAutostart(enabled, runtimeRoot, options);
13
13
  if (process.platform === 'darwin')
14
14
  return configureMacosAutostart(enabled, runtimeRoot);
15
15
  return {
@@ -195,7 +195,8 @@ function prepareCliProbe(command, args, options = {}) {
195
195
  const identity = `${probeInstallationIdentity(command, executable)}|${cliFileIdentity(launch.launcherPath)}`;
196
196
  const key = JSON.stringify([command, args]);
197
197
  let entry = cliProbeCache.get(key);
198
- if (!entry || entry.identity !== identity || (entry.retryAt !== undefined && Date.now() >= entry.retryAt)) {
198
+ if (!entry || entry.identity !== identity || (entry.retryAt !== undefined && Date.now() >= entry.retryAt)
199
+ || (entry.output !== undefined && options.validateOutput && !options.validateOutput(entry.output))) {
199
200
  entry = { identity };
200
201
  cliProbeCache.set(key, entry);
201
202
  }
@@ -207,10 +208,23 @@ function prepareCliProbe(command, args, options = {}) {
207
208
  };
208
209
  }
209
210
  function failCliProbe(entry, error) {
211
+ entry.output = undefined;
210
212
  entry.error = error;
211
213
  entry.retryAt = Date.now() + CLI_PROBE_FAILURE_BACKOFF_MS;
212
214
  throw error;
213
215
  }
216
+ function validateCliProbeOutput(output, stderr, options) {
217
+ if (options.validateOutput && !options.validateOutput(output)) {
218
+ throw Object.assign(new Error('CLI probe returned invalid output'), {
219
+ code: 'INVALID_PROBE_OUTPUT', status: 0, stdout: output, stderr,
220
+ });
221
+ }
222
+ return output;
223
+ }
224
+ function isRetryableCliProbeError(error) {
225
+ const code = error?.code;
226
+ return code === 'ETIMEDOUT' || code === 'INVALID_PROBE_OUTPUT';
227
+ }
214
228
  export function probeCliSync(command, args, options = {}) {
215
229
  const request = prepareCliProbe(command, args, options);
216
230
  if (request.entry.output !== undefined)
@@ -220,15 +234,16 @@ export function probeCliSync(command, args, options = {}) {
220
234
  for (const [index, timeout] of cliProbeTimeouts(command, options).entries()) {
221
235
  const startedAt = Date.now();
222
236
  try {
223
- return request.entry.output = execFileSync(request.command, request.args, {
237
+ const output = execFileSync(request.command, request.args, {
224
238
  encoding: 'utf8', timeout, windowsHide: true,
225
239
  windowsVerbatimArguments: request.launch.windowsVerbatimArguments,
226
240
  stdio: ['ignore', 'pipe', 'pipe'],
227
241
  });
242
+ return request.entry.output = validateCliProbeOutput(output, undefined, options);
228
243
  }
229
244
  catch (error) {
230
245
  options.onFailure?.(args, startedAt, error, timeout, request.launch);
231
- if (error.code !== 'ETIMEDOUT' || index === cliProbeTimeouts(command, options).length - 1)
246
+ if (!isRetryableCliProbeError(error) || index === cliProbeTimeouts(command, options).length - 1)
232
247
  return failCliProbe(request.entry, error);
233
248
  }
234
249
  }
@@ -240,8 +255,15 @@ export async function probeCli(command, args, options = {}) {
240
255
  return request.entry.output;
241
256
  if (request.entry.error !== undefined)
242
257
  throw request.entry.error;
243
- if (request.entry.pending)
244
- return request.entry.pending;
258
+ if (request.entry.pending) {
259
+ const output = await request.entry.pending;
260
+ try {
261
+ return validateCliProbeOutput(output, undefined, options);
262
+ }
263
+ catch (error) {
264
+ return failCliProbe(request.entry, error);
265
+ }
266
+ }
245
267
  const run = async () => {
246
268
  const timeouts = cliProbeTimeouts(command, options);
247
269
  for (const [index, timeout] of timeouts.entries()) {
@@ -258,8 +280,14 @@ export async function probeCli(command, args, options = {}) {
258
280
  Object.assign(error, { stdout, stderr, path: request.command, spawnargs: request.args });
259
281
  reject(error);
260
282
  }
261
- else
262
- resolve(stdout);
283
+ else {
284
+ try {
285
+ resolve(validateCliProbeOutput(stdout, stderr, options));
286
+ }
287
+ catch (validationError) {
288
+ reject(validationError);
289
+ }
290
+ }
263
291
  });
264
292
  child.stdin?.end();
265
293
  });
@@ -267,7 +295,7 @@ export async function probeCli(command, args, options = {}) {
267
295
  }
268
296
  catch (error) {
269
297
  options.onFailure?.(args, startedAt, error, timeout, request.launch);
270
- if (error.code !== 'ETIMEDOUT' || index === timeouts.length - 1)
298
+ if (!isRetryableCliProbeError(error) || index === timeouts.length - 1)
271
299
  return failCliProbe(request.entry, error);
272
300
  }
273
301
  }