evolcore 0.0.43-test.6 → 0.0.43-test.8

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 (249) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +188 -58
  3. package/dist/agent-template/jobs.js +62 -0
  4. package/dist/agent-template/runtime.js +214 -0
  5. package/dist/agent-template/service.js +465 -0
  6. package/dist/agent-template/tool-runner.js +45 -0
  7. package/dist/agent-template/types.js +5 -0
  8. package/dist/agents/baseagent-availability.js +1 -1
  9. package/dist/agents/claude-runner.js +1 -1
  10. package/dist/agents/codex/app-server-client.js +22 -0
  11. package/dist/agents/codex-runner.js +69 -2
  12. package/dist/aun/aid/agentmd.js +56 -1
  13. package/dist/aun/aid/client.js +3 -1
  14. package/dist/aun/menu/client.js +3 -2
  15. package/dist/aun/msg/p2p.js +6 -1
  16. package/dist/channels/aun.js +277 -49
  17. package/dist/cli/agent-command.js +5 -0
  18. package/dist/cli/agent-create.js +7 -3
  19. package/dist/cli/agent-template.js +124 -0
  20. package/dist/cli/aun-commands.js +2 -2
  21. package/dist/cli/ctl-command.js +2 -1
  22. package/dist/cli/daemon-commands.js +11 -66
  23. package/dist/cli/daemon-lifecycle-client.js +61 -0
  24. package/dist/cli/ecmsg-gateway.js +35 -2
  25. package/dist/cli/events-command.js +109 -0
  26. package/dist/cli/index.js +60 -14
  27. package/dist/cli/invoke-command.js +182 -0
  28. package/dist/cli/managed-command-guard.js +6 -1
  29. package/dist/cli/net-check.js +1 -1
  30. package/dist/cli/restart-monitor.js +160 -83
  31. package/dist/cli/services-command.js +137 -0
  32. package/dist/cli/team-workspace-command.js +134 -0
  33. package/dist/cli/thread-command.js +103 -13
  34. package/dist/cli/watch-msg.js +1 -1
  35. package/dist/config/boot-log.js +8 -8
  36. package/dist/config/config-field-policy.js +2 -2
  37. package/dist/config/config-manager.js +0 -7
  38. package/dist/config/invoke-ipc-service.js +118 -0
  39. package/dist/config/schema-migration.js +45 -15
  40. package/dist/config-store.js +2 -1
  41. package/dist/core/agent-ipc-registration.js +25 -4
  42. package/dist/core/agent-reload-coordinator.js +6 -4
  43. package/dist/core/agent-runtime.js +106 -10
  44. package/dist/core/auth/delegation-authorization.js +66 -0
  45. package/dist/core/auth/operation-authorizer.js +2 -0
  46. package/dist/core/auth/operation-catalog.js +29 -0
  47. package/dist/core/baseagent-loader.js +60 -130
  48. package/dist/core/channel-loader.js +10 -1
  49. package/dist/core/channel-runtime.js +20 -12
  50. package/dist/core/command/agent-control.js +12 -2
  51. package/dist/core/command/agent-storage-menu.js +1 -1
  52. package/dist/core/command/agent-template-menu.js +147 -0
  53. package/dist/core/command/chatmode-config.js +2 -36
  54. package/dist/core/command/command-handler.js +80 -17
  55. package/dist/core/command/data-root-resolver.js +32 -23
  56. package/dist/core/command/eventcenter-menu.js +468 -0
  57. package/dist/core/command/menu-catalog.js +15 -0
  58. package/dist/core/command/menu-handler.js +216 -90
  59. package/dist/core/command/menu-protocol.js +71 -13
  60. package/dist/core/command/menu-query-batch.js +194 -0
  61. package/dist/core/command/slash-gate.js +1 -1
  62. package/dist/core/command/slash-handler.js +34 -42
  63. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  64. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  65. package/dist/core/command/team-workspace-initializer.js +2 -0
  66. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  67. package/dist/core/command/team-workspace-job-store.js +88 -0
  68. package/dist/core/command/team-workspace-management-service.js +2 -0
  69. package/dist/core/command/team-workspace-management-store.js +96 -0
  70. package/dist/core/command/team-workspace-management.js +265 -0
  71. package/dist/core/command/team-workspace-members-menu.js +88 -0
  72. package/dist/core/command/team-workspace-store.js +612 -0
  73. package/dist/core/command/team-workspace-team.js +193 -0
  74. package/dist/core/daemon-control.js +22 -5
  75. package/dist/core/daemon-lifecycle.js +323 -191
  76. package/dist/core/handoff/runtime.js +45 -13
  77. package/dist/core/invoke/executors/index.js +13 -0
  78. package/dist/core/invoke/executors/media.js +283 -0
  79. package/dist/core/invoke/executors/text.js +198 -0
  80. package/dist/core/invoke/invoke-service.js +157 -0
  81. package/dist/core/invoke/style-router.js +48 -0
  82. package/dist/core/invoke/types.js +19 -0
  83. package/dist/core/ipc-registration.js +50 -7
  84. package/dist/core/legacy-rename.js +41 -0
  85. package/dist/core/memory/consolidation.js +7 -5
  86. package/dist/core/message/aun-ipc-sender.js +252 -17
  87. package/dist/core/message/im-renderer.js +116 -85
  88. package/dist/core/message/message-bridge.js +4 -0
  89. package/dist/core/message/message-queue.js +66 -15
  90. package/dist/core/message/message-utils.js +10 -2
  91. package/dist/core/message/peer-mode.js +7 -34
  92. package/dist/core/message/pending-hints.js +29 -5
  93. package/dist/core/message/response-engine.js +194 -61
  94. package/dist/core/message/send-options.js +7 -4
  95. package/dist/core/message/send-routing.js +50 -5
  96. package/dist/core/ownership/owner-resolver.js +7 -0
  97. package/dist/core/pack-auth.js +94 -0
  98. package/dist/core/pack-install.js +194 -0
  99. package/dist/core/permission/ec-command-parser.js +51 -17
  100. package/dist/core/permission/protected-paths.js +12 -2
  101. package/dist/core/permission/shell-environment.js +9 -0
  102. package/dist/core/rate-window.js +48 -0
  103. package/dist/core/relation/peer-identity.js +28 -0
  104. package/dist/core/session/session-file-health.js +243 -0
  105. package/dist/core/session/session-fs-store.js +67 -28
  106. package/dist/core/session/session-idle-monitor.js +59 -19
  107. package/dist/core/session/session-manager.js +13 -4
  108. package/dist/core/task/task-recovery-service.js +13 -2
  109. package/dist/core/thread/command-parser.js +9 -2
  110. package/dist/core/thread/thread-operation.js +21 -2
  111. package/dist/core/thread/thread-route.js +13 -2
  112. package/dist/core/thread/thread-service.js +52 -3
  113. package/dist/directory/owner-directory-admission.js +40 -53
  114. package/dist/directory/owner-directory-cache.js +89 -113
  115. package/dist/directory/owner-directory-query-operation.js +8 -10
  116. package/dist/eck/kit-renderer.js +7 -5
  117. package/dist/eck/message-renderer.js +2 -0
  118. package/dist/ecweb/basic-settings-service.js +1 -1
  119. package/dist/ecweb/message-context-service.js +0 -4
  120. package/dist/ecweb/runtime/lifecycle.js +6 -2
  121. package/dist/ecweb/runtime/supervisor.js +19 -4
  122. package/dist/event-center/admission-materializer.js +124 -0
  123. package/dist/event-center/bus-gate.js +154 -0
  124. package/dist/event-center/bus-host.js +307 -0
  125. package/dist/event-center/bus-resolver.js +120 -0
  126. package/dist/event-center/center-config.js +127 -0
  127. package/dist/event-center/daemon.js +44 -0
  128. package/dist/event-center/directory-source.js +55 -0
  129. package/dist/event-center/dispatcher.js +157 -0
  130. package/dist/event-center/event-log.js +110 -0
  131. package/dist/event-center/index-generator.js +73 -0
  132. package/dist/event-center/ipc-operation.js +423 -0
  133. package/dist/event-center/ledger.js +52 -0
  134. package/dist/event-center/pack-loader.js +207 -0
  135. package/dist/event-center/pack-manager.js +85 -0
  136. package/dist/event-center/registry.js +463 -0
  137. package/dist/event-center/runtime.js +837 -0
  138. package/dist/event-center/script-runner.js +356 -0
  139. package/dist/event-center/types.js +51 -0
  140. package/dist/event-center/validation.js +435 -0
  141. package/dist/index.js +424 -135
  142. package/dist/ipc.js +106 -12
  143. package/dist/paths.js +20 -0
  144. package/dist/product.js +14 -0
  145. package/dist/proxy/manager.js +5 -1
  146. package/dist/proxy/service-supervisor.js +13 -4
  147. package/dist/response-system/engines/v1/index.js +0 -1
  148. package/dist/response-system/engines/v1/proactive-flow.js +4 -2
  149. package/dist/response-system/modes/single-session/index.js +1 -1
  150. package/dist/services/dispatcher.js +100 -0
  151. package/dist/services/idempotency.js +90 -0
  152. package/dist/services/identity.js +52 -0
  153. package/dist/services/index-generator.js +70 -0
  154. package/dist/services/index.js +449 -0
  155. package/dist/services/ipc-operation.js +550 -0
  156. package/dist/services/ledger.js +52 -0
  157. package/dist/services/message-log.js +112 -0
  158. package/dist/services/pack-manager.js +215 -0
  159. package/dist/services/reply.js +55 -0
  160. package/dist/services/router.js +98 -0
  161. package/dist/services/script-runner.js +422 -0
  162. package/dist/services/service-payload.js +70 -0
  163. package/dist/services/types.js +18 -0
  164. package/dist/services/validation.js +297 -0
  165. package/dist/trigger/application-service.js +18 -0
  166. package/dist/trigger/event-source.js +1 -1
  167. package/dist/trigger/ipc-service.js +3 -1
  168. package/dist/trigger/scheduler.js +38 -0
  169. package/dist/trigger/script-sandbox.js +170 -24
  170. package/dist/utils/cross-platform.js +24 -10
  171. package/dist/utils/evolcore-version.js +69 -27
  172. package/dist/utils/instance-registry.js +19 -13
  173. package/dist/utils/npm-ops.js +2 -1
  174. package/dist/utils/package-version-info.js +6 -3
  175. package/dist/utils/process-introspect.js +45 -9
  176. package/dist/utils/startup-trace.js +74 -37
  177. package/dist/utils/windows-shell-trust.js +80 -6
  178. package/kits/docs/INDEX.md +2 -2
  179. package/kits/docs/aun/ABILITY_CALLING.md +9 -15
  180. package/kits/docs/context-assembly.md +1 -1
  181. package/kits/docs/evolcore/INDEX.md +3 -1
  182. package/kits/docs/evolcore/ability.md +4 -0
  183. package/kits/docs/evolcore/agent.md +22 -1
  184. package/kits/docs/evolcore/aid.md +1 -1
  185. package/kits/docs/evolcore/event-center.md +227 -0
  186. package/kits/docs/evolcore/file-navigation.md +10 -264
  187. package/kits/docs/evolcore/fs.md +5 -3
  188. package/kits/docs/evolcore/group.md +1 -1
  189. package/kits/docs/evolcore/memory-architecture.md +2 -0
  190. package/kits/docs/evolcore/menu-protocol.md +28 -1
  191. package/kits/docs/evolcore/msg.md +21 -9
  192. package/kits/docs/evolcore/provider.md +3 -1
  193. package/kits/docs/evolcore/response.md +5 -5
  194. package/kits/docs/evolcore/services.md +294 -0
  195. package/kits/docs/evolcore/task.md +2 -0
  196. package/kits/docs/evolcore/team-workspace.md +41 -0
  197. package/kits/docs/evolcore/thread-chain.md +15 -3
  198. package/kits/eck_manifest.json +26 -0
  199. package/kits/rules/02-navigation.md +10 -1
  200. package/kits/rules/06-channel.md +1 -0
  201. package/kits/schemas/_meta.json +17 -6
  202. package/kits/schemas/agent-config.schema.19.json +5 -7
  203. package/kits/schemas/agent-config.schema.20.json +936 -0
  204. package/kits/schemas/relation-config.schema.12.json +2 -3
  205. package/kits/schemas/role-config.schema.2.json +4 -4
  206. package/kits/skills/.switches.json +1 -5
  207. package/kits/skills/ability/SKILL.md +56 -0
  208. package/kits/skills/ability/references/calling.md +56 -0
  209. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  210. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  211. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  212. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  213. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  214. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  215. package/kits/skills/ec-group/SKILL.md +5 -8
  216. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  217. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  218. package/kits/skills/ec-trigger/SKILL.md +4 -4
  219. package/kits/skills/personal-assistant/SKILL.md +6 -6
  220. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  221. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  222. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  223. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  224. package/kits/skills/thread-ops/SKILL.md +10 -10
  225. package/kits/templates/message-fragments/item.md +1 -1
  226. package/kits/templates/system-fragments/channel.md +3 -3
  227. package/kits/templates/system-fragments/commands.md +5 -3
  228. package/kits/templates/system-fragments/reply.md +1 -5
  229. package/kits/templates/system-fragments/thread.md +13 -10
  230. package/package.json +5 -6
  231. package/scripts/agent-template/index.mjs +40 -0
  232. package/scripts/agent-template/inspect.mjs +240 -0
  233. package/scripts/agent-template/overlay.mjs +71 -0
  234. package/scripts/agent-template/pack.mjs +169 -0
  235. package/scripts/agent-template/shared/common.mjs +235 -0
  236. package/scripts/agent-template/shared/evolcore.mjs +75 -0
  237. package/scripts/agent-template/shared/plan.mjs +129 -0
  238. package/scripts/agent-template/shared/team-schema.json +70 -0
  239. package/scripts/agent-template/shared/template-contract.mjs +154 -0
  240. package/scripts/agent-template/shared/template-package.mjs +265 -0
  241. package/scripts/agent-template/shared/template-runtime.mjs +80 -0
  242. package/scripts/agent-template/shared/template.mjs +142 -0
  243. package/dist/cli/pa-workspace-command.js +0 -225
  244. package/dist/core/command/pa-workspace-store.js +0 -468
  245. package/dist/core/relation/pa-team.js +0 -132
  246. package/kits/docs/evolcore/pa-workspace.md +0 -51
  247. package/kits/skills/aid-ability/SKILL.md +0 -244
  248. package/kits/skills/ec-ability/SKILL.md +0 -67
  249. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -448,8 +448,8 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
448
448
  const activeSession = await this.sessionManager.getActiveSession(channel, channelId);
449
449
  let activeAgent;
450
450
  const getActiveAgent = () => {
451
- if (!activeAgent)
452
- activeAgent = this.getAgent(channel, activeSession?.baseagent);
451
+ if (!activeAgent && activeSession)
452
+ activeAgent = this.getLoadedAgent(channel, activeSession.baseagent);
453
453
  return activeAgent;
454
454
  };
455
455
  const getActiveAgentIfAvailable = () => {
@@ -491,7 +491,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
491
491
  || activeSession?.chatType
492
492
  || (chatType === 'group' ? 'group' : 'private');
493
493
  const chatmodeChoices = activeChatType === 'group' ? 'proactive'
494
- : identity.role === 'owner' ? 'interactive|proactive|paactive' : 'interactive|proactive';
494
+ : 'interactive|proactive';
495
495
  const groupSlash = applyGroupSlashPolicy && activeChatType === 'group';
496
496
  if (applyGroupSlashPolicy) {
497
497
  const groupGuard = guardGroupSlashCommand(normalizedContent, activeChatType);
@@ -570,7 +570,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
570
570
  sessionManager: this.sessionManager,
571
571
  messageQueue: this.messageQueue,
572
572
  isSessionPaused: sessionId => this.processor?.isPauseRequested?.(sessionId) ?? false,
573
- getAgentForSession: session => this.getAgent(channel, session.baseagent),
573
+ getAgentForSession: session => this.getLoadedAgent(channel, session.baseagent),
574
574
  });
575
575
  if (idleGuard)
576
576
  return idleGuard;
@@ -794,7 +794,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
794
794
  const probeBackendActivity = (current, gateSnapshot) => {
795
795
  const probes = {
796
796
  paused: () => this.processor?.isPauseRequested?.(current.id) ?? false,
797
- activeStream: () => this.getAgent(channel, current.baseagent).hasActiveStream(current.id),
797
+ activeStream: () => this.getLoadedAgent(channel, current.baseagent)?.hasActiveStream(current.id) ?? false,
798
798
  };
799
799
  if (this.permissionGateway) {
800
800
  probes.pendingPermission = () => this.permissionGateway.getPendingRequests(current.id).length > 0;
@@ -1286,7 +1286,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1286
1286
  const permSession = await getExistingSessionForCommand();
1287
1287
  if (!permSession)
1288
1288
  return { kind: 'command.result', text: '当前没有活跃会话' };
1289
- const permAgent = this.getAgent(channel, permSession.baseagent);
1289
+ const permAgent = await this.ensureAgent(channel, permSession.baseagent);
1290
1290
  // 角色来自会话身份;permissionMode 只从该角色定义解析。
1291
1291
  const permSelfAid = selfAID ?? permSession.selfAID ?? this.resolveSelfAID(channel);
1292
1292
  const permChannelType = permSession.channelType ?? this.resolveChannelType(channel);
@@ -1420,7 +1420,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1420
1420
  if (!pauseSession) {
1421
1421
  return { kind: 'system.notice', text: '当前没有活跃会话', subtype: 'session.pause.idle' };
1422
1422
  }
1423
- const pauseAgent = this.getAgent(channel, pauseSession.baseagent);
1423
+ const pauseAgent = await this.ensureAgent(channel, pauseSession.baseagent);
1424
1424
  const hasActiveTask = pauseAgent.hasActiveStream(pauseSession.id)
1425
1425
  || this.messageQueue.isProcessing(pauseSession.id);
1426
1426
  if (!hasActiveTask) {
@@ -1511,6 +1511,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1511
1511
  const currentSession = await getExistingSessionForCommand();
1512
1512
  const previousBaseagent = owningAgent.baseagent || this.parseDefaultBaseagent();
1513
1513
  try {
1514
+ await this.ensureAgent(channel, args, owningAgent.aid);
1514
1515
  owningAgent.setActiveBaseagent(args);
1515
1516
  }
1516
1517
  catch (error) {
@@ -1529,7 +1530,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1529
1530
  if (args === 'reset' || args === 'check') {
1530
1531
  const modelSession = await getExistingSessionForCommand();
1531
1532
  const fallbackBaseagent = modelSession?.baseagent || this.agentRegistry?.resolveByChannel(channel)?.baseagent || this.parseDefaultBaseagent();
1532
- const modelAgent = this.getAgent(channel, fallbackBaseagent);
1533
+ const modelAgent = await this.ensureAgent(channel, fallbackBaseagent);
1533
1534
  const modelChatType = modelSession?.chatType
1534
1535
  ?? (chatType === 'private' || chatType === 'group' ? chatType : undefined);
1535
1536
  const peerKeyId = modelChatType === 'group'
@@ -1621,7 +1622,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1621
1622
  if (!args || args === 'list' || args === 'current') {
1622
1623
  const modelSession = await getExistingSessionForCommand();
1623
1624
  const fallbackBaseagent = modelSession?.baseagent || this.agentRegistry?.resolveByChannel(channel)?.baseagent || this.parseDefaultBaseagent();
1624
- const modelAgent = this.getAgent(channel, fallbackBaseagent);
1625
+ const modelAgent = await this.ensureAgent(channel, fallbackBaseagent);
1625
1626
  const modelTarget = resolveSlashRelationTarget.call(this, {
1626
1627
  session: modelSession,
1627
1628
  channel,
@@ -1774,7 +1775,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1774
1775
  }
1775
1776
  // 切换模型写入 Agent 级 baseagents 配置;没有活跃会话时也不应创建空会话。
1776
1777
  const fallbackBaseagent = modelSession?.baseagent || this.agentRegistry?.resolveByChannel(channel)?.baseagent || this.parseDefaultBaseagent();
1777
- const modelAgent = this.getAgent(channel, fallbackBaseagent);
1778
+ const modelAgent = await this.ensureAgent(channel, fallbackBaseagent);
1778
1779
  const modelSelector = { self: selfAID ?? modelSession?.selfAID ?? this.resolveSelfAID(channel) };
1779
1780
  let configuredModel;
1780
1781
  try {
@@ -1903,7 +1904,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1903
1904
  if (!args) {
1904
1905
  const effortSession = await getExistingSessionForCommand();
1905
1906
  const fallbackBaseagent = effortSession?.baseagent || this.agentRegistry?.resolveByChannel(channel)?.baseagent || this.parseDefaultBaseagent();
1906
- const effortAgent = this.getAgent(channel, fallbackBaseagent);
1907
+ const effortAgent = await this.ensureAgent(channel, fallbackBaseagent);
1907
1908
  const effortSelector = { self: selfAID ?? effortSession?.selfAID ?? this.resolveSelfAID(channel) };
1908
1909
  let modelConfig = {};
1909
1910
  try {
@@ -1969,7 +1970,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
1969
1970
  }
1970
1971
  const effortSession = await getExistingSessionForCommand();
1971
1972
  const fallbackBaseagent = effortSession?.baseagent || this.agentRegistry?.resolveByChannel(channel)?.baseagent || this.parseDefaultBaseagent();
1972
- const effortAgent = this.getAgent(channel, fallbackBaseagent);
1973
+ const effortAgent = await this.ensureAgent(channel, fallbackBaseagent);
1973
1974
  const effortSelf = selfAID ?? effortSession?.selfAID ?? this.resolveSelfAID(channel);
1974
1975
  let modelConfig = {};
1975
1976
  try {
@@ -2216,7 +2217,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2216
2217
  return null;
2217
2218
  return { kind: 'command.result', text: `✅ 中间输出模式: ${activityArg}(${label})` };
2218
2219
  }
2219
- // /chatmode 命令:私聊提供 interactive/proactive/paactive,群聊固定 proactive
2220
+ // /chatmode 命令:私聊提供 interactive/proactive,群聊固定 proactive
2220
2221
  // - 查看:所有人可用
2221
2222
  // - 设置:单聊任何角色可设置;群聊仅管理员可设置
2222
2223
  if (normalizedContent === '/chatmode' || normalizedContent.startsWith('/chatmode ')) {
@@ -2229,9 +2230,6 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2229
2230
  ...(activeChatType !== 'group'
2230
2231
  ? [{ key: 'interactive', name: '交互模式', desc: '被动响应:收到消息时才回复,回复直接显示' }] : []),
2231
2232
  { key: 'proactive', name: '主动模式', desc: '主动推进:流式输出静默,由 Agent 自调 ctl send 发声' },
2232
- ...((existingChatmodeSession?.channelType ?? this.resolveChannelType?.(channel)) === 'aun'
2233
- && activeChatType === 'private' && identity.role === 'owner'
2234
- ? [{ key: 'paactive', name: 'PA 模式', desc: '自动文本显示为 activity,正式回复由 Agent 显式发送' }] : []),
2235
2233
  ];
2236
2234
  const interaction = {
2237
2235
  type: 'interaction',
@@ -2291,29 +2289,23 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2291
2289
  if (target.field === 'group' && arg !== 'proactive') {
2292
2290
  return { kind: 'command.error', text: '❌ 群聊仅支持 proactive 模式' };
2293
2291
  }
2294
- if (arg === 'paactive' && identity.role !== 'owner') {
2295
- return { kind: 'command.error', text: '❌ paactive 模式仅限 owner' };
2296
- }
2297
2292
  if (arg === currentMode) {
2298
2293
  return { kind: 'command.result', text: `📋 当前会话模式已是 ${arg}` };
2299
2294
  }
2300
- if ((arg === 'interactive' || arg === 'paactive') && isPrivateChatmodeRoleLocked(target.field, target.role)) {
2295
+ if (arg === 'interactive' && isPrivateChatmodeRoleLocked(target.field, target.role)) {
2301
2296
  return { kind: 'command.error', text: '❌ 私聊交互模式仅限 owner/admin,当前角色固定为 proactive' };
2302
2297
  }
2303
- if (arg === 'paactive' && (target.field !== 'private' || !target.sel.peerKey?.startsWith('aun#'))) {
2304
- return { kind: 'command.error', text: '❌ paactive 仅支持 AUN 人类私聊' };
2305
- }
2306
2298
  // 仅在真正需要切换时才要求会话空闲
2307
2299
  if (chatmodeSession && threadId) {
2308
2300
  const threadSession = await this.sessionManager.getThreadSession(channel, channelId, threadId);
2309
2301
  if (threadSession) {
2310
- const threadAgent = this.getAgent(channel, threadSession.baseagent);
2302
+ const threadAgent = await this.ensureAgent(channel, threadSession.baseagent);
2311
2303
  if (threadAgent.hasActiveStream(threadSession.id) || this.messageQueue?.isProcessing(threadSession.id)) {
2312
2304
  return { kind: 'command.error', text: '⚠️ 当前正在处理消息,请稍后再试\n使用 /stop 中断当前任务后重试' };
2313
2305
  }
2314
2306
  }
2315
2307
  }
2316
- else if (chatmodeSession && (getActiveAgent().hasActiveStream(chatmodeSession.id) || this.messageQueue?.isProcessing(chatmodeSession.id))) {
2308
+ else if (chatmodeSession && (getActiveAgent()?.hasActiveStream(chatmodeSession.id) || this.messageQueue?.isProcessing(chatmodeSession.id))) {
2317
2309
  return { kind: 'command.error', text: '⚠️ 当前正在处理消息,请稍后再试\n使用 /stop 中断当前任务后重试' };
2318
2310
  }
2319
2311
  const chatmodeAuthDenied = await authorizeIntent({
@@ -2340,7 +2332,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2340
2332
  if (chatmodeAuthDenied)
2341
2333
  return chatmodeAuthDenied;
2342
2334
  try {
2343
- writeChatmodeConfig({ ...target, scope: 'relation' }, arg, authSubject);
2335
+ writeChatmodeConfig({ ...target, scope: 'relation' }, arg);
2344
2336
  }
2345
2337
  catch (e) {
2346
2338
  return { kind: 'command.error', text: `Failed to update relation chatmode: ${e?.message || e}` };
@@ -2458,11 +2450,11 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2458
2450
  if (!stopSession) {
2459
2451
  return { kind: 'system.notice', text: '当前没有正在处理的任务', subtype: 'session.stop.idle' };
2460
2452
  }
2461
- const stopAgent = this.getAgent(channel, stopSession.baseagent);
2453
+ const stopAgent = this.getLoadedAgent(channel, stopSession.baseagent);
2462
2454
  const sessionKey = stopSession.id;
2463
2455
  this.processor?.clearPauseSession?.(sessionKey);
2464
2456
  const queueLength = this.messageQueue.getQueueLength(sessionKey);
2465
- const hasActive = stopAgent.hasActiveStream(sessionKey);
2457
+ const hasActive = stopAgent?.hasActiveStream(sessionKey) ?? false;
2466
2458
  const isProcessing = this.messageQueue.isProcessing(sessionKey);
2467
2459
  if (queueLength === 0 && !hasActive && !isProcessing) {
2468
2460
  // Even an idle session can have an undelivered task:error recovery.
@@ -2612,7 +2604,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2612
2604
  const projectPath = path.isAbsolute(session.projectPath)
2613
2605
  ? session.projectPath
2614
2606
  : path.resolve(process.cwd(), session.projectPath);
2615
- const currentSessionAgent = this.getAgent(channel, session.baseagent);
2607
+ const currentSessionAgent = await this.ensureAgent(channel, session.baseagent);
2616
2608
  if (!currentSessionAgent.capabilities?.compact) {
2617
2609
  return { kind: 'command.error', text: `❌ 当前 Agent (${currentSessionAgent.name}) 不支持 /compact` };
2618
2610
  }
@@ -2728,12 +2720,12 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2728
2720
  return { kind: 'command.result', text: `📊 会话状态:当前没有活跃会话\n发送消息或使用 /new [名称] 创建会话` };
2729
2721
  }
2730
2722
  const sessionKey = this.getQueueKey(session, channel, channelId);
2731
- const sessionAgent = this.getAgent(channel, session.baseagent);
2732
- const isCurrentlyProcessing = this.messageQueue.isProcessing(sessionKey) || sessionAgent.hasActiveStream(sessionKey)
2733
- || sessionAgent.hasActiveOperation?.(sessionKey) === true;
2723
+ const sessionAgent = this.getLoadedAgent(channel, session.baseagent);
2724
+ const isCurrentlyProcessing = this.messageQueue.isProcessing(sessionKey) || sessionAgent?.hasActiveStream(sessionKey)
2725
+ || sessionAgent?.hasActiveOperation?.(sessionKey) === true;
2734
2726
  const queueLength = this.messageQueue.getQueueLength(sessionKey);
2735
2727
  const isThread = isTopicSession(session);
2736
- const executionState = sessionAgent.getExecutionState?.(sessionKey);
2728
+ const executionState = sessionAgent?.getExecutionState?.(sessionKey);
2737
2729
  let sessionStatus = executionState === 'interrupting' ? '中断收尾中(等待旧执行退出)' : isCurrentlyProcessing || queueLength > 0 ? '处理中' : '空闲';
2738
2730
  // 处理中时显示时长
2739
2731
  if (isCurrentlyProcessing && executionState !== 'interrupting') {
@@ -2901,7 +2893,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
2901
2893
  const newBaseagent = newSession.baseagent || newAgent?.baseagent || this.parseDefaultBaseagent();
2902
2894
  // 与 /model 卡片保持一致:按 关系>角色>agent 解析实际生效的 model/effort,
2903
2895
  // 不直接读 EvolAgent.model(那只是 agent 级静态配置,会无视关系/角色级覆盖)。
2904
- const newRunner = this.getAgent(channel, newSession.baseagent);
2896
+ const newRunner = await this.ensureAgent(channel, newSession.baseagent);
2905
2897
  const newModelTarget = resolveSlashRelationTarget.call(this, {
2906
2898
  session: newSession,
2907
2899
  channel,
@@ -3888,7 +3880,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
3888
3880
  const oldName = displaySessionTitle(session.name, '(未命名)');
3889
3881
  const success = await this.sessionManager.renameSession(session.id, newName);
3890
3882
  if (success && session.agentSessionId) {
3891
- const renameAgent = this.getAgent(channel, session.baseagent);
3883
+ const renameAgent = await this.ensureAgent(channel, session.baseagent);
3892
3884
  await renameAgent.setSessionName?.(session.agentSessionId, newName).catch((error) => {
3893
3885
  logger.debug('[CommandHandler] Backend session rename sync failed:', error);
3894
3886
  });
@@ -3961,9 +3953,9 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
3961
3953
  return { kind: 'command.error', text: `❌ 删除失败` };
3962
3954
  }
3963
3955
  this.eventBus.publish({ type: 'session:deleted', sessionId: targetSession.id });
3964
- const targetAgent = this.getAgent(channel, targetSession.baseagent);
3956
+ const targetAgent = this.getLoadedAgent(channel, targetSession.baseagent);
3965
3957
  this.processor?.clearPauseSession?.(targetSession.id);
3966
- await targetAgent.closeSession(targetSession.id);
3958
+ await targetAgent?.closeSession(targetSession.id);
3967
3959
  return { kind: 'command.result', text: `✓ 已删除会话: ${displaySessionTitle(targetSession.name, sessionName)}\n会话文件已保留,可通过 CLI 访问` };
3968
3960
  }
3969
3961
  // /fork 命令:分支当前会话
@@ -3975,7 +3967,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
3975
3967
  if (!session.agentSessionId) {
3976
3968
  return { kind: 'command.error', text: `❌ 当前会话尚未初始化对话,无法分支\n\n请先发送一条消息,然后再使用 /fork` };
3977
3969
  }
3978
- const forkAgent = this.getAgent(channel, session.baseagent);
3970
+ const forkAgent = await this.ensureAgent(channel, session.baseagent);
3979
3971
  if (!forkAgent.capabilities?.fork) {
3980
3972
  return { kind: 'command.error', text: `❌ 当前 Agent (${forkAgent.name}) 不支持 /fork\n\n可使用 /new 创建新会话替代` };
3981
3973
  }
@@ -4015,7 +4007,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
4015
4007
  if (!rewindBaseagent) {
4016
4008
  return { kind: 'command.error', text: '❌ 当前会话缺少 baseagent 绑定,拒绝隐式切换' };
4017
4009
  }
4018
- const rewindAgent = this.getAgent(channel, rewindBaseagent);
4010
+ const rewindAgent = await this.ensureAgent(channel, rewindBaseagent);
4019
4011
  if (!session.agentSessionId) {
4020
4012
  return { kind: 'command.error', text: '❌ 当前会话无历史记录\n\n请先发送一条消息,然后再使用 /rewind' };
4021
4013
  }
@@ -4052,7 +4044,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
4052
4044
  if (!current.agentSessionId) {
4053
4045
  return '❌ 当前会话无历史记录\n\n请先发送一条消息,然后再使用 /rewind';
4054
4046
  }
4055
- const currentAgent = this.getAgent(channel, current.baseagent);
4047
+ const currentAgent = await this.ensureAgent(channel, current.baseagent);
4056
4048
  if (!currentAgent.getSessionMessages) {
4057
4049
  return `❌ 当前 Agent (${currentAgent.name}) 不支持 /rewind`;
4058
4050
  }
@@ -4075,7 +4067,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
4075
4067
  if (!rewindBaseagent) {
4076
4068
  return { kind: 'command.error', text: '❌ 当前会话缺少 baseagent 绑定,拒绝隐式切换' };
4077
4069
  }
4078
- const rewindAgent = this.getAgent(channel, rewindBaseagent);
4070
+ const rewindAgent = await this.ensureAgent(channel, rewindBaseagent);
4079
4071
  if (!session.agentSessionId) {
4080
4072
  return { kind: 'command.error', text: '❌ 当前会话无历史记录\n\n请先发送一条消息,然后再使用 /rewind' };
4081
4073
  }
@@ -4093,7 +4085,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
4093
4085
  const repairSession = await getExistingSessionForCommand();
4094
4086
  if (!repairSession)
4095
4087
  return { kind: 'command.result', text: '当前没有活跃会话' };
4096
- const repairAgent = this.getAgent(channel, repairSession.baseagent);
4088
+ const repairAgent = await this.ensureAgent(channel, repairSession.baseagent);
4097
4089
  const { checkSessionFile, backupSessionFile } = await import('../session/session-file-health.js');
4098
4090
  await interruptPausedSessionBeforeReplacement(repairSession);
4099
4091
  try {
@@ -0,0 +1,350 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { atomicWriteJson } from '../../utils/atomic-write.js';
4
+ import { agentDataDir, agentOutputDir, agentWorkspaceDir, legacyTeamWorkspaceDir } from '../../paths.js';
5
+ import { isValidAid } from '../../aun/aid/validation.js';
6
+ import { teamWorkspaceStore } from './team-workspace-store.js';
7
+ import { ownerResolver } from '../ownership/owner-resolver.js';
8
+ import { ConfigTarget, read } from '../../config/config-manager.js';
9
+ import { teamWorkspaceManagementStore, readWorkspaceMarker, workspaceMarkerPath, } from './team-workspace-management-store.js';
10
+ import { teamWorkspaceJobStore } from './team-workspace-job-store.js';
11
+ export class TeamWorkspaceBootstrapError extends Error {
12
+ code;
13
+ retryable;
14
+ constructor(code, message, retryable = true) {
15
+ super(message);
16
+ this.code = code;
17
+ this.retryable = retryable;
18
+ this.name = 'TeamWorkspaceBootstrapError';
19
+ }
20
+ }
21
+ export function resolveTeamWorkspaceIdentity(agentAid) {
22
+ if (!isValidAid(agentAid))
23
+ return null;
24
+ const config = read(ConfigTarget.Agent, { self: agentAid }, { cache: false });
25
+ if (!config)
26
+ return null;
27
+ const ownerAid = ownerResolver.owner(agentAid) ?? config.owner ?? config.owners?.[0];
28
+ if (!ownerAid || !isValidAid(ownerAid))
29
+ return null;
30
+ return { agentAid, ownerAid };
31
+ }
32
+ const initializationWait = new Int32Array(new SharedArrayBuffer(4));
33
+ export class TeamWorkspaceInitializer {
34
+ initialize(identity, rootPath = agentWorkspaceDir(identity.agentAid), options = {}) {
35
+ if (!path.isAbsolute(rootPath))
36
+ throw new TeamWorkspaceBootstrapError('INVALID_ARGUMENT', 'Team workspace path must be absolute', false);
37
+ teamWorkspaceStore.importPersonalAssistantRegistration(identity.agentAid, identity.ownerAid);
38
+ const root = path.resolve(rootPath);
39
+ const current = teamWorkspaceStore.read(identity.agentAid);
40
+ if (current && current.ownerAid !== identity.ownerAid) {
41
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_IDENTITY_MISMATCH', 'Workspace registration belongs to another Owner', false);
42
+ }
43
+ fs.mkdirSync(path.dirname(root), { recursive: true });
44
+ if (fs.existsSync(root) && !fs.statSync(root).isDirectory())
45
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_UNAVAILABLE', 'Team workspace is not a directory');
46
+ fs.mkdirSync(root, { recursive: true });
47
+ const marker = readWorkspaceMarker(root);
48
+ if (marker && (marker.agentAid !== identity.agentAid || marker.ownerAid !== identity.ownerAid)) {
49
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_IDENTITY_MISMATCH', 'Workspace marker belongs to another Agent or Owner', false);
50
+ }
51
+ if (!marker && !options.allowExistingContent && fs.readdirSync(root).length > 0) {
52
+ throw new TeamWorkspaceBootstrapError('DIRECTORY_OCCUPIED', 'The default Team workspace directory is not empty', false);
53
+ }
54
+ const createdAt = marker?.createdAt ?? Date.now();
55
+ const outputRoot = agentOutputDir(identity.agentAid);
56
+ const fromOutput = path.relative(outputRoot, root);
57
+ if (fromOutput === '' || !fromOutput.startsWith(`..${path.sep}`) && fromOutput !== '..' && !path.isAbsolute(fromOutput)) {
58
+ throw new TeamWorkspaceBootstrapError('OUTPUT_MIGRATION_CONFLICT', 'Workspace cannot be inside the Agent output directory', false);
59
+ }
60
+ migrateWorkspaceOutput(path.join(root, 'output'), outputRoot);
61
+ fs.mkdirSync(path.join(root, 'capture'), { recursive: true });
62
+ fs.mkdirSync(path.dirname(outputRoot), { recursive: true });
63
+ fs.mkdirSync(outputRoot, { recursive: true });
64
+ ensureOutputAlias(path.join(root, 'output'), outputRoot);
65
+ fs.mkdirSync(path.join(root, '.workspace'), { recursive: true });
66
+ const markerPath = workspaceMarkerPath(root);
67
+ if (!marker)
68
+ atomicWriteJson(markerPath, { schemaVersion: 1, agentAid: identity.agentAid, ownerAid: identity.ownerAid, workspaceVersion: 1, createdAt, initializedBy: 'evolcore' });
69
+ const state = teamWorkspaceStore.bind(identity.agentAid, identity.ownerAid, root, outputRoot);
70
+ if (!readWorkspaceMarker(root)?.workspaceId)
71
+ atomicWriteJson(markerPath, { schemaVersion: 1, agentAid: identity.agentAid, ownerAid: identity.ownerAid, workspaceVersion: 1, createdAt, initializedBy: 'evolcore', workspaceId: state.workspaceId });
72
+ return { state, createdAt };
73
+ }
74
+ }
75
+ function migrateWorkspaceOutput(source, target) {
76
+ const targetStat = existingStat(target);
77
+ if (targetStat && (!targetStat.isDirectory() || targetStat.isSymbolicLink())) {
78
+ throw new TeamWorkspaceBootstrapError('OUTPUT_MIGRATION_CONFLICT', 'Agent output is not a plain directory; neither directory was changed', false);
79
+ }
80
+ if (samePath(source, target))
81
+ return;
82
+ const sourceStat = existingStat(source);
83
+ if (!sourceStat)
84
+ return;
85
+ if (sourceStat.isSymbolicLink()) {
86
+ try {
87
+ if (samePath(fs.realpathSync(source), fs.realpathSync(target)))
88
+ return;
89
+ }
90
+ catch { /* A broken or unrelated link is a migration conflict. */ }
91
+ throw new TeamWorkspaceBootstrapError('OUTPUT_MIGRATION_CONFLICT', 'Workspace output is linked to an unexpected location; neither directory was changed', false);
92
+ }
93
+ if (!sourceStat.isDirectory()) {
94
+ throw new TeamWorkspaceBootstrapError('OUTPUT_MIGRATION_CONFLICT', 'Workspace output is not a plain directory; it was not moved', false);
95
+ }
96
+ assertOutputMergeHasNoConflicts(source, target);
97
+ if (!targetStat) {
98
+ fs.mkdirSync(path.dirname(target), { recursive: true });
99
+ try {
100
+ fs.renameSync(source, target);
101
+ return;
102
+ }
103
+ catch (error) {
104
+ if (error.code !== 'EXDEV')
105
+ throw error;
106
+ }
107
+ fs.mkdirSync(target);
108
+ }
109
+ moveOutputEntries(source, target);
110
+ fs.rmdirSync(source);
111
+ }
112
+ function assertOutputMergeHasNoConflicts(source, target) {
113
+ for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
114
+ const sourcePath = path.join(source, entry.name);
115
+ const targetPath = path.join(target, entry.name);
116
+ if (!entry.isDirectory() && !entry.isFile()) {
117
+ throw new TeamWorkspaceBootstrapError('OUTPUT_MIGRATION_CONFLICT', 'Workspace output contains a non-regular entry; neither directory was changed', false);
118
+ }
119
+ const targetStat = existingStat(targetPath);
120
+ if (entry.isDirectory() && (!targetStat || targetStat.isDirectory() && !targetStat.isSymbolicLink())) {
121
+ assertOutputMergeHasNoConflicts(sourcePath, targetPath);
122
+ continue;
123
+ }
124
+ if (!targetStat)
125
+ continue;
126
+ throw new TeamWorkspaceBootstrapError('OUTPUT_MIGRATION_CONFLICT', `Workspace output conflicts with Agent output at ${entry.name}; neither directory was changed`, false);
127
+ }
128
+ }
129
+ function moveOutputEntries(source, target) {
130
+ for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
131
+ const sourcePath = path.join(source, entry.name);
132
+ const targetPath = path.join(target, entry.name);
133
+ if (entry.isDirectory()) {
134
+ fs.mkdirSync(targetPath, { recursive: true });
135
+ moveOutputEntries(sourcePath, targetPath);
136
+ fs.rmdirSync(sourcePath);
137
+ }
138
+ else {
139
+ try {
140
+ fs.renameSync(sourcePath, targetPath);
141
+ }
142
+ catch (error) {
143
+ if (error.code !== 'EXDEV')
144
+ throw error;
145
+ fs.copyFileSync(sourcePath, targetPath, fs.constants.COPYFILE_EXCL);
146
+ const stat = fs.statSync(sourcePath);
147
+ fs.utimesSync(targetPath, stat.atime, stat.mtime);
148
+ fs.unlinkSync(sourcePath);
149
+ }
150
+ }
151
+ }
152
+ }
153
+ function ensureOutputAlias(alias, target) {
154
+ if (samePath(alias, target))
155
+ return;
156
+ const stat = existingStat(alias);
157
+ if (stat) {
158
+ if (stat.isSymbolicLink()) {
159
+ try {
160
+ if (samePath(fs.realpathSync(alias), fs.realpathSync(target)))
161
+ return;
162
+ }
163
+ catch { /* Broken alias is a conflict. */ }
164
+ throw new TeamWorkspaceBootstrapError('OUTPUT_MIGRATION_CONFLICT', 'Workspace output alias points to another location; it was not replaced', false);
165
+ }
166
+ throw new TeamWorkspaceBootstrapError('OUTPUT_MIGRATION_CONFLICT', 'Workspace output directory remains after migration; it was not replaced', false);
167
+ }
168
+ fs.symlinkSync(target, alias, process.platform === 'win32' ? 'junction' : 'dir');
169
+ }
170
+ function existingStat(filePath) {
171
+ try {
172
+ return fs.lstatSync(filePath);
173
+ }
174
+ catch (error) {
175
+ if (error.code === 'ENOENT')
176
+ return undefined;
177
+ throw error;
178
+ }
179
+ }
180
+ export class TeamWorkspaceBootstrapService {
181
+ initializer;
182
+ flights = new Map();
183
+ constructor(initializer = new TeamWorkspaceInitializer()) {
184
+ this.initializer = initializer;
185
+ }
186
+ migrateOutput(identity) {
187
+ teamWorkspaceStore.importPersonalAssistantRegistration(identity.agentAid, identity.ownerAid);
188
+ const binding = teamWorkspaceStore.read(identity.agentAid);
189
+ if (!binding || binding.outputRootPath || binding.ownerAid !== identity.ownerAid)
190
+ return;
191
+ withInitializationLock(identity.agentAid, () => this.initializer.initialize(identity, binding.rootPath, { allowExistingContent: true }));
192
+ }
193
+ migrateLegacyDefault(identity) {
194
+ return withInitializationLock(identity.agentAid, () => {
195
+ const state = teamWorkspaceStore.read(identity.agentAid);
196
+ if (!state || state.ownerAid !== identity.ownerAid)
197
+ return false;
198
+ const legacyRoot = path.resolve(legacyTeamWorkspaceDir(identity.agentAid));
199
+ if (!samePath(state.rootPath, legacyRoot))
200
+ return false;
201
+ const workspaceRoot = path.resolve(agentWorkspaceDir(identity.agentAid));
202
+ const legacyExists = fs.existsSync(legacyRoot);
203
+ const workspaceExists = fs.existsSync(workspaceRoot);
204
+ if (legacyExists && workspaceExists) {
205
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_MIGRATION_CONFLICT', 'Both legacy and Agent workspace directories exist; neither was changed', false);
206
+ }
207
+ if (legacyExists) {
208
+ const stat = fs.lstatSync(legacyRoot);
209
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
210
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_MIGRATION_CONFLICT', 'Legacy workspace is not a plain directory; it was not moved', false);
211
+ }
212
+ const markerPath = workspaceMarkerPath(legacyRoot);
213
+ const markerExists = fs.existsSync(markerPath);
214
+ const marker = markerExists ? readWorkspaceMarker(legacyRoot) : null;
215
+ if (markerExists && !marker) {
216
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_IDENTITY_MISMATCH', 'Legacy workspace marker is invalid; it was not moved', false);
217
+ }
218
+ if (marker && (marker.agentAid !== identity.agentAid || marker.ownerAid !== identity.ownerAid)) {
219
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_IDENTITY_MISMATCH', 'Legacy workspace marker belongs to another Agent or Owner', false);
220
+ }
221
+ if (marker?.workspaceId && marker.workspaceId !== state.workspaceId) {
222
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_IDENTITY_MISMATCH', 'Legacy workspace marker does not match the stored workspace binding', false);
223
+ }
224
+ const createdAt = marker?.createdAt ?? Date.now();
225
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
226
+ atomicWriteJson(markerPath, {
227
+ schemaVersion: 1, agentAid: identity.agentAid, ownerAid: identity.ownerAid,
228
+ workspaceVersion: 1, createdAt, initializedBy: 'evolcore', workspaceId: state.workspaceId,
229
+ });
230
+ fs.mkdirSync(path.dirname(workspaceRoot), { recursive: true });
231
+ fs.renameSync(legacyRoot, workspaceRoot);
232
+ }
233
+ else if (!workspaceExists) {
234
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_UNAVAILABLE', 'Neither the legacy nor Agent workspace directory exists');
235
+ }
236
+ else {
237
+ const marker = readWorkspaceMarker(workspaceRoot);
238
+ if (!marker || marker.agentAid !== identity.agentAid || marker.ownerAid !== identity.ownerAid || marker.workspaceId !== state.workspaceId) {
239
+ throw new TeamWorkspaceBootstrapError('WORKSPACE_MIGRATION_CONFLICT', 'Agent workspace exists without a matching workspace marker; it was not adopted', false);
240
+ }
241
+ }
242
+ teamWorkspaceStore.rebindRoot(identity.agentAid, identity.ownerAid, workspaceRoot);
243
+ return true;
244
+ });
245
+ }
246
+ start(identity, operationId = `startup:${identity.agentAid}`) {
247
+ teamWorkspaceStore.importPersonalAssistantRegistration(identity.agentAid, identity.ownerAid);
248
+ this.migrateLegacyDefault(identity);
249
+ let existingBinding = teamWorkspaceStore.read(identity.agentAid);
250
+ if (existingBinding && existingBinding.ownerAid === identity.ownerAid) {
251
+ // Keep the registered columns and workspace identity while moving only
252
+ // deliverables into the same Agent-owned output used by other Agents.
253
+ existingBinding = withInitializationLock(identity.agentAid, () => this.initializer.initialize(identity, existingBinding.rootPath, { allowExistingContent: true }).state);
254
+ const legacyState = teamWorkspaceManagementStore.ensure(identity.agentAid, identity.ownerAid);
255
+ if (legacyState.status !== 'ready') {
256
+ return Promise.resolve(teamWorkspaceManagementStore.update(identity.agentAid, {
257
+ status: 'ready', createdAt: legacyState.createdAt ?? Date.now(), boundAt: legacyState.boundAt ?? Date.now(),
258
+ activeJobId: undefined, lastError: undefined,
259
+ }));
260
+ }
261
+ return Promise.resolve(legacyState);
262
+ }
263
+ const current = teamWorkspaceManagementStore.read(identity.agentAid);
264
+ if (current?.status === 'ready' && teamWorkspaceStore.read(identity.agentAid))
265
+ return Promise.resolve(current);
266
+ const active = this.flights.get(identity.agentAid);
267
+ if (active)
268
+ return active;
269
+ const state = teamWorkspaceManagementStore.ensure(identity.agentAid, identity.ownerAid);
270
+ const job = teamWorkspaceJobStore.create({ agentAid: identity.agentAid, ownerAid: identity.ownerAid, principalId: identity.ownerAid, operationId, type: 'initialize', fingerprint: JSON.stringify({ agentAid: identity.agentAid, ownerAid: identity.ownerAid }) });
271
+ teamWorkspaceManagementStore.update(identity.agentAid, { status: 'initializing', attempts: state.attempts + 1, activeJobId: job.jobId, lastError: undefined });
272
+ const flight = this.run(identity, job).finally(() => this.flights.delete(identity.agentAid));
273
+ this.flights.set(identity.agentAid, flight);
274
+ return flight;
275
+ }
276
+ async run(identity, job) {
277
+ teamWorkspaceJobStore.update(identity.agentAid, job.jobId, { status: 'running', progress: 10 });
278
+ try {
279
+ const result = withInitializationLock(identity.agentAid, () => this.initializer.initialize(identity));
280
+ const next = teamWorkspaceManagementStore.update(identity.agentAid, { status: 'ready', createdAt: result.createdAt, boundAt: Date.now(), activeJobId: undefined, lastError: undefined });
281
+ teamWorkspaceJobStore.update(identity.agentAid, job.jobId, { status: 'succeeded', progress: 100, result: { workspaceId: result.state.workspaceId } });
282
+ return next;
283
+ }
284
+ catch (error) {
285
+ const code = error instanceof TeamWorkspaceBootstrapError ? error.code : 'INITIALIZE_FAILED';
286
+ const message = error instanceof TeamWorkspaceBootstrapError
287
+ ? error.message
288
+ : initializationFailureMessage(error);
289
+ const retryable = error instanceof TeamWorkspaceBootstrapError ? error.retryable : true;
290
+ const next = teamWorkspaceManagementStore.update(identity.agentAid, { status: 'failed', activeJobId: undefined, lastError: { code, message, retryable } });
291
+ teamWorkspaceJobStore.update(identity.agentAid, job.jobId, { status: 'failed', progress: 100, error: { code, message } });
292
+ return next;
293
+ }
294
+ }
295
+ flight(agentAid) { return this.flights.get(agentAid); }
296
+ }
297
+ function withInitializationLock(agentAid, action) {
298
+ const directory = agentDataDir(agentAid);
299
+ fs.mkdirSync(directory, { recursive: true });
300
+ const lockPath = path.join(directory, 'team-workspace-initialize.lock');
301
+ let fd;
302
+ const deadline = Date.now() + 10_000;
303
+ while (fd === undefined) {
304
+ try {
305
+ fd = fs.openSync(lockPath, 'wx', 0o600);
306
+ }
307
+ catch (error) {
308
+ if (error.code !== 'EEXIST')
309
+ throw error;
310
+ try {
311
+ if (Date.now() - fs.statSync(lockPath).mtimeMs > 120_000)
312
+ fs.rmSync(lockPath, { force: true });
313
+ }
314
+ catch { }
315
+ if (Date.now() >= deadline)
316
+ throw new TeamWorkspaceBootstrapError('CONFLICT', 'Team workspace initialization is busy');
317
+ Atomics.wait(initializationWait, 0, 0, 20);
318
+ }
319
+ }
320
+ try {
321
+ return action();
322
+ }
323
+ finally {
324
+ try {
325
+ fs.closeSync(fd);
326
+ }
327
+ catch { }
328
+ try {
329
+ fs.rmSync(lockPath, { force: true });
330
+ }
331
+ catch { }
332
+ }
333
+ }
334
+ function samePath(left, right) {
335
+ const normalize = (value) => {
336
+ const resolved = path.resolve(value);
337
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
338
+ };
339
+ return normalize(left) === normalize(right);
340
+ }
341
+ function initializationFailureMessage(error) {
342
+ const code = error && typeof error === 'object' && typeof error.code === 'string'
343
+ ? error.code
344
+ : '';
345
+ if (code === 'ENOSPC')
346
+ return 'Insufficient disk space for the Team workspace';
347
+ if (code === 'EACCES' || code === 'EPERM')
348
+ return 'Permission denied while creating the Team workspace';
349
+ return 'Team workspace initialization failed';
350
+ }