crewboss 0.0.0-stage → 0.3.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.
- package/LICENSE +21 -0
- package/README.md +633 -2
- package/bin/crewboss.js +14 -0
- package/package.json +43 -4
- package/src/agent.js +179 -0
- package/src/candidates.js +66 -0
- package/src/cli.js +531 -0
- package/src/collect.js +26 -0
- package/src/config.js +384 -0
- package/src/due.js +10 -0
- package/src/errors.js +47 -0
- package/src/events.js +243 -0
- package/src/fsutil.js +37 -0
- package/src/init.js +174 -0
- package/src/label.js +4 -0
- package/src/launchd.js +243 -0
- package/src/lock.js +62 -0
- package/src/mcp.js +293 -0
- package/src/memory.js +81 -0
- package/src/mods.js +354 -0
- package/src/node-command.js +34 -0
- package/src/personas.js +154 -0
- package/src/plugin.js +43 -0
- package/src/presence.js +160 -0
- package/src/process.js +37 -0
- package/src/quota.js +34 -0
- package/src/routines.js +401 -0
- package/src/rundir.js +43 -0
- package/src/runners/agy.js +26 -0
- package/src/runners/claude.js +39 -0
- package/src/runners/codex.js +26 -0
- package/src/runners/index.js +186 -0
- package/src/runners/opencode.js +28 -0
- package/src/schedule.js +21 -0
- package/src/server.js +773 -0
- package/src/session.js +40 -0
- package/src/store.js +615 -0
- package/src/task-schedule.js +6 -0
- package/src/task-time.js +30 -0
- package/src/tasks.js +129 -0
- package/src/trackers/command.js +126 -0
- package/src/trackers/file.js +160 -0
- package/src/trackers/index.js +16 -0
- package/src/trackers/local.js +57 -0
- package/src/units.js +117 -0
- package/src/warnings.js +19 -0
package/src/server.js
ADDED
|
@@ -0,0 +1,773 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `crewboss serve`: a JSON API (under /api) with optional static UI hosting.
|
|
3
|
+
*
|
|
4
|
+
* Security, even on localhost (other sites in the browser can reach it):
|
|
5
|
+
* - API requests need a token when exposed beyond loopback; loopback token auth is optional;
|
|
6
|
+
* - the Host header must be exactly the configured host and port (DNS rebinding);
|
|
7
|
+
* - a foreign Origin is refused, and writes must send JSON with its Content-Type;
|
|
8
|
+
* - strict security headers (CSP 'self', no framing, no sniffing, no referrer).
|
|
9
|
+
*/
|
|
10
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import http from 'node:http';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
|
|
16
|
+
import { loadConfig, validateUi } from './config.js';
|
|
17
|
+
import { isDue } from './due.js';
|
|
18
|
+
import { TrackerError, UnsupportedError } from './errors.js';
|
|
19
|
+
import { nextRunAt } from './launchd.js';
|
|
20
|
+
import { isLockHeld } from './lock.js';
|
|
21
|
+
import { isValidScope } from './memory.js';
|
|
22
|
+
import { livePresence, presenceLabel } from './presence.js';
|
|
23
|
+
import { EVENT_DIRECTIONS, openStore, TASK_PRIORITIES, TASK_STATUSES } from './store.js';
|
|
24
|
+
import { makeTracker } from './trackers/index.js';
|
|
25
|
+
import { BIN_PATH } from './units.js';
|
|
26
|
+
import { filterDoneSince, parseDoneSince } from './task-time.js';
|
|
27
|
+
|
|
28
|
+
export const DEFAULT_HOST = '127.0.0.1';
|
|
29
|
+
export const DEFAULT_PORT = 4317;
|
|
30
|
+
export const COOKIE_NAME = 'crewboss_token';
|
|
31
|
+
/** The session cookie lasts 30 days; a new token (restart without CREWBOSS_TOKEN) invalidates it anyway. */
|
|
32
|
+
export const COOKIE_MAX_AGE = 30 * 24 * 60 * 60;
|
|
33
|
+
const STATIC_TYPES = new Map(Object.entries({
|
|
34
|
+
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
|
|
35
|
+
'.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
|
|
36
|
+
'.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml',
|
|
37
|
+
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
38
|
+
'.webp': 'image/webp', '.gif': 'image/gif', '.ico': 'image/x-icon',
|
|
39
|
+
'.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8',
|
|
40
|
+
'.map': 'application/json; charset=utf-8',
|
|
41
|
+
}));
|
|
42
|
+
const SECURITY_HEADERS = {
|
|
43
|
+
'Content-Security-Policy': "default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
|
44
|
+
'X-Content-Type-Options': 'nosniff',
|
|
45
|
+
'X-Frame-Options': 'DENY',
|
|
46
|
+
'Referrer-Policy': 'no-referrer',
|
|
47
|
+
'Cache-Control': 'no-store',
|
|
48
|
+
};
|
|
49
|
+
const MAX_BODY_BYTES = 1_000_000;
|
|
50
|
+
const MAX_LIMIT = 500;
|
|
51
|
+
const LIST_STATUSES = [...TASK_STATUSES, 'all'];
|
|
52
|
+
const TASK_FIELDS = ['title', 'notes', 'status', 'priority', 'assignee'];
|
|
53
|
+
/** Largest answer.md the API returns; longer answers are cut and flagged. */
|
|
54
|
+
export const MAX_ANSWER_BYTES = 200_000;
|
|
55
|
+
const TASK_SUMMARY_CHARS = 300;
|
|
56
|
+
const MAX_LOG_TAIL_BYTES = 20_000;
|
|
57
|
+
/** Longest message the API can send to an agent. */
|
|
58
|
+
const MAX_MESSAGE_CHARS = 10_000;
|
|
59
|
+
const RUN_EVENTS_SHOWN = 200;
|
|
60
|
+
const PRESENCE_EVENTS_SHOWN = 20;
|
|
61
|
+
const PRESENCE_RUNS_SCANNED = 500;
|
|
62
|
+
|
|
63
|
+
class HttpError extends Error {
|
|
64
|
+
constructor(status, message) {
|
|
65
|
+
super(message);
|
|
66
|
+
this.status = status;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
71
|
+
const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
|
|
72
|
+
|
|
73
|
+
export function isLoopback(host) {
|
|
74
|
+
return host === 'localhost' || host === '::1' || /^127\./.test(host);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The warning printed when the server listens beyond loopback, or null. */
|
|
78
|
+
export function exposureWarning(host) {
|
|
79
|
+
if (isLoopback(host)) return null;
|
|
80
|
+
return `warning: crewboss serve listens on ${host} and is reachable from the network; `
|
|
81
|
+
+ 'anyone with the token can read and change tasks and memory and run routines';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function noTokenWarning() {
|
|
85
|
+
return 'warning: crewboss serve is running without token authentication; anyone who can reach the URL can control agents, tasks and routines';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 0.0.0.0 and :: listen on every interface: no Host can be derived from them. */
|
|
89
|
+
export function isWildcard(host) {
|
|
90
|
+
return host === '0.0.0.0' || host === '::' || host === '[::]';
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Validate a public URL (the address people open): http or https origin, with no
|
|
95
|
+
* path, query, fragment or credentials. Returns the URL object or throws Error.
|
|
96
|
+
*/
|
|
97
|
+
export function parsePublicUrl(value) {
|
|
98
|
+
let url;
|
|
99
|
+
try {
|
|
100
|
+
url = new URL(value);
|
|
101
|
+
} catch {
|
|
102
|
+
throw new Error(`invalid public URL: ${value}`);
|
|
103
|
+
}
|
|
104
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error(`the public URL must be http or https: ${value}`);
|
|
105
|
+
if (url.username || url.password || url.search || url.hash || (url.pathname && url.pathname !== '/')) {
|
|
106
|
+
throw new Error(`the public URL must be an origin like https://crewboss.example.com, without path, query or credentials: ${value}`);
|
|
107
|
+
}
|
|
108
|
+
return url;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The Host headers (lowercase) and origins the server accepts, and the origin to print.
|
|
113
|
+
* With a public URL, only its host and origin. On loopback, the listening address plus
|
|
114
|
+
* localhost (and 127.0.0.1 and [::1] when listening on "localhost"). Otherwise the
|
|
115
|
+
* listening address only.
|
|
116
|
+
*/
|
|
117
|
+
export function allowedAddresses({ host, port, publicUrl = null }) {
|
|
118
|
+
if (publicUrl) {
|
|
119
|
+
const url = typeof publicUrl === 'string' ? parsePublicUrl(publicUrl) : publicUrl;
|
|
120
|
+
return { hosts: [url.host.toLowerCase()], origins: [url.origin], origin: url.origin };
|
|
121
|
+
}
|
|
122
|
+
if (isWildcard(host)) {
|
|
123
|
+
throw new Error(`listening on ${host} needs a public URL (the address people will open)`);
|
|
124
|
+
}
|
|
125
|
+
const own = `${hostLiteral(host)}:${port}`.toLowerCase();
|
|
126
|
+
const hosts = [own];
|
|
127
|
+
if (isLoopback(host)) {
|
|
128
|
+
hosts.push(`localhost:${port}`);
|
|
129
|
+
if (host === 'localhost') hosts.push(`127.0.0.1:${port}`, `[::1]:${port}`);
|
|
130
|
+
}
|
|
131
|
+
const unique = [...new Set(hosts)];
|
|
132
|
+
return { hosts: unique, origins: unique.map((h) => `http://${h}`), origin: `http://${own}` };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function generateToken() {
|
|
136
|
+
return crypto.randomBytes(24).toString('base64url');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const hostLiteral = (host) => (host.includes(':') ? `[${host}]` : host);
|
|
140
|
+
|
|
141
|
+
function sameSecret(given, expected) {
|
|
142
|
+
if (typeof given !== 'string' || typeof expected !== 'string') return false;
|
|
143
|
+
const a = Buffer.from(given);
|
|
144
|
+
const b = Buffer.from(expected);
|
|
145
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function cookieValue(header, name) {
|
|
149
|
+
for (const part of (header ?? '').split(';')) {
|
|
150
|
+
const eq = part.indexOf('=');
|
|
151
|
+
if (eq > 0 && part.slice(0, eq).trim() === name) {
|
|
152
|
+
try {
|
|
153
|
+
return decodeURIComponent(part.slice(eq + 1).trim());
|
|
154
|
+
} catch {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The command that "run now" launches: the same crewboss, `routines run <name>`. */
|
|
163
|
+
export function routineRunCommand(config, name) {
|
|
164
|
+
return [process.execPath, BIN_PATH, '--config', config.path, 'routines', 'run', name];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Start `routines run <name>` as a separate, detached process; the server does not wait for it. */
|
|
168
|
+
function spawnRoutineProcess(config, name) {
|
|
169
|
+
const [command, ...args] = routineRunCommand(config, name);
|
|
170
|
+
const child = nodeSpawn(command, args, { cwd: config.root, detached: true, stdio: 'ignore' });
|
|
171
|
+
child.on('error', () => {});
|
|
172
|
+
child.unref();
|
|
173
|
+
return child.pid ?? null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function send(res, status, body, headers = {}) {
|
|
177
|
+
res.writeHead(status, { ...SECURITY_HEADERS, ...headers });
|
|
178
|
+
res.end(body);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function sendJson(res, status, value) {
|
|
182
|
+
send(res, status, `${JSON.stringify(value)}\n`, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function readBody(req) {
|
|
186
|
+
return new Promise((resolve, reject) => {
|
|
187
|
+
const chunks = [];
|
|
188
|
+
let size = 0;
|
|
189
|
+
req.on('data', (chunk) => {
|
|
190
|
+
size += chunk.length;
|
|
191
|
+
if (size <= MAX_BODY_BYTES) chunks.push(chunk);
|
|
192
|
+
});
|
|
193
|
+
req.on('end', () => {
|
|
194
|
+
if (size > MAX_BODY_BYTES) reject(new HttpError(413, 'request body too large'));
|
|
195
|
+
else resolve(Buffer.concat(chunks).toString('utf8'));
|
|
196
|
+
});
|
|
197
|
+
req.on('error', reject);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function readJson(req) {
|
|
202
|
+
const type = (req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
|
|
203
|
+
if (type !== 'application/json') throw new HttpError(415, 'writes must send Content-Type: application/json');
|
|
204
|
+
const text = await readBody(req);
|
|
205
|
+
if (!text.trim()) return {};
|
|
206
|
+
try {
|
|
207
|
+
const value = JSON.parse(text);
|
|
208
|
+
if (!isObject(value)) throw new Error('not an object');
|
|
209
|
+
return value;
|
|
210
|
+
} catch {
|
|
211
|
+
throw new HttpError(400, 'the body must be a JSON object');
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function limitOf(query, fallback = 50) {
|
|
216
|
+
const raw = query.get('limit');
|
|
217
|
+
if (raw === null) return fallback;
|
|
218
|
+
if (!/^[1-9][0-9]*$/.test(raw)) throw new HttpError(400, 'limit must be a positive integer');
|
|
219
|
+
return Math.min(Number(raw), MAX_LIMIT);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function optionalString(body, key) {
|
|
223
|
+
if (body[key] === undefined) return undefined;
|
|
224
|
+
if (typeof body[key] !== 'string') throw new HttpError(400, `${key} must be a string`);
|
|
225
|
+
return body[key];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function optionalDue(body) {
|
|
229
|
+
if (body.due === undefined) return undefined;
|
|
230
|
+
if (!isDue(body.due)) throw new HttpError(400, 'due must be a date in YYYY-MM-DD format or null');
|
|
231
|
+
return body.due;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Read a UTF-8 file, at most `max` bytes (the first ones, or the last with `tail`); null if missing. */
|
|
235
|
+
export function readCapped(file, max, { tail = false } = {}) {
|
|
236
|
+
// No symlinks (O_NOFOLLOW), no blocking on a FIFO (O_NONBLOCK), and only regular files.
|
|
237
|
+
const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
|
|
238
|
+
let fd;
|
|
239
|
+
try {
|
|
240
|
+
fd = fs.openSync(file, flags);
|
|
241
|
+
} catch {
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
try {
|
|
245
|
+
const stat = fs.fstatSync(fd);
|
|
246
|
+
if (!stat.isFile()) return null;
|
|
247
|
+
const { size } = stat;
|
|
248
|
+
const buffer = Buffer.alloc(Math.min(size, max));
|
|
249
|
+
fs.readSync(fd, buffer, 0, buffer.length, tail ? size - buffer.length : 0);
|
|
250
|
+
return { text: buffer.toString('utf8'), truncated: size > max };
|
|
251
|
+
} finally {
|
|
252
|
+
fs.closeSync(fd);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** The task of an agent run: what follows the last `# Task` heading of its prompt.txt. */
|
|
257
|
+
export function taskFromPrompt(prompt) {
|
|
258
|
+
const marker = prompt.lastIndexOf('\n# Task\n');
|
|
259
|
+
const rest = marker >= 0 ? prompt.slice(marker + 8) : '';
|
|
260
|
+
return rest.split('\n# Attachment\n')[0].trim();
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The next run of a routine as an ISO string, or null (disabled or a schedule launchd cannot use). */
|
|
264
|
+
function nextRunOf(routine, now = new Date()) {
|
|
265
|
+
if (!routine.enabled) return null;
|
|
266
|
+
try {
|
|
267
|
+
return nextRunAt(routine.schedule, now)?.toISOString() ?? null;
|
|
268
|
+
} catch {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Build the request handler. ctx: {config, store, tracker(), token, expectedHost, origin, spawnRoutine}. */
|
|
274
|
+
function makeRoutes(ctx) {
|
|
275
|
+
const { store } = ctx;
|
|
276
|
+
|
|
277
|
+
// The handler supplies a fresh cache for each HTTP request. A failed optional lookup
|
|
278
|
+
// must not make task or routine listings unavailable.
|
|
279
|
+
const projectsFor = async (request) => {
|
|
280
|
+
if (!request.projectNames) {
|
|
281
|
+
request.projectNames = Promise.resolve().then(async () => {
|
|
282
|
+
const tracker = ctx.tracker();
|
|
283
|
+
if (typeof tracker.listProjects !== 'function') return new Map();
|
|
284
|
+
const projects = await tracker.listProjects();
|
|
285
|
+
return new Map(projects.map((project) => [String(project.id), String(project.name)]));
|
|
286
|
+
}).catch(() => new Map());
|
|
287
|
+
}
|
|
288
|
+
return request.projectNames;
|
|
289
|
+
};
|
|
290
|
+
const withProjectName = async (value, request) => {
|
|
291
|
+
if (!value) return value;
|
|
292
|
+
const projects = await projectsFor(request);
|
|
293
|
+
return { ...value, project_name: projects.get(String(value.project ?? '')) ?? String(value.project ?? '') };
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
const taskTracker = () => {
|
|
297
|
+
const tracker = ctx.tracker();
|
|
298
|
+
if (typeof tracker.listTasks !== 'function') {
|
|
299
|
+
throw new HttpError(501, `the ${ctx.config.tracker.type} tracker does not support task management`);
|
|
300
|
+
}
|
|
301
|
+
return tracker;
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
const routine = (name) => {
|
|
305
|
+
const found = ctx.config.routines.find((r) => r.name === name);
|
|
306
|
+
if (!found) throw new HttpError(404, `unknown routine: ${name}`);
|
|
307
|
+
return found;
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
const lockFile = (name) => path.join(ctx.config.logsDir, 'routines', `${name}.lock`);
|
|
311
|
+
|
|
312
|
+
/** A run's log file, only if its log_dir is inside the configured logs directory. */
|
|
313
|
+
const runFile = (run, name) => {
|
|
314
|
+
if (!run.log_dir) return null;
|
|
315
|
+
let dir;
|
|
316
|
+
let logs;
|
|
317
|
+
try {
|
|
318
|
+
// Real paths, so a symlinked run directory cannot point outside the logs directory.
|
|
319
|
+
dir = fs.realpathSync(run.log_dir);
|
|
320
|
+
logs = fs.realpathSync(ctx.config.logsDir);
|
|
321
|
+
} catch {
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
if (!dir.startsWith(`${logs}${path.sep}`)) return null;
|
|
325
|
+
return path.join(dir, name);
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
/** The task of an agent run, from its prompt.txt; cached, since prompts never change. */
|
|
329
|
+
const taskCache = new Map();
|
|
330
|
+
const taskOf = (run) => {
|
|
331
|
+
if (run.kind !== 'agent') return '';
|
|
332
|
+
if (taskCache.has(run.id)) return taskCache.get(run.id);
|
|
333
|
+
const file = runFile(run, 'prompt.txt');
|
|
334
|
+
const prompt = file ? readCapped(file, MAX_ANSWER_BYTES) : null;
|
|
335
|
+
const task = prompt ? taskFromPrompt(prompt.text) : '';
|
|
336
|
+
if (prompt) taskCache.set(run.id, task);
|
|
337
|
+
return task;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
/** A run as the API shows it: the stored row plus its repository (the last part of work_dir) and task. */
|
|
341
|
+
const runView = (run, { fullTask = false } = {}) => {
|
|
342
|
+
const task = taskOf(run);
|
|
343
|
+
return {
|
|
344
|
+
...run,
|
|
345
|
+
repo: run.work_dir ? path.basename(run.work_dir) : null,
|
|
346
|
+
task: fullTask || task.length <= TASK_SUMMARY_CHARS ? task : `${task.slice(0, TASK_SUMMARY_CHARS)}…`,
|
|
347
|
+
};
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
/** Events with the name and repository of their run, as the API shows them. */
|
|
351
|
+
const eventViews = (events) => {
|
|
352
|
+
const runs = new Map();
|
|
353
|
+
return events.map((event) => {
|
|
354
|
+
if (!runs.has(event.run_id)) runs.set(event.run_id, store.getRun(event.run_id));
|
|
355
|
+
const run = runs.get(event.run_id);
|
|
356
|
+
return { ...event, run_name: run?.name ?? null, repo: run?.work_dir ? path.basename(run.work_dir) : null };
|
|
357
|
+
});
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Current status of the given task ids in the tracker, as a Map id → status. Trackers
|
|
362
|
+
* that cannot list tasks, or fail, give an empty Map: reports still show, without status.
|
|
363
|
+
*/
|
|
364
|
+
const taskStatuses = async (ids) => {
|
|
365
|
+
const unique = [...new Set(ids.filter(Boolean))];
|
|
366
|
+
const tracker = ctx.tracker();
|
|
367
|
+
if (!unique.length || typeof tracker.listTasks !== 'function') return new Map();
|
|
368
|
+
try {
|
|
369
|
+
const tasks = await tracker.listTasks({ ids: unique, status: 'all' });
|
|
370
|
+
return new Map(tasks.map((task) => [String(task.id), task.status]));
|
|
371
|
+
} catch {
|
|
372
|
+
return new Map();
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
/** A report's findings with `task_status`, plus how many of its tasks are done. */
|
|
377
|
+
const withTaskStatus = (report, statuses) => {
|
|
378
|
+
const findings = report.findings.map((f) => ({ ...f, task_status: f.task_id ? statuses.get(String(f.task_id)) ?? null : null }));
|
|
379
|
+
const withTasks = findings.filter((f) => f.task_id);
|
|
380
|
+
return {
|
|
381
|
+
...report,
|
|
382
|
+
findings,
|
|
383
|
+
tasks_total: withTasks.length,
|
|
384
|
+
tasks_done: withTasks.filter((f) => f.task_status === 'done').length,
|
|
385
|
+
};
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
return [
|
|
389
|
+
['GET', /^\/api\/status$/, () => ({
|
|
390
|
+
tracker: ctx.config.tracker.type, routines: ctx.config.routines.length, fullTextSearch: store.fts,
|
|
391
|
+
})],
|
|
392
|
+
|
|
393
|
+
['GET', /^\/api\/projects$/, async () => {
|
|
394
|
+
const tracker = ctx.tracker();
|
|
395
|
+
if (typeof tracker.listProjects !== 'function') return [];
|
|
396
|
+
return tracker.listProjects();
|
|
397
|
+
}],
|
|
398
|
+
['GET', /^\/api\/tasks$/, async (_, query, __, request) => {
|
|
399
|
+
const status = query.get('status');
|
|
400
|
+
if (status !== null && !LIST_STATUSES.includes(status)) throw new HttpError(400, `status must be one of ${LIST_STATUSES.join(', ')}`);
|
|
401
|
+
const doneSince = query.get('done_since');
|
|
402
|
+
if (doneSince !== null) {
|
|
403
|
+
try { parseDoneSince(doneSince); } catch { throw new HttpError(400, 'done_since must be YYYY-MM-DD or an ISO datetime'); }
|
|
404
|
+
}
|
|
405
|
+
let rows = await taskTracker().listTasks({ project: query.get('project'), status: doneSince !== null && status === null ? 'all' : status,
|
|
406
|
+
assignee: query.get('assignee'), doneSince });
|
|
407
|
+
rows = doneSince === null ? rows : filterDoneSince(rows, doneSince);
|
|
408
|
+
const projects = await projectsFor(request);
|
|
409
|
+
return rows.map((task) => ({ ...task, project_name: projects.get(String(task.project ?? '')) ?? String(task.project ?? '') }));
|
|
410
|
+
}],
|
|
411
|
+
['POST', /^\/api\/tasks$/, async (_, __, body) => {
|
|
412
|
+
if (!nonEmpty(body.project) || !nonEmpty(body.title)) throw new HttpError(400, 'project and title are required');
|
|
413
|
+
const priority = body.priority ?? 'medium';
|
|
414
|
+
if (!TASK_PRIORITIES.includes(priority)) throw new HttpError(400, `priority must be one of ${TASK_PRIORITIES.join(', ')}`);
|
|
415
|
+
const due = optionalDue(body);
|
|
416
|
+
const id = await taskTracker().createTask(body.project.trim(), body.title.trim(),
|
|
417
|
+
optionalString(body, 'notes') ?? '', priority, optionalString(body, 'assignee') ?? '', due);
|
|
418
|
+
return [201, { id }];
|
|
419
|
+
}],
|
|
420
|
+
['GET', /^\/api\/tasks\/([^/]+)$/, async ([id], __, ___, request) => {
|
|
421
|
+
const task = await taskTracker().getTask(id);
|
|
422
|
+
if (!task) throw new HttpError(404, `task not found: ${id}`);
|
|
423
|
+
return withProjectName(task, request);
|
|
424
|
+
}],
|
|
425
|
+
['PATCH', /^\/api\/tasks\/([^/]+)$/, async ([id], __, body, request) => {
|
|
426
|
+
const changes = {};
|
|
427
|
+
for (const field of TASK_FIELDS) {
|
|
428
|
+
const value = optionalString(body, field);
|
|
429
|
+
if (value !== undefined) changes[field] = value;
|
|
430
|
+
}
|
|
431
|
+
const due = optionalDue(body);
|
|
432
|
+
if (due !== undefined) changes.due = due;
|
|
433
|
+
if (!Object.keys(changes).length) throw new HttpError(400, `send at least one of ${TASK_FIELDS.join(', ')}, due`);
|
|
434
|
+
if (changes.title !== undefined && !changes.title.trim()) throw new HttpError(400, 'title must not be empty');
|
|
435
|
+
if (changes.status !== undefined && !TASK_STATUSES.includes(changes.status)) {
|
|
436
|
+
throw new HttpError(400, `status must be one of ${TASK_STATUSES.join(', ')}`);
|
|
437
|
+
}
|
|
438
|
+
if (changes.priority !== undefined && !TASK_PRIORITIES.includes(changes.priority)) {
|
|
439
|
+
throw new HttpError(400, `priority must be one of ${TASK_PRIORITIES.join(', ')}`);
|
|
440
|
+
}
|
|
441
|
+
return withProjectName(await taskTracker().updateTask(id, changes), request);
|
|
442
|
+
}],
|
|
443
|
+
['POST', /^\/api\/tasks\/([^/]+)\/comments$/, async ([id], __, body) => {
|
|
444
|
+
if (!nonEmpty(body.body)) throw new HttpError(400, 'body is required');
|
|
445
|
+
const author = optionalString(body, 'author') ?? 'web';
|
|
446
|
+
return [201, await taskTracker().commentTask(id, author, body.body)];
|
|
447
|
+
}],
|
|
448
|
+
|
|
449
|
+
['GET', /^\/api\/routines$/, async (_, __, ___, request) => {
|
|
450
|
+
const projects = await projectsFor(request);
|
|
451
|
+
return ctx.config.routines.map((r) => ({
|
|
452
|
+
name: r.name,
|
|
453
|
+
mod: r.mod ?? null,
|
|
454
|
+
enabled: r.enabled,
|
|
455
|
+
schedule: r.schedule,
|
|
456
|
+
mode: r.mode,
|
|
457
|
+
project: r.project,
|
|
458
|
+
project_name: projects.get(String(r.project)) ?? String(r.project),
|
|
459
|
+
choice: 'size' in r ? `size ${r.size}` : `${r.tool}:${r.model}`,
|
|
460
|
+
running: isLockHeld(lockFile(r.name)),
|
|
461
|
+
last: store.listRuns({ kind: 'routine', name: r.name, limit: 1 })[0] ?? null,
|
|
462
|
+
next_run: nextRunOf(r),
|
|
463
|
+
}));
|
|
464
|
+
}],
|
|
465
|
+
['POST', /^\/api\/routines\/([^/]+)\/run$/, ([name]) => {
|
|
466
|
+
routine(name);
|
|
467
|
+
if (isLockHeld(lockFile(name))) throw new HttpError(409, `routine ${name} is already running`);
|
|
468
|
+
const pid = ctx.spawnRoutine(ctx.config, name);
|
|
469
|
+
return [202, { started: true, routine: name, pid }];
|
|
470
|
+
}],
|
|
471
|
+
|
|
472
|
+
['GET', /^\/api\/runs$/, (_, query) => {
|
|
473
|
+
const kind = query.get('kind');
|
|
474
|
+
if (kind !== null && kind !== 'agent' && kind !== 'routine') throw new HttpError(400, 'kind must be agent or routine');
|
|
475
|
+
return store.listRuns({ kind, name: query.get('name'), limit: limitOf(query) }).map((run) => runView(run));
|
|
476
|
+
}],
|
|
477
|
+
['GET', /^\/api\/runs\/([0-9]+)$/, ([id]) => {
|
|
478
|
+
const run = store.getRun(Number(id));
|
|
479
|
+
if (!run) throw new HttpError(404, `run not found: ${id}`);
|
|
480
|
+
const read = (name, max, options) => {
|
|
481
|
+
const file = runFile(run, name);
|
|
482
|
+
return file ? readCapped(file, max, options) : null;
|
|
483
|
+
};
|
|
484
|
+
const answer = read('answer.md', MAX_ANSWER_BYTES);
|
|
485
|
+
const prompt = read('prompt.txt', MAX_ANSWER_BYTES);
|
|
486
|
+
const log = read('agent.log', MAX_LOG_TAIL_BYTES, { tail: true });
|
|
487
|
+
return {
|
|
488
|
+
...runView(run, { fullTask: true }),
|
|
489
|
+
answer_path: answer ? runFile(run, 'answer.md') : null,
|
|
490
|
+
answer: answer?.text ?? null,
|
|
491
|
+
answer_truncated: answer?.truncated ?? false,
|
|
492
|
+
prompt: prompt?.text ?? null,
|
|
493
|
+
log_tail: log?.text ?? null,
|
|
494
|
+
events: eventViews(store.listEvents({ runId: run.id, limit: RUN_EVENTS_SHOWN })),
|
|
495
|
+
};
|
|
496
|
+
}],
|
|
497
|
+
['POST', /^\/api\/runs\/([0-9]+)\/messages$/, ([id], __, body) => {
|
|
498
|
+
const run = store.getRun(Number(id));
|
|
499
|
+
if (!run) throw new HttpError(404, `run not found: ${id}`);
|
|
500
|
+
if (typeof body.message !== 'string' || !body.message.trim()) throw new HttpError(400, 'message is required');
|
|
501
|
+
if (body.message.length > MAX_MESSAGE_CHARS) throw new HttpError(400, `message is longer than ${MAX_MESSAGE_CHARS} characters`);
|
|
502
|
+
if (run.status !== 'running') throw new HttpError(409, `run ${id} already finished (${run.status}); nobody will read it`);
|
|
503
|
+
return [201, eventViews([store.addEvent(run.id, { direction: 'in', kind: 'reply', message: body.message.trim() })])[0]];
|
|
504
|
+
}],
|
|
505
|
+
['GET', /^\/api\/events$/, (_, query) => {
|
|
506
|
+
const direction = query.get('direction');
|
|
507
|
+
if (direction !== null && !EVENT_DIRECTIONS.includes(direction)) throw new HttpError(400, `direction must be one of ${EVENT_DIRECTIONS.join(', ')}`);
|
|
508
|
+
const since = query.get('since');
|
|
509
|
+
if (since !== null && !/^[0-9]+$/.test(since)) throw new HttpError(400, 'since must be a non-negative integer');
|
|
510
|
+
const run = query.get('run');
|
|
511
|
+
if (run !== null && !/^[1-9][0-9]*$/.test(run)) throw new HttpError(400, 'run must be a positive integer');
|
|
512
|
+
return eventViews(store.listEvents({
|
|
513
|
+
since: since === null ? 0 : Number(since), runId: run === null ? null : Number(run), direction, limit: limitOf(query, 100),
|
|
514
|
+
}));
|
|
515
|
+
}],
|
|
516
|
+
['GET', /^\/api\/presence$/, () => {
|
|
517
|
+
const running = store.listRuns({ limit: PRESENCE_RUNS_SCANNED }).filter((run) => run.status === 'running' && !run.dry_run);
|
|
518
|
+
return livePresence(store).map((row) => {
|
|
519
|
+
const agents = running.filter((run) => run.notify === row.session);
|
|
520
|
+
return {
|
|
521
|
+
...row,
|
|
522
|
+
label: presenceLabel(row),
|
|
523
|
+
agent_count: agents.length,
|
|
524
|
+
agents: agents.map((run) => runView(run)),
|
|
525
|
+
events: eventViews(store.listEvents({ notify: row.session, direction: 'out', limit: PRESENCE_EVENTS_SHOWN })),
|
|
526
|
+
};
|
|
527
|
+
});
|
|
528
|
+
}],
|
|
529
|
+
['GET', /^\/api\/reports$/, async (_, query) => {
|
|
530
|
+
const reports = store.listReports({ source: query.get('source'), limit: limitOf(query) })
|
|
531
|
+
.map((report) => ({ ...report, findings: store.getReport(report.id).findings }));
|
|
532
|
+
const statuses = await taskStatuses(reports.flatMap((r) => r.findings.map((f) => f.task_id)));
|
|
533
|
+
return reports.map((report) => {
|
|
534
|
+
const { findings, ...summary } = withTaskStatus(report, statuses);
|
|
535
|
+
return summary;
|
|
536
|
+
});
|
|
537
|
+
}],
|
|
538
|
+
['GET', /^\/api\/reports\/([0-9]+)$/, async ([id]) => {
|
|
539
|
+
const report = store.getReport(Number(id));
|
|
540
|
+
if (!report) throw new HttpError(404, `report not found: ${id}`);
|
|
541
|
+
return withTaskStatus(report, await taskStatuses(report.findings.map((f) => f.task_id)));
|
|
542
|
+
}],
|
|
543
|
+
|
|
544
|
+
['GET', /^\/api\/memory$/, (_, query) => {
|
|
545
|
+
const scope = query.get('scope');
|
|
546
|
+
if (scope !== null && !isValidScope(scope)) throw new HttpError(400, `invalid scope: ${scope}`);
|
|
547
|
+
const scopes = scope === null ? null : [scope];
|
|
548
|
+
const q = query.get('q');
|
|
549
|
+
const limit = limitOf(query);
|
|
550
|
+
return q && q.trim() ? store.searchMemory(q, { scopes, limit }) : store.listMemory({ scopes, limit });
|
|
551
|
+
}],
|
|
552
|
+
['POST', /^\/api\/memory$/, (_, __, body) => {
|
|
553
|
+
const scope = body.scope ?? 'global';
|
|
554
|
+
if (!isValidScope(scope)) throw new HttpError(400, `invalid scope: ${scope}`);
|
|
555
|
+
if (!nonEmpty(body.text)) throw new HttpError(400, 'text is required');
|
|
556
|
+
return [201, store.addMemory({ scope, text: body.text.trim(), author: optionalString(body, 'author') ?? 'web' })];
|
|
557
|
+
}],
|
|
558
|
+
['DELETE', /^\/api\/memory\/([0-9]+)$/, ([id]) => {
|
|
559
|
+
if (!store.removeMemory(Number(id))) throw new HttpError(404, `memory note not found: ${id}`);
|
|
560
|
+
return { id: Number(id), removed: true };
|
|
561
|
+
}],
|
|
562
|
+
];
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function authorized(req, ctx) {
|
|
566
|
+
if (!ctx.tokenRequired) return true;
|
|
567
|
+
if (!ctx.token) return false;
|
|
568
|
+
const header = req.headers.authorization ?? '';
|
|
569
|
+
if (header.startsWith('Bearer ') && sameSecret(header.slice(7).trim(), ctx.token)) return true;
|
|
570
|
+
return sameSecret(cookieValue(req.headers.cookie, COOKIE_NAME), ctx.token);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function serveStatic(req, res, url, ctx) {
|
|
574
|
+
ctx.refreshConfig();
|
|
575
|
+
const rawPath = req.url.split('?', 1)[0];
|
|
576
|
+
if (rawPath === '/' && (req.method === 'GET' || req.method === 'HEAD') && sameSecret(url.searchParams.get('token'), ctx.token)) {
|
|
577
|
+
const secure = ctx.origin.startsWith('https:') ? '; Secure' : '';
|
|
578
|
+
return send(res, 303, '', {
|
|
579
|
+
Location: '/',
|
|
580
|
+
'Set-Cookie': `${COOKIE_NAME}=${encodeURIComponent(ctx.token)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${COOKIE_MAX_AGE}${secure}`,
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
if (!ctx.uiPath) {
|
|
584
|
+
if (rawPath === '/' && req.method === 'GET') return sendJson(res, 200, { name: 'crewboss', api: '/api/', ui: null });
|
|
585
|
+
return sendJson(res, 404, { error: 'not found' });
|
|
586
|
+
}
|
|
587
|
+
let pathname;
|
|
588
|
+
try { pathname = decodeURIComponent(rawPath); } catch { return sendJson(res, 404, { error: 'not found' }); }
|
|
589
|
+
const segments = pathname.split('/').slice(1);
|
|
590
|
+
if (!pathname.startsWith('/') || pathname.includes('\\') || segments.some((s) => s.startsWith('.') || s === '')) {
|
|
591
|
+
if (pathname !== '/') return sendJson(res, 404, { error: 'not found' });
|
|
592
|
+
}
|
|
593
|
+
const relative = pathname === '/' ? 'index.html' : segments.join('/');
|
|
594
|
+
const type = STATIC_TYPES.get(path.extname(relative).toLowerCase());
|
|
595
|
+
if (!type) return sendJson(res, 404, { error: 'not found' });
|
|
596
|
+
const file = path.resolve(ctx.uiPath, relative);
|
|
597
|
+
if (!file.startsWith(`${ctx.uiPath}${path.sep}`)) return sendJson(res, 404, { error: 'not found' });
|
|
598
|
+
let real;
|
|
599
|
+
try {
|
|
600
|
+
real = fs.realpathSync(file);
|
|
601
|
+
if (!real.startsWith(`${ctx.uiRealPath}${path.sep}`) || !fs.statSync(real).isFile()) {
|
|
602
|
+
return sendJson(res, 404, { error: 'not found' });
|
|
603
|
+
}
|
|
604
|
+
} catch { return sendJson(res, 404, { error: 'not found' }); }
|
|
605
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return sendJson(res, 405, { error: 'method not allowed' });
|
|
606
|
+
const body = fs.readFileSync(real);
|
|
607
|
+
return send(res, 200, req.method === 'HEAD' ? '' : body, { 'Content-Type': type });
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
async function handle(req, res, ctx) {
|
|
611
|
+
if (!ctx.allowedHosts.has((req.headers.host ?? '').toLowerCase())) {
|
|
612
|
+
return sendJson(res, 403, { error: 'invalid Host header' });
|
|
613
|
+
}
|
|
614
|
+
if (req.headers.origin !== undefined && !ctx.allowedOrigins.has(req.headers.origin)) {
|
|
615
|
+
return sendJson(res, 403, { error: 'cross-origin requests are not allowed' });
|
|
616
|
+
}
|
|
617
|
+
const rawPath = req.url.split('?', 1)[0];
|
|
618
|
+
const url = new URL(req.url, 'http://crewboss.invalid');
|
|
619
|
+
// Route from the raw path so URL normalization cannot turn traversal into an API call.
|
|
620
|
+
if (!rawPath.startsWith('/api/')) return serveStatic(req, res, url, ctx);
|
|
621
|
+
if (!authorized(req, ctx)) return sendJson(res, 401, { error: 'missing or invalid token' });
|
|
622
|
+
let decodedPath;
|
|
623
|
+
try { decodedPath = decodeURIComponent(rawPath); } catch { return sendJson(res, 404, { error: 'not found' }); }
|
|
624
|
+
if (decodedPath.includes('\\') || decodedPath.split('/').some((segment) => segment.startsWith('.'))) {
|
|
625
|
+
return sendJson(res, 404, { error: 'not found' });
|
|
626
|
+
}
|
|
627
|
+
ctx.refreshConfig();
|
|
628
|
+
|
|
629
|
+
const candidates = ctx.routes.filter(([, pattern]) => pattern.test(url.pathname));
|
|
630
|
+
if (!candidates.length) return sendJson(res, 404, { error: 'not found' });
|
|
631
|
+
const route = candidates.find(([method]) => method === req.method);
|
|
632
|
+
if (!route) return sendJson(res, 405, { error: 'method not allowed' });
|
|
633
|
+
const body = req.method === 'GET' ? {} : await readJson(req);
|
|
634
|
+
const params = route[1].exec(url.pathname).slice(1).map(decodeURIComponent);
|
|
635
|
+
const result = await route[2](params, url.searchParams, body, {});
|
|
636
|
+
const [status, value] = Array.isArray(result) && typeof result[0] === 'number' ? result : [200, result];
|
|
637
|
+
return sendJson(res, status, value);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
function configMtime(file) {
|
|
641
|
+
try {
|
|
642
|
+
return fs.statSync(file).mtimeMs;
|
|
643
|
+
} catch {
|
|
644
|
+
return null;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function errorResponse(res, err, stderr) {
|
|
649
|
+
if (res.headersSent) {
|
|
650
|
+
res.destroy();
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
if (err instanceof HttpError) {
|
|
654
|
+
sendJson(res, err.status, { error: err.message });
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (err instanceof UnsupportedError) {
|
|
658
|
+
sendJson(res, 501, { error: err.message });
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
if (err instanceof TrackerError) {
|
|
662
|
+
sendJson(res, /not found/.test(err.message) ? 404 : 502, { error: err.message });
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
stderr.write(`crewboss serve: ${err.stack ?? err}\n`);
|
|
666
|
+
sendJson(res, 500, { error: 'internal error' });
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Start the server. Resolves with {server, url, origin, port, token, close()}.
|
|
671
|
+
* The token is `token`, else $CREWBOSS_TOKEN, else a random one when required. `publicUrl` (required with
|
|
672
|
+
* 0.0.0.0 or ::) is the address people open: its Host and Origin become the only valid ones.
|
|
673
|
+
*/
|
|
674
|
+
export async function startServer(config, {
|
|
675
|
+
host = DEFAULT_HOST,
|
|
676
|
+
port = DEFAULT_PORT,
|
|
677
|
+
publicUrl = null,
|
|
678
|
+
ui = undefined,
|
|
679
|
+
uiBase = process.cwd(),
|
|
680
|
+
token = null,
|
|
681
|
+
noToken = false,
|
|
682
|
+
env = process.env,
|
|
683
|
+
store = undefined,
|
|
684
|
+
tracker = undefined,
|
|
685
|
+
spawnRoutine = spawnRoutineProcess,
|
|
686
|
+
stderr = process.stderr,
|
|
687
|
+
} = {}) {
|
|
688
|
+
const uiPath = ui === undefined
|
|
689
|
+
? validateUi(config.uiValue, config.root, config.mods)
|
|
690
|
+
: validateUi(ui, uiBase, config.mods);
|
|
691
|
+
const tokenDisabled = noToken || env.CREWBOSS_NO_TOKEN === '1';
|
|
692
|
+
const tokenRequired = !tokenDisabled && (Boolean(publicUrl) || !isLoopback(host));
|
|
693
|
+
const configuredToken = token || env.CREWBOSS_TOKEN || null;
|
|
694
|
+
const secret = tokenDisabled ? null : configuredToken || (tokenRequired ? generateToken() : null);
|
|
695
|
+
const publicOrigin = publicUrl ? parsePublicUrl(publicUrl) : null;
|
|
696
|
+
if (!publicOrigin && isWildcard(host)) {
|
|
697
|
+
throw new Error(`listening on ${host} needs a public URL (the address people will open)`);
|
|
698
|
+
}
|
|
699
|
+
const db = store ?? openStore(config.root);
|
|
700
|
+
let activeTracker = tracker ?? null;
|
|
701
|
+
let configStamp = configMtime(config.path);
|
|
702
|
+
const ctx = {
|
|
703
|
+
config,
|
|
704
|
+
uiPath,
|
|
705
|
+
uiRealPath: uiPath ? fs.realpathSync(uiPath) : null,
|
|
706
|
+
store: db,
|
|
707
|
+
token: secret,
|
|
708
|
+
tokenRequired,
|
|
709
|
+
spawnRoutine,
|
|
710
|
+
tracker: () => {
|
|
711
|
+
activeTracker ??= makeTracker(ctx.config.tracker, ctx.config.root, { store: db });
|
|
712
|
+
return activeTracker;
|
|
713
|
+
},
|
|
714
|
+
/**
|
|
715
|
+
* Reload crewboss.json when it changed on disk, so new routines or a new tracker show up
|
|
716
|
+
* without restarting. An invalid file keeps the last good config and is reported once.
|
|
717
|
+
*/
|
|
718
|
+
refreshConfig: () => {
|
|
719
|
+
const stamp = configMtime(config.path);
|
|
720
|
+
if (stamp === configStamp) return;
|
|
721
|
+
configStamp = stamp;
|
|
722
|
+
try {
|
|
723
|
+
const next = loadConfig(config.path, { ui, uiBase });
|
|
724
|
+
if (next.root !== ctx.config.root) {
|
|
725
|
+
throw new Error(`root changed from ${ctx.config.root} to ${next.root}; restart crewboss serve to use it`);
|
|
726
|
+
}
|
|
727
|
+
const nextUiPath = ui === undefined ? validateUi(next.uiValue, next.root, next.mods) : validateUi(ui, uiBase, next.mods);
|
|
728
|
+
const nextUiRealPath = nextUiPath ? fs.realpathSync(nextUiPath) : null;
|
|
729
|
+
ctx.config = next;
|
|
730
|
+
if (ui === undefined) {
|
|
731
|
+
ctx.uiPath = nextUiPath;
|
|
732
|
+
ctx.uiRealPath = nextUiRealPath;
|
|
733
|
+
}
|
|
734
|
+
if (!tracker) activeTracker = null;
|
|
735
|
+
} catch (err) {
|
|
736
|
+
stderr.write(`crewboss serve: keeping the previous configuration: ${err.message}\n`);
|
|
737
|
+
}
|
|
738
|
+
},
|
|
739
|
+
};
|
|
740
|
+
ctx.routes = makeRoutes(ctx);
|
|
741
|
+
const server = http.createServer((req, res) => {
|
|
742
|
+
handle(req, res, ctx).catch((err) => errorResponse(res, err, stderr));
|
|
743
|
+
});
|
|
744
|
+
try {
|
|
745
|
+
await new Promise((resolve, reject) => {
|
|
746
|
+
server.once('error', reject);
|
|
747
|
+
server.listen(port, host, resolve);
|
|
748
|
+
});
|
|
749
|
+
} catch (err) {
|
|
750
|
+
if (!store) db.close();
|
|
751
|
+
throw err;
|
|
752
|
+
}
|
|
753
|
+
const actualPort = server.address().port;
|
|
754
|
+
const addresses = allowedAddresses({ host, port: actualPort, publicUrl: publicOrigin });
|
|
755
|
+
ctx.allowedHosts = new Set(addresses.hosts);
|
|
756
|
+
ctx.allowedOrigins = new Set(addresses.origins);
|
|
757
|
+
ctx.origin = addresses.origin;
|
|
758
|
+
return {
|
|
759
|
+
server,
|
|
760
|
+
port: actualPort,
|
|
761
|
+
token: secret,
|
|
762
|
+
origin: ctx.origin,
|
|
763
|
+
uiPath: ctx.uiPath,
|
|
764
|
+
url: secret && tokenRequired ? `${ctx.origin}/?token=${encodeURIComponent(secret)}` : ctx.origin,
|
|
765
|
+
close: () => new Promise((resolve) => {
|
|
766
|
+
server.close(() => {
|
|
767
|
+
if (!store) db.close();
|
|
768
|
+
resolve();
|
|
769
|
+
});
|
|
770
|
+
server.closeAllConnections();
|
|
771
|
+
}),
|
|
772
|
+
};
|
|
773
|
+
}
|