@esquadrao/cli 1.7.1 → 1.9.0

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,457 @@
1
+ // Companion visual local: HTTP + SSE em 127.0.0.1, Node stdlib apenas.
2
+
3
+ import http from 'node:http';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import { spawn, execFile } from 'node:child_process';
8
+ import { fileURLToPath } from 'node:url';
9
+ import process from 'node:process';
10
+ import { listCaptionTemplates } from '../captionTemplates.js';
11
+ import {
12
+ resolveStateDir,
13
+ ensureStateLayout,
14
+ addWorkspace,
15
+ listWorkspaces,
16
+ findWorkspace,
17
+ resolveInside,
18
+ writeFileAtomic,
19
+ } from './stateDir.js';
20
+ import { STAGES, TERMINAL_STAGES, readJob, listJobs, sanitizeLog } from './jobTelemetry.js';
21
+ import { summarizePlan } from './planSummary.js';
22
+ import { getPreview } from './previewCache.js';
23
+
24
+ const PKG_ROOT = fileURLToPath(new URL('../../', import.meta.url));
25
+ const UI_FILE = path.join(PKG_ROOT, 'assets', 'studio-ui', 'index.html');
26
+ const CLI_FILE = path.join(PKG_ROOT, 'bin', 'cli.js');
27
+
28
+ const COMMANDS = new Set(['render', 'auto-clip', 'batch', 'cutout', 'onboard']);
29
+ const JOB_ID = /^[A-Za-z0-9._-]{1,120}$/;
30
+ const MAX_BODY = 1024 * 1024;
31
+
32
+ export function buildChildEnv(base = process.env, extra = {}) {
33
+ const allowed = ['PATH', 'HOME', 'TMPDIR', 'TEMP', 'TMP', 'SystemRoot', 'ComSpec', 'PATHEXT', 'LANG', 'LC_ALL'];
34
+ const env = {};
35
+ for (const key of allowed) if (base[key]) env[key] = base[key];
36
+ for (const [key, value] of Object.entries(base)) {
37
+ if (key.startsWith('ESQUADRAO_') && key !== 'ESQUADRAO_NO_TELEMETRY') env[key] = value;
38
+ }
39
+ return { ...env, ...extra };
40
+ }
41
+
42
+ function json(res, status, payload) {
43
+ const body = JSON.stringify(payload, null, 2);
44
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
45
+ res.end(body);
46
+ }
47
+
48
+ function requireToken(req, token) {
49
+ const header = req.headers['x-esquadrao-token'] || '';
50
+ const auth = String(req.headers.authorization || '');
51
+ const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
52
+ const provided = String(header || bearer);
53
+ if (!provided || provided.length !== token.length) return false;
54
+ return crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(token));
55
+ }
56
+
57
+ function sameOrigin(req, port) {
58
+ const origin = req.headers.origin;
59
+ if (!origin) return true;
60
+ const allowed = new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]);
61
+ return allowed.has(origin);
62
+ }
63
+
64
+ function hostAllowed(req, port) {
65
+ const host = String(req.headers.host || '');
66
+ if (!host) return true;
67
+ return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
68
+ }
69
+
70
+ function sendFile(req, res, file, contentType = 'video/mp4') {
71
+ let stat;
72
+ try { stat = fs.statSync(file); } catch { json(res, 404, { error: 'not_found' }); return; }
73
+ const size = stat.size;
74
+ res.setHeader('Accept-Ranges', 'bytes');
75
+ res.setHeader('Content-Type', contentType);
76
+ const range = req.headers.range;
77
+ if (!range) {
78
+ res.writeHead(200, { 'Content-Length': size });
79
+ if (req.method === 'HEAD') return res.end();
80
+ fs.createReadStream(file).pipe(res);
81
+ return;
82
+ }
83
+ const match = /^bytes=(\d*)-(\d*)$/.exec(String(range).trim());
84
+ if (!match || (match[1] === '' && match[2] === '')) {
85
+ res.writeHead(416, { 'Content-Range': `bytes */${size}` });
86
+ return res.end();
87
+ }
88
+ let start = match[1] === '' ? size - Number(match[2]) : Number(match[1]);
89
+ let end = match[2] === '' ? size - 1 : Number(match[2]);
90
+ start = Math.max(0, start);
91
+ end = Math.min(end, size - 1);
92
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= size) {
93
+ res.writeHead(416, { 'Content-Range': `bytes */${size}` });
94
+ return res.end();
95
+ }
96
+ res.writeHead(206, {
97
+ 'Content-Range': `bytes ${start}-${end}/${size}`,
98
+ 'Content-Length': end - start + 1,
99
+ });
100
+ if (req.method === 'HEAD') return res.end();
101
+ fs.createReadStream(file, { start, end }).pipe(res);
102
+ }
103
+
104
+ function readBody(req) {
105
+ return new Promise((resolve, reject) => {
106
+ let size = 0;
107
+ const chunks = [];
108
+ req.on('data', (chunk) => {
109
+ size += chunk.length;
110
+ if (size > MAX_BODY) {
111
+ reject(new Error('body_too_large'));
112
+ req.destroy();
113
+ return;
114
+ }
115
+ chunks.push(chunk);
116
+ });
117
+ req.on('end', () => {
118
+ if (!chunks.length) return resolve({});
119
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch { reject(new Error('invalid_json')); }
120
+ });
121
+ req.on('error', reject);
122
+ });
123
+ }
124
+
125
+ function readCatalog(workspace) {
126
+ const file = path.join(workspace, '.esquadrao', 'broll-catalog.json');
127
+ if (!fs.existsSync(file)) return [];
128
+ try {
129
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
130
+ if (Array.isArray(data)) return data;
131
+ if (Array.isArray(data.items)) return data.items;
132
+ if (Array.isArray(data.videos)) return data.videos;
133
+ if (Array.isArray(data.catalog)) return data.catalog;
134
+ return [];
135
+ } catch {
136
+ return [];
137
+ }
138
+ }
139
+
140
+ function findArtifact(workspaces, id) {
141
+ for (const workspace of workspaces) {
142
+ const manifestPath = path.join(workspace.path, 'studio.json');
143
+ if (!fs.existsSync(manifestPath)) continue;
144
+ let manifest;
145
+ try { manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); } catch { continue; }
146
+ const record = (manifest.artifacts || []).find((a) => a.id === id || path.basename(String(a.path || ''), '.mp4') === id);
147
+ if (!record) continue;
148
+ const resolved = resolveInside(workspace.path, record.path);
149
+ if (resolved && fs.existsSync(resolved)) return resolved;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ function createServedJob(stateDir, { command, workspace, args }) {
155
+ const id = `job-${new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15)}-${crypto.randomBytes(2).toString('hex')}`;
156
+ const dir = path.join(stateDir, 'jobs', id);
157
+ fs.mkdirSync(dir, { recursive: true });
158
+ const now = new Date().toISOString();
159
+ const record = {
160
+ id,
161
+ command,
162
+ argv: args.map((a) => sanitizeLog(a)),
163
+ workspace,
164
+ status: 'queued',
165
+ stage: 'queued',
166
+ owner: 'serve',
167
+ created_at: now,
168
+ started_at: now,
169
+ finished_at: null,
170
+ exit_code: null,
171
+ error: null,
172
+ updated_at: now,
173
+ };
174
+ writeFileAtomic(path.join(dir, 'job.json'), JSON.stringify(record, null, 2) + '\n');
175
+ fs.appendFileSync(path.join(dir, 'events.ndjson'), JSON.stringify({ seq: 1, ts: now, type: 'stage', stage: 'queued', payload: {} }) + '\n', 'utf8');
176
+ return { id, dir, record };
177
+ }
178
+
179
+ function openBrowser(url) {
180
+ try {
181
+ if (process.platform === 'darwin') spawn('open', [url], { stdio: 'ignore', detached: true }).unref();
182
+ else if (process.platform === 'win32') spawn('cmd', ['/c', 'start', '', url], { stdio: 'ignore', detached: true }).unref();
183
+ else spawn('xdg-open', [url], { stdio: 'ignore', detached: true }).unref();
184
+ } catch {}
185
+ }
186
+
187
+ export async function startServer(options = {}) {
188
+ const env = options.env || process.env;
189
+ const stateDir = path.resolve(options.stateDir || resolveStateDir(env));
190
+ ensureStateLayout(stateDir);
191
+
192
+ const requested = options.dest ? path.resolve(options.dest) : process.cwd();
193
+ let activeWorkspace;
194
+ try {
195
+ activeWorkspace = addWorkspace(stateDir, requested).path;
196
+ } catch (err) {
197
+ throw new Error(`Workspace inválido para o serve: ${err.message}`);
198
+ }
199
+
200
+ const token = crypto.randomBytes(32).toString('hex');
201
+ const port = options.port === undefined ? 4310 : Number(options.port);
202
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
203
+ throw new Error(`Porta inválida: ${options.port}. Use um inteiro entre 0 e 65535.`);
204
+ }
205
+ let active = null;
206
+ const inflight = new Set();
207
+
208
+ const handler = async (req, res) => {
209
+ try {
210
+ const url = new URL(req.url, `http://127.0.0.1:${port}`);
211
+ const pathname = decodeURIComponent(url.pathname);
212
+ res.setHeader('X-Content-Type-Options', 'nosniff');
213
+ res.setHeader('Referrer-Policy', 'no-referrer');
214
+
215
+ if (!hostAllowed(req, actualPort)) return json(res, 403, { error: 'host_not_allowed' });
216
+ if (req.method === 'POST' && !sameOrigin(req, actualPort)) return json(res, 403, { error: 'origin_not_allowed' });
217
+
218
+ if (pathname === '/') {
219
+ if (req.method !== 'GET' && req.method !== 'HEAD') return json(res, 405, { error: 'method_not_allowed' });
220
+ if (!fs.existsSync(UI_FILE)) return json(res, 500, { error: 'ui_missing' });
221
+ const html = fs.readFileSync(UI_FILE);
222
+ res.writeHead(200, {
223
+ 'Content-Type': 'text/html; charset=utf-8',
224
+ 'Cache-Control': 'no-store',
225
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob:; media-src blob:; connect-src 'self'",
226
+ });
227
+ if (req.method === 'HEAD') return res.end();
228
+ return res.end(html);
229
+ }
230
+
231
+ if (!pathname.startsWith('/api/')) return json(res, 404, { error: 'not_found' });
232
+ if (!requireToken(req, token)) return json(res, 401, { error: 'unauthorized' });
233
+
234
+ if (pathname === '/api/catalog' && req.method === 'GET') {
235
+ const workspace = url.searchParams.get('workspace') || activeWorkspace;
236
+ const allowed = findWorkspace(stateDir, workspace);
237
+ if (!allowed) return json(res, 403, { error: 'workspace_not_allowed' });
238
+ return json(res, 200, {
239
+ workspace: allowed.path,
240
+ items: readCatalog(allowed.path),
241
+ templates: listCaptionTemplates(),
242
+ });
243
+ }
244
+
245
+ if (pathname === '/api/workspaces' && req.method === 'GET') {
246
+ return json(res, 200, { active: activeWorkspace, workspaces: listWorkspaces(stateDir) });
247
+ }
248
+
249
+ if (pathname === '/api/jobs' && req.method === 'GET') {
250
+ return json(res, 200, { jobs: listJobs(stateDir) });
251
+ }
252
+
253
+ const preview = /^\/api\/previews\/([^/]+)\.mp4$/.exec(pathname);
254
+ if (preview && (req.method === 'GET' || req.method === 'HEAD')) {
255
+ try {
256
+ const result = await getPreview(preview[1], { stateDir });
257
+ return sendFile(req, res, result.path);
258
+ } catch (err) {
259
+ const status = /Unknown caption template/.test(err.message) ? 404 : 500;
260
+ return json(res, status, { error: status === 404 ? 'template_not_found' : 'preview_failed', message: err.message });
261
+ }
262
+ }
263
+
264
+ if (pathname === '/api/jobs' && req.method === 'POST') {
265
+ let body;
266
+ try { body = await readBody(req); } catch (err) { return json(res, 400, { error: err.message }); }
267
+ const command = String(body.command || '');
268
+ if (!COMMANDS.has(command)) return json(res, 400, { error: 'invalid_command', allowed: [...COMMANDS] });
269
+ const args = body.args === undefined ? [] : body.args;
270
+ if (!Array.isArray(args) || args.some((a) => typeof a !== 'string' || a.includes('\0') || a.length > 512)) {
271
+ return json(res, 400, { error: 'invalid_args' });
272
+ }
273
+ if (args.some((a) => a === '--openai' || a.startsWith('--openai='))) {
274
+ return json(res, 400, { error: 'openai_not_allowed_in_ui' });
275
+ }
276
+ if (args.some((a) => a === '--dest' || a.startsWith('--dest='))) {
277
+ return json(res, 400, { error: 'dest_not_allowed' });
278
+ }
279
+ const workspace = findWorkspace(stateDir, body.workspace || activeWorkspace);
280
+ if (!workspace) return json(res, 403, { error: 'workspace_not_allowed' });
281
+ if (active) return json(res, 409, { error: 'job_in_progress', job_id: active.id });
282
+
283
+ const job = createServedJob(stateDir, { command, workspace: workspace.path, args });
284
+ const childArgs = command === 'onboard'
285
+ ? [CLI_FILE, 'onboard', ...args, '--dest', workspace.path]
286
+ : [CLI_FILE, 'studio', command, ...args, '--dest', workspace.path];
287
+ const child = spawn(process.execPath, childArgs, {
288
+ cwd: workspace.path,
289
+ env: buildChildEnv(env, { ESQUADRAO_JOB_DIR: job.dir, ESQUADRAO_STATE_DIR: stateDir }),
290
+ stdio: ['ignore', 'ignore', 'pipe'],
291
+ shell: false,
292
+ });
293
+ let stderrTail = '';
294
+ child.stderr.on('data', (chunk) => {
295
+ stderrTail = (stderrTail + chunk.toString()).slice(-4000);
296
+ });
297
+ active = { id: job.id, dir: job.dir, child };
298
+ inflight.add(job.id);
299
+ const finalize = (code) => {
300
+ inflight.delete(job.id);
301
+ const current = readJob(job.dir);
302
+ if (!current || !TERMINAL_STAGES.has(current.status)) {
303
+ const status = code === 0 ? 'done' : (code === 130 || code === null ? 'canceled' : 'failed');
304
+ const now = new Date().toISOString();
305
+ const next = {
306
+ ...(current || job.record),
307
+ status,
308
+ stage: status,
309
+ exit_code: typeof code === 'number' ? code : null,
310
+ error: status === 'failed' ? sanitizeLog(stderrTail.split('\n').slice(-4).join(' ')) : (current?.error || null),
311
+ finished_at: now,
312
+ updated_at: now,
313
+ };
314
+ try { writeFileAtomic(path.join(job.dir, 'job.json'), JSON.stringify(next, null, 2) + '\n'); } catch {}
315
+ }
316
+ if (active && active.id === job.id) active = null;
317
+ };
318
+ child.on('exit', (code) => finalize(code));
319
+ child.on('error', () => finalize(1));
320
+ return json(res, 202, { job_id: job.id, status: 'queued', workspace: workspace.path });
321
+ }
322
+
323
+ const events = /^\/api\/jobs\/([^/]+)\/events$/.exec(pathname);
324
+ if (events && req.method === 'GET') {
325
+ const id = events[1];
326
+ if (!JOB_ID.test(id)) return json(res, 400, { error: 'invalid_job_id' });
327
+ const dir = path.join(stateDir, 'jobs', id);
328
+ if (!JOB_ID.test(path.basename(dir)) || !fs.existsSync(path.join(dir, 'job.json'))) {
329
+ return json(res, 404, { error: 'job_not_found' });
330
+ }
331
+ res.writeHead(200, {
332
+ 'Content-Type': 'text/event-stream; charset=utf-8',
333
+ 'Cache-Control': 'no-cache, no-transform',
334
+ Connection: 'keep-alive',
335
+ 'X-Accel-Buffering': 'no',
336
+ });
337
+ const send = (event) => {
338
+ try { res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`); } catch {}
339
+ };
340
+ const file = path.join(dir, 'events.ndjson');
341
+ let offset = 0;
342
+ const pump = () => {
343
+ if (!fs.existsSync(file)) return;
344
+ const content = fs.readFileSync(file, 'utf8');
345
+ if (content.length <= offset) return;
346
+ const chunk = content.slice(offset);
347
+ offset = content.length;
348
+ for (const line of chunk.split('\n')) {
349
+ if (!line.trim()) continue;
350
+ try { send(JSON.parse(line)); } catch {}
351
+ }
352
+ };
353
+ pump();
354
+ let watcher = null;
355
+ try { watcher = fs.watch(dir, { persistent: false }, () => pump()); } catch {}
356
+ const timer = setInterval(pump, 500);
357
+ const heartbeat = setInterval(() => res.write(': ping\n\n'), 15000);
358
+ const stop = () => {
359
+ clearInterval(timer);
360
+ clearInterval(heartbeat);
361
+ try { watcher?.close(); } catch {}
362
+ try { res.end(); } catch {}
363
+ };
364
+ req.on('close', stop);
365
+ const job = readJob(dir);
366
+ if (job && TERMINAL_STAGES.has(job.status)) {
367
+ setTimeout(stop, 50);
368
+ }
369
+ return;
370
+ }
371
+
372
+ const cancel = /^\/api\/jobs\/([^/]+)\/cancel$/.exec(pathname);
373
+ if (cancel && req.method === 'POST') {
374
+ const id = cancel[1];
375
+ if (!JOB_ID.test(id)) return json(res, 400, { error: 'invalid_job_id' });
376
+ const dir = path.join(stateDir, 'jobs', id);
377
+ const job = readJob(dir);
378
+ if (!job) return json(res, 404, { error: 'job_not_found' });
379
+ if (TERMINAL_STAGES.has(job.status)) return json(res, 409, { error: 'job_already_finished', status: job.status });
380
+ let pid = null;
381
+ try { pid = Number(fs.readFileSync(path.join(dir, 'pid'), 'utf8').trim()); } catch {}
382
+ if (!pid && active && active.id === id) pid = active.child.pid;
383
+ if (!pid) return json(res, 409, { error: 'job_pid_unavailable' });
384
+ try {
385
+ if (process.platform === 'win32') execFile('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }, () => {});
386
+ else process.kill(pid, 'SIGINT');
387
+ } catch (err) {
388
+ return json(res, 409, { error: 'cancel_failed', message: err.message });
389
+ }
390
+ return json(res, 202, { job_id: id, status: 'canceling', pid });
391
+ }
392
+
393
+ const artifact = /^\/api\/artifacts\/([^/]+)$/.exec(pathname);
394
+ if (artifact && (req.method === 'GET' || req.method === 'HEAD')) {
395
+ const id = artifact[1];
396
+ if (!JOB_ID.test(id)) return json(res, 400, { error: 'invalid_artifact_id' });
397
+ const file = findArtifact(listWorkspaces(stateDir), id);
398
+ if (!file) return json(res, 404, { error: 'artifact_not_found' });
399
+ return sendFile(req, res, file);
400
+ }
401
+
402
+ return json(res, 404, { error: 'not_found' });
403
+ } catch (err) {
404
+ try { json(res, 500, { error: 'internal_error', message: err.message }); } catch {}
405
+ }
406
+ };
407
+
408
+ const server = http.createServer(handler);
409
+ let actualPort = port;
410
+
411
+ await new Promise((resolve, reject) => {
412
+ server.once('error', (err) => reject(new Error(`Não foi possível escutar em 127.0.0.1:${port}: ${err.message}`)));
413
+ server.listen(port, '127.0.0.1', () => {
414
+ actualPort = server.address().port;
415
+ resolve();
416
+ });
417
+ });
418
+
419
+ const url = `http://127.0.0.1:${actualPort}/#t=${token}`;
420
+ const close = () => new Promise((resolve) => {
421
+ if (active) {
422
+ try { active.child.kill('SIGINT'); } catch {}
423
+ active = null;
424
+ }
425
+ server.close(() => resolve());
426
+ });
427
+
428
+ const onSigint = () => { close().then(() => process.exit(130)); };
429
+ process.once('SIGINT', onSigint);
430
+ server.once('close', () => process.removeListener('SIGINT', onSigint));
431
+
432
+ if (options.open !== false && !options.json) openBrowser(url);
433
+
434
+ if (options.json) {
435
+ console.log(JSON.stringify({ status: 'listening', url, port: actualPort, state_dir: stateDir }, null, 2));
436
+ } else {
437
+ console.log('Esquadrão Studio — companion visual local');
438
+ console.log(`- URL: ${url}`);
439
+ console.log(`- Workspace: ${activeWorkspace}`);
440
+ console.log(`- Estado: ${stateDir}`);
441
+ console.log('- Bind: 127.0.0.1 (apenas esta máquina). Ctrl+C encerra.');
442
+ }
443
+
444
+ return {
445
+ server,
446
+ port: actualPort,
447
+ token,
448
+ url,
449
+ stateDir,
450
+ workspace: activeWorkspace,
451
+ activeJob: () => (active ? active.id : null),
452
+ close,
453
+ };
454
+ }
455
+
456
+ export const SUPPORTED_COMMANDS = [...COMMANDS];
457
+ export { STAGES, summarizePlan };
@@ -0,0 +1,132 @@
1
+ // Resolução multiplataforma do diretório de estado e allowlist de workspaces.
2
+ // Node.js stdlib apenas; nenhuma dependência externa.
3
+
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import crypto from 'node:crypto';
8
+
9
+ export const WORKSPACES_FILE = 'workspaces.json';
10
+
11
+ export function resolveStateDir(env = process.env, platform = process.platform, homedir = os.homedir()) {
12
+ if (env.ESQUADRAO_STATE_DIR) return path.resolve(env.ESQUADRAO_STATE_DIR);
13
+ if (platform === 'win32') {
14
+ const base = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local');
15
+ return path.join(base, 'esquadrao');
16
+ }
17
+ if (platform === 'darwin') {
18
+ return path.join(homedir, 'Library', 'Application Support', 'esquadrao');
19
+ }
20
+ const base = env.XDG_STATE_HOME || path.join(homedir, '.local', 'state');
21
+ return path.join(base, 'esquadrao');
22
+ }
23
+
24
+ export function ensureStateLayout(stateDir) {
25
+ fs.mkdirSync(path.join(stateDir, 'jobs'), { recursive: true });
26
+ fs.mkdirSync(path.join(stateDir, 'previews'), { recursive: true });
27
+ return stateDir;
28
+ }
29
+
30
+ export function writeFileAtomic(file, data) {
31
+ const dir = path.dirname(file);
32
+ fs.mkdirSync(dir, { recursive: true });
33
+ const tmp = path.join(dir, `.tmp-${crypto.randomBytes(6).toString('hex')}`);
34
+ try {
35
+ fs.writeFileSync(tmp, data, 'utf8');
36
+ fs.renameSync(tmp, file);
37
+ } catch (err) {
38
+ try { fs.unlinkSync(tmp); } catch {}
39
+ throw err;
40
+ }
41
+ }
42
+
43
+ export function isPathInside(root, target) {
44
+ const rel = path.relative(path.resolve(root), path.resolve(target));
45
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
46
+ }
47
+
48
+ function normalizeForCompare(p, platform) {
49
+ const resolved = path.resolve(p);
50
+ return platform === 'win32' ? resolved.toLowerCase() : resolved;
51
+ }
52
+
53
+ export function loadWorkspaces(stateDir) {
54
+ const file = path.join(stateDir, WORKSPACES_FILE);
55
+ if (!fs.existsSync(file)) return { version: 1, workspaces: [] };
56
+ try {
57
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
58
+ if (!Array.isArray(data.workspaces)) data.workspaces = [];
59
+ return { version: 1, ...data, workspaces: data.workspaces };
60
+ } catch {
61
+ return { version: 1, workspaces: [] };
62
+ }
63
+ }
64
+
65
+ export function saveWorkspaces(stateDir, data) {
66
+ const file = path.join(stateDir, WORKSPACES_FILE);
67
+ const payload = { version: 1, workspaces: Array.isArray(data.workspaces) ? data.workspaces : [] };
68
+ writeFileAtomic(file, JSON.stringify(payload, null, 2) + '\n');
69
+ return payload;
70
+ }
71
+
72
+ export function realWorkspace(workspacePath) {
73
+ const resolved = path.resolve(workspacePath);
74
+ const stat = fs.statSync(resolved);
75
+ if (!stat.isDirectory()) throw new Error(`Workspace não é um diretório: ${workspacePath}`);
76
+ return fs.realpathSync(resolved);
77
+ }
78
+
79
+ export function addWorkspace(stateDir, workspacePath, name = null, platform = process.platform) {
80
+ const real = realWorkspace(workspacePath);
81
+ const data = loadWorkspaces(stateDir);
82
+ const existing = data.workspaces.find((w) => normalizeForCompare(w.path, platform) === normalizeForCompare(real, platform));
83
+ if (existing) return existing;
84
+ const record = {
85
+ id: `ws-${crypto.createHash('sha256').update(real).digest('hex').slice(0, 8)}`,
86
+ name: name || path.basename(real) || real,
87
+ path: real,
88
+ added_at: new Date().toISOString(),
89
+ };
90
+ data.workspaces.push(record);
91
+ saveWorkspaces(stateDir, data);
92
+ return record;
93
+ }
94
+
95
+ export function findWorkspace(stateDir, workspacePath, platform = process.platform) {
96
+ if (!workspacePath) return null;
97
+ let real;
98
+ try {
99
+ real = fs.realpathSync(path.resolve(workspacePath));
100
+ } catch {
101
+ return null;
102
+ }
103
+ const data = loadWorkspaces(stateDir);
104
+ return data.workspaces.find((w) => normalizeForCompare(w.path, platform) === normalizeForCompare(real, platform)) || null;
105
+ }
106
+
107
+ export function listWorkspaces(stateDir) {
108
+ return loadWorkspaces(stateDir).workspaces.map((w) => ({
109
+ ...w,
110
+ exists: fs.existsSync(w.path),
111
+ }));
112
+ }
113
+
114
+ /** Resolve um caminho dentro de um workspace, rejeitando escape por .. ou symlink. */
115
+ export function resolveInside(root, candidate) {
116
+ if (typeof candidate !== 'string' || !candidate || candidate.includes('\0')) return null;
117
+ let base;
118
+ try {
119
+ base = fs.realpathSync(path.resolve(root));
120
+ } catch {
121
+ return null;
122
+ }
123
+ const target = path.resolve(base, candidate);
124
+ if (!isPathInside(base, target)) return null;
125
+ let real;
126
+ try {
127
+ real = fs.realpathSync(target);
128
+ } catch {
129
+ return null;
130
+ }
131
+ return isPathInside(base, real) ? real : null;
132
+ }