@clagentic/console 1.4.0-beta.1 → 1.4.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.
package/lib/sdk-bridge.js CHANGED
@@ -5,10 +5,12 @@ var execSync = require("child_process").execSync;
5
5
  var execFileSync = require("child_process").execFileSync;
6
6
  var usersModule = require("./users");
7
7
  var { getCodexConfig } = require("./codex-defaults");
8
- var { splitShellSegments, attachSkillDiscovery } = require("./sdk-skill-discovery");
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
11
  var { readAgentToolsFromFile } = require("./agents");
12
+ var { discoverWorkflows } = require("./sdk-workflow-discovery");
13
+ var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
12
14
 
13
15
  // --- lr-29f9: Global concurrent-session ceiling ---
14
16
  // Counts queries that are actively running (startQuery entered, processQueryStream
@@ -18,9 +20,30 @@ var { readAgentToolsFromFile } = require("./agents");
18
20
  var _activeLiveCount = 0;
19
21
  var MAX_CONCURRENT_SESSIONS = (function () {
20
22
  var env = parseInt(process.env.CLAGENTIC_MAX_CONCURRENT_SESSIONS, 10);
21
- return (env > 0) ? env : 6;
23
+ return (env > 0) ? env : 50;
22
24
  })();
23
25
 
26
+ // --- lr-2d91: MemAvailable gate ---
27
+ // Default minimum available memory threshold in MB. Referenced by sdk-bridge
28
+ // and daemon.js — changing this constant is the single place to adjust the default.
29
+ var DEFAULT_MEM_AVAILABLE_MIN_MB = 1024;
30
+
31
+ // Read Linux MemAvailable from /proc/meminfo synchronously.
32
+ // Returns available memory in MB, or null on non-Linux or read failure.
33
+ // Sub-millisecond on Linux; the synchronous read is correct here — this is a
34
+ // pre-launch check, not a hot path, and the async equivalent buys nothing.
35
+ function readMemAvailableMB() {
36
+ if (process.platform !== "linux") return null;
37
+ try {
38
+ var raw = fs.readFileSync("/proc/meminfo", "utf8");
39
+ var match = raw.match(/^MemAvailable:\s+(\d+)\s+kB/m);
40
+ if (!match) return null;
41
+ return Math.floor(parseInt(match[1], 10) / 1024);
42
+ } catch (e) {
43
+ return null;
44
+ }
45
+ }
46
+
24
47
  // Extract serializable tool descriptors from MCP server instances.
25
48
  // Used for IPC to worker processes (McpSdkServerConfigWithInstance is not serializable).
26
49
  function extractMcpDescriptors(mcpServers) {
@@ -349,6 +372,8 @@ function createSDKBridge(opts) {
349
372
  opts: opts,
350
373
  discoverSkillDirs: discoverSkillDirs,
351
374
  mergeSkills: mergeSkills,
375
+ discoverSkillsWithMeta: function(cwdArg) { return discoverSkillsWithMeta(cwdArg); },
376
+ mergeSkillsWithMeta: mergeSkillsWithMeta,
352
377
  });
353
378
  var processSDKMessage = msgProcessor.processSDKMessage;
354
379
  var sendAndRecord = msgProcessor.sendAndRecord;
@@ -1202,12 +1227,37 @@ function createSDKBridge(opts) {
1202
1227
  onProcessingChanged();
1203
1228
  sendAndRecord(session, {
1204
1229
  type: "error",
1205
- text: "Too many active sessions (" + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + "). Wait for another session to finish, or increase CLAGENTIC_MAX_CONCURRENT_SESSIONS.",
1230
+ text: "Too many active sessions (" + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + "). Wait for an active session to finish or close unused sessions.",
1206
1231
  });
1207
1232
  sendAndRecord(session, { type: "done", code: 1 });
1208
1233
  sm.broadcastSessionList();
1209
1234
  return;
1210
1235
  }
1236
+
1237
+ // lr-2d91: MemAvailable gate — check before claiming a slot so a rejected
1238
+ // query never increments the live counter.
1239
+ if (isNewQuery) {
1240
+ var memAvailMB = readMemAvailableMB();
1241
+ var getConfig = opts.getConfig;
1242
+ var memThresholdMB = DEFAULT_MEM_AVAILABLE_MIN_MB;
1243
+ if (typeof getConfig === "function") {
1244
+ var dc = getConfig();
1245
+ if (dc && typeof dc.memAvailableMinMB === "number" && dc.memAvailableMinMB > 0) {
1246
+ memThresholdMB = dc.memAvailableMinMB;
1247
+ }
1248
+ }
1249
+ if (memAvailMB !== null && memAvailMB < memThresholdMB) {
1250
+ console.warn("[sdk-bridge] MemAvailable gate: " + memAvailMB + " MB available, " + memThresholdMB + " MB required — rejecting new query for session " + session.localId);
1251
+ session.isProcessing = false;
1252
+ onProcessingChanged();
1253
+ var memMsg = "Not enough memory to start a new query (" + memAvailMB + " MB available, " + memThresholdMB + " MB required). Wait for an active session to finish or close unused sessions.";
1254
+ sendAndRecord(session, { type: "error", text: memMsg });
1255
+ sendAndRecord(session, { type: "done", code: 1 });
1256
+ send({ type: "toast", level: "warn", message: "Query blocked — not enough memory (" + memAvailMB + " MB available).", duration: 5000 });
1257
+ sm.broadcastSessionList();
1258
+ return;
1259
+ }
1260
+ }
1211
1261
  // Claim the slot now so concurrent callers see the updated count immediately.
1212
1262
  // Set _isCountedLive on the session at the same time so any early-return path
1213
1263
  // below (sync throw, createQuery failure) can release it via releaseSlot().
@@ -1618,16 +1668,15 @@ function createSDKBridge(opts) {
1618
1668
 
1619
1669
  var fsSkills = discoverSkillDirs();
1620
1670
  sm.skillNames = mergeSkills(result.skills, fsSkills);
1671
+ sm.workflowMeta = discoverWorkflows(cwd);
1672
+ // Enriched skill metadata (lr-7d8d)
1673
+ var fsSkillsMeta = discoverSkillsWithMeta(cwd);
1674
+ sm.skillMeta = mergeSkillsWithMeta(result.skills, fsSkillsMeta);
1621
1675
  if (result.slashCommands) {
1622
- var seen = new Set();
1623
- var combined = [];
1624
- var all = result.slashCommands.concat(Array.from(sm.skillNames));
1625
- for (var k = 0; k < all.length; k++) {
1626
- if (!seen.has(all[k])) {
1627
- seen.add(all[k]);
1628
- combined.push(all[k]);
1629
- }
1630
- }
1676
+ // Build enriched {name,desc,type}[] using the shared helper (lr-cf84).
1677
+ // Applies skill/workflow priority chain at warmup time, matching the
1678
+ // live-query init path so the UI receives enriched objects on connect.
1679
+ var combined = buildEnrichedSlashCommands(result.slashCommands, cwd);
1631
1680
  sm.slashCommands = combined;
1632
1681
  sm.setSlashCommandsForVendor(defaultVendor, combined);
1633
1682
  send({ type: "slash_commands", commands: combined, vendor: defaultVendor });
@@ -1912,6 +1961,15 @@ function createSDKBridge(opts) {
1912
1961
  };
1913
1962
  }
1914
1963
 
1964
+ // lr-2d91: Expose live concurrency stats for process_stats WS response.
1965
+ // Called by project-sessions.js when building the process_stats payload.
1966
+ function getMemoryStats() {
1967
+ return {
1968
+ activeLiveCount: _activeLiveCount,
1969
+ maxConcurrentSessions: MAX_CONCURRENT_SESSIONS,
1970
+ };
1971
+ }
1972
+
1915
1973
  return {
1916
1974
  createMessageQueue: createMessageQueue,
1917
1975
  processSDKMessage: processSDKMessage,
@@ -1937,8 +1995,9 @@ function createSDKBridge(opts) {
1937
1995
  createMentionSession: createMentionSession,
1938
1996
  startIdleReaper: startIdleReaper,
1939
1997
  stopIdleReaper: stopIdleReaper,
1998
+ getMemoryStats: getMemoryStats,
1940
1999
  };
1941
2000
  }
1942
2001
 
1943
- module.exports = { createSDKBridge, createMessageQueue };
2002
+ module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, DEFAULT_MEM_AVAILABLE_MIN_MB };
1944
2003
 
@@ -1,4 +1,6 @@
1
1
  var usersModule = require("./users");
2
+ var { discoverWorkflows } = require("./sdk-workflow-discovery");
3
+ var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
2
4
 
3
5
  function attachMessageProcessor(ctx) {
4
6
  var sm = ctx.sm;
@@ -15,6 +17,10 @@ function attachMessageProcessor(ctx) {
15
17
  var opts = ctx.opts;
16
18
  var discoverSkillDirs = ctx.discoverSkillDirs;
17
19
  var mergeSkills = ctx.mergeSkills;
20
+ var discoverSkillsWithMeta = ctx.discoverSkillsWithMeta;
21
+ var mergeSkillsWithMeta = ctx.mergeSkillsWithMeta;
22
+ // Allows callers (and tests) to inject a mock; falls back to the real implementation.
23
+ var discoverWorkflowsFn = ctx.discoverWorkflows || discoverWorkflows;
18
24
 
19
25
  var AUTO_TITLE_TURN_THRESHOLD = 2;
20
26
 
@@ -145,17 +151,22 @@ function attachMessageProcessor(ctx) {
145
151
  if (parsed.yokeType === "init") {
146
152
  var fsSkills = discoverSkillDirs();
147
153
  sm.skillNames = mergeSkills(parsed.skills, fsSkills);
154
+ sm.workflowMeta = discoverWorkflowsFn(cwd);
155
+ // Enriched skill metadata (lr-7d8d) — stored alongside skillNames for consumers
156
+ // that need description and type without breaking existing skillNames callers.
157
+ if (typeof discoverSkillsWithMeta === "function" && typeof mergeSkillsWithMeta === "function") {
158
+ var fsSkillsMeta = discoverSkillsWithMeta(cwd);
159
+ sm.skillMeta = mergeSkillsWithMeta(parsed.skills, fsSkillsMeta);
160
+ }
148
161
  if (parsed.slashCommands) {
149
- // Union: SDK slash_commands + merged skills (deduplicated)
150
- var seen = new Set();
151
- var combined = [];
152
- var all = parsed.slashCommands.concat(Array.from(sm.skillNames));
153
- for (var k = 0; k < all.length; k++) {
154
- if (!seen.has(all[k])) {
155
- seen.add(all[k]);
156
- combined.push(all[k]);
157
- }
158
- }
162
+ // Delegate to shared enrichment helper (lr-cf84). Pass ctx-injected
163
+ // discovery functions so tests can mock filesystem reads as before.
164
+ var _enrichFns = {
165
+ discoverSkillsWithMeta: typeof discoverSkillsWithMeta === "function" ? discoverSkillsWithMeta : undefined,
166
+ mergeSkillsWithMeta: typeof mergeSkillsWithMeta === "function" ? mergeSkillsWithMeta : undefined,
167
+ discoverWorkflows: discoverWorkflowsFn,
168
+ };
169
+ var combined = buildEnrichedSlashCommands(parsed.slashCommands, cwd, _enrichFns);
159
170
  sm.slashCommands = combined;
160
171
  send({ type: "slash_commands", commands: sm.slashCommands });
161
172
  }
@@ -77,6 +77,197 @@ function splitShellSegments(cmd) {
77
77
  return segments;
78
78
  }
79
79
 
80
+ // YAML block scalar indicators: folded (>) and literal (|), with optional
81
+ // chomping modifiers (- or +). When description: is followed by one of these,
82
+ // the actual text is on the subsequent indented lines.
83
+ var YAML_BLOCK_SCALAR_RE = /^[>|][+-]?$/;
84
+
85
+ // Collect YAML block scalar continuation lines starting at index `start`.
86
+ // Stops at the first non-indented, non-blank line or at a `---` boundary.
87
+ // Returns the joined text with parts separated by spaces.
88
+ function collectBlockScalar(lines, start) {
89
+ var parts = [];
90
+ for (var j = start; j < lines.length; j++) {
91
+ var cont = lines[j];
92
+ // Stop at a YAML document boundary or any non-indented non-blank line
93
+ if (cont === "---" || (cont.length > 0 && !/^\s/.test(cont))) {
94
+ break;
95
+ }
96
+ parts.push(cont.trim());
97
+ }
98
+ // Drop trailing blank parts introduced by the block scalar end
99
+ while (parts.length > 0 && parts[parts.length - 1] === "") {
100
+ parts.pop();
101
+ }
102
+ return parts.join(" ").trim();
103
+ }
104
+
105
+ // Strip surrounding single or double quotes from a plain YAML scalar value.
106
+ function stripYamlQuotes(value) {
107
+ if (
108
+ (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') ||
109
+ (value.charAt(0) === "'" && value.charAt(value.length - 1) === "'")
110
+ ) {
111
+ return value.slice(1, -1);
112
+ }
113
+ return value;
114
+ }
115
+
116
+ // Extract a short description from the raw text content of a markdown file.
117
+ // Priority:
118
+ // 1. YAML frontmatter (--- delimited, line 0 === "---"): scan for
119
+ // description: key within the block (before closing ---), handling both
120
+ // plain string (quoted or unquoted) and block scalar (> |) values.
121
+ // 2. Bare frontmatter: description: before the first `#` heading, with block
122
+ // scalar support (lr-2634).
123
+ // 3. First non-empty, non-heading prose line after any heading.
124
+ // 4. Empty string if none found.
125
+ function extractDescriptionFromContent(content) {
126
+ var lines = content.split(/\r?\n/);
127
+
128
+ // --- Priority 1: YAML frontmatter (line 0 must be exactly "---") ---
129
+ if (lines[0] === "---") {
130
+ // Find the closing --- and scan for description: within the block
131
+ var closingIdx = -1;
132
+ for (var fi = 1; fi < lines.length; fi++) {
133
+ if (lines[fi] === "---") { closingIdx = fi; break; }
134
+ if (/^description:\s*\S/.test(lines[fi])) {
135
+ // Plain scalar (possibly quoted)
136
+ var fval = lines[fi].replace(/^description:\s*/, "").trim();
137
+ if (YAML_BLOCK_SCALAR_RE.test(fval)) {
138
+ return collectBlockScalar(lines, fi + 1);
139
+ }
140
+ return stripYamlQuotes(fval);
141
+ }
142
+ if (/^description:\s*$/.test(lines[fi])) {
143
+ // Bare key — block scalar follows on indented lines
144
+ return collectBlockScalar(lines, fi + 1);
145
+ }
146
+ }
147
+ // description: absent from frontmatter — fall through to prose after block
148
+ var proseStart = closingIdx >= 0 ? closingIdx + 1 : 1;
149
+ for (var pi = proseStart; pi < lines.length; pi++) {
150
+ if (/^#/.test(lines[pi])) { continue; }
151
+ var ps = lines[pi].replace(/^#+\s*/, "").trim();
152
+ if (ps.length > 0) { return ps; }
153
+ }
154
+ return "";
155
+ }
156
+
157
+ // --- Priority 2 & 3: bare frontmatter or prose scan ---
158
+ var pastFirstHeading = false;
159
+ for (var i = 0; i < lines.length; i++) {
160
+ var line = lines[i];
161
+ // Bare frontmatter: description: key before the first # heading
162
+ if (!pastFirstHeading && /^description:\s/.test(line)) {
163
+ var value = line.replace(/^description:\s*/, "").trim();
164
+ // YAML block scalar: collect the indented continuation lines
165
+ if (YAML_BLOCK_SCALAR_RE.test(value)) {
166
+ return collectBlockScalar(lines, i + 1);
167
+ }
168
+ return value;
169
+ }
170
+ if (/^#/.test(line)) {
171
+ pastFirstHeading = true;
172
+ continue;
173
+ }
174
+ // First non-empty, non-heading prose line (strip any leading `#` markers)
175
+ var stripped = line.replace(/^#+\s*/, "").trim();
176
+ if (stripped.length > 0) {
177
+ return stripped;
178
+ }
179
+ }
180
+ return "";
181
+ }
182
+
183
+ // Read SKILL.md for a skill directory and extract a short description string.
184
+ // Delegates to extractDescriptionFromContent for the actual parsing logic.
185
+ function extractSkillDescription(skillDir) {
186
+ var skillMd = path.join(skillDir, "SKILL.md");
187
+ var content;
188
+ try {
189
+ content = fs.readFileSync(skillMd, "utf8");
190
+ } catch (e) {
191
+ return "";
192
+ }
193
+ return extractDescriptionFromContent(content);
194
+ }
195
+
196
+ // Return an array of {name, description, type:'skill'} for all discovered
197
+ // skill directories. Reads every SKILL.md to extract a description.
198
+ // Project skills override global skills with the same name (global → project
199
+ // discovery order, last-write wins).
200
+ function discoverSkillsWithMeta(cwd) {
201
+ var dirs = [
202
+ path.join(require("./config").REAL_HOME, ".claude", "skills"),
203
+ path.join(cwd, ".claude", "skills"),
204
+ ];
205
+ // Ordered map so project skills override global skills
206
+ var byName = {};
207
+ for (var d = 0; d < dirs.length; d++) {
208
+ var base = dirs[d];
209
+ var entries;
210
+ try {
211
+ entries = fs.readdirSync(base, { withFileTypes: true });
212
+ } catch (e) {
213
+ continue;
214
+ }
215
+ for (var i = 0; i < entries.length; i++) {
216
+ var entry = entries[i];
217
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
218
+ var skillDir = path.join(base, entry.name);
219
+ var skillMdPath = path.join(skillDir, "SKILL.md");
220
+ try {
221
+ fs.accessSync(skillMdPath, fs.constants.R_OK);
222
+ byName[entry.name] = skillDir;
223
+ } catch (e) {
224
+ // no SKILL.md, skip
225
+ }
226
+ }
227
+ }
228
+ var result = [];
229
+ var names = Object.keys(byName);
230
+ for (var j = 0; j < names.length; j++) {
231
+ var name = names[j];
232
+ result.push({
233
+ name: name,
234
+ description: extractSkillDescription(byName[name]),
235
+ type: "skill",
236
+ });
237
+ }
238
+ return result;
239
+ }
240
+
241
+ // Merge an array of SDK skill names and the enriched fsSkillsWithMeta array
242
+ // into a single deduplicated {name, description, type} array.
243
+ // FS skills (which carry descriptions) always override SDK-name-only entries.
244
+ // SDK-name-only entries get empty description and type 'skill'.
245
+ function mergeSkillsWithMeta(sdkSkillNames, fsSkillsWithMeta) {
246
+ var byName = {};
247
+ if (Array.isArray(sdkSkillNames)) {
248
+ for (var i = 0; i < sdkSkillNames.length; i++) {
249
+ var n = sdkSkillNames[i];
250
+ if (typeof n === "string" && !byName[n]) {
251
+ byName[n] = { name: n, description: "", type: "skill" };
252
+ }
253
+ }
254
+ }
255
+ if (Array.isArray(fsSkillsWithMeta)) {
256
+ for (var j = 0; j < fsSkillsWithMeta.length; j++) {
257
+ var skill = fsSkillsWithMeta[j];
258
+ if (skill && typeof skill.name === "string") {
259
+ // fs entry always overrides sdk-name-only entry
260
+ byName[skill.name] = {
261
+ name: skill.name,
262
+ description: skill.description || "",
263
+ type: skill.type || "skill",
264
+ };
265
+ }
266
+ }
267
+ }
268
+ return Object.keys(byName).map(function(k) { return byName[k]; });
269
+ }
270
+
80
271
  function attachSkillDiscovery(ctx) {
81
272
  var cwd = ctx.cwd;
82
273
 
@@ -128,4 +319,11 @@ function attachSkillDiscovery(ctx) {
128
319
  return { discoverSkillDirs: discoverSkillDirs, mergeSkills: mergeSkills };
129
320
  }
130
321
 
131
- module.exports = { splitShellSegments: splitShellSegments, attachSkillDiscovery: attachSkillDiscovery };
322
+ module.exports = {
323
+ splitShellSegments: splitShellSegments,
324
+ attachSkillDiscovery: attachSkillDiscovery,
325
+ extractDescriptionFromContent: extractDescriptionFromContent,
326
+ extractSkillDescription: extractSkillDescription,
327
+ discoverSkillsWithMeta: discoverSkillsWithMeta,
328
+ mergeSkillsWithMeta: mergeSkillsWithMeta,
329
+ };
@@ -0,0 +1,64 @@
1
+ var _defaultDiscoverSkillsWithMeta = require('./sdk-skill-discovery').discoverSkillsWithMeta;
2
+ var _defaultMergeSkillsWithMeta = require('./sdk-skill-discovery').mergeSkillsWithMeta;
3
+ var _defaultDiscoverWorkflows = require('./sdk-workflow-discovery').discoverWorkflows;
4
+
5
+ // Build enriched {name, desc, type}[] from three sources:
6
+ // 1. skillMeta (highest priority) — type:'skill'
7
+ // 2. workflowMeta — type:'workflow'
8
+ // 3. CLI-emitted names not covered above — type:'builtin', desc:''
9
+ //
10
+ // cliSlashCommands: string[] or {name,...}[] from the CLI init or warmup event
11
+ // cwd: working directory used for skill/workflow discovery
12
+ //
13
+ // The optional third argument `fns` allows callers to inject alternative
14
+ // discovery functions — used by sdk-message-processor.js to pass its
15
+ // context-injected mocks so tests remain hermetic.
16
+ //
17
+ // Both discovery calls are wrapped in try/catch so a missing .claude directory
18
+ // on disk never prevents slash commands from reaching the frontend.
19
+ function buildEnrichedSlashCommands(cliSlashCommands, cwd, fns) {
20
+ var discoverSkillsWithMeta = (fns && fns.discoverSkillsWithMeta) || _defaultDiscoverSkillsWithMeta;
21
+ var mergeSkillsWithMeta = (fns && fns.mergeSkillsWithMeta) || _defaultMergeSkillsWithMeta;
22
+ var discoverWorkflows = (fns && fns.discoverWorkflows) || _defaultDiscoverWorkflows;
23
+
24
+ var fsSkillsMeta = [];
25
+ try { fsSkillsMeta = discoverSkillsWithMeta(cwd); } catch (e) {}
26
+ var skillMeta = [];
27
+ try { skillMeta = mergeSkillsWithMeta([], fsSkillsMeta); } catch (e) {}
28
+
29
+ var workflowMeta = [];
30
+ try { workflowMeta = discoverWorkflows(cwd); } catch (e) {}
31
+
32
+ var seen = new Set();
33
+ var combined = [];
34
+
35
+ // Priority 1: skills with descriptions
36
+ for (var i = 0; i < skillMeta.length; i++) {
37
+ var s = skillMeta[i];
38
+ if (!seen.has(s.name)) {
39
+ seen.add(s.name);
40
+ combined.push({ name: s.name, desc: s.description || '', type: 'skill' });
41
+ }
42
+ }
43
+ // Priority 2: workflows with descriptions
44
+ for (var j = 0; j < workflowMeta.length; j++) {
45
+ var w = workflowMeta[j];
46
+ if (!seen.has(w.name)) {
47
+ seen.add(w.name);
48
+ combined.push({ name: w.name, desc: w.description || '', type: 'workflow' });
49
+ }
50
+ }
51
+ // Priority 3: CLI-emitted names not covered above (builtins)
52
+ var cli = cliSlashCommands || [];
53
+ for (var k = 0; k < cli.length; k++) {
54
+ var entry = cli[k];
55
+ var name = (typeof entry === 'object' && entry !== null) ? entry.name : entry;
56
+ if (name && !seen.has(name)) {
57
+ seen.add(name);
58
+ combined.push({ name: name, desc: '', type: 'builtin' });
59
+ }
60
+ }
61
+ return combined;
62
+ }
63
+
64
+ module.exports = { buildEnrichedSlashCommands: buildEnrichedSlashCommands };
package/lib/sdk-worker.js CHANGED
@@ -40,6 +40,9 @@ var pendingElicitations = {}; // requestId -> resolve
40
40
  var pendingMcpCalls = {}; // requestId -> { resolve, reject }
41
41
  var conn = null;
42
42
  var buffer = "";
43
+ // Reference to the claude CLI child process spawned by spawnClaudeCodeProcess.
44
+ // Stored so cleanup() can send SIGTERM/SIGKILL to it on worker shutdown.
45
+ var _claudeChildProcess = null;
43
46
 
44
47
  // --- Message queue (same implementation as sdk-bridge.js) ---
45
48
  function createMessageQueue() {
@@ -394,6 +397,8 @@ async function handleQueryStart(msg) {
394
397
  env: spawnOpts.env,
395
398
  stdio: ["pipe", "pipe", "pipe"],
396
399
  });
400
+ // Track the child so cleanup() can terminate it on worker shutdown.
401
+ _claudeChildProcess = cp;
397
402
  // Capture ALL CLI stderr
398
403
  if (cp.stderr) {
399
404
  cp.stderr.on("data", function(chunk) {
@@ -649,6 +654,18 @@ function cleanup() {
649
654
  if (conn && !conn.destroyed) {
650
655
  try { conn.end(); } catch (e) {}
651
656
  }
657
+ // Terminate the claude CLI child process. Without this, it outlives the worker
658
+ // and becomes orphaned when the daemon sends SIGTERM to the process group.
659
+ if (_claudeChildProcess && !_claudeChildProcess.killed) {
660
+ try { _claudeChildProcess.kill("SIGTERM"); } catch (e) {}
661
+ // SIGKILL fallback after brief grace period to allow the CLI to flush state.
662
+ var _cpSnapshot = _claudeChildProcess;
663
+ setTimeout(function() {
664
+ if (_cpSnapshot && !_cpSnapshot.killed) {
665
+ try { _cpSnapshot.kill("SIGKILL"); } catch (e) {}
666
+ }
667
+ }, 2000);
668
+ }
652
669
  }
653
670
 
654
671
  // Exit with a grace period so the SDK can flush session state to disk.
@@ -0,0 +1,151 @@
1
+ var fs = require('fs');
2
+ var path = require('path');
3
+ var extractDescriptionFromContent = require('./sdk-skill-discovery').extractDescriptionFromContent;
4
+
5
+ // Regex to locate the meta block and extract string fields from it.
6
+ // The meta block always appears as a static literal near the top of the file:
7
+ // export const meta = { name: 'foo', description: 'bar', ... }
8
+ // We do NOT require() or eval the file — the regex operates on raw source text.
9
+ var RE_META_OPEN = /export\s+const\s+meta\s*=\s*\{/;
10
+ var RE_FIELD = function (field) {
11
+ return new RegExp(field + ":\\s*['\"]([^'\"]+)['\"]");
12
+ };
13
+
14
+ // Parse meta.name and meta.description from raw .js file content.
15
+ // Scans only the first 40 lines so the regex never runs against large files.
16
+ // Returns { name, description } or null if either field cannot be parsed.
17
+ function parseWorkflowMeta(content) {
18
+ // Limit scan to first 40 lines for performance and correctness
19
+ // (meta block is always a static literal at the top of the file).
20
+ var lines = content.split('\n');
21
+ var head = lines.slice(0, 40).join('\n');
22
+
23
+ if (!RE_META_OPEN.test(head)) return null;
24
+
25
+ var nameMatch = RE_FIELD('name').exec(head);
26
+ var descMatch = RE_FIELD('description').exec(head);
27
+
28
+ if (!nameMatch || !descMatch) return null;
29
+
30
+ return {
31
+ name: nameMatch[1],
32
+ description: descMatch[1],
33
+ };
34
+ }
35
+
36
+ // Scan a single workflow directory for .js files with parseable meta blocks.
37
+ // Adds results to the provided map (name -> entry), so later calls override earlier ones.
38
+ function scanWorkflowDir(dir, resultMap) {
39
+ var entries;
40
+ try {
41
+ entries = fs.readdirSync(dir);
42
+ } catch (e) {
43
+ // Directory does not exist or is unreadable — skip silently.
44
+ return;
45
+ }
46
+
47
+ for (var i = 0; i < entries.length; i++) {
48
+ var fname = entries[i];
49
+ if (path.extname(fname) !== '.js') continue;
50
+
51
+ var fpath = path.join(dir, fname);
52
+ var content;
53
+ try {
54
+ content = fs.readFileSync(fpath, 'utf8');
55
+ } catch (e) {
56
+ continue;
57
+ }
58
+
59
+ var meta = parseWorkflowMeta(content);
60
+ if (!meta) continue;
61
+
62
+ // cwd-local entry wins on name collision (inserted last).
63
+ resultMap[meta.name] = {
64
+ name: meta.name,
65
+ description: meta.description,
66
+ type: 'workflow',
67
+ };
68
+ }
69
+ }
70
+
71
+ // Scan a single workflow directory for .md files and extract descriptions.
72
+ // Files named exactly "SKILL.md" are skipped — those are skill definitions,
73
+ // not user-invocable slash commands.
74
+ // Adds results to the provided map (name -> entry), so later calls override earlier ones.
75
+ // .md entries always override .js entries on name collision when scanned after .js.
76
+ function scanWorkflowMdDir(dir, resultMap) {
77
+ var entries;
78
+ try {
79
+ entries = fs.readdirSync(dir);
80
+ } catch (e) {
81
+ // Directory does not exist or is unreadable — skip silently.
82
+ return;
83
+ }
84
+
85
+ for (var i = 0; i < entries.length; i++) {
86
+ var fname = entries[i];
87
+ if (path.extname(fname) !== '.md') continue;
88
+ // SKILL.md is a skill definition file, not a workflow slash command.
89
+ if (fname === 'SKILL.md') continue;
90
+
91
+ var fpath = path.join(dir, fname);
92
+ var content;
93
+ try {
94
+ content = fs.readFileSync(fpath, 'utf8');
95
+ } catch (e) {
96
+ continue;
97
+ }
98
+
99
+ var name = path.basename(fname, '.md');
100
+ var description = extractDescriptionFromContent(content);
101
+
102
+ resultMap[name] = {
103
+ name: name,
104
+ description: description,
105
+ type: 'workflow',
106
+ };
107
+ }
108
+ }
109
+
110
+ // Discover workflow files and return their metadata.
111
+ // Scans:
112
+ // 1. ~/.claude/workflows/ (global, from REAL_HOME)
113
+ // 2. <cwd>/.claude/workflows/ (project-local, wins on name collision)
114
+ //
115
+ // Within each directory, .js files are scanned first, then .md files.
116
+ // .md entries override .js entries on name collision (user-facing slash
117
+ // commands take priority over internal orchestration scripts).
118
+ //
119
+ // Returns an array of { name, description, type: 'workflow' }.
120
+ // Never throws — missing directories are silently skipped.
121
+ //
122
+ // The optional second argument _homeDir is for testing only: it overrides
123
+ // REAL_HOME so tests can inject a temporary directory without module-cache tricks.
124
+ function discoverWorkflows(cwd, _homeDir) {
125
+ var homeDir;
126
+ if (_homeDir) {
127
+ homeDir = _homeDir;
128
+ } else {
129
+ try {
130
+ homeDir = require('./config').REAL_HOME;
131
+ } catch (e) {
132
+ homeDir = require('os').homedir();
133
+ }
134
+ }
135
+
136
+ var resultMap = {};
137
+ var globalWfDir = path.join(homeDir, '.claude', 'workflows');
138
+ var localWfDir = path.join(cwd, '.claude', 'workflows');
139
+
140
+ // Global .js first, then global .md (so .md overrides .js on same name).
141
+ scanWorkflowDir(globalWfDir, resultMap);
142
+ scanWorkflowMdDir(globalWfDir, resultMap);
143
+
144
+ // Project-local .js, then project-local .md — local entries override global.
145
+ scanWorkflowDir(localWfDir, resultMap);
146
+ scanWorkflowMdDir(localWfDir, resultMap);
147
+
148
+ return Object.keys(resultMap).map(function (k) { return resultMap[k]; });
149
+ }
150
+
151
+ module.exports = { discoverWorkflows: discoverWorkflows };