Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/commands/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,15 @@ export async function dispatchCommand(
h.updateConfig({ model: arg });
return { type: "ok", message: `model set to ${arg}` };

case "theme": {
const next = (arg || "").trim().toLowerCase();
if (next === "light" || next === "dark") {
h.updateConfig({ theme: next as "light" | "dark" });
return { type: "ok", message: `Theme set to ${next}` };
}
return { type: "ok", message: `Theme: ${h.config.theme || "dark"}` };
}

case "yolo": {
const next = !(ctx.getYolo?.() ?? h.config.autoApprove);
h.setAutoApprove(next);
Expand Down
10 changes: 10 additions & 0 deletions src/config/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,11 @@ export function loadConfig(overrides: Partial<ArrowConfig> = {}): ArrowConfig {
swarm,
contextBudgetChars:
overrides.contextBudgetChars ?? file.contextBudgetChars ?? 120_000,
theme: overrides.theme ?? file.theme ?? "dark",
shellSafetyLevel: overrides.shellSafetyLevel ?? file.shellSafetyLevel ?? "normal",
fileConfirmationPolicy: overrides.fileConfirmationPolicy ?? file.fileConfirmationPolicy ?? "destructive",
webSearchToggle: overrides.webSearchToggle ?? file.webSearchToggle ?? true,
telemetryOptIn: overrides.telemetryOptIn ?? file.telemetryOptIn ?? false,
};
}

Expand Down Expand Up @@ -424,6 +429,11 @@ export function saveSettings(cfg: Partial<ArrowConfig>): void {
systemExtra: cfg.systemExtra,
swarm: cfg.swarm,
contextBudgetChars: cfg.contextBudgetChars,
theme: cfg.theme,
shellSafetyLevel: cfg.shellSafetyLevel,
fileConfirmationPolicy: cfg.fileConfirmationPolicy,
webSearchToggle: cfg.webSearchToggle,
telemetryOptIn: cfg.telemetryOptIn,
};
writeFileSync(SETTINGS_PATH, stringifyYaml(safe), "utf8");
saveConfig(safe as Partial<ArrowConfig>);
Expand Down
5 changes: 5 additions & 0 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ export interface ArrowConfig {
swarm: SwarmConfig;
/** Global context budget (chars) for main agents */
contextBudgetChars: number;
theme?: "dark" | "light";
shellSafetyLevel?: "safe" | "normal" | "low";
fileConfirmationPolicy?: "always" | "never" | "destructive";
webSearchToggle?: boolean;
telemetryOptIn?: boolean;
}

export interface AgentLogLine {
Expand Down
208 changes: 208 additions & 0 deletions src/core/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import { existsSync, readdirSync, statSync, writeFileSync, mkdirSync } from "node:fs";
import { join, dirname } from "node:path";
import { spawn } from "node:child_process";
import type { ArrowConfig } from "../config/types";
import type { Harness } from "./harness";
import { IGNORE_DIRS } from "../tools/workspace";

export async function startServer(cfg: ArrowConfig, harness: Harness) {
const port = process.env.ARROWCODE_PORT ? Number(process.env.ARROWCODE_PORT) : 3000;

console.log(`\n=============================================`);
console.log(`🚀 Starting ArrowCode API Server on port ${port}...`);
console.log(`=============================================\n`);

const server = Bun.serve({
port,
async fetch(req) {
const url = new URL(req.url);

// CORS Headers
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, DELETE",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};

if (req.method === "OPTIONS") {
return new Response("OK", { status: 200, headers });
}

try {
// GET /api/files
if (url.pathname === "/api/files" && req.method === "GET") {
const files: string[] = [];
const walk = (dir: string) => {
let entries: string[];
try {
entries = readdirSync(dir);
} catch {
return;
}
for (const name of entries) {
if (IGNORE_DIRS.has(name)) continue;
const full = join(dir, name);
let st;
try {
st = statSync(full);
} catch {
continue;
}
if (st.isDirectory()) {
walk(full);
} else {
files.push(harness.workspace.rel(full));
}
}
};
walk(harness.workspace.root);
return Response.json({ success: true, files }, { headers });
}

// GET /api/status
if (url.pathname === "/api/status" && req.method === "GET") {
return Response.json({
success: true,
phase: harness.phase,
cycle: harness.cycle,
metrics: harness.metrics,
activeSessionId: harness.sessions.active?.meta.id || null,
}, { headers });
}

// POST /api/query (Streaming SSE)
if (url.pathname === "/api/query" && req.method === "POST") {
const body = await req.json();
const { prompt } = body as { prompt: string };
if (!prompt) {
return Response.json({ error: "Missing prompt" }, { status: 400, headers });
}

let unsubscribe: (() => void) | null = null;
const stream = new ReadableStream({
start(controller) {
unsubscribe = harness.events.on((event) => {
try {
controller.enqueue(`data: ${JSON.stringify(event)}\n\n`);
} catch {
// Client disconnected or stream closed
}
});

// Trigger query in background
void harness.chatDirect(prompt).then(() => {
try {
controller.enqueue(`data: ${JSON.stringify({ type: "stream_done" })}\n\n`);
} catch {
/* ignore */
}
});
},
cancel() {
if (unsubscribe) unsubscribe();
}
});

return new Response(stream, {
headers: {
...headers,
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
}
});
}

// POST /api/edit
if (url.pathname === "/api/edit" && req.method === "POST") {
const body = await req.json();
const { path, content } = body as { path: string; content: string };
if (!path || content === undefined) {
return Response.json({ error: "Missing path or content" }, { status: 400, headers });
}

try {
const absPath = harness.workspace.resolve(path);
mkdirSync(dirname(absPath), { recursive: true });
writeFileSync(absPath, content, "utf8");
harness.files.record("write", path, "api-edit", content);
return Response.json({ success: true, message: `Wrote ${path} successfully.` }, { headers });
} catch (err: any) {
return Response.json({ success: false, error: err.message }, { status: 500, headers });
}
}

// POST /api/run (Streaming SSE)
if (url.pathname === "/api/run" && req.method === "POST") {
const body = await req.json();
const { command } = body as { command: string };
if (!command) {
return Response.json({ error: "Missing command" }, { status: 400, headers });
}

const blocked = [
/rm\s+-rf\s+\/($|\s)/,
/mkfs\./,
/dd\s+if=.*of=\/dev\//,
];
for (const b of blocked) {
if (b.test(command)) {
return Response.json({ error: "Dangerous shell command blocked." }, { status: 403, headers });
}
}

const stream = new ReadableStream({
start(controller) {
const child = spawn(command, {
shell: true,
cwd: harness.workspace.root,
env: { ...process.env, TERM: "dumb" }
});

child.stdout?.on("data", (data) => {
try {
controller.enqueue(`data: ${JSON.stringify({ type: "stdout", text: data.toString() })}\n\n`);
} catch {
/* ignore */
}
});

child.stderr?.on("data", (data) => {
try {
controller.enqueue(`data: ${JSON.stringify({ type: "stderr", text: data.toString() })}\n\n`);
} catch {
/* ignore */
}
});

child.on("close", (code) => {
try {
controller.enqueue(`data: ${JSON.stringify({ type: "close", code })}\n\n`);
controller.close();
} catch {
/* ignore */
}
});
}
});

return new Response(stream, {
headers: {
...headers,
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
}
});
}

return Response.json({ error: "Not Found" }, { status: 404, headers });
} catch (err: any) {
return Response.json({ error: err.message }, { status: 500, headers });
}
}
});

console.log(`Server is listening on http://localhost:${port}`);
return server;
}
Loading
Loading