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/memory.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory notes with a scope: `global`, `persona:<name>`, `project:<id>` or
|
|
3
|
+
* `routine:<name>`. Prompts get the newest notes of their scopes under "# Memory".
|
|
4
|
+
*/
|
|
5
|
+
import { NAME_RE } from './config.js';
|
|
6
|
+
import { openStore } from './store.js';
|
|
7
|
+
|
|
8
|
+
export const MEMORY_ACTIONS = ['add', 'list', 'search', 'rm'];
|
|
9
|
+
export const DEFAULT_MEMORY_MAX_BYTES = 8192;
|
|
10
|
+
/** How many recent notes are considered for a prompt before the byte cap applies. */
|
|
11
|
+
const PROMPT_CANDIDATES = 500;
|
|
12
|
+
|
|
13
|
+
export function isValidScope(scope) {
|
|
14
|
+
if (typeof scope !== 'string') return false;
|
|
15
|
+
if (scope === 'global') return true;
|
|
16
|
+
const colon = scope.indexOf(':');
|
|
17
|
+
if (colon === -1) return false;
|
|
18
|
+
const kind = scope.slice(0, colon);
|
|
19
|
+
const value = scope.slice(colon + 1);
|
|
20
|
+
if (kind === 'persona') return NAME_RE.test(value) || value.split('/').length === 2 && value.split('/').every((part) => NAME_RE.test(part));
|
|
21
|
+
if (kind === 'routine') return NAME_RE.test(value);
|
|
22
|
+
if (kind === 'project') return value.trim() !== '' && !/[\r\n]/.test(value);
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const agentScopes = (personaName) => ['global', `persona:${personaName}`];
|
|
27
|
+
export const routineScopes = (routine) => ['global', `routine:${routine.name}`, `project:${routine.project}`];
|
|
28
|
+
/** Scopes a routine report may write to: its own routine and its project. */
|
|
29
|
+
export const routineReportScopes = (routine) => [`routine:${routine.name}`, `project:${routine.project}`];
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The "# Memory" section with the newest notes of `scopes` whose lines fit in
|
|
33
|
+
* maxBytes, or '' when there are none (or maxBytes is 0).
|
|
34
|
+
*/
|
|
35
|
+
export function memorySection(store, scopes, maxBytes = DEFAULT_MEMORY_MAX_BYTES) {
|
|
36
|
+
if (!maxBytes) return '';
|
|
37
|
+
const lines = [];
|
|
38
|
+
let used = 0;
|
|
39
|
+
for (const note of store.listMemory({ scopes, limit: PROMPT_CANDIDATES })) {
|
|
40
|
+
const line = `- [${note.scope}] ${note.text.replace(/\s*\n\s*/g, ' ')}`;
|
|
41
|
+
const size = Buffer.byteLength(`${line}\n`, 'utf8');
|
|
42
|
+
if (used + size > maxBytes) break;
|
|
43
|
+
lines.push(line);
|
|
44
|
+
used += size;
|
|
45
|
+
}
|
|
46
|
+
return lines.length ? `# Memory\n\n${lines.join('\n')}\n` : '';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function formatNote(note) {
|
|
50
|
+
return `#${note.id} [${note.scope}] ${note.text} (${note.author || 'anonymous'}, ${note.created_at})`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Run one memory action. Resolves with the exit code; a missing note is an error. */
|
|
54
|
+
export async function runMemoryCommand(config, action, args, { store = undefined, stdout = process.stdout, env = process.env } = {}) {
|
|
55
|
+
const db = store ?? openStore(config.root);
|
|
56
|
+
try {
|
|
57
|
+
const print = (value, text) => stdout.write(args.json ? `${JSON.stringify(value, null, 2)}\n` : text);
|
|
58
|
+
const scopes = args.scope ? [args.scope] : null;
|
|
59
|
+
const limit = args.limit === undefined ? undefined : Number(args.limit);
|
|
60
|
+
if (action === 'add') {
|
|
61
|
+
const note = db.addMemory({ scope: args.scope ?? 'global', text: args.text, author: args.author ?? env.USER ?? '' });
|
|
62
|
+
print(note, `${note.id}\n`);
|
|
63
|
+
return 0;
|
|
64
|
+
}
|
|
65
|
+
if (action === 'list' || action === 'search') {
|
|
66
|
+
const notes = action === 'list'
|
|
67
|
+
? db.listMemory({ scopes, ...(limit ? { limit } : {}) })
|
|
68
|
+
: db.searchMemory(args.query, { scopes, ...(limit ? { limit } : {}) });
|
|
69
|
+
print(notes, notes.length ? `${notes.map(formatNote).join('\n')}\n` : 'No notes.\n');
|
|
70
|
+
return 0;
|
|
71
|
+
}
|
|
72
|
+
if (action === 'rm') {
|
|
73
|
+
if (!db.removeMemory(Number(args.id))) throw new Error(`memory note not found: ${args.id}`);
|
|
74
|
+
print({ id: Number(args.id), removed: true }, `removed #${args.id}\n`);
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
throw new Error(`unknown memory action: ${action}`);
|
|
78
|
+
} finally {
|
|
79
|
+
if (!store) db.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
package/src/mods.js
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
/** Git-backed mod installation. All git calls use an argv array and an injectable spawn. */
|
|
2
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { NAME_RE, validateModManifest } from './config.js';
|
|
7
|
+
import { acquireLock } from './lock.js';
|
|
8
|
+
import { isDir, isFile } from './fsutil.js';
|
|
9
|
+
|
|
10
|
+
const SHA = /^[0-9a-f]{40}$/i;
|
|
11
|
+
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
12
|
+
const PRIVATE_REPO_HINT = 'private repositories need git credentials (for example an SSH URL: git@github.com:owner/repo.git)';
|
|
13
|
+
|
|
14
|
+
function gitSource(source, cwd) {
|
|
15
|
+
if (source.startsWith('github:')) {
|
|
16
|
+
const repo = source.slice(7);
|
|
17
|
+
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) throw new Error('invalid github:owner/repo source');
|
|
18
|
+
return `https://github.com/${repo}.git`;
|
|
19
|
+
}
|
|
20
|
+
if (/^(https:\/\/|ssh:\/\/|git@)[^\s]+/.test(source)) return source;
|
|
21
|
+
const local = path.resolve(cwd, source);
|
|
22
|
+
if (!isDir(local)) throw new Error(`local git source is not a folder: ${local}`);
|
|
23
|
+
return local;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Default runner; tests can inject git(args, cwd) instead of spawning a CLI. */
|
|
27
|
+
export function spawnGit(args, cwd, spawn = nodeSpawn, {
|
|
28
|
+
env = process.env, timeoutMs = ['clone', 'fetch', 'ls-remote'].includes(args[0]) ? 300_000 : 60_000,
|
|
29
|
+
kill = process.kill, setTimer = setTimeout, clearTimer = clearTimeout,
|
|
30
|
+
} = {}) {
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
let child;
|
|
33
|
+
try { child = spawn('git', args, { cwd, shell: false, detached: true,
|
|
34
|
+
stdio: ['ignore', 'pipe', 'pipe'], env: { ...env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never' } }); }
|
|
35
|
+
catch (err) { reject(new Error(`git ${args[0]}: ${err.message}`)); return; }
|
|
36
|
+
let out = '';
|
|
37
|
+
let errOut = '';
|
|
38
|
+
let done = false;
|
|
39
|
+
const finish = (error) => {
|
|
40
|
+
if (done) return;
|
|
41
|
+
done = true;
|
|
42
|
+
clearTimer(timer);
|
|
43
|
+
if (error) reject(error); else resolve(out.trim());
|
|
44
|
+
};
|
|
45
|
+
const timer = setTimer(() => {
|
|
46
|
+
try { if (child.pid) kill(-child.pid, 'SIGKILL'); else child.kill?.('SIGKILL'); }
|
|
47
|
+
catch { try { child.kill?.('SIGKILL'); } catch {} }
|
|
48
|
+
finish(new Error(`git ${args[0]} timed out after ${timeoutMs / 1000}s`));
|
|
49
|
+
}, timeoutMs);
|
|
50
|
+
child.stdout.on('data', (chunk) => { out += chunk; });
|
|
51
|
+
child.stderr.on('data', (chunk) => { errOut = (errOut + chunk).slice(-4096); });
|
|
52
|
+
child.on('error', (err) => finish(new Error(`git ${args[0]}: ${err.message}`)));
|
|
53
|
+
child.on('close', (code) => finish(code === 0 ? null
|
|
54
|
+
: new Error(`git ${args[0]} failed (${code}): ${errOut.trim().slice(-1200)}`)));
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function clone(git, source, dest, base, cwd) {
|
|
59
|
+
try { await git(['clone', '--', gitSource(source, cwd), dest], base); }
|
|
60
|
+
catch (err) {
|
|
61
|
+
if (/^(github:|https:\/\/)/.test(source) &&
|
|
62
|
+
/authenticat|credentials|permission denied|could not read username|repository not found|access denied|403|401/i.test(err.message)) {
|
|
63
|
+
throw new Error(`${err.message}\n${PRIVATE_REPO_HINT}`);
|
|
64
|
+
}
|
|
65
|
+
throw err;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function githubRepo(source) {
|
|
70
|
+
const match = source?.match(/^(?:github:|https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\/?$/i);
|
|
71
|
+
return match?.[1].toLowerCase() ?? null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function searchMods(mods, args, { fetch, env, stdout }) {
|
|
75
|
+
const params = new URLSearchParams({ q: `topic:crewboss-mod${args.query ? ` ${args.query}` : ''}`,
|
|
76
|
+
sort: 'stars', order: 'desc', per_page: String(args.limit ?? 20) });
|
|
77
|
+
const headers = { Accept: 'application/vnd.github+json', 'User-Agent': `crewboss/${VERSION}` };
|
|
78
|
+
if (env.GITHUB_TOKEN) headers.Authorization = `Bearer ${env.GITHUB_TOKEN}`;
|
|
79
|
+
let response;
|
|
80
|
+
try {
|
|
81
|
+
response = await fetch(`https://api.github.com/search/repositories?${params}`, {
|
|
82
|
+
headers, signal: AbortSignal.timeout(15_000),
|
|
83
|
+
});
|
|
84
|
+
} catch (err) {
|
|
85
|
+
throw new Error(`GitHub mod search network failure: ${err.message}`);
|
|
86
|
+
}
|
|
87
|
+
if (response.status === 403 || response.status === 429) {
|
|
88
|
+
const reset = response.headers?.get('x-ratelimit-reset');
|
|
89
|
+
const date = reset && Number.isFinite(Number(reset)) ? new Date(Number(reset) * 1000).toISOString() : null;
|
|
90
|
+
throw new Error(`GitHub mod search rate limit exceeded${date ? `; resets at ${date}` : ''}`);
|
|
91
|
+
}
|
|
92
|
+
if (!response.ok) throw new Error(`GitHub mod search failed (HTTP ${response.status})`);
|
|
93
|
+
let data;
|
|
94
|
+
try { data = await response.json(); }
|
|
95
|
+
catch (err) { throw new Error(`GitHub mod search returned invalid JSON: ${err.message}`); }
|
|
96
|
+
const installedSources = new Set(Object.values(mods).map((entry) => githubRepo(entry.source)).filter(Boolean));
|
|
97
|
+
const items = (data.items ?? []).map((repo) => ({
|
|
98
|
+
full_name: repo.full_name, stars: repo.stargazers_count, updated_at: repo.updated_at?.slice(0, 10) ?? '',
|
|
99
|
+
description: repo.description ?? '', installed: installedSources.has(repo.full_name.toLowerCase()),
|
|
100
|
+
install_command: `crewboss mod add github:${repo.full_name}`,
|
|
101
|
+
}));
|
|
102
|
+
if (args.json) stdout.write(JSON.stringify(items) + '\n');
|
|
103
|
+
else if (!items.length) stdout.write('No mods found.\n');
|
|
104
|
+
else for (const item of items) stdout.write(`${item.full_name} ★${item.stars} ${item.updated_at} ${item.description.replace(/\s+/g, ' ')} ${item.install_command}${item.installed ? ' [installed]' : ''}\n`);
|
|
105
|
+
return 0;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function readData(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
109
|
+
|
|
110
|
+
function writeMods(file, mods) {
|
|
111
|
+
const data = readData(file);
|
|
112
|
+
data.mods = mods;
|
|
113
|
+
const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);
|
|
114
|
+
try {
|
|
115
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { encoding: 'utf8', mode: fs.statSync(file).mode });
|
|
116
|
+
fs.renameSync(tmp, file);
|
|
117
|
+
} finally { fs.rmSync(tmp, { force: true }); }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function manifestAt(dir) { return readData(path.join(dir, 'crewboss-mod.json')); }
|
|
121
|
+
function sourceManifestAt(dir, source, sha) {
|
|
122
|
+
try { return manifestAt(dir); }
|
|
123
|
+
catch (err) {
|
|
124
|
+
if (err.code === 'ENOENT') throw new Error(`${source} at ${sha.slice(0, 12)} has no crewboss-mod.json at the repository root; it is not a crewboss mod`);
|
|
125
|
+
throw new Error(`${source}: crewboss-mod.json is not valid JSON: ${err.message}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function validateSourceManifest(dir, name, source, sha) {
|
|
129
|
+
// Read first so absent and unreadable/malformed files have source-oriented diagnostics.
|
|
130
|
+
sourceManifestAt(dir, source, sha);
|
|
131
|
+
try { return validateModManifest(dir, name); }
|
|
132
|
+
catch (err) {
|
|
133
|
+
if (/invalid manifest JSON:/.test(err.message)) {
|
|
134
|
+
throw new Error(`${source}: crewboss-mod.json is not valid JSON: ${err.message.split('invalid manifest JSON: ').at(-1)}`);
|
|
135
|
+
}
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function personas(dir, manifest) {
|
|
140
|
+
if (!manifest.personas) return [];
|
|
141
|
+
return fs.readdirSync(path.join(dir, manifest.personas)).filter((name) => name.endsWith('.md')).map((name) => name.slice(0, -3)).sort();
|
|
142
|
+
}
|
|
143
|
+
function summary(dir, manifest, sha, source) {
|
|
144
|
+
return { name: manifest.name, description: manifest.description ?? '', source, commit: sha,
|
|
145
|
+
personas: personas(dir, manifest), routines: (manifest.routines ?? []).map((r) => ({ name: r.name, schedule: r.schedule,
|
|
146
|
+
mode: r.mode ?? 'read', ...(r.collect ? { collect: r.collect, runsCommands: true } : {}) })), ui: manifest.ui ?? null };
|
|
147
|
+
}
|
|
148
|
+
function displaySummary(item, stdout) {
|
|
149
|
+
stdout.write(`Name: ${item.name}\nDescription: ${item.description}\nSource: ${item.source}\nCommit: ${item.commit}\n`);
|
|
150
|
+
stdout.write(`Personas: ${item.personas.join(', ') || 'none'}\nRoutines:\n`);
|
|
151
|
+
for (const r of item.routines) stdout.write(` ${r.name}: ${r.schedule} (${r.mode})${r.collect ? `\n runs commands: ${r.collect}` : ''}\n`);
|
|
152
|
+
stdout.write(`UI: ${item.ui ?? 'none'}\n`);
|
|
153
|
+
}
|
|
154
|
+
async function confirm({ yes, stdin, stderr, action = 'Install' }) {
|
|
155
|
+
if (yes) return true;
|
|
156
|
+
if (!stdin.isTTY) throw new Error('confirmation requires a TTY; use --yes to proceed');
|
|
157
|
+
stderr.write(`${action}? [y/N] `);
|
|
158
|
+
return new Promise((resolve) => {
|
|
159
|
+
let answer = '';
|
|
160
|
+
const onData = (chunk) => {
|
|
161
|
+
answer += chunk;
|
|
162
|
+
if (!answer.includes('\n') && !answer.includes('\r')) return;
|
|
163
|
+
stdin.off('data', onData);
|
|
164
|
+
resolve(/^y(?:es)?$/i.test(answer.trim()));
|
|
165
|
+
};
|
|
166
|
+
stdin.on('data', onData);
|
|
167
|
+
stdin.once('end', () => resolve(false));
|
|
168
|
+
stdin.resume?.();
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function head(git, dir, ref, { remote = false } = {}) {
|
|
173
|
+
let target = ref;
|
|
174
|
+
if (!target && remote) {
|
|
175
|
+
const remoteHead = await git(['ls-remote', '--symref', 'origin', 'HEAD'], dir);
|
|
176
|
+
target = remoteHead.match(/^ref:\s+refs\/heads\/([^\s]+)\s+HEAD/m)?.[1];
|
|
177
|
+
if (!target) throw new Error('could not resolve remote default branch');
|
|
178
|
+
}
|
|
179
|
+
if (!target) target = 'HEAD';
|
|
180
|
+
const candidates = !remote || SHA.test(target) ? [`${target}^{commit}`, `refs/remotes/origin/${target}^{commit}`]
|
|
181
|
+
: [`refs/remotes/origin/${target}^{commit}`, `${target}^{commit}`];
|
|
182
|
+
let last;
|
|
183
|
+
for (const candidate of candidates) {
|
|
184
|
+
try {
|
|
185
|
+
const sha = await git(['rev-parse', '--verify', candidate], dir);
|
|
186
|
+
if (!SHA.test(sha)) throw new Error(`git returned invalid commit: ${sha}`);
|
|
187
|
+
return sha;
|
|
188
|
+
} catch (err) { last = err; }
|
|
189
|
+
}
|
|
190
|
+
throw last;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function checkoutPinned(git, dir, sha) {
|
|
194
|
+
try { await git(['checkout', '--detach', sha], dir); }
|
|
195
|
+
catch {
|
|
196
|
+
await git(['fetch', 'origin', sha], dir);
|
|
197
|
+
await git(['checkout', '--detach', sha], dir);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function requireClean(output, name) {
|
|
202
|
+
if (output.trim()) throw new Error(`mod ${name} has local changes; clean the folder before continuing`);
|
|
203
|
+
}
|
|
204
|
+
function diffManifest(oldManifest, next) {
|
|
205
|
+
const diff = (a, b) => ({ added: b.filter((x) => !a.includes(x)), removed: a.filter((x) => !b.includes(x)) });
|
|
206
|
+
const oldNames = (oldManifest.routines ?? []).map((r) => r.name);
|
|
207
|
+
const newNames = (next.routines ?? []).map((r) => r.name);
|
|
208
|
+
const changedCollect = newNames.filter((name) => oldNames.includes(name) &&
|
|
209
|
+
(oldManifest.routines.find((r) => r.name === name).collect ?? null) !== (next.routines.find((r) => r.name === name).collect ?? null))
|
|
210
|
+
.map((name) => ({ name, from: oldManifest.routines.find((r) => r.name === name).collect ?? null,
|
|
211
|
+
to: next.routines.find((r) => r.name === name).collect ?? null }));
|
|
212
|
+
return { personas: diff(oldManifest._personas ?? [], next._personas ?? []), routines: diff(oldNames, newNames), changedCollect };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function runModCommand(config, action, args, {
|
|
216
|
+
cwd = process.cwd(), stdin = process.stdin, stdout = process.stdout, stderr = process.stderr,
|
|
217
|
+
spawn = nodeSpawn, git: injectedGit, lock = acquireLock, fetch = globalThis.fetch, env = process.env,
|
|
218
|
+
} = {}) {
|
|
219
|
+
const git = injectedGit ?? ((argv, dir) => spawnGit(argv, dir, spawn));
|
|
220
|
+
const base = path.join(config.root, '.crewboss', 'mods');
|
|
221
|
+
const configFile = config.path;
|
|
222
|
+
if (action === 'search') return searchMods(readData(configFile).mods ?? {}, args, { fetch, env, stdout });
|
|
223
|
+
fs.mkdirSync(base, { recursive: true });
|
|
224
|
+
const release = lock(path.join(base, '.lock'));
|
|
225
|
+
if (!release) throw new Error('another mod operation is running');
|
|
226
|
+
const emit = (value) => args.json ? stdout.write(JSON.stringify(value) + '\n') : stdout.write(`${value}\n`);
|
|
227
|
+
try {
|
|
228
|
+
const data = readData(configFile);
|
|
229
|
+
const mods = data.mods ?? {};
|
|
230
|
+
if (action === 'list') {
|
|
231
|
+
const items = Object.entries(mods).map(([name, entry]) => {
|
|
232
|
+
const dir = path.join(base, name);
|
|
233
|
+
const installed = isFile(path.join(dir, 'crewboss-mod.json'));
|
|
234
|
+
return { name, source: entry.source ?? null, commit: entry.commit?.slice(0, 12) ?? null,
|
|
235
|
+
installed, description: installed ? manifestAt(dir).description ?? '' : '', enabledRoutines: entry.routines ?? [] };
|
|
236
|
+
});
|
|
237
|
+
if (args.json) emit(items);
|
|
238
|
+
else for (const item of items) emit(`${item.name} ${item.commit ?? '-'} ${item.installed ? 'installed' : 'missing'} ${item.source ?? '-'} ${item.description} routines: ${item.enabledRoutines.join(', ') || 'none'}`);
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
if (action === 'add') {
|
|
242
|
+
const temp = fs.mkdtempSync(path.join(base, '.add-'));
|
|
243
|
+
try {
|
|
244
|
+
await clone(git, args.source, temp, base, cwd);
|
|
245
|
+
const sha = await head(git, temp, args.ref);
|
|
246
|
+
await git(['checkout', '--detach', sha], temp);
|
|
247
|
+
const manifest = sourceManifestAt(temp, args.source, sha);
|
|
248
|
+
if (!NAME_RE.test(manifest.name ?? '')) throw new Error(`invalid manifest name: ${JSON.stringify(manifest.name)}`);
|
|
249
|
+
validateModManifest(temp, manifest.name);
|
|
250
|
+
const name = manifest.name;
|
|
251
|
+
const target = path.join(base, name);
|
|
252
|
+
if (Object.hasOwn(mods, name) || fs.existsSync(target)) throw new Error(`mod ${name} is already installed; use mod update`);
|
|
253
|
+
const review = summary(temp, manifest, sha, args.source);
|
|
254
|
+
if (args.json) emit({ review }); else displaySummary(review, stdout);
|
|
255
|
+
if (!await confirm({ ...args, stdin, stdout, stderr })) { emit(args.json ? { status: 'cancelled' } : 'Cancelled.'); return 0; }
|
|
256
|
+
fs.renameSync(temp, target);
|
|
257
|
+
try { writeMods(configFile, { ...mods, [name]: { source: args.source, commit: sha } }); }
|
|
258
|
+
catch (err) { fs.renameSync(target, temp); throw err; }
|
|
259
|
+
emit(args.json ? { status: 'installed', ...review } : `Installed ${name} at ${sha}. Routines are disabled. To enable them, add names to mods.${name}.routines in crewboss.json, then run crewboss routines install.`);
|
|
260
|
+
return 0;
|
|
261
|
+
} finally { fs.rmSync(temp, { recursive: true, force: true }); }
|
|
262
|
+
}
|
|
263
|
+
const name = args.name;
|
|
264
|
+
if (action === 'install') {
|
|
265
|
+
const results = [];
|
|
266
|
+
for (const [modName, entry] of Object.entries(mods)) {
|
|
267
|
+
try {
|
|
268
|
+
if (!entry.source || !entry.commit || !SHA.test(entry.commit)) throw new Error(`mod ${modName} needs a source and full pinned commit`);
|
|
269
|
+
const dir = path.join(base, modName);
|
|
270
|
+
if (!fs.existsSync(dir)) {
|
|
271
|
+
const temp = fs.mkdtempSync(path.join(base, '.install-'));
|
|
272
|
+
try {
|
|
273
|
+
await clone(git, entry.source, temp, base, cwd);
|
|
274
|
+
await checkoutPinned(git, temp, entry.commit);
|
|
275
|
+
validateSourceManifest(temp, modName, entry.source, entry.commit);
|
|
276
|
+
fs.renameSync(temp, dir);
|
|
277
|
+
results.push({ name: modName, status: 'cloned', commit: entry.commit });
|
|
278
|
+
} finally { fs.rmSync(temp, { recursive: true, force: true }); }
|
|
279
|
+
} else {
|
|
280
|
+
requireClean(await git(['status', '--porcelain'], dir), modName);
|
|
281
|
+
const current = await git(['rev-parse', 'HEAD'], dir);
|
|
282
|
+
if (current !== entry.commit) {
|
|
283
|
+
await git(['fetch', 'origin'], dir);
|
|
284
|
+
await checkoutPinned(git, dir, entry.commit);
|
|
285
|
+
try { validateSourceManifest(dir, modName, entry.source, entry.commit); }
|
|
286
|
+
catch (err) { await git(['checkout', '--detach', current], dir); throw err; }
|
|
287
|
+
}
|
|
288
|
+
results.push({ name: modName, status: current === entry.commit ? 'current' : 'checked out', commit: entry.commit });
|
|
289
|
+
}
|
|
290
|
+
} catch (err) {
|
|
291
|
+
results.push({ name: modName, status: 'error', error: err.message });
|
|
292
|
+
stderr.write(`crewboss: error: ${modName}: ${err.message}\n`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (args.json) emit(results); else for (const item of results) emit(`${item.name}: ${item.status} ${item.commit ?? item.error}`);
|
|
296
|
+
return results.some((item) => item.status === 'error') ? 1 : 0;
|
|
297
|
+
}
|
|
298
|
+
if (!Object.hasOwn(mods, name)) throw new Error(`mod ${name} is not configured`);
|
|
299
|
+
const dir = path.join(base, name);
|
|
300
|
+
if (action === 'remove') {
|
|
301
|
+
if (data.ui === `mod:${name}`) throw new Error(`mod ${name} is used by ui; change ui first`);
|
|
302
|
+
if (mods[name].routines?.length) throw new Error(`mod ${name} has enabled routines; remove mods.${name}.routines first`);
|
|
303
|
+
if (!await confirm({ ...args, stdin, stderr, action: 'Remove' })) { emit('Cancelled.'); return 0; }
|
|
304
|
+
const retired = path.join(base, `.remove-${name}-${process.pid}`);
|
|
305
|
+
if (fs.existsSync(dir)) fs.renameSync(dir, retired);
|
|
306
|
+
try {
|
|
307
|
+
const next = { ...mods }; delete next[name]; writeMods(configFile, next);
|
|
308
|
+
} catch (err) { if (fs.existsSync(retired)) fs.renameSync(retired, dir); throw err; }
|
|
309
|
+
fs.rmSync(retired, { recursive: true, force: true });
|
|
310
|
+
emit(`Removed ${name}.`);
|
|
311
|
+
return 0;
|
|
312
|
+
}
|
|
313
|
+
if (!isDir(dir)) throw new Error(`mod ${name} is missing; run crewboss mod install`);
|
|
314
|
+
requireClean(await git(['status', '--porcelain'], dir), name);
|
|
315
|
+
const old = await git(['rev-parse', 'HEAD'], dir);
|
|
316
|
+
if (mods[name].commit && old !== mods[name].commit) {
|
|
317
|
+
throw new Error(`mod ${name} is at ${old}, not its configured commit ${mods[name].commit}; run crewboss mod install first`);
|
|
318
|
+
}
|
|
319
|
+
await git(['fetch', 'origin'], dir);
|
|
320
|
+
const sha = await head(git, dir, args.ref, { remote: true });
|
|
321
|
+
if (old === sha) { emit(args.json ? { name, status: 'current', commit: sha } : `${name} is already at ${sha}.`); return 0; }
|
|
322
|
+
const oldManifest = manifestAt(dir);
|
|
323
|
+
oldManifest._personas = personas(dir, oldManifest);
|
|
324
|
+
let nextManifest;
|
|
325
|
+
try { nextManifest = JSON.parse(await git(['show', `${sha}:crewboss-mod.json`], dir)); }
|
|
326
|
+
catch (err) {
|
|
327
|
+
if (/crewboss-mod\.json/.test(err.message) && /path .* does not exist|does not exist in/.test(err.message)) {
|
|
328
|
+
throw new Error(`${mods[name].source} at ${sha.slice(0, 12)} has no crewboss-mod.json at the repository root; it is not a crewboss mod`);
|
|
329
|
+
}
|
|
330
|
+
if (err instanceof SyntaxError) throw new Error(`${mods[name].source}: crewboss-mod.json is not valid JSON: ${err.message}`);
|
|
331
|
+
throw err;
|
|
332
|
+
}
|
|
333
|
+
nextManifest._personas = nextManifest.personas
|
|
334
|
+
? (await git(['ls-tree', '--name-only', `${sha}:${nextManifest.personas}`], dir)).split('\n').filter((item) => item.endsWith('.md')).map((item) => item.slice(0, -3)).sort()
|
|
335
|
+
: [];
|
|
336
|
+
const changes = diffManifest(oldManifest, nextManifest);
|
|
337
|
+
const commits = await git(['log', '--oneline', `${old}..${sha}`], dir);
|
|
338
|
+
const review = { name, source: mods[name].source, from: old, to: sha, commits, changes };
|
|
339
|
+
if (args.json) emit({ review }); else {
|
|
340
|
+
stdout.write(`Update ${name}: ${old} -> ${sha}\n${commits}\n`);
|
|
341
|
+
stdout.write(`Personas: +${changes.personas.added.join(', ')} -${changes.personas.removed.join(', ')}\n`);
|
|
342
|
+
stdout.write(`Routines: +${changes.routines.added.join(', ')} -${changes.routines.removed.join(', ')}\n`);
|
|
343
|
+
for (const item of changes.changedCollect) stdout.write(`Changed collect ${item.name}: ${item.from ?? '(none)'} -> ${item.to ?? '(none)'} (runs commands)\n`);
|
|
344
|
+
}
|
|
345
|
+
if (!await confirm({ ...args, stdin, stdout, stderr })) { emit(args.json ? { status: 'cancelled' } : 'Cancelled.'); return 0; }
|
|
346
|
+
await git(['checkout', '--detach', sha], dir);
|
|
347
|
+
try {
|
|
348
|
+
validateSourceManifest(dir, name, mods[name].source, sha);
|
|
349
|
+
writeMods(configFile, { ...mods, [name]: { ...mods[name], commit: sha } });
|
|
350
|
+
} catch (err) { await git(['checkout', '--detach', old], dir); throw err; }
|
|
351
|
+
emit(args.json ? { status: 'updated', ...review } : `Updated ${name} to ${sha}.`);
|
|
352
|
+
return 0;
|
|
353
|
+
} finally { release(); }
|
|
354
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Stable way to start Node from a systemd unit or launchd agent. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
/** A path segment that looks like a version: `26.10.0`, `v22.1.0`, `node@22`, `22.1`. */
|
|
6
|
+
const VERSIONED_SEGMENT = /^(?:v?\d+\.\d+(?:\.\d+)?|[^/]*@\d+(?:\.\d+)*)$/;
|
|
7
|
+
|
|
8
|
+
export function hasVersionedPath(file) {
|
|
9
|
+
return file.split(/[\\/]/).some((segment) => VERSIONED_SEGMENT.test(segment));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Words that start Node in a unit, immune to version-manager upgrades.
|
|
14
|
+
*
|
|
15
|
+
* Looks for `node` in the directories of the PATH the unit stores (`env.PATH`, absolute entries only, in order)
|
|
16
|
+
* and takes the first one that is executable, has no version in its path (`26.10.0`, `v22.1.0`, `node@22`) and
|
|
17
|
+
* either resolves to the same file as `execPath` (symlinks such as `/opt/homebrew/bin/node`) or lives in a
|
|
18
|
+
* `shims` directory (mise, asdf: shims pick the version themselves, so they cannot be compared).
|
|
19
|
+
* If none qualifies: `['/usr/bin/env', 'node']`, and Node is found through the stored PATH when the unit runs.
|
|
20
|
+
*/
|
|
21
|
+
export function stableNodeCommand({ env = process.env, execPath = process.execPath, fsApi = fs } = {}) {
|
|
22
|
+
const real = (file) => { try { return fsApi.realpathSync(file); } catch { return null; } };
|
|
23
|
+
const runnable = (file) => { try { fsApi.accessSync(file, fs.constants.X_OK); return true; } catch { return false; } };
|
|
24
|
+
const current = real(execPath);
|
|
25
|
+
for (const dir of (env.PATH ?? '').split(path.delimiter)) {
|
|
26
|
+
if (!path.isAbsolute(dir)) continue;
|
|
27
|
+
const candidate = path.join(dir, 'node');
|
|
28
|
+
if (hasVersionedPath(candidate) || !runnable(candidate)) continue;
|
|
29
|
+
const resolved = real(candidate);
|
|
30
|
+
if (resolved === null) continue;
|
|
31
|
+
if (path.basename(dir) === 'shims' || (current !== null && resolved === current)) return [candidate];
|
|
32
|
+
}
|
|
33
|
+
return ['/usr/bin/env', 'node'];
|
|
34
|
+
}
|
package/src/personas.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/** Agent personas: Markdown files with front matter and a body of instructions. */
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { NAME_RE, TIER_SIZES } from './config.js';
|
|
6
|
+
import { isFile } from './fsutil.js';
|
|
7
|
+
|
|
8
|
+
export const PERSONA_MODES = ['read', 'write'];
|
|
9
|
+
|
|
10
|
+
function unquote(value) {
|
|
11
|
+
if (value.length >= 2 && value[0] === value.at(-1) && (value[0] === '"' || value[0] === "'")) {
|
|
12
|
+
return value.slice(1, -1);
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Parse a small YAML-like front matter (scalars, booleans, lists). Returns {metadata, body}. */
|
|
18
|
+
export function parseFrontMatter(text) {
|
|
19
|
+
const lines = text.split(/\r?\n/);
|
|
20
|
+
if (!lines.length || lines[0].trim() !== '---') throw new Error('missing front matter');
|
|
21
|
+
const end = lines.findIndex((line, i) => i > 0 && line.trim() === '---');
|
|
22
|
+
if (end === -1) throw new Error('unclosed front matter');
|
|
23
|
+
|
|
24
|
+
const metadata = {};
|
|
25
|
+
let listKey = null;
|
|
26
|
+
for (const line of lines.slice(1, end)) {
|
|
27
|
+
const stripped = line.trim();
|
|
28
|
+
if (!stripped || stripped.startsWith('#')) continue;
|
|
29
|
+
if (stripped.startsWith('- ') && listKey) {
|
|
30
|
+
metadata[listKey].push(unquote(stripped.slice(2).trim()));
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
listKey = null;
|
|
34
|
+
const colon = stripped.indexOf(':');
|
|
35
|
+
if (colon === -1) continue;
|
|
36
|
+
const key = stripped.slice(0, colon).trim();
|
|
37
|
+
const val = stripped.slice(colon + 1).trim();
|
|
38
|
+
if (!val) {
|
|
39
|
+
metadata[key] = [];
|
|
40
|
+
listKey = key;
|
|
41
|
+
} else if (val.startsWith('[') && val.endsWith(']')) {
|
|
42
|
+
const inner = val.slice(1, -1).trim();
|
|
43
|
+
metadata[key] = inner ? inner.split(',').map((item) => unquote(item.trim())) : [];
|
|
44
|
+
} else {
|
|
45
|
+
const scalar = unquote(val);
|
|
46
|
+
const lower = scalar.toLowerCase();
|
|
47
|
+
metadata[key] = lower === 'true' ? true : lower === 'false' ? false : scalar;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return { metadata, body: lines.slice(end + 1).join('\n').trim() };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Load <personasDir>/<name>.md and validate its front matter and body. */
|
|
54
|
+
export function loadPersona(name, personasDir, root, { mod = null, skillsRoot = root } = {}) {
|
|
55
|
+
if (!NAME_RE.test(name)) throw new Error(`invalid persona name: '${name}'`);
|
|
56
|
+
const file = path.resolve(personasDir, `${name}.md`);
|
|
57
|
+
if (!isFile(file)) throw new Error(`persona file not found: ${file}`);
|
|
58
|
+
if (mod && !fs.realpathSync(file).startsWith(`${fs.realpathSync(skillsRoot)}${path.sep}`)) {
|
|
59
|
+
throw new Error(`persona '${name}' file must stay inside mod ${mod}`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
let parsed;
|
|
63
|
+
try {
|
|
64
|
+
parsed = parseFrontMatter(fs.readFileSync(file, 'utf8'));
|
|
65
|
+
} catch {
|
|
66
|
+
throw new Error(`persona '${name}' has no front matter; cannot be used as an executing agent`);
|
|
67
|
+
}
|
|
68
|
+
const { metadata, body } = parsed;
|
|
69
|
+
if (!body) throw new Error(`persona '${name}' body is empty`);
|
|
70
|
+
|
|
71
|
+
const personaName = metadata.name;
|
|
72
|
+
if (typeof personaName !== 'string' || !NAME_RE.test(personaName)) {
|
|
73
|
+
throw new Error(`persona '${name}' front matter invalid name: ${JSON.stringify(personaName)}`);
|
|
74
|
+
}
|
|
75
|
+
if (!TIER_SIZES.includes(metadata.size)) {
|
|
76
|
+
throw new Error(`persona '${name}' front matter invalid size: ${JSON.stringify(metadata.size)}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const skills = metadata.skills ?? [];
|
|
80
|
+
if (!Array.isArray(skills)) throw new Error(`persona '${name}' front matter skills must be a list`);
|
|
81
|
+
for (const skill of skills) {
|
|
82
|
+
if (typeof skill !== 'string' || !skill.trim()) throw new Error(`persona '${name}' invalid skill path: ${JSON.stringify(skill)}`);
|
|
83
|
+
const skillPath = path.resolve(skillsRoot, skill);
|
|
84
|
+
if (!isFile(skillPath)) throw new Error(`persona '${name}' skill file not found: ${skill}`);
|
|
85
|
+
if (mod) {
|
|
86
|
+
const relative = path.relative(skillsRoot, skillPath);
|
|
87
|
+
if (!relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)
|
|
88
|
+
|| !fs.realpathSync(skillPath).startsWith(`${fs.realpathSync(skillsRoot)}${path.sep}`)) {
|
|
89
|
+
throw new Error(`persona '${name}' skill must stay inside mod ${mod}: ${skill}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const dir = metadata.dir ?? '.';
|
|
95
|
+
if (typeof dir !== 'string' || !dir.trim()) throw new Error(`persona '${name}' invalid dir: ${JSON.stringify(dir)}`);
|
|
96
|
+
|
|
97
|
+
const mode = metadata.mode ?? 'write';
|
|
98
|
+
if (!PERSONA_MODES.includes(mode)) {
|
|
99
|
+
throw new Error(`persona '${name}' front matter invalid mode: ${JSON.stringify(mode)} (expected read or write)`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const toolList = (key) => {
|
|
103
|
+
const list = metadata[key] ?? [];
|
|
104
|
+
if (!Array.isArray(list) || !list.every((t) => typeof t === 'string' && t.trim())) {
|
|
105
|
+
throw new Error(`persona '${name}' ${key} must be a list of names`);
|
|
106
|
+
}
|
|
107
|
+
return list;
|
|
108
|
+
};
|
|
109
|
+
const allowedTools = toolList('allowed_tools');
|
|
110
|
+
const disallowedTools = toolList('disallowed_tools');
|
|
111
|
+
|
|
112
|
+
return { name: mod ? `${mod}/${name}` : personaName, mod, skillsRoot, size: metadata.size, mode, skills, dir, allowedTools, disallowedTools, body };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Workspace personas win unqualified lookups; mod personas can always be qualified. */
|
|
116
|
+
export function loadConfiguredPersona(config, name) {
|
|
117
|
+
const parts = name.split('/');
|
|
118
|
+
if (parts.length === 2) {
|
|
119
|
+
const [mod, persona] = parts;
|
|
120
|
+
const entry = Object.hasOwn(config.mods ?? {}, mod) ? config.mods[mod] : null;
|
|
121
|
+
if (!entry?.personasDir) throw new Error(`mod persona not found: ${name}`);
|
|
122
|
+
return loadPersona(persona, entry.personasDir, config.root, { mod, skillsRoot: entry.dir });
|
|
123
|
+
}
|
|
124
|
+
if (!NAME_RE.test(name)) throw new Error(`invalid persona name: '${name}'`);
|
|
125
|
+
if (isFile(path.join(config.personasDir, `${name}.md`))) return loadPersona(name, config.personasDir, config.root);
|
|
126
|
+
const matches = Object.values(config.mods ?? {}).filter((entry) => entry.personasDir && isFile(path.join(entry.personasDir, `${name}.md`)));
|
|
127
|
+
if (matches.length > 1) throw new Error(`ambiguous persona '${name}': ${matches.map((entry) => `${entry.name}/${name}`).join(', ')}`);
|
|
128
|
+
if (matches.length) return loadPersona(name, matches[0].personasDir, config.root, { mod: matches[0].name, skillsRoot: matches[0].dir });
|
|
129
|
+
return loadPersona(name, config.personasDir, config.root);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** List each mod persona by its qualified name, including shadowed ones. */
|
|
133
|
+
export function listConfiguredPersonas(config) {
|
|
134
|
+
const files = (dir) => fs.readdirSync(dir).filter((file) => file.endsWith('.md') && NAME_RE.test(file.slice(0, -3)));
|
|
135
|
+
const result = files(config.personasDir).map((file) => loadPersona(file.slice(0, -3), config.personasDir, config.root));
|
|
136
|
+
for (const entry of Object.values(config.mods ?? {})) {
|
|
137
|
+
if (!entry.personasDir) continue;
|
|
138
|
+
for (const file of files(entry.personasDir)) {
|
|
139
|
+
result.push(loadPersona(file.slice(0, -3), entry.personasDir, config.root, { mod: entry.name, skillsRoot: entry.dir }));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Prompt = preamble + persona body + each skill file + memory section (if any) + communication section (if any) + the task. */
|
|
146
|
+
export function buildPrompt(persona, task, root, preamble = '', memory = '', communication = '') {
|
|
147
|
+
const parts = preamble.trim() ? [preamble.trim()] : [];
|
|
148
|
+
parts.push(persona.body);
|
|
149
|
+
for (const skill of persona.skills) parts.push(fs.readFileSync(path.resolve(persona.skillsRoot ?? root, skill), 'utf8'));
|
|
150
|
+
if (memory.trim()) parts.push(memory.trim());
|
|
151
|
+
if (communication.trim()) parts.push(communication.trim());
|
|
152
|
+
parts.push(`# Task\n\n${task}`);
|
|
153
|
+
return `${parts.join('\n\n')}\n`;
|
|
154
|
+
}
|
package/src/plugin.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Executable plugins: run without a shell in the root, send one JSON on stdin,
|
|
3
|
+
* read one JSON from stdout. Non-zero exit, timeout or invalid JSON raise PluginError
|
|
4
|
+
* carrying the tail of stderr.
|
|
5
|
+
*/
|
|
6
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
7
|
+
|
|
8
|
+
import { PluginError, TimeoutError } from './errors.js';
|
|
9
|
+
import { waitForExit } from './process.js';
|
|
10
|
+
|
|
11
|
+
const STDERR_TAIL = 2000;
|
|
12
|
+
|
|
13
|
+
function stderrTail(stderr) {
|
|
14
|
+
const text = stderr.trim();
|
|
15
|
+
return text ? `; stderr: ${text.slice(-STDERR_TAIL)}` : '';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function runPlugin(command, input, { cwd, timeoutSeconds = 60, spawn = nodeSpawn, kill } = {}) {
|
|
19
|
+
const label = command.join(' ');
|
|
20
|
+
const child = spawn(command[0], command.slice(1), { cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: true });
|
|
21
|
+
let stdout = '';
|
|
22
|
+
let stderr = '';
|
|
23
|
+
child.stdout.setEncoding('utf8');
|
|
24
|
+
child.stderr.setEncoding('utf8');
|
|
25
|
+
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
|
26
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
27
|
+
child.stdin.on('error', () => {}); // the plugin may exit without reading its input
|
|
28
|
+
child.stdin.end(`${JSON.stringify(input)}\n`);
|
|
29
|
+
|
|
30
|
+
let code;
|
|
31
|
+
try {
|
|
32
|
+
code = await waitForExit(child, { timeoutSeconds, kill });
|
|
33
|
+
} catch (err) {
|
|
34
|
+
if (err instanceof TimeoutError) throw new PluginError(`plugin '${label}' timed out after ${timeoutSeconds}s${stderrTail(stderr)}`);
|
|
35
|
+
throw new PluginError(`plugin '${label}' failed to start: ${err.message}`);
|
|
36
|
+
}
|
|
37
|
+
if (code !== 0) throw new PluginError(`plugin '${label}' exited ${code}${stderrTail(stderr)}`);
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(stdout);
|
|
40
|
+
} catch (err) {
|
|
41
|
+
throw new PluginError(`plugin '${label}' returned invalid JSON: ${err.message}${stderrTail(stderr)}`);
|
|
42
|
+
}
|
|
43
|
+
}
|