Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

5.1 KB
Raw Blame
"use client";

import { useMemo, useRef } from "react";
import { matchDestructive, useOsApi } from "../lib/host";
import type { AiTool, ToolInvocation, ToolOutcome } from "../lib/host";
import { useApps } from "@/features/appshell";
import {
  type ToolCard,
  alfaRunState,
  alfaProjectContext,
  alfaApprovalScope,
  alfaApprovalKey,
  hasAlfaApproval,
  rememberAlfaApproval,
} from "@/features/appshell/alfa";
import { findHostTool, HOST_AI_TOOLS } from "./registry";
import { recordAlfaTool } from "../lib/alfa-activity";

// The chat panel supplies these so the binding can render each call as a card and
// park on an approval decision for mutate tools.
export type HostToolUi = {
  pushCard: (id: string, card: ToolCard) => void;
  updateCard: (id: string, patch: Partial<ToolCard>) => void;
  /** Resolves when the user clicks Approve/Deny on that card. */
  requestApproval: (id: string) => Promise<{ approve: boolean; remember: boolean }>;
};

// Binds the host-tool catalog to the LIVE OsApi + the approval gate. Returns the
// tool schemas (for the AI request) + `invoke`, which the agent loop calls per
// tool_use. Read tools run immediately; mutate tools push a pending card and
// await the user's decision. Denials (and unknown/failed tools) come back as a
// crash-free failed outcome so the model reads the message and adapts. The
// gate here is an ADDITIONAL human layer over the server's auth + jail + audit —
// not the security boundary.
export function useHostCommands(ui: HostToolUi): {
  tools: AiTool[];
  invoke: (call: ToolInvocation) => Promise<ToolOutcome>;
} {
  const api = useOsApi();
  const apps = useApps();
  const denied = useRef<Set<string>>(new Set());
  const seq = useRef(0);
  return useMemo(
    () => ({
      tools: HOST_AI_TOOLS,
      invoke: async ({ name, input }) => {
        const tool = findHostTool(name);
        const id = `hc${seq.current++}`;
        const args = input ?? {};
        const scope = alfaApprovalScope(alfaProjectContext()?.path, api.mode);
        if (alfaRunState()?.status === "stopped") return { ok: false, result: "Stopped before execution." };
        const startedAt = Date.now();
        if (!tool) {
          const msg = `unknown tool "${name}"`;
          ui.pushCard(id, { name, effect: "mutate", input: args, status: "error", result: msg });
          recordAlfaTool(id, name, "failed", msg, Date.now() - startedAt);
          return { ok: false, result: msg };
        }
        const execute = async (): Promise<ToolOutcome> => {
          if (alfaRunState()?.status === "stopped") return { ok: false, result: "Stopped before execution." };
          ui.updateCard(id, { status: "running" });
          recordAlfaTool(id, name, "started");
          try {
            const result = await tool.run(api, args, { apps });
            ui.updateCard(id, { status: "ok", result });
            recordAlfaTool(id, name, "completed", undefined, Date.now() - startedAt);
            return { ok: true, result };
          } catch (e) {
            const msg = e instanceof Error ? e.message : "tool failed";
            ui.updateCard(id, { status: "error", result: msg });
            recordAlfaTool(id, name, "failed", msg, Date.now() - startedAt);
            return { ok: false, result: msg };
          }
        };

        if (tool.effect === "read") {
          ui.pushCard(id, { name, effect: "read", input: args, status: "running" });
          return execute();
        }

        // mutate → approval gate.
        const danger = name === "exec.run" ? matchDestructive(String(args.cmd ?? "")) ?? undefined : undefined;
        const sig = alfaApprovalKey(name, args, scope);
        ui.pushCard(id, { name, effect: "mutate", input: args, status: "pending", danger, approvalScope: scope });
        recordAlfaTool(id, name, "started", "waiting for approval");
        if (denied.current.has(sig)) {
          ui.updateCard(id, { status: "denied", result: "Auto-denied (already declined this exact call)." });
          recordAlfaTool(id, name, "denied", "auto-denied", Date.now() - startedAt);
          return { ok: false, result: "Auto-denied: the user already declined this exact call. Stop retrying it. Propose an alternative or ask." };
        }
        if (!danger && hasAlfaApproval(name, args, scope)) return execute();
        const { approve, remember } = await ui.requestApproval(id);
        if (!approve) {
          denied.current.add(sig);
          ui.updateCard(id, { status: "denied", result: "Denied by the user." });
          recordAlfaTool(id, name, "denied", "denied by user", Date.now() - startedAt);
          return { ok: false, result: "Denied by the user. Do not retry this exact call; propose an alternative or ask what they'd prefer." };
        }
        if (scope !== alfaApprovalScope(alfaProjectContext()?.path, api.mode) || alfaRunState()?.status === "stopped") {
          ui.updateCard(id, { status: "denied", result: "Stopped or approval scope changed. Send a new request." });
          return { ok: false, result: "Stopped or approval scope changed." };
        }
        if (remember && !danger) rememberAlfaApproval(name, args, scope);
        return execute();
      },
    }),
    [api, apps, ui],
  );
}