@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,707 @@
1
+ /**
2
+ * Container Runner for NanoClaw
3
+ * Spawns agent execution in containers and handles IPC
4
+ */
5
+ import { ChildProcess, exec, spawn } from 'child_process';
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+
9
+ import {
10
+ CONTAINER_IMAGE,
11
+ CONTAINER_MAX_OUTPUT_SIZE,
12
+ CONTAINER_TIMEOUT,
13
+ CREDENTIAL_PROXY_PORT,
14
+ DATA_DIR,
15
+ GROUPS_DIR,
16
+ IDLE_TIMEOUT,
17
+ TIMEZONE,
18
+ } from './config.js';
19
+ import { resolveGroupFolderPath, resolveGroupIpcPath } from './group-folder.js';
20
+ import { logger } from './logger.js';
21
+ import {
22
+ CONTAINER_HOST_GATEWAY,
23
+ CONTAINER_RUNTIME_BIN,
24
+ hostGatewayArgs,
25
+ readonlyMountArgs,
26
+ stopContainer,
27
+ } from './container-runtime.js';
28
+ import { detectAuthMode } from './credential-proxy.js';
29
+ import { validateAdditionalMounts } from './mount-security.js';
30
+ import { RegisteredGroup } from './types.js';
31
+
32
+ // Sentinel markers for robust output parsing (must match agent-runner)
33
+ const OUTPUT_START_MARKER = '---NANOCLAW_OUTPUT_START---';
34
+ const OUTPUT_END_MARKER = '---NANOCLAW_OUTPUT_END---';
35
+
36
+ export interface ContainerInput {
37
+ prompt: string;
38
+ sessionId?: string;
39
+ groupFolder: string;
40
+ chatJid: string;
41
+ isMain: boolean;
42
+ isScheduledTask?: boolean;
43
+ assistantName?: string;
44
+ }
45
+
46
+ export interface ContainerOutput {
47
+ status: 'success' | 'error';
48
+ result: string | null;
49
+ newSessionId?: string;
50
+ error?: string;
51
+ }
52
+
53
+ interface VolumeMount {
54
+ hostPath: string;
55
+ containerPath: string;
56
+ readonly: boolean;
57
+ }
58
+
59
+ function buildVolumeMounts(
60
+ group: RegisteredGroup,
61
+ isMain: boolean,
62
+ ): VolumeMount[] {
63
+ const mounts: VolumeMount[] = [];
64
+ const projectRoot = process.cwd();
65
+ const groupDir = resolveGroupFolderPath(group.folder);
66
+
67
+ if (isMain) {
68
+ // Main gets the project root read-only. Writable paths the agent needs
69
+ // (group folder, IPC, .claude/) are mounted separately below.
70
+ // Read-only prevents the agent from modifying host application code
71
+ // (src/, dist/, package.json, etc.) which would bypass the sandbox
72
+ // entirely on next restart.
73
+ mounts.push({
74
+ hostPath: projectRoot,
75
+ containerPath: '/workspace/project',
76
+ readonly: true,
77
+ });
78
+
79
+ // Shadow .env so the agent cannot read secrets from the mounted project root.
80
+ // Credentials are injected by the credential proxy, never exposed to containers.
81
+ const envFile = path.join(projectRoot, '.env');
82
+ if (fs.existsSync(envFile)) {
83
+ mounts.push({
84
+ hostPath: '/dev/null',
85
+ containerPath: '/workspace/project/.env',
86
+ readonly: true,
87
+ });
88
+ }
89
+
90
+ // Main also gets its group folder as the working directory
91
+ mounts.push({
92
+ hostPath: groupDir,
93
+ containerPath: '/workspace/group',
94
+ readonly: false,
95
+ });
96
+ } else {
97
+ // Other groups only get their own folder
98
+ mounts.push({
99
+ hostPath: groupDir,
100
+ containerPath: '/workspace/group',
101
+ readonly: false,
102
+ });
103
+
104
+ // Global memory directory (read-only for non-main)
105
+ // Only directory mounts are supported, not file mounts
106
+ const globalDir = path.join(GROUPS_DIR, 'global');
107
+ if (fs.existsSync(globalDir)) {
108
+ mounts.push({
109
+ hostPath: globalDir,
110
+ containerPath: '/workspace/global',
111
+ readonly: true,
112
+ });
113
+ }
114
+ }
115
+
116
+ // Per-group Claude sessions directory (isolated from other groups)
117
+ // Each group gets their own .claude/ to prevent cross-group session access
118
+ const groupSessionsDir = path.join(
119
+ DATA_DIR,
120
+ 'sessions',
121
+ group.folder,
122
+ '.claude',
123
+ );
124
+ fs.mkdirSync(groupSessionsDir, { recursive: true });
125
+ const settingsFile = path.join(groupSessionsDir, 'settings.json');
126
+ if (!fs.existsSync(settingsFile)) {
127
+ fs.writeFileSync(
128
+ settingsFile,
129
+ JSON.stringify(
130
+ {
131
+ env: {
132
+ // Enable agent swarms (subagent orchestration)
133
+ // https://code.claude.com/docs/en/agent-teams#orchestrate-teams-of-claude-code-sessions
134
+ CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: '1',
135
+ // Load CLAUDE.md from additional mounted directories
136
+ // https://code.claude.com/docs/en/memory#load-memory-from-additional-directories
137
+ CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: '1',
138
+ // Enable Claude's memory feature (persists user preferences between sessions)
139
+ // https://code.claude.com/docs/en/memory#manage-auto-memory
140
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: '0',
141
+ },
142
+ },
143
+ null,
144
+ 2,
145
+ ) + '\n',
146
+ );
147
+ }
148
+
149
+ // Sync skills from container/skills/ into each group's .claude/skills/
150
+ const skillsSrc = path.join(process.cwd(), 'container', 'skills');
151
+ const skillsDst = path.join(groupSessionsDir, 'skills');
152
+ if (fs.existsSync(skillsSrc)) {
153
+ for (const skillDir of fs.readdirSync(skillsSrc)) {
154
+ const srcDir = path.join(skillsSrc, skillDir);
155
+ if (!fs.statSync(srcDir).isDirectory()) continue;
156
+ const dstDir = path.join(skillsDst, skillDir);
157
+ fs.cpSync(srcDir, dstDir, { recursive: true });
158
+ }
159
+ }
160
+ mounts.push({
161
+ hostPath: groupSessionsDir,
162
+ containerPath: '/home/node/.claude',
163
+ readonly: false,
164
+ });
165
+
166
+ // Per-group IPC namespace: each group gets its own IPC directory
167
+ // This prevents cross-group privilege escalation via IPC
168
+ const groupIpcDir = resolveGroupIpcPath(group.folder);
169
+ fs.mkdirSync(path.join(groupIpcDir, 'messages'), { recursive: true });
170
+ fs.mkdirSync(path.join(groupIpcDir, 'tasks'), { recursive: true });
171
+ fs.mkdirSync(path.join(groupIpcDir, 'input'), { recursive: true });
172
+ mounts.push({
173
+ hostPath: groupIpcDir,
174
+ containerPath: '/workspace/ipc',
175
+ readonly: false,
176
+ });
177
+
178
+ // Copy agent-runner source into a per-group writable location so agents
179
+ // can customize it (add tools, change behavior) without affecting other
180
+ // groups. Recompiled on container startup via entrypoint.sh.
181
+ const agentRunnerSrc = path.join(
182
+ projectRoot,
183
+ 'container',
184
+ 'agent-runner',
185
+ 'src',
186
+ );
187
+ const groupAgentRunnerDir = path.join(
188
+ DATA_DIR,
189
+ 'sessions',
190
+ group.folder,
191
+ 'agent-runner-src',
192
+ );
193
+ if (!fs.existsSync(groupAgentRunnerDir) && fs.existsSync(agentRunnerSrc)) {
194
+ fs.cpSync(agentRunnerSrc, groupAgentRunnerDir, { recursive: true });
195
+ }
196
+ mounts.push({
197
+ hostPath: groupAgentRunnerDir,
198
+ containerPath: '/app/src',
199
+ readonly: false,
200
+ });
201
+
202
+ // Additional mounts validated against external allowlist (tamper-proof from containers)
203
+ if (group.containerConfig?.additionalMounts) {
204
+ const validatedMounts = validateAdditionalMounts(
205
+ group.containerConfig.additionalMounts,
206
+ group.name,
207
+ isMain,
208
+ );
209
+ mounts.push(...validatedMounts);
210
+ }
211
+
212
+ return mounts;
213
+ }
214
+
215
+ function buildContainerArgs(
216
+ mounts: VolumeMount[],
217
+ containerName: string,
218
+ ): string[] {
219
+ const args: string[] = ['run', '-i', '--rm', '--name', containerName];
220
+
221
+ // Pass host timezone so container's local time matches the user's
222
+ args.push('-e', `TZ=${TIMEZONE}`);
223
+
224
+ // Route API traffic through the credential proxy (containers never see real secrets)
225
+ args.push(
226
+ '-e',
227
+ `ANTHROPIC_BASE_URL=http://${CONTAINER_HOST_GATEWAY}:${CREDENTIAL_PROXY_PORT}`,
228
+ );
229
+
230
+ // Mirror the host's auth method with a placeholder value.
231
+ // API key mode: SDK sends x-api-key, proxy replaces with real key.
232
+ // OAuth mode: SDK exchanges placeholder token for temp API key,
233
+ // proxy injects real OAuth token on that exchange request.
234
+ const authMode = detectAuthMode();
235
+ if (authMode === 'api-key') {
236
+ args.push('-e', 'ANTHROPIC_API_KEY=placeholder');
237
+ } else {
238
+ args.push('-e', 'CLAUDE_CODE_OAUTH_TOKEN=placeholder');
239
+ }
240
+
241
+ // Runtime-specific args for host gateway resolution
242
+ args.push(...hostGatewayArgs());
243
+
244
+ // Run as host user so bind-mounted files are accessible.
245
+ // Skip when running as root (uid 0), as the container's node user (uid 1000),
246
+ // or when getuid is unavailable (native Windows without WSL).
247
+ const hostUid = process.getuid?.();
248
+ const hostGid = process.getgid?.();
249
+ if (hostUid != null && hostUid !== 0 && hostUid !== 1000) {
250
+ args.push('--user', `${hostUid}:${hostGid}`);
251
+ args.push('-e', 'HOME=/home/node');
252
+ }
253
+
254
+ for (const mount of mounts) {
255
+ if (mount.readonly) {
256
+ args.push(...readonlyMountArgs(mount.hostPath, mount.containerPath));
257
+ } else {
258
+ args.push('-v', `${mount.hostPath}:${mount.containerPath}`);
259
+ }
260
+ }
261
+
262
+ args.push(CONTAINER_IMAGE);
263
+
264
+ return args;
265
+ }
266
+
267
+ export async function runContainerAgent(
268
+ group: RegisteredGroup,
269
+ input: ContainerInput,
270
+ onProcess: (proc: ChildProcess, containerName: string) => void,
271
+ onOutput?: (output: ContainerOutput) => Promise<void>,
272
+ ): Promise<ContainerOutput> {
273
+ const startTime = Date.now();
274
+
275
+ const groupDir = resolveGroupFolderPath(group.folder);
276
+ fs.mkdirSync(groupDir, { recursive: true });
277
+
278
+ const mounts = buildVolumeMounts(group, input.isMain);
279
+ const safeName = group.folder.replace(/[^a-zA-Z0-9-]/g, '-');
280
+ const containerName = `nanoclaw-${safeName}-${Date.now()}`;
281
+ const containerArgs = buildContainerArgs(mounts, containerName);
282
+
283
+ logger.debug(
284
+ {
285
+ group: group.name,
286
+ containerName,
287
+ mounts: mounts.map(
288
+ (m) =>
289
+ `${m.hostPath} -> ${m.containerPath}${m.readonly ? ' (ro)' : ''}`,
290
+ ),
291
+ containerArgs: containerArgs.join(' '),
292
+ },
293
+ 'Container mount configuration',
294
+ );
295
+
296
+ logger.info(
297
+ {
298
+ group: group.name,
299
+ containerName,
300
+ mountCount: mounts.length,
301
+ isMain: input.isMain,
302
+ },
303
+ 'Spawning container agent',
304
+ );
305
+
306
+ const logsDir = path.join(groupDir, 'logs');
307
+ fs.mkdirSync(logsDir, { recursive: true });
308
+
309
+ return new Promise((resolve) => {
310
+ const container = spawn(CONTAINER_RUNTIME_BIN, containerArgs, {
311
+ stdio: ['pipe', 'pipe', 'pipe'],
312
+ });
313
+
314
+ onProcess(container, containerName);
315
+
316
+ let stdout = '';
317
+ let stderr = '';
318
+ let stdoutTruncated = false;
319
+ let stderrTruncated = false;
320
+
321
+ container.stdin.write(JSON.stringify(input));
322
+ container.stdin.end();
323
+
324
+ // Streaming output: parse OUTPUT_START/END marker pairs as they arrive
325
+ let parseBuffer = '';
326
+ let newSessionId: string | undefined;
327
+ let outputChain = Promise.resolve();
328
+
329
+ container.stdout.on('data', (data) => {
330
+ const chunk = data.toString();
331
+
332
+ // Always accumulate for logging
333
+ if (!stdoutTruncated) {
334
+ const remaining = CONTAINER_MAX_OUTPUT_SIZE - stdout.length;
335
+ if (chunk.length > remaining) {
336
+ stdout += chunk.slice(0, remaining);
337
+ stdoutTruncated = true;
338
+ logger.warn(
339
+ { group: group.name, size: stdout.length },
340
+ 'Container stdout truncated due to size limit',
341
+ );
342
+ } else {
343
+ stdout += chunk;
344
+ }
345
+ }
346
+
347
+ // Stream-parse for output markers
348
+ if (onOutput) {
349
+ parseBuffer += chunk;
350
+ let startIdx: number;
351
+ while ((startIdx = parseBuffer.indexOf(OUTPUT_START_MARKER)) !== -1) {
352
+ const endIdx = parseBuffer.indexOf(OUTPUT_END_MARKER, startIdx);
353
+ if (endIdx === -1) break; // Incomplete pair, wait for more data
354
+
355
+ const jsonStr = parseBuffer
356
+ .slice(startIdx + OUTPUT_START_MARKER.length, endIdx)
357
+ .trim();
358
+ parseBuffer = parseBuffer.slice(endIdx + OUTPUT_END_MARKER.length);
359
+
360
+ try {
361
+ const parsed: ContainerOutput = JSON.parse(jsonStr);
362
+ if (parsed.newSessionId) {
363
+ newSessionId = parsed.newSessionId;
364
+ }
365
+ hadStreamingOutput = true;
366
+ // Activity detected — reset the hard timeout
367
+ resetTimeout();
368
+ // Call onOutput for all markers (including null results)
369
+ // so idle timers start even for "silent" query completions.
370
+ outputChain = outputChain.then(() => onOutput(parsed));
371
+ } catch (err) {
372
+ logger.warn(
373
+ { group: group.name, error: err },
374
+ 'Failed to parse streamed output chunk',
375
+ );
376
+ }
377
+ }
378
+ }
379
+ });
380
+
381
+ container.stderr.on('data', (data) => {
382
+ const chunk = data.toString();
383
+ const lines = chunk.trim().split('\n');
384
+ for (const line of lines) {
385
+ if (line) logger.debug({ container: group.folder }, line);
386
+ }
387
+ // Don't reset timeout on stderr — SDK writes debug logs continuously.
388
+ // Timeout only resets on actual output (OUTPUT_MARKER in stdout).
389
+ if (stderrTruncated) return;
390
+ const remaining = CONTAINER_MAX_OUTPUT_SIZE - stderr.length;
391
+ if (chunk.length > remaining) {
392
+ stderr += chunk.slice(0, remaining);
393
+ stderrTruncated = true;
394
+ logger.warn(
395
+ { group: group.name, size: stderr.length },
396
+ 'Container stderr truncated due to size limit',
397
+ );
398
+ } else {
399
+ stderr += chunk;
400
+ }
401
+ });
402
+
403
+ let timedOut = false;
404
+ let hadStreamingOutput = false;
405
+ const configTimeout = group.containerConfig?.timeout || CONTAINER_TIMEOUT;
406
+ // Grace period: hard timeout must be at least IDLE_TIMEOUT + 30s so the
407
+ // graceful _close sentinel has time to trigger before the hard kill fires.
408
+ const timeoutMs = Math.max(configTimeout, IDLE_TIMEOUT + 30_000);
409
+
410
+ const killOnTimeout = () => {
411
+ timedOut = true;
412
+ logger.error(
413
+ { group: group.name, containerName },
414
+ 'Container timeout, stopping gracefully',
415
+ );
416
+ exec(stopContainer(containerName), { timeout: 15000 }, (err) => {
417
+ if (err) {
418
+ logger.warn(
419
+ { group: group.name, containerName, err },
420
+ 'Graceful stop failed, force killing',
421
+ );
422
+ container.kill('SIGKILL');
423
+ }
424
+ });
425
+ };
426
+
427
+ let timeout = setTimeout(killOnTimeout, timeoutMs);
428
+
429
+ // Reset the timeout whenever there's activity (streaming output)
430
+ const resetTimeout = () => {
431
+ clearTimeout(timeout);
432
+ timeout = setTimeout(killOnTimeout, timeoutMs);
433
+ };
434
+
435
+ container.on('close', (code) => {
436
+ clearTimeout(timeout);
437
+ const duration = Date.now() - startTime;
438
+
439
+ if (timedOut) {
440
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
441
+ const timeoutLog = path.join(logsDir, `container-${ts}.log`);
442
+ fs.writeFileSync(
443
+ timeoutLog,
444
+ [
445
+ `=== Container Run Log (TIMEOUT) ===`,
446
+ `Timestamp: ${new Date().toISOString()}`,
447
+ `Group: ${group.name}`,
448
+ `Container: ${containerName}`,
449
+ `Duration: ${duration}ms`,
450
+ `Exit Code: ${code}`,
451
+ `Had Streaming Output: ${hadStreamingOutput}`,
452
+ ].join('\n'),
453
+ );
454
+
455
+ // Timeout after output = idle cleanup, not failure.
456
+ // The agent already sent its response; this is just the
457
+ // container being reaped after the idle period expired.
458
+ if (hadStreamingOutput) {
459
+ logger.info(
460
+ { group: group.name, containerName, duration, code },
461
+ 'Container timed out after output (idle cleanup)',
462
+ );
463
+ outputChain.then(() => {
464
+ resolve({
465
+ status: 'success',
466
+ result: null,
467
+ newSessionId,
468
+ });
469
+ });
470
+ return;
471
+ }
472
+
473
+ logger.error(
474
+ { group: group.name, containerName, duration, code },
475
+ 'Container timed out with no output',
476
+ );
477
+
478
+ resolve({
479
+ status: 'error',
480
+ result: null,
481
+ error: `Container timed out after ${configTimeout}ms`,
482
+ });
483
+ return;
484
+ }
485
+
486
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
487
+ const logFile = path.join(logsDir, `container-${timestamp}.log`);
488
+ const isVerbose =
489
+ process.env.LOG_LEVEL === 'debug' || process.env.LOG_LEVEL === 'trace';
490
+
491
+ const logLines = [
492
+ `=== Container Run Log ===`,
493
+ `Timestamp: ${new Date().toISOString()}`,
494
+ `Group: ${group.name}`,
495
+ `IsMain: ${input.isMain}`,
496
+ `Duration: ${duration}ms`,
497
+ `Exit Code: ${code}`,
498
+ `Stdout Truncated: ${stdoutTruncated}`,
499
+ `Stderr Truncated: ${stderrTruncated}`,
500
+ ``,
501
+ ];
502
+
503
+ const isError = code !== 0;
504
+
505
+ if (isVerbose || isError) {
506
+ logLines.push(
507
+ `=== Input ===`,
508
+ JSON.stringify(input, null, 2),
509
+ ``,
510
+ `=== Container Args ===`,
511
+ containerArgs.join(' '),
512
+ ``,
513
+ `=== Mounts ===`,
514
+ mounts
515
+ .map(
516
+ (m) =>
517
+ `${m.hostPath} -> ${m.containerPath}${m.readonly ? ' (ro)' : ''}`,
518
+ )
519
+ .join('\n'),
520
+ ``,
521
+ `=== Stderr${stderrTruncated ? ' (TRUNCATED)' : ''} ===`,
522
+ stderr,
523
+ ``,
524
+ `=== Stdout${stdoutTruncated ? ' (TRUNCATED)' : ''} ===`,
525
+ stdout,
526
+ );
527
+ } else {
528
+ logLines.push(
529
+ `=== Input Summary ===`,
530
+ `Prompt length: ${input.prompt.length} chars`,
531
+ `Session ID: ${input.sessionId || 'new'}`,
532
+ ``,
533
+ `=== Mounts ===`,
534
+ mounts
535
+ .map((m) => `${m.containerPath}${m.readonly ? ' (ro)' : ''}`)
536
+ .join('\n'),
537
+ ``,
538
+ );
539
+ }
540
+
541
+ fs.writeFileSync(logFile, logLines.join('\n'));
542
+ logger.debug({ logFile, verbose: isVerbose }, 'Container log written');
543
+
544
+ if (code !== 0) {
545
+ logger.error(
546
+ {
547
+ group: group.name,
548
+ code,
549
+ duration,
550
+ stderr,
551
+ stdout,
552
+ logFile,
553
+ },
554
+ 'Container exited with error',
555
+ );
556
+
557
+ resolve({
558
+ status: 'error',
559
+ result: null,
560
+ error: `Container exited with code ${code}: ${stderr.slice(-200)}`,
561
+ });
562
+ return;
563
+ }
564
+
565
+ // Streaming mode: wait for output chain to settle, return completion marker
566
+ if (onOutput) {
567
+ outputChain.then(() => {
568
+ logger.info(
569
+ { group: group.name, duration, newSessionId },
570
+ 'Container completed (streaming mode)',
571
+ );
572
+ resolve({
573
+ status: 'success',
574
+ result: null,
575
+ newSessionId,
576
+ });
577
+ });
578
+ return;
579
+ }
580
+
581
+ // Legacy mode: parse the last output marker pair from accumulated stdout
582
+ try {
583
+ // Extract JSON between sentinel markers for robust parsing
584
+ const startIdx = stdout.indexOf(OUTPUT_START_MARKER);
585
+ const endIdx = stdout.indexOf(OUTPUT_END_MARKER);
586
+
587
+ let jsonLine: string;
588
+ if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
589
+ jsonLine = stdout
590
+ .slice(startIdx + OUTPUT_START_MARKER.length, endIdx)
591
+ .trim();
592
+ } else {
593
+ // Fallback: last non-empty line (backwards compatibility)
594
+ const lines = stdout.trim().split('\n');
595
+ jsonLine = lines[lines.length - 1];
596
+ }
597
+
598
+ const output: ContainerOutput = JSON.parse(jsonLine);
599
+
600
+ logger.info(
601
+ {
602
+ group: group.name,
603
+ duration,
604
+ status: output.status,
605
+ hasResult: !!output.result,
606
+ },
607
+ 'Container completed',
608
+ );
609
+
610
+ resolve(output);
611
+ } catch (err) {
612
+ logger.error(
613
+ {
614
+ group: group.name,
615
+ stdout,
616
+ stderr,
617
+ error: err,
618
+ },
619
+ 'Failed to parse container output',
620
+ );
621
+
622
+ resolve({
623
+ status: 'error',
624
+ result: null,
625
+ error: `Failed to parse container output: ${err instanceof Error ? err.message : String(err)}`,
626
+ });
627
+ }
628
+ });
629
+
630
+ container.on('error', (err) => {
631
+ clearTimeout(timeout);
632
+ logger.error(
633
+ { group: group.name, containerName, error: err },
634
+ 'Container spawn error',
635
+ );
636
+ resolve({
637
+ status: 'error',
638
+ result: null,
639
+ error: `Container spawn error: ${err.message}`,
640
+ });
641
+ });
642
+ });
643
+ }
644
+
645
+ export function writeTasksSnapshot(
646
+ groupFolder: string,
647
+ isMain: boolean,
648
+ tasks: Array<{
649
+ id: string;
650
+ groupFolder: string;
651
+ prompt: string;
652
+ schedule_type: string;
653
+ schedule_value: string;
654
+ status: string;
655
+ next_run: string | null;
656
+ }>,
657
+ ): void {
658
+ // Write filtered tasks to the group's IPC directory
659
+ const groupIpcDir = resolveGroupIpcPath(groupFolder);
660
+ fs.mkdirSync(groupIpcDir, { recursive: true });
661
+
662
+ // Main sees all tasks, others only see their own
663
+ const filteredTasks = isMain
664
+ ? tasks
665
+ : tasks.filter((t) => t.groupFolder === groupFolder);
666
+
667
+ const tasksFile = path.join(groupIpcDir, 'current_tasks.json');
668
+ fs.writeFileSync(tasksFile, JSON.stringify(filteredTasks, null, 2));
669
+ }
670
+
671
+ export interface AvailableGroup {
672
+ jid: string;
673
+ name: string;
674
+ lastActivity: string;
675
+ isRegistered: boolean;
676
+ }
677
+
678
+ /**
679
+ * Write available groups snapshot for the container to read.
680
+ * Only main group can see all available groups (for activation).
681
+ * Non-main groups only see their own registration status.
682
+ */
683
+ export function writeGroupsSnapshot(
684
+ groupFolder: string,
685
+ isMain: boolean,
686
+ groups: AvailableGroup[],
687
+ registeredJids: Set<string>,
688
+ ): void {
689
+ const groupIpcDir = resolveGroupIpcPath(groupFolder);
690
+ fs.mkdirSync(groupIpcDir, { recursive: true });
691
+
692
+ // Main sees all groups; others see nothing (they can't activate groups)
693
+ const visibleGroups = isMain ? groups : [];
694
+
695
+ const groupsFile = path.join(groupIpcDir, 'available_groups.json');
696
+ fs.writeFileSync(
697
+ groupsFile,
698
+ JSON.stringify(
699
+ {
700
+ groups: visibleGroups,
701
+ lastSync: new Date().toISOString(),
702
+ },
703
+ null,
704
+ 2,
705
+ ),
706
+ );
707
+ }