@radnine/claude-session-daemon 0.8.3 → 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.
@@ -0,0 +1,302 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * #480: turns `codex app-server` notifications into the Claude stream-json
5
+ * events the rest of FlightDeck reads (see harness.js). Pure: it takes a
6
+ * notification and returns the events to emit, so fixtures replay without a
7
+ * process.
8
+ *
9
+ * Protocol facts, recorded from codex 0.162.1 (daemon/test/fixtures/codex):
10
+ * - `turn/started` opens a turn, `turn/completed` closes it with
11
+ * status completed | interrupted | failed.
12
+ * - Items arrive as `item/started` then `item/completed`: agentMessage,
13
+ * commandExecution, fileChange, mcpToolCall, reasoning, webSearch.
14
+ * - A failure (usage limit, auth, overload) arrives as an `error`
15
+ * notification with willRetry false, then `turn/completed` with status
16
+ * failed and turn.error.
17
+ */
18
+
19
+ const SHELL_WRAPPER = /^(?:\/\S*\/)?(?:zsh|bash|sh)\s+-l?c\s+(['"])([\s\S]*)\1$/;
20
+
21
+ /**
22
+ * `/bin/zsh -lc 'git status'` -> `git status`. Codex reports the shell
23
+ * wrapper it ran; Rails shows the command as the tool card summary.
24
+ */
25
+ function unwrapShell(command) {
26
+ if (typeof command !== 'string') return '';
27
+ const match = SHELL_WRAPPER.exec(command.trim());
28
+ return match ? match[2] : command;
29
+ }
30
+
31
+ function toolNameForChange(kind) {
32
+ const type = kind && kind.type;
33
+ if (type === 'add') return 'Write';
34
+ if (type === 'delete') return 'Delete';
35
+ return 'Edit';
36
+ }
37
+
38
+ class CodexTranslator {
39
+ /**
40
+ * @param {object} options
41
+ * @param {string} options.threadId - the Codex thread id, reported as session_id
42
+ * @param {string} [options.model]
43
+ * @param {string} [options.cwd]
44
+ */
45
+ constructor({ threadId, model = null, cwd = null }) {
46
+ this._threadId = threadId;
47
+ this._model = model;
48
+ this._cwd = cwd;
49
+ this._turn = null;
50
+ this._sentText = []; // text of the messages sent, oldest first; the next turn echoes the first
51
+ }
52
+
53
+ /** Remember a message handed to Codex so the turn that takes it can echo it. */
54
+ messageSent(text) {
55
+ this._sentText.push(text);
56
+ }
57
+
58
+ /** True while a turn is open. */
59
+ get turnOpen() { return this._turn !== null; }
60
+
61
+ /** The open turn's id, or null. */
62
+ get turnId() { return this._turn ? this._turn.id : null; }
63
+
64
+ /**
65
+ * @param {string} method - notification method
66
+ * @param {object} params
67
+ * @returns {object[]} stream-json events, in order
68
+ */
69
+ translate(method, params = {}) {
70
+ switch (method) {
71
+ case 'turn/started': return this._turnStarted(params);
72
+ case 'item/started': return this._item(params, 'started');
73
+ case 'item/completed': return this._item(params, 'completed');
74
+ case 'thread/tokenUsage/updated': return this._tokenUsage(params);
75
+ case 'error': return this._error(params);
76
+ case 'turn/completed': return this._turnCompleted(params);
77
+ default: return [];
78
+ }
79
+ }
80
+
81
+ // -------------------------------------------------------------------------
82
+
83
+ _base() {
84
+ return { session_id: this._threadId };
85
+ }
86
+
87
+ _turnStarted({ turn }) {
88
+ this._turn = {
89
+ id: turn && turn.id,
90
+ startedAt: Date.now(),
91
+ lastText: '',
92
+ announced: new Set(),
93
+ unresolved: new Set(), // tool calls with no result yet
94
+ error: null,
95
+ usage: null,
96
+ };
97
+ const text = this._sentText.shift();
98
+ const events = [{
99
+ type: 'system',
100
+ subtype: 'init',
101
+ cwd: this._cwd,
102
+ model: this._model,
103
+ tools: [],
104
+ mcp_servers: [],
105
+ harness: 'codex',
106
+ ...this._base(),
107
+ }];
108
+ if (text !== undefined) {
109
+ events.push({ type: 'user', isReplay: true, message: { role: 'user', content: text }, ...this._base() });
110
+ }
111
+ return events;
112
+ }
113
+
114
+ _item({ item }, phase) {
115
+ if (!item || !this._turn) return [];
116
+
117
+ switch (item.type) {
118
+ case 'agentMessage': return phase === 'completed' ? this._agentMessage(item) : [];
119
+ case 'reasoning': return phase === 'completed' ? this._reasoning(item) : [];
120
+ case 'commandExecution': return this._command(item, phase);
121
+ case 'fileChange': return this._fileChange(item, phase);
122
+ case 'mcpToolCall': return this._mcpCall(item, phase);
123
+ case 'webSearch': return this._webSearch(item);
124
+ default: return [];
125
+ }
126
+ }
127
+
128
+ _assistant(content, id) {
129
+ return {
130
+ type: 'assistant',
131
+ message: { id, type: 'message', role: 'assistant', model: this._model, content },
132
+ ...this._base(),
133
+ };
134
+ }
135
+
136
+ _toolUse(id, name, input) {
137
+ this._turn.announced.add(id);
138
+ this._turn.unresolved.add(id);
139
+ return this._assistant([{ type: 'tool_use', id, name, input }], id);
140
+ }
141
+
142
+ _toolResult(id, content, isError) {
143
+ if (this._turn) this._turn.unresolved.delete(id);
144
+ return {
145
+ type: 'user',
146
+ message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content, is_error: !!isError }] },
147
+ ...this._base(),
148
+ };
149
+ }
150
+
151
+ _agentMessage(item) {
152
+ const text = typeof item.text === 'string' ? item.text : '';
153
+ if (!text) return [];
154
+ this._turn.lastText = text;
155
+ return [this._assistant([{ type: 'text', text }], item.id)];
156
+ }
157
+
158
+ _reasoning(item) {
159
+ const summary = Array.isArray(item.summary) ? item.summary.filter(Boolean).join('\n').trim() : '';
160
+ if (!summary) return [];
161
+ return [this._assistant([{ type: 'thinking', thinking: summary }], item.id)];
162
+ }
163
+
164
+ _command(item, phase) {
165
+ const events = [];
166
+ if (!this._turn.announced.has(item.id)) {
167
+ events.push(this._toolUse(item.id, 'Bash', { command: unwrapShell(item.command), cwd: item.cwd }));
168
+ }
169
+ if (phase === 'completed') {
170
+ let output = typeof item.aggregatedOutput === 'string' ? item.aggregatedOutput : '';
171
+ const failed = item.status === 'failed' || item.status === 'declined' || (item.exitCode != null && item.exitCode !== 0);
172
+ if (item.status === 'declined') output = output || 'Command declined';
173
+ if (failed && item.exitCode != null && item.exitCode !== 0) output = `${output}${output && !output.endsWith('\n') ? '\n' : ''}Exit code ${item.exitCode}`;
174
+ events.push(this._toolResult(item.id, output, failed));
175
+ }
176
+ return events;
177
+ }
178
+
179
+ // One tool card per changed file, so a multi-file patch shows every path.
180
+ _changeId(item, index, count) {
181
+ return count > 1 ? `${item.id}:${index}` : item.id;
182
+ }
183
+
184
+ _fileChange(item, phase) {
185
+ const changes = Array.isArray(item.changes) ? item.changes : [];
186
+ const events = [];
187
+ changes.forEach((change, index) => {
188
+ const id = this._changeId(item, index, changes.length);
189
+ if (!this._turn.announced.has(id)) {
190
+ events.push(this._toolUse(id, toolNameForChange(change.kind), { file_path: change.path, diff: change.diff }));
191
+ }
192
+ if (phase === 'completed') {
193
+ const failed = item.status === 'failed' || item.status === 'declined';
194
+ const verb = item.status === 'declined' ? 'declined' : item.status === 'failed' ? 'failed' : 'applied';
195
+ events.push(this._toolResult(id, `Patch ${verb}: ${change.path}`, failed));
196
+ }
197
+ });
198
+ return events;
199
+ }
200
+
201
+ _mcpCall(item, phase) {
202
+ const events = [];
203
+ if (!this._turn.announced.has(item.id)) {
204
+ const args = item.arguments && typeof item.arguments === 'object' ? item.arguments : {};
205
+ events.push(this._toolUse(item.id, `mcp__${item.server}__${item.tool}`, args));
206
+ }
207
+ if (phase === 'completed') {
208
+ if (item.error || item.status === 'failed') {
209
+ const text = (item.error && item.error.message) || _mcpContent(item.result) || 'MCP tool call failed';
210
+ events.push(this._toolResult(item.id, text, true));
211
+ } else {
212
+ events.push(this._toolResult(item.id, _mcpContent(item.result), false));
213
+ }
214
+ }
215
+ return events;
216
+ }
217
+
218
+ _webSearch(item) {
219
+ if (this._turn.announced.has(item.id)) return [];
220
+ return [this._toolUse(item.id, 'WebSearch', { query: item.query || '' })];
221
+ }
222
+
223
+ _tokenUsage({ tokenUsage }) {
224
+ const last = tokenUsage && tokenUsage.last;
225
+ if (this._turn && last) {
226
+ this._turn.usage = {
227
+ input_tokens: last.inputTokens,
228
+ output_tokens: last.outputTokens,
229
+ cache_read_input_tokens: last.cachedInputTokens,
230
+ };
231
+ }
232
+ return [];
233
+ }
234
+
235
+ _error({ error, willRetry }) {
236
+ if (this._turn && error && !willRetry) this._turn.error = error;
237
+ return [];
238
+ }
239
+
240
+ _turnCompleted({ turn }) {
241
+ const open = this._turn || { startedAt: Date.now(), lastText: '', error: null, usage: null, unresolved: new Set() };
242
+ const events = [];
243
+
244
+ // A turn that ends mid tool call (interrupt, failure) leaves a card with no
245
+ // result. Close each one so the chat does not show it as still running.
246
+ for (const id of open.unresolved) {
247
+ events.push(this._toolResult(id, 'Interrupted before the tool finished', true));
248
+ }
249
+ this._turn = null;
250
+ const status = turn && turn.status;
251
+ const duration = turn && turn.durationMs != null ? turn.durationMs : Date.now() - open.startedAt;
252
+
253
+ // duration_api_ms stays 0: the daemon reads a positive value as proof of a
254
+ // fresh Claude usage reading (_confirmClaudeUsage), and this is not one.
255
+ const result = {
256
+ type: 'result',
257
+ subtype: 'success',
258
+ is_error: false,
259
+ duration_ms: duration,
260
+ duration_api_ms: 0,
261
+ num_turns: 1,
262
+ result: open.lastText,
263
+ total_cost_usd: 0,
264
+ usage: open.usage || undefined,
265
+ ...this._base(),
266
+ };
267
+
268
+ if (status === 'interrupted') {
269
+ // What the Claude CLI writes when SIGINT ends a turn.
270
+ result.subtype = 'error_during_execution';
271
+ result.result = '';
272
+ } else if (status === 'failed') {
273
+ const error = (turn && turn.error) || open.error || { message: 'Codex turn failed' };
274
+ const message = _errorText(error);
275
+ events.push(this._assistant([{ type: 'text', text: message }], `codex-error-${turn && turn.id}`));
276
+ result.subtype = 'error_during_execution';
277
+ result.is_error = true;
278
+ result.result = message;
279
+ }
280
+
281
+ events.push(result);
282
+ return events;
283
+ }
284
+ }
285
+
286
+ function _errorText(error) {
287
+ const message = error.message || 'Codex turn failed';
288
+ const details = error.additionalDetails;
289
+ return details && !message.includes(details) ? `${message}\n${details}` : message;
290
+ }
291
+
292
+ // MCP results are `{content: [{type:'text', text}, ...], structuredContent}`.
293
+ function _mcpContent(result) {
294
+ if (!result) return '';
295
+ const blocks = Array.isArray(result.content) ? result.content : [];
296
+ const texts = blocks.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text);
297
+ if (texts.length > 0) return texts.join('\n');
298
+ if (result.structuredContent !== undefined) return JSON.stringify(result.structuredContent);
299
+ return blocks.length > 0 ? JSON.stringify(blocks) : '';
300
+ }
301
+
302
+ module.exports = { CodexTranslator, unwrapShell };
package/src/config.js CHANGED
@@ -12,9 +12,105 @@ function intEnv(value, defaultVal) {
12
12
  return Number.isNaN(parsed) ? defaultVal : parsed;
13
13
  }
14
14
 
15
+ // Permission modes accepted by `claude --permission-mode`.
16
+ const PERMISSION_MODES = ['acceptEdits', 'auto', 'bypassPermissions', 'manual', 'dontAsk', 'plan'];
17
+
18
+ // The CLI renamed "default" to "manual"; configs in the wild still say "default".
19
+ const PERMISSION_MODE_ALIASES = { default: 'manual' };
20
+
21
+ // 24 hours. Well inside setTimeout's 2^31-1 ms ceiling, past which a timer
22
+ // fires on the next tick instead of waiting.
23
+ const MAX_PERMISSION_TIMEOUT = 86400;
24
+
25
+ /**
26
+ * Resolve the permission mode from the environment.
27
+ *
28
+ * CLAUDE_PERMISSION_MODE wins. Failing that, the legacy CLAUDE_SKIP_PERMISSIONS
29
+ * boolean maps to bypassPermissions. Everything else gets auto — the classifier
30
+ * clears routine work and escalates the rest to FlightDeck (ADR-0009).
31
+ *
32
+ * @param {object} env
33
+ * @returns {{ mode: string, warnings: string[] }}
34
+ */
35
+ function resolvePermissionMode(env) {
36
+ const warnings = [];
37
+ const skip = env.CLAUDE_SKIP_PERMISSIONS === 'true';
38
+ const raw = (env.CLAUDE_PERMISSION_MODE || '').trim();
39
+
40
+ if (skip) {
41
+ warnings.push(
42
+ 'CLAUDE_SKIP_PERMISSIONS is deprecated. Use CLAUDE_PERMISSION_MODE=bypassPermissions instead.'
43
+ );
44
+ }
45
+
46
+ if (!raw) {
47
+ return { mode: skip ? 'bypassPermissions' : 'auto', warnings };
48
+ }
49
+
50
+ // Own-property lookup only: `__proto__`, `constructor` and friends would
51
+ // otherwise resolve to something off Object.prototype instead of the raw value.
52
+ const mode = Object.hasOwn(PERMISSION_MODE_ALIASES, raw) ? PERMISSION_MODE_ALIASES[raw] : raw;
53
+
54
+ if (!PERMISSION_MODES.includes(mode)) {
55
+ throw new Error(
56
+ `Invalid CLAUDE_PERMISSION_MODE: "${raw}". Must be one of: ${PERMISSION_MODES.join(', ')}`
57
+ );
58
+ }
59
+
60
+ if (skip && mode !== 'bypassPermissions') {
61
+ warnings.push(
62
+ `CLAUDE_SKIP_PERMISSIONS=true is ignored because CLAUDE_PERMISSION_MODE="${mode}" is set.`
63
+ );
64
+ }
65
+
66
+ return { mode, warnings };
67
+ }
68
+
69
+ const DEFAULT_PERMISSION_TIMEOUT = 600;
70
+
71
+ /**
72
+ * Resolve the permission timeout, correcting rather than rejecting.
73
+ *
74
+ * A pilot that will not start is worse than one that starts with the default,
75
+ * and there are two ways to inherit a bad value: `0` used to be documented as
76
+ * "disabled" (it never was — the old code fell back to 60), and anything past
77
+ * setTimeout's 2^31-1 ms ceiling fires on the next tick, turning a long wait
78
+ * into an instant deny.
79
+ *
80
+ * @param {object} env
81
+ * @returns {{ timeout: number, warnings: string[] }}
82
+ */
83
+ function resolvePermissionTimeout(env) {
84
+ const warnings = [];
85
+ const raw = intEnv(env.CLAUDE_PERMISSION_TIMEOUT, DEFAULT_PERMISSION_TIMEOUT);
86
+
87
+ if (raw < 1) {
88
+ warnings.push(
89
+ `CLAUDE_PERMISSION_TIMEOUT=${raw} is not supported — there is no "wait forever" setting, ` +
90
+ `because the browser dialog counts down against this value. ` +
91
+ `Using ${DEFAULT_PERMISSION_TIMEOUT}s.`
92
+ );
93
+ return { timeout: DEFAULT_PERMISSION_TIMEOUT, warnings };
94
+ }
95
+
96
+ if (raw > MAX_PERMISSION_TIMEOUT) {
97
+ warnings.push(
98
+ `CLAUDE_PERMISSION_TIMEOUT=${raw} exceeds the ${MAX_PERMISSION_TIMEOUT}s ceiling ` +
99
+ `(a longer timer overflows and fires immediately). Using ${MAX_PERMISSION_TIMEOUT}s.`
100
+ );
101
+ return { timeout: MAX_PERMISSION_TIMEOUT, warnings };
102
+ }
103
+
104
+ return { timeout: raw, warnings };
105
+ }
106
+
15
107
  function loadConfig() {
16
108
  const env = process.env;
17
109
 
110
+ const { mode: permissionMode, warnings: modeWarnings } = resolvePermissionMode(env);
111
+ const { timeout: permissionTimeout, warnings: timeoutWarnings } = resolvePermissionTimeout(env);
112
+ const permissionWarnings = [...modeWarnings, ...timeoutWarnings];
113
+
18
114
  const config = {
19
115
  // Operating mode: 'standalone' runs own WS server, 'actioncable' connects to Rails
20
116
  mode: env.CLAUDE_DAEMON_MODE || 'standalone',
@@ -52,22 +148,32 @@ function loadConfig() {
52
148
  // Daemon identifier (generated at runtime if not set)
53
149
  daemonId: env.CLAUDE_DAEMON_ID || null,
54
150
 
55
- // Skip Claude CLI permission prompts (only safe inside Docker containers)
56
- skipPermissions: env.CLAUDE_SKIP_PERMISSIONS === 'true',
151
+ // Permission mode passed to the Claude CLI via --permission-mode
152
+ permissionMode,
57
153
 
58
- // Permission approval timeout in seconds (0 = disabled)
59
- permissionTimeout: intEnv(env.CLAUDE_PERMISSION_TIMEOUT, 60),
154
+ // Deprecation/conflict notices from resolving the permission mode, logged at startup
155
+ permissionWarnings,
60
156
 
61
- // Permission server port (0 = random, only used when skipPermissions is false)
62
- permissionPort: intEnv(env.CLAUDE_PERMISSION_PORT, 0),
157
+ // Seconds a permission prompt waits for an operator before auto-denying.
158
+ // Prompts are rare under auto mode, so this is generous — but not unbounded,
159
+ // because the browser dialog counts down client-side against this value.
160
+ permissionTimeout,
63
161
 
64
162
  // Path to the Claude CLI binary (override for testing)
65
163
  claudeCommand: env.CLAUDE_COMMAND || 'claude',
66
164
 
165
+ // Path to the Codex CLI binary, for chats on a Codex model (#480)
166
+ codexCommand: env.CODEX_COMMAND || 'codex',
167
+
67
168
  // Stale session timeout in seconds — kill alive processes with no activity beyond this threshold.
68
169
  // Safety net for when WebSocket-based deactivation messages are lost.
69
170
  // Default: 30 minutes (1800s). Set to 0 to disable.
70
171
  staleSessionTimeout: intEnv(env.CLAUDE_STALE_SESSION_TIMEOUT, 1800),
172
+
173
+ // Seconds a command for a session with no process waits for Rails'
174
+ // session_activate before it fails. The activation carries the model and
175
+ // persona, and can arrive just after its command.
176
+ activationWaitTimeout: intEnv(env.CLAUDE_ACTIVATION_WAIT_TIMEOUT, 30),
71
177
  };
72
178
 
73
179
  // Validate mode
@@ -84,6 +190,10 @@ function loadConfig() {
84
190
  throw new Error(`CLAUDE_DAEMON_PORT must be 1-65535, got ${config.port}`);
85
191
  }
86
192
 
193
+ if (config.activationWaitTimeout < 1) {
194
+ throw new Error(`CLAUDE_ACTIVATION_WAIT_TIMEOUT must be >= 1, got ${config.activationWaitTimeout}`);
195
+ }
196
+
87
197
  if (config.staleSessionTimeout < 0) {
88
198
  throw new Error(`CLAUDE_STALE_SESSION_TIMEOUT must be >= 0, got ${config.staleSessionTimeout}`);
89
199
  }
@@ -91,4 +201,4 @@ function loadConfig() {
91
201
  return Object.freeze(config);
92
202
  }
93
203
 
94
- module.exports = { loadConfig };
204
+ module.exports = { loadConfig, PERMISSION_MODES };