@rozek/nanoclaw 0.0.4 → 0.0.6

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