@clagentic/console 1.5.0-beta.2 → 1.5.0-beta.4

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.
Files changed (54) hide show
  1. package/README.md +18 -14
  2. package/bin/cli.js +1 -0
  3. package/lib/cli-sessions.js +71 -18
  4. package/lib/config.js +80 -6
  5. package/lib/daemon-projects.js +1 -1
  6. package/lib/daemon.js +142 -26
  7. package/lib/pages.js +1 -42
  8. package/lib/project-connection.js +4 -8
  9. package/lib/project-external-trigger.js +62 -7
  10. package/lib/project-http.js +17 -1
  11. package/lib/project-loop.js +3 -2
  12. package/lib/project-notifications.js +3 -18
  13. package/lib/project-sessions.js +68 -27
  14. package/lib/project-team.js +417 -0
  15. package/lib/project-user-message.js +5 -10
  16. package/lib/project.js +53 -53
  17. package/lib/public/app.js +7 -15
  18. package/lib/public/css/home-hub.css +36 -0
  19. package/lib/public/css/icon-strip.css +28 -126
  20. package/lib/public/css/menus.css +2 -2
  21. package/lib/public/css/team-panel.css +149 -0
  22. package/lib/public/index.html +72 -15
  23. package/lib/public/modules/admin.js +1 -52
  24. package/lib/public/modules/agent-picker.js +11 -3
  25. package/lib/public/modules/app-cursors.js +43 -47
  26. package/lib/public/modules/app-home-hub.js +12 -0
  27. package/lib/public/modules/app-messages.js +18 -12
  28. package/lib/public/modules/app-rendering.js +1 -2
  29. package/lib/public/modules/server-settings.js +74 -5
  30. package/lib/public/modules/sidebar-mobile.js +9 -88
  31. package/lib/public/modules/sidebar-projects.js +1 -1
  32. package/lib/public/modules/sidebar-sessions.js +6 -2
  33. package/lib/public/modules/sidebar-users.js +37 -307
  34. package/lib/public/modules/team-panel.js +331 -0
  35. package/lib/public/modules/tools.js +3 -0
  36. package/lib/public/modules/user-settings.js +0 -3
  37. package/lib/public/style.css +1 -0
  38. package/lib/sdk-bridge.js +121 -8
  39. package/lib/sdk-message-processor.js +39 -4
  40. package/lib/sdk-worker.js +2 -2
  41. package/lib/server-admin.js +1 -86
  42. package/lib/server-auth.js +13 -124
  43. package/lib/server-dm.js +2 -7
  44. package/lib/server-palette.js +9 -20
  45. package/lib/server-settings.js +41 -243
  46. package/lib/server-skills.js +11 -13
  47. package/lib/server.js +37 -60
  48. package/lib/sessions.js +16 -50
  49. package/lib/terminal-manager.js +13 -15
  50. package/lib/users-auth.js +0 -38
  51. package/lib/users.js +14 -11
  52. package/lib/ws-schema.js +12 -0
  53. package/lib/yoke/adapters/claude.js +5 -0
  54. package/package.json +1 -1
@@ -0,0 +1,331 @@
1
+ // team-panel.js - Live team-activity panel (desktop + mobile)
2
+ // Handles team_state, team_member_update, team_task_update, team_message,
3
+ // team_gone WS messages. Renders desktop #team-panel and mobile team sheet.
4
+
5
+ import { store } from './store.js';
6
+ import { getWs } from './ws-ref.js';
7
+ import { escapeHtml } from './utils.js';
8
+ import { refreshIcons } from './icons.js';
9
+
10
+ // --- Module state ---
11
+ var currentTeam = null;
12
+ var teamMessages = [];
13
+ var panelOpen = false;
14
+
15
+ // --- Helpers ---
16
+
17
+ function sendWs(msg) {
18
+ var ws = getWs();
19
+ if (ws && ws.readyState === 1) ws.send(JSON.stringify(msg));
20
+ }
21
+
22
+ function statusClass(status) {
23
+ if (status === "alive") return "alive";
24
+ if (status === "idle") return "idle";
25
+ if (status === "gone") return "gone";
26
+ return "unknown";
27
+ }
28
+
29
+ function agentId(m) {
30
+ if (typeof m === "string") return m;
31
+ return m.id || m.agentId || "";
32
+ }
33
+
34
+ function agentName(m) {
35
+ if (typeof m === "string") return m;
36
+ return m.name || m.id || m.agentId || "unknown";
37
+ }
38
+
39
+ // --- Render helpers ---
40
+
41
+ function renderMembersSection(container, members, memberStatuses, memberActivities) {
42
+ var header = document.createElement("div");
43
+ header.className = "team-section-header";
44
+ header.textContent = "Members";
45
+ container.appendChild(header);
46
+
47
+ if (!members || members.length === 0) {
48
+ var empty = document.createElement("div");
49
+ empty.className = "team-member-row";
50
+ empty.style.color = "var(--text-dimmer)";
51
+ empty.textContent = "No members";
52
+ container.appendChild(empty);
53
+ return;
54
+ }
55
+
56
+ for (var i = 0; i < members.length; i++) {
57
+ var m = members[i];
58
+ var id = agentId(m);
59
+ var name = agentName(m);
60
+ var status = (memberStatuses && memberStatuses[id]) || "unknown";
61
+ var activity = (memberActivities && memberActivities[id]) || "";
62
+
63
+ var row = document.createElement("div");
64
+ row.className = "team-member-row";
65
+
66
+ var dot = document.createElement("span");
67
+ dot.className = "team-member-status-dot " + statusClass(status);
68
+ row.appendChild(dot);
69
+
70
+ var nameEl = document.createElement("span");
71
+ nameEl.className = "team-member-name";
72
+ nameEl.textContent = name;
73
+ row.appendChild(nameEl);
74
+
75
+ if (activity) {
76
+ var actEl = document.createElement("span");
77
+ actEl.className = "team-member-activity";
78
+ actEl.textContent = activity;
79
+ row.appendChild(actEl);
80
+ }
81
+
82
+ container.appendChild(row);
83
+ }
84
+ }
85
+
86
+ function taskStatusLabel(status) {
87
+ if (status === "completed") return "completed";
88
+ if (status === "in_progress") return "in_progress";
89
+ if (status === "blocked") return "blocked";
90
+ return "pending";
91
+ }
92
+
93
+ function taskCheckmark(status) {
94
+ if (status === "completed") return "✓";
95
+ return "☐";
96
+ }
97
+
98
+ function renderTasksSection(container, tasks) {
99
+ var header = document.createElement("div");
100
+ header.className = "team-section-header";
101
+ header.textContent = "Tasks";
102
+ container.appendChild(header);
103
+
104
+ if (!tasks || tasks.length === 0) {
105
+ var empty = document.createElement("div");
106
+ empty.className = "team-task-item";
107
+ empty.style.color = "var(--text-dimmer)";
108
+ empty.textContent = "No tasks";
109
+ container.appendChild(empty);
110
+ return;
111
+ }
112
+
113
+ for (var i = 0; i < tasks.length; i++) {
114
+ var t = tasks[i];
115
+ var status = taskStatusLabel(t.status);
116
+
117
+ var item = document.createElement("div");
118
+ item.className = "team-task-item";
119
+
120
+ var check = document.createElement("span");
121
+ check.textContent = taskCheckmark(t.status);
122
+ check.style.marginRight = "6px";
123
+ check.style.flexShrink = "0";
124
+ item.appendChild(check);
125
+
126
+ var title = document.createElement("span");
127
+ title.style.flex = "1";
128
+ title.textContent = t.title || t.description || t.id || "Task";
129
+ item.appendChild(title);
130
+
131
+ var pill = document.createElement("span");
132
+ pill.className = "team-task-status " + status;
133
+ pill.textContent = status.replace("_", " ");
134
+ item.appendChild(pill);
135
+
136
+ container.appendChild(item);
137
+ }
138
+ }
139
+
140
+ function renderMessagesSection(container, messages) {
141
+ var header = document.createElement("div");
142
+ header.className = "team-section-header";
143
+ header.textContent = "Messages";
144
+ container.appendChild(header);
145
+
146
+ var recent = messages.slice(-10);
147
+ if (recent.length === 0) {
148
+ var empty = document.createElement("div");
149
+ empty.className = "team-message-item";
150
+ empty.style.color = "var(--text-dimmer)";
151
+ empty.textContent = "No messages yet";
152
+ container.appendChild(empty);
153
+ return;
154
+ }
155
+
156
+ for (var i = 0; i < recent.length; i++) {
157
+ var msg = recent[i];
158
+ var item = document.createElement("div");
159
+ item.className = "team-message-item";
160
+
161
+ var from = document.createElement("div");
162
+ from.className = "team-message-from";
163
+ from.textContent = escapeHtml(msg.fromAgentId || "?") + " → " + escapeHtml(msg.toAgentId || "?") + ":";
164
+ item.appendChild(from);
165
+
166
+ var body = document.createElement("div");
167
+ body.className = "team-message-body";
168
+ body.textContent = msg.summary || msg.body || "";
169
+ item.appendChild(body);
170
+
171
+ container.appendChild(item);
172
+ }
173
+ }
174
+
175
+ function renderTeamPanelBody() {
176
+ var bodyEl = document.getElementById("team-panel-body");
177
+ if (!bodyEl) return;
178
+ bodyEl.innerHTML = "";
179
+
180
+ if (!currentTeam) {
181
+ bodyEl.innerHTML =
182
+ '<div class="team-empty-state">' +
183
+ '<p>No active team</p>' +
184
+ '<p class="team-empty-hint">Start a session with Agent Teams enabled to see live activity here.</p>' +
185
+ '</div>';
186
+ return;
187
+ }
188
+
189
+ renderMembersSection(bodyEl, currentTeam.members, currentTeam._memberStatuses, currentTeam._memberActivities);
190
+
191
+ var divider1 = document.createElement("hr");
192
+ divider1.className = "mobile-sheet-divider";
193
+ bodyEl.appendChild(divider1);
194
+
195
+ renderTasksSection(bodyEl, currentTeam.tasks);
196
+
197
+ var divider2 = document.createElement("hr");
198
+ divider2.className = "mobile-sheet-divider";
199
+ bodyEl.appendChild(divider2);
200
+
201
+ renderMessagesSection(bodyEl, teamMessages);
202
+ }
203
+
204
+ // --- Exports ---
205
+
206
+ export function initTeamPanel() {
207
+ // Wire close button
208
+ var closeBtn = document.getElementById("team-panel-close");
209
+ if (closeBtn) {
210
+ closeBtn.addEventListener("click", function () {
211
+ toggleTeamPanel();
212
+ });
213
+ }
214
+
215
+ // Send team_request_state when WS connects
216
+ store.subscribe(["connected"], function (state, prev) {
217
+ if (state.connected && !prev.connected) {
218
+ sendWs({ type: "team_request_state" });
219
+ }
220
+ });
221
+ }
222
+
223
+ export function handleTeamState(msg) {
224
+ currentTeam = msg.team || null;
225
+ if (currentTeam) {
226
+ currentTeam._memberStatuses = currentTeam._memberStatuses || {};
227
+ currentTeam._memberActivities = currentTeam._memberActivities || {};
228
+ }
229
+ teamMessages = msg.messages || [];
230
+
231
+ var panel = document.getElementById("team-panel");
232
+ if (panel) {
233
+ if (currentTeam) {
234
+ panel.classList.remove("hidden");
235
+ }
236
+ }
237
+
238
+ renderTeamPanelBody();
239
+ }
240
+
241
+ export function handleTeamMemberUpdate(msg) {
242
+ if (!currentTeam) return;
243
+
244
+ // Full member list replacement
245
+ if (msg.members) {
246
+ currentTeam.members = msg.members;
247
+ }
248
+
249
+ // Single member status/activity update
250
+ if (msg.agentId) {
251
+ currentTeam._memberStatuses = currentTeam._memberStatuses || {};
252
+ currentTeam._memberActivities = currentTeam._memberActivities || {};
253
+ if (msg.status) {
254
+ currentTeam._memberStatuses[msg.agentId] = msg.status;
255
+ }
256
+ if (msg.currentActivity) {
257
+ currentTeam._memberActivities[msg.agentId] = msg.currentActivity;
258
+ }
259
+ }
260
+
261
+ renderTeamPanelBody();
262
+ }
263
+
264
+ export function handleTeamTaskUpdate(msg) {
265
+ if (!currentTeam) return;
266
+ if (msg.tasks) {
267
+ currentTeam.tasks = msg.tasks;
268
+ }
269
+ renderTeamPanelBody();
270
+ }
271
+
272
+ export function handleTeamMessage(msg) {
273
+ if (msg.message) {
274
+ teamMessages.push(msg.message);
275
+ if (teamMessages.length > 50) teamMessages.shift();
276
+ }
277
+ renderTeamPanelBody();
278
+ }
279
+
280
+ export function handleTeamGone() {
281
+ currentTeam = null;
282
+ teamMessages = [];
283
+ panelOpen = false;
284
+
285
+ var panel = document.getElementById("team-panel");
286
+ if (panel) panel.classList.add("hidden");
287
+
288
+ renderTeamPanelBody();
289
+ }
290
+
291
+ export function renderSheetTeam(listEl) {
292
+ if (!currentTeam) {
293
+ var empty = document.createElement("div");
294
+ empty.className = "team-empty-state";
295
+ empty.innerHTML =
296
+ '<p>No active team</p>' +
297
+ '<p class="team-empty-hint">Start a session with Agent Teams enabled to see live activity here.</p>';
298
+ listEl.appendChild(empty);
299
+ return;
300
+ }
301
+
302
+ renderMembersSection(listEl, currentTeam.members, currentTeam._memberStatuses, currentTeam._memberActivities);
303
+
304
+ var d1 = document.createElement("hr");
305
+ d1.className = "mobile-sheet-divider";
306
+ listEl.appendChild(d1);
307
+
308
+ renderTasksSection(listEl, currentTeam.tasks);
309
+
310
+ var d2 = document.createElement("hr");
311
+ d2.className = "mobile-sheet-divider";
312
+ listEl.appendChild(d2);
313
+
314
+ renderMessagesSection(listEl, teamMessages);
315
+ }
316
+
317
+ export function toggleTeamPanel() {
318
+ var panel = document.getElementById("team-panel");
319
+ if (!panel) return;
320
+ panelOpen = !panelOpen;
321
+ if (panelOpen) {
322
+ panel.classList.remove("hidden");
323
+ renderTeamPanelBody();
324
+ } else {
325
+ panel.classList.add("hidden");
326
+ }
327
+ }
328
+
329
+ export function hasActiveTeam() {
330
+ return !!currentTeam;
331
+ }
@@ -480,6 +480,9 @@ function permissionInputSummary(toolName, input) {
480
480
 
481
481
  export function renderPermissionRequest(requestId, toolName, toolInput, decisionReason, mateId, vendor) {
482
482
  if (pendingPermissions[requestId]) return;
483
+ // On WS reconnect the DOM node may survive a pendingPermissions reset.
484
+ // Guard against duplicating the card in that case.
485
+ if (ctx && ctx.messagesEl && ctx.messagesEl.querySelector('[data-request-id="' + requestId + '"]')) return;
483
486
  ctx.finalizeAssistantBlock();
484
487
  stopThinking();
485
488
  closeToolGroup();
@@ -380,9 +380,6 @@ function populateAccount() {
380
380
  avatarFallback.classList.add('hidden');
381
381
  }
382
382
  }
383
- // Hide account section in single-user mode (no username)
384
- var accountNav = settingsEl.querySelector('[data-section="us-account"]');
385
- if (accountNav) accountNav.style.display = data.username ? '' : 'none';
386
383
  // Auto-continue toggle
387
384
  var acToggle = document.getElementById('us-auto-continue');
388
385
  if (acToggle) acToggle.checked = !!data.autoContinueOnRateLimit;
@@ -33,4 +33,5 @@
33
33
  @import url("css/at-agents.css");
34
34
  @import url("css/debate.css");
35
35
  @import url("css/notifications-center.css");
36
+ @import url("css/team-panel.css");
36
37
 
package/lib/sdk-bridge.js CHANGED
@@ -8,7 +8,7 @@ var { getCodexConfig } = require("./codex-defaults");
8
8
  var { splitShellSegments, attachSkillDiscovery, discoverSkillsWithMeta, mergeSkillsWithMeta } = require("./sdk-skill-discovery");
9
9
  var { createMessageQueue } = require("./sdk-message-queue");
10
10
  var { attachMessageProcessor } = require("./sdk-message-processor");
11
- var { readAgentToolsFromFile } = require("./agents");
11
+ var { readAgentToolsFromFile, parseFrontmatter, slugifyAgentName, AGENTS_SOURCE_DIR } = require("./agents");
12
12
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
13
13
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
14
14
 
@@ -28,6 +28,11 @@ var MAX_CONCURRENT_SESSIONS = (function () {
28
28
  // and daemon.js — changing this constant is the single place to adjust the default.
29
29
  var DEFAULT_MEM_AVAILABLE_MIN_MB = 1024;
30
30
 
31
+ // --- lr-2d91: cgroup context token guard ---
32
+ // Empirical calibration: claude-opus-4 at 1M context peaks at ~15 GB RSS,
33
+ // yielding approximately 67 tokens per MB of headroom consumed.
34
+ var DEFAULT_TOKENS_PER_MB_HEADROOM = 67;
35
+
31
36
  // Read Linux MemAvailable from /proc/meminfo synchronously.
32
37
  // Returns available memory in MB, or null on non-Linux or read failure.
33
38
  // Sub-millisecond on Linux; the synchronous read is correct here — this is a
@@ -44,6 +49,38 @@ function readMemAvailableMB() {
44
49
  }
45
50
  }
46
51
 
52
+ // Read cgroup memory headroom in MB.
53
+ // Tries cgroup v2 (system.slice/clagentic-console.service) first, then cgroup v1.
54
+ // Returns null if neither is readable, the limit is "max" (unlimited), or on
55
+ // any read error — the caller must treat null as "no limit enforceable".
56
+ function readCgroupHeadroomMB() {
57
+ if (process.platform !== "linux") return null;
58
+ try {
59
+ // cgroup v2
60
+ var cgV2Dir = "/sys/fs/cgroup/system.slice/clagentic-console.service";
61
+ var currentRaw = fs.readFileSync(cgV2Dir + "/memory.current", "utf8").trim();
62
+ var maxRaw = fs.readFileSync(cgV2Dir + "/memory.max", "utf8").trim();
63
+ if (maxRaw === "max") return null;
64
+ var current = parseInt(currentRaw, 10);
65
+ var max = parseInt(maxRaw, 10);
66
+ if (isNaN(current) || isNaN(max) || max <= 0) return null;
67
+ return Math.floor((max - current) / 1024 / 1024);
68
+ } catch (e) {
69
+ // fall through to v1
70
+ }
71
+ try {
72
+ // cgroup v1
73
+ var current1 = parseInt(fs.readFileSync("/sys/fs/cgroup/memory/memory.usage_in_bytes", "utf8").trim(), 10);
74
+ var max1 = parseInt(fs.readFileSync("/sys/fs/cgroup/memory/memory.limit_in_bytes", "utf8").trim(), 10);
75
+ if (isNaN(current1) || isNaN(max1) || max1 <= 0) return null;
76
+ // Typical sentinel for "no limit" in cgroup v1 is a very large value (near INT64_MAX)
77
+ if (max1 > 9e18) return null;
78
+ return Math.floor((max1 - current1) / 1024 / 1024);
79
+ } catch (e) {
80
+ return null;
81
+ }
82
+ }
83
+
47
84
  // Extract serializable tool descriptors from MCP server instances.
48
85
  // Used for IPC to worker processes (McpSdkServerConfigWithInstance is not serializable).
49
86
  function extractMcpDescriptors(mcpServers) {
@@ -369,6 +406,8 @@ function createSDKBridge(opts) {
369
406
  onProcessingChanged: onProcessingChanged,
370
407
  onTurnDone: onTurnDone,
371
408
  onAutoTitle: function (session) { autoGenerateTitle(session); },
409
+ onTeamCreate: opts.onTeamCreate || null,
410
+ onTeamDelete: opts.onTeamDelete || null,
372
411
  opts: opts,
373
412
  discoverSkillDirs: discoverSkillDirs,
374
413
  mergeSkills: mergeSkills,
@@ -414,7 +453,7 @@ function createSDKBridge(opts) {
414
453
  tag: "claude-elicitation",
415
454
  };
416
455
  // Route to session owner only — body carries MCP message text.
417
- if (usersModule.isMultiUser() && session.ownerId && pushModule.sendPushToUser) {
456
+ if (session.ownerId && pushModule.sendPushToUser) {
418
457
  pushModule.sendPushToUser(session.ownerId, _elicitPayload);
419
458
  } else {
420
459
  pushModule.sendPush(_elicitPayload);
@@ -670,7 +709,7 @@ function createSDKBridge(opts) {
670
709
  body: permissionPushBody(toolName, input),
671
710
  };
672
711
  // Route to session owner only — body carries tool name and input (may contain paths/code).
673
- if (usersModule.isMultiUser() && session.ownerId && pushModule.sendPushToUser) {
712
+ if (session.ownerId && pushModule.sendPushToUser) {
674
713
  pushModule.sendPushToUser(session.ownerId, _permPayload);
675
714
  } else {
676
715
  pushModule.sendPush(_permPayload);
@@ -876,8 +915,7 @@ function createSDKBridge(opts) {
876
915
  }
877
916
  var authUser = session.ownerId ? usersModule.findUserById(session.ownerId) : null;
878
917
  var authLinuxUser = authUser && authUser.linuxUser ? authUser.linuxUser : null;
879
- var canAutoLogin = !usersModule.isMultiUser()
880
- || !!authLinuxUser
918
+ var canAutoLogin = !!authLinuxUser
881
919
  || (authUser && authUser.role === "admin");
882
920
  var authTitle = (session.vendor === "codex" ? "Codex" : "Claude Code") + " is not logged in.";
883
921
  var authMsg = {
@@ -1174,8 +1212,7 @@ function createSDKBridge(opts) {
1174
1212
  var vendorName = session.vendor.charAt(0).toUpperCase() + session.vendor.slice(1);
1175
1213
  var authUser = session.ownerId ? usersModule.findUserById(session.ownerId) : null;
1176
1214
  var authLinuxUser = authUser && authUser.linuxUser ? authUser.linuxUser : null;
1177
- var canAutoLogin = !usersModule.isMultiUser()
1178
- || !!authLinuxUser
1215
+ var canAutoLogin = !!authLinuxUser
1179
1216
  || (authUser && authUser.role === "admin");
1180
1217
  var authState = getFreshAuthState();
1181
1218
  logAuthDecision("emit-auth-required", session, "missing adapter", authState);
@@ -1258,6 +1295,40 @@ function createSDKBridge(opts) {
1258
1295
  return;
1259
1296
  }
1260
1297
  }
1298
+ // lr-2d91: cgroup context token guard — applies to ALL turns because long-running
1299
+ // sessions accumulate context across turns and each new turn will load the full
1300
+ // accumulated context into memory. Placed after the memAvailableMinMB gate and
1301
+ // before the slot is claimed so a rejected query never increments the live counter.
1302
+ var contextTokens = session.lastStreamInputTokens || 0;
1303
+ if (contextTokens > 0) {
1304
+ var cgHeadroomMB = readCgroupHeadroomMB();
1305
+ if (cgHeadroomMB !== null) {
1306
+ var tokensPerMb = DEFAULT_TOKENS_PER_MB_HEADROOM;
1307
+ var _getConfig = opts.getConfig;
1308
+ if (typeof _getConfig === "function") {
1309
+ var _cgCfg = _getConfig();
1310
+ if (_cgCfg && typeof _cgCfg.tokensPerMbHeadroom === "number" && _cgCfg.tokensPerMbHeadroom > 0) {
1311
+ tokensPerMb = _cgCfg.tokensPerMbHeadroom;
1312
+ }
1313
+ }
1314
+ var allowedTokens = cgHeadroomMB * tokensPerMb;
1315
+ var warnTokens = Math.floor(allowedTokens * 0.8);
1316
+ if (contextTokens >= allowedTokens) {
1317
+ console.warn("[sdk-bridge] cgroup context guard: " + Math.round(contextTokens / 1000) + "K tokens >= " + Math.round(allowedTokens / 1000) + "K allowed (" + cgHeadroomMB + " MB headroom) — blocking session " + session.localId);
1318
+ session.isProcessing = false;
1319
+ onProcessingChanged();
1320
+ var blockMsg = "Session context too large for available memory (" + Math.round(contextTokens / 1000) + "K tokens, " + cgHeadroomMB + " MB headroom). Start a new session or wait for other sessions to complete.";
1321
+ sendAndRecord(session, { type: "error", text: blockMsg });
1322
+ sendAndRecord(session, { type: "done", code: 1 });
1323
+ send({ type: "toast", level: "error", message: "Session blocked — context too large for available memory.", duration: 7000 });
1324
+ sm.broadcastSessionList();
1325
+ return;
1326
+ } else if (contextTokens >= warnTokens) {
1327
+ send({ type: "toast", level: "warn", message: "Large session context (" + Math.round(contextTokens / 1000) + "K tokens). Consider starting a new session to avoid memory pressure.", duration: 8000 });
1328
+ }
1329
+ }
1330
+ }
1331
+
1261
1332
  // Claim the slot now so concurrent callers see the updated count immediately.
1262
1333
  // Set _isCountedLive on the session at the same time so any early-return path
1263
1334
  // below (sync throw, createQuery failure) can release it via releaseSlot().
@@ -1338,6 +1409,10 @@ function createSDKBridge(opts) {
1338
1409
  // JSON array syntax for the tools field. We read the tools list directly
1339
1410
  // from disk and set claudeOpts.tools explicitly so restriction is enforced
1340
1411
  // even if the SDK's parsing path has any quirks.
1412
+ // lr-5bd7 — declared outside the agent block so the model override can be
1413
+ // applied when queryModel is computed below (after loop-settings resolution).
1414
+ var _agentDeclaredModel = null;
1415
+
1341
1416
  if (session.agentName && sessionAdapter.vendor !== 'codex') {
1342
1417
  claudeOpts.agent = session.agentName;
1343
1418
  var agentTools = readAgentToolsFromFile(session.agentName);
@@ -1345,6 +1420,36 @@ function createSDKBridge(opts) {
1345
1420
  claudeOpts.tools = agentTools;
1346
1421
  console.log("[sdk-bridge] agent tools enforced for " + session.agentName + ": " + agentTools.join(", "));
1347
1422
  }
1423
+
1424
+ // lr-5bd7 — inject AGENT.md body as systemPrompt on the main thread.
1425
+ // The `agents` map approach (PR #264) only applies to subagent invocations
1426
+ // via the Agent tool; it does not deliver the body to the main conversation.
1427
+ // Setting claudeOpts.systemPrompt bypasses settingSources/agents-map resolution
1428
+ // and ensures the model receives the agent persona directly.
1429
+ // We keep claudeOpts.agent set — it still applies tool restrictions via settingSources.
1430
+ var agentSlug = slugifyAgentName(session.agentName);
1431
+ var agentFilePath = path.join(AGENTS_SOURCE_DIR, agentSlug + ".md");
1432
+ var agentRaw;
1433
+ try {
1434
+ agentRaw = fs.readFileSync(agentFilePath, "utf8");
1435
+ } catch (e) {
1436
+ agentRaw = null;
1437
+ }
1438
+ if (agentRaw) {
1439
+ var agentParsed = parseFrontmatter(agentRaw);
1440
+ var agentBody = agentParsed && agentParsed.body ? agentParsed.body.trim() : null;
1441
+ if (agentBody) {
1442
+ claudeOpts.systemPrompt = agentBody;
1443
+ console.log("[sdk-bridge] agent body injected as systemPrompt for " + session.agentName + " (" + agentBody.length + " chars)");
1444
+ }
1445
+ // lr-5bd7 — capture the agent's declared model so we can override queryModel below.
1446
+ // The UI-selected model (sm.currentModel / session.model) must not override the
1447
+ // agent's own model declaration (e.g. opus for holden).
1448
+ if (agentParsed && agentParsed.meta && agentParsed.meta.model) {
1449
+ _agentDeclaredModel = agentParsed.meta.model;
1450
+ console.log("[sdk-bridge] agent declared model for " + session.agentName + ": " + _agentDeclaredModel);
1451
+ }
1452
+ }
1348
1453
  }
1349
1454
 
1350
1455
  // Per-loop settings override global defaults when present
@@ -1429,6 +1534,14 @@ function createSDKBridge(opts) {
1429
1534
  queryModel = modelEntryValue(queryModel) || undefined;
1430
1535
  }
1431
1536
 
1537
+ // lr-5bd7 — agent model wins over the UI-selected model. Apply after all
1538
+ // vendor-validation logic so the agent model goes through as-is (it is
1539
+ // already a valid short-form like "opus" or a full model ID).
1540
+ if (_agentDeclaredModel) {
1541
+ queryModel = _agentDeclaredModel;
1542
+ console.log("[sdk-bridge] agent model override applied: " + queryModel);
1543
+ }
1544
+
1432
1545
  var codexConfig = getCodexConfig(sm);
1433
1546
  var mergedMcpServers = mergeMcpServers(getMcpServers(), getRemoteMcpServers) || undefined;
1434
1547
  var queryOpts = {
@@ -2002,5 +2115,5 @@ function createSDKBridge(opts) {
2002
2115
  };
2003
2116
  }
2004
2117
 
2005
- module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, DEFAULT_MEM_AVAILABLE_MIN_MB };
2118
+ module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, readCgroupHeadroomMB, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM };
2006
2119
 
@@ -14,6 +14,8 @@ function attachMessageProcessor(ctx) {
14
14
  var onProcessingChanged = ctx.onProcessingChanged;
15
15
  var onTurnDone = ctx.onTurnDone;
16
16
  var onAutoTitle = ctx.onAutoTitle;
17
+ var onTeamCreate = ctx.onTeamCreate || null;
18
+ var onTeamDelete = ctx.onTeamDelete || null;
17
19
  var opts = ctx.opts;
18
20
  var discoverSkillDirs = ctx.discoverSkillDirs;
19
21
  var mergeSkills = ctx.mergeSkills;
@@ -233,6 +235,20 @@ function attachMessageProcessor(ctx) {
233
235
  input: parsed.input || {},
234
236
  });
235
237
 
238
+ // TeamCreate: record pending so we can extract the teamId from tool_result
239
+ if (parsed.toolName === "TeamCreate" && onTeamCreate) {
240
+ if (!session._pendingTeamCreates) session._pendingTeamCreates = {};
241
+ session._pendingTeamCreates[parsed.toolId] = {
242
+ cliSessionId: session.cliSessionId || null,
243
+ cwd: cwd,
244
+ };
245
+ }
246
+
247
+ // TeamDelete: fire immediately on execution
248
+ if (parsed.toolName === "TeamDelete" && onTeamDelete) {
249
+ try { onTeamDelete(); } catch (e) {}
250
+ }
251
+
236
252
  } else if (parsed.yokeType === "tool_result") {
237
253
  sendAndRecord(session, {
238
254
  type: "tool_result",
@@ -241,6 +257,26 @@ function attachMessageProcessor(ctx) {
241
257
  is_error: !!parsed.isError,
242
258
  });
243
259
 
260
+ // TeamCreate result: extract team ID from result text and activate
261
+ if (onTeamCreate && session._pendingTeamCreates && session._pendingTeamCreates[parsed.toolId]) {
262
+ var pending = session._pendingTeamCreates[parsed.toolId];
263
+ delete session._pendingTeamCreates[parsed.toolId];
264
+ if (!parsed.isError) {
265
+ // Extract UUID from result text (e.g. "Created team abc123...")
266
+ var resultText = typeof parsed.content === "string" ? parsed.content : "";
267
+ var uuidMatch = resultText.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
268
+ var shortMatch = uuidMatch ? null : resultText.match(/team\s+([a-z0-9_-]{4,})/i);
269
+ var teamId = (uuidMatch && uuidMatch[1]) || (shortMatch && shortMatch[1]) || null;
270
+ if (teamId) {
271
+ try {
272
+ onTeamCreate(teamId, session.cliSessionId || pending.cliSessionId, pending.cwd);
273
+ } catch (e) {
274
+ console.error("[sdk-message-processor] onTeamCreate threw:", e && e.message ? e.message : e);
275
+ }
276
+ }
277
+ }
278
+ }
279
+
244
280
  } else if (parsed.yokeType === "plan_updated") {
245
281
  var todos = Array.isArray(parsed.plan) ? parsed.plan.map(function(step, idx) {
246
282
  var todo = {
@@ -297,7 +333,7 @@ function attachMessageProcessor(ctx) {
297
333
  tag: "claude-ask",
298
334
  };
299
335
  // Route to session owner only — content carries prompt text.
300
- if (usersModule.isMultiUser() && session.ownerId && pushModule.sendPushToUser) {
336
+ if (session.ownerId && pushModule.sendPushToUser) {
301
337
  pushModule.sendPushToUser(session.ownerId, _askPayload);
302
338
  } else {
303
339
  pushModule.sendPush(_askPayload);
@@ -478,8 +514,7 @@ function attachMessageProcessor(ctx) {
478
514
  if (isLoginPrompt) {
479
515
  var authUser = session.ownerId ? usersModule.findUserById(session.ownerId) : null;
480
516
  var authLinuxUser = authUser && authUser.linuxUser ? authUser.linuxUser : null;
481
- var canAutoLogin = !usersModule.isMultiUser()
482
- || !!authLinuxUser
517
+ var canAutoLogin = !!authLinuxUser
483
518
  || (authUser && authUser.role === "admin");
484
519
  var authTitle = session.vendor === "codex" ? "Codex is not logged in." : "Claude Code is not logged in.";
485
520
  var loginCommand = session.vendor === "codex"
@@ -525,7 +560,7 @@ function attachMessageProcessor(ctx) {
525
560
  tag: "claude-done",
526
561
  };
527
562
  // Route to session owner only — body carries response preview text.
528
- if (usersModule.isMultiUser() && session.ownerId && pushModule.sendPushToUser) {
563
+ if (session.ownerId && pushModule.sendPushToUser) {
529
564
  pushModule.sendPushToUser(session.ownerId, _donePayload);
530
565
  } else {
531
566
  pushModule.sendPush(_donePayload);
package/lib/sdk-worker.js CHANGED
@@ -523,10 +523,10 @@ async function handleQueryStart(msg) {
523
523
  try { pendingMcpCalls[k].reject(new Error("Worker shutting down")); } catch(e) {}
524
524
  }
525
525
  for (var k in pendingAskUser) {
526
- try { pendingAskUser[k](new Error("Worker shutting down")); } catch(e) {}
526
+ try { pendingAskUser[k]({ behavior: "deny", message: "Worker shutting down" }); } catch(e) {}
527
527
  }
528
528
  for (var k in pendingElicitations) {
529
- try { pendingElicitations[k](new Error("Worker shutting down")); } catch(e) {}
529
+ try { pendingElicitations[k]({ action: "reject" }); } catch(e) {}
530
530
  }
531
531
  queryInstance = null;
532
532
  messageQueue = null;