-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathserver.js
More file actions
1891 lines (1643 loc) · 57.6 KB
/
server.js
File metadata and controls
1891 lines (1643 loc) · 57.6 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
/**
* Gas Town GUI Bridge Server
*
* Node.js server that bridges the browser UI to the Gas Town CLI.
* - Executes gt/bd commands via child_process
* - Streams real-time events via WebSocket
* - Serves static files
*/
import express from 'express';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import { spawn, execFile } from 'child_process';
import { promisify } from 'util';
import path from 'path';
import fs from 'fs';
import fsPromises from 'fs/promises';
import os from 'os';
import readline from 'readline';
import { fileURLToPath } from 'url';
import { createApp } from './server/app/createApp.js';
import {
buildSessionRegistryFromTown,
clearSessionRegistryCache,
mayorSessionName,
parseTmuxSessions,
runningAddressesFromTmux,
sessionNameForAgentAddress,
sessionNameForService,
} from './server/domain/session/SessionNames.js';
import { AgentPath } from './server/domain/values/AgentPath.js';
import { CommandRunner } from './server/infrastructure/CommandRunner.js';
import { CacheRegistry } from './server/infrastructure/CacheRegistry.js';
import {
DEFAULT_BD_FALLBACK_PATHS,
DEFAULT_GT_FALLBACK_PATHS,
resolveExecutable,
} from './server/infrastructure/ExecutableResolver.js';
import { BDGateway } from './server/gateways/BDGateway.js';
import { GTGateway } from './server/gateways/GTGateway.js';
import { GitHubGateway } from './server/gateways/GitHubGateway.js';
import { TmuxGateway } from './server/gateways/TmuxGateway.js';
import { BeadService } from './server/services/BeadService.js';
import { ConvoyService } from './server/services/ConvoyService.js';
import { FormulaService } from './server/services/FormulaService.js';
import { GitHubService } from './server/services/GitHubService.js';
import { StatusService } from './server/services/StatusService.js';
import { TargetService } from './server/services/TargetService.js';
import { WorkService } from './server/services/WorkService.js';
import { createCLICompatibilityService } from './server/services/CLICompatibilityService.js';
import { registerBeadRoutes } from './server/routes/beads.js';
import { registerConvoyRoutes } from './server/routes/convoys.js';
import { registerFormulaRoutes } from './server/routes/formulas.js';
import { registerGitHubRoutes } from './server/routes/github.js';
import { registerStatusRoutes } from './server/routes/status.js';
import { registerTargetRoutes } from './server/routes/targets.js';
import { registerWorkRoutes } from './server/routes/work.js';
const execFileAsync = promisify(execFile);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const PORT = process.env.GASTOWN_PORT || 7667;
const HOST = process.env.HOST || '127.0.0.1';
const HOME = process.env.HOME || os.homedir();
const GT_ROOT = process.env.GT_ROOT || path.join(HOME, 'gt');
const GT_EXECUTABLE = resolveExecutable({
command: 'gt',
envVarName: 'GT_BIN',
fallbackPaths: DEFAULT_GT_FALLBACK_PATHS,
});
const BD_EXECUTABLE = resolveExecutable({
command: 'bd',
envVarName: 'BD_BIN',
fallbackPaths: DEFAULT_BD_FALLBACK_PATHS,
});
const commandRunner = new CommandRunner();
const gtGateway = new GTGateway({ runner: commandRunner, gtRoot: GT_ROOT, executable: GT_EXECUTABLE });
const bdGateway = new BDGateway({ runner: commandRunner, gtRoot: GT_ROOT, executable: BD_EXECUTABLE });
const tmuxGateway = new TmuxGateway({ runner: commandRunner });
const backendCache = new CacheRegistry();
const convoyService = new ConvoyService({
gtGateway,
cache: backendCache,
emit: (type, data) => emitMutationEvent(type, data),
});
const statusService = new StatusService({ gtGateway, tmuxGateway, cache: backendCache, gtRoot: GT_ROOT });
const targetService = new TargetService({ statusService });
const beadService = new BeadService({
bdGateway,
emit: (type, data) => emitMutationEvent(type, data),
});
const workService = new WorkService({
gtGateway,
bdGateway,
emit: (type, data) => emitMutationEvent(type, data),
});
const gitHubGateway = new GitHubGateway({ runner: commandRunner });
const gitHubService = new GitHubService({ gitHubGateway, statusService, cache: backendCache });
const defaultOrigins = [
`http://localhost:${PORT}`,
`http://127.0.0.1:${PORT}`,
];
const allowedOrigins = process.env.CORS_ORIGINS
? process.env.CORS_ORIGINS.split(',').map(origin => origin.trim()).filter(Boolean)
: defaultOrigins;
const allowNullOrigin = process.env.ALLOW_NULL_ORIGIN === 'true';
const app = createApp({ allowedOrigins, allowNullOrigin });
const server = createServer(app);
const wss = new WebSocketServer({ server });
// Simple in-memory cache with TTL
const cache = new Map();
const CACHE_TTL = {
status: 5000, // 5 seconds for status (frequently changing)
convoys: 10000, // 10 seconds for convoys
mail: 15000, // 15 seconds for mail list
agents: 5000, // 5 seconds for agents
rigs: 5000, // 5 seconds for rigs
formulas: 60000, // 1 minute for formulas (rarely changes)
github_prs: 30000, // 30 seconds for GitHub PRs
github_issues: 30000, // 30 seconds for GitHub issues
doctor: 30000, // 30 seconds for doctor
};
const mailFeedCache = {
mtimeMs: 0,
size: 0,
events: null,
};
function getCached(key) {
const entry = cache.get(key);
if (entry && Date.now() < entry.expires) {
return entry.data;
}
cache.delete(key);
return null;
}
function setCache(key, data, ttl) {
cache.set(key, { data, expires: Date.now() + ttl });
}
const CACHE_INVALIDATION_BY_EVENT = {
rig_added: {
localKeys: ['rigs', 'agents', 'crews'],
localPrefixes: ['rig-config:'],
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
rig_removed: {
localKeys: ['rigs', 'agents', 'crews'],
localPrefixes: ['rig-config:'],
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
crew_added: {
localKeys: ['crews'],
backendKeys: ['status'],
},
crew_removed: {
localKeys: ['crews'],
backendKeys: ['status'],
},
agent_started: {
localKeys: ['agents'],
backendKeys: ['status'],
},
agent_stopped: {
localKeys: ['agents'],
backendKeys: ['status'],
},
agent_restarted: {
localKeys: ['agents'],
backendKeys: ['status'],
},
service_started: {
localKeys: ['agents'],
backendKeys: ['status'],
},
service_stopped: {
localKeys: ['agents'],
backendKeys: ['status'],
},
service_restarted: {
localKeys: ['agents'],
backendKeys: ['status'],
},
convoy_created: {
localKeys: ['agents'],
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
convoy_updated: {
localKeys: ['agents'],
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
work_slung: {
localKeys: ['agents'],
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
work_done: {
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
work_parked: {
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
work_released: {
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
work_reassigned: {
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
bead_created: {
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
escalation: {
backendKeys: ['status'],
backendPrefixes: ['convoys_'],
},
};
function deleteLocalCacheByPrefix(prefix) {
for (const key of cache.keys()) {
if (key.startsWith(prefix)) {
cache.delete(key);
}
}
}
function invalidateCaches(plan = {}) {
const {
localKeys = [],
localPrefixes = [],
backendKeys = [],
backendPrefixes = [],
} = plan;
for (const key of localKeys) {
cache.delete(key);
}
for (const prefix of localPrefixes) {
deleteLocalCacheByPrefix(prefix);
}
for (const key of backendKeys) {
backendCache.delete(key);
}
for (const prefix of backendPrefixes) {
backendCache.deleteByPrefix(prefix);
}
}
function emitMutationEvent(type, data) {
invalidateCaches(CACHE_INVALIDATION_BY_EVENT[type]);
broadcast({ type, data });
}
/**
* Parse rig names from `gt rig list` text output.
* Handles both legacy " rigname" and current "🟢 rigname" / "🛑 rigname" formats.
*/
function parseRigNames(text) {
const rigs = [];
for (const line of text.split('\n')) {
// Match " rigname" (2-space indent) or "emoji rigname" (status indicator prefix)
const match = line.match(/^(?:\s{1,2}|\S+\s+)([a-zA-Z0-9_-]+)$/);
if (match) {
rigs.push({ name: match[1] });
}
}
return rigs;
}
// Rig config cache TTL (5 minutes - rig configs rarely change)
const RIG_CONFIG_TTL = 300000;
/**
* Get rig configuration with caching
* @param {string} rigName - Name of the rig
* @returns {Promise<Object|null>} - Rig config or null if not found
*/
async function getRigConfig(rigName) {
const cacheKey = `rig-config:${rigName}`;
const cached = getCached(cacheKey);
if (cached !== null) return cached;
try {
const rigConfigPath = path.join(GT_ROOT, rigName, 'config.json');
const rigConfigContent = await fsPromises.readFile(rigConfigPath, 'utf8');
const config = JSON.parse(rigConfigContent);
setCache(cacheKey, config, RIG_CONFIG_TTL);
return config;
} catch (e) {
// Config not found or invalid - cache null to avoid repeated reads
setCache(cacheKey, null, 60000); // Cache null for 1 minute
return null;
}
}
// Cache cleanup interval - removes expired entries to prevent memory leaks
const CACHE_CLEANUP_INTERVAL = 60000; // 1 minute
setInterval(() => {
const now = Date.now();
let cleaned = 0;
for (const [key, entry] of cache.entries()) {
if (now >= entry.expires) {
cache.delete(key);
cleaned++;
}
}
if (cleaned > 0) {
console.log(`[Cache] Cleaned ${cleaned} expired entries, ${cache.size} remaining`);
}
}, CACHE_CLEANUP_INTERVAL);
// Middleware
app.use('/assets', express.static(path.join(__dirname, 'assets')));
app.use('/css', express.static(path.join(__dirname, 'css')));
// Add cache-control headers for JS files to improve load times
app.use('/js', express.static(path.join(__dirname, 'js'), {
maxAge: '1h',
setHeaders: (res, filePath) => {
// Set cache-control for JS files
if (filePath.endsWith('.js')) {
res.setHeader('Cache-Control', 'public, max-age=3600');
}
}
}));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('/favicon.ico', (req, res) => {
res.sendFile(path.join(__dirname, 'assets', 'favicon.ico'));
});
// Store connected WebSocket clients
const clients = new Set();
// Broadcast to all connected clients
function broadcast(data) {
const message = JSON.stringify(data);
clients.forEach(client => {
if (client.readyState === 1) { // OPEN
client.send(message);
}
});
}
// Safely quote shell arguments to prevent command injection
// Escapes all shell metacharacters and wraps in single quotes
function quoteArg(arg) {
if (arg === null || arg === undefined) return "''";
const str = String(arg);
// Single quotes are the safest - only need to escape single quotes themselves
// Replace each ' with '\'' (end quote, escaped quote, start quote)
return "'" + str.replace(/'/g, "'\\''") + "'";
}
function requireAgentPath(req, res) {
try {
return new AgentPath(req.params.rig, req.params.name);
} catch {
res.status(400).json({ error: 'Invalid rig or agent name' });
return null;
}
}
// Check if a specific tmux session is running
async function isSessionRunning(sessionName) {
try {
const { stdout } = await execFileAsync('tmux', ['has-session', '-t', sessionName]);
return true;
} catch {
return false;
}
}
// Mayor message history (in-memory, last 100 messages)
const mayorMessageHistory = [];
const MAX_MESSAGE_HISTORY = 100;
function addMayorMessage(target, message, status, response = null) {
const entry = {
id: Date.now().toString(36) + Math.random().toString(36).substr(2, 5),
timestamp: new Date().toISOString(),
target,
message,
status, // 'sent', 'failed', 'auto-started'
response
};
mayorMessageHistory.unshift(entry);
if (mayorMessageHistory.length > MAX_MESSAGE_HISTORY) {
mayorMessageHistory.pop();
}
// Broadcast to connected clients
broadcast({ type: 'mayor_message', data: entry });
return entry;
}
async function getSessionRegistry() {
return buildSessionRegistryFromTown(GT_ROOT);
}
async function getRunningAgentAddresses() {
try {
const registry = await getSessionRegistry();
const { stdout } = await execFileAsync('tmux', ['ls']);
return runningAddressesFromTmux(stdout, registry);
} catch {
return new Set();
}
}
// Parse GitHub URL to extract owner/repo
function parseGitHubUrl(url) {
if (!url) return null;
// Handle various GitHub URL formats:
// https://github.com/owner/repo
// https://github.com/owner/repo.git
// git@github.com:owner/repo.git
// ssh://git@github.com/owner/repo.git
let match = url.match(/github\.com[/:]([^/]+)\/([^/.\s]+)/);
if (match) {
return { owner: match[1], repo: match[2].replace(/\.git$/, '') };
}
return null;
}
// Get default branch for a GitHub repo
async function getDefaultBranch(url) {
const parsed = parseGitHubUrl(url);
if (!parsed) {
console.log(`[GitHub] Could not parse URL: ${url}`);
return null;
}
try {
// Use gh api to get repo info including default branch
const { stdout } = await execFileAsync('gh', [
'api', `repos/${parsed.owner}/${parsed.repo}`, '--jq', '.default_branch'
], { timeout: 10000 });
const branch = String(stdout || '').trim();
if (branch) {
console.log(`[GitHub] Detected default branch for ${parsed.owner}/${parsed.repo}: ${branch}`);
return branch;
}
} catch (err) {
console.warn(`[GitHub] Could not detect default branch for ${url}:`, err.message);
}
return null;
}
// Get polecat output from tmux (last N lines)
async function getPolecatOutput(sessionName, lines = 50) {
try {
const safeLines = Math.max(1, Math.min(10000, parseInt(lines, 10) || 50));
const { stdout } = await execFileAsync('tmux', ['capture-pane', '-t', sessionName, '-p']);
const output = String(stdout || '');
if (!output) return '';
const outputLines = output.split('\n');
return outputLines.slice(-safeLines).join('\n').trim();
} catch {
return null;
}
}
// Execute a Gas Town command
async function executeGT(args, options = {}) {
const cmd = `${GT_EXECUTABLE} ${args.join(' ')}`;
console.log(`[GT] Executing: ${cmd}`);
try {
const { stdout, stderr } = await execFileAsync(GT_EXECUTABLE, args, {
cwd: options.cwd || GT_ROOT,
timeout: options.timeout || 30000,
env: { ...process.env, ...options.env }
});
if (stderr && !options.ignoreStderr) {
console.warn(`[GT] stderr: ${stderr}`);
}
return { success: true, data: String(stdout || '').trim() };
} catch (error) {
// Combine stdout and stderr for error output
const output = String(error.stdout || '') + '\n' + String(error.stderr || '');
const trimmedOutput = output.trim();
// Check if this looks like a real error (contains "Error:" or "error:")
const looksLikeError = /\bError:/i.test(trimmedOutput) || error.code !== 0;
// Commands like 'gt doctor' or 'gt status' exit with code 1 when issues found, but still have useful output
// However, if output contains "Error:" it's a real error, not just informational
if (trimmedOutput && !looksLikeError) {
console.warn(`[GT] Command exited with non-zero but has output: ${error.message}`);
console.warn(`[GT] Output:\n${trimmedOutput}`);
return { success: true, data: trimmedOutput, exitCode: error.code };
}
console.error(`[GT] Error: ${error.message}`);
if (trimmedOutput) console.error(`[GT] Output:\n${trimmedOutput}`);
return { success: false, error: trimmedOutput || error.message, exitCode: error.code };
}
}
// Execute a Beads command
async function executeBD(args, options = {}) {
const cmd = `${BD_EXECUTABLE} ${args.join(' ')}`;
console.log(`[BD] Executing: ${cmd}`);
// Set BEADS_DIR to ensure bd finds the database
const beadsDir = path.join(GT_ROOT, '.beads');
try {
const { stdout } = await execFileAsync(BD_EXECUTABLE, args, {
cwd: options.cwd || GT_ROOT,
timeout: options.timeout || 30000,
env: { ...process.env, BEADS_DIR: beadsDir }
});
return { success: true, data: String(stdout || '').trim() };
} catch (error) {
return { success: false, error: error.message };
}
}
const cliCompatibilityService = createCLICompatibilityService({
executeGT: (args, options) => executeGT(args, options),
executeBD: (args, options) => executeBD(args, options),
killTmuxSession: async (sessionName) => {
try {
await execFileAsync('tmux', ['kill-session', '-t', sessionName]);
} catch {
// Session may not exist; safe to ignore.
}
},
});
// Parse JSON output from commands
function parseJSON(output) {
try {
return JSON.parse(output);
} catch {
return null;
}
}
async function loadMailFeedEvents(feedPath) {
const stats = await fsPromises.stat(feedPath);
if (mailFeedCache.events &&
mailFeedCache.mtimeMs === stats.mtimeMs &&
mailFeedCache.size === stats.size) {
return mailFeedCache.events;
}
const fileStream = fs.createReadStream(feedPath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
const mailEvents = [];
for await (const line of rl) {
if (!line.trim()) continue;
try {
const event = JSON.parse(line);
if (event.type === 'mail') {
// Transform feed event to mail-like object
mailEvents.push({
id: `feed-${event.ts}-${mailEvents.length}`,
from: event.actor || 'unknown',
to: event.payload?.to || 'unknown',
subject: event.payload?.subject || event.summary || '(No Subject)',
body: event.payload?.body || event.payload?.message || '',
timestamp: event.ts,
read: true, // Feed mail is historical
priority: event.payload?.priority || 'normal',
feedEvent: true, // Mark as feed-sourced
});
}
} catch {
// Skip malformed lines
}
}
// Sort newest first
mailEvents.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
mailFeedCache.events = mailEvents;
mailFeedCache.mtimeMs = stats.mtimeMs;
mailFeedCache.size = stats.size;
return mailEvents;
}
// ============= REST API Endpoints =============
// Town status overview
registerStatusRoutes(app, { statusService });
// List convoys
registerConvoyRoutes(app, { convoyService });
// Work dispatch, escalation, and bead/work actions
registerWorkRoutes(app, { workService });
// Beads
registerBeadRoutes(app, { beadService });
// Get available sling targets
registerTargetRoutes(app, { targetService });
// Get mail inbox
app.get('/api/mail', async (req, res) => {
// Check cache
if (req.query.refresh !== 'true') {
const cached = getCached('mail');
if (cached) return res.json(cached);
}
const result = await executeGT(['mail', 'inbox', '--json']);
if (result.success) {
const data = parseJSON(result.data) || [];
setCache('mail', data, CACHE_TTL.mail);
res.json(data);
} else {
res.status(500).json({ error: result.error });
}
});
// Send mail
app.post('/api/mail', async (req, res) => {
const { to, subject, message, priority } = req.body;
const args = ['mail', 'send', to, '-s', subject, '-m', message];
if (priority) args.push('--priority', priority);
const result = await executeGT(args);
if (result.success) {
res.json({ success: true });
} else {
res.status(500).json({ error: result.error });
}
});
// Get all mail from feed (for observability) with pagination
app.get('/api/mail/all', async (req, res) => {
try {
// Pagination params (default: page 1, 50 items per page)
const page = Math.max(1, parseInt(req.query.page, 10) || 1);
const limit = Math.min(200, Math.max(1, parseInt(req.query.limit, 10) || 50));
const offset = (page - 1) * limit;
const feedPath = path.join(GT_ROOT, '.events.jsonl');
try {
await fsPromises.access(feedPath);
} catch {
mailFeedCache.events = null;
return res.json({ items: [], total: 0, page, limit, hasMore: false });
}
const mailEvents = await loadMailFeedEvents(feedPath);
// Apply pagination
const total = mailEvents.length;
const paginatedItems = mailEvents.slice(offset, offset + limit);
const hasMore = offset + limit < total;
res.json({
items: paginatedItems,
total,
page,
limit,
hasMore
});
} catch (err) {
console.error('[API] Failed to read feed for mail:', err);
res.status(500).json({ error: 'Failed to read mail feed' });
}
});
// Get single mail message
app.get('/api/mail/:id', async (req, res) => {
const { id } = req.params;
try {
const result = await executeGT(['mail', 'read', id, '--json']);
if (result.success) {
const mail = parseJSON(result.data);
res.json(mail || { id, error: 'Not found' });
} else {
res.status(404).json({ error: 'Mail not found' });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Mark mail as read
app.post('/api/mail/:id/read', async (req, res) => {
const { id } = req.params;
try {
const result = await executeGT(['mail', 'mark-read', id]);
if (result.success) {
res.json({ success: true, id, read: true });
} else {
res.status(500).json({ error: result.error || 'Failed to mark as read' });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Mark mail as unread
app.post('/api/mail/:id/unread', async (req, res) => {
const { id } = req.params;
try {
const result = await executeGT(['mail', 'mark-unread', id]);
if (result.success) {
res.json({ success: true, id, read: false });
} else {
res.status(500).json({ error: result.error || 'Failed to mark as unread' });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ============= Nudge API =============
// Send a message to Mayor (or other agent)
app.post('/api/nudge', async (req, res) => {
const { target, message, autoStart = true } = req.body;
if (!message) {
return res.status(400).json({ error: 'Message is required' });
}
// Default to mayor if no target specified
const nudgeTarget = target || 'mayor';
const registry = await getSessionRegistry();
const sessionName = sessionNameForAgentAddress(nudgeTarget, registry) || `gt-${nudgeTarget}`;
try {
// Check if target session is running
const isRunning = await isSessionRunning(sessionName);
let wasAutoStarted = false;
if (!isRunning) {
console.log(`[Nudge] Session ${sessionName} not running`);
// Auto-start Mayor if requested
if (nudgeTarget === 'mayor' && autoStart) {
console.log(`[Nudge] Auto-starting Mayor...`);
const startResult = await executeGT(['mayor', 'start'], { timeout: 30000 });
if (!startResult.success) {
const entry = addMayorMessage(nudgeTarget, message, 'failed', 'Failed to auto-start Mayor');
return res.status(500).json({
error: 'Mayor not running and failed to auto-start',
details: startResult.error,
messageId: entry.id
});
}
wasAutoStarted = true;
console.log(`[Nudge] Mayor auto-started successfully`);
// Wait a moment for Mayor to initialize
await new Promise(resolve => setTimeout(resolve, 2000));
// Broadcast that Mayor was started
emitMutationEvent('service_started', { service: 'mayor', autoStarted: true });
} else if (!isRunning) {
const entry = addMayorMessage(nudgeTarget, message, 'failed', `Session ${sessionName} not running`);
return res.status(400).json({
error: `${nudgeTarget} is not running`,
hint: nudgeTarget === 'mayor' ? 'Set autoStart: true to start Mayor automatically' : `Start the ${nudgeTarget} service first`,
messageId: entry.id
});
}
}
// Send the nudge
const result = await executeGT(['nudge', nudgeTarget, message], { timeout: 10000 });
if (result.success) {
const status = wasAutoStarted ? 'auto-started' : 'sent';
const entry = addMayorMessage(nudgeTarget, message, status);
res.json({
success: true,
target: nudgeTarget,
message,
wasAutoStarted,
messageId: entry.id
});
} else {
const entry = addMayorMessage(nudgeTarget, message, 'failed', result.error);
res.status(500).json({
error: result.error || 'Failed to send message',
messageId: entry.id
});
}
} catch (err) {
const entry = addMayorMessage(nudgeTarget, message, 'failed', err.message);
res.status(500).json({ error: err.message, messageId: entry.id });
}
});
// Get Mayor message history
app.get('/api/mayor/messages', (req, res) => {
const limit = Math.min(parseInt(req.query.limit) || 50, MAX_MESSAGE_HISTORY);
res.json(mayorMessageHistory.slice(0, limit));
});
// Get related PRs/commits for a bead
app.get('/api/bead/:beadId/links', async (req, res) => {
const { beadId } = req.params;
const links = { prs: [], commits: [] };
try {
// Get bead details to check close time for matching
const beadResult = await executeBD(['show', beadId, '--json']);
let beadClosedAt = null;
if (beadResult.success) {
const beadData = parseJSON(beadResult.data);
const bead = Array.isArray(beadData) ? beadData[0] : beadData;
if (bead && bead.closed_at) {
beadClosedAt = new Date(bead.closed_at);
}
}
// Get list of rig names
const rigsResult = await executeGT(['rig', 'list']);
if (!rigsResult.success) {
return res.json(links);
}
// Parse rig names from both legacy and emoji-prefixed formats
const rigNames = parseRigNames(rigsResult.data).map((rig) => rig.name);
console.log(`[Links] Found rigs: ${rigNames.join(', ')}`);
// Get repo URL for each rig by checking git remote
for (const rigName of rigNames) {
const rigPath = path.join(GT_ROOT, rigName, 'mayor', 'rig');
try {
const { stdout } = await execFileAsync('git', ['-C', rigPath, 'remote', 'get-url', 'origin'], { timeout: 5000 });
const repoUrl = String(stdout || '').trim();
// Extract owner/repo from GitHub URL
const repoMatch = repoUrl.match(/github\.com[/:]([^/]+\/[^/.\s]+)/);
if (!repoMatch) continue;
const repo = repoMatch[1].replace(/\.git$/, '');
// Search for PRs (title, body, branch containing bead ID, or polecat PRs near close time)
try {
const { stdout: prOutput } = await execFileAsync(
'gh',
['pr', 'list', '--repo', repo, '--state', 'all', '--limit', '20', '--json', 'number,title,url,state,headRefName,body,createdAt,updatedAt'],
{ timeout: 10000 }
);
const prs = JSON.parse(String(prOutput || '') || '[]');
for (const pr of prs) {
// Check if PR is related to this bead
let isRelated =
(pr.title && pr.title.includes(beadId)) ||
(pr.headRefName && pr.headRefName.includes(beadId)) ||
(pr.body && pr.body.includes(beadId));
// Also match polecat PRs created/updated within 1 hour of bead close time
if (!isRelated && beadClosedAt && pr.headRefName && pr.headRefName.startsWith('polecat/')) {
const prUpdated = new Date(pr.updatedAt || pr.createdAt);
const timeDiff = Math.abs(beadClosedAt - prUpdated);
const oneHour = 60 * 60 * 1000;
if (timeDiff < oneHour) {
isRelated = true;
}
}
if (isRelated) {
links.prs.push({
repo,
number: pr.number,
title: pr.title,
url: pr.url,
state: pr.state,
branch: pr.headRefName,
});
}
}
} catch (ghErr) {
console.log(`[Links] Could not search ${repo}: ${ghErr.message}`);
}
} catch (gitErr) {
// Skip rigs without git repos
console.log(`[Links] Could not get repo for ${rigName}: ${gitErr.message}`);
}
}
res.json(links);
} catch (err) {
console.error('[Links] Error:', err);
res.json(links);
}
});
// Get agent list
app.get('/api/agents', async (req, res) => {
// Check cache
if (req.query.refresh !== 'true') {
const cached = getCached('agents');
if (cached) return res.json(cached);
}
const [result, runningAddresses] = await Promise.all([
executeGT(['status', '--json', '--fast'], { timeout: 30000 }),
getRunningAgentAddresses()
]);
if (result.success) {
const data = parseJSON(result.data);
const agents = data?.agents || [];
// Enhance agents with running state
for (const agent of agents) {
agent.running = runningAddresses.has(agent.address?.replace(/\/$/, ''));
}
// Also include running polecats from rigs
const polecats = [];
for (const rig of data?.rigs || []) {
for (const hook of rig.hooks || []) {
const isRunning = runningAddresses.has(hook.agent) ||
runningAddresses.has(hook.agent?.replace(/\//, '/polecats/'));
polecats.push({
name: hook.agent,
rig: rig.name,
role: hook.role,
running: isRunning,
has_work: hook.has_work,
hook_bead: hook.hook_bead
});
}
}
const response = { agents, polecats, runningPolecats: Array.from(runningAddresses) };
setCache('agents', response, CACHE_TTL.agents);
res.json(response);
} else {
res.status(500).json({ error: result.error });
}
});
// Get Mayor output (tmux buffer)
app.get('/api/mayor/output', async (req, res) => {
const lines = parseInt(req.query.lines) || 100;
const sessionName = mayorSessionName();
try {
const output = await getPolecatOutput(sessionName, lines);
const isRunning = await isSessionRunning(sessionName);
if (output !== null) {
res.json({
session: sessionName,
output,
running: isRunning,
// Include recent messages sent to Mayor for context
recentMessages: mayorMessageHistory.slice(0, 10)
});
} else {
res.json({ session: sessionName, output: null, running: isRunning, recentMessages: [] });
}
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Get polecat output (what they're working on)
app.get('/api/polecat/:rig/:name/output', async (req, res) => {