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/src/launchd.js ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * macOS scheduling: one launchd agent (~/Library/LaunchAgents/<label>.plist) per enabled
3
+ * routine. The routine `schedule` keeps the systemd OnCalendar syntax and is translated
4
+ * to StartCalendarInterval; forms launchd cannot express are refused before anything is written.
5
+ */
6
+ import { spawnSync } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+
11
+ import { stableNodeCommand } from './node-command.js';
12
+ import { scheduledEntries } from './task-schedule.js';
13
+ import { BIN_PATH, unitName } from './units.js';
14
+
15
+ const MAX_INTERVALS = 300;
16
+ const SHORTHANDS = {
17
+ hourly: [{ Minute: 0 }],
18
+ daily: [{ Hour: 0, Minute: 0 }],
19
+ weekly: [{ Weekday: 1, Hour: 0, Minute: 0 }],
20
+ monthly: [{ Day: 1, Hour: 0, Minute: 0 }],
21
+ yearly: [{ Month: 1, Day: 1, Hour: 0, Minute: 0 }],
22
+ annually: [{ Month: 1, Day: 1, Hour: 0, Minute: 0 }],
23
+ };
24
+ const WEEKDAYS = { mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6, sun: 0 };
25
+ const WEEKDAY_ORDER = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
26
+ const HINT = "use forms like 'hourly', 'daily', 'Mon *-*-* 09:00:00', 'Mon..Fri 08:30', '*-*-* 00/4:00:00' or '*-*-01 06:00'";
27
+
28
+ export function defaultLaunchAgentsDir() {
29
+ return path.join(os.homedir(), 'Library', 'LaunchAgents');
30
+ }
31
+
32
+ function fail(schedule, reason) {
33
+ throw new Error(`schedule '${schedule}' cannot be used with launchd: ${reason}; ${HINT}`);
34
+ }
35
+
36
+ /** Parse one numeric calendar field (`*`, `5`, `1,15`, `1..5`, `0/4`). null means any value. */
37
+ function parseField(text, min, max, schedule, name) {
38
+ if (text === '*') return null;
39
+ const values = new Set();
40
+ for (const item of text.split(',')) {
41
+ let match;
42
+ if ((match = /^(\*|\d+)\/(\d+)$/.exec(item))) {
43
+ const start = match[1] === '*' ? min : Number(match[1]);
44
+ const step = Number(match[2]);
45
+ if (step < 1) fail(schedule, `invalid step in ${name}`);
46
+ for (let v = start; v <= max; v += step) values.add(v);
47
+ } else if ((match = /^(\d+)\.\.(\d+)$/.exec(item))) {
48
+ for (let v = Number(match[1]); v <= Number(match[2]); v += 1) values.add(v);
49
+ } else if (/^\d+$/.test(item)) {
50
+ values.add(Number(item));
51
+ } else {
52
+ fail(schedule, `invalid ${name} '${item}'`);
53
+ }
54
+ }
55
+ for (const v of values) if (v < min || v > max) fail(schedule, `${name} ${v} is out of range`);
56
+ return [...values].sort((a, b) => a - b);
57
+ }
58
+
59
+ function parseWeekdays(text, schedule) {
60
+ const values = new Set();
61
+ for (const item of text.toLowerCase().split(',')) {
62
+ const [from, to, extra] = item.split('..').map((d) => d.slice(0, 3));
63
+ if (extra !== undefined || !(from in WEEKDAYS) || (to !== undefined && !(to in WEEKDAYS))) {
64
+ fail(schedule, `invalid weekday '${item}'`);
65
+ }
66
+ if (to === undefined) {
67
+ values.add(WEEKDAYS[from]);
68
+ continue;
69
+ }
70
+ const a = WEEKDAY_ORDER.indexOf(from);
71
+ const b = WEEKDAY_ORDER.indexOf(to);
72
+ if (b < a) fail(schedule, `invalid weekday range '${item}'`);
73
+ for (let i = a; i <= b; i += 1) values.add(WEEKDAYS[WEEKDAY_ORDER[i]]);
74
+ }
75
+ return [...values].sort((x, y) => x - y);
76
+ }
77
+
78
+ /**
79
+ * Translate a systemd OnCalendar expression into launchd StartCalendarInterval entries.
80
+ * Supports the shorthands (hourly, daily, weekly, monthly, yearly) and
81
+ * `[weekdays] [*-month-day] [hour:minute[:00]]` with `*`, lists, ranges and steps.
82
+ */
83
+ export function onCalendarToLaunchd(schedule) {
84
+ const text = schedule.trim();
85
+ const shorthand = SHORTHANDS[text.toLowerCase()];
86
+ if (shorthand) return shorthand.map((entry) => ({ ...entry }));
87
+
88
+ const tokens = text.split(/\s+/);
89
+ let weekdays = null;
90
+ let date = null;
91
+ let time = null;
92
+ if (/^[A-Za-z]/.test(tokens[0])) weekdays = parseWeekdays(tokens.shift(), schedule);
93
+ for (const token of tokens) {
94
+ if (time === null && token.includes(':') && !token.includes('-')) time = token;
95
+ else if (date === null && token.includes('-') && !token.includes(':')) date = token;
96
+ else fail(schedule, `unexpected '${token}'`);
97
+ }
98
+
99
+ const dateParts = (date ?? '*-*-*').split('-');
100
+ if (dateParts.length === 3) {
101
+ if (dateParts[0] !== '*') fail(schedule, 'a specific year is not supported');
102
+ dateParts.shift();
103
+ }
104
+ if (dateParts.length !== 2) fail(schedule, `invalid date '${date}'`);
105
+ const months = parseField(dateParts[0], 1, 12, schedule, 'month');
106
+ const days = parseField(dateParts[1], 1, 31, schedule, 'day');
107
+
108
+ const timeParts = (time ?? '00:00:00').split(':');
109
+ if (timeParts.length < 2 || timeParts.length > 3) fail(schedule, `invalid time '${time}'`);
110
+ if (timeParts.length === 3 && !/^0+$/.test(timeParts[2])) fail(schedule, 'seconds other than 00 are not supported');
111
+ const hours = parseField(timeParts[0], 0, 23, schedule, 'hour');
112
+ const minutes = parseField(timeParts[1], 0, 59, schedule, 'minute');
113
+
114
+ if (weekdays && days) fail(schedule, 'combining weekdays with specific days is not supported');
115
+ if (!minutes) fail(schedule, 'running every minute is not supported');
116
+
117
+ let entries = [{}];
118
+ for (const [key, values] of [['Month', months], ['Day', days], ['Weekday', weekdays], ['Hour', hours], ['Minute', minutes]]) {
119
+ if (!values) continue;
120
+ entries = entries.flatMap((entry) => values.map((v) => ({ ...entry, [key]: v })));
121
+ if (entries.length > MAX_INTERVALS) fail(schedule, `it expands to more than ${MAX_INTERVALS} intervals`);
122
+ }
123
+ return entries;
124
+ }
125
+
126
+ /**
127
+ * The next local time (a Date, after `from` and at least one minute later) when launchd would start
128
+ * a routine with this schedule, or null if none within a year. Throws like onCalendarToLaunchd.
129
+ */
130
+ export function nextRunAt(schedule, from = new Date()) {
131
+ const entries = onCalendarToLaunchd(schedule);
132
+ const start = new Date(from);
133
+ start.setSeconds(0, 0);
134
+ start.setMinutes(start.getMinutes() + 1);
135
+ for (let offset = 0; offset <= 366; offset += 1) {
136
+ const day = new Date(start.getFullYear(), start.getMonth(), start.getDate() + offset);
137
+ let best = null;
138
+ for (const entry of entries) {
139
+ if (entry.Month !== undefined && entry.Month !== day.getMonth() + 1) continue;
140
+ if (entry.Day !== undefined && entry.Day !== day.getDate()) continue;
141
+ if (entry.Weekday !== undefined && entry.Weekday !== day.getDay()) continue;
142
+ const hours = entry.Hour === undefined ? [...Array(24).keys()] : [entry.Hour];
143
+ for (const hour of hours) {
144
+ const at = new Date(day.getFullYear(), day.getMonth(), day.getDate(), hour, entry.Minute ?? 0);
145
+ if (at >= start && (best === null || at < best)) best = at;
146
+ }
147
+ }
148
+ if (best) return best;
149
+ }
150
+ return null;
151
+ }
152
+
153
+ const xml = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
154
+
155
+ /** The plist of one routine. */
156
+ export function renderPlist(config, routine, { env = process.env, nodeCommand = stableNodeCommand({ env }), binPath = BIN_PATH } = {}) {
157
+ const label = unitName(config, routine.name);
158
+ const logFile = path.join(config.logsDir, 'routines', `${routine.name}.log`);
159
+ const args = [...nodeCommand, binPath, '--config', config.path,
160
+ ...(routine.tidy ? ['task', 'tidy'] : ['routines', 'run', routine.name])];
161
+ const intervals = onCalendarToLaunchd(routine.schedule).map((entry) => [
162
+ ' <dict>',
163
+ ...Object.entries(entry).map(([key, value]) => ` <key>${key}</key><integer>${value}</integer>`),
164
+ ' </dict>',
165
+ ].join('\n'));
166
+ return [
167
+ '<?xml version="1.0" encoding="UTF-8"?>',
168
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
169
+ '<plist version="1.0">',
170
+ '<dict>',
171
+ ` <key>Label</key><string>${xml(label)}</string>`,
172
+ ' <key>ProgramArguments</key>',
173
+ ' <array>',
174
+ ...args.map((arg) => ` <string>${xml(arg)}</string>`),
175
+ ' </array>',
176
+ ` <key>WorkingDirectory</key><string>${xml(config.root)}</string>`,
177
+ ' <key>EnvironmentVariables</key>',
178
+ ' <dict>',
179
+ ` <key>PATH</key><string>${xml(env.PATH ?? '')}</string>`,
180
+ ` <key>HOME</key><string>${xml(env.HOME ?? os.homedir())}</string>`,
181
+ ' </dict>',
182
+ ` <key>StandardOutPath</key><string>${xml(logFile)}</string>`,
183
+ ` <key>StandardErrorPath</key><string>${xml(logFile)}</string>`,
184
+ ' <key>StartCalendarInterval</key>',
185
+ ' <array>',
186
+ ...intervals,
187
+ ' </array>',
188
+ ' <key>RunAtLoad</key><false/>',
189
+ '</dict>',
190
+ '</plist>',
191
+ '',
192
+ ].join('\n');
193
+ }
194
+
195
+ /** Run `launchctl args`; with check, a failure throws. */
196
+ export function runLaunchctl(args, { check = true } = {}) {
197
+ const result = spawnSync('launchctl', args, { stdio: ['ignore', 'inherit', 'pipe'] });
198
+ if (check && (result.error || result.status !== 0)) {
199
+ const reason = result.error ? result.error.message : `exit ${result.status}: ${String(result.stderr ?? '').trim()}`;
200
+ throw new Error(`launchctl ${args.join(' ')} failed: ${reason}`);
201
+ }
202
+ return result.status;
203
+ }
204
+
205
+ /**
206
+ * Install a launchd agent per enabled routine and remove those of disabled or deleted
207
+ * ones (every plist with the configured prefix). With uninstall, remove them all.
208
+ * Every schedule is translated before anything is written.
209
+ */
210
+ export function manageLaunchd(config, {
211
+ uninstall = false,
212
+ agentsDir = defaultLaunchAgentsDir(),
213
+ launchctl = runLaunchctl,
214
+ uid = process.getuid?.() ?? 0,
215
+ env = process.env,
216
+ nodeCommand = stableNodeCommand({ env }),
217
+ binPath = BIN_PATH,
218
+ } = {}) {
219
+ const prefix = config.unitPrefix;
220
+ const domain = `gui/${uid}`;
221
+ const desired = uninstall ? [] : scheduledEntries(config);
222
+ const plists = desired.map((routine) => [routine, renderPlist(config, routine, { env, nodeCommand, binPath })]);
223
+ fs.mkdirSync(agentsDir, { recursive: true });
224
+ fs.mkdirSync(path.join(config.logsDir, 'routines'), { recursive: true });
225
+
226
+ const desiredNames = new Set(desired.map((routine) => routine.name));
227
+ const existing = fs.readdirSync(agentsDir)
228
+ .filter((file) => file.startsWith(prefix) && file.endsWith('.plist'))
229
+ .map((file) => file.slice(prefix.length, -'.plist'.length));
230
+ const removed = existing.filter((name) => !desiredNames.has(name)).sort();
231
+ for (const name of removed) {
232
+ launchctl(['bootout', `${domain}/${prefix}${name}`], { check: false });
233
+ fs.rmSync(path.join(agentsDir, `${prefix}${name}.plist`), { force: true });
234
+ }
235
+ for (const [routine, plist] of plists) {
236
+ const label = unitName(config, routine.name);
237
+ const file = path.join(agentsDir, `${label}.plist`);
238
+ fs.writeFileSync(file, plist, 'utf8');
239
+ launchctl(['bootout', `${domain}/${label}`], { check: false });
240
+ launchctl(['bootstrap', domain, file], { check: true });
241
+ }
242
+ return { installed: [...desiredNames], removed };
243
+ }
package/src/lock.js ADDED
@@ -0,0 +1,62 @@
1
+ /** Per-routine lock: a file created exclusively ('wx') holding the owner's PID. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ /** True if a process with this PID exists (EPERM means it exists but is not ours). */
6
+ export function processAlive(pid) {
7
+ try {
8
+ process.kill(pid, 0);
9
+ return true;
10
+ } catch (err) {
11
+ return err.code === 'EPERM';
12
+ }
13
+ }
14
+
15
+ function readOwner(file) {
16
+ try {
17
+ return fs.readFileSync(file, 'utf8').trim();
18
+ } catch (err) {
19
+ if (err.code === 'ENOENT') return null;
20
+ throw err;
21
+ }
22
+ }
23
+
24
+ /** True if the lock exists and is held by a live process (an empty lock counts as held). */
25
+ export function isLockHeld(file, { isAlive = processAlive } = {}) {
26
+ const owner = readOwner(file);
27
+ if (owner === null) return false;
28
+ if (owner === '') return true;
29
+ const pid = Number(owner);
30
+ return Number.isInteger(pid) && pid > 0 && isAlive(pid);
31
+ }
32
+
33
+ /**
34
+ * Try to take the lock. Returns a release function, or null if another live
35
+ * process holds it. A lock whose PID no longer exists is removed and retried once.
36
+ * An empty lock file is treated as held: its owner may be about to write its PID.
37
+ */
38
+ export function acquireLock(file, { pid = process.pid, isAlive = processAlive } = {}) {
39
+ fs.mkdirSync(path.dirname(file), { recursive: true });
40
+ for (let attempt = 0; attempt < 2; attempt += 1) {
41
+ try {
42
+ const fd = fs.openSync(file, 'wx');
43
+ try {
44
+ fs.writeSync(fd, `${pid}\n`);
45
+ } finally {
46
+ fs.closeSync(fd);
47
+ }
48
+ return () => {
49
+ if (readOwner(file) === String(pid)) fs.rmSync(file, { force: true });
50
+ };
51
+ } catch (err) {
52
+ if (err.code !== 'EEXIST') throw err;
53
+ }
54
+ const owner = readOwner(file);
55
+ if (owner === null) continue; // released in between: retry
56
+ if (owner === '') return null;
57
+ const ownerPid = Number(owner);
58
+ if (Number.isInteger(ownerPid) && ownerPid > 0 && isAlive(ownerPid)) return null;
59
+ fs.rmSync(file, { force: true }); // stale: its process is gone
60
+ }
61
+ return null;
62
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,293 @@
1
+ /** Newline-delimited JSON-RPC MCP server. stdout is reserved for protocol messages. */
2
+ import { spawn as nodeSpawn } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import readline from 'node:readline';
6
+
7
+ import { parseModelArg } from './candidates.js';
8
+ import { loadConfig, TIER_SIZES } from './config.js';
9
+ import { isDueDate } from './due.js';
10
+ import { isValidScope } from './memory.js';
11
+ import { listConfiguredPersonas, loadConfiguredPersona, PERSONA_MODES } from './personas.js';
12
+ import { MAX_ANSWER_BYTES, readCapped, taskFromPrompt } from './server.js';
13
+ import { isLockHeld } from './lock.js';
14
+ import { nextRunAt } from './launchd.js';
15
+ import { openStore, TASK_PRIORITIES, TASK_STATUSES } from './store.js';
16
+ import { makeTracker } from './trackers/index.js';
17
+ import { BIN_PATH } from './units.js';
18
+ import { filterDoneSince, parseDoneSince } from './task-time.js';
19
+
20
+ const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
21
+ const PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
22
+ const prop = (type, description, extra = {}) => ({ type, description, ...extra });
23
+ const str = (description, extra) => prop('string', description, extra);
24
+ const num = (description, extra) => prop('integer', description, extra);
25
+ const bool = (description) => prop('boolean', description);
26
+ const schema = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
27
+ const id = num('Positive run or memory note ID.', { minimum: 1 });
28
+ const limit = num('Maximum results, from 1 to 500.', { minimum: 1, maximum: 500 });
29
+ const text = str('Nonempty text.');
30
+ const taskId = str('Task ID.');
31
+ const scope = str('Memory scope: global, persona:<name>, project:<id>, or routine:<name>.');
32
+ const status = str('Task status.', { enum: TASK_STATUSES });
33
+ const priority = str('Task priority.', { enum: TASK_PRIORITIES });
34
+ const due = str('Due date as YYYY-MM-DD.');
35
+ const taskFields = { title: text, notes: str('Task notes.'), status, priority, assignee: str('Assignee.'), due: str('Due date as YYYY-MM-DD, or none to clear it.') };
36
+ const TOOLS = [
37
+ ['agent_start', 'Start a detached persona run and return its reserved run ID.', schema({
38
+ persona: str('Persona name.'), task: text, size: str('Model tier.', { enum: TIER_SIZES }),
39
+ mode: str('Agent mode.', { enum: PERSONA_MODES }), model: str('Forced tool:model[@effort].'),
40
+ dir: str('Working directory relative to the workspace root.'), allow_paid: bool('Allow paid candidates.'),
41
+ dry_run: bool('Record a dry run without launching an agent runner.'),
42
+ }, ['persona', 'task'])],
43
+ ['run_show', 'Show a run and its capped answer.', schema({ run_id: id }, ['run_id'])],
44
+ ['runs_list', 'List recent runs.', schema({ kind: str('Run kind.', { enum: ['agent', 'routine'] }), name: str('Persona or routine name.'), status: str('Run status.', { enum: ['running', 'ok', 'issues', 'error', 'skipped'] }), limit })],
45
+ ['events', 'List agent and launcher messages.', schema({ run_id: id, since: num('Return events after this event ID.', { minimum: 0 }), limit })],
46
+ ['say', 'Send a reply to a running agent.', schema({ run_id: id, message: text }, ['run_id', 'message'])],
47
+ ['projects_list', 'List tracker projects and their display names.', schema({})],
48
+ ['task_list', 'List tracker tasks.', schema({ project: str('Project ID.'), status: str('Status filter.', { enum: [...TASK_STATUSES, 'all'] }), assignee: str('Assignee.'), due_before: due, done_since: str('YYYY-MM-DD or ISO datetime; includes open tasks and recently done tasks.') })],
49
+ ['task_show', 'Show a tracker task.', schema({ id: taskId }, ['id'])],
50
+ ['task_add', 'Create a tracker task.', schema({ project: text, title: text, notes: str('Task notes.'), priority, assignee: str('Assignee.'), due }, ['project', 'title'])],
51
+ ['task_update', 'Update tracker task fields.', schema({ id: taskId, ...taskFields }, ['id'])],
52
+ ['task_done', 'Mark a tracker task done.', schema({ id: taskId }, ['id'])],
53
+ ['task_comment', 'Comment on a tracker task.', schema({ id: taskId, text, author: str('Comment author.') }, ['id', 'text'])],
54
+ ['memory_add', 'Add a scoped memory note.', schema({ text, scope, author: str('Note author.') }, ['text'])],
55
+ ['memory_list', 'List memory notes.', schema({ scope, limit })],
56
+ ['memory_search', 'Search memory notes.', schema({ query: text, scope, limit }, ['query'])],
57
+ ['memory_remove', 'Delete a memory note.', schema({ id }, ['id'])],
58
+ ['routines_list', 'List configured routines.', schema({})],
59
+ ['routine_run', 'Start a detached routine run.', schema({ name: str('Routine name.'), dry_run: bool('Run without tracker writes.') }, ['name'])],
60
+ ['personas_list', 'List usable personas.', schema({})],
61
+ ].map(([name, description, inputSchema]) => ({ name, description, inputSchema }));
62
+ const TOOL_BY_NAME = new Map(TOOLS.map((tool) => [tool.name, tool]));
63
+ const object = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
64
+ const positive = (v) => Number.isSafeInteger(v) && v > 0;
65
+
66
+ class ParamsError extends Error {}
67
+ function validateInput(input, inputSchema, toolName) {
68
+ if (!object(input)) throw new ParamsError('arguments must be an object');
69
+ for (const key of Object.keys(input)) {
70
+ if (!(key in inputSchema.properties)) throw new ParamsError(`unknown argument: ${key}`);
71
+ const rule = inputSchema.properties[key];
72
+ const value = input[key];
73
+ if (rule.type === 'integer' ? !Number.isSafeInteger(value) : typeof value !== rule.type) throw new ParamsError(`${key} must be ${rule.type}`);
74
+ if (rule.enum && !rule.enum.includes(value)) throw new ParamsError(`${key} must be one of ${rule.enum.join(', ')}`);
75
+ if (rule.minimum !== undefined && value < rule.minimum || rule.maximum !== undefined && value > rule.maximum) throw new ParamsError(`${key} is out of range`);
76
+ }
77
+ for (const key of inputSchema.required) if (!(key in input)) throw new ParamsError(`missing argument: ${key}`);
78
+ for (const key of ['persona', 'task', 'message', 'project', 'title', 'id', 'text', 'query', 'name', 'dir']) {
79
+ if (key in input && typeof input[key] === 'string' && !input[key].trim()) throw new ParamsError(`${key} must not be empty`);
80
+ }
81
+ if (input.message?.length > 10_000) throw new ParamsError('message is longer than 10000 characters');
82
+ if (input.scope !== undefined && !isValidScope(input.scope)) throw new ParamsError('invalid memory scope');
83
+ if (input.due !== undefined && (input.due === 'none' ? toolName !== 'task_update' : !isDueDate(input.due))) throw new ParamsError('due must be YYYY-MM-DD');
84
+ if (input.due_before !== undefined && !isDueDate(input.due_before)) throw new ParamsError('due_before must be YYYY-MM-DD');
85
+ if (input.model !== undefined) {
86
+ try { parseModelArg(input.model); } catch (err) { throw new ParamsError(err.message); }
87
+ }
88
+ if (toolName === 'task_update' && Object.keys(input).length === 1) throw new ParamsError('task_update needs at least one field');
89
+ return input;
90
+ }
91
+
92
+ function stamp(file) {
93
+ try { const stat = fs.statSync(file); return `${stat.mtimeMs}:${stat.size}`; }
94
+ catch { return null; }
95
+ }
96
+ function cappedAnswer(run, config) {
97
+ if (!run.log_dir) return { answer: null, answer_truncated: false, answer_path: null };
98
+ try {
99
+ const dir = fs.realpathSync(run.log_dir);
100
+ const logs = fs.realpathSync(config.logsDir);
101
+ if (!dir.startsWith(`${logs}${path.sep}`)) return { answer: null, answer_truncated: false, answer_path: null };
102
+ const value = readCapped(path.join(dir, 'answer.md'), MAX_ANSWER_BYTES);
103
+ return { answer: value?.text ?? null, answer_truncated: value?.truncated ?? false,
104
+ answer_path: value ? path.join(dir, 'answer.md') : null };
105
+ } catch { return { answer: null, answer_truncated: false, answer_path: null }; }
106
+ }
107
+ function viewRun(run) { return { ...run, repo: run.work_dir ? path.basename(run.work_dir) : null }; }
108
+ function eventViews(db, rows) {
109
+ return rows.map((row) => {
110
+ const run = db.getRun(row.run_id);
111
+ return { ...row, run_name: run?.name ?? null, repo: run?.work_dir ? path.basename(run.work_dir) : null };
112
+ });
113
+ }
114
+ function detached(spawn, args, config, env, onFailure = () => {}) {
115
+ const child = spawn(process.execPath, [BIN_PATH, '--config', config.path, ...args], {
116
+ cwd: config.root, stdio: 'ignore', detached: true, env,
117
+ });
118
+ child.on?.('error', onFailure);
119
+ child.on?.('close', (code) => { if (code !== 0) onFailure(new Error(`detached process exited with code ${code}`)); });
120
+ child.unref?.();
121
+ if (!positive(child.pid)) throw new Error('detached process has no PID');
122
+ return child.pid;
123
+ }
124
+ function toolResult(value) {
125
+ const result = Array.isArray(value) ? { items: value } : value;
126
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], structuredContent: result };
127
+ }
128
+ function toolError(error) {
129
+ return { isError: true, content: [{ type: 'text', text: error.message }], structuredContent: { error: error.message } };
130
+ }
131
+
132
+ /** Serve until stdin ends. All collaborators are injectable for stream and process tests. */
133
+ export async function startMcpServer(config, {
134
+ stdin = process.stdin, stdout = process.stdout, stderr = process.stderr, env = process.env,
135
+ spawn = nodeSpawn, store = undefined, tracker = undefined,
136
+ } = {}) {
137
+ const db = store ?? openStore(config.root);
138
+ let current = config;
139
+ let configStamp = stamp(config.path);
140
+ let activeTracker = tracker ?? null;
141
+ const refresh = () => {
142
+ const nextStamp = stamp(config.path);
143
+ if (nextStamp === configStamp) return;
144
+ configStamp = nextStamp;
145
+ try {
146
+ const next = loadConfig(config.path);
147
+ if (next.root !== current.root) throw new Error(`root changed from ${current.root} to ${next.root}; restart crewboss mcp to use it`);
148
+ current = next;
149
+ if (!tracker) activeTracker = null;
150
+ } catch (err) { stderr.write(`crewboss mcp: keeping the previous configuration: ${err.message}\n`); }
151
+ };
152
+ const taskTracker = () => {
153
+ activeTracker ??= makeTracker(current.tracker, current.root, { store: db });
154
+ for (const method of ['listTasks', 'getTask', 'updateTask', 'commentTask']) {
155
+ if (typeof activeTracker[method] !== 'function') throw new Error(`the ${current.tracker.type} tracker does not support task commands`);
156
+ }
157
+ return activeTracker;
158
+ };
159
+ const listProjects = async () => {
160
+ const active = taskTracker();
161
+ return typeof active.listProjects === 'function' ? active.listProjects() : [];
162
+ };
163
+ const call = async (name, a) => {
164
+ const t = taskTracker;
165
+ switch (name) {
166
+ case 'agent_start': {
167
+ const persona = loadConfiguredPersona(current, a.persona);
168
+ const workDir = path.resolve(current.root, a.dir ?? persona.dir);
169
+ if (!fs.existsSync(workDir) || !fs.statSync(workDir).isDirectory()) throw new Error(`working directory not found: ${workDir}`);
170
+ const runId = db.startRun({ kind: 'agent', name: persona.name, dryRun: a.dry_run ?? false, workDir, reserved: true });
171
+ const args = ['agent', a.persona, a.task, '--run-id', String(runId)];
172
+ for (const [key, flag] of [['size', '--size'], ['mode', '--mode'], ['model', '--model'], ['dir', '--dir']]) if (a[key] !== undefined) args.push(flag, a[key]);
173
+ if (a.allow_paid) args.push('--allow-paid');
174
+ if (a.dry_run) args.push('--dry-run');
175
+ try {
176
+ const pid = detached(spawn, args, current, env, (err) => {
177
+ try {
178
+ const run = db.getRun(runId);
179
+ if (run?.status === 'running' && run.pid === null) db.finishRun(runId, { status: 'error', exitCode: 1, summary: err.message });
180
+ } catch { /* The MCP stream may have closed after the child exited. */ }
181
+ });
182
+ return { run_id: runId, persona: persona.name, pid, status: 'running' };
183
+ } catch (err) {
184
+ db.finishRun(runId, { status: 'error', exitCode: 1, summary: err.message });
185
+ throw err;
186
+ }
187
+ }
188
+ case 'run_show': {
189
+ const run = db.getRun(a.run_id);
190
+ if (!run) throw new Error(`run not found: ${a.run_id}`);
191
+ let task = '';
192
+ if (run.kind === 'agent' && run.log_dir) {
193
+ const prompt = readCapped(path.join(run.log_dir, 'prompt.txt'), MAX_ANSWER_BYTES);
194
+ if (prompt) task = taskFromPrompt(prompt.text);
195
+ }
196
+ return { ...viewRun(run), task, ...cappedAnswer(run, current) };
197
+ }
198
+ case 'runs_list': return db.listRuns({ kind: a.kind ?? null, name: a.name ?? null, limit: 500 }).filter((r) => !a.status || r.status === a.status).slice(0, a.limit ?? 50).map(viewRun);
199
+ case 'events': return eventViews(db, db.listEvents({ runId: a.run_id ?? null, since: a.since ?? 0, limit: a.limit ?? 100 }));
200
+ case 'say': {
201
+ const run = db.getRun(a.run_id);
202
+ if (!run) throw new Error(`run not found: ${a.run_id}`);
203
+ if (run.status !== 'running') throw new Error(`run ${run.id} already finished (${run.status}); nobody will read it`);
204
+ return eventViews(db, [db.addEvent(run.id, { direction: 'in', kind: 'reply', message: a.message.trim() })])[0];
205
+ }
206
+ case 'task_list': {
207
+ if (a.done_since) parseDoneSince(a.done_since);
208
+ let rows = await t().listTasks({ project: a.project ?? null, status: a.done_since && a.status === undefined ? 'all' : a.status ?? null,
209
+ assignee: a.assignee ?? null, doneSince: a.done_since ?? null });
210
+ if (a.done_since) rows = filterDoneSince(rows, a.done_since);
211
+ if (a.due_before) rows = rows.filter((row) => row.due && row.due <= a.due_before);
212
+ return rows;
213
+ }
214
+ case 'projects_list': return listProjects();
215
+ case 'task_show': {
216
+ const row = await t().getTask(a.id);
217
+ if (!row) throw new Error(`task not found: ${a.id}`);
218
+ return row;
219
+ }
220
+ case 'task_add': return { id: await t().createTask(a.project.trim(), a.title.trim(), a.notes ?? '', a.priority ?? 'medium', a.assignee ?? '', a.due) };
221
+ case 'task_update': return t().updateTask(a.id, Object.fromEntries(Object.entries(a).filter(([k]) => k !== 'id').map(([k, v]) => [k, k === 'due' && v === 'none' ? null : v])));
222
+ case 'task_done': return t().updateTask(a.id, { status: 'done' });
223
+ case 'task_comment': return t().commentTask(a.id, a.author ?? env.USER ?? '', a.text);
224
+ case 'memory_add': return db.addMemory({ scope: a.scope ?? 'global', text: a.text, author: a.author ?? env.USER ?? '' });
225
+ case 'memory_list': return db.listMemory({ scopes: a.scope ? [a.scope] : null, limit: a.limit ?? 50 });
226
+ case 'memory_search': return db.searchMemory(a.query, { scopes: a.scope ? [a.scope] : null, limit: a.limit ?? 20 });
227
+ case 'memory_remove':
228
+ if (!db.removeMemory(a.id)) throw new Error(`memory note not found: ${a.id}`);
229
+ return { id: a.id, removed: true };
230
+ case 'routines_list': {
231
+ let projects = [];
232
+ try { projects = await listProjects(); } catch { /* Routines remain available without project names. */ }
233
+ const projectNames = new Map(projects.map((project) => [String(project.id), String(project.name)]));
234
+ return current.routines.map((r) => {
235
+ let nextRun = null;
236
+ if (r.enabled) {
237
+ try { nextRun = nextRunAt(r.schedule, new Date())?.toISOString() ?? null; } catch { /* Some schedules cannot be expressed on this platform. */ }
238
+ }
239
+ return { name: r.name, mod: r.mod ?? null, enabled: r.enabled, schedule: r.schedule, mode: r.mode, project: r.project,
240
+ project_name: projectNames.get(String(r.project)) ?? String(r.project),
241
+ choice: 'size' in r ? `size ${r.size}` : `${r.tool}:${r.model}`,
242
+ running: isLockHeld(path.join(current.logsDir, 'routines', `${r.name}.lock`)),
243
+ last: db.listRuns({ kind: 'routine', name: r.name, limit: 1 })[0] ?? null, next_run: nextRun };
244
+ });
245
+ }
246
+ case 'routine_run': {
247
+ if (!current.routines.some((r) => r.name === a.name)) throw new Error(`unknown routine: ${a.name}`);
248
+ if (isLockHeld(path.join(current.logsDir, 'routines', `${a.name}.lock`))) throw new Error(`routine ${a.name} is already running`);
249
+ const pid = detached(spawn, ['routines', 'run', a.name, ...(a.dry_run ? ['--dry-run'] : [])], current, env);
250
+ return { started: true, routine: a.name, pid };
251
+ }
252
+ case 'personas_list': return listConfiguredPersonas(current).map((p) => ({
253
+ name: p.name, mod: p.mod, size: p.size, mode: p.mode, dir: p.dir, description: p.body.split(/\r?\n/)[0],
254
+ }));
255
+ default: throw new ParamsError(`unknown tool: ${name}`);
256
+ }
257
+ };
258
+ const send = (message) => stdout.write(`${JSON.stringify(message)}\n`);
259
+ const error = (idValue, code, message) => send({ jsonrpc: '2.0', id: idValue, error: { code, message } });
260
+ try {
261
+ for await (const line of readline.createInterface({ input: stdin, crlfDelay: Infinity })) {
262
+ let request;
263
+ try { request = JSON.parse(line); } catch { error(null, -32700, 'Parse error'); continue; }
264
+ if (!object(request) || request.jsonrpc !== '2.0' || typeof request.method !== 'string' || ('id' in request && !(typeof request.id === 'string' || typeof request.id === 'number'))) {
265
+ error(object(request) && 'id' in request ? request.id : null, -32600, 'Invalid Request');
266
+ continue;
267
+ }
268
+ const hasId = 'id' in request;
269
+ if (!hasId) continue;
270
+ try {
271
+ let result;
272
+ if (request.method === 'initialize') {
273
+ if (!object(request.params) || typeof request.params.protocolVersion !== 'string') throw new ParamsError('initialize needs protocolVersion');
274
+ result = { protocolVersion: PROTOCOLS.includes(request.params.protocolVersion) ? request.params.protocolVersion : PROTOCOLS[0], capabilities: { tools: {} }, serverInfo: { name: 'crewboss', version: VERSION }, instructions: 'Crewboss runs coding agents, routines, tasks, and memory. Agent runs are asynchronous: start one, then poll events and run_show.' };
275
+ } else if (request.method === 'ping') result = {};
276
+ else if (request.method === 'tools/list') result = { tools: TOOLS };
277
+ else if (request.method === 'tools/call') {
278
+ if (!object(request.params) || typeof request.params.name !== 'string') throw new ParamsError('tools/call needs a tool name');
279
+ const tool = TOOL_BY_NAME.get(request.params.name);
280
+ if (!tool) throw new ParamsError(`unknown tool: ${request.params.name}`);
281
+ const args = validateInput(request.params.arguments === undefined ? {} : request.params.arguments, tool.inputSchema, tool.name);
282
+ refresh();
283
+ try { result = toolResult(await call(tool.name, args)); }
284
+ catch (err) { result = toolError(err); }
285
+ } else { error(request.id, -32601, 'Method not found'); continue; }
286
+ send({ jsonrpc: '2.0', id: request.id, result });
287
+ } catch (err) {
288
+ if (err instanceof ParamsError) error(request.id, -32602, err.message);
289
+ else { stderr.write(`crewboss mcp: ${err.stack ?? err.message}\n`); error(request.id, -32603, 'Internal error'); }
290
+ }
291
+ }
292
+ } finally { if (!store) db.close(); }
293
+ }