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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
import { requireWorkflowScope, workflowExecutionContext } from "./graph-authority";
import { liveCapabilityContext } from "@/lib/capabilities/live-authority";
import path from "node:path";
import { promises as fs } from "node:fs";
import { capabilityReportedFailure } from "@/lib/capabilities/result-outcome";
import { executeCapabilityCall } from "@/lib/capabilities/execute";
import { isCapabilityDirectResult, type CapabilityRunContext, type CapabilityTool } from "@/lib/capabilities/tool";
import { boundedResultText } from "@/lib/capabilities/result-budget";
import { resolveProjectHint } from "@/lib/host/projects-api";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphRun, WorkflowGraphRunNode } from "@/lib/contracts/workflow-graph";
import { graphObject } from "./graph-schema";
import { bindLoopItem, bindWorkflowValue } from "./graph-bindings";
import { executeFlowNode, workflowItems, type FlowNodeResult } from "./graph-flow-nodes";
import { workflowVariableValues } from "./variables";
import { organizationTargetDigest, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";
import { workflowCacheDelete, workflowCacheGet, workflowCacheSet } from "./cache-store";
import { deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "./data-table-store";
import { repeatWorkflow, runWorkflowGraphChild } from "./graph-repeat";
type Resolver = (name: string) => CapabilityTool | undefined;
type NodeExecutionResult = FlowNodeResult;
const BLOCKED_TOOL_NODES = new Set(["workflow_start", "workflow_finish", "workflow_cancel", "flow_run", "flow_status", "workflow_graph"]);
function compact(value: unknown): unknown {
try { return JSON.parse(boundedResultText(typeof value === "string" ? { text: value } : value, { maxTextBytes: 12 * 1024, overflowHint: "Open the underlying project/tool result for full details." })); }
catch { return { text: String(value).slice(0, 12_000) }; }
}
function resultData(result: unknown): unknown {
if (capabilityReportedFailure(result)) throw new Error("downstream tool reported an error");
if (!isCapabilityDirectResult(result)) return result;
if (result.isError) throw new Error("downstream tool reported an error");
if (result.structuredContent) return result.structuredContent;
const text = result.content.filter((item) => item.type === "text").map((item) => item.text).join("\n");
try { return JSON.parse(text); } catch { return { text }; }
}
async function callTool(name: string, args: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<unknown> {
context = await workflowExecutionContext(context);
const tool = resolve(name); if (!tool) throw new Error(`workflow tool unavailable: ${name}`);
context = await liveCapabilityContext(context, name, args);
const outcome = await executeCapabilityCall({ tool, args, scope: context.scope, actor: context.actor, context });
if (outcome.kind !== "success") throw new Error(outcome.message); return resultData(outcome.result);
}
async function resolvedProject(hint: unknown): Promise<{ id: string; name: string; path: string; matchedBy: string }> {
if (typeof hint !== "string" || !hint) throw new Error("project node requires config.project");
const project = await resolveProjectHint(hint); if (!project || project.matchedBy === "fuzzy") throw new Error("project node requires an exact resolvable project");
return { id: project.id, name: project.name, path: project.path, matchedBy: project.matchedBy };
}
async function loopTool(config: Record<string, unknown>, runtime: unknown, context: CapabilityRunContext, resolve: Resolver) {
const tool = typeof config.tool === "string" ? config.tool : ""; if (!tool || BLOCKED_TOOL_NODES.has(tool)) throw new Error("loop node requires a bounded tool");
const all = workflowItems(config, runtime), concurrency = Math.max(1, Math.min(4, Math.trunc(Number(config.concurrency) || 1))), results: unknown[] = [];
for (let start = 0; start < all.length; start += concurrency) {
const batch = all.slice(start, start + concurrency);
results.push(...await Promise.all(batch.map(async (item, offset) => {
const args = bindLoopItem(graphObject(config.arguments) ? config.arguments : {}, item, start + offset) as Record<string, unknown>;
if (context.workflowId) args.workflow_id = context.workflowId; return callTool(tool, args, context, resolve);
})));
}
return { output: { count: all.length, results }, log: `Looped ${all.length} item(s) through ${tool}.` };
}
async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph: WorkflowGraph, graphInput: Record<string, unknown>, outputs: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<NodeExecutionResult> {
const runtime = { input: graphInput, trigger: run.trigger, nodes: Object.fromEntries(Object.entries(outputs).map(([id, output]) => [id, { output }])), graph: { id: graph.id, name: graph.name, metadata: graph.metadata } };
const principal = context.principal ?? context.actor; if (!principal) throw new Error("workflow node requires principal");
const config = bindWorkflowValue(node.config, runtime, await workflowVariableValues(principal)) as Record<string, unknown>;
context = await workflowExecutionContext(context);
if (node.type === "channel_send") requireWorkflowScope(context, "exec");
if (node.type === "data_table" && ["insert", "update", "delete"].includes(String(config.mode))) requireWorkflowScope(context, "write");
if (node.type === "cache" && ["set", "get_or_set", "delete"].includes(String(config.mode))) requireWorkflowScope(context, "write");
const project = typeof config.project === "string" ? config.project : graph.metadata.project;
if (["manual", "schedule", "webhook", "channel_trigger"].includes(node.type)) return { output: graphInput, log: `${node.type} trigger accepted.` };
if (node.type === "project") return { output: await resolvedProject(config.project ?? project), log: "Canonical project resolved at runtime." };
if (node.type === "folder") {
const resolved = await resolvedProject(config.project ?? project), relative = typeof config.path === "string" ? config.path : ".", target = path.resolve(resolved.path, relative), root = resolved.path.endsWith(path.sep) ? resolved.path : resolved.path + path.sep;
if (target !== resolved.path && !target.startsWith(root)) throw new Error("folder node path escapes project root"); const stat = await fs.stat(target); if (!stat.isDirectory()) throw new Error("folder node target is not a directory");
return { output: { project: resolved.id, path: target, relativePath: path.relative(resolved.path, target) || "." }, log: "Folder resolved inside the canonical project root." };
}
if (node.type === "skill") { const query = typeof config.query === "string" ? config.query : typeof config.key === "string" ? config.key : node.name; return { output: await callTool("skills_search", { query, top_k: Number(config.top_k) || 8, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Skill catalog queried with provenance/trust metadata." }; }
if (node.type === "knowledge") {
if (!project) throw new Error("knowledge node requires project binding");
if (typeof config.query === "string" && config.query) return { output: await callTool("project_memory_search", { project, query: config.query, limit: Number(config.limit) || 8, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Project memory queried." };
return { output: await callTool("project_knowledge_get", { project, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Project knowledge resolved." };
}
if (node.type === "data_table") {
const mode = typeof config.mode === "string" ? config.mode : "list";
if (mode === "list") return { output: { tables: await listWorkflowDataTables(principal) }, log: "Workflow data tables listed." };
const tableId = typeof config.tableId === "string" ? config.tableId : "";
if (!tableId) throw new Error("data_table node requires config.tableId");
if (mode === "get") return { output: await getWorkflowDataTable(principal, tableId), log: "Workflow data table read." };
if (mode === "insert" || mode === "update") {
const values = graphObject(config.values) ? config.values : graphInput;
const rowId = mode === "update" ? String(config.rowId ?? "") : undefined;
if (mode === "update" && !rowId) throw new Error("data_table update requires config.rowId");
return { output: await upsertWorkflowDataTableRow(principal, tableId, rowId, values), log: `Workflow data-table row ${mode === "insert" ? "inserted" : "updated"}.` };
}
if (mode === "delete") {
const rowId = String(config.rowId ?? ""); if (!rowId) throw new Error("data_table delete requires config.rowId");
return { output: await deleteWorkflowDataTableRow(principal, tableId, rowId), log: "Workflow data-table row deleted." };
}
throw new Error("data_table node mode must be list, get, insert, update, or delete");
}
if (node.type === "cache") {
const key = typeof config.key === "string" ? config.key : `${graph.id}:${node.id}`;
const mode = typeof config.mode === "string" ? config.mode : "get";
if (mode === "delete") return { output: await workflowCacheDelete(principal, key), log: `Cache ${key} deleted.` };
if (mode === "get") return { output: await workflowCacheGet(principal, key), log: `Cache ${key} read.` };
if (mode === "get_or_set") {
const hit = await workflowCacheGet(principal, key); if (hit.hit) return { output: hit, log: `Cache ${key} hit.` };
const stored = await workflowCacheSet(principal, key, Object.hasOwn(config, "value") ? config.value : graphInput, Number(config.ttlSeconds) || 300);
return { output: { ...stored, cacheMiss: true }, log: `Cache ${key} populated.` };
}
if (mode === "set") return { output: await workflowCacheSet(principal, key, Object.hasOwn(config, "value") ? config.value : graphInput, Number(config.ttlSeconds) || 300), log: `Cache ${key} stored.` };
throw new Error("cache node mode must be get, set, get_or_set, or delete");
}
if (node.type === "memory") {
const scope = config.scope === "project" ? "project" : "agent", mode = typeof config.mode === "string" ? config.mode : "search";
if (scope === "project") {
if (!project) throw new Error("project memory node requires project binding");
if (mode === "search") return { output: await callTool("project_memory_search", { project, query: String(config.query ?? ""), limit: Number(config.limit) || 8 }, context, resolve), log: "Project memory searched." };
if (mode === "remember") return { output: await callTool("project_memory_upsert", { project, kind: String(config.kind ?? "decision"), title: String(config.title ?? node.name), summary: String(config.value ?? config.summary ?? ""), source: "automation" }, context, resolve), log: "Project memory persisted." };
throw new Error("project memory node supports search or remember");
}
if (mode === "read") return { output: await callTool("agent_memory_read", {}, context, resolve), log: "Agent memory read." };
if (mode === "search") return { output: await callTool("agent_memory_search", { query: String(config.query ?? ""), limit: Number(config.limit) || 12, ...(typeof config.document === "string" && config.document ? { document: config.document } : {}) }, context, resolve), log: "Agent memory searched." };
if (mode === "remember") return { output: await callTool("agent_memory_remember", { document: String(config.document ?? "MEMORY.md"), key: String(config.key ?? node.id), value: String(config.value ?? ""), kind: String(config.kind ?? "procedural"), mode: String(config.writeMode ?? "replace") }, context, resolve), log: "Agent memory persisted." };
if (mode === "forget") return { output: await callTool("agent_memory_forget", { document: String(config.document ?? "MEMORY.md"), key: String(config.key ?? "") }, context, resolve), log: "Agent memory forgotten." };
throw new Error("agent memory node mode must be read, search, remember, or forget");
}
if (node.type === "session") {
const mode = typeof config.mode === "string" ? config.mode : "current";
if (mode === "current") return { output: await callTool("agent_session_current", {}, context, resolve), log: "Current durable session resolved." };
if (mode === "list") return { output: await callTool("agent_sessions_list", { limit: Number(config.limit) || 20 }, context, resolve), log: "Durable sessions listed." };
if (mode === "resume") return { output: await callTool("agent_session_resume", { session_ref: String(config.sessionRef ?? config.sessionId ?? "") }, context, resolve), log: "Session resume packet loaded." };
if (mode === "note") return { output: await callTool("agent_session_note", { note: String(config.note ?? "") }, context, resolve), log: "Session note saved." };
throw new Error("session node mode must be current, list, resume, or note");
}
if (node.type === "directory") {
const source = typeof config.source === "string" ? config.source : "tools", query = String(config.query ?? "").toLowerCase().trim();
if (source === "tools") {
const tools = (context.capabilities?.list(context.scope) ?? []).filter((tool) => !context.allowedTools || context.allowedTools.includes(tool.name));
return { output: { tools: tools.filter((tool) => !query || `${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query)).slice(0, Math.max(1, Math.min(100, Number(config.limit) || 50))) }, log: "MSO capability directory queried." };
}
if (source === "workflows") { const { listWorkflowGraphs } = await import("./graph-store"); const rows = await listWorkflowGraphs(principal); return { output: { workflows: rows.filter((row) => !query || `${row.name} ${row.description} ${(row.metadata.tags ?? []).join(" ")}`.toLowerCase().includes(query)).map((row) => ({ id: row.id, name: row.name, status: row.status, updatedAt: row.updatedAt, nodes: row.nodes.length })) }, log: "Workflow directory queried." }; }
if (source === "sessions") return { output: await callTool("agent_sessions_list", { limit: Number(config.limit) || 30 }, context, resolve), log: "Session directory queried." };
if (source === "projects") return { output: await callTool("projects_list", { query: String(config.query ?? "") }, context, resolve), log: "Project directory queried." };
if (source === "skills") return { output: await callTool("skills_search", { query: String(config.query ?? node.name), top_k: Number(config.limit) || 12 }, context, resolve), log: "Skill directory queried." };
throw new Error("directory node source must be tools, workflows, sessions, projects, or skills");
}
const flow = await executeFlowNode(node, config, graph, outputs, runtime); if (flow) return flow;
if (node.type === "output") return { output: Object.hasOwn(config, "value") ? config.value : { nodes: outputs }, log: "Workflow output collected." };
if (node.type === "loop") return loopTool(config, runtime, context, resolve);
if (node.type === "repeat") return repeatWorkflow(config, run, graph, context, resolve);
if (node.type === "tool") {
const tool = typeof config.tool === "string" ? config.tool : ""; if (!tool || BLOCKED_TOOL_NODES.has(tool)) throw new Error("tool node requires a bounded non-workflow tool");
const args = graphObject(config.arguments) ? structuredClone(config.arguments) : {}; if (context.workflowId) args.workflow_id = context.workflowId;
return { output: await callTool(tool, args, context, resolve), log: `Tool ${tool} completed.` };
}
if (node.type === "channel_send") {
if (typeof config.channelId !== "string" || !config.channelId) throw new Error("channel_send node requires channelId");
if (typeof config.text !== "string" || !config.text) throw new Error("channel_send node requires text");
const { sendChannelText } = await import("@/lib/channels");
return { output: await sendChannelText(config.channelId, { text: config.text, ...(typeof config.target === "string" && config.target ? { target: config.target } : {}) }), log: "Channel message sent." };
}
if (node.type === "integration") {
for (const key of ["user", "provider", "connection", "operation"]) if (typeof config[key] !== "string" || !config[key]) throw new Error(`integration node requires ${key}`);
const args = { user: config.user, provider: config.provider, connection: config.connection, operation: config.operation, ...(typeof config.tool === "string" ? { tool: config.tool } : {}), ...(graphObject(config.arguments) ? { arguments: config.arguments } : {}), ...(config.confirm === true ? { confirm: true } : {}), ...(context.workflowId ? { workflow_id: context.workflowId } : {}) };
return { output: await callTool("integration_execute", args, context, resolve), log: `Integration ${config.provider}/${config.connection} completed.` };
}
if (node.type === "project_function") { if (!project || typeof config.name !== "string") throw new Error("project_function node requires project and name"); return { output: await callTool("project_function_call", { project, name: config.name, input: graphObject(config.input) ? config.input : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project function ${config.name} completed.` }; }
if (node.type === "project_mcp") { if (!project || typeof config.server !== "string" || typeof config.tool !== "string") throw new Error("project_mcp node requires project/server/tool"); return { output: await callTool("project_mcp_call", { project, server: config.server, tool: config.tool, arguments: graphObject(config.arguments) ? config.arguments : {}, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Project MCP ${config.server}.${config.tool} completed.` }; }
if (node.type === "script") { if (!project || typeof config.script_id !== "string") throw new Error("script node requires project and script_id"); return { output: await callTool("project_script_run", { project, script_id: config.script_id, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Script ${config.script_id} completed.` }; }
if (node.type === "agent") {
if (typeof config.message !== "string" || !config.message.trim()) throw new Error("agent node requires message");
if (typeof config.sessionRef === "string" && config.sessionRef.trim()) {
const { runDurableSessionTurn } = await import("@/lib/agent/session-turn");
return { output: await runDurableSessionTurn({ principal, sessionRef: config.sessionRef.trim(), objective: config.message, capabilities: context.capabilities, authority: context, persist: true }), log: `Durable agent turn completed for session ${config.sessionRef.trim()}.` };
}
if (typeof config.orgSeatId === "string" && config.orgSeatId) {
const seat = await resolveOrganizationSeat(config.orgSeatId), target = seat.target;
if (config.orgTargetDigest !== organizationTargetDigest(seat)) throw new Error("organization execution binding changed; review and save the workflow before running it");
if (seat.state !== "active" || seat.seatMode === "inactive") throw new Error(`organization seat ${seat.title} is not active`);
if (target.kind === "project-agent") { const args: Record<string, unknown> = { project: target.project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" }; if (context.workflowId) args.workflow_id = context.workflowId; return { output: await callTool("project_agent_run", args, context, resolve), log: `Organization seat ${seat.title} routed to project agent.` }; }
if (target.kind === "local-agent") return { output: await callTool("local_agent_request", { target: target.ref, objective: config.message, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Organization seat ${seat.title} routed to local agent.` };
if (target.kind === "a2a") return { output: await callTool("a2a_handoff", { target: target.ref, objective: config.message, return_immediately: config.wait === false, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: `Organization seat ${seat.title} routed to A2A agent.` };
throw new Error(`organization seat ${seat.title} has no execution target`);
}
if (!project) throw new Error("agent node requires project or organization seat");
const args: Record<string, unknown> = { project, message: config.message, wait: config.wait !== false, plan_mode: Boolean(config.plan_mode), max_scope: ["read", "write", "exec"].includes(String(config.max_scope)) ? config.max_scope : "write" }; if (context.workflowId) args.workflow_id = context.workflowId; return { output: await callTool("project_agent_run", args, context, resolve), log: "Project agent action completed." };
}
if (node.type === "subflow") {
if (typeof config.workflowId === "string" && config.workflowId) {
const { child, latest } = await runWorkflowGraphChild(
config.workflowId,
graphObject(config.input) ? config.input : {},
`${run.id}:${node.id}`,
run,
graph,
context,
resolve,
);
return { output: latest, log: `Workflow subflow ${child.name} completed.` };
}
if (!project || typeof config.flow !== "string") throw new Error("subflow node requires workflowId or project/flow"); const started = await callTool("flow_run", { project, flow: config.flow, input: graphObject(config.input) ? config.input : {}, idempotency_key: `${run.id}:${node.id}`, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve) as Record<string, unknown>;
const runId = typeof started.id === "string" ? started.id : typeof started.run_id === "string" ? started.run_id : undefined; if (!runId) return { output: started, log: `Subflow ${config.flow} started.` };
let latest: unknown = started; for (let tries = 0; tries < 24; tries += 1) { latest = await callTool("flow_status", { run_id: runId, wait_ms: 25_000 }, context, resolve); if (graphObject(latest) && latest.state !== "running") break; }
if (graphObject(latest) && !["completed", "completed_with_errors"].includes(String(latest.state))) throw new Error(`subflow ${config.flow} did not complete successfully`); return { output: latest, log: `Subflow ${config.flow} completed.` };
}
throw new Error(`unsupported workflow node type: ${node.type}`);
}
export function nodeRuntimeView(row: WorkflowGraphRunNode): WorkflowGraphRunNode { return structuredClone(row); }
export { executeNode, compact };