1616package io .github .agentic .ai .workflow ;
1717
1818import com .fasterxml .jackson .databind .ObjectMapper ;
19+ import com .networknt .schema .Error ;
20+ import com .networknt .schema .Schema ;
21+ import com .networknt .schema .SchemaRegistry ;
22+ import com .networknt .schema .SpecificationVersion ;
1923import io .github .agentic .ai .agent .Agent ;
2024import io .github .agentic .ai .agent .AgentEvent ;
2125import io .github .agentic .ai .agent .AgentExecutionContext ;
2226import io .github .agentic .ai .agent .AgentOutcome ;
2327import io .github .agentic .ai .agent .AgentRequest ;
28+ import io .github .agentic .ai .agent .AgentResult ;
2429import io .github .agentic .ai .api .chat .ChatMessage ;
2530import io .github .agentic .ai .api .chat .ContentPart ;
2631import io .github .agentic .ai .api .chat .ToolCall ;
4449import java .util .concurrent .Flow ;
4550import java .util .concurrent .Semaphore ;
4651import java .util .function .Function ;
52+ import tools .jackson .databind .JsonNode ;
53+ import tools .jackson .databind .json .JsonMapper ;
4754
4855/**
4956 * Independent workflow executor. It interprets the closed workflow DSL directly and
5057 * never creates or references StateGraph, CompiledGraph or Loop runtime classes.
58+ *
59+ * <p>
60+ * When the definition declares an input schema, the request inputs are validated
61+ * against it before the first step runs — before any tool or agent side effect. When
62+ * it declares an output schema, the completed output snapshot is validated before the
63+ * COMPLETED outcome is delivered; a violating output terminates the stream with a
64+ * {@link WorkflowValidationException} instead. Inputs are validated on the fresh run
65+ * only: a resume request continues from the state owned by its continuation and often
66+ * carries no inputs, so re-validating them there would make suspended workflows
67+ * impossible to complete. Subflows share the parent run's inputs, so a nested
68+ * definition's input schema is a publish-time contract for its own callers and is not
69+ * applied again at the subflow entry.
5170 */
5271public final class WorkflowAgent implements Agent {
5372
73+ private static final JsonMapper JSON = JsonMapper .builder ().build ();
74+
75+ private static final SchemaRegistry SCHEMAS = SchemaRegistry .withDefaultDialect (SpecificationVersion .DRAFT_2020_12 );
76+
5477 private final WorkflowDefinition definition ;
5578
5679 private final Function <String , Agent > agentResolver ;
@@ -65,6 +88,10 @@ public final class WorkflowAgent implements Agent {
6588
6689 private final Map <String , StoredContinuation > continuations = new ConcurrentHashMap <>();
6790
91+ private final Schema inputSchema ;
92+
93+ private final Schema outputSchema ;
94+
6895 private WorkflowAgent (Builder builder ) {
6996 this .definition = Objects .requireNonNull (builder .definition , "definition must not be null" );
7097 this .definition .validate ();
@@ -73,6 +100,8 @@ private WorkflowAgent(Builder builder) {
73100 this .registry = Objects .requireNonNull (builder .registry , "registry must not be null" );
74101 this .mapper = Objects .requireNonNull (builder .mapper , "mapper must not be null" );
75102 this .subflowMaxDepth = builder .subflowMaxDepth ;
103+ this .inputSchema = compileSchema (definition .inputSchema ());
104+ this .outputSchema = compileSchema (definition .outputSchema ());
76105 }
77106
78107 public static Builder builder (WorkflowDefinition definition ) {
@@ -90,6 +119,34 @@ public WorkflowDefinition definition() {
90119 return definition ;
91120 }
92121
122+ private static Schema compileSchema (String schemaText ) {
123+ return schemaText == null ? null : SCHEMAS .getSchema (schemaText );
124+ }
125+
126+ private static void validate (Map <String , Object > value , Schema schema , String boundary ) {
127+ if (schema == null ) {
128+ return ;
129+ }
130+ JsonNode node ;
131+ try {
132+ node = JSON .valueToTree (value );
133+ }
134+ catch (RuntimeException exception ) {
135+ throw new WorkflowValidationException ("Workflow " + boundary + " is not representable as JSON" ,
136+ List .of (new AgentResult .OutputValidationIssue (AgentResult .ERROR_CODE_SCHEMA_MALFORMED , "$" ,
137+ "Workflow " + boundary + " is not representable as JSON: " + exception .getMessage ())));
138+ }
139+ List <AgentResult .OutputValidationIssue > issues = new ArrayList <>();
140+ for (Error error : schema .validate (node )) {
141+ issues .add (new AgentResult .OutputValidationIssue (AgentResult .ERROR_CODE_SCHEMA_VIOLATION ,
142+ error .getInstanceLocation ().toString (), error .getMessage ()));
143+ }
144+ if (!issues .isEmpty ()) {
145+ throw new WorkflowValidationException (
146+ "Workflow " + boundary + " does not match the declared " + boundary + "Schema" , issues );
147+ }
148+ }
149+
93150 public static final class Builder {
94151
95152 private final WorkflowDefinition definition ;
@@ -216,6 +273,9 @@ private void runSafely() {
216273 emit (new AgentEvent .Finished (outcome ));
217274 }
218275 else {
276+ // The output boundary: a completed delivery must match the declared
277+ // output schema, whatever path (fresh run or resume) produced it.
278+ validate (result .data .state , outputSchema , "output" );
219279 AgentOutcome outcome = AgentOutcome .completed (result .data .messages , result .data .state ,
220280 result .data .usage ());
221281 emit (new AgentEvent .Finished (outcome ));
@@ -237,9 +297,13 @@ private ExecutionResult run() {
237297 if (stored == null || !stored .matches (context )) {
238298 throw new IllegalArgumentException ("Unknown or unauthorized workflow resume token" );
239299 }
300+ // Inputs were validated on the fresh run that produced this continuation;
301+ // a resume request carries the continuation's state forward.
240302 return stored .continuation .resume (request , context );
241303 }
242304 RunData data = new RunData (request );
305+ // The input boundary: refuse before any step, tool or agent side effect.
306+ validate (data .inputs , inputSchema , "input" );
243307 return executeSteps (definition .steps (), 0 , data , context );
244308 }
245309
@@ -266,10 +330,19 @@ private ExecutionResult executeSteps(List<WorkflowStep> steps, int index, RunDat
266330 if (result .suspension == null ) {
267331 return executeSteps (steps , index + 1 , data , context );
268332 }
269- return result .continueWith ((request , resumeContext ) -> {
270- ExecutionResult resumed = result .continuation .resume (request , resumeContext );
271- return resumed .suspension == null ? executeSteps (steps , index + 1 , data , resumeContext ) : resumed ;
272- });
333+ return continueAfter (result , steps , index , data );
334+ }
335+
336+ /**
337+ * Wraps a suspension so the remaining steps survive any number of further
338+ * suspensions: every time the wrapped continuation suspends again, the
339+ * continue-after step is composed onto the new suspension (issue #274 review).
340+ */
341+ private ExecutionResult continueAfter (ExecutionResult suspended , List <WorkflowStep > steps , int index ,
342+ RunData data ) {
343+ return suspended .continueWith ((resumed , request , resumeContext ) ->
344+ resumed .suspension == null ? executeSteps (steps , index + 1 , data , resumeContext )
345+ : continueAfter (resumed , steps , index , data ));
273346 }
274347
275348 private ExecutionResult executeStep (WorkflowStep step , RunData data , AgentExecutionContext context ) {
@@ -299,22 +372,7 @@ private ExecutionResult executeStep(WorkflowStep step, RunData data, AgentExecut
299372 ExecutionResult result = executeStep (loop .body (), data , context );
300373 if (result .suspension != null ) {
301374 int nextIteration = iteration + 1 ;
302- return result .continueWith ((request , resumeContext ) -> {
303- ExecutionResult resumed = result .continuation .resume (request , resumeContext );
304- if (resumed .suspension != null ) {
305- return resumed ;
306- }
307- for (int next = nextIteration ; next < loop .maxIterations (); next ++) {
308- if (!truthy (resolve (loop .condition (), data ))) {
309- return ExecutionResult .completed (data );
310- }
311- ExecutionResult nested = executeStep (loop .body (), data , resumeContext );
312- if (nested .suspension != null ) {
313- return nested ;
314- }
315- }
316- return ExecutionResult .completed (data );
317- });
375+ return continueLoopAfter (result , loop , nextIteration , data );
318376 }
319377 }
320378 throw new WorkflowExecutionException ("Workflow loop exceeded maxIterations: " + loop .id ());
@@ -366,34 +424,56 @@ private ExecutionResult executeSubflow(WorkflowStep.Subflow subflow, RunData dat
366424 }
367425 }
368426
427+ /**
428+ * The loop counterpart of {@link #continueAfter}: the remaining iterations survive
429+ * any number of further suspensions, both of the wrapped continuation and of the
430+ * body invocations inside the remaining iterations.
431+ */
432+ private ExecutionResult continueLoopAfter (ExecutionResult suspended , WorkflowStep .Loop loop , int nextIteration ,
433+ RunData data ) {
434+ return suspended .continueWith ((resumed , request , resumeContext ) -> {
435+ if (resumed .suspension != null ) {
436+ return continueLoopAfter (resumed , loop , nextIteration , data );
437+ }
438+ for (int next = nextIteration ; next < loop .maxIterations (); next ++) {
439+ if (!truthy (resolve (loop .condition (), data ))) {
440+ return ExecutionResult .completed (data );
441+ }
442+ ExecutionResult nested = executeStep (loop .body (), data , resumeContext );
443+ if (nested .suspension != null ) {
444+ return continueLoopAfter (nested , loop , next + 1 , data );
445+ }
446+ }
447+ return ExecutionResult .completed (data );
448+ });
449+ }
450+
369451 private ExecutionResult executeAgent (WorkflowStep .Agent step , RunData data , AgentExecutionContext context ) {
370452 Agent agent = Objects .requireNonNull (agentResolver .apply (step .agentRef ()),
371453 "agent resolver returned no agent for " + step .agentRef ());
372454 Map <String , Object > inputs = resolveMap (step .inputs (), data );
373455 AgentOutcome outcome = await (agent .invoke (new AgentRequest (data .messages , inputs , null ), context ));
456+ return resumeUntilCompleted (step , agent , data , outcome );
457+ }
458+
459+ /**
460+ * Applies a completed child outcome, or suspends on the child's own resume token
461+ * and re-enters this same path on resume, so any number of child suspensions is
462+ * resumed until the child actually completes.
463+ */
464+ private ExecutionResult resumeUntilCompleted (WorkflowStep .Agent step , Agent agent , RunData data ,
465+ AgentOutcome outcome ) {
374466 data .messages .addAll (outcome .messages ());
375467 data .addUsage (outcome .usage ());
376- if (outcome .status () == AgentOutcome .Status .SUSPENDED ) {
377- return ExecutionResult .suspended (data , outcome .suspension ().prompts (), (request , resumeContext ) -> {
378- AgentOutcome resumed = await (agent .invoke (new AgentRequest (request .messages (), request .inputs (),
379- outcome .suspension ().resumeToken ()), resumeContext ));
380- data .messages .addAll (resumed .messages ());
381- data .addUsage (resumed .usage ());
382- if (resumed .status () == AgentOutcome .Status .SUSPENDED ) {
383- return ExecutionResult .suspended (data , resumed .suspension ().prompts (), (next , nextContext ) -> {
384- AgentOutcome finalOutcome = await (agent .invoke (new AgentRequest (next .messages (), next .inputs (),
385- resumed .suspension ().resumeToken ()), nextContext ));
386- data .messages .addAll (finalOutcome .messages ());
387- data .addUsage (finalOutcome .usage ());
388- return finalOutcome .status () == AgentOutcome .Status .SUSPENDED
389- ? ExecutionResult .suspended (data , finalOutcome .suspension ().prompts (), (again , againContext ) ->
390- ExecutionResult .completed (data )) : applyAgentOutput (step , finalOutcome , data );
391- });
392- }
393- return applyAgentOutput (step , resumed , data );
394- });
395- }
396- return applyAgentOutput (step , outcome , data );
468+ if (outcome .status () != AgentOutcome .Status .SUSPENDED ) {
469+ return applyAgentOutput (step , outcome , data );
470+ }
471+ AgentOutcome .Suspension suspension = outcome .suspension ();
472+ return ExecutionResult .suspended (data , suspension .prompts (), (request , resumeContext ) -> {
473+ AgentOutcome resumed = await (agent .invoke (
474+ new AgentRequest (request .messages (), request .inputs (), suspension .resumeToken ()), resumeContext ));
475+ return resumeUntilCompleted (step , agent , data , resumed );
476+ });
397477 }
398478
399479 private ExecutionResult applyAgentOutput (WorkflowStep .Agent step , AgentOutcome outcome , RunData data ) {
@@ -641,6 +721,12 @@ private interface Continuation {
641721 ExecutionResult resume (AgentRequest request , AgentExecutionContext context );
642722 }
643723
724+ /** The work that continues after the wrapped continuation has resumed exactly once. */
725+ @ FunctionalInterface
726+ private interface ContinuedStep {
727+ ExecutionResult after (ExecutionResult resumed , AgentRequest request , AgentExecutionContext context );
728+ }
729+
644730 private record SuspensionData (Map <String , Object > prompts ) {
645731 }
646732
@@ -653,10 +739,13 @@ private static ExecutionResult suspended(RunData data, Map<String, Object> promp
653739 return new ExecutionResult (data , new SuspensionData (Map .copyOf (prompts )), continuation );
654740 }
655741
656- private ExecutionResult continueWith (Continuation next ) {
657- return new ExecutionResult (null , suspension , (request , context ) -> {
658- ExecutionResult result = continuation .resume (request , context );
659- return result .suspension == null ? next .resume (request , context ) : result ;
742+ private ExecutionResult continueWith (ContinuedStep next ) {
743+ // The wrapper keeps the suspension-point snapshot: the suspended outcome is
744+ // built from this data before the continuation ever runs. The continuation
745+ // itself runs exactly once; the step after the resume receives its result.
746+ return new ExecutionResult (data , suspension , (request , context ) -> {
747+ ExecutionResult resumed = continuation .resume (request , context );
748+ return next .after (resumed , request , context );
660749 });
661750 }
662751 }
0 commit comments