@radnine/claude-session-daemon 0.5.2 → 0.5.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/README.md +121 -0
- package/package.json +2 -1
- package/src/claude-process.js +11 -2
- package/src/connections/standalone-server.js +108 -16
- package/src/daemon.js +51 -1
- package/src/skills-config.js +103 -0
package/README.md
CHANGED
|
@@ -102,17 +102,138 @@ npx @anthropic-ai/claude-code login
|
|
|
102
102
|
|
|
103
103
|
This authenticates via your browser. Credentials are stored locally and the daemon uses them automatically.
|
|
104
104
|
|
|
105
|
+
### WebSocket Authentication (Shared Secret)
|
|
106
|
+
|
|
107
|
+
By default, the daemon allows unauthenticated connections from localhost and auto-generates a random token for non-localhost connections (logged on startup). This works for local development but not for remote environments like GitHub Codespaces where port forwarding proxies prevent the localhost bypass.
|
|
108
|
+
|
|
109
|
+
To configure a shared secret that both the daemon and addon use:
|
|
110
|
+
|
|
111
|
+
1. Set `CLAUDE_AUTH_TOKEN` for the daemon and `STORYBOOK_CLAUDE_DAEMON_TOKEN` for Storybook:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
# Generate a secret (or use any string)
|
|
115
|
+
export CLAUDE_SHARED_SECRET=$(openssl rand -hex 32)
|
|
116
|
+
|
|
117
|
+
# Daemon reads this
|
|
118
|
+
export CLAUDE_AUTH_TOKEN=$CLAUDE_SHARED_SECRET
|
|
119
|
+
|
|
120
|
+
# Storybook addon reads this
|
|
121
|
+
export STORYBOOK_CLAUDE_DAEMON_TOKEN=$CLAUDE_SHARED_SECRET
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
2. Inject the token into Storybook's manager frame via `managerHead` in your `.storybook/main.js`:
|
|
125
|
+
|
|
126
|
+
```js
|
|
127
|
+
export default {
|
|
128
|
+
addons: ['@radnine/storybook-addon-claude'],
|
|
129
|
+
|
|
130
|
+
managerHead: (head) => {
|
|
131
|
+
const port = process.env.STORYBOOK_CLAUDE_DAEMON_PORT || 3001;
|
|
132
|
+
const token = process.env.STORYBOOK_CLAUDE_DAEMON_TOKEN || '';
|
|
133
|
+
return `${head}<script>window.__CLAUDE_DAEMON_PORT__ = ${port};${
|
|
134
|
+
token ? `window.__CLAUDE_DAEMON_TOKEN__ = "${token}";` : ''
|
|
135
|
+
}</script>`;
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The addon reads the token from `window.__CLAUDE_DAEMON_TOKEN__` (most reliable in the Storybook manager frame) and falls back to `process.env.STORYBOOK_CLAUDE_DAEMON_TOKEN`.
|
|
141
|
+
|
|
142
|
+
### GitHub Codespaces
|
|
143
|
+
|
|
144
|
+
In Codespaces, each forwarded port gets its own subdomain (e.g. `codespace-name-3001.app.github.dev`). The addon auto-detects this URL pattern and connects via `wss://` instead of `ws://localhost`.
|
|
145
|
+
|
|
146
|
+
Setup:
|
|
147
|
+
|
|
148
|
+
1. Add the shared secret env vars to your `devcontainer.json`:
|
|
149
|
+
|
|
150
|
+
```jsonc
|
|
151
|
+
{
|
|
152
|
+
"containerEnv": {
|
|
153
|
+
"CLAUDE_SHARED_SECRET": "${localEnv:CLAUDE_SHARED_SECRET}"
|
|
154
|
+
},
|
|
155
|
+
"postStartCommand": "export CLAUDE_AUTH_TOKEN=$CLAUDE_SHARED_SECRET && export STORYBOOK_CLAUDE_DAEMON_TOKEN=$CLAUDE_SHARED_SECRET"
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Or generate a fresh secret on every Codespace start:
|
|
160
|
+
|
|
161
|
+
```jsonc
|
|
162
|
+
{
|
|
163
|
+
"postStartCommand": "export CLAUDE_SHARED_SECRET=$(openssl rand -hex 32) && export CLAUDE_AUTH_TOKEN=$CLAUDE_SHARED_SECRET && export STORYBOOK_CLAUDE_DAEMON_TOKEN=$CLAUDE_SHARED_SECRET"
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
2. Set the daemon port to **public** visibility in the Codespaces Ports tab. The shared secret provides the auth layer — you don't need GitHub's proxy auth.
|
|
168
|
+
|
|
169
|
+
3. Add the `managerHead` injection to your `.storybook/main.js` (see above).
|
|
170
|
+
|
|
171
|
+
4. Start the daemon and Storybook as usual. The addon will automatically detect the Codespaces hostname and connect to `wss://codespace-name-PORT.app.github.dev`.
|
|
172
|
+
|
|
173
|
+
## Custom Skills
|
|
174
|
+
|
|
175
|
+
The addon's skills bar shows configurable shortcut buttons. Define them in a YAML file at `.storybook/claude-skills.yml` in your project:
|
|
176
|
+
|
|
177
|
+
```yaml
|
|
178
|
+
skills:
|
|
179
|
+
- id: sync-components
|
|
180
|
+
label: Sync Components
|
|
181
|
+
icon: "↻"
|
|
182
|
+
type: prompt
|
|
183
|
+
prompt: "Synchronize all Storybook components with their Figma designs. Report what changed."
|
|
184
|
+
description: "Sync components with designs"
|
|
185
|
+
|
|
186
|
+
- id: run-tests
|
|
187
|
+
label: Run Tests
|
|
188
|
+
icon: "▶"
|
|
189
|
+
type: slash_command
|
|
190
|
+
command: /test
|
|
191
|
+
description: "Run the full test suite"
|
|
192
|
+
|
|
193
|
+
- id: audit-stories
|
|
194
|
+
label: Audit
|
|
195
|
+
icon: "🔍"
|
|
196
|
+
type: prompt
|
|
197
|
+
prompt: "Audit all components and list any that are missing Storybook stories or have outdated ones."
|
|
198
|
+
description: "Find missing or outdated stories"
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Each skill requires `id`, `label`, `icon`, and either `prompt` or `command`:
|
|
202
|
+
|
|
203
|
+
- **`type: prompt`** (default) — sends the `prompt` text as a chat message
|
|
204
|
+
- **`type: slash_command`** — sends the `command` value (e.g. `/test`) as a chat message
|
|
205
|
+
- **`description`** — shown as a tooltip on hover; falls back to `prompt` if omitted
|
|
206
|
+
|
|
207
|
+
If no YAML file is found, the addon falls back to built-in default skills. The dynamic PR skill (New PR / Finalize PR) is always included regardless of config — it's driven by git context, not YAML.
|
|
208
|
+
|
|
209
|
+
The daemon looks for the YAML file relative to its working directory. By default this is `process.cwd()`. If you run the daemon from a different directory than your Storybook project (e.g. via a Procfile from the repo root), set `CLAUDE_WORKING_DIR` to point to the directory containing `.storybook/`:
|
|
210
|
+
|
|
211
|
+
```bash
|
|
212
|
+
CLAUDE_WORKING_DIR=path/to/storybook-project claude-session-daemon start
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
In Docker mode, `CLAUDE_WORKING_DIR` should point to your mounted workspace (e.g. `/workspace`).
|
|
216
|
+
|
|
105
217
|
## Environment Variables
|
|
106
218
|
|
|
107
219
|
| Variable | Default | Description |
|
|
108
220
|
|---|---|---|
|
|
109
221
|
| `ANTHROPIC_API_KEY` | — | Required for Docker mode |
|
|
222
|
+
| `CLAUDE_WORKING_DIR` | `process.cwd()` | Project root for skills config and git context |
|
|
110
223
|
| `CLAUDE_DAEMON_PORT` | `3001` | WebSocket server port |
|
|
224
|
+
| `CLAUDE_AUTH_TOKEN` | random UUID | Shared secret for WebSocket auth (see above) |
|
|
111
225
|
| `CLAUDE_MAX_SESSIONS` | `10` | Max concurrent Claude sessions |
|
|
112
226
|
| `CLAUDE_LOG_LEVEL` | `info` | Log level (`debug`, `info`, `warn`, `error`) |
|
|
113
227
|
| `CLAUDE_SKIP_PERMISSIONS` | `false` | Skip Claude CLI permission prompts (Docker only) |
|
|
114
228
|
| `CLAUDE_DISABLE_AUTH` | `false` | Disable WebSocket auth (Docker only) |
|
|
115
229
|
|
|
230
|
+
**Addon-side variables** (set when starting Storybook):
|
|
231
|
+
|
|
232
|
+
| Variable | Default | Description |
|
|
233
|
+
|---|---|---|
|
|
234
|
+
| `STORYBOOK_CLAUDE_DAEMON_PORT` | `3001` | Daemon port (or inject via `window.__CLAUDE_DAEMON_PORT__`) |
|
|
235
|
+
| `STORYBOOK_CLAUDE_DAEMON_TOKEN` | — | Shared secret (or inject via `window.__CLAUDE_DAEMON_TOKEN__`) |
|
|
236
|
+
|
|
116
237
|
## License
|
|
117
238
|
|
|
118
239
|
Proprietary. See [LICENSE](./LICENSE) for terms.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@radnine/claude-session-daemon",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.3",
|
|
4
4
|
"description": "Node.js daemon for managing Claude CLI sessions",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"repository": {
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
"node": ">=18.0.0"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
+
"js-yaml": "^4.1.0",
|
|
33
34
|
"ws": "^8.16.0"
|
|
34
35
|
},
|
|
35
36
|
"devDependencies": {}
|
package/src/claude-process.js
CHANGED
|
@@ -33,6 +33,7 @@ class ClaudeProcess extends EventEmitter {
|
|
|
33
33
|
|
|
34
34
|
this._sessionId = sessionId;
|
|
35
35
|
this._claudeSessionId = options.claudeSessionId || randomUUID();
|
|
36
|
+
this._resume = options.resume || false; // Resume an existing CLI session instead of starting new
|
|
36
37
|
this._workingDir = options.workingDir || process.cwd();
|
|
37
38
|
this._logger = options.logger || _defaultLogger();
|
|
38
39
|
this._claudeCommand = options.claudeCommand || 'claude';
|
|
@@ -64,10 +65,18 @@ class ClaudeProcess extends EventEmitter {
|
|
|
64
65
|
'--verbose',
|
|
65
66
|
'--input-format', 'stream-json',
|
|
66
67
|
'--output-format', 'stream-json',
|
|
67
|
-
'--session-id', this._claudeSessionId,
|
|
68
|
-
'--replay-user-messages',
|
|
69
68
|
];
|
|
70
69
|
|
|
70
|
+
if (this._resume) {
|
|
71
|
+
// Resume an existing CLI session (e.g. after cancel) — preserves conversation context
|
|
72
|
+
args.push('--resume', this._claudeSessionId);
|
|
73
|
+
} else {
|
|
74
|
+
// Start a fresh session
|
|
75
|
+
args.push('--session-id', this._claudeSessionId);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
args.push('--replay-user-messages');
|
|
79
|
+
|
|
71
80
|
if (this._skipPermissions) {
|
|
72
81
|
args.push('--dangerously-skip-permissions');
|
|
73
82
|
}
|
|
@@ -6,6 +6,7 @@ const { WebSocketServer, WebSocket } = require('ws');
|
|
|
6
6
|
const { BaseConnection } = require('./base-connection');
|
|
7
7
|
const { SessionStore } = require('../session-store');
|
|
8
8
|
const { getGitContext } = require('../git-context');
|
|
9
|
+
const { getSkillsConfig } = require('../skills-config');
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* Standalone WebSocket server that accepts direct client connections.
|
|
@@ -16,11 +17,13 @@ const { getGitContext } = require('../git-context');
|
|
|
16
17
|
* { type: 'activate', sessionId, workingDir }
|
|
17
18
|
* { type: 'command', sessionId, commandId, text }
|
|
18
19
|
* { type: 'clear_session', sessionId }
|
|
20
|
+
* { type: 'cancel', sessionId, commandId }
|
|
19
21
|
* { type: 'ping' }
|
|
20
22
|
*
|
|
21
23
|
* Message protocol (server -> client):
|
|
22
24
|
* { type: 'session_activated', sessionId }
|
|
23
25
|
* { type: 'session_cleared', sessionId, timestamp }
|
|
26
|
+
* { type: 'cancelled', sessionId, commandId, timestamp }
|
|
24
27
|
* { type: 'output', sessionId, commandId, data, timestamp }
|
|
25
28
|
* { type: 'complete', sessionId, commandId, exitCode, durationMs, timestamp }
|
|
26
29
|
* { type: 'error', sessionId, code, message, timestamp }
|
|
@@ -36,10 +39,12 @@ class StandaloneServer extends BaseConnection {
|
|
|
36
39
|
super(daemon, logger);
|
|
37
40
|
this._port = config.port != null ? config.port : 3001;
|
|
38
41
|
this._token = config.authToken || crypto.randomUUID();
|
|
42
|
+
this._config = config;
|
|
39
43
|
this._wss = null;
|
|
40
44
|
this._sessions = new Map(); // sessionId -> Set<WebSocket>
|
|
41
45
|
this._clients = new Map(); // WebSocket -> { authenticated: boolean }
|
|
42
46
|
this._sessionStore = options.sessionStore || new SessionStore();
|
|
47
|
+
this._cancelledSessions = new Set(); // sessionIds with pending cancel (suppress exit→complete)
|
|
43
48
|
}
|
|
44
49
|
|
|
45
50
|
/** Actual port the server is listening on (useful when started with port 0). */
|
|
@@ -109,25 +114,32 @@ class StandaloneServer extends BaseConnection {
|
|
|
109
114
|
// Send methods (called by BaseConnection event wiring and directly)
|
|
110
115
|
// ---------------------------------------------------------------------------
|
|
111
116
|
|
|
112
|
-
|
|
117
|
+
sendComplete(sessionId, commandId, exitCode, durationMs) {
|
|
118
|
+
// Suppress the exit→complete event for sessions that were cancelled.
|
|
119
|
+
// The cancelled message is sent separately by _handleCancel.
|
|
120
|
+
if (this._cancelledSessions.has(sessionId)) {
|
|
121
|
+
this._cancelledSessions.delete(sessionId);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
113
125
|
const msg = {
|
|
114
|
-
type: '
|
|
126
|
+
type: 'complete',
|
|
115
127
|
sessionId,
|
|
116
128
|
commandId,
|
|
117
|
-
|
|
129
|
+
exitCode,
|
|
130
|
+
durationMs,
|
|
118
131
|
timestamp: Date.now(),
|
|
119
132
|
};
|
|
120
133
|
this._broadcast(sessionId, msg);
|
|
121
134
|
this._sessionStore.append(sessionId, msg);
|
|
122
135
|
}
|
|
123
136
|
|
|
124
|
-
|
|
137
|
+
sendOutput(sessionId, commandId, data) {
|
|
125
138
|
const msg = {
|
|
126
|
-
type: '
|
|
139
|
+
type: 'output',
|
|
127
140
|
sessionId,
|
|
128
141
|
commandId,
|
|
129
|
-
|
|
130
|
-
durationMs,
|
|
142
|
+
data,
|
|
131
143
|
timestamp: Date.now(),
|
|
132
144
|
};
|
|
133
145
|
this._broadcast(sessionId, msg);
|
|
@@ -153,9 +165,10 @@ class StandaloneServer extends BaseConnection {
|
|
|
153
165
|
_handleConnection(ws, req) {
|
|
154
166
|
const isLocalhost = this._isLocalhostConnection(req);
|
|
155
167
|
const authDisabled = process.env.CLAUDE_DISABLE_AUTH === 'true';
|
|
168
|
+
const requireAuth = this._config.requireAuth === true;
|
|
156
169
|
|
|
157
170
|
// Validate auth token from query param (skip for localhost or when auth disabled in Docker)
|
|
158
|
-
if (!isLocalhost && !authDisabled) {
|
|
171
|
+
if ((requireAuth || !isLocalhost) && !authDisabled) {
|
|
159
172
|
let token = null;
|
|
160
173
|
try {
|
|
161
174
|
const url = new URL(req.url, `http://localhost:${this.port}`);
|
|
@@ -236,6 +249,10 @@ class StandaloneServer extends BaseConnection {
|
|
|
236
249
|
this._handleClearSession(ws, msg);
|
|
237
250
|
break;
|
|
238
251
|
|
|
252
|
+
case 'cancel':
|
|
253
|
+
this._handleCancel(ws, msg);
|
|
254
|
+
break;
|
|
255
|
+
|
|
239
256
|
case 'query':
|
|
240
257
|
this._handleQuery(ws, msg);
|
|
241
258
|
break;
|
|
@@ -297,7 +314,7 @@ class StandaloneServer extends BaseConnection {
|
|
|
297
314
|
}
|
|
298
315
|
}
|
|
299
316
|
|
|
300
|
-
_handleCommand(ws, msg) {
|
|
317
|
+
async _handleCommand(ws, msg) {
|
|
301
318
|
const { sessionId, commandId, text } = msg;
|
|
302
319
|
|
|
303
320
|
if (!sessionId || !text) {
|
|
@@ -328,12 +345,19 @@ class StandaloneServer extends BaseConnection {
|
|
|
328
345
|
try {
|
|
329
346
|
this._daemon.sendMessage(sessionId, text);
|
|
330
347
|
} catch (err) {
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
})
|
|
348
|
+
// Session process may be dead (e.g. after cancel). Try to re-activate
|
|
349
|
+
// and retry once before giving up.
|
|
350
|
+
try {
|
|
351
|
+
await this._daemon.activateSession(sessionId);
|
|
352
|
+
this._daemon.sendMessage(sessionId, text);
|
|
353
|
+
} catch (retryErr) {
|
|
354
|
+
this._sendToClient(ws, {
|
|
355
|
+
type: 'error',
|
|
356
|
+
code: 'COMMAND_FAILED',
|
|
357
|
+
message: retryErr.message,
|
|
358
|
+
timestamp: Date.now(),
|
|
359
|
+
});
|
|
360
|
+
}
|
|
337
361
|
}
|
|
338
362
|
}
|
|
339
363
|
|
|
@@ -370,6 +394,55 @@ class StandaloneServer extends BaseConnection {
|
|
|
370
394
|
}
|
|
371
395
|
}
|
|
372
396
|
|
|
397
|
+
async _handleCancel(ws, msg) {
|
|
398
|
+
const { sessionId, commandId } = msg;
|
|
399
|
+
|
|
400
|
+
if (!sessionId) {
|
|
401
|
+
this._sendToClient(ws, {
|
|
402
|
+
type: 'error',
|
|
403
|
+
code: 'INVALID_MESSAGE',
|
|
404
|
+
message: 'cancel requires sessionId',
|
|
405
|
+
timestamp: Date.now(),
|
|
406
|
+
});
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
try {
|
|
411
|
+
// Mark session as cancelled before killing, so the session:exit event
|
|
412
|
+
// doesn't produce a spurious 'complete' message.
|
|
413
|
+
this._cancelledSessions.add(sessionId);
|
|
414
|
+
const result = await this._daemon.cancelSession(sessionId);
|
|
415
|
+
|
|
416
|
+
if (result.success) {
|
|
417
|
+
const cancelledMsg = {
|
|
418
|
+
type: 'cancelled',
|
|
419
|
+
sessionId,
|
|
420
|
+
commandId,
|
|
421
|
+
timestamp: Date.now(),
|
|
422
|
+
};
|
|
423
|
+
this._broadcast(sessionId, cancelledMsg);
|
|
424
|
+
this._sessionStore.append(sessionId, cancelledMsg);
|
|
425
|
+
this._logger.info('Session cancelled', { sessionId, commandId });
|
|
426
|
+
} else {
|
|
427
|
+
this._cancelledSessions.delete(sessionId);
|
|
428
|
+
this._sendToClient(ws, {
|
|
429
|
+
type: 'error',
|
|
430
|
+
code: 'CANCEL_FAILED',
|
|
431
|
+
message: result.message,
|
|
432
|
+
timestamp: Date.now(),
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
} catch (err) {
|
|
436
|
+
this._cancelledSessions.delete(sessionId);
|
|
437
|
+
this._sendToClient(ws, {
|
|
438
|
+
type: 'error',
|
|
439
|
+
code: 'CANCEL_FAILED',
|
|
440
|
+
message: err.message,
|
|
441
|
+
timestamp: Date.now(),
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
373
446
|
async _handleQuery(ws, msg) {
|
|
374
447
|
const { queryType } = msg;
|
|
375
448
|
|
|
@@ -386,7 +459,7 @@ class StandaloneServer extends BaseConnection {
|
|
|
386
459
|
switch (queryType) {
|
|
387
460
|
case 'git_context': {
|
|
388
461
|
try {
|
|
389
|
-
const data = await getGitContext();
|
|
462
|
+
const data = await getGitContext(this._config.workingDir);
|
|
390
463
|
this._sendToClient(ws, {
|
|
391
464
|
type: 'query_result',
|
|
392
465
|
queryType: 'git_context',
|
|
@@ -403,6 +476,25 @@ class StandaloneServer extends BaseConnection {
|
|
|
403
476
|
}
|
|
404
477
|
break;
|
|
405
478
|
}
|
|
479
|
+
case 'skills_config': {
|
|
480
|
+
try {
|
|
481
|
+
const data = await getSkillsConfig(this._config.workingDir);
|
|
482
|
+
this._sendToClient(ws, {
|
|
483
|
+
type: 'query_result',
|
|
484
|
+
queryType: 'skills_config',
|
|
485
|
+
data,
|
|
486
|
+
timestamp: Date.now(),
|
|
487
|
+
});
|
|
488
|
+
} catch (err) {
|
|
489
|
+
this._sendToClient(ws, {
|
|
490
|
+
type: 'error',
|
|
491
|
+
code: 'QUERY_FAILED',
|
|
492
|
+
message: err.message,
|
|
493
|
+
timestamp: Date.now(),
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
break;
|
|
497
|
+
}
|
|
406
498
|
default:
|
|
407
499
|
this._sendToClient(ws, {
|
|
408
500
|
type: 'error',
|
package/src/daemon.js
CHANGED
|
@@ -28,6 +28,7 @@ class Daemon extends EventEmitter {
|
|
|
28
28
|
super();
|
|
29
29
|
|
|
30
30
|
this._processes = new Map(); // sessionId -> ClaudeProcess
|
|
31
|
+
this._cancelledSessionIds = new Map(); // sessionId -> claudeSessionId (for resume after cancel)
|
|
31
32
|
this._config = config;
|
|
32
33
|
this._logger = logger;
|
|
33
34
|
this._running = false;
|
|
@@ -143,10 +144,18 @@ class Daemon extends EventEmitter {
|
|
|
143
144
|
);
|
|
144
145
|
}
|
|
145
146
|
|
|
147
|
+
// Reuse the Claude CLI session ID from a cancelled session to preserve
|
|
148
|
+
// conversation context, or use the one provided in options, or generate new.
|
|
149
|
+
const savedClaudeSessionId = this._cancelledSessionIds.get(sessionId);
|
|
150
|
+
const claudeSessionId = options.claudeSessionId || savedClaudeSessionId || undefined;
|
|
151
|
+
const shouldResume = !!savedClaudeSessionId && !options.claudeSessionId;
|
|
152
|
+
this._cancelledSessionIds.delete(sessionId);
|
|
153
|
+
|
|
146
154
|
// Create new process
|
|
147
155
|
const proc = this._createProcess(sessionId, {
|
|
148
156
|
workingDir: options.workingDir || this._config.workingDir,
|
|
149
|
-
claudeSessionId
|
|
157
|
+
claudeSessionId,
|
|
158
|
+
resume: shouldResume,
|
|
150
159
|
skipPermissions: this._config.skipPermissions,
|
|
151
160
|
logger: this._logger.child(`Session:${sessionId}`),
|
|
152
161
|
});
|
|
@@ -210,6 +219,47 @@ class Daemon extends EventEmitter {
|
|
|
210
219
|
this._logger.info('Terminating session', { sessionId });
|
|
211
220
|
await proc.kill();
|
|
212
221
|
this._processes.delete(sessionId);
|
|
222
|
+
this._cancelledSessionIds.delete(sessionId);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Cancel a session's running process (kill it but preserve session state).
|
|
227
|
+
*
|
|
228
|
+
* Unlike terminateSession(), this does NOT delete the session from the pool,
|
|
229
|
+
* allowing activateSession() to respawn it later if needed.
|
|
230
|
+
*
|
|
231
|
+
* @param {string} sessionId
|
|
232
|
+
* @returns {Promise<{success: boolean, message: string}>}
|
|
233
|
+
*/
|
|
234
|
+
async cancelSession(sessionId) {
|
|
235
|
+
const proc = this._processes.get(sessionId);
|
|
236
|
+
|
|
237
|
+
if (!proc) {
|
|
238
|
+
this._logger.warn('Cancel requested for unknown session', { sessionId });
|
|
239
|
+
return {
|
|
240
|
+
success: false,
|
|
241
|
+
message: `Session not found: "${sessionId}"`,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (!proc.isAlive()) {
|
|
246
|
+
this._logger.warn('Cancel requested for dead process', { sessionId, pid: proc.pid });
|
|
247
|
+
return {
|
|
248
|
+
success: false,
|
|
249
|
+
message: `Session process already stopped: "${sessionId}"`,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
this._logger.info('Cancelling session', { sessionId, pid: proc.pid });
|
|
254
|
+
// Preserve the Claude CLI session ID so we can resume the conversation
|
|
255
|
+
this._cancelledSessionIds.set(sessionId, proc.claudeSessionId);
|
|
256
|
+
await proc.kill();
|
|
257
|
+
this._processes.delete(sessionId);
|
|
258
|
+
|
|
259
|
+
return {
|
|
260
|
+
success: true,
|
|
261
|
+
message: `Session cancelled: "${sessionId}"`,
|
|
262
|
+
};
|
|
213
263
|
}
|
|
214
264
|
|
|
215
265
|
/**
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const yaml = require('js-yaml');
|
|
6
|
+
|
|
7
|
+
const CACHE_TTL_MS = 30000; // 30 seconds
|
|
8
|
+
|
|
9
|
+
let _cache = null;
|
|
10
|
+
let _cacheTimestamp = 0;
|
|
11
|
+
let _cacheDir = null;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Read skills configuration from `.storybook/claude-skills.yml` in the given
|
|
15
|
+
* working directory.
|
|
16
|
+
*
|
|
17
|
+
* Results are cached for 30 seconds.
|
|
18
|
+
*
|
|
19
|
+
* @param {string} [workingDir] - Project root (defaults to process.cwd())
|
|
20
|
+
* @returns {Promise<{skills: Array, source: string}>}
|
|
21
|
+
*/
|
|
22
|
+
async function getSkillsConfig(workingDir) {
|
|
23
|
+
const cwd = workingDir || process.cwd();
|
|
24
|
+
|
|
25
|
+
const now = Date.now();
|
|
26
|
+
if (_cache && _cacheDir === cwd && now - _cacheTimestamp < CACHE_TTL_MS) {
|
|
27
|
+
return _cache;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const filePath = path.join(cwd, '.storybook', 'claude-skills.yml');
|
|
31
|
+
|
|
32
|
+
let result;
|
|
33
|
+
try {
|
|
34
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
35
|
+
const parsed = yaml.load(raw);
|
|
36
|
+
|
|
37
|
+
if (!parsed || !Array.isArray(parsed.skills)) {
|
|
38
|
+
result = { skills: [], source: 'none' };
|
|
39
|
+
} else {
|
|
40
|
+
const skills = parsed.skills
|
|
41
|
+
.filter(validateSkill)
|
|
42
|
+
.map(normalizeSkill);
|
|
43
|
+
result = { skills, source: 'yaml' };
|
|
44
|
+
}
|
|
45
|
+
} catch (err) {
|
|
46
|
+
if (err.code === 'ENOENT') {
|
|
47
|
+
result = { skills: [], source: 'none' };
|
|
48
|
+
} else {
|
|
49
|
+
// YAML parse error or permission issue — surface it but don't crash
|
|
50
|
+
result = { skills: [], source: 'error', error: err.message };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
_cache = result;
|
|
55
|
+
_cacheDir = cwd;
|
|
56
|
+
_cacheTimestamp = now;
|
|
57
|
+
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Validate that a skill entry has the required fields.
|
|
63
|
+
*/
|
|
64
|
+
function validateSkill(entry) {
|
|
65
|
+
if (!entry || typeof entry !== 'object') return false;
|
|
66
|
+
if (!entry.id || !entry.label || !entry.icon) return false;
|
|
67
|
+
if (entry.type === 'slash_command') {
|
|
68
|
+
return !!entry.command;
|
|
69
|
+
}
|
|
70
|
+
return !!entry.prompt;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Normalize a skill entry — for slash_command type, map `command` to `prompt`.
|
|
75
|
+
*/
|
|
76
|
+
function normalizeSkill(entry) {
|
|
77
|
+
const skill = {
|
|
78
|
+
id: entry.id,
|
|
79
|
+
label: entry.label,
|
|
80
|
+
icon: entry.icon,
|
|
81
|
+
description: entry.description || null,
|
|
82
|
+
type: entry.type || 'prompt',
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
if (skill.type === 'slash_command') {
|
|
86
|
+
skill.prompt = entry.command;
|
|
87
|
+
} else {
|
|
88
|
+
skill.prompt = entry.prompt;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return skill;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Clear the cache (useful for testing).
|
|
96
|
+
*/
|
|
97
|
+
function clearCache() {
|
|
98
|
+
_cache = null;
|
|
99
|
+
_cacheTimestamp = 0;
|
|
100
|
+
_cacheDir = null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
module.exports = { getSkillsConfig, clearCache };
|