@radnine/claude-session-daemon 0.8.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Dockerfile CHANGED
@@ -19,10 +19,13 @@ COPY src/ ./src/
19
19
  COPY docker-entrypoint.sh /usr/local/bin/
20
20
  RUN chmod +x /usr/local/bin/docker-entrypoint.sh
21
21
 
22
- # Default environment for standalone Docker usage
22
+ # Default environment for standalone Docker usage.
23
+ # Standalone mode never attaches a permission broker, so an escalated prompt has
24
+ # nowhere to go and would be denied on the spot. The container is the boundary.
23
25
  ENV CLAUDE_DAEMON_MODE=standalone \
24
26
  CLAUDE_WORKING_DIR=/workspace \
25
- CLAUDE_DAEMON_PORT=3001
27
+ CLAUDE_DAEMON_PORT=3001 \
28
+ CLAUDE_PERMISSION_MODE=bypassPermissions
26
29
 
27
30
  EXPOSE 3001
28
31
 
package/README.md CHANGED
@@ -43,7 +43,7 @@ services:
43
43
  - CLAUDE_DAEMON_MODE=standalone
44
44
  - CLAUDE_WORKING_DIR=/workspace
45
45
  - CLAUDE_DAEMON_PORT=3001
46
- - CLAUDE_SKIP_PERMISSIONS=true
46
+ - CLAUDE_PERMISSION_MODE=bypassPermissions
47
47
  - CLAUDE_DISABLE_AUTH=true
48
48
  stop_grace_period: 10s
49
49
  restart: unless-stopped
@@ -219,14 +219,27 @@ In Docker mode, `CLAUDE_WORKING_DIR` should point to your mounted workspace (e.g
219
219
  | Variable | Default | Description |
220
220
  |---|---|---|
221
221
  | `ANTHROPIC_API_KEY` | — | Required for Docker mode |
222
+ | `CLAUDE_DAEMON_MODE` | `standalone` | `standalone` runs its own WebSocket server. `actioncable` connects to a FlightDeck (Rails) server |
222
223
  | `CLAUDE_WORKING_DIR` | `process.cwd()` | Project root for skills config and git context |
223
224
  | `CLAUDE_DAEMON_PORT` | `3001` | WebSocket server port |
224
- | `CLAUDE_AUTH_TOKEN` | random UUID | Shared secret for WebSocket auth (see above) |
225
- | `CLAUDE_MAX_SESSIONS` | `10` | Max concurrent Claude sessions |
225
+ | `CLAUDE_AUTH_TOKEN` | random UUID | Shared secret for WebSocket auth (see above). Required in `actioncable` mode, where it is the pilot's token and the daemon exits without it. Never passed to chats (#482) |
226
+ | `CLAUDE_RAILS_URL` | `http://localhost:3000` | FlightDeck server URL. Set it for `actioncable` mode, because FlightDeck runs on `:3600`. `pilot-manager` sets it from `server_url` in its config, which `--server URL` saves |
227
+ | `CLAUDE_DAEMON_ID` | random UUID, new each start | Pilot ID sent to FlightDeck in `actioncable` mode. Must match the registered pilot. `pilot-manager` sets it |
228
+ | `CLAUDE_MAX_SESSIONS` | `15` | Max concurrent Claude sessions |
226
229
  | `CLAUDE_LOG_LEVEL` | `info` | Log level (`debug`, `info`, `warn`, `error`) |
227
- | `CLAUDE_SKIP_PERMISSIONS` | `false` | Skip Claude CLI permission prompts (Docker only) |
230
+ | `CLAUDE_HEARTBEAT_INTERVAL` | `30` | Seconds between the daemon's health checks. In `actioncable` mode FlightDeck sets the heartbeat interval when the pilot registers (currently 30s) |
231
+ | `CLAUDE_CLEANUP_INTERVAL` | `300` | Seconds between sweeps that remove dead sessions and kill stale ones |
232
+ | `CLAUDE_STALE_SESSION_TIMEOUT` | `1800` | Seconds a running session can go without activity before the cleanup sweep kills it. `0` disables |
233
+ | `CLAUDE_STARTUP_TIMEOUT` | `5` | Parsed at startup, but no daemon code uses it yet |
234
+ | `CLAUDE_COMMAND` | `claude` | Claude CLI binary to spawn. Also used for `claude auth status` |
235
+ | `CLAUDE_EFFORT` | — | Machine default reasoning effort (`low`, `medium`, `high`, `xhigh`, `max`) that the daemon reports to FlightDeck. Overrides the `effort` key in `~/.claude/settings.json` |
236
+ | `CLAUDE_PERMISSION_MODE` | `auto` | Claude CLI permission mode: `auto`, `acceptEdits`, `manual`, `dontAsk`, `plan`, `bypassPermissions` |
237
+ | `CLAUDE_PERMISSION_TIMEOUT` | `600` | Seconds a permission prompt waits for an operator before auto-denying (1–86400) |
238
+ | `CLAUDE_SKIP_PERMISSIONS` | `false` | **Deprecated** — alias for `CLAUDE_PERMISSION_MODE=bypassPermissions` |
228
239
  | `CLAUDE_DISABLE_AUTH` | `false` | Disable WebSocket auth (Docker only) |
229
240
 
241
+ Sessions inherit the daemon's environment, so Claude CLI variables such as `CLAUDE_CONFIG_DIR` and `CLAUDE_CODE_OAUTH_TOKEN` apply to every session. The daemon reads those two itself only to report which Claude account the pilot runs as.
242
+
230
243
  **Addon-side variables** (set when starting Storybook):
231
244
 
232
245
  | Variable | Default | Description |
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@radnine/claude-session-daemon",
3
- "version": "0.8.0",
3
+ "version": "0.9.2",
4
4
  "description": "Node.js daemon for managing Claude CLI sessions",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "git+ssh://git@github.com/radixhound/rad-project.git",
8
+ "url": "git+ssh://git@github.com/radixhound/flight-deck.git",
9
9
  "directory": "daemon"
10
10
  },
11
11
  "main": "src/index.js",
@@ -14,7 +14,6 @@
14
14
  },
15
15
  "files": [
16
16
  "src/**",
17
- "hooks/**",
18
17
  "LICENSE",
19
18
  "Dockerfile",
20
19
  "docker-entrypoint.sh",
@@ -1,56 +1,222 @@
1
1
  'use strict';
2
2
 
3
+ const { execFile } = require('node:child_process');
3
4
  const fs = require('node:fs').promises;
4
5
  const os = require('node:os');
5
6
  const path = require('node:path');
7
+ const { promisify } = require('node:util');
8
+
9
+ const execFileAsync = promisify(execFile);
6
10
 
7
11
  const CACHE_TTL_MS = 60_000;
12
+ const EXEC_TIMEOUT_MS = 5000;
13
+
8
14
  let _cache = null; // { value, expiresAt }
9
15
 
10
16
  /**
11
- * Read the logged-in Claude account from ~/.claude.json.
17
+ * Report which Claude account a pilot actually runs as.
12
18
  *
13
- * The Claude CLI persists the active OAuth account at `oauthAccount.emailAddress`.
14
- * We surface email + account/org UUIDs so the UI can warn when the user is logged
15
- * into a different account than they expect (different rate limits).
19
+ * The daemon spawns the CLI with `{...process.env, ...sessionEnv}`, so the
20
+ * account in force is whatever that environment resolves to — and two env vars
21
+ * move it off the home directory:
16
22
  *
17
- * Cached for 60s; returns null if the file is missing/malformed or the field is absent.
23
+ * - CLAUDE_CONFIG_DIR relocates the whole config directory. Pointed at a
24
+ * directory with no account, the CLI is signed out even though the login
25
+ * Keychain still holds the default credentials.
26
+ * - CLAUDE_CODE_OAUTH_TOKEN overrides the login entirely, while
27
+ * `~/.claude.json` goes on naming the default account.
18
28
  *
19
- * @param {string} [filePath] - Override path for tests.
20
- * @returns {Promise<{email: string, account_uuid: string|null, organization_uuid: string|null}|null>}
29
+ * Reading `~/.claude.json` therefore states the opposite of the truth under
30
+ * either one, which defeats the point of the display — catching a pilot on an
31
+ * unexpected subscription. So we ask the CLI (`claude auth status`, JSON on
32
+ * stdout) with the same environment, and fall back to the config file only when
33
+ * the subprocess gives us nothing.
34
+ *
35
+ * Always resolves to an account object, never null. `signed_out` and `unknown`
36
+ * are answers: they overwrite the last-known account on the server, where a
37
+ * null would leave the previous pilot's email sitting on screen. A wrong-but-
38
+ * confident email is the defect this exists to prevent.
39
+ *
40
+ * Cached for 60s — which also bounds the subprocess to once a minute.
41
+ *
42
+ * @param {object} [options]
43
+ * @param {object} [options.env] - Environment to resolve against (default process.env).
44
+ * @param {Function} [options.exec] - execFile-style runner, for tests.
45
+ * @param {string} [options.configFile] - Override the resolved `.claude.json` path.
46
+ * @returns {Promise<{state: string, email: string|null, account_uuid: string|null,
47
+ * organization_uuid: string|null, auth_method: string|null,
48
+ * subscription_type: string|null, source: string, config_dir: string|null}>}
21
49
  */
22
- async function getClaudeAccount(filePath) {
50
+ async function getClaudeAccount(options = {}) {
23
51
  const now = Date.now();
24
- if (!filePath && _cache && _cache.expiresAt > now) {
52
+ const cacheable = !options.env && !options.exec && !options.configFile;
53
+ if (cacheable && _cache && _cache.expiresAt > now) {
25
54
  return _cache.value;
26
55
  }
27
56
 
28
- const target = filePath || path.join(os.homedir(), '.claude.json');
29
- let value = null;
57
+ const env = options.env || process.env;
58
+ const exec = options.exec || execFileAsync;
59
+ const configDir = readEnv(env, 'CLAUDE_CONFIG_DIR');
60
+ const configFile = options.configFile || path.join(configDir || os.homedir(), '.claude.json');
61
+
62
+ const [status, fileAccount] = await Promise.all([
63
+ readAuthStatus(env, exec),
64
+ readClaudeConfigAccount(configFile),
65
+ ]);
66
+
67
+ const value = status
68
+ ? fromAuthStatus(status, fileAccount, configDir)
69
+ : fromConfigFile(fileAccount, env, configDir);
70
+
71
+ if (cacheable) {
72
+ _cache = { value, expiresAt: now + CACHE_TTL_MS };
73
+ }
74
+ return value;
75
+ }
30
76
 
77
+ /**
78
+ * Read the account recorded in a `.claude.json`.
79
+ *
80
+ * The Claude CLI persists the active OAuth account at `oauthAccount.emailAddress`.
81
+ * Returns null if the file is missing/malformed or the field is absent — note
82
+ * that a config directory the CLI has written to but nobody has logged into has
83
+ * a `.claude.json` with no `oauthAccount` at all, so null here means "this file
84
+ * names no account", not "signed out".
85
+ *
86
+ * @param {string} filePath
87
+ * @returns {Promise<{email: string, account_uuid: string|null, organization_uuid: string|null}|null>}
88
+ */
89
+ async function readClaudeConfigAccount(filePath) {
31
90
  try {
32
- const raw = await fs.readFile(target, 'utf8');
91
+ const raw = await fs.readFile(filePath, 'utf8');
33
92
  const parsed = JSON.parse(raw);
34
93
  const oauth = parsed && parsed.oauthAccount;
35
94
  if (oauth && typeof oauth.emailAddress === 'string' && oauth.emailAddress.length > 0) {
36
- value = {
95
+ return {
37
96
  email: oauth.emailAddress,
38
97
  account_uuid: oauth.accountUuid || null,
39
98
  organization_uuid: oauth.organizationUuid || null,
40
99
  };
41
100
  }
42
101
  } catch (_) {
43
- value = null;
102
+ return null;
44
103
  }
104
+ return null;
105
+ }
45
106
 
46
- if (!filePath) {
47
- _cache = { value, expiresAt: now + CACHE_TTL_MS };
107
+ /**
108
+ * Run `claude auth status` and return its parsed JSON verdict, or null when the
109
+ * CLI gives us no usable answer.
110
+ */
111
+ async function readAuthStatus(env, exec) {
112
+ const command = readEnv(env, 'CLAUDE_COMMAND') || 'claude';
113
+ let stdout = null;
114
+
115
+ try {
116
+ ({ stdout } = await exec(command, ['auth', 'status'], { env, timeout: EXEC_TIMEOUT_MS }));
117
+ } catch (err) {
118
+ // Signed out is reported as exit 1 with the JSON verdict still on stdout
119
+ // (verified against CLI 2.1.246), so a non-zero exit is not "no answer".
120
+ stdout = err && typeof err.stdout === 'string' ? err.stdout : null;
48
121
  }
49
- return value;
122
+
123
+ if (!stdout) return null;
124
+
125
+ try {
126
+ const parsed = JSON.parse(stdout);
127
+ // `loggedIn` is the field the whole verdict hangs on. Without it we are
128
+ // looking at partial output or a different command's JSON.
129
+ return parsed && typeof parsed.loggedIn === 'boolean' ? parsed : null;
130
+ } catch (_) {
131
+ return null;
132
+ }
133
+ }
134
+
135
+ function fromAuthStatus(status, fileAccount, configDir) {
136
+ const authMethod = nonEmpty(status.authMethod);
137
+
138
+ if (!status.loggedIn) {
139
+ return account({ state: 'signed_out', auth_method: authMethod, source: 'cli', config_dir: configDir });
140
+ }
141
+
142
+ const email = nonEmpty(status.email);
143
+ if (!email) {
144
+ // Signed in, but the CLI will not name the account — the token-auth case.
145
+ return account({
146
+ state: 'unknown',
147
+ auth_method: authMethod,
148
+ subscription_type: nonEmpty(status.subscriptionType),
149
+ source: 'cli',
150
+ config_dir: configDir,
151
+ });
152
+ }
153
+
154
+ // `auth status` has no account UUID of its own. Borrow it from the config
155
+ // file only when that file names the same account we just resolved.
156
+ const sameAccount = fileAccount && fileAccount.email === email;
157
+
158
+ return account({
159
+ state: 'signed_in',
160
+ email,
161
+ account_uuid: sameAccount ? fileAccount.account_uuid : null,
162
+ organization_uuid: nonEmpty(status.orgId) || (sameAccount ? fileAccount.organization_uuid : null),
163
+ auth_method: authMethod,
164
+ subscription_type: nonEmpty(status.subscriptionType),
165
+ source: 'cli',
166
+ config_dir: configDir,
167
+ });
168
+ }
169
+
170
+ // Fallback for when the CLI gave us nothing. Weaker than the CLI on purpose:
171
+ // credentials live in the login Keychain keyed to the config directory, so a
172
+ // `.claude.json` naming an account does not prove a session is signed in to it.
173
+ // This keeps a broken or slow CLI degrading to the old behaviour rather than
174
+ // blanking the display.
175
+ function fromConfigFile(fileAccount, env, configDir) {
176
+ // A token overrides whatever the config file names, and without the CLI we
177
+ // cannot resolve it. The file's email is the one answer we know is wrong.
178
+ if (readEnv(env, 'CLAUDE_CODE_OAUTH_TOKEN')) {
179
+ return account({ state: 'unknown', auth_method: 'oauth_token', source: 'config_file', config_dir: configDir });
180
+ }
181
+
182
+ if (fileAccount) {
183
+ return account({
184
+ state: 'signed_in',
185
+ email: fileAccount.email,
186
+ account_uuid: fileAccount.account_uuid,
187
+ organization_uuid: fileAccount.organization_uuid,
188
+ source: 'config_file',
189
+ config_dir: configDir,
190
+ });
191
+ }
192
+
193
+ return account({ state: 'unknown', source: 'config_file', config_dir: configDir });
194
+ }
195
+
196
+ /** Build the full payload shape so every field is present in every state. */
197
+ function account(fields) {
198
+ return {
199
+ state: fields.state,
200
+ email: fields.email || null,
201
+ account_uuid: fields.account_uuid || null,
202
+ organization_uuid: fields.organization_uuid || null,
203
+ auth_method: fields.auth_method || null,
204
+ subscription_type: fields.subscription_type || null,
205
+ source: fields.source,
206
+ config_dir: fields.config_dir || null,
207
+ };
208
+ }
209
+
210
+ function nonEmpty(value) {
211
+ return typeof value === 'string' && value.trim().length > 0 ? value : null;
212
+ }
213
+
214
+ function readEnv(env, name) {
215
+ return nonEmpty(env && env[name]);
50
216
  }
51
217
 
52
218
  function _resetCacheForTests() {
53
219
  _cache = null;
54
220
  }
55
221
 
56
- module.exports = { getClaudeAccount, _resetCacheForTests };
222
+ module.exports = { getClaudeAccount, readClaudeConfigAccount, _resetCacheForTests };