@cortex-agent/server 2026.9.15 → 2026.9.25

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 (297) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/config/thread-templates/agents/creative.json +17 -0
  6. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  7. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  8. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  9. package/defaults/hooks/new-session-hook.mjs +2 -2
  10. package/defaults/hooks/rules-loader.mjs +2 -2
  11. package/defaults/hooks/status-md-guard.mjs +8 -8
  12. package/defaults/hooks/task-status-check.mjs +18 -76
  13. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  14. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  15. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  16. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  17. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  18. package/defaults/prompts/systemPrompts/creative.md +13 -0
  19. package/defaults/prompts/systemPrompts/direct.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  25. package/dist/agent-adapter/claude/adapter.js +19 -1
  26. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  27. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  28. package/dist/agent-adapter/claude/spawn-args.js +14 -0
  29. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  30. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  31. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  32. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  33. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  34. package/dist/agent-adapter/pi/child-runner.js +5 -1
  35. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  36. package/dist/agent-adapter/pi/event-parser.js +46 -2
  37. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  38. package/dist/agent-adapter/pi/extensions.js +10 -3
  39. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  40. package/dist/agent-adapter/pi/pi-session.js +5 -0
  41. package/dist/agent-adapter/pi/runtime.js +3 -0
  42. package/dist/agent-adapter/pi/session-options.js +5 -1
  43. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  44. package/dist/agent-adapter/pi/subagent.js +18 -0
  45. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  46. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  47. package/dist/agent-adapter/types.d.ts +6 -0
  48. package/dist/core/agents/subagent/types.d.ts +3 -0
  49. package/dist/core/config-generator.js +17 -2
  50. package/dist/core/debug-mode.d.ts +11 -10
  51. package/dist/core/debug-mode.js +12 -18
  52. package/dist/core/exec-async.d.ts +26 -0
  53. package/dist/core/exec-async.js +47 -0
  54. package/dist/core/locales/en.d.ts +14 -1
  55. package/dist/core/locales/slices/commands.d.ts +12 -1
  56. package/dist/core/locales/slices/commands.js +24 -2
  57. package/dist/core/locales/slices/startup.d.ts +2 -0
  58. package/dist/core/locales/slices/startup.js +4 -0
  59. package/dist/core/mcp-tool-gate.js +1 -0
  60. package/dist/core/media-types.d.ts +10 -0
  61. package/dist/core/media-types.js +34 -0
  62. package/dist/core/platform-settings-spec.js +1 -1
  63. package/dist/core/rebuild-progress.d.ts +58 -0
  64. package/dist/core/rebuild-progress.js +103 -0
  65. package/dist/core/resilient-watch.js +5 -3
  66. package/dist/core/run-registry.d.ts +7 -0
  67. package/dist/core/run-registry.js +6 -0
  68. package/dist/core/settings-spec.d.ts +21 -0
  69. package/dist/core/settings-spec.js +28 -1
  70. package/dist/core/types/agent-types.d.ts +3 -1
  71. package/dist/core/types/thread-types.d.ts +23 -4
  72. package/dist/core/utils.d.ts +1 -1
  73. package/dist/core/utils.js +1 -1
  74. package/dist/domain/agents/agent-state.d.ts +7 -0
  75. package/dist/domain/agents/agent-state.js +9 -1
  76. package/dist/domain/agents/agent-switch.d.ts +38 -0
  77. package/dist/domain/agents/agent-switch.js +106 -0
  78. package/dist/domain/agents/config.d.ts +20 -2
  79. package/dist/domain/agents/config.js +58 -4
  80. package/dist/domain/agents/index.d.ts +1 -0
  81. package/dist/domain/agents/index.js +1 -0
  82. package/dist/domain/agents/profile-manager.d.ts +6 -0
  83. package/dist/domain/agents/profile-manager.js +14 -1
  84. package/dist/domain/executions/registry.d.ts +3 -2
  85. package/dist/domain/executions/registry.js +84 -10
  86. package/dist/domain/mcp/bundled-server.js +4 -3
  87. package/dist/domain/mcp/feishu/file.js +37 -18
  88. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  89. package/dist/domain/mcp/feishu-server.js +1 -1
  90. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  91. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  92. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  93. package/dist/domain/mcp/tools/remote-file.js +44 -0
  94. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  95. package/dist/domain/mcp/tools/slack.js +22 -7
  96. package/dist/domain/mcp/tools/task-ops.js +5 -13
  97. package/dist/domain/mcp/tools/ui-file.js +23 -10
  98. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  99. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  100. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  101. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  102. package/dist/domain/plugins/runtime.js +1 -1
  103. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  104. package/dist/domain/plugins/skill-projection.js +76 -19
  105. package/dist/domain/projects/project-store.d.ts +1 -1
  106. package/dist/domain/projects/project-store.js +3 -3
  107. package/dist/domain/remote/client-bootstrap.js +1 -1
  108. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  109. package/dist/domain/remote/client-hot-reload.js +30 -24
  110. package/dist/domain/remote/client-manager.js +39 -119
  111. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  112. package/dist/domain/remote/cortex-client-config.js +1 -1
  113. package/dist/domain/remote/device-file.d.ts +51 -0
  114. package/dist/domain/remote/device-file.js +193 -0
  115. package/dist/domain/remote/device-port.js +3 -0
  116. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  117. package/dist/domain/remote/reverse-stream.js +19 -6
  118. package/dist/domain/runs/engine-spec.js +4 -0
  119. package/dist/domain/runs/request.d.ts +6 -0
  120. package/dist/domain/runs/run.js +1 -0
  121. package/dist/domain/runs/spec-loader.d.ts +4 -3
  122. package/dist/domain/runs/spec-loader.js +4 -3
  123. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  124. package/dist/domain/scheduling/scheduler.js +14 -12
  125. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  126. package/dist/domain/sessions/session-lifecycle.js +13 -1
  127. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  128. package/dist/domain/system/rebuild-hold.js +91 -0
  129. package/dist/domain/system/server-update-check.d.ts +2 -1
  130. package/dist/domain/system/server-update-check.js +15 -13
  131. package/dist/domain/tasks/archiver.js +21 -13
  132. package/dist/domain/tasks/claim-recovery.js +2 -2
  133. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  134. package/dist/domain/tasks/dispatch-utils.js +46 -1
  135. package/dist/domain/tasks/dispatcher.js +4 -5
  136. package/dist/domain/tasks/mutator.d.ts +2 -2
  137. package/dist/domain/tasks/mutator.js +62 -61
  138. package/dist/domain/tasks/system/task-cli.js +2 -2
  139. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  140. package/dist/domain/tasks/system/task-completion.js +69 -6
  141. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  142. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  143. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  144. package/dist/domain/tasks/system/task-lock.js +29 -1
  145. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  146. package/dist/domain/tasks/system/task-mutations.js +25 -2
  147. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  148. package/dist/domain/tasks/system/task-state.js +20 -3
  149. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  150. package/dist/domain/threads/prompt-builder.js +28 -10
  151. package/dist/domain/threads/runner.js +10 -4
  152. package/dist/domain/threads/state-machine.js +15 -11
  153. package/dist/domain/threads/template-loader.js +6 -4
  154. package/dist/domain/threads/template-validate.d.ts +43 -6
  155. package/dist/domain/threads/template-validate.js +12 -0
  156. package/dist/domain/ui-service/app-router.d.ts +34 -3
  157. package/dist/domain/ui-service/app-router.js +9 -14
  158. package/dist/domain/ui-service/input-schemas.d.ts +28 -5
  159. package/dist/domain/ui-service/input-schemas.js +24 -9
  160. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  161. package/dist/domain/ui-service/mutate/sessions.d.ts +6 -1
  162. package/dist/domain/ui-service/mutate/sessions.js +54 -0
  163. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  164. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  165. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  166. package/dist/domain/ui-service/platform-settings.js +1 -1
  167. package/dist/domain/ui-service/plugins-shared.js +1 -1
  168. package/dist/domain/ui-service/query/config.js +20 -2
  169. package/dist/domain/ui-service/query/executions.js +0 -2
  170. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  171. package/dist/domain/ui-service/query/memory.js +29 -35
  172. package/dist/domain/ui-service/query/sessions.js +96 -12
  173. package/dist/domain/ui-service/query/system.js +19 -0
  174. package/dist/domain/ui-service/query/threads.js +1 -54
  175. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  176. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  177. package/dist/domain/ui-service/query-input-schemas.d.ts +4 -0
  178. package/dist/domain/ui-service/query-input-schemas.js +5 -0
  179. package/dist/domain/ui-service/trpc.js +1 -1
  180. package/dist/domain/ui-service/types.d.ts +229 -51
  181. package/dist/domain/ui-service/types.js +1 -1
  182. package/dist/domain/ui-service/ui-service.js +8 -31
  183. package/dist/domain/waitpoints/notices.d.ts +21 -0
  184. package/dist/domain/waitpoints/notices.js +115 -0
  185. package/dist/domain/waitpoints/service.d.ts +91 -0
  186. package/dist/domain/waitpoints/service.js +243 -0
  187. package/dist/entry/app.js +52 -11
  188. package/dist/entry/auth-login-cli.js +1 -1
  189. package/dist/entry/auth-login-terminal.js +1 -1
  190. package/dist/entry/daemon-notice.d.ts +10 -1
  191. package/dist/entry/daemon-notice.js +16 -1
  192. package/dist/entry/daemon.d.ts +43 -2
  193. package/dist/entry/daemon.js +163 -9
  194. package/dist/entry/init-auth.js +1 -1
  195. package/dist/entry/init.js +6 -6
  196. package/dist/entry/signal-cli.d.ts +30 -0
  197. package/dist/entry/signal-cli.js +207 -0
  198. package/dist/entry/start-ui-http.d.ts +1 -1
  199. package/dist/entry/start-ui-http.js +2 -2
  200. package/dist/events/event-types.d.ts +0 -7
  201. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  202. package/dist/hooks/cortex-hook-api.mjs +2 -2
  203. package/dist/hooks/new-session-hook.mjs +2 -2
  204. package/dist/hooks/rules-loader.mjs +2 -2
  205. package/dist/hooks/status-md-guard.mjs +8 -8
  206. package/dist/hooks/task-status-check.mjs +18 -76
  207. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  208. package/dist/orchestration/agent-file-send.d.ts +9 -0
  209. package/dist/orchestration/agent-file-send.js +21 -2
  210. package/dist/orchestration/agent-runner.d.ts +3 -2
  211. package/dist/orchestration/agent-runner.js +33 -12
  212. package/dist/orchestration/attachments-store.d.ts +31 -0
  213. package/dist/orchestration/attachments-store.js +184 -0
  214. package/dist/orchestration/conversation-request.d.ts +37 -0
  215. package/dist/orchestration/conversation-request.js +91 -22
  216. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  217. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  218. package/dist/orchestration/mid-turn-inject.js +9 -4
  219. package/dist/orchestration/outputs-store.d.ts +11 -0
  220. package/dist/orchestration/outputs-store.js +32 -6
  221. package/dist/orchestration/resume-dispatcher.js +4 -2
  222. package/dist/orchestration/routing/commands/mode.js +114 -63
  223. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  224. package/dist/orchestration/routing/file-handler.js +22 -5
  225. package/dist/orchestration/routing/webhook.js +193 -39
  226. package/dist/orchestration/session-gateway.d.ts +1 -1
  227. package/dist/orchestration/session-gateway.js +1 -0
  228. package/dist/orchestration/thread-executor.d.ts +2 -0
  229. package/dist/orchestration/thread-executor.js +24 -1
  230. package/dist/orchestration/thread-input.d.ts +3 -2
  231. package/dist/orchestration/thread-input.js +8 -9
  232. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  233. package/dist/orchestration/turn/turn-prep.js +19 -8
  234. package/dist/orchestration/turn/turn.js +1 -0
  235. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  236. package/dist/orchestration/waitpoint-ingress.js +172 -0
  237. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  238. package/dist/orchestration/waitpoint-notifier.js +119 -0
  239. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  240. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  241. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  242. package/dist/orchestration/waitpoint-sweep.js +87 -0
  243. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  244. package/dist/platform/adapters/feishu-image.js +71 -0
  245. package/dist/platform/adapters/feishu.d.ts +2 -0
  246. package/dist/platform/adapters/feishu.js +26 -16
  247. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  248. package/dist/platform/ui-http/listening-ports.js +1 -1
  249. package/dist/platform/ui-http/ui-session.js +1 -1
  250. package/dist/store/conversation-display-projection.d.ts +9 -1
  251. package/dist/store/conversation-display-projection.js +13 -6
  252. package/dist/store/conversation-history-reader.d.ts +19 -0
  253. package/dist/store/conversation-history-reader.js +163 -44
  254. package/dist/store/conversation-history-repo.d.ts +37 -10
  255. package/dist/store/conversation-history-repo.js +161 -139
  256. package/dist/store/conversation-ledger-repo.js +1 -1
  257. package/dist/store/execution-repo.d.ts +1 -19
  258. package/dist/store/execution-repo.js +1 -18
  259. package/dist/store/project-notes-repo.js +11 -2
  260. package/dist/store/prompt-migration-replacements.js +1 -1
  261. package/dist/store/session-registry-import.js +1 -1
  262. package/dist/store/session-registry-journal.d.ts +4 -0
  263. package/dist/store/session-registry-journal.js +5 -1
  264. package/dist/store/session-registry-repo.d.ts +2 -1
  265. package/dist/store/session-registry-repo.js +3 -1
  266. package/dist/store/task-repo.d.ts +6 -3
  267. package/dist/store/task-repo.js +26 -10
  268. package/dist/store/version-migrations.d.ts +13 -3
  269. package/dist/store/version-migrations.js +254 -24
  270. package/dist/store/waitpoint-repo.d.ts +108 -0
  271. package/dist/store/waitpoint-repo.js +94 -0
  272. package/package.json +3 -2
  273. package/web/dist/AGENTS.md +10 -0
  274. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  275. package/web/dist/assets/{index-CEZ0DSei.js → index-BAeLybF0.js} +1 -1
  276. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  277. package/web/dist/index.html +12 -4
  278. package/web/dist/theme.css +211 -40
  279. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  280. package/dist/domain/executions/log-tailer.d.ts +0 -71
  281. package/dist/domain/executions/log-tailer.js +0 -194
  282. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  283. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  284. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  285. package/dist/domain/remote/cortex-client.d.ts +0 -1
  286. package/dist/domain/remote/cortex-client.js +0 -662
  287. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  288. package/dist/domain/tasks/system/cortex-run.js +0 -360
  289. package/web/dist/assets/index-CRDJo39X.css +0 -1
  290. package/web/dist/assets/index-DjuPJVZE.js +0 -444
  291. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  292. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  293. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  294. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  295. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  296. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  297. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -0,0 +1,172 @@
1
+ // input: signal payloads (HTTP route, local spool files), waitpoint service
2
+ // output: ingestSignal / drainLocalSpool / recentSignalRejections / SIGNAL_SPOOL_DIR
3
+ // pos: The single door every external signal walks through, whatever carried it. Applies the
4
+ // signal to its waitpoint and, when that fires, hands it to the notifier. Lives in
5
+ // orchestration/ because it reaches the notifier; the state machine stays in domain/.
6
+ //
7
+ // Two properties this layer owns and the service does not:
8
+ // - anti-enumeration: unknown ids and bad secrets are rate-limited globally and recorded
9
+ // in a bounded dead-letter ring, so a typo in a training script is debuggable and a
10
+ // scan for live waitpoints is not free.
11
+ // - spool ingestion: a file dropped in the spool dir is equivalent to a POST, which is how
12
+ // a machine with no curl (or no route to the daemon) still reports.
13
+ import fs from 'node:fs/promises';
14
+ import path from 'node:path';
15
+ import { createLogger } from '../core/log.js';
16
+ import { WORKSPACE_DIR } from '../core/paths.js';
17
+ import { applySignal, productionWaitpointDeps, } from '../domain/waitpoints/service.js';
18
+ import { productionNotifierDeps, scheduleWaitpointDelivery, } from './waitpoint-notifier.js';
19
+ const log = createLogger('waitpoint-ingress');
20
+ /** Any process that can write a file can signal: drop `<anything>.json` here. */
21
+ export const SIGNAL_SPOOL_DIR = path.join(WORKSPACE_DIR, 'signals');
22
+ /** Files that could never be applied (unparseable, unknown id) are parked here, not deleted. */
23
+ export const SIGNAL_SPOOL_BAD_DIR = path.join(SIGNAL_SPOOL_DIR, 'bad');
24
+ /** A spool entry larger than this is refused outright — signals are summaries, not logs. */
25
+ export const SPOOL_FILE_MAX_BYTES = 64 * 1024;
26
+ const REJECTION_RING_MAX = 50;
27
+ const rejections = [];
28
+ /** Failed lookups allowed per minute across all callers, before every miss is refused unread. */
29
+ const MISS_BUDGET_PER_MINUTE = 60;
30
+ let missWindowStart = 0;
31
+ let missCount = 0;
32
+ function recordRejection(reason, id, source, now) {
33
+ rejections.push({ at: now, reason, id, source });
34
+ if (rejections.length > REJECTION_RING_MAX)
35
+ rejections.shift();
36
+ log.warn(`signal rejected (${reason}) for ${id || '(no id)'} from ${source}`);
37
+ }
38
+ /** Recent rejected signals, newest last. Diagnostic surface for "my script says 404". */
39
+ export function recentSignalRejections() {
40
+ return [...rejections];
41
+ }
42
+ /** Test hook. */
43
+ export function resetSignalIngressState() {
44
+ rejections.length = 0;
45
+ missWindowStart = 0;
46
+ missCount = 0;
47
+ }
48
+ function overMissBudget(now) {
49
+ if (now - missWindowStart > 60_000) {
50
+ missWindowStart = now;
51
+ missCount = 0;
52
+ }
53
+ missCount += 1;
54
+ return missCount > MISS_BUDGET_PER_MINUTE;
55
+ }
56
+ export const productionIngestDeps = {
57
+ service: productionWaitpointDeps,
58
+ notifier: productionNotifierDeps,
59
+ now: () => Date.now(),
60
+ };
61
+ /**
62
+ * Apply one signal and schedule the wake it earned.
63
+ *
64
+ * Returns the raw outcome; mapping it onto HTTP status codes is the route's job, because the spool
65
+ * path has no status codes to map onto.
66
+ */
67
+ export async function ingestSignal(input, deps = productionIngestDeps) {
68
+ const now = deps.now();
69
+ if (!input.id || typeof input.id !== 'string') {
70
+ recordRejection('not-found', String(input.id ?? ''), input.source, now);
71
+ return { kind: 'not-found' };
72
+ }
73
+ const outcome = await applySignal(input, deps.service);
74
+ if (outcome.kind === 'not-found' || outcome.kind === 'bad-secret') {
75
+ if (overMissBudget(now)) {
76
+ recordRejection('rate-limited', input.id, input.source, now);
77
+ return { kind: 'rate-limited' };
78
+ }
79
+ recordRejection(outcome.kind, input.id, input.source, now);
80
+ return outcome;
81
+ }
82
+ if (outcome.kind === 'accepted' && outcome.fired) {
83
+ scheduleWaitpointDelivery(outcome.waitpoint, deps.notifier);
84
+ }
85
+ return outcome;
86
+ }
87
+ async function readSpoolDir(dir, badDir) {
88
+ let names;
89
+ try {
90
+ names = await fs.readdir(dir);
91
+ }
92
+ catch {
93
+ return [];
94
+ }
95
+ const entries = [];
96
+ for (const name of names) {
97
+ if (!name.endsWith('.json'))
98
+ continue;
99
+ const full = path.join(dir, name);
100
+ try {
101
+ const stat = await fs.stat(full);
102
+ if (!stat.isFile())
103
+ continue;
104
+ if (stat.size > SPOOL_FILE_MAX_BYTES) {
105
+ await quarantine(full, name, badDir);
106
+ continue;
107
+ }
108
+ const parsed = JSON.parse(await fs.readFile(full, 'utf8'));
109
+ if (typeof parsed !== 'object' || parsed === null) {
110
+ await quarantine(full, name, badDir);
111
+ continue;
112
+ }
113
+ entries.push({ file: name, payload: parsed });
114
+ }
115
+ catch {
116
+ // A half-written file is normal: writers are told to write `.tmp` then rename, but a
117
+ // truncated or malformed one must not stall the whole batch. Park it and move on.
118
+ await quarantine(full, name, badDir);
119
+ }
120
+ }
121
+ return entries;
122
+ }
123
+ async function quarantine(fullPath, name, badDir) {
124
+ try {
125
+ await fs.mkdir(badDir, { recursive: true });
126
+ await fs.rename(fullPath, path.join(badDir, `${Date.now()}-${name}`));
127
+ log.warn(`spool entry ${name} is unusable; parked under signals/bad/`);
128
+ }
129
+ catch {
130
+ // Best effort — a file we cannot even move must not break the drain.
131
+ }
132
+ }
133
+ /**
134
+ * Apply every spool file on this machine and delete the ones that landed.
135
+ *
136
+ * A file is removed only after its signal was accepted or was already resolved; anything still
137
+ * addressable to a live waitpoint is left for the next tick. The filename doubles as the dedupe
138
+ * key, so re-reading a file whose delete was lost is harmless.
139
+ */
140
+ export async function drainLocalSpool(deps = productionIngestDeps, dir = SIGNAL_SPOOL_DIR) {
141
+ const badDir = path.join(dir, 'bad');
142
+ const entries = await readSpoolDir(dir, badDir);
143
+ let applied = 0;
144
+ for (const entry of entries) {
145
+ const outcome = await ingestSignal(toSignalInput(entry.payload, `spool:${entry.file}`, 'spool'), deps);
146
+ if (outcome.kind === 'not-found' || outcome.kind === 'bad-secret') {
147
+ await quarantine(path.join(dir, entry.file), entry.file, badDir);
148
+ continue;
149
+ }
150
+ if (outcome.kind === 'rate-limited')
151
+ continue;
152
+ await fs.unlink(path.join(dir, entry.file)).catch(() => { });
153
+ if (outcome.kind === 'accepted')
154
+ applied += 1;
155
+ }
156
+ return applied;
157
+ }
158
+ /** Normalise an untrusted payload (HTTP body or spool file) into a SignalInput. */
159
+ export function toSignalInput(payload, dedupeKey, source) {
160
+ return {
161
+ id: typeof payload.id === 'string' ? payload.id : '',
162
+ secret: typeof payload.secret === 'string' ? payload.secret : '',
163
+ status: payload.status === 'fail' || payload.status === 'progress' || payload.status === 'ok'
164
+ ? payload.status
165
+ : undefined,
166
+ message: typeof payload.message === 'string' ? payload.message : null,
167
+ data: payload.data ?? null,
168
+ member: typeof payload.member === 'string' ? payload.member : null,
169
+ source,
170
+ dedupeKey,
171
+ };
172
+ }
@@ -0,0 +1,21 @@
1
+ import { waitpointRepo, type Waitpoint } from '../store/waitpoint-repo.js';
2
+ export interface WaitpointNotifierDeps {
3
+ repo: Pick<typeof waitpointRepo, 'get' | 'list' | 'update'>;
4
+ deliver: (channel: string, text: string, tag: string) => Promise<void>;
5
+ now: () => number;
6
+ }
7
+ export declare const productionNotifierDeps: WaitpointNotifierDeps;
8
+ /**
9
+ * Arrange for a fired waitpoint to be delivered: immediately, or after its coalesce window so a
10
+ * burst of sibling signals (eight arms finishing at once) becomes one turn instead of eight.
11
+ */
12
+ export declare function scheduleWaitpointDelivery(wp: Waitpoint, deps?: WaitpointNotifierDeps): void;
13
+ /**
14
+ * Drain every waitpoint carrying an undelivered wake. Used at boot (a restart drops the in-memory
15
+ * coalesce timers) and on each sweep tick (retry after a delivery failure). Returns the count sent.
16
+ */
17
+ export declare function deliverPendingWaitpoints(deps?: WaitpointNotifierDeps): Promise<number>;
18
+ /** Mark freshly expired waitpoints for delivery so their owner learns nobody ever signalled. */
19
+ export declare function notifyWaitpointExpiry(expired: Waitpoint[], deps?: WaitpointNotifierDeps): Promise<void>;
20
+ /** Test hook: drop any armed coalesce timers. */
21
+ export declare function resetWaitpointTimers(): void;
@@ -0,0 +1,119 @@
1
+ // input: waitpoint repo records with delivery.pending set, session-gateway
2
+ // output: deliverPendingWaitpoints / scheduleWaitpointDelivery / notifyWaitpointExpiry
3
+ // pos: Turns a fired waitpoint into a wake turn. Lives in orchestration/ because it reaches
4
+ // session-gateway; the firing decision itself is domain/waitpoints/service.ts.
5
+ // Delivery is disk-driven: applySignal only sets `delivery.pending`, and every path here
6
+ // (immediate, coalesced, boot replay, sweep retry) drains that same bit, so a crash between
7
+ // firing and delivering costs at most one replay rather than the notice.
8
+ import { createLogger } from '../core/log.js';
9
+ import { waitpointRepo } from '../store/waitpoint-repo.js';
10
+ import { buildExpiryNotice, buildSignalNotice } from '../domain/waitpoints/notices.js';
11
+ import { deliverToSession } from './session-gateway.js';
12
+ const log = createLogger('waitpoint-notifier');
13
+ export const productionNotifierDeps = {
14
+ repo: waitpointRepo,
15
+ deliver: async (channel, text, tag) => {
16
+ await deliverToSession({ channel, text, origin: 'external-signal', tag });
17
+ },
18
+ now: () => Date.now(),
19
+ };
20
+ /** Coalesce timers, keyed by waitpoint id. In-memory only — a lost timer is recovered by the sweep. */
21
+ const pendingTimers = new Map();
22
+ /**
23
+ * Deliver one waitpoint's pending wake, if it still has one.
24
+ *
25
+ * Clears `delivery.pending` *before* sending: a duplicate wake is a wasted turn, while a dropped
26
+ * one is a silently lost notification, so the bit is restored on failure and the sweep retries.
27
+ */
28
+ async function deliverOne(id, deps) {
29
+ const claimed = await deps.repo.update(id, (wp) => {
30
+ if (!wp.delivery.pending)
31
+ return { next: wp, result: null };
32
+ wp.delivery.pending = false;
33
+ wp.delivery.attempts += 1;
34
+ wp.delivery.lastAt = deps.now();
35
+ return { next: wp, result: wp };
36
+ });
37
+ const wp = claimed ?? null;
38
+ if (!wp)
39
+ return false;
40
+ const now = deps.now();
41
+ const text = wp.state === 'expired'
42
+ ? buildExpiryNotice(wp, now)
43
+ : buildSignalNotice(wp, { signals: undeliveredSignals(wp), now, rateLimited: wp.rateLimitNotified === true });
44
+ try {
45
+ await deps.deliver(wp.owner.channel, text, wp.id);
46
+ await deps.repo.update(id, (current) => {
47
+ for (const signal of current.signals)
48
+ signal.deliveredAt = signal.deliveredAt ?? now;
49
+ current.delivery.lastError = null;
50
+ return { next: current, result: undefined };
51
+ });
52
+ log.info(`delivered ${wp.id} to ${wp.owner.channel}`);
53
+ return true;
54
+ }
55
+ catch (error) {
56
+ const message = error.message;
57
+ await deps.repo.update(id, (current) => {
58
+ current.delivery.pending = true;
59
+ current.delivery.lastError = message;
60
+ return { next: current, result: undefined };
61
+ });
62
+ log.error(`deliver ${wp.id} failed, will retry: ${message}`);
63
+ return false;
64
+ }
65
+ }
66
+ /** Signals not yet folded into a previous wake — what this notice is actually reporting. */
67
+ function undeliveredSignals(wp) {
68
+ const fresh = wp.signals.filter((s) => !s.deliveredAt);
69
+ return fresh.length > 0 ? fresh : wp.signals.slice(-1);
70
+ }
71
+ /**
72
+ * Arrange for a fired waitpoint to be delivered: immediately, or after its coalesce window so a
73
+ * burst of sibling signals (eight arms finishing at once) becomes one turn instead of eight.
74
+ */
75
+ export function scheduleWaitpointDelivery(wp, deps = productionNotifierDeps) {
76
+ if (wp.coalesceMs <= 0) {
77
+ void deliverOne(wp.id, deps).catch((e) => log.error(`deliver ${wp.id}: ${e.message}`));
78
+ return;
79
+ }
80
+ if (pendingTimers.has(wp.id))
81
+ return;
82
+ const timer = setTimeout(() => {
83
+ pendingTimers.delete(wp.id);
84
+ void deliverOne(wp.id, deps).catch((e) => log.error(`deliver ${wp.id}: ${e.message}`));
85
+ }, wp.coalesceMs);
86
+ timer.unref?.();
87
+ pendingTimers.set(wp.id, timer);
88
+ }
89
+ /**
90
+ * Drain every waitpoint carrying an undelivered wake. Used at boot (a restart drops the in-memory
91
+ * coalesce timers) and on each sweep tick (retry after a delivery failure). Returns the count sent.
92
+ */
93
+ export async function deliverPendingWaitpoints(deps = productionNotifierDeps) {
94
+ const all = await deps.repo.list();
95
+ let delivered = 0;
96
+ for (const wp of all) {
97
+ if (!wp.delivery.pending)
98
+ continue;
99
+ if (await deliverOne(wp.id, deps))
100
+ delivered += 1;
101
+ }
102
+ return delivered;
103
+ }
104
+ /** Mark freshly expired waitpoints for delivery so their owner learns nobody ever signalled. */
105
+ export async function notifyWaitpointExpiry(expired, deps = productionNotifierDeps) {
106
+ for (const wp of expired) {
107
+ await deps.repo.update(wp.id, (current) => {
108
+ current.delivery.pending = true;
109
+ return { next: current, result: undefined };
110
+ });
111
+ await deliverOne(wp.id, deps).catch((e) => log.error(`expiry notice ${wp.id}: ${e.message}`));
112
+ }
113
+ }
114
+ /** Test hook: drop any armed coalesce timers. */
115
+ export function resetWaitpointTimers() {
116
+ for (const timer of pendingTimers.values())
117
+ clearTimeout(timer);
118
+ pendingTimers.clear();
119
+ }
@@ -0,0 +1,20 @@
1
+ import { type IngestDeps } from './waitpoint-ingress.js';
2
+ export interface RemoteDrainDeps {
3
+ ingest: IngestDeps;
4
+ listDeviceTargets: () => Promise<string[]>;
5
+ isDeviceOnline: (device: string) => boolean;
6
+ runBash: (device: string, command: string, timeoutMs: number) => Promise<{
7
+ stdout: string;
8
+ }>;
9
+ }
10
+ export declare const productionRemoteDrainDeps: RemoteDrainDeps;
11
+ /** Split the read command's output back into `{ name, body }` pairs. */
12
+ export declare function parseSpoolBatch(stdout: string): Array<{
13
+ name: string;
14
+ body: string;
15
+ }>;
16
+ /**
17
+ * Visit every device that owns at least one armed waitpoint and collect what it left for us.
18
+ * Offline devices are skipped silently — their files keep until they reconnect.
19
+ */
20
+ export declare function drainDeviceSpools(deps?: RemoteDrainDeps): Promise<number>;
@@ -0,0 +1,147 @@
1
+ // input: armed waitpoints whose emitFrom names a device, client-manager's command channel
2
+ // output: drainDeviceSpools
3
+ // pos: Collects signals from connected devices. A job on a lab box cannot POST to the daemon —
4
+ // the webhook listens on loopback only — so the daemon goes and fetches instead, over the
5
+ // WebSocket the device already holds open.
6
+ //
7
+ // Nothing is installed on the device and no protocol is added: this is three ordinary
8
+ // `bash` actions (list, read, remove) of the kind remote_bash already sends. The
9
+ // alternative, a client-side push, would mean a new message type and a change to the
10
+ // hot-reload bundle — a protocol change on both ends, for a 30s latency win.
11
+ //
12
+ // Read-then-apply-then-remove, in that order. A crash between apply and remove replays the
13
+ // file on the next tick, where the filename-as-dedupe-key drops it. The reverse order would
14
+ // lose signals instead, which is the failure that matters.
15
+ import { createLogger } from '../core/log.js';
16
+ import { waitpointRepo } from '../store/waitpoint-repo.js';
17
+ import { isDeviceOnline, sendCommand } from '../domain/remote/client-manager.js';
18
+ import { ingestSignal, productionIngestDeps, toSignalInput } from './waitpoint-ingress.js';
19
+ const log = createLogger('waitpoint-drain');
20
+ /** Marker the read command prints before each file, so one round trip returns the whole batch. */
21
+ const FILE_MARKER = '===CORTEX-SIGNAL:';
22
+ /**
23
+ * Spool location on the device. A literal — nothing from a waitpoint is ever interpolated into a
24
+ * command string, which is what keeps this from being an injection surface.
25
+ */
26
+ const REMOTE_SPOOL = '"$HOME/.cortex/tmp/signals"';
27
+ /** Per-file read ceiling, matching the local spool cap. */
28
+ const READ_CAP_BYTES = 64 * 1024;
29
+ const READ_COMMAND = [
30
+ `d=${REMOTE_SPOOL}`,
31
+ '[ -d "$d" ] || exit 0',
32
+ 'for f in "$d"/*.json; do',
33
+ ' [ -f "$f" ] || continue',
34
+ ` printf '%s%s\\n' '${FILE_MARKER}' "$(basename "$f")"`,
35
+ ` head -c ${READ_CAP_BYTES} "$f"`,
36
+ " printf '\\n'",
37
+ 'done',
38
+ ].join('\n');
39
+ /** Only names this shape are ever echoed back into a command. */
40
+ const SAFE_NAME = /^[A-Za-z0-9._-]+\.json$/;
41
+ async function listDevicesWithArmedWaitpoints() {
42
+ const armed = await waitpointRepo.listArmed();
43
+ const devices = new Set();
44
+ for (const wp of armed) {
45
+ if (wp.emitFrom.kind === 'device' && wp.emitFrom.device)
46
+ devices.add(wp.emitFrom.device);
47
+ }
48
+ return [...devices];
49
+ }
50
+ export const productionRemoteDrainDeps = {
51
+ ingest: productionIngestDeps,
52
+ listDeviceTargets: listDevicesWithArmedWaitpoints,
53
+ isDeviceOnline,
54
+ runBash: async (device, command, timeoutMs) => {
55
+ const result = await sendCommand(device, {
56
+ action: 'bash',
57
+ params: { command, timeout: timeoutMs },
58
+ timeout: timeoutMs,
59
+ });
60
+ return { stdout: String(result?.stdout ?? '') };
61
+ },
62
+ };
63
+ /** Split the read command's output back into `{ name, body }` pairs. */
64
+ export function parseSpoolBatch(stdout) {
65
+ const out = [];
66
+ const chunks = stdout.split(FILE_MARKER);
67
+ for (const chunk of chunks) {
68
+ if (!chunk.trim())
69
+ continue;
70
+ const newline = chunk.indexOf('\n');
71
+ if (newline < 0)
72
+ continue;
73
+ const name = chunk.slice(0, newline).trim();
74
+ const body = chunk.slice(newline + 1);
75
+ if (!SAFE_NAME.test(name)) {
76
+ log.warn(`skipping spool entry with an unusable name: ${JSON.stringify(name).slice(0, 80)}`);
77
+ continue;
78
+ }
79
+ out.push({ name, body });
80
+ }
81
+ return out;
82
+ }
83
+ /**
84
+ * Drain one device's spool. Returns how many signals were applied.
85
+ *
86
+ * `device` is a registry key, not user text, but it is still never put into a command string —
87
+ * it only selects which socket the command goes down.
88
+ */
89
+ async function drainOneDevice(device, deps) {
90
+ const { stdout } = await deps.runBash(device, READ_COMMAND, 30_000);
91
+ const entries = parseSpoolBatch(stdout);
92
+ if (entries.length === 0)
93
+ return 0;
94
+ const done = [];
95
+ let applied = 0;
96
+ for (const entry of entries) {
97
+ let payload;
98
+ try {
99
+ payload = JSON.parse(entry.body);
100
+ if (typeof payload !== 'object' || payload === null)
101
+ throw new Error('not an object');
102
+ }
103
+ catch {
104
+ // Leave it on the device rather than deleting evidence of a malformed writer; the name is
105
+ // logged so it can be found. It will be re-read, and re-skipped, each tick.
106
+ log.warn(`${device}: spool entry ${entry.name} is not JSON; leaving it in place`);
107
+ continue;
108
+ }
109
+ const outcome = await ingestSignal(toSignalInput(payload, `spool:${device}:${entry.name}`, `device:${device}`), deps.ingest);
110
+ if (outcome.kind === 'rate-limited')
111
+ continue;
112
+ if (outcome.kind === 'bad-secret') {
113
+ log.warn(`${device}: spool entry ${entry.name} has a bad secret; leaving it in place`);
114
+ continue;
115
+ }
116
+ done.push(entry.name);
117
+ if (outcome.kind === 'accepted')
118
+ applied += 1;
119
+ }
120
+ if (done.length > 0) {
121
+ // Names are validated against SAFE_NAME above, so single-quoting is sufficient and there is
122
+ // nothing left that could close the quote.
123
+ const args = done.map((n) => `'${n}'`).join(' ');
124
+ await deps.runBash(device, `cd ${REMOTE_SPOOL} && rm -f -- ${args}`, 15_000)
125
+ .catch((e) => log.error(`${device}: failed to clear ${done.length} drained signal(s): ${e.message}`));
126
+ }
127
+ return applied;
128
+ }
129
+ /**
130
+ * Visit every device that owns at least one armed waitpoint and collect what it left for us.
131
+ * Offline devices are skipped silently — their files keep until they reconnect.
132
+ */
133
+ export async function drainDeviceSpools(deps = productionRemoteDrainDeps) {
134
+ const devices = await deps.listDeviceTargets();
135
+ let applied = 0;
136
+ for (const device of devices) {
137
+ if (!deps.isDeviceOnline(device))
138
+ continue;
139
+ try {
140
+ applied += await drainOneDevice(device, deps);
141
+ }
142
+ catch (error) {
143
+ log.error(`${device}: spool drain failed: ${error.message}`);
144
+ }
145
+ }
146
+ return applied;
147
+ }
@@ -0,0 +1,42 @@
1
+ import { type WaitpointServiceDeps } from '../domain/waitpoints/service.js';
2
+ import { type WaitpointNotifierDeps } from './waitpoint-notifier.js';
3
+ import { type IngestDeps } from './waitpoint-ingress.js';
4
+ import { type RemoteDrainDeps } from './waitpoint-remote-drain.js';
5
+ export interface WaitpointSweepDeps {
6
+ service: WaitpointServiceDeps;
7
+ notifier: WaitpointNotifierDeps;
8
+ ingest: IngestDeps;
9
+ /** Set to null to skip the device round trip entirely (tests, and hosts with no clients). */
10
+ remote: RemoteDrainDeps | null;
11
+ now: () => number;
12
+ /** Override the drained spool directory. Production leaves it unset (the default location). */
13
+ spoolDir?: string;
14
+ }
15
+ export declare const productionSweepDeps: WaitpointSweepDeps;
16
+ export interface SweepResult {
17
+ spooled: number;
18
+ fromDevices: number;
19
+ expired: number;
20
+ delivered: number;
21
+ purged: number;
22
+ }
23
+ /**
24
+ * One pass: take in whatever the outside world left on disk, age out what is past due, then flush
25
+ * every undelivered wake. Order matters — draining first means a signal that landed a second before
26
+ * the deadline still beats the expiry notice.
27
+ */
28
+ export declare function sweepWaitpoints(deps?: WaitpointSweepDeps): Promise<SweepResult>;
29
+ /** Start the periodic waitpoint sweep. No-op when the configured interval is disabled. */
30
+ export declare function startWaitpointSweep(): void;
31
+ /**
32
+ * Stop the loop. Must run before the repos are flushed on shutdown: a timer firing after
33
+ * waitpointRepo.flush() resolves would enqueue a mutate() whose write is then lost.
34
+ */
35
+ export declare function stopWaitpointSweep(): void;
36
+ /**
37
+ * Boot reconciliation. A restart drops every in-memory coalesce timer, so a waitpoint that fired
38
+ * moments before shutdown has `delivery.pending` set and nobody scheduled to send it; the spool may
39
+ * also hold signals written while the daemon was down. Returns what it recovered, and never throws
40
+ * — a recovery failure must not block startup.
41
+ */
42
+ export declare function recoverWaitpoints(deps?: WaitpointSweepDeps): Promise<SweepResult>;
@@ -0,0 +1,87 @@
1
+ // input: settings (waitpointSweepMs), waitpoint service, notifier, ingress
2
+ // output: sweepWaitpoints / startWaitpointSweep / stopWaitpointSweep / recoverWaitpoints
3
+ // pos: The disk-driven backstop for waitpoints. Every fast path (the coalesce timer, the HTTP
4
+ // route) is in-memory and dies with the process; this loop re-derives everything from
5
+ // waitpoints.json and the spool directory, so a signal that arrived while the daemon was
6
+ // restarting is still delivered, just later.
7
+ //
8
+ // Deliberately self-rearming setTimeout rather than setInterval: a slow sweep must not
9
+ // stack, and the cadence is re-read each tick so a settings change takes effect next round.
10
+ import { createLogger } from '../core/log.js';
11
+ import { getSettings } from '../core/settings.js';
12
+ import { expireDueWaitpoints, productionWaitpointDeps } from '../domain/waitpoints/service.js';
13
+ import { deliverPendingWaitpoints, notifyWaitpointExpiry, productionNotifierDeps, } from './waitpoint-notifier.js';
14
+ import { drainLocalSpool, productionIngestDeps } from './waitpoint-ingress.js';
15
+ import { drainDeviceSpools, productionRemoteDrainDeps } from './waitpoint-remote-drain.js';
16
+ const log = createLogger('waitpoint-sweep');
17
+ export const productionSweepDeps = {
18
+ service: productionWaitpointDeps,
19
+ notifier: productionNotifierDeps,
20
+ ingest: productionIngestDeps,
21
+ remote: productionRemoteDrainDeps,
22
+ now: () => Date.now(),
23
+ };
24
+ /**
25
+ * One pass: take in whatever the outside world left on disk, age out what is past due, then flush
26
+ * every undelivered wake. Order matters — draining first means a signal that landed a second before
27
+ * the deadline still beats the expiry notice.
28
+ */
29
+ export async function sweepWaitpoints(deps = productionSweepDeps) {
30
+ const spooled = await (deps.spoolDir
31
+ ? drainLocalSpool(deps.ingest, deps.spoolDir)
32
+ : drainLocalSpool(deps.ingest)).catch((e) => {
33
+ log.error(`spool drain: ${e.message}`);
34
+ return 0;
35
+ });
36
+ const fromDevices = deps.remote
37
+ ? await drainDeviceSpools(deps.remote).catch((e) => {
38
+ log.error(`device drain: ${e.message}`);
39
+ return 0;
40
+ })
41
+ : 0;
42
+ const { expired, purged } = await expireDueWaitpoints(deps.service);
43
+ if (expired.length > 0)
44
+ await notifyWaitpointExpiry(expired, deps.notifier);
45
+ const delivered = await deliverPendingWaitpoints(deps.notifier);
46
+ return { spooled, fromDevices, expired: expired.length, delivered, purged };
47
+ }
48
+ let timer = null;
49
+ function arm(intervalMs) {
50
+ timer = setTimeout(async () => {
51
+ timer = null;
52
+ await sweepWaitpoints().catch((e) => log.error(`sweep: ${e.message}`));
53
+ const next = getSettings().waitpointSweepMs;
54
+ // Runtime zero stops re-arming until restart; startup zero never starts the loop.
55
+ if (next > 0)
56
+ arm(next);
57
+ }, intervalMs);
58
+ timer.unref?.();
59
+ }
60
+ /** Start the periodic waitpoint sweep. No-op when the configured interval is disabled. */
61
+ export function startWaitpointSweep() {
62
+ const intervalMs = getSettings().waitpointSweepMs;
63
+ if (intervalMs <= 0)
64
+ return;
65
+ arm(intervalMs);
66
+ }
67
+ /**
68
+ * Stop the loop. Must run before the repos are flushed on shutdown: a timer firing after
69
+ * waitpointRepo.flush() resolves would enqueue a mutate() whose write is then lost.
70
+ */
71
+ export function stopWaitpointSweep() {
72
+ if (timer)
73
+ clearTimeout(timer);
74
+ timer = null;
75
+ }
76
+ /**
77
+ * Boot reconciliation. A restart drops every in-memory coalesce timer, so a waitpoint that fired
78
+ * moments before shutdown has `delivery.pending` set and nobody scheduled to send it; the spool may
79
+ * also hold signals written while the daemon was down. Returns what it recovered, and never throws
80
+ * — a recovery failure must not block startup.
81
+ */
82
+ export async function recoverWaitpoints(deps = productionSweepDeps) {
83
+ return sweepWaitpoints(deps).catch((e) => {
84
+ log.error(`recovery failed: ${e.message}`);
85
+ return { spooled: 0, fromDevices: 0, expired: 0, delivered: 0, purged: 0 };
86
+ });
87
+ }
@@ -0,0 +1,19 @@
1
+ /** Feishu rejects an image upload above 10 MB (im/v1/images). Anything larger goes as a file. */
2
+ export declare const FEISHU_IMAGE_MAX_BYTES: number;
3
+ /**
4
+ * The mime Feishu would show inline for this file, or null when it must be sent as a file.
5
+ *
6
+ * Decided from the bytes, not the extension: the agent writes `chart.png` with whatever its plotting
7
+ * library produced, and a mislabelled file that is uploaded as an image is rejected by the API.
8
+ */
9
+ export declare function inlineImageMime(filePath: string, size: number): Promise<string | null>;
10
+ /**
11
+ * Upload `filePath` as a chat image and return its `image_key`, or null when the caller should send
12
+ * it as a file instead.
13
+ *
14
+ * Null is the ordinary outcome for a non-image, an oversized image — and for an upload the app is
15
+ * not allowed to make: `im/v1/images` needs the `im:resource` scope, which an app registered before
16
+ * Cortex ever sent an image will not have. A missing scope must degrade to the previous behaviour,
17
+ * never lose the send.
18
+ */
19
+ export declare function uploadFeishuImage(client: unknown, filePath: string, size: number): Promise<string | null>;