@clagentic/console 1.4.0-beta.2 → 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.
@@ -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 };
package/lib/server.js CHANGED
@@ -180,6 +180,7 @@ function createServer(opts) {
180
180
  var onSetPin = opts.onSetPin || null;
181
181
  var onSetKeepAwake = opts.onSetKeepAwake || null;
182
182
  var onSetImageRetention = opts.onSetImageRetention || null;
183
+ var onSetMemAvailableThreshold = opts.onSetMemAvailableThreshold || null;
183
184
  var onShutdown = opts.onShutdown || null;
184
185
  var onRestart = opts.onRestart || null;
185
186
  var onSetUpdateChannel = opts.onSetUpdateChannel || null;
@@ -1075,6 +1076,7 @@ function createServer(opts) {
1075
1076
  onSetPin: onSetPin,
1076
1077
  onSetKeepAwake: onSetKeepAwake,
1077
1078
  onSetImageRetention: onSetImageRetention,
1079
+ onSetMemAvailableThreshold: onSetMemAvailableThreshold,
1078
1080
  onSetUpdateChannel: onSetUpdateChannel,
1079
1081
  updateChannel: onGetDaemonConfig ? (onGetDaemonConfig().updateChannel || "stable") : "stable",
1080
1082
  onShutdown: onShutdown,
package/lib/sessions.js CHANGED
@@ -1060,6 +1060,8 @@ function createSessionManager(opts) {
1060
1060
  return {
1061
1061
  get activeSessionId() { return activeSessionId; },
1062
1062
  get nextLocalId() { return nextLocalId; },
1063
+ // slashCommands and slashCommandsByVendor store {name, desc, type}[] (lr-1c7f).
1064
+ // Previously string[]; now enriched objects. Setters are generic pass-through.
1063
1065
  get slashCommands() { return slashCommands; },
1064
1066
  set slashCommands(v) { slashCommands = v; },
1065
1067
  get slashCommandsByVendor() { return slashCommandsByVendor; },
@@ -103,6 +103,9 @@ var pendingElicitations = {}; // requestId -> resolve
103
103
  var pendingMcpToolCalls = {}; // requestId -> { resolve, reject }
104
104
  var conn = null;
105
105
  var buffer = "";
106
+ // Reference to the claude CLI child process spawned by spawnClaudeCodeProcess.
107
+ // Stored so cleanup() can send SIGTERM/SIGKILL to it on worker shutdown.
108
+ var _claudeChildProcess = null;
106
109
 
107
110
  // --- Message queue (same implementation as sdk-bridge.js) ---
108
111
  function createMessageQueue() {
@@ -458,6 +461,8 @@ async function handleQueryStart(msg) {
458
461
  env: spawnOpts.env,
459
462
  stdio: ["pipe", "pipe", "pipe"],
460
463
  });
464
+ // Track the child so cleanup() can terminate it on worker shutdown.
465
+ _claudeChildProcess = cp;
461
466
  // Capture ALL CLI stderr
462
467
  if (cp.stderr) {
463
468
  cp.stderr.on("data", function(chunk) {
@@ -730,6 +735,18 @@ function cleanup() {
730
735
  if (conn && !conn.destroyed) {
731
736
  try { conn.end(); } catch (e) {}
732
737
  }
738
+ // Terminate the claude CLI child process. Without this, it outlives the worker
739
+ // and becomes orphaned when the daemon sends SIGTERM to the process group.
740
+ if (_claudeChildProcess && !_claudeChildProcess.killed) {
741
+ try { _claudeChildProcess.kill("SIGTERM"); } catch (e) {}
742
+ // SIGKILL fallback after brief grace period to allow the CLI to flush state.
743
+ var _cpSnapshot = _claudeChildProcess;
744
+ setTimeout(function() {
745
+ if (_cpSnapshot && !_cpSnapshot.killed) {
746
+ try { _cpSnapshot.kill("SIGKILL"); } catch (e) {}
747
+ }
748
+ }, 2000);
749
+ }
733
750
  }
734
751
 
735
752
  // Exit with a grace period so the SDK can flush session state to disk.
@@ -523,6 +523,11 @@ function spawnWorker(linuxUser, workerScriptPath, cwd) {
523
523
  env: workerEnv,
524
524
  cwd: cwd,
525
525
  stdio: ["ignore", "pipe", "pipe"],
526
+ // detached: true gives the worker its own process group (pgid = worker.pid).
527
+ // This lets us send SIGTERM/SIGKILL to the whole group (kill(-pgid)) when
528
+ // the daemon shuts down, reaping grandchild claude CLI processes too.
529
+ // We do NOT call .unref() so the daemon still tracks the worker.
530
+ detached: true,
526
531
  });
527
532
 
528
533
  worker.process.stdout.on("data", function(data) {
@@ -613,10 +618,15 @@ function spawnWorker(linuxUser, workerScriptPath, cwd) {
613
618
  worker.kill = function() {
614
619
  console.log("[yoke/claude] worker.kill() called, pid=" + (worker.process ? worker.process.pid : "?") + " stack=" + new Error().stack.split("\n").slice(1, 4).join(" | "));
615
620
  worker.send({ type: "shutdown" });
616
- // Force kill after 5 seconds if still alive (gives SDK time to save session)
621
+ // Kill the entire process group (worker + any grandchild claude CLI processes).
622
+ // Negative pid targets the process group (pgid = worker.pid when detached: true).
623
+ if (worker.process && worker.process.pid) {
624
+ try { process.kill(-worker.process.pid, "SIGTERM"); } catch (e) {}
625
+ }
626
+ // Force kill the whole group after 5 seconds if still alive (gives SDK time to save session)
617
627
  setTimeout(function() {
618
628
  if (worker.process && !worker.process.killed) {
619
- try { worker.process.kill("SIGKILL"); } catch (e) {}
629
+ try { process.kill(-worker.process.pid, "SIGKILL"); } catch (e) {}
620
630
  }
621
631
  }, 5000);
622
632
  // Don't call cleanupWorker here. Let the exit handler do it after
@@ -934,7 +944,7 @@ function createWorkerQueryHandle(worker, canUseTool, onElicitation, callMcpTool)
934
944
  worker._abortTimeout = setTimeout(function() {
935
945
  if (worker.process && !worker.process.killed) {
936
946
  console.log("[yoke/claude] Abort timeout: force-killing worker pid=" + (worker.process ? worker.process.pid : "?"));
937
- try { worker.process.kill("SIGKILL"); } catch (e) {}
947
+ try { process.kill(-worker.process.pid, "SIGKILL"); } catch (e) {}
938
948
  }
939
949
  }, 5000);
940
950
  },