swarm-code 0.1.5 → 0.1.7
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/dist/config.js +1 -1
- package/dist/hooks/runner.d.ts +35 -0
- package/dist/hooks/runner.js +95 -0
- package/dist/interactive-swarm.js +1 -2
- package/dist/main.d.ts +1 -1
- package/dist/main.js +11 -8
- package/dist/prompts/orchestrator.js +4 -3
- package/dist/swarm.js +40 -0
- package/dist/ui/onboarding.js +325 -83
- package/package.json +1 -1
package/dist/config.js
CHANGED
|
@@ -23,7 +23,7 @@ const DEFAULTS = {
|
|
|
23
23
|
max_session_budget_usd: 10.0,
|
|
24
24
|
default_agent: "opencode",
|
|
25
25
|
default_model: "anthropic/claude-sonnet-4-6",
|
|
26
|
-
auto_model_selection:
|
|
26
|
+
auto_model_selection: true,
|
|
27
27
|
compression_strategy: "structured",
|
|
28
28
|
compression_max_tokens: 1000,
|
|
29
29
|
worktree_base_dir: ".swarm-worktrees",
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook runner — executes user-defined commands at lifecycle points.
|
|
3
|
+
*
|
|
4
|
+
* Hooks provide deterministic control flow (not LLM-decided).
|
|
5
|
+
* They run shell commands and surface only errors — success is silent.
|
|
6
|
+
*
|
|
7
|
+
* Lifecycle points:
|
|
8
|
+
* - post_thread: After a thread commits (before compression)
|
|
9
|
+
* - post_merge: After merge_threads() completes
|
|
10
|
+
* - post_session: When the session ends
|
|
11
|
+
*/
|
|
12
|
+
export interface HookConfig {
|
|
13
|
+
command: string;
|
|
14
|
+
on_failure: "warn" | "block";
|
|
15
|
+
}
|
|
16
|
+
export interface HooksConfig {
|
|
17
|
+
post_thread: HookConfig[];
|
|
18
|
+
post_merge: HookConfig[];
|
|
19
|
+
post_session: HookConfig[];
|
|
20
|
+
}
|
|
21
|
+
export interface HookResult {
|
|
22
|
+
success: boolean;
|
|
23
|
+
output: string;
|
|
24
|
+
command: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Load hooks from swarm_config.yaml hooks section, or from .swarm/hooks.yaml.
|
|
28
|
+
*/
|
|
29
|
+
export declare function loadHooks(projectDir: string): HooksConfig;
|
|
30
|
+
/**
|
|
31
|
+
* Run hooks for a lifecycle point.
|
|
32
|
+
* Returns results for each hook. On "block" failure, throws.
|
|
33
|
+
* Success output is swallowed — only errors are surfaced.
|
|
34
|
+
*/
|
|
35
|
+
export declare function runHooks(hooks: HookConfig[], cwd: string, label: string): HookResult[];
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hook runner — executes user-defined commands at lifecycle points.
|
|
3
|
+
*
|
|
4
|
+
* Hooks provide deterministic control flow (not LLM-decided).
|
|
5
|
+
* They run shell commands and surface only errors — success is silent.
|
|
6
|
+
*
|
|
7
|
+
* Lifecycle points:
|
|
8
|
+
* - post_thread: After a thread commits (before compression)
|
|
9
|
+
* - post_merge: After merge_threads() completes
|
|
10
|
+
* - post_session: When the session ends
|
|
11
|
+
*/
|
|
12
|
+
import { execSync } from "node:child_process";
|
|
13
|
+
import * as fs from "node:fs";
|
|
14
|
+
import * as path from "node:path";
|
|
15
|
+
const DEFAULT_HOOKS = {
|
|
16
|
+
post_thread: [],
|
|
17
|
+
post_merge: [],
|
|
18
|
+
post_session: [],
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Load hooks from swarm_config.yaml hooks section, or from .swarm/hooks.yaml.
|
|
22
|
+
*/
|
|
23
|
+
export function loadHooks(projectDir) {
|
|
24
|
+
const hooksFile = path.join(projectDir, ".swarm", "hooks.yaml");
|
|
25
|
+
if (!fs.existsSync(hooksFile))
|
|
26
|
+
return { ...DEFAULT_HOOKS };
|
|
27
|
+
try {
|
|
28
|
+
const raw = fs.readFileSync(hooksFile, "utf-8");
|
|
29
|
+
return parseHooksYaml(raw);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return { ...DEFAULT_HOOKS };
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function parseHooksYaml(raw) {
|
|
36
|
+
const hooks = { post_thread: [], post_merge: [], post_session: [] };
|
|
37
|
+
let currentSection = null;
|
|
38
|
+
for (const line of raw.split("\n")) {
|
|
39
|
+
const trimmed = line.trim();
|
|
40
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
41
|
+
continue;
|
|
42
|
+
if (trimmed === "post_thread:" || trimmed === "post_merge:" || trimmed === "post_session:") {
|
|
43
|
+
currentSection = trimmed.replace(":", "");
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (currentSection && trimmed.startsWith("- command:")) {
|
|
47
|
+
const command = trimmed
|
|
48
|
+
.replace("- command:", "")
|
|
49
|
+
.trim()
|
|
50
|
+
.replace(/^["']|["']$/g, "");
|
|
51
|
+
if (command) {
|
|
52
|
+
hooks[currentSection].push({ command, on_failure: "warn" });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (currentSection && trimmed.startsWith("on_failure:")) {
|
|
56
|
+
const val = trimmed.replace("on_failure:", "").trim();
|
|
57
|
+
const last = hooks[currentSection][hooks[currentSection].length - 1];
|
|
58
|
+
if (last && (val === "warn" || val === "block")) {
|
|
59
|
+
last.on_failure = val;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return hooks;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Run hooks for a lifecycle point.
|
|
67
|
+
* Returns results for each hook. On "block" failure, throws.
|
|
68
|
+
* Success output is swallowed — only errors are surfaced.
|
|
69
|
+
*/
|
|
70
|
+
export function runHooks(hooks, cwd, label) {
|
|
71
|
+
const results = [];
|
|
72
|
+
for (const hook of hooks) {
|
|
73
|
+
try {
|
|
74
|
+
execSync(hook.command, {
|
|
75
|
+
cwd,
|
|
76
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
77
|
+
timeout: 60_000,
|
|
78
|
+
encoding: "utf-8",
|
|
79
|
+
});
|
|
80
|
+
// Success — silent (context-efficient per harness engineering best practice)
|
|
81
|
+
results.push({ success: true, output: "", command: hook.command });
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
const stderr = err.stderr || err.stdout || err.message || "unknown error";
|
|
85
|
+
// Only surface error output
|
|
86
|
+
const output = `[${label}] Hook failed: ${hook.command}\n${stderr}`.trim();
|
|
87
|
+
results.push({ success: false, output, command: hook.command });
|
|
88
|
+
if (hook.on_failure === "block") {
|
|
89
|
+
throw new Error(output);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return results;
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=runner.js.map
|
|
@@ -80,8 +80,7 @@ function parseInteractiveArgs(args) {
|
|
|
80
80
|
// Silently ignore unknown flags and positional args
|
|
81
81
|
}
|
|
82
82
|
if (!dir) {
|
|
83
|
-
|
|
84
|
-
process.exit(1);
|
|
83
|
+
dir = process.cwd();
|
|
85
84
|
}
|
|
86
85
|
return {
|
|
87
86
|
dir: path.resolve(dir),
|
package/dist/main.d.ts
CHANGED
|
@@ -10,6 +10,6 @@
|
|
|
10
10
|
* swarm run → single-shot RLM CLI run
|
|
11
11
|
* swarm viewer → browse trajectory files
|
|
12
12
|
* swarm benchmark → run benchmarks
|
|
13
|
-
* swarm → interactive
|
|
13
|
+
* swarm → interactive REPL (uses current directory)
|
|
14
14
|
*/
|
|
15
15
|
export declare function buildHelp(): string;
|
package/dist/main.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* swarm run → single-shot RLM CLI run
|
|
11
11
|
* swarm viewer → browse trajectory files
|
|
12
12
|
* swarm benchmark → run benchmarks
|
|
13
|
-
* swarm → interactive
|
|
13
|
+
* swarm → interactive REPL (uses current directory)
|
|
14
14
|
*/
|
|
15
15
|
import { bold, coral, cyan, dim, isTTY, symbols, termWidth, yellow } from "./ui/theme.js";
|
|
16
16
|
export function buildHelp() {
|
|
@@ -45,8 +45,10 @@ export function buildHelp() {
|
|
|
45
45
|
lines.push(` ${yellow("swarm mcp")} ${dim("Start MCP server (stdio)")}`);
|
|
46
46
|
lines.push(` ${yellow("swarm mcp")} --dir ./project ${dim("Start with default directory")}`);
|
|
47
47
|
lines.push("");
|
|
48
|
+
lines.push(` ${bold("INTERACTIVE")} ${dim("(default — uses current directory)")}`);
|
|
49
|
+
lines.push(` ${yellow("swarm")} ${dim("Interactive REPL in current dir")}`);
|
|
50
|
+
lines.push("");
|
|
48
51
|
lines.push(` ${bold("RLM MODE")} ${dim("(text processing, inherited from rlm-cli)")}`);
|
|
49
|
-
lines.push(` ${yellow("swarm")} ${dim("Interactive terminal (default)")}`);
|
|
50
52
|
lines.push(` ${yellow("swarm run")} [options] "<query>" ${dim("Run a single query")}`);
|
|
51
53
|
lines.push(` ${yellow("swarm viewer")} ${dim("Browse saved trajectory files")}`);
|
|
52
54
|
lines.push(` ${yellow("swarm benchmark")} <name> [--idx] ${dim("Run benchmark")}`);
|
|
@@ -125,13 +127,14 @@ async function main() {
|
|
|
125
127
|
}
|
|
126
128
|
return;
|
|
127
129
|
}
|
|
128
|
-
const command = args[0] || "
|
|
130
|
+
const command = args[0] || "";
|
|
131
|
+
// Default: no command → interactive swarm mode using current directory
|
|
132
|
+
if (!command || command === "interactive" || command === "i") {
|
|
133
|
+
const { runInteractiveSwarm } = await import("./interactive-swarm.js");
|
|
134
|
+
await runInteractiveSwarm(["--dir", process.cwd(), ...args.slice(command ? 1 : 0)]);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
129
137
|
switch (command) {
|
|
130
|
-
case "interactive":
|
|
131
|
-
case "i": {
|
|
132
|
-
await import("./interactive.js");
|
|
133
|
-
break;
|
|
134
|
-
}
|
|
135
138
|
case "viewer":
|
|
136
139
|
case "view": {
|
|
137
140
|
process.argv = [process.argv[0], process.argv[1], ...args.slice(1)];
|
|
@@ -56,11 +56,11 @@ ${agentDescriptions}
|
|
|
56
56
|
|
|
57
57
|
1. **Analyze first**: Use \`llm_query()\` or direct Python to understand the codebase/task
|
|
58
58
|
2. **Decompose**: Break the task into independent, parallelizable units
|
|
59
|
-
3. **Extract context**: For each thread, extract ONLY the relevant code/context — don't send everything
|
|
59
|
+
3. **Extract context**: For each thread, extract ONLY the relevant code/context — don't send everything. Keep thread context under 5000 chars; agents have access to the full worktree
|
|
60
60
|
4. **Spawn threads**: Use \`async_thread()\` + \`asyncio.gather()\` for parallel work
|
|
61
61
|
5. **Inspect results**: Check each thread's result for success/failure
|
|
62
62
|
6. **Merge**: Call \`merge_threads()\` to integrate changes
|
|
63
|
-
7. **Verify**:
|
|
63
|
+
7. **Verify**: ALWAYS spawn a verification thread after merging — run the project's test/typecheck/lint commands. If verification fails, fix before calling FINAL()
|
|
64
64
|
8. **Report**: Call \`FINAL()\` with a summary
|
|
65
65
|
|
|
66
66
|
## Episode Quality & Caching
|
|
@@ -77,7 +77,8 @@ ${agentDescriptions}
|
|
|
77
77
|
4. Use \`print()\` for intermediate output visible in the next iteration
|
|
78
78
|
5. Max ${config.max_threads} concurrent threads, ${config.max_total_threads} total per session
|
|
79
79
|
6. Thread timeout: ${config.thread_timeout_ms / 1000}s per thread
|
|
80
|
-
7. Don't call FINAL prematurely — verify thread results first
|
|
80
|
+
7. Don't call FINAL prematurely — verify thread results first. Always run verification after merge.
|
|
81
|
+
8. Prefer cheap models for sub-agent threads (haiku, gpt-4o-mini) — save premium models for complex work
|
|
81
82
|
8. The REPL persists state — variables survive across iterations
|
|
82
83
|
|
|
83
84
|
## Examples
|
package/dist/swarm.js
CHANGED
|
@@ -25,6 +25,7 @@ await import("./agents/claude-code.js");
|
|
|
25
25
|
await import("./agents/codex.js");
|
|
26
26
|
await import("./agents/aider.js");
|
|
27
27
|
import { randomBytes } from "node:crypto";
|
|
28
|
+
import { loadHooks, runHooks } from "./hooks/runner.js";
|
|
28
29
|
import { EpisodicMemory } from "./memory/episodic.js";
|
|
29
30
|
import { buildSwarmSystemPrompt } from "./prompts/orchestrator.js";
|
|
30
31
|
import { classifyTaskComplexity, describeAvailableAgents, FailureTracker, routeTask } from "./routing/model-router.js";
|
|
@@ -296,6 +297,7 @@ function resolveModel(modelId) {
|
|
|
296
297
|
export async function runSwarmMode(rawArgs) {
|
|
297
298
|
const args = parseSwarmArgs(rawArgs);
|
|
298
299
|
const config = loadConfig();
|
|
300
|
+
const hooks = loadHooks(args.dir);
|
|
299
301
|
// Configure UI
|
|
300
302
|
if (args.json)
|
|
301
303
|
setJsonMode(true);
|
|
@@ -420,6 +422,12 @@ export async function runSwarmMode(rawArgs) {
|
|
|
420
422
|
}
|
|
421
423
|
// Thread handler
|
|
422
424
|
const threadHandler = async (task, threadContext, agentBackend, model, files) => {
|
|
425
|
+
// Context-size guard: warn and truncate if orchestrator sends too much context
|
|
426
|
+
const MAX_THREAD_CONTEXT = 50_000;
|
|
427
|
+
if (threadContext.length > MAX_THREAD_CONTEXT) {
|
|
428
|
+
logWarn(`Thread context too large (${(threadContext.length / 1024).toFixed(0)}KB) — truncating to ${MAX_THREAD_CONTEXT / 1000}KB. Agents have full worktree access; pass only relevant excerpts.`);
|
|
429
|
+
threadContext = `${threadContext.slice(0, MAX_THREAD_CONTEXT)}\n\n[... truncated — ${threadContext.length - MAX_THREAD_CONTEXT} chars removed ...]`;
|
|
430
|
+
}
|
|
423
431
|
let resolvedAgent = agentBackend || config.default_agent;
|
|
424
432
|
let resolvedModel = model || config.default_model;
|
|
425
433
|
let routeSlot = "";
|
|
@@ -449,6 +457,18 @@ export async function runSwarmMode(rawArgs) {
|
|
|
449
457
|
},
|
|
450
458
|
files,
|
|
451
459
|
});
|
|
460
|
+
// Run post-thread hooks (typecheck, lint, etc.) — success is silent, only errors surface
|
|
461
|
+
if (result.success && hooks.post_thread.length > 0) {
|
|
462
|
+
try {
|
|
463
|
+
const worktreePath = path.join(args.dir, config.worktree_base_dir, `wt-${threadId}`);
|
|
464
|
+
if (fs.existsSync(worktreePath)) {
|
|
465
|
+
runHooks(hooks.post_thread, worktreePath, "post_thread");
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
catch (hookErr) {
|
|
469
|
+
logWarn(`Post-thread hook failed: ${hookErr.message}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
452
472
|
// Track failure in the failure tracker for routing adjustments
|
|
453
473
|
if (!result.success) {
|
|
454
474
|
failureTracker.recordFailure(resolvedAgent, resolvedModel, task, result.summary || "unknown error");
|
|
@@ -494,6 +514,26 @@ export async function runSwarmMode(rawArgs) {
|
|
|
494
514
|
const summary = results
|
|
495
515
|
.map((r) => (r.success ? `Merged ${r.branch}: ${r.message}` : `FAILED ${r.branch}: ${r.message}`))
|
|
496
516
|
.join("\n");
|
|
517
|
+
// Run post-merge hooks (tests, etc.) — success is silent
|
|
518
|
+
if (merged > 0 && hooks.post_merge.length > 0) {
|
|
519
|
+
try {
|
|
520
|
+
const hookResults = runHooks(hooks.post_merge, args.dir, "post_merge");
|
|
521
|
+
const hookFailures = hookResults.filter((r) => !r.success);
|
|
522
|
+
if (hookFailures.length > 0) {
|
|
523
|
+
const hookOutput = hookFailures.map((r) => r.output).join("\n");
|
|
524
|
+
return {
|
|
525
|
+
result: `${summary}\n\nPost-merge verification failed:\n${hookOutput}`,
|
|
526
|
+
success: false,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
catch (hookErr) {
|
|
531
|
+
return {
|
|
532
|
+
result: `${summary}\n\nPost-merge hook blocked: ${hookErr.message}`,
|
|
533
|
+
success: false,
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
}
|
|
497
537
|
return {
|
|
498
538
|
result: summary || "No threads to merge",
|
|
499
539
|
success: results.every((r) => r.success),
|
package/dist/ui/onboarding.js
CHANGED
|
@@ -10,11 +10,12 @@
|
|
|
10
10
|
*
|
|
11
11
|
* Triggered once on first `swarm --dir` invocation. Saves ~/.swarm/.initialized marker.
|
|
12
12
|
*/
|
|
13
|
-
import { spawn } from "node:child_process";
|
|
13
|
+
import { execFileSync, execSync, spawn, spawn as spawnChild } from "node:child_process";
|
|
14
14
|
import * as fs from "node:fs";
|
|
15
15
|
import * as os from "node:os";
|
|
16
16
|
import * as path from "node:path";
|
|
17
17
|
import * as readline from "node:readline";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
18
19
|
import { getLogLevel, isJsonMode } from "./log.js";
|
|
19
20
|
import { bold, coral, cyan, dim, green, isTTY, red, stripAnsi, symbols, termWidth, yellow } from "./theme.js";
|
|
20
21
|
// ── Constants ─────────────────────────────────────────────────────────────────
|
|
@@ -22,7 +23,19 @@ const SWARM_DIR = path.join(os.homedir(), ".swarm");
|
|
|
22
23
|
const MARKER_FILE = path.join(SWARM_DIR, ".initialized");
|
|
23
24
|
const CRED_FILE = path.join(SWARM_DIR, "credentials");
|
|
24
25
|
const USER_CONFIG_FILE = path.join(SWARM_DIR, "config.yaml");
|
|
25
|
-
|
|
26
|
+
// Read version from package.json instead of hardcoding
|
|
27
|
+
function getVersion() {
|
|
28
|
+
try {
|
|
29
|
+
const __dir = path.dirname(fileURLToPath(import.meta.url));
|
|
30
|
+
const pkgPath = path.join(__dir, "..", "..", "package.json");
|
|
31
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
32
|
+
return pkg.version || "0.0.0";
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return "0.0.0";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const VERSION = getVersion();
|
|
26
39
|
/** Which API key each agent backend requires (or supports). */
|
|
27
40
|
const AGENT_PROVIDERS = {
|
|
28
41
|
opencode: {
|
|
@@ -127,6 +140,147 @@ async function checkAgentBackends() {
|
|
|
127
140
|
results.push({ name: "direct-llm", ok: true, detail: "built-in" });
|
|
128
141
|
return results;
|
|
129
142
|
}
|
|
143
|
+
// ── Ollama helpers ────────────────────────────────────────────────────────────
|
|
144
|
+
function isOllamaInstalled() {
|
|
145
|
+
try {
|
|
146
|
+
execFileSync("ollama", ["--version"], { stdio: ["ignore", "pipe", "pipe"], timeout: 5000 });
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function isOllamaModelAvailable(model) {
|
|
154
|
+
try {
|
|
155
|
+
const output = execFileSync("ollama", ["list"], {
|
|
156
|
+
encoding: "utf-8",
|
|
157
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
158
|
+
timeout: 10000,
|
|
159
|
+
});
|
|
160
|
+
return output.includes(model);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
async function installOllama() {
|
|
167
|
+
process.stderr.write(`\n ${bold("Installing Ollama...")}\n\n`);
|
|
168
|
+
if (process.platform === "darwin") {
|
|
169
|
+
try {
|
|
170
|
+
execFileSync("brew", ["--version"], { stdio: "ignore", timeout: 5000 });
|
|
171
|
+
process.stderr.write(` ${dim("Using Homebrew...")}\n`);
|
|
172
|
+
try {
|
|
173
|
+
execSync("brew install ollama", { stdio: "inherit", timeout: 120000 });
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
process.stderr.write(` ${dim("Homebrew install failed, trying curl installer...")}\n`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
// No brew — fall through to curl
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (process.platform === "linux" || process.platform === "darwin") {
|
|
185
|
+
try {
|
|
186
|
+
execSync("curl -fsSL https://ollama.com/install.sh | sh", { stdio: "inherit", timeout: 180000 });
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
process.stderr.write(` ${dim("Download Ollama from: https://ollama.com/download")}\n`);
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
function isOllamaServing() {
|
|
197
|
+
try {
|
|
198
|
+
execFileSync("curl", ["-sf", "http://127.0.0.1:11434/api/tags"], {
|
|
199
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
200
|
+
timeout: 3000,
|
|
201
|
+
});
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function startOllamaServe() {
|
|
209
|
+
const child = spawnChild("ollama", ["serve"], { stdio: "ignore", detached: true });
|
|
210
|
+
child.unref();
|
|
211
|
+
}
|
|
212
|
+
async function pullOllamaModel(model) {
|
|
213
|
+
process.stderr.write(`\n ${bold(`Pulling ${model}...`)} ${dim("(this may take a few minutes)")}\n\n`);
|
|
214
|
+
return new Promise((resolve) => {
|
|
215
|
+
const child = spawnChild("ollama", ["pull", model], { stdio: "inherit" });
|
|
216
|
+
child.on("close", (code) => resolve(code === 0));
|
|
217
|
+
child.on("error", () => resolve(false));
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
async function ensureOllamaSetup(promptFn, model) {
|
|
221
|
+
const shortModel = model.replace("ollama/", "");
|
|
222
|
+
if (!isOllamaInstalled()) {
|
|
223
|
+
process.stderr.write(`\n ${dim("Ollama is not installed. It's needed to run open-source models locally.")}\n`);
|
|
224
|
+
const prompt = promptFn();
|
|
225
|
+
const install = await prompt.ask(` ${coral(symbols.arrow)} Install Ollama now? [Y/n]: `);
|
|
226
|
+
prompt.close();
|
|
227
|
+
if (install.toLowerCase() !== "n" && install.toLowerCase() !== "no") {
|
|
228
|
+
const ok = await installOllama();
|
|
229
|
+
if (!ok) {
|
|
230
|
+
process.stderr.write(`\n ${red("Failed to install Ollama.")}\n`);
|
|
231
|
+
process.stderr.write(` ${dim("Install manually from https://ollama.com/download")}\n\n`);
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
process.stderr.write(` ${green(symbols.check)} Ollama installed\n`);
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
process.stderr.write(`\n ${dim("Install later from https://ollama.com/download")}\n\n`);
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
process.stderr.write(` ${green(symbols.check)} Ollama installed\n`);
|
|
243
|
+
}
|
|
244
|
+
if (!isOllamaServing()) {
|
|
245
|
+
process.stderr.write(` ${dim("Starting Ollama server...")}\n`);
|
|
246
|
+
startOllamaServe();
|
|
247
|
+
let retries = 10;
|
|
248
|
+
while (retries > 0 && !isOllamaServing()) {
|
|
249
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
250
|
+
retries--;
|
|
251
|
+
}
|
|
252
|
+
if (isOllamaServing()) {
|
|
253
|
+
process.stderr.write(` ${green(symbols.check)} Ollama server running\n`);
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
process.stderr.write(` ${yellow(symbols.warn)} Could not start Ollama server. Run ${bold("ollama serve")} manually.\n`);
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
process.stderr.write(` ${green(symbols.check)} Ollama server running\n`);
|
|
262
|
+
}
|
|
263
|
+
if (isOllamaModelAvailable(shortModel)) {
|
|
264
|
+
process.stderr.write(` ${green(symbols.check)} Model ${bold(shortModel)} ready\n\n`);
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
process.stderr.write(` ${dim(`Model ${shortModel} not found locally.`)}\n`);
|
|
268
|
+
const prompt = promptFn();
|
|
269
|
+
const pull = await prompt.ask(`\n ${coral(symbols.arrow)} Pull ${bold(shortModel)} now? [Y/n]: `);
|
|
270
|
+
prompt.close();
|
|
271
|
+
if (pull.toLowerCase() !== "n" && pull.toLowerCase() !== "no") {
|
|
272
|
+
const ok = await pullOllamaModel(shortModel);
|
|
273
|
+
if (!ok) {
|
|
274
|
+
process.stderr.write(`\n ${red(`Failed to pull ${shortModel}.`)}\n`);
|
|
275
|
+
process.stderr.write(` ${dim(`Try manually: ollama pull ${shortModel}`)}\n\n`);
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
process.stderr.write(` ${green(symbols.check)} Model ${bold(shortModel)} ready\n\n`);
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
process.stderr.write(`\n ${dim(`Run later: ollama pull ${shortModel}`)}\n\n`);
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
130
284
|
// ── Interactive helpers ───────────────────────────────────────────────────────
|
|
131
285
|
function createPrompt() {
|
|
132
286
|
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
@@ -396,93 +550,174 @@ export async function runOnboarding() {
|
|
|
396
550
|
process.stderr.write(`\n ${dim("Using direct-llm (no coding agent) as fallback.")}\n`);
|
|
397
551
|
chosenAgent = "direct-llm";
|
|
398
552
|
}
|
|
399
|
-
// ── Step 2: Configure API keys
|
|
553
|
+
// ── Step 2: Configure backend / API keys ────────────────────────────
|
|
400
554
|
const agentInfo = AGENT_PROVIDERS[chosenAgent];
|
|
401
555
|
const neededKeys = agentInfo?.required ?? ["ANTHROPIC_API_KEY"];
|
|
402
|
-
// For agents that accept any provider (opencode, aider), at least one key is needed
|
|
403
556
|
const needsAnyKey = neededKeys.length > 1;
|
|
404
|
-
const missingKeys = neededKeys.filter((k) => !apiKeys.has(k));
|
|
405
557
|
const hasAnyNeeded = neededKeys.some((k) => apiKeys.has(k));
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
558
|
+
let chosenModel = "anthropic/claude-sonnet-4-6";
|
|
559
|
+
let usesOllama = false;
|
|
560
|
+
let usesOpenRouter = false;
|
|
561
|
+
// OpenCode with no API keys → offer Ollama (default) or OpenRouter
|
|
562
|
+
if (chosenAgent === "opencode" && !hasAnyNeeded) {
|
|
563
|
+
sectionHeader("Backend", w);
|
|
564
|
+
process.stderr.write(` ${bold("OpenCode")} ${dim("— choose your backend:")}\n\n`);
|
|
565
|
+
process.stderr.write(` ${cyan("1")} Ollama ${dim("Run models locally (free, requires download)")}\n`);
|
|
566
|
+
process.stderr.write(` ${cyan("2")} OpenRouter ${dim("Cloud API for 200+ models (requires API key)")}\n`);
|
|
567
|
+
process.stderr.write(` ${cyan("3")} API Key ${dim("Configure Anthropic/OpenAI/Google directly")}\n`);
|
|
568
|
+
process.stderr.write("\n");
|
|
569
|
+
const prompt = createPrompt();
|
|
570
|
+
const backendChoice = await prompt.ask(` ${coral(symbols.arrow)} Backend [1]: `);
|
|
571
|
+
prompt.close();
|
|
572
|
+
const choice = backendChoice.trim();
|
|
573
|
+
if (choice === "2") {
|
|
574
|
+
// OpenRouter setup
|
|
575
|
+
process.stderr.write("\n");
|
|
576
|
+
const keyPrompt = createPrompt();
|
|
577
|
+
const orKey = await keyPrompt.ask(` ${coral(symbols.arrow)} OPENROUTER_API_KEY: `);
|
|
578
|
+
keyPrompt.close();
|
|
579
|
+
if (orKey?.trim()) {
|
|
580
|
+
process.env.OPENROUTER_API_KEY = orKey.trim();
|
|
581
|
+
saveCredential("OPENROUTER_API_KEY", orKey.trim());
|
|
582
|
+
process.stderr.write(` ${green(symbols.check)} OpenRouter configured\n`);
|
|
583
|
+
chosenModel = "openrouter/auto";
|
|
584
|
+
usesOpenRouter = true;
|
|
585
|
+
}
|
|
586
|
+
else {
|
|
587
|
+
process.stderr.write(` ${dim("No key provided — you can set OPENROUTER_API_KEY in .env later")}\n`);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
else if (choice === "3") {
|
|
591
|
+
// Fall through to standard API key setup below
|
|
410
592
|
}
|
|
411
593
|
else {
|
|
412
|
-
|
|
594
|
+
// Default: Ollama setup
|
|
595
|
+
process.stderr.write("\n");
|
|
596
|
+
const ok = await ensureOllamaSetup(createPrompt, "ollama/deepseek-coder-v2");
|
|
597
|
+
if (ok) {
|
|
598
|
+
usesOllama = true;
|
|
599
|
+
chosenModel = "ollama/deepseek-coder-v2";
|
|
600
|
+
}
|
|
413
601
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
const
|
|
419
|
-
const
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
602
|
+
// If choice was "3", do the standard API key flow
|
|
603
|
+
if (choice === "3") {
|
|
604
|
+
sectionHeader("API Keys", w);
|
|
605
|
+
process.stderr.write(` ${bold(chosenAgent)} supports multiple providers. Configure at least one:\n\n`);
|
|
606
|
+
const missingKeys = neededKeys.filter((k) => !apiKeys.has(k));
|
|
607
|
+
for (const envVar of missingKeys) {
|
|
608
|
+
const provider = PROVIDERS.find((p) => p.envVar === envVar);
|
|
609
|
+
if (!provider)
|
|
610
|
+
continue;
|
|
611
|
+
const kp = createPrompt();
|
|
612
|
+
const yn = await kp.ask(` ${coral(symbols.arrow)} Configure ${bold(provider.name)} (${dim(envVar)})? [y/n]: `);
|
|
613
|
+
kp.close();
|
|
614
|
+
if (yn.toLowerCase() !== "y" && yn.toLowerCase() !== "yes") {
|
|
615
|
+
process.stderr.write(` ${dim(symbols.dash)} Skipped ${provider.name}\n`);
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
process.stderr.write(` ${dim(`Paste your ${provider.name} API key (input hidden):`)}\n`);
|
|
619
|
+
const key = await readHiddenInput(` ${coral(symbols.arrow)} `);
|
|
620
|
+
if (key && key.length >= 10) {
|
|
621
|
+
saveCredential(envVar, key);
|
|
622
|
+
apiKeys.set(envVar, key);
|
|
623
|
+
process.stderr.write(` ${green(symbols.check)} Saved ${provider.name} key to ${dim("~/.swarm/credentials")}\n\n`);
|
|
624
|
+
}
|
|
625
|
+
else {
|
|
626
|
+
process.stderr.write(` ${dim("Skipped — set later in .env or ~/.swarm/credentials")}\n\n`);
|
|
627
|
+
}
|
|
628
|
+
if (apiKeys.has(envVar))
|
|
629
|
+
break;
|
|
424
630
|
}
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
else if (!hasAnyNeeded) {
|
|
634
|
+
// Non-opencode agent with missing keys — standard API key flow
|
|
635
|
+
const missingKeys = neededKeys.filter((k) => !apiKeys.has(k));
|
|
636
|
+
if (missingKeys.length > 0) {
|
|
637
|
+
sectionHeader("API Keys", w);
|
|
638
|
+
if (needsAnyKey) {
|
|
639
|
+
process.stderr.write(` ${bold(chosenAgent)} supports multiple providers. Configure at least one:\n\n`);
|
|
431
640
|
}
|
|
432
641
|
else {
|
|
433
|
-
process.stderr.write(` ${
|
|
642
|
+
process.stderr.write(` ${bold(chosenAgent)} needs the following API key(s):\n\n`);
|
|
643
|
+
}
|
|
644
|
+
for (const envVar of missingKeys) {
|
|
645
|
+
const provider = PROVIDERS.find((p) => p.envVar === envVar);
|
|
646
|
+
if (!provider)
|
|
647
|
+
continue;
|
|
648
|
+
const prompt = createPrompt();
|
|
649
|
+
const yn = await prompt.ask(` ${coral(symbols.arrow)} Configure ${bold(provider.name)} (${dim(envVar)})? [y/n]: `);
|
|
650
|
+
prompt.close();
|
|
651
|
+
if (yn.toLowerCase() !== "y" && yn.toLowerCase() !== "yes") {
|
|
652
|
+
process.stderr.write(` ${dim(symbols.dash)} Skipped ${provider.name}\n`);
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
process.stderr.write(` ${dim(`Paste your ${provider.name} API key (input hidden):`)}\n`);
|
|
656
|
+
const key = await readHiddenInput(` ${coral(symbols.arrow)} `);
|
|
657
|
+
if (key && key.length >= 10) {
|
|
658
|
+
saveCredential(envVar, key);
|
|
659
|
+
apiKeys.set(envVar, key);
|
|
660
|
+
process.stderr.write(` ${green(symbols.check)} Saved ${provider.name} key to ${dim("~/.swarm/credentials")}\n\n`);
|
|
661
|
+
}
|
|
662
|
+
else {
|
|
663
|
+
process.stderr.write(` ${dim("Skipped — set later in .env or ~/.swarm/credentials")}\n\n`);
|
|
664
|
+
}
|
|
665
|
+
if (needsAnyKey && apiKeys.has(envVar))
|
|
666
|
+
break;
|
|
434
667
|
}
|
|
435
|
-
// For multi-provider agents, stop after first successful key
|
|
436
|
-
if (needsAnyKey && apiKeys.has(envVar))
|
|
437
|
-
break;
|
|
438
668
|
}
|
|
439
669
|
}
|
|
440
|
-
else
|
|
441
|
-
// Keys already configured — just confirm
|
|
670
|
+
else {
|
|
442
671
|
process.stderr.write(` ${green(symbols.check)} API keys already configured\n`);
|
|
443
672
|
}
|
|
444
673
|
// ── Step 3: Choose default model ─────────────────────────────────────
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
674
|
+
if (!usesOllama && !usesOpenRouter) {
|
|
675
|
+
const configuredProviders = PROVIDERS.filter((p) => apiKeys.has(p.envVar));
|
|
676
|
+
if (configuredProviders.length > 0) {
|
|
677
|
+
sectionHeader("Default Model", w);
|
|
678
|
+
const modelOptions = configuredProviders.flatMap((p) => {
|
|
679
|
+
const models = [];
|
|
680
|
+
if (p.envVar === "ANTHROPIC_API_KEY") {
|
|
681
|
+
models.push({
|
|
682
|
+
label: `claude-sonnet-4-6 ${dim("(fast, capable)")}`,
|
|
683
|
+
value: "anthropic/claude-sonnet-4-6",
|
|
684
|
+
recommended: true,
|
|
685
|
+
}, {
|
|
686
|
+
label: `claude-opus-4-6 ${dim("(most capable)")}`,
|
|
687
|
+
value: "anthropic/claude-opus-4-6",
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
else if (p.envVar === "OPENAI_API_KEY") {
|
|
691
|
+
models.push({ label: `gpt-4o ${dim("(fast, versatile)")}`, value: "openai/gpt-4o" }, { label: `o3 ${dim("(reasoning)")}`, value: "openai/o3" });
|
|
692
|
+
}
|
|
693
|
+
else if (p.envVar === "GEMINI_API_KEY") {
|
|
694
|
+
models.push({
|
|
695
|
+
label: `gemini-2.5-flash ${dim("(fast, cheap)")}`,
|
|
696
|
+
value: "google/gemini-2.5-flash",
|
|
697
|
+
}, { label: `gemini-2.5-pro ${dim("(capable)")}`, value: "google/gemini-2.5-pro" });
|
|
698
|
+
}
|
|
699
|
+
return models;
|
|
700
|
+
});
|
|
701
|
+
if (modelOptions.length > 0) {
|
|
702
|
+
process.stderr.write(` ${bold("Pick a default model for coding threads:")}\n\n`);
|
|
703
|
+
for (let i = 0; i < modelOptions.length; i++) {
|
|
704
|
+
const opt = modelOptions[i];
|
|
705
|
+
const rec = opt.recommended ? ` ${coral("(recommended)")}` : "";
|
|
706
|
+
process.stderr.write(` ${cyan(String(i + 1))} ${opt.label}${rec}\n`);
|
|
707
|
+
}
|
|
708
|
+
process.stderr.write("\n");
|
|
709
|
+
const prompt = createPrompt();
|
|
710
|
+
const modelChoice = await prompt.ask(` ${coral(symbols.arrow)} Choice [1]: `);
|
|
711
|
+
prompt.close();
|
|
712
|
+
const idx = parseInt(modelChoice, 10);
|
|
713
|
+
if (idx >= 1 && idx <= modelOptions.length) {
|
|
714
|
+
chosenModel = modelOptions[idx - 1].value;
|
|
715
|
+
}
|
|
716
|
+
else {
|
|
717
|
+
chosenModel = modelOptions[0].value;
|
|
718
|
+
}
|
|
719
|
+
process.stderr.write(` ${green(symbols.check)} Default model: ${bold(chosenModel)}\n`);
|
|
484
720
|
}
|
|
485
|
-
process.stderr.write(` ${green(symbols.check)} Default model: ${bold(chosenModel)}\n`);
|
|
486
721
|
}
|
|
487
722
|
}
|
|
488
723
|
// ── Step 4: Save config ──────────────────────────────────────────────
|
|
@@ -491,22 +726,29 @@ export async function runOnboarding() {
|
|
|
491
726
|
sectionHeader("Ready", w);
|
|
492
727
|
process.stderr.write(` ${green(symbols.check)} Agent: ${bold(chosenAgent)}\n`);
|
|
493
728
|
process.stderr.write(` ${green(symbols.check)} Model: ${bold(chosenModel)}\n`);
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
729
|
+
if (usesOllama) {
|
|
730
|
+
process.stderr.write(` ${green(symbols.check)} Backend: ${bold("Ollama")} ${dim("(local)")}\n`);
|
|
731
|
+
}
|
|
732
|
+
else if (usesOpenRouter) {
|
|
733
|
+
process.stderr.write(` ${green(symbols.check)} Backend: ${bold("OpenRouter")}\n`);
|
|
734
|
+
}
|
|
735
|
+
else {
|
|
736
|
+
const keyNames = [...apiKeys.keys()].map((k) => {
|
|
737
|
+
const p = PROVIDERS.find((pr) => pr.envVar === k);
|
|
738
|
+
return p?.name ?? k;
|
|
739
|
+
});
|
|
740
|
+
if (keyNames.length > 0) {
|
|
741
|
+
process.stderr.write(` ${green(symbols.check)} Keys: ${bold(keyNames.join(", "))}\n`);
|
|
742
|
+
}
|
|
500
743
|
}
|
|
501
744
|
process.stderr.write(` ${green(symbols.check)} Config: ${dim("~/.swarm/config.yaml")}\n`);
|
|
502
|
-
process.stderr.write(
|
|
503
|
-
process.stderr.write(` ${dim("Edit")} ${cyan("~/.swarm/config.yaml")} ${dim("to change these settings anytime.")}\n`);
|
|
745
|
+
process.stderr.write("\n");
|
|
504
746
|
// If still missing critical deps, show warnings
|
|
505
747
|
if (!gitVer) {
|
|
506
|
-
process.stderr.write(
|
|
748
|
+
process.stderr.write(` ${red(symbols.cross)} ${bold("git is required.")} Install it before using swarm.\n`);
|
|
507
749
|
}
|
|
508
|
-
if (apiKeys.size === 0) {
|
|
509
|
-
process.stderr.write(
|
|
750
|
+
if (apiKeys.size === 0 && !usesOllama && !usesOpenRouter) {
|
|
751
|
+
process.stderr.write(` ${yellow(symbols.warn)} ${bold("No API keys configured.")}\n`);
|
|
510
752
|
process.stderr.write(` ${dim("Add keys to")} ${cyan("~/.swarm/credentials")} ${dim("or")} ${cyan(".env")}${dim(":")}\n`);
|
|
511
753
|
process.stderr.write(` ${dim("ANTHROPIC_API_KEY=sk-ant-...")}\n`);
|
|
512
754
|
process.stderr.write(` ${dim("OPENAI_API_KEY=sk-...")}\n`);
|
package/package.json
CHANGED