@radnine/claude-session-daemon 0.5.2 → 0.6.0
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/action-cable-client.js +76 -31
- package/src/connections/standalone-server.js +108 -16
- package/src/daemon.js +61 -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.
|
|
3
|
+
"version": "0.6.0",
|
|
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
|
}
|
|
@@ -4,14 +4,15 @@ const crypto = require('node:crypto');
|
|
|
4
4
|
const os = require('node:os');
|
|
5
5
|
const WebSocket = require('ws');
|
|
6
6
|
const { BaseConnection } = require('./base-connection');
|
|
7
|
+
const { getGitContext } = require('../git-context');
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* ActionCable WebSocket client that connects to a Rails server.
|
|
10
11
|
*
|
|
11
12
|
* Implements the ActionCable protocol:
|
|
12
|
-
* 1. Connect to ws://<host>/cable?
|
|
13
|
+
* 1. Connect to ws://<host>/cable?pilot_id=<id>
|
|
13
14
|
* 2. Wait for {"type":"welcome"}
|
|
14
|
-
* 3. Subscribe to
|
|
15
|
+
* 3. Subscribe to PilotChannel
|
|
15
16
|
* 4. Exchange messages via ActionCable envelope wrapping
|
|
16
17
|
*
|
|
17
18
|
* Reconnects automatically with exponential backoff on connection loss.
|
|
@@ -68,7 +69,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
68
69
|
return this._connected;
|
|
69
70
|
}
|
|
70
71
|
|
|
71
|
-
/** Whether the
|
|
72
|
+
/** Whether the PilotChannel subscription is confirmed. */
|
|
72
73
|
get subscribed() {
|
|
73
74
|
return this._subscribed;
|
|
74
75
|
}
|
|
@@ -121,7 +122,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
121
122
|
}
|
|
122
123
|
|
|
123
124
|
// ---------------------------------------------------------------------------
|
|
124
|
-
// Outbound message methods (Rails
|
|
125
|
+
// Outbound message methods (Rails PilotChannel format)
|
|
125
126
|
// ---------------------------------------------------------------------------
|
|
126
127
|
|
|
127
128
|
/**
|
|
@@ -187,7 +188,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
187
188
|
type: 'error',
|
|
188
189
|
error_code: errorCode,
|
|
189
190
|
message: message,
|
|
190
|
-
context: {
|
|
191
|
+
context: { pilot_id: this._daemonId, session_id: sessionId },
|
|
191
192
|
severity: 'error',
|
|
192
193
|
timestamp: new Date().toISOString(),
|
|
193
194
|
});
|
|
@@ -201,12 +202,12 @@ class ActionCableClient extends BaseConnection {
|
|
|
201
202
|
* Wrap a daemon message in an ActionCable envelope and send it.
|
|
202
203
|
* The `identifier` and `data` fields are double-encoded (JSON string inside JSON).
|
|
203
204
|
*
|
|
204
|
-
* @param {object} messageData - The payload to send on the
|
|
205
|
+
* @param {object} messageData - The payload to send on the PilotChannel
|
|
205
206
|
*/
|
|
206
207
|
sendDaemonMessage(messageData) {
|
|
207
208
|
const identifier = JSON.stringify({
|
|
208
|
-
channel: '
|
|
209
|
-
|
|
209
|
+
channel: 'PilotChannel',
|
|
210
|
+
pilot_id: this._daemonId,
|
|
210
211
|
});
|
|
211
212
|
|
|
212
213
|
const envelope = {
|
|
@@ -224,13 +225,13 @@ class ActionCableClient extends BaseConnection {
|
|
|
224
225
|
|
|
225
226
|
/**
|
|
226
227
|
* Build the WebSocket URL from the Rails server URL.
|
|
227
|
-
* Converts http(s) to ws(s) and appends /cable?
|
|
228
|
+
* Converts http(s) to ws(s) and appends /cable?pilot_id=<id>.
|
|
228
229
|
* @returns {string}
|
|
229
230
|
*/
|
|
230
231
|
_buildWebSocketUrl() {
|
|
231
232
|
const url = new URL(this._railsUrl);
|
|
232
233
|
const protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
233
|
-
return `${protocol}//${url.host}/cable?
|
|
234
|
+
return `${protocol}//${url.host}/cable?pilot_id=${this._daemonId}`;
|
|
234
235
|
}
|
|
235
236
|
|
|
236
237
|
/**
|
|
@@ -245,7 +246,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
245
246
|
const headers = {};
|
|
246
247
|
if (this._authToken) {
|
|
247
248
|
headers['Authorization'] = `Bearer ${this._authToken}`;
|
|
248
|
-
headers['X-
|
|
249
|
+
headers['X-Pilot-Auth'] = this._authToken;
|
|
249
250
|
}
|
|
250
251
|
|
|
251
252
|
this._ws = new WebSocket(wsUrl, { headers });
|
|
@@ -261,11 +262,13 @@ class ActionCableClient extends BaseConnection {
|
|
|
261
262
|
*/
|
|
262
263
|
_onOpen() {
|
|
263
264
|
this._connected = true;
|
|
264
|
-
const wasReconnecting = this._reconnectAttempts > 0;
|
|
265
|
-
this._reconnectAttempts = 0;
|
|
266
265
|
|
|
267
|
-
|
|
268
|
-
|
|
266
|
+
// NOTE: Do NOT reset _reconnectAttempts here. The backoff counter is only
|
|
267
|
+
// reset once the subscription is confirmed (_handleSubscriptionConfirmed).
|
|
268
|
+
// Resetting on open would cause a tight reconnect loop when the WebSocket
|
|
269
|
+
// connects but the subscription is then rejected (e.g. invalid auth token).
|
|
270
|
+
if (this._reconnectAttempts > 0) {
|
|
271
|
+
this._logger.info('WebSocket reconnected, waiting for subscription confirmation');
|
|
269
272
|
} else {
|
|
270
273
|
this._logger.info('WebSocket connection opened, waiting for welcome');
|
|
271
274
|
}
|
|
@@ -358,10 +361,10 @@ class ActionCableClient extends BaseConnection {
|
|
|
358
361
|
// ---------------------------------------------------------------------------
|
|
359
362
|
|
|
360
363
|
/**
|
|
361
|
-
* Welcome received — subscribe to
|
|
364
|
+
* Welcome received — subscribe to PilotChannel.
|
|
362
365
|
*/
|
|
363
366
|
_handleWelcome() {
|
|
364
|
-
this._logger.info('Received welcome, subscribing to
|
|
367
|
+
this._logger.info('Received welcome, subscribing to PilotChannel');
|
|
365
368
|
this._subscribeToDaemonChannel();
|
|
366
369
|
}
|
|
367
370
|
|
|
@@ -370,7 +373,8 @@ class ActionCableClient extends BaseConnection {
|
|
|
370
373
|
*/
|
|
371
374
|
_handleSubscriptionConfirmed(msg) {
|
|
372
375
|
this._subscribed = true;
|
|
373
|
-
this.
|
|
376
|
+
this._reconnectAttempts = 0; // Backoff resets only after full connect+subscribe success
|
|
377
|
+
this._logger.info('PilotChannel subscription confirmed');
|
|
374
378
|
this.emit('subscribed');
|
|
375
379
|
this._sendDaemonRegistration();
|
|
376
380
|
}
|
|
@@ -380,7 +384,9 @@ class ActionCableClient extends BaseConnection {
|
|
|
380
384
|
*/
|
|
381
385
|
_handleSubscriptionRejected(msg) {
|
|
382
386
|
this._subscribed = false;
|
|
383
|
-
|
|
387
|
+
const reason = (msg && msg.reason) || 'unknown';
|
|
388
|
+
this._logger.warn(`PilotChannel subscription rejected (reason: ${reason}, attempt: ${this._reconnectAttempts + 1}). Backoff will increase.`);
|
|
389
|
+
// Do NOT reset _reconnectAttempts here — let backoff escalate to avoid tight loop
|
|
384
390
|
this._scheduleReconnect();
|
|
385
391
|
}
|
|
386
392
|
|
|
@@ -418,6 +424,9 @@ class ActionCableClient extends BaseConnection {
|
|
|
418
424
|
case 'session_recover':
|
|
419
425
|
this._handleSessionRecovery(inner);
|
|
420
426
|
break;
|
|
427
|
+
case 'session_pause':
|
|
428
|
+
this._handleSessionPause(inner);
|
|
429
|
+
break;
|
|
421
430
|
case 'session_deactivate':
|
|
422
431
|
this._handleSessionDeactivation(inner);
|
|
423
432
|
break;
|
|
@@ -437,14 +446,17 @@ class ActionCableClient extends BaseConnection {
|
|
|
437
446
|
/**
|
|
438
447
|
* Send daemon registration message after subscription is confirmed.
|
|
439
448
|
*/
|
|
440
|
-
_sendDaemonRegistration() {
|
|
449
|
+
async _sendDaemonRegistration() {
|
|
441
450
|
this._logger.info('Sending daemon registration');
|
|
451
|
+
|
|
452
|
+
const gitContext = await this._getGitContext();
|
|
453
|
+
|
|
442
454
|
this.sendDaemonMessage({
|
|
443
|
-
type: '
|
|
455
|
+
type: 'pilot_connect',
|
|
444
456
|
version: '1.0',
|
|
445
457
|
auth: {
|
|
446
458
|
token: this._authToken,
|
|
447
|
-
|
|
459
|
+
pilot_id: this._daemonId,
|
|
448
460
|
},
|
|
449
461
|
capabilities: this._capabilities,
|
|
450
462
|
system_info: {
|
|
@@ -453,6 +465,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
453
465
|
arch: process.arch,
|
|
454
466
|
working_directory: this._workingDir,
|
|
455
467
|
},
|
|
468
|
+
git_context: gitContext,
|
|
456
469
|
});
|
|
457
470
|
}
|
|
458
471
|
|
|
@@ -569,6 +582,22 @@ class ActionCableClient extends BaseConnection {
|
|
|
569
582
|
this._sendRecoveryStatus(sessionId, 'completed', 'recovery_finished');
|
|
570
583
|
}
|
|
571
584
|
|
|
585
|
+
/**
|
|
586
|
+
* Handle session_pause — cancel session gracefully, saving claudeSessionId for resume.
|
|
587
|
+
* @param {object} message
|
|
588
|
+
*/
|
|
589
|
+
async _handleSessionPause(message) {
|
|
590
|
+
const sessionId = message.session_id;
|
|
591
|
+
this._logger.info('Pausing session', { sessionId });
|
|
592
|
+
|
|
593
|
+
try {
|
|
594
|
+
await this._daemon.cancelSession(sessionId);
|
|
595
|
+
this._sendSessionStateUpdate(sessionId, { status: 'paused' });
|
|
596
|
+
} catch (err) {
|
|
597
|
+
this._logger.error('Failed to pause session', { sessionId, error: err.message });
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
572
601
|
/**
|
|
573
602
|
* Handle session_deactivate — terminate the session process.
|
|
574
603
|
* @param {object} message
|
|
@@ -634,7 +663,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
634
663
|
type: 'error',
|
|
635
664
|
error_code: errorCode,
|
|
636
665
|
message: errorMessage,
|
|
637
|
-
context: {
|
|
666
|
+
context: { pilot_id: this._daemonId, ...context },
|
|
638
667
|
severity: 'error',
|
|
639
668
|
timestamp: new Date().toISOString(),
|
|
640
669
|
});
|
|
@@ -671,17 +700,33 @@ class ActionCableClient extends BaseConnection {
|
|
|
671
700
|
/**
|
|
672
701
|
* Send a heartbeat message to the server.
|
|
673
702
|
*/
|
|
674
|
-
_sendHeartbeat() {
|
|
703
|
+
async _sendHeartbeat() {
|
|
704
|
+
const gitContext = await this._getGitContext();
|
|
705
|
+
|
|
675
706
|
this.sendDaemonMessage({
|
|
676
707
|
type: 'heartbeat',
|
|
677
|
-
|
|
708
|
+
pilot_id: this._daemonId,
|
|
678
709
|
status: 'healthy',
|
|
679
710
|
session_summary: this._getSessionSummary(),
|
|
680
711
|
resource_usage: this._getResourceUsage(),
|
|
712
|
+
git_context: gitContext,
|
|
681
713
|
timestamp: new Date().toISOString(),
|
|
682
714
|
});
|
|
683
715
|
}
|
|
684
716
|
|
|
717
|
+
/**
|
|
718
|
+
* Get git context (branch, PR, remote) for the working directory.
|
|
719
|
+
* Returns cached results (30s TTL via git-context module).
|
|
720
|
+
*/
|
|
721
|
+
async _getGitContext() {
|
|
722
|
+
try {
|
|
723
|
+
return await getGitContext(this._workingDir);
|
|
724
|
+
} catch (err) {
|
|
725
|
+
this._logger.warn('Failed to get git context', { error: err.message });
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
685
730
|
/**
|
|
686
731
|
* Get a summary of daemon sessions from the daemon health check.
|
|
687
732
|
* @returns {object}
|
|
@@ -728,12 +773,12 @@ class ActionCableClient extends BaseConnection {
|
|
|
728
773
|
// ---------------------------------------------------------------------------
|
|
729
774
|
|
|
730
775
|
/**
|
|
731
|
-
* Send a subscribe command for
|
|
776
|
+
* Send a subscribe command for PilotChannel.
|
|
732
777
|
*/
|
|
733
778
|
_subscribeToDaemonChannel() {
|
|
734
779
|
const identifier = JSON.stringify({
|
|
735
|
-
channel: '
|
|
736
|
-
|
|
780
|
+
channel: 'PilotChannel',
|
|
781
|
+
pilot_id: this._daemonId,
|
|
737
782
|
});
|
|
738
783
|
|
|
739
784
|
this._send({
|
|
@@ -743,12 +788,12 @@ class ActionCableClient extends BaseConnection {
|
|
|
743
788
|
}
|
|
744
789
|
|
|
745
790
|
/**
|
|
746
|
-
* Send an unsubscribe command for
|
|
791
|
+
* Send an unsubscribe command for PilotChannel.
|
|
747
792
|
*/
|
|
748
793
|
_unsubscribe() {
|
|
749
794
|
const identifier = JSON.stringify({
|
|
750
|
-
channel: '
|
|
751
|
-
|
|
795
|
+
channel: 'PilotChannel',
|
|
796
|
+
pilot_id: this._daemonId,
|
|
752
797
|
});
|
|
753
798
|
|
|
754
799
|
this._send({
|
|
@@ -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
|
/**
|
|
@@ -324,6 +374,16 @@ class Daemon extends EventEmitter {
|
|
|
324
374
|
*/
|
|
325
375
|
_forwardEvents(sessionId, proc) {
|
|
326
376
|
proc.on('output', (data) => {
|
|
377
|
+
// Suppress informational rate_limit_event messages (status: "allowed")
|
|
378
|
+
// These are not actual rate limits — only forward when truly rate-limited
|
|
379
|
+
if (data?.type === 'rate_limit_event') {
|
|
380
|
+
const status = data?.rate_limit_info?.status;
|
|
381
|
+
if (status === 'allowed') {
|
|
382
|
+
this._logger.debug('Suppressing informational rate_limit_event', { sessionId, status });
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
327
387
|
this.emit('session:output', { sessionId, data });
|
|
328
388
|
});
|
|
329
389
|
|
|
@@ -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 };
|