diff --git a/cmd/lk/simulate.go b/cmd/lk/simulate.go index efe65487..2c085a13 100644 --- a/cmd/lk/simulate.go +++ b/cmd/lk/simulate.go @@ -380,11 +380,22 @@ func scenarioGroupToYAML(group *livekit.ScenarioGroup) ([]byte, error) { if f.ID == "" { f.ID = utils.NewGuid(utils.ScenarioGroupPrefix) } + for name, node := range group.GetNodes() { + v, err := protoToYAML(node) + if err != nil { + return nil, fmt.Errorf("failed to encode node %q: %w", name, err) + } + if f.Nodes == nil { + f.Nodes = map[string]yaml.Node{} + } + f.Nodes[name] = v + } for _, s := range group.GetScenarios() { ys := yamlScenario{ ID: s.GetId(), Label: s.GetLabel(), Instructions: s.GetInstructions(), + Start: s.GetStart(), AgentExpectations: s.GetAgentExpectations(), Tags: s.GetTags(), } @@ -404,17 +415,20 @@ func scenarioGroupToYAML(group *livekit.ScenarioGroup) ([]byte, error) { } // scenariosFile mirrors a scenarios.yaml; `userdata` is a nested mapping here -// and JSON-encoded into the proto's string field. +// and JSON-encoded into the proto's string field. Each `nodes` entry is a +// SimulatorNode in protojson form (see simulate_flow.go). type scenariosFile struct { - ID string `yaml:"id"` - Name string `yaml:"name"` - Scenarios []yamlScenario `yaml:"scenarios"` + ID string `yaml:"id"` + Name string `yaml:"name"` + Nodes map[string]yaml.Node `yaml:"nodes,omitempty"` + Scenarios []yamlScenario `yaml:"scenarios"` } type yamlScenario struct { ID string `yaml:"id"` Label string `yaml:"label"` - Instructions string `yaml:"instructions"` + Instructions string `yaml:"instructions,omitempty"` + Start string `yaml:"start,omitempty"` AgentExpectations string `yaml:"agent_expectations"` Tags map[string]string `yaml:"tags"` Userdata map[string]any `yaml:"userdata"` @@ -488,6 +502,11 @@ func loadScenarioGroup(path string) (*livekit.ScenarioGroup, error) { return nil, fmt.Errorf("scenarios file has no id") } group := &livekit.ScenarioGroup{Id: f.ID, Name: f.Name} + nodes, err := decodeNodes(f.Nodes) + if err != nil { + return nil, err + } + group.Nodes = nodes seen := map[string]bool{} for _, s := range f.Scenarios { if s.ID == "" { @@ -497,6 +516,13 @@ func loadScenarioGroup(path string) (*livekit.ScenarioGroup, error) { return nil, fmt.Errorf("duplicate scenario id %q", s.ID) } seen[s.ID] = true + if s.Start != "" && s.Instructions != "" { + return nil, fmt.Errorf("scenario %q: set `start` or `instructions`, not both", s.Label) + } + // with nodes in the file, a scenario with neither is most likely a misspelled `start` + if s.Start == "" && s.Instructions == "" && len(group.Nodes) > 0 { + return nil, fmt.Errorf("scenario %q: set `start` or `instructions`", s.Label) + } var userdata string if len(s.Userdata) > 0 { b, err := json.Marshal(s.Userdata) @@ -509,11 +535,15 @@ func loadScenarioGroup(path string) (*livekit.ScenarioGroup, error) { Id: s.ID, Label: s.Label, Instructions: s.Instructions, + Start: s.Start, AgentExpectations: s.AgentExpectations, Tags: s.Tags, Userdata: userdata, }) } + if err := checkFlows(group); err != nil { + return nil, err + } return group, nil } diff --git a/cmd/lk/simulate_flow.go b/cmd/lk/simulate_flow.go new file mode 100644 index 00000000..322dc4b9 --- /dev/null +++ b/cmd/lk/simulate_flow.go @@ -0,0 +1,369 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "regexp" + "sort" + "strings" + "time" + + "gopkg.in/yaml.v3" + + "github.com/livekit/protocol/livekit" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" +) + +// builtinNodePrefix marks the nodes the server provides, such as +// livekit/hangup. Which built-ins exist is for the server to say. +const builtinNodePrefix = "livekit/" + +// maxNodeTimeout is the documented limit of SimulatorNode.Timeout.after. +const maxNodeTimeout = 20 * time.Second + +// decodeNodes reads the `nodes` of a scenarios.yaml. +func decodeNodes(nodes map[string]yaml.Node) (map[string]*livekit.SimulatorNode, error) { + if len(nodes) == 0 { + return nil, nil + } + names := make([]string, 0, len(nodes)) + for name := range nodes { + names = append(names, name) + } + sort.Strings(names) + out := make(map[string]*livekit.SimulatorNode, len(nodes)) + for _, name := range names { + value := nodes[name] + node, err := decodeNode(name, &value) + if err != nil { + return nil, err + } + out[name] = node + } + return out, nil +} + +// decodeNode reads one entry of a scenarios.yaml's `nodes`. +func decodeNode(name string, value *yaml.Node) (*livekit.SimulatorNode, error) { + if strings.HasPrefix(name, builtinNodePrefix) { + return nil, fmt.Errorf("node %q: the %s prefix is reserved for built-in nodes", name, builtinNodePrefix) + } + node := &livekit.SimulatorNode{} + if err := yamlToProto(value, node); err != nil { + return nil, fmt.Errorf("node %q: %w", name, err) + } + return node, nil +} + +// jsonPosition is where protojson saw an error in the JSON it was given, +// which is not a place in the user's file. +var jsonPosition = regexp.MustCompile(`\(line \d+:\d+\):\s*`) + +// yamlToProto decodes YAML into m through protojson, so field names, enum +// names, and durations follow the server's parser. A scalar goes in as its +// source text, except an integer for an enum field: otherwise YAML reads +// `2026-01-01` as a date and `0123` as an octal number. Errors name the line +// in the YAML. +func yamlToProto(n *yaml.Node, m proto.Message) error { + d := yamlDecoder{open: map[yamlPlace]bool{}} + v, err := d.message(n, m.ProtoReflect().Descriptor()) + if err != nil { + return err + } + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return err + } + if err := protojson.Unmarshal(b.Bytes(), m); err != nil { + return fmt.Errorf("line %d: %s", n.Line, jsonPosition.ReplaceAllString(err.Error(), "")) + } + return nil +} + +// yamlDecoder turns YAML into the JSON form of a message. +type yamlDecoder struct { + // the mappings and sequences being read, so an anchor that contains itself + // fails instead of recursing forever; keyed by place, since a node can be + // a copy of the one an alias points to + open map[yamlPlace]bool +} + +type yamlPlace struct{ line, column int } + +func placeOf(n *yaml.Node) yamlPlace { return yamlPlace{n.Line, n.Column} } + +func (d *yamlDecoder) message(n *yaml.Node, md protoreflect.MessageDescriptor) (any, error) { + n, err := d.resolve(n) + if err != nil { + return nil, err + } + if isYAMLNull(n) { + return nil, fmt.Errorf("line %d: no fields", n.Line) + } + if n.Kind != yaml.MappingNode { + return nil, fmt.Errorf("line %d: expected a mapping", n.Line) + } + if err := d.enter(n); err != nil { + return nil, err + } + defer d.leave(n) + pairs, err := d.pairs(n) + if err != nil { + return nil, err + } + out := make(map[string]any, len(pairs)) + for _, pair := range pairs { + key, value := pair[0], pair[1] + fd := md.Fields().ByJSONName(key.Value) + if fd == nil { + fd = md.Fields().ByTextName(key.Value) + } + if fd == nil { + return nil, fmt.Errorf("line %d: unknown field %q", key.Line, key.Value) + } + v, err := d.field(key, value, fd) + if err != nil { + return nil, err + } + out[key.Value] = v + } + return out, nil +} + +func (d *yamlDecoder) field(key, n *yaml.Node, fd protoreflect.FieldDescriptor) (any, error) { + n, err := d.resolve(n) + if err != nil { + return nil, err + } + if isYAMLNull(n) { + return nil, fmt.Errorf("line %d: %s has no value (quote a value that starts with #)", key.Line, key.Value) + } + if !fd.IsList() { + return d.single(n, fd) + } + if n.Kind != yaml.SequenceNode { + return nil, fmt.Errorf("line %d: %s takes a list", n.Line, key.Value) + } + if err := d.enter(n); err != nil { + return nil, err + } + defer d.leave(n) + out := make([]any, 0, len(n.Content)) + for _, item := range n.Content { + item, err := d.resolve(item) + if err != nil { + return nil, err + } + if isYAMLNull(item) { + return nil, fmt.Errorf("line %d: empty item in %s", item.Line, key.Value) + } + v, err := d.single(item, fd) + if err != nil { + return nil, err + } + out = append(out, v) + } + return out, nil +} + +// single is one value of fd: a nested message, or a scalar. +func (d *yamlDecoder) single(n *yaml.Node, fd protoreflect.FieldDescriptor) (any, error) { + if fd.Kind() == protoreflect.MessageKind && n.Kind == yaml.MappingNode { + return d.message(n, fd.Message()) + } + // every other value is a scalar, a duration included + if n.Kind != yaml.ScalarNode { + return nil, fmt.Errorf("line %d: %s takes a single value", n.Line, fd.TextName()) + } + if n.Style&yaml.TaggedStyle != 0 && n.ShortTag() != "!!str" && n.ShortTag() != "!!int" { + return nil, fmt.Errorf("line %d: the %s tag is not supported", n.Line, n.ShortTag()) + } + if fd.Kind() == protoreflect.EnumKind && n.ShortTag() == "!!int" { + return json.Number(n.Value), nil // protojson takes an enum's number as well as its name + } + return n.Value, nil +} + +// pairs is a mapping's keys and values, with `<<` merge keys expanded. A key +// the mapping sets itself wins over a merged one, and an earlier merge wins +// over a later one, as YAML defines. +func (d *yamlDecoder) pairs(n *yaml.Node) ([][2]*yaml.Node, error) { + var own, merged [][2]*yaml.Node + seen := map[string]bool{} + for i := 0; i+1 < len(n.Content); i += 2 { + key, value := n.Content[i], n.Content[i+1] + if key.ShortTag() == "!!merge" { + sources, err := d.mergeSources(value) + if err != nil { + return nil, err + } + for _, source := range sources { + if err := d.enter(source); err != nil { + return nil, err + } + inner, err := d.pairs(source) + d.leave(source) + if err != nil { + return nil, err + } + merged = append(merged, inner...) + } + continue + } + if seen[key.Value] { + return nil, fmt.Errorf("line %d: duplicate key %q", key.Line, key.Value) + } + seen[key.Value] = true + own = append(own, [2]*yaml.Node{key, value}) + } + for _, pair := range merged { + if !seen[pair[0].Value] { + seen[pair[0].Value] = true + own = append(own, pair) + } + } + return own, nil +} + +func (d *yamlDecoder) mergeSources(n *yaml.Node) ([]*yaml.Node, error) { + n, err := d.resolve(n) + if err != nil { + return nil, err + } + items := []*yaml.Node{n} + if n.Kind == yaml.SequenceNode { + items = n.Content + } + sources := make([]*yaml.Node, 0, len(items)) + for _, item := range items { + item, err := d.resolve(item) + if err != nil { + return nil, err + } + if item.Kind != yaml.MappingNode { + return nil, fmt.Errorf("line %d: `<<` merges only mappings", item.Line) + } + sources = append(sources, item) + } + return sources, nil +} + +// resolve follows aliases and document wrappers to the node they stand for. +func (d *yamlDecoder) resolve(n *yaml.Node) (*yaml.Node, error) { + for { + switch n.Kind { + case yaml.AliasNode: + n = n.Alias + case yaml.DocumentNode: + if len(n.Content) == 0 { + return nil, fmt.Errorf("line %d: empty document", n.Line) + } + n = n.Content[0] + default: + return n, nil + } + } +} + +func (d *yamlDecoder) enter(n *yaml.Node) error { + if d.open[placeOf(n)] { + return fmt.Errorf("line %d: anchor %q contains itself", n.Line, n.Anchor) + } + d.open[placeOf(n)] = true + return nil +} + +func (d *yamlDecoder) leave(n *yaml.Node) { + delete(d.open, placeOf(n)) +} + +func isYAMLNull(n *yaml.Node) bool { + return n.Kind == yaml.ScalarNode && n.ShortTag() == "!!null" +} + +// protoToYAML is the inverse of yamlToProto. +func protoToYAML(m proto.Message) (yaml.Node, error) { + var n yaml.Node + b, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(m) + if err != nil { + return n, err + } + var v any + if err := json.Unmarshal(b, &v); err != nil { + return n, err + } + err = n.Encode(v) + return n, err +} + +// checkFlows reports what the server would reject in the nodes a scenario can +// reach, so a bad file fails before the agent starts. Nodes no scenario +// reaches are not checked, as on the server. +func checkFlows(group *livekit.ScenarioGroup) error { + var errs []error + var pending []string + follow := func(where, field, to string) { + switch { + case to == "": + errs = append(errs, fmt.Errorf("%s: %s names no node", where, field)) + case strings.HasPrefix(to, builtinNodePrefix): + // a built-in: the server knows which exist + case group.GetNodes()[to] == nil: + errs = append(errs, fmt.Errorf("%s: %s %q is not a node", where, field, to)) + default: + pending = append(pending, to) + } + } + for _, s := range group.GetScenarios() { + if s.GetStart() != "" { + follow(fmt.Sprintf("scenario %q", s.GetLabel()), "start", s.GetStart()) + } + } + checked := map[string]bool{} + for len(pending) > 0 { + name := pending[0] + pending = pending[1:] + if checked[name] { + continue + } + checked[name] = true + node := group.GetNodes()[name] + where := fmt.Sprintf("node %q", name) + if node.GetThen() != "" { + follow(where, "then", node.GetThen()) + } + for i, route := range node.GetRoutes() { + follow(where, fmt.Sprintf("routes[%d].to", i), route.GetTo()) + } + if timeout := node.GetTimeout(); timeout != nil { + follow(where, "timeout.to", timeout.GetTo()) + switch after := timeout.GetAfter().AsDuration(); { + case after <= 0: + errs = append(errs, fmt.Errorf("%s: timeout.after must be more than 0s", where)) + case after > maxNodeTimeout: + errs = append(errs, fmt.Errorf("%s: timeout.after is %s, more than %s", where, after, maxNodeTimeout)) + } + } + } + return errors.Join(errs...) +} diff --git a/cmd/lk/simulate_scenario_ids_test.go b/cmd/lk/simulate_scenario_ids_test.go index 73f8b114..5eb2ed1f 100644 --- a/cmd/lk/simulate_scenario_ids_test.go +++ b/cmd/lk/simulate_scenario_ids_test.go @@ -20,9 +20,12 @@ import ( "regexp" "strings" "testing" + "time" "github.com/livekit/protocol/livekit" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/durationpb" "gopkg.in/yaml.v3" ) @@ -197,3 +200,509 @@ func TestScenarioGroupToYAMLFillsIDs(t *testing.T) { require.True(t, strings.HasPrefix(loaded.GetScenarios()[0].GetId(), "SCN_")) require.Equal(t, "fixed", loaded.GetScenarios()[1].GetId()) } + +func TestLoadScenarioGroupSimulatorFlow(t *testing.T) { + const nodes = ` +nodes: + menu: + say: Press 1 for sales. + speaker: MACHINE + routes: + - match: "1" + to: sales + timeout: + after: 8s + to: livekit/hangup + sales: + instructions: You are a sales rep. +` + cases := []struct { + name string + yaml string + want *livekit.ScenarioGroup + wantErr []string + }{ + { + name: "nodes and start", + yaml: ` +id: g1 +name: n` + nodes + ` +scenarios: + - id: s1 + label: call + start: menu +`, + want: &livekit.ScenarioGroup{ + Id: "g1", + Name: "n", + Nodes: map[string]*livekit.SimulatorNode{ + "menu": { + Say: "Press 1 for sales.", + Speaker: livekit.SimulatorNode_MACHINE, + Routes: []*livekit.SimulatorNode_Route{{Match: "1", To: "sales"}}, + Timeout: &livekit.SimulatorNode_Timeout{After: durationpb.New(8 * time.Second), To: "livekit/hangup"}, + }, + "sales": { + Instructions: "You are a sales rep.", + }, + }, + Scenarios: []*livekit.Scenario{{ + Id: "s1", + Label: "call", + Start: "menu", + }}, + }, + }, + { + name: "built-in start", + yaml: ` +id: g1 +name: n +scenarios: + - id: s1 + label: call + start: livekit/unavailable +`, + want: &livekit.ScenarioGroup{ + Id: "g1", + Name: "n", + Scenarios: []*livekit.Scenario{{Id: "s1", Label: "call", Start: "livekit/unavailable"}}, + }, + }, + { + name: "instructions only", + yaml: ` +id: g1 +name: n +scenarios: + - id: s1 + label: order + instructions: order a burger + agent_expectations: confirms the order +`, + want: &livekit.ScenarioGroup{ + Id: "g1", + Name: "n", + Scenarios: []*livekit.Scenario{{ + Id: "s1", + Label: "order", + Instructions: "order a burger", + AgentExpectations: "confirms the order", + }}, + }, + }, + { + name: "unknown node key", + yaml: ` +id: g1 +name: n +nodes: + menu: + sya: typo +scenarios: + - id: s1 + label: call + start: menu +`, + wantErr: []string{`node "menu": line 6: unknown field "sya"`}, + }, + { + name: "start and instructions", + yaml: ` +id: g1 +name: n` + nodes + ` +scenarios: + - id: s1 + label: call + start: menu + instructions: hi +`, + wantErr: []string{`scenario "call"`, "`start` or `instructions`, not both"}, + }, + { + name: "unknown start", + yaml: ` +id: g1 +name: n` + nodes + ` +scenarios: + - id: s1 + label: call + start: nowhere +`, + wantErr: []string{`scenario "call"`, `start "nowhere"`}, + }, + { + name: "misspelled start", + yaml: ` +id: g1 +name: n` + nodes + ` +scenarios: + - id: s1 + label: call + strat: menu +`, + wantErr: []string{`scenario "call": set ` + "`start` or `instructions`"}, + }, + { + name: "scalars keep their source text", + yaml: ` +id: g1 +name: n +nodes: + menu: + say: 2026-01-01 + routes: + - match: 0123 + to: livekit/hangup + - match: 1 + to: livekit/hangup + - match: yes + to: livekit/hangup +scenarios: + - id: s1 + label: call + start: menu +`, + want: &livekit.ScenarioGroup{ + Id: "g1", + Name: "n", + Nodes: map[string]*livekit.SimulatorNode{ + "menu": { + Say: "2026-01-01", + Routes: []*livekit.SimulatorNode_Route{ + {Match: "0123", To: "livekit/hangup"}, + {Match: "1", To: "livekit/hangup"}, + {Match: "yes", To: "livekit/hangup"}, + }, + }, + }, + Scenarios: []*livekit.Scenario{{Id: "s1", Label: "call", Start: "menu"}}, + }, + }, + { + name: "unquoted pound", + yaml: ` +id: g1 +name: n +nodes: + menu: + say: Enter your number. + routes: + - match: # + to: livekit/hangup +scenarios: + - id: s1 + label: call + start: menu +`, + wantErr: []string{`node "menu"`, "line 8: match has no value"}, + }, + { + name: "empty then", + yaml: ` +id: g1 +name: n +nodes: + menu: + say: hi + then: +scenarios: + - id: s1 + label: call + start: menu +`, + wantErr: []string{`node "menu"`, "then has no value"}, + }, + { + name: "dangling targets", + yaml: ` +id: g1 +name: n +nodes: + menu: + say: hi + routes: + - match: "1" + to: nowhere + - match: "2" + timeout: + after: 30s + to: next + next: + say: bye + then: gone +scenarios: + - id: s1 + label: call + start: menu +`, + wantErr: []string{ + `node "menu": routes[0].to "nowhere" is not a node`, + `node "menu": routes[1].to names no node`, + `node "menu": timeout.after is 30s, more than 20s`, + `node "next": then "gone" is not a node`, + }, + }, + { + name: "unreached nodes and unknown built-ins pass", + yaml: ` +id: g1 +name: n +nodes: + orphan: + say: hi + then: nowhere +scenarios: + - id: s1 + label: call + start: livekit/busy +`, + want: &livekit.ScenarioGroup{ + Id: "g1", + Name: "n", + Nodes: map[string]*livekit.SimulatorNode{"orphan": {Say: "hi", Then: "nowhere"}}, + Scenarios: []*livekit.Scenario{{Id: "s1", Label: "call", Start: "livekit/busy"}}, + }, + }, + { + name: "an anchor that contains itself", + yaml: ` +id: g1 +name: n +nodes: + menu: &menu + say: hi + routes: [*menu] +scenarios: + - id: s1 + label: call + start: menu +`, + wantErr: []string{`node "menu": line 5: anchor "menu" contains itself`}, + }, + { + name: "an anchor used as a string field", + yaml: ` +id: g1 +name: n +nodes: + loop: &loop { say: hi, then: *loop } +scenarios: + - id: s1 + label: call + start: loop +`, + wantErr: []string{`node "loop": line 5: then takes a single value`}, + }, + { + name: "merge keys, numeric enums, and aliases", + yaml: ` +id: g1 +name: n +x-defaults: &machine + speaker: MACHINE + timeout: { after: 8s, to: livekit/hangup } +nodes: + menu: + <<: *machine + say: For Sam, press 1. + timeout: { after: 5s, to: menu } + greeting: + <<: [*machine] + say: Hello. + speaker: 0 +scenarios: + - id: s1 + label: call + start: menu + - id: s2 + label: greeting + start: greeting +`, + want: &livekit.ScenarioGroup{ + Id: "g1", + Name: "n", + Nodes: map[string]*livekit.SimulatorNode{ + "menu": { + Say: "For Sam, press 1.", + Speaker: livekit.SimulatorNode_MACHINE, + Timeout: &livekit.SimulatorNode_Timeout{After: durationpb.New(5 * time.Second), To: "menu"}, + }, + "greeting": { + Say: "Hello.", + Speaker: livekit.SimulatorNode_PERSON, + Timeout: &livekit.SimulatorNode_Timeout{After: durationpb.New(8 * time.Second), To: "livekit/hangup"}, + }, + }, + Scenarios: []*livekit.Scenario{ + {Id: "s1", Label: "call", Start: "menu"}, + {Id: "s2", Label: "greeting", Start: "greeting"}, + }, + }, + }, + { + name: "a null behind an alias", + yaml: ` +id: g1 +name: n +x-none: &none ~ +nodes: + menu: { say: hi, then: *none } +scenarios: + - id: s1 + label: call + start: menu +`, + wantErr: []string{`node "menu": line 6: then has no value`}, + }, + { + name: "an explicit tag", + yaml: ` +id: g1 +name: n +nodes: + menu: { say: !!binary aGk=, then: livekit/hangup } +scenarios: + - id: s1 + label: call + start: menu +`, + wantErr: []string{`node "menu": line 5: the !!binary tag is not supported`}, + }, + { + name: "an empty node", + yaml: ` +id: g1 +name: n +nodes: + menu: +scenarios: + - id: s1 + label: call + start: menu +`, + wantErr: []string{`node "menu": line 5: no fields`}, + }, + { + name: "a timeout of zero", + yaml: ` +id: g1 +name: n +nodes: + menu: { say: hi, timeout: { after: 0s, to: livekit/hangup } } + hold: { say: hold, timeout: { to: livekit/hangup } } +scenarios: + - id: s1 + label: call + start: menu + - id: s2 + label: hold + start: hold +`, + wantErr: []string{ + `node "menu": timeout.after must be more than 0s`, + `node "hold": timeout.after must be more than 0s`, + }, + }, + { + name: "reserved node name", + yaml: ` +id: g1 +name: n +nodes: + livekit/hangup: + say: bye +scenarios: + - id: s1 + label: call + start: livekit/hangup +`, + wantErr: []string{`node "livekit/hangup": the livekit/ prefix is reserved`}, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + group, err := loadScenarioGroup(writeScenariosFile(t, c.yaml)) + if c.wantErr != nil { + for _, e := range c.wantErr { + require.ErrorContains(t, err, e) + } + require.NotRegexp(t, `\(line \d+:\d+\)`, err.Error(), "a position in the JSON, not the YAML") + return + } + require.NoError(t, err) + require.True(t, proto.Equal(c.want, group), "got %v", group) + }) + } +} + +func TestScenarioGroupToYAMLRoundTripsFlow(t *testing.T) { + path := writeScenariosFile(t, ` +id: g1 +name: n +nodes: + menu: + say: Press 1. + speaker: MACHINE + routes: + - match: "1" + to: livekit/hangup + - match: "#" + to: livekit/hangup + timeout: + after: 1.5s + to: livekit/voicemail + date: + say: "2026-01-01" + then: livekit/hangup +scenarios: + - id: s1 + label: call + start: menu +`) + group, err := loadScenarioGroup(path) + require.NoError(t, err) + out, err := scenarioGroupToYAML(group) + require.NoError(t, err) + again, err := loadScenarioGroup(writeScenariosFile(t, string(out))) + require.NoError(t, err) + require.True(t, proto.Equal(group, again), "got %v\nyaml:\n%s", again, out) +} + +func TestInsertScenarioIDsKeepsNodes(t *testing.T) { + in := `name: n +nodes: + menu: + say: hi # greet +scenarios: + - label: call + start: menu +` + out, added, err := insertScenarioIDs([]byte(in)) + require.NoError(t, err) + require.Equal(t, 2, added) + ids := regexp.MustCompile(`(SCNG?)_\w+`) + want := `id: SCNG_x +name: n +nodes: + menu: + say: hi # greet +scenarios: + - id: SCN_x + label: call + start: menu +` + require.Equal(t, want, ids.ReplaceAllString(string(out), "${1}_x")) +} + +func TestScenarioWithoutStartOrInstructionsLoads(t *testing.T) { + group, err := loadScenarioGroup(writeScenariosFile(t, ` +id: g1 +name: n +scenarios: + - id: s1 + label: call +`)) + require.NoError(t, err) + require.Len(t, group.GetScenarios(), 1) +} diff --git a/go.mod b/go.mod index 27d6fc2e..3214d89e 100644 --- a/go.mod +++ b/go.mod @@ -24,7 +24,7 @@ require ( github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 github.com/joho/godotenv v1.5.1 github.com/klauspost/compress v1.20.1 - github.com/livekit/protocol v1.53.3-0.20261108034403-b499314eeb9a + github.com/livekit/protocol v1.54.1-0.20261113133823-facac3f93e4a github.com/livekit/server-sdk-go/v2 v2.20.0 github.com/mattn/go-isatty v0.0.22 github.com/moby/moby/client v0.4.1 diff --git a/go.sum b/go.sum index e384308f..86f86e02 100644 --- a/go.sum +++ b/go.sum @@ -366,8 +366,8 @@ github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731 h1:9x+U2HGLrSw5AT github.com/livekit/mageutil v0.0.0-20250511045019-0f1ff63f7731/go.mod h1:Rs3MhFwutWhGwmY1VQsygw28z5bWcnEYmS1OG9OxjOQ= github.com/livekit/mediatransportutil v0.0.0-20261014192331-dd8e31a0adc0 h1:BSLyHr3Lsl71bHGHsfiYNmbohugR2yoaf9HjAZeFJnc= github.com/livekit/mediatransportutil v0.0.0-20261014192331-dd8e31a0adc0/go.mod h1:o8CFmAdrVwzJNOCsQCLUzXRjokkufNshnQHOe4fRaqU= -github.com/livekit/protocol v1.53.3-0.20261108034403-b499314eeb9a h1:jtNeZN43OIHT4N3lIc0yKQxrHdFndRpJTlwylXq5/AE= -github.com/livekit/protocol v1.53.3-0.20261108034403-b499314eeb9a/go.mod h1:S0AnW03n6zgnWZOq+T4L1PtT9POxTBgrgEH1jyR6fl4= +github.com/livekit/protocol v1.54.1-0.20261113133823-facac3f93e4a h1:E2vN3nPvnjaf2TEChE7w/7pjj0sfC85P7euP6uYvpjQ= +github.com/livekit/protocol v1.54.1-0.20261113133823-facac3f93e4a/go.mod h1:S0AnW03n6zgnWZOq+T4L1PtT9POxTBgrgEH1jyR6fl4= github.com/livekit/psrpc v0.8.2 h1:7tbkhBJoYlK5Csfkdv1XYbZjyAQeaEZgupvIXNCv7Dc= github.com/livekit/psrpc v0.8.2/go.mod h1:6KnU8vULoizX0Er9NNfeKJDV8ug87j3fuo19M0bhj6Q= github.com/livekit/server-sdk-go/v2 v2.20.0 h1:c6GbM615QgLfBq9lsGiHiGaDniqeRlV9rv5PKMXs9+U=