@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 +5 -2
- package/README.md +17 -4
- package/package.json +2 -3
- package/src/claude-account.js +184 -18
- package/src/claude-process.js +362 -69
- package/src/claude-usage.js +46 -0
- package/src/codex-process.js +772 -0
- package/src/codex-translator.js +302 -0
- package/src/config.js +117 -7
- package/src/connections/action-cable-client.js +623 -54
- package/src/connections/base-connection.js +6 -4
- package/src/connections/command-receipts.js +38 -0
- package/src/daemon.js +351 -21
- package/src/fs-bridge.js +480 -0
- package/src/harness.js +131 -0
- package/src/index.js +17 -15
- package/src/permission-broker.js +236 -0
- package/src/persona-scanner.js +267 -1
- package/src/turn-tracker.js +146 -0
- package/hooks/permission-gate.sh +0 -40
- package/src/permission-server.js +0 -266
package/src/claude-process.js
CHANGED
|
@@ -6,6 +6,8 @@ const { createInterface } = require('node:readline');
|
|
|
6
6
|
const { randomUUID } = require('node:crypto');
|
|
7
7
|
const fs = require('node:fs');
|
|
8
8
|
const path = require('node:path');
|
|
9
|
+
const { TurnTracker } = require('./turn-tracker');
|
|
10
|
+
const { stripDaemonSecrets } = require('./harness');
|
|
9
11
|
|
|
10
12
|
const MAX_CHUNK_SIZE = 50000; // 50KB — lines larger than this get flagged
|
|
11
13
|
|
|
@@ -13,12 +15,17 @@ const MAX_CHUNK_SIZE = 50000; // 50KB — lines larger than this get flagged
|
|
|
13
15
|
* Wraps a single Claude CLI child process.
|
|
14
16
|
*
|
|
15
17
|
* Emits:
|
|
16
|
-
* 'output'
|
|
17
|
-
*
|
|
18
|
-
* '
|
|
19
|
-
* '
|
|
20
|
-
* '
|
|
18
|
+
* 'output' — (data, tag) parsed JSON message from stdout; tag is
|
|
19
|
+
* { commandId, turnCommandIds? } from the TurnTracker (#175)
|
|
20
|
+
* 'error' — (line) unparseable stdout line
|
|
21
|
+
* 'stderr' — (line) stderr line
|
|
22
|
+
* 'exit' — (code, signal, { commandId, unfinishedCommandIds, readCommandIds }) process exited
|
|
23
|
+
* 'spawned' — process started successfully
|
|
24
|
+
* 'permission_request' — (req) the CLI is asking whether a tool call may run
|
|
25
|
+
* 'permission_cancelled' — ({ controlRequestId }) the CLI withdrew a pending ask
|
|
21
26
|
*/
|
|
27
|
+
const ASK_USER_QUESTION = 'AskUserQuestion';
|
|
28
|
+
|
|
22
29
|
class ClaudeProcess extends EventEmitter {
|
|
23
30
|
/**
|
|
24
31
|
* @param {string} sessionId - Logical session ID (from Rails or caller)
|
|
@@ -27,11 +34,11 @@ class ClaudeProcess extends EventEmitter {
|
|
|
27
34
|
* @param {string} [options.claudeSessionId] - UUID for --session-id flag
|
|
28
35
|
* @param {object} [options.logger] - Logger instance
|
|
29
36
|
* @param {string} [options.claudeCommand] - Path to claude binary
|
|
30
|
-
* @param {
|
|
37
|
+
* @param {string} [options.permissionMode] - Claude CLI permission mode (default 'auto')
|
|
31
38
|
* @param {Function} [options._spawnFn] - For testing: replacement for child_process.spawn
|
|
32
39
|
* @param {object} [options.sessionEnv] - Extra env vars to inject into the spawned process
|
|
33
40
|
* @param {string} [options.systemPrompt] - Appended to Claude's default system prompt at spawn time via --append-system-prompt
|
|
34
|
-
* @param {string} [options.model] - Claude model id passed to the CLI via --model (
|
|
41
|
+
* @param {string} [options.model] - Claude model id passed to the CLI via --model (the server always sends the session's stored model)
|
|
35
42
|
*/
|
|
36
43
|
constructor(sessionId, options = {}) {
|
|
37
44
|
super();
|
|
@@ -42,8 +49,7 @@ class ClaudeProcess extends EventEmitter {
|
|
|
42
49
|
this._workingDir = options.workingDir || process.cwd();
|
|
43
50
|
this._logger = options.logger || _defaultLogger();
|
|
44
51
|
this._claudeCommand = options.claudeCommand || 'claude';
|
|
45
|
-
this.
|
|
46
|
-
this._permissionPort = options.permissionPort || null;
|
|
52
|
+
this._permissionMode = options.permissionMode || 'auto';
|
|
47
53
|
this._spawnFn = options._spawnFn || defaultSpawn;
|
|
48
54
|
this._sessionEnv = options.sessionEnv || {};
|
|
49
55
|
this._systemPrompt = options.systemPrompt || null;
|
|
@@ -54,6 +60,21 @@ class ClaudeProcess extends EventEmitter {
|
|
|
54
60
|
this._child = null;
|
|
55
61
|
this._pid = null;
|
|
56
62
|
this._startedAt = null;
|
|
63
|
+
|
|
64
|
+
// Map of the CLI's control request_id -> the tool input it asked about.
|
|
65
|
+
// An allow response has to echo the input back as `updatedInput`.
|
|
66
|
+
this._pendingControl = new Map();
|
|
67
|
+
|
|
68
|
+
// #130: AskUserQuestion requests held open until Chris answers in
|
|
69
|
+
// FlightDeck. control request_id -> { toolUseId, input }. Never answered
|
|
70
|
+
// with deny: the CLI ends the turn on a deny and ignores a later allow.
|
|
71
|
+
this._heldQuestions = new Map();
|
|
72
|
+
// Requests already answered, so a repeat of the same answer (Rails sends
|
|
73
|
+
// it again when our ack got lost) is acknowledged without a second write.
|
|
74
|
+
this._answeredQuestions = new Set();
|
|
75
|
+
|
|
76
|
+
// #175: which command each stdout line belongs to.
|
|
77
|
+
this._turns = new TurnTracker();
|
|
57
78
|
}
|
|
58
79
|
|
|
59
80
|
// -------------------------------------------------------------------------
|
|
@@ -71,10 +92,7 @@ class ClaudeProcess extends EventEmitter {
|
|
|
71
92
|
|
|
72
93
|
this._state = 'spawning';
|
|
73
94
|
|
|
74
|
-
|
|
75
|
-
if (this._permissionPort && !this._skipPermissions) {
|
|
76
|
-
this._ensurePermissionHook();
|
|
77
|
-
}
|
|
95
|
+
this._removeLegacyPermissionHook();
|
|
78
96
|
|
|
79
97
|
const args = [
|
|
80
98
|
'--verbose',
|
|
@@ -104,15 +122,27 @@ class ClaudeProcess extends EventEmitter {
|
|
|
104
122
|
args.push('--append-system-prompt', this._systemPrompt);
|
|
105
123
|
}
|
|
106
124
|
|
|
107
|
-
|
|
125
|
+
args.push('--permission-mode', this._permissionMode);
|
|
126
|
+
|
|
127
|
+
// Deliver permission prompts to us as control requests on the stdout
|
|
128
|
+
// stream we already read, answered on the stdin we already write. Every
|
|
129
|
+
// mode needs it (#130): the CLI offers AskUserQuestion only when a run has
|
|
130
|
+
// a permission host, and FlightDeck turns that tool into Action Items.
|
|
131
|
+
args.push('--permission-prompt-tool', 'stdio');
|
|
132
|
+
|
|
133
|
+
if (this._permissionMode === 'bypassPermissions') {
|
|
134
|
+
// The mode alone is not enough: the CLI refuses to enter bypass without
|
|
135
|
+
// the explicit flag.
|
|
108
136
|
args.push('--dangerously-skip-permissions');
|
|
137
|
+
// A permission host also brings EnterPlanMode and ExitPlanMode, which a
|
|
138
|
+
// bypass run never had. Leave them out, so the only new tool in bypass
|
|
139
|
+
// is AskUserQuestion (#130, AC 1).
|
|
140
|
+
args.push('--disallowedTools', 'EnterPlanMode', 'ExitPlanMode');
|
|
109
141
|
}
|
|
110
142
|
|
|
111
143
|
const env = { ...process.env, ...this._sessionEnv, CLAUDE_SESSION_ID: this._sessionId };
|
|
112
|
-
if (this._permissionPort) {
|
|
113
|
-
env.CLAUDE_PERMISSION_PORT = String(this._permissionPort);
|
|
114
|
-
}
|
|
115
144
|
delete env.CLAUDECODE; // Prevent nested session detection
|
|
145
|
+
stripDaemonSecrets(env);
|
|
116
146
|
|
|
117
147
|
const opts = {
|
|
118
148
|
cwd: this._workingDir,
|
|
@@ -124,9 +154,20 @@ class ClaudeProcess extends EventEmitter {
|
|
|
124
154
|
sessionId: this._sessionId,
|
|
125
155
|
claudeSessionId: this._claudeSessionId,
|
|
126
156
|
cwd: this._workingDir,
|
|
157
|
+
permissionMode: this._permissionMode,
|
|
127
158
|
});
|
|
128
159
|
|
|
129
160
|
this._child = this._spawnFn(this._claudeCommand, args, opts);
|
|
161
|
+
|
|
162
|
+
// A child that dies mid-write turns the next stdin write into an EPIPE.
|
|
163
|
+
// Unhandled, a stream 'error' takes the whole daemon down with it, so every
|
|
164
|
+
// session dies because one CLI exited at the wrong moment.
|
|
165
|
+
if (this._child.stdin && typeof this._child.stdin.on === 'function') {
|
|
166
|
+
this._child.stdin.on('error', (err) => {
|
|
167
|
+
this._logger.warn('Claude stdin error', { pid: this._pid, error: err.message });
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
130
171
|
this._pid = this._child.pid;
|
|
131
172
|
this._startedAt = Date.now();
|
|
132
173
|
this._state = 'running';
|
|
@@ -141,31 +182,123 @@ class ClaudeProcess extends EventEmitter {
|
|
|
141
182
|
/**
|
|
142
183
|
* Send a user message to the Claude CLI stdin.
|
|
143
184
|
* @param {string} text - The message content
|
|
185
|
+
* @param {string|null} [commandId] - The Rails command it came from (#175)
|
|
144
186
|
* @returns {boolean} true if written, false if process not running
|
|
145
187
|
*/
|
|
146
|
-
sendMessage(text) {
|
|
188
|
+
sendMessage(text, commandId = null) {
|
|
147
189
|
if (this._state !== 'running' || !this._child) {
|
|
148
190
|
this._logger.warn('Cannot send message: process not running');
|
|
149
191
|
return false;
|
|
150
192
|
}
|
|
151
193
|
|
|
152
|
-
const
|
|
194
|
+
const written = this._writeLine({
|
|
153
195
|
type: 'user',
|
|
154
196
|
message: { role: 'user', content: text },
|
|
155
|
-
})
|
|
197
|
+
});
|
|
198
|
+
if (written > 0) this._turns.written(commandId, text);
|
|
199
|
+
this._logger.debug('Sent message to stdin', { length: written, commandId });
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Answer a permission prompt the CLI raised as a `can_use_tool` control request.
|
|
205
|
+
*
|
|
206
|
+
* @param {string} controlRequestId - request_id from the control request
|
|
207
|
+
* @param {string} decision - 'approve' or 'deny'
|
|
208
|
+
* @param {string} [reason] - Shown to Claude on denial
|
|
209
|
+
* @returns {boolean} true if the response was written
|
|
210
|
+
*/
|
|
211
|
+
respondToPermission(controlRequestId, decision, reason) {
|
|
212
|
+
const input = this._pendingControl.get(controlRequestId);
|
|
213
|
+
|
|
214
|
+
if (input === undefined) {
|
|
215
|
+
this._logger.warn('Permission response for unknown control request', { controlRequestId });
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
this._pendingControl.delete(controlRequestId);
|
|
220
|
+
|
|
221
|
+
if (this._state !== 'running' || !this._child) {
|
|
222
|
+
// The CLI is already gone; there is nobody left to tell.
|
|
223
|
+
this._logger.warn('Cannot answer permission: process not running', { controlRequestId });
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const response = decision === 'approve'
|
|
228
|
+
? { behavior: 'allow', updatedInput: input }
|
|
229
|
+
: { behavior: 'deny', message: reason || 'Denied by user via FlightDeck' };
|
|
230
|
+
|
|
231
|
+
this._writeLine({
|
|
232
|
+
type: 'control_response',
|
|
233
|
+
response: { subtype: 'success', request_id: controlRequestId, response },
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
this._logger.info('Answered permission request', { controlRequestId, decision });
|
|
237
|
+
return true;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* #130: answer a held AskUserQuestion. `answers` maps each question's text
|
|
242
|
+
* to the chosen label (comma-joined labels for a multi-select), or to a
|
|
243
|
+
* marked discussion note. Always an allow: the CLI turns it into the tool
|
|
244
|
+
* result the agent reads.
|
|
245
|
+
*
|
|
246
|
+
* @param {string} controlRequestId - request_id of the held request
|
|
247
|
+
* @param {Object<string,string>} answers
|
|
248
|
+
* @returns {boolean} true if the answer was written to the CLI
|
|
249
|
+
*/
|
|
250
|
+
answerQuestion(controlRequestId, answers) {
|
|
251
|
+
const held = this._heldQuestions.get(controlRequestId);
|
|
252
|
+
|
|
253
|
+
if (held === undefined) {
|
|
254
|
+
if (this._answeredQuestions.has(controlRequestId) && this._state === 'running') {
|
|
255
|
+
this._logger.info('AskUserQuestion already answered; acknowledging the repeat', { controlRequestId });
|
|
256
|
+
return true;
|
|
257
|
+
}
|
|
258
|
+
this._logger.warn('Answer for unknown AskUserQuestion request', { controlRequestId });
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (this._state !== 'running' || !this._child) {
|
|
263
|
+
this._logger.warn('Cannot answer AskUserQuestion: process not running', { controlRequestId });
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
this._heldQuestions.delete(controlRequestId);
|
|
268
|
+
this._answeredQuestions.add(controlRequestId);
|
|
269
|
+
this._writeLine({
|
|
270
|
+
type: 'control_response',
|
|
271
|
+
response: {
|
|
272
|
+
subtype: 'success',
|
|
273
|
+
request_id: controlRequestId,
|
|
274
|
+
response: { behavior: 'allow', updatedInput: { ...held.input, answers: { ...answers } } },
|
|
275
|
+
},
|
|
276
|
+
});
|
|
156
277
|
|
|
157
|
-
this.
|
|
158
|
-
this._logger.debug('Sent message to stdin', { length: payload.length });
|
|
278
|
+
this._logger.info('Answered AskUserQuestion', { controlRequestId, toolUseId: held.toolUseId });
|
|
159
279
|
return true;
|
|
160
280
|
}
|
|
161
281
|
|
|
282
|
+
/**
|
|
283
|
+
* #130: the AskUserQuestion requests this process still holds, so they can
|
|
284
|
+
* be reported again after FlightDeck reconnects.
|
|
285
|
+
* @returns {Array<{controlRequestId: string, toolUseId: string|null, questions: Array}>}
|
|
286
|
+
*/
|
|
287
|
+
heldQuestions() {
|
|
288
|
+
return Array.from(this._heldQuestions, ([controlRequestId, held]) => ({
|
|
289
|
+
controlRequestId,
|
|
290
|
+
toolUseId: held.toolUseId,
|
|
291
|
+
questions: Array.isArray(held.input.questions) ? held.input.questions : [],
|
|
292
|
+
}));
|
|
293
|
+
}
|
|
294
|
+
|
|
162
295
|
/**
|
|
163
296
|
* Send a slash command (e.g., /compact, /status).
|
|
164
297
|
* @param {string} command - The slash command string
|
|
165
298
|
* @returns {boolean} true if written
|
|
166
299
|
*/
|
|
167
|
-
sendSlashCommand(command) {
|
|
168
|
-
return this.sendMessage(command);
|
|
300
|
+
sendSlashCommand(command, commandId = null) {
|
|
301
|
+
return this.sendMessage(command, commandId);
|
|
169
302
|
}
|
|
170
303
|
|
|
171
304
|
/**
|
|
@@ -237,10 +370,13 @@ class ClaudeProcess extends EventEmitter {
|
|
|
237
370
|
*/
|
|
238
371
|
isAlive() {
|
|
239
372
|
if (!this._child || !this._pid) return false;
|
|
373
|
+
if (this._state === 'stopped') return false;
|
|
240
374
|
|
|
241
375
|
try {
|
|
242
|
-
|
|
243
|
-
|
|
376
|
+
// Signal 0 = check existence. Once the child has exited, Node returns
|
|
377
|
+
// false here instead of throwing; counting that as alive made
|
|
378
|
+
// getProcess() hand back a dead CLI and every command to it vanish.
|
|
379
|
+
return this._child.kill(0) !== false;
|
|
244
380
|
} catch (_) {
|
|
245
381
|
return false;
|
|
246
382
|
}
|
|
@@ -256,66 +392,111 @@ class ClaudeProcess extends EventEmitter {
|
|
|
256
392
|
get sessionId() { return this._sessionId; }
|
|
257
393
|
get startedAt() { return this._startedAt; }
|
|
258
394
|
get workingDir() { return this._workingDir; }
|
|
395
|
+
/** #175: the command the CLI read last, or undefined before it has read one. */
|
|
396
|
+
get currentCommandId() { return this._turns.currentCommandId; }
|
|
397
|
+
/** #175: commands written to this process that no result has ended yet. */
|
|
398
|
+
unfinishedCommandIds() { return this._turns.unfinishedCommandIds(); }
|
|
399
|
+
/** #224: the unfinished commands the CLI has taken. */
|
|
400
|
+
readCommandIds() { return this._turns.readCommandIds(); }
|
|
259
401
|
|
|
260
402
|
// -------------------------------------------------------------------------
|
|
261
403
|
// Internal
|
|
262
404
|
// -------------------------------------------------------------------------
|
|
263
405
|
|
|
264
406
|
/**
|
|
265
|
-
*
|
|
266
|
-
*
|
|
407
|
+
* Strip the `permission-gate.sh` PreToolUse hook that daemons <= 0.8.x wrote
|
|
408
|
+
* into the working repo's `.claude/settings.local.json`.
|
|
409
|
+
*
|
|
410
|
+
* The script ships no more, so leaving the entry behind means every tool call
|
|
411
|
+
* in that repo invokes a missing command. We only clean up our own litter —
|
|
412
|
+
* other people's hooks are left exactly as they are, and the file is only
|
|
413
|
+
* rewritten when something actually changed.
|
|
267
414
|
*/
|
|
268
|
-
|
|
269
|
-
const
|
|
415
|
+
_removeLegacyPermissionHook() {
|
|
416
|
+
const settingsPath = path.join(this._workingDir, '.claude', 'settings.local.json');
|
|
270
417
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
return;
|
|
418
|
+
let settings;
|
|
419
|
+
try {
|
|
420
|
+
settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
|
421
|
+
} catch (_) {
|
|
422
|
+
return; // No file, or not ours to parse
|
|
276
423
|
}
|
|
277
424
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
425
|
+
const entries = settings?.hooks?.PreToolUse;
|
|
426
|
+
if (!Array.isArray(entries)) return;
|
|
427
|
+
|
|
428
|
+
const isGateCommand = (cmd) => typeof cmd === 'string' && cmd.includes('permission-gate.sh');
|
|
429
|
+
|
|
430
|
+
const kept = [];
|
|
431
|
+
let changed = false;
|
|
432
|
+
|
|
433
|
+
for (const entry of entries) {
|
|
434
|
+
if (!entry || typeof entry !== 'object') {
|
|
435
|
+
kept.push(entry);
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// Daemons <= 0.8.0 wrote a top-level `command`; later ones used a nested
|
|
440
|
+
// `hooks` array. Both shapes are ours to remove.
|
|
441
|
+
if (isGateCommand(entry.command)) {
|
|
442
|
+
changed = true;
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
if (Array.isArray(entry.hooks)) {
|
|
447
|
+
const others = entry.hooks.filter((h) => !(h && isGateCommand(h.command)));
|
|
282
448
|
|
|
283
|
-
|
|
284
|
-
|
|
449
|
+
if (others.length !== entry.hooks.length) {
|
|
450
|
+
changed = true;
|
|
451
|
+
// An entry that held nothing but the gate goes with it.
|
|
452
|
+
if (others.length === 0) continue;
|
|
453
|
+
entry.hooks = others;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
285
456
|
|
|
286
|
-
|
|
287
|
-
if (!fs.existsSync(claudeDir)) {
|
|
288
|
-
fs.mkdirSync(claudeDir, { recursive: true });
|
|
457
|
+
kept.push(entry);
|
|
289
458
|
}
|
|
290
459
|
|
|
291
|
-
|
|
292
|
-
let settings = {};
|
|
293
|
-
try {
|
|
294
|
-
const raw = fs.readFileSync(settingsPath, 'utf8');
|
|
295
|
-
settings = JSON.parse(raw);
|
|
296
|
-
} catch (_) { /* file doesn't exist or isn't valid JSON */ }
|
|
297
|
-
|
|
298
|
-
// Ensure hooks.PreToolUse array exists
|
|
299
|
-
if (!settings.hooks) settings.hooks = {};
|
|
300
|
-
if (!Array.isArray(settings.hooks.PreToolUse)) settings.hooks.PreToolUse = [];
|
|
301
|
-
|
|
302
|
-
// Check if our hook is already registered (avoid duplicates)
|
|
303
|
-
const alreadyRegistered = settings.hooks.PreToolUse.some(
|
|
304
|
-
(h) => h.command && h.command.includes('permission-gate.sh')
|
|
305
|
-
);
|
|
306
|
-
|
|
307
|
-
if (!alreadyRegistered) {
|
|
308
|
-
settings.hooks.PreToolUse.push({
|
|
309
|
-
matcher: '',
|
|
310
|
-
command: hookScript,
|
|
311
|
-
});
|
|
460
|
+
if (!changed) return;
|
|
312
461
|
|
|
462
|
+
if (kept.length > 0) {
|
|
463
|
+
settings.hooks.PreToolUse = kept;
|
|
464
|
+
} else {
|
|
465
|
+
delete settings.hooks.PreToolUse;
|
|
466
|
+
if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
try {
|
|
313
470
|
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
|
|
314
|
-
this._logger.info('
|
|
471
|
+
this._logger.info('Removed legacy permission-gate hook from project settings', {
|
|
315
472
|
settingsPath,
|
|
316
|
-
hookScript,
|
|
317
473
|
});
|
|
474
|
+
} catch (err) {
|
|
475
|
+
this._logger.warn('Could not remove legacy permission-gate hook', {
|
|
476
|
+
settingsPath,
|
|
477
|
+
error: err.message,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Write one JSON line to the child's stdin.
|
|
484
|
+
* Callers rely on one line per call, in call order.
|
|
485
|
+
*
|
|
486
|
+
* @param {object} obj
|
|
487
|
+
* @returns {number} characters written, or 0 if the pipe rejected the write
|
|
488
|
+
*/
|
|
489
|
+
_writeLine(obj) {
|
|
490
|
+
const payload = JSON.stringify(obj) + '\n';
|
|
491
|
+
|
|
492
|
+
try {
|
|
493
|
+
this._child.stdin.write(payload);
|
|
494
|
+
} catch (err) {
|
|
495
|
+
this._logger.warn('Failed to write to Claude stdin', { error: err.message });
|
|
496
|
+
return 0;
|
|
318
497
|
}
|
|
498
|
+
|
|
499
|
+
return payload.length;
|
|
319
500
|
}
|
|
320
501
|
|
|
321
502
|
_setupStdout() {
|
|
@@ -327,13 +508,25 @@ class ClaudeProcess extends EventEmitter {
|
|
|
327
508
|
try {
|
|
328
509
|
const data = JSON.parse(line);
|
|
329
510
|
|
|
511
|
+
// Control requests are a side-channel between the CLI and us, not
|
|
512
|
+
// transcript content — answer them here instead of forwarding.
|
|
513
|
+
if (data.type === 'control_request') {
|
|
514
|
+
this._handleControlRequest(data);
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
if (data.type === 'control_cancel_request') {
|
|
519
|
+
this._handleControlCancel(data);
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
|
|
330
523
|
// Flag oversized lines for the transport layer
|
|
331
524
|
if (line.length > MAX_CHUNK_SIZE) {
|
|
332
525
|
data._oversized = true;
|
|
333
526
|
data._originalSize = line.length;
|
|
334
527
|
}
|
|
335
528
|
|
|
336
|
-
this.emit('output', data);
|
|
529
|
+
this.emit('output', data, this._turns.observe(data));
|
|
337
530
|
} catch (_) {
|
|
338
531
|
// Not valid JSON — emit as error
|
|
339
532
|
this._logger.warn('Unparseable stdout line', { line: line.slice(0, 200) });
|
|
@@ -342,6 +535,87 @@ class ClaudeProcess extends EventEmitter {
|
|
|
342
535
|
});
|
|
343
536
|
}
|
|
344
537
|
|
|
538
|
+
/**
|
|
539
|
+
* Dispatch a control request from the CLI.
|
|
540
|
+
*
|
|
541
|
+
* `can_use_tool` is the permission prompt — the only subtype we serve. Every
|
|
542
|
+
* other subtype gets an error response rather than silence, because the CLI
|
|
543
|
+
* blocks until it hears something back.
|
|
544
|
+
*/
|
|
545
|
+
_handleControlRequest(data) {
|
|
546
|
+
const controlRequestId = data.request_id;
|
|
547
|
+
const request = data.request || {};
|
|
548
|
+
|
|
549
|
+
if (request.subtype !== 'can_use_tool') {
|
|
550
|
+
this._logger.warn('Unsupported control request subtype', {
|
|
551
|
+
controlRequestId,
|
|
552
|
+
subtype: request.subtype,
|
|
553
|
+
});
|
|
554
|
+
this._writeControlError(controlRequestId, `Unsupported control request subtype: ${request.subtype}`);
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const toolInput = request.input || {};
|
|
559
|
+
|
|
560
|
+
// #130: an agent's question to Chris. Hold it open and report it; the
|
|
561
|
+
// answer comes back through answerQuestion(). Not a permission prompt.
|
|
562
|
+
if (request.tool_name === ASK_USER_QUESTION) {
|
|
563
|
+
this._heldQuestions.set(controlRequestId, { toolUseId: request.tool_use_id || null, input: toolInput });
|
|
564
|
+
this._logger.info('Holding AskUserQuestion for FlightDeck', { controlRequestId, toolUseId: request.tool_use_id });
|
|
565
|
+
this.emit('ask_user_question', {
|
|
566
|
+
controlRequestId,
|
|
567
|
+
toolUseId: request.tool_use_id || null,
|
|
568
|
+
questions: Array.isArray(toolInput.questions) ? toolInput.questions : [],
|
|
569
|
+
});
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// Bypass mode never asked before #130 added the permission host. Anything
|
|
574
|
+
// but AskUserQuestion is allowed at once, so a bypass run behaves exactly
|
|
575
|
+
// as it did (AC 1 found only ExitPlanMode, which the flags now leave out).
|
|
576
|
+
if (this._permissionMode === 'bypassPermissions') {
|
|
577
|
+
this._logger.info('Auto-allowing tool in bypass mode', { controlRequestId, toolName: request.tool_name });
|
|
578
|
+
this._writeLine({
|
|
579
|
+
type: 'control_response',
|
|
580
|
+
response: { subtype: 'success', request_id: controlRequestId, response: { behavior: 'allow', updatedInput: toolInput } },
|
|
581
|
+
});
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
this._pendingControl.set(controlRequestId, toolInput);
|
|
586
|
+
|
|
587
|
+
this.emit('permission_request', {
|
|
588
|
+
controlRequestId,
|
|
589
|
+
toolName: request.tool_name || 'unknown',
|
|
590
|
+
toolInput,
|
|
591
|
+
description: request.description || null,
|
|
592
|
+
decisionReasonType: request.decision_reason_type || null,
|
|
593
|
+
toolUseId: request.tool_use_id || null,
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* The CLI withdrew a prompt it had raised (e.g. the turn was interrupted).
|
|
599
|
+
*/
|
|
600
|
+
_handleControlCancel(data) {
|
|
601
|
+
const controlRequestId = data.request_id;
|
|
602
|
+
|
|
603
|
+
if (this._releaseQuestion(controlRequestId, 'cancelled')) return;
|
|
604
|
+
if (!this._pendingControl.delete(controlRequestId)) return;
|
|
605
|
+
|
|
606
|
+
this._logger.info('Permission request cancelled by CLI', { controlRequestId });
|
|
607
|
+
this.emit('permission_cancelled', { controlRequestId });
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
_writeControlError(controlRequestId, message) {
|
|
611
|
+
if (this._state !== 'running' || !this._child) return;
|
|
612
|
+
|
|
613
|
+
this._writeLine({
|
|
614
|
+
type: 'control_response',
|
|
615
|
+
response: { subtype: 'error', request_id: controlRequestId, error: message },
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
|
|
345
619
|
_setupStderr() {
|
|
346
620
|
const rl = createInterface({ input: this._child.stderr });
|
|
347
621
|
|
|
@@ -357,10 +631,29 @@ class ClaudeProcess extends EventEmitter {
|
|
|
357
631
|
this._child.on('close', (code, signal) => {
|
|
358
632
|
this._logger.info('Claude process exited', { code, signal, pid: this._pid });
|
|
359
633
|
this._state = 'stopped';
|
|
360
|
-
this.
|
|
634
|
+
for (const controlRequestId of Array.from(this._heldQuestions.keys())) {
|
|
635
|
+
this._releaseQuestion(controlRequestId, 'exited');
|
|
636
|
+
}
|
|
637
|
+
this.emit('exit', code, signal, {
|
|
638
|
+
commandId: this._turns.newestWrittenCommandId,
|
|
639
|
+
unfinishedCommandIds: this._turns.unfinishedCommandIds(),
|
|
640
|
+
readCommandIds: this._turns.readCommandIds(),
|
|
641
|
+
});
|
|
361
642
|
});
|
|
362
643
|
}
|
|
363
644
|
|
|
645
|
+
// A held AskUserQuestion can no longer be answered here (the CLI withdrew
|
|
646
|
+
// it, or the process ended). FlightDeck then delivers the answer as text.
|
|
647
|
+
_releaseQuestion(controlRequestId, reason) {
|
|
648
|
+
const held = this._heldQuestions.get(controlRequestId);
|
|
649
|
+
if (!held) return false;
|
|
650
|
+
|
|
651
|
+
this._heldQuestions.delete(controlRequestId);
|
|
652
|
+
this._logger.info('Released AskUserQuestion', { controlRequestId, reason });
|
|
653
|
+
this.emit('ask_user_question_released', { controlRequestId, toolUseId: held.toolUseId, reason });
|
|
654
|
+
return true;
|
|
655
|
+
}
|
|
656
|
+
|
|
364
657
|
/**
|
|
365
658
|
* Wait for the child process to emit 'close', up to timeoutMs.
|
|
366
659
|
* @param {number} timeoutMs
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The account usage a CLI `rate_limit_event` carries, in the heartbeat's
|
|
5
|
+
* `claude_usage` shape (#258):
|
|
6
|
+
*
|
|
7
|
+
* { five_hour: {utilization, resets_at}, seven_day: {utilization, resets_at}, observed_at }
|
|
8
|
+
*
|
|
9
|
+
* The CLI copies `rate_limit_info.unifiedWindows` from the
|
|
10
|
+
* `anthropic-ratelimit-unified-*` response headers, so only subscription
|
|
11
|
+
* (OAuth) logins have it. `utilization` is the fraction of the window used
|
|
12
|
+
* and can pass 1; `resets_at` is unix seconds, as the CLI sends it.
|
|
13
|
+
*
|
|
14
|
+
* `unifiedWindows` is marked internal in the CLI's SDK schema, so a missing
|
|
15
|
+
* or malformed field returns null and the caller keeps its last reading. A
|
|
16
|
+
* window the event leaves out keeps its value from `previous`.
|
|
17
|
+
*
|
|
18
|
+
* @param {object} event - A parsed stream-json line of type rate_limit_event.
|
|
19
|
+
* @param {object|null} [previous] - The last reading this returned.
|
|
20
|
+
* @param {Date} [now] - When the daemon saw the event.
|
|
21
|
+
* @returns {object|null}
|
|
22
|
+
*/
|
|
23
|
+
function usageFromRateLimitEvent(event, previous = null, now = new Date()) {
|
|
24
|
+
const unified = event?.rate_limit_info?.unifiedWindows;
|
|
25
|
+
if (!unified || typeof unified !== 'object') return null;
|
|
26
|
+
|
|
27
|
+
const fiveHour = readWindow(unified.five_hour);
|
|
28
|
+
const sevenDay = readWindow(unified.seven_day);
|
|
29
|
+
if (!fiveHour && !sevenDay) return null;
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
five_hour: fiveHour || previous?.five_hour || null,
|
|
33
|
+
seven_day: sevenDay || previous?.seven_day || null,
|
|
34
|
+
observed_at: now.toISOString(),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function readWindow(window) {
|
|
39
|
+
if (!window || !Number.isFinite(window.utilization)) return null;
|
|
40
|
+
return {
|
|
41
|
+
utilization: window.utilization,
|
|
42
|
+
resets_at: Number.isFinite(window.resetsAt) ? window.resetsAt : null,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
module.exports = { usageFromRateLimitEvent };
|