evolcore 0.0.43-test.5 → 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 (259) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/bin/ecmsg.js +281 -81
  3. package/dist/agents/baseagent-availability.js +20 -5
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +36 -3
  7. package/dist/agents/codex-runner.js +75 -8
  8. package/dist/aun/group/invite-service.js +3 -2
  9. package/dist/aun/msg/p2p.js +6 -1
  10. package/dist/aun/service-proxy.js +18 -6
  11. package/dist/channels/aun.js +306 -30
  12. package/dist/cli/agent-create.js +18 -8
  13. package/dist/cli/aun-commands.js +9 -1
  14. package/dist/cli/daemon-commands.js +34 -65
  15. package/dist/cli/daemon-lifecycle-client.js +61 -0
  16. package/dist/cli/ecmsg-gateway.js +38 -3
  17. package/dist/cli/events-command.js +73 -0
  18. package/dist/cli/index.js +31 -14
  19. package/dist/cli/init.js +75 -0
  20. package/dist/cli/invoke-command.js +182 -0
  21. package/dist/cli/managed-command-guard.js +6 -1
  22. package/dist/cli/provider-command.js +1 -1
  23. package/dist/cli/restart-monitor.js +67 -50
  24. package/dist/cli/services-command.js +111 -0
  25. package/dist/cli/task-context.js +38 -1
  26. package/dist/cli/team-workspace-command.js +134 -0
  27. package/dist/cli/thread-command.js +6 -2
  28. package/dist/cli/watch-logs.js +6 -4
  29. package/dist/cli/watch-msg.js +1 -1
  30. package/dist/config/boot-log.js +6 -4
  31. package/dist/config/builtin-roles.js +2 -2
  32. package/dist/config/config-field-policy.js +2 -2
  33. package/dist/config/config-manager.js +1 -8
  34. package/dist/config/invoke-ipc-service.js +118 -0
  35. package/dist/config/peer-role-resolver.js +1 -1
  36. package/dist/config/provider-identity-migration.js +92 -17
  37. package/dist/config/provider-local-sync.js +2 -0
  38. package/dist/config/providers-config.js +13 -0
  39. package/dist/config/providers-management.js +100 -10
  40. package/dist/config/role-service.js +8 -8
  41. package/dist/config/role-store.js +22 -22
  42. package/dist/config/schema-migration.js +86 -88
  43. package/dist/config/snapshot.js +70 -41
  44. package/dist/config-store.js +2 -1
  45. package/dist/core/agent-reload-coordinator.js +6 -4
  46. package/dist/core/agent-runtime.js +146 -15
  47. package/dist/core/auth/delegation-authorization.js +66 -0
  48. package/dist/core/auth/operation-catalog.js +20 -0
  49. package/dist/core/baseagent-loader.js +75 -42
  50. package/dist/core/channel-loader.js +45 -13
  51. package/dist/core/channel-runtime.js +116 -45
  52. package/dist/core/command/agent-control.js +1 -1
  53. package/dist/core/command/agent-storage-menu.js +1 -1
  54. package/dist/core/command/chatmode-config.js +2 -36
  55. package/dist/core/command/command-handler.js +58 -16
  56. package/dist/core/command/data-root-resolver.js +32 -23
  57. package/dist/core/command/eventcenter-menu.js +338 -0
  58. package/dist/core/command/menu-catalog.js +8 -0
  59. package/dist/core/command/menu-handler.js +206 -87
  60. package/dist/core/command/menu-protocol.js +142 -22
  61. package/dist/core/command/menu-query-batch.js +194 -0
  62. package/dist/core/command/role-menu.js +27 -15
  63. package/dist/core/command/slash-gate.js +1 -1
  64. package/dist/core/command/slash-handler.js +34 -42
  65. package/dist/core/command/team-workspace-bootstrap.js +350 -0
  66. package/dist/core/command/{pa-workspace-calendar.js → team-workspace-calendar.js} +7 -7
  67. package/dist/core/command/team-workspace-initializer.js +2 -0
  68. package/dist/core/command/{pa-workspace-items.js → team-workspace-items.js} +83 -68
  69. package/dist/core/command/team-workspace-job-store.js +88 -0
  70. package/dist/core/command/team-workspace-management-service.js +2 -0
  71. package/dist/core/command/team-workspace-management-store.js +96 -0
  72. package/dist/core/command/team-workspace-management.js +265 -0
  73. package/dist/core/command/team-workspace-members-menu.js +88 -0
  74. package/dist/core/command/team-workspace-store.js +612 -0
  75. package/dist/core/command/team-workspace-team.js +193 -0
  76. package/dist/core/daemon-control.js +45 -15
  77. package/dist/core/daemon-lifecycle.js +478 -75
  78. package/dist/core/handoff/dispatcher.js +9 -3
  79. package/dist/core/handoff/runtime.js +130 -42
  80. package/dist/core/handoff/store.js +190 -2
  81. package/dist/core/handoff/types.js +5 -0
  82. package/dist/core/initialization/service.js +4 -4
  83. package/dist/core/invoke/executors/index.js +13 -0
  84. package/dist/core/invoke/executors/media.js +283 -0
  85. package/dist/core/invoke/executors/text.js +198 -0
  86. package/dist/core/invoke/invoke-service.js +157 -0
  87. package/dist/core/invoke/style-router.js +48 -0
  88. package/dist/core/invoke/types.js +19 -0
  89. package/dist/core/ipc-registration.js +51 -11
  90. package/dist/core/lifecycle-notice.js +10 -4
  91. package/dist/core/memory/consolidation.js +7 -5
  92. package/dist/core/message/aun-ipc-sender.js +149 -19
  93. package/dist/core/message/im-renderer.js +28 -84
  94. package/dist/core/message/message-bridge.js +57 -4
  95. package/dist/core/message/message-queue.js +46 -4
  96. package/dist/core/message/message-utils.js +10 -2
  97. package/dist/core/message/peer-mode.js +7 -34
  98. package/dist/core/message/pending-hints.js +4 -10
  99. package/dist/core/message/response-engine.js +163 -52
  100. package/dist/core/message/send-options.js +7 -4
  101. package/dist/core/message/send-routing.js +55 -7
  102. package/dist/core/ownership/owner-resolver.js +8 -0
  103. package/dist/core/permission/ec-command-parser.js +14 -3
  104. package/dist/core/permission/protected-paths.js +12 -2
  105. package/dist/core/permission/shell-environment.js +9 -0
  106. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  107. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  108. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  109. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  110. package/dist/core/session/session-file-health.js +243 -0
  111. package/dist/core/session/session-fs-store.js +163 -3
  112. package/dist/core/session/session-idle-monitor.js +9 -1
  113. package/dist/core/session/session-manager.js +36 -2
  114. package/dist/core/task/task-recovery-service.js +13 -2
  115. package/dist/core/thread/command-parser.js +9 -2
  116. package/dist/core/thread/thread-operation.js +21 -2
  117. package/dist/core/thread/thread-route.js +13 -2
  118. package/dist/directory/owner-directory-admission.js +42 -30
  119. package/dist/directory/owner-directory-cache.js +143 -126
  120. package/dist/directory/owner-directory-query-operation.js +9 -8
  121. package/dist/eck/kit-renderer.js +7 -5
  122. package/dist/ecweb/basic-settings-service.js +1 -1
  123. package/dist/ecweb/message-context-service.js +0 -4
  124. package/dist/ecweb/runtime/lifecycle.js +14 -8
  125. package/dist/ecweb/runtime/supervisor.js +62 -30
  126. package/dist/event-center/admission-materializer.js +114 -0
  127. package/dist/event-center/bus-gate.js +136 -0
  128. package/dist/event-center/bus-host.js +290 -0
  129. package/dist/event-center/bus-resolver.js +120 -0
  130. package/dist/event-center/center-config.js +100 -0
  131. package/dist/event-center/client-factory.js +50 -0
  132. package/dist/event-center/daemon.js +45 -0
  133. package/dist/event-center/directory-source.js +53 -0
  134. package/dist/event-center/dispatcher.js +157 -0
  135. package/dist/event-center/event-log.js +110 -0
  136. package/dist/event-center/index-generator.js +63 -0
  137. package/dist/event-center/ipc-operation.js +308 -0
  138. package/dist/event-center/ledger.js +52 -0
  139. package/dist/event-center/pack-loader.js +202 -0
  140. package/dist/event-center/pack-manager.js +85 -0
  141. package/dist/event-center/registry.js +238 -0
  142. package/dist/event-center/runtime.js +641 -0
  143. package/dist/event-center/script-runner.js +356 -0
  144. package/dist/event-center/types.js +35 -0
  145. package/dist/event-center/validation.js +413 -0
  146. package/dist/index.js +751 -268
  147. package/dist/ipc.js +66 -12
  148. package/dist/paths.js +20 -0
  149. package/dist/product.js +14 -0
  150. package/dist/proxy/manager.js +43 -18
  151. package/dist/proxy/service-supervisor.js +78 -35
  152. package/dist/response-system/engines/v1/index.js +0 -1
  153. package/dist/response-system/modes/single-session/index.js +1 -1
  154. package/dist/services/dispatcher.js +100 -0
  155. package/dist/services/idempotency.js +90 -0
  156. package/dist/services/identity.js +52 -0
  157. package/dist/services/index-generator.js +70 -0
  158. package/dist/services/index.js +449 -0
  159. package/dist/services/ipc-operation.js +458 -0
  160. package/dist/services/ledger.js +52 -0
  161. package/dist/services/message-log.js +112 -0
  162. package/dist/services/pack-manager.js +204 -0
  163. package/dist/services/reply.js +55 -0
  164. package/dist/services/router.js +95 -0
  165. package/dist/services/script-runner.js +422 -0
  166. package/dist/services/service-payload.js +70 -0
  167. package/dist/services/types.js +18 -0
  168. package/dist/services/validation.js +297 -0
  169. package/dist/trigger/application-service.js +21 -1
  170. package/dist/trigger/audit.js +19 -4
  171. package/dist/trigger/authorization.js +14 -5
  172. package/dist/trigger/event-source.js +1 -1
  173. package/dist/trigger/history.js +176 -7
  174. package/dist/trigger/ipc-service.js +3 -1
  175. package/dist/trigger/manager.js +1 -3
  176. package/dist/trigger/scheduler.js +78 -5
  177. package/dist/trigger/script-sandbox.js +118 -22
  178. package/dist/utils/cross-platform.js +175 -13
  179. package/dist/utils/evolcore-version.js +69 -27
  180. package/dist/utils/host-info.js +11 -8
  181. package/dist/utils/instance-registry.js +19 -13
  182. package/dist/utils/npm-ops.js +48 -0
  183. package/dist/utils/process-introspect.js +109 -10
  184. package/dist/utils/startup-trace.js +222 -44
  185. package/dist/utils/windows-shell-trust.js +80 -6
  186. package/kits/docs/INDEX.md +2 -2
  187. package/kits/docs/aun/ABILITY_CALLING.md +10 -17
  188. package/kits/docs/context-assembly.md +1 -1
  189. package/kits/docs/evolcore/INDEX.md +5 -2
  190. package/kits/docs/evolcore/ability.md +4 -0
  191. package/kits/docs/evolcore/aid.md +1 -1
  192. package/kits/docs/evolcore/ctl.md +2 -1
  193. package/kits/docs/evolcore/event-center.md +207 -0
  194. package/kits/docs/evolcore/file-navigation.md +10 -264
  195. package/kits/docs/evolcore/fs.md +3 -2
  196. package/kits/docs/evolcore/group.md +2 -2
  197. package/kits/docs/evolcore/memory-architecture.md +2 -0
  198. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  199. package/kits/docs/evolcore/menu-protocol.md +21 -0
  200. package/kits/docs/evolcore/msg.md +27 -8
  201. package/kits/docs/evolcore/provider.md +23 -3
  202. package/kits/docs/evolcore/response.md +5 -5
  203. package/kits/docs/evolcore/services.md +277 -0
  204. package/kits/docs/evolcore/task.md +2 -0
  205. package/kits/docs/evolcore/team-workspace.md +41 -0
  206. package/kits/eck_manifest.json +45 -7
  207. package/kits/eck_message_manifest.json +3 -3
  208. package/kits/rules/02-navigation.md +10 -1
  209. package/kits/rules/06-channel.md +5 -6
  210. package/kits/schemas/_meta.json +17 -6
  211. package/kits/schemas/agent-config.schema.19.json +5 -7
  212. package/kits/schemas/agent-config.schema.20.json +936 -0
  213. package/kits/schemas/daemon.schema.1.json +5 -0
  214. package/kits/schemas/daemon.schema.2.json +5 -0
  215. package/kits/schemas/daemon.schema.3.json +2 -1
  216. package/kits/schemas/daemon.schema.4.json +2 -1
  217. package/kits/schemas/daemon.schema.5.json +2 -1
  218. package/kits/schemas/daemon.schema.6.json +1 -1
  219. package/kits/schemas/daemon.schema.7.json +1 -1
  220. package/kits/schemas/daemon.schema.8.json +2 -1
  221. package/kits/schemas/daemon.schema.9.json +2 -1
  222. package/kits/schemas/relation-config.schema.12.json +2 -3
  223. package/kits/schemas/role-config.schema.2.json +4 -4
  224. package/kits/schemas/role-registry.schema.1.json +2 -2
  225. package/kits/schemas/single-session.schema.1.json +1 -1
  226. package/kits/schemas/single-session.schema.2.json +1 -1
  227. package/kits/schemas/single-session.schema.3.json +1 -1
  228. package/kits/skills/.switches.json +1 -5
  229. package/kits/skills/ability/SKILL.md +56 -0
  230. package/kits/skills/ability/references/calling.md +56 -0
  231. package/kits/skills/{ec-ability → ability}/references/contract-checklist.md +1 -1
  232. package/kits/skills/{ec-ability → ability}/references/development.md +9 -33
  233. package/kits/skills/{ec-ability → ability}/references/management.md +2 -2
  234. package/kits/skills/{ec-ability → ability}/references/recovery.md +1 -1
  235. package/kits/skills/{ec-ability → ability}/references/runtime-protocol.md +2 -0
  236. package/kits/skills/ec-agent-create/SKILL.md +0 -1
  237. package/kits/skills/ec-group/SKILL.md +8 -5
  238. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  239. package/kits/skills/ec-service-proxy/SKILL.md +34 -5
  240. package/kits/skills/ec-trigger/SKILL.md +4 -4
  241. package/kits/skills/personal-assistant/SKILL.md +6 -6
  242. package/kits/skills/personal-assistant/references/02-bootstrap.md +4 -4
  243. package/kits/skills/personal-assistant/scripts/clean.mjs +4 -4
  244. package/kits/skills/personal-assistant/scripts/init.mjs +2 -2
  245. package/kits/skills/personal-assistant/scripts/pa.mjs +4 -4
  246. package/kits/skills/thread-ops/SKILL.md +10 -10
  247. package/kits/templates/system-fragments/channel.md +3 -3
  248. package/kits/templates/system-fragments/commands.md +9 -7
  249. package/kits/templates/system-fragments/reply.md +2 -6
  250. package/kits/templates/system-fragments/session.md +1 -1
  251. package/kits/templates/system-fragments/thread.md +11 -9
  252. package/package.json +5 -6
  253. package/dist/cli/pa-workspace-command.js +0 -225
  254. package/dist/core/command/pa-workspace-store.js +0 -468
  255. package/dist/core/relation/pa-team.js +0 -132
  256. package/kits/docs/evolcore/pa-workspace.md +0 -51
  257. package/kits/skills/aid-ability/SKILL.md +0 -244
  258. package/kits/skills/ec-ability/SKILL.md +0 -67
  259. package/kits/skills/ec-ability/references/workflows.md +0 -15
@@ -1,10 +1,350 @@
1
1
  import { tryParseChannelKey } from './channel-loader.js';
2
+ import { needsHandoffRecovery } from './handoff/types.js';
2
3
  import { replyContextFromSession } from './message/message-utils.js';
3
4
  import { logger } from '../utils/logger.js';
4
5
  import fs from 'fs';
5
6
  import { disposeAgentInstances } from './runner-reload-transaction.js';
6
7
  import { sessionTopicThreadId } from './thread/topic-id.js';
7
8
  import { StartupTracer } from '../utils/startup-trace.js';
9
+ import { OFFLINE_TOTAL_BUDGET_MS } from './lifecycle-notice.js';
10
+ import { monitorEventLoopDelay, performance } from 'node:perf_hooks';
11
+ import { setImmediate as yieldToIo } from 'node:timers/promises';
12
+ import path from 'node:path';
13
+ import { agentTriggersDir } from '../paths.js';
14
+ import { readLastJsonlLineAsync, scanAgentChatDirsAsync } from './session/session-fs-store.js';
15
+ import { fileToSession } from './session/session-mapper.js';
16
+ import { HandoffStore } from './handoff/store.js';
17
+ export class StartupGate {
18
+ outcome;
19
+ resolve;
20
+ timer;
21
+ promise = new Promise(resolve => { this.resolve = resolve; });
22
+ get status() { return this.outcome ?? 'pending'; }
23
+ settle(outcome) {
24
+ if (this.outcome)
25
+ return;
26
+ this.outcome = outcome;
27
+ if (this.timer)
28
+ clearTimeout(this.timer);
29
+ this.resolve(outcome);
30
+ }
31
+ releaseAfter(ms, onTimeout) {
32
+ if (this.outcome || this.timer)
33
+ return;
34
+ this.timer = setTimeout(() => { try {
35
+ onTimeout();
36
+ }
37
+ finally {
38
+ this.settle('timeout');
39
+ } }, ms);
40
+ this.timer.unref?.();
41
+ }
42
+ }
43
+ async function directories(root) {
44
+ try {
45
+ return (await fs.promises.readdir(root, { withFileTypes: true })).filter(entry => entry.isDirectory()).map(entry => entry.name);
46
+ }
47
+ catch (error) {
48
+ if (error.code === 'ENOENT')
49
+ return [];
50
+ throw error;
51
+ }
52
+ }
53
+ async function json(file) {
54
+ try {
55
+ return JSON.parse(await fs.promises.readFile(file, 'utf8'));
56
+ }
57
+ catch (error) {
58
+ if (error.code === 'ENOENT')
59
+ return undefined;
60
+ throw error;
61
+ }
62
+ }
63
+ export async function discoverStartupWork(options) {
64
+ const plan = {
65
+ priorityAids: new Set(), triggerAids: new Set(), requiredChannelKeys: new Set(),
66
+ requiredExternalAids: new Set(), pendingSessions: [], staleSessions: [], sessionScanFailed: false,
67
+ handoffSnapshots: new Map(),
68
+ };
69
+ const known = new Set(options.agentAids);
70
+ const uncertain = (aid, error) => {
71
+ if (known.has(aid)) {
72
+ plan.priorityAids.add(aid);
73
+ plan.requiredExternalAids.add(aid);
74
+ }
75
+ logger.warn(`[startup] Work classification uncertain for ${aid}; prioritizing recovery: ${error}`);
76
+ };
77
+ const noteMessage = (message, queueKey) => {
78
+ const aid = message?.selfAID || tryParseChannelKey(message?.channel || '')?.selfAID
79
+ || queueKey?.split('::')[0];
80
+ if (!known.has(aid)) {
81
+ for (const candidate of known)
82
+ uncertain(candidate, 'unresolved persisted input owner');
83
+ return;
84
+ }
85
+ plan.priorityAids.add(aid);
86
+ if (message?.channel)
87
+ plan.requiredChannelKeys.add(message.channel);
88
+ else
89
+ plan.requiredExternalAids.add(aid);
90
+ };
91
+ const queueStarted = Date.now();
92
+ let queueItems = 0;
93
+ let queueFiles = 0;
94
+ try {
95
+ const queue = await json(options.queuePath);
96
+ if (queue !== undefined) {
97
+ queueFiles = 1;
98
+ if (!queue || ![1, 2].includes(queue.version) || !Array.isArray(queue.queues)
99
+ || (queue.active !== undefined && !Array.isArray(queue.active)))
100
+ throw new Error('invalid queue snapshot');
101
+ for (const bucket of [...queue.queues, ...(queue.active ?? [])]) {
102
+ if (!Array.isArray(bucket.items))
103
+ throw new Error('invalid queue bucket');
104
+ for (const item of bucket.items) {
105
+ queueItems++;
106
+ noteMessage(item.message, bucket.queueKey);
107
+ for (const part of item.parts ?? [])
108
+ noteMessage(part.message, bucket.queueKey);
109
+ }
110
+ }
111
+ }
112
+ }
113
+ catch (error) {
114
+ for (const aid of known)
115
+ uncertain(aid, error);
116
+ }
117
+ finally {
118
+ options.onScan?.({ phase: 'queue', durationMs: Date.now() - queueStarted, files: queueFiles, items: queueItems });
119
+ options.onQueueCaptured?.();
120
+ }
121
+ const now = Date.now();
122
+ const triggerDir = options.triggerDir ?? agentTriggersDir;
123
+ const handoffStore = options.handoffStore ?? new HandoffStore();
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];
168
+ let next = 0;
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;
174
+ try {
175
+ const snapshots = await handoffStore.listAsync(aid);
176
+ files = snapshots.length;
177
+ plan.handoffSnapshots.set(aid, snapshots);
178
+ if (snapshots.some(needsHandoffRecovery))
179
+ plan.priorityAids.add(aid);
180
+ }
181
+ catch (error) {
182
+ uncertain(aid, error);
183
+ }
184
+ options.onScan?.({ phase: 'handoff', aid, durationMs: Date.now() - started, files });
185
+ started = Date.now();
186
+ files = 0;
187
+ let chats = 0;
188
+ try {
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');
194
+ try {
195
+ dirs.push({ dirPath, names: await fs.promises.readdir(dirPath) });
196
+ }
197
+ catch (error) {
198
+ if (error.code !== 'ENOENT')
199
+ throw error;
200
+ }
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);
215
+ if (!session.processingState)
216
+ continue;
217
+ const startedAt = Number.parseInt(session.processingState.split(':', 1)[0], 10);
218
+ if (Number.isFinite(startedAt) && now - startedAt < 3_600_000) {
219
+ plan.pendingSessions.push(session);
220
+ plan.priorityAids.add(aid);
221
+ plan.requiredChannelKeys.add(session.channel);
222
+ }
223
+ else
224
+ plan.staleSessions.push(session);
225
+ }
226
+ }
227
+ }
228
+ }
229
+ }
230
+ catch (error) {
231
+ plan.sessionScanFailed = true;
232
+ uncertain(aid, error);
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);
242
+ }
243
+ })]);
244
+ return plan;
245
+ }
246
+ /** Bounded admission for startup side effects. Dependency waits belong outside this queue. */
247
+ export class StartupTaskQueue {
248
+ concurrency;
249
+ intervalMs;
250
+ backgroundConcurrency;
251
+ pending = [];
252
+ active = 0;
253
+ activeBackground = 0;
254
+ stopped = false;
255
+ timer;
256
+ constructor(concurrency = 2, intervalMs = 50, backgroundConcurrency = concurrency) {
257
+ this.concurrency = concurrency;
258
+ this.intervalMs = intervalMs;
259
+ this.backgroundConcurrency = backgroundConcurrency;
260
+ if (!Number.isInteger(concurrency) || concurrency < 1 || !Number.isFinite(intervalMs) || intervalMs < 0
261
+ || !Number.isInteger(backgroundConcurrency) || backgroundConcurrency < 1 || backgroundConcurrency > concurrency) {
262
+ throw new Error('Invalid startup task queue limits');
263
+ }
264
+ }
265
+ run(run, valid = () => true, priority = 'foreground') {
266
+ if (this.stopped)
267
+ return Promise.resolve(false);
268
+ const result = new Promise((resolve, reject) => {
269
+ this.pending.push({ run, valid, resolve, reject, priority });
270
+ });
271
+ this.schedule();
272
+ return result;
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
+ }
279
+ stop() {
280
+ this.stopped = true;
281
+ if (this.timer)
282
+ clearTimeout(this.timer);
283
+ this.timer = undefined;
284
+ for (const task of this.pending.splice(0))
285
+ task.resolve(false);
286
+ }
287
+ schedule() {
288
+ if (this.stopped || this.timer || this.active >= this.concurrency || !this.pending.length)
289
+ return;
290
+ if (this.activeBackground >= this.backgroundConcurrency
291
+ && !this.pending.some(task => task.priority === 'foreground'))
292
+ return;
293
+ // Yield between admissions even when tasks finish synchronously.
294
+ this.timer = setTimeout(() => {
295
+ this.timer = undefined;
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];
302
+ if (!task)
303
+ return;
304
+ this.active++;
305
+ if (task.priority === 'background')
306
+ this.activeBackground++;
307
+ void Promise.resolve().then(async () => {
308
+ if (this.stopped || !task.valid())
309
+ return false;
310
+ await task.run();
311
+ return true;
312
+ }).then(task.resolve, task.reject).finally(() => {
313
+ this.active--;
314
+ if (task.priority === 'background')
315
+ this.activeBackground--;
316
+ this.schedule();
317
+ });
318
+ this.schedule();
319
+ }, this.intervalMs);
320
+ }
321
+ }
322
+ /** Observe startup task admission without delaying IPC or background services. */
323
+ export function startupTaskReadiness(state) {
324
+ if (state.agents.some(agent => agent.runnerFailed))
325
+ return 'failed';
326
+ return state.ipcReady && state.controlAunReady && state.agents.every(agent => agent.runnerReady && agent.aunReady && agent.recoveryReady && agent.authorizationReady)
327
+ ? 'ready' : 'pending';
328
+ }
329
+ /**
330
+ * Await `promise`, but never longer than `ms`. Swallows rejection the same way the
331
+ * caller's best-effort sends do: a failed notice must not fail the shutdown.
332
+ */
333
+ async function withDeadline(promise, ms) {
334
+ if (!promise)
335
+ return;
336
+ let timer;
337
+ try {
338
+ await Promise.race([
339
+ promise.then(() => undefined, () => undefined),
340
+ new Promise(resolve => { timer = setTimeout(resolve, ms); timer.unref?.(); }),
341
+ ]);
342
+ }
343
+ finally {
344
+ if (timer)
345
+ clearTimeout(timer);
346
+ }
347
+ }
8
348
  export function daemonIdleTimeoutMs(settings) {
9
349
  const idleTimeoutSec = settings.idleMonitor?.timeout;
10
350
  return typeof idleTimeoutSec === 'number' && Number.isFinite(idleTimeoutSec) && idleTimeoutSec > 0
@@ -21,37 +361,63 @@ export function daemonConversationTotalExecutionMs(settings) {
21
361
  ? seconds * 1000
22
362
  : undefined;
23
363
  }
24
- export async function cleanupStartupHandoffs(recoveryAids, handoffRuntime) {
25
- // 各 AID 的 handoff 目录互相独立,discard 走 per-target 互斥锁,
26
- // 因此可以并发;串行执行只会把 21 个 AID 的启动清理时间叠加起来。
27
- await Promise.all(recoveryAids.map(async (aid) => {
28
- try {
29
- const discarded = await handoffRuntime.discardExpired([aid]);
30
- if (discarded > 0)
31
- logger.info(`[Handoff] discarded ${discarded} expired handoff(s) for ${aid}`);
32
- const expired = handoffRuntime.expireQueued([aid]);
33
- if (expired > 0)
34
- logger.info(`[Handoff] expired ${expired} stale queued delivery item(s) for ${aid}`);
35
- }
36
- catch (error) {
37
- logger.error(`[Handoff] startup TTL cleanup failed for ${aid}:`, error);
38
- }
39
- }));
40
- }
41
- export async function recoverStartupHandoffs({ channelInstances, recoveryAids, agentRegistry, queuePendingObserverHints, startupObserverRecoveries, handoffRuntime, setStartupRecoveryPending, onStartupHintsRecovered, }) {
364
+ export async function recoverStartupHandoffs({ channelInstances, recoveryAids, agentRegistry, queuePendingObserverHints, startupObserverRecoveries, handoffRuntime, cleanupAgentHandoffs, trace, setStartupRecoveryPending, onStartupHintsRecovered, onAgentHintsRecovered, beforeAgentRecovery, waitForNormalReady, isCancelled, }) {
365
+ const terminalAudits = new Map();
366
+ const loopDelay = monitorEventLoopDelay({ resolution: 20 });
367
+ const utilizationStart = performance.eventLoopUtilization();
368
+ loopDelay.enable();
42
369
  try {
43
- for (const inst of channelInstances) {
44
- if (inst.channelType !== 'aun')
45
- continue;
46
- const agent = agentRegistry.resolveByChannel(inst.adapter.channelKey);
47
- if (agent && recoveryAids.includes(agent.aid)) {
48
- startupObserverRecoveries.push(...queuePendingObserverHints(agent.aid, inst.adapter.channelKey));
49
- }
50
- }
370
+ // Registration is local and scoped to each Agent. Never wait for all transports.
51
371
  await Promise.all(startupObserverRecoveries);
52
- // cleanupStartupHandoffs 已经对同一批 AID 做过 TTL 清理,这里不要再重扫一遍
53
- // 事件流与快照目录:recover 默认会再跑一次 discardExpired,等于把整段 I/O 翻倍。
54
- const outcomes = await Promise.allSettled(recoveryAids.map(aid => handoffRuntime.recover([aid], { discardExpired: false })));
372
+ const outcomes = await Promise.allSettled(recoveryAids.map(async (aid) => {
373
+ // Cleanup only gates this Agent; another Agent's history must not hold
374
+ // its restored input behind a global cleanup barrier.
375
+ await beforeAgentRecovery?.(aid);
376
+ if (isCancelled?.())
377
+ return;
378
+ while (!isCancelled?.()) {
379
+ const agentStarted = Date.now();
380
+ try {
381
+ const options = {
382
+ isCancelled,
383
+ onPhase: (phase, start, end, detail, status) => trace?.addSpan(`daemon.handoffRecovery.${phase}`, start, end, detail ? `${aid}; ${detail}` : aid, status),
384
+ };
385
+ const snapshots = await cleanupAgentHandoffs?.(aid, options);
386
+ if (isCancelled?.())
387
+ return;
388
+ const hintsStarted = Date.now();
389
+ const hints = channelInstances
390
+ .filter(inst => inst.channelType === 'aun'
391
+ && agentRegistry.resolveByChannel(inst.adapter.channelKey)?.aid === aid)
392
+ .map(inst => queuePendingObserverHints(aid, inst.adapter.channelKey));
393
+ const results = await Promise.allSettled(hints);
394
+ const failure = results.find(result => result.status === 'rejected');
395
+ trace?.addSpan('daemon.handoffRecovery.hints', hintsStarted, Date.now(), failure ? `${aid}; retry pending` : aid, failure ? undefined : 'ok');
396
+ if (failure?.status === 'rejected')
397
+ throw failure.reason;
398
+ if (isCancelled?.())
399
+ return;
400
+ // recover persists local origin inputs; remote sends use the dispatcher.
401
+ await handoffRuntime.recover([aid], { ...options, discardExpired: false,
402
+ ...(snapshots ? { snapshots: snapshots.filter(needsHandoffRecovery) } : {}) });
403
+ trace?.addSpan('daemon.handoffRecovery.agent', agentStarted, Date.now(), aid, isCancelled?.() ? 'cancelled' : 'ok');
404
+ if (!isCancelled?.()) {
405
+ const terminal = snapshots?.filter(snapshot => !needsHandoffRecovery(snapshot));
406
+ if (terminal?.length)
407
+ terminalAudits.set(aid, terminal);
408
+ onAgentHintsRecovered?.(aid);
409
+ }
410
+ return;
411
+ }
412
+ catch (error) {
413
+ // This attempt will be retried. A failed span would permanently
414
+ // mark the whole startup failed even after a successful recovery.
415
+ trace?.addSpan('daemon.handoffRecovery.agent', agentStarted, Date.now(), `${aid}; retry pending`);
416
+ logger.warn(`[Handoff] startup registration waits for ${aid}: ${error}`);
417
+ await new Promise(resolve => { const timer = setTimeout(resolve, 1_000); timer.unref?.(); });
418
+ }
419
+ }
420
+ }));
55
421
  outcomes.forEach((outcome, index) => {
56
422
  if (outcome.status === 'rejected') {
57
423
  logger.error(`[Handoff] startup recovery failed for ${recoveryAids[index]}:`, outcome.reason);
@@ -59,47 +425,56 @@ export async function recoverStartupHandoffs({ channelInstances, recoveryAids, a
59
425
  });
60
426
  }
61
427
  finally {
62
- // 这里只关掉"启动恢复还在等"的标志,不再顺带放行队列:
63
- // 渠道可能永远不会全连上,放行改由 releaseRestoredQueue 的超时兜底负责。
428
+ loopDelay.disable();
429
+ const utilization = performance.eventLoopUtilization(utilizationStart);
430
+ const diagnostics = { loopMaxMs: Math.round(loopDelay.max / 1e6),
431
+ loopP99Ms: Math.round(loopDelay.percentile(99) / 1e6),
432
+ loopActiveMs: Math.round(utilization.active), loopIdleMs: Math.round(utilization.idle) };
433
+ for (const [key, value] of Object.entries(diagnostics))
434
+ trace?.setMeta?.(`handoffRecovery.${key}`, String(value));
435
+ logger.info(`[Handoff] startup scheduling: ${Object.entries(diagnostics).map(([key, value]) => `${key}=${value}`).join(' ')}`);
436
+ // Individual failed Agents remain blocked; completion does not manufacture readiness.
64
437
  setStartupRecoveryPending(false);
65
- // hint 恢复可能抛错,但队列放行不能因此永远等下去——失败也视为已恢复完。
66
438
  onStartupHintsRecovered?.();
67
439
  startupObserverRecoveries.length = 0;
68
440
  }
69
- }
70
- /** 恢复队列放行的兜底时限:与 CLI 等待 ready 的 30s 对齐。 */
71
- export const RESTORE_QUEUE_TIMEOUT_MS = 30_000;
72
- /**
73
- * 放行启动时从磁盘读回的消息队列。
74
- *
75
- * 正常情况下等渠道首连结束再放行(此时发送侧大概率可用);但 `connectAll` 对总时长
76
- * 没有任何上限,一条通道卡在握手/认证退避里就会让重启前的消息永远躺在内存里——
77
- * 没有日志、不报错,表现为"重启后老消息没回音、新消息正常"。
78
- *
79
- * 所以这里加兜底:超时就先放行,最坏结果是某个 session 的一轮回复走发送侧排队重试,
80
- * 好过整批消息静默卡死。超时必须打日志,否则等于把"静默卡死"换成"静默提前放行"。
81
- */
82
- export async function releaseRestoredQueue({ channelConnectSettled, pendingCount, startRestoredQueue, timeoutMs = RESTORE_QUEUE_TIMEOUT_MS, }) {
83
- const pending = pendingCount();
84
- if (pending === 0) {
85
- startRestoredQueue();
441
+ // Start only after every Agent's foreground registration has settled. Audit
442
+ // failures retry independently and never hold restored input or normal Ready.
443
+ if (!terminalAudits.size || isCancelled?.())
86
444
  return;
87
- }
88
- let timedOut = false;
89
- const timer = new Promise(resolve => {
90
- const handle = setTimeout(() => { timedOut = true; resolve(); }, timeoutMs);
91
- // 不等它:渠道先连上时不应挂住事件循环到超时。
92
- if (typeof handle.unref === 'function')
93
- handle.unref();
94
- });
95
- await Promise.race([channelConnectSettled.catch(() => undefined), timer]);
96
- if (timedOut) {
97
- logger.warn(`[Queue] Channel connect still pending after ${Math.round(timeoutMs / 1000)}s; releasing ${pending} restored message(s) anyway`);
98
- }
99
- startRestoredQueue();
445
+ const finishAudit = trace?.startTask?.('daemon.handoffTerminalAuditComplete');
446
+ let auditSkipped = false;
447
+ void (async () => {
448
+ if (waitForNormalReady && !await waitForNormalReady()) {
449
+ auditSkipped = true;
450
+ return;
451
+ }
452
+ if (isCancelled?.())
453
+ return;
454
+ await yieldToIo();
455
+ while (terminalAudits.size && !isCancelled?.()) {
456
+ for (const [aid, snapshots] of terminalAudits) {
457
+ if (isCancelled?.())
458
+ break;
459
+ const started = Date.now();
460
+ try {
461
+ await handoffRuntime.recover([aid], { snapshots, discardExpired: false, isCancelled,
462
+ onPhase: (phase, start, end, detail, status) => trace?.addSpan(`daemon.handoffTerminalAudit.${phase}`, start, end, detail ? `${aid}; ${detail}` : aid, status) });
463
+ trace?.addSpan('daemon.handoffTerminalAudit.agent', started, Date.now(), aid, isCancelled?.() ? 'cancelled' : 'ok');
464
+ terminalAudits.delete(aid);
465
+ }
466
+ catch (error) {
467
+ logger.warn(`[Handoff] terminal audit retry pending for ${aid}: ${error}`);
468
+ }
469
+ }
470
+ if (terminalAudits.size && !isCancelled?.()) {
471
+ await new Promise(resolve => { const timer = setTimeout(resolve, 1_000); timer.unref?.(); });
472
+ }
473
+ }
474
+ })().catch(error => logger.warn(`[Handoff] terminal audit failed: ${error}`))
475
+ .finally(() => finishAudit?.(isCancelled?.() ? 'cancelled' : auditSkipped ? 'skipped' : 'ok'));
100
476
  }
101
- export function resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap, }) {
102
- const pendingSessions = sessionManager.getPendingProcessingSessions();
477
+ export function resumePendingSessions({ sessionManager, messageQueue, droppedTriggerSessionIds, agentRegistry, agentMap, pendingSessions = sessionManager.getPendingProcessingSessions(), }) {
103
478
  if (pendingSessions.length === 0)
104
479
  return;
105
480
  logger.info(`[Resume] Found ${pendingSessions.length} pending session(s) from before restart`);
@@ -166,7 +541,7 @@ export function resumePendingSessions({ sessionManager, messageQueue, droppedTri
166
541
  });
167
542
  }
168
543
  }
169
- export function createDaemonShutdown({ disposePluginResources, lifecycleNotices, 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, }) {
170
545
  let shutdownSignal = 'unknown';
171
546
  let shutdownInProgress = false;
172
547
  return async (signal, traceId) => {
@@ -181,9 +556,35 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
181
556
  lifecycleNotices?.beginShutdown();
182
557
  }
183
558
  catch { }
184
- // 下线提示是 best-effort:发起后不等待,退出流程照常继续。
559
+ // 下线提示是 best-effort:sendOffline 自带总预算(offlineTotalMs),等它不会拖住退出。
185
560
  // 注意必须在这里触发——后面 daemon.channels 会断开 AUN 连接。
186
- void lifecycleNotices?.sendOffline(shutdownSignal)?.catch(() => { });
561
+ //
562
+ // 必须 await,不能 fire-and-forget:出站准入要读 Ownership 共识,而准入现在是
563
+ // 异步的(发送前 await ownerResolver.refresh)。若不等它,stopOwnership 会在准入
564
+ // 恢复执行前清空 resolver,snapshot() 重建空 subject 后一律判 unavailable,
565
+ // 下线通知就会被 CONTACT_DENIED 拦下。
566
+ try {
567
+ await withDeadline(lifecycleNotices?.sendOffline(shutdownSignal), OFFLINE_TOTAL_BUDGET_MS);
568
+ }
569
+ catch (error) {
570
+ // A synchronous throw must not abort the exit; the notice is best-effort.
571
+ logger.warn(`[Shutdown] offline notice failed: ${error instanceof Error ? error.message : String(error)}`);
572
+ }
573
+ // Detaching ownership emits invalidations. Stop listeners first so those
574
+ // invalidations cannot enqueue refreshes against a resolver being destroyed.
575
+ for (const channel of [...channelInstances.map(instance => instance.channel), controlChannel]) {
576
+ try {
577
+ channel?.prepareShutdown?.();
578
+ }
579
+ catch (error) {
580
+ logger.warn(`[Shutdown] channel quiesce failed: ${error}`);
581
+ }
582
+ }
583
+ // resolver 只在通知发完之后释放,绝不挂在信号回调里抢先清空。
584
+ try {
585
+ stopOwnership?.();
586
+ }
587
+ catch { }
187
588
  const pid = process.pid;
188
589
  const ppid = process.ppid;
189
590
  logger.info(`\n\nShutting down gracefully... (signal=${shutdownSignal}, pid=${pid}, ppid=${ppid})`);
@@ -233,19 +634,21 @@ export function createDaemonShutdown({ disposePluginResources, lifecycleNotices,
233
634
  });
234
635
  });
235
636
  try {
236
- const queueShutdown = messageQueue.shutdownGracefully();
237
- await shutdownStep('daemon.stopPermissions', 'cancel pending permissions', () => permissionGateway.cancelAllPending('daemon_restart'));
238
- // 这两步各带超时(5s / 6.5s),退出慢的头号嫌疑就是它们空等到超时。
239
- await shutdownStep('daemon.triggerIdle', 'wait for trigger schedulers', async () => {
240
- await triggerSchedulers.waitForIdle(5_000);
241
- });
242
- 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 () => {
243
641
  await triggerSchedulers.suspendForDaemonExit();
244
642
  });
245
- 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]);
246
648
  await shutdownStep('daemon.agentRunners', 'dispose agent runners', async () => {
247
649
  if (startupRunners)
248
650
  await Promise.allSettled([startupRunners]);
651
+ await waitForRunnerLoads?.();
249
652
  const currentInstances = [...agentMap.entries()].map(([key, agent]) => {
250
653
  const split = key.lastIndexOf('::');
251
654
  return {
@@ -81,15 +81,21 @@ export class HandoffDispatcher {
81
81
  this.running.delete(key);
82
82
  }
83
83
  }
84
- expireQueued(selfAid, targetSessionId) {
84
+ expireQueued(selfAid, targetSessionId, candidates) {
85
85
  if (this.queueTtlMs === undefined)
86
86
  return [];
87
87
  const now = this.now();
88
88
  const expired = [];
89
- const queued = targetSessionId
89
+ const queued = candidates ? candidates.filter(instance => instance.state === 'queued') : targetSessionId
90
90
  ? this.store.listByTarget(selfAid, targetSessionId, 'queued')
91
91
  : this.store.list(selfAid).filter(instance => instance.state === 'queued');
92
- for (const instance of queued) {
92
+ for (const snapshot of queued) {
93
+ // created_at is immutable; young candidates need no second disk read.
94
+ if (now - snapshot.created_at < this.queueTtlMs)
95
+ continue;
96
+ const instance = this.store.get(selfAid, snapshot.handoff_id);
97
+ if (!instance || instance.state !== 'queued')
98
+ continue;
93
99
  if (now - instance.created_at < this.queueTtlMs)
94
100
  continue;
95
101
  expired.push(this.store.recordSendExpired(selfAid, instance.handoff_id, this.queueTtlMs, now));