@radnine/claude-session-daemon 0.9.6 → 0.9.7

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 CHANGED
@@ -241,6 +241,8 @@ In Docker mode, `CLAUDE_WORKING_DIR` should point to your mounted workspace (e.g
241
241
 
242
242
  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.
243
243
 
244
+ **Jobs (#638).** A chat can run as a job (lead, builder, verifier, investigator, writer or reporter). Each job is a Claude Code output style file that FlightDeck serves at `GET /api/jobs` (pilot token, ETag). Before it launches a chat with a job, the daemon writes the files into `$CLAUDE_CONFIG_DIR/output-styles/` (else `~/.claude/output-styles/`) as `flightdeck-<job>.md`, refetching only when the `jobs_etag` in `session_activate` changes. Every Claude launch and resume passes `--settings '{"outputStyle":"<style>"}'`: the job's style ("FlightDeck Builder"), or `default` for a chat with no job. A missing job file logs a warning naming the job, and the chat still launches. A Codex chat gets the job file's text at the front of its developer instructions.
245
+
244
246
  **Addon-side variables** (set when starting Storybook):
245
247
 
246
248
  | Variable | Default | Description |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@radnine/claude-session-daemon",
3
- "version": "0.9.6",
3
+ "version": "0.9.7",
4
4
  "description": "Node.js daemon for managing Claude CLI sessions",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -12,6 +12,7 @@ const { TurnTracker } = require('./turn-tracker');
12
12
  // process ends it, and a resumed chat never hears from it.
13
13
  const LIFELONG_BACKGROUND_TOOLS = new Set(['Monitor', 'CronCreate', 'ScheduleWakeup']);
14
14
  const { stripDaemonSecrets } = require('./harness');
15
+ const { validJob, styleNameFor, jobFilePath } = require('./job-styles');
15
16
 
16
17
  const MAX_CHUNK_SIZE = 50000; // 50KB — lines larger than this get flagged
17
18
 
@@ -43,6 +44,8 @@ class ClaudeProcess extends EventEmitter {
43
44
  * @param {object} [options.sessionEnv] - Extra env vars to inject into the spawned process
44
45
  * @param {string} [options.systemPrompt] - Appended to Claude's default system prompt at spawn time via --append-system-prompt
45
46
  * @param {string} [options.model] - Claude model id passed to the CLI via --model (the server always sends the session's stored model)
47
+ * @param {string} [options.job] - #638: the chat's job slug; its output style goes in --settings
48
+ * @param {string} [options.outputStyle] - #638: the job's style name, as Rails sends it
46
49
  */
47
50
  constructor(sessionId, options = {}) {
48
51
  super();
@@ -59,6 +62,8 @@ class ClaudeProcess extends EventEmitter {
59
62
  this._systemPrompt = options.systemPrompt || null;
60
63
  this._model = options.model || null;
61
64
  this._effort = options.effort || null;
65
+ this._job = validJob(options.job) ? options.job : null;
66
+ this._outputStyle = this._job ? (options.outputStyle || styleNameFor(this._job)) : null;
62
67
 
63
68
  this._state = 'idle';
64
69
  this._child = null;
@@ -132,6 +137,11 @@ class ClaudeProcess extends EventEmitter {
132
137
  args.push('--effort', this._effort);
133
138
  }
134
139
 
140
+ // #638: name the style on every launch, resume included. A resume without
141
+ // the flag runs Default, and the flag beats a .claude/settings.local.json
142
+ // that sets one. With no job the chat runs Default on purpose.
143
+ args.push('--settings', JSON.stringify({ outputStyle: this._outputStyle || 'default' }));
144
+
135
145
  if (this._systemPrompt) {
136
146
  args.push('--append-system-prompt', this._systemPrompt);
137
147
  }
@@ -158,6 +168,16 @@ class ClaudeProcess extends EventEmitter {
158
168
  delete env.CLAUDECODE; // Prevent nested session detection
159
169
  stripDaemonSecrets(env);
160
170
 
171
+ // #638: the CLI silently runs Default for a style it can't find, so say so.
172
+ if (this._job) {
173
+ const jobFile = jobFilePath(this._job, env);
174
+ if (!fs.existsSync(jobFile)) {
175
+ this._logger.warn(`Job file for job "${this._job}" is missing; the chat runs the Default output style`, {
176
+ sessionId: this._sessionId, job: this._job, outputStyle: this._outputStyle, path: jobFile,
177
+ });
178
+ }
179
+ }
180
+
161
181
  const opts = {
162
182
  cwd: this._workingDir,
163
183
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -10,6 +10,7 @@ const path = require('node:path');
10
10
  const { TurnTracker } = require('./turn-tracker');
11
11
  const { CodexTranslator } = require('./codex-translator');
12
12
  const { stripDaemonSecrets } = require('./harness');
13
+ const { validJob, readJobBody, jobFilePath } = require('./job-styles');
13
14
 
14
15
  const REQUEST_TIMEOUT_MS = 60000;
15
16
 
@@ -61,6 +62,7 @@ class CodexProcess extends EventEmitter {
61
62
  * @param {string} [options.systemPrompt] - persona prompt, sent as developer instructions
62
63
  * @param {string} [options.model] - Codex model id
63
64
  * @param {string} [options.effort] - reasoning effort for each turn
65
+ * @param {string} [options.job] - #638: the chat's job; its file's text leads the developer instructions
64
66
  * @param {object} [options.sessionEnv] - extra env for the child
65
67
  * @param {{command: string, args: string[], env?: object}} [options.radMcp] - how to start the rad MCP server
66
68
  * @param {Array<{name: string, command: string, args: string[], env?: object}>} [options.mcpServers] - the other
@@ -81,6 +83,8 @@ class CodexProcess extends EventEmitter {
81
83
  this._systemPrompt = options.systemPrompt || null;
82
84
  this._model = options.model || null;
83
85
  this._effort = options.effort || null;
86
+ this._job = validJob(options.job) ? options.job : null;
87
+ this._jobText = null;
84
88
  this._radMcp = options.radMcp;
85
89
  this._mcpServers = options.mcpServers;
86
90
  this._skillRoots = [];
@@ -131,6 +135,15 @@ class CodexProcess extends EventEmitter {
131
135
  });
132
136
  this._skillRoots = claudeSkillRoots(env, this._workingDir);
133
137
  this._memoryIndex = memoryIndexPath(env, this._workingDir);
138
+ // #638: Codex takes no output style file, so the job reaches it as text.
139
+ if (this._job) {
140
+ this._jobText = readJobBody(this._job, env);
141
+ if (!this._jobText) {
142
+ this._logger.warn(`Job file for job "${this._job}" is missing; the Codex chat starts without its job text`, {
143
+ sessionId: this._sessionId, job: this._job, path: jobFilePath(this._job, env),
144
+ });
145
+ }
146
+ }
134
147
 
135
148
  this._logger.info(`Spawning Codex app-server: ${this._codexCommand}`, {
136
149
  sessionId: this._sessionId,
@@ -316,7 +329,7 @@ class CodexProcess extends EventEmitter {
316
329
  sandbox: 'workspace-write',
317
330
  };
318
331
  if (this._model) params.model = this._model;
319
- const instructions = developerInstructions(this._systemPrompt, this._memoryIndex);
332
+ const instructions = developerInstructions(this._systemPrompt, this._memoryIndex, this._jobText);
320
333
  if (instructions) params.developerInstructions = instructions;
321
334
 
322
335
  let response;
@@ -751,11 +764,15 @@ function memoryIndexPath(env = process.env, workingDir = process.cwd(), home = o
751
764
  return fs.existsSync(index) ? index : null;
752
765
  }
753
766
 
754
- // The persona prompt, plus one line pointing at the memory index when there is one.
755
- function developerInstructions(systemPrompt, memoryIndex) {
756
- if (!memoryIndex) return systemPrompt || null;
757
- const line = `Before you start, read your memory index at ${memoryIndex}. It lists what earlier chats in this repo learned; open the files it links to when they bear on your task.`;
758
- return systemPrompt ? `${systemPrompt}\n\n${line}` : line;
767
+ // The job's text (#638), then the persona prompt, then one line pointing at
768
+ // the memory index when there is one.
769
+ function developerInstructions(systemPrompt, memoryIndex, jobText = null) {
770
+ const parts = [jobText, systemPrompt];
771
+ if (memoryIndex) {
772
+ parts.push(`Before you start, read your memory index at ${memoryIndex}. It lists what earlier chats in this repo learned; open the files it links to when they bear on your task.`);
773
+ }
774
+ const present = parts.filter(Boolean);
775
+ return present.length ? present.join('\n\n') : null;
759
776
  }
760
777
 
761
778
  /**
@@ -12,6 +12,7 @@ const { getClaudeAccount } = require('../claude-account');
12
12
  const { getMachineEffort } = require('../machine-effort');
13
13
  const { scanPersonas, readPersonaBody, scanCrewMap, buildCrewHeader, personaSlugFromPath } = require('../persona-scanner');
14
14
  const { handleFsRequest } = require('../fs-bridge');
15
+ const { JobFiles } = require('../job-styles');
15
16
  const daemonPkg = require('../../package.json');
16
17
 
17
18
  // #109: a session holds at most this many commands for its activation; the
@@ -50,6 +51,9 @@ class ActionCableClient extends BaseConnection {
50
51
  this._capabilities = config.capabilities || {};
51
52
  this._workingDir = config.workingDir || process.cwd();
52
53
 
54
+ // #638: the job files FlightDeck serves, written before a launch.
55
+ this._jobFiles = new JobFiles({ railsUrl: this._railsUrl, authToken: this._authToken, logger: this._logger });
56
+
53
57
  // CREW-3 #181: whether the last heartbeat found .claude/crew.yml, and
54
58
  // whether a {removed: true} for a lost file still has to go out.
55
59
  this._crewMapSeen = false;
@@ -844,6 +848,8 @@ class ActionCableClient extends BaseConnection {
844
848
  const systemPromptPath = message.system_prompt_path || undefined;
845
849
  const model = message.model || undefined;
846
850
  const effort = message.reasoning_effort || undefined;
851
+ const job = message.job || undefined;
852
+ const outputStyle = message.output_style || undefined;
847
853
  let systemPrompt = message.system_prompt || undefined;
848
854
 
849
855
  if (systemPromptPath) {
@@ -868,8 +874,13 @@ class ActionCableClient extends BaseConnection {
868
874
  sessionId, userId, claudeSessionId, resetGit,
869
875
  hasSystemPrompt: !!systemPrompt,
870
876
  fileBacked: !!systemPromptPath,
877
+ job,
871
878
  });
872
879
 
880
+ // #638: write the current job files before the CLI looks for them. A
881
+ // failure is a warning (sync never rejects); the chat still launches.
882
+ if (job) await this._jobFiles.sync(message.jobs_etag);
883
+
873
884
  try {
874
885
  const proc = await this._daemon.activateSession(sessionId, {
875
886
  workingDir: this._config.workingDir,
@@ -878,6 +889,8 @@ class ActionCableClient extends BaseConnection {
878
889
  systemPrompt,
879
890
  model,
880
891
  effort,
892
+ job,
893
+ outputStyle,
881
894
  });
882
895
 
883
896
  this.sendDaemonMessage({
package/src/daemon.js CHANGED
@@ -283,6 +283,10 @@ class Daemon extends EventEmitter {
283
283
  const systemPrompt = options.systemPrompt || inherited.systemPrompt;
284
284
  const model = options.model || inherited.model;
285
285
  const effort = options.effort || inherited.effort;
286
+ // #638: the job (and its style name) is fixed for the chat's life, so a
287
+ // resume the daemon starts on its own keeps it.
288
+ const job = options.job || inherited.job;
289
+ const outputStyle = options.outputStyle || inherited.outputStyle;
286
290
 
287
291
  // Reset git state to clean main when requested (scheduled sessions).
288
292
  // Awaited so spawn waits for a clean tree, but async under the hood so the
@@ -305,6 +309,8 @@ class Daemon extends EventEmitter {
305
309
  systemPrompt,
306
310
  model,
307
311
  effort,
312
+ job,
313
+ outputStyle,
308
314
  logger: this._logger.child(`Session:${sessionId}`),
309
315
  });
310
316
 
@@ -337,6 +343,8 @@ class Daemon extends EventEmitter {
337
343
  systemPrompt,
338
344
  model,
339
345
  effort,
346
+ job,
347
+ outputStyle,
340
348
  });
341
349
 
342
350
  this._logger.info('Session activated', { sessionId, activeCount: this._processes.size });
@@ -0,0 +1,156 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const matter = require('gray-matter');
7
+
8
+ /**
9
+ * Jobs (#638). A FlightDeck chat runs as a job (lead, builder, verifier,
10
+ * investigator, writer, reporter), and each job is a Claude Code output style
11
+ * file. FlightDeck holds the files and serves them at GET /api/jobs with an
12
+ * ETag. Before a Claude launch the daemon writes them into the Claude config
13
+ * folder's output-styles/ ($CLAUDE_CONFIG_DIR, else ~/.claude), where the CLI
14
+ * looks them up by the `name` in their frontmatter. A Codex chat reads the
15
+ * same file and gets its body in its developer instructions.
16
+ *
17
+ * Rails sends the job, its style name and the files' ETag (jobs_etag) in
18
+ * session_activate, so the daemon fetches only when the set changed.
19
+ */
20
+
21
+ // A job slug is plain lowercase letters: it becomes part of a file name.
22
+ const JOB_PATTERN = /^[a-z]+$/;
23
+ const JOB_FILENAME = /^flightdeck-[a-z]+\.md$/;
24
+ const FETCH_TIMEOUT_MS = 5000;
25
+
26
+ function validJob(job) {
27
+ return typeof job === 'string' && JOB_PATTERN.test(job);
28
+ }
29
+
30
+ /** "FlightDeck Builder" for "builder" — the name FlightDeck gives the style. */
31
+ function styleNameFor(job) {
32
+ return `FlightDeck ${job.charAt(0).toUpperCase()}${job.slice(1)}`;
33
+ }
34
+
35
+ function outputStylesDir(env = process.env, home = os.homedir()) {
36
+ return path.join(env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'output-styles');
37
+ }
38
+
39
+ function jobFilePath(job, env = process.env, home = os.homedir()) {
40
+ return path.join(outputStylesDir(env, home), `flightdeck-${job}.md`);
41
+ }
42
+
43
+ /** The job file's text without its frontmatter, or null when it isn't there. */
44
+ function readJobBody(job, env = process.env, home = os.homedir()) {
45
+ if (!validJob(job)) return null;
46
+ let raw;
47
+ try {
48
+ raw = fs.readFileSync(jobFilePath(job, env, home), 'utf8');
49
+ } catch (_) {
50
+ return null;
51
+ }
52
+ return matter(raw).content.trim() || null;
53
+ }
54
+
55
+ /**
56
+ * Keeps the pilot's copy of the job files current. One per daemon connection.
57
+ */
58
+ class JobFiles {
59
+ /**
60
+ * @param {object} options
61
+ * @param {string} options.railsUrl - FlightDeck's base URL
62
+ * @param {string|null} options.authToken - the pilot token (CLAUDE_AUTH_TOKEN)
63
+ * @param {object} options.logger
64
+ * @param {object} [options.env] - where CLAUDE_CONFIG_DIR is read (default process.env)
65
+ * @param {Function} [options.fetchFn] - tests: replacement for global fetch
66
+ */
67
+ constructor({ railsUrl, authToken, logger, env = process.env, fetchFn = globalThis.fetch }) {
68
+ this._railsUrl = railsUrl;
69
+ this._authToken = authToken;
70
+ this._logger = logger;
71
+ this._env = env;
72
+ this._fetch = fetchFn;
73
+ this._etag = null; // the ETag of the set last written
74
+ this._inFlight = null; // one fetch at a time; concurrent launches share it
75
+ }
76
+
77
+ get etag() {
78
+ return this._etag;
79
+ }
80
+
81
+ /**
82
+ * Write the current job files unless `etag` names the set already written.
83
+ * Never rejects: a failure is a warning, and the launch goes on (the CLI
84
+ * runs Default for a style it can't find, and ClaudeProcess warns).
85
+ *
86
+ * @param {string|null|undefined} etag - jobs_etag from session_activate
87
+ */
88
+ async sync(etag) {
89
+ if (etag && etag === this._etag) return;
90
+ if (!this._inFlight) {
91
+ this._inFlight = this._fetchAndWrite().finally(() => { this._inFlight = null; });
92
+ }
93
+ await this._inFlight;
94
+ }
95
+
96
+ async _fetchAndWrite() {
97
+ // CLAUDE_RAILS_URL is http(s); a ws(s) one still names the same server.
98
+ const url = new URL('/api/jobs', String(this._railsUrl).replace(/^ws(s?):/, 'http$1:')).toString();
99
+ const headers = { Accept: 'application/json' };
100
+ if (this._authToken) headers.Authorization = `Bearer ${this._authToken}`;
101
+ if (this._etag) headers['If-None-Match'] = this._etag;
102
+
103
+ let response;
104
+ try {
105
+ response = await this._fetch(url, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
106
+ } catch (err) {
107
+ this._logger.warn('Could not fetch the job files from FlightDeck', { url, error: err.message });
108
+ return;
109
+ }
110
+
111
+ if (response.status === 304) return;
112
+ if (!response.ok) {
113
+ this._logger.warn(`Could not fetch the job files from FlightDeck: HTTP ${response.status}`, { url });
114
+ return;
115
+ }
116
+
117
+ let body;
118
+ try {
119
+ body = await response.json();
120
+ } catch (err) {
121
+ this._logger.warn('FlightDeck sent job files that are not JSON', { url, error: err.message });
122
+ return;
123
+ }
124
+
125
+ const dir = outputStylesDir(this._env);
126
+ try {
127
+ fs.mkdirSync(dir, { recursive: true });
128
+ for (const job of Array.isArray(body.jobs) ? body.jobs : []) {
129
+ if (!JOB_FILENAME.test(job.filename || '') || typeof job.content !== 'string') {
130
+ this._logger.warn('Skipping a job file with an unexpected name', { filename: job.filename });
131
+ continue;
132
+ }
133
+ // Write then rename, so a CLI starting now never reads half a file.
134
+ const target = path.join(dir, job.filename);
135
+ const temp = `${target}.${process.pid}.tmp`;
136
+ fs.writeFileSync(temp, job.content);
137
+ fs.renameSync(temp, target);
138
+ }
139
+ } catch (err) {
140
+ this._logger.warn('Could not write the job files', { dir, error: err.message });
141
+ return;
142
+ }
143
+
144
+ this._etag = response.headers.get('etag') || null;
145
+ this._logger.info('Wrote the job files', { dir, etag: this._etag });
146
+ }
147
+ }
148
+
149
+ module.exports = {
150
+ JobFiles,
151
+ validJob,
152
+ styleNameFor,
153
+ outputStylesDir,
154
+ jobFilePath,
155
+ readJobBody,
156
+ };
@@ -21,7 +21,7 @@ const RANK_TITLES = { 1: 'Chief of Staff', 2: 'officer', 3: 'crew' };
21
21
  * - slug is derived from the filename (minus the .md suffix)
22
22
  * - YAML frontmatter is parsed for optional `name`, `description`, `role`, `tokens`
23
23
  * (the heartbeat wire format calls this field `decision_tokens` — see below),
24
- * `model` and `reasoning_effort`
24
+ * `model`, `reasoning_effort` and `default_job`
25
25
  * - body is parsed but NOT included in the returned metadata (heartbeat carries
26
26
  * metadata only; body is re-read at activation time in Phase 3)
27
27
  * - path is returned relative to workingDir for stable cross-pilot keys
@@ -33,7 +33,8 @@ const RANK_TITLES = { 1: 'Chief of Staff', 2: 'officer', 3: 'crew' };
33
33
  *
34
34
  * `model` and `reasoning_effort` (#596) are what the persona launches with
35
35
  * when nobody picks. They pass through as trimmed text; Rails owns the model
36
- * list and drops a value it doesn't know.
36
+ * list and drops a value it doesn't know. `default_job` (#638) is the job it
37
+ * launches as, passed through the same way.
37
38
  *
38
39
  * Failure modes are non-fatal:
39
40
  * - missing personas directory => empty array
@@ -44,7 +45,7 @@ const RANK_TITLES = { 1: 'Chief of Staff', 2: 'officer', 3: 'crew' };
44
45
  * @param {string} workingDir - The pilot's working directory.
45
46
  * @param {object} [opts]
46
47
  * @param {{warn: function}} [opts.logger] - Optional logger; warnings only.
47
- * @returns {Promise<Array<{slug: string, name: string|null, description: string|null, path: string, role: string|null, decision_tokens: Array|null, model: string|null, reasoning_effort: string|null}>>}
48
+ * @returns {Promise<Array<{slug: string, name: string|null, description: string|null, path: string, role: string|null, decision_tokens: Array|null, model: string|null, reasoning_effort: string|null, default_job: string|null}>>}
48
49
  */
49
50
  async function scanPersonas(workingDir, opts = {}) {
50
51
  if (!workingDir) return [];
@@ -107,6 +108,9 @@ async function _parsePersonaFile(filePath, fileName, workingDir, logger) {
107
108
  decision_tokens: Array.isArray(frontmatter.tokens) ? frontmatter.tokens.slice() : null,
108
109
  model: _trimmedOrNull(frontmatter.model),
109
110
  reasoning_effort: _trimmedOrNull(frontmatter.reasoning_effort),
111
+ // #638: the job the persona launches as when nobody picks one. Passed
112
+ // through as written; Rails drops one that isn't a job it knows.
113
+ default_job: _trimmedOrNull(frontmatter.default_job),
110
114
  };
111
115
  }
112
116