diff --git a/apps/web/src/components/M3PluginSlotHost.tsx b/apps/web/src/components/M3PluginSlotHost.tsx index be404b4bf04d9..1feae55d4503a 100644 --- a/apps/web/src/components/M3PluginSlotHost.tsx +++ b/apps/web/src/components/M3PluginSlotHost.tsx @@ -20,6 +20,7 @@ interface M3PluginRecord { readonly manifest: M3PluginManifest; readonly enabled: boolean; readonly status: "active" | "disabled" | "starting" | "error"; + readonly builtin?: boolean; readonly entryUrl: string | null; readonly sidecarPort: number | null; readonly errorMessage?: string; @@ -736,20 +737,22 @@ export function M3PluginSlotHost() { > {plugin.enabled ? gt("Disable") : gt("Enable")} - + {!plugin.builtin ? ( + + ) : null} )) diff --git a/m3/plugin-host/PluginHostManager.test.ts b/m3/plugin-host/PluginHostManager.test.ts index 22a0f00471079..259bff3ec8dcc 100644 --- a/m3/plugin-host/PluginHostManager.test.ts +++ b/m3/plugin-host/PluginHostManager.test.ts @@ -82,7 +82,7 @@ describe("m3/plugin-host", () => { it("discovers static & sidecar plugins in ~/.m3/plugins, spawns sidecar on dynamic port, and blocks path traversal", async () => { const tmpDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "m3-plugin-host-test-")); - const manager = new PluginHostManager({ m3HomeDir: tmpDir }); + const manager = new PluginHostManager({ m3HomeDir: tmpDir, builtinPluginsDirs: [] }); try { // 1. Static HTML/JS plugin const staticDir = NodePath.join(tmpDir, "plugins", "dashboard"); diff --git a/m3/plugin-host/manifest.ts b/m3/plugin-host/manifest.ts index 5dc348af0ff15..152b9241bed10 100644 --- a/m3/plugin-host/manifest.ts +++ b/m3/plugin-host/manifest.ts @@ -50,6 +50,8 @@ export interface M3PluginRecord { readonly enabled: boolean; readonly status: M3PluginStatus; readonly isSymlink: boolean; + /** True when bundled natively with M3 Code under `m3/plugins/`. */ + readonly builtin?: boolean; /** URL the UI iframe/webview loads (either static bundle path or sidecar proxy path). */ readonly entryUrl: string | null; readonly sidecarPort: number | null; diff --git a/m3/plugin-host/server/PluginHostManager.ts b/m3/plugin-host/server/PluginHostManager.ts index df93faf32c7df..94d882e63a2fe 100644 --- a/m3/plugin-host/server/PluginHostManager.ts +++ b/m3/plugin-host/server/PluginHostManager.ts @@ -4,6 +4,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeNet from "node:net"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; +import * as NodeURL from "node:url"; import { createBridgeEvent, type M3BridgeEventMessage } from "../bridgeProtocol.ts"; import { @@ -34,6 +35,11 @@ interface RunningSidecar { export interface PluginHostOptions { /** Override base M3 home directory (defaults to M3CODE_HOME or ~/.m3). */ readonly m3HomeDir?: string; + /** + * Optional directories containing bundled native plugins (defaults to `m3/plugins/`). + * Pass `[]` to disable built-in plugin discovery in isolated tests. + */ + readonly builtinPluginsDirs?: ReadonlyArray; } const EMPTY_STATE: PersistedPluginsState = { plugins: {} }; @@ -128,9 +134,15 @@ function runGitClone(url: string, targetDir: string): Promise { }); } +const DEFAULT_BUILTIN_PLUGINS_DIR = NodePath.resolve( + NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), + "../../plugins", +); + export class PluginHostManager { readonly m3HomeDir: string; readonly pluginsDir: string; + readonly builtinPluginsDirs: ReadonlyArray; readonly statePath: string; private readonly sidecars = new Map(); @@ -142,6 +154,10 @@ export class PluginHostManager { ? NodePath.resolve(options.m3HomeDir) : resolveDefaultM3Home(); this.pluginsDir = NodePath.join(this.m3HomeDir, "plugins"); + this.builtinPluginsDirs = + options.builtinPluginsDirs !== undefined + ? options.builtinPluginsDirs.map((dir) => NodePath.resolve(dir)) + : [DEFAULT_BUILTIN_PLUGINS_DIR]; this.statePath = NodePath.join(this.m3HomeDir, "userdata", "plugins-state.json"); } @@ -193,7 +209,12 @@ export class PluginHostManager { } const port = await allocateLoopbackPort(); - const child = NodeChildProcess.spawn(manifest.runtime.command, [...manifest.runtime.args], { + const resolvedCommand = + manifest.runtime.command === "node" && !("electron" in process.versions) + ? process.execPath + : manifest.runtime.command; + const dataDir = NodePath.join(this.m3HomeDir, "userdata", "plugins", manifest.id); + const child = NodeChildProcess.spawn(resolvedCommand, [...manifest.runtime.args], { cwd: rootDir, env: { ...process.env, @@ -202,6 +223,8 @@ export class PluginHostManager { M3_PLUGIN_PORT: String(port), M3_PLUGIN_ID: manifest.id, M3_PLUGIN_DIR: rootDir, + M3_HOME_DIR: this.m3HomeDir, + M3_PLUGIN_DATA_DIR: dataDir, }, stdio: ["ignore", "pipe", "pipe"], }); @@ -268,22 +291,22 @@ export class PluginHostManager { await Promise.all(ids.map((id) => this.stopSidecar(id))); } - async list(): Promise<{ - readonly pluginsDir: string; - readonly plugins: ReadonlyArray; - }> { - const state = await this.readState(); + private async scanPluginDirectory( + dir: string, + builtin: boolean, + state: PersistedPluginsState, + ): Promise> { let entries: string[] = []; try { - entries = await NodeFSP.readdir(this.pluginsDir); + entries = await NodeFSP.readdir(dir); } catch { - return { pluginsDir: this.pluginsDir, plugins: [] }; + return []; } const visible = entries.filter((entry) => !entry.startsWith(".")); const records = await Promise.all( visible.map(async (entry): Promise => { - const rootDir = NodePath.join(this.pluginsDir, entry); + const rootDir = NodePath.join(dir, entry); let isSymlink = false; try { const lstat = await NodeFSP.lstat(rootDir); @@ -317,6 +340,7 @@ export class PluginHostManager { enabled: false, status: "error", isSymlink, + ...(builtin ? { builtin: true } : {}), entryUrl: null, sidecarPort: null, errorMessage: validated.error, @@ -335,6 +359,7 @@ export class PluginHostManager { enabled: false, status: "disabled", isSymlink, + ...(builtin ? { builtin: true } : {}), entryUrl: null, sidecarPort: null, ...(saved?.installedAt ? { installedAt: saved.installedAt } : {}), @@ -351,6 +376,7 @@ export class PluginHostManager { enabled: true, status: errorMessage ? "error" : running ? "active" : "starting", isSymlink, + ...(builtin ? { builtin: true } : {}), entryUrl: running ? `/api/m3-plugins/sidecar/${encodeURIComponent(manifest.id)}/?m3_plugin_id=${encodeURIComponent(manifest.id)}` : null, @@ -368,6 +394,7 @@ export class PluginHostManager { enabled: true, status: "active", isSymlink, + ...(builtin ? { builtin: true } : {}), entryUrl: `/api/m3-plugins/static/${encodeURIComponent(manifest.id)}/${cleanEntry}?m3_plugin_id=${encodeURIComponent(manifest.id)}`, sidecarPort: null, ...(saved?.installedAt ? { installedAt: saved.installedAt } : {}), @@ -376,9 +403,31 @@ export class PluginHostManager { }), ); - const plugins = records - .filter((record): record is M3PluginRecord => record !== undefined) - .sort((a, b) => a.manifest.name.localeCompare(b.manifest.name)); + return records.filter((record): record is M3PluginRecord => record !== undefined); + } + + async list(): Promise<{ + readonly pluginsDir: string; + readonly plugins: ReadonlyArray; + }> { + const state = await this.readState(); + const byId = new Map(); + + for (const builtinDir of this.builtinPluginsDirs) { + const builtinRecords = await this.scanPluginDirectory(builtinDir, true, state); + for (const record of builtinRecords) { + byId.set(record.manifest.id, record); + } + } + + const userRecords = await this.scanPluginDirectory(this.pluginsDir, false, state); + for (const record of userRecords) { + byId.set(record.manifest.id, record); + } + + const plugins = [...byId.values()].sort((a, b) => + a.manifest.name.localeCompare(b.manifest.name), + ); return { pluginsDir: this.pluginsDir, plugins }; } @@ -448,6 +497,9 @@ export class PluginHostManager { const listed = await this.list(); const target = listed.plugins.find((p) => p.manifest.id === pluginId); if (!target) return false; + if (target.builtin) { + throw new Error(`Built-in plugin "${pluginId}" cannot be uninstalled; disable it instead.`); + } await this.stopSidecar(pluginId); await NodeFSP.rm(target.rootDir, { recursive: true, force: true }); const state = await this.readState(); diff --git a/m3/plugin-host/server/httpHandler.ts b/m3/plugin-host/server/httpHandler.ts index b49986346a141..f4dd18f929977 100644 --- a/m3/plugin-host/server/httpHandler.ts +++ b/m3/plugin-host/server/httpHandler.ts @@ -136,8 +136,12 @@ export async function handleM3PluginHttpRequest( const body = await readJsonBody(request); const pluginId = typeof body.pluginId === "string" ? body.pluginId.trim() : ""; if (!pluginId) return errorResponse('Missing required field "pluginId".', 400); - const removed = await manager.uninstall(pluginId); - return jsonResponse({ ok: true, removed, pluginId }); + try { + const removed = await manager.uninstall(pluginId); + return jsonResponse({ ok: true, removed, pluginId }); + } catch (err) { + return errorResponse(err instanceof Error ? err.message : String(err), 400); + } } if (pathname === "/api/m3-plugins/toggle" && method === "POST") { diff --git a/m3/plugins/ci-runners/ciRunners.test.ts b/m3/plugins/ci-runners/ciRunners.test.ts new file mode 100644 index 0000000000000..33770e8439972 --- /dev/null +++ b/m3/plugins/ci-runners/ciRunners.test.ts @@ -0,0 +1,239 @@ +// @effect-diagnostics nodeBuiltinImport:off globalFetch:off -- tests exercise the standalone CI Runners plugin store, direct HTTP runner API, and deployment planner against loopback servers. +import * as NodeFSP from "node:fs/promises"; +import * as NodeHttp from "node:http"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { assert, describe, it } from "vitest"; + +import { PluginHostManager } from "../../plugin-host/server/PluginHostManager.ts"; +import { generateDeploymentPlan, M3_RUNNER_AGENT_SCRIPT } from "./runnerDeployer.mjs"; +import { RunnerStore } from "./runnerStore.mjs"; +import { startServer } from "./server.mjs"; + +function listenMockServer( + handler: (req: NodeHttp.IncomingMessage, res: NodeHttp.ServerResponse) => void, +): Promise<{ readonly server: NodeHttp.Server; readonly baseUrl: string }> { + return new Promise((resolve, reject) => { + const server = NodeHttp.createServer(handler); + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { + const addr = server.address(); + if (!addr || typeof addr === "string") { + reject(new Error("Failed to bind mock server")); + return; + } + resolve({ server, baseUrl: `http://127.0.0.1:${addr.port}` }); + }); + }); +} + +function closeServer(server: NodeHttp.Server): Promise { + return new Promise((resolve) => server.close(() => resolve())); +} + +describe("m3/plugins/ci-runners", () => { + it("auto-discovers built-in ci-runners plugin in PluginHostManager, spawns sidecar, and blocks uninstall", async () => { + const tmpDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "m3-ci-plugin-host-")); + const manager = new PluginHostManager({ m3HomeDir: tmpDir }); + try { + const listed = await manager.list(); + const ciPlugin = listed.plugins.find((p) => p.manifest.id === "ci-runners"); + assert.isDefined(ciPlugin); + assert.strictEqual(ciPlugin.builtin, true); + assert.strictEqual(ciPlugin.status, "active"); + assert.isNotNull(ciPlugin.sidecarPort); + + const healthRes = await fetch(`http://127.0.0.1:${ciPlugin.sidecarPort}/api/health`); + assert.strictEqual(healthRes.status, 200); + const health = (await healthRes.json()) as { ok: boolean; pluginId: string }; + assert.strictEqual(health.ok, true); + assert.strictEqual(health.pluginId, "ci-runners"); + + let uninstallFailed = false; + try { + await manager.uninstall("ci-runners"); + } catch (err) { + uninstallFailed = err instanceof Error && err.message.includes("Built-in plugin"); + } + assert.strictEqual(uninstallFailed, true); + } finally { + await manager.shutdown(); + await NodeFSP.rm(tmpDir, { recursive: true, force: true }); + } + }); + + it("masks secrets in RunnerStore and proxies probe, trigger, runs, logs, and cancel directly to a custom HTTP runner", async () => { + const tmpDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "m3-ci-runners-api-")); + let capturedAuth = ""; + let cancelledId = ""; + + const mockRunner = await listenMockServer((req, res) => { + capturedAuth = req.headers.authorization ?? ""; + const url = new URL(req.url ?? "/", "http://127.0.0.1"); + res.writeHead(200, { "content-type": "application/json" }); + + if (req.method === "GET" && url.pathname === "/health") { + res.end( + JSON.stringify({ + ok: true, + name: "spark-runner-1", + version: "1.0.0", + platform: "linux", + concurrency: 4, + activeJobs: 1, + busy: false, + labels: ["self-hosted", "gpu"], + }), + ); + return; + } + if (req.method === "POST" && url.pathname === "/runs") { + res.end(JSON.stringify({ id: "run_live_42", status: "in_progress" })); + return; + } + if (req.method === "GET" && url.pathname === "/runs") { + res.end( + JSON.stringify({ + runs: [ + { + id: "run_live_42", + name: "pnpm test", + ref: "feat/ci", + status: "completed", + exitCode: 0, + }, + ], + }), + ); + return; + } + if (req.method === "GET" && url.pathname === "/runs/run_live_42/logs") { + res.end(JSON.stringify({ id: "run_live_42", logs: "$ pnpm test\nPASS all 12 tests\n" })); + return; + } + if (req.method === "POST" && url.pathname === "/runs/run_live_42/cancel") { + cancelledId = "run_live_42"; + res.end(JSON.stringify({ ok: true, id: "run_live_42", status: "cancelled" })); + return; + } + res.statusCode = 404; + res.end(JSON.stringify({ error: "not found" })); + }); + + const sidecar = await startServer({ + port: 0, + store: new RunnerStore(tmpDir), + }); + const apiBase = `http://127.0.0.1:${sidecar.port}`; + + try { + // 1. Register runner and verify token masking + const createRes = await fetch(`${apiBase}/api/runners`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + name: "Spark Runner", + provider: "custom-http", + apiBaseUrl: mockRunner.baseUrl, + labels: "self-hosted, gpu", + token: "super-secret-runner-token-9876", + }), + }); + assert.strictEqual(createRes.status, 201); + const created = (await createRes.json()) as { + ok: boolean; + runner: { id: string; tokenSet: boolean; tokenPreview: string; token?: string }; + }; + assert.strictEqual(created.ok, true); + assert.strictEqual(created.runner.tokenSet, true); + assert.strictEqual(created.runner.tokenPreview, "••••9876"); + assert.isUndefined(created.runner.token); + + const runnerId = created.runner.id; + + // 2. Probe runner directly + const probeRes = await fetch(`${apiBase}/api/runners/${runnerId}/probe`, { method: "POST" }); + const probe = (await probeRes.json()) as { + online: boolean; + concurrency: number; + activeJobs: number; + }; + assert.strictEqual(probe.online, true); + assert.strictEqual(probe.concurrency, 4); + assert.strictEqual(probe.activeJobs, 1); + assert.strictEqual(capturedAuth, "Bearer super-secret-runner-token-9876"); + + // 3. Trigger run + const trigRes = await fetch(`${apiBase}/api/runners/${runnerId}/trigger`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ref: "feat/ci", command: "pnpm test" }), + }); + assert.strictEqual(trigRes.status, 202); + const trig = (await trigRes.json()) as { ok: boolean; runId: string }; + assert.strictEqual(trig.runId, "run_live_42"); + + // 4. List runs + const runsRes = await fetch(`${apiBase}/api/runners/${runnerId}/runs`); + const runsBody = (await runsRes.json()) as { + runs: Array<{ id: string; conclusion: string }>; + }; + assert.strictEqual(runsBody.runs.length, 1); + assert.strictEqual(runsBody.runs[0]?.id, "run_live_42"); + assert.strictEqual(runsBody.runs[0]?.conclusion, "success"); + + // 5. Fetch logs + const logsRes = await fetch(`${apiBase}/api/runners/${runnerId}/runs/run_live_42/logs`); + const logsBody = (await logsRes.json()) as { logs: string }; + assert.include(logsBody.logs, "PASS all 12 tests"); + + // 6. Cancel run + const cancelRes = await fetch(`${apiBase}/api/runners/${runnerId}/runs/run_live_42/cancel`, { + method: "POST", + }); + assert.strictEqual(cancelRes.status, 200); + assert.strictEqual(cancelledId, "run_live_42"); + } finally { + await closeServer(sidecar.server); + await closeServer(mockRunner.server); + await NodeFSP.rm(tmpDir, { recursive: true, force: true }); + } + }); + + it("generates Docker, systemd, and SSH deployment plans for self-hosted runners", () => { + const dockerPlan = generateDeploymentPlan({ + provider: "custom-http", + mode: "docker", + name: "Spark CI 01", + port: 8899, + concurrency: 4, + labels: ["self-hosted", "arm64"], + }); + assert.strictEqual(dockerPlan.name, "spark-ci-01"); + assert.strictEqual(dockerPlan.suggestedApiBaseUrl, "http://127.0.0.1:8899"); + assert.include(dockerPlan.dockerComposeYaml, "8899:8899"); + assert.include(dockerPlan.dockerComposeYaml, "M3_RUNNER_CONCURRENCY"); + assert.include(M3_RUNNER_AGENT_SCRIPT, "/health"); + + const ghSystemd = generateDeploymentPlan({ + provider: "github", + mode: "systemd", + name: "gh-linux-1", + instanceUrl: "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/MiaAI-Lab/m3code", + labels: "self-hosted,linux,x64", + }); + assert.include(ghSystemd.systemdUnit, "REPO_URL=https://github.com/MiaAI-Lab/m3code"); + assert.include(ghSystemd.systemdUnit, "NoNewPrivileges=true"); + + const sshPlan = generateDeploymentPlan({ + provider: "forgejo", + mode: "ssh", + name: "forgejo-box", + sshHost: "10.0.0.42", + sshUser: "deploy", + instanceUrl: "https://git.internal", + }); + assert.include(sshPlan.sshCommand, "deploy@10.0.0.42"); + assert.include(sshPlan.remoteInstallScript, "FORGEJO_INSTANCE_URL=https://git.internal"); + }); +}); diff --git a/m3/plugins/ci-runners/plugin.json b/m3/plugins/ci-runners/plugin.json new file mode 100644 index 0000000000000..dccc75e56e3f8 --- /dev/null +++ b/m3/plugins/ci-runners/plugin.json @@ -0,0 +1,15 @@ +{ + "id": "ci-runners", + "name": "CI Runners", + "version": "1.0.0", + "description": "Direct API layer for self-hosted CI runners (custom HTTP, GitHub Actions, GitLab Runner, Forgejo/Gitea) plus Docker, systemd, and SSH runner deployment.", + "author": "M3 Code", + "runtime": { + "type": "sidecar", + "command": "node", + "args": ["server.mjs"], + "healthPath": "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/api/health" + }, + "slots": ["sidebar-tab", "right-panel", "thread-toolbar"], + "subscriptions": ["thread:updated", "workspace:changed"] +} diff --git a/m3/plugins/ci-runners/runnerApi.mjs b/m3/plugins/ci-runners/runnerApi.mjs new file mode 100644 index 0000000000000..61f455cbaa262 --- /dev/null +++ b/m3/plugins/ci-runners/runnerApi.mjs @@ -0,0 +1,607 @@ +const DEFAULT_TIMEOUT_MS = 12_000; + +function authHeaders(runner) { + const headers = { + accept: "application/json", + "user-agent": "m3code-ci-runners-plugin/1.0", + }; + if (!runner.token) return headers; + + switch (runner.provider) { + case "github": + headers.authorization = `Bearer ${runner.token}`; + headers["x-github-api-version"] = "2022-11-28"; + break; + case "gitlab": + headers["private-token"] = runner.token; + break; + case "forgejo": + headers.authorization = `token ${runner.token}`; + break; + default: + headers.authorization = `Bearer ${runner.token}`; + break; + } + return headers; +} + +async function fetchJson(url, options = {}) { + const startedAt = Date.now(); + const response = await fetch(url, { + ...options, + signal: AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS), + }); + const latencyMs = Date.now() - startedAt; + const text = await response.text(); + let json = null; + try { + json = text.length > 0 ? JSON.parse(text) : null; + } catch { + json = null; + } + return { + ok: response.ok, + status: response.status, + latencyMs, + text, + json, + }; +} + +function encodeGitLabProject(repo) { + return encodeURIComponent(repo.replace(/^\/+|\/+$/g, "")); +} + +function requireRepo(runner) { + if (!runner.repo || runner.repo.trim().length === 0) { + throw new Error( + `Runner "${runner.name}" requires a repository/project path (e.g. "owner/repo").`, + ); + } + return runner.repo.trim(); +} + +/** + * Probe a configured runner or self-hosted runner fleet for live health, status, and capacity. + */ +export async function probeRunner(runner) { + const base = runner.apiBaseUrl.replace(/\/+$/, ""); + const headers = authHeaders(runner); + + try { + if (runner.provider === "custom-http") { + const res = await fetchJson(`${base}/health`, { method: "GET", headers }); + if (!res.ok) { + return { + online: false, + status: "error", + httpStatus: res.status, + latencyMs: res.latencyMs, + error: res.json?.error ?? res.text.slice(0, 300) ?? `HTTP ${res.status}`, + nodes: [], + }; + } + const data = res.json ?? {}; + return { + online: true, + status: data.busy ? "busy" : "online", + httpStatus: res.status, + latencyMs: res.latencyMs, + version: data.version ?? null, + activeJobs: Number(data.activeJobs ?? 0), + concurrency: Number(data.concurrency ?? 1), + labels: Array.isArray(data.labels) ? data.labels : runner.labels, + nodes: Array.isArray(data.nodes) + ? data.nodes + : [ + { + id: data.runnerId ?? runner.id, + name: data.name ?? runner.name, + status: data.busy ? "busy" : "online", + os: data.platform ?? data.os ?? "linux", + labels: Array.isArray(data.labels) ? data.labels : runner.labels, + }, + ], + }; + } + + if (runner.provider === "github") { + const repo = requireRepo(runner); + const endpoint = repo.includes("/") + ? `${base}/repos/${repo}/actions/runners` + : `${base}/orgs/${repo}/actions/runners`; + const res = await fetchJson(endpoint, { method: "GET", headers }); + if (!res.ok) { + return { + online: false, + status: "error", + httpStatus: res.status, + latencyMs: res.latencyMs, + error: res.json?.message ?? `GitHub API returned HTTP ${res.status}`, + nodes: [], + }; + } + const rawRunners = Array.isArray(res.json?.runners) ? res.json.runners : []; + const nodes = rawRunners.map((r) => ({ + id: String(r.id), + name: r.name, + status: r.busy ? "busy" : r.status === "online" ? "online" : "offline", + os: r.os ?? "unknown", + labels: Array.isArray(r.labels) ? r.labels.map((l) => l.name) : [], + })); + const onlineCount = nodes.filter((n) => n.status === "online" || n.status === "busy").length; + return { + online: onlineCount > 0 || nodes.length === 0, + status: onlineCount > 0 ? "online" : nodes.length > 0 ? "offline" : "online", + httpStatus: res.status, + latencyMs: res.latencyMs, + activeJobs: nodes.filter((n) => n.status === "busy").length, + concurrency: nodes.length, + nodes, + }; + } + + if (runner.provider === "gitlab") { + const endpoint = runner.repo + ? `${base}/api/v4/projects/${encodeGitLabProject(runner.repo)}/runners` + : `${base}/api/v4/runners`; + const res = await fetchJson(endpoint, { method: "GET", headers }); + if (!res.ok) { + return { + online: false, + status: "error", + httpStatus: res.status, + latencyMs: res.latencyMs, + error: res.json?.message ?? `GitLab API returned HTTP ${res.status}`, + nodes: [], + }; + } + const rawRunners = Array.isArray(res.json) ? res.json : []; + const nodes = rawRunners.map((r) => ({ + id: String(r.id), + name: r.description || `runner-${r.id}`, + status: r.status === "online" ? "online" : r.paused ? "paused" : "offline", + os: r.platform ?? "linux", + labels: Array.isArray(r.tag_list) ? r.tag_list : [], + })); + const onlineCount = nodes.filter((n) => n.status === "online").length; + return { + online: onlineCount > 0 || nodes.length === 0, + status: onlineCount > 0 ? "online" : nodes.length > 0 ? "offline" : "online", + httpStatus: res.status, + latencyMs: res.latencyMs, + activeJobs: 0, + concurrency: nodes.length, + nodes, + }; + } + + if (runner.provider === "forgejo") { + const endpoint = runner.repo + ? `${base}/api/v1/repos/${runner.repo}/actions/runners` + : `${base}/api/v1/admin/runners`; + const res = await fetchJson(endpoint, { method: "GET", headers }); + if (!res.ok) { + return { + online: false, + status: "error", + httpStatus: res.status, + latencyMs: res.latencyMs, + error: res.json?.message ?? `Forgejo API returned HTTP ${res.status}`, + nodes: [], + }; + } + const rawRunners = Array.isArray(res.json) + ? res.json + : Array.isArray(res.json?.runners) + ? res.json.runners + : []; + const nodes = rawRunners.map((r) => ({ + id: String(r.id), + name: r.name ?? `runner-${r.id}`, + status: r.busy + ? "busy" + : r.status === "online" || r.status === "idle" + ? "online" + : "offline", + os: r.os ?? "linux", + labels: Array.isArray(r.labels) + ? r.labels.map((l) => (typeof l === "string" ? l : l.name)) + : [], + })); + const onlineCount = nodes.filter((n) => n.status === "online" || n.status === "busy").length; + return { + online: onlineCount > 0 || nodes.length === 0, + status: onlineCount > 0 ? "online" : nodes.length > 0 ? "offline" : "online", + httpStatus: res.status, + latencyMs: res.latencyMs, + activeJobs: nodes.filter((n) => n.status === "busy").length, + concurrency: nodes.length, + nodes, + }; + } + + return { + online: false, + status: "error", + error: `Unsupported provider: ${runner.provider}`, + nodes: [], + }; + } catch (err) { + return { + online: false, + status: "unreachable", + error: err instanceof Error ? err.message : String(err), + nodes: [], + }; + } +} + +/** + * List recent CI runs directly from the runner or forge API. + */ +export async function listRuns(runner, options = {}) { + const limit = Math.min(Math.max(Number(options.limit ?? 20), 1), 100); + const base = runner.apiBaseUrl.replace(/\/+$/, ""); + const headers = authHeaders(runner); + + if (runner.provider === "custom-http") { + const res = await fetchJson(`${base}/runs?limit=${limit}`, { method: "GET", headers }); + if (!res.ok) { + throw new Error(res.json?.error ?? `Runner returned HTTP ${res.status}`); + } + const items = Array.isArray(res.json) + ? res.json + : Array.isArray(res.json?.runs) + ? res.json.runs + : []; + return items.map((r) => ({ + id: String(r.id), + name: r.name ?? r.workflow ?? r.command ?? `Run ${r.id}`, + ref: r.ref ?? r.branch ?? "main", + status: r.status ?? "unknown", + conclusion: + r.conclusion ?? (r.exitCode === 0 ? "success" : r.exitCode != null ? "failure" : null), + durationMs: r.durationMs ?? null, + createdAt: r.createdAt ?? r.startedAt ?? null, + url: r.url ?? null, + })); + } + + if (runner.provider === "github") { + const repo = requireRepo(runner); + const res = await fetchJson(`${base}/repos/${repo}/actions/runs?per_page=${limit}`, { + method: "GET", + headers, + }); + if (!res.ok) { + throw new Error(res.json?.message ?? `GitHub API returned HTTP ${res.status}`); + } + const items = Array.isArray(res.json?.workflow_runs) ? res.json.workflow_runs : []; + return items.map((r) => ({ + id: String(r.id), + name: r.name || r.display_title || `Run #${r.run_number}`, + ref: r.head_branch ?? "main", + status: r.status ?? "unknown", + conclusion: r.conclusion ?? null, + durationMs: null, + createdAt: r.created_at ?? null, + url: r.html_url ?? null, + })); + } + + if (runner.provider === "gitlab") { + const repo = requireRepo(runner); + const res = await fetchJson( + `${base}/api/v4/projects/${encodeGitLabProject(repo)}/pipelines?per_page=${limit}`, + { method: "GET", headers }, + ); + if (!res.ok) { + throw new Error(res.json?.message ?? `GitLab API returned HTTP ${res.status}`); + } + const items = Array.isArray(res.json) ? res.json : []; + return items.map((p) => ({ + id: String(p.id), + name: `Pipeline #${p.id}`, + ref: p.ref ?? "main", + status: + p.status === "success" || p.status === "failed" || p.status === "canceled" + ? "completed" + : p.status, + conclusion: + p.status === "success" + ? "success" + : p.status === "failed" + ? "failure" + : p.status === "canceled" + ? "cancelled" + : null, + durationMs: null, + createdAt: p.created_at ?? null, + url: p.web_url ?? null, + })); + } + + if (runner.provider === "forgejo") { + const repo = requireRepo(runner); + const res = await fetchJson(`${base}/api/v1/repos/${repo}/actions/runs?limit=${limit}`, { + method: "GET", + headers, + }); + if (!res.ok) { + throw new Error(res.json?.message ?? `Forgejo API returned HTTP ${res.status}`); + } + const items = Array.isArray(res.json?.workflow_runs) + ? res.json.workflow_runs + : Array.isArray(res.json) + ? res.json + : []; + return items.map((r) => ({ + id: String(r.id), + name: r.title ?? r.name ?? `Run #${r.id}`, + ref: r.ref ?? r.branch ?? "main", + status: r.status ?? "unknown", + conclusion: r.conclusion ?? null, + durationMs: null, + createdAt: r.created ?? r.created_at ?? null, + url: r.html_url ?? null, + })); + } + + throw new Error(`Unsupported provider "${runner.provider}".`); +} + +/** + * Trigger a CI run directly on the runner or forge API. + */ +export async function triggerRun(runner, payload = {}) { + const base = runner.apiBaseUrl.replace(/\/+$/, ""); + const headers = { + ...authHeaders(runner), + "content-type": "application/json", + }; + const ref = + (typeof payload.ref === "string" && payload.ref.trim()) || runner.defaultRef || "main"; + const workflow = + (typeof payload.workflow === "string" && payload.workflow.trim()) || + runner.defaultWorkflow || + ""; + + if (runner.provider === "custom-http") { + const body = { + ref, + ...(workflow ? { workflow } : {}), + ...(typeof payload.command === "string" && payload.command.trim() + ? { command: payload.command.trim() } + : {}), + ...(typeof payload.cwd === "string" && payload.cwd.trim() ? { cwd: payload.cwd.trim() } : {}), + ...(payload.env && typeof payload.env === "object" ? { env: payload.env } : {}), + labels: runner.labels, + }; + const res = await fetchJson(`${base}/runs`, { + method: "POST", + headers, + body: JSON.stringify(body), + }); + if (!res.ok) { + throw new Error(res.json?.error ?? `Runner rejected trigger (HTTP ${res.status})`); + } + return { + ok: true, + runId: String(res.json?.id ?? res.json?.runId ?? ""), + status: res.json?.status ?? "queued", + ref, + workflow, + command: body.command ?? "", + raw: res.json, + }; + } + + if (runner.provider === "github") { + const repo = requireRepo(runner); + if (!workflow) { + throw new Error('GitHub workflow dispatch requires "workflow" (e.g. "ci.yml").'); + } + const res = await fetchJson( + `${base}/repos/${repo}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, + { + method: "POST", + headers, + body: JSON.stringify({ + ref, + ...(payload.inputs && typeof payload.inputs === "object" + ? { inputs: payload.inputs } + : {}), + }), + }, + ); + if (!res.ok) { + throw new Error(res.json?.message ?? `GitHub dispatch failed (HTTP ${res.status})`); + } + return { ok: true, runId: "", status: "dispatched", ref, workflow }; + } + + if (runner.provider === "gitlab") { + const repo = requireRepo(runner); + const variables = + payload.env && typeof payload.env === "object" + ? Object.entries(payload.env).map(([key, value]) => ({ key, value: String(value) })) + : undefined; + const res = await fetchJson(`${base}/api/v4/projects/${encodeGitLabProject(repo)}/pipeline`, { + method: "POST", + headers, + body: JSON.stringify({ + ref, + ...(variables && variables.length > 0 ? { variables } : {}), + }), + }); + if (!res.ok) { + throw new Error(res.json?.message ?? `GitLab pipeline trigger failed (HTTP ${res.status})`); + } + return { + ok: true, + runId: String(res.json?.id ?? ""), + status: res.json?.status ?? "created", + ref, + workflow, + url: res.json?.web_url ?? null, + }; + } + + if (runner.provider === "forgejo") { + const repo = requireRepo(runner); + if (!workflow) { + throw new Error('Forgejo workflow dispatch requires "workflow" (e.g. "ci.yaml").'); + } + const res = await fetchJson( + `${base}/api/v1/repos/${repo}/actions/workflows/${encodeURIComponent(workflow)}/dispatches`, + { + method: "POST", + headers, + body: JSON.stringify({ + ref, + ...(payload.inputs && typeof payload.inputs === "object" + ? { inputs: payload.inputs } + : {}), + }), + }, + ); + if (!res.ok) { + throw new Error(res.json?.message ?? `Forgejo dispatch failed (HTTP ${res.status})`); + } + return { ok: true, runId: "", status: "dispatched", ref, workflow }; + } + + throw new Error(`Unsupported provider "${runner.provider}".`); +} + +/** + * Cancel an active CI run. + */ +export async function cancelRun(runner, runId) { + const base = runner.apiBaseUrl.replace(/\/+$/, ""); + const headers = authHeaders(runner); + const safeId = encodeURIComponent(String(runId)); + + let url; + if (runner.provider === "custom-http") { + url = `${base}/runs/${safeId}/cancel`; + } else if (runner.provider === "github") { + url = `${base}/repos/${requireRepo(runner)}/actions/runs/${safeId}/cancel`; + } else if (runner.provider === "gitlab") { + url = `${base}/api/v4/projects/${encodeGitLabProject(requireRepo(runner))}/pipelines/${safeId}/cancel`; + } else if (runner.provider === "forgejo") { + url = `${base}/api/v1/repos/${requireRepo(runner)}/actions/runs/${safeId}/cancel`; + } else { + throw new Error(`Unsupported provider "${runner.provider}".`); + } + + const res = await fetchJson(url, { method: "POST", headers }); + if (!res.ok) { + throw new Error(res.json?.error ?? res.json?.message ?? `Cancel failed (HTTP ${res.status})`); + } + return { ok: true, runId: String(runId), status: "cancelled" }; +} + +/** + * Fetch logs / job trace for a CI run. + */ +export async function getRunLogs(runner, runId) { + const base = runner.apiBaseUrl.replace(/\/+$/, ""); + const headers = authHeaders(runner); + const safeId = encodeURIComponent(String(runId)); + + if (runner.provider === "custom-http") { + const res = await fetchJson(`${base}/runs/${safeId}/logs`, { method: "GET", headers }); + if (!res.ok) { + throw new Error(res.json?.error ?? `Failed to fetch logs (HTTP ${res.status})`); + } + return { + runId: String(runId), + logs: typeof res.json?.logs === "string" ? res.json.logs : res.text, + }; + } + + if (runner.provider === "github") { + const repo = requireRepo(runner); + const jobsRes = await fetchJson(`${base}/repos/${repo}/actions/runs/${safeId}/jobs`, { + method: "GET", + headers, + }); + if (!jobsRes.ok) { + throw new Error( + jobsRes.json?.message ?? `GitHub jobs lookup failed (HTTP ${jobsRes.status})`, + ); + } + const jobs = Array.isArray(jobsRes.json?.jobs) ? jobsRes.json.jobs : []; + const lines = jobs.map((job) => { + const steps = Array.isArray(job.steps) + ? job.steps.map((s) => ` - [${s.conclusion ?? s.status}] ${s.name}`).join("\n") + : ""; + return `Job: ${job.name} (${job.conclusion ?? job.status})\n${steps}`; + }); + return { + runId: String(runId), + logs: lines.join("\n\n") || "No jobs reported for this run.", + jobs: jobs.map((j) => ({ + id: j.id, + name: j.name, + status: j.status, + conclusion: j.conclusion, + })), + }; + } + + if (runner.provider === "gitlab") { + const repo = encodeGitLabProject(requireRepo(runner)); + const jobsRes = await fetchJson(`${base}/api/v4/projects/${repo}/pipelines/${safeId}/jobs`, { + method: "GET", + headers, + }); + if (!jobsRes.ok) { + throw new Error( + jobsRes.json?.message ?? `GitLab jobs lookup failed (HTTP ${jobsRes.status})`, + ); + } + const jobs = Array.isArray(jobsRes.json) ? jobsRes.json : []; + const targetJob = jobs.find((j) => j.status === "failed") ?? jobs[0]; + if (!targetJob) { + return { runId: String(runId), logs: "No jobs found for this pipeline." }; + } + const traceRes = await fetchJson(`${base}/api/v4/projects/${repo}/jobs/${targetJob.id}/trace`, { + method: "GET", + headers: { ...headers, accept: "text/plain" }, + }); + return { + runId: String(runId), + jobId: String(targetJob.id), + jobName: targetJob.name, + logs: traceRes.ok ? traceRes.text : `Failed to read trace (HTTP ${traceRes.status})`, + }; + } + + if (runner.provider === "forgejo") { + const repo = requireRepo(runner); + const jobsRes = await fetchJson(`${base}/api/v1/repos/${repo}/actions/runs/${safeId}/jobs`, { + method: "GET", + headers, + }); + if (!jobsRes.ok) { + throw new Error( + jobsRes.json?.message ?? `Forgejo jobs lookup failed (HTTP ${jobsRes.status})`, + ); + } + const jobs = Array.isArray(jobsRes.json?.jobs) + ? jobsRes.json.jobs + : Array.isArray(jobsRes.json) + ? jobsRes.json + : []; + const lines = jobs.map((j) => `Job: ${j.name ?? j.id} (${j.conclusion ?? j.status})`); + return { + runId: String(runId), + logs: lines.join("\n") || "No jobs reported for this run.", + }; + } + + throw new Error(`Unsupported provider "${runner.provider}".`); +} diff --git a/m3/plugins/ci-runners/runnerDeployer.mjs b/m3/plugins/ci-runners/runnerDeployer.mjs new file mode 100644 index 0000000000000..8a5ff8832195b --- /dev/null +++ b/m3/plugins/ci-runners/runnerDeployer.mjs @@ -0,0 +1,500 @@ +import * as NodeChildProcess from "node:child_process"; + +import { normalizeLabels, RUNNER_PROVIDERS } from "./runnerStore.mjs"; + +export const DEPLOY_MODES = ["docker", "systemd", "ssh"]; + +const SAFE_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; +const SAFE_HOST_RE = /^[a-zA-Z0-9._:-]+$/; +const SAFE_USER_RE = /^[a-zA-Z0-9._-]+$/; + +function shellQuote(value) { + return `'${String(value).replace(/'/g, `'\\''`)}'`; +} + +function sanitizeRunnerName(raw) { + const cleaned = String(raw ?? "m3-runner") + .trim() + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 64); + return cleaned.length > 0 && SAFE_NAME_RE.test(cleaned) ? cleaned : "m3-runner"; +} + +function sanitizePort(raw, fallback) { + const num = Number(raw ?? fallback); + if (!Number.isInteger(num) || num < 1 || num > 65535) { + throw new Error(`Invalid port: ${raw}`); + } + return num; +} + +function sanitizeConcurrency(raw) { + const num = Number(raw ?? 2); + if (!Number.isInteger(num) || num < 1 || num > 64) { + throw new Error(`Invalid concurrency: ${raw} (expected 1..64)`); + } + return num; +} + +/** + * Zero-dependency self-hosted HTTP CI runner daemon (`m3-runner-agent.mjs`). + * Teams can deploy this directly on any Linux/macOS host via Docker, systemd, or SSH + * and manage it over the M3 CI Runners plugin API. + */ +export const M3_RUNNER_AGENT_SCRIPT = `#!/usr/bin/env node +import * as http from "node:http"; +import * as cp from "node:child_process"; +import * as crypto from "node:crypto"; +import * as os from "node:os"; + +const PORT = Number(process.env.M3_RUNNER_PORT || process.env.PORT || 8787); +const HOST = process.env.M3_RUNNER_HOST || "0.0.0.0"; +const NAME = process.env.M3_RUNNER_NAME || os.hostname(); +const TOKEN = process.env.M3_RUNNER_TOKEN || ""; +const WORKDIR = process.env.M3_RUNNER_WORKDIR || process.cwd(); +const CONCURRENCY = Math.max(1, Number(process.env.M3_RUNNER_CONCURRENCY || 2)); +const LABELS = (process.env.M3_RUNNER_LABELS || "self-hosted,m3-runner") + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + +const runs = new Map(); +const procs = new Map(); + +function activeCount() { + let n = 0; + for (const r of runs.values()) if (r.status === "in_progress") n++; + return n; +} + +function sendJson(res, status, data) { + res.writeHead(status, { "content-type": "application/json; charset=utf-8" }); + res.end(JSON.stringify(data)); +} + +function isAuthorized(req) { + if (!TOKEN) return true; + const auth = req.headers.authorization || ""; + return auth === \`Bearer \${TOKEN}\`; +} + +function readJson(req) { + return new Promise((resolve) => { + const chunks = []; + req.on("data", (c) => chunks.push(c)); + req.on("end", () => { + try { + resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}")); + } catch { + resolve({}); + } + }); + }); +} + +http.createServer(async (req, res) => { + if (!isAuthorized(req)) return sendJson(res, 401, { error: "Unauthorized" }); + const url = new URL(req.url || "/", "http://localhost"); + const pathname = url.pathname; + + if (req.method === "GET" && pathname === "/health") { + const activeJobs = activeCount(); + return sendJson(res, 200, { + ok: true, + name: NAME, + version: "1.0.0", + platform: process.platform, + arch: process.arch, + labels: LABELS, + concurrency: CONCURRENCY, + activeJobs, + busy: activeJobs >= CONCURRENCY, + }); + } + + if (req.method === "GET" && pathname === "/runs") { + const limit = Math.min(100, Math.max(1, Number(url.searchParams.get("limit") || 20))); + const list = [...runs.values()] + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) + .slice(0, limit) + .map(({ logs: _logs, ...meta }) => meta); + return sendJson(res, 200, { runs: list }); + } + + if (req.method === "POST" && pathname === "/runs") { + if (activeCount() >= CONCURRENCY) { + return sendJson(res, 429, { error: "Runner at max concurrency." }); + } + const body = await readJson(req); + const command = typeof body.command === "string" ? body.command.trim() : ""; + if (!command) return sendJson(res, 400, { error: 'Field "command" is required.' }); + const id = \`run_\${crypto.randomBytes(6).toString("hex")}\`; + const startedAt = Date.now(); + const record = { + id, + name: body.workflow || command.slice(0, 60), + ref: body.ref || "main", + command, + status: "in_progress", + conclusion: null, + exitCode: null, + durationMs: null, + createdAt: new Date(startedAt).toISOString(), + logs: \`$ \${command}\\n\`, + }; + runs.set(id, record); + const child = cp.spawn("sh", ["-lc", command], { + cwd: typeof body.cwd === "string" && body.cwd.trim() ? body.cwd.trim() : WORKDIR, + env: { ...process.env, ...(body.env && typeof body.env === "object" ? body.env : {}) }, + stdio: ["ignore", "pipe", "pipe"], + }); + procs.set(id, child); + const append = (chunk) => { + record.logs = (record.logs + chunk.toString("utf8")).slice(-200_000); + }; + child.stdout.on("data", append); + child.stderr.on("data", append); + child.on("close", (code, signal) => { + procs.delete(id); + record.status = "completed"; + record.exitCode = code; + record.durationMs = Date.now() - startedAt; + if (record.conclusion !== "cancelled") { + record.conclusion = code === 0 ? "success" : signal ? "cancelled" : "failure"; + } + }); + return sendJson(res, 202, { id, status: record.status }); + } + + const logsMatch = /^\\/runs\\/([^/]+)\\/logs$/.exec(pathname); + if (req.method === "GET" && logsMatch) { + const run = runs.get(decodeURIComponent(logsMatch[1])); + if (!run) return sendJson(res, 404, { error: "Run not found" }); + return sendJson(res, 200, { id: run.id, logs: run.logs }); + } + + const cancelMatch = /^\\/runs\\/([^/]+)\\/cancel$/.exec(pathname); + if (req.method === "POST" && cancelMatch) { + const id = decodeURIComponent(cancelMatch[1]); + const run = runs.get(id); + if (!run) return sendJson(res, 404, { error: "Run not found" }); + const child = procs.get(id); + run.conclusion = "cancelled"; + if (child) child.kill("SIGTERM"); + return sendJson(res, 200, { ok: true, id, status: "cancelled" }); + } + + return sendJson(res, 404, { error: "Not found" }); +}).listen(PORT, HOST, () => { + console.log(\`[m3-runner-agent] \${NAME} listening on http://\${HOST}:\${PORT}\`); +}); +`; + +/** + * Generate an auditable deployment plan (Docker Compose, `docker run` argv, systemd unit, or SSH script) + * for a self-hosted CI runner. + */ +export function generateDeploymentPlan(input = {}) { + const provider = RUNNER_PROVIDERS.includes(input.provider) ? input.provider : "custom-http"; + const mode = DEPLOY_MODES.includes(input.mode) ? input.mode : "docker"; + const name = sanitizeRunnerName(input.name ?? `m3-${provider}-runner`); + const labels = normalizeLabels(input.labels ?? ["self-hosted", "linux", provider]); + const concurrency = sanitizeConcurrency(input.concurrency ?? 2); + const port = sanitizePort(input.port ?? 8787, 8787); + const workDir = + typeof input.workDir === "string" && input.workDir.trim().length > 0 + ? input.workDir.trim() + : "/var/lib/m3-runner"; + const instanceUrl = + typeof input.instanceUrl === "string" && input.instanceUrl.trim().length > 0 + ? input.instanceUrl.trim().replace(/\/+$/, "") + : provider === "github" + ? "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/OWNER/REPO" + : provider === "gitlab" + ? "https://gitlab.example.com" + : provider === "forgejo" + ? "https://git.example.com" + : `http://127.0.0.1:${port}`; + const registrationToken = + typeof input.registrationToken === "string" ? input.registrationToken.trim() : ""; + const tokenPlaceholder = registrationToken || ""; + + let image = "node:22-alpine"; + let dockerEnv = []; + let dockerPorts = []; + let dockerVolumes = []; + + if (provider === "custom-http") { + image = + typeof input.image === "string" && input.image.trim() ? input.image.trim() : "node:22-alpine"; + dockerPorts = [`${port}:${port}`]; + dockerVolumes = [`${workDir}:/workspace`]; + dockerEnv = [ + `M3_RUNNER_NAME=${name}`, + `M3_RUNNER_PORT=${port}`, + `M3_RUNNER_WORKDIR=/workspace`, + `M3_RUNNER_CONCURRENCY=${concurrency}`, + `M3_RUNNER_LABELS=${labels.join(",")}`, + ...(registrationToken ? [`M3_RUNNER_TOKEN=${registrationToken}`] : []), + ]; + } else if (provider === "github") { + image = + typeof input.image === "string" && input.image.trim() + ? input.image.trim() + : "myoung34/github-runner:latest"; + dockerVolumes = ["/var/run/docker.sock:/var/run/docker.sock", `${workDir}:/tmp/runner`]; + dockerEnv = [ + `REPO_URL=${instanceUrl}`, + `RUNNER_NAME=${name}`, + `RUNNER_TOKEN=${tokenPlaceholder}`, + `RUNNER_WORKDIR=/tmp/runner`, + `LABELS=${labels.join(",")}`, + ]; + } else if (provider === "gitlab") { + image = + typeof input.image === "string" && input.image.trim() + ? input.image.trim() + : "gitlab/gitlab-runner:latest"; + dockerVolumes = [ + "/var/run/docker.sock:/var/run/docker.sock", + `${workDir}/config:/etc/gitlab-runner`, + ]; + dockerEnv = [ + `CI_SERVER_URL=${instanceUrl}`, + `REGISTRATION_TOKEN=${tokenPlaceholder}`, + `RUNNER_NAME=${name}`, + `RUNNER_TAG_LIST=${labels.join(",")}`, + ]; + } else if (provider === "forgejo") { + image = + typeof input.image === "string" && input.image.trim() + ? input.image.trim() + : "code.forgejo.org/forgejo/runner:latest"; + dockerVolumes = ["/var/run/docker.sock:/var/run/docker.sock", `${workDir}:/data`]; + dockerEnv = [ + `FORGEJO_INSTANCE_URL=${instanceUrl}`, + `FORGEJO_RUNNER_TOKEN=${tokenPlaceholder}`, + `FORGEJO_RUNNER_NAME=${name}`, + `FORGEJO_RUNNER_LABELS=${labels.join(",")}`, + ]; + } + + const dockerRunArgv = [ + "run", + "-d", + "--restart", + "unless-stopped", + "--name", + name, + ...dockerPorts.flatMap((p) => ["-p", p]), + ...dockerVolumes.flatMap((v) => ["-v", v]), + ...dockerEnv.flatMap((e) => ["-e", e]), + image, + ...(provider === "custom-http" + ? ["node", "-e", M3_RUNNER_AGENT_SCRIPT.replace(/^#!.*\n/, "")] + : []), + ]; + + const displayDockerCmd = [ + "docker", + ...dockerRunArgv.map((arg) => + arg.length > 160 + ? "" + : /[\s"'$&|;]/.test(arg) + ? shellQuote(arg) + : arg, + ), + ].join(" "); + + const composeLines = [ + "services:", + ` ${name}:`, + ` image: ${image}`, + ` container_name: ${name}`, + " restart: unless-stopped", + ...(dockerPorts.length > 0 ? [" ports:", ...dockerPorts.map((p) => ` - "${p}"`)] : []), + ...(dockerVolumes.length > 0 + ? [" volumes:", ...dockerVolumes.map((v) => ` - "${v}"`)] + : []), + " environment:", + ...dockerEnv.map((e) => { + const [k, ...rest] = e.split("="); + return ` ${k}: "${rest.join("=")}"`; + }), + ]; + + const systemdUnit = `[Unit] +Description=M3 Self-Hosted CI Runner (${name} / ${provider}) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +WorkingDirectory=${workDir} +${dockerEnv.map((e) => `Environment="${e}"`).join("\n")} +ExecStart=${ + provider === "custom-http" + ? `/usr/bin/env node ${workDir}/m3-runner-agent.mjs` + : provider === "gitlab" + ? `/usr/bin/gitlab-runner run --working-directory ${workDir}` + : provider === "forgejo" + ? `/usr/local/bin/forgejo-runner daemon --config ${workDir}/config.yml` + : `${workDir}/run.sh` + } +Restart=always +RestartSec=5 +NoNewPrivileges=true + +[Install] +WantedBy=multi-user.target +`; + + const sshHost = typeof input.sshHost === "string" ? input.sshHost.trim() : ""; + const sshUser = + typeof input.sshUser === "string" && input.sshUser.trim() ? input.sshUser.trim() : "root"; + const sshPort = sanitizePort(input.sshPort ?? 22, 22); + + const remoteInstallScript = [ + "set -euo pipefail", + `mkdir -p ${shellQuote(workDir)}`, + ...(provider === "custom-http" + ? [ + `cat <<'EOF_M3_AGENT' > ${shellQuote(`${workDir}/m3-runner-agent.mjs`)}`, + M3_RUNNER_AGENT_SCRIPT.trimEnd(), + "EOF_M3_AGENT", + `chmod +x ${shellQuote(`${workDir}/m3-runner-agent.mjs`)}`, + ] + : []), + `if command -v docker >/dev/null 2>&1; then`, + ` docker rm -f ${shellQuote(name)} >/dev/null 2>&1 || true`, + ` ${displayDockerCmd.replace("", shellQuote(M3_RUNNER_AGENT_SCRIPT.replace(/^#!.*\n/, "")))}`, + `else`, + ` echo "Docker not found on remote host; writing systemd unit to ${workDir}/${name}.service"`, + ` cat <<'EOF_UNIT' > ${shellQuote(`${workDir}/${name}.service`)}`, + systemdUnit.trimEnd(), + "EOF_UNIT", + "fi", + ].join("\n"); + + const sshPreview = sshHost + ? `ssh -p ${sshPort} -o BatchMode=yes ${shellQuote(`${sshUser}@${sshHost}`)} 'bash -s' < deploy-${name}.sh` + : `ssh -p ${sshPort} -o BatchMode=yes @ 'bash -s' < deploy-${name}.sh`; + + const suggestedApiBaseUrl = + provider === "custom-http" ? `http://${sshHost || "127.0.0.1"}:${port}` : instanceUrl; + + return { + provider, + mode, + name, + labels, + concurrency, + port, + workDir, + image, + suggestedApiBaseUrl, + dockerCommand: displayDockerCmd, + dockerRunArgv, + dockerComposeYaml: `${composeLines.join("\n")}\n`, + systemdUnit, + sshCommand: sshPreview, + remoteInstallScript, + }; +} + +function execFileCapture(command, args, options = {}) { + return new Promise((resolve) => { + const child = NodeChildProcess.spawn(command, args, { + stdio: [options.stdin ? "pipe" : "ignore", "pipe", "pipe"], + timeout: options.timeoutMs ?? 60_000, + }); + let stdout = ""; + let stderr = ""; + child.stdout?.on("data", (chunk) => { + stdout = `${stdout}${chunk.toString("utf8")}`.slice(-32_000); + }); + child.stderr?.on("data", (chunk) => { + stderr = `${stderr}${chunk.toString("utf8")}`.slice(-32_000); + }); + child.on("error", (err) => { + resolve({ ok: false, exitCode: -1, stdout, stderr: err.message }); + }); + child.on("close", (code) => { + resolve({ + ok: code === 0, + exitCode: code ?? -1, + stdout: stdout.trim(), + stderr: stderr.trim(), + }); + }); + if (options.stdin && child.stdin) { + child.stdin.write(options.stdin); + child.stdin.end(); + } + }); +} + +/** + * Execute a runner deployment via local Docker or remote SSH. + * Uses argv-based `spawn` (no local shell interpolation) for safety. + */ +export async function executeDeployment(input = {}) { + const plan = generateDeploymentPlan(input); + + if (plan.mode === "docker") { + const result = await execFileCapture("docker", plan.dockerRunArgv, { timeoutMs: 90_000 }); + return { + ...result, + mode: "docker", + plan: { + name: plan.name, + provider: plan.provider, + suggestedApiBaseUrl: plan.suggestedApiBaseUrl, + labels: plan.labels, + }, + }; + } + + if (plan.mode === "ssh") { + const sshHost = typeof input.sshHost === "string" ? input.sshHost.trim() : ""; + const sshUser = + typeof input.sshUser === "string" && input.sshUser.trim() ? input.sshUser.trim() : "root"; + const sshPort = sanitizePort(input.sshPort ?? 22, 22); + if (!sshHost || !SAFE_HOST_RE.test(sshHost)) { + throw new Error('Valid "sshHost" is required for SSH deployment.'); + } + if (!SAFE_USER_RE.test(sshUser)) { + throw new Error('Invalid "sshUser" for SSH deployment.'); + } + const result = await execFileCapture( + "ssh", + [ + "-p", + String(sshPort), + "-o", + "BatchMode=yes", + "-o", + "ConnectTimeout=10", + `${sshUser}@${sshHost}`, + "bash -s", + ], + { stdin: `${plan.remoteInstallScript}\n`, timeoutMs: 120_000 }, + ); + return { + ...result, + mode: "ssh", + plan: { + name: plan.name, + provider: plan.provider, + suggestedApiBaseUrl: plan.suggestedApiBaseUrl, + labels: plan.labels, + }, + }; + } + + throw new Error( + `Direct execution supports "docker" and "ssh" modes; for "systemd", copy the generated unit file.`, + ); +} diff --git a/m3/plugins/ci-runners/runnerStore.mjs b/m3/plugins/ci-runners/runnerStore.mjs new file mode 100644 index 0000000000000..d1c5ef28f9e69 --- /dev/null +++ b/m3/plugins/ci-runners/runnerStore.mjs @@ -0,0 +1,262 @@ +import * as NodeCrypto from "node:crypto"; +import * as NodeFSP from "node:fs/promises"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +export const RUNNER_PROVIDERS = ["custom-http", "github", "gitlab", "forgejo"]; +const PROVIDER_SET = new Set(RUNNER_PROVIDERS); + +const MAX_RUN_HISTORY = 200; + +function asRecord(value) { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined; +} + +function nonEmptyString(value) { + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +export function validateApiBaseUrl(raw) { + const str = nonEmptyString(raw); + if (!str) { + throw new Error("apiBaseUrl is required."); + } + let parsed; + try { + parsed = new URL(str); + } catch { + throw new Error(`Invalid apiBaseUrl: "${str}".`); + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error(`apiBaseUrl must use http:// or https:// (got "${parsed.protocol}").`); + } + return parsed.toString().replace(/\/+$/, ""); +} + +export function normalizeLabels(raw) { + if (Array.isArray(raw)) { + return [ + ...new Set( + raw + .map((item) => (typeof item === "string" ? item.trim() : "")) + .filter((item) => item.length > 0), + ), + ]; + } + if (typeof raw === "string") { + return [ + ...new Set( + raw + .split(",") + .map((item) => item.trim()) + .filter((item) => item.length > 0), + ), + ]; + } + return []; +} + +export function maskSecret(secret) { + if (typeof secret !== "string" || secret.length === 0) return null; + if (secret.length <= 4) return "••••"; + return `••••${secret.slice(-4)}`; +} + +export function toPublicRunner(runner) { + const { token, ...rest } = runner; + return { + ...rest, + tokenSet: typeof token === "string" && token.length > 0, + tokenPreview: maskSecret(token), + }; +} + +export function resolveDefaultDataDir() { + const envDir = nonEmptyString(process.env.M3_PLUGIN_DATA_DIR); + if (envDir) return NodePath.resolve(envDir); + const envHome = + nonEmptyString(process.env.M3_HOME_DIR) ?? nonEmptyString(process.env.M3CODE_HOME); + const baseHome = envHome + ? NodePath.resolve(envHome.replace(/^~(?=\/|$)/, NodeOS.homedir())) + : NodePath.join(NodeOS.homedir(), ".m3"); + return NodePath.join(baseHome, "userdata", "plugins", "ci-runners"); +} + +export class RunnerStore { + constructor(dataDir = resolveDefaultDataDir()) { + this.dataDir = NodePath.resolve(dataDir); + this.statePath = NodePath.join(this.dataDir, "runners.json"); + } + + async readState() { + try { + const raw = await NodeFSP.readFile(this.statePath, "utf8"); + const parsed = JSON.parse(raw); + return { + runners: Array.isArray(parsed?.runners) ? parsed.runners : [], + runs: Array.isArray(parsed?.runs) ? parsed.runs : [], + }; + } catch { + return { runners: [], runs: [] }; + } + } + + async writeState(state) { + await NodeFSP.mkdir(this.dataDir, { recursive: true, mode: 0o700 }); + const tmpPath = `${this.statePath}.${process.pid}.${NodeCrypto.randomBytes(4).toString("hex")}.tmp`; + await NodeFSP.writeFile(tmpPath, `${JSON.stringify(state, null, 2)}\n`, { + encoding: "utf8", + mode: 0o600, + }); + await NodeFSP.rename(tmpPath, this.statePath); + } + + async listRunners() { + const state = await this.readState(); + return state.runners.map(toPublicRunner); + } + + async getRunnerRaw(id) { + const state = await this.readState(); + return state.runners.find((r) => r.id === id) ?? null; + } + + async createRunner(input) { + const rec = asRecord(input); + if (!rec) throw new Error("Runner payload must be a JSON object."); + + const name = nonEmptyString(rec.name); + if (!name) throw new Error('Field "name" is required.'); + + const provider = nonEmptyString(rec.provider) ?? "custom-http"; + if (!PROVIDER_SET.has(provider)) { + throw new Error( + `Unsupported provider "${provider}". Expected: ${RUNNER_PROVIDERS.join(", ")}.`, + ); + } + + const apiBaseUrl = validateApiBaseUrl(rec.apiBaseUrl); + const repo = nonEmptyString(rec.repo) ?? ""; + const defaultWorkflow = nonEmptyString(rec.defaultWorkflow) ?? ""; + const defaultRef = nonEmptyString(rec.defaultRef) ?? "main"; + const token = typeof rec.token === "string" ? rec.token.trim() : ""; + const labels = normalizeLabels(rec.labels); + const deploy = asRecord(rec.deploy) ?? null; + const now = new Date().toISOString(); + + const runner = { + id: nonEmptyString(rec.id) ?? `runner_${NodeCrypto.randomBytes(6).toString("hex")}`, + name, + provider, + apiBaseUrl, + repo, + defaultWorkflow, + defaultRef, + labels, + token, + deploy, + createdAt: now, + updatedAt: now, + }; + + const state = await this.readState(); + if (state.runners.some((r) => r.id === runner.id)) { + throw new Error(`Runner "${runner.id}" already exists.`); + } + state.runners.push(runner); + await this.writeState(state); + return toPublicRunner(runner); + } + + async updateRunner(id, patch) { + const rec = asRecord(patch); + if (!rec) throw new Error("Update payload must be a JSON object."); + + const state = await this.readState(); + const index = state.runners.findIndex((r) => r.id === id); + if (index === -1) return null; + + const existing = state.runners[index]; + const nextProvider = + rec.provider !== undefined ? nonEmptyString(rec.provider) : existing.provider; + if (!nextProvider || !PROVIDER_SET.has(nextProvider)) { + throw new Error(`Unsupported provider "${String(rec.provider)}".`); + } + + const updated = { + ...existing, + name: rec.name !== undefined ? (nonEmptyString(rec.name) ?? existing.name) : existing.name, + provider: nextProvider, + apiBaseUrl: + rec.apiBaseUrl !== undefined ? validateApiBaseUrl(rec.apiBaseUrl) : existing.apiBaseUrl, + repo: + rec.repo !== undefined + ? typeof rec.repo === "string" + ? rec.repo.trim() + : "" + : existing.repo, + defaultWorkflow: + rec.defaultWorkflow !== undefined + ? typeof rec.defaultWorkflow === "string" + ? rec.defaultWorkflow.trim() + : "" + : existing.defaultWorkflow, + defaultRef: + rec.defaultRef !== undefined + ? (nonEmptyString(rec.defaultRef) ?? "main") + : existing.defaultRef, + labels: rec.labels !== undefined ? normalizeLabels(rec.labels) : existing.labels, + token: + rec.token !== undefined + ? typeof rec.token === "string" && rec.token.trim().length > 0 + ? rec.token.trim() + : rec.clearToken === true + ? "" + : existing.token + : existing.token, + deploy: rec.deploy !== undefined ? (asRecord(rec.deploy) ?? null) : existing.deploy, + updatedAt: new Date().toISOString(), + }; + + state.runners[index] = updated; + await this.writeState(state); + return toPublicRunner(updated); + } + + async deleteRunner(id) { + const state = await this.readState(); + const next = state.runners.filter((r) => r.id !== id); + if (next.length === state.runners.length) return false; + state.runners = next; + await this.writeState(state); + return true; + } + + async recordLocalRun(entry) { + const state = await this.readState(); + const record = { + id: entry.id ?? `run_${NodeCrypto.randomBytes(6).toString("hex")}`, + runnerId: entry.runnerId, + ref: entry.ref ?? "main", + workflow: entry.workflow ?? "", + command: entry.command ?? "", + status: entry.status ?? "queued", + conclusion: entry.conclusion ?? null, + url: entry.url ?? null, + createdAt: entry.createdAt ?? new Date().toISOString(), + }; + state.runs = [record, ...state.runs.filter((r) => r.id !== record.id)].slice( + 0, + MAX_RUN_HISTORY, + ); + await this.writeState(state); + return record; + } + + async listLocalRuns(runnerId) { + const state = await this.readState(); + return runnerId ? state.runs.filter((r) => r.runnerId === runnerId) : state.runs; + } +} diff --git a/m3/plugins/ci-runners/server.mjs b/m3/plugins/ci-runners/server.mjs new file mode 100644 index 0000000000000..71bec0c519c3c --- /dev/null +++ b/m3/plugins/ci-runners/server.mjs @@ -0,0 +1,249 @@ +import * as NodeFSP from "node:fs/promises"; +import * as NodeHttp from "node:http"; +import * as NodePath from "node:path"; +import * as NodeURL from "node:url"; + +import { cancelRun, getRunLogs, listRuns, probeRunner, triggerRun } from "./runnerApi.mjs"; +import { + executeDeployment, + generateDeploymentPlan, + M3_RUNNER_AGENT_SCRIPT, +} from "./runnerDeployer.mjs"; +import { RunnerStore } from "./runnerStore.mjs"; + +const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); +const UI_INDEX_PATH = NodePath.join(__dirname, "ui", "index.html"); + +function sendJson(res, status, body) { + res.writeHead(status, { + "content-type": "application/json; charset=utf-8", + "cache-control": "no-store", + }); + res.end(JSON.stringify(body)); +} + +function readJsonBody(req) { + return new Promise((resolve) => { + const chunks = []; + req.on("data", (chunk) => chunks.push(chunk)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + if (!raw.trim()) { + resolve({}); + return; + } + try { + const parsed = JSON.parse(raw); + resolve( + typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {}, + ); + } catch { + resolve({}); + } + }); + req.on("error", () => resolve({})); + }); +} + +export function createCiRunnersRequestHandler(store = new RunnerStore()) { + return async function handleRequest(req, res) { + const method = req.method ?? "GET"; + const parsedUrl = new URL(req.url ?? "/", "http://127.0.0.1"); + const pathname = parsedUrl.pathname.replace(/\/+$/, "") || "/"; + + try { + if (method === "GET" && (pathname === "/" || pathname === "/index.html")) { + const html = await NodeFSP.readFile(UI_INDEX_PATH, "utf8"); + res.writeHead(200, { + "content-type": "text/html; charset=utf-8", + "cache-control": "no-store", + }); + res.end(html); + return; + } + + if (method === "GET" && pathname === "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/api/health") { + const runners = await store.listRunners(); + return sendJson(res, 200, { + ok: true, + pluginId: process.env.M3_PLUGIN_ID ?? "ci-runners", + version: "1.0.0", + runnerCount: runners.length, + }); + } + + if (method === "GET" && pathname === "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/api/runners") { + const runners = await store.listRunners(); + return sendJson(res, 200, { ok: true, runners }); + } + + if (method === "POST" && pathname === "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/api/runners") { + const body = await readJsonBody(req); + const runner = await store.createRunner(body); + return sendJson(res, 201, { ok: true, runner }); + } + + const runnerMatch = /^\/api\/runners\/([^/]+)$/.exec(pathname); + if (runnerMatch) { + const id = decodeURIComponent(runnerMatch[1]); + if (method === "PUT" || method === "PATCH") { + const body = await readJsonBody(req); + const updated = await store.updateRunner(id, body); + if (!updated) + return sendJson(res, 404, { ok: false, error: `Runner "${id}" not found.` }); + return sendJson(res, 200, { ok: true, runner: updated }); + } + if (method === "DELETE") { + const deleted = await store.deleteRunner(id); + if (!deleted) + return sendJson(res, 404, { ok: false, error: `Runner "${id}" not found.` }); + return sendJson(res, 200, { ok: true, id }); + } + } + + const probeMatch = /^\/api\/runners\/([^/]+)\/probe$/.exec(pathname); + if (method === "POST" && probeMatch) { + const id = decodeURIComponent(probeMatch[1]); + const runner = await store.getRunnerRaw(id); + if (!runner) return sendJson(res, 404, { ok: false, error: `Runner "${id}" not found.` }); + const status = await probeRunner(runner); + return sendJson(res, 200, { ok: true, runnerId: id, ...status }); + } + + const runsMatch = /^\/api\/runners\/([^/]+)\/runs$/.exec(pathname); + if (method === "GET" && runsMatch) { + const id = decodeURIComponent(runsMatch[1]); + const runner = await store.getRunnerRaw(id); + if (!runner) return sendJson(res, 404, { ok: false, error: `Runner "${id}" not found.` }); + const limit = Number(parsedUrl.searchParams.get("limit") ?? 20); + try { + const runs = await listRuns(runner, { limit }); + return sendJson(res, 200, { ok: true, runnerId: id, runs, source: "live" }); + } catch (err) { + const localRuns = await store.listLocalRuns(id); + return sendJson(res, 200, { + ok: true, + runnerId: id, + runs: localRuns, + source: "local-history", + warning: err instanceof Error ? err.message : String(err), + }); + } + } + + const triggerMatch = /^\/api\/runners\/([^/]+)\/trigger$/.exec(pathname); + if (method === "POST" && triggerMatch) { + const id = decodeURIComponent(triggerMatch[1]); + const runner = await store.getRunnerRaw(id); + if (!runner) return sendJson(res, 404, { ok: false, error: `Runner "${id}" not found.` }); + const body = await readJsonBody(req); + const result = await triggerRun(runner, body); + const recorded = await store.recordLocalRun({ + id: result.runId || undefined, + runnerId: id, + ref: result.ref, + workflow: result.workflow, + command: result.command, + status: result.status, + url: result.url ?? null, + }); + return sendJson(res, 202, { ok: true, ...result, record: recorded }); + } + + const cancelMatch = /^\/api\/runners\/([^/]+)\/runs\/([^/]+)\/cancel$/.exec(pathname); + if (method === "POST" && cancelMatch) { + const id = decodeURIComponent(cancelMatch[1]); + const runId = decodeURIComponent(cancelMatch[2]); + const runner = await store.getRunnerRaw(id); + if (!runner) return sendJson(res, 404, { ok: false, error: `Runner "${id}" not found.` }); + const result = await cancelRun(runner, runId); + return sendJson(res, 200, result); + } + + const logsMatch = /^\/api\/runners\/([^/]+)\/runs\/([^/]+)\/logs$/.exec(pathname); + if (method === "GET" && logsMatch) { + const id = decodeURIComponent(logsMatch[1]); + const runId = decodeURIComponent(logsMatch[2]); + const runner = await store.getRunnerRaw(id); + if (!runner) return sendJson(res, 404, { ok: false, error: `Runner "${id}" not found.` }); + const result = await getRunLogs(runner, runId); + return sendJson(res, 200, { ok: true, ...result }); + } + + if (method === "POST" && pathname === "/api/deploy/plan") { + const body = await readJsonBody(req); + const plan = generateDeploymentPlan(body); + return sendJson(res, 200, { ok: true, plan }); + } + + if (method === "POST" && pathname === "/api/deploy/execute") { + const body = await readJsonBody(req); + const result = await executeDeployment(body); + let registeredRunner = null; + if (result.ok && body.autoRegister === true) { + try { + registeredRunner = await store.createRunner({ + name: result.plan.name, + provider: result.plan.provider, + apiBaseUrl: result.plan.suggestedApiBaseUrl, + labels: result.plan.labels, + token: typeof body.registrationToken === "string" ? body.registrationToken : "", + deploy: { mode: result.mode, host: body.sshHost ?? "127.0.0.1" }, + }); + } catch { + // Runner with same id/name may already exist; still return deploy success. + } + } + return sendJson(res, result.ok ? 200 : 500, { + ...result, + ...(registeredRunner ? { registeredRunner } : {}), + }); + } + + if (method === "GET" && pathname === "/api/deploy/agent-script") { + res.writeHead(200, { + "content-type": "application/javascript; charset=utf-8", + "content-disposition": 'attachment; filename="m3-runner-agent.mjs"', + "cache-control": "no-store", + }); + res.end(M3_RUNNER_AGENT_SCRIPT); + return; + } + + return sendJson(res, 404, { ok: false, error: `Unknown endpoint: ${method} ${pathname}` }); + } catch (err) { + return sendJson(res, 400, { + ok: false, + error: err instanceof Error ? err.message : String(err), + }); + } + }; +} + +export function startServer(options = {}) { + const port = Number(options.port ?? process.env.M3_PLUGIN_PORT ?? process.env.PORT ?? 0); + const host = options.host ?? "127.0.0.1"; + const store = options.store ?? new RunnerStore(options.dataDir); + const server = NodeHttp.createServer(createCiRunnersRequestHandler(store)); + return new Promise((resolve, reject) => { + server.on("error", reject); + server.listen(port, host, () => { + const addr = server.address(); + resolve({ + server, + port: typeof addr === "object" && addr ? addr.port : port, + store, + }); + }); + }); +} + +const isMain = + process.argv[1] && NodePath.resolve(process.argv[1]) === NodeURL.fileURLToPath(import.meta.url); + +if (isMain) { + startServer().catch((err) => { + console.error("[ci-runners] failed to start:", err); + process.exit(1); + }); +} diff --git a/m3/plugins/ci-runners/ui/index.html b/m3/plugins/ci-runners/ui/index.html new file mode 100644 index 0000000000000..5ab8e95a13bb1 --- /dev/null +++ b/m3/plugins/ci-runners/ui/index.html @@ -0,0 +1,746 @@ + + + + + + M3 CI Runners + + + + +
+

CI Runners Native Plugin

+ +
+ + + +
+ + + +
+
+
+ Self-Hosted Runner Fleet + 0 configured +
+
+
+ +
+
Connect a CI Runner
+
+
+ + + + + + + +
+
+ +
+
+
+
+ + + + + + +
+ + + +