diff --git a/home/server.ts b/home/server.ts deleted file mode 100644 index a3d3bf157..000000000 --- a/home/server.ts +++ /dev/null @@ -1,790 +0,0 @@ -#!/usr/bin/env -S npx tsx -/** - * Brain — local Node HTTP server. - * - * Boots, tails ~/./events.jsonl, projects events into in-memory - * state, serves a minimal /control view and a /api/state JSON endpoint. - * - * No external deps beyond what the existing repo already brings in (node:* - * for the server, zod via src/lib/events for parsing). M2 deliberately keeps - * the surface tiny: this is the smallest possible thing that proves the - * event-log → state projection → UI loop works. - * - * Run: npx tsx home/server.ts - * Test: echo '' >> ~/./events.jsonl - * curl http://localhost:3001/api/state - * - * Brain growth: M3 wires a Bridge that pulls events from the OS / hooks. - * M5 adds the decide() function. M6 wires dispatch back to - * workers. This file stays small. - */ - -import http from "node:http"; -import fs from "node:fs"; -import path from "node:path"; -import os from "node:os"; -import { randomUUID } from "node:crypto"; -import { spawnSync } from "node:child_process"; -import { fileURLToPath } from "node:url"; -import { APP_NAME, APP_SLUG } from "@/config/brand"; -import type { Autonomy, Adapter } from "@/lib/events"; -import { ADAPTERS, parseEvent } from "@/lib/events"; -import { tailLog } from "./log"; -import { applyEvent, type GlobalState, type ProjectState } from "./state"; -import { decide, type Decision } from "./decide"; -import { appendEvent } from "./emit"; -import { renderPromptForDispatch } from "./render"; -import { resolveProjectPath, resolveProjectAdapter, loadProjects } from "./projects"; -import { ORCHESTRATION_TASK_INTENT_IDS, type OrchestrationTaskIntentId } from "@/lib/orchestration"; - -// Boot-mode gate. Naked `npx tsx home/server.ts` (no flags) should NOT spin -// up the HTTP server + fs.watch — otherwise a one-shot test invocation -// (e.g. inside a `tail -3` pipe) leaves an orphan server eating port 3001 -// + watching the event log forever. Require an explicit --start. -if (!process.argv.includes("--start")) { - console.log(`${APP_NAME} brain — local HTTP server (Brain layer of the home/ stack). -Usage: npx tsx home/server.ts --start -Env: APP_HOME_PORT port to bind (default 3001)`); - process.exit(0); -} - -const LOG_PATH = path.join(os.homedir(), `.${APP_SLUG}`, "events.jsonl"); -const PORT = parseInt(process.env.APP_HOME_PORT ?? process.env.FLEETCROWN_HOME_PORT ?? process.env.COCKPIT_HOME_PORT ?? "3001", 10); - -// Repo root derived from this file's location — used by the same-machine -// inject fast path below to spawn bash with the right script paths. -const __filename = fileURLToPath(import.meta.url); -const REPO_ROOT = path.resolve(path.dirname(__filename), ".."); -const AGENT_HOOK_LIB = path.join(REPO_ROOT, "scripts", "agent-hook-lib.sh"); -const BRAND_LIB = path.join(REPO_ROOT, "scripts", "_brand.sh"); - -let state: GlobalState = new Map(); -let lastError: { ts: string; message: string; raw?: string } | null = null; - -/** - * Union live event-projected state with registered-but-eventless projects - * from agent-projects.conf so the UI can show every project the user has - * registered, even ones that have never emitted an event yet (fresh boot, - * new project just added, etc.). Live state always wins on name collision. - * - * Lowercase-keyed dedup matches the registry's case-insensitive lookup. - */ -function assembleProjectList(): ProjectState[] { - const live = Array.from(state.values()); - const liveLower = new Set(live.map((p) => p.project.toLowerCase())); - const idleRegistered: ProjectState[] = []; - for (const cfg of loadProjects().values()) { - if (liveLower.has(cfg.name.toLowerCase())) continue; - idleRegistered.push({ - project: cfg.name, - lastEventTs: "", // empty signals "never seen an event" to the UI - recentOutcomes: [], - }); - } - return [...live, ...idleRegistered]; -} - -const handle = tailLog( - LOG_PATH, - (event) => { state = applyEvent(state, event); }, - (err, raw) => { - lastError = { ts: new Date().toISOString(), message: err.message, raw }; - // Don't spam — only echo parse errors to stderr if they look unexpected. - if (!err.message.startsWith("parse: schema:")) console.error("[home]", err.message); - }, -); - -// ── HTML page (vanilla JS, polls /api/state every 2s) ──────────────────────── -// -// Editing trap: the entire HTML+JS body lives inside the backtick template -// literal below. Two characters need careful handling when adding content -// here that don't matter in a normal .ts file: -// • Backticks (`) close the literal — escape as \` or avoid in comments -// and strings. A stray ` mid-comment produces opaque TS1005 errors -// pointing at the surrounding line, not the backtick itself. -// • ${expr} interpolates at server-render time. Use \${ in any JS that -// should evaluate in the browser (we already do this for refresh's -// template strings — see the renderProposal returns). -// -// If a tsc syntax error points at a line that "looks fine," grep for an -// unescaped backtick or ${ in the surrounding template body. - -const INDEX_HTML = ` - - - -${APP_NAME} · home - - - -
-

${APP_NAME} · home

- tailing ~/.${APP_SLUG}/events.jsonl - -
-
-
-

-
-
-`;
-
-// ── HTTP handlers ────────────────────────────────────────────────────────────
-
-// ── Same-machine fast path ───────────────────────────────────────────────────
-//
-// /control in the browser tries POST http://localhost:3001/api/inject before
-// falling back to the cloud /api/inject. Cutting Vercel + Postgres + long-poll
-// out of the local case turns 7 hops into 3 (browser → home → zellij → agent)
-// and removes the failure modes that come with each missing hop.
-//
-// Security model:
-//   - The home server binds to 127.0.0.1 only (see listen() at the bottom),
-//     so machines on the LAN cannot reach it.
-//   - CORS allow-list is tight: only the deployed cloud origin and the local
-//     dev server can read responses. The browser blocks cross-origin reads
-//     from anywhere else, so a malicious page in another tab cannot tell
-//     whether the inject succeeded.
-//   - POST is harmless without a valid project name — bad inputs return 4xx
-//     with no side effect.
-
-const ALLOWED_ORIGINS = new Set([
-  "https://fleetcrown.vercel.app",
-  "http://localhost:3000",
-  "http://127.0.0.1:3000",
-]);
-
-function applyCors(req: http.IncomingMessage, res: http.ServerResponse): void {
-  const origin = (req.headers.origin ?? "") as string;
-  if (ALLOWED_ORIGINS.has(origin)) {
-    res.setHeader("Access-Control-Allow-Origin", origin);
-    res.setHeader("Vary", "Origin");
-    res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
-    res.setHeader("Access-Control-Allow-Headers", "Content-Type");
-    // Chrome's Private Network Access blocks HTTPS pages (cloud /control)
-    // from reaching a private IP / loopback (this server on 127.0.0.1)
-    // unless the target opts in by acknowledging the cross-network
-    // request. Without this header the browser silently aborts the
-    // request before the daemon ever sees it.
-    // https://developer.chrome.com/blog/private-network-access-preflight
-    res.setHeader("Access-Control-Allow-Private-Network", "true");
-  }
-}
-
-const server = http.createServer((req, res) => {
-  const url = req.url ?? "/";
-
-  // Preflight for the fast-path inject from cross-origin /control.
-  if (req.method === "OPTIONS") {
-    applyCors(req, res);
-    res.statusCode = 204;
-    res.end();
-    return;
-  }
-  applyCors(req, res);
-
-  if (url === "/" || url === "/control") {
-    res.setHeader("Content-Type", "text/html; charset=utf-8");
-    res.end(INDEX_HTML);
-    return;
-  }
-
-  if (url === "/api/state") {
-    res.setHeader("Content-Type", "application/json");
-    // Annotate each project with the local /tmp/agent-queue- length so
-    // the /control UI can surface a "Nqueued" badge. The file mirror is
-    // hydrated by the FleetCrown API/daemon bridge from DB authority.
-    // Reading the file lets home/ show queue depth without taking
-    // a DB dep — keeping home/ local-first.
-    const projects = assembleProjectList().map((p) => {
-      let queueLen = 0;
-      try {
-        const raw = fs.readFileSync(path.join("/tmp", `agent-queue-${p.project.toLowerCase()}`), "utf8");
-        const arr = JSON.parse(raw);
-        if (Array.isArray(arr)) queueLen = arr.length;
-      } catch { /* file missing or unreadable → no badge */ }
-      return { ...p, queueLen };
-    });
-    res.end(JSON.stringify({
-      projects,
-      logPath: LOG_PATH,
-      position: handle.position(),
-      lastError,
-    }));
-    return;
-  }
-
-  if (url === "/api/health") {
-    res.setHeader("Content-Type", "application/json");
-    res.end(JSON.stringify({ ok: true, projectCount: state.size, logPath: LOG_PATH }));
-    return;
-  }
-
-  // Same-machine fast path. Body: { project: string, prompt: string }.
-  // Looks up the project's filesystem path from agent-projects.conf, then
-  // spawns bash to source agent-hook-lib.sh and call inject_prompt directly.
-  // Returns {ok:true} on success or {ok:false, reason} on failure — the
-  // reason is the structured single-line message inject_prompt emits via
-  // _inject_fail_reason, so the caller can render it to the user without
-  // having to re-diagnose.
-  if (url === "/api/inject" && req.method === "POST") {
-    let body = "";
-    req.on("data", (chunk) => { body += String(chunk); });
-    req.on("end", () => {
-      try {
-        const parsed = body.trim() ? JSON.parse(body) : {};
-        const project: string | undefined = parsed.project;
-        const prompt: string | undefined = parsed.prompt;
-        if (typeof project !== "string" || !project || typeof prompt !== "string") {
-          res.statusCode = 400;
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({ ok: false, reason: "bad-request: body must be {project: string, prompt: string}" }));
-          return;
-        }
-        // Resolve project_dir from the same SSOT the daemon reads. Falls
-        // back to empty string — inject_prompt's cwd path is optional.
-        const projectDir = resolveProjectPath(project) ?? "";
-
-        // Source brand + agent-hook-lib then invoke inject_prompt with our
-        // three positional args. Stderr lines starting with "inject:" carry
-        // the structured failure reason; we grep for the last one.
-        const result = spawnSync(
-          "bash",
-          [
-            "-c",
-            `source "${BRAND_LIB}" 2>/dev/null; source "${AGENT_HOOK_LIB}" || exit 90; inject_prompt "$1" "$2" "$3"`,
-            "fleetcrown-inject",
-            project,
-            prompt,
-            projectDir,
-          ],
-          { encoding: "utf8", timeout: 8000 },
-        );
-
-        if (result.status === 0) {
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({ ok: true }));
-          return;
-        }
-
-        // Pull the last "inject:" line out of stderr for the reason; otherwise
-        // synthesize a fallback that still names the failure mode.
-        const stderr = (result.stderr ?? "").toString();
-        const lastReasonLine = stderr.split("\n").filter((l) => l.startsWith("inject:")).pop();
-        const reason = lastReasonLine
-          ? lastReasonLine.slice("inject:".length)
-          : result.status === 90
-            ? `bash-init: could not source ${AGENT_HOOK_LIB} — is the repo checked out and home/ daemon started from it?`
-            : result.signal === "SIGTERM" || result.signal === null && result.status === null
-              ? "timeout: inject_prompt did not return within 8s — zellij may be hung; restart your session"
-              : `inject_prompt exit=${result.status}: ${stderr.trim().split("\n").pop() ?? "no output"}`;
-
-        res.statusCode = 200;
-        res.setHeader("Content-Type", "application/json");
-        res.end(JSON.stringify({ ok: false, reason }));
-      } catch (err) {
-        res.statusCode = 500;
-        res.setHeader("Content-Type", "application/json");
-        res.end(JSON.stringify({ ok: false, reason: `home-inject crash: ${err instanceof Error ? err.message : String(err)}` }));
-      }
-    });
-    return;
-  }
-
-  // Convenience: POST a JSONL event body to append to the log. Used for manual
-  // testing; the real producers are home/watcher.ts, home/worker.ts, and the
-  // emit_worker_finished function in scripts/agent-hook-bridge.sh.
-  //
-  // Validated against the v=1 schema before append — otherwise a typo or
-  // half-built event leaves a permanent garbled line in the log that
-  // parseEvent on the read side has to skip on every boot.
-  if (url === "/api/events" && req.method === "POST") {
-    let body = "";
-    req.on("data", (chunk) => { body += String(chunk); });
-    req.on("end", () => {
-      try {
-        const line = body.trim();
-        if (!line) {
-          res.statusCode = 400;
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({ ok: false, error: "empty body" }));
-          return;
-        }
-        const parsed = parseEvent(line);
-        if (!parsed.ok) {
-          res.statusCode = 400;
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({ ok: false, error: parsed.error, raw: parsed.raw }));
-          return;
-        }
-        // Append the original line (preserves caller's field ordering /
-        // formatting) — parsed.event is just the validation product.
-        fs.appendFileSync(LOG_PATH, line + "\n");
-        res.setHeader("Content-Type", "application/json");
-        res.end(JSON.stringify({ ok: true, kind: parsed.event.kind }));
-      } catch (e) {
-        res.statusCode = 500;
-        res.setHeader("Content-Type", "application/json");
-        res.end(JSON.stringify({ ok: false, error: String(e) }));
-      }
-    });
-    return;
-  }
-
-  // Cancel an in-flight run. Emits a bridge.cancel event that:
-  //  1) the worker tails and turns into a Ctrl+C sent to the project's tab
-  //  2) state.ts projects into "currentRun = undefined" once the runId matches
-  //  3) the worker treats as a terminator so a never-started dispatch sitting
-  //     in pendingDispatches doesn't fire on next worker restart
-  //
-  // Body: { project: string, runId?: string, reason?: string }
-  // If runId is omitted, the live currentRun.runId is used. 404 if there's
-  // no active run for the project.
-  if (url === "/api/cancel" && req.method === "POST") {
-    let body = "";
-    req.on("data", (chunk) => { body += String(chunk); });
-    req.on("end", () => {
-      try {
-        const parsed = body.trim() ? JSON.parse(body) : {};
-        const projectName: string | undefined = parsed.project;
-        if (typeof projectName !== "string" || !projectName) {
-          res.statusCode = 400;
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({ error: "missing 'project' string in body" }));
-          return;
-        }
-        const liveState = state.get(projectName);
-        const runId: string | undefined =
-          (typeof parsed.runId === "string" && parsed.runId) || liveState?.currentRun?.runId;
-        if (!runId) {
-          res.statusCode = 404;
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({
-            error: `no active run for project: ${projectName}`,
-            hint: "POST body can include a runId to cancel a specific run; otherwise the project must have a currentRun.",
-          }));
-          return;
-        }
-        const reason = (typeof parsed.reason === "string" && parsed.reason.slice(0, 200)) || "user cancel";
-        const cancelled = appendEvent({
-          kind: "bridge.cancel",
-          project: projectName,
-          runId,
-          reason,
-        });
-        // Eager projection — match the /api/dispatch pattern. Closes the
-        // same race: a follow-up dispatch arriving before fs.watch fires
-        // would see stale currentRun and refuse to proceed; with eager
-        // apply, currentRun is already cleared (bridge.cancel projection
-        // matches runId and unsets it). Idempotent re-application by
-        // tailLog: cancelledRunIds.filter() dedupes, currentRun stays
-        // undefined.
-        state = applyEvent(state, cancelled);
-        res.setHeader("Content-Type", "application/json");
-        res.end(JSON.stringify({ ok: true, runId, reason }));
-      } catch (e) {
-        res.statusCode = 400;
-        res.setHeader("Content-Type", "application/json");
-        res.end(JSON.stringify({ error: String(e) }));
-      }
-    });
-    return;
-  }
-
-  // M6 — dispatch. Run decide() against the current state for a project and
-  // either emit a bridge.dispatch event (when autonomy + confidence say "go")
-  // or return the proposed action for a confirm-mode UI to render.
-  //
-  // Body: { project: string, queueHead?: string, autonomy?: Autonomy, projectPath?: string }
-  // Response on auto-execute: { dispatched: true,  decision, runId }
-  // Response on hold:         { dispatched: false, decision }
-  if (url === "/api/dispatch" && req.method === "POST") {
-    let body = "";
-    req.on("data", (chunk) => { body += String(chunk); });
-    req.on("end", () => {
-      try {
-        const parsed = body.trim() ? JSON.parse(body) : {};
-        const projectName: string | undefined = parsed.project;
-        if (typeof projectName !== "string" || !projectName) {
-          res.statusCode = 400;
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({ error: "missing 'project' string in body" }));
-          return;
-        }
-        // Look up the project — first in the live event-projected state, then
-        // fall back to the agent-projects.conf registry so a brand-new project
-        // (no events yet) can still receive its first dispatch. Last resort:
-        // accept the name verbatim; the brain has nothing to reason about so
-        // decide() defaults to "next_best" with neutral confidence, but that's
-        // a valid first run.
-        const liveState = state.get(projectName);
-        const registered = resolveProjectPath(projectName);
-        if (!liveState && !registered) {
-          res.statusCode = 404;
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({
-            error: `unknown project: ${projectName}`,
-            hint: "Add it to ~/.config/agent-projects.conf (TabName|/absolute/path), or POST a worker.* event first.",
-          }));
-          return;
-        }
-        const projectState: ProjectState = liveState ?? {
-          project: projectName,
-          lastEventTs: new Date().toISOString(),
-          recentOutcomes: [],
-        };
-        const decision = decide({
-          project: projectState,
-          queueHead: typeof parsed.queueHead === "string" ? parsed.queueHead : undefined,
-          autonomy: parsed.autonomy as Autonomy | undefined,
-        });
-
-        // Wait actions never dispatch; same for any action where the autonomy
-        // gate said hold. Return the proposal so a confirm-mode UI can render
-        // the countdown + auto-fire button.
-        if (decision.action.kind === "wait" || !decision.autoExecute) {
-          res.setHeader("Content-Type", "application/json");
-          res.end(JSON.stringify({ dispatched: false, decision }));
-          return;
-        }
-
-        // Auto-execute: emit a bridge.dispatch event with a fresh run id.
-        const runId = randomUUID();
-        // Resolve the project's filesystem path so the rendered prompt reads
-        // "Work on the project at /home/g/dev/" instead of the project
-        // name as fallback. Caller-supplied wins; otherwise look up the
-        // existing ~/.config/agent-projects.conf SSOT.
-        const projectPath =
-          (typeof parsed.projectPath === "string" && parsed.projectPath) ||
-          resolveProjectPath(projectName);
-        // Pick up the user's prompt queue if present: caller-supplied (request
-        // body) wins, else read /tmp/agent-queue- — the file mirror the
-        // cloud /api/beacon/queue/[tab] PUT writes (best-effort) for bash-hook
-        // and home/ compat. Either source flows through buildPromptForDispatch
-        // → renderTaskForAdapter → renderQueueBlock so the dispatched prompt
-        // body shows the agent what's pending. Empty/missing queue → no block.
-        const queue: string[] = (() => {
-          if (Array.isArray(parsed.queue)) {
-            return parsed.queue.filter((s: unknown): s is string => typeof s === "string");
-          }
-          try {
-            const file = path.join("/tmp", `agent-queue-${projectName.toLowerCase()}`);
-            const raw = fs.readFileSync(file, "utf8");
-            const arr = JSON.parse(raw);
-            return Array.isArray(arr) ? arr.filter((s: unknown): s is string => typeof s === "string") : [];
-          } catch { return []; }
-        })();
-        const prompt = buildPromptForDispatch(decision, projectState, projectPath, queue);
-        const intent = decision.action.intent;
-        // Adapter resolution: caller-supplied wins (lets the UI override per
-        // dispatch), otherwise fall back to the project's declared adapter
-        // from agent-projects.conf's 3rd field. Worker defaults to "claude"
-        // downstream if both are absent.
-        const adapter: Adapter | undefined =
-          (typeof parsed.adapter === "string" && (ADAPTERS as readonly string[]).includes(parsed.adapter)
-            ? (parsed.adapter as Adapter)
-            : undefined)
-          ?? resolveProjectAdapter(projectName);
-        const dispatched = appendEvent({
-          kind: "bridge.dispatch",
-          project: projectName,
-          intent,
-          prompt,
-          runId,
-          autonomy: (parsed.autonomy as Autonomy | undefined) ?? "confirm",
-          adapter,
-          reason: decision.action.reason,
-          confidence: decision.confidence,
-        });
-        // Eagerly project so a concurrent /api/dispatch reads the post-state
-        // and decide() returns "wait" instead of firing a second dispatch.
-        // tailLog will re-apply the same event when fs.watch fires; that's
-        // idempotent for bridge.dispatch (just overwrites currentRun).
-        state = applyEvent(state, dispatched);
-        res.setHeader("Content-Type", "application/json");
-        res.end(JSON.stringify({ dispatched: true, decision, runId }));
-      } catch (e) {
-        res.statusCode = 400;
-        res.setHeader("Content-Type", "application/json");
-        res.end(JSON.stringify({ error: String(e) }));
-      }
-    });
-    return;
-  }
-
-  res.statusCode = 404;
-  res.setHeader("Content-Type", "text/plain");
-  res.end("Not Found");
-});
-
-/**
- * Build the dispatch prompt for a decision.
- *
- * M7: replaces the M6 stub. Reuses the existing src/lib/orchestration
- * renderer via home/render.ts (single SSOT for prompt text). If the
- * decision carries an explicit prompt string (queue-drain case), that's
- * passed through as a 'custom' intent so the queue item itself becomes
- * the prompt body — same behavior as today's queue→intent="custom" flip.
- */
-function buildPromptForDispatch(
-  decision: Decision,
-  project: ProjectState,
-  projectPath?: string,
-  queue?: string[],
-): string {
-  if (decision.action.kind === "wait") {
-    // Caller is supposed to short-circuit on wait — never dispatch one.
-    throw new Error("buildPromptForDispatch called on a wait decision");
-  }
-  const intentRaw = decision.action.intent;
-  // Decision.action.intent is a free-form string in the home types; gate
-  // it against the canonical id set before handing to the renderer.
-  const intent =
-    (ORCHESTRATION_TASK_INTENT_IDS as readonly string[]).includes(intentRaw)
-      ? (intentRaw as OrchestrationTaskIntentId)
-      : "next_best";
-  // Queue-drain case: the queue item IS the prompt. Pass it through as
-  // intent="custom" so renderTaskForAdapter echoes it verbatim. The
-  // remaining queue (everything after the drained head) still flows so
-  // the agent sees what's coming after this run.
-  if (decision.action.kind === "dispatch" && decision.action.prompt) {
-    return renderPromptForDispatch({
-      project: project.project,
-      projectPath,
-      intent: "custom",
-      customInstructions: decision.action.prompt,
-      queue,
-    });
-  }
-  return renderPromptForDispatch({
-    project: project.project,
-    projectPath,
-    intent,
-    queue,
-  });
-}
-
-// Bind to 127.0.0.1 only so the same-machine fast-path /api/inject endpoint
-// is unreachable from the LAN. Cross-origin browser callers reach it via
-// fetch("http://localhost:3001/...") with the CORS allow-list above.
-server.listen(PORT, "127.0.0.1", () => {
-  console.log(`[home] ${APP_NAME} brain listening on http://127.0.0.1:${PORT}`);
-  console.log(`[home] tailing ${LOG_PATH}`);
-});
-
-const shutdown = (signal: string) => {
-  console.log(`[home] ${signal} — shutting down`);
-  handle.close();
-  server.close(() => process.exit(0));
-};
-process.on("SIGINT",  () => shutdown("SIGINT"));
-process.on("SIGTERM", () => shutdown("SIGTERM"));
diff --git a/scripts/home-start.sh b/scripts/home-start.sh
deleted file mode 100755
index a93860d44..000000000
--- a/scripts/home-start.sh
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/env bash
-# Start the home/ stack — server (Brain) + watcher (Bridge) + worker (Consumer).
-# Logs go to /tmp/${APP_SLUG}-home.log so you can tail one file to see all
-# three. Ctrl-C kills the whole stack cleanly.
-#
-# Use:    bash scripts/home-start.sh
-#         (UI at http://localhost:3001)
-#
-# Tail logs in another terminal:
-#         tail -f /tmp/${APP_SLUG}-home.log
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-# shellcheck source=_brand.sh
-source "$SCRIPT_DIR/_brand.sh"
-
-REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
-LOG_FILE="$(_brand_tmp 'home.log')"
-PIDS=()
-
-log() { echo "[home-start] $(date '+%H:%M:%S') $*"; }
-
-# Truncate the log on each restart so old runs don't accumulate.
-: > "$LOG_FILE"
-log "logs → $LOG_FILE"
-
-# Refuse to start if any port:3001 is already taken — prevents the
-# double-launch foot-gun where two server.ts processes silently race on
-# the same log file.
-if curl -sf --max-time 0.5 http://localhost:3001/api/health >/dev/null 2>&1; then
-  log "ERROR: something is already serving localhost:3001 — refusing to start"
-  log "       (curl http://localhost:3001/api/health if you want to see what)"
-  exit 1
-fi
-
-shutdown() {
-  log "shutdown requested — stopping ${#PIDS[@]} process(es)"
-  for pid in "${PIDS[@]}"; do
-    kill "$pid" 2>/dev/null || true
-  done
-  # Give them ~1s to exit gracefully, then SIGKILL the stragglers.
-  sleep 1
-  for pid in "${PIDS[@]}"; do
-    kill -9 "$pid" 2>/dev/null || true
-  done
-  exit 0
-}
-trap shutdown SIGINT SIGTERM EXIT
-
-cd "$REPO_ROOT"
-
-# Each process tags its output so the merged log is readable when grepped.
-# --start is required by all three since 2026-05 — naked `npx tsx home/X.ts`
-# now exits with a usage banner so accidental one-shots don't leave orphans.
-launch() {
-  local name="$1" cmd="$2"
-  ( exec npx tsx "$cmd" --start 2>&1 | sed -u "s/^/[${name}] /" >> "$LOG_FILE" ) &
-  PIDS+=("$!")
-  log "started $name (pid $!) → $cmd --start"
-}
-
-launch server  home/server.ts
-launch watcher home/watcher.ts
-launch worker  home/worker.ts
-
-log "${#PIDS[@]} process(es) running — Ctrl-C to stop"
-log "tail -f $LOG_FILE"
-
-# Wait for any child to exit. If one dies, take the whole stack down so the
-# user gets a clear signal instead of a half-broken loop.
-wait -n
-log "a child process exited — taking the stack down"
-shutdown
diff --git a/src/app/api/agent/daemon/route.ts b/src/app/api/agent/daemon/route.ts
index 85a94f050..946eaef8e 100644
--- a/src/app/api/agent/daemon/route.ts
+++ b/src/app/api/agent/daemon/route.ts
@@ -1,139 +1,30 @@
 import { NextResponse } from "next/server";
-import { readFile } from "node:fs/promises";
-import { gzipSync } from "node:zlib";
-import path from "node:path";
 
 /**
- * Serves a gzipped tarball of the local helper runtime so a new customer can
- * install the agent fleet without cloning the repo:
+ * GET /api/agent/daemon
  *
- *   scripts/fleetcrown-daemon.sh — main polling loop
- *   scripts/_brand.sh            — brand SSOT (APP_NAME / APP_SLUG / APP_DOMAIN)
- *   scripts/agent-hook-lib.sh    — zellij inject_prompt + shared helpers
- *   scripts/agent-hook-bridge.sh — agent CLI bridge
+ * Used to serve a gzipped tarball of the bash daemon (~3000 lines across
+ * fleetcrown-daemon.sh / agent-hook-bridge.sh / agent-hook-lib.sh + a
+ * Python beacon stack) so a new customer could install the local helper
+ * runtime in one command. Retired in Session 4 of killing-the-bash-daemon
+ * (2026-06-11). The bash stack has been replaced by Fleet Runner desktop
+ * (Electron app) which customers download from /download as a signed
+ * native installer per platform — no bash, no Python beacon, no systemd.
  *
- * Together ~1500 lines of bash. They are the local execution surface.
- *
- * Tarball is built in pure Node — the first version of this route used
- * spawn("tar", ...) and 500'd on Vercel because the runtime image may not
- * carry the tar binary (or spawn can't reach it). The ustar format is
- * trivial enough (one 512-byte header per file + content padded to 512,
- * then 1024 zero bytes as end-of-archive) that doing it ourselves avoids
- * the system-binary dependency entirely.
- *
- * Files extract at the destination root (no `scripts/` prefix) so the
- * agent CLI writes them straight into ~/.local/share/fleetcrown/.
- *
- * Public (no auth) — matches the matcher exception in src/proxy.ts.
- * next.config.ts includes the source files in this route's
- * outputFileTracingIncludes so they land in the Vercel deployment bundle.
+ * Kept as a 410 Gone for existing installer scripts that may still POST
+ * here. The Location header points at /download so a redirected browser
+ * lands on the Fleet Runner download CTA.
  */
-const FILES = [
-  // Core daemon + shared brand/zellij helpers + bridge entry point.
-  "fleetcrown-daemon.sh",
-  "fleet",
-  "_brand.sh",
-  "_agents.sh",
-  "agent-hook-lib.sh",
-  "agent-hook-bridge.sh",
-  // Per-agent task runners. Claude uses an inline command (no runner); codex
-  // and gemini require these wrappers — without them the daemon hard-fails
-  // when dispatching either agent. The bridge expects $SCRIPT_DIR/run-X-task.sh.
-  "run-codex-task.sh",
-  "run-gemini-task.sh",
-  // systemd installer — the agent CLI's --install flag spawns this so a new
-  // customer's daemon survives shell exit. Uses $SCRIPT_DIR for service
-  // WorkingDirectory + ExecStart, which resolves correctly under the flat
-  // ~/.local/share/fleetcrown/ layout (no PROJECT_DIR/.. assumption is hit on
-  // the env-var token path that the CLI feeds in).
-  "install-fleetcrown-daemon.sh",
-  // Python helpers referenced by agent-hook-bridge.sh. All are wrapped in
-  // `|| true` / `2>/dev/null` in the bridge so absence degrades gracefully —
-  // but real customers want the full experience (audio beacon, idle detection,
-  // notifications). beacon imports _beacon_config so both ship together.
-  "beacon.py",
-  "_beacon_config.py",
-  "get-idle-secs.py",
-  "notify-choice.py",
-  "sync-agent-runtime-config.py",
-  // Audio transcription is invoked by fleetcrown-daemon.sh for recorded prompt
-  // commands and must travel with the flat installed runtime.
-  "transcribe.py",
-] as const;
-
 export async function GET() {
-  const scriptsDir = path.join(process.cwd(), "scripts");
-
-  try {
-    const tarball = await buildTarball(scriptsDir, FILES);
-    return new NextResponse(new Uint8Array(tarball), {
-      status: 200,
-      headers: {
-        "Content-Type": "application/gzip",
-        "Cache-Control": "public, max-age=300, s-maxage=300",
-        "Content-Disposition": 'attachment; filename="fleetcrown-daemon.tar.gz"',
-      },
-    });
-  } catch (e) {
-    console.error("[agent/daemon] build failed:", (e as Error)?.message, (e as Error)?.stack);
-    return NextResponse.json(
-      { error: "Daemon bundle unavailable", detail: (e as Error)?.message },
-      { status: 500 },
-    );
-  }
-}
-
-/**
- * Build a ustar gzip archive in memory. No external binaries, no extra
- * deps — just Node builtins. ~50 lines of format-spec implementation.
- */
-async function buildTarball(dir: string, files: readonly string[]): Promise {
-  const chunks: Buffer[] = [];
-  for (const name of files) {
-    const content = await readFile(path.join(dir, name));
-    chunks.push(ustarHeader(name, content.length));
-    chunks.push(padTo512(content));
-  }
-  chunks.push(Buffer.alloc(1024)); // end-of-archive: two zeroed 512-byte blocks
-  return gzipSync(Buffer.concat(chunks));
-}
-
-/**
- * ustar header (512 bytes). Mode 0755 for everything — the .sh files are
- * either run directly or sourced; making the non-executables executable
- * too is harmless. The agent CLI re-chmods the two main executables on
- * extraction regardless.
- *
- * Checksum is the sum of all header bytes treating the checksum field
- * itself as 8 ASCII spaces; written as 6-digit octal + NUL + space.
- */
-function ustarHeader(name: string, size: number): Buffer {
-  const h = Buffer.alloc(512);
-  h.write(name, 0, Math.min(name.length, 99), "utf8");
-  writeOctal(h, 100, 8, 0o755);
-  writeOctal(h, 108, 8, 0);
-  writeOctal(h, 116, 8, 0);
-  writeOctal(h, 124, 12, size);
-  writeOctal(h, 136, 12, Math.floor(Date.now() / 1000));
-  h.write("        ", 148, 8, "ascii"); // checksum placeholder = 8 spaces
-  h.write("0", 156, 1, "ascii");          // typeflag: regular file
-  h.write("ustar\0", 257, 6, "ascii");
-  h.write("00", 263, 2, "ascii");
-
-  let sum = 0;
-  for (let i = 0; i < 512; i++) sum += h[i];
-  h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii");
-
-  return h;
-}
-
-function writeOctal(buf: Buffer, offset: number, len: number, value: number): void {
-  // Format: zero-padded octal of (len-1) digits + trailing NUL.
-  buf.write(value.toString(8).padStart(len - 1, "0") + "\0", offset, len, "ascii");
-}
-
-function padTo512(buf: Buffer): Buffer {
-  const remainder = buf.length % 512;
-  if (remainder === 0) return buf;
-  return Buffer.concat([buf, Buffer.alloc(512 - remainder)]);
+  return NextResponse.json(
+    {
+      ok: false,
+      error: "The bash daemon installer was retired on 2026-06-11. Download Fleet Runner from /download instead.",
+      next: "/download",
+    },
+    {
+      status: 410,
+      headers: { Location: "/download" },
+    },
+  );
 }
diff --git a/src/app/api/system/daemon/route.ts b/src/app/api/system/daemon/route.ts
deleted file mode 100644
index 23477c2e7..000000000
--- a/src/app/api/system/daemon/route.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-/**
- * POST /api/system/daemon  { action: "start" | "restart" | "stop" }
- * GET  /api/system/daemon  (returns current state)
- *
- * Controls the fleetcrown-daemon.service systemd user unit. Local-only —
- * Vercel cloud has no daemon to control, so the
- * route 403s when isRuntimeAvailable() is false. This is the one-click
- * recovery path the user surfaced 2026-05-31: until now, when the daemon
- * went offline the only recovery was a terminal command, which is
- * product-fatal for the "fleet control" value prop.
- *
- * Security: the route shells out to systemctl. We hard-code the unit-name
- * candidate list + action whitelist; no user input is interpolated into
- * the shell command. RUNTIME_AVAILABLE is the local-machine gate (Vercel
- * never sets it, so cloud users can never reach the shell-out path).
- */
-import { NextRequest, NextResponse } from "next/server";
-import { exec } from "node:child_process";
-import { promisify } from "node:util";
-import { readJsonBody, z } from "@/lib/api/route-helpers";
-import { getApiUserId } from "@/lib/session";
-import { isRuntimeAvailable } from "@/lib/runtime";
-
-const execp = promisify(exec);
-
-const DaemonAction = z.object({
-  action: z.enum(["start", "restart", "stop", "status"]),
-});
-
-const DAEMON_UNIT = "fleetcrown-daemon.service";
-
-// Resolved unit is cached after the first lookup. systemd unit installation is
-// a one-time setup event; this cache stays valid for the life of the process.
-let _resolvedUnit: string | null = null;
-
-async function getUnit(): Promise {
-  if (_resolvedUnit) return _resolvedUnit;
-  try {
-    await execp(`systemctl --user cat ${DAEMON_UNIT}`, { timeout: 2000 });
-  } catch { /* default to canonical so errors reference the only supported unit */ }
-  _resolvedUnit = DAEMON_UNIT;
-  return _resolvedUnit;
-}
-
-async function systemctlState(): Promise<"active" | "inactive" | "failed" | "unknown"> {
-  try {
-    const { stdout } = await execp(`systemctl --user is-active ${await getUnit()}`, { timeout: 5000 });
-    const s = stdout.trim();
-    if (s === "active" || s === "inactive" || s === "failed") return s;
-    return "unknown";
-  } catch (e: unknown) {
-    const stdout = (e as { stdout?: string })?.stdout?.toString().trim();
-    if (stdout === "inactive" || stdout === "failed") return stdout;
-    return "unknown";
-  }
-}
-
-export async function GET() {
-  if (!isRuntimeAvailable()) {
-    return NextResponse.json({ error: "Daemon control unavailable on cloud — runs only on the local install." }, { status: 403 });
-  }
-  const userId = await getApiUserId();
-  if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
-  const state = await systemctlState();
-  return NextResponse.json({ state, unit: await getUnit() });
-}
-
-export async function POST(req: NextRequest) {
-  if (!isRuntimeAvailable()) {
-    return NextResponse.json({
-      error: "Daemon control unavailable on cloud — runs only on the local install. Start the daemon from your machine.",
-    }, { status: 403 });
-  }
-  const userId = await getApiUserId();
-  if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
-
-  const dataOrResp = await readJsonBody(req, DaemonAction);
-  if (dataOrResp instanceof NextResponse) return dataOrResp;
-
-  const { action } = dataOrResp;
-  const unit = await getUnit();
-
-  // "status" is just a GET in POST clothing — no side effect.
-  if (action === "status") {
-    return NextResponse.json({ state: await systemctlState(), unit });
-  }
-
-  try {
-    await execp(`systemctl --user ${action} ${unit}`, { timeout: 10000 });
-    // systemctl returns immediately; give the unit a beat to settle so the
-    // state we report back is post-action, not pre-action.
-    await new Promise((r) => setTimeout(r, 800));
-    const state = await systemctlState();
-    return NextResponse.json({ ok: true, action, state, unit });
-  } catch (e: unknown) {
-    const message = e instanceof Error ? e.message : String(e);
-    return NextResponse.json({
-      ok: false,
-      error: `systemctl ${action} ${unit} failed: ${message}`,
-      state: await systemctlState(),
-    }, { status: 500 });
-  }
-}
diff --git a/src/app/api/system/doctor/route.ts b/src/app/api/system/doctor/route.ts
index 283181e5f..c5d07c5c7 100644
--- a/src/app/api/system/doctor/route.ts
+++ b/src/app/api/system/doctor/route.ts
@@ -83,7 +83,13 @@ export async function GET() {
 
   const checks: DoctorCheck[] = [];
 
-  for (const unit of ["fleetcrown-app.service", "fleetcrown-beacon-window.service", "fleetcrown-daemon.service"]) {
+  // Session 4 of killing-the-bash-daemon: only the local Next.js prod wrapper
+  // remains as a FleetCrown systemd unit. Fleet Runner desktop is a regular
+  // Electron app the user launches from their tray menu — it has no
+  // systemd unit to probe (its process tree appears under app-fleet-
+  // runner@.service if the user enabled systemd integration, but that's
+  // an OS-level convenience, not a FleetCrown surface).
+  for (const unit of ["fleetcrown-app.service"]) {
     try {
       const [active, enabled] = await Promise.all([
         shell(`systemctl --user is-active ${unit}`).catch(() => "inactive"),
@@ -109,16 +115,25 @@ export async function GET() {
     legacyUnits ? legacyUnits.split("\n").slice(0, 3).join("; ") : "No active unit files listed.",
   ));
 
+  // Session 4 of killing-the-bash-daemon retired the bash bridge that the
+  // Stop hook used to exec. The hook is now expected to be a no-op (or
+  // absent) — Fleet Runner's embedded watcher (home/watcher.ts) detects the
+  // status:ready transition by filesystem mtime and triggers dispatch via
+  // its own TS module (desktop/src/main/dispatch.ts). A hook that still
+  // points at the deleted bridge is broken; flag it.
   const stopHook = `${homedir()}/.claude/hooks/stop.sh`;
-  const notificationHook = `${homedir()}/.claude/hooks/notification.sh`;
-  const hookTarget = ".local/share/fleetcrown-beacon/agent-hook-bridge.sh";
-  const stopOk = existsSync(stopHook) && readFileSync(stopHook, "utf8").includes(hookTarget);
-  const notificationOk = existsSync(notificationHook) && readFileSync(notificationHook, "utf8").includes(hookTarget);
+  const deadBridgeTarget = ".local/share/fleetcrown-beacon/agent-hook-bridge.sh";
+  const stopExists = existsSync(stopHook);
+  const stopReferencesDeadBridge = stopExists && readFileSync(stopHook, "utf8").includes(deadBridgeTarget);
   checks.push(check(
     "hooks",
-    "Claude hooks",
-    stopOk && notificationOk ? "pass" : "fail",
-    stopOk && notificationOk ? "stop and notification hooks target FleetCrown." : "One or more hooks do not target the FleetCrown bridge.",
+    "Claude Stop hook",
+    !stopReferencesDeadBridge ? "pass" : "fail",
+    !stopExists
+      ? "No stop.sh installed — Fleet Runner's filesystem watcher triggers dispatch instead."
+      : stopReferencesDeadBridge
+        ? "stop.sh still points at the retired bash bridge — rewrite to `exit 0` or remove the file entirely."
+        : "stop.sh is a no-op (correct post-migration state).",
   ));
 
   const token = readTokenFile();
diff --git a/src/components/control/DaemonControls.tsx b/src/components/control/DaemonControls.tsx
deleted file mode 100644
index e93086752..000000000
--- a/src/components/control/DaemonControls.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-"use client";
-
-/**
- * One-click daemon lifecycle controls for the local install (RUNTIME_AVAILABLE=true).
- * Solves the recurring "daemon offline, no UI to recover" complaint surfaced
- * 2026-05-31: until now the only way to start the helper after a crash/sleep
- * was a terminal command, which broke the "fleet control" value prop.
- *
- * Cloud users see a disabled tooltip — there's no remote daemon to control.
- */
-import { useState } from "react";
-import { Play, RotateCw, Square, Loader2, Check, AlertTriangle } from "lucide-react";
-import { postJson } from "@/lib/api/fetch";
-
-type DaemonState = "active" | "inactive" | "failed" | "unknown";
-
-export function DaemonControls({
-  runtimeAvailable,
-  currentState,
-  onAfter,
-}: {
-  /** True on local installs only — cloud renders disabled buttons. */
-  runtimeAvailable: boolean;
-  /** Pre-fetched state to label the primary action correctly (Start vs Restart). */
-  currentState: DaemonState;
-  /** Caller refreshes its view after an action lands. */
-  onAfter?: () => void;
-}) {
-  const [busy, setBusy] = useState(null);
-  const [outcome, setOutcome] = useState(null);
-
-  const act = async (action: "start" | "restart" | "stop") => {
-    setBusy(action);
-    setOutcome(null);
-    try {
-      const res = await postJson("/api/system/daemon", { action });
-      const json = await res.json() as { ok?: boolean; state?: DaemonState; error?: string };
-      if (json.ok && json.state) {
-        setOutcome({ kind: "ok", state: json.state, action });
-        onAfter?.();
-      } else {
-        setOutcome({ kind: "error", message: json.error ?? `${action} failed` });
-      }
-    } catch (e) {
-      setOutcome({ kind: "error", message: e instanceof Error ? e.message : String(e) });
-    } finally {
-      setBusy(null);
-    }
-  };
-
-  const cloudTooltip = "Daemon control runs on your local install only — the cloud has no helper process to start.";
-  const disabled = !runtimeAvailable;
-  const startLabel = currentState === "active" ? "Running" : "Start daemon";
-
-  return (
-    
- - - - - - - {outcome?.kind === "ok" && ( - - {outcome.action} → {outcome.state} - - )} - {outcome?.kind === "error" && ( - - failed - - )} -
- ); -} diff --git a/src/components/control/DaemonStatusBanner.tsx b/src/components/control/DaemonStatusBanner.tsx index 4cb4a0a3e..cb235d2da 100644 --- a/src/components/control/DaemonStatusBanner.tsx +++ b/src/components/control/DaemonStatusBanner.tsx @@ -6,7 +6,6 @@ import { X, Radio, WifiOff, Sparkles, Download, Terminal, Cpu, Loader2 } from "l import { timeAgo } from "@/lib/dates"; import { APP_NAME } from "@/config/brand"; import { getJson, postJson } from "@/lib/api/fetch"; -import { DaemonControls } from "./DaemonControls"; import "@/components/desktop/types"; // declare global window.fleetRunner type DaemonState = "active" | "inactive" | "failed" | "unknown"; @@ -34,7 +33,6 @@ export function DaemonStatusBanner({ onRefresh, }: Props) { const [dismissed, setDismissed] = useState(false); - const [unitState, setUnitState] = useState("unknown"); // Detect Fleet Runner so we can short-circuit the "Install Fleet Runner" // CTA and replace it with a one-click "Pair this app" button when the // user is already running inside the desktop shell. @@ -43,17 +41,6 @@ export function DaemonStatusBanner({ const [pairError, setPairError] = useState(null); const [pairedTokenLabel, setPairedTokenLabel] = useState(null); - // Probe systemd unit state on mount + after every successful control - // action. Decoupled from daemonOffline (which is "is the daemon pushing - // updates?") so the button labels reflect whether the unit is loaded but - // not pushing vs truly stopped. Local-only — cloud 403s the GET. - useEffect(() => { - if (!runtimeAvailable) return; - getJson<{ state: DaemonState }>("/api/system/daemon") - .then((r) => setUnitState(r.state)) - .catch(() => setUnitState("unknown")); - }, [runtimeAvailable]); - useEffect(() => { setInsideFleetRunner(typeof window !== "undefined" && !!window.fleetRunner); }, []); @@ -100,9 +87,6 @@ export function DaemonStatusBanner({ : null; const refreshAfterAction = () => { - getJson<{ state: DaemonState }>("/api/system/daemon") - .then((r) => setUnitState(r.state)) - .catch(() => {}); onRefresh?.(); }; @@ -243,24 +227,18 @@ export function DaemonStatusBanner({

The helper on your computer stopped sending updates. All agent commands are safely queued until it reconnects.

- - {!runtimeAvailable && ( -
-

- You're on the cloud install — daemon control runs only from your local machine. - Open {APP_NAME} at http://localhost:3000 to start/restart the helper. -

-

- Token expired or migrated DB?{" "} - Mint a fresh ck_* token{" "} - and re-paste it into Fleet Runner / your CLI installer. -

-
- )} +
+

+ Launch Fleet Runner from your tray / app menu to bring it back online. Closed it by accident?{" "} + Re-install Fleet Runner + {" "}or check its log for the connection error. +

+

+ Token expired or migrated DB?{" "} + Mint a fresh ck_* token{" "} + and re-paste it into Fleet Runner. +

+
)} diff --git a/src/hooks/use-control-data.ts b/src/hooks/use-control-data.ts index 42643fc02..382b7e816 100644 --- a/src/hooks/use-control-data.ts +++ b/src/hooks/use-control-data.ts @@ -223,63 +223,13 @@ export function useControlData(): ControlDataHook { return () => clearTimeout(id); }, [lastTabResultsAt]); - // Try the same-machine fast path first: when the user's home/ daemon is - // listening on localhost:3001, route inject directly there and skip - // Vercel + Postgres + daemon-polling (7 hops → 3). The fast path needs a - // resolved customPrompt; promptKey-only dispatches still go cloud-side - // where the key→prompt resolver lives. - // - // Failure modes that fall through to the cloud path: - // - no daemon (connection refused / DNS / timeout) - // - daemon responded {ok:false} — the reason already carries the - // actionable detail; we re-throw it so the caller can render it - // without a cloud round-trip - // - dispatch carries only a promptKey (no resolved text) — local - // daemon can't expand it without the cloud prompt registry - const tryLocalInject = async (tab: string, customPrompt: string): Promise<{ ok: true } | { ok: false; reason: string } | null> => { - if (typeof window === "undefined") return null; - try { - const ctrl = new AbortController(); - const timer = setTimeout(() => ctrl.abort(), 600); - const r = await fetch("http://127.0.0.1:3001/api/inject", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ project: tab, prompt: customPrompt }), - signal: ctrl.signal, - }); - clearTimeout(timer); - if (!r.ok) return null; - const body = await r.json().catch(() => null); - if (!body || typeof body !== "object") return null; - if (body.ok === true) return { ok: true }; - if (body.ok === false && typeof body.reason === "string") return { ok: false, reason: body.reason }; - return null; - } catch { - // No local daemon (most common case for cloud-only users), or it timed - // out. Either way, cloud path takes over silently. - return null; - } - }; - const inject = async (tab: string, promptKey?: string, customPrompt?: string): Promise<{ mode: "direct" | "queued" }> => { - // Local fast path: only fires when we have resolved prompt text (no - // promptKey-only dispatch) AND no per-card adapter override beyond the - // default — the local daemon picks the running adapter by process scan. - if (customPrompt && !promptKey) { - const localResult = await tryLocalInject(tab, customPrompt); - if (localResult?.ok === true) { - setTimeout(refresh, REFRESH_AFTER_DISPATCH_MS); - return { mode: "direct" }; - } - if (localResult?.ok === false) { - // The reason is the same actionable string the cloud path would - // eventually surface — throwing here saves the cloud round-trip - // when we already know exactly what went wrong. - throw new Error(localResult.reason); - } - // Fall through to cloud — local daemon unreachable or non-JSON reply. - } - + // Same-machine fast path (POST localhost:3001/api/inject → home/server.ts + // → bash inject_prompt) was retired in Session 4 of killing-the-bash- + // daemon (2026-06-11). Every inject now goes through the cloud + // /api/inject endpoint; Fleet Runner desktop polls /api/control/commands + // and types the resulting prompt into zellij. Same end-state, one + // transport instead of two, no bash anywhere. const res = await postJson("/api/inject", { tab, promptKey, customPrompt, adapter: data?.agentConfig.agent ?? selectedAgent }); if (!res.ok) await throwApiError(res, `HTTP ${res.status}`); const body = await res.json().catch(() => ({}));