claude-code-controller 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1110 @@
1
+ // src/controller.ts
2
+ import { EventEmitter } from "events";
3
+ import { execSync as execSync2 } from "child_process";
4
+ import { randomUUID as randomUUID2 } from "crypto";
5
+
6
+ // src/team-manager.ts
7
+ import { readFile, writeFile, mkdir, rm } from "fs/promises";
8
+ import { existsSync } from "fs";
9
+ import { randomUUID } from "crypto";
10
+
11
+ // src/paths.ts
12
+ import { homedir } from "os";
13
+ import { join } from "path";
14
+ var CLAUDE_DIR = join(homedir(), ".claude");
15
+ function teamsDir() {
16
+ return join(CLAUDE_DIR, "teams");
17
+ }
18
+ function teamDir(teamName) {
19
+ return join(teamsDir(), teamName);
20
+ }
21
+ function teamConfigPath(teamName) {
22
+ return join(teamDir(teamName), "config.json");
23
+ }
24
+ function inboxesDir(teamName) {
25
+ return join(teamDir(teamName), "inboxes");
26
+ }
27
+ function inboxPath(teamName, agentName) {
28
+ return join(inboxesDir(teamName), `${agentName}.json`);
29
+ }
30
+ function tasksBaseDir() {
31
+ return join(CLAUDE_DIR, "tasks");
32
+ }
33
+ function tasksDir(teamName) {
34
+ return join(tasksBaseDir(), teamName);
35
+ }
36
+ function taskPath(teamName, taskId) {
37
+ return join(tasksDir(teamName), `${taskId}.json`);
38
+ }
39
+
40
+ // src/team-manager.ts
41
+ var TeamManager = class {
42
+ teamName;
43
+ sessionId;
44
+ log;
45
+ constructor(teamName, logger) {
46
+ this.teamName = teamName;
47
+ this.sessionId = randomUUID();
48
+ this.log = logger;
49
+ }
50
+ /**
51
+ * Create the team directory structure and config.json.
52
+ * The controller registers itself as the lead member.
53
+ */
54
+ async create(opts) {
55
+ const dir = teamDir(this.teamName);
56
+ const inboxDir = inboxesDir(this.teamName);
57
+ const taskDir = tasksDir(this.teamName);
58
+ await mkdir(dir, { recursive: true });
59
+ await mkdir(inboxDir, { recursive: true });
60
+ await mkdir(taskDir, { recursive: true });
61
+ const leadName = "controller";
62
+ const leadAgentId = `${leadName}@${this.teamName}`;
63
+ const config = {
64
+ name: this.teamName,
65
+ description: opts?.description,
66
+ createdAt: Date.now(),
67
+ leadAgentId,
68
+ leadSessionId: this.sessionId,
69
+ members: [
70
+ {
71
+ agentId: leadAgentId,
72
+ name: leadName,
73
+ agentType: "controller",
74
+ joinedAt: Date.now(),
75
+ tmuxPaneId: "",
76
+ cwd: opts?.cwd || process.cwd(),
77
+ subscriptions: []
78
+ }
79
+ ]
80
+ };
81
+ await this.writeConfig(config);
82
+ this.log.info(`Team "${this.teamName}" created`);
83
+ return config;
84
+ }
85
+ /**
86
+ * Add a member to the team config.
87
+ */
88
+ async addMember(member) {
89
+ const config = await this.getConfig();
90
+ config.members = config.members.filter((m) => m.name !== member.name);
91
+ config.members.push(member);
92
+ await this.writeConfig(config);
93
+ this.log.debug(`Added member "${member.name}" to team`);
94
+ }
95
+ /**
96
+ * Remove a member from the team config.
97
+ */
98
+ async removeMember(name) {
99
+ const config = await this.getConfig();
100
+ config.members = config.members.filter((m) => m.name !== name);
101
+ await this.writeConfig(config);
102
+ this.log.debug(`Removed member "${name}" from team`);
103
+ }
104
+ /**
105
+ * Read the current team config.
106
+ */
107
+ async getConfig() {
108
+ const path = teamConfigPath(this.teamName);
109
+ if (!existsSync(path)) {
110
+ throw new Error(
111
+ `Team "${this.teamName}" does not exist (no config.json)`
112
+ );
113
+ }
114
+ const raw = await readFile(path, "utf-8");
115
+ return JSON.parse(raw);
116
+ }
117
+ /**
118
+ * Check if the team already exists on disk.
119
+ */
120
+ exists() {
121
+ return existsSync(teamConfigPath(this.teamName));
122
+ }
123
+ /**
124
+ * Destroy the team: remove all team directories and task directories.
125
+ */
126
+ async destroy() {
127
+ const dir = teamDir(this.teamName);
128
+ const taskDir = tasksDir(this.teamName);
129
+ if (existsSync(dir)) {
130
+ await rm(dir, { recursive: true, force: true });
131
+ }
132
+ if (existsSync(taskDir)) {
133
+ await rm(taskDir, { recursive: true, force: true });
134
+ }
135
+ this.log.info(`Team "${this.teamName}" destroyed`);
136
+ }
137
+ async writeConfig(config) {
138
+ const path = teamConfigPath(this.teamName);
139
+ await writeFile(path, JSON.stringify(config, null, 2), "utf-8");
140
+ }
141
+ };
142
+
143
+ // src/task-manager.ts
144
+ import { readFile as readFile2, writeFile as writeFile2, readdir, mkdir as mkdir2, rm as rm2 } from "fs/promises";
145
+ import { existsSync as existsSync2 } from "fs";
146
+ var TaskManager = class {
147
+ constructor(teamName, log) {
148
+ this.teamName = teamName;
149
+ this.log = log;
150
+ }
151
+ nextId = 1;
152
+ /**
153
+ * Initialize the task directory. Call after team creation.
154
+ * Also scans for existing tasks to set the next ID correctly.
155
+ */
156
+ async init() {
157
+ const dir = tasksDir(this.teamName);
158
+ await mkdir2(dir, { recursive: true });
159
+ const existing = await this.list();
160
+ if (existing.length > 0) {
161
+ const maxId = Math.max(...existing.map((t) => parseInt(t.id, 10)));
162
+ this.nextId = maxId + 1;
163
+ }
164
+ }
165
+ /**
166
+ * Create a new task. Returns the assigned task ID.
167
+ */
168
+ async create(task) {
169
+ const id = String(this.nextId++);
170
+ const full = {
171
+ id,
172
+ subject: task.subject,
173
+ description: task.description,
174
+ activeForm: task.activeForm,
175
+ owner: task.owner,
176
+ status: task.status || "pending",
177
+ blocks: task.blocks || [],
178
+ blockedBy: task.blockedBy || [],
179
+ metadata: task.metadata
180
+ };
181
+ await this.writeTask(full);
182
+ this.log.debug(`Created task #${id}: ${task.subject}`);
183
+ return id;
184
+ }
185
+ /**
186
+ * Get a task by ID.
187
+ */
188
+ async get(taskId) {
189
+ const path = taskPath(this.teamName, taskId);
190
+ if (!existsSync2(path)) {
191
+ throw new Error(`Task #${taskId} not found`);
192
+ }
193
+ const raw = await readFile2(path, "utf-8");
194
+ return JSON.parse(raw);
195
+ }
196
+ /**
197
+ * Update a task. Merges the provided fields.
198
+ */
199
+ async update(taskId, updates) {
200
+ const task = await this.get(taskId);
201
+ Object.assign(task, updates);
202
+ await this.writeTask(task);
203
+ this.log.debug(`Updated task #${taskId}: status=${task.status}`);
204
+ return task;
205
+ }
206
+ /**
207
+ * Add blocking relationships.
208
+ */
209
+ async addBlocks(taskId, blockedTaskIds) {
210
+ const task = await this.get(taskId);
211
+ const toAdd = blockedTaskIds.filter((id) => !task.blocks.includes(id));
212
+ task.blocks.push(...toAdd);
213
+ await this.writeTask(task);
214
+ for (const blockedId of toAdd) {
215
+ const blocked = await this.get(blockedId);
216
+ if (!blocked.blockedBy.includes(taskId)) {
217
+ blocked.blockedBy.push(taskId);
218
+ await this.writeTask(blocked);
219
+ }
220
+ }
221
+ }
222
+ /**
223
+ * List all tasks.
224
+ */
225
+ async list() {
226
+ const dir = tasksDir(this.teamName);
227
+ if (!existsSync2(dir)) return [];
228
+ const files = await readdir(dir);
229
+ const tasks = [];
230
+ for (const file of files) {
231
+ if (!file.endsWith(".json")) continue;
232
+ const raw = await readFile2(taskPath(this.teamName, file.replace(".json", "")), "utf-8");
233
+ tasks.push(JSON.parse(raw));
234
+ }
235
+ return tasks.sort((a, b) => parseInt(a.id) - parseInt(b.id));
236
+ }
237
+ /**
238
+ * Delete a task file.
239
+ */
240
+ async delete(taskId) {
241
+ const path = taskPath(this.teamName, taskId);
242
+ if (existsSync2(path)) {
243
+ await rm2(path);
244
+ this.log.debug(`Deleted task #${taskId}`);
245
+ }
246
+ }
247
+ /**
248
+ * Wait for a task to reach a target status.
249
+ */
250
+ async waitFor(taskId, targetStatus = "completed", opts) {
251
+ const timeout = opts?.timeout ?? 3e5;
252
+ const interval = opts?.pollInterval ?? 1e3;
253
+ const deadline = Date.now() + timeout;
254
+ while (Date.now() < deadline) {
255
+ const task = await this.get(taskId);
256
+ if (task.status === targetStatus) return task;
257
+ await sleep(interval);
258
+ }
259
+ throw new Error(
260
+ `Timeout waiting for task #${taskId} to reach "${targetStatus}"`
261
+ );
262
+ }
263
+ async writeTask(task) {
264
+ const path = taskPath(this.teamName, task.id);
265
+ await writeFile2(path, JSON.stringify(task, null, 4), "utf-8");
266
+ }
267
+ };
268
+ function sleep(ms) {
269
+ return new Promise((r) => setTimeout(r, ms));
270
+ }
271
+
272
+ // src/process-manager.ts
273
+ import { spawn } from "child_process";
274
+ import { execSync } from "child_process";
275
+ var ProcessManager = class {
276
+ processes = /* @__PURE__ */ new Map();
277
+ log;
278
+ constructor(logger) {
279
+ this.log = logger;
280
+ }
281
+ /**
282
+ * Spawn a new claude CLI process in teammate mode.
283
+ * Uses a Python PTY wrapper to provide the terminal the TUI needs.
284
+ */
285
+ spawn(opts) {
286
+ let binary = opts.claudeBinary || "claude";
287
+ if (!binary.startsWith("/")) {
288
+ try {
289
+ binary = execSync(`which ${binary}`, { encoding: "utf-8" }).trim();
290
+ } catch {
291
+ }
292
+ }
293
+ const claudeArgs = [
294
+ "--teammate-mode",
295
+ opts.teammateMode || "auto",
296
+ "--agent-id",
297
+ opts.agentId,
298
+ "--agent-name",
299
+ opts.agentName,
300
+ "--team-name",
301
+ opts.teamName
302
+ ];
303
+ if (opts.agentType) {
304
+ claudeArgs.push("--agent-type", opts.agentType);
305
+ }
306
+ if (opts.color) {
307
+ claudeArgs.push("--agent-color", opts.color);
308
+ }
309
+ if (opts.parentSessionId) {
310
+ claudeArgs.push("--parent-session-id", opts.parentSessionId);
311
+ }
312
+ if (opts.model) {
313
+ claudeArgs.push("--model", opts.model);
314
+ }
315
+ if (opts.permissions) {
316
+ for (const perm of opts.permissions) {
317
+ claudeArgs.push("--allowedTools", perm);
318
+ }
319
+ }
320
+ this.log.info(
321
+ `Spawning agent "${opts.agentName}": ${binary} ${claudeArgs.join(" ")}`
322
+ );
323
+ const cmdJson = JSON.stringify([binary, ...claudeArgs]);
324
+ const pythonScript = `
325
+ import pty, os, sys, json, signal, select
326
+
327
+ cmd = json.loads(sys.argv[1])
328
+ pid, fd = pty.fork()
329
+ if pid == 0:
330
+ os.execvp(cmd[0], cmd)
331
+ else:
332
+ signal.signal(signal.SIGTERM, lambda *a: (os.kill(pid, signal.SIGTERM), sys.exit(0)))
333
+ signal.signal(signal.SIGINT, lambda *a: (os.kill(pid, signal.SIGTERM), sys.exit(0)))
334
+ try:
335
+ while True:
336
+ r, _, _ = select.select([fd, 0], [], [], 1.0)
337
+ if fd in r:
338
+ try:
339
+ data = os.read(fd, 4096)
340
+ if not data:
341
+ break
342
+ os.write(1, data)
343
+ except OSError:
344
+ break
345
+ if 0 in r:
346
+ try:
347
+ data = os.read(0, 4096)
348
+ if not data:
349
+ break
350
+ os.write(fd, data)
351
+ except OSError:
352
+ break
353
+ except:
354
+ pass
355
+ finally:
356
+ try:
357
+ os.kill(pid, signal.SIGTERM)
358
+ except:
359
+ pass
360
+ _, status = os.waitpid(pid, 0)
361
+ sys.exit(os.WEXITSTATUS(status) if os.WIFEXITED(status) else 1)
362
+ `;
363
+ const proc = spawn("python3", ["-c", pythonScript, cmdJson], {
364
+ cwd: opts.cwd || process.cwd(),
365
+ stdio: ["pipe", "pipe", "pipe"],
366
+ env: {
367
+ ...process.env,
368
+ CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: "1",
369
+ ...opts.env
370
+ }
371
+ });
372
+ this.processes.set(opts.agentName, proc);
373
+ proc.on("exit", (code, signal) => {
374
+ this.log.info(
375
+ `Agent "${opts.agentName}" exited (code=${code}, signal=${signal})`
376
+ );
377
+ this.processes.delete(opts.agentName);
378
+ });
379
+ proc.on("error", (err) => {
380
+ this.log.error(`Agent "${opts.agentName}" process error: ${err.message}`);
381
+ this.processes.delete(opts.agentName);
382
+ });
383
+ return proc;
384
+ }
385
+ /**
386
+ * Register a callback for when an agent process exits.
387
+ */
388
+ onExit(name, callback) {
389
+ const proc = this.processes.get(name);
390
+ if (proc) proc.on("exit", (code) => callback(code));
391
+ }
392
+ /**
393
+ * Get the process for a named agent.
394
+ */
395
+ get(name) {
396
+ return this.processes.get(name);
397
+ }
398
+ /**
399
+ * Check if an agent process is still running.
400
+ */
401
+ isRunning(name) {
402
+ const proc = this.processes.get(name);
403
+ return proc !== void 0 && proc.exitCode === null && !proc.killed;
404
+ }
405
+ /**
406
+ * Get the PID of a running agent.
407
+ */
408
+ getPid(name) {
409
+ return this.processes.get(name)?.pid;
410
+ }
411
+ /**
412
+ * Kill a specific agent process.
413
+ */
414
+ async kill(name, signal = "SIGTERM") {
415
+ const proc = this.processes.get(name);
416
+ if (!proc) return;
417
+ proc.kill(signal);
418
+ await Promise.race([
419
+ new Promise((resolve) => proc.on("exit", () => resolve())),
420
+ new Promise(
421
+ (resolve) => setTimeout(() => {
422
+ if (this.processes.has(name)) {
423
+ this.log.warn(`Force-killing agent "${name}" with SIGKILL`);
424
+ try {
425
+ proc.kill("SIGKILL");
426
+ } catch {
427
+ }
428
+ }
429
+ resolve();
430
+ }, 5e3)
431
+ )
432
+ ]);
433
+ this.processes.delete(name);
434
+ }
435
+ /**
436
+ * Kill all agent processes.
437
+ */
438
+ async killAll() {
439
+ const names = [...this.processes.keys()];
440
+ await Promise.all(names.map((name) => this.kill(name)));
441
+ }
442
+ /**
443
+ * Get all running agent names.
444
+ */
445
+ runningAgents() {
446
+ return [...this.processes.keys()].filter((n) => this.isRunning(n));
447
+ }
448
+ };
449
+
450
+ // src/inbox.ts
451
+ import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "fs/promises";
452
+ import { existsSync as existsSync3 } from "fs";
453
+ import { dirname } from "path";
454
+ import { lock } from "proper-lockfile";
455
+ var LOCK_OPTIONS = {
456
+ retries: { retries: 5, minTimeout: 50, maxTimeout: 500 },
457
+ stale: 1e4
458
+ };
459
+ async function ensureDir(filePath) {
460
+ const dir = dirname(filePath);
461
+ if (!existsSync3(dir)) {
462
+ await mkdir3(dir, { recursive: true });
463
+ }
464
+ }
465
+ async function ensureFile(filePath) {
466
+ await ensureDir(filePath);
467
+ if (!existsSync3(filePath)) {
468
+ await writeFile3(filePath, "[]", "utf-8");
469
+ }
470
+ }
471
+ async function writeInbox(teamName, agentName, message, logger) {
472
+ const path = inboxPath(teamName, agentName);
473
+ await ensureFile(path);
474
+ let release;
475
+ try {
476
+ release = await lock(path, LOCK_OPTIONS);
477
+ const raw = await readFile3(path, "utf-8");
478
+ const messages = JSON.parse(raw || "[]");
479
+ messages.push({ ...message, read: false });
480
+ await writeFile3(path, JSON.stringify(messages, null, 2), "utf-8");
481
+ logger?.debug(`Wrote message to inbox ${agentName}`, message.from);
482
+ } finally {
483
+ if (release) await release();
484
+ }
485
+ }
486
+ async function readInbox(teamName, agentName) {
487
+ const path = inboxPath(teamName, agentName);
488
+ if (!existsSync3(path)) return [];
489
+ const raw = await readFile3(path, "utf-8");
490
+ return JSON.parse(raw || "[]");
491
+ }
492
+ async function readUnread(teamName, agentName) {
493
+ const path = inboxPath(teamName, agentName);
494
+ if (!existsSync3(path)) return [];
495
+ let release;
496
+ try {
497
+ release = await lock(path, LOCK_OPTIONS);
498
+ const raw = await readFile3(path, "utf-8");
499
+ const messages = JSON.parse(raw || "[]");
500
+ const unread = messages.filter((m) => !m.read);
501
+ if (unread.length === 0) return [];
502
+ for (const m of messages) {
503
+ m.read = true;
504
+ }
505
+ await writeFile3(path, JSON.stringify(messages, null, 2), "utf-8");
506
+ return unread;
507
+ } finally {
508
+ if (release) await release();
509
+ }
510
+ }
511
+ function parseMessage(msg) {
512
+ try {
513
+ const parsed = JSON.parse(msg.text);
514
+ if (parsed && typeof parsed === "object" && "type" in parsed) {
515
+ return parsed;
516
+ }
517
+ } catch {
518
+ }
519
+ return { type: "plain_text", text: msg.text };
520
+ }
521
+
522
+ // src/inbox-poller.ts
523
+ var InboxPoller = class {
524
+ teamName;
525
+ agentName;
526
+ interval;
527
+ timer = null;
528
+ log;
529
+ handlers = [];
530
+ constructor(teamName, agentName, logger, opts) {
531
+ this.teamName = teamName;
532
+ this.agentName = agentName;
533
+ this.log = logger;
534
+ this.interval = opts?.pollInterval ?? 500;
535
+ }
536
+ /**
537
+ * Register a handler for new messages.
538
+ */
539
+ onMessages(handler) {
540
+ this.handlers.push(handler);
541
+ }
542
+ /**
543
+ * Start polling.
544
+ */
545
+ start() {
546
+ if (this.timer) return;
547
+ this.log.debug(
548
+ `Starting inbox poller for "${this.agentName}" (interval=${this.interval}ms)`
549
+ );
550
+ this.timer = setInterval(() => this.poll(), this.interval);
551
+ }
552
+ /**
553
+ * Stop polling.
554
+ */
555
+ stop() {
556
+ if (this.timer) {
557
+ clearInterval(this.timer);
558
+ this.timer = null;
559
+ this.log.debug(`Stopped inbox poller for "${this.agentName}"`);
560
+ }
561
+ }
562
+ /**
563
+ * Poll once for new messages.
564
+ */
565
+ async poll() {
566
+ try {
567
+ const unread = await readUnread(this.teamName, this.agentName);
568
+ if (unread.length === 0) return [];
569
+ const events = unread.map((raw) => ({
570
+ raw,
571
+ parsed: parseMessage(raw)
572
+ }));
573
+ for (const handler of this.handlers) {
574
+ try {
575
+ handler(events);
576
+ } catch (err) {
577
+ this.log.error("Inbox handler error:", String(err));
578
+ }
579
+ }
580
+ return events;
581
+ } catch (err) {
582
+ this.log.error("Inbox poll error:", String(err));
583
+ return [];
584
+ }
585
+ }
586
+ };
587
+
588
+ // src/agent-handle.ts
589
+ var AgentHandle = class {
590
+ name;
591
+ pid;
592
+ controller;
593
+ constructor(controller, name, pid) {
594
+ this.controller = controller;
595
+ this.name = name;
596
+ this.pid = pid;
597
+ }
598
+ /**
599
+ * Send a message to this agent.
600
+ */
601
+ async send(message, summary) {
602
+ return this.controller.send(this.name, message, summary);
603
+ }
604
+ /**
605
+ * Wait for a response from this agent.
606
+ * Returns the text of the first unread plain-text message.
607
+ */
608
+ async receive(opts) {
609
+ const messages = await this.controller.receive(this.name, opts);
610
+ const texts = messages.map((m) => m.text);
611
+ return texts.join("\n");
612
+ }
613
+ /**
614
+ * Send a message and wait for the response. Convenience method.
615
+ */
616
+ async ask(question, opts) {
617
+ await this.send(question);
618
+ return this.receive(opts);
619
+ }
620
+ /**
621
+ * Check if the agent process is still running.
622
+ */
623
+ get isRunning() {
624
+ return this.controller.isAgentRunning(this.name);
625
+ }
626
+ /**
627
+ * Request the agent to shut down gracefully.
628
+ */
629
+ async shutdown() {
630
+ return this.controller.sendShutdownRequest(this.name);
631
+ }
632
+ /**
633
+ * Force-kill the agent process.
634
+ */
635
+ async kill() {
636
+ return this.controller.killAgent(this.name);
637
+ }
638
+ /**
639
+ * Async iterator for agent events (messages from this agent).
640
+ * Polls the controller's inbox for messages from this agent.
641
+ */
642
+ async *events(opts) {
643
+ const interval = opts?.pollInterval ?? 500;
644
+ const timeout = opts?.timeout ?? 0;
645
+ const deadline = timeout > 0 ? Date.now() + timeout : Infinity;
646
+ while (Date.now() < deadline) {
647
+ try {
648
+ const messages = await this.controller.receive(this.name, {
649
+ timeout: interval,
650
+ pollInterval: interval
651
+ });
652
+ for (const msg of messages) {
653
+ yield msg;
654
+ }
655
+ } catch {
656
+ }
657
+ if (!this.isRunning) return;
658
+ }
659
+ }
660
+ };
661
+
662
+ // src/logger.ts
663
+ var LEVELS = {
664
+ debug: 0,
665
+ info: 1,
666
+ warn: 2,
667
+ error: 3,
668
+ silent: 4
669
+ };
670
+ function createLogger(level = "info") {
671
+ const threshold = LEVELS[level];
672
+ const noop = () => {
673
+ };
674
+ const make = (lvl, fn) => (msg, ...args) => {
675
+ if (LEVELS[lvl] >= threshold) {
676
+ fn(`[claude-ctrl:${lvl}]`, msg, ...args);
677
+ }
678
+ };
679
+ return {
680
+ debug: threshold <= LEVELS.debug ? make("debug", console.debug) : noop,
681
+ info: threshold <= LEVELS.info ? make("info", console.info) : noop,
682
+ warn: threshold <= LEVELS.warn ? make("warn", console.warn) : noop,
683
+ error: threshold <= LEVELS.error ? make("error", console.error) : noop
684
+ };
685
+ }
686
+ var silentLogger = {
687
+ debug: () => {
688
+ },
689
+ info: () => {
690
+ },
691
+ warn: () => {
692
+ },
693
+ error: () => {
694
+ }
695
+ };
696
+
697
+ // src/controller.ts
698
+ var AGENT_COLORS = [
699
+ "#00FF00",
700
+ "#00BFFF",
701
+ "#FF6347",
702
+ "#FFD700",
703
+ "#DA70D6",
704
+ "#40E0D0",
705
+ "#FF69B4",
706
+ "#7B68EE"
707
+ ];
708
+ var ClaudeCodeController = class extends EventEmitter {
709
+ teamName;
710
+ team;
711
+ tasks;
712
+ processes;
713
+ poller;
714
+ log;
715
+ cwd;
716
+ claudeBinary;
717
+ defaultEnv;
718
+ colorIndex = 0;
719
+ initialized = false;
720
+ constructor(opts) {
721
+ super();
722
+ this.teamName = opts?.teamName || `ctrl-${randomUUID2().slice(0, 8)}`;
723
+ this.cwd = opts?.cwd || process.cwd();
724
+ this.claudeBinary = opts?.claudeBinary || "claude";
725
+ this.defaultEnv = opts?.env || {};
726
+ this.log = opts?.logger || createLogger(opts?.logLevel ?? "info");
727
+ this.team = new TeamManager(this.teamName, this.log);
728
+ this.tasks = new TaskManager(this.teamName, this.log);
729
+ this.processes = new ProcessManager(this.log);
730
+ this.poller = new InboxPoller(
731
+ this.teamName,
732
+ "controller",
733
+ this.log
734
+ );
735
+ this.poller.onMessages((events) => this.handlePollEvents(events));
736
+ }
737
+ // ─── Lifecycle ───────────────────────────────────────────────────────
738
+ /**
739
+ * Initialize the controller: create the team and start polling.
740
+ * Must be called before any other operations.
741
+ */
742
+ async init() {
743
+ if (this.initialized) return this;
744
+ await this.team.create({ cwd: this.cwd });
745
+ await this.tasks.init();
746
+ this.poller.start();
747
+ this.initialized = true;
748
+ this.log.info(
749
+ `Controller initialized (team="${this.teamName}")`
750
+ );
751
+ return this;
752
+ }
753
+ /**
754
+ * Graceful shutdown:
755
+ * 1. Send shutdown requests to all agents
756
+ * 2. Wait briefly for acknowledgment
757
+ * 3. Kill remaining processes
758
+ * 4. Clean up team files
759
+ */
760
+ async shutdown() {
761
+ this.log.info("Shutting down controller...");
762
+ const running = this.processes.runningAgents();
763
+ const shutdownPromises = [];
764
+ for (const name of running) {
765
+ try {
766
+ await this.sendShutdownRequest(name);
767
+ shutdownPromises.push(
768
+ new Promise((resolve) => {
769
+ const proc = this.processes.get(name);
770
+ if (!proc) return resolve();
771
+ const timer = setTimeout(() => resolve(), 1e4);
772
+ proc.on("exit", () => {
773
+ clearTimeout(timer);
774
+ resolve();
775
+ });
776
+ })
777
+ );
778
+ } catch {
779
+ }
780
+ }
781
+ if (shutdownPromises.length > 0) {
782
+ await Promise.all(shutdownPromises);
783
+ }
784
+ await this.processes.killAll();
785
+ this.poller.stop();
786
+ await this.team.destroy();
787
+ this.initialized = false;
788
+ this.log.info("Controller shut down");
789
+ }
790
+ // ─── Agent Management ────────────────────────────────────────────────
791
+ /**
792
+ * Spawn a new Claude Code agent.
793
+ */
794
+ async spawnAgent(opts) {
795
+ this.ensureInitialized();
796
+ const agentId = `${opts.name}@${this.teamName}`;
797
+ const color = AGENT_COLORS[this.colorIndex++ % AGENT_COLORS.length];
798
+ const cwd = opts.cwd || this.cwd;
799
+ const member = {
800
+ agentId,
801
+ name: opts.name,
802
+ agentType: opts.type || "general-purpose",
803
+ model: opts.model,
804
+ joinedAt: Date.now(),
805
+ tmuxPaneId: "",
806
+ cwd,
807
+ subscriptions: []
808
+ };
809
+ await this.team.addMember(member);
810
+ const env = Object.keys(this.defaultEnv).length > 0 || opts.env ? { ...this.defaultEnv, ...opts.env } : void 0;
811
+ const proc = this.processes.spawn({
812
+ teamName: this.teamName,
813
+ agentName: opts.name,
814
+ agentId,
815
+ agentType: opts.type || "general-purpose",
816
+ model: opts.model,
817
+ cwd,
818
+ parentSessionId: this.team.sessionId,
819
+ color,
820
+ claudeBinary: this.claudeBinary,
821
+ permissions: opts.permissions,
822
+ env
823
+ });
824
+ this.emit("agent:spawned", opts.name, proc.pid ?? 0);
825
+ this.processes.onExit(opts.name, (code) => {
826
+ this.emit("agent:exited", opts.name, code ?? null);
827
+ });
828
+ return new AgentHandle(this, opts.name, proc.pid);
829
+ }
830
+ // ─── Messaging ───────────────────────────────────────────────────────
831
+ /**
832
+ * Send a message to a specific agent.
833
+ */
834
+ async send(agentName, message, summary) {
835
+ this.ensureInitialized();
836
+ await writeInbox(
837
+ this.teamName,
838
+ agentName,
839
+ {
840
+ from: "controller",
841
+ text: message,
842
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
843
+ summary
844
+ },
845
+ this.log
846
+ );
847
+ }
848
+ /**
849
+ * Send a structured shutdown request to an agent.
850
+ */
851
+ async sendShutdownRequest(agentName) {
852
+ const requestId = `shutdown-${Date.now()}@${agentName}`;
853
+ const msg = JSON.stringify({
854
+ type: "shutdown_request",
855
+ requestId,
856
+ from: "controller",
857
+ reason: "Controller shutdown requested",
858
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
859
+ });
860
+ await this.send(agentName, msg);
861
+ }
862
+ /**
863
+ * Broadcast a message to all registered agents (except controller).
864
+ */
865
+ async broadcast(message, summary) {
866
+ this.ensureInitialized();
867
+ const config = await this.team.getConfig();
868
+ const agents = config.members.filter((m) => m.name !== "controller");
869
+ await Promise.all(
870
+ agents.map((a) => this.send(a.name, message, summary))
871
+ );
872
+ }
873
+ /**
874
+ * Wait for messages from a specific agent.
875
+ * Polls the controller's inbox for messages from the given agent.
876
+ *
877
+ * Returns when:
878
+ * - A non-idle message is received (SendMessage from agent), OR
879
+ * - An idle_notification is received (agent finished its turn),
880
+ * in which case the idle message is returned.
881
+ */
882
+ async receive(agentName, opts) {
883
+ const timeout = opts?.timeout ?? 6e4;
884
+ const interval = opts?.pollInterval ?? 500;
885
+ const deadline = Date.now() + timeout;
886
+ while (Date.now() < deadline) {
887
+ const unread = await readUnread(this.teamName, "controller");
888
+ const fromAgent = unread.filter((m) => m.from === agentName);
889
+ if (fromAgent.length > 0) {
890
+ const PROTOCOL_TYPES = /* @__PURE__ */ new Set([
891
+ "shutdown_approved",
892
+ "plan_approval_response",
893
+ "permission_response"
894
+ ]);
895
+ const meaningful = fromAgent.filter((m) => {
896
+ const parsed = parseMessage(m);
897
+ return parsed.type !== "idle_notification" && !PROTOCOL_TYPES.has(parsed.type);
898
+ });
899
+ if (meaningful.length > 0) {
900
+ return opts?.all ? meaningful : [meaningful[0]];
901
+ }
902
+ const idles = fromAgent.filter((m) => {
903
+ const parsed = parseMessage(m);
904
+ return parsed.type === "idle_notification";
905
+ });
906
+ if (idles.length > 0) {
907
+ return opts?.all ? idles : [idles[0]];
908
+ }
909
+ }
910
+ await sleep2(interval);
911
+ }
912
+ throw new Error(
913
+ `Timeout (${timeout}ms) waiting for message from "${agentName}"`
914
+ );
915
+ }
916
+ /**
917
+ * Wait for any message from any agent.
918
+ */
919
+ async receiveAny(opts) {
920
+ const timeout = opts?.timeout ?? 6e4;
921
+ const interval = opts?.pollInterval ?? 500;
922
+ const deadline = Date.now() + timeout;
923
+ while (Date.now() < deadline) {
924
+ const unread = await readUnread(this.teamName, "controller");
925
+ const meaningful = unread.filter((m) => {
926
+ const parsed = parseMessage(m);
927
+ return parsed.type !== "idle_notification";
928
+ });
929
+ if (meaningful.length > 0) {
930
+ return meaningful[0];
931
+ }
932
+ await sleep2(interval);
933
+ }
934
+ throw new Error(`Timeout (${timeout}ms) waiting for any message`);
935
+ }
936
+ // ─── Tasks ───────────────────────────────────────────────────────────
937
+ /**
938
+ * Create a task and optionally notify the assigned agent.
939
+ */
940
+ async createTask(task) {
941
+ this.ensureInitialized();
942
+ const taskId = await this.tasks.create(task);
943
+ if (task.owner) {
944
+ const fullTask = await this.tasks.get(taskId);
945
+ const assignmentMsg = JSON.stringify({
946
+ type: "task_assignment",
947
+ taskId,
948
+ subject: fullTask.subject,
949
+ description: fullTask.description,
950
+ assignedBy: "controller",
951
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
952
+ });
953
+ await this.send(task.owner, assignmentMsg);
954
+ }
955
+ return taskId;
956
+ }
957
+ /**
958
+ * Assign a task to an agent.
959
+ */
960
+ async assignTask(taskId, agentName) {
961
+ const task = await this.tasks.update(taskId, { owner: agentName });
962
+ const msg = JSON.stringify({
963
+ type: "task_assignment",
964
+ taskId,
965
+ subject: task.subject,
966
+ description: task.description,
967
+ assignedBy: "controller",
968
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
969
+ });
970
+ await this.send(agentName, msg);
971
+ }
972
+ // ─── Protocol Responses ───────────────────────────────────────────
973
+ /**
974
+ * Approve or reject a teammate's plan.
975
+ * Send this in response to a `plan:approval_request` event.
976
+ */
977
+ async sendPlanApproval(agentName, requestId, approve, feedback) {
978
+ const msg = JSON.stringify({
979
+ type: "plan_approval_response",
980
+ requestId,
981
+ from: "controller",
982
+ approved: approve,
983
+ feedback,
984
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
985
+ });
986
+ await this.send(agentName, msg);
987
+ }
988
+ /**
989
+ * Approve or reject a teammate's permission/tool-use request.
990
+ * Send this in response to a `permission:request` event.
991
+ */
992
+ async sendPermissionResponse(agentName, requestId, approve) {
993
+ const msg = JSON.stringify({
994
+ type: "permission_response",
995
+ requestId,
996
+ from: "controller",
997
+ approved: approve,
998
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
999
+ });
1000
+ await this.send(agentName, msg);
1001
+ }
1002
+ /**
1003
+ * Wait for a task to be completed.
1004
+ */
1005
+ async waitForTask(taskId, timeout) {
1006
+ return this.tasks.waitFor(taskId, "completed", { timeout });
1007
+ }
1008
+ // ─── Utilities ───────────────────────────────────────────────────────
1009
+ /**
1010
+ * Check if an agent process is still running.
1011
+ */
1012
+ isAgentRunning(name) {
1013
+ return this.processes.isRunning(name);
1014
+ }
1015
+ /**
1016
+ * Kill a specific agent.
1017
+ */
1018
+ async killAgent(name) {
1019
+ await this.processes.kill(name);
1020
+ await this.team.removeMember(name);
1021
+ }
1022
+ /**
1023
+ * Get the installed Claude Code version.
1024
+ */
1025
+ getClaudeVersion() {
1026
+ try {
1027
+ const version = execSync2(`${this.claudeBinary} --version`, {
1028
+ encoding: "utf-8",
1029
+ timeout: 5e3
1030
+ }).trim();
1031
+ return version;
1032
+ } catch {
1033
+ return null;
1034
+ }
1035
+ }
1036
+ /**
1037
+ * Verify that the required CLI flags exist in the installed version.
1038
+ */
1039
+ verifyCompatibility() {
1040
+ const version = this.getClaudeVersion();
1041
+ return { compatible: version !== null, version };
1042
+ }
1043
+ // ─── Internal ────────────────────────────────────────────────────────
1044
+ handlePollEvents(events) {
1045
+ for (const event of events) {
1046
+ const { raw, parsed } = event;
1047
+ switch (parsed.type) {
1048
+ case "idle_notification":
1049
+ this.emit("idle", raw.from);
1050
+ break;
1051
+ case "shutdown_approved":
1052
+ this.log.info(
1053
+ `Shutdown approved by "${raw.from}" (requestId=${parsed.requestId})`
1054
+ );
1055
+ this.emit("shutdown:approved", raw.from, parsed);
1056
+ break;
1057
+ case "plan_approval_request":
1058
+ this.log.info(
1059
+ `Plan approval request from "${raw.from}" (requestId=${parsed.requestId})`
1060
+ );
1061
+ this.emit("plan:approval_request", raw.from, parsed);
1062
+ break;
1063
+ case "permission_request":
1064
+ this.log.info(
1065
+ `Permission request from "${raw.from}": ${parsed.toolName} (requestId=${parsed.requestId})`
1066
+ );
1067
+ this.emit("permission:request", raw.from, parsed);
1068
+ break;
1069
+ case "plain_text":
1070
+ this.emit("message", raw.from, raw);
1071
+ break;
1072
+ default:
1073
+ this.emit("message", raw.from, raw);
1074
+ }
1075
+ }
1076
+ }
1077
+ ensureInitialized() {
1078
+ if (!this.initialized) {
1079
+ throw new Error(
1080
+ "Controller not initialized. Call init() first."
1081
+ );
1082
+ }
1083
+ }
1084
+ };
1085
+ function sleep2(ms) {
1086
+ return new Promise((r) => setTimeout(r, ms));
1087
+ }
1088
+ export {
1089
+ AgentHandle,
1090
+ ClaudeCodeController,
1091
+ InboxPoller,
1092
+ ProcessManager,
1093
+ TaskManager,
1094
+ TeamManager,
1095
+ createLogger,
1096
+ inboxPath,
1097
+ inboxesDir,
1098
+ parseMessage,
1099
+ readInbox,
1100
+ readUnread,
1101
+ silentLogger,
1102
+ taskPath,
1103
+ tasksBaseDir,
1104
+ tasksDir,
1105
+ teamConfigPath,
1106
+ teamDir,
1107
+ teamsDir,
1108
+ writeInbox
1109
+ };
1110
+ //# sourceMappingURL=index.js.map