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.

feat(workflows): add bounded repeat-until loops

Rahman45e7679fe495
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 932e2389..23f23659 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `workflows` add bounded repeat-until loops
- `agent` add durable local-agent standby
**Fixed**
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 4c4aa3a0..ac3f4250 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,13 @@
+## 2026-09-21 — Add bounded Repeat Until for reusable Session workflows
+
+Workflow Graph could already save successful/reviewable Session action history as a private workflow draft and invoke saved workflows through Subflow, but its graph schema deliberately rejected cyclic edges and the existing `loop` node only iterated arrays. That left ordinary automation patterns such as “run this saved task, inspect its result, and try again until ready” without a native bounded control-flow primitive.
+
+This release adds `Repeat Until` as a first-class Flow node without weakening the DAG safety boundary. A Repeat node references another saved Workflow Graph by `workflowId`, supplies its normal input plus `input.repeat.iteration` and the previous iteration result, reads the child workflow's explicit Output node, and evaluates a configurable result path. Exact JSON comparison is available through `equals`; omitting it uses truthiness. A match follows the `done` port, while reaching the configured iteration limit follows `exhausted`. Child failures still use the normal workflow error/retry semantics.
+
+The loop is intentionally bounded rather than an unrestricted visual back-edge: `maxIterations` is 1–50, inter-iteration delay is bounded, total repeat duration is capped below the parent run timeout, cross-workflow ancestry still rejects recursion, and every child execution receives its own persisted run receipt. The parent stores compact iteration metadata and final output instead of duplicating full child receipts. Existing acyclic graphs, item-loop behavior, Subflow, schedules/webhooks, and Session workflow drafts remain compatible.
+
+The Workflow inspector exposes the saved workflow selector, input bindings, condition path/value, iteration/delay/duration bounds, and `done` / `exhausted` ports. The Sessions view now makes the reuse path explicit: a reviewed “Save session as workflow draft” result can become the body of a Subflow or Repeat Until node. AI-assisted workflow drafting has the same bounded Repeat contract. Regression proves a saved child workflow matching on iteration three, the exhausted path after two iterations, Session draft behavior, graph layout, and existing flow controls. Full `bun run verify` and the official isolated production build/release E2E both pass.
+
## 2026-09-20 — Add a static Native MCP App host-mount probe
A fresh ChatGPT acceptance from this session still executed `render_mso_page("/integrations")` and `integration_setup_open` successfully but surfaced their decoded structured objects instead of mounting the declared MCP App resource. That repeats the same failure across Page, Block/List history and dedicated Integrations setup while current tool schema, registered-app binding and production package state are already refreshed.
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index 76326096..555d8e32 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -39,11 +39,12 @@ Webhook endpoint:
- `merge` — combine, append or pass-through incoming outputs
- `batch` — split up to 1000 items into deterministic batches
- `loop` — execute one bounded tool for each item with concurrency 1–4
+- `repeat` — execute one saved Workflow Graph repeatedly until a result condition matches, with explicit `done` / `exhausted` branches, `maxIterations` 1–50, optional inter-iteration delay, and a hard node duration cap
- `wait` — delay/until, bounded to ten minutes inside a run
- `subflow` — execute another private Workflow Graph, or a legacy project flow
- `output` — explicit result collection
-Graph edges stay acyclic. Repetition is represented by the bounded `loop` node or reusable subflow rather than unrestricted cyclic edges, preventing accidental runaway server automation. Cross-workflow recursion is rejected with an ancestry guard.
+Graph edges stay acyclic. Item fan-out uses `loop`; conditional loop-back uses `repeat`, which reruns a referenced saved Workflow Graph internally instead of creating an unrestricted graph cycle. `repeat` always has hard iteration/time bounds and emits `done` or `exhausted`. Cross-workflow recursion is rejected with an ancestry guard.
### Actions and context
@@ -62,6 +63,32 @@ Project/folder nodes resolve the live canonical server path when the graph runs
Script nodes intentionally do **not** execute arbitrary shell or browser-supplied JavaScript. The Inspector can search the selected project's `.agent/scripts` catalog, shows candidate/tested state and step count, and persists the chosen `script_id` in the graph. Execution delegates to `project_script_run`, which re-reads the manifest and refuses steps outside the bounded replay-safe RASMIC policy. A successful candidate replay is promoted to tested by the existing script runner.
+## Repeat Until and saved Session workflows
+
+`repeat` is the bounded equivalent of a normal `while` / `do...while` automation loop:
+
+1. Select an existing `workflowId` as the body. A workflow created with **Save session as workflow draft** is valid after its disabled learned actions have been reviewed and enabled.
+2. The child workflow runs with the configured `input` plus `input.repeat.iteration` and `input.repeat.previous`.
+3. MSO reads the child workflow's explicit Output node. `path` is resolved against `{ result, iteration, previous }`; for example `result.output.ok`.
+4. When `equals` is configured, MSO performs exact JSON equality. Without `equals`, normal truthiness is used.
+5. A match routes `done`; reaching `maxIterations` routes `exhausted`. A child failure remains a node failure and can use the normal red error branch / retry policy.
+
+Example configuration:
+
+```json
+{
+ "workflowId": "saved-workflow-id",
+ "input": { "target": "production" },
+ "path": "result.output.ready",
+ "equals": true,
+ "maxIterations": 10,
+ "delayMs": 30000,
+ "maxDurationMs": 600000
+}
+```
+
+Each child execution has its own persisted Workflow run receipt. The parent `repeat` receipt stores bounded iteration metadata and the final output rather than duplicating every child receipt.
+
## Data binding
Node config supports safe declarative bindings:
diff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsx
index dc2fc0e9..e1a260ac 100644
--- a/frontend/slices/workflows/components/workflow-canvas.tsx
+++ b/frontend/slices/workflows/components/workflow-canvas.tsx
@@ -21,6 +21,7 @@ type FlowEdge = Edge;
function sourceHandles(node: WorkflowGraphNode): Array<string | undefined> {
if (node.type === "condition") return ["true", "false"];
+ if (node.type === "repeat") return ["done", "exhausted"];
if (node.type === "switch") { const cases = Array.isArray(node.config.cases) ? node.config.cases : []; return [...cases.map((row,index)=>row&&typeof row==="object"&&typeof (row as {handle?:unknown}).handle==="string"?String((row as {handle:string}).handle):`case-${index+1}`),"default"]; }
return [undefined];
}
diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsx
index 3fee5e0c..2f9e9581 100644
--- a/frontend/slices/workflows/components/workflow-inspector.tsx
+++ b/frontend/slices/workflows/components/workflow-inspector.tsx
@@ -29,7 +29,7 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph
const applyAdvanced=(text:string)=>{try{const value=JSON.parse(text);if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Config must be an object");patch({config:value as Record<string,unknown>});setAdvancedError("");}catch(e){setAdvancedError(e instanceof Error?e.message:"Invalid JSON");}};
const openTarget=async()=>{const resolved=await resolveNode(graph.id,node.id);openWindow("files-manager",resolved.name,undefined,{path:resolved.path},{multi:true});};
const copyWebhook=()=>void navigator.clipboard?.writeText(`${window.location.origin}/api/v1/workflows/webhook/${graph.id}/${node.id}`);
- const actionNode=["tool","project_function","project_mcp","integration","script","agent","subflow","loop"].includes(node.type);
+ const actionNode=["tool","project_function","project_mcp","integration","script","agent","subflow","loop","repeat"].includes(node.type);
return <div className="space-y-4 p-3 text-xs">
<Field label="Name"><Input value={node.name} onChange={(e)=>patch({name:e.target.value})}/></Field>
<Field label="Type"><select className={selectClass} value={node.type} onChange={(e)=>patch({type:e.target.value as WorkflowGraphNodeType})}>{WORKFLOW_GRAPH_NODE_TYPES.map((type)=><option key={type} value={type}>{type}</option>)}</select></Field>
@@ -43,6 +43,7 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph
{node.type==="integration"&&<>{["user","provider","connection","operation"].map((key)=><Field key={key} label={key[0]!.toUpperCase()+key.slice(1)}><Input value={String(node.config[key]??"")} onChange={(e)=>setConfig(key,e.target.value)}/></Field>)}</>}
{node.type==="agent"&&<Field label="Agent objective"><Textarea value={String(node.config.message??"")} onChange={(e)=>setConfig("message",e.target.value)}/></Field>}
{node.type==="subflow"&&<><Field label="Workflow graph"><select className={selectClass} value={String(node.config.workflowId??"")} onChange={(e)=>e.target.value?setConfig("workflowId",e.target.value):removeConfig("workflowId")}><option value="">Legacy project flow</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field>{!node.config.workflowId&&<Field label="Legacy flow id"><Input value={String(node.config.flow??"")} onChange={(e)=>setConfig("flow",e.target.value)}/></Field>}</>}
+ {node.type==="repeat"&&<><Field label="Workflow to repeat"><select className={selectClass} value={String(node.config.workflowId??"")} onChange={(e)=>e.target.value?setConfig("workflowId",e.target.value):removeConfig("workflowId")}><option value="">Select saved workflow</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field><JsonField label="Input JSON / bindings" value={node.config.input??{}} onChange={(value)=>setConfig("input",value)}/><Field label="Condition path"><Input value={String(node.config.path??"result.output")} placeholder="result.output.ok" onChange={(e)=>setConfig("path",e.target.value)}/></Field><label className="flex items-center justify-between"><span>Compare exact value</span><Switch checked={Object.hasOwn(node.config,"equals")} onCheckedChange={(checked)=>checked?setConfig("equals",true):removeConfig("equals")}/></label>{Object.hasOwn(node.config,"equals")&&<JsonField label="Expected JSON" value={node.config.equals} onChange={(value)=>setConfig("equals",value)}/>}<Field label="Max iterations"><Input type="number" min={1} max={50} value={number(node.config.maxIterations,5)} onChange={(e)=>setConfig("maxIterations",Number(e.target.value))}/></Field><Field label="Delay between iterations ms"><Input type="number" min={0} max={600000} value={number(node.config.delayMs,1000)} onChange={(e)=>setConfig("delayMs",Number(e.target.value))}/></Field><Field label="Max repeat duration ms"><Input type="number" min={1000} max={840000} value={number(node.config.maxDurationMs,600000)} onChange={(e)=>setConfig("maxDurationMs",Number(e.target.value))}/></Field><p className="text-[10px] text-muted-foreground">Each child run receives <code>input.repeat.iteration</code> and the previous iteration output. Route <code>done</code> when the condition matches or <code>exhausted</code> when limits are reached.</p></>}
{node.type==="wait"&&<Field label="Delay ms"><Input type="number" min={0} max={600000} value={number(node.config.delayMs,1000)} onChange={(e)=>setConfig("delayMs",Number(e.target.value))}/></Field>}
{node.type==="cache"&&<><Field label="Cache mode"><select className={selectClass} value={String(node.config.mode??"get_or_set")} onChange={(e)=>setConfig("mode",e.target.value)}>{["get_or_set","get","set","delete"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field><Field label="Cache key"><Input value={String(node.config.key??"")} onChange={(e)=>setConfig("key",e.target.value)}/></Field>{["get_or_set","set"].includes(String(node.config.mode??"get_or_set"))&&<><Field label="TTL seconds"><Input type="number" min={0} max={2592000} value={number(node.config.ttlSeconds,300)} onChange={(e)=>setConfig("ttlSeconds",Number(e.target.value))}/></Field><JsonField label="Value JSON / binding" value={node.config.value??{"$ref":"input"}} onChange={(value)=>setConfig("value",value)}/></>}</>}
{node.type==="memory"&&<><Field label="Memory scope"><select className={selectClass} value={String(node.config.scope??"agent")} onChange={(e)=>setConfig("scope",e.target.value)}><option value="agent">Agent memory</option><option value="project">Project memory</option></select></Field><Field label="Memory mode"><select className={selectClass} value={String(node.config.mode??"search")} onChange={(e)=>setConfig("mode",e.target.value)}>{(node.config.scope==="project"?["search","remember"]:["read","search","remember","forget"]).map((x)=><option key={x} value={x}>{x}</option>)}</select></Field>{String(node.config.mode??"search")==="search"&&<Field label="Query"><Input value={String(node.config.query??"")} onChange={(e)=>setConfig("query",e.target.value)}/></Field>}{node.config.scope!=="project"&&<Field label="Document"><select className={selectClass} value={String(node.config.document??"MEMORY.md")} onChange={(e)=>setConfig("document",e.target.value)}><option value="MEMORY.md">MEMORY.md</option><option value="USER.md">USER.md</option></select></Field>}{["remember","forget"].includes(String(node.config.mode))&&<Field label="Memory key"><Input value={String(node.config.key??"")} onChange={(e)=>setConfig("key",e.target.value)}/></Field>}{String(node.config.mode)==="remember"&&<Field label={node.config.scope==="project"?"Summary":"Value"}><Textarea value={String(node.config.value??node.config.summary??"")} onChange={(e)=>setConfig(node.config.scope==="project"?"summary":"value",e.target.value)}/></Field>}</>}
diff --git a/frontend/slices/workflows/components/workflow-session-details.tsx b/frontend/slices/workflows/components/workflow-session-details.tsx
index 331e5ad2..93d8bd11 100644
--- a/frontend/slices/workflows/components/workflow-session-details.tsx
+++ b/frontend/slices/workflows/components/workflow-session-details.tsx
@@ -106,7 +106,7 @@ export function WorkflowSessionDetails({ view, node, onOpenTerminal, onOpenCode,
{view.omittedEvents ? <p className="mt-2 text-[10px] text-muted-foreground">Projection uses the latest {view.shownEvents} of {view.totalEvents} events to stay fast. Raw session history remains the source of truth.</p> : null}
</div>
<ScrollArea className="min-h-0 flex-1"><div className="space-y-3 p-3">
- {!node || node.id === "session-root" ? <><div><div className="text-[10px] uppercase text-muted-foreground">Flow</div><div className="mt-1 text-sm font-semibold">{view.session.title}</div><Button data-slot="save-session-workflow-draft" type="button" size="sm" variant="outline" className="mt-2 h-7 text-[10px]" disabled={savingDraft} onClick={() => onSaveDraft()}><Save className="size-3.5"/>Save session as workflow draft</Button></div><div className="space-y-1.5">{view.steps.map((item) => <div key={item.ref} className="rounded-lg border bg-background/35 p-2"><div className="flex items-center gap-2"><code className="rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold">{item.ref}</code><span className="text-xs font-medium">{item.title}</span><span className="ml-auto text-[10px] text-muted-foreground">{item.actions.length} actions</span></div><p className="mt-1 text-[10px] text-muted-foreground">{item.summary}</p></div>)}</div></> : step ? <>
+ {!node || node.id === "session-root" ? <><div><div className="text-[10px] uppercase text-muted-foreground">Flow</div><div className="mt-1 text-sm font-semibold">{view.session.title}</div><Button data-slot="save-session-workflow-draft" type="button" size="sm" variant="outline" className="mt-2 h-7 text-[10px]" disabled={savingDraft} onClick={() => onSaveDraft()}><Save className="size-3.5"/>Save session as workflow draft</Button><p className="mt-1.5 max-w-sm text-[10px] text-muted-foreground">Saved Session workflows can be reused by workflow ID in Subflow or Repeat Until nodes.</p></div><div className="space-y-1.5">{view.steps.map((item) => <div key={item.ref} className="rounded-lg border bg-background/35 p-2"><div className="flex items-center gap-2"><code className="rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold">{item.ref}</code><span className="text-xs font-medium">{item.title}</span><span className="ml-auto text-[10px] text-muted-foreground">{item.actions.length} actions</span></div><p className="mt-1 text-[10px] text-muted-foreground">{item.summary}</p></div>)}</div></> : step ? <>
<div><div className="flex items-center gap-2"><code className="rounded bg-muted px-1.5 py-0.5 font-mono text-[10px] font-semibold">{step.ref}</code><Badge variant="outline" className="text-[9px] capitalize">{step.category}</Badge></div><div className="mt-2 break-words text-sm font-semibold">{step.title}</div><p className="mt-1 text-xs text-muted-foreground">{step.summary}</p><Button data-slot="save-step-workflow-draft" type="button" size="sm" variant="outline" className="mt-2 h-7 text-[10px]" disabled={savingDraft} onClick={() => onSaveDraft(step.ref)}><Save className="size-3.5"/>Save {step.ref} as workflow draft</Button></div>
<div className="border-t pt-3"><div className="mb-2 flex items-center justify-between"><div className="text-[10px] font-semibold uppercase text-muted-foreground">Action groups</div><span className="text-[10px] text-muted-foreground">{step.groups.length} groups · {step.actions.length} actions</span></div><div className="space-y-1.5">{actionGroups(step, view.session.id, onOpenTerminal, onOpenCode)}</div></div>
</> : <p className="text-xs text-muted-foreground">Select a semantic step to inspect its actions.</p>}
diff --git a/lib/contracts/workflow-graph.ts b/lib/contracts/workflow-graph.ts
index 3cd718ca..f9934442 100644
--- a/lib/contracts/workflow-graph.ts
+++ b/lib/contracts/workflow-graph.ts
@@ -1,7 +1,7 @@
import type { GraphCustomNode } from "./graph-custom-nodes";
export const WORKFLOW_GRAPH_NODE_TYPES = [
"manual", "schedule", "webhook", "tool", "project_function", "project_mcp", "integration", "script", "agent", "subflow",
- "condition", "switch", "merge", "batch", "loop", "wait", "cache", "memory", "session", "directory", "project", "folder", "skill", "knowledge", "output",
+ "condition", "switch", "merge", "batch", "loop", "repeat", "wait", "cache", "memory", "session", "directory", "project", "folder", "skill", "knowledge", "output",
] as const;
export type WorkflowGraphNodeType = (typeof WORKFLOW_GRAPH_NODE_TYPES)[number];
export type WorkflowGraphStatus = "draft" | "active" | "archived";
diff --git a/lib/workflow/ai-assist.ts b/lib/workflow/ai-assist.ts
index 54ca0b91..3a638db0 100644
--- a/lib/workflow/ai-assist.ts
+++ b/lib/workflow/ai-assist.ts
@@ -4,7 +4,7 @@ import { parseWorkflowGraphDefinition } from "./graph-schema";
export async function suggestWorkflowGraph(prompt:string){
const request=prompt.trim();if(!request||request.length>4000)throw new Error("workflow AI prompt must be 1-4000 characters");
const prepared=await prepareSelectedModel(),abort=new AbortController(),timer=setTimeout(()=>abort.abort(new Error("workflow AI suggestion timed out")),45_000);let text="";
- const system=["Design one MSO workflow graph as strict JSON only. No markdown.",`Allowed node types: ${WORKFLOW_GRAPH_NODE_TYPES.join(", ")}.`,`Return keys: name, description, status, inputs, metadata, nodes, edges. Status must be draft.`,"Every node needs id,name,type,position{x,y},config. Every edge needs id,source,target and optional sourceHandle, style (solid|dashed), disabled (boolean).","Never output credentials, tokens, passwords, cookies, authorization headers, or secret values. Use {$var:\"NAME\"} for runtime private variables and integration nodes for credential-backed provider actions.","Use schedule/webhook nodes only as roots. Use true/false handles for condition, named handles/default for switch, error handle for failure branches. Prefer DRY subflows and explicit output nodes."].join(" ");
+ const system=["Design one MSO workflow graph as strict JSON only. No markdown.",`Allowed node types: ${WORKFLOW_GRAPH_NODE_TYPES.join(", ")}.`,`Return keys: name, description, status, inputs, metadata, nodes, edges. Status must be draft.`,"Every node needs id,name,type,position{x,y},config. Every edge needs id,source,target and optional sourceHandle, style (solid|dashed), disabled (boolean).","Never output credentials, tokens, passwords, cookies, authorization headers, or secret values. Use {$var:\"NAME\"} for runtime private variables and integration nodes for credential-backed provider actions.","Use schedule/webhook nodes only as roots. Use true/false handles for condition, named handles/default for switch, done/exhausted handles for repeat, and error handle for failure branches. Repeat runs one saved workflowId until config.path matches config.equals (or becomes truthy), always with maxIterations and maxDurationMs. Prefer DRY subflows and explicit output nodes."].join(" ");
try{await streamPreparedSelectedModel({prepared,messages:[{role:"user",text:request}],system,signal:abort.signal,emit:(event,data)=>{if(event==="delta"&&typeof data==="string"&&text.length<256*1024)text+=data;}});}finally{clearTimeout(timer);}
const clean=text.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/,""),start=clean.indexOf("{"),end=clean.lastIndexOf("}");if(start<0||end<=start)throw new Error("workflow AI did not return JSON");
let raw:unknown;try{raw=JSON.parse(clean.slice(start,end+1));}catch{throw new Error("workflow AI returned invalid JSON");}
diff --git a/lib/workflow/graph-engine.test.ts b/lib/workflow/graph-engine.test.ts
index da0e00bc..4909fc1b 100644
--- a/lib/workflow/graph-engine.test.ts
+++ b/lib/workflow/graph-engine.test.ts
@@ -121,6 +121,47 @@ describe("workflow graph engine", () => {
const recursive = await startWorkflowGraph(parent, {}, "subflow-recursive", context, () => undefined), recursiveDone = await workflowGraphRunStatus("graph-owner", recursive.id, 5000);
expect(recursiveDone.state).toBe("failed"); expect(recursiveDone.nodes.find((node) => node.id === "child")?.error).toContain("recursive");
});
+ it("repeats a saved workflow until its output matches and routes exhaustion separately", async () => {
+ const child = await createWorkflowGraph("graph-owner", { name: "Repeat child", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "repeat-child-start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "repeat-child-out", name: "Out", type: "output", position: { x: 120, y: 0 }, config: { value: { $ref: "input.repeat.iteration" } } },
+ ], edges: [{ id: "repeat-child-e", source: "repeat-child-start", target: "repeat-child-out" }] });
+
+ const matchedGraph = await createWorkflowGraph("graph-owner", { name: "Repeat matched", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "repeat-start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "repeat-node", name: "Repeat until 3", type: "repeat", position: { x: 120, y: 0 }, config: { workflowId: child.id, path: "result.output", equals: 3, maxIterations: 5, delayMs: 0, maxDurationMs: 30_000 } },
+ { id: "repeat-done", name: "Done", type: "output", position: { x: 280, y: 0 }, config: { value: "done" } },
+ { id: "repeat-exhausted", name: "Exhausted", type: "output", position: { x: 280, y: 120 }, config: { value: "exhausted" } },
+ ], edges: [
+ { id: "repeat-e1", source: "repeat-start", target: "repeat-node" },
+ { id: "repeat-e2", source: "repeat-node", target: "repeat-done", sourceHandle: "done" },
+ { id: "repeat-e3", source: "repeat-node", target: "repeat-exhausted", sourceHandle: "exhausted" },
+ ] });
+ const matchedStarted = await startWorkflowGraph(matchedGraph, {}, "repeat-until-match", context, () => undefined);
+ const matched = await workflowGraphRunStatus("graph-owner", matchedStarted.id, 5000);
+ expect(matched.state).toBe("completed");
+ expect(matched.nodes.find((node) => node.id === "repeat-done")?.state).toBe("completed");
+ expect(matched.nodes.find((node) => node.id === "repeat-exhausted")?.state).toBe("skipped");
+ expect(matched.nodes.find((node) => node.id === "repeat-node")?.output).toMatchObject({ matched: true, exhausted: false, count: 3 });
+
+ const exhaustedGraph = await createWorkflowGraph("graph-owner", { name: "Repeat exhausted", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ { id: "exhaust-start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },
+ { id: "exhaust-node", name: "Repeat twice", type: "repeat", position: { x: 120, y: 0 }, config: { workflowId: child.id, path: "result.output", equals: 3, maxIterations: 2, delayMs: 0, maxDurationMs: 30_000 } },
+ { id: "exhaust-done", name: "Done", type: "output", position: { x: 280, y: 0 }, config: { value: "done" } },
+ { id: "exhaust-out", name: "Exhausted", type: "output", position: { x: 280, y: 120 }, config: { value: "exhausted" } },
+ ], edges: [
+ { id: "exhaust-e1", source: "exhaust-start", target: "exhaust-node" },
+ { id: "exhaust-e2", source: "exhaust-node", target: "exhaust-done", sourceHandle: "done" },
+ { id: "exhaust-e3", source: "exhaust-node", target: "exhaust-out", sourceHandle: "exhausted" },
+ ] });
+ const exhaustedStarted = await startWorkflowGraph(exhaustedGraph, {}, "repeat-until-exhausted", context, () => undefined);
+ const exhausted = await workflowGraphRunStatus("graph-owner", exhaustedStarted.id, 5000);
+ expect(exhausted.state).toBe("completed");
+ expect(exhausted.nodes.find((node) => node.id === "exhaust-done")?.state).toBe("skipped");
+ expect(exhausted.nodes.find((node) => node.id === "exhaust-out")?.state).toBe("completed");
+ expect(exhausted.nodes.find((node) => node.id === "exhaust-node")?.output).toMatchObject({ matched: false, exhausted: true, count: 2 });
+ });
+
it("executes a saved RASMIC script node through project_script_run", async () => {
let received: Record<string, unknown> | undefined;
const graph = await createWorkflowGraph("graph-owner", { name: "Script run", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
diff --git a/lib/workflow/graph-repeat.ts b/lib/workflow/graph-repeat.ts
new file mode 100644
index 00000000..eec6d627
--- /dev/null
+++ b/lib/workflow/graph-repeat.ts
@@ -0,0 +1,142 @@
+import type { CapabilityRunContext, CapabilityTool } from "@/lib/capabilities/tool";
+import { boundedResultText } from "@/lib/capabilities/result-budget";
+import type { WorkflowGraph, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+import { graphObject } from "./graph-schema";
+import { workflowPath } from "./graph-bindings";
+
+type Resolver = (name: string) => CapabilityTool | undefined;
+
+function compact(value: unknown): unknown {
+ try {
+ return JSON.parse(boundedResultText(typeof value === "string" ? { text: value } : value, {
+ maxTextBytes: 12 * 1024,
+ overflowHint: "Open the child workflow run receipt for full details.",
+ }));
+ } catch {
+ return { text: String(value).slice(0, 12_000) };
+ }
+}
+
+function explicitWorkflowOutput(
+ graph: WorkflowGraph,
+ run: Pick<WorkflowGraphRun, "id" | "state" | "nodes">,
+): unknown {
+ const outputs = graph.nodes
+ .filter((node) => node.type === "output")
+ .map((node) => ({ id: node.id, value: run.nodes.find((row) => row.id === node.id)?.output }))
+ .filter((row) => row.value !== undefined);
+ if (outputs.length === 1) return outputs[0]!.value;
+ if (outputs.length > 1) return Object.fromEntries(outputs.map((row) => [row.id, row.value]));
+ return { state: run.state, runId: run.id };
+}
+
+export async function runWorkflowGraphChild(
+ workflowId: string,
+ input: Record<string, unknown>,
+ key: string,
+ run: WorkflowGraphRun,
+ graph: WorkflowGraph,
+ context: CapabilityRunContext,
+ resolve: Resolver,
+ deadlineAt?: number,
+) {
+ const principal = context.principal ?? context.actor;
+ if (!principal) throw new Error("workflow child requires principal");
+ const { getWorkflowGraph } = await import("./graph-store");
+ const { startWorkflowGraph, workflowGraphRunStatus } = await import("./graph-engine");
+ const child = await getWorkflowGraph(principal, workflowId);
+ if (!child) throw new Error("workflow child graph not found");
+ const started = await startWorkflowGraph(
+ child,
+ input,
+ key,
+ context,
+ resolve,
+ principal,
+ { type: "system", receivedAt: new Date().toISOString() },
+ run.ancestry ?? [graph.id],
+ );
+ let latest = started;
+ for (let polls = 0; polls < 24 && latest.state === "running"; polls += 1) {
+ const remaining = deadlineAt === undefined ? 25_000 : deadlineAt - Date.now();
+ if (remaining <= 0) throw new Error("repeat node exceeded maxDurationMs");
+ latest = await workflowGraphRunStatus(principal, latest.id, Math.min(25_000, remaining));
+ }
+ if (latest.state === "failed" || latest.state === "interrupted" || latest.state === "running")
+ throw new Error(`workflow child ${child.name} did not complete successfully`);
+ return { child, latest };
+}
+
+export async function repeatWorkflow(
+ config: Record<string, unknown>,
+ run: WorkflowGraphRun,
+ graph: WorkflowGraph,
+ context: CapabilityRunContext,
+ resolve: Resolver,
+) {
+ const workflowId = typeof config.workflowId === "string" ? config.workflowId.trim() : "";
+ if (!workflowId) throw new Error("repeat node requires workflowId");
+ const maxIterations = Math.trunc(Number(config.maxIterations ?? 5));
+ if (!Number.isSafeInteger(maxIterations) || maxIterations < 1 || maxIterations > 50)
+ throw new Error("repeat node maxIterations must be 1-50");
+ const delayMs = Math.trunc(Number(config.delayMs ?? 0));
+ if (!Number.isSafeInteger(delayMs) || delayMs < 0 || delayMs > 10 * 60_000)
+ throw new Error("repeat node delayMs must be 0-600000");
+ const maxDurationMs = Math.trunc(Number(config.maxDurationMs ?? 10 * 60_000));
+ if (!Number.isSafeInteger(maxDurationMs) || maxDurationMs < 1_000 || maxDurationMs > 14 * 60_000)
+ throw new Error("repeat node maxDurationMs must be 1000-840000");
+ const path = typeof config.path === "string" && config.path.trim() ? config.path.trim() : "result.output";
+ const baseInput = graphObject(config.input) ? structuredClone(config.input) : {};
+ const deadlineAt = Date.now() + maxDurationMs;
+ const iterations: Array<{ iteration: number; runId: string; state: string; matched: boolean; condition: unknown }> = [];
+ let previous: unknown = null;
+ let final: unknown = null;
+
+ for (let iteration = 1; iteration <= maxIterations; iteration += 1) {
+ if (Date.now() >= deadlineAt) throw new Error("repeat node exceeded maxDurationMs");
+ const childInput = { ...baseInput, repeat: { iteration, previous } };
+ const { child, latest } = await runWorkflowGraphChild(
+ workflowId,
+ childInput,
+ `${run.id}:${workflowId}:${iteration}`,
+ run,
+ graph,
+ context,
+ resolve,
+ deadlineAt,
+ );
+ const output = explicitWorkflowOutput(child, latest);
+ const result = { runId: latest.id, state: latest.state, output };
+ const conditionValue = workflowPath({ result, iteration, previous }, path);
+ const matched = Object.hasOwn(config, "equals")
+ ? JSON.stringify(conditionValue) === JSON.stringify(config.equals)
+ : Boolean(conditionValue);
+ const safeOutput = compact(output);
+ final = { iteration, ...result, output: safeOutput, condition: compact(conditionValue), matched };
+ iterations.push({
+ iteration,
+ runId: latest.id,
+ state: latest.state,
+ matched,
+ condition: compact(conditionValue),
+ });
+ if (matched) {
+ return {
+ output: { matched: true, exhausted: false, count: iteration, iterations, final },
+ handles: ["done"],
+ log: `Repeat Until matched after ${iteration} iteration(s).`,
+ };
+ }
+ previous = { iteration, runId: latest.id, state: latest.state, output: safeOutput };
+ if (iteration < maxIterations && delayMs > 0) {
+ const remaining = deadlineAt - Date.now();
+ if (remaining <= 0 || delayMs > remaining) throw new Error("repeat node exceeded maxDurationMs");
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, delayMs));
+ }
+ }
+ return {
+ output: { matched: false, exhausted: true, count: maxIterations, iterations, final },
+ handles: ["exhausted"],
+ log: `Repeat Until exhausted after ${maxIterations} iteration(s).`,
+ };
+}
diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.ts
index 98a228e5..3c50e2c6 100644
--- a/lib/workflow/graph-runtime.ts
+++ b/lib/workflow/graph-runtime.ts
@@ -12,6 +12,7 @@ import { executeFlowNode, workflowItems, type FlowNodeResult } from "./graph-flo
import { workflowVariableValues } from "./variables";
import { organizationLocalAgentPrincipal, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";
import { workflowCacheDelete, workflowCacheGet, workflowCacheSet } from "./cache-store";
+import { repeatWorkflow, runWorkflowGraphChild } from "./graph-repeat";
type Resolver = (name: string) => CapabilityTool | undefined;
type NodeExecutionResult = FlowNodeResult;
@@ -120,6 +121,7 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph
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;
@@ -148,12 +150,15 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph
}
if (node.type === "subflow") {
if (typeof config.workflowId === "string" && config.workflowId) {
- const principal = context.principal ?? context.actor; if (!principal) throw new Error("workflow subflow requires principal");
- const { getWorkflowGraph } = await import("./graph-store"), { startWorkflowGraph, workflowGraphRunStatus } = await import("./graph-engine"), child = await getWorkflowGraph(principal, config.workflowId);
- if (!child) throw new Error("subflow workflow graph not found");
- const started = await startWorkflowGraph(child, graphObject(config.input) ? config.input : {}, `${run.id}:${node.id}`, context, resolve, principal, { type: "system", receivedAt: new Date().toISOString() }, run.ancestry ?? [graph.id]);
- let latest = started; for (let tries = 0; tries < 24 && latest.state === "running"; tries += 1) latest = await workflowGraphRunStatus(principal, latest.id, 25_000);
- if (latest.state === "failed" || latest.state === "interrupted" || latest.state === "running") throw new Error(`subflow workflow ${child.name} did not complete successfully`);
+ 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>;
diff --git a/lib/workflow/graph-schema.test.ts b/lib/workflow/graph-schema.test.ts
index 8a09db73..2044bd82 100644
--- a/lib/workflow/graph-schema.test.ts
+++ b/lib/workflow/graph-schema.test.ts
@@ -30,7 +30,7 @@ describe("workflow graph schema", () => {
});
it("accepts parity node types but keeps triggers root-only", () => {
- expect(parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "start", name: "Schedule", type: "schedule", position: { x: 0, y: 0 }, config: { mode: "interval", everyMinutes: 5 } }, { id: "wait", name: "Wait", type: "wait", position: { x: 100, y: 0 }, config: { delayMs: 0 } }, base().nodes[1]], edges: [{ id: "a", source: "start", target: "wait" }, { id: "b", source: "wait", target: "done" }] }).nodes.map((node) => node.type)).toEqual(["schedule", "wait", "output"]);
+ expect(parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "start", name: "Schedule", type: "schedule", position: { x: 0, y: 0 }, config: { mode: "interval", everyMinutes: 5 } }, { id: "repeat", name: "Repeat", type: "repeat", position: { x: 100, y: 0 }, config: { workflowId: "saved-workflow", path: "result.output", equals: true, maxIterations: 5 } }, { id: "wait", name: "Wait", type: "wait", position: { x: 200, y: 0 }, config: { delayMs: 0 } }, base().nodes[1]], edges: [{ id: "a", source: "start", target: "repeat" }, { id: "b", source: "repeat", target: "wait", sourceHandle: "done" }, { id: "c", source: "wait", target: "done" }] }).nodes.map((node) => node.type)).toEqual(["schedule", "repeat", "wait", "output"]);
expect(() => parseWorkflowGraphDefinition({ ...base(), nodes: [base().nodes[0], { id: "hook", name: "Hook", type: "webhook", position: { x: 100, y: 0 }, config: {} }], edges: [{ id: "bad", source: "start", target: "hook" }] })).toThrow("root");
});
});
diff --git a/lib/workflow/node-catalog.ts b/lib/workflow/node-catalog.ts
index 62fb62c5..1e6e6bca 100644
--- a/lib/workflow/node-catalog.ts
+++ b/lib/workflow/node-catalog.ts
@@ -9,6 +9,7 @@ export const WORKFLOW_NODE_CATALOG:WorkflowNodeCatalogItem[]=[
{type:"merge",title:"Merge",category:"Flow",description:"Merge enabled incoming node outputs.",defaults:{mode:"combine"}},
{type:"batch",title:"Split In Batches",category:"Flow",description:"Chunk an array into deterministic batches.",defaults:{size:10}},
{type:"loop",title:"Loop Over Items",category:"Flow",description:"Run one bounded tool once per item without cyclic graph edges.",defaults:{concurrency:1}},
+ {type:"repeat",title:"Repeat Until",category:"Flow",description:"Run a saved workflow repeatedly until its output matches a condition or a hard iteration/time limit is reached.",handles:["done","exhausted"],defaults:{input:{},path:"result.output",equals:true,maxIterations:5,delayMs:1000,maxDurationMs:600000}},
{type:"wait",title:"Wait",category:"Flow",description:"Delay execution or wait until a timestamp within run timeout.",defaults:{delayMs:1000}},
{type:"cache",title:"Cache",category:"Context",description:"Read/write/delete a private principal-scoped TTL cache for reusable workflow data.",defaults:{mode:"get_or_set",ttlSeconds:300,key:"workflow-cache"}},
{type:"memory",title:"Memory",category:"Context",description:"Read/search/remember MSO agent memory or repo-local project memory.",defaults:{scope:"agent",mode:"search",query:""}},