@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.
- package/Dockerfile +5 -2
- package/README.md +17 -4
- package/package.json +1 -2
- package/src/claude-process.js +357 -104
- 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 +577 -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 +106 -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/fs-bridge.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const fs = require('node:fs').promises;
|
|
4
4
|
const path = require('node:path');
|
|
5
|
+
const { spawn } = require('node:child_process');
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Generalized filesystem RPC for the daemon<->Rails bridge (fs_request /
|
|
@@ -266,6 +267,104 @@ async function handleListRequest(requestedPath, workingDir) {
|
|
|
266
267
|
return { op: 'list', path: requestedPath, exists: true, entries };
|
|
267
268
|
}
|
|
268
269
|
|
|
270
|
+
/**
|
|
271
|
+
* True only for an ordinary folder, the one case `open` may run on without
|
|
272
|
+
* `-R`. macOS treats a bundle (`Evil.app`, `.workflow`, `.prefPane`, …) as
|
|
273
|
+
* a directory to fs.stat, but plain `open` on it launches or installs it.
|
|
274
|
+
* So a directory with any extension, or one holding `Contents/Info.plist`
|
|
275
|
+
* (a bundle without the usual extension), is revealed with `-R` instead.
|
|
276
|
+
*
|
|
277
|
+
* @param {string} realPath
|
|
278
|
+
* @param {import('node:fs').Stats} stats
|
|
279
|
+
* @returns {Promise<boolean>}
|
|
280
|
+
*/
|
|
281
|
+
async function isPlainFolder(realPath, stats) {
|
|
282
|
+
if (!stats.isDirectory()) return false;
|
|
283
|
+
if (path.extname(realPath) !== '') return false;
|
|
284
|
+
try {
|
|
285
|
+
await fs.access(path.join(realPath, 'Contents', 'Info.plist'));
|
|
286
|
+
return false;
|
|
287
|
+
} catch {
|
|
288
|
+
return true;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Reveal in Finder (`op: "reveal"`, backlog #286). Rails sends the path an
|
|
294
|
+
* agent registered — an artifact's original file, or a reveal_link — and
|
|
295
|
+
* this runs `open -R <path>` for a file (Finder opens its folder with the
|
|
296
|
+
* file selected) or `open <path>` for a plain folder. Anything else that
|
|
297
|
+
* is a directory to fs.stat, such as an app bundle, gets `-R` too, so a
|
|
298
|
+
* click can never launch it (isPlainFolder).
|
|
299
|
+
*
|
|
300
|
+
* Unlike stat/read/list there is no containment root: decision #219 lets
|
|
301
|
+
* an agent point at any path on its Mac, and the browser never sends a
|
|
302
|
+
* path (Rails looks it up by token). What stays strict is the shape: the
|
|
303
|
+
* path must be an absolute string with no NUL byte, it is resolved through
|
|
304
|
+
* fs.realpath, and `open` runs through spawn with an argument array, never
|
|
305
|
+
* a shell, so nothing in the path is ever interpreted.
|
|
306
|
+
*
|
|
307
|
+
* A path that doesn't exist is a normal answer ({ exists: false }), which
|
|
308
|
+
* Rails shows as "Not found on <machine>".
|
|
309
|
+
*
|
|
310
|
+
* @param {*} requestedPath
|
|
311
|
+
* @param {{ spawnFn?: Function, platform?: string }} [opts] - test seams
|
|
312
|
+
* @returns {Promise<object>} { op, path, exists, mode? , error? }
|
|
313
|
+
*/
|
|
314
|
+
async function handleRevealRequest(requestedPath, opts) {
|
|
315
|
+
const spawnFn = (opts && opts.spawnFn) || spawn;
|
|
316
|
+
const platform = (opts && opts.platform) || process.platform;
|
|
317
|
+
const fail = (error) => ({ op: 'reveal', path: requestedPath, error });
|
|
318
|
+
|
|
319
|
+
if (typeof requestedPath !== 'string' || requestedPath.length === 0) {
|
|
320
|
+
return fail('Path must be a non-empty string');
|
|
321
|
+
}
|
|
322
|
+
if (requestedPath.includes('\0')) return fail('Access denied: path contains a NUL byte');
|
|
323
|
+
if (!path.isAbsolute(requestedPath)) return fail('Path must be absolute');
|
|
324
|
+
if (platform !== 'darwin') return fail('Reveal in Finder only works on macOS');
|
|
325
|
+
|
|
326
|
+
let realPath;
|
|
327
|
+
let stats;
|
|
328
|
+
try {
|
|
329
|
+
realPath = await fs.realpath(requestedPath);
|
|
330
|
+
stats = await fs.stat(realPath);
|
|
331
|
+
} catch (err) {
|
|
332
|
+
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
|
|
333
|
+
return { op: 'reveal', path: requestedPath, exists: false };
|
|
334
|
+
}
|
|
335
|
+
return fail(`Failed to resolve path: ${err.message}`);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const mode = (await isPlainFolder(realPath, stats)) ? 'open' : 'select';
|
|
339
|
+
const args = mode === 'open' ? [realPath] : ['-R', realPath];
|
|
340
|
+
|
|
341
|
+
return new Promise((resolve) => {
|
|
342
|
+
let settled = false;
|
|
343
|
+
const finish = (result) => {
|
|
344
|
+
if (settled) return;
|
|
345
|
+
settled = true;
|
|
346
|
+
resolve(result);
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
let child;
|
|
350
|
+
try {
|
|
351
|
+
child = spawnFn('open', args, { stdio: 'ignore' });
|
|
352
|
+
} catch (err) {
|
|
353
|
+
finish(fail(`Failed to run open: ${err.message}`));
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
child.on('error', (err) => finish(fail(`Failed to run open: ${err.message}`)));
|
|
358
|
+
child.on('exit', (code) => {
|
|
359
|
+
if (code === 0) {
|
|
360
|
+
finish({ op: 'reveal', path: requestedPath, exists: true, mode });
|
|
361
|
+
} else {
|
|
362
|
+
finish(fail(`open exited with code ${code}`));
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
|
|
269
368
|
/**
|
|
270
369
|
* Handle a single fs_request end-to-end and return the response payload
|
|
271
370
|
* fields (everything an fs_response carries EXCEPT `type`, `request_id`,
|
|
@@ -285,6 +384,12 @@ async function handleFsRequest(message, opts) {
|
|
|
285
384
|
|
|
286
385
|
const fail = (error) => ({ op, path: requestedPath, error });
|
|
287
386
|
|
|
387
|
+
// Reveal has its own rules (absolute path, no containment root); see
|
|
388
|
+
// handleRevealRequest above.
|
|
389
|
+
if (op === 'reveal') {
|
|
390
|
+
return handleRevealRequest(requestedPath, opts);
|
|
391
|
+
}
|
|
392
|
+
|
|
288
393
|
if (op !== 'stat' && op !== 'read' && op !== 'list') {
|
|
289
394
|
return fail(`Unsupported operation: "${op}"`);
|
|
290
395
|
}
|
|
@@ -371,4 +476,5 @@ module.exports = {
|
|
|
371
476
|
isPathContained,
|
|
372
477
|
resolveContained,
|
|
373
478
|
handleFsRequest,
|
|
479
|
+
handleRevealRequest,
|
|
374
480
|
};
|
package/src/harness.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The harness contract (#480).
|
|
5
|
+
*
|
|
6
|
+
* A "harness" is the daemon-side wrapper around one vendor CLI, one long-lived
|
|
7
|
+
* child per FlightDeck chat. The daemon holds a pool of them and speaks only
|
|
8
|
+
* this contract, so Claude, Codex and (#481) Gemini ACP plug in the same way.
|
|
9
|
+
*
|
|
10
|
+
* Every harness is an EventEmitter that writes Claude stream-json events,
|
|
11
|
+
* because that is the shape Rails, TurnTracker and terminal_controller.js
|
|
12
|
+
* already read: `system/init` when a turn starts, a `user` line with
|
|
13
|
+
* `isReplay: true` echoing the message it took, `assistant` lines with
|
|
14
|
+
* `text` / `thinking` / `tool_use` blocks, `user` lines with `tool_result`
|
|
15
|
+
* blocks, and one top-level `result` when the turn ends. A harness for another
|
|
16
|
+
* vendor translates its own protocol into those lines.
|
|
17
|
+
*
|
|
18
|
+
* Methods:
|
|
19
|
+
* spawn() start the child; throws unless idle
|
|
20
|
+
* sendMessage(text, commandId) hand the child a user message; false if it is not running
|
|
21
|
+
* interrupt() stop the running turn, keep the process and the conversation
|
|
22
|
+
* kill(timeoutMs) graceful stop (Promise); the conversation stays resumable
|
|
23
|
+
* isAlive() the OS process is still up
|
|
24
|
+
* Resume: constructor options `{ resume: true, claudeSessionId }` reattach the
|
|
25
|
+
* vendor conversation `claudeSessionId` names. After spawn, the same getter
|
|
26
|
+
* returns the id the daemon must store to resume later (a Claude CLI session
|
|
27
|
+
* uuid, a Codex thread id, a Gemini session id). A harness that learns the id
|
|
28
|
+
* asynchronously also defines `ready()` (Promise); the daemon awaits it
|
|
29
|
+
* before it reads the id.
|
|
30
|
+
* Getters: pid, state, sessionId, claudeSessionId, startedAt, workingDir,
|
|
31
|
+
* currentCommandId; plus unfinishedCommandIds() and readCommandIds().
|
|
32
|
+
* Events: 'output' (data, tag), 'error' (line), 'stderr' (line), 'exit'
|
|
33
|
+
* (code, signal, turns), 'spawned'. Optional: 'permission_request',
|
|
34
|
+
* 'permission_cancelled', 'ask_user_question', 'ask_user_question_released'
|
|
35
|
+
* with respondToPermission / answerQuestion / heldQuestions.
|
|
36
|
+
*/
|
|
37
|
+
const HARNESS_CONTRACT = Object.freeze({
|
|
38
|
+
methods: ['spawn', 'sendMessage', 'interrupt', 'kill', 'isAlive', 'unfinishedCommandIds', 'readCommandIds', 'on', 'emit'],
|
|
39
|
+
getters: ['pid', 'state', 'sessionId', 'claudeSessionId', 'startedAt', 'workingDir', 'currentCommandId'],
|
|
40
|
+
events: ['output', 'error', 'stderr', 'exit', 'spawned'],
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Model ids that belong to Codex. `codex app-server`'s model/list on 0.162.1
|
|
45
|
+
* returns gpt-6.1-sol, gpt-6-astra, gpt-6-sol, gpt-6-luna, gpt-5.6-sol,
|
|
46
|
+
* gpt-5.6-terra and gpt-5.6-luna (plus hidden gpt-reserve and
|
|
47
|
+
* codex-auto-review). Matching by family prefix keeps a new model id working
|
|
48
|
+
* without a daemon release.
|
|
49
|
+
*/
|
|
50
|
+
const CODEX_MODEL_PATTERN = /^(gpt-|o\d|codex)/i;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The daemon's own credentials, which no chat may see (#482). Every harness
|
|
54
|
+
* builds its child's env from the daemon's, so without this a chat that runs
|
|
55
|
+
* `env` could read them.
|
|
56
|
+
*
|
|
57
|
+
* CLAUDE_AUTH_TOKEN is the pilot's token: the daemon's ActionCable link to
|
|
58
|
+
* FlightDeck (and the standalone server's shared secret). Holding it is enough
|
|
59
|
+
* to connect as the pilot. The daemon reads it once, at start, into its frozen
|
|
60
|
+
* config, so a chat never needs it. The pilot id, Rails URL and other
|
|
61
|
+
* CLAUDE_* settings are not secrets. Vendor API keys belong to the auth-mode
|
|
62
|
+
* switches (#480), and RAD_TOKEN / MCP_AUTH_TOKEN are what a chat's rad MCP
|
|
63
|
+
* server signs in with, so they stay.
|
|
64
|
+
*/
|
|
65
|
+
const DAEMON_SECRET_ENV_VARS = Object.freeze(['CLAUDE_AUTH_TOKEN']);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Remove the daemon's own credentials from a chat's env. Mutates and returns
|
|
69
|
+
* `env`, which must be the child's own copy, never process.env.
|
|
70
|
+
*
|
|
71
|
+
* @param {object} env
|
|
72
|
+
* @returns {object} env
|
|
73
|
+
*/
|
|
74
|
+
function stripDaemonSecrets(env) {
|
|
75
|
+
for (const name of DAEMON_SECRET_ENV_VARS) delete env[name];
|
|
76
|
+
return env;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Which harness runs a model id. Anything that is not a Codex model id
|
|
81
|
+
* (including no model at all) runs on Claude, as before #480.
|
|
82
|
+
*
|
|
83
|
+
* @param {string|null|undefined} model
|
|
84
|
+
* @returns {'claude'|'codex'}
|
|
85
|
+
*/
|
|
86
|
+
function harnessNameForModel(model) {
|
|
87
|
+
return typeof model === 'string' && CODEX_MODEL_PATTERN.test(model.trim()) ? 'codex' : 'claude';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Names the contract members `proc` does not provide. Empty means it conforms.
|
|
92
|
+
* @param {object} proc
|
|
93
|
+
* @returns {string[]}
|
|
94
|
+
*/
|
|
95
|
+
function missingFromContract(proc) {
|
|
96
|
+
const missing = [];
|
|
97
|
+
for (const name of HARNESS_CONTRACT.methods) {
|
|
98
|
+
if (typeof proc[name] !== 'function') missing.push(`${name}()`);
|
|
99
|
+
}
|
|
100
|
+
for (const name of HARNESS_CONTRACT.getters) {
|
|
101
|
+
if (!(name in proc)) missing.push(name);
|
|
102
|
+
}
|
|
103
|
+
return missing;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Build the harness for a spawn. Required lazily so a Claude-only daemon never
|
|
108
|
+
* loads the Codex wrapper.
|
|
109
|
+
*
|
|
110
|
+
* @param {string} sessionId
|
|
111
|
+
* @param {object} options - the ClaudeProcess options, plus `codexCommand`
|
|
112
|
+
* @returns {object} an unspawned harness
|
|
113
|
+
*/
|
|
114
|
+
function createHarnessProcess(sessionId, options = {}) {
|
|
115
|
+
if (harnessNameForModel(options.model) === 'codex') {
|
|
116
|
+
const CodexProcess = require('./codex-process');
|
|
117
|
+
return new CodexProcess(sessionId, options);
|
|
118
|
+
}
|
|
119
|
+
const ClaudeProcess = require('./claude-process');
|
|
120
|
+
return new ClaudeProcess(sessionId, options);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
module.exports = {
|
|
124
|
+
HARNESS_CONTRACT,
|
|
125
|
+
CODEX_MODEL_PATTERN,
|
|
126
|
+
DAEMON_SECRET_ENV_VARS,
|
|
127
|
+
stripDaemonSecrets,
|
|
128
|
+
harnessNameForModel,
|
|
129
|
+
missingFromContract,
|
|
130
|
+
createHarnessProcess,
|
|
131
|
+
};
|
package/src/index.js
CHANGED
|
@@ -19,8 +19,13 @@ function main() {
|
|
|
19
19
|
mode: config.mode,
|
|
20
20
|
maxSessions: config.maxSessions,
|
|
21
21
|
workingDir: config.workingDir,
|
|
22
|
+
permissionMode: config.permissionMode,
|
|
22
23
|
});
|
|
23
24
|
|
|
25
|
+
for (const warning of config.permissionWarnings) {
|
|
26
|
+
logger.warn(warning);
|
|
27
|
+
}
|
|
28
|
+
|
|
24
29
|
const daemon = new Daemon(config, logger);
|
|
25
30
|
daemon.start();
|
|
26
31
|
|
|
@@ -39,24 +44,21 @@ function main() {
|
|
|
39
44
|
|
|
40
45
|
const client = new ActionCableClient(daemon, config, logger);
|
|
41
46
|
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
timeout: config.permissionTimeout,
|
|
48
|
-
|
|
47
|
+
// Hold escalated permission prompts until an operator answers in FlightDeck.
|
|
48
|
+
// Pointless in bypass mode, where the CLI never asks.
|
|
49
|
+
if (config.permissionMode !== 'bypassPermissions') {
|
|
50
|
+
const { PermissionBroker } = require('./permission-broker');
|
|
51
|
+
const broker = new PermissionBroker(
|
|
52
|
+
{ timeout: config.permissionTimeout },
|
|
53
|
+
createLogger({ level: config.logLevel, module: 'PermissionBroker' })
|
|
54
|
+
);
|
|
49
55
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
// Make port available to Claude CLI hook scripts
|
|
55
|
-
daemon._permissionPort = port;
|
|
56
|
-
});
|
|
56
|
+
daemon.setPermissionBroker(broker);
|
|
57
|
+
client.setPermissionBroker(broker);
|
|
58
|
+
logger.info('Permission broker ready', { timeout: config.permissionTimeout });
|
|
57
59
|
|
|
58
60
|
daemon.on('stopped', () => {
|
|
59
|
-
|
|
61
|
+
broker.stop();
|
|
60
62
|
});
|
|
61
63
|
}
|
|
62
64
|
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { randomUUID } = require('node:crypto');
|
|
4
|
+
const { EventEmitter } = require('node:events');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Holds permission prompts raised by Claude CLI sessions until an operator
|
|
8
|
+
* answers in FlightDeck, or the timeout expires.
|
|
9
|
+
*
|
|
10
|
+
* The CLI delivers prompts as `can_use_tool` control requests on the session's
|
|
11
|
+
* stdout stream (see ClaudeProcess); the broker owns the waiting, the timeout
|
|
12
|
+
* and the request-id namespace Rails sees, and knows nothing about which
|
|
13
|
+
* transport carried the prompt in.
|
|
14
|
+
*
|
|
15
|
+
* Emits:
|
|
16
|
+
* 'permission_request' — { requestId, sessionId, toolName, toolInput, filePath,
|
|
17
|
+
* description, riskLevel, decisionReasonType, timeoutSeconds }
|
|
18
|
+
* 'permission_timeout' — { requestId, sessionId }
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* const broker = new PermissionBroker({ timeout: 600 }, logger);
|
|
22
|
+
* broker.on('permission_request', (req) => forwardToRails(req));
|
|
23
|
+
* const requestId = broker.register(req, (decision, reason) => proc.respondToPermission(...));
|
|
24
|
+
* // Later, when the operator responds:
|
|
25
|
+
* broker.resolve(requestId, 'approve');
|
|
26
|
+
*/
|
|
27
|
+
class PermissionBroker extends EventEmitter {
|
|
28
|
+
/**
|
|
29
|
+
* @param {object} config
|
|
30
|
+
* @param {number} [config.timeout=600] - Seconds before a prompt auto-denies
|
|
31
|
+
* @param {object} logger
|
|
32
|
+
*/
|
|
33
|
+
constructor(config = {}, logger) {
|
|
34
|
+
super();
|
|
35
|
+
// `?? 600`, not `|| 600` — a caller that means "no wait" gets what it asked
|
|
36
|
+
// for rather than silently inheriting the ten-minute default.
|
|
37
|
+
this._defaultTimeout = config.timeout ?? 600;
|
|
38
|
+
this._logger = logger;
|
|
39
|
+
|
|
40
|
+
// Map of requestId -> { timer, sessionId, controlRequestId, respond }
|
|
41
|
+
this._pending = new Map();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Register a prompt and start its clock.
|
|
46
|
+
*
|
|
47
|
+
* @param {object} req - From ClaudeProcess's 'permission_request' event, plus sessionId
|
|
48
|
+
* @param {Function} respond - (decision, reason) => void; answers the owning CLI
|
|
49
|
+
* @returns {string} The request id Rails and the browser will use
|
|
50
|
+
*/
|
|
51
|
+
register(req, respond) {
|
|
52
|
+
const requestId = `perm_${randomUUID().slice(0, 12)}`;
|
|
53
|
+
const sessionId = req.sessionId || 'unknown';
|
|
54
|
+
const toolName = req.toolName || 'unknown';
|
|
55
|
+
const toolInput = req.toolInput || {};
|
|
56
|
+
const filePath = this._extractFilePath(toolName, toolInput);
|
|
57
|
+
const description = req.description || this._buildDescription(toolName, toolInput);
|
|
58
|
+
const riskLevel = this._classifyRisk(toolName);
|
|
59
|
+
const timeoutSeconds = this._defaultTimeout;
|
|
60
|
+
|
|
61
|
+
this._logger.info('Permission request received', { requestId, sessionId, toolName, riskLevel });
|
|
62
|
+
|
|
63
|
+
const timer = setTimeout(() => {
|
|
64
|
+
this._logger.warn('Permission request timed out', { requestId });
|
|
65
|
+
this._pending.delete(requestId);
|
|
66
|
+
respond('deny', 'Timed out waiting for approval');
|
|
67
|
+
this.emit('permission_timeout', { requestId, sessionId });
|
|
68
|
+
}, timeoutSeconds * 1000);
|
|
69
|
+
|
|
70
|
+
this._pending.set(requestId, {
|
|
71
|
+
timer,
|
|
72
|
+
sessionId,
|
|
73
|
+
controlRequestId: req.controlRequestId || null,
|
|
74
|
+
respond,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
this.emit('permission_request', {
|
|
78
|
+
requestId,
|
|
79
|
+
sessionId,
|
|
80
|
+
toolName,
|
|
81
|
+
toolInput,
|
|
82
|
+
filePath,
|
|
83
|
+
description,
|
|
84
|
+
riskLevel,
|
|
85
|
+
decisionReasonType: req.decisionReasonType || null,
|
|
86
|
+
timeoutSeconds,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
return requestId;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Resolve a pending permission request.
|
|
94
|
+
* @param {string} requestId
|
|
95
|
+
* @param {string} decision - 'approve' or 'deny'
|
|
96
|
+
* @param {string} [reason] - Optional reason for denial
|
|
97
|
+
*/
|
|
98
|
+
resolve(requestId, decision, reason) {
|
|
99
|
+
const pending = this._take(requestId);
|
|
100
|
+
if (!pending) {
|
|
101
|
+
this._logger.warn('Permission response for unknown request', { requestId });
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
this._logger.info('Permission resolved', { requestId, decision });
|
|
106
|
+
pending.respond(decision, reason);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Drop a pending request without answering the CLI — for prompts the CLI has
|
|
111
|
+
* already withdrawn, or whose session died. Tells FlightDeck to clear the
|
|
112
|
+
* dialog, which would otherwise sit there until its own countdown ran out.
|
|
113
|
+
*
|
|
114
|
+
* @param {string} requestId
|
|
115
|
+
* @param {string} [reason]
|
|
116
|
+
*/
|
|
117
|
+
cancel(requestId, reason) {
|
|
118
|
+
const pending = this._take(requestId);
|
|
119
|
+
if (!pending) return;
|
|
120
|
+
|
|
121
|
+
this._logger.info('Permission request cancelled', { requestId, reason });
|
|
122
|
+
this.emit('permission_timeout', { requestId, sessionId: pending.sessionId });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Cancel every pending request a session raised (e.g. its process exited).
|
|
127
|
+
* @param {string} sessionId
|
|
128
|
+
* @param {string} [reason]
|
|
129
|
+
*/
|
|
130
|
+
denyAllForSession(sessionId, reason = 'Session disconnected') {
|
|
131
|
+
for (const requestId of [...this._pending.keys()]) {
|
|
132
|
+
if (this._pending.get(requestId)?.sessionId === sessionId) {
|
|
133
|
+
this._deny(requestId, reason);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Find the request id a session raised for a given CLI control request.
|
|
140
|
+
* @param {string} sessionId
|
|
141
|
+
* @param {string} controlRequestId
|
|
142
|
+
* @returns {string|null}
|
|
143
|
+
*/
|
|
144
|
+
findByControlRequestId(sessionId, controlRequestId) {
|
|
145
|
+
for (const [requestId, pending] of this._pending) {
|
|
146
|
+
if (pending.sessionId === sessionId && pending.controlRequestId === controlRequestId) {
|
|
147
|
+
return requestId;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Deny everything pending — daemon shutdown.
|
|
155
|
+
*/
|
|
156
|
+
stop() {
|
|
157
|
+
for (const requestId of [...this._pending.keys()]) {
|
|
158
|
+
this._deny(requestId, 'Daemon shutting down');
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Number of pending requests. */
|
|
163
|
+
get pendingCount() {
|
|
164
|
+
return this._pending.size;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ---------------------------------------------------------------------------
|
|
168
|
+
// Internal
|
|
169
|
+
// ---------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Deny a pending request and tell FlightDeck to clear its dialog.
|
|
173
|
+
* The CLI may already be gone, in which case respond() is a no-op.
|
|
174
|
+
*/
|
|
175
|
+
_deny(requestId, reason) {
|
|
176
|
+
const pending = this._take(requestId);
|
|
177
|
+
if (!pending) return;
|
|
178
|
+
|
|
179
|
+
this._logger.info('Permission denied', { requestId, reason });
|
|
180
|
+
pending.respond('deny', reason);
|
|
181
|
+
this.emit('permission_timeout', { requestId, sessionId: pending.sessionId });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Remove a pending entry and stop its timer. */
|
|
185
|
+
_take(requestId) {
|
|
186
|
+
const pending = this._pending.get(requestId);
|
|
187
|
+
if (!pending) return null;
|
|
188
|
+
|
|
189
|
+
clearTimeout(pending.timer);
|
|
190
|
+
this._pending.delete(requestId);
|
|
191
|
+
return pending;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Extract the file path from tool input if applicable.
|
|
196
|
+
*/
|
|
197
|
+
_extractFilePath(toolName, toolInput) {
|
|
198
|
+
// Bash's `path` would be a cwd, not the thing being acted on.
|
|
199
|
+
if (toolName === 'Bash') return null;
|
|
200
|
+
|
|
201
|
+
return toolInput.file_path || toolInput.path || null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Build a human-readable description of the tool action.
|
|
206
|
+
* Only used when the CLI did not supply one.
|
|
207
|
+
*/
|
|
208
|
+
_buildDescription(toolName, toolInput) {
|
|
209
|
+
switch (toolName) {
|
|
210
|
+
case 'Bash':
|
|
211
|
+
return `Execute: ${(toolInput.command || '').slice(0, 200)}`;
|
|
212
|
+
case 'Write':
|
|
213
|
+
return `Write file: ${toolInput.file_path || 'unknown'}`;
|
|
214
|
+
case 'Edit':
|
|
215
|
+
return `Edit file: ${toolInput.file_path || 'unknown'}`;
|
|
216
|
+
case 'Read':
|
|
217
|
+
return `Read file: ${toolInput.file_path || 'unknown'}`;
|
|
218
|
+
default:
|
|
219
|
+
return `${toolName}: ${JSON.stringify(toolInput).slice(0, 200)}`;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Classify risk level based on tool type and input.
|
|
225
|
+
*
|
|
226
|
+
* The control request carries no risk field, so this stays with us — it drives
|
|
227
|
+
* the dialog's colour, and Rails validates it against low|medium|high.
|
|
228
|
+
*/
|
|
229
|
+
_classifyRisk(toolName) {
|
|
230
|
+
if (toolName === 'Bash') return 'high';
|
|
231
|
+
if (toolName === 'Read' || toolName === 'Glob' || toolName === 'Grep') return 'low';
|
|
232
|
+
return 'medium';
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
module.exports = { PermissionBroker };
|