@clagentic/console 1.5.0-beta.1 → 1.5.0-beta.3

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.
@@ -3,6 +3,8 @@ var path = require("path");
3
3
 
4
4
  // How long (ms) to keep processed trigger files before pruning on startup.
5
5
  var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
6
+ var POLL_INTERVAL_MS = 30 * 1000; // 30 s backstop scan
7
+ var WATCHER_REARM_INTERVAL_MS = 5 * 60 * 1000; // 5 min inotify rebind
6
8
 
7
9
  /**
8
10
  * External trigger watcher — global singleton.
@@ -35,6 +37,14 @@ var PROCESSED_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
35
37
  * Daemon-down recovery: unprocessed files that predate the current process
36
38
  * start are picked up via a startup scan (scanExisting). No file is lost
37
39
  * if the daemon is restarted while triggers are pending.
40
+ *
41
+ * Watcher hardening (three layers):
42
+ * Layer 1 — 30 s polling backstop: scanExisting() on an interval so files
43
+ * are never permanently missed if fs.watch silently dies.
44
+ * Layer 2 — 5 min periodic re-arm: close and re-open the fs.watch binding
45
+ * so the inotify registration is never more than 5 min stale.
46
+ * Layer 3 — health export: getHealth() returns watcher liveness, last-event
47
+ * timestamp, and poll-interval presence for external monitoring.
38
48
  */
39
49
  function attachExternalTrigger(ctx) {
40
50
  var triggersDir = ctx.triggersDir;
@@ -47,6 +57,11 @@ function attachExternalTrigger(ctx) {
47
57
  // from the initial scan + watcher race.
48
58
  var dispatched = {};
49
59
 
60
+ // Hardening state
61
+ var pollInterval = null;
62
+ var rearmTimer = null;
63
+ var watcherLastEventMs = 0;
64
+
50
65
  // --- Directory setup ---
51
66
 
52
67
  function ensureDirs() {
@@ -231,12 +246,16 @@ function attachExternalTrigger(ctx) {
231
246
  }, 200);
232
247
  }
233
248
 
234
- function startWatcher() {
235
- ensureDirs();
236
- pruneOldProcessed();
237
- scanExisting(); // pick up files dropped while daemon was down
249
+ // --- Layer 2: periodic watcher re-arm ---
250
+
251
+ function armWatcher() {
252
+ if (watcher) {
253
+ try { watcher.close(); } catch (e) {}
254
+ watcher = null;
255
+ }
238
256
  try {
239
257
  watcher = fs.watch(triggersDir, function (eventType, filename) {
258
+ watcherLastEventMs = Date.now();
240
259
  if (filename && !filename.endsWith(".json")) return;
241
260
  onDirChange();
242
261
  });
@@ -244,18 +263,47 @@ function attachExternalTrigger(ctx) {
244
263
  console.error("[external-trigger] Watcher error:", e.message || e);
245
264
  stopWatcher();
246
265
  });
247
- console.log("[external-trigger] Watching:", triggersDir);
248
266
  } catch (e) {
249
- console.error("[external-trigger] Failed to start watcher:", e.message || e);
267
+ console.error("[external-trigger] Failed to arm watcher:", e.message || e);
250
268
  }
251
269
  }
252
270
 
271
+ function startWatcher() {
272
+ ensureDirs();
273
+ pruneOldProcessed();
274
+ scanExisting(); // pick up files dropped while daemon was down
275
+
276
+ armWatcher();
277
+ console.log("[external-trigger] Watching:", triggersDir);
278
+
279
+ // Layer 1: polling backstop — catches files if fs.watch silently dies
280
+ pollInterval = setInterval(function () {
281
+ scanExisting();
282
+ }, POLL_INTERVAL_MS);
283
+ pollInterval.unref();
284
+
285
+ // Layer 2: periodic re-arm — keeps inotify registration fresh
286
+ rearmTimer = setInterval(function () {
287
+ armWatcher();
288
+ console.log("[external-trigger] Watcher re-armed");
289
+ }, WATCHER_REARM_INTERVAL_MS);
290
+ rearmTimer.unref();
291
+ }
292
+
253
293
  function stopWatcher() {
254
294
  clearTimeout(debounce);
255
295
  if (watcher) {
256
296
  try { watcher.close(); } catch (e) {}
257
297
  watcher = null;
258
298
  }
299
+ if (pollInterval) {
300
+ clearInterval(pollInterval);
301
+ pollInterval = null;
302
+ }
303
+ if (rearmTimer) {
304
+ clearInterval(rearmTimer);
305
+ rearmTimer = null;
306
+ }
259
307
  }
260
308
 
261
309
  // --- Startup scan (daemon-down recovery) ---
@@ -289,8 +337,15 @@ function attachExternalTrigger(ctx) {
289
337
  return {
290
338
  startWatcher: startWatcher,
291
339
  stopWatcher: stopWatcher,
340
+ // Layer 3: health export for external monitoring
341
+ getHealth: function () {
342
+ return {
343
+ watcherAlive: !!watcher,
344
+ lastEventMs: watcherLastEventMs,
345
+ pollActive: !!pollInterval,
346
+ };
347
+ },
292
348
  };
293
349
  }
294
350
 
295
351
  module.exports = { attachExternalTrigger: attachExternalTrigger };
296
-
@@ -26,8 +26,24 @@ var MAX_UPLOAD_BYTES = 50 * 1024 * 1024; // 50 MB
26
26
  function parseJsonBody(req) {
27
27
  return new Promise(function (resolve, reject) {
28
28
  var body = "";
29
- req.on("data", function (chunk) { body += chunk; });
29
+ var bodyBytes = 0;
30
+ // Hard cap: enforce limit while buffering, not only after full accumulation.
31
+ // 1.4x headroom covers base64-encoded payloads (base64 expands by ~4/3).
32
+ var hardCap = MAX_UPLOAD_BYTES * 1.4;
33
+ var rejected = false;
34
+ req.on("data", function (chunk) {
35
+ if (rejected) return;
36
+ bodyBytes += Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk);
37
+ if (bodyBytes > hardCap) {
38
+ rejected = true;
39
+ req.destroy();
40
+ reject(new Error("Request body too large"));
41
+ return;
42
+ }
43
+ body += chunk;
44
+ });
30
45
  req.on("end", function () {
46
+ if (rejected) return;
31
47
  try { resolve(JSON.parse(body)); }
32
48
  catch (e) { reject(e); }
33
49
  });
@@ -678,6 +678,7 @@ function attachLoop(ctx) {
678
678
  // Unlock the last coder session so users can continue interacting with it.
679
679
  // Capture owner before clearing state so push routing still works.
680
680
  var _loopOwnerUserId = null;
681
+ var _lastSessionId = loopState.currentSessionId;
681
682
  if (loopState.currentSessionId) {
682
683
  var lastCoderSession = sm.sessions.get(loopState.currentSessionId);
683
684
  if (lastCoderSession) {
@@ -737,7 +738,7 @@ function attachLoop(ctx) {
737
738
  name: loopState.name,
738
739
  iterations: loopState.iteration,
739
740
  maxIterations: loopState.maxIterations,
740
- sessionId: loopState.currentSessionId,
741
+ sessionId: _lastSessionId,
741
742
  });
742
743
  }
743
744
 
@@ -170,17 +170,55 @@ function attachSessions(ctx) {
170
170
  // Hidden client-side when active project is a Mate; we still answer here
171
171
  // because the daemon shouldn't make UX decisions that the client already
172
172
  // owns. UI gates the surface; daemon stays a data plane.
173
+ //
174
+ // Background refresh: respond immediately with the cached list, then kick
175
+ // off a refresh(). If the catalog changes, re-send to this client only.
176
+ // Cost is paid exactly when the user opens the agent picker — not on a timer.
173
177
  if (msg.type === "list_agents") {
174
178
  var favorites = [];
175
179
  var recents = [];
176
180
  try { favorites = agentsFavorites.listFavorites(); recents = agentsFavorites.listRecents(); }
177
181
  catch (e) { /* favorites are best-effort */ }
182
+ var cachedAgents = agentsModule.getAll();
178
183
  sendTo(ws, {
179
184
  type: "agents_list",
180
- agents: agentsModule.getAll(),
185
+ agents: cachedAgents,
181
186
  favorites: favorites,
182
187
  recents: recents,
183
188
  });
189
+ // Refresh in background; re-send only if the catalog changed.
190
+ var cachedJson = JSON.stringify(cachedAgents);
191
+ agentsModule.refresh().then(function () {
192
+ var freshAgents = agentsModule.getAll();
193
+ if (JSON.stringify(freshAgents) === cachedJson) return;
194
+ var favFresh = [];
195
+ var recFresh = [];
196
+ try { favFresh = agentsFavorites.listFavorites(); recFresh = agentsFavorites.listRecents(); }
197
+ catch (e) { /* best-effort */ }
198
+ sendTo(ws, { type: "agents_list", agents: freshAgents, favorites: favFresh, recents: recFresh });
199
+ }).catch(function (e) {
200
+ console.error("[project-sessions] background agent refresh failed:", e && e.message ? e.message : e);
201
+ });
202
+ return true;
203
+ }
204
+
205
+ // refresh_agents — explicit on-demand refresh triggered from the settings UI.
206
+ // Re-runs SDK discovery, then broadcasts the updated catalog to ALL connected
207
+ // clients. Responds immediately with ok:true (async broadcast follows).
208
+ if (msg.type === "refresh_agents") {
209
+ sendTo(ws, { type: "refresh_agents_result", ok: true });
210
+ agentsModule.refresh().then(function () {
211
+ var freshAgents = agentsModule.getAll();
212
+ var favFresh = [];
213
+ var recFresh = [];
214
+ try { favFresh = agentsFavorites.listFavorites(); recFresh = agentsFavorites.listRecents(); }
215
+ catch (e) { /* best-effort */ }
216
+ send({ type: "agents_list", agents: freshAgents, favorites: favFresh, recents: recFresh });
217
+ send({ type: "toast", level: "info", message: "Agent catalog refreshed — " + freshAgents.length + " agent" + (freshAgents.length === 1 ? "" : "s") + " found." });
218
+ }).catch(function (e) {
219
+ console.error("[project-sessions] refresh_agents failed:", e && e.message ? e.message : e);
220
+ send({ type: "toast", level: "error", message: "Agent catalog refresh failed." });
221
+ });
184
222
  return true;
185
223
  }
186
224
 
@@ -1555,6 +1593,7 @@ function attachSessions(ctx) {
1555
1593
  // --- Daemon config / server management (admin-only in multi-user mode) ---
1556
1594
  if (msg.type === "get_daemon_config" || msg.type === "set_pin" || msg.type === "set_keep_awake" ||
1557
1595
  msg.type === "set_auto_continue" || msg.type === "set_image_retention" || msg.type === "set_mem_available_threshold" ||
1596
+ msg.type === "set_tokens_per_mb_headroom" ||
1558
1597
  msg.type === "set_lite_auto_enroll" ||
1559
1598
  msg.type === "shutdown_server" || msg.type === "restart_server") {
1560
1599
  if (usersModule.isMultiUser()) {
@@ -1629,6 +1668,15 @@ function attachSessions(ctx) {
1629
1668
  return true;
1630
1669
  }
1631
1670
 
1671
+ if (msg.type === "set_tokens_per_mb_headroom") {
1672
+ if (typeof opts.onSetTokensPerMbHeadroom === "function") {
1673
+ var tpmResult = opts.onSetTokensPerMbHeadroom(msg.value);
1674
+ sendTo(ws, { type: "set_tokens_per_mb_headroom_result", ok: tpmResult.ok, tokensPerMbHeadroom: tpmResult.tokensPerMbHeadroom });
1675
+ send({ type: "tokens_per_mb_headroom_changed", tokensPerMbHeadroom: tpmResult.tokensPerMbHeadroom });
1676
+ }
1677
+ return true;
1678
+ }
1679
+
1632
1680
  if (msg.type === "shutdown_server") {
1633
1681
  if (typeof opts.onShutdown === "function") {
1634
1682
  sendTo(ws, { type: "shutdown_server_result", ok: true });
@@ -0,0 +1,417 @@
1
+ // lib/project-team.js
2
+ // Team activity watcher: watches ~/.claude/teams/, ~/.claude/tasks/, and
3
+ // per-teammate subagent JSONL files. Emits team_state, team_member_update,
4
+ // team_task_update, team_message, team_gone WS messages.
5
+
6
+ var fs = require("fs");
7
+ var path = require("path");
8
+ var utils = require("./utils");
9
+
10
+ function attachTeam(ctx) {
11
+ var send = ctx.send;
12
+ var config = ctx.config;
13
+ // sm is optional (may be null if not yet wired)
14
+ var sm = ctx.sm || null;
15
+
16
+ var teamState = null; // null or { teamId, teamName, description, members[], tasks[] }
17
+ var teamMessages = []; // last 50 team_message payloads
18
+ var agentTails = {}; // agentId -> { path, offset, watcher }
19
+ var memberLastActivity = {}; // agentId -> Unix ms timestamp
20
+ var memberStatus = {}; // agentId -> last known status string
21
+ var teamWatcher = null;
22
+ var taskWatcher = null;
23
+ var configWatcher = null;
24
+ var livenessTimer = null;
25
+ var deactivatePendingMs = 0; // epoch when deactivate-if-missing starts
26
+ var DEACTIVATE_AFTER_MS = 30000;
27
+
28
+ function getClaudeDir() {
29
+ return path.join(config.REAL_HOME, ".claude");
30
+ }
31
+
32
+ function getTeamDir(teamId) {
33
+ return path.join(getClaudeDir(), "teams", teamId);
34
+ }
35
+
36
+ function getTaskDir(teamId) {
37
+ return path.join(getClaudeDir(), "tasks", teamId);
38
+ }
39
+
40
+ function readJsonSafe(filePath) {
41
+ try {
42
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
43
+ } catch (e) {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ function emitTeamState() {
49
+ if (!teamState) return;
50
+ send({ type: "team_state", team: teamState, messages: teamMessages });
51
+ }
52
+
53
+ function emitTeamGone() {
54
+ send({ type: "team_gone" });
55
+ }
56
+
57
+ function deactivateTeam() {
58
+ // Stop all watchers and timers
59
+ if (livenessTimer) { clearInterval(livenessTimer); livenessTimer = null; }
60
+ if (configWatcher) { try { configWatcher.close(); } catch (e) {} configWatcher = null; }
61
+ if (taskWatcher) { try { taskWatcher.close(); } catch (e) {} taskWatcher = null; }
62
+
63
+ var agentIds = Object.keys(agentTails);
64
+ for (var i = 0; i < agentIds.length; i++) {
65
+ var tail = agentTails[agentIds[i]];
66
+ if (tail && tail.watcher) { try { tail.watcher.close(); } catch (e) {} }
67
+ }
68
+ agentTails = {};
69
+ memberLastActivity = {};
70
+ memberStatus = {};
71
+ deactivatePendingMs = 0;
72
+ teamMessages = [];
73
+ teamState = null;
74
+ emitTeamGone();
75
+ console.log("[project-team] Team deactivated");
76
+ }
77
+
78
+ function watchTaskDir(teamId) {
79
+ var dir = getTaskDir(teamId);
80
+ try {
81
+ if (!fs.existsSync(dir)) return;
82
+ } catch (e) {
83
+ return;
84
+ }
85
+
86
+ function readTasks() {
87
+ try {
88
+ var files = fs.readdirSync(dir);
89
+ var tasks = [];
90
+ for (var i = 0; i < files.length; i++) {
91
+ if (!files[i].endsWith(".json")) continue;
92
+ var t = readJsonSafe(path.join(dir, files[i]));
93
+ if (t) tasks.push(t);
94
+ }
95
+ return tasks;
96
+ } catch (e) {
97
+ return [];
98
+ }
99
+ }
100
+
101
+ var lastTasksJson = "";
102
+
103
+ function checkTasks() {
104
+ if (!teamState) return;
105
+ var tasks = readTasks();
106
+ var tasksJson = JSON.stringify(tasks);
107
+ if (tasksJson === lastTasksJson) return;
108
+ lastTasksJson = tasksJson;
109
+ teamState.tasks = tasks;
110
+ send({ type: "team_task_update", tasks: tasks });
111
+ }
112
+
113
+ try {
114
+ taskWatcher = fs.watch(dir, function (event) {
115
+ checkTasks();
116
+ });
117
+ taskWatcher.on("error", function () {});
118
+ checkTasks();
119
+ } catch (e) {
120
+ // task dir may not exist — no-op
121
+ }
122
+ }
123
+
124
+ function tailAgentJSONL(agentId, filePath) {
125
+ if (agentTails[agentId] && agentTails[agentId].watcher) {
126
+ // Already tailing this agent
127
+ return;
128
+ }
129
+
130
+ var entry = { path: filePath, offset: 0, watcher: null };
131
+ agentTails[agentId] = entry;
132
+
133
+ function readNewLines() {
134
+ try {
135
+ var stat = fs.statSync(filePath);
136
+ if (stat.size <= entry.offset) return;
137
+ var fd = fs.openSync(filePath, "r");
138
+ var bufSize = stat.size - entry.offset;
139
+ var buf = Buffer.alloc(bufSize);
140
+ var bytesRead = fs.readSync(fd, buf, 0, bufSize, entry.offset);
141
+ fs.closeSync(fd);
142
+ entry.offset += bytesRead;
143
+
144
+ var text = buf.slice(0, bytesRead).toString("utf8");
145
+ var lines = text.split("\n");
146
+ for (var i = 0; i < lines.length; i++) {
147
+ var line = lines[i].trim();
148
+ if (!line) continue;
149
+ try {
150
+ var parsed = JSON.parse(line);
151
+ processAgentLine(agentId, parsed);
152
+ } catch (e) {
153
+ // Non-JSON line — skip
154
+ }
155
+ }
156
+ } catch (e) {
157
+ // File may not exist or be unreadable — tolerate
158
+ }
159
+ }
160
+
161
+ function processAgentLine(aid, parsed) {
162
+ // Update liveness timestamp on any new line
163
+ memberLastActivity[aid] = Date.now();
164
+
165
+ // Look for SendMessage tool use (peer DM)
166
+ if (parsed.message && parsed.message.role === "assistant") {
167
+ var content = parsed.message.content;
168
+ if (Array.isArray(content)) {
169
+ for (var ci = 0; ci < content.length; ci++) {
170
+ var block = content[ci];
171
+ if (block.type === "tool_use") {
172
+ if (block.name === "SendMessage") {
173
+ var input = block.input || {};
174
+ var msg = {
175
+ fromAgentId: aid,
176
+ toAgentId: input.to || "",
177
+ summary: (input.message || "").slice(0, 120),
178
+ body: input.message || "",
179
+ ts: Date.now(),
180
+ };
181
+ teamMessages.push(msg);
182
+ if (teamMessages.length > 50) teamMessages.shift();
183
+ send({ type: "team_message", message: msg });
184
+ } else {
185
+ // Non-SendMessage tool_use: emit activity update
186
+ send({
187
+ type: "team_member_update",
188
+ agentId: aid,
189
+ currentActivity: block.name,
190
+ });
191
+ }
192
+ }
193
+ }
194
+ }
195
+ }
196
+ }
197
+
198
+ // Start watching the file
199
+ try {
200
+ // Read any existing content first
201
+ try {
202
+ var stat = fs.statSync(filePath);
203
+ entry.offset = stat.size; // Start from end (only new lines)
204
+ } catch (e) {}
205
+
206
+ entry.watcher = fs.watch(filePath, function (event) {
207
+ readNewLines();
208
+ });
209
+ entry.watcher.on("error", function () {});
210
+ } catch (e) {
211
+ // File doesn't exist yet — watcher will fail silently
212
+ }
213
+ }
214
+
215
+ function reconcileAgentTails(members) {
216
+ if (!Array.isArray(members)) return;
217
+ // members is an array of agentId strings or objects with id field
218
+ var memberIds = {};
219
+ for (var i = 0; i < members.length; i++) {
220
+ var m = members[i];
221
+ var id = typeof m === "string" ? m : (m.id || m.agentId || "");
222
+ if (!id) continue;
223
+ memberIds[id] = true;
224
+ }
225
+
226
+ // Stop tails for members no longer in team
227
+ var existing = Object.keys(agentTails);
228
+ for (var ei = 0; ei < existing.length; ei++) {
229
+ if (!memberIds[existing[ei]]) {
230
+ var tail = agentTails[existing[ei]];
231
+ if (tail && tail.watcher) { try { tail.watcher.close(); } catch (e) {} }
232
+ delete agentTails[existing[ei]];
233
+ }
234
+ }
235
+
236
+ // The JSONL path requires cliSessionId and cwd which come in via onTeamCreate.
237
+ // Store them on the entry when available.
238
+ for (var mi = 0; mi < members.length; mi++) {
239
+ var member = members[mi];
240
+ var agentId = typeof member === "string" ? member : (member.id || member.agentId || "");
241
+ if (!agentId) continue;
242
+ if (!agentTails[agentId]) {
243
+ // We don't have a JSONL path yet — mark as pending
244
+ agentTails[agentId] = { path: null, offset: 0, watcher: null };
245
+ }
246
+ }
247
+ }
248
+
249
+ function watchConfigJson(teamId) {
250
+ var configPath = path.join(getTeamDir(teamId), "config.json");
251
+ var lastMembersJson = "";
252
+
253
+ function reloadConfig() {
254
+ var data = readJsonSafe(configPath);
255
+ if (!data) {
256
+ // config.json disappeared
257
+ deactivatePendingMs = deactivatePendingMs || Date.now();
258
+ return;
259
+ }
260
+ deactivatePendingMs = 0;
261
+ if (!teamState) return;
262
+
263
+ var newMembers = data.members || [];
264
+ var newMembersJson = JSON.stringify(newMembers);
265
+ if (newMembersJson === lastMembersJson) return;
266
+ lastMembersJson = newMembersJson;
267
+
268
+ teamState.members = newMembers;
269
+ teamState.teamName = data.name || teamState.teamName;
270
+ teamState.description = data.description || teamState.description;
271
+
272
+ reconcileAgentTails(newMembers);
273
+
274
+ send({ type: "team_member_update", members: teamState.members });
275
+ }
276
+
277
+ try {
278
+ configWatcher = fs.watch(configPath, function (event) {
279
+ reloadConfig();
280
+ });
281
+ configWatcher.on("error", function () {});
282
+ } catch (e) {
283
+ // File doesn't exist — tolerate
284
+ }
285
+ }
286
+
287
+ function runLivenessCheck() {
288
+ if (!teamState) return;
289
+
290
+ var now = Date.now();
291
+ var members = teamState.members || [];
292
+ var changed = false;
293
+
294
+ for (var i = 0; i < members.length; i++) {
295
+ var m = members[i];
296
+ var aid = typeof m === "string" ? m : (m.id || m.agentId || "");
297
+ if (!aid) continue;
298
+
299
+ var last = memberLastActivity[aid] || 0;
300
+ var status;
301
+ if (last > now - 60000) {
302
+ status = "alive";
303
+ } else if (last > 0) {
304
+ status = "idle";
305
+ } else {
306
+ status = "unknown";
307
+ }
308
+
309
+ if (memberStatus[aid] !== status) {
310
+ memberStatus[aid] = status;
311
+ changed = true;
312
+ send({ type: "team_member_update", agentId: aid, status: status });
313
+ }
314
+ }
315
+
316
+ // Deactivate check: if config.json has been missing for 30s and all are gone
317
+ if (deactivatePendingMs > 0 && (now - deactivatePendingMs) > DEACTIVATE_AFTER_MS) {
318
+ deactivateTeam();
319
+ }
320
+ }
321
+
322
+ function activateTeam(teamId, cliSessionId, cwd) {
323
+ if (teamState) deactivateTeam();
324
+
325
+ var configPath = path.join(getTeamDir(teamId), "config.json");
326
+ var data = readJsonSafe(configPath);
327
+ var members = (data && data.members) || [];
328
+ var tasks = [];
329
+
330
+ // Read initial tasks
331
+ var taskDir = getTaskDir(teamId);
332
+ try {
333
+ if (fs.existsSync(taskDir)) {
334
+ var files = fs.readdirSync(taskDir);
335
+ for (var i = 0; i < files.length; i++) {
336
+ if (!files[i].endsWith(".json")) continue;
337
+ var t = readJsonSafe(path.join(taskDir, files[i]));
338
+ if (t) tasks.push(t);
339
+ }
340
+ }
341
+ } catch (e) {}
342
+
343
+ teamState = {
344
+ teamId: teamId,
345
+ teamName: (data && data.name) || teamId,
346
+ description: (data && data.description) || "",
347
+ members: members,
348
+ tasks: tasks,
349
+ };
350
+
351
+ // Wire up JSONL tails for each member
352
+ if (cliSessionId && cwd) {
353
+ var sessionsBase = path.join(config.REAL_HOME, ".clagentic", "sessions");
354
+ var encodedCwd = utils.resolveEncodedDir(sessionsBase, cwd);
355
+ var subagentDir = path.join(
356
+ config.REAL_HOME,
357
+ ".claude",
358
+ "projects",
359
+ encodedCwd,
360
+ cliSessionId,
361
+ "subagents"
362
+ );
363
+
364
+ for (var mi = 0; mi < members.length; mi++) {
365
+ var m = members[mi];
366
+ var aid = typeof m === "string" ? m : (m.id || m.agentId || "");
367
+ if (!aid) continue;
368
+ var jsonlPath = path.join(subagentDir, "agent-" + aid + ".jsonl");
369
+ tailAgentJSONL(aid, jsonlPath);
370
+ }
371
+ }
372
+
373
+ watchConfigJson(teamId);
374
+ watchTaskDir(teamId);
375
+
376
+ livenessTimer = setInterval(runLivenessCheck, 15000);
377
+
378
+ emitTeamState();
379
+ console.log("[project-team] Team activated: " + teamId);
380
+ }
381
+
382
+ function onTeamCreate(teamId, cliSessionId, cwd) {
383
+ activateTeam(teamId, cliSessionId, cwd);
384
+ }
385
+
386
+ function onTeamDelete() {
387
+ if (teamState) deactivateTeam();
388
+ }
389
+
390
+ function handleClientMsg(ws, msg) {
391
+ if (msg.type === "team_request_state") {
392
+ if (teamState) {
393
+ try {
394
+ ws.send(JSON.stringify({ type: "team_state", team: teamState, messages: teamMessages }));
395
+ } catch (e) {}
396
+ }
397
+ return true;
398
+ }
399
+ return false;
400
+ }
401
+
402
+ function getState() {
403
+ return teamState;
404
+ }
405
+
406
+ // Feature-detect: if ~/.claude/teams/ doesn't exist, this module is a no-op
407
+ // at activate time. Watchers are only created on activateTeam().
408
+
409
+ return {
410
+ onTeamCreate: onTeamCreate,
411
+ onTeamDelete: onTeamDelete,
412
+ handleClientMsg: handleClientMsg,
413
+ getState: getState,
414
+ };
415
+ }
416
+
417
+ module.exports = { attachTeam: attachTeam };