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
@@ -0,0 +1,193 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isValidAid } from '../../aun/aid/validation.js';
3
+ import { ConfigTarget, mutateConfig, read } from '../../config/config-manager.js';
4
+ import { getPeerSnapshot, isAcceptedPeer } from '../../config/peer-book.js';
5
+ import { readOwnerDirectoryMembership } from '../../directory/owner-directory-admission.js';
6
+ import { readAunPeerKind } from '../relation/peer-identity.js';
7
+ export class TeamWorkspaceTeamError extends Error {
8
+ code;
9
+ data;
10
+ constructor(code, message, data) {
11
+ super(message);
12
+ this.code = code;
13
+ this.data = data;
14
+ this.name = 'TeamWorkspaceTeamError';
15
+ }
16
+ }
17
+ /** Structural validation also applies to removals of contacts that are no longer active. */
18
+ export function normalizeTeamMemberAids(value, selfAid) {
19
+ if (!Array.isArray(value) || value.length > 200) {
20
+ throw new TeamWorkspaceTeamError('INVALID_ARGUMENT', 'team must be an array of at most 200 Agent AIDs');
21
+ }
22
+ const members = value.map(item => typeof item === 'string' ? item.trim() : '');
23
+ if (members.some(aid => !isValidAid(aid)) || new Set(members).size !== members.length) {
24
+ throw new TeamWorkspaceTeamError('INVALID_ARGUMENT', 'team must contain unique valid Agent AIDs');
25
+ }
26
+ if (selfAid && members.includes(selfAid))
27
+ throw new TeamWorkspaceTeamError('INVALID_ARGUMENT', 'team cannot contain its own Agent AID');
28
+ return members;
29
+ }
30
+ function contactSnapshot(selfAid) {
31
+ try {
32
+ return getPeerSnapshot(selfAid);
33
+ }
34
+ catch {
35
+ throw new TeamWorkspaceTeamError('CONTACT_BOOK_INVALID', 'The current Agent contact book is unavailable');
36
+ }
37
+ }
38
+ function assertPeerContacts(selfAid, members) {
39
+ const snapshot = contactSnapshot(selfAid);
40
+ for (const aid of members) {
41
+ if (readAunPeerKind(selfAid, aid).kind !== 'private' || !snapshot.contacts.has(aid) || !isAcceptedPeer(selfAid, aid)) {
42
+ throw new TeamWorkspaceTeamError('TEAM_MEMBER_NOT_CONTACT', `Team member must be an active private Agent contact: ${aid}`, { memberAid: aid });
43
+ }
44
+ }
45
+ }
46
+ function assertActiveContacts(selfAid, members) {
47
+ for (const aid of members) {
48
+ const membership = readOwnerDirectoryMembership(selfAid, aid);
49
+ // Older/local installations do not have an Owner directory snapshot yet.
50
+ // Keep the established peer-book admission path usable in that case.
51
+ if (membership === undefined) {
52
+ assertPeerContacts(selfAid, members);
53
+ return;
54
+ }
55
+ // Directory unavailable
56
+ if (membership.category === 'unavailable') {
57
+ throw new TeamWorkspaceTeamError('CONTACT_BOOK_INVALID', 'Cannot verify team members: Owner directory temporarily unavailable');
58
+ }
59
+ // Not found in directory
60
+ if (membership.category === 'not_found') {
61
+ throw new TeamWorkspaceTeamError('TEAM_MEMBER_NOT_CONTACT', `Team member must be in Owner's directory: ${aid}`, { memberAid: aid });
62
+ }
63
+ // Only agent and human types can be team members (not host/device/service)
64
+ if (membership.category !== 'agent' && membership.category !== 'human' && membership.category !== 'assistant') {
65
+ throw new TeamWorkspaceTeamError('TEAM_MEMBER_NOT_CONTACT', `Team member must be an agent or human contact: ${aid}`, { memberAid: aid });
66
+ }
67
+ // Blocked contacts cannot be team members
68
+ if (membership.blocked) {
69
+ throw new TeamWorkspaceTeamError('TEAM_MEMBER_NOT_CONTACT', `Team member cannot be blocked: ${aid}`, { memberAid: aid });
70
+ }
71
+ }
72
+ }
73
+ function requireAgentConfig(selfAid) {
74
+ const config = read(ConfigTarget.Agent, { self: selfAid }, { cache: false });
75
+ if (!config)
76
+ throw new TeamWorkspaceTeamError('AGENT_NOT_FOUND', `Agent config was not found: ${selfAid}`);
77
+ return config;
78
+ }
79
+ function membersState(selfAid, value) {
80
+ const members = normalizeTeamMemberAids(value, selfAid);
81
+ const hash = createHash('sha256').update(JSON.stringify([selfAid, members])).digest('hex');
82
+ return { members, membersRevision: `sha256:${hash}` };
83
+ }
84
+ /** Revision covers only team membership, so unrelated config writes do not cause conflicts. */
85
+ export function readTeamMembersState(selfAid) {
86
+ return membersState(selfAid, requireAgentConfig(selfAid).team ?? []);
87
+ }
88
+ /** Keep stale contacts visible to the Owner so they can be removed. */
89
+ export function readTeamMemberDetails(selfAid, members) {
90
+ // Keep the legacy/local contact-book view when no Owner directory is configured.
91
+ if (members.some(aid => readOwnerDirectoryMembership(selfAid, aid) === undefined)) {
92
+ const snapshot = contactSnapshot(selfAid);
93
+ return members.map(aid => {
94
+ const contact = snapshot.contacts.get(aid);
95
+ const contactStatus = contact ? contact.status ?? 'active' : 'missing';
96
+ const reason = !contact ? 'NOT_A_CONTACT'
97
+ : contactStatus !== 'active' ? 'CONTACT_NOT_ACTIVE'
98
+ : readAunPeerKind(selfAid, aid).kind !== 'private' ? 'NOT_PRIVATE_CONTACT' : undefined;
99
+ return {
100
+ aid,
101
+ ...(contact?.displayName ? { displayName: contact.displayName } : {}),
102
+ contactStatus,
103
+ availability: reason ? 'unavailable' : 'available',
104
+ ...(reason ? { reason } : {}),
105
+ };
106
+ });
107
+ }
108
+ return members.map(aid => {
109
+ const membership = readOwnerDirectoryMembership(selfAid, aid);
110
+ // Directory not configured or unavailable
111
+ if (membership === undefined || membership.category === 'unavailable') {
112
+ return {
113
+ aid,
114
+ contactStatus: 'unavailable',
115
+ availability: 'unavailable',
116
+ reason: 'OWNER_DIRECTORY_UNAVAILABLE',
117
+ };
118
+ }
119
+ // Not found in directory
120
+ if (membership.category === 'not_found') {
121
+ return {
122
+ aid,
123
+ contactStatus: 'missing',
124
+ availability: 'unavailable',
125
+ reason: 'NOT_IN_OWNER_DIRECTORY',
126
+ };
127
+ }
128
+ // Blocked or wrong type
129
+ if (membership.blocked || (membership.category !== 'agent' && membership.category !== 'human' && membership.category !== 'assistant')) {
130
+ return {
131
+ aid,
132
+ displayName: membership.entry?.name,
133
+ contactStatus: membership.blocked ? 'missing' : 'unavailable',
134
+ availability: 'unavailable',
135
+ reason: membership.blocked ? 'NOT_IN_OWNER_DIRECTORY' : 'NOT_AGENT_TYPE',
136
+ };
137
+ }
138
+ // Valid contact
139
+ return {
140
+ aid,
141
+ displayName: membership.entry?.name,
142
+ contactStatus: 'active',
143
+ availability: 'available',
144
+ };
145
+ });
146
+ }
147
+ export function readTeamMembers(selfAid) {
148
+ const { members } = readTeamMembersState(selfAid);
149
+ assertActiveContacts(selfAid, members);
150
+ return members;
151
+ }
152
+ export function updateTeamMembers(selfAid, members) {
153
+ const normalized = normalizeTeamMemberAids(members, selfAid);
154
+ const result = mutateConfig(ConfigTarget.Agent, { self: selfAid }, config => {
155
+ requireAgentConfig(selfAid);
156
+ assertActiveContacts(selfAid, normalized);
157
+ config.team = normalized;
158
+ return normalized;
159
+ });
160
+ return { members: result.value, changed: result.changed };
161
+ }
162
+ /** Compare and mutate under the same ConfigManager lock used by the CLI. */
163
+ export function mutateTeamMembers(selfAid, mode, members, expectedRevision) {
164
+ if (typeof expectedRevision !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(expectedRevision)) {
165
+ throw new TeamWorkspaceTeamError('INVALID_ARGUMENT', 'args.expectedRevision must be a membersRevision returned by the members view');
166
+ }
167
+ const requested = normalizeTeamMemberAids(members, selfAid);
168
+ if (mode !== 'replace' && requested.length === 0) {
169
+ throw new TeamWorkspaceTeamError('INVALID_ARGUMENT', 'Add and remove operations require at least one member');
170
+ }
171
+ const result = mutateConfig(ConfigTarget.Agent, { self: selfAid }, config => {
172
+ requireAgentConfig(selfAid);
173
+ const current = membersState(selfAid, config.team ?? []);
174
+ if (current.membersRevision !== expectedRevision) {
175
+ throw new TeamWorkspaceTeamError('CONFLICT', 'Team members changed; query members again before retrying', { membersRevision: current.membersRevision });
176
+ }
177
+ // Removing a blocked/deleted contact must not require it to be accepted again.
178
+ if (mode !== 'remove')
179
+ assertActiveContacts(selfAid, requested);
180
+ const selected = new Set(requested);
181
+ const next = mode === 'replace' ? requested
182
+ : mode === 'remove' ? current.members.filter(aid => !selected.has(aid))
183
+ : [...current.members, ...requested.filter(aid => !current.members.includes(aid))];
184
+ const state = membersState(selfAid, next);
185
+ const addedCount = next.filter(aid => !current.members.includes(aid)).length;
186
+ const removedCount = current.members.filter(aid => !next.includes(aid)).length;
187
+ // Preserve omitted team on an unchanged empty list; no-op calls need no write.
188
+ if (state.membersRevision !== current.membersRevision)
189
+ config.team = state.members;
190
+ return { ...state, totalCount: next.length, addedCount, removedCount };
191
+ });
192
+ return { ...result.value, changed: result.changed };
193
+ }
@@ -37,14 +37,17 @@ export function startDaemonControlAid({ daemonCfg, cmdHandler, bindService, diag
37
37
  onServiceProxyManager?.(serviceProxyManager);
38
38
  let stopping = false;
39
39
  onShutdown(() => { stopping = true; return serviceProxyManager.stop(); });
40
- const startServices = async () => {
40
+ const startServices = async (phase) => {
41
+ phase?.('waiting', 'normal Ready');
41
42
  if (waitForServices && !await waitForServices())
42
- return;
43
- if (!stopping)
44
- await serviceProxyManager.start();
43
+ return false;
44
+ if (stopping)
45
+ return false;
46
+ phase?.('running');
47
+ await serviceProxyManager.start();
45
48
  };
46
49
  const proxyStartup = startupTrace
47
- ? startupTrace.track('daemon.serviceProxyStart', startServices)
50
+ ? startupTrace.track('daemon.serviceProxyStart', startServices, undefined, { initialPhase: 'waiting' })
48
51
  : startServices();
49
52
  void proxyStartup.catch((error) => {
50
53
  logger.warn(`ServiceProxy manager 启动失败(不影响 daemon 主流程): ${error?.message || error}`);
@@ -88,9 +88,13 @@ export async function discoverStartupWork(options) {
88
88
  else
89
89
  plan.requiredExternalAids.add(aid);
90
90
  };
91
+ const queueStarted = Date.now();
92
+ let queueItems = 0;
93
+ let queueFiles = 0;
91
94
  try {
92
95
  const queue = await json(options.queuePath);
93
96
  if (queue !== undefined) {
97
+ queueFiles = 1;
94
98
  if (!queue || ![1, 2].includes(queue.version) || !Array.isArray(queue.queues)
95
99
  || (queue.active !== undefined && !Array.isArray(queue.active)))
96
100
  throw new Error('invalid queue snapshot');
@@ -98,6 +102,7 @@ export async function discoverStartupWork(options) {
98
102
  if (!Array.isArray(bucket.items))
99
103
  throw new Error('invalid queue bucket');
100
104
  for (const item of bucket.items) {
105
+ queueItems++;
101
106
  noteMessage(item.message, bucket.queueKey);
102
107
  for (const part of item.parts ?? [])
103
108
  noteMessage(part.message, bucket.queueKey);
@@ -110,19 +115,65 @@ export async function discoverStartupWork(options) {
110
115
  uncertain(aid, error);
111
116
  }
112
117
  finally {
118
+ options.onScan?.({ phase: 'queue', durationMs: Date.now() - queueStarted, files: queueFiles, items: queueItems });
113
119
  options.onQueueCaptured?.();
114
120
  }
115
121
  const now = Date.now();
116
122
  const triggerDir = options.triggerDir ?? agentTriggersDir;
117
123
  const handoffStore = options.handoffStore ?? new HandoffStore();
118
- const aids = [...new Set([...known, options.daemonTriggerAid])];
124
+ const scanTriggers = async (aid) => {
125
+ const started = Date.now();
126
+ let files = 0;
127
+ try {
128
+ for (const id of await directories(triggerDir(aid))) {
129
+ files++;
130
+ const active = await json(path.join(triggerDir(aid), id, 'active.json'));
131
+ if (active === undefined)
132
+ continue;
133
+ if (!active || typeof active.runs !== 'object' || !active.runs || Array.isArray(active.runs)) {
134
+ throw new Error(`invalid Trigger active state: ${id}`);
135
+ }
136
+ if (Object.keys(active.runs).length) {
137
+ plan.triggerAids.add(aid);
138
+ const definition = await json(path.join(triggerDir(aid), id, 'trigger.json'));
139
+ if (!definition) {
140
+ plan.requiredExternalAids.add(aid);
141
+ continue;
142
+ }
143
+ for (const key of [definition.origin?.channelKey, definition.feedback?.target?.channelKey,
144
+ ...Object.values(active.runs).map((run) => run?.source?.payload?.channelKey ?? run?.source?.payload?.channel)]) {
145
+ if (typeof key === 'string')
146
+ plan.requiredChannelKeys.add(key);
147
+ }
148
+ if (definition.feedback?.strategy === 'event_session')
149
+ plan.requiredExternalAids.add(aid);
150
+ }
151
+ }
152
+ }
153
+ catch (error) {
154
+ plan.triggerAids.add(aid);
155
+ uncertain(aid, error);
156
+ }
157
+ if (plan.triggerAids.has(aid)) {
158
+ const owner = aid === options.daemonTriggerAid ? options.primaryAid : aid;
159
+ if (owner)
160
+ plan.priorityAids.add(owner);
161
+ }
162
+ options.onScan?.({ phase: 'triggers', aid, durationMs: Date.now() - started, files });
163
+ };
164
+ // A daemon-owned run can make the primary Agent busy. Finish that decision
165
+ // before publishing its classification, without delaying other Agents.
166
+ const daemonTriggerScan = scanTriggers(options.daemonTriggerAid);
167
+ const aids = [...known];
119
168
  let next = 0;
120
- await Promise.all(Array.from({ length: Math.min(4, aids.length) }, async () => {
121
- while (next < aids.length) {
122
- const aid = aids[next++];
123
- if (known.has(aid)) {
169
+ await Promise.all([daemonTriggerScan, ...Array.from({ length: Math.min(4, aids.length) }, async () => {
170
+ while (next < aids.length) {
171
+ const aid = aids[next++];
172
+ let started = Date.now();
173
+ let files = 0;
124
174
  try {
125
175
  const snapshots = await handoffStore.listAsync(aid);
176
+ files = snapshots.length;
126
177
  plan.handoffSnapshots.set(aid, snapshots);
127
178
  if (snapshots.some(needsHandoffRecovery))
128
179
  plan.priorityAids.add(aid);
@@ -130,27 +181,39 @@ export async function discoverStartupWork(options) {
130
181
  catch (error) {
131
182
  uncertain(aid, error);
132
183
  }
184
+ options.onScan?.({ phase: 'handoff', aid, durationMs: Date.now() - started, files });
185
+ started = Date.now();
186
+ files = 0;
187
+ let chats = 0;
133
188
  try {
134
- for (const chat of await scanAgentChatDirsAsync(options.sessionsRoot, aid)) {
135
- for (const metaDir of [chat.dirPath, path.join(chat.dirPath, '_threads')]) {
136
- let names;
189
+ for (const chat of await scanAgentChatDirsAsync(options.sessionsRoot, aid, undefined, { includeEntries: true })) {
190
+ chats++;
191
+ const dirs = [{ dirPath: chat.dirPath, names: chat.entries.map(entry => entry.name) }];
192
+ if (chat.entries.some(entry => entry.name === '_threads')) {
193
+ const dirPath = path.join(chat.dirPath, '_threads');
137
194
  try {
138
- names = await fs.promises.readdir(metaDir);
195
+ dirs.push({ dirPath, names: await fs.promises.readdir(dirPath) });
139
196
  }
140
197
  catch (error) {
141
- if (error.code === 'ENOENT')
142
- continue;
143
- throw error;
198
+ if (error.code !== 'ENOENT')
199
+ throw error;
144
200
  }
145
- const files = names.filter(name => /^meta_.*\.jsonl$/.test(name));
146
- for (let offset = 0; offset < files.length; offset += 8) {
147
- await Promise.all(files.slice(offset, offset + 8).map(async (name) => {
148
- const data = await readLastJsonlLineAsync(path.join(metaDir, name), path.basename(metaDir) === '_threads');
149
- if (!data)
150
- return;
151
- const session = fileToSession(data);
201
+ }
202
+ for (const dir of dirs) {
203
+ const names = dir.names.filter(name => /^meta_.*\.jsonl$/.test(name));
204
+ files += names.length;
205
+ for (let offset = 0; offset < names.length; offset += 8) {
206
+ const records = await Promise.allSettled(names.slice(offset, offset + 8).map(name => readLastJsonlLineAsync(path.join(dir.dirPath, name), path.basename(dir.dirPath) === '_threads')));
207
+ // Do not release classification while another read in a failed
208
+ // batch is still able to mutate the work plan.
209
+ for (const record of records) {
210
+ if (record.status === 'rejected')
211
+ throw record.reason;
212
+ if (!record.value)
213
+ continue;
214
+ const session = fileToSession(record.value);
152
215
  if (!session.processingState)
153
- return;
216
+ continue;
154
217
  const startedAt = Number.parseInt(session.processingState.split(':', 1)[0], 10);
155
218
  if (Number.isFinite(startedAt) && now - startedAt < 3_600_000) {
156
219
  plan.pendingSessions.push(session);
@@ -159,7 +222,7 @@ export async function discoverStartupWork(options) {
159
222
  }
160
223
  else
161
224
  plan.staleSessions.push(session);
162
- }));
225
+ }
163
226
  }
164
227
  }
165
228
  }
@@ -168,69 +231,51 @@ export async function discoverStartupWork(options) {
168
231
  plan.sessionScanFailed = true;
169
232
  uncertain(aid, error);
170
233
  }
234
+ options.onScan?.({ phase: 'sessions', aid, durationMs: Date.now() - started, files, directories: chats });
235
+ if (aid === options.daemonTriggerAid)
236
+ await daemonTriggerScan;
237
+ else
238
+ await scanTriggers(aid);
239
+ if (aid === options.primaryAid)
240
+ await daemonTriggerScan;
241
+ options.onAgentDiscovered?.(aid, plan);
171
242
  }
172
- try {
173
- for (const id of await directories(triggerDir(aid))) {
174
- const active = await json(path.join(triggerDir(aid), id, 'active.json'));
175
- if (active === undefined)
176
- continue;
177
- if (!active || typeof active.runs !== 'object' || !active.runs || Array.isArray(active.runs)) {
178
- throw new Error(`invalid Trigger active state: ${id}`);
179
- }
180
- if (Object.keys(active.runs).length) {
181
- plan.triggerAids.add(aid);
182
- const definition = await json(path.join(triggerDir(aid), id, 'trigger.json'));
183
- if (!definition) {
184
- plan.requiredExternalAids.add(aid);
185
- continue;
186
- }
187
- for (const key of [definition.origin?.channelKey, definition.feedback?.target?.channelKey,
188
- ...Object.values(active.runs).map((run) => run?.source?.payload?.channelKey ?? run?.source?.payload?.channel)]) {
189
- if (typeof key === 'string')
190
- plan.requiredChannelKeys.add(key);
191
- }
192
- if (definition.feedback?.strategy === 'event_session')
193
- plan.requiredExternalAids.add(aid);
194
- }
195
- }
196
- }
197
- catch (error) {
198
- plan.triggerAids.add(aid);
199
- uncertain(aid, error);
200
- }
201
- if (plan.triggerAids.has(aid)) {
202
- const owner = aid === options.daemonTriggerAid ? options.primaryAid : aid;
203
- if (owner)
204
- plan.priorityAids.add(owner);
205
- }
206
- }
207
- }));
243
+ })]);
208
244
  return plan;
209
245
  }
210
246
  /** Bounded admission for startup side effects. Dependency waits belong outside this queue. */
211
247
  export class StartupTaskQueue {
212
248
  concurrency;
213
249
  intervalMs;
250
+ backgroundConcurrency;
214
251
  pending = [];
215
252
  active = 0;
253
+ activeBackground = 0;
216
254
  stopped = false;
217
255
  timer;
218
- constructor(concurrency = 2, intervalMs = 50) {
256
+ constructor(concurrency = 2, intervalMs = 50, backgroundConcurrency = concurrency) {
219
257
  this.concurrency = concurrency;
220
258
  this.intervalMs = intervalMs;
221
- if (!Number.isInteger(concurrency) || concurrency < 1 || !Number.isFinite(intervalMs) || intervalMs < 0) {
259
+ this.backgroundConcurrency = backgroundConcurrency;
260
+ if (!Number.isInteger(concurrency) || concurrency < 1 || !Number.isFinite(intervalMs) || intervalMs < 0
261
+ || !Number.isInteger(backgroundConcurrency) || backgroundConcurrency < 1 || backgroundConcurrency > concurrency) {
222
262
  throw new Error('Invalid startup task queue limits');
223
263
  }
224
264
  }
225
- run(run, valid = () => true) {
265
+ run(run, valid = () => true, priority = 'foreground') {
226
266
  if (this.stopped)
227
267
  return Promise.resolve(false);
228
268
  const result = new Promise((resolve, reject) => {
229
- this.pending.push({ run, valid, resolve, reject });
269
+ this.pending.push({ run, valid, resolve, reject, priority });
230
270
  });
231
271
  this.schedule();
232
272
  return result;
233
273
  }
274
+ /** Once priority work is ready (or degraded), background work may use all slots. */
275
+ releaseBackground() {
276
+ this.backgroundConcurrency = this.concurrency;
277
+ this.schedule();
278
+ }
234
279
  stop() {
235
280
  this.stopped = true;
236
281
  if (this.timer)
@@ -242,13 +287,23 @@ export class StartupTaskQueue {
242
287
  schedule() {
243
288
  if (this.stopped || this.timer || this.active >= this.concurrency || !this.pending.length)
244
289
  return;
290
+ if (this.activeBackground >= this.backgroundConcurrency
291
+ && !this.pending.some(task => task.priority === 'foreground'))
292
+ return;
245
293
  // Yield between admissions even when tasks finish synchronously.
246
294
  this.timer = setTimeout(() => {
247
295
  this.timer = undefined;
248
- const task = this.pending.shift();
296
+ // Choose at admission time, so newly classified priority work can pass
297
+ // queued idle channels without interrupting an existing connection.
298
+ let index = this.pending.findIndex(task => task.priority === 'foreground');
299
+ if (index < 0 && this.activeBackground < this.backgroundConcurrency)
300
+ index = 0;
301
+ const task = index < 0 ? undefined : this.pending.splice(index, 1)[0];
249
302
  if (!task)
250
303
  return;
251
304
  this.active++;
305
+ if (task.priority === 'background')
306
+ this.activeBackground++;
252
307
  void Promise.resolve().then(async () => {
253
308
  if (this.stopped || !task.valid())
254
309
  return false;
@@ -256,6 +311,8 @@ export class StartupTaskQueue {
256
311
  return true;
257
312
  }).then(task.resolve, task.reject).finally(() => {
258
313
  this.active--;
314
+ if (task.priority === 'background')
315
+ this.activeBackground--;
259
316
  this.schedule();
260
317
  });
261
318
  this.schedule();
@@ -323,7 +380,7 @@ export async function recoverStartupHandoffs({ channelInstances, recoveryAids, a
323
380
  try {
324
381
  const options = {
325
382
  isCancelled,
326
- onPhase: (phase, start, end, detail) => trace?.addSpan(`daemon.handoffRecovery.${phase}`, start, end, detail ? `${aid}; ${detail}` : aid),
383
+ onPhase: (phase, start, end, detail, status) => trace?.addSpan(`daemon.handoffRecovery.${phase}`, start, end, detail ? `${aid}; ${detail}` : aid, status),
327
384
  };
328
385
  const snapshots = await cleanupAgentHandoffs?.(aid, options);
329
386
  if (isCancelled?.())
@@ -402,7 +459,7 @@ export async function recoverStartupHandoffs({ channelInstances, recoveryAids, a
402
459
  const started = Date.now();
403
460
  try {
404
461
  await handoffRuntime.recover([aid], { snapshots, discardExpired: false, isCancelled,
405
- onPhase: (phase, start, end, detail) => trace?.addSpan(`daemon.handoffTerminalAudit.${phase}`, start, end, detail ? `${aid}; ${detail}` : aid) });
462
+ onPhase: (phase, start, end, detail, status) => trace?.addSpan(`daemon.handoffTerminalAudit.${phase}`, start, end, detail ? `${aid}; ${detail}` : aid, status) });
406
463
  trace?.addSpan('daemon.handoffTerminalAudit.agent', started, Date.now(), aid, isCancelled?.() ? 'cancelled' : 'ok');
407
464
  terminalAudits.delete(aid);
408
465
  }
@@ -484,7 +541,7 @@ export function resumePendingSessions({ sessionManager, messageQueue, droppedTri
484
541
  });
485
542
  }
486
543
  }
487
- export function createDaemonShutdown({ disposePluginResources, lifecycleNotices, stopOwnership, ipcServer, readySignalPath, bindService, ecwebSupervisor, messageQueue, permissionGateway, removePermissionConfigListener, stopStatsPersistence, triggerSchedulers, agentMap, eventBus, removeGroupInviteConfigListener, groupInviteReviewService, channelLoader, channelInstances, startupRunners, cancelStartup, controlChannel, sessionManager, removeAll, exit, }) {
544
+ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices, stopOwnership, ipcServer, readySignalPath, bindService, ecwebSupervisor, messageQueue, permissionGateway, removePermissionConfigListener, stopStatsPersistence, triggerSchedulers, agentMap, eventBus, removeGroupInviteConfigListener, groupInviteReviewService, channelLoader, channelInstances, startupRunners, waitForRunnerLoads, cancelStartup, controlChannel, sessionManager, removeAll, exit, }) {
488
545
  let shutdownSignal = 'unknown';
489
546
  let shutdownInProgress = false;
490
547
  return async (signal, traceId) => {
@@ -577,19 +634,21 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
577
634
  });
578
635
  });
579
636
  try {
580
- const queueShutdown = messageQueue.shutdownGracefully();
581
- await shutdownStep('daemon.stopPermissions', 'cancel pending permissions', () => permissionGateway.cancelAllPending('daemon_restart'));
582
- // 这两步各带超时(5s / 6.5s),退出慢的头号嫌疑就是它们空等到超时。
583
- await shutdownStep('daemon.triggerIdle', 'wait for trigger schedulers', async () => {
584
- await triggerSchedulers.waitForIdle(5_000);
585
- });
586
- await shutdownStep('daemon.triggerSuspend', 'suspend trigger schedulers', async () => {
637
+ // Freeze Trigger admission and mark resumable runs suspended before the
638
+ // queue interrupts their turns. Waiting for idle first adds a full 5s for
639
+ // long-lived runs and still leaves timers free to start more work.
640
+ const triggerShutdown = shutdownStep('daemon.triggerSuspend', 'suspend trigger schedulers', async () => {
587
641
  await triggerSchedulers.suspendForDaemonExit();
588
642
  });
589
- await shutdownStep('daemon.queueDrain', 'interrupt active message queue tasks', async () => { await queueShutdown; });
643
+ const queueShutdown = shutdownStep('daemon.queueDrain', 'interrupt active message queue tasks', async () => {
644
+ await messageQueue.shutdownGracefully();
645
+ });
646
+ await shutdownStep('daemon.stopPermissions', 'cancel pending permissions', () => permissionGateway.cancelAllPending('daemon_restart'));
647
+ await Promise.all([triggerShutdown, queueShutdown]);
590
648
  await shutdownStep('daemon.agentRunners', 'dispose agent runners', async () => {
591
649
  if (startupRunners)
592
650
  await Promise.allSettled([startupRunners]);
651
+ await waitForRunnerLoads?.();
593
652
  const currentInstances = [...agentMap.entries()].map(([key, agent]) => {
594
653
  const split = key.lastIndexOf('::');
595
654
  return {
@@ -700,7 +700,7 @@ export class HandoffRuntime {
700
700
  const snapshots = options.snapshots ?? await this.store.listAsync(selfAid, stats => {
701
701
  scanDetail = Object.entries(stats).map(([key, value]) => `${key}=${Math.round(value)}`).join('; ');
702
702
  });
703
- options.onPhase?.('scan', started, Date.now(), scanDetail);
703
+ options.onPhase?.('scan', started, Date.now(), scanDetail, options.snapshots ? 'skipped' : 'ok');
704
704
  started = Date.now();
705
705
  if (options.discardExpired !== false)
706
706
  await this.discardExpiredCandidates(selfAid, snapshots);
@@ -715,7 +715,7 @@ export class HandoffRuntime {
715
715
  this.dispatcher.expireQueued(selfAid, undefined, [snapshot]);
716
716
  await yieldToIo();
717
717
  }
718
- options.onPhase?.('cleanup', started, Date.now());
718
+ options.onPhase?.('cleanup', started, Date.now(), undefined, snapshots.length ? 'ok' : 'skipped');
719
719
  return snapshots;
720
720
  }
721
721
  async recover(selfAids, options = {}) {
@@ -820,7 +820,7 @@ export class HandoffRuntime {
820
820
  }
821
821
  const started = Date.now();
822
822
  await Promise.all(originEnqueues);
823
- options.onPhase?.('origin', started, Date.now());
823
+ options.onPhase?.('origin', started, Date.now(), undefined, originEnqueues.length ? 'ok' : 'skipped');
824
824
  }
825
825
  async discardWithTargetLock(selfAid, handoffId, reason, details, expectedVersion, now = this.now?.()) {
826
826
  const snapshot = this.store.get(selfAid, handoffId);
@@ -0,0 +1,13 @@
1
+ import { TEXT_EXECUTORS } from './text.js';
2
+ import { MEDIA_EXECUTORS } from './media.js';
3
+ /**
4
+ * 全部内置执行器。
5
+ *
6
+ * 新增内置形态时在这里登记,并在 `style-router.ts` 的路由说明里同步。
7
+ * 路由是显式的,不做动态探测。
8
+ */
9
+ export const BUILTIN_EXECUTORS = [
10
+ ...TEXT_EXECUTORS,
11
+ ...MEDIA_EXECUTORS,
12
+ ];
13
+ export { TEXT_EXECUTORS, MEDIA_EXECUTORS };