evolcore 0.0.43-test.6 → 0.0.43-test.7

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 (197) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/bin/ecmsg.js +171 -54
  3. package/dist/agents/baseagent-availability.js +1 -1
  4. package/dist/agents/codex/app-server-client.js +22 -0
  5. package/dist/agents/codex-runner.js +69 -2
  6. package/dist/aun/msg/p2p.js +6 -1
  7. package/dist/channels/aun.js +234 -21
  8. package/dist/cli/agent-create.js +2 -2
  9. package/dist/cli/daemon-commands.js +6 -66
  10. package/dist/cli/daemon-lifecycle-client.js +61 -0
  11. package/dist/cli/ecmsg-gateway.js +35 -2
  12. package/dist/cli/events-command.js +73 -0
  13. package/dist/cli/index.js +31 -14
  14. package/dist/cli/invoke-command.js +182 -0
  15. package/dist/cli/managed-command-guard.js +6 -1
  16. package/dist/cli/restart-monitor.js +45 -47
  17. package/dist/cli/services-command.js +111 -0
  18. package/dist/cli/team-workspace-command.js +134 -0
  19. package/dist/cli/thread-command.js +6 -2
  20. package/dist/cli/watch-msg.js +1 -1
  21. package/dist/config/config-field-policy.js +2 -2
  22. package/dist/config/config-manager.js +0 -7
  23. package/dist/config/invoke-ipc-service.js +118 -0
  24. package/dist/config/schema-migration.js +6 -1
  25. package/dist/config-store.js +2 -1
  26. package/dist/core/agent-reload-coordinator.js +6 -4
  27. package/dist/core/agent-runtime.js +104 -10
  28. package/dist/core/auth/delegation-authorization.js +66 -0
  29. package/dist/core/auth/operation-catalog.js +20 -0
  30. package/dist/core/baseagent-loader.js +60 -130
  31. package/dist/core/channel-loader.js +10 -1
  32. package/dist/core/channel-runtime.js +4 -3
  33. package/dist/core/command/agent-control.js +1 -1
  34. package/dist/core/command/agent-storage-menu.js +1 -1
  35. package/dist/core/command/chatmode-config.js +2 -36
  36. package/dist/core/command/command-handler.js +53 -11
  37. package/dist/core/command/data-root-resolver.js +32 -23
  38. package/dist/core/command/eventcenter-menu.js +338 -0
  39. package/dist/core/command/menu-catalog.js +8 -0
  40. package/dist/core/command/menu-handler.js +198 -84
  41. package/dist/core/command/menu-protocol.js +60 -11
  42. package/dist/core/command/menu-query-batch.js +194 -0
  43. package/dist/core/command/slash-gate.js +1 -1
  44. package/dist/core/command/slash-handler.js +34 -42
  45. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  46. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  47. package/dist/core/command/team-workspace-initializer.js +2 -0
  48. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  49. package/dist/core/command/team-workspace-job-store.js +88 -0
  50. package/dist/core/command/team-workspace-management-service.js +2 -0
  51. package/dist/core/command/team-workspace-management-store.js +96 -0
  52. package/dist/core/command/team-workspace-management.js +265 -0
  53. package/dist/core/command/team-workspace-members-menu.js +88 -0
  54. package/dist/core/command/team-workspace-store.js +612 -0
  55. package/dist/core/command/team-workspace-team.js +193 -0
  56. package/dist/core/daemon-control.js +8 -5
  57. package/dist/core/daemon-lifecycle.js +132 -73
  58. package/dist/core/handoff/runtime.js +3 -3
  59. package/dist/core/invoke/executors/index.js +13 -0
  60. package/dist/core/invoke/executors/media.js +283 -0
  61. package/dist/core/invoke/executors/text.js +198 -0
  62. package/dist/core/invoke/invoke-service.js +157 -0
  63. package/dist/core/invoke/style-router.js +48 -0
  64. package/dist/core/invoke/types.js +19 -0
  65. package/dist/core/ipc-registration.js +46 -7
  66. package/dist/core/memory/consolidation.js +7 -5
  67. package/dist/core/message/aun-ipc-sender.js +147 -17
  68. package/dist/core/message/im-renderer.js +28 -84
  69. package/dist/core/message/message-bridge.js +4 -0
  70. package/dist/core/message/message-utils.js +10 -2
  71. package/dist/core/message/peer-mode.js +7 -34
  72. package/dist/core/message/response-engine.js +157 -54
  73. package/dist/core/message/send-options.js +7 -4
  74. package/dist/core/message/send-routing.js +43 -5
  75. package/dist/core/ownership/owner-resolver.js +7 -0
  76. package/dist/core/permission/ec-command-parser.js +3 -2
  77. package/dist/core/permission/protected-paths.js +12 -2
  78. package/dist/core/permission/shell-environment.js +9 -0
  79. package/dist/core/session/session-file-health.js +243 -0
  80. package/dist/core/session/session-fs-store.js +2 -3
  81. package/dist/core/task/task-recovery-service.js +13 -2
  82. package/dist/core/thread/command-parser.js +9 -2
  83. package/dist/core/thread/thread-operation.js +21 -2
  84. package/dist/core/thread/thread-route.js +13 -2
  85. package/dist/directory/owner-directory-admission.js +40 -53
  86. package/dist/directory/owner-directory-cache.js +89 -113
  87. package/dist/directory/owner-directory-query-operation.js +8 -10
  88. package/dist/eck/kit-renderer.js +7 -5
  89. package/dist/ecweb/basic-settings-service.js +1 -1
  90. package/dist/ecweb/message-context-service.js +0 -4
  91. package/dist/ecweb/runtime/lifecycle.js +6 -2
  92. package/dist/ecweb/runtime/supervisor.js +19 -4
  93. package/dist/event-center/admission-materializer.js +114 -0
  94. package/dist/event-center/bus-gate.js +136 -0
  95. package/dist/event-center/bus-host.js +290 -0
  96. package/dist/event-center/bus-resolver.js +120 -0
  97. package/dist/event-center/center-config.js +100 -0
  98. package/dist/event-center/client-factory.js +50 -0
  99. package/dist/event-center/daemon.js +45 -0
  100. package/dist/event-center/directory-source.js +53 -0
  101. package/dist/event-center/dispatcher.js +157 -0
  102. package/dist/event-center/event-log.js +110 -0
  103. package/dist/event-center/index-generator.js +63 -0
  104. package/dist/event-center/ipc-operation.js +308 -0
  105. package/dist/event-center/ledger.js +52 -0
  106. package/dist/event-center/pack-loader.js +202 -0
  107. package/dist/event-center/pack-manager.js +85 -0
  108. package/dist/event-center/registry.js +238 -0
  109. package/dist/event-center/runtime.js +641 -0
  110. package/dist/event-center/script-runner.js +356 -0
  111. package/dist/event-center/types.js +35 -0
  112. package/dist/event-center/validation.js +413 -0
  113. package/dist/index.js +285 -99
  114. package/dist/ipc.js +66 -12
  115. package/dist/paths.js +20 -0
  116. package/dist/product.js +14 -0
  117. package/dist/proxy/manager.js +5 -1
  118. package/dist/proxy/service-supervisor.js +13 -4
  119. package/dist/response-system/engines/v1/index.js +0 -1
  120. package/dist/response-system/modes/single-session/index.js +1 -1
  121. package/dist/services/dispatcher.js +100 -0
  122. package/dist/services/idempotency.js +90 -0
  123. package/dist/services/identity.js +52 -0
  124. package/dist/services/index-generator.js +70 -0
  125. package/dist/services/index.js +449 -0
  126. package/dist/services/ipc-operation.js +458 -0
  127. package/dist/services/ledger.js +52 -0
  128. package/dist/services/message-log.js +112 -0
  129. package/dist/services/pack-manager.js +204 -0
  130. package/dist/services/reply.js +55 -0
  131. package/dist/services/router.js +95 -0
  132. package/dist/services/script-runner.js +422 -0
  133. package/dist/services/service-payload.js +70 -0
  134. package/dist/services/types.js +18 -0
  135. package/dist/services/validation.js +297 -0
  136. package/dist/trigger/application-service.js +18 -0
  137. package/dist/trigger/event-source.js +1 -1
  138. package/dist/trigger/ipc-service.js +3 -1
  139. package/dist/trigger/script-sandbox.js +118 -22
  140. package/dist/utils/cross-platform.js +24 -10
  141. package/dist/utils/evolcore-version.js +69 -27
  142. package/dist/utils/instance-registry.js +19 -13
  143. package/dist/utils/process-introspect.js +45 -9
  144. package/dist/utils/startup-trace.js +74 -37
  145. package/dist/utils/windows-shell-trust.js +80 -6
  146. package/kits/docs/INDEX.md +2 -2
  147. package/kits/docs/aun/ABILITY_CALLING.md +7 -14
  148. package/kits/docs/context-assembly.md +1 -1
  149. package/kits/docs/evolcore/INDEX.md +2 -0
  150. package/kits/docs/evolcore/ability.md +4 -0
  151. package/kits/docs/evolcore/aid.md +1 -1
  152. package/kits/docs/evolcore/event-center.md +207 -0
  153. package/kits/docs/evolcore/file-navigation.md +10 -264
  154. package/kits/docs/evolcore/fs.md +3 -2
  155. package/kits/docs/evolcore/group.md +1 -1
  156. package/kits/docs/evolcore/memory-architecture.md +2 -0
  157. package/kits/docs/evolcore/menu-protocol.md +21 -0
  158. package/kits/docs/evolcore/msg.md +15 -3
  159. package/kits/docs/evolcore/provider.md +3 -1
  160. package/kits/docs/evolcore/response.md +5 -5
  161. package/kits/docs/evolcore/services.md +277 -0
  162. package/kits/docs/evolcore/task.md +2 -0
  163. package/kits/docs/evolcore/team-workspace.md +41 -0
  164. package/kits/eck_manifest.json +26 -0
  165. package/kits/rules/02-navigation.md +10 -1
  166. package/kits/schemas/_meta.json +17 -6
  167. package/kits/schemas/agent-config.schema.19.json +5 -7
  168. package/kits/schemas/agent-config.schema.20.json +936 -0
  169. package/kits/schemas/relation-config.schema.12.json +2 -3
  170. package/kits/schemas/role-config.schema.2.json +4 -4
  171. package/kits/skills/.switches.json +1 -5
  172. package/kits/skills/ability/SKILL.md +56 -0
  173. package/kits/skills/ability/references/calling.md +56 -0
  174. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  175. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  176. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  177. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  178. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  179. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  180. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  181. package/kits/skills/personal-assistant/SKILL.md +6 -6
  182. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  183. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  184. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  185. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  186. package/kits/templates/system-fragments/channel.md +3 -3
  187. package/kits/templates/system-fragments/commands.md +5 -3
  188. package/kits/templates/system-fragments/reply.md +0 -5
  189. package/kits/templates/system-fragments/thread.md +10 -8
  190. package/package.json +3 -5
  191. package/dist/cli/pa-workspace-command.js +0 -225
  192. package/dist/core/command/pa-workspace-store.js +0 -468
  193. package/dist/core/relation/pa-team.js +0 -132
  194. package/kits/docs/evolcore/pa-workspace.md +0 -51
  195. package/kits/skills/aid-ability/SKILL.md +0 -244
  196. package/kits/skills/ec-ability/SKILL.md +0 -67
  197. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -27,14 +27,17 @@ import { appendMessageLog, appendMessageLogStrict, buildOutboundEntry, buildInbo
27
27
  import { createSendFileMarkerPattern } from '../core/message/file-markers.js';
28
28
  import { chatDirPath } from '../core/session/session-fs-store.js';
29
29
  import { readSessionLoopConfig, resolveSessionLoopTarget } from '../core/session/session-idle-monitor.js';
30
- import { sessionFullAccessStatus } from '../core/role/runtime-policy.js';
30
+ import { resolveRuntimePermissionMode, sessionFullAccessStatus } from '../core/role/runtime-policy.js';
31
31
  import { readTopicLabel, readTopicStatus } from '../core/session/session-mapper.js';
32
32
  import { appendHintAddDetailed, appendHintRemoveDetailed, appendHintPromoteDetailed, parseInjectRequest, peekHints, withHintTargetLock } from '../core/message/pending-hints.js';
33
33
  import { appendAidLifecycle } from '../aun/aid/identity.js';
34
34
  import { getAidStore, loadClient, SLOT } from '../aun/aid/store.js';
35
+ import { classifyServicePayloadType, getServiceRouter, readLocalSelfIdentity, } from '../services/index.js';
36
+ import { agentServicesDir } from '../paths.js';
35
37
  import { MAX_AUN_ATTACHMENT_SIZE, uploadBufferAndBuildPayload, uploadFileAndBuildPayload } from '../aun/msg/upload.js';
36
38
  import { loadAgent } from '../config-store.js';
37
39
  import { configuredOwnerList, firstConfiguredOwner } from '../config/owner-config.js';
40
+ import { resolvePeerRoleDetail } from '../config/peer-role-resolver.js';
38
41
  import { resolveAgentLifecycle } from '../config/lifecycle.js';
39
42
  import { resolveEffective } from '../config/config-manager.js';
40
43
  import { isManagementRole } from '../config/builtin-roles.js';
@@ -805,6 +808,14 @@ export class AUNChannel {
805
808
  ownerDirectoryRetryAttempts = 0;
806
809
  ownerDirectoryResolvedSignature;
807
810
  store = null;
811
+ /** 服务路由实例(懒建;services/router.json 不存在时也建,只是总闸关闭)。 */
812
+ serviceRouter = null;
813
+ /**
814
+ * 本 agent 的工程目录,由插件从 `ChannelBuildContext.defaultProjectPath` 注入。
815
+ * 与 `onProjectPathRequest`(附件落盘)同源;服务脚本沙箱的 cwd 也用它,
816
+ * 保证同一条 invoke 链路上所有消费方看到的是同一个目录。
817
+ */
818
+ defaultProjectPath;
808
819
  /** 实际连接的网关 URL(来自 authenticate() 返回值 / connection.state 事件),替代旧 (client as any)._gatewayUrl。 */
809
820
  gatewayUrl = '';
810
821
  projectPathProvider;
@@ -2007,11 +2018,12 @@ export class AUNChannel {
2007
2018
  if (runtime.ownerAid !== senderAid || !sameContactBinding(binding, currentContactBinding(selfAid)))
2008
2019
  return;
2009
2020
  runtime.cache.saveAuthorization(parsed);
2010
- logger.info(`${this.logPrefix()} owner.directory.grant: authorization saved for ${selfAid}`);
2011
- // 授权被撤销/拒绝时 saveAuthorization 已经清掉凭证和快照,这里无事可做:
2012
- // 下一次 owner.directory.changed 会写 pending,准入回落到"名录不可用"。
2013
- if (runtime.cache.scopeAccess('contacts') !== 'authorized')
2021
+ if (runtime.cache.isRevoked())
2014
2022
  return;
2023
+ logger.info(`${this.logPrefix()} owner.directory.grant: grant applied for ${selfAid}`);
2024
+ // 撤销/拒绝时 saveAuthorization 已经清掉本地快照,这里无事可做:
2025
+ // 持久化撤权边界会阻止后续 changed 或共享广播恢复旧快照。
2026
+ // 生效时 grant 清除撤权状态,并触发拉取。
2015
2027
  // 授权是 Owner 的主动操作,用户点完就在等结果。写标记 + 立即拉取 + 落地,
2016
2028
  // 不再等"下一条入站消息"——那条消息可能几小时后才来。
2017
2029
  await runtime.cache.handleOwnerChangedEvent(senderAid);
@@ -2459,6 +2471,12 @@ export class AUNChannel {
2459
2471
  // Peer snapshots refresh lazily on the next lookup. The self name is
2460
2472
  // held separately by this channel, so refresh it with the existing API.
2461
2473
  if (aid === (this._aid || this.config.aid)) {
2474
+ // 名片 type/exttype 是 requires 判定的依据:变更后重新扫描包。
2475
+ if (this.serviceRouter) {
2476
+ const identity = readLocalSelfIdentity(aid) ?? { aid, type: 'agent', exttype: '' };
2477
+ this.serviceRouter.ensureStarted(identity);
2478
+ this.serviceRouter.reload();
2479
+ }
2462
2480
  void refreshAgentDisplayName(aid).then(name => {
2463
2481
  if (!name || !isCurrentClient() || this.intentionalDisconnect)
2464
2482
  return;
@@ -2959,7 +2977,7 @@ export class AUNChannel {
2959
2977
  }
2960
2978
  async downloadAttachment(att, channelId, delivery) {
2961
2979
  const ownerAid = att.owner_aid
2962
- || (delivery?.chatType === 'private' ? channelId : '')
2980
+ || (delivery?.chatType === 'private' && !delivery.service ? channelId : '')
2963
2981
  || this._aid
2964
2982
  || '';
2965
2983
  const objectKey = att.object_key;
@@ -3309,7 +3327,50 @@ export class AUNChannel {
3309
3327
  }
3310
3328
  return;
3311
3329
  }
3330
+ // ── 服务路由:应答与请求分两支,应答优先。 ──
3331
+ // 应答必须早于请求分支,否则会被 unmatched 静默丢弃,等待者永远收不到结果。
3332
+ // 插在这里(claim 之前):服务分支无条件自己 claim 一次,之后既有路径原样不动。
3333
+ const serviceKind = classifyServicePayloadType(msg.payload?.type);
3334
+ if (serviceKind === 'result') {
3335
+ // 交给既有请求注册表匹配;命中后由它更新记录并唤醒等待者。
3336
+ const matched = getAunRequestRegistry().resolveIncoming({
3337
+ selfAid: this._aid || this.config.aid,
3338
+ fromAid,
3339
+ fromDeviceId: typeof msg.sender_device_id === 'string' ? msg.sender_device_id : undefined,
3340
+ messageId,
3341
+ payload: msg.payload,
3342
+ encrypted: !!env.encrypted,
3343
+ transport: 'p2p',
3344
+ });
3345
+ if (matched)
3346
+ return;
3347
+ logger.debug(`${this.logPrefix()} Unmatched service result: mid=${messageId} from=${fromAid}`);
3348
+ return;
3349
+ }
3350
+ if (serviceKind === 'request') {
3351
+ if (!this.claimInboundMessage('private', messageId, seq))
3352
+ return;
3353
+ await this.handleServiceMessage({
3354
+ fromAid,
3355
+ messageId,
3356
+ encrypted: !!env.encrypted,
3357
+ receivedAt,
3358
+ payload: (msg.payload && typeof msg.payload === 'object') ? msg.payload : {},
3359
+ });
3360
+ return;
3361
+ }
3312
3362
  const appOwned = !this.config.pureIdentity;
3363
+ // ── 事件中心隔离(P1)──
3364
+ // AUN pubsub 事件(aun.pubsub/1)在传输层是加密 P2P 消息,与聊天共用 message.received 流。
3365
+ // 只凭受保护头判定(SDK 归一化后的可信信号;payload.type 可伪造,不单独作为依据),
3366
+ // 在去重表/observer 镜像/身份解析/入站日志/回声过滤之前早退:
3367
+ // 事件只由 EventService 的 onEvent 消费,消息层不产生会话、不进 thread。
3368
+ const earlyProtectedHeaders = verifiedProtectedHeaders(msg, env);
3369
+ if (earlyProtectedHeaders?.message_class === 'sdk_control'
3370
+ && earlyProtectedHeaders.sdk_control_protocol === 'aun.pubsub') {
3371
+ logger.debug(`${this.logPrefix()} P2P dropped: pubsub control envelope (mid=${messageId})`);
3372
+ return;
3373
+ }
3313
3374
  if (!appOwned && !this.claimInboundMessage('private', messageId, seq))
3314
3375
  return;
3315
3376
  const protectedHeaders = verifiedProtectedHeaders(msg, env);
@@ -3400,6 +3461,18 @@ export class AUNChannel {
3400
3461
  logger.info(`${this.logPrefix()} P2P dropped terminal error: from=${fromAid || 'unknown'} mid=${messageId}`);
3401
3462
  return;
3402
3463
  }
3464
+ // ── services 模式:常规消息只认 Owner,其余一律不进 Agent。 ──
3465
+ // 判定放在准入之后、observer 镜像之前:blocked 静默,非 Owner 回引导语。
3466
+ // 只认本机名片 type === 'services';普通 agent 完全不受影响。
3467
+ if (appOwned && readLocalSelfIdentity(this.config.aid)?.type === 'services') {
3468
+ const decision = evaluateAppContactAdmission(this.config.aid, fromAid);
3469
+ if (!decision.allow || decision.reason !== 'owner') {
3470
+ if (decision.reason !== 'blocked') {
3471
+ await this.replyServiceModeRejection(fromAid, inboundType, !!env.encrypted);
3472
+ }
3473
+ return;
3474
+ }
3475
+ }
3403
3476
  // Observer forward (inbound):在所有过滤之前转发原始明文 payload。
3404
3477
  // forwardInbound 内部排除 self-echo 与 from-owner。
3405
3478
  // 显式排除 observer.inject:它是 owner 对本 agent 的控制消息,不应镜像给观察者
@@ -4857,6 +4930,126 @@ export class AUNChannel {
4857
4930
  onProjectPathRequest(provider) {
4858
4931
  this.projectPathProvider = provider;
4859
4932
  }
4933
+ /**
4934
+ * 注入本 agent 的工程目录(`ChannelBuildContext.defaultProjectPath`)。
4935
+ * 服务脚本在非 fullaccess 档位下以它为沙箱 cwd;未注入时服务脚本按
4936
+ * `SCRIPT_SANDBOX_UNAVAILABLE` 明确拒绝,不回落 `process.cwd()`——
4937
+ * 后者会把整个 EvolCore 仓当成工程目录,沙箱边界会被悄悄放大。
4938
+ */
4939
+ setDefaultProjectPath(projectPath) {
4940
+ const trimmed = projectPath?.trim();
4941
+ this.defaultProjectPath = trimmed ? trimmed : undefined;
4942
+ }
4943
+ // ── 服务路由 ────────────────────────────────────────────────────────────
4944
+ /** 供 daemon 启动时预热与 IPC 运维取用(不改变懒建语义)。 */
4945
+ getServiceRouter() {
4946
+ return this.ensureServiceRouter();
4947
+ }
4948
+ /**
4949
+ * 懒建服务路由实例并完成首次扫描。
4950
+ * identity 用本地名片(不触发网络);requires 判定与 ECK 变量读同一份。
4951
+ */
4952
+ ensureServiceRouter() {
4953
+ if (this.serviceRouter)
4954
+ return this.serviceRouter;
4955
+ const aid = this.config.aid;
4956
+ const identity = readLocalSelfIdentity(aid) ?? { aid, type: 'agent', exttype: '' };
4957
+ this.serviceRouter = getServiceRouter(aid, agentServicesDir(aid), {
4958
+ aid,
4959
+ identity: () => readLocalSelfIdentity(aid) ?? identity,
4960
+ // 与 trigger / 事件中心同源:agent 的工程目录。沙箱要求绝对真实目录,
4961
+ // 存在性与 H/L 分类由 buildTriggerScriptLaunch 自己校验并明确报错。
4962
+ getProjectPath: () => this.defaultProjectPath,
4963
+ permissionMode: () => resolveRuntimePermissionMode({ selfAid: aid }).effectiveValue,
4964
+ // bypass + owner 才免沙箱;角色取调用方(service 消息的 from)。解析失败按未知处理。
4965
+ resolvePeerRole: fromAid => {
4966
+ try {
4967
+ return resolvePeerRoleDetail({
4968
+ selfAid: aid,
4969
+ channelKey: `aun#${aid}#main`,
4970
+ channelType: 'aun',
4971
+ chatType: 'private',
4972
+ actorId: fromAid,
4973
+ conversationId: fromAid,
4974
+ }).effectiveRole;
4975
+ }
4976
+ catch {
4977
+ return undefined;
4978
+ }
4979
+ },
4980
+ });
4981
+ this.serviceRouter.ensureStarted(identity);
4982
+ return this.serviceRouter;
4983
+ }
4984
+ /**
4985
+ * services 模式下给非 Owner 的引导回复。
4986
+ * 协议消息(menu./bind./observer./friend./contact.request.)一律静默;受限流(builtin),超限静默。
4987
+ */
4988
+ async replyServiceModeRejection(toAid, inboundType, encrypted) {
4989
+ const type = typeof inboundType === 'string' ? inboundType : '';
4990
+ if (type.startsWith('menu.') || type.startsWith('bind.') || type.startsWith('observer.')
4991
+ || type.startsWith('friend.') || type.startsWith('contact.request.'))
4992
+ return;
4993
+ const router = this.ensureServiceRouter();
4994
+ const limit = router.consumeBuiltinQuota(toAid);
4995
+ if (!limit.allow)
4996
+ return;
4997
+ const text = `我是服务节点,只接受 Owner 的直接消息。\n可用的服务调用方式:ec services describe ${this.config.aid}\n如需联系,请通过 Owner 申请。`;
4998
+ const result = await this.sendStructuredResult(toAid, { type: 'text', text }, {
4999
+ delivery: { chatType: 'private' },
5000
+ metadata: { encrypted, source: 'daemon' },
5001
+ });
5002
+ if (!result.ok) {
5003
+ logger.debug(`${this.logPrefix()} Service-mode rejection not delivered: code=${result.code ?? 'UNKNOWN'} to=${toAid}`);
5004
+ }
5005
+ }
5006
+ /** 服务调用的准入判决。blocked 静默;其余未通过回 NOT_AUTHORIZED。 */
5007
+ serviceAdmission(fromAid) {
5008
+ const decision = evaluateAppContactAdmission(this.config.aid, fromAid);
5009
+ if (decision.allow)
5010
+ return { admission: 'allow' };
5011
+ if (decision.reason === 'blocked')
5012
+ return { admission: 'blocked' };
5013
+ return { admission: 'not_authorized', requestContact: currentContactBinding(this.config.aid)?.owner_aid };
5014
+ }
5015
+ /**
5016
+ * 入站服务消息(请求支)。调用方已完成 claim。
5017
+ * 应答支不经过这里——那由 AunRequestRegistry 在消息层更早匹配。
5018
+ */
5019
+ async handleServiceMessage(input) {
5020
+ const router = this.ensureServiceRouter();
5021
+ const payload = input.payload;
5022
+ const rawType = typeof payload.type === 'string' ? payload.type : '';
5023
+ const requestId = typeof payload.request_id === 'string' && payload.request_id
5024
+ ? payload.request_id
5025
+ : input.messageId;
5026
+ const message = {
5027
+ type: rawType,
5028
+ requestId,
5029
+ requestIdGenerated: requestId === input.messageId,
5030
+ fromAid: input.fromAid,
5031
+ messageId: input.messageId,
5032
+ encrypted: input.encrypted,
5033
+ payload,
5034
+ receivedAt: input.receivedAt,
5035
+ };
5036
+ const { admission, requestContact } = this.serviceAdmission(input.fromAid);
5037
+ const reply = await router.handleRequest(message, { admission, requestContact });
5038
+ if (!reply.shouldSend)
5039
+ return;
5040
+ await this.sendServiceReply(input.fromAid, input.messageId, input.encrypted, reply);
5041
+ }
5042
+ /** 回复:点对点、带 service 标记位,不带 threadId/topicName/chatmode。 */
5043
+ async sendServiceReply(toAid, replyToMessageId, encrypted, reply) {
5044
+ const result = await this.sendStructuredResult(toAid, reply.payload, {
5045
+ delivery: { chatType: 'private', service: { type: reply.type, requestId: reply.requestId } },
5046
+ metadata: { encrypted, source: 'daemon' },
5047
+ replyToMessageId,
5048
+ });
5049
+ if (!result.ok) {
5050
+ logger.warn(`${this.logPrefix()} Service reply send failed: type=${reply.type} code=${result.code ?? 'UNKNOWN'} error=${result.error ?? ''}`);
5051
+ }
5052
+ }
4860
5053
  setSessionStateResolver(resolver) {
4861
5054
  this.sessionStateResolver = resolver;
4862
5055
  }
@@ -5324,6 +5517,10 @@ export class AUNChannel {
5324
5517
  }
5325
5518
  }
5326
5519
  appContactOutboundBlock(channelId, delivery, payload, params) {
5520
+ // 服务回复是对一次已到达请求的应答,不是主动联系;且拒绝信息本身必须能送达,
5521
+ // 否则调用方只会看到超时。
5522
+ if (delivery.chatType === 'private' && delivery.service)
5523
+ return undefined;
5327
5524
  if (delivery.chatType === 'group' || this.config.pureIdentity
5328
5525
  || this.hasContactControlPermit(channelId, payload, params))
5329
5526
  return undefined;
@@ -5338,6 +5535,8 @@ export class AUNChannel {
5338
5535
  error: `联系人准入未通过:${decision.reason}` };
5339
5536
  }
5340
5537
  async prepareAppContactOutbound(channelId, delivery, payload, params) {
5538
+ if (delivery.chatType === 'private' && delivery.service)
5539
+ return undefined;
5341
5540
  if (delivery.chatType === 'private' && !this.config.pureIdentity
5342
5541
  && !this.hasContactControlPermit(channelId, payload, params)
5343
5542
  && !this.acceptsVerifiedOwnership(channelId, payload, params)) {
@@ -5381,7 +5580,7 @@ export class AUNChannel {
5381
5580
  logger.error(`${this.logPrefix()} Dropped durable AUN payload: invalid payload.mentions (${detail}) code=${code} channel=${channelId}`);
5382
5581
  return { ok: false, status: 'permanent', error: detail, code };
5383
5582
  }
5384
- if (delivery.chatType === 'private') {
5583
+ if (delivery.chatType === 'private' && !delivery.service) {
5385
5584
  normalizedPayload = this.withCurrentTopicName(channelId, normalizedPayload);
5386
5585
  }
5387
5586
  if (!this.client || !this.connected) {
@@ -5406,6 +5605,12 @@ export class AUNChannel {
5406
5605
  // Truncate payload if too large (AUN SDK limit: 1MB)
5407
5606
  const friendPayload = typeof payload.type === 'string' && payload.type.startsWith('friend.');
5408
5607
  const truncatedPayload = friendPayload ? payloadWithCausationRef : this.truncatePayloadIfNeeded(await this.withSessionState(channelId, payloadWithCausationRef, context), label);
5608
+ if (payload.type === 'activity' && truncatedPayload.type !== 'activity') {
5609
+ return {
5610
+ ok: false, status: 'permanent', code: 'PAYLOAD_TOO_LARGE',
5611
+ error: 'activity payload cannot fit the AUN limit without losing its structure',
5612
+ };
5613
+ }
5409
5614
  const params = { payload: truncatedPayload, encrypt };
5410
5615
  const isMenuPayload = typeof truncatedPayload.type === 'string' && truncatedPayload.type.startsWith('menu.');
5411
5616
  if (!isGroup && ['menu.response', 'menu.event'].includes(truncatedPayload.type))
@@ -5962,7 +6167,7 @@ export class AUNChannel {
5962
6167
  code: 'INVALID_REQUEST_TTL',
5963
6168
  };
5964
6169
  }
5965
- const contactBlock = await this.prepareAppContactOutbound(args.to, { chatType: 'private' }, finalPayload, { encrypt: args.encrypt, rawPayload: preserveRawPayload, ownershipVerified: args.ownershipVerified === true });
6170
+ const contactBlock = await this.prepareAppContactOutbound(args.to, args.service ? { chatType: 'private', service: args.service } : { chatType: 'private' }, finalPayload, { encrypt: args.encrypt, rawPayload: preserveRawPayload, ownershipVerified: args.ownershipVerified === true });
5966
6171
  if (contactBlock)
5967
6172
  return { ok: false, code: contactBlock.code, error: contactBlock.error };
5968
6173
  if (preserveRawPayload && jsonUtf8Size(finalPayload) > AUN_MAX_PAYLOAD_SIZE) {
@@ -5999,7 +6204,8 @@ export class AUNChannel {
5999
6204
  peerKey: formatPeerKey('aun', args.to),
6000
6205
  });
6001
6206
  }
6002
- if (chatmode && !finalPayload.chatmode)
6207
+ // 服务调用不是会话消息:不注入 chatmode,避免对端入站日志与脚本 data 被会话字段污染。
6208
+ if (chatmode && !finalPayload.chatmode && !args.service)
6003
6209
  finalPayload.chatmode = chatmode;
6004
6210
  const parentCausation = preserveRawPayload ? undefined : normalizeCausation(args.causation);
6005
6211
  const outboundCausation = parentCausation ? deriveCausation(parentCausation) : undefined;
@@ -6010,7 +6216,7 @@ export class AUNChannel {
6010
6216
  }
6011
6217
  if (args.debug)
6012
6218
  finalPayload.debug = { ...args.debug, sentAt: localTimestamp() };
6013
- if (!preserveRawPayload) {
6219
+ if (!preserveRawPayload && !args.service) {
6014
6220
  finalPayload = this.withCurrentTopicName(args.to, finalPayload);
6015
6221
  }
6016
6222
  if (!preserveRawPayload) {
@@ -6045,7 +6251,12 @@ export class AUNChannel {
6045
6251
  }
6046
6252
  this.forwardOutbound(result, args.debug);
6047
6253
  let logWritten = false;
6048
- if (args.log?.content !== undefined) {
6254
+ // 自发(`--to <本端AID>`)不写出站日志:chatDir 会按 (to=本端, self=本端) 算成
6255
+ // 「我↔我」目录,`ThreadService.listPeers` 的磁盘兜底会把它列成真实对端,
6256
+ // 而话题 T 的历史里也会凭空多出一条「发给本端自己」的出站记录。
6257
+ // 「自己收到了什么」由本地注入那条入站记录(source='self-address')表达。
6258
+ const selfAddressed = args.to.replace(/^@/, '').toLowerCase() === this.config.aid.replace(/^@/, '').toLowerCase();
6259
+ if (!selfAddressed && args.log?.content !== undefined) {
6049
6260
  const classified = classifyAunPayloadForLog(finalPayload);
6050
6261
  const chatDir = chatDirPath(resolvePaths().sessionsDir, 'aun', args.to, this.config.aid);
6051
6262
  fs.mkdirSync(chatDir, { recursive: true });
@@ -6356,7 +6567,7 @@ export class AUNChannel {
6356
6567
  payload.chatmode = context.metadata.chatmode;
6357
6568
  if (context?.metadata?.forkAnchor)
6358
6569
  payload.fork_anchor = context.metadata.forkAnchor;
6359
- if (delivery.chatType === 'private') {
6570
+ if (delivery.chatType === 'private' && !delivery.service) {
6360
6571
  Object.assign(payload, this.withCurrentTopicName(channelId, payload));
6361
6572
  }
6362
6573
  const causation = normalizeCausation(context?.metadata?.causation);
@@ -6763,7 +6974,7 @@ export class AUNChannel {
6763
6974
  if (context?.debug)
6764
6975
  payloadWithChatmode.debug = { ...context.debug, sentAt: localTimestamp() };
6765
6976
  let thoughtPayload = payloadWithChatmode;
6766
- if (delivery.chatType === 'private') {
6977
+ if (delivery.chatType === 'private' && !delivery.service) {
6767
6978
  thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
6768
6979
  }
6769
6980
  thoughtPayload = this.limitThoughtPayload(thoughtPayload);
@@ -6812,7 +7023,7 @@ export class AUNChannel {
6812
7023
  if (!isThoughtTooLargeError(error))
6813
7024
  throw error;
6814
7025
  thoughtPayload = this.thoughtPayloadFallback(thoughtPayload);
6815
- if (delivery.chatType === 'private') {
7026
+ if (delivery.chatType === 'private' && !delivery.service) {
6816
7027
  thoughtPayload = this.withCurrentTopicName(channelId, thoughtPayload);
6817
7028
  }
6818
7029
  params.payload = thoughtPayload;
@@ -6871,7 +7082,7 @@ export class AUNChannel {
6871
7082
  finalPayload.thread_id = context.threadId;
6872
7083
  if (context?.replyToMessageId && !finalPayload.ref_message_id)
6873
7084
  finalPayload.ref_message_id = context.replyToMessageId;
6874
- if (!isGroup) {
7085
+ if (!isGroup && !delivery.service) {
6875
7086
  Object.assign(finalPayload, this.withCurrentTopicName(channelId, finalPayload));
6876
7087
  }
6877
7088
  const isMenuPayload = typeof finalPayload.type === 'string' && finalPayload.type.startsWith('menu.');
@@ -6912,7 +7123,8 @@ export class AUNChannel {
6912
7123
  return { ok: false, ...failure };
6913
7124
  }
6914
7125
  logger.info(`${this.logPrefix()} message.send (${payload.type}) ok: to=${this.peerLabel(targetAid)} mid=${mid} encrypt=${encrypt}`);
6915
- if (!isMenuPayload)
7126
+ // 服务回复不进 observer 镜像(回归 13)。
7127
+ if (!isMenuPayload && !delivery.service)
6916
7128
  this.forwardOutbound(result);
6917
7129
  return { ok: true, messageId: mid };
6918
7130
  }
@@ -7191,7 +7403,7 @@ export class AUNChannel {
7191
7403
  attachment: { ...attachment },
7192
7404
  context,
7193
7405
  }), context);
7194
- if (!isGroup) {
7406
+ if (!isGroup && !delivery.service) {
7195
7407
  Object.assign(filePayload, this.withCurrentTopicName(channelId, filePayload));
7196
7408
  }
7197
7409
  const fileTargetAid = channelId;
@@ -7814,6 +8026,8 @@ export class AUNChannelPlugin {
7814
8026
  aunTrace: ctx.debug?.aunTrace,
7815
8027
  aunSdkLog: ctx.debug?.aunSdkLog,
7816
8028
  });
8029
+ // 工程目录:服务脚本沙箱 cwd 与附件落盘共用同一个来源。
8030
+ channel.setDefaultProjectPath(ctx.defaultProjectPath);
7817
8031
  const mode = resolveShowActivities(inst);
7818
8032
  const adapter = {
7819
8033
  channelName: inst.name,
@@ -8039,13 +8253,12 @@ export class AUNChannelPlugin {
8039
8253
  continue;
8040
8254
  }
8041
8255
  const aunPayload = channel.buildActivityPayload(envelope, replyCtx, item);
8042
- if (envelope.chatmode === 'proactive') {
8256
+ if (envelope.chatmode === 'proactive' && envelope.activityTransport !== 'message') {
8043
8257
  await channel.sendThought(channelId, envelope.taskId, aunPayload, replyCtx);
8044
8258
  }
8045
8259
  else {
8046
- // Interactive and PA activities are reliable structured payloads;
8047
- // sendReliableStructured internally selects the activity
8048
- // outbox queue while preserving the common delivery contract.
8260
+ // The PA's proactive activities share interactive's reliable
8261
+ // activity outbox without changing the execution flow.
8049
8262
  const result = await channel.sendReliableStructured(channelId, aunPayload, replyCtx, channel.activityLogText(item));
8050
8263
  // Test and legacy adapters may stub this method without a
8051
8264
  // structured result; the call itself still proves acceptance.
@@ -1133,8 +1133,8 @@ export function validateInitializationPlan(plan) {
1133
1133
  if (plan.chatmode !== undefined) {
1134
1134
  if (!plan.chatmode || typeof plan.chatmode !== 'object' || Array.isArray(plan.chatmode)
1135
1135
  || Object.entries(plan.chatmode).some(([scope, value]) => !['private', 'group', 'nothuman'].includes(scope)
1136
- || !(scope === 'group' ? ['proactive'] : ['interactive', 'proactive', ...(scope === 'private' ? ['paactive'] : [])]).includes(value))) {
1137
- failure('INVALID_ARGS', 'chatmode.group must be proactive; paactive is private AUN only');
1136
+ || !(scope === 'group' ? ['proactive'] : ['interactive', 'proactive']).includes(value))) {
1137
+ failure('INVALID_ARGS', 'chatmode.group must be proactive; private/nothuman must be interactive or proactive');
1138
1138
  }
1139
1139
  }
1140
1140
  if (plan.avatarFile !== undefined && plan.avatarUrl !== undefined)
@@ -32,7 +32,8 @@ import { logLevelRank } from '../utils/logger.js';
32
32
  import { inspectDataMigrationRequirement } from '../core/data-migration.js';
33
33
  import { readHostInfo, readVersionInfo } from '../utils/host-info.js';
34
34
  import { queryStatusActivity, queryStatusActivityByAgent } from '../stats/query.js';
35
- import { listCodexAppServerProcesses, unregisterCodexAppServerProcess } from '../agents/codex/app-server-registry.js';
35
+ import { DAEMON_PROBE_TIMEOUT_MS, DAEMON_SHUTDOWN_TIMEOUT_MS, probeDaemon, requestDaemonShutdown } from './daemon-lifecycle-client.js';
36
+ export { DAEMON_SHUTDOWN_TIMEOUT_MS, requestDaemonShutdown, stopCodexAppServerOrphans } from './daemon-lifecycle-client.js';
36
37
  import { DEFAULT_ECWEB_PORT, ecwebService, serviceRuntimeMode, setEcwebEnabled } from '../config/daemon-services.js';
37
38
  import { checkCodexProjectPath, inspectCodexManagedHook, ensureCodexManagedHook, runCodexHookLaunchDiagnostic, } from '../agents/codex/diagnostics.js';
38
39
  import { formatClaudeSandboxDependencies, formatCodexSandboxAvailability, inspectClaudeSandboxDependencies, inspectCodexSandboxAvailability, probeClaudeSandboxDependencies, probeCodexSandboxAvailability, } from '../core/permission/sandbox-runtime.js';
@@ -135,37 +136,6 @@ function printNoSelfAgentHints(options) {
135
136
  console.log(` - ${skippedAgent.dirName}: ${skippedAgent.reason}`);
136
137
  }
137
138
  }
138
- // Windows named-pipe connection setup can take a couple of seconds on a busy
139
- // host (especially on the first request after the daemon starts). A one-second
140
- // probe causes `ec stop` to skip the IPC shutdown path and fall back to
141
- // taskkill, even though the daemon is healthy and able to shut down gracefully.
142
- const DAEMON_PROBE_TIMEOUT_MS = platform.isWindows ? 5_000 : 1_000;
143
- export const DAEMON_SHUTDOWN_TIMEOUT_MS = platform.isWindows ? 10_000 : 3_000;
144
- async function probeDaemon(socketPath, timeoutMs = DAEMON_PROBE_TIMEOUT_MS, throwOnError = false) {
145
- const response = await ipcQuery(socketPath, { type: 'ping' }, timeoutMs, { throwOnError });
146
- if (response?.pong !== true || !Number.isInteger(response.pid) || response.pid <= 0)
147
- return null;
148
- return response;
149
- }
150
- /** Ask the daemon to run its own graceful shutdown lifecycle. */
151
- export async function requestDaemonShutdown(socketPath, timeoutMs = DAEMON_SHUTDOWN_TIMEOUT_MS, reason = 'cli', expectedPids, traceId) {
152
- const daemon = await probeDaemon(socketPath, Math.min(timeoutMs, DAEMON_PROBE_TIMEOUT_MS));
153
- if (!daemon || (expectedPids && !expectedPids.has(daemon.pid)))
154
- return null;
155
- const response = await ipcQuery(socketPath, {
156
- type: 'shutdown',
157
- reason,
158
- expectedPid: daemon.pid,
159
- // 让 daemon 侧退出阶段落进同一条停止甘特图(时间轴按同一次停止对齐)。
160
- ...(traceId ? { traceId } : {}),
161
- }, timeoutMs);
162
- if (response?.ok !== true || response.accepted !== true
163
- || !Number.isInteger(response.pid) || response.pid <= 0
164
- || response.pid !== daemon.pid) {
165
- return null;
166
- }
167
- return response.pid;
168
- }
169
139
  function hasVisibleDaemonPid(status, ping) {
170
140
  return status.mains.some(entry => entry.alive && entry.record.pid === ping.pid);
171
141
  }
@@ -1513,12 +1483,13 @@ function renderStatusOverview(snapshot) {
1513
1483
  renderStatusFields(overviewFields);
1514
1484
  const startup = snapshot.daemon.startup;
1515
1485
  if (startup) {
1516
- const phases = { classifying: '识别待恢复任务(控制面可用)', recovering: '优先恢复进行中任务', loading: '加载其余 Agent', ready: '正常 Ready', failed: '启动未就绪(关键模块失败)' };
1517
- const states = { waiting: '等待前置阶段', starting: '启动中', recovering: '恢复运行中任务', ready: '已就绪', failed: '失败', disabled: '已禁用' };
1486
+ const phases = { classifying: '识别待恢复任务(控制面可用)', recovering: '优先恢复进行中任务', loading: '完成启动准入', ready: '正常 Ready', failed: '启动未就绪(关键模块失败)' };
1487
+ const states = { waiting: '等待前置阶段', starting: '启动中', recovering: '恢复运行中任务', ready: '已就绪', failed: '失败', disabled: '已禁用', deferred: '按需加载(未加载)' };
1518
1488
  const agents = startup.agents;
1519
1489
  renderStatusFields([
1520
1490
  ['启动进度', phases[startup.phase]],
1521
1491
  ['已加载', `Runner ${agents.filter(agent => agent.runner === 'ready').length}/${agents.length}`
1492
+ + `(按需 ${agents.filter(agent => agent.runner === 'deferred').length})`
1522
1493
  + ` · AUN ${agents.filter(agent => agent.aun).length}/${agents.length}`
1523
1494
  + ` · 恢复登记 ${agents.filter(agent => agent.recovery).length}/${agents.length}`
1524
1495
  + ` · Trigger ${startup.triggers.loaded}/${startup.triggers.total}`],
@@ -2938,7 +2909,7 @@ async function cmdWatchAid() {
2938
2909
  // 标记生成:[明文/密文|自主/响应](紫色=工具渲染标记)
2939
2910
  const mkTags = (encrypt, chatmode) => {
2940
2911
  const enc = encrypt ? '密文' : '明文';
2941
- const mode = chatmode === 'paactive' ? 'PA' : chatmode === 'proactive' ? '自主' : '响应';
2912
+ const mode = chatmode === 'proactive' ? '自主' : '响应';
2942
2913
  return `${MAGENTA}[${enc}|${mode}]${RST}`;
2943
2914
  };
2944
2915
  let msgPreview = '';
@@ -3393,37 +3364,6 @@ async function stopStartedEcweb(pid, expectedStartedAt) {
3393
3364
  return false;
3394
3365
  return platform.waitForProcessExit(pid, 5_000);
3395
3366
  }
3396
- /** 清理 EvolCore 登记的 codex app-server 孤儿进程,返回清理的进程数。 */
3397
- export function stopCodexAppServerOrphans() {
3398
- const entries = listCodexAppServerProcesses();
3399
- if (entries.length === 0)
3400
- return 0;
3401
- const codexProcs = new Set(platform.findProcesses('codex app-server'));
3402
- let killed = 0;
3403
- for (const entry of entries) {
3404
- const { pid, startedAt } = entry.record;
3405
- if (!platform.isProcessRunning(pid)) {
3406
- unregisterCodexAppServerProcess(entry.filePath);
3407
- continue;
3408
- }
3409
- // PID 复用时丢弃登记,不发送信号;命令行探测失败则保留登记,等待下次重试。
3410
- const actualStartedAt = getProcessStartTime(pid);
3411
- if (!startTimeMatches(startedAt, actualStartedAt)) {
3412
- unregisterCodexAppServerProcess(entry.filePath);
3413
- continue;
3414
- }
3415
- if (!codexProcs.has(pid))
3416
- continue;
3417
- try {
3418
- if (platform.killProcess(pid, true)) {
3419
- killed++;
3420
- unregisterCodexAppServerProcess(entry.filePath);
3421
- }
3422
- }
3423
- catch { }
3424
- }
3425
- return killed;
3426
- }
3427
3367
  /** Stop managed ECWeb, including verified listeners without instance records. */
3428
3368
  async function stopManagedEcweb(p) {
3429
3369
  try {
@@ -0,0 +1,61 @@
1
+ import { ipcQuery } from '../ipc.js';
2
+ import * as platform from '../utils/cross-platform.js';
3
+ import { getProcessStartTime, startTimeMatches } from '../utils/process-introspect.js';
4
+ import { listCodexAppServerProcesses, unregisterCodexAppServerProcess } from '../agents/codex/app-server-registry.js';
5
+ // A busy Windows named pipe may need several seconds to accept a connection.
6
+ export const DAEMON_PROBE_TIMEOUT_MS = platform.isWindows ? 5_000 : 1_000;
7
+ export const DAEMON_SHUTDOWN_TIMEOUT_MS = platform.isWindows ? 10_000 : 3_000;
8
+ export async function probeDaemon(socketPath, timeoutMs = DAEMON_PROBE_TIMEOUT_MS, throwOnError = false) {
9
+ const response = await ipcQuery(socketPath, { type: 'ping' }, timeoutMs, { throwOnError });
10
+ if (response?.pong !== true || !Number.isInteger(response.pid) || response.pid <= 0)
11
+ return null;
12
+ return response;
13
+ }
14
+ /** Ask the verified daemon to run its own graceful shutdown lifecycle. */
15
+ export async function requestDaemonShutdown(socketPath, timeoutMs = DAEMON_SHUTDOWN_TIMEOUT_MS, reason = 'cli', expectedPids, traceId) {
16
+ const daemon = await probeDaemon(socketPath, Math.min(timeoutMs, DAEMON_PROBE_TIMEOUT_MS));
17
+ if (!daemon || (expectedPids && !expectedPids.has(daemon.pid)))
18
+ return null;
19
+ const response = await ipcQuery(socketPath, {
20
+ type: 'shutdown',
21
+ reason,
22
+ expectedPid: daemon.pid,
23
+ ...(traceId ? { traceId } : {}),
24
+ }, timeoutMs);
25
+ if (response?.ok !== true || response.accepted !== true
26
+ || !Number.isInteger(response.pid) || response.pid <= 0
27
+ || response.pid !== daemon.pid)
28
+ return null;
29
+ return response.pid;
30
+ }
31
+ /** Clean up only registered, identity-verified EvolCore Codex app-server children. */
32
+ export function stopCodexAppServerOrphans() {
33
+ const entries = listCodexAppServerProcesses();
34
+ if (entries.length === 0)
35
+ return 0;
36
+ const codexProcs = new Set(platform.findProcesses('codex app-server'));
37
+ let killed = 0;
38
+ for (const entry of entries) {
39
+ const { pid, startedAt } = entry.record;
40
+ if (!platform.isProcessRunning(pid)) {
41
+ unregisterCodexAppServerProcess(entry.filePath);
42
+ continue;
43
+ }
44
+ // Discard reused PIDs without signalling; retain unverified commands to retry.
45
+ const actualStartedAt = getProcessStartTime(pid);
46
+ if (!startTimeMatches(startedAt, actualStartedAt)) {
47
+ unregisterCodexAppServerProcess(entry.filePath);
48
+ continue;
49
+ }
50
+ if (!codexProcs.has(pid))
51
+ continue;
52
+ try {
53
+ if (platform.killProcess(pid, true)) {
54
+ killed++;
55
+ unregisterCodexAppServerProcess(entry.filePath);
56
+ }
57
+ }
58
+ catch { }
59
+ }
60
+ return killed;
61
+ }