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