@clagentic/console 1.2.0-beta.1 → 1.2.0-beta.2

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/lib/agents.js CHANGED
@@ -26,6 +26,7 @@
26
26
  //
27
27
  // This implementation lives only on our fork; we are not pushing it upstream.
28
28
 
29
+ var fs = require("fs");
29
30
  var path = require("path");
30
31
  var os = require("os");
31
32
 
@@ -79,6 +80,51 @@ function slugifyAgentName(name) {
79
80
  .slice(0, 64);
80
81
  }
81
82
 
83
+ // lr-4c90 — Read the tools list for a named agent directly from its on-disk
84
+ // frontmatter. The SDK AgentInfo surface (supportedAgents()) does not expose
85
+ // the tools field — only name, description, and model are returned. Reading
86
+ // the file directly is the only synchronous path for belt-and-suspenders
87
+ // enforcement in the query setup path.
88
+ //
89
+ // agentName: the agent identity string (e.g. "agentic-director").
90
+ // Returns: string[] of tool names if the tools field is a valid JSON array,
91
+ // null if the file is absent, the frontmatter is missing, or the
92
+ // tools field cannot be parsed.
93
+ //
94
+ // Failures are silent (logged at debug level) — callers treat null as "no
95
+ // restriction from this source" and fall through to whatever the SDK applies
96
+ // via claudeOpts.agent.
97
+ function readAgentToolsFromFile(agentName) {
98
+ if (!agentName || typeof agentName !== "string") return null;
99
+ var slug = slugifyAgentName(agentName);
100
+ if (!slug) return null;
101
+ var filePath = path.join(AGENTS_SOURCE_DIR, slug + ".md");
102
+ var raw;
103
+ try {
104
+ raw = fs.readFileSync(filePath, "utf8");
105
+ } catch (e) {
106
+ // File not found is expected for agents with no on-disk definition.
107
+ return null;
108
+ }
109
+ var parsed = parseFrontmatter(raw);
110
+ if (!parsed || !parsed.meta) return null;
111
+ var toolsVal = parsed.meta.tools;
112
+ if (!toolsVal || typeof toolsVal !== "string") return null;
113
+ var trimmed = toolsVal.trim();
114
+ if (trimmed.charAt(0) !== "[") return null; // not a JSON array — skip
115
+ try {
116
+ var arr = JSON.parse(trimmed);
117
+ if (!Array.isArray(arr)) return null;
118
+ var result = [];
119
+ for (var i = 0; i < arr.length; i++) {
120
+ if (typeof arr[i] === "string" && arr[i]) result.push(arr[i]);
121
+ }
122
+ return result.length > 0 ? result : null;
123
+ } catch (e) {
124
+ return null;
125
+ }
126
+ }
127
+
82
128
  // --- SDK-backed discovery cache ---
83
129
 
84
130
  // Module-level cache. Populated by refresh(); read by getAll().
@@ -182,6 +228,7 @@ module.exports = {
182
228
  PLUGINS_CACHE_DIR: PLUGINS_CACHE_DIR,
183
229
  parseFrontmatter: parseFrontmatter,
184
230
  slugifyAgentName: slugifyAgentName,
231
+ readAgentToolsFromFile: readAgentToolsFromFile,
185
232
  // New SDK-backed surface:
186
233
  refresh: refresh,
187
234
  getAll: getAll,
@@ -21,7 +21,9 @@
21
21
  // Body: { conversation_id, participant, claim_id, [session_label], [force] }
22
22
  // Response: { claim_id, heartbeat_ts, effective }
23
23
  // All requests over HTTP/1.1 on the Unix domain socket, no TLS.
24
- // Identity header: X-Relay-Caller-Lead: "andy" (operator bypass).
24
+ // Identity header: X-Relay-Caller-Lead sourced from CLAGENTIC_OPERATOR_LEAD env
25
+ // (set by per-installation config). Falls back to empty string — relay treats
26
+ // an absent header as anonymous operator access, which is safe for UI-path sessions.
25
27
  //
26
28
  // Conversation list: read ~/.lore/conversation-sidecars/ directly (same as
27
29
  // clagentic conversation list). No relay round-trip needed for listing — the
@@ -51,7 +53,7 @@ var REQUEST_TIMEOUT_MS = 8000; // 8s max per relay call
51
53
 
52
54
  function relaySocketPath() {
53
55
  if (process.env.CLAGENTIC_RELAY_SOCKET) return process.env.CLAGENTIC_RELAY_SOCKET;
54
- var home = os.homedir() || "/root";
56
+ var home = os.homedir();
55
57
  return path.join(home, ".lore", "relay.sock");
56
58
  }
57
59
 
@@ -89,7 +91,7 @@ function relayPost(urlPath, body) {
89
91
  headers: {
90
92
  "Content-Type": "application/json",
91
93
  "Content-Length": Buffer.byteLength(data),
92
- "X-Relay-Caller-Lead": "andy",
94
+ "X-Relay-Caller-Lead": process.env.CLAGENTIC_OPERATOR_LEAD || "",
93
95
  },
94
96
  };
95
97
 
@@ -102,7 +104,7 @@ function relayPost(urlPath, body) {
102
104
  var msg = raw;
103
105
  try {
104
106
  var parsed = JSON.parse(raw);
105
- if (parsed.message) msg = parsed.error + ": " + parsed.message;
107
+ if (parsed.message) msg = (parsed.error ? parsed.error + ": " : "") + parsed.message;
106
108
  } catch (e) {}
107
109
  return reject(new Error("relay " + urlPath + " HTTP " + res.statusCode + ": " + msg));
108
110
  }
@@ -131,7 +133,7 @@ function relayPost(urlPath, body) {
131
133
  // We read these directly — no relay round-trip needed.
132
134
 
133
135
  function loreHomeDir() {
134
- var home = os.homedir() || "/root";
136
+ var home = os.homedir();
135
137
  return path.join(home, ".lore");
136
138
  }
137
139
 
@@ -166,10 +168,11 @@ function listOpenConversationsForAgent(agentName) {
166
168
 
167
169
  // --- Per-session claim state ---
168
170
  //
169
- // Map from session.localId -> { agentName, claims: Map<convId, claimId>, timer }
170
- // where timer is the heartbeat setInterval handle.
171
+ // Map from session.localId -> { agentName, claims: Map<convId, claimId>, timer, watcher }
172
+ // where timer is the heartbeat setInterval handle and watcher is the fs.watch
173
+ // handle for the sidecar directory (stops on detach).
171
174
 
172
- var _sessionClaims = new Map(); // localId -> { agentName, claims, timer }
175
+ var _sessionClaims = new Map(); // localId -> { agentName, claims, timer, watcher }
173
176
 
174
177
  // Generate a UUID for use as claimId. Uses crypto.randomUUID if available
175
178
  // (Node 14.17+), falls back to a hex blob.
@@ -275,15 +278,59 @@ function startHeartbeatLoop(localId) {
275
278
  state.timer = timer;
276
279
  }
277
280
 
281
+ // Watch the sidecar directory for new conversation files. When a new sidecar
282
+ // appears where agentName is a participant, auto-claims via onNewConversation.
283
+ // Called from attachAgentSession after relay reachability is confirmed.
284
+ //
285
+ // preExistingConvIds: Set of conversation_id strings that existed at watcher-start
286
+ // time. Events for these are ignored — operator decides whether to claim them,
287
+ // per lr-9cfc spec. Only sidecar files not in this set trigger auto-claim.
288
+ //
289
+ // Returns the fs.FSWatcher instance, or null if the directory is absent.
290
+ function startSidecarWatcher(localId, agentName, preExistingConvIds) {
291
+ var sidecarDir = path.join(loreHomeDir(), "conversation-sidecars");
292
+ // Keyed by filename so concurrent events for different files don't cancel each other.
293
+ var debounceMap = new Map();
294
+ var watcher;
295
+ try {
296
+ watcher = fs.watch(sidecarDir, function (eventType, filename) {
297
+ if (!filename || !filename.endsWith(".json")) return;
298
+ // Debounce per filename to avoid double-fire from write + rename events.
299
+ var prev = debounceMap.get(filename);
300
+ if (prev) clearTimeout(prev);
301
+ debounceMap.set(filename, setTimeout(function () {
302
+ debounceMap.delete(filename);
303
+ var fullPath = path.join(sidecarDir, filename);
304
+ var raw;
305
+ try { raw = fs.readFileSync(fullPath, "utf8"); } catch (e) { return; }
306
+ var obj;
307
+ try { obj = JSON.parse(raw); } catch (e) { return; }
308
+ if (!obj || obj.status !== "open") return;
309
+ var convId = obj.conversation_id;
310
+ if (!convId) return;
311
+ // Skip conversations that existed before the watcher started — those are
312
+ // display-only; the operator must explicitly claim them (lr-9cfc spec).
313
+ if (preExistingConvIds && preExistingConvIds.has(convId)) return;
314
+ var participants = Array.isArray(obj.participants) ? obj.participants : [];
315
+ var isParticipant = participants.some(function (p) { return p && p.name === agentName; });
316
+ if (!isParticipant) return;
317
+ onNewConversation(localId, agentName, convId);
318
+ }, 50));
319
+ });
320
+ } catch (e) {
321
+ // Sidecar dir absent or watch not supported — silently ignore.
322
+ return null;
323
+ }
324
+ return watcher;
325
+ }
326
+
278
327
  // --- Public API ---
279
328
 
280
329
  // Called when a new session is opened with agentName set.
281
330
  // 1. Checks relay reachability; if absent, returns immediately (no-op).
282
331
  // 2. Lists open conversations for agentName from sidecars.
283
- // 3. For each open conv: registers a live claim (catches 409 silently).
284
- // 4. Starts heartbeat loop.
285
- // 5. Surfaces open conv list to operator via sendToSessionFn (system message).
286
- // Does NOT auto-claim new conversations here — that is handled by onNewConversation.
332
+ // 3. Surfaces open conv list to operator (display-only — operator decides to claim).
333
+ // 4. Starts heartbeat loop and sidecar watcher for auto-claiming new conversations.
287
334
  //
288
335
  // sendToSessionFn: function(obj) — sends to all clients viewing this session.
289
336
  //
@@ -297,6 +344,7 @@ function attachAgentSession(session, agentName, sendToSessionFn) {
297
344
  agentName: agentName,
298
345
  claims: new Map(),
299
346
  timer: null,
347
+ watcher: null,
300
348
  });
301
349
 
302
350
  isRelayReachable().then(function (reachable) {
@@ -312,15 +360,17 @@ function attachAgentSession(session, agentName, sendToSessionFn) {
312
360
  // List open conversations for this agent.
313
361
  var openConvs = listOpenConversationsForAgent(agentName);
314
362
 
315
- // Surface open conversations to operator (display-only, per task spec).
363
+ // Surface open conversations to operator (display-only, per task spec lr-9cfc).
364
+ // Pre-existing conversations are NOT auto-claimed — operator decides per-conversation
365
+ // to avoid recreating the stale-claim/zombie-blocking problem fixed 2026-05-19.
316
366
  if (openConvs.length > 0 && typeof sendToSessionFn === "function") {
317
- var lines = ["Open conversations where " + agentName + " is a participant:"];
367
+ var lines = ["Open conversations where " + agentName + " is a participant (not claimed — operator decides):"];
318
368
  for (var k = 0; k < openConvs.length; k++) {
319
369
  var c = openConvs[k];
320
370
  var short = (c.conversation_id || "").substring(0, 8);
321
371
  lines.push(" " + short + " [" + (c.kind || "?") + "] " + (c.topic || "(no topic)") + " (msgs: " + (c.message_count || 0) + ")");
322
372
  }
323
- lines.push("To claim: clagentic claim register --conv <id> --participant " + agentName);
373
+ lines.push("New conversations opened after this session starts will be auto-claimed.");
324
374
  sendToSessionFn({
325
375
  type: "system_message",
326
376
  text: lines.join("\n"),
@@ -329,26 +379,17 @@ function attachAgentSession(session, agentName, sendToSessionFn) {
329
379
  });
330
380
  }
331
381
 
332
- // Register a live claim for each open conversation.
333
- var sessionLabel = "console-ui-" + agentName + "-" + Date.now();
334
- var registerPromises = openConvs.map(function (c) {
335
- var convId = c.conversation_id;
336
- if (!convId) return Promise.resolve();
337
- return registerClaim(agentName, convId, sessionLabel).then(function (claimId) {
338
- if (!claimId) return;
339
- var s = _sessionClaims.get(localId);
340
- if (!s) return;
341
- s.claims.set(convId, claimId);
342
- console.log("[relay-agent-claims] claimed conv " + convId.substring(0, 8) + " for session " + localId + " (" + agentName + ")");
343
- });
344
- });
345
-
346
- Promise.all(registerPromises).then(function () {
347
- var s = _sessionClaims.get(localId);
348
- if (!s) return;
349
- // Start heartbeat loop (even if no claims yet — new convs may be added).
382
+ // Do NOT auto-claim pre-existing conversations (lr-9cfc spec).
383
+ // Start the heartbeat loop and sidecar watcher so new conversations are
384
+ // auto-claimed via onNewConversation as they appear.
385
+ // Pass the pre-existing conv IDs so the watcher can ignore sidecar rewrites
386
+ // for conversations that were open before this session started.
387
+ var preExistingIds = new Set(openConvs.map(function (c) { return c.conversation_id; }));
388
+ var s = _sessionClaims.get(localId);
389
+ if (s) {
350
390
  startHeartbeatLoop(localId);
351
- });
391
+ s.watcher = startSidecarWatcher(localId, agentName, preExistingIds);
392
+ }
352
393
  });
353
394
  }
354
395
 
@@ -379,7 +420,7 @@ function onNewConversation(localId, agentName, convId) {
379
420
  }
380
421
 
381
422
  // Called when a session is deleted or its agentName is cleared.
382
- // Releases all live claims and stops the heartbeat loop.
423
+ // Releases all live claims, stops the heartbeat loop, and closes the sidecar watcher.
383
424
  // Best-effort — never throws.
384
425
  function detachAgentSession(localId) {
385
426
  var state = _sessionClaims.get(localId);
@@ -391,6 +432,12 @@ function detachAgentSession(localId) {
391
432
  state.timer = null;
392
433
  }
393
434
 
435
+ // Stop sidecar watcher.
436
+ if (state.watcher) {
437
+ try { state.watcher.close(); } catch (e) {}
438
+ state.watcher = null;
439
+ }
440
+
394
441
  // Release all claims (best-effort, async).
395
442
  var agentName = state.agentName;
396
443
  var entries = Array.from(state.claims.entries());
@@ -427,4 +474,7 @@ module.exports = {
427
474
  // exported for tests
428
475
  listOpenConversationsForAgent: listOpenConversationsForAgent,
429
476
  isRelayReachable: isRelayReachable,
477
+ registerClaim: registerClaim,
478
+ heartbeatClaim: heartbeatClaim,
479
+ releaseClaim: releaseClaim,
430
480
  };
package/lib/sdk-bridge.js CHANGED
@@ -8,6 +8,7 @@ var { getCodexConfig } = require("./codex-defaults");
8
8
  var { splitShellSegments, attachSkillDiscovery } = 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
12
 
12
13
  // Extract serializable tool descriptors from MCP server instances.
13
14
  // Used for IPC to worker processes (McpSdkServerConfigWithInstance is not serializable).
@@ -1193,8 +1194,19 @@ function createSDKBridge(opts) {
1193
1194
  // hides the Agent Chat entry point for Codex projects; this guard is
1194
1195
  // belt-and-suspenders for sessions that carry agentName from a prior
1195
1196
  // vendor switch or a direct ws message.
1197
+ //
1198
+ // lr-4c90 — belt-and-suspenders tool enforcement: the SDK's `agent` option
1199
+ // should apply tool restrictions, but only does so when the agent file uses
1200
+ // JSON array syntax for the tools field. We read the tools list directly
1201
+ // from disk and set claudeOpts.tools explicitly so restriction is enforced
1202
+ // even if the SDK's parsing path has any quirks.
1196
1203
  if (session.agentName && sessionAdapter.vendor !== 'codex') {
1197
1204
  claudeOpts.agent = session.agentName;
1205
+ var agentTools = readAgentToolsFromFile(session.agentName);
1206
+ if (agentTools) {
1207
+ claudeOpts.tools = agentTools;
1208
+ console.log("[sdk-bridge] agent tools enforced for " + session.agentName + ": " + agentTools.join(", "));
1209
+ }
1198
1210
  }
1199
1211
 
1200
1212
  // Per-loop settings override global defaults when present
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.2.0-beta.1",
6
+ "version": "1.2.0-beta.2",
7
7
  "description": "Self-hosted console for Claude Code and Codex. Multi-user, browser-based, persistent AI sessions.",
8
8
  "bin": {
9
9
  "clagentic": "./bin/cli.js",