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 { requireWorkflowReceiptAuthority, workflowExecutionContext } from "./graph-authority";
import { getApprovedDevice } from "@/lib/auth/device-store";
import { receiptRedactor } from "./receipt-redaction";
import { createHash, randomUUID } from "node:crypto";
import type { CapabilityRunContext, CapabilityTool } from "@/lib/capabilities/tool";
import type { WorkflowGraph, WorkflowGraphRun, WorkflowGraphRunEdgeState } from "@/lib/contracts/workflow-graph";
import { appendAgentSessionEvent } from "@/lib/agent/session-store";
import { redactText } from "@/lib/security/redact-text";
import { graphObject } from "./graph-schema";
import { workflowGraphOwner } from "./graph-store";
import { compact, executeNode } from "./graph-runtime";
import { lockWorkflowGraphRun, pruneWorkflowGraphRuns, publicWorkflowGraphRun, readWorkflowGraphRun, readWorkflowGraphScheduleClaim, writeWorkflowGraphRun } from "./graph-run-store";
import { workflowSecretValues } from "./variables";
const state = globalThis as typeof globalThis & { msoGraphInstance?: string; msoGraphPending?: Map<string, Promise<void>>; msoGraphCancelled?: Set<string> };
const INSTANCE = state.msoGraphInstance ??= randomUUID();
const pending = state.msoGraphPending ??= new Map<string, Promise<void>>();
const cancelled = state.msoGraphCancelled ??= new Set<string>();
type Resolver = (name: string) => CapabilityTool | undefined;
export type WorkflowRunTrigger = WorkflowGraphRun["trigger"];
function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }
function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (value && typeof value === "object") return `{${Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([k,v])=>`${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`; return JSON.stringify(value); }
function assertRuntimeInput(value: unknown, depth = 0): void {
if (depth > 14) throw new Error("workflow runtime input too deep");
if (Array.isArray(value)) { value.forEach((item) => assertRuntimeInput(item, depth + 1)); return; }
if (!graphObject(value)) return;
for (const [key, child] of Object.entries(value)) {
if (["__proto__", "constructor", "prototype"].includes(key)) throw new Error("workflow runtime input contains an unsafe key");
assertRuntimeInput(child, depth + 1);
}
}
function inputObject(raw: unknown): Record<string, unknown> { if (!graphObject(raw) || Buffer.byteLength(JSON.stringify(raw)) > 64 * 1024) throw new Error("workflow graph input must be an object up to 64 KiB"); assertRuntimeInput(raw); return structuredClone(raw); }
function retryPolicy(node: WorkflowGraph["nodes"][number]) { const raw = graphObject(node.config.retry) ? node.config.retry : {}; return { maxAttempts: Math.max(1, Math.min(5, Math.trunc(Number(raw.maxAttempts) || 1))), backoffMs: Math.max(0, Math.min(30_000, Math.trunc(Number(raw.backoffMs) || 0))) }; }
function sleep(ms:number){return ms?new Promise((resolve)=>setTimeout(resolve,ms)):Promise.resolve();}
async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<void> {
const rows = new Map(run.nodes.map((row) => [row.id, row])), outputs: Record<string, unknown> = {}, redactor = receiptRedactor(await workflowSecretValues(context.principal ?? context.actor ?? ""));
const activeEdges = graph.edges.filter((edge) => !edge.disabled);
const edgeState = new Map(graph.edges.map((edge) => [edge.id, edge.disabled ? "disabled" as WorkflowGraphRunEdgeState : run.edges?.find((row) => row.id === edge.id)?.state ?? "pending" as WorkflowGraphRunEdgeState]));
// Keep disabled incoming edges as disabled dependencies so a node whose only route is inactive is skipped, not promoted to a new root. Outgoing resolution touches active edges only.
const incoming = new Map(graph.nodes.map((node)=>[node.id,graph.edges.filter((edge)=>edge.target===node.id)])), outgoing = new Map(graph.nodes.map((node)=>[node.id,activeEdges.filter((edge)=>edge.source===node.id)]));
const setEdge=(id:string,state:WorkflowGraphRunEdgeState)=>{edgeState.set(id,state);const row=run.edges?.find((item)=>item.id===id);if(row)row.state=state;};
const disableOutgoing=(id:string)=>{for(const edge of outgoing.get(id)??[])if(edgeState.get(edge.id)==="pending")setEdge(edge.id,"disabled");};
const resolveOutgoing=(id:string,handles?:string[])=>{for(const edge of outgoing.get(id)??[]){const enabled=handles?Boolean(edge.sourceHandle&&handles.includes(edge.sourceHandle)):!edge.sourceHandle;setEdge(edge.id,enabled?"enabled":"disabled");}};
const sessionEvent=(state:string,detail:string)=>appendAgentSessionEvent(context.principal ?? context.actor ?? "",run.sessionId,{kind:"workflow",tool:"workflow_graph",state,workflowId:graph.id,detail}).catch(()=>undefined);
let handledErrors=false;
try {
const remaining=new Set(graph.nodes.map((node)=>node.id));
while(remaining.size){
if(cancelled.has(run.id)){run.state="interrupted";run.error="Stopped by user.";for(const pendingId of remaining){const queued=rows.get(pendingId);if(queued?.state==="queued"){queued.state="skipped";queued.logs.push("Skipped because the execution was stopped.");}}throw new Error(run.error);}
if(Date.now()-Date.parse(run.startedAt)>15*60_000)throw new Error("workflow graph exceeded 15 minutes; remaining nodes were not started");
let progressed=false;
for(const node of graph.nodes){
if(cancelled.has(run.id)){run.state="interrupted";run.error="Stopped by user.";for(const pendingId of remaining){const queued=rows.get(pendingId);if(queued?.state==="queued"){queued.state="skipped";queued.logs.push("Skipped because the execution was stopped.");}}throw new Error(run.error);}
if(!remaining.has(node.id))continue; const deps=incoming.get(node.id)??[]; if(deps.some((edge)=>edgeState.get(edge.id)==="pending"))continue; const row=rows.get(node.id)!;
const triggerNode=["manual","schedule","webhook","channel_trigger"].includes(node.type),triggerMismatch=Boolean(triggerNode&&run.trigger?.nodeId&&run.trigger.nodeId!==node.id);if(node.disabled||triggerMismatch||(deps.length>0&&deps.every((edge)=>edgeState.get(edge.id)==="disabled"))){row.state="skipped";row.finishedAt=new Date().toISOString();row.logs.push(node.disabled?"Node disabled by workflow definition.":triggerMismatch?"Skipped because another trigger started this run.":"Skipped because no incoming branch was selected.");disableOutgoing(node.id);remaining.delete(node.id);progressed=true;run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);continue;}
row.state="running";row.startedAt=new Date().toISOString();row.logs.push("Node started.");run.updatedAt=row.startedAt;await writeWorkflowGraphRun(run);await sessionEvent("running",`${node.name} · ${node.type}`); const started=Date.now(),policy=retryPolicy(node); let failure:unknown;
for(let attempt=1;attempt<=policy.maxAttempts;attempt+=1){row.attempts=attempt;try{const result=await executeNode(node,run,graph,input,outputs,context,resolve);row.output=compact(redactor.value(result.output));outputs[node.id]=result.output;row.state="completed";if(result.log)row.logs.push(result.log);resolveOutgoing(node.id,result.handles);failure=undefined;break;}catch(error){failure=error;row.logs.push(`Attempt ${attempt}/${policy.maxAttempts} failed: ${redactor.text(redactText(error instanceof Error?error.message:"node failed",500))}`);if(attempt<policy.maxAttempts)await sleep(Math.min(30_000,policy.backoffMs*Math.max(1,2**(attempt-1))));}}
if(failure){row.state="failed";row.error=redactor.text(redactText(failure instanceof Error?failure.message:"node failed",800));outputs[node.id]={error:row.error};const errorEdges=(outgoing.get(node.id)??[]).filter((edge)=>edge.sourceHandle==="error"),continueOnError=node.config.onError==="continue";if(errorEdges.length||continueOnError){handledErrors=true;resolveOutgoing(node.id,errorEdges.length?["error"]:undefined);row.logs.push(errorEdges.length?"Failure routed through error output.":"Failure continued by node policy.");}else{run.failedNodeId=node.id;run.failedNodeName=node.name;run.error=row.error;run.state="failed";for(const pendingId of remaining){if(pendingId===node.id)continue;const blocked=rows.get(pendingId)!;if(blocked.state==="queued"){blocked.state="blocked";blocked.logs.push(`Blocked by failed node ${node.name}.`);}}row.durationMs=Date.now()-started;row.finishedAt=new Date().toISOString();run.updatedAt=row.finishedAt;await writeWorkflowGraphRun(run);throw failure;}}
row.durationMs=Date.now()-started;row.finishedAt=new Date().toISOString();run.updatedAt=row.finishedAt;await writeWorkflowGraphRun(run);await sessionEvent(row.state,node.name);remaining.delete(node.id);progressed=true;
}
if(!progressed&&remaining.size)throw new Error("workflow graph could not make progress; inspect dependencies/branches");
}
run.state=handledErrors?"completed_with_errors":"completed";
} catch(error){if(run.state!=="failed"&&run.state!=="interrupted"){run.state="failed";run.error=redactor.text(redactText(error instanceof Error?error.message:"workflow graph failed",800));}}
run.finishedAt=run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);await sessionEvent(run.state,graph.name);
}
async function maybeRunErrorWorkflow(run:WorkflowGraphRun,graph:WorkflowGraph,context:CapabilityRunContext,resolve:Resolver,principal:string){
const errorId=graph.metadata.errorWorkflowId;if(run.state!=="failed"||!errorId||errorId===graph.id)return;
const {getWorkflowGraph}=await import("./graph-store"),errorGraph=await getWorkflowGraph(principal,errorId);if(!errorGraph||errorGraph.status==="archived")return;
await startWorkflowGraph(errorGraph,{error:{runId:run.id,graphId:graph.id,graphName:graph.name,nodeId:run.failedNodeId,nodeName:run.failedNodeName,message:run.error}},`error:${run.id}`,context,resolve,principal,{type:"system",receivedAt:new Date().toISOString()},run.ancestry??[graph.id]);
}
export function workflowGraphRunId(owner:string,key:string,graphId:string,triggerNodeId=""){return hash(canonical([owner,graphId,triggerNodeId,key])).slice(0,32);}
export async function startWorkflowGraph(graph: WorkflowGraph, rawInput: unknown, idempotencyKey: string, context: CapabilityRunContext, resolve: Resolver, storagePrincipal?: string, trigger?: WorkflowRunTrigger, ancestry: string[] = []) {
context = await workflowExecutionContext(context, trigger);
const principal=storagePrincipal??context.principal;if(!principal||!context.sessionId)throw new Error("workflow graph requires an authenticated principal/session");if(ancestry.includes(graph.id)||ancestry.length>=16)throw new Error("recursive workflow subflow detected");if(graph.status==="archived")throw new Error("archived workflow graph cannot run");if(!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey))throw new Error("idempotency_key must be 1-128 simple characters");
const triggerNodeId=trigger?.nodeId??graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook","channel_trigger"].includes(node.type))?.id??"";
const owner=workflowGraphOwner(principal),input=inputObject(rawInput),fingerprint=hash(canonical({graphId:graph.id,revision:graph.revision,input})),id=workflowGraphRunId(owner,idempotencyKey,graph.id,triggerNodeId);
return lockWorkflowGraphRun(owner,id,async()=>{const legacy=await readWorkflowGraphRun(owner,hash(`${owner}:${idempotencyKey}`).slice(0,32));const existing=await readWorkflowGraphRun(owner,id)??(legacy?.graphId===graph.id&&(legacy.trigger?.nodeId??"")===triggerNodeId?legacy:null);if(existing){await requireWorkflowReceiptAuthority(principal,existing,context.scope);if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}if(await readWorkflowGraphScheduleClaim(owner,id))throw new Error("one-shot schedule intent already committed; receipt unavailable, reconcile before an explicit new run");const device=principal.startsWith("web:")?await getApprovedDevice(principal.slice(4)):null;if(principal.startsWith("web:")&&(!device||device.role==="viewer"))throw new Error("workflow device is revoked or lacks operator authority");await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,executionScope:context.scope,executionRole:device?.role==="owner"?"owner":device?.role==="operator"?"operator":undefined,state:"running",startedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),pid:process.pid,instance:INSTANCE,nodes:graph.nodes.map((node)=>({id:node.id,name:node.name,type:node.type,state:"queued",logs:[]})),edges:graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,...(edge.sourceHandle?{sourceHandle:edge.sourceHandle}:{}),state:edge.disabled?"disabled":"pending"})),trigger:trigger??{type:"manual",nodeId:graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook","channel_trigger"].includes(node.type))?.id,receivedAt:new Date().toISOString()},ancestry:[...ancestry,graph.id],runtimeInput:structuredClone(input)};await writeWorkflowGraphRun(run);await appendAgentSessionEvent(principal,run.sessionId,{kind:"workflow",tool:"workflow_graph",state:"started",workflowId:graph.id,detail:graph.name}).catch(()=>undefined);const work=execute(run,graph,input,context,resolve).then(()=>maybeRunErrorWorkflow(run,graph,context,resolve,principal)).catch(()=>undefined).finally(()=>{pending.delete(id);cancelled.delete(id);});pending.set(id,work);return publicWorkflowGraphRun(run);});
}
export async function workflowGraphRunStatus(principal:string,id:string,waitMs=0,scope:CapabilityRunContext["scope"]="exec"){
if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25_000)throw new Error("wait_ms must be 0-25000");
const owner=workflowGraphOwner(principal);let run=await readWorkflowGraphRun(owner,id);
if(!run)throw new Error("workflow graph run not found for this principal");
await requireWorkflowReceiptAuthority(principal,run,scope);
if(run.state==="running"&&waitMs>0){
const work=pending.get(id);
if(work){
let timer:ReturnType<typeof setTimeout>|undefined;
await Promise.race([work,new Promise((resolve)=>{timer=setTimeout(resolve,waitMs);})]);
clearTimeout(timer);
}
// Completion can remove pending work while the initial authority check yields.
run=await readWorkflowGraphRun(owner,id)??run;
}
if(run.state==="running"&&run.instance!==INSTANCE){let gone=false;try{process.kill(run.pid,0);}catch(error){gone=(error as NodeJS.ErrnoException).code==="ESRCH";}if(gone){run.state="interrupted";run.updatedAt=run.finishedAt=new Date().toISOString();await writeWorkflowGraphRun(run);}}
await requireWorkflowReceiptAuthority(principal,run,scope);
return publicWorkflowGraphRun(run);
}
export async function requestWorkflowGraphStop(principal:string,id:string,scope:CapabilityRunContext["scope"]="exec"){const owner=workflowGraphOwner(principal),run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");await requireWorkflowReceiptAuthority(principal,run,scope);if(run.state!=="running")return{...publicWorkflowGraphRun(run),stopRequested:false};if(run.instance!==INSTANCE||!pending.has(id))throw new Error("workflow execution is owned by another runtime; refresh its status before retrying stop");cancelled.add(id);return{...publicWorkflowGraphRun(run),stopRequested:true};}