@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/fs-bridge.js
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs').promises;
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { spawn } = require('node:child_process');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Generalized filesystem RPC for the daemon<->Rails bridge (fs_request /
|
|
9
|
+
* fs_response). This generalizes the older, plan-doc-specific file_request
|
|
10
|
+
* flow (see connections/action-cable-client.js `_handleFileRequest`) to
|
|
11
|
+
* arbitrary ops (`stat`, `read`, `list`) behind realpath-based
|
|
12
|
+
* containment, since the old flow's lexical `path.resolve()` +
|
|
13
|
+
* `.startsWith()` check has two known defects:
|
|
14
|
+
* 1. Symlink escape: a symlink that lives *inside* the working directory
|
|
15
|
+
* but points outside it passes the lexical check untouched, because
|
|
16
|
+
* `path.resolve` does not follow symlinks.
|
|
17
|
+
* 2. Prefix collision: `.startsWith(workingDir)` is a *string* prefix
|
|
18
|
+
* test, so a sibling directory whose name extends the workdir's name
|
|
19
|
+
* (e.g. workdir `/work`, sibling `/work-evil`) is wrongly treated as
|
|
20
|
+
* contained.
|
|
21
|
+
*
|
|
22
|
+
* Both are fixed by resolving both sides through `fs.realpath` and
|
|
23
|
+
* comparing with `path.relative`, never with string prefixes.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
// Extensions allowed for fs_request reads/stats, compared lowercase.
|
|
27
|
+
// Extend this list as new doc types need to be exposed to Rails.
|
|
28
|
+
//
|
|
29
|
+
// File bridge S3 added the code-extension block below (clickable file
|
|
30
|
+
// references in chat need to fetch source files, not just docs) — kept in
|
|
31
|
+
// lockstep with VaultFileTypes::ALLOWED_EXTENSIONS (app/models/vault_file_types.rb)
|
|
32
|
+
// by hand; VaultFileTypesSpec asserts the two lists match by reading this
|
|
33
|
+
// file off disk.
|
|
34
|
+
const ALLOWED_EXTENSIONS = Object.freeze([
|
|
35
|
+
'.md', '.markdown', '.txt',
|
|
36
|
+
'.rb', '.js', '.ts', '.jsx', '.tsx', '.json', '.yaml', '.yml',
|
|
37
|
+
'.erb', '.html', '.css', '.scss', '.py', '.sh', '.sql', '.scad', '.toml',
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
// Reject reads of files larger than this before ever touching file content.
|
|
41
|
+
const MAX_READ_BYTES = 1048576; // 1 MB
|
|
42
|
+
|
|
43
|
+
// Reject `list` results with more raw directory entries than this — a typed
|
|
44
|
+
// error, not silent truncation, so the caller knows the listing is
|
|
45
|
+
// incomplete rather than assuming it saw everything.
|
|
46
|
+
const MAX_LIST_ENTRIES = 500;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Cheap, fs-free pre-check on the raw requested path string. Must run
|
|
50
|
+
* before any fs access.
|
|
51
|
+
*
|
|
52
|
+
* @param {*} requestedPath
|
|
53
|
+
* @param {{ allowEmptyRoot?: boolean }} [options] - `allowEmptyRoot: true`
|
|
54
|
+
* lets `""` (and `"."`, which already passes unmodified below) through as
|
|
55
|
+
* a legal reference to the working directory itself. Only `list` passes
|
|
56
|
+
* this — `stat`/`read` are unaffected and still reject an empty path,
|
|
57
|
+
* since neither of those operations has a meaningful "root" target.
|
|
58
|
+
* @returns {string|null} an error message, or null if the shape is fine
|
|
59
|
+
*/
|
|
60
|
+
function checkPathShape(requestedPath, options) {
|
|
61
|
+
const allowEmptyRoot = Boolean(options && options.allowEmptyRoot);
|
|
62
|
+
|
|
63
|
+
if (typeof requestedPath !== 'string') {
|
|
64
|
+
return 'Path must be a non-empty string';
|
|
65
|
+
}
|
|
66
|
+
if (requestedPath.length === 0) {
|
|
67
|
+
if (allowEmptyRoot) return null;
|
|
68
|
+
return 'Path must be a non-empty string';
|
|
69
|
+
}
|
|
70
|
+
if (requestedPath.includes('\0')) {
|
|
71
|
+
return 'Access denied: path contains a NUL byte';
|
|
72
|
+
}
|
|
73
|
+
if (path.isAbsolute(requestedPath)) {
|
|
74
|
+
return 'Access denied: absolute paths are not allowed';
|
|
75
|
+
}
|
|
76
|
+
const segments = requestedPath.split('/');
|
|
77
|
+
if (segments.includes('..')) {
|
|
78
|
+
return 'Access denied: path contains directory traversal';
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Case-insensitive extension allowlist check.
|
|
85
|
+
* @param {string} requestedPath
|
|
86
|
+
* @returns {boolean}
|
|
87
|
+
*/
|
|
88
|
+
function isAllowedExtension(requestedPath) {
|
|
89
|
+
const ext = path.extname(requestedPath).toLowerCase();
|
|
90
|
+
return ALLOWED_EXTENSIONS.includes(ext);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Pure containment predicate: is `realTarget` equal to, or inside,
|
|
95
|
+
* `realWorkdir`? Both arguments MUST already be realpath-resolved — this
|
|
96
|
+
* function does no fs I/O, so it is safe (and intended) to unit test
|
|
97
|
+
* directly with hand-constructed strings (e.g. prefix-collision cases).
|
|
98
|
+
*
|
|
99
|
+
* Deliberately uses `path.relative` rather than a string-prefix test —
|
|
100
|
+
* `path.relative('/work', '/work-evil/x')` is `'../work-evil/x'`, which
|
|
101
|
+
* `.startsWith('..')` catches, whereas `'/work-evil/x'.startsWith('/work')`
|
|
102
|
+
* would (wrongly) be `true`.
|
|
103
|
+
*
|
|
104
|
+
* @param {string} realWorkdir
|
|
105
|
+
* @param {string} realTarget
|
|
106
|
+
* @returns {boolean}
|
|
107
|
+
*/
|
|
108
|
+
function isPathContained(realWorkdir, realTarget) {
|
|
109
|
+
if (realTarget === realWorkdir) return true;
|
|
110
|
+
const rel = path.relative(realWorkdir, realTarget);
|
|
111
|
+
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Resolve `requestedPath` (workdir-relative, already shape-checked) against
|
|
116
|
+
* `workingDir` and decide containment using realpath on both sides.
|
|
117
|
+
*
|
|
118
|
+
* Two cases:
|
|
119
|
+
* - The target exists: realpath the target itself and check containment
|
|
120
|
+
* against the realpath'd working dir.
|
|
121
|
+
* - The target does not exist (ENOENT): realpath the target's *parent*
|
|
122
|
+
* directory instead and apply the same containment check to it. This
|
|
123
|
+
* closes the symlinked-directory variant of the escape (a directory
|
|
124
|
+
* symlink inside the workdir pointing outside, traversed to a path that
|
|
125
|
+
* happens not to exist) while still letting a plain "file not found"
|
|
126
|
+
* inside the real workdir report `exists: false` cleanly. If the parent
|
|
127
|
+
* itself doesn't exist, there is nothing further up worth resolving —
|
|
128
|
+
* report `exists: false` without leaking any fs structure.
|
|
129
|
+
*
|
|
130
|
+
* @param {string} workingDir - absolute working directory (may itself be
|
|
131
|
+
* a symlink; realpath'd here)
|
|
132
|
+
* @param {string} requestedPath - workdir-relative path, already passed
|
|
133
|
+
* through `checkPathShape`
|
|
134
|
+
* @returns {Promise<
|
|
135
|
+
* { contained: true, exists: true, realPath: string } |
|
|
136
|
+
* { contained: true, exists: false } |
|
|
137
|
+
* { contained: false, error: string }
|
|
138
|
+
* >}
|
|
139
|
+
*/
|
|
140
|
+
async function resolveContained(workingDir, requestedPath) {
|
|
141
|
+
let realWorkdir;
|
|
142
|
+
try {
|
|
143
|
+
realWorkdir = await fs.realpath(workingDir);
|
|
144
|
+
} catch (err) {
|
|
145
|
+
return { contained: false, error: `Cannot resolve working directory: ${err.message}` };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const candidate = path.resolve(workingDir, requestedPath);
|
|
149
|
+
|
|
150
|
+
try {
|
|
151
|
+
const realTarget = await fs.realpath(candidate);
|
|
152
|
+
if (!isPathContained(realWorkdir, realTarget)) {
|
|
153
|
+
return { contained: false, error: 'Access denied: path is outside the working directory' };
|
|
154
|
+
}
|
|
155
|
+
return { contained: true, exists: true, realPath: realTarget };
|
|
156
|
+
} catch (err) {
|
|
157
|
+
if (err.code !== 'ENOENT') {
|
|
158
|
+
return { contained: false, error: `Cannot resolve path: ${err.message}` };
|
|
159
|
+
}
|
|
160
|
+
// Candidate itself doesn't exist — check the parent directory instead.
|
|
161
|
+
const parent = path.dirname(candidate);
|
|
162
|
+
let realParent;
|
|
163
|
+
try {
|
|
164
|
+
realParent = await fs.realpath(parent);
|
|
165
|
+
} catch (parentErr) {
|
|
166
|
+
if (parentErr.code === 'ENOENT') {
|
|
167
|
+
// Nothing further up exists either — plain not-found, no structure leaked.
|
|
168
|
+
return { contained: true, exists: false };
|
|
169
|
+
}
|
|
170
|
+
return { contained: false, error: `Cannot resolve path: ${parentErr.message}` };
|
|
171
|
+
}
|
|
172
|
+
if (!isPathContained(realWorkdir, realParent)) {
|
|
173
|
+
return { contained: false, error: 'Access denied: path is outside the working directory' };
|
|
174
|
+
}
|
|
175
|
+
return { contained: true, exists: false };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Directory listing for the tree browser (`op: "list"`). One level deep —
|
|
181
|
+
* no recursion, the caller (the UI tree) lazy-loads deeper levels with
|
|
182
|
+
* further `list` calls. Entries are filtered (dotfiles/dot-dirs excluded,
|
|
183
|
+
* files restricted to `ALLOWED_EXTENSIONS`, symlink entries omitted rather
|
|
184
|
+
* than resolved — see the module README/PR notes for why: resolving each
|
|
185
|
+
* entry's realpath to decide whether *it* escapes containment would cost an
|
|
186
|
+
* extra stat per entry for a case that's already covered defense-in-depth
|
|
187
|
+
* by `resolveContained` rejecting the escape the moment anything tries to
|
|
188
|
+
* `list`/`stat`/`read` *through* that symlink) and sorted dirs-first, then
|
|
189
|
+
* by name.
|
|
190
|
+
*
|
|
191
|
+
* @param {string} requestedPath - already shape-checked (empty allowed)
|
|
192
|
+
* @param {string} workingDir
|
|
193
|
+
* @returns {Promise<object>} response fields for an fs_response
|
|
194
|
+
*/
|
|
195
|
+
async function handleListRequest(requestedPath, workingDir) {
|
|
196
|
+
const fail = (error) => ({ op: 'list', path: requestedPath, error });
|
|
197
|
+
|
|
198
|
+
// "" and "." both mean "the working directory itself" — resolveContained/
|
|
199
|
+
// path.resolve already treat "." this way, so only "" needs normalizing.
|
|
200
|
+
const normalizedPath = requestedPath === '' ? '.' : requestedPath;
|
|
201
|
+
|
|
202
|
+
const resolution = await resolveContained(workingDir, normalizedPath);
|
|
203
|
+
if (!resolution.contained) {
|
|
204
|
+
return fail(resolution.error);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (!resolution.exists) {
|
|
208
|
+
return { op: 'list', path: requestedPath, exists: false };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
let stats;
|
|
212
|
+
try {
|
|
213
|
+
stats = await fs.stat(resolution.realPath);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
return fail(`Failed to stat path: ${err.message}`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (!stats.isDirectory()) {
|
|
219
|
+
return fail('Not a directory');
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
let dirents;
|
|
223
|
+
try {
|
|
224
|
+
dirents = await fs.readdir(resolution.realPath, { withFileTypes: true });
|
|
225
|
+
} catch (err) {
|
|
226
|
+
return fail(`Failed to read directory: ${err.message}`);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const candidates = dirents.filter((dirent) => {
|
|
230
|
+
if (dirent.name.startsWith('.')) return false; // .git, .claude, etc. stay invisible
|
|
231
|
+
if (dirent.isDirectory()) return true;
|
|
232
|
+
if (dirent.isFile()) return isAllowedExtension(dirent.name);
|
|
233
|
+
return false; // symlinks and other special entry types omitted
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// Capped on the *filtered* count (what would actually be returned), not
|
|
237
|
+
// the raw directory size — a directory full of excluded dotfiles/other
|
|
238
|
+
// extensions shouldn't be rejected just for being noisy; it's the
|
|
239
|
+
// resulting `entries` payload (and the per-entry stat calls below) this
|
|
240
|
+
// limit protects.
|
|
241
|
+
if (candidates.length > MAX_LIST_ENTRIES) {
|
|
242
|
+
return fail(`Directory too large: ${candidates.length} entries exceeds ${MAX_LIST_ENTRIES} entry limit`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const entries = [];
|
|
246
|
+
for (const dirent of candidates) {
|
|
247
|
+
const entryPath = path.join(resolution.realPath, dirent.name);
|
|
248
|
+
let entryStats;
|
|
249
|
+
try {
|
|
250
|
+
entryStats = await fs.stat(entryPath);
|
|
251
|
+
} catch (_err) {
|
|
252
|
+
continue; // raced/removed between readdir and stat — drop it silently
|
|
253
|
+
}
|
|
254
|
+
entries.push({
|
|
255
|
+
name: dirent.name,
|
|
256
|
+
type: dirent.isDirectory() ? 'dir' : 'file',
|
|
257
|
+
size_bytes: entryStats.size,
|
|
258
|
+
mtime: entryStats.mtime.toISOString(),
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
entries.sort((a, b) => {
|
|
263
|
+
if (a.type !== b.type) return a.type === 'dir' ? -1 : 1;
|
|
264
|
+
return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
return { op: 'list', path: requestedPath, exists: true, entries };
|
|
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
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Handle a single fs_request end-to-end and return the response payload
|
|
370
|
+
* fields (everything an fs_response carries EXCEPT `type`, `request_id`,
|
|
371
|
+
* `reply_stream`, and `timestamp` — the caller/transport layer attaches
|
|
372
|
+
* those). `content` is present only on a successful `read`; `entries` is
|
|
373
|
+
* present only on a successful `list` of a directory; `error` is always
|
|
374
|
+
* mutually exclusive with `exists`/`mtime`/`size_bytes`/`content`/`entries`.
|
|
375
|
+
*
|
|
376
|
+
* @param {{ op: string, path: string }} message
|
|
377
|
+
* @param {{ workingDir: string, logger?: object }} opts
|
|
378
|
+
* @returns {Promise<object>} response fields: { op, path, exists?, mtime?, size_bytes?, content?, entries?, error? }
|
|
379
|
+
*/
|
|
380
|
+
async function handleFsRequest(message, opts) {
|
|
381
|
+
const { workingDir } = opts || {};
|
|
382
|
+
const op = message && message.op;
|
|
383
|
+
const requestedPath = message && message.path;
|
|
384
|
+
|
|
385
|
+
const fail = (error) => ({ op, path: requestedPath, error });
|
|
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
|
+
|
|
393
|
+
if (op !== 'stat' && op !== 'read' && op !== 'list') {
|
|
394
|
+
return fail(`Unsupported operation: "${op}"`);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (!workingDir) {
|
|
398
|
+
return fail('No working directory configured');
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const shapeError = checkPathShape(requestedPath, { allowEmptyRoot: op === 'list' });
|
|
402
|
+
if (shapeError) return fail(shapeError);
|
|
403
|
+
|
|
404
|
+
if (op === 'list') {
|
|
405
|
+
return handleListRequest(requestedPath, workingDir);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
if (!isAllowedExtension(requestedPath)) {
|
|
409
|
+
const ext = path.extname(requestedPath) || '(none)';
|
|
410
|
+
return fail(`Disallowed file extension: ${ext}`);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const resolution = await resolveContained(workingDir, requestedPath);
|
|
414
|
+
if (!resolution.contained) {
|
|
415
|
+
return fail(resolution.error);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if (!resolution.exists) {
|
|
419
|
+
return { op, path: requestedPath, exists: false };
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
let stats;
|
|
423
|
+
try {
|
|
424
|
+
stats = await fs.stat(resolution.realPath);
|
|
425
|
+
} catch (err) {
|
|
426
|
+
return fail(`Failed to stat file: ${err.message}`);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
if (!stats.isFile()) {
|
|
430
|
+
return fail('Not a regular file');
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
if (op === 'stat') {
|
|
434
|
+
// stat must never read file content.
|
|
435
|
+
return {
|
|
436
|
+
op,
|
|
437
|
+
path: requestedPath,
|
|
438
|
+
exists: true,
|
|
439
|
+
mtime: stats.mtime.toISOString(),
|
|
440
|
+
size_bytes: stats.size,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// op === 'read' — check size BEFORE reading content.
|
|
445
|
+
if (stats.size > MAX_READ_BYTES) {
|
|
446
|
+
return fail(`File too large: ${stats.size} bytes exceeds ${MAX_READ_BYTES} byte limit`);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
let buffer;
|
|
450
|
+
try {
|
|
451
|
+
buffer = await fs.readFile(resolution.realPath);
|
|
452
|
+
} catch (err) {
|
|
453
|
+
return fail(`Failed to read file: ${err.message}`);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (buffer.includes(0)) {
|
|
457
|
+
return fail('binary file');
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
return {
|
|
461
|
+
op,
|
|
462
|
+
path: requestedPath,
|
|
463
|
+
exists: true,
|
|
464
|
+
mtime: stats.mtime.toISOString(),
|
|
465
|
+
size_bytes: stats.size,
|
|
466
|
+
content: buffer.toString('utf8'),
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
module.exports = {
|
|
471
|
+
ALLOWED_EXTENSIONS,
|
|
472
|
+
MAX_READ_BYTES,
|
|
473
|
+
MAX_LIST_ENTRIES,
|
|
474
|
+
checkPathShape,
|
|
475
|
+
isAllowedExtension,
|
|
476
|
+
isPathContained,
|
|
477
|
+
resolveContained,
|
|
478
|
+
handleFsRequest,
|
|
479
|
+
handleRevealRequest,
|
|
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
|
|