@rozek/nanoclaw 1.2.17

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 (305) hide show
  1. package/.claude/settings.json +1 -0
  2. package/.claude/skills/add-compact/SKILL.md +135 -0
  3. package/.claude/skills/add-discord/SKILL.md +203 -0
  4. package/.claude/skills/add-gmail/SKILL.md +220 -0
  5. package/.claude/skills/add-image-vision/SKILL.md +94 -0
  6. package/.claude/skills/add-ollama-tool/SKILL.md +153 -0
  7. package/.claude/skills/add-parallel/SKILL.md +290 -0
  8. package/.claude/skills/add-pdf-reader/SKILL.md +104 -0
  9. package/.claude/skills/add-reactions/SKILL.md +117 -0
  10. package/.claude/skills/add-slack/SKILL.md +207 -0
  11. package/.claude/skills/add-telegram/SKILL.md +222 -0
  12. package/.claude/skills/add-telegram-swarm/SKILL.md +384 -0
  13. package/.claude/skills/add-voice-transcription/SKILL.md +148 -0
  14. package/.claude/skills/add-whatsapp/SKILL.md +372 -0
  15. package/.claude/skills/convert-to-apple-container/SKILL.md +175 -0
  16. package/.claude/skills/customize/SKILL.md +110 -0
  17. package/.claude/skills/debug/SKILL.md +349 -0
  18. package/.claude/skills/get-qodo-rules/SKILL.md +122 -0
  19. package/.claude/skills/get-qodo-rules/references/output-format.md +41 -0
  20. package/.claude/skills/get-qodo-rules/references/pagination.md +33 -0
  21. package/.claude/skills/get-qodo-rules/references/repository-scope.md +26 -0
  22. package/.claude/skills/qodo-pr-resolver/SKILL.md +326 -0
  23. package/.claude/skills/qodo-pr-resolver/resources/providers.md +329 -0
  24. package/.claude/skills/setup/SKILL.md +218 -0
  25. package/.claude/skills/update-nanoclaw/SKILL.md +235 -0
  26. package/.claude/skills/update-skills/SKILL.md +130 -0
  27. package/.claude/skills/use-local-whisper/SKILL.md +152 -0
  28. package/.claude/skills/x-integration/SKILL.md +417 -0
  29. package/.claude/skills/x-integration/agent.ts +243 -0
  30. package/.claude/skills/x-integration/host.ts +159 -0
  31. package/.claude/skills/x-integration/lib/browser.ts +148 -0
  32. package/.claude/skills/x-integration/lib/config.ts +62 -0
  33. package/.claude/skills/x-integration/scripts/like.ts +56 -0
  34. package/.claude/skills/x-integration/scripts/post.ts +66 -0
  35. package/.claude/skills/x-integration/scripts/quote.ts +80 -0
  36. package/.claude/skills/x-integration/scripts/reply.ts +74 -0
  37. package/.claude/skills/x-integration/scripts/retweet.ts +62 -0
  38. package/.claude/skills/x-integration/scripts/setup.ts +87 -0
  39. package/.env.example +1 -0
  40. package/.github/CODEOWNERS +10 -0
  41. package/.github/PULL_REQUEST_TEMPLATE.md +14 -0
  42. package/.github/workflows/bump-version.yml +32 -0
  43. package/.github/workflows/ci.yml +25 -0
  44. package/.github/workflows/merge-forward-skills.yml +160 -0
  45. package/.github/workflows/update-tokens.yml +42 -0
  46. package/.husky/pre-commit +1 -0
  47. package/.mcp.json +3 -0
  48. package/.nvmrc +1 -0
  49. package/.prettierrc +3 -0
  50. package/CHANGELOG.md +8 -0
  51. package/CLAUDE.md +64 -0
  52. package/CONTRIBUTING.md +23 -0
  53. package/CONTRIBUTORS.md +15 -0
  54. package/LICENSE +21 -0
  55. package/NanoClaw_with_Web-Support.md +290 -0
  56. package/README.md +261 -0
  57. package/README_zh.md +200 -0
  58. package/assets/nanoclaw-favicon.png +0 -0
  59. package/assets/nanoclaw-icon.png +0 -0
  60. package/assets/nanoclaw-logo-dark.png +0 -0
  61. package/assets/nanoclaw-logo.png +0 -0
  62. package/assets/nanoclaw-profile.jpeg +0 -0
  63. package/assets/nanoclaw-sales.png +0 -0
  64. package/assets/social-preview.jpg +0 -0
  65. package/config-examples/mount-allowlist.json +25 -0
  66. package/container/Dockerfile +70 -0
  67. package/container/agent-runner/package-lock.json +1524 -0
  68. package/container/agent-runner/package.json +21 -0
  69. package/container/agent-runner/src/index.ts +558 -0
  70. package/container/agent-runner/src/ipc-mcp-stdio.ts +338 -0
  71. package/container/agent-runner/tsconfig.json +15 -0
  72. package/container/build.sh +23 -0
  73. package/container/skills/agent-browser/SKILL.md +159 -0
  74. package/container/skills/capabilities/SKILL.md +100 -0
  75. package/container/skills/status/SKILL.md +104 -0
  76. package/dist/channels/index.d.ts +2 -0
  77. package/dist/channels/index.d.ts.map +1 -0
  78. package/dist/channels/index.js +9 -0
  79. package/dist/channels/index.js.map +1 -0
  80. package/dist/channels/registry.d.ts +13 -0
  81. package/dist/channels/registry.d.ts.map +1 -0
  82. package/dist/channels/registry.js +11 -0
  83. package/dist/channels/registry.js.map +1 -0
  84. package/dist/channels/registry.test.d.ts +2 -0
  85. package/dist/channels/registry.test.d.ts.map +1 -0
  86. package/dist/channels/registry.test.js +32 -0
  87. package/dist/channels/registry.test.js.map +1 -0
  88. package/dist/channels/web.d.ts +2 -0
  89. package/dist/channels/web.d.ts.map +1 -0
  90. package/dist/channels/web.js +1738 -0
  91. package/dist/channels/web.js.map +1 -0
  92. package/dist/cli.d.ts +11 -0
  93. package/dist/cli.d.ts.map +1 -0
  94. package/dist/cli.js +182 -0
  95. package/dist/cli.js.map +1 -0
  96. package/dist/config.d.ts +19 -0
  97. package/dist/config.d.ts.map +1 -0
  98. package/dist/config.js +36 -0
  99. package/dist/config.js.map +1 -0
  100. package/dist/container-runner.d.ts +44 -0
  101. package/dist/container-runner.d.ts.map +1 -0
  102. package/dist/container-runner.js +467 -0
  103. package/dist/container-runner.js.map +1 -0
  104. package/dist/container-runner.test.d.ts +2 -0
  105. package/dist/container-runner.test.d.ts.map +1 -0
  106. package/dist/container-runner.test.js +150 -0
  107. package/dist/container-runner.test.js.map +1 -0
  108. package/dist/container-runtime.d.ts +22 -0
  109. package/dist/container-runtime.d.ts.map +1 -0
  110. package/dist/container-runtime.js +96 -0
  111. package/dist/container-runtime.js.map +1 -0
  112. package/dist/container-runtime.test.d.ts +2 -0
  113. package/dist/container-runtime.test.d.ts.map +1 -0
  114. package/dist/container-runtime.test.js +93 -0
  115. package/dist/container-runtime.test.js.map +1 -0
  116. package/dist/credential-proxy.d.ts +21 -0
  117. package/dist/credential-proxy.d.ts.map +1 -0
  118. package/dist/credential-proxy.js +95 -0
  119. package/dist/credential-proxy.js.map +1 -0
  120. package/dist/credential-proxy.test.d.ts +2 -0
  121. package/dist/credential-proxy.test.d.ts.map +1 -0
  122. package/dist/credential-proxy.test.js +134 -0
  123. package/dist/credential-proxy.test.js.map +1 -0
  124. package/dist/db.d.ts +115 -0
  125. package/dist/db.d.ts.map +1 -0
  126. package/dist/db.js +549 -0
  127. package/dist/db.js.map +1 -0
  128. package/dist/db.test.d.ts +2 -0
  129. package/dist/db.test.d.ts.map +1 -0
  130. package/dist/db.test.js +360 -0
  131. package/dist/db.test.js.map +1 -0
  132. package/dist/env.d.ts +8 -0
  133. package/dist/env.d.ts.map +1 -0
  134. package/dist/env.js +42 -0
  135. package/dist/env.js.map +1 -0
  136. package/dist/formatting.test.d.ts +2 -0
  137. package/dist/formatting.test.d.ts.map +1 -0
  138. package/dist/formatting.test.js +183 -0
  139. package/dist/formatting.test.js.map +1 -0
  140. package/dist/group-folder.d.ts +5 -0
  141. package/dist/group-folder.d.ts.map +1 -0
  142. package/dist/group-folder.js +44 -0
  143. package/dist/group-folder.js.map +1 -0
  144. package/dist/group-folder.test.d.ts +2 -0
  145. package/dist/group-folder.test.d.ts.map +1 -0
  146. package/dist/group-folder.test.js +29 -0
  147. package/dist/group-folder.test.js.map +1 -0
  148. package/dist/group-queue.d.ts +34 -0
  149. package/dist/group-queue.d.ts.map +1 -0
  150. package/dist/group-queue.js +263 -0
  151. package/dist/group-queue.js.map +1 -0
  152. package/dist/group-queue.test.d.ts +2 -0
  153. package/dist/group-queue.test.d.ts.map +1 -0
  154. package/dist/group-queue.test.js +341 -0
  155. package/dist/group-queue.test.js.map +1 -0
  156. package/dist/index.d.ts +12 -0
  157. package/dist/index.d.ts.map +1 -0
  158. package/dist/index.js +518 -0
  159. package/dist/index.js.map +1 -0
  160. package/dist/ipc-auth.test.d.ts +2 -0
  161. package/dist/ipc-auth.test.d.ts.map +1 -0
  162. package/dist/ipc-auth.test.js +434 -0
  163. package/dist/ipc-auth.test.js.map +1 -0
  164. package/dist/ipc.d.ts +32 -0
  165. package/dist/ipc.d.ts.map +1 -0
  166. package/dist/ipc.js +311 -0
  167. package/dist/ipc.js.map +1 -0
  168. package/dist/logger.d.ts +3 -0
  169. package/dist/logger.d.ts.map +1 -0
  170. package/dist/logger.js +14 -0
  171. package/dist/logger.js.map +1 -0
  172. package/dist/mount-security.d.ts +34 -0
  173. package/dist/mount-security.d.ts.map +1 -0
  174. package/dist/mount-security.js +325 -0
  175. package/dist/mount-security.js.map +1 -0
  176. package/dist/remote-control.d.ts +32 -0
  177. package/dist/remote-control.d.ts.map +1 -0
  178. package/dist/remote-control.js +185 -0
  179. package/dist/remote-control.js.map +1 -0
  180. package/dist/remote-control.test.d.ts +2 -0
  181. package/dist/remote-control.test.d.ts.map +1 -0
  182. package/dist/remote-control.test.js +321 -0
  183. package/dist/remote-control.test.js.map +1 -0
  184. package/dist/router.d.ts +8 -0
  185. package/dist/router.d.ts.map +1 -0
  186. package/dist/router.js +37 -0
  187. package/dist/router.js.map +1 -0
  188. package/dist/routing.test.d.ts +2 -0
  189. package/dist/routing.test.d.ts.map +1 -0
  190. package/dist/routing.test.js +81 -0
  191. package/dist/routing.test.js.map +1 -0
  192. package/dist/sender-allowlist.d.ts +14 -0
  193. package/dist/sender-allowlist.d.ts.map +1 -0
  194. package/dist/sender-allowlist.js +79 -0
  195. package/dist/sender-allowlist.js.map +1 -0
  196. package/dist/sender-allowlist.test.d.ts +2 -0
  197. package/dist/sender-allowlist.test.d.ts.map +1 -0
  198. package/dist/sender-allowlist.test.js +186 -0
  199. package/dist/sender-allowlist.test.js.map +1 -0
  200. package/dist/session-commands.d.ts +47 -0
  201. package/dist/session-commands.d.ts.map +1 -0
  202. package/dist/session-commands.js +102 -0
  203. package/dist/session-commands.js.map +1 -0
  204. package/dist/session-commands.test.d.ts +2 -0
  205. package/dist/session-commands.test.d.ts.map +1 -0
  206. package/dist/session-commands.test.js +190 -0
  207. package/dist/session-commands.test.js.map +1 -0
  208. package/dist/task-scheduler.d.ts +22 -0
  209. package/dist/task-scheduler.d.ts.map +1 -0
  210. package/dist/task-scheduler.js +210 -0
  211. package/dist/task-scheduler.js.map +1 -0
  212. package/dist/task-scheduler.test.d.ts +2 -0
  213. package/dist/task-scheduler.test.d.ts.map +1 -0
  214. package/dist/task-scheduler.test.js +107 -0
  215. package/dist/task-scheduler.test.js.map +1 -0
  216. package/dist/timezone.d.ts +6 -0
  217. package/dist/timezone.d.ts.map +1 -0
  218. package/dist/timezone.js +17 -0
  219. package/dist/timezone.js.map +1 -0
  220. package/dist/timezone.test.d.ts +2 -0
  221. package/dist/timezone.test.d.ts.map +1 -0
  222. package/dist/timezone.test.js +23 -0
  223. package/dist/timezone.test.js.map +1 -0
  224. package/dist/types.d.ts +78 -0
  225. package/dist/types.d.ts.map +1 -0
  226. package/dist/types.js +2 -0
  227. package/dist/types.js.map +1 -0
  228. package/docs/APPLE-CONTAINER-NETWORKING.md +90 -0
  229. package/docs/DEBUG_CHECKLIST.md +143 -0
  230. package/docs/REQUIREMENTS.md +196 -0
  231. package/docs/SDK_DEEP_DIVE.md +643 -0
  232. package/docs/SECURITY.md +122 -0
  233. package/docs/SPEC.md +785 -0
  234. package/docs/docker-sandboxes.md +359 -0
  235. package/docs/nanoclaw-architecture-final.md +1063 -0
  236. package/docs/nanorepo-architecture.md +168 -0
  237. package/docs/skills-as-branches.md +662 -0
  238. package/groups/global/CLAUDE.md +58 -0
  239. package/groups/main/CLAUDE.md +246 -0
  240. package/launchd/com.nanoclaw.plist +32 -0
  241. package/package.json +45 -0
  242. package/repo-tokens/README.md +113 -0
  243. package/repo-tokens/action.yml +186 -0
  244. package/repo-tokens/badge.svg +23 -0
  245. package/repo-tokens/examples/green.svg +14 -0
  246. package/repo-tokens/examples/red.svg +14 -0
  247. package/repo-tokens/examples/yellow-green.svg +14 -0
  248. package/repo-tokens/examples/yellow.svg +14 -0
  249. package/scripts/run-migrations.ts +105 -0
  250. package/setup/container.ts +144 -0
  251. package/setup/environment.test.ts +121 -0
  252. package/setup/environment.ts +94 -0
  253. package/setup/groups.ts +229 -0
  254. package/setup/index.ts +58 -0
  255. package/setup/mounts.ts +115 -0
  256. package/setup/platform.test.ts +120 -0
  257. package/setup/platform.ts +132 -0
  258. package/setup/register.test.ts +257 -0
  259. package/setup/register.ts +177 -0
  260. package/setup/service.test.ts +187 -0
  261. package/setup/service.ts +362 -0
  262. package/setup/status.ts +16 -0
  263. package/setup/verify.ts +192 -0
  264. package/setup.sh +161 -0
  265. package/src/channels/index.ts +12 -0
  266. package/src/channels/registry.test.ts +42 -0
  267. package/src/channels/registry.ts +32 -0
  268. package/src/channels/web.ts +1856 -0
  269. package/src/cli.ts +209 -0
  270. package/src/config.ts +73 -0
  271. package/src/container-runner.test.ts +210 -0
  272. package/src/container-runner.ts +707 -0
  273. package/src/container-runtime.test.ts +149 -0
  274. package/src/container-runtime.ts +127 -0
  275. package/src/credential-proxy.test.ts +192 -0
  276. package/src/credential-proxy.ts +125 -0
  277. package/src/db.test.ts +484 -0
  278. package/src/db.ts +803 -0
  279. package/src/env.ts +42 -0
  280. package/src/formatting.test.ts +256 -0
  281. package/src/group-folder.test.ts +43 -0
  282. package/src/group-folder.ts +44 -0
  283. package/src/group-queue.test.ts +484 -0
  284. package/src/group-queue.ts +365 -0
  285. package/src/index.ts +731 -0
  286. package/src/ipc-auth.test.ts +679 -0
  287. package/src/ipc.ts +461 -0
  288. package/src/logger.ts +16 -0
  289. package/src/mount-security.ts +419 -0
  290. package/src/remote-control.test.ts +397 -0
  291. package/src/remote-control.ts +224 -0
  292. package/src/router.ts +52 -0
  293. package/src/routing.test.ts +170 -0
  294. package/src/sender-allowlist.test.ts +216 -0
  295. package/src/sender-allowlist.ts +128 -0
  296. package/src/session-commands.test.ts +247 -0
  297. package/src/session-commands.ts +163 -0
  298. package/src/task-scheduler.test.ts +129 -0
  299. package/src/task-scheduler.ts +295 -0
  300. package/src/timezone.test.ts +29 -0
  301. package/src/timezone.ts +16 -0
  302. package/src/types.ts +107 -0
  303. package/tsconfig.json +20 -0
  304. package/vitest.config.ts +7 -0
  305. package/vitest.skills.config.ts +7 -0
@@ -0,0 +1,365 @@
1
+ import { ChildProcess } from 'child_process';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+
5
+ import { DATA_DIR, MAX_CONCURRENT_CONTAINERS } from './config.js';
6
+ import { logger } from './logger.js';
7
+
8
+ interface QueuedTask {
9
+ id: string;
10
+ groupJid: string;
11
+ fn: () => Promise<void>;
12
+ }
13
+
14
+ const MAX_RETRIES = 5;
15
+ const BASE_RETRY_MS = 5000;
16
+
17
+ interface GroupState {
18
+ active: boolean;
19
+ idleWaiting: boolean;
20
+ isTaskContainer: boolean;
21
+ runningTaskId: string | null;
22
+ pendingMessages: boolean;
23
+ pendingTasks: QueuedTask[];
24
+ process: ChildProcess | null;
25
+ containerName: string | null;
26
+ groupFolder: string | null;
27
+ retryCount: number;
28
+ }
29
+
30
+ export class GroupQueue {
31
+ private groups = new Map<string, GroupState>();
32
+ private activeCount = 0;
33
+ private waitingGroups: string[] = [];
34
+ private processMessagesFn: ((groupJid: string) => Promise<boolean>) | null =
35
+ null;
36
+ private shuttingDown = false;
37
+
38
+ private getGroup(groupJid: string): GroupState {
39
+ let state = this.groups.get(groupJid);
40
+ if (!state) {
41
+ state = {
42
+ active: false,
43
+ idleWaiting: false,
44
+ isTaskContainer: false,
45
+ runningTaskId: null,
46
+ pendingMessages: false,
47
+ pendingTasks: [],
48
+ process: null,
49
+ containerName: null,
50
+ groupFolder: null,
51
+ retryCount: 0,
52
+ };
53
+ this.groups.set(groupJid, state);
54
+ }
55
+ return state;
56
+ }
57
+
58
+ setProcessMessagesFn(fn: (groupJid: string) => Promise<boolean>): void {
59
+ this.processMessagesFn = fn;
60
+ }
61
+
62
+ enqueueMessageCheck(groupJid: string): void {
63
+ if (this.shuttingDown) return;
64
+
65
+ const state = this.getGroup(groupJid);
66
+
67
+ if (state.active) {
68
+ state.pendingMessages = true;
69
+ logger.debug({ groupJid }, 'Container active, message queued');
70
+ return;
71
+ }
72
+
73
+ if (this.activeCount >= MAX_CONCURRENT_CONTAINERS) {
74
+ state.pendingMessages = true;
75
+ if (!this.waitingGroups.includes(groupJid)) {
76
+ this.waitingGroups.push(groupJid);
77
+ }
78
+ logger.debug(
79
+ { groupJid, activeCount: this.activeCount },
80
+ 'At concurrency limit, message queued',
81
+ );
82
+ return;
83
+ }
84
+
85
+ this.runForGroup(groupJid, 'messages').catch((err) =>
86
+ logger.error({ groupJid, err }, 'Unhandled error in runForGroup'),
87
+ );
88
+ }
89
+
90
+ enqueueTask(groupJid: string, taskId: string, fn: () => Promise<void>): void {
91
+ if (this.shuttingDown) return;
92
+
93
+ const state = this.getGroup(groupJid);
94
+
95
+ // Prevent double-queuing: check both pending and currently-running task
96
+ if (state.runningTaskId === taskId) {
97
+ logger.debug({ groupJid, taskId }, 'Task already running, skipping');
98
+ return;
99
+ }
100
+ if (state.pendingTasks.some((t) => t.id === taskId)) {
101
+ logger.debug({ groupJid, taskId }, 'Task already queued, skipping');
102
+ return;
103
+ }
104
+
105
+ if (state.active) {
106
+ state.pendingTasks.push({ id: taskId, groupJid, fn });
107
+ if (state.idleWaiting) {
108
+ this.closeStdin(groupJid);
109
+ }
110
+ logger.debug({ groupJid, taskId }, 'Container active, task queued');
111
+ return;
112
+ }
113
+
114
+ if (this.activeCount >= MAX_CONCURRENT_CONTAINERS) {
115
+ state.pendingTasks.push({ id: taskId, groupJid, fn });
116
+ if (!this.waitingGroups.includes(groupJid)) {
117
+ this.waitingGroups.push(groupJid);
118
+ }
119
+ logger.debug(
120
+ { groupJid, taskId, activeCount: this.activeCount },
121
+ 'At concurrency limit, task queued',
122
+ );
123
+ return;
124
+ }
125
+
126
+ // Run immediately
127
+ this.runTask(groupJid, { id: taskId, groupJid, fn }).catch((err) =>
128
+ logger.error({ groupJid, taskId, err }, 'Unhandled error in runTask'),
129
+ );
130
+ }
131
+
132
+ registerProcess(
133
+ groupJid: string,
134
+ proc: ChildProcess,
135
+ containerName: string,
136
+ groupFolder?: string,
137
+ ): void {
138
+ const state = this.getGroup(groupJid);
139
+ state.process = proc;
140
+ state.containerName = containerName;
141
+ if (groupFolder) state.groupFolder = groupFolder;
142
+ }
143
+
144
+ /**
145
+ * Mark the container as idle-waiting (finished work, waiting for IPC input).
146
+ * If tasks are pending, preempt the idle container immediately.
147
+ */
148
+ notifyIdle(groupJid: string): void {
149
+ const state = this.getGroup(groupJid);
150
+ state.idleWaiting = true;
151
+ if (state.pendingTasks.length > 0) {
152
+ this.closeStdin(groupJid);
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Send a follow-up message to the active container via IPC file.
158
+ * Returns true if the message was written, false if no active container.
159
+ */
160
+ sendMessage(groupJid: string, text: string): boolean {
161
+ const state = this.getGroup(groupJid);
162
+ if (!state.active || !state.groupFolder || state.isTaskContainer)
163
+ return false;
164
+ state.idleWaiting = false; // Agent is about to receive work, no longer idle
165
+
166
+ const inputDir = path.join(DATA_DIR, 'ipc', state.groupFolder, 'input');
167
+ try {
168
+ fs.mkdirSync(inputDir, { recursive: true });
169
+ const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 6)}.json`;
170
+ const filepath = path.join(inputDir, filename);
171
+ const tempPath = `${filepath}.tmp`;
172
+ fs.writeFileSync(tempPath, JSON.stringify({ type: 'message', text }));
173
+ fs.renameSync(tempPath, filepath);
174
+ return true;
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Signal the active container to wind down by writing a close sentinel.
182
+ */
183
+ closeStdin(groupJid: string): void {
184
+ const state = this.getGroup(groupJid);
185
+ if (!state.active || !state.groupFolder) return;
186
+
187
+ const inputDir = path.join(DATA_DIR, 'ipc', state.groupFolder, 'input');
188
+ try {
189
+ fs.mkdirSync(inputDir, { recursive: true });
190
+ fs.writeFileSync(path.join(inputDir, '_close'), '');
191
+ } catch {
192
+ // ignore
193
+ }
194
+ }
195
+
196
+ private async runForGroup(
197
+ groupJid: string,
198
+ reason: 'messages' | 'drain',
199
+ ): Promise<void> {
200
+ const state = this.getGroup(groupJid);
201
+ state.active = true;
202
+ state.idleWaiting = false;
203
+ state.isTaskContainer = false;
204
+ state.pendingMessages = false;
205
+ this.activeCount++;
206
+
207
+ logger.debug(
208
+ { groupJid, reason, activeCount: this.activeCount },
209
+ 'Starting container for group',
210
+ );
211
+
212
+ try {
213
+ if (this.processMessagesFn) {
214
+ const success = await this.processMessagesFn(groupJid);
215
+ if (success) {
216
+ state.retryCount = 0;
217
+ } else {
218
+ this.scheduleRetry(groupJid, state);
219
+ }
220
+ }
221
+ } catch (err) {
222
+ logger.error({ groupJid, err }, 'Error processing messages for group');
223
+ this.scheduleRetry(groupJid, state);
224
+ } finally {
225
+ state.active = false;
226
+ state.process = null;
227
+ state.containerName = null;
228
+ state.groupFolder = null;
229
+ this.activeCount--;
230
+ this.drainGroup(groupJid);
231
+ }
232
+ }
233
+
234
+ private async runTask(groupJid: string, task: QueuedTask): Promise<void> {
235
+ const state = this.getGroup(groupJid);
236
+ state.active = true;
237
+ state.idleWaiting = false;
238
+ state.isTaskContainer = true;
239
+ state.runningTaskId = task.id;
240
+ this.activeCount++;
241
+
242
+ logger.debug(
243
+ { groupJid, taskId: task.id, activeCount: this.activeCount },
244
+ 'Running queued task',
245
+ );
246
+
247
+ try {
248
+ await task.fn();
249
+ } catch (err) {
250
+ logger.error({ groupJid, taskId: task.id, err }, 'Error running task');
251
+ } finally {
252
+ state.active = false;
253
+ state.isTaskContainer = false;
254
+ state.runningTaskId = null;
255
+ state.process = null;
256
+ state.containerName = null;
257
+ state.groupFolder = null;
258
+ this.activeCount--;
259
+ this.drainGroup(groupJid);
260
+ }
261
+ }
262
+
263
+ private scheduleRetry(groupJid: string, state: GroupState): void {
264
+ state.retryCount++;
265
+ if (state.retryCount > MAX_RETRIES) {
266
+ logger.error(
267
+ { groupJid, retryCount: state.retryCount },
268
+ 'Max retries exceeded, dropping messages (will retry on next incoming message)',
269
+ );
270
+ state.retryCount = 0;
271
+ return;
272
+ }
273
+
274
+ const delayMs = BASE_RETRY_MS * Math.pow(2, state.retryCount - 1);
275
+ logger.info(
276
+ { groupJid, retryCount: state.retryCount, delayMs },
277
+ 'Scheduling retry with backoff',
278
+ );
279
+ setTimeout(() => {
280
+ if (!this.shuttingDown) {
281
+ this.enqueueMessageCheck(groupJid);
282
+ }
283
+ }, delayMs);
284
+ }
285
+
286
+ private drainGroup(groupJid: string): void {
287
+ if (this.shuttingDown) return;
288
+
289
+ const state = this.getGroup(groupJid);
290
+
291
+ // Tasks first (they won't be re-discovered from SQLite like messages)
292
+ if (state.pendingTasks.length > 0) {
293
+ const task = state.pendingTasks.shift()!;
294
+ this.runTask(groupJid, task).catch((err) =>
295
+ logger.error(
296
+ { groupJid, taskId: task.id, err },
297
+ 'Unhandled error in runTask (drain)',
298
+ ),
299
+ );
300
+ return;
301
+ }
302
+
303
+ // Then pending messages
304
+ if (state.pendingMessages) {
305
+ this.runForGroup(groupJid, 'drain').catch((err) =>
306
+ logger.error(
307
+ { groupJid, err },
308
+ 'Unhandled error in runForGroup (drain)',
309
+ ),
310
+ );
311
+ return;
312
+ }
313
+
314
+ // Nothing pending for this group; check if other groups are waiting for a slot
315
+ this.drainWaiting();
316
+ }
317
+
318
+ private drainWaiting(): void {
319
+ while (
320
+ this.waitingGroups.length > 0 &&
321
+ this.activeCount < MAX_CONCURRENT_CONTAINERS
322
+ ) {
323
+ const nextJid = this.waitingGroups.shift()!;
324
+ const state = this.getGroup(nextJid);
325
+
326
+ // Prioritize tasks over messages
327
+ if (state.pendingTasks.length > 0) {
328
+ const task = state.pendingTasks.shift()!;
329
+ this.runTask(nextJid, task).catch((err) =>
330
+ logger.error(
331
+ { groupJid: nextJid, taskId: task.id, err },
332
+ 'Unhandled error in runTask (waiting)',
333
+ ),
334
+ );
335
+ } else if (state.pendingMessages) {
336
+ this.runForGroup(nextJid, 'drain').catch((err) =>
337
+ logger.error(
338
+ { groupJid: nextJid, err },
339
+ 'Unhandled error in runForGroup (waiting)',
340
+ ),
341
+ );
342
+ }
343
+ // If neither pending, skip this group
344
+ }
345
+ }
346
+
347
+ async shutdown(_gracePeriodMs: number): Promise<void> {
348
+ this.shuttingDown = true;
349
+
350
+ // Count active containers but don't kill them — they'll finish on their own
351
+ // via idle timeout or container timeout. The --rm flag cleans them up on exit.
352
+ // This prevents WhatsApp reconnection restarts from killing working agents.
353
+ const activeContainers: string[] = [];
354
+ for (const [jid, state] of this.groups) {
355
+ if (state.process && !state.process.killed && state.containerName) {
356
+ activeContainers.push(state.containerName);
357
+ }
358
+ }
359
+
360
+ logger.info(
361
+ { activeCount: this.activeCount, detachedContainers: activeContainers },
362
+ 'GroupQueue shutting down (containers detached, not killed)',
363
+ );
364
+ }
365
+ }