@radnine/claude-session-daemon 0.7.2 → 0.7.4
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@radnine/claude-session-daemon",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "Node.js daemon for managing Claude CLI sessions",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"repository": {
|
|
@@ -31,8 +31,8 @@
|
|
|
31
31
|
"node": ">=18.0.0"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
+
"gray-matter": "^4.0.3",
|
|
34
35
|
"js-yaml": "^4.1.0",
|
|
35
36
|
"ws": "^8.16.0"
|
|
36
|
-
}
|
|
37
|
-
"devDependencies": {}
|
|
37
|
+
}
|
|
38
38
|
}
|
|
@@ -8,6 +8,7 @@ const WebSocket = require('ws');
|
|
|
8
8
|
const { BaseConnection } = require('./base-connection');
|
|
9
9
|
const { getGitContext } = require('../git-context');
|
|
10
10
|
const { getClaudeAccount } = require('../claude-account');
|
|
11
|
+
const { scanPersonas, readPersonaBody } = require('../persona-scanner');
|
|
11
12
|
const daemonPkg = require('../../package.json');
|
|
12
13
|
|
|
13
14
|
/**
|
|
@@ -629,6 +630,20 @@ class ActionCableClient extends BaseConnection {
|
|
|
629
630
|
|
|
630
631
|
/**
|
|
631
632
|
* Handle session_activate — spawn or reuse a Claude process for the session.
|
|
633
|
+
*
|
|
634
|
+
* Two ways to seed the Claude system prompt:
|
|
635
|
+
* - `system_prompt` — inline body (DB-backed Prompt path)
|
|
636
|
+
* - `system_prompt_path` — relative path under workingDir to a
|
|
637
|
+
* file-backed Persona (.claude/personas/<slug>.md). Read fresh
|
|
638
|
+
* every activation; frontmatter stripped; path traversal rejected.
|
|
639
|
+
*
|
|
640
|
+
* When both are present, system_prompt_path wins. The file is the
|
|
641
|
+
* canonical source for file-backed personas, and Rails should not
|
|
642
|
+
* have a stale snapshot to fall back to.
|
|
643
|
+
*
|
|
644
|
+
* Errors from path validation or file reads are reported back as a
|
|
645
|
+
* structured SESSION_ACTIVATION_FAILED — never a silent hang.
|
|
646
|
+
*
|
|
632
647
|
* @param {object} message
|
|
633
648
|
*/
|
|
634
649
|
async _handleSessionActivation(message) {
|
|
@@ -636,9 +651,30 @@ class ActionCableClient extends BaseConnection {
|
|
|
636
651
|
const userId = message.user_id;
|
|
637
652
|
const claudeSessionId = message.claude_session_id || undefined;
|
|
638
653
|
const resetGit = !!message.reset_git_state;
|
|
639
|
-
const
|
|
654
|
+
const systemPromptPath = message.system_prompt_path || undefined;
|
|
655
|
+
let systemPrompt = message.system_prompt || undefined;
|
|
656
|
+
|
|
657
|
+
if (systemPromptPath) {
|
|
658
|
+
try {
|
|
659
|
+
// Re-read every activation — authors edit persona files mid-session
|
|
660
|
+
// and we want the next session to pick that up without a daemon restart.
|
|
661
|
+
systemPrompt = await readPersonaBody(this._config.workingDir, systemPromptPath);
|
|
662
|
+
} catch (err) {
|
|
663
|
+
this._logger.error('Persona resolution failed', { sessionId, systemPromptPath, code: err.code, error: err.message });
|
|
664
|
+
this._sendError('SESSION_ACTIVATION_FAILED', err.message, {
|
|
665
|
+
session_id: sessionId,
|
|
666
|
+
system_prompt_path: systemPromptPath,
|
|
667
|
+
reason: err.code || 'PERSONA_RESOLUTION_FAILED',
|
|
668
|
+
});
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
640
672
|
|
|
641
|
-
this._logger.info('Received session_activate', {
|
|
673
|
+
this._logger.info('Received session_activate', {
|
|
674
|
+
sessionId, userId, claudeSessionId, resetGit,
|
|
675
|
+
hasSystemPrompt: !!systemPrompt,
|
|
676
|
+
fileBacked: !!systemPromptPath,
|
|
677
|
+
});
|
|
642
678
|
|
|
643
679
|
try {
|
|
644
680
|
const proc = await this._daemon.activateSession(sessionId, {
|
|
@@ -1109,9 +1145,10 @@ class ActionCableClient extends BaseConnection {
|
|
|
1109
1145
|
* Send a heartbeat message to the server.
|
|
1110
1146
|
*/
|
|
1111
1147
|
async _sendHeartbeat() {
|
|
1112
|
-
const [gitContext, claudeAccount] = await Promise.all([
|
|
1148
|
+
const [gitContext, claudeAccount, personas] = await Promise.all([
|
|
1113
1149
|
this._getGitContext(),
|
|
1114
1150
|
this._getClaudeAccount(),
|
|
1151
|
+
this._getPersonas(),
|
|
1115
1152
|
]);
|
|
1116
1153
|
|
|
1117
1154
|
this.sendDaemonMessage({
|
|
@@ -1123,10 +1160,31 @@ class ActionCableClient extends BaseConnection {
|
|
|
1123
1160
|
resource_usage: this._getResourceUsage(),
|
|
1124
1161
|
git_context: gitContext,
|
|
1125
1162
|
claude_account: claudeAccount,
|
|
1163
|
+
personas,
|
|
1126
1164
|
timestamp: new Date().toISOString(),
|
|
1127
1165
|
});
|
|
1128
1166
|
}
|
|
1129
1167
|
|
|
1168
|
+
/**
|
|
1169
|
+
* Scan the pilot's working directory for file-backed personas.
|
|
1170
|
+
* Body content is intentionally not included — heartbeat carries metadata only.
|
|
1171
|
+
* Failures degrade to an empty list; the heartbeat must never block on this.
|
|
1172
|
+
*/
|
|
1173
|
+
async _getPersonas() {
|
|
1174
|
+
try {
|
|
1175
|
+
const personas = await scanPersonas(this._workingDir, { logger: this._logger });
|
|
1176
|
+
if (personas.length > 0) {
|
|
1177
|
+
this._logger.debug(`Reporting ${personas.length} file-backed persona(s) in heartbeat`, {
|
|
1178
|
+
slugs: personas.map((p) => p.slug),
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
return personas;
|
|
1182
|
+
} catch (err) {
|
|
1183
|
+
this._logger.warn('Persona scan failed; reporting empty list', { error: err.message });
|
|
1184
|
+
return [];
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1130
1188
|
/**
|
|
1131
1189
|
* Get git context (branch, PR, remote) for the working directory.
|
|
1132
1190
|
* Returns cached results (30s TTL via git-context module).
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs').promises;
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const matter = require('gray-matter');
|
|
6
|
+
|
|
7
|
+
const PERSONA_SUBDIR = '.claude/personas';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Scan <workingDir>/.claude/personas/*.md and return parsed persona metadata.
|
|
11
|
+
*
|
|
12
|
+
* For each .md file:
|
|
13
|
+
* - slug is derived from the filename (minus the .md suffix)
|
|
14
|
+
* - YAML frontmatter is parsed for optional `name`, `description`, `role`, `tokens`
|
|
15
|
+
* (the heartbeat wire format calls this field `decision_tokens` — see below)
|
|
16
|
+
* - body is parsed but NOT included in the returned metadata (heartbeat carries
|
|
17
|
+
* metadata only; body is re-read at activation time in Phase 3)
|
|
18
|
+
* - path is returned relative to workingDir for stable cross-pilot keys
|
|
19
|
+
*
|
|
20
|
+
* The frontmatter key is `tokens` (short and idiomatic for persona authors),
|
|
21
|
+
* but the heartbeat emits it as `decision_tokens` so the Rails default
|
|
22
|
+
* filter_parameters rule (which redacts anything matching /token/) doesn't
|
|
23
|
+
* blank the array in dev logs. Same data, name chosen for log-friendliness.
|
|
24
|
+
*
|
|
25
|
+
* Failure modes are non-fatal:
|
|
26
|
+
* - missing personas directory => empty array
|
|
27
|
+
* - unreadable file => skipped with logger.warn
|
|
28
|
+
* - invalid YAML frontmatter => persona is still returned with slug only
|
|
29
|
+
* (the whole file is treated as body, per spec)
|
|
30
|
+
*
|
|
31
|
+
* @param {string} workingDir - The pilot's working directory.
|
|
32
|
+
* @param {object} [opts]
|
|
33
|
+
* @param {{warn: function}} [opts.logger] - Optional logger; warnings only.
|
|
34
|
+
* @returns {Promise<Array<{slug: string, name: string|null, description: string|null, path: string, role: string|null, decision_tokens: Array|null}>>}
|
|
35
|
+
*/
|
|
36
|
+
async function scanPersonas(workingDir, opts = {}) {
|
|
37
|
+
if (!workingDir) return [];
|
|
38
|
+
const logger = opts.logger;
|
|
39
|
+
const personaDir = path.join(workingDir, PERSONA_SUBDIR);
|
|
40
|
+
|
|
41
|
+
let entries;
|
|
42
|
+
try {
|
|
43
|
+
entries = await fs.readdir(personaDir, { withFileTypes: true });
|
|
44
|
+
} catch (err) {
|
|
45
|
+
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return [];
|
|
46
|
+
if (logger) logger.warn(`Failed to read personas directory ${personaDir}: ${err.message}`);
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const personas = [];
|
|
51
|
+
for (const entry of entries) {
|
|
52
|
+
// Accept symlinks too — vault setups (e.g. Command Center) often
|
|
53
|
+
// symlink .claude/personas/<slug>.md to a canonical Agents/*.md
|
|
54
|
+
// note so the persona and the vault note share one source.
|
|
55
|
+
// fs.readFile follows symlinks transparently; if the link is broken
|
|
56
|
+
// or points at a non-file, _parsePersonaFile logs and skips.
|
|
57
|
+
if (!entry.name.endsWith('.md')) continue;
|
|
58
|
+
if (!entry.isFile() && !entry.isSymbolicLink()) continue;
|
|
59
|
+
const filePath = path.join(personaDir, entry.name);
|
|
60
|
+
const persona = await _parsePersonaFile(filePath, entry.name, workingDir, logger);
|
|
61
|
+
if (persona) personas.push(persona);
|
|
62
|
+
}
|
|
63
|
+
personas.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
64
|
+
return personas;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function _parsePersonaFile(filePath, fileName, workingDir, logger) {
|
|
68
|
+
const slug = fileName.replace(/\.md$/, '');
|
|
69
|
+
|
|
70
|
+
let raw;
|
|
71
|
+
try {
|
|
72
|
+
raw = await fs.readFile(filePath, 'utf8');
|
|
73
|
+
} catch (err) {
|
|
74
|
+
if (logger) logger.warn(`Failed to read persona file ${filePath}: ${err.message}`);
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let frontmatter = {};
|
|
79
|
+
try {
|
|
80
|
+
const parsed = matter(raw);
|
|
81
|
+
frontmatter = parsed.data || {};
|
|
82
|
+
} catch (err) {
|
|
83
|
+
if (logger) {
|
|
84
|
+
logger.warn(`Invalid YAML frontmatter in ${filePath}, treating whole file as body: ${err.message}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
slug,
|
|
90
|
+
name: _stringOrNull(frontmatter.name),
|
|
91
|
+
description: _stringOrNull(frontmatter.description),
|
|
92
|
+
path: path.relative(workingDir, filePath),
|
|
93
|
+
role: _stringOrNull(frontmatter.role),
|
|
94
|
+
decision_tokens: Array.isArray(frontmatter.tokens) ? frontmatter.tokens.slice() : null,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function _stringOrNull(v) {
|
|
99
|
+
return typeof v === 'string' && v.length > 0 ? v : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Read a persona file fresh from disk, validate it stays inside the
|
|
104
|
+
* pilot's working tree, strip frontmatter, and return the body.
|
|
105
|
+
*
|
|
106
|
+
* Used at session activation time when Rails sends `system_prompt_path`
|
|
107
|
+
* (a relative path under the pilot's working dir) instead of an inline
|
|
108
|
+
* `system_prompt`. The body is never cached — every activation re-reads
|
|
109
|
+
* the file so authors can edit a persona and see changes on the next
|
|
110
|
+
* session without restarting the daemon.
|
|
111
|
+
*
|
|
112
|
+
* Path-traversal hardening:
|
|
113
|
+
* - `relativePath` is resolved against `workingDir`
|
|
114
|
+
* - the resolved path MUST live under `workingDir + path.sep`
|
|
115
|
+
* - absolute paths, `..` escapes, and bind-mount tricks are rejected
|
|
116
|
+
*
|
|
117
|
+
* @param {string} workingDir - The pilot's working directory (absolute).
|
|
118
|
+
* @param {string} relativePath - Persona file path, expected relative
|
|
119
|
+
* to workingDir (e.g. `.claude/personas/commander.md`).
|
|
120
|
+
* @returns {Promise<string>} The persona body (frontmatter stripped).
|
|
121
|
+
* @throws {Error} with `.code` set to one of:
|
|
122
|
+
* - `PERSONA_WORKING_DIR_MISSING` — no workingDir configured
|
|
123
|
+
* - `PERSONA_PATH_INVALID` — relativePath empty/non-string
|
|
124
|
+
* - `PERSONA_PATH_ESCAPES_WORKING_DIR` — traversal attempt
|
|
125
|
+
* - `PERSONA_FILE_UNREADABLE` — missing or read error
|
|
126
|
+
*/
|
|
127
|
+
async function readPersonaBody(workingDir, relativePath) {
|
|
128
|
+
if (!workingDir) {
|
|
129
|
+
const err = new Error('No workingDir configured for persona resolution');
|
|
130
|
+
err.code = 'PERSONA_WORKING_DIR_MISSING';
|
|
131
|
+
throw err;
|
|
132
|
+
}
|
|
133
|
+
if (typeof relativePath !== 'string' || relativePath.length === 0) {
|
|
134
|
+
const err = new Error('system_prompt_path must be a non-empty string');
|
|
135
|
+
err.code = 'PERSONA_PATH_INVALID';
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const resolved = path.resolve(workingDir, relativePath);
|
|
140
|
+
// Add path.sep so workingDir="/var/foo" does not accept "/var/foobar".
|
|
141
|
+
if (!resolved.startsWith(workingDir + path.sep) && resolved !== workingDir) {
|
|
142
|
+
const err = new Error(`Persona path escapes working dir: ${relativePath}`);
|
|
143
|
+
err.code = 'PERSONA_PATH_ESCAPES_WORKING_DIR';
|
|
144
|
+
throw err;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
let raw;
|
|
148
|
+
try {
|
|
149
|
+
raw = await fs.readFile(resolved, 'utf8');
|
|
150
|
+
} catch (readErr) {
|
|
151
|
+
const err = new Error(`Cannot read persona file ${relativePath}: ${readErr.message}`);
|
|
152
|
+
err.code = 'PERSONA_FILE_UNREADABLE';
|
|
153
|
+
err.cause = readErr;
|
|
154
|
+
throw err;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let body = raw;
|
|
158
|
+
try {
|
|
159
|
+
const parsed = matter(raw);
|
|
160
|
+
body = parsed.content;
|
|
161
|
+
} catch (_parseErr) {
|
|
162
|
+
// Mirror scanPersonas: malformed YAML => treat whole file as body.
|
|
163
|
+
body = raw;
|
|
164
|
+
}
|
|
165
|
+
return body;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
module.exports = { scanPersonas, readPersonaBody, PERSONA_SUBDIR };
|