-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1411 lines (1236 loc) · 46.4 KB
/
Copy pathindex.js
File metadata and controls
1411 lines (1236 loc) · 46.4 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
#!/usr/bin/env node
import { execSync, execFileSync, execFile, spawn } from 'node:child_process';
import https from 'node:https';
import http from 'node:http';
import crypto from 'node:crypto';
import { createInterface } from 'node:readline';
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import nacl from 'tweetnacl';
import naclUtil from 'tweetnacl-util';
const { encodeBase64, decodeBase64, encodeUTF8, decodeUTF8 } = naclUtil;
const __dirname = dirname(fileURLToPath(import.meta.url));
// === Config ===
const ATS_BIN = '/ml2/nanobot/.nvm/versions/node/v24.13.0/bin/ats';
const NANOBOT_BIN = '/ml2/nanobot/.nvm/versions/node/v24.13.0/bin/claude';
const CHANNEL = 'ada-dispatch';
const TELEGRAM_CHAT_ID = '6644666619';
const LEASE_MS = 14400000; // 4 hours
const NANOBOT_TIMEOUT_MS = 14400000; // 4 hours (matches lease)
const MAX_TASK_RETRIES = 3;
const ACTOR_FLAGS = ['--actor-type', 'agent', '--actor-id', 'ada-dispatch', '--actor-name', 'Ada Dispatch'];
const INTERNAL_PAYLOAD_FIELDS = ['callback_url', 'quiet', 'encrypted', 'sender', 'ciphertext', 'nonce', 'pubkey', 'from', 'depends_on'];
const DISPATCH_KEYS_PATH = join(__dirname, 'dispatch-keys.json');
const TRUSTED_KEYS_PATH = join(__dirname, 'trusted-keys.json');
const PENDING_REGISTRATIONS_PATH = join(__dirname, 'pending-registrations.json');
const CONFIG_PATH = join(__dirname, 'config.json');
// Watch reconnection
const WATCH_RECONNECT_BASE_MS = 2000;
const WATCH_RECONNECT_MAX_MS = 60000;
// Track retry counts per task ID to detect poison tasks
const taskRetries = new Map();
// Track tasks currently being processed to avoid duplicates
const processingTasks = new Set();
// === GPU semaphore ===
// Only GPU-heavy tasks (music generation, TTS, etc.) are serialized.
// Non-GPU tasks run concurrently without waiting.
const GPU_CONCURRENCY = parseInt(process.env.GPU_CONCURRENCY, 10) || 1;
const gpuQueue = []; // FIFO queue of { resolve } waiting for a GPU slot
let gpuSlotsUsed = 0; // how many GPU slots are currently held
function gpuAcquire() {
if (gpuSlotsUsed < GPU_CONCURRENCY) {
gpuSlotsUsed++;
return Promise.resolve();
}
return new Promise((resolve) => gpuQueue.push({ resolve }));
}
function gpuRelease() {
if (gpuQueue.length > 0) {
const next = gpuQueue.shift();
next.resolve();
// slot count stays the same — transferred to next waiter
} else {
gpuSlotsUsed = Math.max(0, gpuSlotsUsed - 1);
}
}
function isGpuTask(task) {
// Explicit payload override: { gpu: false } skips GPU queue
if (task.payload && task.payload.gpu === false) return false;
if (task.payload && task.payload.gpu === true) return true;
// Keyword heuristic fallback (narrow keywords only — avoids false positives)
const text = ((task.title || '') + ' ' + (task.description || '') + ' ' + JSON.stringify(task.payload || {})).toLowerCase();
const gpuKeywords = ['ace-step', 'acestep', 'cover mode', 'qwen tts', 'qwen3-tts'];
return gpuKeywords.some(kw => text.includes(kw));
}
// === Dependency tracking ===
// Tasks waiting for dependencies to complete. Map<taskId, task>
const waitingOnDeps = new Map();
const DEP_CHECK_INTERVAL_MS = 10000; // Re-check waiting tasks every 10s
let depCheckInterval = null;
let running = true;
// === Config management ===
function loadConfig() {
const defaults = { require_encryption: false };
if (!existsSync(CONFIG_PATH)) return defaults;
try {
return { ...defaults, ...JSON.parse(readFileSync(CONFIG_PATH, 'utf-8')) };
} catch { return defaults; }
}
// === Logging ===
function log(level, msg, data = {}) {
const entry = { ts: new Date().toISOString(), level, msg, ...data };
process.stdout.write(JSON.stringify(entry) + '\n');
}
// === Telegram ===
const TELEGRAM_TOKEN = '8516158841:AAEiuEc956VdL0i6NIRqJ8o606ZYGV4AmDU';
function telegram(text) {
const body = JSON.stringify({ chat_id: TELEGRAM_CHAT_ID, text, parse_mode: 'HTML' });
const req = https.request(`https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
timeout: 10000,
}, (res) => {
res.resume();
if (res.statusCode !== 200) log('warn', 'Telegram API error', { statusCode: res.statusCode });
});
req.on('error', (err) => log('warn', 'Telegram send failed', { error: err.message }));
req.write(body);
req.end();
}
function shouldNotify(task) {
return !task.payload?.quiet;
}
// === Key management ===
function loadDispatchKeys() {
if (!existsSync(DISPATCH_KEYS_PATH)) return null;
return JSON.parse(readFileSync(DISPATCH_KEYS_PATH, 'utf-8'));
}
function ensureDispatchKeys() {
let keys = loadDispatchKeys();
if (!keys) {
keys = generateKeypair();
log('info', 'Generated dispatch keypair on first run', { publicKey: keys.publicKey });
}
return keys;
}
function loadTrustedKeys() {
if (!existsSync(TRUSTED_KEYS_PATH)) return {};
return JSON.parse(readFileSync(TRUSTED_KEYS_PATH, 'utf-8'));
}
function saveTrustedKeys(trusted) {
writeFileSync(TRUSTED_KEYS_PATH, JSON.stringify(trusted, null, 2) + '\n');
}
function loadPendingRegistrations() {
if (!existsSync(PENDING_REGISTRATIONS_PATH)) return {};
return JSON.parse(readFileSync(PENDING_REGISTRATIONS_PATH, 'utf-8'));
}
function savePendingRegistrations(pending) {
writeFileSync(PENDING_REGISTRATIONS_PATH, JSON.stringify(pending, null, 2) + '\n');
}
function generateKeypair() {
const kp = nacl.box.keyPair();
const keys = {
publicKey: encodeBase64(kp.publicKey),
secretKey: encodeBase64(kp.secretKey),
};
writeFileSync(DISPATCH_KEYS_PATH, JSON.stringify(keys, null, 2) + '\n');
return keys;
}
function fingerprint(publicKeyBase64) {
const hash = crypto.createHash('sha256').update(publicKeyBase64).digest('hex');
return hash.slice(0, 16);
}
function addTrustedKey(name, publicKey) {
const decoded = decodeBase64(publicKey);
if (decoded.length !== nacl.box.publicKeyLength) {
throw new Error(`Invalid public key length: expected ${nacl.box.publicKeyLength} bytes, got ${decoded.length}`);
}
const trusted = loadTrustedKeys();
trusted[name] = {
publicKey,
fingerprint: fingerprint(publicKey),
addedAt: new Date().toISOString(),
};
saveTrustedKeys(trusted);
return trusted;
}
function findTrustedKeyByPubkey(publicKey) {
const trusted = loadTrustedKeys();
for (const [name, info] of Object.entries(trusted)) {
if (info.publicKey === publicKey) return { name, ...info };
}
return null;
}
function findTrustedKeyByFingerprint(fp) {
const trusted = loadTrustedKeys();
for (const [name, info] of Object.entries(trusted)) {
if (info.fingerprint === fp || fingerprint(info.publicKey) === fp) return { name, ...info };
}
return null;
}
// === Encryption helpers ===
function encryptForRecipient(plaintext, recipientPublicKeyBase64, senderSecretKeyBase64) {
const nonce = nacl.randomBytes(nacl.box.nonceLength);
const messageBytes = decodeUTF8(plaintext);
const recipientPubKey = decodeBase64(recipientPublicKeyBase64);
const senderSecKey = decodeBase64(senderSecretKeyBase64);
const ciphertext = nacl.box(messageBytes, nonce, recipientPubKey, senderSecKey);
return {
nonce: encodeBase64(nonce),
ciphertext: encodeBase64(ciphertext),
};
}
function decryptFromSender(ciphertextBase64, nonceBase64, senderPublicKeyBase64, recipientSecretKeyBase64) {
const ciphertext = decodeBase64(ciphertextBase64);
const nonce = decodeBase64(nonceBase64);
const senderPubKey = decodeBase64(senderPublicKeyBase64);
const recipientSecKey = decodeBase64(recipientSecretKeyBase64);
const plaintext = nacl.box.open(ciphertext, nonce, senderPubKey, recipientSecKey);
if (!plaintext) return null;
return encodeUTF8(plaintext);
}
// === Registration flow ===
function isRegistrationRequest(task) {
const title = (task.title || '').toLowerCase().trim();
return title === 'register' && task.payload?.pubkey;
}
function handleRegistration(task) {
const taskId = task.id || task.uuid;
const pubkey = task.payload.pubkey;
const fp = fingerprint(pubkey);
log('info', 'Registration request received', { taskId, fingerprint: fp });
// Validate key format
try {
const decoded = decodeBase64(pubkey);
if (decoded.length !== nacl.box.publicKeyLength) {
throw new Error(`Invalid key length: ${decoded.length}`);
}
} catch (err) {
log('warn', 'Registration rejected: invalid key', { taskId, error: err.message });
try {
claimTask(taskId);
failTask(taskId, `Invalid public key: ${err.message}`);
} catch {}
telegram(`🔑 Registration REJECTED — invalid key format.\nFingerprint: <code>${fp}</code>\nError: ${err.message}`);
return;
}
// Check if already trusted
const existing = findTrustedKeyByPubkey(pubkey);
if (existing) {
log('info', 'Registration request for already-trusted key', { taskId, name: existing.name });
try {
claimTask(taskId);
const dispatchKeys = ensureDispatchKeys();
completeTask(taskId, {
status: 'already_registered',
name: existing.name,
ada_public_key: dispatchKeys.publicKey,
message: `Key already registered as "${existing.name}".`,
});
} catch {}
return;
}
// Store pending registration
const pending = loadPendingRegistrations();
pending[fp] = {
pubkey,
requestedAt: new Date().toISOString(),
taskId,
};
savePendingRegistrations(pending);
// Claim and hold the task
try { claimTask(taskId); } catch {}
// Notify admin
telegram(
`🔑 <b>New registration request</b>\n` +
`Fingerprint: <code>${fp}</code>\n` +
`Public key: <code>${pubkey.slice(0, 24)}...</code>\n` +
`Task ID: ${taskId}\n\n` +
`To approve, run on gateway:\n<code>node /home/openclaw/projects/ada-dispatch/index.js approve ${fp} <name></code>`
);
log('info', 'Registration pending admin approval', { taskId, fingerprint: fp });
// Complete the task with pending status so it doesn't block
try {
completeTask(taskId, {
status: 'pending_approval',
fingerprint: fp,
message: 'Registration request submitted. Admin has been notified. You will be approved shortly.',
});
} catch {}
}
function approveRegistration(fp, name) {
const pending = loadPendingRegistrations();
const reg = pending[fp];
if (!reg) {
// Check if fingerprint matches a partial match
const match = Object.entries(pending).find(([k]) => k.startsWith(fp));
if (!match) {
console.error(`No pending registration found for fingerprint: ${fp}`);
process.exit(1);
}
return approveRegistration(match[0], name);
}
// Add to trusted keys
addTrustedKey(name, reg.pubkey);
// Remove from pending
delete pending[fp];
savePendingRegistrations(pending);
const dispatchKeys = ensureDispatchKeys();
console.log(`Approved registration for "${name}".`);
console.log(`Fingerprint: ${fp}`);
console.log(`Public key: ${reg.pubkey}`);
console.log(`Ada's public key: ${dispatchKeys.publicKey}`);
// Notify via Telegram
telegram(
`✅ <b>Registration approved</b>\n` +
`Name: ${name}\n` +
`Fingerprint: <code>${fp}</code>\n` +
`Ada's public key: <code>${dispatchKeys.publicKey}</code>`
);
log('info', 'Registration approved', { name, fingerprint: fp });
}
function rejectRegistration(fp, reason) {
const pending = loadPendingRegistrations();
const reg = pending[fp];
if (!reg) {
const match = Object.entries(pending).find(([k]) => k.startsWith(fp));
if (!match) {
console.error(`No pending registration found for fingerprint: ${fp}`);
process.exit(1);
}
return rejectRegistration(match[0], reason);
}
delete pending[fp];
savePendingRegistrations(pending);
console.log(`Rejected registration for fingerprint: ${fp}`);
telegram(
`❌ <b>Registration rejected</b>\n` +
`Fingerprint: <code>${fp}</code>\n` +
`Reason: ${reason || 'Not approved by admin'}`
);
log('info', 'Registration rejected', { fingerprint: fp, reason });
}
// === Encrypted task decryption ===
function decryptTask(task) {
const payload = task.payload;
if (!payload?.encrypted) return { task, sender: null };
// Support both "sender" (name lookup) and "from" (pubkey lookup)
const senderName = payload.sender;
const senderPubkey = payload.from;
let senderPublicKey;
let resolvedSender;
if (senderName) {
const trusted = loadTrustedKeys();
if (!trusted[senderName]) {
throw new Error(`Sender "${senderName}" not in trusted-keys.json`);
}
senderPublicKey = trusted[senderName].publicKey;
resolvedSender = senderName;
} else if (senderPubkey) {
const found = findTrustedKeyByPubkey(senderPubkey);
if (!found) {
throw new Error(`Public key not in trusted-keys.json (fingerprint: ${fingerprint(senderPubkey)})`);
}
senderPublicKey = found.publicKey;
resolvedSender = found.name;
} else {
throw new Error('Encrypted task missing sender/from field');
}
const dispatchKeys = loadDispatchKeys();
if (!dispatchKeys) {
throw new Error('No dispatch keypair found — run: node index.js keygen');
}
const plaintext = decryptFromSender(
payload.ciphertext, payload.nonce,
senderPublicKey, dispatchKeys.secretKey
);
if (!plaintext) {
throw new Error(`Decryption failed for sender "${resolvedSender}" — wrong key or tampered data`);
}
const decrypted = JSON.parse(plaintext);
log('info', 'AUTH: Decryption successful', {
sender: resolvedSender,
fingerprint: fingerprint(senderPublicKey),
taskId: task.id || task.uuid,
});
// Merge decrypted fields back into the task
const mergedTask = {
...task,
title: decrypted.title || task.title,
description: decrypted.description || task.description,
payload: { ...decrypted.payload, callback_url: payload.callback_url, quiet: payload.quiet },
_sender: resolvedSender,
_senderPublicKey: senderPublicKey,
};
return { task: mergedTask, sender: resolvedSender, senderPublicKey };
}
// === Encrypt response for sender ===
function encryptResponse(responseText, senderPublicKey) {
const dispatchKeys = loadDispatchKeys();
if (!dispatchKeys || !senderPublicKey) return null;
try {
return encryptForRecipient(responseText, senderPublicKey, dispatchKeys.secretKey);
} catch (err) {
log('warn', 'Failed to encrypt response', { error: err.message });
return null;
}
}
// === Authentication check ===
function authenticateTask(task) {
const config = loadConfig();
const payload = task.payload || {};
const taskId = task.id || task.uuid;
// Encrypted tasks are authenticated by the decryption process
if (payload.encrypted) {
return { authenticated: true, encrypted: true };
}
// Registration requests bypass auth
if (isRegistrationRequest(task)) {
return { authenticated: true, registration: true };
}
// Plaintext task
if (config.require_encryption) {
log('warn', 'AUTH: Plaintext task REJECTED (require_encryption=true)', {
taskId, title: task.title,
});
telegram(
`🚫 <b>Task rejected</b> — encryption required\n` +
`Task: ${task.title || taskId}\n` +
`Encryption is now mandatory. Use encrypt-task.js to submit encrypted tasks.`
);
return { authenticated: false, reason: 'Encryption required. Plaintext tasks are no longer accepted.' };
}
// Grace period: allow but warn
log('warn', 'AUTH: Plaintext task accepted (grace period)', {
taskId, title: task.title,
});
return { authenticated: true, encrypted: false, warning: 'plaintext_grace_period' };
}
// === CLI subcommands ===
function handleCLI(args) {
const cmd = args[0];
if (cmd === 'keygen') {
const keys = generateKeypair();
console.log('Generated new dispatch keypair.');
console.log(`Public key: ${keys.publicKey}`);
console.log(`Fingerprint: ${fingerprint(keys.publicKey)}`);
console.log(`Saved to: ${DISPATCH_KEYS_PATH}`);
console.log('\nShare your public key with task submitters so they can encrypt tasks for you.');
process.exit(0);
}
if (cmd === 'add-key') {
const name = args[1];
const pubkey = args[2];
if (!name || !pubkey) {
console.error('Usage: node index.js add-key <name> <public-key-base64>');
process.exit(1);
}
try {
addTrustedKey(name, pubkey);
console.log(`Added trusted key for "${name}".`);
console.log(`Fingerprint: ${fingerprint(pubkey)}`);
console.log(`Saved to: ${TRUSTED_KEYS_PATH}`);
} catch (err) {
console.error(`Error: ${err.message}`);
process.exit(1);
}
process.exit(0);
}
if (cmd === 'remove-key') {
const name = args[1];
if (!name) {
console.error('Usage: node index.js remove-key <name>');
process.exit(1);
}
const trusted = loadTrustedKeys();
if (!trusted[name]) {
console.error(`No trusted key found for "${name}".`);
process.exit(1);
}
delete trusted[name];
saveTrustedKeys(trusted);
console.log(`Removed trusted key for "${name}".`);
process.exit(0);
}
if (cmd === 'list-keys') {
const trusted = loadTrustedKeys();
const entries = Object.entries(trusted);
if (entries.length === 0) {
console.log('No trusted keys registered.');
} else {
console.log('Trusted entities:');
for (const [name, info] of entries) {
const fp = info.fingerprint || fingerprint(info.publicKey);
console.log(` ${name}: ${info.publicKey} (fp: ${fp}, added ${info.addedAt})`);
}
}
const dispatch = loadDispatchKeys();
if (dispatch) {
console.log(`\nDispatch public key: ${dispatch.publicKey}`);
console.log(`Dispatch fingerprint: ${fingerprint(dispatch.publicKey)}`);
} else {
console.log('\nNo dispatch keypair found. Run: node index.js keygen');
}
const pending = loadPendingRegistrations();
const pendingEntries = Object.entries(pending);
if (pendingEntries.length > 0) {
console.log('\nPending registrations:');
for (const [fp, info] of pendingEntries) {
console.log(` ${fp}: requested ${info.requestedAt} (task ${info.taskId})`);
}
}
process.exit(0);
}
if (cmd === 'approve') {
const fp = args[1];
const name = args[2];
if (!fp || !name) {
console.error('Usage: node index.js approve <fingerprint> <name>');
process.exit(1);
}
approveRegistration(fp, name);
process.exit(0);
}
if (cmd === 'reject') {
const fp = args[1];
const reason = args.slice(2).join(' ') || 'Not approved';
if (!fp) {
console.error('Usage: node index.js reject <fingerprint> [reason]');
process.exit(1);
}
rejectRegistration(fp, reason);
process.exit(0);
}
if (cmd === 'pending') {
const pending = loadPendingRegistrations();
const entries = Object.entries(pending);
if (entries.length === 0) {
console.log('No pending registrations.');
} else {
console.log('Pending registrations:');
for (const [fp, info] of entries) {
console.log(` Fingerprint: ${fp}`);
console.log(` Public key: ${info.pubkey}`);
console.log(` Requested: ${info.requestedAt}`);
console.log(` Task ID: ${info.taskId}`);
console.log('');
}
}
process.exit(0);
}
if (cmd === 'create') {
// Wrapper around `ats create` with --depends-on support
const title = args[1];
if (!title) {
console.error('Usage: node index.js create <title> [--description <text>] [--depends-on <id,...>] [--payload <json>] [--channel <ch>] [--priority <1-10>]');
process.exit(1);
}
const createArgs = ['create', title, '--channel', CHANNEL];
let dependsOn = null;
let existingPayload = {};
for (let i = 2; i < args.length; i++) {
if (args[i] === '--depends-on' && args[i + 1]) {
dependsOn = args[i + 1].split(',').map(s => s.trim()).filter(Boolean);
i++;
} else if (args[i] === '--payload' && args[i + 1]) {
try { existingPayload = JSON.parse(args[i + 1]); } catch { existingPayload = {}; }
i++;
} else {
createArgs.push(args[i]);
if (args[i].startsWith('--') && args[i + 1] && !args[i + 1].startsWith('--')) {
createArgs.push(args[i + 1]);
i++;
}
}
}
// Validate depends_on targets exist
if (dependsOn) {
for (const depId of dependsOn) {
try {
const dep = getTask(depId);
if (!dep) {
console.error(`Error: dependency task #${depId} not found`);
process.exit(1);
}
} catch (err) {
console.error(`Error: cannot verify dependency task #${depId}: ${err.message}`);
process.exit(1);
}
}
existingPayload.depends_on = dependsOn;
}
if (Object.keys(existingPayload).length > 0) {
createArgs.push('--payload', JSON.stringify(existingPayload));
}
try {
const result = ats(...createArgs);
process.stdout.write(result);
if (dependsOn) {
console.log(`Dependencies: ${dependsOn.map(d => '#' + d).join(', ')}`);
}
} catch (err) {
console.error('Failed to create task:', err.stderr || err.message);
process.exit(1);
}
process.exit(0);
}
if (cmd === 'deps') {
// Show dependency graph for channel tasks
let filterTaskId = null;
let statusFilter = null;
for (let i = 1; i < args.length; i++) {
if (args[i] === '--task' && args[i + 1]) { filterTaskId = args[i + 1]; i++; }
if (args[i] === '--status' && args[i + 1]) { statusFilter = args[i + 1]; i++; }
}
const listArgs = ['list', '--channel', CHANNEL, '-f', 'json'];
if (statusFilter && statusFilter !== 'all') {
listArgs.push('--status', statusFilter);
} else {
listArgs.push('--all');
}
const tasks = atsJSON(...listArgs);
const taskList = Array.isArray(tasks) ? tasks : [];
const taskMap = new Map();
for (const t of taskList) taskMap.set(String(t.id || t.uuid), t);
const relevant = filterTaskId
? taskList.filter(t => String(t.id || t.uuid) === filterTaskId)
: taskList.filter(t => getTaskDependencies(t).length > 0);
if (relevant.length === 0) {
console.log(filterTaskId ? `Task #${filterTaskId} has no dependencies.` : 'No tasks with dependencies found.');
process.exit(0);
}
const statusIcon = (s) => ({ pending: '\u25CB', in_progress: '\u25D1', completed: '\u25CF', failed: '\u2717', cancelled: '\u2298' }[s] || '?');
console.log('Dependency Graph:');
console.log('');
for (const t of relevant) {
const id = t.id || t.uuid;
const deps = getTaskDependencies(t);
console.log(` ${statusIcon(t.status)} #${id} ${t.title || '(untitled)'} [${t.status}]`);
for (let i = 0; i < deps.length; i++) {
const depId = deps[i];
const dep = taskMap.get(depId);
const connector = i === deps.length - 1 ? '\u2514\u2500' : '\u251C\u2500';
if (dep) {
console.log(` ${connector} depends on ${statusIcon(dep.status)} #${depId} ${dep.title || '(untitled)'} [${dep.status}]`);
} else {
console.log(` ${connector} depends on ? #${depId} (not found)`);
}
}
console.log('');
}
process.exit(0);
}
if (cmd === 'config') {
const key = args[1];
const value = args[2];
if (!key) {
const config = loadConfig();
console.log(JSON.stringify(config, null, 2));
process.exit(0);
}
const config = loadConfig();
if (value === 'true') config[key] = true;
else if (value === 'false') config[key] = false;
else config[key] = value;
writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n');
console.log(`Set ${key} = ${JSON.stringify(config[key])}`);
process.exit(0);
}
// Not a CLI command — continue to main()
return false;
}
// === Preflight ===
function preflight() {
for (const check of [{ name: 'ats', bin: ATS_BIN }, { name: 'claude', bin: NANOBOT_BIN }]) {
try {
const version = execSync(`'${check.bin}' --version`, {
encoding: 'utf-8', timeout: 10000, stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
log('info', `Preflight passed: ${check.name}`, { bin: check.bin, version });
} catch (err) {
log('error', `Preflight failed: ${check.name}`, { bin: check.bin, error: err.message });
process.exit(1);
}
}
// Ensure dispatch keypair exists
ensureDispatchKeys();
}
// === ATS helpers ===
function ats(...args) {
const fullArgs = [...ACTOR_FLAGS, ...args];
try {
return execFileSync(ATS_BIN, fullArgs, {
encoding: 'utf-8', timeout: 30000, stdio: ['pipe', 'pipe', 'pipe'],
});
} catch (err) {
log('debug', 'ats command failed', { args: fullArgs, stderr: err.stderr, stdout: err.stdout });
throw err;
}
}
function atsJSON(...args) {
const raw = ats(...args, '-f', 'json');
const arrayMatch = raw.match(/\[[\s\S]*\]/);
if (arrayMatch) {
try { return JSON.parse(arrayMatch[0]); } catch { return []; }
}
const objMatch = raw.match(/\{[\s\S]*\}/);
if (objMatch) {
try { return JSON.parse(objMatch[0]); } catch { return null; }
}
return [];
}
function getTask(taskId) {
const raw = ats('get', String(taskId), '-f', 'json');
const match = raw.match(/\{[\s\S]*\}/);
if (!match) return null;
try { return JSON.parse(match[0]); } catch { return null; }
}
function listPending() {
const tasks = atsJSON('list', '--channel', CHANNEL, '--status', 'pending');
return Array.isArray(tasks) ? tasks : [];
}
function claimTask(taskId) {
ats('claim', String(taskId), '--lease', String(LEASE_MS));
}
function completeTask(taskId, outputs) {
ats('complete', String(taskId), '--outputs', JSON.stringify(outputs));
}
function failTask(taskId, reason) {
ats('fail', String(taskId), '--reason', reason);
}
function postMessage(taskId, message) {
try { ats('message', 'add', String(taskId), message); }
catch (err) { log('warn', 'Failed to post ATS message', { taskId, error: err.message }); }
}
// === Callback notification ===
async function notifyCallback(task, status, result) {
const callbackUrl = task.payload?.callback_url;
if (!callbackUrl) return;
const taskId = task.id || task.uuid;
const body = JSON.stringify({ task_id: taskId, status, result, completed_at: new Date().toISOString() });
try {
const url = new URL(callbackUrl);
const transport = url.protocol === 'https:' ? https : http;
await new Promise((resolve, reject) => {
const req = transport.request(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
timeout: 10000,
}, (res) => { res.resume(); resolve(); });
req.on('error', reject);
req.write(body);
req.end();
});
log('info', 'Callback notified', { taskId, callbackUrl, status });
} catch (err) {
log('warn', 'Callback notification failed', { taskId, callbackUrl, error: err.message });
}
}
// === Prompt builder ===
function buildPrompt(task) {
const parts = ['You are Ada, processing a task from the ada-dispatch channel. Execute the task described below.'];
if (task.title) parts.push(`<task-title>\n${task.title}\n</task-title>`);
if (task.description) parts.push(`<task-description>\n${task.description}\n</task-description>`);
if (task.payload) {
const safePayload = { ...task.payload };
for (const field of INTERNAL_PAYLOAD_FIELDS) delete safePayload[field];
if (Object.keys(safePayload).length > 0) {
parts.push(`<task-context>\n${JSON.stringify(safePayload, null, 2)}\n</task-context>`);
}
}
return parts.join('\n\n');
}
// === Nanobot execution ===
function runNanobot(prompt, sessionId) {
const child = spawn(
NANOBOT_BIN,
['-p', '--dangerously-skip-permissions'],
{ stdio: ['pipe', 'pipe', 'pipe'] }
);
// Feed prompt via stdin (avoids arg-length and multi-line issues)
child.stdin.write(prompt);
child.stdin.end();
// Track whether the process has already exited to prevent timeout race
let processExited = false;
let killedByTimeout = false;
// Timeout guard — only kill if the process hasn't already exited
const timer = setTimeout(() => {
if (!processExited) {
killedByTimeout = true;
child.kill('SIGTERM');
}
}, NANOBOT_TIMEOUT_MS);
const promise = new Promise((resolve, reject) => {
let stdout = '';
child.stdout.on('data', (chunk) => { stdout += chunk; });
child.stderr.on('data', () => {}); // drain stderr
child.on('close', (code, signal) => {
processExited = true;
clearTimeout(timer);
// If the process exited with code 0, always resolve — even if a
// SIGTERM was sent (the process finished before the signal landed)
if (code === 0) {
resolve(stdout);
} else if (killedByTimeout) {
reject(new Error('Nanobot timed out (killed after timeout)'));
} else if (signal === 'SIGTERM' || code === 143) {
reject(new Error('Nanobot cancelled'));
} else {
reject(new Error(`Nanobot exited with code ${code}`));
}
});
child.on('error', (err) => {
processExited = true;
clearTimeout(timer);
reject(new Error(err.message || 'Nanobot execution failed'));
});
});
return { promise, child };
}
// === Dependency resolution ===
function getTaskDependencies(task) {
const deps = task.payload?.depends_on;
if (!deps) return [];
const arr = Array.isArray(deps) ? deps : [deps];
return arr.map(String);
}
function checkDependencies(task) {
const deps = getTaskDependencies(task);
if (deps.length === 0) return { ready: true };
const pending = [];
const failed = [];
const completed = [];
for (const depId of deps) {
try {
const depTask = getTask(depId);
if (!depTask) {
failed.push({ id: depId, reason: 'not found' });
continue;
}
const status = depTask.status;
if (status === 'completed') {
completed.push(depId);
} else if (status === 'failed' || status === 'cancelled') {
failed.push({ id: depId, reason: status });
} else {
pending.push(depId);
}
} catch (err) {
log('warn', 'Failed to check dependency status', { depId, error: err.message });
pending.push(depId);
}
}
if (failed.length > 0) {
return { ready: false, blocked: true, failed, pending, completed };
}
if (pending.length > 0) {
return { ready: false, blocked: false, pending, completed };
}
return { ready: true, completed };
}
function recheckWaitingTasks() {
if (waitingOnDeps.size === 0) return;
log('debug', 'Re-checking dependency queue', { count: waitingOnDeps.size });
for (const [taskId, task] of waitingOnDeps) {
const depStatus = checkDependencies(task);
if (depStatus.ready) {
log('info', 'Dependencies satisfied, dispatching', { taskId, deps: getTaskDependencies(task) });
waitingOnDeps.delete(taskId);
if (!running) {
log('info', 'Shutdown in progress, skipping dispatch of deferred task', { taskId });
continue;
}
dispatchTask(task);
} else if (depStatus.blocked) {
const reasons = depStatus.failed.map(f => `#${f.id} (${f.reason})`).join(', ');
log('warn', 'Task blocked by failed dependencies', { taskId, failed: reasons });
waitingOnDeps.delete(taskId);
try {
claimTask(taskId);
failTask(taskId, `Blocked: dependency ${reasons} failed`);
if (shouldNotify(task)) telegram(`🚫 Blocked: ${task.title} — dependency ${reasons} failed`);
} catch (err) {
log('error', 'Failed to mark blocked task', { taskId, error: err.message });
}
notifyCallback(task, 'failed', `Blocked: dependency ${reasons} failed`);
}
// else: still waiting, leave in queue
}
}
// === Task dispatch ===
// GPU tasks go through the semaphore; non-GPU tasks run immediately (concurrent).
function dispatchTask(task) {
const taskId = task.id || task.uuid;
// Prevent duplicate dispatch
if (processingTasks.has(taskId)) {
log('debug', 'Task already processing, skipping', { taskId });
return;
}
// Handle registration requests immediately (no GPU needed)
if (isRegistrationRequest(task)) {
log('info', 'AUTH: Registration request detected, handling immediately', { taskId });
handleRegistration(task);
return;
}
// Authentication check (reject early)
const auth = authenticateTask(task);