forked from Lexus2016/claude-code-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
4707 lines (4313 loc) · 220 KB
/
server.js
File metadata and controls
4707 lines (4313 loc) · 220 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const path = require('path');
const fs = require('fs');
const os = require('os');
const url = require('url');
const { execSync, spawn: spawnProc } = require('child_process');
const crypto = require('crypto');
const multer = require('multer');
const Database = require('better-sqlite3');
const cookieParser = require('cookie-parser');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const auth = require('./auth');
const ClaudeCLI = require('./claude-cli');
const ClaudeSSH = require('./claude-ssh');
const { testSshConnection } = require('./claude-ssh');
const TelegramBot = require('./telegram-bot');
const TunnelManager = require('./tunnel-manager');
// ─── Load .env file (no external dependency needed) ───────────────────────
{
const envPath = path.join(process.env.APP_DIR || __dirname, '.env');
if (fs.existsSync(envPath)) {
for (const line of fs.readFileSync(envPath, 'utf-8').split(/\r?\n/)) {
const t = line.trim();
if (!t || t.startsWith('#')) continue;
const eq = t.indexOf('=');
if (eq < 0) continue;
const k = t.slice(0, eq).trim();
const v = t.slice(eq + 1).trim().replace(/^(['"])(.*)\1$/, '$2');
if (k && !(k in process.env)) process.env[k] = v;
}
console.log('✅ .env loaded');
}
}
// ─── Structured Logger ────────────────────────────────────────────────────────
// Reads LOG_LEVEL + NODE_ENV from process.env (already populated from .env above).
// Production: emits newline-delimited JSON for log aggregators (Loki, Datadog, etc.)
// Development: human-readable output with icons.
const LOG_LEVELS = { error: 0, warn: 1, info: 2, debug: 3 };
const _logLevel = LOG_LEVELS[(process.env.LOG_LEVEL || 'info').toLowerCase()] ?? LOG_LEVELS.info;
const _isProd = process.env.NODE_ENV === 'production';
const log = (() => {
function write(level, msg, meta = {}) {
if (LOG_LEVELS[level] > _logLevel) return;
const time = new Date().toISOString();
if (_isProd) {
process.stdout.write(JSON.stringify({ level, time, msg, ...meta }) + '\n');
} else {
const icons = { error: '❌', warn: '⚠️ ', info: 'ℹ️ ', debug: '🔍' };
const metaStr = Object.keys(meta).length ? ' ' + JSON.stringify(meta) : '';
process.stdout.write(`${icons[level] || ''} [${time}] ${msg}${metaStr}\n`);
}
}
return {
error: (msg, meta = {}) => write('error', msg, meta),
warn: (msg, meta = {}) => write('warn', msg, meta),
info: (msg, meta = {}) => write('info', msg, meta),
debug: (msg, meta = {}) => write('debug', msg, meta),
};
})();
const app = express();
const server = http.createServer(app);
const wss = new WebSocketServer({ noServer: true });
const PORT = process.env.PORT || 3000;
// When launched via npx/global install, cli.js sets APP_DIR to cwd so user
// data persists in the user's directory, not inside the npm cache.
const APP_DIR = process.env.APP_DIR || __dirname;
const WORKDIR = process.env.WORKDIR || path.join(APP_DIR, 'workspace');
const CONFIG_PATH = path.join(APP_DIR, 'config.json');
// ─── Security config ──────────────────────────────────────────────────────────
// Trust X-Forwarded-For when behind nginx/Caddy (needed for rate limiting)
if (process.env.TRUST_PROXY === 'true') app.set('trust proxy', 1);
// Brute-force protection on auth mutation endpoints (login / setup)
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'Too many attempts, please try again later' },
});
// Set secure flag on cookies only when served over HTTPS (behind a proxy)
const SECURE_COOKIES = process.env.TRUST_PROXY === 'true';
// Directories that authenticated users may browse/create projects in
const ALLOWED_BROWSE_ROOTS = [
path.resolve(os.homedir()),
path.resolve(WORKDIR),
path.resolve(APP_DIR),
path.resolve(__dirname),
];
const SKILLS_DIR = path.join(APP_DIR, 'skills');
const DB_PATH = path.join(APP_DIR, 'data', 'chats.db');
const PROJECTS_FILE = path.join(APP_DIR, 'data', 'projects.json');
const REMOTE_HOSTS_FILE = path.join(APP_DIR, 'data', 'remote-hosts.json');
const HOSTS_KEY_FILE = path.join(APP_DIR, 'data', 'hosts.key');
const UPLOADS_DIR = path.join(APP_DIR, 'data', 'uploads');
// Category map for bundled skills — used when skill is auto-discovered (not in config)
const BUNDLED_SKILL_META = {
'auto-mode': { label:'🎯 Auto-Skill Mode', category:'system' },
'backend': { label:'⚙️ Backend Engineer', category:'engineering' },
'api-designer': { label:'🔌 API Designer', category:'engineering' },
'frontend': { label:'🎨 Frontend Engineer', category:'engineering' },
'fullstack': { label:'🔗 Fullstack Engineer', category:'engineering' },
'devops': { label:'🐳 DevOps Engineer', category:'engineering' },
'postgres-wizard': { label:'🗄️ PostgreSQL Wizard', category:'engineering' },
'data-engineer': { label:'📊 Data Engineer', category:'engineering' },
'llm-architect': { label:'🧠 LLM Architect', category:'ai' },
'prompt-engineer': { label:'✍️ Prompt Engineer', category:'ai' },
'rag-engineer': { label:'🔍 RAG Engineer', category:'ai' },
'code-quality': { label:'💎 Code Quality', category:'quality' },
'debugging-master': { label:'🐛 Debugging Master', category:'quality' },
'code-review': { label:'👁️ Code Reviewer', category:'quality' },
'system-designer': { label:'🏗️ System Designer', category:'quality' },
'security': { label:'🔒 Security Expert', category:'security' },
'auth-specialist': { label:'🛡️ Auth Specialist', category:'security' },
'ui-design': { label:'🎭 UI Designer', category:'design' },
'ux-design': { label:'🧩 UX Designer', category:'design' },
'product-management':{ label:'📋 Product Manager', category:'product' },
'docs-engineer': { label:'📚 Docs Engineer', category:'product' },
'technical-writer': { label:'✒️ Technical Writer', category:'product' },
'investment-banking':{ label:'💼 Investment Banking Analyst', category:'finance' },
'researcher': { label:'🔬 Deep Researcher', category:'research' },
};
// ─── Server-side i18n for user-facing defaults ──────────────────────────────
const SERVER_I18N = {
uk: { newSession: 'Нова сесія', newTask: 'Нова задача' },
en: { newSession: 'New session', newTask: 'New task' },
ru: { newSession: 'Новая сессия', newTask: 'Новая задача' },
};
// All possible default session titles across languages (used to detect "untitled" sessions)
const DEFAULT_SESSION_TITLES = new Set(Object.values(SERVER_I18N).map(v => v.newSession));
const DEFAULT_TASK_TITLES = new Set(Object.values(SERVER_I18N).map(v => v.newTask));
/** Get user's preferred language from config (cached via loadMergedConfig). */
function getUserLang() {
try { return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8')).lang || 'en'; } catch { return 'en'; }
}
function i18nSession() { return SERVER_I18N[getUserLang()]?.newSession || SERVER_I18N.en.newSession; }
function i18nTask() { return SERVER_I18N[getUserLang()]?.newTask || SERVER_I18N.en.newTask; }
// ─── Global Claude Code directory (priority: global → local) ─────────────────
const GLOBAL_CLAUDE_DIR = path.join(os.homedir(), '.claude');
const GLOBAL_SKILLS_DIR = path.join(GLOBAL_CLAUDE_DIR, 'skills');
const GLOBAL_CONFIG_PATH = path.join(GLOBAL_CLAUDE_DIR, 'config.json');
const claudeCli = new ClaudeCLI({ cwd: WORKDIR });
// Expand leading ~ to os.homedir() — works on macOS, Linux and Windows
function expandTilde(v) {
if (typeof v !== 'string') return v;
if (v === '~') return os.homedir();
if (v.startsWith('~/') || v.startsWith('~\\')) return path.join(os.homedir(), v.slice(2));
return v;
}
// Recursively expand ~ in all string values of an object (used for MCP env maps)
function expandTildeInObj(obj) {
if (!obj || typeof obj !== 'object') return obj;
const out = {};
for (const [k, v] of Object.entries(obj)) out[k] = expandTilde(v);
return out;
}
// Kill a process by PID. On Windows uses `taskkill /T /F` to kill the entire
// process tree (cmd.exe → node.exe chains). On Unix sends SIGTERM.
function killByPid(pid) {
const n = Number(pid);
if (!Number.isInteger(n) || n <= 0) return;
try {
if (process.platform === 'win32') {
execSync(`taskkill /PID ${n} /T /F`, { stdio: 'ignore' });
} else {
process.kill(n, 'SIGTERM');
}
} catch {} // Process may already be dead (ESRCH)
}
[WORKDIR, SKILLS_DIR, path.dirname(DB_PATH), UPLOADS_DIR].forEach(d => {
if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });
});
// ============================================
// MODELS
// ============================================
// CLI uses its own MODEL_MAP with short aliases (haiku/sonnet/opus)
// ============================================
// CLAUDE MAX LIMITS
// ============================================
const CLAUDE_MAX_LIMITS = {
daily: 45, // ~45 messages per day on Claude Max
weekly: 225, // ~225 messages per week on Claude Max
};
// ============================================
// DATABASE MAINTENANCE SETTINGS
// ============================================
const SESSION_TTL_DAYS = parseInt(process.env.SESSION_TTL_DAYS || '30', 10); // delete sessions older than N days
const CLEANUP_INTERVAL_HOURS = parseInt(process.env.CLEANUP_INTERVAL_HOURS || '24', 10); // run cleanup every N hours
// ============================================
// DATABASE MAINTENANCE FUNCTIONS
// ============================================
/**
* Delete sessions older than SESSION_TTL_DAYS.
* Messages are auto-deleted via ON DELETE CASCADE.
*/
function cleanOldSessions() {
try {
const result = db.prepare(`DELETE FROM sessions WHERE updated_at < datetime('now', '-' || ? || ' days')`).run(SESSION_TTL_DAYS);
if (result.changes > 0) {
log.info(`[cleanup] Deleted ${result.changes} sessions older than ${SESSION_TTL_DAYS} days`);
}
return result.changes;
} catch (err) {
log.error('[cleanup] Failed to clean old sessions:', err.message);
return 0;
}
}
/**
* Run WAL checkpoint to merge WAL file into main database.
* Prevents unbounded WAL growth and keeps DB file compact.
*/
function checkpointDatabase() {
try {
// TRUNCATE mode: blocks writers briefly but fully resets WAL file
const result = db.pragma('wal_checkpoint(TRUNCATE)');
if (result[0]?.checkpointed > 0) {
log.info(`[cleanup] WAL checkpoint: moved ${result[0].checkpointed} pages to main DB`);
}
return result;
} catch (err) {
log.error('[cleanup] WAL checkpoint failed:', err.message);
return null;
}
}
/**
* Full cleanup routine: old sessions + checkpoint.
*/
function runDatabaseMaintenance() {
const deleted = cleanOldSessions();
if (deleted > 0) {
// Only checkpoint if we actually deleted something
checkpointDatabase();
}
}
// ============================================
// SESSION ID SANITIZATION
// ============================================
// Extracts a clean UUID string from potentially corrupted claude_session_id values.
// Bug: runMultiAgent fallback could store { cid, completed } objects or nested JSON
// like {"cid":"{\"cid\":\"uuid\",\"completed\":true}","completed":false}
// This helper recursively unwraps to find the actual UUID.
const UUID_RE = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
function sanitizeSessionId(val) {
if (!val) return null;
// Already a clean UUID
if (typeof val === 'string' && UUID_RE.test(val)) return val;
// Object with .cid field (from runCliSingle return value)
if (typeof val === 'object' && val !== null && val.cid) return sanitizeSessionId(val.cid);
// JSON string — try to parse and extract
if (typeof val === 'string') {
try {
const parsed = JSON.parse(val);
if (parsed && typeof parsed === 'object' && parsed.cid) return sanitizeSessionId(parsed.cid);
} catch {}
// Maybe a UUID is embedded somewhere in the string
const m = val.match(/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i);
if (m) return m[1];
}
return null;
}
// ============================================
// DATABASE
// ============================================
const db = new Database(DB_PATH);
db.pragma('journal_mode = WAL');
// Performance pragmas — safe with WAL mode
db.pragma('synchronous = NORMAL'); // WAL durability guarantees make FULL unnecessary
db.pragma('cache_size = -32000'); // 32 MB page cache
db.pragma('temp_store = MEMORY'); // Temp tables in RAM
db.pragma('foreign_keys = ON'); // Enforce FK constraints (was silently off)
db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL DEFAULT 'New session',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
claude_session_id TEXT,
active_mcp TEXT DEFAULT '[]',
active_skills TEXT DEFAULT '[]',
mode TEXT DEFAULT 'auto',
agent_mode TEXT DEFAULT 'single',
model TEXT DEFAULT 'sonnet',
workdir TEXT
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
role TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'text',
content TEXT NOT NULL,
tool_name TEXT,
agent_id TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_msg_session ON messages(session_id);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
title TEXT NOT NULL DEFAULT 'New task',
description TEXT DEFAULT '',
status TEXT NOT NULL DEFAULT 'backlog',
sort_order REAL DEFAULT 0,
session_id TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE SET NULL
);
`);
// Safe migration for existing databases
try { db.exec(`ALTER TABLE sessions ADD COLUMN workdir TEXT`); } catch {}
try { db.exec(`ALTER TABLE messages ADD COLUMN reply_to_id INTEGER REFERENCES messages(id)`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN last_user_msg TEXT`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN workdir TEXT`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN notes TEXT DEFAULT ''`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN model TEXT DEFAULT 'sonnet'`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN mode TEXT DEFAULT 'auto'`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN agent_mode TEXT DEFAULT 'single'`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN max_turns INTEGER DEFAULT 30`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN retry_count INTEGER DEFAULT 0`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN worker_pid INTEGER`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN attachments TEXT`); } catch {}
try { db.exec(`ALTER TABLE messages ADD COLUMN attachments TEXT`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN engine TEXT`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN partial_text TEXT`); } catch {}
// Task Dispatch: chain dependencies + auto-recovery columns
try { db.exec(`ALTER TABLE tasks ADD COLUMN depends_on TEXT`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN chain_id TEXT`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN source_session_id TEXT`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN failure_reason TEXT`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN task_retry_count INTEGER DEFAULT 0`); } catch {}
// Scheduled tasks: time-based triggers + recurring runs
try { db.exec(`ALTER TABLE tasks ADD COLUMN scheduled_at INTEGER`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN recurrence TEXT`); } catch {}
try { db.exec(`ALTER TABLE tasks ADD COLUMN recurrence_end_at INTEGER`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN remote_host TEXT`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN remote_workdir TEXT`); } catch {}
try { db.exec(`ALTER TABLE sessions ADD COLUMN sort_order REAL`); } catch {}
// Performance indexes — safe to re-run (IF NOT EXISTS)
try { db.exec(`CREATE INDEX IF NOT EXISTS idx_task_status ON tasks(status)`); } catch {}
try { db.exec(`CREATE INDEX IF NOT EXISTS idx_task_session ON tasks(session_id)`); } catch {}
try { db.exec(`CREATE INDEX IF NOT EXISTS idx_msg_created ON messages(created_at)`); } catch {}
try { db.exec(`CREATE INDEX IF NOT EXISTS idx_task_chain ON tasks(chain_id)`); } catch {}
// Telegram bot: telegram_devices table is created by TelegramBot constructor (single source of truth)
// Telegram Phase 2: session persistence + message source tracking
try { db.exec(`ALTER TABLE telegram_devices ADD COLUMN last_session_id TEXT`); } catch(e) {}
try { db.exec(`ALTER TABLE telegram_devices ADD COLUMN last_workdir TEXT`); } catch(e) {}
try { db.exec(`ALTER TABLE messages ADD COLUMN source TEXT DEFAULT 'web'`); } catch(e) {}
// Sanitize a value for better-sqlite3 bind parameters.
// better-sqlite3 EXPANDS arrays: each element counts as a separate bind value.
// An empty array [] contributes 0 binds, causing "Too few parameter values".
// This guard ensures only primitive types reach .run()/.get()/.all().
function sqlVal(v) {
if (v === undefined) return null;
if (v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'bigint') return v;
if (typeof v === 'boolean') return v ? 1 : 0;
if (Buffer.isBuffer(v)) return v;
// Array or object — stringify it (and log a warning for debugging)
log.warn('sqlVal: coerced non-primitive to string', { type: typeof v, isArray: Array.isArray(v), preview: JSON.stringify(v)?.substring(0, 100) });
return JSON.stringify(v);
}
// Wrap a prepared statement so .run()/.get()/.all() auto-sanitize all args via sqlVal().
// This catches the "Too few parameter values" RangeError at the source — no matter
// which code path triggers it — by ensuring arrays/objects never reach better-sqlite3.
function wrapStmt(stmt, label) {
const origRun = stmt.run.bind(stmt);
const origGet = stmt.get.bind(stmt);
const origAll = stmt.all.bind(stmt);
stmt.run = function(...args) {
const safe = args.map(sqlVal);
try { return origRun(...safe); }
catch (e) {
log.error(`stmt.run FAILED [${label}]`, { args: safe.map(a => a === null ? 'NULL' : typeof a === 'string' ? a.substring(0,60) : a), err: e.message, stack: e.stack });
throw e;
}
};
stmt.get = function(...args) {
const safe = args.map(sqlVal);
try { return origGet(...safe); }
catch (e) {
log.error(`stmt.get FAILED [${label}]`, { args: safe.map(a => a === null ? 'NULL' : typeof a === 'string' ? a.substring(0,60) : a), err: e.message });
throw e;
}
};
stmt.all = function(...args) {
// named-param objects ({w: ...}) — pass through, don't map
if (args.length === 1 && args[0] && typeof args[0] === 'object' && !Array.isArray(args[0]) && !Buffer.isBuffer(args[0])) {
return origAll(args[0]);
}
const safe = args.map(sqlVal);
try { return origAll(...safe); }
catch (e) {
log.error(`stmt.all FAILED [${label}]`, { args: safe.map(a => a === null ? 'NULL' : typeof a === 'string' ? a.substring(0,60) : a), err: e.message });
throw e;
}
};
return stmt;
}
const stmts = {
createSession: db.prepare(`INSERT INTO sessions (id,title,active_mcp,active_skills,mode,agent_mode,model,engine,workdir) VALUES (?,?,?,?,?,?,?,?,?)`),
updateTitle: db.prepare(`UPDATE sessions SET title=?,updated_at=datetime('now') WHERE id=?`),
updateClaudeId: (() => {
const _stmt = db.prepare(`UPDATE sessions SET claude_session_id=?,updated_at=datetime('now') WHERE id=?`);
const _origRun = _stmt.run.bind(_stmt);
_stmt.run = (cid, sessionId) => {
const clean = sanitizeSessionId(cid);
if (cid && !clean) log.warn('updateClaudeId: rejected non-UUID session_id', { raw: String(cid).substring(0, 80), sessionId });
return _origRun(clean, sessionId);
};
return _stmt;
})(),
updateConfig: db.prepare(`UPDATE sessions SET active_mcp=?,active_skills=?,mode=?,agent_mode=?,model=?,workdir=?,updated_at=datetime('now') WHERE id=?`),
getSessions: db.prepare(`SELECT id,title,created_at,updated_at,mode,agent_mode,model,workdir,claude_session_id FROM sessions ORDER BY CASE WHEN sort_order IS NULL THEN 0 ELSE 1 END ASC, sort_order ASC, updated_at DESC LIMIT 100`),
getSessionsByWorkdir: db.prepare(`SELECT id,title,created_at,updated_at,mode,agent_mode,model,workdir,claude_session_id FROM sessions WHERE workdir=? ORDER BY CASE WHEN sort_order IS NULL THEN 0 ELSE 1 END ASC, sort_order ASC, updated_at DESC LIMIT 100`),
getSession: db.prepare(`SELECT * FROM sessions WHERE id=?`),
deleteSession: db.prepare(`DELETE FROM sessions WHERE id=?`),
addMsg: db.prepare(`INSERT INTO messages (session_id,role,type,content,tool_name,agent_id,reply_to_id,attachments) VALUES (?,?,?,?,?,?,?,?)`),
addTelegramMsg: db.prepare(`INSERT INTO messages (session_id,role,type,content,tool_name,agent_id,reply_to_id,attachments,source) VALUES (?,?,?,?,?,?,?,?,'telegram')`),
getMsgs: db.prepare(`SELECT * FROM messages WHERE session_id=? ORDER BY id ASC`),
// Lightweight: strip tool content (frontend only needs tool_name + agent_id for badge counts)
getMsgsLite: db.prepare(`SELECT id, session_id, role, type, CASE WHEN type='tool' THEN '' ELSE content END AS content, tool_name, agent_id, created_at, reply_to_id, attachments, source FROM messages WHERE session_id=? ORDER BY id ASC`),
getMsgsPaginated: db.prepare(`SELECT * FROM messages WHERE session_id=? AND (type IS NULL OR type != 'tool') ORDER BY id ASC LIMIT ? OFFSET ?`),
countMsgs: db.prepare(`SELECT COUNT(*) AS total FROM messages WHERE session_id=? AND (type IS NULL OR type != 'tool')`),
setLastUserMsg: db.prepare(`UPDATE sessions SET last_user_msg=? WHERE id=?`),
clearLastUserMsg: db.prepare(`UPDATE sessions SET last_user_msg=NULL, retry_count=0 WHERE id=?`),
setPartialText: db.prepare(`UPDATE sessions SET partial_text=? WHERE id=?`),
getInterrupted: db.prepare(`SELECT id, title, last_user_msg FROM sessions WHERE last_user_msg IS NOT NULL`),
incrementRetry: db.prepare(`UPDATE sessions SET retry_count = COALESCE(retry_count, 0) + 1 WHERE id=?`),
// Tasks (Kanban)
getTasks: db.prepare(`
SELECT t.*, s.title as sess_title, s.claude_session_id, s.model as sess_model,
s.updated_at as sess_updated_at, COALESCE(s.retry_count, 0) as retry_count
FROM tasks t LEFT JOIN sessions s ON t.session_id = s.id
WHERE (@w IS NULL OR t.workdir = @w)
ORDER BY t.sort_order ASC, t.created_at ASC
`),
getTask: db.prepare(`SELECT * FROM tasks WHERE id=?`),
createTask: db.prepare(`INSERT INTO tasks (id,title,description,notes,status,sort_order,session_id,workdir,model,mode,agent_mode,max_turns,attachments,depends_on,chain_id,source_session_id,scheduled_at,recurrence,recurrence_end_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),
updateTask: db.prepare(`UPDATE tasks SET title=?,description=?,notes=?,status=?,sort_order=?,session_id=?,workdir=?,model=?,mode=?,agent_mode=?,max_turns=?,attachments=?,depends_on=?,chain_id=?,source_session_id=?,scheduled_at=?,recurrence=?,recurrence_end_at=?,updated_at=datetime('now') WHERE id=?`),
patchTaskStatus: db.prepare(`UPDATE tasks SET status=?,sort_order=?,updated_at=datetime('now') WHERE id=?`),
deleteTask: db.prepare(`DELETE FROM tasks WHERE id=?`),
deleteTasksBySession: db.prepare(`DELETE FROM tasks WHERE session_id=?`),
countTasksBySession: db.prepare(`SELECT COUNT(*) as n FROM tasks WHERE session_id=?`),
getTasksEtag: db.prepare(`SELECT COALESCE(MAX(updated_at),'') as ts, COUNT(*) as n FROM tasks`),
// processQueue hot-path — prepared once, reused every 60 s
getTodoTasks: db.prepare(`SELECT * FROM tasks WHERE status='todo' AND (scheduled_at IS NULL OR scheduled_at <= unixepoch()) ORDER BY sort_order ASC, created_at ASC`),
getInProgressTasks: db.prepare(`SELECT * FROM tasks WHERE status='in_progress'`),
getTasksByChain: db.prepare(`SELECT * FROM tasks WHERE chain_id=? ORDER BY sort_order ASC`),
// startTask hot-path
setTaskSession: db.prepare(`UPDATE tasks SET session_id=?, updated_at=datetime('now') WHERE id=?`),
setTaskInProgress: db.prepare(`UPDATE tasks SET status='in_progress', updated_at=datetime('now') WHERE id=?`),
// Stats queries
activeAgents: db.prepare(`
SELECT DISTINCT agent_id
FROM messages
WHERE role = 'assistant'
AND agent_id IS NOT NULL
AND datetime(created_at) >= datetime('now', '-5 minutes')
`),
dailyMessages: db.prepare(`
SELECT COUNT(*) AS count
FROM messages
WHERE role = 'user'
AND date(created_at) = date('now')
`),
weeklyMessages: db.prepare(`
SELECT COUNT(*) AS count
FROM messages
WHERE role = 'user'
AND datetime(created_at) >= datetime('now', '-7 days')
`),
contextTokens: db.prepare(`
SELECT COALESCE(SUM(LENGTH(content)), 0) AS total
FROM messages
WHERE session_id = ?
`),
// getSession endpoint helpers — pre-compiled to avoid re-prepare on every load
hasRunningTask: db.prepare(`SELECT id FROM tasks WHERE session_id=? AND status='in_progress' LIMIT 1`),
getChainTasks: db.prepare(`SELECT id, title, status, depends_on, chain_id FROM tasks WHERE source_session_id=? ORDER BY sort_order ASC`),
};
// Auto-sanitize ALL prepared statements — prevents "Too few parameter values"
// on every code path (chat, tasks, queue, reconnect, telegram, etc.)
for (const [name, stmt] of Object.entries(stmts)) wrapStmt(stmt, name);
function genId() { return Date.now().toString(36) + Math.random().toString(36).slice(2, 8); }
// ─── Active task registry ─────────────────────────────────────────────────
// Keeps running Claude subprocesses alive when the browser tab closes/reloads.
// Key: localSessionId, Value: { proxy, abortController, cleanupTimer }
const activeTasks = new Map();
const TASK_IDLE_TIMEOUT_MS = 30 * 60 * 1000; // abort orphaned tasks after 30 min
// ─── Session Watchers (real-time task worker → chat streaming) ────────────
// When chat client opens a session, it subscribes via WS. Task worker broadcasts
// text/tool/done events to all watchers of that session.
const sessionWatchers = new Map(); // sessionId → Set<WebSocket>
const taskBuffers = new Map(); // taskId → accumulated text (for late subscribers)
const chatBuffers = new Map(); // sessionId → accumulated text for direct chat (for catch-up on reconnect)
const MAX_CHAT_BUFFER = 2 * 1024 * 1024; // 2 MB cap per session — prevents unbounded growth
const sessionQueues = new Map(); // sessionId → [msg, ...] — queue persistence across WS reconnects (page refresh)
// ─── Ask User (Internal MCP) ─────────────────────────────────────────────
// Pending user questions: requestId → { resolve, sessionId, timer, question, options, inputType }
const pendingAskUser = new Map();
const ASK_USER_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
const ASK_USER_SECRET = require('crypto').randomBytes(16).toString('hex');
// ─── Notify User (Internal MCP) ──────────────────────────────────────────
const NOTIFY_SECRET = require('crypto').randomBytes(16).toString('hex');
// ─── Set UI State (Internal MCP) ──────────────────────────────────────────
const SET_UI_STATE_SECRET = require('crypto').randomBytes(16).toString('hex');
function broadcastToSession(sessionId, data) {
const watchers = sessionWatchers.get(sessionId);
if (!watchers?.size) return;
const msg = JSON.stringify(data);
for (const w of watchers) {
if (w.readyState === 1) {
try { w.send(msg); } catch { watchers.delete(w); }
} else if (w.readyState > 1) {
watchers.delete(w); // CLOSING/CLOSED — won't recover
}
}
if (!watchers.size) sessionWatchers.delete(sessionId);
}
// ─── Kanban Task Queue Worker ─────────────────────────────────────────────
const MAX_TASK_WORKERS = Math.max(1, parseInt(process.env.MAX_TASK_WORKERS || '5', 10));
const taskRunning = new Set(); // task IDs currently executing
const runningTaskAborts = new Map(); // taskId → AbortController
const stoppingTasks = new Set(); // task IDs being manually stopped (onDone must not overwrite status)
async function startTask(task) {
if (taskRunning.has(task.id)) return;
taskRunning.add(task.id);
console.log(`[taskWorker] starting "${task.title}" (${task.id})`);
let _retryBackoffMs = 0; // Set by auto-retry logic, used by finally for processQueue delay
let sessionId = task.session_id;
let _taskStartedAt = Date.now();
try {
// Create session + link task + mark in_progress — all atomic
db.transaction(() => {
if (!sessionId) {
sessionId = genId();
stmts.createSession.run(sessionId, task.title.substring(0, 200), '[]', '[]', task.mode || 'auto', task.agent_mode || 'single', task.model || 'sonnet', 'cli', task.workdir || null);
stmts.setTaskSession.run(sessionId, task.id);
}
stmts.setTaskInProgress.run(task.id);
})();
// Build prompt
const parts = [task.title];
if (task.description?.trim()) parts.push(task.description.trim());
if (task.notes?.trim()) parts.push(`---\nУточнення:\n${task.notes.trim()}`);
// Write attachment files to workspace so Claude Code can read them
if (task.attachments) {
try {
const atts = JSON.parse(task.attachments);
if (Array.isArray(atts) && atts.length) {
const attDir = path.join(task.workdir || WORKDIR, '.kanban-attachments', task.id);
fs.mkdirSync(attDir, { recursive: true });
const names = [];
for (const att of atts) {
if (att.base64 && att.name) {
// Sanitize filename: strip directory traversal, keep only the base name
const safeName = path.basename(att.name);
if (!safeName) continue;
fs.writeFileSync(path.join(attDir, safeName), Buffer.from(att.base64, 'base64'));
names.push(safeName);
}
}
if (names.length) {
parts.push(`---\nAttached files (in .kanban-attachments/${task.id}/):\n${names.map(n => `- ${n}`).join('\n')}`);
}
}
} catch (e) { console.error('[taskWorker] attachments write error:', e); }
}
// Chain task: add dependency context as safety net (primary context via --resume)
if (task.depends_on) {
try {
const deps = JSON.parse(task.depends_on);
const depNames = deps.map(depId => { const dep = stmts.getTask.get(depId); return dep ? dep.title : null; }).filter(Boolean);
if (depNames.length) {
parts.push(`---\nPrevious tasks completed: ${depNames.join(', ')}\nTheir results are in your session context via --resume.`);
}
} catch {}
}
const prompt = parts.join('\n\n') + TASK_VERIFICATION_SUFFIX;
_taskStartedAt = Date.now(); // reset to accurate time after prompt building
// Check if this is a restart: only skip saving if the LAST user message
// has the exact same prompt (crash recovery). Previously checked for ANY
// user message which broke when a new task reused an existing session.
const lastUserMsg = db.prepare(`SELECT id, content FROM messages WHERE session_id=? AND role='user' ORDER BY id DESC LIMIT 1`).get(sessionId);
const isRetry = lastUserMsg && lastUserMsg.content === prompt;
if (!isRetry) {
// New task or different prompt — save user message
try { stmts.addMsg.run(sessionId, 'user', 'text', prompt, null, null, null, null); }
catch (e) { log.error('startTask addMsg failed', { sessionId, promptLen: prompt.length, err: e.message, stack: e.stack }); throw e; }
} else {
// Restart after crash with same prompt — increment retry counter, don't duplicate
try { stmts.incrementRetry.run(sessionId); } catch (e) { log.error('startTask incrementRetry failed', { err: e.message }); }
}
// Resume existing claude session if any
const session = stmts.getSession.get(sessionId);
const claudeSessionId = sanitizeSessionId(session?.claude_session_id) || null;
const cli = new ClaudeCLI({ cwd: task.workdir || WORKDIR });
const taskAbort = new AbortController();
runningTaskAborts.set(task.id, taskAbort);
let fullText = '', newCid = claudeSessionId, hasError = false;
taskBuffers.set(task.id, '');
// Notify watchers — use task_retrying for restarts, task_started for first run
// Include prompt so client can show user message bubble during live streaming
if (isRetry) {
const retryCount = session?.retry_count || 1;
broadcastToSession(sessionId, { type: 'task_retrying', taskId: task.id, title: task.title, prompt, retryCount, tabId: sessionId });
} else {
broadcastToSession(sessionId, { type: 'task_started', taskId: task.id, title: task.title, prompt, tabId: sessionId });
}
// Auto-continue loop: keep resuming until agent completes or budget exhausted
let taskContinueCount = 0;
let currentTaskPrompt = prompt;
let currentTaskCid = claudeSessionId;
let lastTaskResult = null;
const effectiveTaskMaxTurns = task.max_turns || 30;
while (true) {
lastTaskResult = null;
hasError = false; // Reset per iteration — only the LAST iteration's error state matters for final status
const stream = cli.send({ prompt: currentTaskPrompt, sessionId: currentTaskCid, model: session?.model || task.model || 'sonnet', maxTurns: effectiveTaskMaxTurns, abortController: taskAbort });
// Save subprocess PID so startup recovery can kill orphans on restart
if (stream.process?.pid) {
db.prepare(`UPDATE tasks SET worker_pid=? WHERE id=?`).run(stream.process.pid, task.id);
}
await new Promise(resolve => {
stream
.onText(t => {
fullText += t;
taskBuffers.set(task.id, (taskBuffers.get(task.id) || '') + t);
broadcastToSession(sessionId, { type: 'text', text: t, tabId: sessionId });
})
.onTool((name, inp) => {
try { stmts.addMsg.run(sessionId, 'assistant', 'tool', (inp || '').substring(0, 500), name, null, null, null); } catch {}
if (name !== 'ask_user' && name !== 'notify_user' && name !== 'set_ui_state') {
broadcastToSession(sessionId, { type: 'tool', tool: name, input: (inp || '').substring(0, 600), tabId: sessionId });
}
})
.onSessionId(sid => { newCid = sid; currentTaskCid = sid; try { stmts.updateClaudeId.run(sid, sessionId); } catch {} })
.onResult(r => { lastTaskResult = r; })
.onError(err => {
hasError = true;
console.error(`[taskWorker] task ${task.id} error:`, err);
try { stmts.addMsg.run(sessionId, 'assistant', 'text', `❌ ${err.substring(0, 500)}`, null, null, null, null); } catch {}
broadcastToSession(sessionId, { type: 'error', error: err.substring(0, 500), tabId: sessionId });
})
.onDone(sid => {
if (sid) { newCid = sid; currentTaskCid = sid; }
resolve();
});
});
// ✅ Success — agent finished naturally
if (lastTaskResult?.subtype === 'success') break;
// 💰 Budget limit — can't continue
if (lastTaskResult?.subtype === 'error_max_budget_usd') break;
// 🛑 User stopped or aborted
if (taskAbort?.signal?.aborted || stoppingTasks.has(task.id)) break;
// 🔄 Auto-continue budget exhausted
if (taskContinueCount >= MAX_AUTO_CONTINUES) {
console.log(`[taskWorker] task ${task.id}: auto-continue budget exhausted (${MAX_AUTO_CONTINUES})`);
break;
}
// 🔄 Auto-continue — agent stopped but didn't finish
taskContinueCount++;
console.log(`[taskWorker] task ${task.id}: auto-continuing (${taskContinueCount}/${MAX_AUTO_CONTINUES}), reason: ${lastTaskResult?.subtype || 'unknown'}`);
const notice = `\n⏳ Auto-continuing (${taskContinueCount}/${MAX_AUTO_CONTINUES})...\n`;
fullText += notice;
taskBuffers.set(task.id, (taskBuffers.get(task.id) || '') + notice);
broadcastToSession(sessionId, { type: 'text', text: notice, tabId: sessionId });
currentTaskPrompt = 'Continue where you left off. Complete the remaining work. When finished, run the MANDATORY POST-TASK VERIFICATION from your original instructions.';
}
// After loop: persist text and determine task status
try {
if (newCid) { try { stmts.updateClaudeId.run(newCid, sessionId); } catch (e) { log.error('taskWorker updateClaudeId failed', { cid: String(newCid).substring(0,50), sessionId, err: e.message, stack: e.stack }); } }
if (fullText) { try { stmts.addMsg.run(sessionId, 'assistant', 'text', fullText, null, null, null, null); } catch (e) { log.error('taskWorker addMsg(assistant) failed', { sessionId, textLen: fullText.length, err: e.message, stack: e.stack }); } }
const wasStopped = stoppingTasks.has(task.id);
stoppingTasks.delete(task.id);
if (!wasStopped) {
const isSuccess = lastTaskResult?.subtype === 'success' && !hasError;
const isRateLimited = hasError && (fullText.includes('rate_limit') || fullText.includes('overloaded') || fullText.includes('Too many'));
const MAX_CHAIN_RETRIES = 2;
if (isSuccess) {
// ✅ Success
db.prepare(`UPDATE tasks SET status='done', failure_reason=NULL, worker_pid=NULL, updated_at=datetime('now') WHERE id=?`)
.run(task.id);
db.prepare(`UPDATE sessions SET retry_count=0 WHERE id=?`).run(sessionId);
log.info(`[taskWorker] task ${task.id}: done`);
// 🔄 Auto-schedule next occurrence for recurring tasks
scheduleNextRun(task);
// Notify Telegram about completed task
if (telegramBot && telegramBot.isRunning()) {
telegramBot.notifyTaskComplete({
sessionId,
title: task.title || 'Task',
status: 'done',
duration: Date.now() - _taskStartedAt,
}).catch(() => {});
}
} else if (task.chain_id && (task.task_retry_count || 0) < MAX_CHAIN_RETRIES) {
// 🔄 Auto-retry for chain tasks — don't give up on first failure
const reason = isRateLimited ? 'rate_limited' : 'agent_incomplete';
_retryBackoffMs = isRateLimited ? Math.min(60000 * ((task.task_retry_count || 0) + 1), 300000) : 3000;
db.prepare(`UPDATE tasks SET status='todo', failure_reason=?, task_retry_count=COALESCE(task_retry_count,0)+1, worker_pid=NULL, updated_at=datetime('now') WHERE id=?`)
.run(reason, task.id);
log.warn(`[taskWorker] task ${task.id}: chain retry ${(task.task_retry_count||0)+1}/${MAX_CHAIN_RETRIES}, reason: ${reason}, backoff: ${_retryBackoffMs}ms`);
if (task.source_session_id) {
const _ctx = getNotificationContext(task.source_session_id);
broadcastToSession(task.source_session_id, {
type: 'notification', level: 'warn',
title: `Retrying: "${task.title}"`,
detail: `Attempt ${(task.task_retry_count||0)+2}/${MAX_CHAIN_RETRIES+1}${isRateLimited ? '. Rate limited, backing off.' : ''}`,
chainTaskId: task.id, chainStatus: 'retry',
sessionTitle: _ctx.sessionTitle, projectName: _ctx.projectName,
});
}
} else {
// ❌ Failed — retries exhausted or not a chain task
const reason = isRateLimited ? 'rate_limited' : 'agent_incomplete';
db.prepare(`UPDATE tasks SET status='cancelled', failure_reason=?, worker_pid=NULL, updated_at=datetime('now') WHERE id=?`)
.run(reason, task.id);
log.error(`[taskWorker] task ${task.id}: cancelled (${reason}, subtype: ${lastTaskResult?.subtype || 'unknown'})`);
// Notify source chat about the failed task
if (task.source_session_id) {
const _ctx = getNotificationContext(task.source_session_id);
broadcastToSession(task.source_session_id, {
type: 'notification', level: 'error',
title: `Task failed: "${task.title}"`,
detail: task.chain_id ? `Retries exhausted (${reason}). Dependent tasks will be cancelled.` : reason,
chainTaskId: task.id, chainStatus: 'cancelled',
sessionTitle: _ctx.sessionTitle, projectName: _ctx.projectName,
});
}
// Notify Telegram about failed task
if (telegramBot && telegramBot.isRunning()) {
telegramBot.notifyTaskComplete({
sessionId,
title: task.title || 'Task',
status: 'error',
duration: Date.now() - _taskStartedAt,
error: reason,
}).catch(() => {});
}
// Cascade cancel of dependents happens in next processQueue() run
}
} else {
// User manually stopped — mark as user_cancelled, cascade will follow
db.prepare(`UPDATE tasks SET status='cancelled', failure_reason='user_cancelled', worker_pid=NULL, updated_at=datetime('now') WHERE id=?`)
.run(task.id);
log.info(`[taskWorker] task ${task.id}: stopped by user`);
}
} catch (e) {
console.error(`[taskWorker] task ${task.id} onDone DB error:`, e);
}
broadcastToSession(sessionId, { type: 'done', tabId: sessionId, taskId: task.id, duration: Date.now() - _taskStartedAt });
} catch (err) {
log.error(`[taskWorker] task ${task.id} exception`, { message: err.message, name: err.name, stack: err.stack });
try {
// Exception: auto-retry for chain tasks, cancel for non-chain
const failureMsg = `${err.name}: ${err.message}`;
if (task.chain_id && (task.task_retry_count || 0) < 2) {
db.prepare(`UPDATE tasks SET status='todo', failure_reason=?, task_retry_count=COALESCE(task_retry_count,0)+1, worker_pid=NULL, updated_at=datetime('now') WHERE id=?`).run(failureMsg, task.id);
_retryBackoffMs = 5000;
log.warn(`[taskWorker] task ${task.id}: exception → auto-retry`);
} else {
db.prepare(`UPDATE tasks SET status='cancelled', failure_reason=?, worker_pid=NULL, updated_at=datetime('now') WHERE id=?`).run(failureMsg, task.id);
}
} catch {}
// Send done so the client doesn't wait forever for an event that will never arrive.
if (sessionId) broadcastToSession(sessionId, { type: 'done', tabId: sessionId, taskId: task.id, duration: Date.now() - _taskStartedAt });
} finally {
taskBuffers.delete(task.id);
taskRunning.delete(task.id);
runningTaskAborts.delete(task.id);
setTimeout(processQueue, _retryBackoffMs || 500);
}
}
// ─── Recurring task scheduler ────────────────────────────────────────────────
function calcNextRun(scheduled_at, recurrence) {
const d = new Date(scheduled_at * 1000);
if (recurrence === 'hourly') d.setHours(d.getHours() + 1);
if (recurrence === 'daily') d.setDate(d.getDate() + 1);
if (recurrence === 'weekly') d.setDate(d.getDate() + 7);
if (recurrence === 'monthly') d.setMonth(d.getMonth() + 1);
return Math.floor(d.getTime() / 1000);
}
function scheduleNextRun(task) {
if (!task.recurrence || !task.scheduled_at) return;
const now = Math.floor(Date.now() / 1000);
// Find next future occurrence — handles server downtime gaps gracefully.
// Cap iterations to prevent runaway loops for very old tasks.
let next = calcNextRun(task.scheduled_at, task.recurrence);
let guard = 0;
while (next <= now && guard < 10000) { next = calcNextRun(next, task.recurrence); guard++; }
if (guard >= 10000) { log.warn(`[schedule] Too many iterations for "${task.title}", skipping`); return; }
// Respect end date
if (task.recurrence_end_at && next > task.recurrence_end_at) {
log.info(`[schedule] Recurrence series ended for "${task.title}"`);
return;
}
const newId = genId();
stmts.createTask.run(
newId, task.title, task.description || '', task.notes || '', 'todo', task.sort_order || 0,
task.session_id || null, task.workdir || null, task.model || 'sonnet',
task.mode || 'auto', task.agent_mode || 'single', task.max_turns || 30,
null, null, null, null,
next, task.recurrence, task.recurrence_end_at || null
);
log.info(`[schedule] Next run queued: "${task.title}" → ${new Date(next * 1000).toISOString()}`);
}
function processQueue() {
const todo = stmts.getTodoTasks.all();
if (!todo.length) return;
const inProg = stmts.getInProgressTasks.all();
// Sessions currently occupied (in_progress or just started by taskRunning)
const occupiedSids = new Set(inProg.filter(t => t.session_id).map(t => t.session_id));
// Workdir-level lock: prevents parallel chain tasks from writing to the same directory concurrently
const occupiedWorkdirs = new Set(inProg.filter(t => t.workdir).map(t => t.workdir));
// Count independent running tasks (null session_id)
let indepRunning = inProg.filter(t => !t.session_id).length;
const startedSids = new Set();
const startedWorkdirs = new Set();
for (const task of todo) {
if (taskRunning.has(task.id)) continue;
// Dependency gate: check depends_on before starting chain tasks
if (task.depends_on) {
try {
const deps = JSON.parse(task.depends_on);
if (deps.length) {
const failedDep = deps.find(depId => {
const dep = stmts.getTask.get(depId);
return dep && dep.status === 'cancelled';
});
if (failedDep) {
// Cascade cancel: dependency failed, this task can't run
db.prepare(`UPDATE tasks SET status='cancelled', failure_reason='dep_failed', notes=?, updated_at=datetime('now') WHERE id=?`)
.run(`Blocked: dependency ${failedDep} failed`, task.id);
log.warn('Task cascade-cancelled', { taskId: task.id, failedDep });
if (task.source_session_id) {
const _ctx = getNotificationContext(task.source_session_id);
broadcastToSession(task.source_session_id, {
type: 'notification', level: 'warn',
title: `Task cancelled: "${task.title}"`,
detail: 'Dependency failed',
chainTaskId: task.id, chainStatus: 'cancelled',
sessionTitle: _ctx.sessionTitle, projectName: _ctx.projectName,
});
}
continue;
}
const allDone = deps.every(depId => {
const dep = stmts.getTask.get(depId);
return dep && dep.status === 'done';
});
if (!allDone) continue; // deps not ready yet
}
} catch (e) { log.error('depends_on parse error', { taskId: task.id, error: e.message }); }
}
// Workdir lock: only for chain tasks — prevents parallel chains from conflicting in the same directory.
// Independent tasks (no chain_id) can run in parallel per workdir; the user explicitly chose concurrency.
if (task.chain_id && task.workdir && (occupiedWorkdirs.has(task.workdir) || startedWorkdirs.has(task.workdir))) continue;
if (task.session_id) {
// Shared session: one at a time per session
if (!occupiedSids.has(task.session_id) && !startedSids.has(task.session_id)) {
occupiedSids.add(task.session_id);
startedSids.add(task.session_id);
if (task.workdir) startedWorkdirs.add(task.workdir);
startTask(task).catch(e => console.error('[taskWorker]', e));
}
} else {
// Independent: up to MAX_TASK_WORKERS concurrent
if (indepRunning < MAX_TASK_WORKERS) {
indepRunning++;
if (task.workdir) startedWorkdirs.add(task.workdir);
startTask(task).catch(e => console.error('[taskWorker]', e));
}
}
}
}
// Run every 15s (fast enough to pick up unblocked tasks promptly,
// light enough to be negligible — just two SELECT queries on SQLite)
setInterval(processQueue, 15000);
// Kick off on startup — smart recovery for in_progress tasks
setTimeout(() => {
const stuck = db.prepare(`SELECT * FROM tasks WHERE status='in_progress'`).all();
for (const task of stuck) {
// Step 1: Kill orphaned subprocess to prevent double-execution.
// When Node restarts, spawned 'claude' processes become OS orphans and keep running.
// We kill them before deciding what to do with the task.
if (task.worker_pid) {
killByPid(task.worker_pid);
console.log(`[startup] sent kill to orphan PID ${task.worker_pid} for task "${task.title}"`);
}
// Step 2: Determine if the task actually completed.
// Assistant text is only written to DB on onDone — so its presence means success.
let newStatus = 'todo'; // default: retry (task was interrupted)
if (task.chain_id) {
// Chain task: ALWAYS retry. Shared session has messages from other tasks in the
// chain, so the "has assistant message" heuristic gives false positives.
// --resume will recover full context from the shared Claude session.
newStatus = 'todo';
} else if (task.session_id) {
const assistantMsg = db.prepare(
`SELECT id FROM messages WHERE session_id=? AND role='assistant' AND type='text' LIMIT 1`
).get(task.session_id);
if (assistantMsg) newStatus = 'done'; // completed before/during restart
}
db.prepare(`UPDATE tasks SET status=?, worker_pid=NULL, updated_at=datetime('now') WHERE id=?`)
.run(newStatus, task.id);
console.log(`[startup] recovered task "${task.title}" (${task.id}): in_progress → ${newStatus}`);
}
processQueue();
}, 3000);
class WsProxy {
constructor(ws) { this._ws = ws; this._buffer = []; }
send(data) {
if (this._ws && this._ws.readyState === 1) {
this._ws.send(data);
} else if (this._buffer.length < 1000) {
this._buffer.push(data);
}
}
attach(newWs) {
this._ws = newWs;
const buf = this._buffer.splice(0);
for (const msg of buf) { try { newWs.send(msg); } catch {} }
}
detach() { this._ws = null; }
}
// ─── Telegram Proxy (duck-typed WsProxy for Telegram bot streaming) ──────────
class TelegramProxy {
constructor(bot, chatId, sessionId, userId) {
this._bot = bot;
this._chatId = chatId;
this._sessionId = sessionId;
this._userId = userId;
this._buffer = '';
this._progressMsgId = null;
this._updateTimer = null;
this._lastEditAt = 0;
this._toolsUsed = [];
this._finished = false;
// Typing indicator — sends "typing..." action every 4s
this._typingInterval = setInterval(() => {
this._bot._callApi('sendChatAction', { chat_id: this._chatId, action: 'typing' }).catch(() => {});
}, 4000);
// Safety net: auto-stop typing after 30 min to prevent interval leak if
// neither _finalize nor _sendError are called (e.g. subprocess crash)
this._typingSafetyTimer = setTimeout(() => this._stopTyping(), 30 * 60 * 1000);
// Send initial typing action immediately
this._bot._callApi('sendChatAction', { chat_id: this._chatId, action: 'typing' }).catch(() => {});
}
_stopTyping() {