From c680109d042bdcb95afebf8df0e641cf2fec4ba2 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 6 Nov 2026 18:00:27 -0600 Subject: [PATCH] Add experimental visual hive control desk with opt-in provider adapters Validated with 9 backend tests and DOM workflow integration. Live provider logins and rendered-browser qualification remain pending. --- AGENTS.md | 6 + README.md | 5 + control-desk/.gitignore | 4 + control-desk/README.md | 191 ++++++++ control-desk/VERIFICATION.md | 41 ++ control-desk/engine.mjs | 406 +++++++++++++++++ control-desk/package-lock.json | 548 +++++++++++++++++++++++ control-desk/package.json | 17 + control-desk/providers.mjs | 139 ++++++ control-desk/public/app.js | 345 +++++++++++++++ control-desk/public/index.html | 275 ++++++++++++ control-desk/public/style.css | 743 ++++++++++++++++++++++++++++++++ control-desk/server.mjs | 352 +++++++++++++++ control-desk/store.mjs | 165 +++++++ control-desk/test/desk.test.mjs | 304 +++++++++++++ control-desk/test/ui-smoke.cjs | 99 +++++ 16 files changed, 3640 insertions(+) create mode 100644 control-desk/.gitignore create mode 100644 control-desk/README.md create mode 100644 control-desk/VERIFICATION.md create mode 100644 control-desk/engine.mjs create mode 100644 control-desk/package-lock.json create mode 100644 control-desk/package.json create mode 100644 control-desk/providers.mjs create mode 100644 control-desk/public/app.js create mode 100644 control-desk/public/index.html create mode 100644 control-desk/public/style.css create mode 100644 control-desk/server.mjs create mode 100644 control-desk/store.mjs create mode 100644 control-desk/test/desk.test.mjs create mode 100644 control-desk/test/ui-smoke.cjs diff --git a/AGENTS.md b/AGENTS.md index cf91db8..86da708 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,12 @@ compiler, a runtime, a gate, or evidence that any claim is true. Eight skills live under `skills//SKILL.md` in the Agent Skills layout (frontmatter `name` and `description`, then the body): +`control-desk/` additionally contains an experimental Node.js host adapter and browser UI. It owns +only its locally created tasks and is outside the qualified Omega trusted stack. It does not +replace canonical `spark-hive` authority or the shared crumb protocol. For changes there, run +`cd control-desk && npm test` and update its verification record. The skill/example gates below +remain applicable to changes in those paths. + | Path | Covers | |---|---| | `skills/omega-harness/SKILL.md` | The workflow: orient, implement in `.om`, compile, run, challenge, effects, repeated errors, guide upkeep | diff --git a/README.md b/README.md index 7b97e88..380acd4 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,10 @@ # Omega Harness +The experimental [visual hive control desk](control-desk/README.md) provides a local task board, +opt-in provider connections, isolated coding attempts, operator steering and artifact review. +It is a Node.js host adapter candidate; see its verification record and integration boundaries +before connecting it to a live hive. + Agent skills for working in Omega, the `.om` language of AienOS, and in the AIEN repositories. An agent that loads these skills finds the actual source before acting, writes `.om` code that the seeded compiler accepts, runs what it builds, and reports its status without overstating it. Skills can't make agents flawless. What these do is turn the mistakes agents keep repeating into checks they must run before they claim anything: stale syntax, guessed compiler limits, compiling without running, labeling host-only runs as qualified, and choosing the wrong repository. diff --git a/control-desk/.gitignore b/control-desk/.gitignore new file mode 100644 index 0000000..2109548 --- /dev/null +++ b/control-desk/.gitignore @@ -0,0 +1,4 @@ +.state/ +config.local.json +artifacts/ +node_modules/ diff --git a/control-desk/README.md b/control-desk/README.md new file mode 100644 index 0000000..2d6e9eb --- /dev/null +++ b/control-desk/README.md @@ -0,0 +1,191 @@ +# Omega control desk — host adapter candidate + +A local visual workbench for an operator-directed hive. It starts paused, connects only the routes +you enable, and keeps task decisions separate from agent transcripts. This initial implementation +is a Node.js host adapter with a browser UI. It is **not an Omega-native runtime or a replacement +for the canonical `spark-hive` task authority**. It owns only tasks created in this desk. + +## Run + +Requires Node.js 24+, Git, and Linux or macOS. No runtime packages to install. + +```sh +cd control-desk +npm test +node server.mjs --repo /absolute/path/to/your/repository +``` + +Open the local URL printed in the terminal. Its fragment contains a private control token. The +server binds to `127.0.0.1` only. Keep the tab and controller on the same machine; do not expose this +prototype through a public tunnel. The browser does not receive provider keys. + +For a separate simulation, without paid model calls: + +```sh +node server.mjs --demo --state /tmp/omega-desk-demo --port 8788 +``` + +Simulation is explicitly labeled. Real providers remain disabled until you enable them. The +simulation worker produces synthetic text and does not edit a repository. + +Options: `--state DIR` (default `control-desk/.state`), `--repo DIR`, `--port 8787`, +`--capacity 3`, and `--demo`. State must be on a local filesystem, not a network share. +Do not run as root. The state directory contains prompts, logs, source snapshots and results; +keep it private and out of Git. No telemetry or third-party frontend assets are loaded. + +## Connect your accounts + +Use the gear beside a connection to edit its command, endpoint, model, timeout, and slot limit. +Saving does not enable a disabled connection. Install and log into the relevant official tool +on the machine running the desk, then enable that connection. Executable detection is labeled +**login unverified**; authentication and quota are exercised by the actual task. + +| Connection | Included route | Authentication / scope | +| --- | --- | --- | +| Claude | `claude -p {prompt}` | Existing Claude Code login and permission policy | +| OpenAI | `codex exec --json --sandbox workspace-write {prompt}` | Existing Codex login and permission policy | +| Grok | `grok -p {prompt}` | Existing Grok Build login and permission policy | +| Gemini | `gemini -p {prompt}` | Existing Gemini CLI login and permission policy | +| Antigravity | `agy -p {prompt}` | Existing Antigravity CLI login and permission policy | +| Muse | Custom command, initially empty | Your actual Muse adapter; no assumed undocumented endpoint | +| Omega | Chat-completions endpoint, initially disabled | Your configured local model; advisory text in this adapter | + +Commands are argument arrays passed directly to `spawn`, never interpolated into a shell. Each +`{prompt}` placeholder receives the full instruction as one argument. With no placeholder the +prompt is sent on stdin. A command inherits the controller's environment and the user's normal +CLI configuration. Never put secrets into command arguments: settings are visible in the UI. + +An account's subscription, regional availability, CLI access and API allowance are determined by +its provider. This desk does not convert web subscriptions into API credits or extract session +cookies. Sign in using each vendor's normal CLI flow; no automatic login changes or installations +are made. Default commands preserve the CLI's permission policy. A permission refusal can end +a headless task; inspect its output and deliberately configure the official tool before retrying. + +For a local or remote **OpenAI-compatible chat-completions** route, set the full endpoint URL, +model, and optionally a key environment variable name such as `OMEGA_API_KEY`. Export that variable +before starting the server. HTTPS is required except on loopback. Credentials in URLs and redirects +are refused. Native Anthropic/Gemini APIs are not this wire format: use their CLI routes or an +explicit adapter. Chat routes return advisory text; they do not run tools or modify files. + +You can bootstrap additional routes using a JSON array in `STATE_DIR/providers.json` before the +first saved connection change. After that, saved database settings take precedence. Example: + +```json +[ + { + "id": "muse", + "name": "Muse", + "kind": "command", + "command": ["/absolute/path/to/muse-adapter", "--prompt", "{prompt}"], + "enabled": false, + "limit": 1, + "timeoutSeconds": 900 + } +] +``` + +That array replaces the initial list; use the UI for ordinary changes. Command adapters must stay +in the foreground and terminate their children when stopped. Keep publishing, deployment and +remote mutations outside these workers. Existing workers keep their original connection settings +when you edit or disable a connection; disabling prevents new dispatch only. + +## Work as a hive + +1. Assign a task with a concrete goal and acceptance criteria. A **queen** task asks the chosen + model for a bounded JSON plan; a **worker** task performs one assignment. +2. Review a queen's plan and choose **Import plan**. The complete plan is validated and inserted + atomically. Import pauses new dispatch so you can inspect it. Existing workers continue. +3. Resume dispatch. Tasks with accepted dependencies run within both the global limit and the + provider's own limit. Disabled or unavailable providers retain their queued tasks. There is + no fallback to a different provider and no automatic retry of failed requests. +4. Watch output and select tasks to inspect the exact instruction and dependency states. Pause + blocks new work; **Stop active** also requests cancellation of current attempts. +5. To redirect an active worker, stop it, wait for settlement, add direction, and explicitly retry. + The successor starts in a fresh checkout. Earlier artifacts remain on disk. This initial + adapter does not claim provider-native mid-turn steering or automatic patch continuation. +6. Inspect the output and patch. **Accept this receipt** records your review of exact hashes and + releases dependents. Acceptance does not mean tests passed, merge changes, or deploy anything. + +Plan format (dependencies are indices of earlier tasks, starting at zero): + +```json +{"tasks":[ + {"title":"Inspect startup","prompt":"Find the startup failure and report evidence.","provider":"claude","dependsOn":[]}, + {"title":"Design the repair","prompt":"Use the accepted evidence to propose a minimal repair.","provider":"openai","dependsOn":[0]} +]} +``` + +Maximum 12 tasks per imported plan. Workers receive dependency receipt metadata and local artifact +paths. They do **not** automatically receive dependency patches in their checkout. Any integration +task must explicitly inspect and apply chosen patches, test the combined result, and submit its own +receipt. Advisory HTTP workers receive metadata only, not filesystem contents. + +## Isolation, recovery and evidence + +- Each CLI attempt clones the configured repository's committed `HEAD` into its own directory, + checks out that exact commit, and removes the origin remote. Source working-tree edits are not + copied. Git submodules and LFS payloads are not provisioned automatically. +- SQLite uses WAL and `synchronous=FULL`; state changes and events commit together. One controller + holds a state-directory lock. Revision checks reject stale task commands. Attempts carry a + generation so late completion cannot turn a stopped attempt into success. +- On restart, in-flight tasks become **interrupted** and dispatch remains paused. A crash can leave + a foreground adapter's subprocesses alive. Inspect them before removing a stale + `controller.lock`; the desk intentionally does not guess or kill arbitrary stored PIDs. An + interrupted retry requires the operator's explicit recovery acknowledgement. +- Stops send TERM then KILL to the local adapter process group. Remote effects may already have + occurred; detached daemons can escape that group. “Canceled” means the local adapter settled, + not that remote work was rolled back. Hard process containment requires the next sandbox phase. +- A successful adapter exit generates `result.txt`, `changes.patch`, and `receipt.json` under + `STATE_DIR/runs/TASK/ATTEMPT`. The patch is relative to the captured base and includes commits, + tracked edits, and nonignored untracked files. Ignored build outputs are not submitted. + Patches are stored and hashed as raw bytes; the browser shows a UTF-8 preview. For non-UTF-8 + content, inspect the original `changes.patch` artifact instead of copying the browser preview. +- Receipt inspection and acceptance recompute artifact hashes. This establishes byte identity, + not authorship, correctness, a passing test suite, or protection against a malicious same-user + process. Full output is bounded: the result keeps the last 200,000 characters; output events + retain at most 8,192 characters per chunk. A 2 MiB adapter output limit stops runaway output. +- Git operations have a 60-second deadline; inference has the configured deadline. Patches are + capped at 8 MiB. HTTP response bodies are capped at 2 MiB. The event API is cursor-paged at 200 + rows; the UI keeps 500 entries and displays 100. One state directory supports 1,000 tasks. + +The checkout is a collaboration boundary, **not an OS sandbox**. Provider tools retain their own +filesystem/network permissions. This candidate is for a trusted operator and trusted CLI tools +on one machine. The process can read the user's provider configuration and environment. Do not +infer hostile-code containment from the visual controls or the removed Git remote. + +## Next integration gates + +1. Wire this UI to canonical `spark-hive` through a versioned adapter after core issue + [925](https://github.com/aien-dev/aien-sovereign-core-mv/issues/925) supplies fenced claims and + artifact-bound submission. Retire this candidate's separate scheduler when that path is ready. + Do not mirror mutable task authority into crumbs, summaries, or a second live queue. +2. Add real per-provider conformance receipts on the operator's installed CLI versions: login, + streaming, permission refusal, quota exhaustion, cancellation, restart, and artifact recovery. +3. Add contained workers (namespaces/containers or native equivalent), resource limits, private + credential injection, and a separate publication actor. Add local disk quotas and archival. +4. Add native event adapters (ACP/app-server where supported) for tool cards, permission requests, + measured usage, mid-turn steering and reliable session continuation. Current output is bounded + text, which can include raw JSON from Codex; no token-price estimates are invented. +5. Add exact-base integration and independent verification receipts before a merge desk. Add + `.om` protocol validation against an actual compiler pin before claiming an Omega-native path. + +## Verification + +```sh +npm test +``` + +For the DOM workflow integration check, install development dependencies with `npm ci`, then run +`npm run test:ui`. This checks actual UI handlers against the backend; it does not render CSS. + +Tests exercise local HTTP control, stale revisions, exact receipt acceptance, dependencies, +atomic plan import, cancellation, timeout/provider isolation, restart recovery, connection +validation, and actual Git checkout isolation. They use synthetic workers, not paid providers. +See `VERIFICATION.md` for the observed run and current limitations. + +Provider command references inspected 2026-11-06: +[Claude](https://code.claude.com/docs/en/headless), +[Codex](https://developers.openai.com/codex/noninteractive), +[Grok Build](https://docs.x.ai/build/overview), +[Gemini](https://geminicli.com/docs/cli/headless/), +[Antigravity](https://antigravity.google/docs/cli/headless). diff --git a/control-desk/VERIFICATION.md b/control-desk/VERIFICATION.md new file mode 100644 index 0000000..c82b5bf --- /dev/null +++ b/control-desk/VERIFICATION.md @@ -0,0 +1,41 @@ +# Control desk verification — 2026-11-06 + +Scope: initial host adapter candidate on Linux, Node.js v24.22.1. Base repository revision: +`bd107ca15c40b6cdfef0f23afb03a884fe3c8086`. This record describes the change containing this file; +it is not a qualification receipt for canonical `spark-hive`, Omega compiler code, or live models. + +| Check | Observed result | +| --- | --- | +| `npm test` | PASS: 9 tests, 0 failures | +| `npm run test:ui` (jsdom + actual local HTTP backend) | PASS: create task, dispatch, inspect receipt, accept, import dependency plan, pause, save Muse command; zero DOM runtime errors | +| JavaScript parse checks | PASS for server and browser entry points | +| Actual Git fixture worker | PASS: isolated clone gets generated files; submitted patch applies to a fresh clone and preserves non-UTF-8 bytes; source repository stays clean; worker clone has no origin remote | +| Wrong/missing access token and cross-origin request | Refused | +| Stale task revision, wrong receipt hashes, tampered receipt file | Refused | +| Self-dependent plan | Refused atomically; zero tasks inserted | +| Interrupted attempt | Preserved as interrupted; no automatic replay | +| Stop then steer and retry | Old attempt stays canceled; explicit retry has a new generation | +| Slow provider alongside another provider | Other provider proceeds within its slot; slow attempt fails on deadline | +| Real browser layout and mobile rendering | NOT_RUN: local browser startup failed on environment socket permissions; supplied cloud browser could not reach the loopback server | +| Live Claude, Codex, Grok, Gemini, Antigravity, Muse or Omega execution | NOT_RUN: no operator login/model connection was exercised | +| Spark deployment, canonical task-authority integration, OS containment, native `.om` implementation | NOT_RUN / future integration gates | + +The browser test uses jsdom for DOM event handling, dialog shims, and Node's fetch against the +actual server. It is not a rendered-browser or screenshot test. It uses the explicitly simulated +provider. The separate backend Git fixture does execute a local synthetic command in a real clone. + +Reproduce: + +```sh +cd control-desk +npm ci +npm test +npm run test:ui +node --check server.mjs +node --check public/app.js +``` + +`jsdom` is a development-only dependency. Starting the desk uses Node built-ins and static assets; +it does not require installing those test dependencies. Run a real browser and one harmless task +with each installed provider before relying on that route for engineering work. Record CLI +versions and actual login, permission, quota, stop and resume behavior in subsequent receipts. diff --git a/control-desk/engine.mjs b/control-desk/engine.mjs new file mode 100644 index 0000000..d0239a2 --- /dev/null +++ b/control-desk/engine.mjs @@ -0,0 +1,406 @@ +import { spawn } from "node:child_process"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { createHash } from "node:crypto"; +import path from "node:path"; +import { readiness } from "./providers.mjs"; + +const hash = (s) => createHash("sha256").update(s).digest("hex"); +export function command(argv, cwd, signal, binary = false) { + return new Promise((resolve, reject) => { + const p = spawn(argv[0], argv.slice(1), { + cwd, + signal, + timeout: 60000, + killSignal: "SIGKILL", + stdio: ["ignore", "pipe", "pipe"], + env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, + }); + const chunks = []; + let err = "", + size = 0; + p.stdout.on("data", (b) => { + size += b.length; + if (size > 8 * 1024 * 1024) p.kill(); + else chunks.push(b); + }); + p.stderr.on("data", (b) => { + err = (err + b).slice(-8000); + }); + p.on("error", reject); + p.on("close", (code) => + code === 0 && size <= 8 * 1024 * 1024 + ? resolve( + binary + ? Buffer.concat(chunks) + : Buffer.concat(chunks).toString("utf8"), + ) + : reject(Error(err || `Command failed (${code}); output limit 8 MiB`)), + ); + }); +} +export class Engine { + constructor(store, { state, repo, providers, capacity = 3, demo = false }) { + Object.assign(this, { store, state, repo, providers, capacity, demo }); + this.active = new Map(); + this.paused = true; + this.ticking = false; + store.recover(); + } + async tick() { + if (this.paused || this.ticking) return; + this.ticking = true; + try { + const tasks = this.store.summaries().reverse(); + const statuses = new Map(tasks.map((t) => [t.id, t.status])); + for (const t of tasks) { + if (this.active.size >= this.capacity) break; + const p = this.providers.find((p) => p.id === t.provider); + if ( + t.status !== "queued" || + !p || + !p.enabled || + !["ready", "simulation"].some((x) => readiness(p).startsWith(x)) + ) + continue; + if (t.deps.some((id) => statuses.get(id) !== "accepted")) continue; + if ( + [...this.active.values()].filter((a) => a.provider === p.id).length >= + p.limit + ) + continue; + const claimed = this.store.change( + t.id, + t.revision, + (x) => { + x.status = "running"; + x.attempt++; + x.note = "Starting isolated attempt"; + x.receipt = null; + }, + "started", + ); + const a = { + provider: p.id, + attempt: claimed.attempt, + abort: new AbortController(), + process: null, + stopped: false, + }; + this.active.set(t.id, a); + this.run(claimed, structuredClone(p), a) + .catch((e) => this.finish(t.id, a, "failed", String(e.message))) + .finally(() => this.active.delete(t.id)); + } + } finally { + this.ticking = false; + } + } + finish(id, a, status, note, receipt = null) { + const t = this.store.get(id); + if (t.attempt !== a.attempt || t.status !== "running" || a.stopped) return; + this.store.change( + id, + t.revision, + (x) => { + x.status = status; + x.note = note; + x.receipt = receipt; + }, + status, + ); + } + stop(id) { + const t = this.store.get(id), + a = this.active.get(id); + if (t.status === "queued") + return this.store.change(id, t.revision, (x) => { + x.status = "canceled"; + x.note = "Canceled before dispatch"; + }); + if (!a || !["running", "stopping"].includes(t.status)) + throw Error("Task is not running"); + if (t.status === "stopping") return t; + a.stopped = true; + a.abort.abort(); + this.kill(a, "SIGTERM"); + const timer = setTimeout(() => this.kill(a, "SIGKILL"), 1500); + timer.unref(); + return this.store.change( + id, + t.revision, + (x) => { + x.status = "stopping"; + x.note = + "Stop requested; waiting for local adapter to settle. Remote effects may already exist."; + }, + "stop-requested", + ); + } + kill(a, signal) { + if (a.process?.pid) + try { + process.kill(-a.process.pid, signal); + } catch {} + } + async run(t, p, a) { + let timer; + const directory = path.join(this.state, "runs", t.id, String(a.attempt)); + try { + await mkdir(directory, { recursive: true, mode: 0o700 }); + const workspace = path.join(directory, "workspace"); + let base = null; + if (p.kind === "command") { + if (!this.repo) + throw Error( + "Start the desk with --repo /path/to/repository for coding tasks", + ); + base = ( + await command(["git", "rev-parse", "HEAD"], this.repo, a.abort.signal) + ).trim(); + // Separate object/index/config storage avoids competing writes to a shared working tree. + await command( + [ + "git", + "clone", + "--no-hardlinks", + "--no-local", + "--no-checkout", + "--", + this.repo, + workspace, + ], + directory, + a.abort.signal, + ); + await command( + ["git", "checkout", "--detach", base], + workspace, + a.abort.signal, + ); + await command( + ["git", "remote", "remove", "origin"], + workspace, + a.abort.signal, + ); + } + const dependencies = t.deps.map((id) => { + const d = this.store.get(id); + return { id: d.id, title: d.title, receipt: d.receipt }; + }); + const planInstruction = `Propose a bounded work plan as JSON {"tasks":[{"title":"...","prompt":"goal and acceptance criteria","provider":"provider-id","dependsOn":[]}]}. Maximum 12 tasks. dependsOn contains zero-based indices of earlier tasks. Available provider IDs: ${this.providers.map((p) => p.id).join(", ")}. Do not launch other agents or change task authority. The operator reviews and imports your plan.\n`; + const prompt = `Task: ${t.title}\nRole: ${t.role}\n${t.role === "queen" ? planInstruction : ""}${t.prompt}\n\nAccepted dependency receipts (source changes are not automatically integrated):\n${JSON.stringify(dependencies)}\n\nWork only in this isolated checkout. Follow its AGENTS.md. Do not push, deploy, publish, or alter other workspaces. Report checks actually run and remaining uncertainty. The operator reviews the result.`; + const started = this.store.get(t.id); + if (a.stopped) return; + this.store.change(t.id, started.revision, (x) => { + x.workspace = p.kind === "command" ? workspace : null; + x.note = "Adapter running"; + x.base = base; + }); + timer = setTimeout(() => { + a.timedOut = true; + a.abort.abort(); + this.kill(a, "SIGTERM"); + setTimeout(() => this.kill(a, "SIGKILL"), 1500).unref(); + }, p.timeoutSeconds * 1000); + let output = ""; + const emit = (text) => { + output = (output + text).slice(-200000); + this.store.event(t.id, "output", text); + }; + if (p.kind === "demo") { + for (const text of [ + "SIMULATION: reading the task contract.\n", + "SIMULATION: proposing isolated work and verification.\n", + "SIMULATION: result ready for operator review. No model or repository was changed.\n", + ]) { + await new Promise((resolve, reject) => { + const handle = setTimeout(resolve, 400); + a.abort.signal.addEventListener( + "abort", + () => { + clearTimeout(handle); + reject(Error("Stopped")); + }, + { once: true }, + ); + }); + emit(text); + } + } else if (p.kind === "chat") { + const key = p.keyEnv ? process.env[p.keyEnv] : null; + const response = await fetch(p.endpoint, { + method: "POST", + redirect: "error", + signal: a.abort.signal, + headers: { + "Content-Type": "application/json", + ...(key ? { Authorization: `Bearer ${key}` } : {}), + }, + body: JSON.stringify({ + model: p.model, + messages: [{ role: "user", content: prompt }], + stream: false, + max_tokens: 4096, + }), + }); + if (!response.ok) + throw Error( + `Provider HTTP ${response.status}; check login, quota and endpoint`, + ); + let body = "", + bytes = 0; + const decoder = new TextDecoder(); + for await (const chunk of response.body) { + bytes += chunk.length; + if (bytes > 2 * 1024 * 1024) { + a.abort.abort(); + throw Error("Provider response exceeds 2 MiB"); + } + body += decoder.decode(chunk, { stream: true }); + } + body += decoder.decode(); + const text = JSON.parse(body).choices?.[0]?.message?.content; + if (typeof text !== "string") + throw Error("Expected chat-completions text response"); + emit(text); + } else { + await new Promise((resolve, reject) => { + const argv = p.command.map((s) => s.replaceAll("{prompt}", prompt)); + const child = spawn(argv[0], argv.slice(1), { + cwd: workspace, + detached: true, + stdio: ["pipe", "pipe", "pipe"], + env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }, + }); + a.process = child; + child.stdout.setEncoding("utf8"); + child.stderr.setEncoding("utf8"); + let bytes = 0; + const onData = (b) => { + bytes += Buffer.byteLength(b); + if (bytes > 2 * 1024 * 1024) { + this.kill(a, "SIGKILL"); + return; + } + emit(b.toString()); + }; + child.stdout.on("data", onData); + child.stderr.on("data", onData); + child.on("error", reject); + child.on("close", (code) => { + this.kill(a, "SIGKILL"); + code === 0 && bytes <= 2 * 1024 * 1024 + ? resolve() + : reject( + Error( + bytes > 2 * 1024 * 1024 + ? "Output limit exceeded" + : `Adapter exited ${code}; inspect output for permissions, login or quota`, + ), + ); + }); + child.stdin.on("error", () => {}); + child.stdin.end( + p.command.some((s) => s.includes("{prompt}")) ? "" : prompt, + ); + if (a.stopped || a.abort.signal.aborted) this.kill(a, "SIGTERM"); + }); + } + if (a.timedOut) throw Error("Adapter deadline exceeded"); + if (a.stopped) return; + let diff = "", + head = base; + if (p.kind === "command") { + await command( + ["git", "add", "-N", "--", "."], + workspace, + a.abort.signal, + ); + diff = await command( + ["git", "diff", "--binary", base, "--"], + workspace, + a.abort.signal, + true, + ); + head = ( + await command(["git", "rev-parse", "HEAD"], workspace, a.abort.signal) + ).trim(); + } + await writeFile(path.join(directory, "result.txt"), output, { + mode: 0o600, + }); + await writeFile(path.join(directory, "changes.patch"), diff, { + mode: 0o600, + }); + const receipt = { + attempt: a.attempt, + base, + head, + outputSha256: hash(output), + patchSha256: hash(diff), + directory, + simulation: p.kind === "demo", + advisory: p.kind === "chat", + finished: new Date().toISOString(), + }; + await writeFile( + path.join(directory, "receipt.json"), + JSON.stringify(receipt, null, 2), + { mode: 0o600 }, + ); + this.finish( + t.id, + a, + "review", + "Adapter finished. Inspect output and patch; exit success is not verification.", + receipt, + ); + } catch (e) { + this.finish( + t.id, + a, + "failed", + a.timedOut ? "Adapter deadline exceeded" : e.message, + ); + } finally { + clearTimeout(timer); + if (a.stopped) { + const x = this.store.get(t.id); + if (x.status === "stopping") + this.store.change( + t.id, + x.revision, + (v) => { + v.status = "canceled"; + v.note = + "Local adapter settled. Inspect workspace and remote effects before retry."; + }, + "stopped", + ); + } + } + } + async receipt(id) { + const t = this.store.get(id); + if (!t.receipt) throw Error("No completed receipt"); + const output = await readFile( + path.join(t.receipt.directory, "result.txt"), + "utf8", + ), + patch = await readFile(path.join(t.receipt.directory, "changes.patch")); + if ( + hash(output) !== t.receipt.outputSha256 || + hash(patch) !== t.receipt.patchSha256 + ) + throw Error("Receipt artifact hash mismatch"); + return { receipt: t.receipt, output, patch: patch.toString("utf8") }; + } + async shutdown() { + this.paused = true; + for (const id of this.active.keys()) + try { + this.stop(id); + } catch {} + while (this.active.size) await new Promise((r) => setTimeout(r, 50)); + } +} diff --git a/control-desk/package-lock.json b/control-desk/package-lock.json new file mode 100644 index 0000000..8b6ab2f --- /dev/null +++ b/control-desk/package-lock.json @@ -0,0 +1,548 @@ +{ + "name": "omega-control-desk", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "omega-control-desk", + "version": "0.1.0", + "devDependencies": { + "jsdom": "26.1.0" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@asamuzakjp/css-color": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", + "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.3", + "@csstools/css-color-parser": "^3.0.9", + "@csstools/css-parser-algorithms": "^3.0.4", + "@csstools/css-tokenizer": "^3.0.3", + "lru-cache": "^10.4.3" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/cssstyle": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", + "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^3.2.0", + "rrweb-cssom": "^0.8.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/data-urls": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", + "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", + "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", + "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-encoding": "^3.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "26.1.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", + "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssstyle": "^4.2.1", + "data-urls": "^5.0.0", + "decimal.js": "^10.5.0", + "html-encoding-sniffer": "^4.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "nwsapi": "^2.2.16", + "parse5": "^7.2.1", + "rrweb-cssom": "^0.8.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^5.1.1", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^3.1.1", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^14.1.1", + "ws": "^8.18.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nwsapi": { + "version": "2.2.28", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", + "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", + "dev": true, + "license": "MIT" + }, + "node_modules/parse5": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", + "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^6.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/rrweb-cssom": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", + "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tldts": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", + "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.86" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.86", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", + "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", + "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz", + "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "dev": true, + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "14.2.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz", + "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^5.1.0", + "webidl-conversions": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ws": { + "version": "8.22.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", + "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/control-desk/package.json b/control-desk/package.json new file mode 100644 index 0000000..7e0ff4f --- /dev/null +++ b/control-desk/package.json @@ -0,0 +1,17 @@ +{ + "name": "omega-control-desk", + "private": true, + "version": "0.1.0", + "type": "module", + "engines": { + "node": ">=24" + }, + "scripts": { + "start": "node server.mjs", + "test": "node --test test/*.test.mjs", + "test:ui": "node test/ui-smoke.cjs" + }, + "devDependencies": { + "jsdom": "26.1.0" + } +} diff --git a/control-desk/providers.mjs b/control-desk/providers.mjs new file mode 100644 index 0000000..e556905 --- /dev/null +++ b/control-desk/providers.mjs @@ -0,0 +1,139 @@ +import { accessSync, constants } from "node:fs"; +import path from "node:path"; + +export const defaults = [ + { + id: "omega", + name: "Omega", + kind: "chat", + endpoint: "http://127.0.0.1:18091/v1/chat/completions", + model: "", + note: "Local model · advisory text only", + }, + { + id: "claude", + name: "Claude", + kind: "command", + command: ["claude", "-p", "{prompt}"], + note: "Claude Code · existing CLI login", + }, + { + id: "openai", + name: "OpenAI", + kind: "command", + command: [ + "codex", + "exec", + "--json", + "--sandbox", + "workspace-write", + "{prompt}", + ], + note: "Codex · existing CLI login", + }, + { + id: "grok", + name: "Grok", + kind: "command", + command: ["grok", "-p", "{prompt}"], + note: "Grok Build · existing CLI login", + }, + { + id: "gemini", + name: "Gemini", + kind: "command", + command: ["gemini", "-p", "{prompt}"], + note: "Gemini CLI · existing CLI login", + }, + { + id: "antigravity", + name: "Antigravity", + kind: "command", + command: ["agy", "-p", "{prompt}"], + note: "Antigravity CLI · existing CLI login", + }, + { + id: "muse", + name: "Muse", + kind: "command", + command: [], + note: "Supply your Muse command adapter", + }, +].map((p) => ({ ...p, enabled: false, limit: 1, timeoutSeconds: 900 })); + +export function installed(binary) { + if (!binary) return false; + return ( + binary.includes("/") + ? [binary] + : (process.env.PATH || "") + .split(path.delimiter) + .map((d) => path.join(d, binary)) + ).some((p) => { + try { + accessSync(p, constants.X_OK); + return true; + } catch { + return false; + } + }); +} +export function validateProvider(p) { + if (!p || !/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) + throw Error("Invalid provider id"); + if (typeof p.name !== "string" || p.name.length > 60 || !p.name.trim()) + throw Error("Invalid provider name"); + if (!["command", "chat", "demo"].includes(p.kind)) + throw Error("Invalid provider kind"); + if (!Number.isInteger(p.limit) || p.limit < 1 || p.limit > 8) + throw Error("Provider limit must be 1–8"); + if ( + !Number.isInteger(p.timeoutSeconds) || + p.timeoutSeconds < 1 || + p.timeoutSeconds > 3600 + ) + throw Error("Timeout must be 1–3600 seconds"); + if ( + p.kind === "command" && + (!Array.isArray(p.command) || + p.command.length > 32 || + !p.command.every((a) => typeof a === "string" && a.length < 40000)) + ) + throw Error("Command must be an argv array"); + if (p.kind === "chat") { + const u = new URL(p.endpoint); + if (u.username || u.password || u.search || u.hash) + throw Error("Use keyEnv for credentials, not endpoint URLs"); + if ( + u.protocol !== "https:" && + !( + u.protocol === "http:" && + ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname) + ) + ) + throw Error("Use HTTPS or loopback HTTP"); + if (p.keyEnv && !/^[A-Z_][A-Z0-9_]*$/.test(p.keyEnv)) + throw Error("Invalid key environment variable"); + if ( + typeof p.model !== "string" || + p.model.length > 200 || + p.endpoint.length > 2000 + ) + throw Error("Invalid model or endpoint"); + } + return p; +} +export function readiness(p) { + if (!p.enabled) return "disabled"; + if (p.kind === "command") + return installed(p.command?.[0]) + ? "ready · login unverified" + : "needs CLI / configuration"; + if (p.kind === "chat") + return !p.model + ? "needs model" + : p.keyEnv && !process.env[p.keyEnv] + ? "needs key environment" + : "ready · endpoint unverified"; + return "simulation"; +} diff --git a/control-desk/public/app.js b/control-desk/public/app.js new file mode 100644 index 0000000..380d758 --- /dev/null +++ b/control-desk/public/app.js @@ -0,0 +1,345 @@ +const $ = (s) => document.querySelector(s), + esc = (s) => + String(s ?? "").replace( + /[&<>"']/g, + (c) => + ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + })[c], + ); +let token = location.hash.slice(1) || sessionStorage.getItem("omega-token"); +if (token) sessionStorage.setItem("omega-token", token); +history.replaceState(null, "", location.pathname); +let state, + selected, + detail, + filter = "all", + cursor = 0, + events = [], + receipt = null, + receiptKey = "", + busy = false, + online = false; +async function api(route, data) { + const r = await fetch("/api/" + route, { + method: data ? "POST" : "GET", + headers: { + "X-Omega-Token": token || "", + "Content-Type": "application/json", + }, + ...(data ? { body: JSON.stringify(data) } : {}), + }); + const result = await r.json(); + if (!r.ok) throw Error(result.error || `HTTP ${r.status}`); + return result; +} +function notice(text) { + $("#notice").hidden = !text; + $("#notice").textContent = text || ""; + document.querySelectorAll(".dialog-error").forEach((el) => el.remove()); + const dialog = document.querySelector("dialog[open]"); + if (text && dialog) { + const error = document.createElement("p"); + error.className = "dialog-error"; + error.setAttribute("role", "alert"); + error.textContent = text; + dialog.prepend(error); + } +} +async function act(fn) { + try { + await fn(); + notice(""); + await refresh(); + } catch (e) { + notice(e.message); + } +} +const label = (t) => { + if (t.status !== "queued") return t.status; + if ( + t.deps.some( + (id) => state.tasks.find((d) => d.id === id)?.status !== "accepted", + ) + ) + return "waiting"; + const p = state.providers.find((p) => p.id === t.provider); + if ( + !p?.enabled || + !["ready", "simulation"].some((s) => p.readiness.startsWith(s)) + ) + return "blocked"; + return "queued"; +}; +const reason = (t) => + label(t) === "blocked" + ? "Connection: " + + (state.providers.find((p) => p.id === t.provider)?.readiness || + "unavailable") + : label(t) === "waiting" + ? "Waiting for accepted dependency receipts" + : t.note || "Ready for an available worker slot"; +function render() { + $("#health").textContent = state.paused ? "Dispatch paused" : "Dispatch live"; + $("#health").className = state.paused ? "paused" : "live"; + $("#pause").textContent = state.paused ? "Resume dispatch" : "Pause dispatch"; + $("#mode").textContent = state.demo + ? "Simulation enabled · real routes stay opt-in" + : state.repo + ? "Repository connected" + : "No coding repository selected"; + $("#connection-count").textContent = + state.providers.filter((p) => p.enabled).length + + "/" + + state.providers.length; + $("#providers").innerHTML = state.providers + .map( + (p) => + `
${esc(p.name[0])}${esc(p.name)}${p.kind !== "demo" ? `` : ""}
${esc(p.readiness)}
${esc(p.kind === "chat" ? "Advisory text" : p.kind === "demo" ? "Simulation" : "CLI worker")}
`, + ) + .join(""); + $("#active").textContent = state.active; + $("#capacity").textContent = `of ${state.capacity} total worker slots`; + for (const key of ["queued", "review", "accepted"]) + $("#" + key).textContent = state.tasks.filter( + (t) => t.status === key, + ).length; + const tasks = state.tasks.filter( + (t) => + filter === "all" || + (filter === "blocked" && + ["failed", "interrupted", "canceled", "waiting", "blocked"].includes( + label(t), + )) || + t.status === filter, + ); + $("#tasks").innerHTML = tasks.length + ? tasks + .map( + (t) => + ``, + ) + .join("") + : `
⌘

${filter === "all" ? "Make your next move." : "No work in this view."}

${filter === "all" ? "Connect a worker, assign a concrete goal, and resume dispatch when you are ready." : ""}

`; + renderInspector(); + $("#events").innerHTML = + events + .slice(-100) + .reverse() + .map( + (e) => + `
${esc(e.kind)}${esc(e.text.slice(0, 240))}
`, + ) + .join("") || + '

Events appear here as you operate the hive.

'; +} +function renderInspector() { + const summary = state.tasks.find((t) => t.id === selected); + if (!summary) return; + const t = { + ...summary, + prompt: detail?.id === selected ? detail.prompt : "Loading instructions…", + }; + const running = ["running", "stopping"].includes(t.status), + retry = ["review", "failed", "canceled", "interrupted"].includes(t.status); + $("#inspector").innerHTML = + `

${esc(t.title)}

${esc(label(t))}

${esc(reason(t))}

YOUR INSTRUCTIONS

${esc(t.prompt)}
${ + t.deps.length + ? "

DEPENDENCIES

" + + t.deps + .map((id) => { + const d = state.tasks.find((x) => x.id === id); + return ``; + }) + .join("") + : "" + }
${running || t.status === "queued" ? '" : ""}${retry ? '' : ""}${!running && t.status !== "accepted" ? '' : ""}${t.receipt ? '' : ""}

ATTEMPT OUTPUT

${esc(
+      events
+        .filter((e) => e.task === t.id && e.kind === "output")
+        .slice(-20)
+        .map((e) => e.text)
+        .join("") || "No output received.",
+    )}
${receipt && receiptKey === t.id + ":" + t.attempt ? `

RECEIPT · ATTEMPT ${t.attempt}

${t.receipt?.simulation ? "Simulation. No model was invoked." : t.receipt?.advisory ? "Advisory text only. No code was executed." : "Isolated checkout result."}

Patch SHA-256${esc(receipt.receipt.patchSha256)}

RESULT

${esc(receipt.output)}

PATCH

${esc(receipt.patch || "(No tracked or untracked patch changes)")}
${t.status === "review" ? '

Acceptance records your review. It does not merge or deploy.

' : ""}
` : ""}`; +} +async function refresh() { + if (busy) return; + busy = true; + try { + state = await api("state"); + if (selected && state.tasks.some((t) => t.id === selected)) + detail = await api("task/" + selected); + const incoming = await api("events?after=" + cursor); + if (incoming.length) { + cursor = incoming.at(-1).seq; + events.push(...incoming); + events = events.slice(-500); + } + online = true; + render(); + } catch (e) { + online = false; + $("#health").textContent = "Disconnected"; + $("#health").className = "paused"; + notice(e.message); + } finally { + busy = false; + } +} +$("#providers").addEventListener("change", (e) => + act(async () => { + const id = e.target.dataset.provider || e.target.dataset.slots, + p = state.providers.find((p) => p.id === id); + if (p) + await api("providers", { + id, + enabled: e.target.dataset.provider ? e.target.checked : p.enabled, + limit: e.target.dataset.slots ? Number(e.target.value) : p.limit, + }); + }), +); +$("#pause").onclick = () => + act(() => api("control", { action: state.paused ? "resume" : "pause" })); +$("#stop-all").onclick = () => + act(() => api("control", { action: "stop-all" })); +$("#configure").onclick = () => $("#guide").showModal(); +document + .querySelectorAll("[data-close]") + .forEach((b) => (b.onclick = () => b.closest("dialog").close())); +$("#new-task").onclick = () => { + if (!state || !online) return; + $("#provider-select").innerHTML = state.providers + .map( + (p) => + ``, + ) + .join(""); + const ready = state.providers.find((p) => p.enabled); + if (ready) $("#provider-select").value = ready.id; + $("#dependency-select").innerHTML = state.tasks + .map( + (t) => + ``, + ) + .join(""); + $("#task-dialog").showModal(); +}; +$("#task-form").onsubmit = (e) => { + e.preventDefault(); + act(async () => { + const f = new FormData(e.target); + const task = await api("tasks", { + title: f.get("title"), + prompt: f.get("prompt"), + provider: f.get("provider"), + role: f.get("role"), + deps: f.getAll("deps"), + }); + selected = task.id; + e.target.reset(); + $("#task-dialog").close(); + }); +}; +document.addEventListener("click", (e) => { + const t = e.target.closest("[data-task]"); + if (t) { + selected = t.dataset.task; + receipt = null; + render(); + refresh(); + } + const f = e.target.closest("[data-filter]"); + if (f) { + filter = f.dataset.filter; + document + .querySelectorAll("[data-filter]") + .forEach((b) => b.classList.toggle("selected", b === f)); + render(); + } +}); +$("#inspector").addEventListener("click", (e) => { + const action = e.target.closest("[data-action]")?.dataset.action; + if (!action) return; + act(async () => { + const t = state.tasks.find((x) => x.id === selected), + data = { id: t.id, revision: t.revision, action }; + if (action === "receipt") { + receipt = await api("receipt/" + t.id); + receiptKey = t.id + ":" + t.attempt; + return; + } + if (action === "steer") { + data.text = prompt( + "Direction for the next dispatch (existing artifacts stay on disk):", + ); + if (!data.text) return; + } + if (action === "retry" && t.status === "interrupted") { + data.confirmOrphans = confirm( + "Have you inspected the old process and its workspace, and confirmed it can no longer make changes?", + ); + if (!data.confirmOrphans) return; + } + if (action === "accept") { + data.patchSha256 = receipt?.receipt.patchSha256; + data.outputSha256 = receipt?.receipt.outputSha256; + } + await api("task", data); + if (action === "retry") receipt = null; + }); +}); +await refresh(); +setInterval(refresh, 1200); + +$("#providers").addEventListener("click", (e) => { + const id = e.target.closest("[data-configure]")?.dataset.configure; + if (!id) return; + const p = state.providers.find((p) => p.id === id), + f = $("#connection-form"); + $("#connection-name").textContent = p.name; + for (const k of [ + "id", + "kind", + "endpoint", + "model", + "keyEnv", + "limit", + "timeoutSeconds", + ]) + f.elements[k].value = p[k] ?? ""; + f.elements.command.value = JSON.stringify(p.command || []); + $("#connection-dialog").showModal(); +}); +$("#connection-form").onsubmit = (e) => { + e.preventDefault(); + act(async () => { + const f = new FormData(e.target), + p = state.providers.find((p) => p.id === f.get("id")); + await api("providers", { + id: p.id, + enabled: p.enabled, + kind: f.get("kind"), + command: JSON.parse(f.get("command") || "[]"), + endpoint: f.get("endpoint"), + model: f.get("model"), + keyEnv: f.get("keyEnv"), + limit: Number(f.get("limit")), + timeoutSeconds: Number(f.get("timeoutSeconds")), + }); + $("#connection-dialog").close(); + }); +}; + +$("#import-plan").onclick = () => $("#plan-dialog").showModal(); +$("#plan-form").onsubmit = (e) => { + e.preventDefault(); + act(async () => { + const plan = JSON.parse(new FormData(e.target).get("plan")); + await api("plan", plan); + $("#plan-dialog").close(); + e.target.reset(); + }); +}; diff --git a/control-desk/public/index.html b/control-desk/public/index.html new file mode 100644 index 0000000..160d88f --- /dev/null +++ b/control-desk/public/index.html @@ -0,0 +1,275 @@ + + + + + + Omega · Hive control + + + + +
+
+
+
SOVEREIGN INTELLIGENCE / WORKSPACE
+

Your hive. Your direction.

+
+
+ Connecting +
+
+ +
+
+ 0bounded concurrency +
+
+ 0dependencies stay visible +
+
+ 0you accept the evidence +
+
+ 0merge remains a separate action +
+
+
+
+
+
+

Mission board

+

Assign a goal. Follow the work. Steer when it matters.

+
+
+ +
+
+
+ +
+
+
+
+
WORK INSPECTOR
+
+
+ ◎ +

Keep sight of every step.

+

+ Select a task to see its instructions, live output, + dependencies, and exact review artifacts. +

+
+
+
+
+
+
+

Activity stream

+ Local journal · latest 100 entries +
+
+
+
+ Operator-led hive + Explicit connections · isolated attempts · durable receipts +
+
+ +
+
GIVE THE HIVE DIRECTION
+

Assign a task

+ +
+ +
+ +
+ +
+
+
+ +
YOUR ACCOUNTS, YOUR CHOICE
+

Connect the tools you use

+

+ Install and sign in to the provider's official CLI on the machine + running this desk, then enable its connection. “Ready” checks the + executable; the first task checks actual login and quota. +

+

+ Claude → claude · OpenAI → codex · Grok → + grok · Gemini → gemini · Antigravity → + agy +

+

+ Use the gear beside a connection to configure Omega, Muse, custom + commands, and chat-compatible API routes. A + providers.json file can bootstrap a fresh state directory. + See control-desk/README.md. Credentials stay in official + CLI storage or server-side environment variables. +

+

+ Each service controls which subscription, region, and account can use + its tools. API billing and subscription access can differ. No silent + fallback switches your provider. +

+

+ Pause stops new dispatch. Stop active requests cancellation. To change a + running task: stop it, wait for it to settle, add steering, then + explicitly retry. Existing checkouts are retained. +

+ +
+ +
+
CONNECTION SETTINGS
+

+ +
+ +
+
+ +
+

+ Settings apply to future attempts. Existing workers retain their + original connection. Saving does not enable a disabled connection. +

+
+ +
+
+
+ +
+
QUEEN → OPERATOR → HIVE
+

Review and import a plan

+

+ Paste a queen's proposed JSON plan. Import queues its tasks atomically + and pauses new dispatch so you can inspect the assignments before + resuming. +

+ +

+ Dependencies refer to earlier task indices, starting at 0. Existing + active workers continue. Each accepted result releases its dependents; + code integration remains explicit. +

+
+ +
+
+
+ + + diff --git a/control-desk/public/style.css b/control-desk/public/style.css new file mode 100644 index 0000000..f001505 --- /dev/null +++ b/control-desk/public/style.css @@ -0,0 +1,743 @@ +:root { + color-scheme: dark; + --bg: #0c1117; + --panel: #111922; + --line: #25313c; + --text: #e1e8e9; + --muted: #93a4b1; + --mint: #98d6b9; + --gold: #dec589; + --red: #eb9d9d; + font: + 14px/1.5 Inter, + ui-sans-serif, + system-ui, + -apple-system, + BlinkMacSystemFont, + "Segoe UI", + sans-serif; +} +* { + box-sizing: border-box; +} +body { + margin: 0; + background: var(--bg); + color: var(--text); + display: flex; +} +button, +input, +textarea, +select { + font: inherit; +} +button { + color: var(--text); + border: 1px solid var(--line); + background: #18232d; + border-radius: 7px; + padding: 9px 13px; + cursor: pointer; + transition: background 0.15s; +} +button:hover { + background: #273746; +} +button:focus-visible, +input:focus-visible, +textarea:focus-visible, +select:focus-visible { + outline: 2px solid var(--mint); + outline-offset: 3px; +} +button.primary { + background: var(--mint); + color: #15281f; + border-color: var(--mint); + font-weight: 650; +} +button.danger { + color: var(--red); +} +aside { + width: 238px; + flex-shrink: 0; + min-height: 100vh; + background: #10171e; + border-right: 1px solid var(--line); + padding: 30px 20px; + position: sticky; + top: 0; + height: 100vh; + overflow: auto; +} +.brand { + display: flex; + align-items: center; + gap: 13px; + color: var(--mint); + text-decoration: none; + font-size: 44px; + line-height: 1; +} +.brand span { + font-size: 19px; + letter-spacing: 3px; + color: var(--text); +} +.brand small { + display: block; + font-size: 9px; + letter-spacing: 2px; + color: var(--muted); + margin-top: 10px; +} +.section-label { + margin: 36px 0 18px; + font-size: 10px; + letter-spacing: 1.5px; + color: var(--muted); + display: flex; + justify-content: space-between; +} +.provider { + padding: 13px 0; + border-bottom: 1px solid #202b35; +} +.provider-line { + display: flex; + align-items: center; + gap: 9px; +} +.provider strong { + font-size: 13px; +} +.avatar { + width: 28px; + height: 28px; + border: 1px solid var(--line); + border-radius: 8px; + display: grid; + place-items: center; + color: var(--muted); + font-size: 12px; +} +.enabled .avatar { + background: #19332d; + color: var(--mint); + border-color: #315447; +} +.provider small { + display: block; + color: var(--muted); + font-size: 10px; + margin: 6px 0; +} +.switch { + margin-left: auto; + position: relative; + width: 28px; + height: 16px; +} +.switch input { + width: 28px; + height: 16px; + margin: 0; + opacity: 0; + position: absolute; + z-index: 1; + cursor: pointer; +} +.switch span { + display: block; + background: #37434d; + border-radius: 12px; + height: 16px; +} +.switch span:after { + content: ""; + position: absolute; + top: 3px; + left: 3px; + width: 10px; + height: 10px; + background: #cad6d9; + border-radius: 100%; + transition: left 0.2s; +} +.switch input:checked + span { + background: #447d66; +} +.switch input:checked + span:after { + left: 15px; +} +.switch input:focus-visible + span { + outline: 2px solid var(--mint); +} +.slots { + display: flex; + justify-content: space-between; + font-size: 10px; + color: var(--muted); +} +select { + background: #14202a; + color: var(--text); + border: 1px solid var(--line); + border-radius: 4px; +} +.slots select { + font-size: 10px; +} +.aside-bottom { + margin-top: 30px; + font-size: 11px; + color: var(--muted); +} +.aside-bottom small { + font-size: 10px; +} +.aside-bottom p { + font-size: 13px; + margin-top: 25px; +} +.aside-bottom button { + font-size: 11px; +} +.orb { + display: inline-block; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--mint); + margin-right: 5px; +} +main { + padding: 32px 36px; + flex: 1; + min-width: 0; + max-width: 1800px; +} +header { + display: flex; + gap: 20px; + align-items: center; + justify-content: space-between; +} +.eyebrow { + font-size: 10px; + letter-spacing: 1.5px; + color: var(--mint); + font-weight: 600; +} +h1 { + font-size: 28px; + letter-spacing: -0.7px; + font-weight: 500; + margin: 8px 0 0; +} +h2 { + font-size: 17px; + font-weight: 550; + margin: 0; +} +h3 { + font-size: 15px; + font-weight: 550; + margin: 12px 0 6px; +} +.header-actions { + display: flex; + gap: 9px; + align-items: center; + font-size: 12px; +} +.header-actions button { + font-size: 12px; +} +#health { + font-size: 11px; + margin-right: 4px; +} +#health.paused { + color: var(--gold); +} +#health.live { + color: var(--mint); +} +#notice { + background: #352728; + border: 1px solid #714648; + border-radius: 8px; + color: #f5c8c8; + padding: 12px; + margin-top: 20px; +} +.metrics { + display: grid; + grid-template-columns: repeat(4, 1fr); + margin: 32px 0; + gap: 14px; +} +.metrics > div { + border: 1px solid var(--line); + border-radius: 9px; + padding: 17px 21px; + background: linear-gradient(130deg, #17222c, #111a22); +} +.metrics label { + display: block; + font-size: 10px; + color: var(--muted); + letter-spacing: 1.2px; +} +.metrics strong { + display: block; + font-size: 34px; + font-weight: 450; + margin: 6px 0; + color: var(--mint); +} +.metrics small { + font-size: 10px; + color: var(--muted); +} +.workspace { + display: grid; + grid-template-columns: minmax(0, 1.25fr) minmax(300px, 1fr); + border: 1px solid var(--line); + border-radius: 10px; + overflow: hidden; + min-height: 480px; +} +.board { + padding: 24px; +} +.board-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; +} +.board-header p { + font-size: 11px; + color: var(--muted); + margin: 5px 0; +} +.board-header button { + font-size: 12px; + white-space: nowrap; +} +.filters { + display: flex; + gap: 8px; + margin: 23px 0 18px; + flex-wrap: wrap; +} +.filters button { + font-size: 11px; + border-color: transparent; + background: transparent; + color: var(--muted); + padding: 5px 9px; +} +.filters button.selected { + color: var(--mint); + background: #19302a; + border: 1px solid #335346; +} +#tasks { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(235px, 1fr)); + gap: 12px; + align-items: start; + max-height: 680px; + overflow: auto; +} +.task { + text-align: left; + padding: 16px; + background: #121d26; + border: 1px solid #293843; + border-radius: 8px; + min-height: 157px; +} +.task.chosen { + border-color: var(--mint); + background: #172a2b; +} +.task-top { + display: flex; + justify-content: space-between; + align-items: center; + gap: 5px; +} +.task-top small, +.task-bottom { + font-size: 10px; + color: var(--muted); +} +.task p { + font-size: 11px; + color: var(--muted); + line-height: 1.5; + margin: 6px 0 18px; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} +.task-bottom { + display: flex; + justify-content: space-between; + gap: 5px; + border-top: 1px solid var(--line); + padding-top: 10px; +} +.badge { + font-size: 9px; + text-transform: uppercase; + letter-spacing: 0.8px; + background: #263543; + color: #b7c9d9; + padding: 3px 6px; + border-radius: 4px; + display: inline-block; +} +.badge.running, +.badge.accepted { + background: #204535; + color: #a8e0bf; +} +.badge.review, +.badge.waiting { + background: #463e29; + color: var(--gold); +} +.badge.failed, +.badge.interrupted, +.badge.canceled, +.badge.stopping { + background: #422d35; + color: var(--red); +} +.inspector { + padding: 25px; + background: #101923; + border-left: 1px solid var(--line); + min-width: 0; + max-height: 820px; + overflow: auto; +} +.inspector h2 { + margin: 18px 0 10px; +} +.inspector-note { + font-size: 12px; + color: var(--muted); +} +h4 { + font-size: 10px; + letter-spacing: 1.1px; + color: var(--muted); + font-weight: 500; + margin: 24px 0 10px; +} +.empty { + padding: 60px 12px; + text-align: center; + color: var(--muted); + grid-column: 1/-1; +} +.empty h2 { + color: var(--text); + margin: 20px 0 8px; +} +.empty p { + font-size: 12px; + max-width: 280px; + margin: auto; + line-height: 1.7; +} +.large-symbol { + font-size: 42px; + color: #669b89; + font-weight: 300; +} +pre { + white-space: pre-wrap; + overflow-wrap: anywhere; + font: + 11px/1.7 ui-monospace, + SFMono-Regular, + Menlo, + monospace; + background: #0a1219; + padding: 14px; + border: 1px solid #22313b; + border-radius: 6px; + max-height: 320px; + overflow: auto; +} +.prompt { + background: transparent; + border: 0; + padding: 0; + color: #b7c6ce; + max-height: 160px; +} +.actions { + display: flex; + gap: 8px; + flex-wrap: wrap; + margin-top: 18px; +} +.actions button { + font-size: 11px; +} +.dependency { + display: block; + font-size: 11px; + margin: 4px 0; +} +.receipt code { + display: block; + overflow-wrap: anywhere; + font-size: 10px; + color: var(--mint); +} +.receipt p { + font-size: 12px; +} +.receipt small { + font-size: 10px; + color: var(--muted); +} +.muted { + color: var(--muted); + font-size: 11px; +} +.activity { + margin-top: 25px; + border: 1px solid var(--line); + border-radius: 9px; + padding: 20px 24px; +} +.activity .board-header { + margin-bottom: 15px; +} +.activity .board-header span { + font-size: 10px; + color: var(--muted); +} +#events { + max-height: 200px; + overflow: auto; +} +.event { + display: grid; + grid-template-columns: 85px 90px 1fr; + gap: 10px; + border-top: 1px solid #202c36; + padding: 9px 0; + font-size: 11px; +} +.event time { + color: var(--muted); +} +.event-kind { + color: var(--mint); +} +.event > span:last-child { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: #afbec7; +} +footer { + font-size: 10px; + display: flex; + justify-content: space-between; + color: var(--muted); + padding-top: 24px; +} +dialog { + max-width: 600px; + width: calc(100vw - 32px); + background: #14202a; + border: 1px solid #354a58; + border-radius: 12px; + color: var(--text); + padding: 30px; + box-shadow: 0 20px 90px #0008; +} +dialog::backdrop { + background: #02080cc4; + backdrop-filter: blur(4px); +} +dialog h2 { + margin: 10px 0 20px; +} +dialog p { + font-size: 13px; + color: #b6c6ce; +} +form > label, +.form-row label { + display: flex; + flex-direction: column; + gap: 8px; + font-size: 12px; + margin: 17px 0; +} +input, +textarea, +form select { + background: #0c151e; + border: 1px solid #364957; + border-radius: 6px; + color: var(--text); + padding: 10px; + min-width: 0; + width: 100%; +} +textarea { + resize: vertical; +} +.form-row { + display: flex; + gap: 15px; +} +.form-row label { + flex: 1; + margin: 0; +} +form small { + color: var(--muted); + font-size: 10px; +} +.dialog-actions { + display: flex; + justify-content: flex-end; + gap: 10px; + margin-top: 20px; +} +#dependency-select { + max-height: 90px; +} +@media (max-width: 1200px) { + main { + padding: 24px; + } + header { + align-items: start; + flex-direction: column; + } + .workspace { + grid-template-columns: 1fr 1fr; + } + aside { + width: 210px; + padding: 24px 15px; + } + .metrics { + gap: 8px; + } + .metrics > div { + padding: 14px; + } + .metrics small { + font-size: 9px; + } +} +@media (max-width: 860px) { + body { + display: block; + } + aside { + position: static; + width: 100%; + height: auto; + min-height: 0; + padding: 18px; + border-right: 0; + } + .brand { + font-size: 32px; + } + .section-label { + margin: 20px 0 8px; + } + #providers { + display: flex; + gap: 15px; + overflow: auto; + } + .provider { + min-width: 175px; + } + .aside-bottom { + display: none; + } + main { + padding: 20px; + } + .workspace { + grid-template-columns: 1fr; + } + .inspector { + border-left: 0; + border-top: 1px solid var(--line); + max-height: none; + } + .metrics { + margin: 20px 0; + grid-template-columns: repeat(2, 1fr); + } + h1 { + font-size: 25px; + } + .event { + grid-template-columns: 70px 65px 1fr; + font-size: 10px; + } + footer span { + display: none; + } + .header-actions { + flex-wrap: wrap; + } + .board { + padding: 18px; + } + .board-header { + align-items: start; + } + .board-header p { + max-width: 200px; + } +} + +.connection-edit { + padding: 0 4px; + border: 0; + background: transparent; + color: var(--muted); + font-size: 12px; +} + +.board-buttons { + display: flex; + flex-wrap: wrap; + gap: 7px; + justify-content: flex-end; +} + +.badge.blocked { + background: #463e29; + color: var(--gold); +} +.dialog-error { + color: var(--red); +} diff --git a/control-desk/server.mjs b/control-desk/server.mjs new file mode 100644 index 0000000..2405b19 --- /dev/null +++ b/control-desk/server.mjs @@ -0,0 +1,352 @@ +import http from "node:http"; +import { readFile, writeFile, mkdir, unlink, realpath } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { randomBytes } from "node:crypto"; +import { Store } from "./store.mjs"; +import { Engine } from "./engine.mjs"; +import { defaults, readiness, validateProvider } from "./providers.mjs"; + +const root = path.dirname(fileURLToPath(import.meta.url)); +export async function start({ + state = path.join(root, ".state"), + repo = null, + port = 8787, + demo = false, + capacity = 3, +} = {}) { + if (!Number.isInteger(capacity) || capacity < 1 || capacity > 16) + throw Error("Capacity must be 1–16"); + state = path.resolve(state); + if (repo) repo = await realpath(repo); + await mkdir(state, { recursive: true, mode: 0o700 }); + const lock = path.join(state, "controller.lock"); + try { + await writeFile(lock, String(process.pid), { flag: "wx", mode: 0o600 }); + } catch (e) { + throw Error( + `State is already locked. Stop its controller first. After a crash, inspect old child processes and remove ${lock} before recovery.`, + ); + } + let store, server, timer; + try { + store = new Store(path.join(state, "desk.sqlite")); + let providers = store.setting("providers") || structuredClone(defaults); + const config = path.join(state, "providers.json"); + if (!store.setting("providers")) + try { + providers = JSON.parse(await readFile(config, "utf8")); + } catch (e) { + if (e.code !== "ENOENT") throw e; + } + if (!Array.isArray(providers) || providers.length > 32) + throw Error("Expected at most 32 providers"); + if (demo) + providers = [ + { + id: "demo", + name: "Simulation", + kind: "demo", + enabled: true, + limit: 3, + timeoutSeconds: 30, + note: "Simulated worker · no provider usage", + }, + ...providers.filter((p) => p.id !== "demo"), + ]; + else if (providers.some((p) => p.kind === "demo")) + throw Error("Demo providers require --demo"); + providers.forEach(validateProvider); + if (new Set(providers.map((p) => p.id)).size !== providers.length) + throw Error("Duplicate provider ids"); + const engine = new Engine(store, { + state, + repo, + providers, + capacity, + demo, + }); + const token = randomBytes(32).toString("hex"); + const send = (res, status, body) => { + res.writeHead(status, { + "Content-Type": "application/json", + "Cache-Control": "no-store", + }); + res.end(JSON.stringify(body)); + }; + server = http.createServer(async (req, res) => { + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Referrer-Policy", "no-referrer"); + res.setHeader( + "Content-Security-Policy", + "default-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", + ); + const origin = `http://127.0.0.1:${server.address().port}`; + try { + if ( + req.headers.host !== new URL(origin).host || + (req.headers.origin && req.headers.origin !== origin) + ) + return send(res, 403, { + error: "Open the exact loopback URL printed by the server", + }); + const url = new URL(req.url, origin); + if (!url.pathname.startsWith("/api/")) { + const files = { + "/": ["index.html", "text/html"], + "/app.js": ["app.js", "text/javascript"], + "/style.css": ["style.css", "text/css"], + }; + const file = files[url.pathname]; + if (req.method !== "GET" || !file) + return send(res, 404, { error: "Not found" }); + res.writeHead(200, { + "Content-Type": file[1], + "Cache-Control": "no-store", + }); + return res.end(await readFile(path.join(root, "public", file[0]))); + } + if (req.headers["x-omega-token"] !== token) + return send(res, 401, { + error: "Open the startup URL with its access token", + }); + if (req.method === "GET") { + if (url.pathname === "/api/state") + return send(res, 200, { + paused: engine.paused, + demo, + repo, + capacity, + active: engine.active.size, + providers: providers.map((p) => ({ + ...p, + readiness: readiness(p), + })), + tasks: store.summaries(), + }); + const taskMatch = url.pathname.match(/^\/api\/task\/([a-f0-9-]+)$/); + if (taskMatch) return send(res, 200, store.get(taskMatch[1])); + if (url.pathname === "/api/events") { + const after = Number(url.searchParams.get("after") || 0); + if (!Number.isSafeInteger(after) || after < 0) + throw Error("Invalid cursor"); + return send( + res, + 200, + store.events(after, url.searchParams.get("task")), + ); + } + const match = url.pathname.match(/^\/api\/receipt\/([a-f0-9-]+)$/); + if (match) return send(res, 200, await engine.receipt(match[1])); + return send(res, 404, { error: "Not found" }); + } + if (req.method !== "POST") return send(res, 405, { error: "Use POST" }); + if (!req.headers["content-type"]?.startsWith("application/json")) + return send(res, 415, { error: "Use application/json" }); + let body = "", + size = 0; + for await (const chunk of req) { + size += chunk.length; + if (size > 65536) { + send(res, 413, { error: "Request too large" }); + return; + } + body += chunk; + } + const input = JSON.parse(body || "{}"); + if (url.pathname === "/api/control") { + if (!["pause", "resume", "stop-all"].includes(input.action)) + throw Error("Unknown control"); + engine.paused = input.action !== "resume"; + if (input.action === "stop-all") + for (const id of engine.active.keys()) engine.stop(id); + store.event(null, "control", input.action); + return send(res, 200, { paused: engine.paused }); + } + if (url.pathname === "/api/providers") { + const p = providers.find((p) => p.id === input.id); + if (!p) throw Error("Unknown provider"); + if (typeof input.enabled !== "boolean") + throw Error("enabled must be boolean"); + const changes = {}; + for (const k of [ + "kind", + "command", + "endpoint", + "model", + "keyEnv", + "timeoutSeconds", + ]) + if (input[k] !== undefined) changes[k] = input[k]; + if ((changes.kind === "demo" || p.kind === "demo") && !demo) + throw Error("Simulation requires demo mode"); + const updated = validateProvider({ + ...p, + ...changes, + enabled: input.enabled, + limit: Number(input.limit), + }); + Object.assign(p, updated); + store.setting( + "providers", + providers.filter((p) => p.kind !== "demo"), + ); + store.event( + null, + "provider", + `${p.name}: ${p.enabled ? "enabled" : "disabled"}, slots ${p.limit}`, + ); + return send(res, 200, { ok: true }); + } + if (url.pathname === "/api/tasks") { + if (!providers.some((p) => p.id === input.provider)) + throw Error("Unknown provider"); + return send(res, 201, store.create(input)); + } + if (url.pathname === "/api/plan") { + if ( + !Array.isArray(input.tasks) || + input.tasks.length < 1 || + input.tasks.length > 12 + ) + throw Error("Plan must have 1–12 tasks"); + if ( + input.tasks.some((t) => !providers.some((p) => p.id === t.provider)) + ) + throw Error("Plan references an unknown provider"); + // Import is an explicit operator action. Pause dispatch for inspection before resuming. + const tasks = store.plan(input.tasks); + engine.paused = true; + store.event( + null, + "plan-imported", + `${tasks.length} tasks queued; dispatch paused for inspection`, + ); + return send(res, 201, tasks); + } + if (url.pathname === "/api/task") { + const t = store.get(input.id); + if (t.revision !== input.revision) + throw Error("Stale revision: refresh before acting"); + if (input.action === "stop") return send(res, 200, engine.stop(t.id)); + if (input.action === "accept") await engine.receipt(t.id); + const changed = store.change( + t.id, + t.revision, + (x) => { + if (input.action === "accept") { + if (x.status !== "review" || !x.receipt) + throw Error( + "Only a completed, reviewed receipt can be accepted", + ); + if ( + input.patchSha256 !== x.receipt.patchSha256 || + input.outputSha256 !== x.receipt.outputSha256 + ) + throw Error("Review the current receipt before accepting"); + x.status = "accepted"; + x.note = + "Operator accepted this receipt. Nothing merged or deployed."; + } else if (input.action === "retry") { + if ( + !["failed", "canceled", "interrupted", "review"].includes( + x.status, + ) || + engine.active.has(x.id) + ) + throw Error("Wait for the previous attempt to settle"); + if (x.status === "interrupted" && input.confirmOrphans !== true) + throw Error( + "Inspect old processes and acknowledge recovery before retrying", + ); + x.status = "queued"; + x.note = + "Explicit retry in a new checkout; previous artifacts remain on disk"; + x.receipt = null; + } else if (input.action === "steer") { + if ( + ![ + "queued", + "failed", + "canceled", + "interrupted", + "review", + ].includes(x.status) + ) + throw Error( + "Stop the running attempt before steering its successor", + ); + const note = String(input.text || "").trim(); + if ( + !note || + note.length > 4000 || + x.prompt.length + note.length > 32000 + ) + throw Error("Steering text missing or too long"); + x.prompt += `\n\nOperator steering:\n${note}`; + x.note = + "Steering saved for next dispatch; not applied to a running attempt"; + } else throw Error("Unknown action"); + }, + input.action, + ); + return send(res, 200, changed); + } + send(res, 404, { error: "Not found" }); + } catch (e) { + send(res, 400, { error: e.message }); + } + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(port, "127.0.0.1", resolve); + }); + timer = setInterval( + () => engine.tick().catch((e) => store.event(null, "error", e.message)), + 250, + ); + timer.unref(); + return { + server, + engine, + store, + token, + url: `http://127.0.0.1:${server.address().port}/#${token}`, + async close() { + clearInterval(timer); + await engine.shutdown(); + await new Promise((r) => server.close(r)); + store.close(); + await unlink(lock); + }, + }; + } catch (e) { + clearInterval(timer); + server?.close(); + store?.close(); + await unlink(lock); + throw e; + } +} +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const args = process.argv.slice(2), + get = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined); + const desk = await start({ + state: get("--state"), + repo: get("--repo"), + port: Number(get("--port") || 8787), + capacity: Number(get("--capacity") || 3), + demo: args.includes("--demo"), + }); + console.log( + `Omega control desk (paused on startup)\n${desk.url}\nKeep this local access URL private.`, + ); + let closing = false; + for (const signal of ["SIGINT", "SIGTERM"]) + process.on(signal, async () => { + if (closing) return; + closing = true; + await desk.close(); + process.exit(0); + }); +} diff --git a/control-desk/store.mjs b/control-desk/store.mjs new file mode 100644 index 0000000..07aca4f --- /dev/null +++ b/control-desk/store.mjs @@ -0,0 +1,165 @@ +import { DatabaseSync } from "node:sqlite"; +import { randomUUID } from "node:crypto"; + +export class Store { + constructor(file) { + this.db = new DatabaseSync(file); + this.db + .exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; + CREATE TABLE IF NOT EXISTS tasks(id TEXT PRIMARY KEY, body TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS events(seq INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, task TEXT, kind TEXT NOT NULL, text TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT NOT NULL);`); + } + transaction(fn) { + this.db.exec("BEGIN IMMEDIATE"); + try { + const result = fn(); + this.db.exec("COMMIT"); + return result; + } catch (e) { + this.db.exec("ROLLBACK"); + throw e; + } + } + event(task, kind, text) { + this.db + .prepare("INSERT INTO events(at,task,kind,text) VALUES(?,?,?,?)") + .run(new Date().toISOString(), task, kind, String(text).slice(0, 8192)); + } + all() { + return this.db + .prepare("SELECT body FROM tasks ORDER BY rowid DESC") + .all() + .map((r) => JSON.parse(r.body)); + } + summaries() { + return this.db + .prepare( + "SELECT json_remove(body, '$.prompt') AS body FROM tasks ORDER BY rowid DESC", + ) + .all() + .map((r) => JSON.parse(r.body)); + } + get(id) { + const r = this.db.prepare("SELECT body FROM tasks WHERE id=?").get(id); + if (!r) throw Error("Task not found"); + return JSON.parse(r.body); + } + save(t) { + this.db + .prepare( + "INSERT INTO tasks VALUES(?,?) ON CONFLICT(id) DO UPDATE SET body=excluded.body", + ) + .run(t.id, JSON.stringify(t)); + return t; + } + create(input) { + return this.transaction(() => this.createInsideTransaction(input)); + } + plan(inputs) { + return this.transaction(() => { + const created = []; + for (const [index, input] of inputs.entries()) { + if ( + !Array.isArray(input.dependsOn || []) || + (input.dependsOn || []).some( + (n) => !Number.isInteger(n) || n < 0 || n >= index, + ) + ) + throw Error("Plan dependencies must reference earlier task indices"); + created.push( + this.createInsideTransaction({ + ...input, + deps: (input.dependsOn || []).map((n) => created[n].id), + role: "worker", + }), + ); + } + return created; + }); + } + createInsideTransaction(input) { + if ( + this.db.prepare("SELECT COUNT(*) AS count FROM tasks").get().count >= 1000 + ) + throw Error( + "Desk limit reached: archive this state directory before a new mission", + ); + const title = String(input.title || "").trim(), + prompt = String(input.prompt || "").trim(); + if (!title || title.length > 160 || !prompt || prompt.length > 32000) + throw Error("Provide a title (160 max) and prompt (32000 max)"); + const deps = [...new Set(input.deps || [])]; + if (deps.length > 20) throw Error("Too many dependencies"); + deps.forEach((id) => this.get(id)); + const t = { + id: randomUUID(), + title, + prompt, + provider: input.provider, + role: input.role === "queen" ? "queen" : "worker", + deps, + status: "queued", + revision: 1, + attempt: 0, + created: new Date().toISOString(), + note: "", + receipt: null, + }; + this.save(t); + this.event(t.id, "created", title); + return t; + } + change(id, revision, fn, kind = "changed") { + return this.transaction(() => { + const t = this.get(id); + if (t.revision !== revision) + throw Error("Stale revision: refresh before acting"); + fn(t); + t.revision++; + this.save(t); + this.event(id, kind, t.note || t.status); + return t; + }); + } + setting(key, value) { + if (value !== undefined) + this.db + .prepare( + "INSERT INTO settings VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", + ) + .run(key, JSON.stringify(value)); + const r = this.db + .prepare("SELECT value FROM settings WHERE key=?") + .get(key); + return r ? JSON.parse(r.value) : undefined; + } + events(after = 0, task = null) { + return task + ? this.db + .prepare( + "SELECT * FROM events WHERE seq>? AND task=? ORDER BY seq LIMIT 200", + ) + .all(after, task) + : this.db + .prepare("SELECT * FROM events WHERE seq>? ORDER BY seq LIMIT 200") + .all(after); + } + recover() { + for (const t of this.summaries()) + if (["running", "stopping"].includes(t.status)) + this.change( + t.id, + t.revision, + (x) => { + x.status = "interrupted"; + x.note = + "Controller restarted. Inspect the old process/workspace before explicitly retrying; no automatic replay."; + }, + "recovered", + ); + } + close() { + this.db.close(); + } +} diff --git a/control-desk/test/desk.test.mjs b/control-desk/test/desk.test.mjs new file mode 100644 index 0000000..9bb9b24 --- /dev/null +++ b/control-desk/test/desk.test.mjs @@ -0,0 +1,304 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, writeFile, readFile, rm, mkdir } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { start } from "../server.mjs"; +import { Store } from "../store.mjs"; +import { command } from "../engine.mjs"; + +async function fixture(t, options = {}) { + const dir = await mkdtemp(path.join(os.tmpdir(), "omega-desk-")); + const desk = await start({ state: dir, port: 0, demo: true, ...options }); + t.after(async () => { + await desk.close(); + await rm(dir, { recursive: true, force: true }); + }); + const api = async (route, data) => { + const response = await fetch(new URL("/api/" + route, desk.url), { + method: data ? "POST" : "GET", + headers: { + "X-Omega-Token": desk.token, + "Content-Type": "application/json", + }, + ...(data ? { body: JSON.stringify(data) } : {}), + }); + const body = await response.json(); + return { status: response.status, body }; + }; + return { ...desk, dir, api }; +} +async function until(fn) { + const end = Date.now() + 15000; + while (Date.now() < end) { + const v = await fn(); + if (v) return v; + await new Promise((r) => setTimeout(r, 50)); + } + throw Error("Timed out"); +} +const input = { + title: "A bounded task", + prompt: "Produce evidence", + provider: "demo", + deps: [], +}; + +test("queen plan import is atomic, acyclic, and pauses dispatch", async (t) => { + const d = await fixture(t); + await d.api("control", { action: "resume" }); + const invalid = await d.api("plan", { + tasks: [ + { ...input, dependsOn: [] }, + { ...input, dependsOn: [1] }, + ], + }); + assert.equal(invalid.status, 400); + assert.equal(d.store.all().length, 0); + const valid = await d.api("plan", { + tasks: [ + { ...input, dependsOn: [] }, + { ...input, dependsOn: [0] }, + ], + }); + assert.equal(valid.status, 201); + assert.deepEqual(valid.body[1].deps, [valid.body[0].id]); + assert.equal(d.engine.paused, true); +}); + +test("connection changes persist and invalid endpoint credentials are refused", async (t) => { + const d = await fixture(t); + const invalid = await d.api("providers", { + id: "omega", + enabled: false, + limit: 1, + endpoint: "https://secret:password@example.com/v1/chat/completions", + }); + assert.equal(invalid.status, 400); + const valid = await d.api("providers", { + id: "muse", + enabled: false, + limit: 2, + command: ["muse-agent", "{prompt}"], + }); + assert.equal(valid.status, 200); + assert.deepEqual( + d.store.setting("providers").find((p) => p.id === "muse").command, + ["muse-agent", "{prompt}"], + ); + assert.equal( + (await d.api("state")).body.providers.find((p) => p.id === "muse").enabled, + false, + ); +}); + +test("authentication, cross-origin rejection, and paused startup", async (t) => { + const d = await fixture(t); + assert.equal((await fetch(new URL("/api/state", d.url))).status, 401); + assert.equal( + ( + await fetch(new URL("/api/state", d.url), { + headers: { + Origin: "https://untrusted.example", + "X-Omega-Token": d.token, + }, + }) + ).status, + 403, + ); + const s = await d.api("state"); + assert.equal(s.body.paused, true); + assert.equal((await d.api("control", { action: "nonsense" })).status, 400); + await assert.rejects(start({ state: d.dir, port: 0 }), /already locked/); +}); + +test("dependency release requires exact receipt acceptance; stale writes fail", async (t) => { + const d = await fixture(t); + const a = (await d.api("tasks", input)).body; + const b = ( + await d.api("tasks", { ...input, title: "Dependent", deps: [a.id] }) + ).body; + await d.api("control", { action: "resume" }); + await until(() => d.store.get(a.id).status === "review"); + assert.equal(d.store.get(b.id).status, "queued"); + assert.equal( + (await d.api("task", { id: a.id, revision: a.revision, action: "stop" })) + .status, + 400, + ); + let current = d.store.get(a.id); + assert.equal( + ( + await d.api("task", { + id: a.id, + revision: current.revision, + action: "accept", + patchSha256: "fake", + outputSha256: "fake", + }) + ).status, + 400, + ); + const r = (await d.api("receipt/" + a.id)).body; + assert.equal( + ( + await d.api("task", { + id: a.id, + revision: current.revision, + action: "accept", + ...r.receipt, + }) + ).status, + 200, + ); + await until(() => d.store.get(b.id).status === "review"); + assert.equal(d.store.get(a.id).status, "accepted"); +}); + +test("stop settles without stale success; steering and retry create a new attempt", async (t) => { + const d = await fixture(t); + const a = (await d.api("tasks", input)).body; + await d.api("control", { action: "resume" }); + await until(() => d.store.get(a.id).status === "running"); + let current = d.store.get(a.id); + assert.equal( + ( + await d.api("task", { + id: a.id, + revision: current.revision, + action: "stop", + }) + ).status, + 200, + ); + await until(() => d.store.get(a.id).status === "canceled"); + current = d.store.get(a.id); + assert.equal(current.receipt, null); + await d.api("task", { + id: a.id, + revision: current.revision, + action: "steer", + text: "Check cancellation too", + }); + current = d.store.get(a.id); + await d.api("task", { + id: a.id, + revision: current.revision, + action: "retry", + }); + await until(() => d.store.get(a.id).status === "review"); + assert.equal(d.store.get(a.id).attempt, 2); +}); + +test("artifact corruption prevents inspection and acceptance", async (t) => { + const d = await fixture(t); + const a = (await d.api("tasks", input)).body; + await d.api("control", { action: "resume" }); + await until(() => d.store.get(a.id).status === "review"); + const current = d.store.get(a.id); + await writeFile( + path.join(current.receipt.directory, "result.txt"), + "tampered", + ); + assert.equal((await d.api("receipt/" + a.id)).status, 400); + assert.equal( + ( + await d.api("task", { + id: a.id, + revision: current.revision, + action: "accept", + ...current.receipt, + }) + ).status, + 400, + ); +}); + +test("restart marks uncertain attempts interrupted without replay", async (t) => { + const dir = await mkdtemp(path.join(os.tmpdir(), "omega-recover-")); + const store = new Store(path.join(dir, "desk.sqlite")); + const a = store.create(input); + store.change(a.id, a.revision, (x) => { + x.status = "running"; + x.attempt = 1; + }); + store.close(); + const d = await start({ state: dir, port: 0, demo: true }); + t.after(async () => { + await d.close(); + await rm(dir, { recursive: true, force: true }); + }); + assert.equal(d.store.get(a.id).status, "interrupted"); + assert.equal(d.engine.paused, true); + assert.equal(d.engine.active.size, 0); +}); + +test("CLI worker uses isolated clone, captures untracked edits, leaves source unchanged", async (t) => { + const repo = await mkdtemp(path.join(os.tmpdir(), "omega-source-")); + t.after(() => rm(repo, { recursive: true, force: true })); + await command(["git", "init"], repo); + await command(["git", "config", "user.name", "Test"], repo); + await command(["git", "config", "user.email", "test@example.invalid"], repo); + await writeFile(path.join(repo, "original.txt"), "original\n"); + await command(["git", "add", "."], repo); + await command(["git", "commit", "-m", "initial"], repo); + const d = await fixture(t, { repo }); + d.engine.providers.push({ + id: "fixture", + name: "Fixture", + kind: "command", + enabled: true, + limit: 1, + timeoutSeconds: 10, + command: [ + process.execPath, + "-e", + "const fs=require('node:fs'); fs.writeFileSync('generated.txt','isolated\\n'); fs.writeFileSync('legacy.txt',Buffer.from([255,254,10])); console.log('fixture passed')", + ], + }); + const a = (await d.api("tasks", { ...input, provider: "fixture" })).body; + await d.api("control", { action: "resume" }); + await until(() => ["review", "failed"].includes(d.store.get(a.id).status)); + const current = d.store.get(a.id); + assert.equal(current.status, "review", current.note); + const r = await d.engine.receipt(a.id); + assert.match(r.patch, /generated.txt/); + assert.match(r.output, /fixture passed/); + assert.equal(await command(["git", "status", "--porcelain"], repo), ""); + assert.equal(await command(["git", "remote"], current.workspace), ""); + const verification = path.join(d.dir, "verification"); + await command(["git", "clone", "--", repo, verification], d.dir); + await command( + ["git", "apply", path.join(current.receipt.directory, "changes.patch")], + verification, + ); + assert.deepEqual( + await readFile(path.join(verification, "legacy.txt")), + Buffer.from([255, 254, 10]), + ); +}); + +test("slow provider does not consume other provider slot; timeout releases capacity", async (t) => { + const d = await fixture(t, { capacity: 2 }); + d.engine.providers.push({ + id: "slow", + name: "Slow", + kind: "demo", + enabled: true, + limit: 1, + timeoutSeconds: 1, + }); + const a = (await d.api("tasks", { ...input, provider: "slow" })).body; + const b = (await d.api("tasks", { ...input, provider: "slow" })).body; + const c = (await d.api("tasks", input)).body; + await d.api("control", { action: "resume" }); + await until( + () => + d.store.get(a.id).status === "running" && + d.store.get(c.id).status === "running", + ); + assert.equal(d.store.get(b.id).status, "queued"); + await until(() => d.store.get(a.id).status === "failed"); + await until(() => d.store.get(c.id).status === "review"); + assert.match(d.store.get(a.id).note, /deadline/); +}); diff --git a/control-desk/test/ui-smoke.cjs b/control-desk/test/ui-smoke.cjs new file mode 100644 index 0000000..495c160 --- /dev/null +++ b/control-desk/test/ui-smoke.cjs @@ -0,0 +1,99 @@ +const { JSDOM, VirtualConsole } = require("jsdom"); +const fs = require("node:fs/promises"); +const assert = require("node:assert/strict"); +(async () => { + const root = require("node:path").resolve(__dirname, ".."); + const { start } = await import(root + "/server.mjs"); + const state = await fs.mkdtemp("/tmp/omega-dom-"); + const d = await start({ state, port: 0, demo: true }); + const errors = []; + const vc = new VirtualConsole(); + vc.on("jsdomError", (e) => errors.push(e.message)); + const dom = new JSDOM( + await fs.readFile(root + "/public/index.html", "utf8"), + { url: d.url, runScripts: "dangerously", virtualConsole: vc }, + ); + const w = dom.window; + w.fetch = (url, args) => fetch(new URL(url, d.url), args); + w.HTMLDialogElement.prototype.showModal = function () { + this.setAttribute("open", ""); + }; + w.HTMLDialogElement.prototype.close = function () { + this.removeAttribute("open"); + }; + const $ = (s) => w.document.querySelector(s); + const wait = async (fn) => { + for (let i = 0; i < 200; i++) { + if (fn()) return; + await new Promise((r) => setTimeout(r, 50)); + } + throw Error("DOM condition timed out"); + }; + const submit = (form) => + form.dispatchEvent( + new w.Event("submit", { bubbles: true, cancelable: true }), + ); + try { + await w.eval( + "(async()=>{" + + (await fs.readFile(root + "/public/app.js", "utf8")) + + "})()", + ); + assert.equal($("#health").textContent, "Dispatch paused"); + $("#new-task").click(); + const f = $("#task-form"); + f.elements.title.value = "DOM integration task"; + f.elements.prompt.value = "Exercise the real UI and backend"; + submit(f); + await wait(() => d.store.all().length === 1); + await wait(() => !$("#task-dialog").hasAttribute("open")); + $("#pause").click(); + await wait(() => d.store.all()[0].status === "review"); + await wait(() => $('[data-action="receipt"]')); + $('[data-action="receipt"]').click(); + await wait(() => $('[data-action="accept"]')); + $('[data-action="accept"]').click(); + await wait(() => d.store.all()[0].status === "accepted"); + $("#import-plan").click(); + $("#plan-form").elements.plan.value = JSON.stringify({ + tasks: [ + { + title: "Investigate", + prompt: "Investigate the contract", + provider: "demo", + dependsOn: [], + }, + { + title: "Verify", + prompt: "Verify the accepted result", + provider: "demo", + dependsOn: [0], + }, + ], + }); + submit($("#plan-form")); + await wait(() => d.store.all().length === 3); + assert.equal(d.engine.paused, true); + $('[data-configure="muse"]').click(); + const c = $("#connection-form"); + c.elements.command.value = '["muse-agent", "{prompt}"]'; + submit(c); + await wait( + () => + d.store.setting("providers")?.find((p) => p.id === "muse") + .command[0] === "muse-agent", + ); + await wait(() => !$("#connection-dialog").hasAttribute("open")); + assert.equal(errors.length, 0, errors.join("\n")); + console.log( + "PASS: real UI handlers create task, resume, inspect receipt, accept, import dependent plan and pause, configure Muse; 0 DOM runtime errors. Layout/rendering NOT RUN.", + ); + } finally { + w.close(); + await d.close(); + await fs.rm(state, { recursive: true, force: true }); + } +})().catch((e) => { + console.error(e); + process.exitCode = 1; +});