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.
@@ -0,0 +1,26 @@
1
+ /** Runner for the `agy` CLI. The working directory is the process cwd. */
2
+
3
+ export const ANSWER_ON_STDOUT = true;
4
+ /** allowed_tools / disallowed_tools are not mapped: the launcher notes it in agent.log. */
5
+ export const SUPPORTS_TOOL_LISTS = false;
6
+ export const SUPPORTS_ATTACHMENT = false;
7
+
8
+ export function buildCommand(candidate, prompt, { mode } = {}) {
9
+ const effort = candidate.effort ? ['--effort', candidate.effort] : [];
10
+ if (mode === 'write') {
11
+ return ['agy', '--model', candidate.model, '--output-format', 'text', ...effort,
12
+ '--dangerously-skip-permissions', `-p=${prompt}`];
13
+ }
14
+ return ['agy', '-p', prompt, '--model', candidate.model, '--mode', 'plan', '--sandbox', '--output-format', 'text', ...effort];
15
+ }
16
+
17
+ export function warnings() {
18
+ return [];
19
+ }
20
+
21
+ /** Write mode skips permissions, so the commands run; the read-mode sandbox may block them. */
22
+ export function communicationNote(mode) {
23
+ return mode === 'write'
24
+ ? null
25
+ : 'note: the agy read-mode sandbox may block `crewboss notify` / `crewboss inbox`; if they fail, say so in the answer';
26
+ }
@@ -0,0 +1,39 @@
1
+ /** Runner for the Claude Code CLI (`claude`). */
2
+ import { assertCommunicationAllowed, claudeAllowedTools } from '../events.js';
3
+
4
+ /** The answer is the process stdout, which the launcher writes to answer.md. */
5
+ export const ANSWER_ON_STDOUT = true;
6
+ export const SUPPORTS_ATTACHMENT = false;
7
+ /** Honours allowed_tools / disallowed_tools (in both modes). */
8
+ export const SUPPORTS_TOOL_LISTS = true;
9
+
10
+ /**
11
+ * Build the `claude` command. The working directory is the process cwd. Agents are always
12
+ * allowed `crewboss notify` and `crewboss inbox` (see events.js), plus SendMessage and ListAgents
13
+ * when a live session was named with `notify`.
14
+ */
15
+ export function buildCommand(candidate, prompt, { mode, allowedTools = [], disallowedTools = [], notify = null } = {}) {
16
+ assertCommunicationAllowed(disallowedTools);
17
+ const allowed = claudeAllowedTools(allowedTools, { notify });
18
+ const cmd = [
19
+ 'claude', '-p', prompt,
20
+ '--model', candidate.model,
21
+ '--output-format', 'text',
22
+ '--permission-mode', mode === 'write' ? 'acceptEdits' : 'plan',
23
+ ];
24
+ cmd.push('--allowedTools', allowed.join(','));
25
+ if (disallowedTools.length) cmd.push('--disallowedTools', disallowedTools.join(','));
26
+ return cmd;
27
+ }
28
+
29
+ /** Notes about candidate options this CLI cannot honour. */
30
+ export function warnings(candidate) {
31
+ return candidate.effort
32
+ ? [`warning: effort '${candidate.effort}' is not supported by claude and was ignored`]
33
+ : [];
34
+ }
35
+
36
+ /** Claude Code runs the channel commands with the permissions buildCommand grants: no extra note. */
37
+ export function communicationNote() {
38
+ return null;
39
+ }
@@ -0,0 +1,26 @@
1
+ /** Runner for the Codex CLI (`codex exec`). */
2
+ import path from 'node:path';
3
+
4
+ /** Codex writes the answer itself with -o; stdout and stderr go to agent.log. */
5
+ export const ANSWER_ON_STDOUT = false;
6
+ /** allowed_tools / disallowed_tools are not mapped: the launcher notes it in agent.log. */
7
+ export const SUPPORTS_TOOL_LISTS = false;
8
+ export const SUPPORTS_ATTACHMENT = false;
9
+
10
+ export function buildCommand(candidate, prompt, { runDir, workDir, mode } = {}) {
11
+ const sandbox = mode === 'write' ? 'workspace-write' : 'read-only';
12
+ const cmd = ['codex', 'exec', '-C', String(workDir), '-s', sandbox, '-m', candidate.model, '-c', 'features.apps=false'];
13
+ if (candidate.effort) cmd.push('-c', `model_reasoning_effort=${candidate.effort}`);
14
+ return [...cmd, '-o', path.join(runDir, 'answer.md'), prompt];
15
+ }
16
+
17
+ export function warnings() {
18
+ return [];
19
+ }
20
+
21
+ /** The sandbox keeps the agent from writing the store (outside its working directory), or from running anything at all. */
22
+ export function communicationNote(mode) {
23
+ return mode === 'write'
24
+ ? 'note: the codex workspace-write sandbox may block `crewboss notify` / `crewboss inbox` (they write the crewboss store, outside the working directory); if they fail, say so in the answer'
25
+ : 'note: the codex read-only sandbox blocks `crewboss notify` / `crewboss inbox` (they write the crewboss store); the agent cannot talk to whoever launched it';
26
+ }
@@ -0,0 +1,186 @@
1
+ /** CLI runners: build each tool's command, launch it, and fall back within a tier on startup failure. */
2
+ import { spawn as nodeSpawn } from 'node:child_process';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ import { communicationNotes } from '../events.js';
7
+ import { findBinary } from '../fsutil.js';
8
+ import { formatCandidateLabel } from '../label.js';
9
+ import { waitForExit } from '../process.js';
10
+ import { isoNow } from '../rundir.js';
11
+ import { withoutSessionCredentials } from '../session.js';
12
+ import * as agy from './agy.js';
13
+ import * as claude from './claude.js';
14
+ import * as codex from './codex.js';
15
+ import * as opencode from './opencode.js';
16
+
17
+ export const RUNNERS = { claude, codex, agy, opencode };
18
+ export const TOOLS = new Set(Object.keys(RUNNERS));
19
+ export const MODES = new Set(['read', 'write']);
20
+ export const STARTUP_ERROR_STRINGS = ['429', 'model_not_found', 'Free usage limit', 'quota'];
21
+ const STARTUP_WINDOW_SECONDS = 60;
22
+
23
+ export function getRunner(tool) {
24
+ const runner = RUNNERS[tool];
25
+ if (!runner) throw new Error(`unknown tool '${tool}', expected one of ${[...TOOLS].sort().join(', ')}`);
26
+ return runner;
27
+ }
28
+
29
+ export function buildCommand(candidate, prompt, {
30
+ runDir, workDir, mode = 'write', attachment = null, allowedTools = [], disallowedTools = [], notify = null,
31
+ } = {}) {
32
+ if (!MODES.has(mode)) throw new Error(`invalid mode '${mode}'`);
33
+ return getRunner(candidate.tool).buildCommand(candidate, prompt, {
34
+ runDir, workDir, mode, attachment, allowedTools, disallowedTools, notify,
35
+ });
36
+ }
37
+
38
+ /** Notes for agent.log: the runner's own warnings plus tool lists it cannot honour. */
39
+ export function launchWarnings(candidate, { mode = 'write', allowedTools = [], disallowedTools = [] } = {}) {
40
+ const runner = getRunner(candidate.tool);
41
+ const notes = [...runner.warnings(candidate)];
42
+ const channel = runner.communicationNote(mode);
43
+ if (channel) notes.push(channel);
44
+ if (candidate.tool === 'claude') notes.push(...communicationNotes(disallowedTools));
45
+ if (!runner.SUPPORTS_TOOL_LISTS) {
46
+ if (allowedTools.length) notes.push(`warning: allowed_tools is not supported by ${candidate.tool} and was ignored`);
47
+ if (disallowedTools.length) notes.push(`warning: disallowed_tools is not supported by ${candidate.tool} and was ignored`);
48
+ }
49
+ return notes;
50
+ }
51
+
52
+ /**
53
+ * Run the candidate's CLI with stdin closed. agent.log gets stdout and stderr;
54
+ * answer.md gets the answer. `env` is added to the child's environment (crewboss puts
55
+ * CREWBOSS_RUN_ID and CREWBOSS_CONFIG there for every runner). Resolves with {returncode, duration} (seconds).
56
+ */
57
+ export async function launch(candidate, prompt, runDir, workDir, {
58
+ mode = 'write',
59
+ attachment = null,
60
+ allowedTools = [],
61
+ disallowedTools = [],
62
+ notify = null,
63
+ env = {},
64
+ timeoutSeconds = null,
65
+ spawn = nodeSpawn,
66
+ which = findBinary,
67
+ kill = process.kill.bind(process),
68
+ } = {}) {
69
+ const runner = getRunner(candidate.tool);
70
+ const binary = which(candidate.tool);
71
+ if (!binary) {
72
+ throw new Error(`Required binary '${candidate.tool}' not found in PATH: ${process.env.PATH ?? ''}`);
73
+ }
74
+ const cmd = buildCommand(candidate, prompt, { runDir, workDir, mode, attachment, allowedTools, disallowedTools, notify });
75
+ cmd[0] = binary;
76
+
77
+ const answerPath = path.join(runDir, 'answer.md');
78
+ const logFd = fs.openSync(path.join(runDir, 'agent.log'), 'a');
79
+ let answerFd = null;
80
+ try {
81
+ for (const note of launchWarnings(candidate, { mode, allowedTools, disallowedTools })) fs.writeSync(logFd, `${note}\n`);
82
+ let stdio;
83
+ if (runner.ANSWER_ON_STDOUT) {
84
+ answerFd = fs.openSync(answerPath, 'w');
85
+ stdio = ['ignore', answerFd, logFd];
86
+ } else {
87
+ stdio = ['ignore', logFd, logFd];
88
+ }
89
+ const start = performance.now();
90
+ const child = spawn(cmd[0], cmd.slice(1), {
91
+ cwd: workDir, stdio, env: withoutSessionCredentials({ ...process.env, ...env }), detached: timeoutSeconds != null,
92
+ });
93
+ const returncode = await waitForExit(child, { timeoutSeconds, kill });
94
+ const duration = (performance.now() - start) / 1000;
95
+ if (answerFd !== null) {
96
+ fs.closeSync(answerFd);
97
+ answerFd = null;
98
+ // Copy stdout to agent.log so it holds both streams.
99
+ const answer = fs.readFileSync(answerPath, 'utf8');
100
+ if (answer) fs.writeSync(logFd, `\n${answer}`);
101
+ }
102
+ return { returncode, duration };
103
+ } finally {
104
+ if (answerFd !== null) fs.closeSync(answerFd);
105
+ fs.closeSync(logFd);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * A run failed at startup if it ended within 60 s and either its log shows a known
111
+ * startup error (429, model_not_found, Free usage limit, quota) or it exited non-zero.
112
+ * Only the log is inspected, never answer.md. Returns [failed, reason].
113
+ */
114
+ export function isStartupFailure(returncode, duration, logText) {
115
+ if (duration > STARTUP_WINDOW_SECONDS) return [false, ''];
116
+ for (const err of STARTUP_ERROR_STRINGS) {
117
+ if (logText.includes(err) || (err === 'quota' && logText.toLowerCase().includes('quota'))) {
118
+ return [true, `log contains '${err}'`];
119
+ }
120
+ }
121
+ if (returncode !== 0) return [true, `non-zero exit ${returncode} within 60 s (${duration.toFixed(1)}s)`];
122
+ return [false, ''];
123
+ }
124
+
125
+ function readLogFrom(logPath, offset) {
126
+ if (!fs.existsSync(logPath)) return '';
127
+ const text = fs.readFileSync(logPath, 'utf8');
128
+ const bytes = Buffer.from(text, 'utf8');
129
+ const start = bytes.length < offset ? 0 : offset;
130
+ return bytes.subarray(start).toString('utf8');
131
+ }
132
+
133
+ /**
134
+ * Try candidates in order, moving to the next one of the same list only when a
135
+ * candidate fails at startup (and checkStartup is on). A launch exception counts as
136
+ * exit 1 with its real duration, so a timeout after a long run is not retried.
137
+ * Resolves with {proc, chosen, error, skipped, startTime, endTime}; chosen is null
138
+ * when every candidate failed at startup.
139
+ */
140
+ export async function launchWithFallback(candidates, prompt, runDir, workDir, {
141
+ mode = 'write',
142
+ attachment = null,
143
+ allowedTools = [],
144
+ disallowedTools = [],
145
+ notify = null,
146
+ env = {},
147
+ timeoutSeconds = null,
148
+ checkStartup = true,
149
+ launcher = launch,
150
+ clock = () => performance.now(),
151
+ stdout = process.stdout,
152
+ stderr = process.stderr,
153
+ } = {}) {
154
+ const logPath = path.join(runDir, 'agent.log');
155
+ const skipped = [];
156
+ for (const candidate of candidates) {
157
+ const label = formatCandidateLabel(candidate);
158
+ stdout.write(`Chosen candidate: ${label}\n`);
159
+ const offset = fs.existsSync(logPath) ? fs.statSync(logPath).size : 0;
160
+ const startTime = isoNow();
161
+ const started = clock();
162
+ let proc = null;
163
+ let error = null;
164
+ try {
165
+ proc = await launcher(candidate, prompt, runDir, workDir, {
166
+ mode, attachment, allowedTools, disallowedTools, notify, env, timeoutSeconds,
167
+ });
168
+ } catch (err) {
169
+ error = err;
170
+ fs.appendFileSync(logPath, `\nLaunch exception: ${err.message}\n`, 'utf8');
171
+ }
172
+ const duration = proc?.duration ?? (clock() - started) / 1000;
173
+ const returncode = proc ? proc.returncode : 1;
174
+ if (checkStartup) {
175
+ const [failed, reason] = isStartupFailure(returncode, duration, readLogFrom(logPath, offset));
176
+ if (failed) {
177
+ skipped.push({ candidate, reason: `startup failure: ${reason}` });
178
+ const next = candidates[candidates.indexOf(candidate) + 1];
179
+ if (next) stderr.write(`Failed at startup: ${label} (${reason}) -> trying ${formatCandidateLabel(next)}\n`);
180
+ continue;
181
+ }
182
+ }
183
+ return { proc, chosen: candidate, error, skipped, startTime, endTime: isoNow() };
184
+ }
185
+ return { proc: null, chosen: null, error: null, skipped, startTime: null, endTime: null };
186
+ }
@@ -0,0 +1,28 @@
1
+ /** Runner for the `opencode` CLI. */
2
+
3
+ export const ANSWER_ON_STDOUT = true;
4
+ /** allowed_tools / disallowed_tools are not mapped: the launcher notes it in agent.log. */
5
+ export const SUPPORTS_TOOL_LISTS = false;
6
+ export const SUPPORTS_ATTACHMENT = true;
7
+
8
+ export function buildCommand(candidate, prompt, { workDir, mode, attachment = null } = {}) {
9
+ // `-f` is an array option, so it swallows following positionals; keep it last.
10
+ const attach = attachment ? ['-f', String(attachment)] : [];
11
+ if (mode === 'write') {
12
+ return ['opencode', 'run', '--auto', '-m', candidate.model, '--dir', String(workDir), prompt, ...attach];
13
+ }
14
+ return ['opencode', 'run', '-m', candidate.model, '--agent', 'plan', prompt, ...attach];
15
+ }
16
+
17
+ export function warnings(candidate) {
18
+ return candidate.effort
19
+ ? [`warning: effort '${candidate.effort}' is not supported by opencode and was ignored`]
20
+ : [];
21
+ }
22
+
23
+ /** `--auto` approves commands in write mode; the read-only plan agent may ask for permission and be denied. */
24
+ export function communicationNote(mode) {
25
+ return mode === 'write'
26
+ ? null
27
+ : 'note: the opencode plan agent may deny `crewboss notify` / `crewboss inbox`; if they fail, say so in the answer';
28
+ }
@@ -0,0 +1,21 @@
1
+ /** Pick the scheduler of this system for `routines install|uninstall`: systemd on Linux, launchd on macOS. */
2
+ import { manageLaunchd } from './launchd.js';
3
+ import { manageUnits } from './units.js';
4
+
5
+ export function schedulerFor(platform) {
6
+ if (platform === 'linux') return 'systemd';
7
+ if (platform === 'darwin') return 'launchd';
8
+ throw new Error(`routines install is not supported on ${platform}; run routines with "crewboss routines run <name>" from your own scheduler`);
9
+ }
10
+
11
+ /**
12
+ * Install (or with uninstall remove) the schedules of the enabled routines.
13
+ * options: {uninstall, platform, unitDir, systemctl} for systemd, {agentsDir, launchctl, uid} for launchd.
14
+ */
15
+ export function manageSchedules(config, { platform = process.platform, unitDir, systemctl, agentsDir, launchctl, uid, uninstall = false } = {}) {
16
+ const scheduler = schedulerFor(platform);
17
+ const result = scheduler === 'launchd'
18
+ ? manageLaunchd(config, { uninstall, agentsDir, launchctl, uid })
19
+ : manageUnits(config, { uninstall, unitDir, systemctl });
20
+ return { scheduler, ...result };
21
+ }