Call runs the function in a fresh FunctionScope and returns the computed return values keyed by return uid.
(ctx context.Context, args map[string]expr.Value)
| 24 | // Call runs the function in a fresh FunctionScope and returns |
| 25 | // the computed return values keyed by return uid. |
| 26 | func (f *Function) Call(ctx context.Context, args map[string]expr.Value) (map[string]expr.Value, error) { |
| 27 | fs, err := NewFunctionScope(f.DeclaredVars, args) |
| 28 | if err != nil { |
| 29 | return nil, fmt.Errorf("function %s: %w", f.Info.Name, err) |
| 30 | } |
| 31 | // Seed function scope with node outputs |
| 32 | for _, a := range f.Executables { |
| 33 | if em, ok := a.(Emitter); ok { |
| 34 | RegisterNodeOutputs(fs, em) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Seed the call scope with the entry edge's side effects (e.g. an AgentTask |
| 39 | // prompt) before the entry node runs, evaluated against the freshly-seeded |
| 40 | // args. A zero transition is a no-op. |
| 41 | if err := f.EntryTransition.Apply(fs); err != nil { |
| 42 | return nil, fmt.Errorf("function %s: entry transition: %w", f.Info.Name, err) |
| 43 | } |
| 44 | |
| 45 | // Run the function scoped state machine until it returns to idle (must be |
| 46 | // acyclic — a cycle here would otherwise hang this Call, and with it the |
| 47 | // state-runner, forever; the ctx check keeps such a loop cancellable). |
| 48 | state := f.EntryTransition.TargetID |
| 49 | for state != StateIdle { |
| 50 | select { |
| 51 | case <-ctx.Done(): |
| 52 | return nil, fmt.Errorf("function %s: %w", f.Info.Name, ctx.Err()) |
| 53 | default: |
| 54 | } |
| 55 | node, ok := f.Executables[state] |
| 56 | if !ok { |
| 57 | return nil, fmt.Errorf("function %s: node %q not found", f.Info.Name, state) |
| 58 | } |
| 59 | next, err := node.Execute(ctx, fs) |
| 60 | if err != nil { |
| 61 | return nil, fmt.Errorf("function %s: node %s: %w", f.Info.Name, state, err) |
| 62 | } |
| 63 | state = next |
| 64 | } |
| 65 | |
| 66 | // Evaluate output expressions using the function scope and return. |
| 67 | out := make(map[string]expr.Value, len(f.OutputAssignments)) |
| 68 | for _, ret := range f.Info.Returns { |
| 69 | e, ok := f.OutputAssignments[ret.Uid] |
| 70 | if !ok { |
| 71 | return nil, fmt.Errorf("function %s: missing output assignment for return %s", f.Info.Name, ret.Name) |
| 72 | } |
| 73 | v, err := expr.Eval(e, fs) |
| 74 | if err != nil { |
| 75 | return nil, fmt.Errorf("function %s: output assignment %s: %w", f.Info.Name, ret.Name, err) |
| 76 | } |