evolcore 0.0.43-test.4 → 0.0.43-test.6

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 (186) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ecmsg.js +437 -91
  3. package/dist/agents/baseagent-availability.js +19 -4
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +14 -3
  7. package/dist/agents/codex-runner.js +18 -23
  8. package/dist/aun/aid/agentmd.js +25 -0
  9. package/dist/aun/aid/control-aid.js +15 -0
  10. package/dist/aun/aid/identity.js +8 -0
  11. package/dist/aun/aid/ownership-operation.js +12 -3
  12. package/dist/aun/group/invite-service.js +3 -2
  13. package/dist/aun/service-proxy.js +18 -6
  14. package/dist/channels/aun.js +99 -23
  15. package/dist/channels/daemon.js +2 -2
  16. package/dist/cli/agent-create.js +19 -7
  17. package/dist/cli/aid-bind-command.js +3 -0
  18. package/dist/cli/aun-commands.js +19 -4
  19. package/dist/cli/code-stats.js +451 -213
  20. package/dist/cli/ctl-command.js +1 -3
  21. package/dist/cli/daemon-commands.js +42 -4
  22. package/dist/cli/directory.js +3 -1
  23. package/dist/cli/ecmsg-gateway.js +206 -0
  24. package/dist/cli/index.js +6 -0
  25. package/dist/cli/init.js +120 -13
  26. package/dist/cli/provider-command.js +82 -5
  27. package/dist/cli/restart-monitor.js +35 -24
  28. package/dist/cli/stats.js +8 -1
  29. package/dist/cli/task-context.js +41 -1
  30. package/dist/cli/watch-logs.js +6 -4
  31. package/dist/config/boot-log.js +16 -3
  32. package/dist/config/builtin-roles.js +2 -2
  33. package/dist/config/config-manager.js +5 -14
  34. package/dist/config/daemon-services.js +1 -0
  35. package/dist/config/peer-role-resolver.js +6 -6
  36. package/dist/config/provider-identity-migration.js +277 -0
  37. package/dist/config/provider-identity.js +37 -0
  38. package/dist/config/provider-ipc-service.js +40 -3
  39. package/dist/config/provider-local-sync.js +155 -0
  40. package/dist/config/providers-config.js +45 -4
  41. package/dist/config/providers-management.js +242 -76
  42. package/dist/config/providers.js +4 -1
  43. package/dist/config/role-service.js +8 -8
  44. package/dist/config/role-store.js +22 -22
  45. package/dist/config/schema-migration.js +143 -86
  46. package/dist/config/snapshot.js +70 -41
  47. package/dist/core/agent-runtime.js +48 -9
  48. package/dist/core/auth/auth-gateway.js +5 -3
  49. package/dist/core/auth/delegation-diagnostics.js +6 -2
  50. package/dist/core/auth/operation-authorizer.js +3 -1
  51. package/dist/core/auth/operation-catalog.js +6 -4
  52. package/dist/core/baseagent-loader.js +114 -11
  53. package/dist/core/channel-loader.js +36 -13
  54. package/dist/core/channel-runtime.js +112 -42
  55. package/dist/core/command/cli-intent-parser.js +2 -1
  56. package/dist/core/command/command-handler.js +16 -11
  57. package/dist/core/command/menu-handler.js +8 -3
  58. package/dist/core/command/menu-protocol.js +80 -7
  59. package/dist/core/command/provider-menu.js +4 -2
  60. package/dist/core/command/role-menu.js +29 -17
  61. package/dist/core/command/slash-handler.js +52 -16
  62. package/dist/core/daemon-control.js +42 -15
  63. package/dist/core/daemon-lifecycle.js +411 -67
  64. package/dist/core/handoff/dispatcher.js +9 -3
  65. package/dist/core/handoff/runtime.js +139 -45
  66. package/dist/core/handoff/store.js +190 -2
  67. package/dist/core/handoff/types.js +5 -0
  68. package/dist/core/initialization/service.js +7 -6
  69. package/dist/core/ipc-registration.js +5 -4
  70. package/dist/core/lifecycle-notice.js +10 -4
  71. package/dist/core/message/aun-ipc-sender.js +83 -5
  72. package/dist/core/message/message-admission.js +2 -0
  73. package/dist/core/message/message-bridge.js +53 -4
  74. package/dist/core/message/message-queue.js +46 -4
  75. package/dist/core/message/pending-hints.js +4 -10
  76. package/dist/core/message/response-engine.js +33 -25
  77. package/dist/core/message/send-options.js +40 -0
  78. package/dist/core/message/send-routing.js +320 -0
  79. package/dist/core/ownership/owner-resolver.js +112 -8
  80. package/dist/core/permission/ec-command-parser.js +159 -16
  81. package/dist/core/permission/readonly-shell-query.js +66 -7
  82. package/dist/core/permission/tool-error-code.js +13 -1
  83. package/dist/core/permission/tool-policy.js +74 -20
  84. package/dist/core/relation/same-owner-proof.js +131 -0
  85. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  86. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  87. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  88. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  89. package/dist/core/session/session-fs-store.js +164 -3
  90. package/dist/core/session/session-idle-monitor.js +103 -17
  91. package/dist/core/session/session-manager.js +105 -18
  92. package/dist/core/thread/thread-route.js +5 -2
  93. package/dist/directory/owner-directory-admission.js +26 -1
  94. package/dist/directory/owner-directory-cache.js +739 -109
  95. package/dist/directory/owner-directory-markdown.js +146 -36
  96. package/dist/directory/owner-directory-query-operation.js +6 -3
  97. package/dist/directory/owner-directory-scope.js +12 -0
  98. package/dist/directory/owner-directory-search.js +5 -1
  99. package/dist/directory/owner-directory-store.js +28 -0
  100. package/dist/ecweb/basic-settings-service.js +15 -1
  101. package/dist/ecweb/message-context-service.js +2 -2
  102. package/dist/ecweb/providers-service.js +3 -1
  103. package/dist/ecweb/runtime/lifecycle.js +26 -15
  104. package/dist/ecweb/runtime/supervisor.js +120 -51
  105. package/dist/index.js +551 -250
  106. package/dist/paths.js +2 -1
  107. package/dist/proxy/manager.js +40 -17
  108. package/dist/proxy/service-supervisor.js +67 -33
  109. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  110. package/dist/trigger/application-service.js +4 -1
  111. package/dist/trigger/audit.js +19 -4
  112. package/dist/trigger/authorization.js +14 -5
  113. package/dist/trigger/event-source.js +4 -0
  114. package/dist/trigger/feedback.js +26 -2
  115. package/dist/trigger/history.js +176 -7
  116. package/dist/trigger/manager.js +1 -3
  117. package/dist/trigger/scheduler.js +81 -8
  118. package/dist/trigger/system-definitions.js +2 -2
  119. package/dist/trigger/validation.js +4 -0
  120. package/dist/utils/autostart.js +2 -2
  121. package/dist/utils/cross-platform.js +188 -12
  122. package/dist/utils/host-info.js +11 -8
  123. package/dist/utils/npm-ops.js +48 -0
  124. package/dist/utils/process-introspect.js +64 -1
  125. package/dist/utils/public-suffix.js +5811 -0
  126. package/dist/utils/startup-trace.js +160 -19
  127. package/dist/utils/windows-autostart.js +41 -7
  128. package/ecagent/dist/harness/env/nodejs.js +46 -2
  129. package/kits/docs/aun/ABILITY_CALLING.md +6 -6
  130. package/kits/docs/channels/aun.md +1 -1
  131. package/kits/docs/channels/feishu.md +2 -2
  132. package/kits/docs/context-assembly.md +20 -4
  133. package/kits/docs/evolcore/INDEX.md +5 -3
  134. package/kits/docs/evolcore/agent.md +2 -2
  135. package/kits/docs/evolcore/aid.md +8 -2
  136. package/kits/docs/evolcore/ctl.md +15 -5
  137. package/kits/docs/evolcore/directory.md +48 -15
  138. package/kits/docs/evolcore/group.md +8 -8
  139. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  140. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  141. package/kits/docs/evolcore/menu-protocol.md +32 -3
  142. package/kits/docs/evolcore/msg.md +38 -30
  143. package/kits/docs/evolcore/provider.md +57 -5
  144. package/kits/docs/evolcore/response.md +2 -2
  145. package/kits/docs/evolcore/thread-chain.md +11 -13
  146. package/kits/docs/evolcore/tool-authorization.md +17 -0
  147. package/kits/docs/evolcore/trigger.md +2 -2
  148. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  149. package/kits/docs/prompt-loading-architecture.md +30 -20
  150. package/kits/eck_manifest.auxiliary.json +5 -5
  151. package/kits/eck_manifest.json +44 -32
  152. package/kits/eck_manifest.memory.json +18 -18
  153. package/kits/eck_message_manifest.json +3 -3
  154. package/kits/rules/01-overview.md +1 -1
  155. package/kits/rules/06-channel.md +7 -8
  156. package/kits/schemas/_meta.json +7 -1
  157. package/kits/schemas/daemon.schema.1.json +5 -0
  158. package/kits/schemas/daemon.schema.2.json +5 -0
  159. package/kits/schemas/daemon.schema.3.json +2 -1
  160. package/kits/schemas/daemon.schema.4.json +2 -1
  161. package/kits/schemas/daemon.schema.5.json +2 -1
  162. package/kits/schemas/daemon.schema.6.json +1 -1
  163. package/kits/schemas/daemon.schema.7.json +1 -1
  164. package/kits/schemas/daemon.schema.8.json +2 -1
  165. package/kits/schemas/daemon.schema.9.json +2 -1
  166. package/kits/schemas/providers.schema.2.json +74 -0
  167. package/kits/schemas/role-registry.schema.1.json +2 -2
  168. package/kits/schemas/single-session.schema.1.json +1 -1
  169. package/kits/schemas/single-session.schema.2.json +1 -1
  170. package/kits/schemas/single-session.schema.3.json +1 -1
  171. package/kits/skills/aid-ability/SKILL.md +7 -7
  172. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  173. package/kits/skills/ec-group/SKILL.md +8 -5
  174. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  175. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  176. package/kits/skills/ec-trigger/SKILL.md +9 -9
  177. package/kits/skills/ec-trigger/references/examples.md +1 -1
  178. package/kits/skills/thread-ops/SKILL.md +10 -10
  179. package/kits/templates/system-fragments/channel.md +5 -5
  180. package/kits/templates/system-fragments/commands.md +7 -6
  181. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  182. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  183. package/kits/templates/system-fragments/reply.md +48 -28
  184. package/kits/templates/system-fragments/session.md +3 -10
  185. package/kits/templates/system-fragments/thread.md +5 -5
  186. package/package.json +4 -4
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 关联) */
@@ -9,7 +9,7 @@ import { resolvePaths } from '../paths.js';
9
9
  import { atomicWriteJson } from '../utils/atomic-write.js';
10
10
  import { logger as defaultLogger } from '../utils/logger.js';
11
11
  import { probeServiceRoot } from '../aun/service-proxy.js';
12
- import { startServiceProxy } from '../aun/service-proxy.js';
12
+ import { readServiceProxyEndpoint, startServiceProxy } from '../aun/service-proxy.js';
13
13
  import { ServiceSupervisor } from './service-supervisor.js';
14
14
  const MUTATIONS = new Set([
15
15
  'build', 'update', 'apply', 'publish', 'unpublish', 'remove', 'start', 'stop',
@@ -69,6 +69,7 @@ export class ServiceProxyManager {
69
69
  removeConfigListener;
70
70
  activeProxy = null;
71
71
  activeProxySignature = '';
72
+ activeProxyConfigSignature = '';
72
73
  activeProxyNames = [];
73
74
  applyQueue = Promise.resolve();
74
75
  stopped = false;
@@ -82,11 +83,22 @@ export class ServiceProxyManager {
82
83
  error: undefined,
83
84
  };
84
85
  inflight = new Map();
86
+ settleInitialPublication;
85
87
  constructor(options) {
86
88
  this.options = options;
87
89
  this.supervisor = new ServiceSupervisor(defaultLogger);
88
90
  }
89
91
  async start() {
92
+ this.settleInitialPublication ??= this.options.startupTrace?.startTask('daemon.serviceProxyReady');
93
+ try {
94
+ await this.startRuntime();
95
+ }
96
+ catch (error) {
97
+ this.settleInitialPublication?.('failed');
98
+ throw error;
99
+ }
100
+ }
101
+ async startRuntime() {
90
102
  this.stopped = false;
91
103
  this.removeConfigListener = onConfigWrite(({ target }) => {
92
104
  if (target === ConfigTarget.Process)
@@ -103,34 +115,24 @@ export class ServiceProxyManager {
103
115
  && service.proxy.source === 'instance'
104
116
  && basename.startsWith(service.name + '-')))
105
117
  return;
106
- const serviceName = configured.find(service => service.proxy?.enabled === true
107
- && service.proxy.source === 'instance'
108
- && basename.startsWith(service.name + '-'))?.name;
109
- if (this.proxyTransport.proxyServer !== 'unconfirmed')
110
- return;
111
118
  if (this.instanceApplyTimer)
112
119
  clearTimeout(this.instanceApplyTimer);
113
120
  this.instanceApplyTimer = setTimeout(() => {
114
121
  this.instanceApplyTimer = undefined;
115
- const activeProxyConfig = this.activeProxyNames
116
- .map(name => findService(loadDaemonConfig().services ?? [], name))
117
- .filter((service) => !!service);
118
- const dirtySnapshot = activeProxyConfig.map(service => service.name === serviceName
119
- ? { ...service, runtime: { ...service.runtime, generation: Date.now() } }
120
- : service);
121
- this.activeProxySignature = hash(dirtySnapshot);
122
122
  void this.scheduleApply().catch(error => {
123
123
  defaultLogger.warn('[ServiceProxy] instance change apply failed: ' + (error instanceof Error ? error.message : String(error)));
124
124
  });
125
125
  }, 250);
126
126
  this.instanceApplyTimer.unref?.();
127
127
  });
128
- await this.supervisor.start(loadDaemonConfig().services ?? []);
129
- void this.scheduleApply().catch(error => {
130
- defaultLogger.warn('[ServiceProxy] initial apply failed: ' + (error instanceof Error ? error.message : String(error)));
128
+ this.applyQueue = this.applyQueue.then(async () => {
129
+ if (!this.stopped)
130
+ await this.supervisor.start(loadDaemonConfig().services ?? []);
131
131
  });
132
+ await this.scheduleApply();
132
133
  }
133
134
  async stop() {
135
+ this.settleInitialPublication?.('cancelled');
134
136
  if (this.stopped)
135
137
  return;
136
138
  this.stopped = true;
@@ -325,6 +327,7 @@ export class ServiceProxyManager {
325
327
  port: current.port ?? DEFAULT_ECWEB_PORT,
326
328
  runtimeMode: 'managed',
327
329
  restart: current.runtime?.restart,
330
+ health: current.health,
328
331
  });
329
332
  return { ok: true, ...result, operationId, jobId: operationId, state: 'completed', runtime: this.options.ecwebSupervisor.status() };
330
333
  }
@@ -402,12 +405,23 @@ export class ServiceProxyManager {
402
405
  port: ecweb?.port ?? DEFAULT_ECWEB_PORT,
403
406
  runtimeMode: ecweb ? serviceRuntimeMode(ecweb) : 'managed',
404
407
  restart: ecweb?.runtime?.restart,
408
+ health: ecweb?.health,
405
409
  });
406
410
  await this.supervisor.reconcile(services);
407
411
  if (this.stopped)
408
412
  return;
409
413
  const desired = services.filter(service => service.enabled === true && service.proxy?.enabled === true);
410
- const signature = hash(desired);
414
+ const publication = desired.map(service => ({ name: service.name, proxy: service.proxy }));
415
+ const configSignature = hash(desired.map(service => ({ name: service.name, proxy: service.proxy, port: service.port })));
416
+ // A pending handle is already discovering endpoints. Its ready callback
417
+ // reconciles once more using the endpoints it actually registered.
418
+ if (this.activeProxy && this.proxyTransport.state === 'starting'
419
+ && configSignature === this.activeProxyConfigSignature)
420
+ return;
421
+ const endpoints = Object.fromEntries(await Promise.all(desired.map(async (service) => [service.name, await readServiceProxyEndpoint(service)])));
422
+ if (this.stopped)
423
+ return;
424
+ const signature = hash({ publication, endpoints });
411
425
  if (signature === this.activeProxySignature)
412
426
  return;
413
427
  const oldNames = this.activeProxy ? (this.activeProxySignature ? this.readActiveProxyNames() : []) : [];
@@ -425,11 +439,13 @@ export class ServiceProxyManager {
425
439
  this.activeProxy = null;
426
440
  }
427
441
  this.activeProxySignature = signature;
442
+ this.activeProxyConfigSignature = configSignature;
428
443
  this.activeProxyNames = nextNames;
429
444
  this.proxyTransport.updatedAt = Date.now();
430
445
  this.proxyTransport.gatewayRegistered = false;
431
446
  this.proxyTransport.proxyServer = 'unknown';
432
447
  if (desired.length === 0) {
448
+ this.settleInitialPublication?.('skipped');
433
449
  if (!this.proxyTransport.error)
434
450
  this.proxyTransport.state = 'unpublished';
435
451
  return;
@@ -438,6 +454,7 @@ export class ServiceProxyManager {
438
454
  this.proxyTransport.state = 'starting';
439
455
  const handle = startServiceProxy(this.options.controlChannel, this.options.providerAid, desired);
440
456
  if (!handle) {
457
+ this.settleInitialPublication?.('failed');
441
458
  this.proxyTransport.state = 'unpublished';
442
459
  return;
443
460
  }
@@ -446,6 +463,10 @@ export class ServiceProxyManager {
446
463
  void handle.ready.then(result => {
447
464
  if (this.stopped || this.activeProxy !== handle)
448
465
  return;
466
+ this.settleInitialPublication?.(result.registered === desired.length && result.gatewayRegistered ? 'ok' : 'failed');
467
+ this.activeProxySignature = hash({ publication,
468
+ endpoints: Object.fromEntries(desired.map(service => [service.name, handle.endpoints[service.name] ?? null])),
469
+ });
449
470
  this.proxyTransport.gatewayRegistered = result.gatewayRegistered;
450
471
  this.proxyTransport.proxyServer = 'unconfirmed';
451
472
  if (result.registered === 0) {
@@ -462,9 +483,11 @@ export class ServiceProxyManager {
462
483
  }
463
484
  this.proxyTransport.state = result.gatewayRegistered ? 'active' : 'degraded';
464
485
  this.proxyTransport.error = result.gatewayRegistered ? undefined : 'Gateway registration has not been confirmed';
486
+ void this.scheduleApply().catch(error => defaultLogger.warn('[ServiceProxy] endpoint reconciliation failed: ' + String(error)));
465
487
  }).catch(error => {
466
488
  if (this.stopped || this.activeProxy !== handle)
467
489
  return;
490
+ this.settleInitialPublication?.('failed');
468
491
  this.proxyTransport.state = 'degraded';
469
492
  this.proxyTransport.error = error instanceof Error ? error.message : String(error);
470
493
  });
@@ -4,8 +4,8 @@ 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';
8
- import { getProcessStartTime, startTimeMatches } from '../utils/process-introspect.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
+ import { getProcessStartTimeAsync, 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';
11
11
  import { atomicWriteJson } from '../utils/atomic-write.js';
@@ -77,12 +77,12 @@ async function tcpReady(port, timeoutMs) {
77
77
  });
78
78
  }
79
79
  async function checkHealth(service, pid) {
80
- if (pid > 0 && !platform.isProcessRunning(pid))
80
+ if (pid > 0 && !(await platform.isProcessRunningAsync(pid)))
81
81
  return false;
82
82
  if (!service.port)
83
83
  return pid > 0;
84
84
  if (pid > 0) {
85
- const listeners = platform.findProcessByPort(service.port);
85
+ const listeners = await platform.findProcessByPortAsync(service.port);
86
86
  if (listeners.length > 0 && !listeners.includes(pid))
87
87
  return false;
88
88
  }
@@ -207,7 +207,9 @@ export class ServiceSupervisor {
207
207
  void this.monitorHealth(active).finally(() => this.scheduleHealthCheck(active));
208
208
  continue;
209
209
  }
210
- const active = this.adoptOrCreate(service);
210
+ const active = await this.adoptOrCreate(service);
211
+ if (this.stopped)
212
+ return;
211
213
  this.active.set(service.name, active);
212
214
  if (active.state !== 'ready') {
213
215
  void this.queueOperation(service.name, () => this.startEntry(active)).catch(() => { });
@@ -242,7 +244,9 @@ export class ServiceSupervisor {
242
244
  this.desired.set(name, service);
243
245
  let active = this.active.get(name);
244
246
  if (!active) {
245
- active = this.adoptOrCreate(service);
247
+ active = await this.adoptOrCreate(service);
248
+ if (this.stopped)
249
+ throw Object.assign(new Error('service start cancelled: ' + name), { code: 'SERVICE_START_CANCELLED' });
246
250
  this.active.set(name, active);
247
251
  }
248
252
  await this.startEntry(active);
@@ -306,9 +310,11 @@ export class ServiceSupervisor {
306
310
  });
307
311
  }
308
312
  async verifyAdopted(active) {
309
- if (active.state !== 'starting' || !active.pid || !platform.isProcessRunning(active.pid))
310
- return;
311
313
  const generation = active.generation;
314
+ if (active.state !== 'starting' || !active.pid || !(await platform.isProcessRunningAsync(active.pid)))
315
+ return;
316
+ if (generation !== active.generation || active.stopping || this.stopped)
317
+ return;
312
318
  const healthy = await checkHealth(active.config, active.pid);
313
319
  if (generation !== active.generation || active.stopping || this.stopped)
314
320
  return;
@@ -333,13 +339,16 @@ export class ServiceSupervisor {
333
339
  this.scheduleRestart(active);
334
340
  }
335
341
  }
336
- adoptOrCreate(service) {
342
+ async adoptOrCreate(service) {
337
343
  const hash = serviceConfigHash(service);
338
344
  const records = readInstanceRecords(service.name);
339
- const liveRecords = records
340
- .filter(record => platform.isProcessRunning(record.pid)
341
- && startTimeMatches(record.startedAt, getProcessStartTime(record.pid)))
342
- .sort((a, b) => b.startedAt - a.startedAt);
345
+ const liveRecords = [];
346
+ for (const record of records) {
347
+ if ((await platform.isProcessRunningAsync(record.pid))
348
+ && startTimeMatches(record.startedAt, await getProcessStartTimeAsync(record.pid)))
349
+ liveRecords.push(record);
350
+ }
351
+ liveRecords.sort((a, b) => b.startedAt - a.startedAt);
343
352
  const adopted = liveRecords.find(record => record.configHash === hash);
344
353
  if (adopted) {
345
354
  return {
@@ -362,7 +371,7 @@ export class ServiceSupervisor {
362
371
  };
363
372
  }
364
373
  for (const record of records) {
365
- if (platform.isProcessRunning(record.pid) && getProcessStartTime(record.pid) === null)
374
+ if ((await platform.isProcessRunningAsync(record.pid)) && await getProcessStartTimeAsync(record.pid) === null)
366
375
  continue;
367
376
  try {
368
377
  fs.unlinkSync(record.filePath);
@@ -423,8 +432,11 @@ export class ServiceSupervisor {
423
432
  if (this.stopped || active.stopping || active.intentionalStop)
424
433
  return;
425
434
  const generation = active.generation;
426
- if (active.pid && platform.isProcessRunning(active.pid)) {
427
- if (active.adoptionAllowed !== false && startTimeMatches(active.startedAt, getProcessStartTime(active.pid))) {
435
+ const running = active.pid && await platform.isProcessRunningAsync(active.pid);
436
+ if (generation !== active.generation || this.stopped || active.stopping || active.intentionalStop)
437
+ return;
438
+ if (running) {
439
+ if (active.adoptionAllowed !== false && startTimeMatches(active.startedAt, await getProcessStartTimeAsync(active.pid))) {
428
440
  const healthy = await checkHealth(active.config, active.pid);
429
441
  if (generation !== active.generation || this.stopped || active.intentionalStop) {
430
442
  throw Object.assign(new Error('service start cancelled: ' + active.config.name), { code: 'SERVICE_START_CANCELLED' });
@@ -452,7 +464,10 @@ export class ServiceSupervisor {
452
464
  }
453
465
  }
454
466
  if (active.config.port) {
455
- const listeners = platform.findProcessByPort(active.config.port);
467
+ const listeners = await platform.findProcessByPortAsync(active.config.port);
468
+ if (this.stopped || active.stopping || active.intentionalStop) {
469
+ throw Object.assign(new Error('service start cancelled: ' + active.config.name), { code: 'SERVICE_START_CANCELLED' });
470
+ }
456
471
  if (listeners.length > 0) {
457
472
  active.portConflictPids = listeners;
458
473
  const error = Object.assign(new Error('configured service port is owned by another process: ' + active.config.port + ' (pid=' + listeners.join(',') + ')'), { code: 'PORT_IN_USE' });
@@ -518,11 +533,12 @@ export class ServiceSupervisor {
518
533
  if (!pid)
519
534
  throw Object.assign(new Error('failed to obtain PID for ' + active.config.name), { code: 'PROCESS_START_FAILED' });
520
535
  active.pid = pid;
521
- active.startedAt = getProcessStartTime(pid) ?? 0;
536
+ active.startedAt = 0;
522
537
  active.recordPath = recordPath(active.config.name, pid);
523
538
  active.adoptionAllowed = true;
524
539
  active.portConflictPids = undefined;
525
540
  active.generation += 1;
541
+ const childGeneration = active.generation;
526
542
  child.once('exit', (code, signal) => {
527
543
  if (active.process !== child)
528
544
  return;
@@ -551,6 +567,19 @@ export class ServiceSupervisor {
551
567
  // for that case as well.
552
568
  this.scheduleRestart(active);
553
569
  });
570
+ child.unref();
571
+ const identity = active.identityPromise = getProcessStartTimeAsync(pid);
572
+ const startedAt = await identity;
573
+ if (active.identityPromise === identity)
574
+ active.identityPromise = undefined;
575
+ const running = await platform.isProcessRunningAsync(pid);
576
+ if (active.process !== child || !running) {
577
+ throw Object.assign(new Error('service exited before identity verification: ' + active.config.name), { code: 'PROCESS_EXITED' });
578
+ }
579
+ active.startedAt = startedAt ?? 0;
580
+ if (this.stopped || active.stopping || active.intentionalStop) {
581
+ throw Object.assign(new Error('service start cancelled: ' + active.config.name), { code: 'SERVICE_START_CANCELLED' });
582
+ }
554
583
  fs.mkdirSync(resolvePaths().instanceDir, { recursive: true });
555
584
  atomicWriteJson(active.recordPath, {
556
585
  owner: 'evolcore-service-supervisor',
@@ -562,12 +591,12 @@ export class ServiceSupervisor {
562
591
  attemptId: active.attemptId,
563
592
  });
564
593
  this.logLifecycle(active, 'service.spawned', { startedAt: active.startedAt });
565
- child.unref();
566
594
  if (!active.startedAt) {
567
595
  throw Object.assign(new Error('cannot verify newly spawned process identity: ' + active.config.name), { code: 'PROCESS_IDENTITY_UNVERIFIED' });
568
596
  }
569
597
  await this.waitForHealth(active);
570
- if (active.stopping || this.stopped || !platform.isProcessRunning(pid))
598
+ if (!(await platform.isProcessRunningAsync(pid)) || active.stopping || this.stopped
599
+ || active.intentionalStop || active.generation !== childGeneration || active.process !== child)
571
600
  return;
572
601
  fs.mkdirSync(resolvePaths().instanceDir, { recursive: true });
573
602
  atomicWriteJson(active.recordPath, {
@@ -587,7 +616,7 @@ export class ServiceSupervisor {
587
616
  await run();
588
617
  }
589
618
  async waitForHealth(active) {
590
- const deadline = Date.now() + (active.config.health?.startupTimeoutMs ?? 45000);
619
+ const deadline = Date.now() + (active.config.health?.startupTimeoutMs ?? SERVICE_STARTUP_TIMEOUT_MS);
591
620
  const interval = SERVICE_HEALTH_INTERVALS[active.config.health?.type ?? 'tcp'].startup;
592
621
  const generation = active.generation;
593
622
  do {
@@ -595,22 +624,25 @@ export class ServiceSupervisor {
595
624
  throw Object.assign(new Error('service start cancelled: ' + active.config.name), { code: 'SERVICE_START_CANCELLED' });
596
625
  }
597
626
  if (active.config.port) {
598
- const listeners = platform.findProcessByPort(active.config.port);
627
+ const listeners = await platform.findProcessByPortAsync(active.config.port);
599
628
  if (listeners.length > 0 && !listeners.includes(active.pid)) {
600
629
  active.portConflictPids = listeners;
601
630
  throw Object.assign(new Error('configured service port is owned by another process: ' + active.config.port + ' (pid=' + listeners.join(',') + ')'), { code: 'PORT_IN_USE' });
602
631
  }
603
632
  }
604
- if (active.stopping || this.stopped || !platform.isProcessRunning(active.pid)) {
633
+ if (active.stopping || this.stopped || !(await platform.isProcessRunningAsync(active.pid))) {
605
634
  throw Object.assign(new Error('service exited before ready: ' + active.config.name), { code: 'READINESS_TIMEOUT' });
606
635
  }
607
636
  const healthy = await checkHealth(active.config, active.pid);
608
637
  if (generation !== active.generation || active.intentionalStop || this.stopped) {
609
638
  throw Object.assign(new Error('service start cancelled: ' + active.config.name), { code: 'SERVICE_START_CANCELLED' });
610
639
  }
611
- if (!platform.isProcessRunning(active.pid)) {
640
+ if (!(await platform.isProcessRunningAsync(active.pid))) {
612
641
  throw Object.assign(new Error('service exited before ready: ' + active.config.name), { code: 'PROCESS_EXITED' });
613
642
  }
643
+ if (generation !== active.generation || active.stopping || active.intentionalStop || this.stopped) {
644
+ throw Object.assign(new Error('service start cancelled: ' + active.config.name), { code: 'SERVICE_START_CANCELLED' });
645
+ }
614
646
  if (healthy) {
615
647
  active.healthy = true;
616
648
  active.checkedAt = Date.now();
@@ -656,10 +688,10 @@ export class ServiceSupervisor {
656
688
  clearTimeout(active.restartTimer);
657
689
  active.restartTimer = undefined;
658
690
  const pid = active.pid;
659
- const expectedStartedAt = active.startedAt;
660
- if (pid > 0 && platform.isProcessRunning(pid)) {
661
- const actualStartedAt = getProcessStartTime(pid);
662
- if (actualStartedAt === null) {
691
+ const expectedStartedAt = active.startedAt || await active.identityPromise || 0;
692
+ if (pid > 0 && (await platform.isProcessRunningAsync(pid))) {
693
+ const actualStartedAt = await getProcessStartTimeAsync(pid);
694
+ if (actualStartedAt === null && (await platform.isProcessRunningAsync(pid))) {
663
695
  active.state = 'failed';
664
696
  active.lastError = 'cannot verify managed process identity; refusing to stop or replace it (pid=' + pid + ')';
665
697
  active.lastErrorCode = 'PROCESS_IDENTITY_UNVERIFIED';
@@ -667,20 +699,20 @@ export class ServiceSupervisor {
667
699
  this.log.error('[ServiceSupervisor] stop blocked service=' + active.config.name + ' pid=' + pid + ' reason=identity-unverified');
668
700
  return false;
669
701
  }
670
- if (startTimeMatches(expectedStartedAt, actualStartedAt)) {
702
+ if ((await platform.isProcessRunningAsync(pid)) && startTimeMatches(expectedStartedAt, actualStartedAt)) {
671
703
  try {
672
704
  platform.killProcessTree(pid, false);
673
705
  }
674
706
  catch { }
675
707
  let exited = await platform.waitForProcessExit(pid, active.config.runtime?.stopTimeoutMs ?? 10000);
676
- if (!exited && startTimeMatches(expectedStartedAt, getProcessStartTime(pid))) {
708
+ if (!exited && startTimeMatches(expectedStartedAt, await getProcessStartTimeAsync(pid))) {
677
709
  try {
678
710
  platform.killProcessTree(pid, true);
679
711
  }
680
712
  catch { }
681
713
  exited = await platform.waitForProcessExit(pid, 5000);
682
714
  }
683
- const remainingStartedAt = !exited && platform.isProcessRunning(pid) ? getProcessStartTime(pid) : undefined;
715
+ const remainingStartedAt = !exited && (await platform.isProcessRunningAsync(pid)) ? await getProcessStartTimeAsync(pid) : undefined;
684
716
  if (remainingStartedAt === null || (remainingStartedAt !== undefined && startTimeMatches(expectedStartedAt, remainingStartedAt))) {
685
717
  active.state = 'failed';
686
718
  active.lastError = 'process did not exit after graceful and forced termination (pid=' + pid + ')';
@@ -776,7 +808,9 @@ export class ServiceSupervisor {
776
808
  return;
777
809
  active.healthy = healthy;
778
810
  active.checkedAt = Date.now();
779
- const listeners = active.config.port ? platform.findProcessByPort(active.config.port) : [];
811
+ const listeners = active.config.port ? await platform.findProcessByPortAsync(active.config.port) : [];
812
+ if (generation !== active.generation || active.stopping || this.stopped)
813
+ return;
780
814
  active.portConflictPids = listeners.length ? listeners : undefined;
781
815
  if (listeners.length === 0 && active.config.runtime?.restart?.enabled !== false) {
782
816
  active.failures = [];
@@ -793,7 +827,7 @@ export class ServiceSupervisor {
793
827
  return;
794
828
  }
795
829
  const healthy = (serviceRuntimeMode(active.config) === 'external'
796
- || startTimeMatches(active.startedAt, getProcessStartTime(active.pid)))
830
+ || startTimeMatches(active.startedAt, await getProcessStartTimeAsync(active.pid)))
797
831
  && await checkHealth(active.config, active.pid);
798
832
  if (generation !== active.generation || active.stopping || this.stopped)
799
833
  return;
@@ -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) {
@@ -36,6 +36,8 @@ export class TriggerSchedulerRegistry {
36
36
  }
37
37
  catch (error) {
38
38
  logger.error(`[Trigger] Scheduler init failed for ${agentAid}: ${error instanceof Error ? error.message : String(error)}`);
39
+ // Propagate failure to admission/readiness and allow ensureStarted to retry.
40
+ throw error;
39
41
  }
40
42
  }
41
43
  async ensureStarted(agentAid, start) {
@@ -108,11 +110,12 @@ export function buildTriggerScheduler(owner, dependencies, options = {}) {
108
110
  removeConsolidationCheckTrigger(manager);
109
111
  }
110
112
  const state = new TriggerRunStateStore(manager);
111
- const agentTriggerAudit = dependencies.triggerAudit.withHistory(manager.history);
113
+ const agentTriggerAudit = dependencies.triggerAudit.withHistory(manager.history, { deferHistoryImport: true });
112
114
  const dispatcher = new TriggerFeedbackDispatcher({
113
115
  getChannel: dependencies.getTriggerChannel,
114
116
  sessionManager: dependencies.sessionManager,
115
117
  messageQueue: dependencies.messageQueue,
118
+ canDispatchSessionLoopOnce: dependencies.canDispatchSessionLoopOnce,
116
119
  recoverTask: request => dependencies.responseEngine.recoverTask(request),
117
120
  inspectTargetExecution: (sessionId, attemptId, selfAid) => (dependencies.responseEngine.inspectTargetExecution(sessionId, attemptId, selfAid)),
118
121
  eventBus: dependencies.eventBus,
@@ -6,10 +6,14 @@ export class TriggerAuditLogger {
6
6
  history;
7
7
  writer;
8
8
  logDir;
9
- constructor(logDir = resolvePaths().logs, history, writer) {
9
+ historyReady;
10
+ constructor(logDir = resolvePaths().logs, history, writer, options = {}) {
10
11
  this.history = history;
11
12
  this.logDir = logDir;
12
- this.history?.importAuditLogs(logDir);
13
+ if (!options.deferHistoryImport) {
14
+ this.history?.importAuditLogs(logDir);
15
+ this.historyReady = Promise.resolve();
16
+ }
13
17
  this.writer = writer ?? new LogWriter({
14
18
  baseName: 'trigger-runs',
15
19
  logDir,
@@ -17,8 +21,19 @@ export class TriggerAuditLogger {
17
21
  retention: { days: 7 },
18
22
  });
19
23
  }
20
- withHistory(history) {
21
- return new TriggerAuditLogger(this.logDir, history, this.writer);
24
+ withHistory(history, options = {}) {
25
+ return new TriggerAuditLogger(this.logDir, history, this.writer, options);
26
+ }
27
+ initializeHistory() {
28
+ return this.historyReady ??= (async () => {
29
+ try {
30
+ await this.history?.importAuditLogsAsync(this.logDir);
31
+ }
32
+ catch (error) {
33
+ this.historyReady = undefined;
34
+ throw error;
35
+ }
36
+ })();
22
37
  }
23
38
  write(record) {
24
39
  this.writer.write(JSON.stringify(record));
@@ -2,7 +2,7 @@ import crypto from 'crypto';
2
2
  import { eventPatternIncludesInternal } from '../core/event-catalog.js';
3
3
  import { trustedExecutionIdentityInput } from '../core/auth/agent-delegation.js';
4
4
  import { authorizeOperation, buildAuthSubject } from '../core/auth/auth-gateway.js';
5
- import { refreshOwnershipForAuthorization } from '../core/ownership/owner-resolver.js';
5
+ import { ownerResolver, refreshOwnershipForAuthorization } from '../core/ownership/owner-resolver.js';
6
6
  import { isManagementRole } from '../config/builtin-roles.js';
7
7
  import { checkRoleAccess, resolvePeerRoleDetail, roleToSessionIdentity } from '../config/peer-role-resolver.js';
8
8
  import { validateModelSelectionForRole } from '../core/model/model-permission.js';
@@ -215,9 +215,21 @@ export async function authorizeTriggerExecution(definition, dependencies) {
215
215
  && definition.labels.originAuthorization !== 'creator-session-v1') {
216
216
  return { allowed: false, reason: 'legacy cross-thread review creator is unverified; recreate the Trigger from its source conversation' };
217
217
  }
218
- await refreshOwnershipForAuthorization(definition.agentAid, {
218
+ const origin = definition.origin;
219
+ if (!origin?.peerId)
220
+ return { allowed: false, reason: 'trigger origin peer is missing' };
221
+ if (definition.execution.permissionMode === 'fullaccess' && !definition.authorizedBy) {
222
+ return { allowed: false, reason: 'fullaccess Trigger approval provenance is missing' };
223
+ }
224
+ const ownership = await refreshOwnershipForAuthorization(definition.agentAid, {
219
225
  allowTransient: true, includeDaemon: definition.execution.permissionMode === 'fullaccess',
220
226
  });
227
+ const originType = origin.channelType || tryParseChannelKey(origin.channelKey)?.type;
228
+ const requiresDaemonOwner = definition.execution.permissionMode === 'fullaccess';
229
+ if (ownership.some(view => view.consensusStatus === 'unavailable'
230
+ && (requiresDaemonOwner ? view.subjectAid === ownerResolver.getDaemonAid() : originType === 'aun'))) {
231
+ return { allowed: false, retryable: true, reason: 'Ownership authorization evidence is temporarily unavailable' };
232
+ }
221
233
  if (definition.execution.permissionMode === 'fullaccess') {
222
234
  if (!definition.authorizedBy) {
223
235
  return { allowed: false, reason: 'fullaccess Trigger approval provenance is missing' };
@@ -227,9 +239,6 @@ export async function authorizeTriggerExecution(definition, dependencies) {
227
239
  return { allowed: false, reason: 'fullaccess Trigger approver is no longer a current daemon-owner' };
228
240
  }
229
241
  }
230
- const origin = definition.origin;
231
- if (!origin?.peerId)
232
- return { allowed: false, reason: 'trigger origin peer is missing' };
233
242
  if (definition.execution.permissionMode === 'fullaccess') {
234
243
  return { allowed: true, scope: 'daemon', permissionMode: 'fullaccess' };
235
244
  }
@@ -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,