From f8ac0bf672dfd7d9e5c6155646b51c7b72b6c2dc Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:31:05 -0500 Subject: [PATCH 01/15] feat(session): remember sessions, and mark a draft vf edited since its last compile Why: round 7 made every `conversation send` with the draft compile it first (3a5542e). It works, but puts a ~0.4 s compile on every message (draft send 1.55 s median, compile 0.40 s). The owner decided on an explicit session lifecycle (`vf session start`, `send`, `update`, `get`, `end`, `run-script`) and compile rule B: compile when a session starts, and before a turn only when vf itself edited the draft since the last compile. A conversation isn't pinned to a build: each turn runs the newest compile (live probe), so an edit reaches an open session once anything compiles. Design: internal/sessions keeps one small JSON file beside vf's config, ~/.config/vf/sessions.json, written whole and renamed into place. Per project and environment it holds the sessions vf started (ID, version, start time, the last reply's buttons) with the current one, and when vf last edited and compiled the draft. An edit that names no environment (a secret, a merge) marks all of the project's. The new package name keeps internal/session, the home prompt's context, as it is. The mark is set by one after-success SDK hook, since every request goes out through the SDK and its operation ID says what the request does. A successful POST, PUT, PATCH or DELETE marks its project's environment, but for writes that aren't edits: conversation turns, state and scripts, publish, test and evaluation runs and records, function and tool execute/check, knowledge-base query, searches, transcripts, analytics, workspaces and phone numbers. Any compile, vf's own or `vf environment compile`, clears it. A dry run's stand-in answer marks nothing. Marking too much costs one compile; a missed edit is still caught after the turn by needsRecompile. Change: internal/sessions (store, IDs s- plus 8 random characters), sdk/sdkinternal/hooks/editmark.go and one registration line. Tests: the store, which writes are edits and where project and environment are read, and real commands against a fake API (edit marks, compile clears, reads, turns, state, dry runs and refused edits don't). --- internal/cli/editmark_test.go | 98 +++++++ internal/sdk/sdkinternal/hooks/editmark.go | 103 +++++++ .../sdk/sdkinternal/hooks/editmark_test.go | 62 ++++ .../sdk/sdkinternal/hooks/registration.go | 2 + internal/sessions/sessions.go | 276 ++++++++++++++++++ internal/sessions/sessions_test.go | 109 +++++++ 6 files changed, 650 insertions(+) create mode 100644 internal/cli/editmark_test.go create mode 100644 internal/sdk/sdkinternal/hooks/editmark.go create mode 100644 internal/sdk/sdkinternal/hooks/editmark_test.go create mode 100644 internal/sessions/sessions.go create mode 100644 internal/sessions/sessions_test.go diff --git a/internal/cli/editmark_test.go b/internal/cli/editmark_test.go new file mode 100644 index 00000000..7417900b --- /dev/null +++ b/internal/cli/editmark_test.go @@ -0,0 +1,98 @@ +// This file is not generated by Speakeasy. It covers the edit mark compile +// rule B reads (internal/sessions, sdk/sdkinternal/hooks/editmark.go), with +// real vf commands against a fake API: an edit marks the draft, a compile +// clears it, and reads, turns, failures and dry runs leave it as it was. + +package cli + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sessions" +) + +// editServer answers every request as the API does a success, but for a +// write whose path says "fail", which it refuses. +func editServer(t *testing.T) string { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Query().Get("environmentAlias") == "fail": + w.WriteHeader(http.StatusUnprocessableEntity) + io.WriteString(w, `{"message":"Validation failed"}`) + case strings.HasSuffix(r.URL.Path, "/compile"): + io.WriteString(w, `{"message":"Environment compiled","durationMs":5}`) + case strings.Contains(r.URL.Path, "/conversation/"): + io.WriteString(w, `{"traces":[],"needsRecompile":false}`) + default: + io.WriteString(w, `{"message":"Agent updated."}`) + } + })) + t.Cleanup(srv.Close) + return srv.URL +} + +// runInHome runs vf with home as $HOME, so what one command records the +// next one reads. +func runInHome(t *testing.T, home, url string, agent bool, args ...string) (stdout, stderr string, err error) { + t.Helper() + t.Setenv("VF_TOKEN", "vfp_fake") + t.Setenv("VF_SERVER_URL", url) + t.Setenv("HOME", home) + output.ResetAgentMode() + t.Cleanup(output.ResetAgentMode) + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var out, errOut bytes.Buffer + root.SetOut(&out) + root.SetErr(&errOut) + root.SetIn(strings.NewReader("")) + mode := "--agent-mode=false" + if agent { + mode = "--agent-mode" + } + root.SetArgs(append(args, mode, "--no-interactive")) + err = renderError(root.ExecuteC()) // as main does + return out.String(), errOut.String(), err +} + +func TestAnEditMarksTheDraftUntilItIsCompiled(t *testing.T) { + url := editServer(t) + home := t.TempDir() + scope := []string{"-p", "p1", "-e", "main"} + step := func(name string, wantEdited bool, args ...string) { + t.Helper() + _, errOut, _ := runInHome(t, home, url, false, append(args, scope...)...) + if got := sessions.Edited("p1", "main"); got != wantEdited { + t.Errorf("after %s: edited %v, want %v\n%s", name, got, wantEdited, errOut) + } + } + step("a read", false, "agent", "get") + step("a dry run of an edit", false, "agent", "update", "--instructions", "Be brief.", "--dry-run") + step("a turn", false, "conversation", "send", "-u", "u1", "--text", "hi", "--no-compile") + step("setting a user's variables", false, "conversation", "state", "update-variables", "-u", "u1", "--variables", `{"tier":"gold"}`) + step("an edit", true, "agent", "update", "--instructions", "Be brief.") + step("a read after it", true, "agent", "get") + step("vf environment compile", false, "environment", "compile") + + // A refused edit changed nothing. + _, _, _ = runInHome(t, home, url, false, "agent", "update", "--instructions", "Be brief.", "-p", "p1", "-e", "fail") + if sessions.Edited("p1", "fail") { + t.Error("a refused edit marked the draft") + } + // An edit to another environment leaves this one alone. + _, _, _ = runInHome(t, home, url, false, "agent", "update", "--instructions", "Be brief.", "-p", "p1", "-e", "staging") + if sessions.Edited("p1", "main") || !sessions.Edited("p1", "staging") { + t.Error("an edit marked the wrong environment") + } +} diff --git a/internal/sdk/sdkinternal/hooks/editmark.go b/internal/sdk/sdkinternal/hooks/editmark.go new file mode 100644 index 00000000..ade1b18d --- /dev/null +++ b/internal/sdk/sdkinternal/hooks/editmark.go @@ -0,0 +1,103 @@ +// This file is not generated by Speakeasy. It notes, for compile rule B, +// when vf edits a project's draft and when the draft is compiled. +// +// A conversation runs the environment's newest compile, so a turn after an +// edit runs the old agent until something compiles the draft. vf used to +// compile before every turn, which put ~0.4 s on each message. Now it +// compiles when a session starts, and before a turn only when vf itself +// edited the draft since the last compile (internal/sessions). +// +// Every request goes out through the SDK, so its after-success hook sees +// them all. A write (POST, PUT, PATCH, DELETE) that succeeded marks its +// project's environment edited, unless it is one of the writes that aren't +// edits: conversation turns, state and scripts, publish, test and +// evaluation runs, executing a function or tool, a knowledge-base query, +// searches, transcripts and analytics. A compile clears the mark. A write +// that names no environment, such as a secret's, marks all of the +// project's. Marking too much costs one compile; an edit vf missed is still +// caught after the turn, by needsRecompile. + +package hooks + +import ( + "net/http" + "strings" + + "github.com/voiceflow/cli/internal/sessions" +) + +type editMarkHook struct{} + +var _ afterSuccessHook = (*editMarkHook)(nil) + +// dryRunHeader marks the stand-in answer of a --dry-run (output/dryrun.go): +// nothing was sent, so nothing changed. +const dryRunHeader = "X-Vf-Dry-Run" + +// The writes that write nothing to a draft, by the start of their +// operation's ID (its controller) or its end (what it does). Tests and +// evaluations are kept beside the agent, not in it. +var ( + notEditControllers = []string{ + "StableConversation", "StableTest", "StableEvaluation", "StableTranscript", + "StableAnalytics", "StableWorkspace", "StablePhoneNumber", + } + notEditActions = []string{ + "_publish", "_searchText", "_updateTrafficSplit", "_execute", "_check", "_query", + "_searchInstructionsV2", "_searchPromptV2", "_getMany", "_previewSitemap", + } +) + +// AfterSuccess marks the draft edited after a write, and compiled after a +// compile. It never changes the response. +func (h *editMarkHook) AfterSuccess(hookCtx AfterSuccessContext, res *http.Response) (*http.Response, error) { + if res == nil || res.Request == nil || res.Header.Get(dryRunHeader) != "" { + return res, nil + } + op := hookCtx.OperationID + projectID, env := projectAndEnvironment(res.Request) + switch { + case op == "StableEnvironmentController_compile": + _ = sessions.MarkCompiled(projectID, env) + case isEdit(res.Request.Method, op): + _ = sessions.MarkEdited(projectID, env) + } + return res, nil +} + +// isEdit reports whether a request with method to operation op writes to a +// project's draft. +func isEdit(method, op string) bool { + if method == http.MethodGet || method == http.MethodHead || op == "StableProjectController_create" { + return false // a new project has no session to keep up to date + } + for _, c := range notEditControllers { + if strings.HasPrefix(op, c) { + return false + } + } + for _, a := range notEditActions { + if strings.HasSuffix(op, a) { + return false + } + } + return true +} + +// projectAndEnvironment are the project ID and environment alias a request +// names: in its query (?projectID=…&environmentAlias=…), or in its path +// (/v1/stable/project/{projectID}, /v1/stable/environment/{alias}/…). +func projectAndEnvironment(req *http.Request) (projectID, env string) { + q := req.URL.Query() + projectID, env = q.Get("projectID"), q.Get("environmentAlias") + parts := strings.Split(strings.Trim(req.URL.Path, "/"), "/") + for i := 0; i+1 < len(parts); i++ { + switch { + case parts[i] == "project" && projectID == "": + projectID = parts[i+1] + case parts[i] == "environment" && env == "" && parts[i+1] != "merge" && parts[i+1] != "update-traffic-split": + env = parts[i+1] + } + } + return projectID, env +} diff --git a/internal/sdk/sdkinternal/hooks/editmark_test.go b/internal/sdk/sdkinternal/hooks/editmark_test.go new file mode 100644 index 00000000..ae873ebf --- /dev/null +++ b/internal/sdk/sdkinternal/hooks/editmark_test.go @@ -0,0 +1,62 @@ +// This file is not generated by Speakeasy. It covers editmark.go: which +// requests count as edits to a draft, and where their project and +// environment are read from. + +package hooks + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestWhichWritesAreEdits(t *testing.T) { + for _, c := range []struct { + method, op string + edit bool + }{ + {"PATCH", "StableAgentController_updateV2", true}, + {"PATCH", "StableAgentController_patchInstructionsV2", true}, + {"POST", "StableFunctionController_create", true}, + {"POST", "StableDocumentController_createText", true}, + {"PUT", "StableSecretController_setValue", true}, + {"DELETE", "StableToolController_deleteV2", true}, + {"PUT", "StableEnvironmentController_merge", true}, + {"GET", "StableAgentController_get", false}, + {"PUT", "StableConversationController_send", false}, + {"POST", "StableConversationController_runScript", false}, + {"PATCH", "StableConversationStateController_updateVariables", false}, + {"DELETE", "StableConversationStateController_delete", false}, + {"POST", "StableEnvironmentController_publish", false}, + {"POST", "StableTestRunController_create", false}, + {"POST", "StableTestController_create", false}, + {"POST", "StableEvaluationController_run", false}, + {"POST", "StableFunctionController_execute", false}, + {"POST", "StableFunctionController_check", false}, + {"POST", "StableKnowledgeBaseController_query", false}, + {"POST", "StableTranscriptController_searchV2", false}, + {"POST", "StableAnalyticsController_queryCallCount", false}, + {"POST", "StableAgentController_searchInstructionsV2", false}, + {"POST", "StablePromptController_getMany", false}, + {"POST", "StableProjectController_create", false}, + } { + if got := isEdit(c.method, c.op); got != c.edit { + t.Errorf("%s %s: edit %v, want %v", c.method, c.op, got, c.edit) + } + } +} + +func TestTheProjectAndEnvironmentComeFromTheQueryOrThePath(t *testing.T) { + for _, c := range []struct{ url, project, env string }{ + {"/v2/stable/agent?projectID=p1&environmentAlias=main", "p1", "main"}, + {"/v1/stable/environment/staging/compile?projectID=p1", "p1", "staging"}, + {"/v1/stable/project/p1", "p1", ""}, + {"/v2/stable/secret?projectID=p1", "p1", ""}, + {"/v1/stable/environment/merge?projectID=p1", "p1", ""}, + } { + req := httptest.NewRequest(http.MethodPost, c.url, nil) + if p, e := projectAndEnvironment(req); p != c.project || e != c.env { + t.Errorf("%s: %q %q, want %q %q", c.url, p, e, c.project, c.env) + } + } +} diff --git a/internal/sdk/sdkinternal/hooks/registration.go b/internal/sdk/sdkinternal/hooks/registration.go index 9145abad..4fb7ed2a 100644 --- a/internal/sdk/sdkinternal/hooks/registration.go +++ b/internal/sdk/sdkinternal/hooks/registration.go @@ -6,4 +6,6 @@ func initHooks(h *Hooks) { h.registerBeforeRequestHook(&clientTypeHook{}) h.registerBeforeRequestHook(&teachHook{}) + + h.registerAfterSuccessHook(&editMarkHook{}) // editmark.go: an edit marks the draft to compile before the next turn } diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go new file mode 100644 index 00000000..0a18b763 --- /dev/null +++ b/internal/sessions/sessions.go @@ -0,0 +1,276 @@ +// This file is not generated by Speakeasy. It remembers two things on this +// machine, per project and environment: the sessions vf started with the +// agent, and whether vf edited the draft since it was last compiled. +// +// `vf session send` without -s continues the session `vf session start` +// began, so vf keeps the last one started, with its version and start time: +// `vf session end` looks for the transcript created after that start. And +// a turn compiles the draft first only when vf itself edited it since the +// last compile (compile rule B): a conversation runs the newest compile, +// and a compile costs ~0.4 s, so a plain turn shouldn't pay for one. The +// mark is set by a hook on every successful request that writes to a +// project (sdk/sdkinternal/hooks/editmark.go), and cleared by every compile. +// +// It is one small JSON file beside vf's config, ~/.config/vf/sessions.json, +// written whole to a temporary file and renamed into place, so a reader +// never sees half of it. Two vf processes writing at once can lose one +// write: a lost edit mark is caught after the turn by needsRecompile, and a +// lost session by passing -s. + +package sessions + +import ( + "crypto/rand" + "encoding/json" + "os" + "path/filepath" + "slices" + "time" +) + +// Session is one conversation vf started with the agent. Its ID is the +// runtime's user ID: transcripts are filed under it. +type Session struct { + ID string `json:"id"` + Version string `json:"version"` // draft or published + StartedAt time.Time `json:"startedAt,omitzero"` + // Buttons are the ones the agent's last reply offered, for + // `vf session send --button`. + Buttons []Button `json:"buttons,omitempty"` +} + +// Button is a button the agent offered: its label, and the request a press +// sends. +type Button struct { + Name string `json:"name"` + Request json.RawMessage `json:"request,omitempty"` +} + +// AllEnvironments is the environment an edit marks when its request names +// none, such as a secret's: every environment of the project. +const AllEnvironments = "*" + +// keep is how many sessions vf remembers per project and environment. +const keep = 20 + +type scope struct { + Current string `json:"current,omitempty"` + Sessions []Session `json:"sessions,omitempty"` // newest first + EditedAt time.Time `json:"editedAt,omitzero"` + CompiledAt time.Time `json:"compiledAt,omitzero"` +} + +type file struct { + Scopes map[string]*scope `json:"scopes"` +} + +// Path is where the file is: ~/.config/vf/sessions.json. +func Path() string { + home, err := os.UserHomeDir() + if err != nil || home == "" { + return "" + } + return filepath.Join(home, ".config", "vf", "sessions.json") +} + +// now is the clock, a var so tests can step it. +var now = time.Now + +func key(projectID, env string) string { return projectID + "/" + env } + +func read() *file { + f := &file{Scopes: map[string]*scope{}} + if path := Path(); path != "" { + if data, err := os.ReadFile(path); err == nil { + _ = json.Unmarshal(data, f) + } + } + if f.Scopes == nil { + f.Scopes = map[string]*scope{} + } + return f +} + +func (f *file) scope(projectID, env string) *scope { + k := key(projectID, env) + if f.Scopes[k] == nil { + f.Scopes[k] = &scope{} + } + return f.Scopes[k] +} + +func (f *file) write() error { + path := Path() + if path == "" { + return os.ErrNotExist + } + for k, s := range f.Scopes { + if s.Current == "" && len(s.Sessions) == 0 && s.EditedAt.IsZero() && s.CompiledAt.IsZero() { + delete(f.Scopes, k) + } + } + data, err := json.MarshalIndent(f, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(path), "sessions-*.json") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + if _, err := tmp.Write(append(data, '\n')); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} + +// change reads the file, applies fn, and writes it back. +func change(fn func(f *file)) error { + f := read() + fn(f) + return f.write() +} + +// NewID is a new session ID: s- and 8 random lowercase letters and digits. +func NewID() string { + const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" + b := make([]byte, 8) + _, _ = rand.Read(b) + for i := range b { + b[i] = alphabet[int(b[i])%len(alphabet)] + } + return "s-" + string(b) +} + +// Current is the session last started in the project's environment on this +// machine, if it hasn't been ended. +func Current(projectID, env string) (Session, bool) { + s := read().Scopes[key(projectID, env)] + if s == nil || s.Current == "" { + return Session{}, false + } + return lookup(s, s.Current) +} + +// Lookup is the session id, if vf started it in the project's environment. +func Lookup(projectID, env, id string) (Session, bool) { + s := read().Scopes[key(projectID, env)] + if s == nil { + return Session{}, false + } + return lookup(s, id) +} + +func lookup(s *scope, id string) (Session, bool) { + for _, it := range s.Sessions { + if it.ID == id { + return it, true + } + } + return Session{}, false +} + +// Find is the session id that vf started in any of the project's +// environments, and that environment: the one started last, when the ID +// was used in several. +func Find(projectID, id string) (env string, found Session, ok bool) { + for k, s := range read().Scopes { + p, e, cut := cutKey(k) + if !cut || p != projectID { + continue + } + if it, has := lookup(s, id); has && (!ok || it.StartedAt.After(found.StartedAt)) { + env, found, ok = e, it, true + } + } + return env, found, ok +} + +func cutKey(k string) (projectID, env string, ok bool) { + for i := len(k) - 1; i >= 0; i-- { + if k[i] == '/' { + return k[:i], k[i+1:], true + } + } + return "", "", false +} + +// Start records s as started in the project's environment, and makes it the +// current session there. +func Start(projectID, env string, s Session) error { + return change(func(f *file) { + sc := f.scope(projectID, env) + sc.Sessions = slices.DeleteFunc(sc.Sessions, func(it Session) bool { return it.ID == s.ID }) + sc.Sessions = append([]Session{s}, sc.Sessions...) + if len(sc.Sessions) > keep { + sc.Sessions = sc.Sessions[:keep] + } + sc.Current = s.ID + }) +} + +// SetButtons records the buttons the agent's last reply in session id +// offered. A session vf didn't start isn't recorded. +func SetButtons(projectID, env, id string, buttons []Button) error { + return change(func(f *file) { + sc := f.scope(projectID, env) + for i := range sc.Sessions { + if sc.Sessions[i].ID == id { + sc.Sessions[i].Buttons = buttons + } + } + }) +} + +// End forgets id as the current session, if it is. +func End(projectID, env, id string) error { + return change(func(f *file) { + if sc := f.scope(projectID, env); sc.Current == id { + sc.Current = "" + } + }) +} + +// MarkEdited records that vf edited the draft of the project's environment; +// AllEnvironments for an edit to the project that names none. +func MarkEdited(projectID, env string) error { + if projectID == "" { + return nil + } + if env == "" { + env = AllEnvironments + } + return change(func(f *file) { f.scope(projectID, env).EditedAt = now().UTC() }) +} + +// MarkCompiled records that the draft of the project's environment was just +// compiled: the edits vf made before now are in it. +func MarkCompiled(projectID, env string) error { + if projectID == "" || env == "" { + return nil + } + return change(func(f *file) { f.scope(projectID, env).CompiledAt = now().UTC() }) +} + +// Edited reports whether vf edited the draft of the project's environment +// since its last compile. +func Edited(projectID, env string) bool { + f := read() + compiled := time.Time{} + if s := f.Scopes[key(projectID, env)]; s != nil { + compiled = s.CompiledAt + } + for _, e := range []string{env, AllEnvironments} { + if s := f.Scopes[key(projectID, e)]; s != nil && s.EditedAt.After(compiled) { + return true + } + } + return false +} diff --git a/internal/sessions/sessions_test.go b/internal/sessions/sessions_test.go new file mode 100644 index 00000000..1cb8e808 --- /dev/null +++ b/internal/sessions/sessions_test.go @@ -0,0 +1,109 @@ +// This file is not generated by Speakeasy. It covers sessions.go. + +package sessions + +import ( + "encoding/json" + "os" + "regexp" + "testing" + "time" +) + +// tempHome points the file at a fresh home, and steps the clock a second at +// a time, so each mark is later than the one before. +func tempHome(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + clock := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + now = func() time.Time { clock = clock.Add(time.Second); return clock } + t.Cleanup(func() { now = time.Now }) +} + +func TestANewIDIsShortAndRandom(t *testing.T) { + a, b := NewID(), NewID() + if !regexp.MustCompile(`^s-[a-z0-9]{8}$`).MatchString(a) || a == b { + t.Errorf("ids %q, %q", a, b) + } +} + +func TestTheLastSessionStartedIsCurrentUntilItEnds(t *testing.T) { + tempHome(t) + if _, ok := Current("p1", "main"); ok { + t.Fatal("a session before any started") + } + start := time.Date(2026, 12, 1, 16, 14, 29, 0, time.UTC) + for _, id := range []string{"s-1", "s-2"} { + if err := Start("p1", "main", Session{ID: id, Version: "draft", StartedAt: start}); err != nil { + t.Fatal(err) + } + } + if s, ok := Current("p1", "main"); !ok || s.ID != "s-2" || s.Version != "draft" || !s.StartedAt.Equal(start) { + t.Errorf("current = %+v, %v", s, ok) + } + if _, ok := Current("p1", "staging"); ok { + t.Error("another environment has no session") + } + if err := End("p1", "main", "s-1"); err != nil { + t.Fatal(err) + } + if s, _ := Current("p1", "main"); s.ID != "s-2" { + t.Errorf("ending another session changed the current one: %+v", s) + } + _ = End("p1", "main", "s-2") + if _, ok := Current("p1", "main"); ok { + t.Error("an ended session is still current") + } + if s, ok := Lookup("p1", "main", "s-1"); !ok || s.Version != "draft" { + t.Errorf("an ended session is forgotten: %+v", s) + } + if env, s, ok := Find("p1", "s-2"); !ok || env != "main" || s.ID != "s-2" { + t.Errorf("find = %q %+v %v", env, s, ok) + } +} + +func TestButtonsAreKeptForTheirSession(t *testing.T) { + tempHome(t) + _ = Start("p1", "main", Session{ID: "s-1", Version: "draft"}) + _ = SetButtons("p1", "main", "s-1", []Button{{Name: "Yes", Request: []byte(`{"type":"path-1"}`)}}) + s, _ := Current("p1", "main") + var request struct{ Type string } + if len(s.Buttons) != 1 || s.Buttons[0].Name != "Yes" || json.Unmarshal(s.Buttons[0].Request, &request) != nil || request.Type != "path-1" { + t.Errorf("buttons = %+v", s.Buttons) + } +} + +func TestAnEditIsMarkedUntilTheNextCompile(t *testing.T) { + tempHome(t) + if Edited("p1", "main") { + t.Fatal("edited before any edit") + } + _ = MarkEdited("p1", "main") + if !Edited("p1", "main") || Edited("p1", "staging") || Edited("p2", "main") { + t.Error("an edit marks its own project and environment only") + } + _ = MarkCompiled("p1", "main") + if Edited("p1", "main") { + t.Error("a compile clears the mark") + } + _ = MarkEdited("p1", "") // a secret, say: no environment + if !Edited("p1", "main") || !Edited("p1", "staging") { + t.Error("an edit that names no environment marks them all") + } + _ = MarkCompiled("p1", "main") + if Edited("p1", "main") || !Edited("p1", "staging") { + t.Error("a compile clears its own environment only") + } +} + +func TestTheFileIsWrittenWhole(t *testing.T) { + tempHome(t) + _ = MarkEdited("p1", "main") + entries, err := os.ReadDir(Path()[:len(Path())-len("/sessions.json")]) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != "sessions.json" { + t.Errorf("files: %v", entries) + } +} From 045de32989a7d460b98469c2e50a44cc9140f470 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:58:53 -0500 Subject: [PATCH 02/15] feat(session): vf session start, send, update, get and end, with compile rule B Why: talking to an agent took a user ID, the scope, a version and JSON on every turn, and nothing said which user ID held which conversation or how to end one and find its transcript (round 7: human-newcomer F2, agent-migrator F2, human-poweruser F9). Testers reused one user ID across edits and read replies swayed by the conversation before. And compiling the draft before every turn put ~0.4 s on each message. Design: a session is one conversation, and its ID is the runtime's user ID. start compiles the draft, ends and clears a reused ID's conversation (end action, then state delete), sets the variables, then launches, the order the live probe showed works, and records the session as current for its project and environment. send takes the message as its words, --action or --button (the last reply's buttons are kept with the session); with none going it starts one and says so. update and get set and read the variables; end sends the end action and searches the transcripts once by session ID, looking again for up to 5 s, and takes the newest since the session started. Rule B: a turn with the draft compiles first only when it starts a conversation or vf edited the draft since its last compile; an edit made elsewhere is caught by needsRecompile, compiled after, and warned about in one line. conversation send follows the same rule. Change: conversation/session*.go hold the group, hooked in with one line in conversation/root.go; autocompile.go decides by rule B; the Ctrl-C hint points at vf session get; no_session exits 2. Tests: session_test.go (rule B across commands, reused ID order, send with no session, buttons, end's transcript lookup, Next lines run), sessionend_test.go (none yet then found, giving up, newest since the start), autocompile tests rewritten for rule B. --- internal/cli/autocompile_test.go | 133 ++--- internal/cli/conversation/autocompile.go | 147 +++--- internal/cli/conversation/autocompile_test.go | 2 +- internal/cli/conversation/canceled.go | 15 +- internal/cli/conversation/endaction.go | 8 +- internal/cli/conversation/root.go | 1 + internal/cli/conversation/send.go | 2 +- internal/cli/conversation/session.go | 366 +++++++++++++ internal/cli/conversation/sessionend.go | 161 ++++++ internal/cli/conversation/sessionend_test.go | 91 ++++ internal/cli/conversation/sessionsend.go | 209 ++++++++ internal/cli/conversation/sessionstart.go | 321 ++++++++++++ internal/cli/conversation/sessionstate.go | 192 +++++++ internal/cli/conversation/version.go | 6 +- internal/cli/conversationcancel_test.go | 10 +- internal/cli/session_test.go | 496 ++++++++++++++++++ internal/cli/strayargs_test.go | 5 +- internal/output/exitcode.go | 2 +- 18 files changed, 2028 insertions(+), 139 deletions(-) create mode 100644 internal/cli/conversation/session.go create mode 100644 internal/cli/conversation/sessionend.go create mode 100644 internal/cli/conversation/sessionend_test.go create mode 100644 internal/cli/conversation/sessionsend.go create mode 100644 internal/cli/conversation/sessionstart.go create mode 100644 internal/cli/conversation/sessionstate.go create mode 100644 internal/cli/session_test.go diff --git a/internal/cli/autocompile_test.go b/internal/cli/autocompile_test.go index bc6abe05..e8542525 100644 --- a/internal/cli/autocompile_test.go +++ b/internal/cli/autocompile_test.go @@ -1,6 +1,8 @@ // This file is not generated by Speakeasy. It covers -// conversation/autocompile.go: every turn with the draft runs the latest -// edits. +// conversation/autocompile.go, compile rule B: a turn with the draft +// compiles it first when it starts a conversation, or vf edited the draft +// since its last compile; a turn an edit made elsewhere missed compiles it +// after. The session commands are covered in session_test.go. package cli @@ -15,6 +17,7 @@ import ( "testing" "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sessions" ) // conversationServer answers compile with compileStatus, the user's state @@ -90,22 +93,21 @@ const ( // ended. goingState = `{"state":{"stack":[{"diagramID":"d1","nodeID":"n1","storage":{},"variables":{}}],"storage":{},"variables":{"name":"Sam"}}}` noneState = `{"state":{"stack":[],"storage":{},"variables":{}}}` - // The warning after a turn an edit made during it missed. - staleWarning = "This turn ran the build from before an edit made during it. vf compiled it, so your next turn runs it." + // The warning after a turn an edit made elsewhere, or during it, missed. + staleWarning = "This turn ran the build from before an edit made elsewhere or during it. vf compiled it, so your next turn runs it." ) // buildServer is the runtime as the live check found it: a turn runs the // draft as last compiled, the conversation's state isn't pinned to a build, -// and a turn that ran a build older than the draft says needsRecompile. The -// draft starts edited since its last compile, as after `agent update`; the -// agent's reply follows the edit only when the turn ran it. It records each -// request as "compile", "conversation" or "state", and edit marks the draft -// edited again. -func buildServer(t *testing.T) (url string, requests func() []string, edit func()) { +// and a turn that ran a build older than the draft says needsRecompile. An +// edit (`vf agent update`) marks the draft edited; the agent's reply follows +// the edit only when the turn ran it. It records each request as +// "compile", "conversation" or "edit". +func buildServer(t *testing.T) (url string, requests func() []string) { t.Helper() var mu sync.Mutex var seen []string - edited := true + edited := false srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.Copy(io.Discard, r.Body) mu.Lock() @@ -125,51 +127,57 @@ func buildServer(t *testing.T) (url string, requests func() []string, edit func( json.NewEncoder(w).Encode(map[string]any{"needsRecompile": edited, "traces": []any{ map[string]any{"type": "text", "payload": map[string]any{"message": reply}}, }}) - default: // maria's state: a conversation going - seen = append(seen, "state") - io.WriteString(w, goingState) + case r.Method == http.MethodGet: // a read before the edit, if any + io.WriteString(w, `{}`) + default: // the edit + seen = append(seen, "edit") + edited = true + io.WriteString(w, `{"message":"Agent updated."}`) } })) t.Cleanup(srv.Close) return srv.URL, func() []string { - mu.Lock() - defer mu.Unlock() - got := append([]string(nil), seen...) - seen = nil - return got - }, func() { - mu.Lock() - edited = true - mu.Unlock() - } + mu.Lock() + defer mu.Unlock() + got := append([]string(nil), seen...) + seen = nil + return got + } } // round-6 human-newcomer:F3: `agent update --instructions "… Always end // every reply with the exact sentence: Have a great coffee day!"`, then // `conversation send` to maria, mid-conversation: "Are you open on // Thanksgiving?" The reply ignored the new rule, and vf warned only after -// the turn was spent. vf compiled only before a turn that started a -// conversation; maria's had started. Every turn with the draft now compiles -// it first: the second turn, and the one after another edit. +// the turn was spent. Rule B: vf made the edit, so the turn after it +// compiles first; the turn after that doesn't need to, and doesn't. func TestTheTurnAfterAnEditRunsIt(t *testing.T) { - url, requests, edit := buildServer(t) - send := []string{"send", "-u", "maria", "-p", "p1", "-e", "main", "--text", "Are you open on Thanksgiving?"} - for i, name := range []string{"the first turn after an edit", "the next turn", "the turn after another edit"} { - if i == 2 { - edit() + url, requests := buildServer(t) + home := t.TempDir() + send := []string{"conversation", "send", "-u", "maria", "-p", "p1", "-e", "main", "--text", "Are you open on Thanksgiving?"} + edit := []string{"agent", "update", "-p", "p1", "-e", "main", "--instructions", "Always end every reply with: Have a great coffee day!"} + for _, c := range []struct{ name, want string }{ + {"the first turn after an edit", "edit compile conversation"}, + {"the next turn", "conversation"}, + {"the turn after another edit", "edit compile conversation"}, + } { + if strings.HasPrefix(c.want, "edit") { + if _, errOut, err := runInHome(t, home, url, false, edit...); err != nil { + t.Fatalf("%s: %v\n%s", c.name, err, errOut) + } } - out, err := runConversation(t, url, send...) + out, errOut, err := runInHome(t, home, url, false, send...) if err != nil { - t.Fatalf("%s: %v\n%s", name, err, out) + t.Fatalf("%s: %v\n%s", c.name, err, errOut) } - if got := strings.Join(requests(), " "); got != "compile conversation" { - t.Errorf("%s: requests = %q, want a compile, then the turn", name, got) + if got := strings.Join(requests(), " "); got != c.want { + t.Errorf("%s: requests = %q, want %q", c.name, got, c.want) } if !strings.Contains(out, "Have a great coffee day!") { - t.Errorf("%s: the reply didn't follow the edit:\n%s", name, out) + t.Errorf("%s: the reply didn't follow the edit:\n%s", c.name, out) } - if strings.Contains(out, "⚠") || strings.Contains(out, "build") || strings.Contains(out, "Compiled") { - t.Errorf("%s: more than the reply:\n%s", name, out) + if strings.Contains(errOut, "⚠") || strings.Contains(errOut, "build") || strings.Contains(errOut, "Compiled") { + t.Errorf("%s: more than the reply:\n%s", c.name, errOut) } } } @@ -187,11 +195,13 @@ func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) { {"run-script --no-compile", script, append([]string{"run-script", "-m", `["hi"]`, "--no-compile"}, scope...), "conversation"}, {"run-script on published", script, append([]string{"run-script", "-m", `["hi"]`, "--version-param", "published"}, scope...), "conversation"}, {"a launch compiles first", freshTurn, append(send, "-a", `{"type":"launch"}`), "compile conversation"}, - {"a later turn compiles first too", freshTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "compile conversation"}, - {"--text compiles first", freshTurn, append(send, "--text", "hi"), "compile conversation"}, - {"--body compiles first", freshTurn, append(send, "--body", `{"action":{"type":"text","payload":"hi"},"version":"draft"}`), "compile conversation"}, - {"an edit during the turn compiles after it too", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "compile conversation compile"}, - {"an edit during the turn, -o json", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "-o", "json"), "compile conversation compile"}, + {"a launch in --body compiles first", freshTurn, append(send, "--body", `{"action":{"type":"launch"},"version":"draft"}`), "compile conversation"}, + {"a later turn doesn't", freshTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "conversation"}, + {"nor --text", freshTurn, append(send, "--text", "hi"), "conversation"}, + {"nor --body", freshTurn, append(send, "--body", `{"action":{"type":"text","payload":"hi"},"version":"draft"}`), "conversation"}, + {"an edit elsewhere compiles after the turn", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`), "conversation compile"}, + {"an edit elsewhere, -o json", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "-o", "json"), "conversation compile"}, + {"an edit elsewhere, a launch", staleTurn, append(send, "-a", `{"type":"launch"}`), "compile conversation compile"}, {"a stale turn with --no-compile", staleTurn, append(send, "-a", `{"type":"text","payload":"hi"}`, "--no-compile"), "conversation"}, {"--no-compile", freshTurn, append(send, "--text", "hi", "--no-compile"), "conversation"}, {"a turn on published", freshTurn, []string{"send", "-u", "u1", "-v", "published", "-p", "p1", "-e", "main", "--text", "hi"}, "conversation"}, @@ -224,7 +234,7 @@ func TestAConversationWithTheDraftCompilesItFirst(t *testing.T) { } // The state GET that told vf whether a send started a conversation is -// gone: every turn compiles, whatever the user's state. +// gone: a turn reads the action it sends, whatever the user's state. func TestATurnReadsNoStateFirst(t *testing.T) { send := []string{"send", "-u", "new-user", "-v", "draft", "-p", "p1", "-e", "main", "--text", "hi"} for _, c := range []struct { @@ -243,16 +253,16 @@ func TestATurnReadsNoStateFirst(t *testing.T) { if err != nil { t.Fatalf("%v\n%s", err, out) } - if got := strings.Join(requests(), " "); got != "compile conversation" { - t.Errorf("requests = %q, want %q", got, "compile conversation") + if got := strings.Join(requests(), " "); got != "conversation" { + t.Errorf("requests = %q, want %q", got, "conversation") } }) } } -// After a turn an edit made during it missed, vf compiles and says so in -// plain words: no new --user-id, no state delete, since the next turn -// compiles anyway and a conversation isn't pinned to a build. +// After a turn an edit made elsewhere missed, vf compiles and says so in +// plain words: no new --user-id, no state delete, since a conversation +// isn't pinned to a build. func TestAStaleTurnSaysVfCompiledIt(t *testing.T) { for _, agent := range []bool{false, true} { url, _ := conversationServer(t, 200, staleTurn) @@ -279,7 +289,7 @@ func TestACompileAfterTheTurnThatFailsOnlyWarns(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if strings.HasSuffix(r.URL.Path, "/compile") { - if compiles++; compiles > 1 { + if compiles++; compiles >= 1 { // the turn didn't compile first: rule B w.WriteHeader(http.StatusInternalServerError) io.WriteString(w, `{"message":"boom"}`) return @@ -295,9 +305,12 @@ func TestACompileAfterTheTurnThatFailsOnlyWarns(t *testing.T) { t.Fatalf("%v\n%s%s", err, out, errOut) } flat := strings.Join(strings.Fields(errOut), " ") - if !strings.Contains(flat, "vf couldn't compile the draft after it (boom), so your next turn compiles it first.") || strings.Contains(flat, "nothing was sent") { + if !strings.Contains(flat, "vf couldn't compile the draft after it (boom), so your next turn compiles it first.") || strings.Contains(flat, "nothing was sent") || compiles != 1 { t.Errorf("stderr:\n%s", errOut) } + if !sessions.Edited("p1", "main") { + t.Error("the next turn won't compile first, as the warning says") + } } // A draft that won't compile stops the turn before it spends credits: the @@ -316,14 +329,16 @@ func TestADraftThatWontCompileSendsNothing(t *testing.T) { {404, "not_found", output.ExitNotFound}, } { for _, args := range [][]string{ - {"send", "-u", "u1", "-p", "p1", "-e", "main", "--text", "hi"}, - {"run-script", "-m", `["hi"]`, "-p", "p1", "-e", "main"}, + {"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "-a", `{"type":"launch"}`}, + {"conversation", "run-script", "-m", `["hi"]`, "-p", "p1", "-e", "main"}, + {"session", "start", "-p", "p1", "-e", "main"}, + {"session", "send", "-p", "p1", "-e", "main", "hi"}, // with no session going, it starts one } { for _, agent := range []bool{false, true} { - name := strings.Join([]string{http.StatusText(c.status), args[0], map[bool]string{false: "human", true: "agent"}[agent]}, ", ") + name := strings.Join([]string{http.StatusText(c.status), args[0] + " " + args[1], map[bool]string{false: "human", true: "agent"}[agent]}, ", ") t.Run(name, func(t *testing.T) { url, requests := conversationServer(t, c.status, freshTurn) - stdout, stderr, err := runMode2(t, url, agent, append([]string{"conversation"}, args...)...) + stdout, stderr, err := runMode2(t, url, agent, args...) if err == nil { t.Fatalf("no error:\n%s%s", stdout, stderr) } @@ -373,10 +388,10 @@ func TestCompilingAddsNothingToAgentOrJSONOutput(t *testing.T) { agent bool args []string }{ - {"agent mode", true, []string{"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "--text", "hi"}}, + {"agent mode", true, []string{"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "-a", `{"type":"launch"}`}}, {"agent mode, run-script", true, []string{"conversation", "run-script", "-m", `["hi"]`, "-p", "p1", "-e", "main"}}, - {"-o json", false, []string{"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "--text", "hi", "-o", "json"}}, - {"--jq", false, []string{"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "--text", "hi", "--jq", ".needsRecompile"}}, + {"-o json", false, []string{"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "-a", `{"type":"launch"}`, "-o", "json"}}, + {"--jq", false, []string{"conversation", "send", "-u", "u1", "-p", "p1", "-e", "main", "-a", `{"type":"launch"}`, "--jq", ".needsRecompile"}}, {"-o json, run-script", false, []string{"conversation", "run-script", "-m", `["hi"]`, "-p", "p1", "-e", "main", "-o", "json"}}, } { t.Run(c.name, func(t *testing.T) { diff --git a/internal/cli/conversation/autocompile.go b/internal/cli/conversation/autocompile.go index d447338d..347e2187 100644 --- a/internal/cli/conversation/autocompile.go +++ b/internal/cli/conversation/autocompile.go @@ -1,43 +1,39 @@ -// This file is not generated by Speakeasy. It has every conversation turn -// with the draft run the latest edits, by compiling the draft first. +// This file is not generated by Speakeasy. It compiles the draft before a +// conversation turn when the turn needs it: compile rule B. // // A conversation runs the environment's last compiled build, and nothing // compiled it after an edit. So `agent update` then `conversation send` // talked to the old agent: testers read the old replies as "my edit didn't -// work", and spent credits on it. +// work", and spent credits on it. A live check on the real API showed: // -// vf used to compile only before a turn that starts a conversation, reading -// the user's state first to tell, and after a later turn that came back with -// needsRecompile. The first turn after an edit mid-conversation still ran -// the old build (round-6 human-newcomer:F3: an instructions edit, then -// "Are you open on Thanksgiving?" to the same user, answered without the new -// rule). A live check on the real API showed why, and what it costs to fix: -// -// - A conversation's state records the build it ran: the base stack -// frame's storage.compiledSourceHash. -// - Edit, compile, then the same user's next turn: the turn uses the new -// prompt, and the hash changes. Sessions are not pinned to a build, so -// the only stale turn is one between an edit and a compile. +// - A conversation is not pinned to a build: each turn runs the newest +// compile, so an edit reaches a conversation already going on its next +// turn after any compile. // - Edit with no compile, then a turn: that turn runs the old build, with // needsRecompile: true. // - A compile takes 0.2–0.3 s on the server for a tiny agent, and -// 0.5–0.8 s for a large one (193K characters of instructions, 28 -// functions, 25 tools), changed or not. A turn takes 0.9–2.1 s. -// - Nothing cheap says whether a compile is needed: the environment has -// only createdAt and release dates, and a compile's answer only a -// message and how long it took. +// 0.5–0.8 s for a large one, changed or not. Nothing cheap says whether +// one is needed. // -// So vf compiles the draft before every turn with it: each send, launch or -// not, and run-script. It reads no state first. One spinner line says -// "Compiling the draft…", then "Waiting for the agent…", and nothing of it -// stays after a turn; a compile over 2 s leaves a muted line saying how long -// it took. A draft that won't compile stops before anything is sent, with -// error_type compile_failed. +// Round 7 compiled the draft before every turn with it. That worked, but +// put ~0.4 s on every message (a draft send took 1.55 s at the median, its +// compile 0.40 s), and speed is how vf is judged. So now, rule B: vf +// compiles the draft when a conversation starts (`vf session start`, a +// launch action, run-script), and before any other turn only when vf itself +// edited the draft since the last compile, which internal/sessions keeps +// track of. A plain turn never compiles, and its spinner says nothing about +// compiling. One that does says "Compiling the draft…", then "Waiting for +// the agent…" on one line, and nothing of it stays after the turn; a +// compile over 2 s leaves a muted line saying how long it took. A draft that +// won't compile stops before anything is sent, with error_type +// compile_failed. // -// needsRecompile can still come back true, when an edit lands while the turn -// runs. Then vf compiles again after it and says so, so the next turn, from -// vf or anywhere else, runs the edit. --no-compile runs whatever was last -// compiled. The published version is a release, and is never compiled. +// An edit vf didn't make (in Creator, or by another client), or one that +// lands while a turn runs, still leaves that turn on the old build, and the +// answer says needsRecompile. Then vf compiles after it and warns in one +// line, so the next turn, from vf or anywhere else, runs the edit. +// --no-compile runs whatever was last compiled. The published version is a +// release, and is never compiled. package conversation @@ -56,6 +52,7 @@ import ( "github.com/voiceflow/cli/internal/sdk" "github.com/voiceflow/cli/internal/sdk/models/components" "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/sessions" "github.com/voiceflow/cli/internal/ui" ) @@ -82,17 +79,23 @@ var spinLine = client.StartSpinnerLine // compiles it otherwise. func addNoCompileFlag(cmd *cobra.Command) { usage := "Run the draft as last compiled. Without it, vf compiles the draft first, so the script runs your latest edits." - if cmd.Name() == "send" { - usage = "Run the draft as last compiled. Without it, vf compiles the draft before every turn, so the turn runs your latest edits." + switch cmd.Name() { + case "send": + usage = "Run the draft as last compiled. Without it, vf compiles the draft before a turn that starts a conversation, and before any turn after vf edited the draft." cmd.Long += "\n\n" + sendCompiles + case "start": + usage = "Run the draft as last compiled. Without it, vf compiles the draft first, so the session runs your latest edits." } cmd.Flags().Bool(noCompileFlag, false, usage) } -// sendCompiles is what send's help says about compiling the draft. -const sendCompiles = `With the draft, vf compiles it before every turn, so each turn runs your latest edits, in a conversation old or new. A compile takes about half a second. If the draft won't compile, vf says why and sends nothing. +// sendCompiles is what send's help says about compiling the draft, and +// about what an edit changes in a conversation already going. +const sendCompiles = `With the draft, vf compiles it when a conversation starts, and before a turn when vf edited the draft since its last compile, so the turn runs your edits. Other turns don't compile. If the draft won't compile, vf says why and sends nothing. + +An edit made elsewhere, in Creator or by another client, can miss a turn. Then vf compiles after it, and warns: the next turn runs the edit. --no-compile runs the draft as last compiled. The published version is never compiled. -An edit made while a turn runs can miss that turn. Then vf compiles again after it, and warns. --no-compile runs the draft as last compiled. The published version is never compiled.` +The agent gets your edits on its next turn, but in a conversation already going its earlier replies can still sway it. To try an edit cleanly, start a new session: 'vf session start'.` // turnWait is the wait for one turn, a send or a script: one spinner line, // through the compile and the turn, and the context the turn's request goes @@ -106,24 +109,36 @@ type turnWait struct { stopOnce sync.Once } -// compileBeforeSend compiles the draft before req's turn. Send the turn with -// the wait's ctx, and stop the wait once it is back. +// compileBeforeSend starts req's turn, compiling the draft first when rule +// B says to. Send the turn with the wait's ctx, and stop the wait once it is +// back. func compileBeforeSend(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerSendRequest) (*turnWait, error) { - return startTurn(cmd, s, string(req.Body.Version) == "draft", req.ProjectID, req.EnvironmentAlias) + starts := actionType(req.Body.Action) == string(components.LaunchRequestTypeLaunch) + compiles := compilesFirst(cmd, string(req.Body.Version), starts, req.ProjectID, req.EnvironmentAlias) + return startTurn(cmd, s, compiles, req.ProjectID, req.EnvironmentAlias) } -// compileBeforeScript is compileBeforeSend for run-script, whose version is -// the draft unless it says published. +// compileBeforeScript is compileBeforeSend for run-script, which starts a +// conversation, with the draft unless it says published. func compileBeforeScript(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerRunScriptRequest) (*turnWait, error) { - draft := req.Body.Version == nil || string(*req.Body.Version) == "draft" - return startTurn(cmd, s, draft, req.ProjectID, req.EnvironmentAlias) + version := "draft" + if req.Body.Version != nil { + version = string(*req.Body.Version) + } + return startTurn(cmd, s, compilesFirst(cmd, version, true, req.ProjectID, req.EnvironmentAlias), req.ProjectID, req.EnvironmentAlias) +} + +// compilesFirst is compile rule B: with the draft, and without +// --no-compile, a turn that starts a conversation compiles it first, and +// any other turn does when vf edited the draft since its last compile. +func compilesFirst(cmd *cobra.Command, version string, starts bool, projectID, alias string) bool { + return version == "draft" && !skipCompile(cmd) && (starts || sessions.Edited(projectID, alias)) } -// startTurn starts the turn's spinner line and, for the draft, compiles it. -// A compile that fails stops the turn: the spinner goes, and the error is -// reported. -func startTurn(cmd *cobra.Command, s *sdk.VoiceflowSDK, draft bool, projectID, alias string) (*turnWait, error) { - compiles := draft && !skipCompile(cmd) +// startTurn starts the turn's spinner line and, when compiles says so, +// compiles the draft. A compile that fails stops the turn: the spinner goes, +// and the error is reported. +func startTurn(cmd *cobra.Command, s *sdk.VoiceflowSDK, compiles bool, projectID, alias string) (*turnWait, error) { message, hint := waitingMessage, waitingHint if compiles { message, hint = compilingMessage, compilingHint @@ -159,34 +174,44 @@ func (w *turnWait) stop() { } // compileAfterStaleSend reads a send's answer before it is printed. When the -// turn ran a stale build of the draft, which vf compiled just before it, an -// edit landed while it ran: the function it returns compiles the draft -// again once the answer is printed, and says so. +// turn ran a stale build of the draft, it had been edited since its last +// compile, elsewhere or while the turn ran: the function it returns compiles +// the draft once the answer is printed, and says so. func compileAfterStaleSend(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableConversationControllerSendRequest, res *operations.StableConversationControllerSendResponse) func() error { - none := func() error { return nil } - if res == nil || client.IsDryRun(cmd) || string(req.Body.Version) != "draft" || skipCompile(cmd) { - return none + if res == nil { + return func() error { return nil } } answer := res.StableConversationSendResponse if answer == nil { answer = &components.StableConversationSendResponse{} if !output.PeekJSON(res.HTTPMeta.Response, answer) { - return none + return func() error { return nil } } } - if !answer.NeedsRecompile { - return none + return compileAfterStaleTurn(cmd, s, string(req.Body.Version), answer.NeedsRecompile, req.ProjectID, req.EnvironmentAlias) +} + +// staleTurn says what happened to a turn that ran a build older than the +// draft. +const staleTurn = "This turn ran the build from before an edit made elsewhere or during it." + +// compileAfterStaleTurn is compileAfterStaleSend for an answer already +// read, whose needsRecompile is stale. +func compileAfterStaleTurn(cmd *cobra.Command, s *sdk.VoiceflowSDK, version string, stale bool, projectID, alias string) func() error { + if !stale || client.IsDryRun(cmd) || version != "draft" || skipCompile(cmd) { + return func() error { return nil } } return func() error { - const stale = "This turn ran the build from before an edit made during it." ctx := client.WithSpinnerMessage(cmd.Context(), compilingMessage) - if err := compile(ctx, s, req.ProjectID, req.EnvironmentAlias); err != nil { + if err := compile(ctx, s, projectID, alias); err != nil { // The turn ran and printed: failing now would read as a send - // that didn't happen, and invite sending it again. - warn(cmd, stale+" vf couldn't compile the draft after it ("+compileError(cmd, err)+"), so your next turn compiles it first.") + // that didn't happen, and invite sending it again. The next turn + // compiles first instead. + _ = sessions.MarkEdited(projectID, alias) + warn(cmd, staleTurn+" vf couldn't compile the draft after it ("+compileError(cmd, err)+"), so your next turn compiles it first.") return nil } - warn(cmd, stale+" vf compiled it, so your next turn runs it.") + warn(cmd, staleTurn+" vf compiled it, so your next turn runs it.") return nil } } diff --git a/internal/cli/conversation/autocompile_test.go b/internal/cli/conversation/autocompile_test.go index 8ac2b85f..1fe376df 100644 --- a/internal/cli/conversation/autocompile_test.go +++ b/internal/cli/conversation/autocompile_test.go @@ -85,7 +85,7 @@ func sendAtATerminal(t *testing.T, compileTime time.Duration, args ...string) (d cmd.SetErr(&out) s := sdk.New(sdk.WithServerURL(srv.URL), sdk.WithSecurity(components.Security{Token: "vfp_fake"})) req := &operations.StableConversationControllerSendRequest{UserID: "u1", ProjectID: "p1", EnvironmentAlias: "main", - Body: components.StableConversationSendRequest{Version: "draft", Action: components.CreateAnyRequestTextRequest(components.TextRequest{Type: "text", Payload: "hi"})}} + Body: components.StableConversationSendRequest{Version: "draft", Action: components.CreateAnyRequestLaunchRequest(components.LaunchRequest{Type: "launch"})}} // rule B compiles before a launch wait, err := compileBeforeSend(cmd, s, req) if err != nil { diff --git a/internal/cli/conversation/canceled.go b/internal/cli/conversation/canceled.go index fcf51664..89da9770 100644 --- a/internal/cli/conversation/canceled.go +++ b/internal/cli/conversation/canceled.go @@ -106,12 +106,17 @@ func mayHaveReached(what, next string) output.Explanation { } // lastTurnCommand is the command that shows the last message the agent got -// from userID, and its reply: the runtime keeps them in the user's state as -// last_utterance and last_response. +// from userID, and its reply: the runtime keeps them in the session's state +// as last_utterance and last_response. A session's ID is its user ID +// (session.go), and the version is named when it isn't the draft, which a +// session vf didn't start talks to otherwise. func lastTurnCommand(userID, projectID, alias, version string) string { - return "vf conversation state get --user-id " + shellWord(userID) + " --project-id " + shellWord(projectID) + - " --environment-alias " + shellWord(alias) + " --version-param " + shellWord(version) + - ` --jq ".state.variables | {last_utterance, last_response}"` + line := "vf session get --session " + shellWord(userID) + " --project-id " + shellWord(projectID) + + " --environment-alias " + shellWord(alias) + if version != "draft" { + line += " --version-param " + shellWord(version) + } + return line + ` --jq ".state.variables | {last_utterance, last_response}"` } // shellWord is s as one shell word: as it is when nothing in it needs diff --git a/internal/cli/conversation/endaction.go b/internal/cli/conversation/endaction.go index 98c621a3..1a8c5d36 100644 --- a/internal/cli/conversation/endaction.go +++ b/internal/cli/conversation/endaction.go @@ -40,6 +40,12 @@ const endReason = "Ended with vf conversation send" // when it has no reason, and is sent as an end action, without the label // the SDK's path-request reading of it adds. Other actions are left alone. func giveEndAReason(req *operations.StableConversationControllerSendRequest) { + giveEndReason(req, endReason) +} + +// giveEndReason is giveEndAReason, with reason for an end action that +// gives none: `vf session send` says it ended the conversation. +func giveEndReason(req *operations.StableConversationControllerSendRequest, reason string) { action := req.Body.Action raw, err := json.Marshal(action) if err != nil { @@ -57,7 +63,7 @@ func giveEndAReason(req *operations.StableConversationControllerSendRequest) { delete(payload, "label") } if payload["reason"] == nil || payload["reason"] == "" { // "": the SDK's zero value for one left out - payload["reason"] = endReason + payload["reason"] = reason } fields["payload"] = payload if raw, err = json.Marshal(fields); err != nil { diff --git a/internal/cli/conversation/root.go b/internal/cli/conversation/root.go index 22ee7af3..257e7753 100644 --- a/internal/cli/conversation/root.go +++ b/internal/cli/conversation/root.go @@ -34,6 +34,7 @@ func InitConversationRoot(parent *cobra.Command) error { return err } + addSessionGroup(parent) // session.go: vf session, a conversation at a time parent.AddCommand(ConversationCmd) return nil } diff --git a/internal/cli/conversation/send.go b/internal/cli/conversation/send.go index 17ae45d0..ee90c20f 100644 --- a/internal/cli/conversation/send.go +++ b/internal/cli/conversation/send.go @@ -89,7 +89,7 @@ func runSendCmd(cmd *cobra.Command, args []string) error { if output.WantsRawJSON(cmd) { sdkOpts = append(sdkOpts, operations.WithSkipDeserialization()) } - wait, err := compileBeforeSend(cmd, s, req) // autocompile.go: every turn with the draft runs the latest edits + wait, err := compileBeforeSend(cmd, s, req) // autocompile.go: rule B compiles the draft first when the turn needs it if err != nil { return err } diff --git a/internal/cli/conversation/session.go b/internal/cli/conversation/session.go new file mode 100644 index 00000000..54ecc03e --- /dev/null +++ b/internal/cli/conversation/session.go @@ -0,0 +1,366 @@ +// This file is not generated by Speakeasy. It is `vf session`: talk to an +// agent one conversation at a time, as a person would. +// +// `vf conversation send` took a user ID, a project, an environment, a +// version and a JSON action on every turn, and nothing said which user ID +// held which conversation, or when one began or ended (round 7: +// human-newcomer F2, agent-migrator F2, human-poweruser F9). Testers reused +// one user ID across edits and read replies swayed by the conversation +// before, and couldn't find the transcript to run an evaluation on. +// +// A session is one conversation. `start` begins a fresh one: the variables +// set first, then a launch. `send` says the next thing, `update` and `get` +// set and read its variables, and `end` ends it and finds its transcript. +// vf remembers the current session for each project and environment +// (internal/sessions), so a turn needs only the message. The session ID is +// the runtime's user ID, and the transcript's sessionID: -s names one, and +// -u, its old name, still works. +// +// Each command here lives in this package to share what `conversation send` +// already does: compile rule B (autocompile.go), the reply as a chat reads +// (reply.go), and what a Ctrl-C left behind (canceled.go). + +package conversation + +import ( + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" +) + +const ( + sessionFlag = "session" + userIDFlag = "user-id" + varFlag = "var" + variablesFlag = "variables" +) + +const sessionLong = `Talk to the agent one conversation at a time, as a person would. + +'vf session start' begins a fresh conversation, 'vf session send' says the next thing, and 'vf session end' ends it and finds its transcript, for 'vf evaluation run'. vf remembers the session each start began as the current one for its project and environment, so a turn takes only the message. A send with none going starts one. + +The session ID is the conversation's user ID: -s names a session, and -u still works.` + +// sessionScopeMeta are the flags every session command takes: where the +// agent is. They default, and are picked, as conversation send's are. +var sessionScopeMeta = []flagutil.FlagMeta{ + {FlagName: "project-id", Shorthand: "p", FieldPath: "ProjectID", Kind: flagutil.FlagKindString, Required: true, Description: "[required]"}, + {FlagName: "environment-alias", Shorthand: "e", FieldPath: "EnvironmentAlias", Kind: flagutil.FlagKindString, Required: true, Description: "[required]"}, +} + +// sessionScope is where a session command talks to the agent, and with +// start, which version. +type sessionScope struct { + ProjectID string + EnvironmentAlias string + Version string +} + +// addSessionGroup adds `vf session` under parent. +func addSessionGroup(parent *cobra.Command) { + group := &cobra.Command{ + Use: "session", + Short: "Start a session with the agent, send turns, end it", + Long: sessionLong, + RunE: func(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + return cmd.Help() + }, + } + addSessionStart(group) // sessionstart.go + addSessionSend(group) // sessionsend.go + addSessionUpdate(group) // sessionstate.go + addSessionGet(group) // sessionstate.go + addSessionEnd(group) // sessionend.go + parent.AddCommand(group) +} + +// addSessionFlags gives cmd the scope's flags, meta, and -s, with -u as its +// other name. +func addSessionFlags(cmd *cobra.Command, meta []flagutil.FlagMeta, sessionHelp string) { + flagutil.RegisterFlags(cmd, meta) + cmd.Flags().StringP(sessionFlag, "s", "", sessionHelp) + cmd.Flags().StringP(userIDFlag, "u", "", "Another name for --session: a session's ID is its conversation's user ID.") + _ = cmd.Flags().MarkHidden(userIDFlag) +} + +// scopeOf is where cmd talks to the agent: the flags given, the home +// prompt's context, or what the pickers ask for at a terminal. +func scopeOf(cmd *cobra.Command, meta []flagutil.FlagMeta) (sessionScope, error) { + if interactive.ShouldPrompt(cmd, meta) { + if err := interactive.PromptAndSetFlags(cmd, meta); err != nil { + return sessionScope{}, err + } + } + scope, err := flagutil.BuildRequest[sessionScope](cmd, meta, "", "") + if err != nil { + return sessionScope{}, err + } + return *scope, nil +} + +// givenSession is the session -s, or -u, names, or "". +func givenSession(cmd *cobra.Command) string { + if id, _ := cmd.Flags().GetString(sessionFlag); id != "" { + return id + } + id, _ := cmd.Flags().GetString(userIDFlag) + return id +} + +// sessionOf is the session cmd acts on: the one -s names, or else the +// current one. A session vf didn't start talks to the draft. +func sessionOf(cmd *cobra.Command, scope sessionScope) (sessions.Session, bool) { + if id := givenSession(cmd); id != "" { + s, ok := sessions.Lookup(scope.ProjectID, scope.EnvironmentAlias, id) + if !ok { + s = sessions.Session{ID: id} + } + if s.Version == "" { + s.Version = "draft" + } + return s, true + } + s, ok := sessions.Current(scope.ProjectID, scope.EnvironmentAlias) + if ok && s.Version == "" { + s.Version = "draft" + } + return s, ok +} + +// noSession explains a command that needs a session when none is going. +func noSession(cmd *cobra.Command, scope sessionScope) error { + x := output.Explanation{ + Type: "no_session", + Title: "No session is going in " + scope.EnvironmentAlias, + Why: []string{"vf remembers the session 'vf session start' began until 'vf session end' ends it, " + + "for each project and environment, and there is none now."}, + Next: []string{ + "`vf session start" + session.Scope(scope.ProjectID, scope.EnvironmentAlias) + "` starts one", + "Or name a session with -s", + }, + } + return output.Report(cmd, x, errors.New("no session is going: start one, or name one with -s")) +} + +// sdkFor is the client a session command talks to the API with, and the +// options each of its calls takes. +func sdkFor(cmd *cobra.Command) (*sdk.VoiceflowSDK, []operations.Option, error) { + s, err := client.NewClient(cmd) + if err != nil { + return nil, nil, err + } + opts, err := output.PrepareCallOpts(cmd) + if err != nil { + return nil, nil, err + } + if err := output.ValidateGlobalServerIndex(cmd, len(sdk.ServerList)); err != nil { + return nil, nil, err + } + return s, opts, nil +} + +// rawAnswer is opts with the answer left as the API sent it, for vf to read as +// JSON values and print as they came. +func rawAnswer(opts []operations.Option) []operations.Option { + return append(slices.Clip(opts), operations.WithSkipDeserialization()) +} + +// sendRequest is a turn in session id. +func sendRequest(scope sessionScope, id, version string, action components.AnyRequest) *operations.StableConversationControllerSendRequest { + return &operations.StableConversationControllerSendRequest{ + UserID: id, + ProjectID: scope.ProjectID, + EnvironmentAlias: scope.EnvironmentAlias, + Body: components.StableConversationSendRequest{Action: action, Version: components.StableConversationSendRequestVersion(version)}, + } +} + +// sessionTurn is a turn's answer, as the API sent it. +type sessionTurn struct { + res *operations.StableConversationControllerSendResponse + answer map[string]any // nil in a dry run + traces []map[string]any + stale bool +} + +// takeTurn sends req with wait's context, ends the wait, and reads the +// answer. A Ctrl-C says whether the turn went out (canceled.go). +func takeTurn(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, wait *turnWait, req *operations.StableConversationControllerSendRequest) (*sessionTurn, error) { + res, err := s.Conversation.Send(wait.ctx, *req, rawAnswer(opts)...) + wait.stop() + if err != nil { + return nil, sendFailed(cmd, wait, req, err) + } + t := &sessionTurn{res: res} + if client.IsDryRun(cmd) || !output.PeekJSON(res.HTTPMeta.Response, &t.answer) { + return t, nil + } + list, _ := t.answer["traces"].([]any) + for _, item := range list { + if trace, ok := item.(map[string]any); ok { + t.traces = append(t.traces, trace) + } + } + t.stale, _ = t.answer["needsRecompile"].(bool) + return t, nil +} + +// buttons are the buttons the turn's reply offers, for --button to press. +func (t *sessionTurn) buttons() []sessions.Button { + var out []sessions.Button + add := func(list any) { + items, _ := list.([]any) + for _, item := range items { + b, _ := item.(map[string]any) + request, err := json.Marshal(b["request"]) + if name := text(b, "name"); name != "" && b["request"] != nil && err == nil { + out = append(out, sessions.Button{Name: name, Request: request}) + } + } + } + for _, trace := range t.traces { + payload, _ := trace["payload"].(map[string]any) + switch trace["type"] { + case "choice", "cardV2": + add(payload["buttons"]) + case "carousel": + cards, _ := payload["cards"].([]any) + for _, c := range cards { + card, _ := c.(map[string]any) + add(card["buttons"]) + } + } + } + return out +} + +// printsAnswer is whether cmd prints a turn's answer as the API sent it: +// JSON, YAML, a table or --jq. Pretty output and TOON print it as said. +func printsAnswer(cmd *cobra.Command) bool { + format := outputFormat(cmd) + return output.WantsRawJSON(cmd) || (format != "pretty" && format != "toon") +} + +// printTurn prints a turn for scripts and agents: the answer, or for an +// agent the turn as said, with fields beside it. A dry run, or +// --include-headers, prints the response as Result does any other. +func printTurn(cmd *cobra.Command, t *sessionTurn, fields map[string]any) error { + if headers, _ := flagutil.GetBoolFlag(cmd, "include-headers"); headers || client.IsDryRun(cmd) || t.answer == nil { + return output.Result(cmd, t.res) + } + out := t.value(cmd) + for k, v := range fields { + out[k] = v + } + return output.Result(cmd, out) +} + +// value is the turn as printTurn prints it, without the fields: the answer +// as sent for scripts, and for an agent what was said (reply.go). +func (t *sessionTurn) value(cmd *cobra.Command) map[string]any { + out := map[string]any{} + if printsAnswer(cmd) { + for k, v := range t.answer { + out[k] = v + } + return out + } + out = readTurn(t.traces, t.stale).digest() + if debug, _ := cmd.Flags().GetBool(showDebugFlag); debug { + out["traces"] = t.traces + delete(out, "tracesHidden") + } + return out +} + +// writeTurn prints a turn for a person, as `conversation send` does. +func writeTurn(cmd *cobra.Command, t *sessionTurn) { + debug, _ := cmd.Flags().GetBool(showDebugFlag) + said := readTurn(t.traces, t.stale) + out, done := output.ResultWriter(cmd) + said.write(cmd, out, debug) + done() + if t.stale && skipCompile(cmd) { + warn(cmd, "This turn ran an older build of the draft: --no-compile kept it. Leave --no-compile out to run your latest edits.") + } + if debug { + enc := json.NewEncoder(cmd.OutOrStdout()) + enc.SetIndent("", " ") + fmt.Fprintln(cmd.OutOrStdout()) + _ = enc.Encode(t.traces) + } +} + +// forAPerson is whether cmd prints its turns as a chat reads: pretty +// output, and not a dry run or --include-headers, which print the response. +func forAPerson(cmd *cobra.Command) bool { + headers, _ := flagutil.GetBoolFlag(cmd, "include-headers") + return !headers && !client.IsDryRun(cmd) && !printsAnswer(cmd) && outputFormat(cmd) == "pretty" +} + +// note prints a muted line for a person, under the turn. +func note(cmd *cobra.Command, line string) { + out := cmd.OutOrStdout() + fmt.Fprintln(out, output.UI(cmd, out).Muted(line)) +} + +// writeNext says what to run next, on stderr, as an update's Next does. +func writeNext(cmd *cobra.Command, tips ...ui.Tip) { + w := cmd.ErrOrStderr() + u := output.UI(cmd, w) + fmt.Fprintln(w, u.Bold("Next:")) + for _, row := range u.Tips(tips, ui.TerminalWidth(w)-2) { + fmt.Fprintln(w, " "+row) + } +} + +// sessionCommand is `vf session `, with the scope the home prompt's +// context doesn't hold and, unless id is "", -s id. +func sessionCommand(verb string, scope sessionScope, id string) string { + line := "vf session " + verb + if id != "" { + line += " -s " + shellWord(id) + } + return line + session.Scope(scope.ProjectID, scope.EnvironmentAlias) +} + +// rememberButtons keeps the buttons the turn offered, for the next turn's +// --button. A session vf didn't start has no record to keep them in. +func rememberButtons(cmd *cobra.Command, scope sessionScope, id string, t *sessionTurn) { + if client.IsDryRun(cmd) || t.answer == nil { + return + } + _ = sessions.SetButtons(scope.ProjectID, scope.EnvironmentAlias, id, t.buttons()) +} + +// endAction is an end action, with reason. +func endAction(reason string) components.AnyRequest { + return components.CreateAnyRequestEndRequest(components.EndRequest{ + Type: components.EndRequestTypeEnd, + Payload: &components.EndRequestPayload{Reason: reason}, + }) +} + +// quoted is s in double quotes, for a person to read as typed. +func quoted(s string) string { + return `"` + strings.ReplaceAll(s, `"`, `\"`) + `"` +} diff --git a/internal/cli/conversation/sessionend.go b/internal/cli/conversation/sessionend.go new file mode 100644 index 00000000..73455f74 --- /dev/null +++ b/internal/cli/conversation/sessionend.go @@ -0,0 +1,161 @@ +// This file is not generated by Speakeasy. It is `vf session end`: end the +// conversation, and find its transcript for an evaluation. +// +// An evaluation runs only on a transcript that has ended, and finding it +// took an end action in JSON, a reason the help didn't mention, and a +// transcript search by a session ID nobody had said was the user ID (round +// 7: agent-migrator F2). end sends the end action, then searches the +// project's transcripts once by the session's ID: the newest created at or +// after the session started is its own, since a reused ID has older ones. +// The live check found it at once, 0.47 s after the end; vf looks again for +// up to 5 s before saying it isn't there yet, and still exits 0, since the +// session did end. + +package conversation + +import ( + "context" + "fmt" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" +) + +// transcriptWait is how long vf looks for a session's transcript, and +// transcriptPoll how long it waits between looks. +var transcriptWait, transcriptPoll = 5 * time.Second, 500 * time.Millisecond + +// clockSlack is how much earlier than the session's recorded start its +// transcript may say it began: this computer's clock and the API's differ. +const clockSlack = 10 * time.Second + +func addSessionEnd(parent *cobra.Command) { + cmd := &cobra.Command{ + Use: "end", + Short: "End the session, and find its transcript", + Long: "End the current session's conversation, and find its transcript, for 'vf evaluation run'. The session is no longer the current one.", + Example: " vf session end -p -e ", + RunE: runSessionEnd, + } + addSessionFlags(cmd, sessionScopeMeta, sessionHelp) + parent.AddCommand(cmd) +} + +func runSessionEnd(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + scope, err := scopeOf(cmd, sessionScopeMeta) + if err != nil { + return err + } + rec, ok := sessionOf(cmd, scope) + if !ok { + return noSession(cmd, scope) + } + s, opts, err := sdkFor(cmd) + if err != nil { + return err + } + req := sendRequest(scope, rec.ID, rec.Version, endAction("Ended with vf session end")) + res, err := s.Conversation.Send(client.WithSpinnerMessage(cmd.Context(), "Ending the session…"), *req, rawAnswer(opts)...) + if err != nil { + return output.Error(cmd, err) + } + if client.IsDryRun(cmd) { + return output.Result(cmd, res) + } + _ = sessions.End(scope.ProjectID, scope.EnvironmentAlias, rec.ID) + found, err := FindTranscript(client.WithSpinnerMessage(cmd.Context(), "Finding its transcript…"), s, opts, scope.ProjectID, scope.EnvironmentAlias, rec.ID, rec.StartedAt) + if err != nil { + return output.Error(cmd, err) + } + result := map[string]any{"session": rec.ID, "ended": true, "transcriptID": nil} + if found != nil { + result["transcriptID"] = found.ID + } else { + result["reason"] = notFoundYet + } + if !output.ForAPerson(cmd) { + return output.Result(cmd, result) + } + out := cmd.OutOrStdout() + u := output.UI(cmd, out) + if found == nil { + fmt.Fprintln(out, u.Status(ui.StatusDone, "Ended session "+rec.ID)) + warn(cmd, notFoundYet+" `"+transcriptSearch(scope, rec.ID)+"` lists it once it is.") + return nil + } + fmt.Fprintln(out, u.Status(ui.StatusDone, "Ended session "+rec.ID+" "+u.Glyph(ui.Separator)+" transcript "+found.ID)) + writeNext(cmd, ui.Tip{ + Command: "vf evaluation run -e -t " + found.ID + session.Scope(scope.ProjectID, ""), + Does: "Run an evaluation on it", + }) + return nil +} + +// notFoundYet says the transcript wasn't there when vf looked. +const notFoundYet = "The API had no transcript for the session yet." + +// transcriptSearch is the command that lists session id's transcripts. +func transcriptSearch(scope sessionScope, id string) string { + return "vf transcript search --session-id " + shellWord(id) + session.Scope(scope.ProjectID, "") + " --environment-alias " + shellWord(scope.EnvironmentAlias) +} + +// FindTranscript is session id's transcript: of the project's transcripts +// in environment alias with that session ID, the newest created at or +// after since, or the newest of all when since is zero. While there is +// none it looks again, for up to 5 s, then gives nil. +func FindTranscript(ctx context.Context, s *sdk.VoiceflowSDK, opts []operations.Option, projectID, alias, id string, since time.Time) (*components.StableTranscriptSummary, error) { + body := components.StableTranscriptSearchRequestV2{SessionID: &id} + if alias != "" { + body.EnvironmentAlias = &alias + } + req := operations.StableTranscriptControllerSearchV2Request{ProjectID: projectID, Body: body} + deadline := time.Now().Add(transcriptWait) + for { + res, err := s.Transcript.Search(ctx, req, opts...) + if err != nil { + return nil, err + } + if found := newestSince(res, id, since); found != nil { + return found, nil + } + if !time.Now().Before(deadline) { + return nil, nil + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(transcriptPoll): + } + } +} + +// newestSince is the newest transcript of session id in res created at or +// after since, or nil. +func newestSince(res *operations.StableTranscriptControllerSearchV2Response, id string, since time.Time) *components.StableTranscriptSummary { + if res == nil || res.StableTranscriptSearchResponseV2 == nil { + return nil + } + var newest *components.StableTranscriptSummary + for i, t := range res.StableTranscriptSearchResponseV2.Transcripts { + if t.SessionID != id || (!since.IsZero() && t.CreatedAt.Before(since.Add(-clockSlack))) { + continue + } + if newest == nil || t.CreatedAt.After(newest.CreatedAt) { + newest = &res.StableTranscriptSearchResponseV2.Transcripts[i] + } + } + return newest +} diff --git a/internal/cli/conversation/sessionend_test.go b/internal/cli/conversation/sessionend_test.go new file mode 100644 index 00000000..45b7b291 --- /dev/null +++ b/internal/cli/conversation/sessionend_test.go @@ -0,0 +1,91 @@ +// This file is not generated by Speakeasy. It covers how sessionend.go +// finds a session's transcript: it looks again while the API has none yet, +// gives up after a while, and takes the newest since the session started. + +package conversation + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/voiceflow/cli/internal/sdk" + "github.com/voiceflow/cli/internal/sdk/models/components" +) + +// transcriptServer answers each search with the next of answers, the last +// one again and again, and counts the searches. +func transcriptServer(t *testing.T, answers ...string) (*sdk.VoiceflowSDK, func() int) { + t.Helper() + var mu sync.Mutex + searches := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + mu.Lock() + answer := answers[min(searches, len(answers)-1)] + searches++ + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, answer) + })) + t.Cleanup(srv.Close) + s := sdk.New(sdk.WithServerURL(srv.URL), sdk.WithSecurity(components.Security{Token: "vfp_fake"})) + return s, func() int { mu.Lock(); defer mu.Unlock(); return searches } +} + +func transcripts(list ...string) string { + return `{"transcripts":[` + strings.Join(list, ",") + `],"returned":` + string(rune('0'+len(list))) + `,"hasMore":false}` +} + +func summary(id, session string, created time.Time) string { + return `{"id":"` + id + `","sessionID":"` + session + `","createdAt":"` + created.UTC().Format(time.RFC3339) + `","endedAt":null,"creatorURL":""}` +} + +func quickLooks(t *testing.T, wait time.Duration) { + savedWait, savedPoll := transcriptWait, transcriptPoll + transcriptWait, transcriptPoll = wait, 10*time.Millisecond + t.Cleanup(func() { transcriptWait, transcriptPoll = savedWait, savedPoll }) +} + +func TestFindTranscriptLooksAgainUntilItIsThere(t *testing.T) { + quickLooks(t, time.Second) + started := time.Now() + s, searches := transcriptServer(t, transcripts(), transcripts(), transcripts(summary("t-1", "s-1", started))) + found, err := FindTranscript(context.Background(), s, nil, "p1", "main", "s-1", started) + if err != nil || found == nil || found.ID != "t-1" || searches() != 3 { + t.Errorf("found %+v, %v after %d searches", found, err, searches()) + } +} + +func TestFindTranscriptGivesUpAfterAWhile(t *testing.T) { + quickLooks(t, 50*time.Millisecond) + started := time.Now() + // Only an earlier conversation with the same ID: not this session's. + s, searches := transcriptServer(t, transcripts(summary("t-old", "s-1", started.Add(-time.Hour)))) + found, err := FindTranscript(context.Background(), s, nil, "p1", "main", "s-1", started) + if err != nil || found != nil || searches() < 2 { + t.Errorf("found %+v, %v after %d searches", found, err, searches()) + } +} + +func TestFindTranscriptTakesTheNewestSinceTheStart(t *testing.T) { + quickLooks(t, 0) + started := time.Now() + s, _ := transcriptServer(t, transcripts( + summary("t-old", "s-1", started.Add(-time.Hour)), + summary("t-new", "s-1", started.Add(-2*time.Second)), // this computer's clock a little ahead + summary("t-other", "s-2", started.Add(time.Minute)), + )) + if found, err := FindTranscript(context.Background(), s, nil, "p1", "main", "s-1", started); err != nil || found == nil || found.ID != "t-new" { + t.Errorf("found %+v, %v", found, err) + } + // With no start known, the newest of all. + if found, err := FindTranscript(context.Background(), s, nil, "p1", "main", "s-1", time.Time{}); err != nil || found == nil || found.ID != "t-new" { + t.Errorf("with no start: found %+v, %v", found, err) + } +} diff --git a/internal/cli/conversation/sessionsend.go b/internal/cli/conversation/sessionsend.go new file mode 100644 index 00000000..13fab41e --- /dev/null +++ b/internal/cli/conversation/sessionsend.go @@ -0,0 +1,209 @@ +// This file is not generated by Speakeasy. It is `vf session send`: say +// the next thing in a session, in plain words. +// +// `conversation send` needed --user-id, --text and the scope on every turn. +// Here the message is the command's words, `vf session send What are your +// hours?`, and the session is the current one, so a turn is that line. With +// no session going, send starts one first, as `vf session start` would, and +// says so. --action sends any other action, and --button presses a button +// the agent's last reply offered, by its label: vf keeps each reply's +// buttons with the session, and sends the button's own request. +// +// A turn compiles the draft first only when compile rule B says to +// (autocompile.go): when it starts a conversation, or vf edited the draft +// since its last compile. It prints as `conversation send`'s does; JSON and +// TOON add the session's ID, and the launch's turn when send started one. + +package conversation + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/usage" +) + +const buttonFlag = "button" + +const sessionSendLong = `Say the next thing to the agent in the current session: the words after send are the message. + +With no session going, vf starts one first, as 'vf session start' does, and says which. -s talks in another session. --action sends an action instead of a message, and --button presses a button the agent's last reply offered.` + +const sessionSendExample = ` vf session send -p -e 'What are your hours?' + vf session send -p -e --button 'Book a table' + vf session send -p -e --action '{"type":"launch"}'` + +func addSessionSend(parent *cobra.Command) { + cmd := &cobra.Command{ + Use: "send ", + Short: "Say the next thing to the agent", + Long: sessionSendLong, + Example: sessionSendExample, + Args: cobra.ArbitraryArgs, // the message + RunE: runSessionSend, + } + addSessionFlags(cmd, sessionScopeMeta, "The session to talk in. Without it, the current one: the one the last 'vf session start' began.") + cmd.Flags().String(actionFlag, "", `An action to send instead of a message, as JSON: {"type":"launch"} starts the conversation over, and {"type":"end","payload":{"reason":"done"}} ends it.`) + cmd.Flags().String(buttonFlag, "", "Press a button the agent's last reply offered, by its label.") + addNoCompileFlag(cmd) // autocompile.go + addShowDebugFlag(cmd) // reply.go + addCustomFlag(cmd) // actiontype.go + parent.AddCommand(cmd) +} + +func runSessionSend(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + scope, err := scopeOf(cmd, sessionScopeMeta) + if err != nil { + return err + } + message := strings.Join(args, " ") + if err := oneThingToSay(cmd, scope, message); err != nil { + return err + } + s, opts, err := sdkFor(cmd) + if err != nil { + return err + } + rec, going := sessionOf(cmd, scope) + var launch *sessionTurn + if !going { + o := startOptions{id: sessions.NewID(), version: "draft"} + if launch, err = startSession(cmd, s, opts, scope, o); err != nil { + return err + } + rec = sessions.Session{ID: o.id, Version: o.version, Buttons: launch.buttons()} + } + action, said, err := actionToSend(cmd, scope, rec, message) + if err != nil { + return err + } + if launch != nil && forAPerson(cmd) { + sayCurrent(cmd, "Started session", rec.ID) + writeTurn(cmd, launch) + out := cmd.OutOrStdout() + fmt.Fprintln(out, output.UI(cmd, out).Bold("You ")+said) + } + req := sendRequest(scope, rec.ID, rec.Version, action) + giveEndReason(req, "Ended with vf session send") // endaction.go + starts := actionType(req.Body.Action) == string(components.LaunchRequestTypeLaunch) + wait, err := startTurn(cmd, s, compilesFirst(cmd, rec.Version, starts, scope.ProjectID, scope.EnvironmentAlias), scope.ProjectID, scope.EnvironmentAlias) // autocompile.go: rule B + if err != nil { + return err + } + t, err := takeTurn(cmd, s, opts, wait, req) + if err != nil { + return err + } + rememberButtons(cmd, scope, rec.ID, t) + compiled := compileAfterStaleTurn(cmd, s, rec.Version, t.stale, scope.ProjectID, scope.EnvironmentAlias) // autocompile.go: an edit the turn missed + if forAPerson(cmd) { + writeTurn(cmd, t) + return compiled() + } + fields := map[string]any{"session": rec.ID} + if launch != nil && launch.answer != nil { + fields["launch"] = launch.value(cmd) + } + if err := printTurn(cmd, t, fields); err != nil { + return err + } + return compiled() +} + +// oneThingToSay checks that send was given one thing to say: a message, +// --action or --button. +func oneThingToSay(cmd *cobra.Command, scope sessionScope, message string) error { + given := 0 + for _, said := range []bool{message != "", flagutil.FlagChanged(cmd, actionFlag), flagutil.FlagChanged(cmd, buttonFlag)} { + if said { + given++ + } + } + switch { + case given > 1: + x := output.Explanation{ + Type: "usage_error", + Title: "A message, --action and --button each say what to send", + Why: []string{"A turn sends one of them."}, + Next: []string{"Keep the message, --action or --button, and leave out the others"}, + } + return output.Report(cmd, x, errors.New("a message, --action and --button can't be combined")) + case given == 0: + x := output.Explanation{ + Type: "usage_error", + Title: "Say what to send", + Why: []string{"The words after send are the message."}, + Next: []string{"`" + sessionCommand("send", scope, givenSession(cmd)) + " Hello` says Hello to the agent"}, + } + return output.Report(cmd, x, errors.New("no message to send")) + } + return nil +} + +// actionToSend is the action a turn sends, and what the person said, as a +// chat shows it. +func actionToSend(cmd *cobra.Command, scope sessionScope, rec sessions.Session, message string) (components.AnyRequest, string, error) { + switch { + case flagutil.FlagChanged(cmd, buttonFlag): + label, _ := cmd.Flags().GetString(buttonFlag) + for _, b := range rec.Buttons { + var action components.AnyRequest + if strings.EqualFold(strings.TrimSpace(b.Name), strings.TrimSpace(label)) && json.Unmarshal(b.Request, &action) == nil { + return action, "[" + b.Name + "]", nil + } + } + return components.AnyRequest{}, "", noSuchButton(cmd, scope, rec, label) + case flagutil.FlagChanged(cmd, actionFlag): + given, _ := cmd.Flags().GetString(actionFlag) + var action components.AnyRequest + if err := json.Unmarshal([]byte(given), &action); err != nil { + var typed struct { + Type *string `json:"type"` + } + if json.Unmarshal([]byte(given), &typed) == nil && typed.Type != nil && !sendable(cmd, *typed.Type) { + return action, "", unknownType(cmd, *typed.Type) // actiontype.go + } + x := output.Explanation{ + Type: "invalid_flag_value", + Title: "--action isn't an action vf can send", + Why: []string{`An action is JSON with a "type", such as {"type":"launch"}: ` + err.Error() + "."}, + } + return action, "", output.Report(cmd, x, err) + } + if typ := actionType(action); !sendable(cmd, typ) { + return action, "", unknownType(cmd, typ) // actiontype.go: a misspelt type isn't sent + } + return action, given, nil + } + text := components.TextRequest{Type: components.TextRequestTypeText, Payload: message} + return components.CreateAnyRequestTextRequest(text), message, nil +} + +// noSuchButton explains a --button the last reply didn't offer. +func noSuchButton(cmd *cobra.Command, scope sessionScope, rec sessions.Session, label string) error { + x := output.Explanation{ + Type: "invalid_flag_value", + Title: "The agent's last reply offered no button " + quoted(label), + Why: []string{"vf keeps the buttons of each reply in a session it started, and the last reply in " + rec.ID + " offered none."}, + Next: []string{"`" + sessionCommand("send", scope, givenSession(cmd)) + " " + shellWord(label) + "` sends the label as a message"}, + } + if len(rec.Buttons) > 0 { + names := make([]string, len(rec.Buttons)) + for i, b := range rec.Buttons { + names[i] = quoted(b.Name) + } + x.Why = []string{"It offered " + strings.Join(names, ", ") + "."} + } + return output.Report(cmd, x, fmt.Errorf("no button %q in the last reply", label)) +} diff --git a/internal/cli/conversation/sessionstart.go b/internal/cli/conversation/sessionstart.go new file mode 100644 index 00000000..235a7ecf --- /dev/null +++ b/internal/cli/conversation/sessionstart.go @@ -0,0 +1,321 @@ +// This file is not generated by Speakeasy. It is `vf session start`: a +// fresh conversation with the agent, as a new person starts one. +// +// A live check on the real API (round 8) settled how. run-script refuses an +// empty script, so a start can't be one. Variables set before a user has +// any state are kept through the launch, so vf sets them first, then +// launches. A relaunch keeps the variables an ID had, and goes on in its +// transcript unless an end action came first. So when -s names an ID whose +// conversation is going, vf ends it, then deletes its state, and only then +// sets the variables and launches: the session starts clean, in a +// transcript of its own. A generated ID has nothing to clear. +// +// With the draft, vf compiles first (autocompile.go), so the session runs +// the latest edits. The session becomes the current one for its project +// and environment, for `send`, `update`, `get` and `end` to act on. + +package conversation + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk" + "github.com/voiceflow/cli/internal/sdk/models/components" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" +) + +const startLong = `Start a fresh conversation with the agent, and make it the current session. + +With the draft, vf compiles it first, so the session runs your latest edits. Variables given with --var or --variables are set before the launch, as a known caller's would be. -s reuses a session ID, such as a phone number the agent expects: vf ends the conversation it had and clears its state first, so the session starts clean.` + +const startExample = ` vf session start -p -e + vf session start -p -e --var tier=gold --var visits=3 + vf session start -p -e -s +15551234567 --variables '{"name":"Ana"}'` + +// startMeta are start's scope flags, and the version it talks to. +var startMeta = append(slices.Clip(sessionScopeMeta), flagutil.FlagMeta{ + FlagName: "version-param", Shorthand: "v", FieldPath: "Version", Kind: flagutil.FlagKindEnum, + HasDefault: true, DefaultStr: "draft", EnumValues: []string{"draft", "published"}, + Description: "Which version to talk to: draft, your latest edits, compiled first; or published, what your live users talk to since the last 'vf environment publish'. (options: draft, published)", +}) + +func addSessionStart(parent *cobra.Command) { + cmd := &cobra.Command{ + Use: "start", + Short: "Start a fresh conversation with the agent", + Long: startLong, + Example: startExample, + RunE: runSessionStart, + } + addSessionFlags(cmd, startMeta, "The session ID, which the agent reads as user_id. Leave it out for a new one. "+ + "One used before starts over: vf ends its conversation and clears its state first.") + addVariableFlags(cmd) + cmd.Flags().String("persona", "", "The persona to launch as, by name.") + addNoCompileFlag(cmd) // autocompile.go + addShowDebugFlag(cmd) // reply.go + parent.AddCommand(cmd) +} + +// addVariableFlags gives cmd --var and --variables. +func addVariableFlags(cmd *cobra.Command) { + cmd.Flags().StringArray(varFlag, nil, "A variable to set, as name=value; repeat it for more. "+ + "The value is text, unless it is a JSON number, true, false or null.") + cmd.Flags().String(variablesFlag, "", `Variables to set, as a JSON object keyed by name, such as {"tier":"gold","visits":3}. --var sets one on top.`) + flagutil.ReadsText(cmd, variablesFlag) // @file, or - for stdin +} + +func runSessionStart(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + scope, err := scopeOf(cmd, startMeta) + if err != nil { + return err + } + vars, err := variablesOf(cmd) + if err != nil { + return err + } + s, opts, err := sdkFor(cmd) + if err != nil { + return err + } + o := startOptions{id: givenSession(cmd), version: scope.Version, vars: vars} + o.persona, _ = cmd.Flags().GetString("persona") + if o.given = o.id != ""; !o.given { + o.id = sessions.NewID() + } + t, err := startSession(cmd, s, opts, scope, o) + if err != nil { + return err + } + compiled := compileAfterStaleTurn(cmd, s, o.version, t.stale, scope.ProjectID, scope.EnvironmentAlias) // autocompile.go + if !forAPerson(cmd) { + if err := printTurn(cmd, t, map[string]any{"session": o.id, "version": o.version, "projectID": scope.ProjectID, "environment": scope.EnvironmentAlias}); err != nil { + return err + } + return compiled() + } + writeTurn(cmd, t) + sayCurrent(cmd, "Session", o.id) + writeNext(cmd, + ui.Tip{Command: sessionCommand("send", scope, "") + ` ""`, Does: "Say the next thing"}, + ui.Tip{Command: sessionCommand("end", scope, ""), Does: "End it, and find its transcript"}, + ) + return compiled() +} + +// sayCurrent says, for a person, which session is now the current one. +func sayCurrent(cmd *cobra.Command, lead, id string) { + out := cmd.OutOrStdout() + u := output.UI(cmd, out) + fmt.Fprintln(out, lead+" "+u.Accent(id)+u.Muted(" (the current one)")) +} + +// startOptions are how a session starts. +type startOptions struct { + id string + given bool // -s named the ID, which may have a conversation to clear + version string + vars map[string]any + persona string +} + +// startSession starts session o.id: it compiles the draft, ends and clears +// a conversation the ID had, sets the variables, launches, and records the +// session as the current one. One spinner line waits through it all. A dry +// run shows each request it can, and records nothing. +func startSession(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, o startOptions) (*sessionTurn, error) { + compiles := compilesFirst(cmd, o.version, true, scope.ProjectID, scope.EnvironmentAlias) + wait, err := startTurn(cmd, s, compiles, scope.ProjectID, scope.EnvironmentAlias) // autocompile.go + if err != nil { + return nil, err + } + // The requests before the launch go without the trace that tells a + // Ctrl-C whether the turn went out: only the launch is a turn. + if err := prepareSession(client.WithoutSpinner(cmd.Context()), s, opts, scope, o); err != nil { + wait.stop() + if canceled(err) { + return nil, nothingSent(cmd, err) + } + return nil, output.Error(cmd, err) + } + launch := components.LaunchRequest{Type: components.LaunchRequestTypeLaunch} + if o.persona != "" { + launch.Payload = &components.LaunchRequestPayload{Persona: &o.persona} + } + startedAt := time.Now() + t, err := takeTurn(cmd, s, opts, wait, sendRequest(scope, o.id, o.version, components.CreateAnyRequestLaunchRequest(launch))) + if err != nil { + return nil, err + } + if client.IsDryRun(cmd) { + return t, nil + } + record := sessions.Session{ID: o.id, Version: o.version, StartedAt: startedAt, Buttons: t.buttons()} + if err := sessions.Start(scope.ProjectID, scope.EnvironmentAlias, record); err != nil { + warn(cmd, "vf couldn't remember the session ("+err.Error()+"): name it with -s "+o.id+" on each command.") + } + return t, nil +} + +// prepareSession does what comes before a session's launch: for an ID -s +// named, it ends the conversation the ID has going and deletes its state; +// then it sets the variables. +func prepareSession(ctx context.Context, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, o startOptions) error { + if o.given { + answer, err := readState(ctx, s, opts, scope, o.id, o.version) + if err != nil { + return err + } + if state := stateOf(answer); hasState(state) { + if stack, _ := state["stack"].([]any); len(stack) > 0 { + req := sendRequest(scope, o.id, o.version, endAction("Ended by vf session start, to start the session again")) + if _, err := s.Conversation.Send(ctx, *req, rawAnswer(opts)...); err != nil { + return err + } + } + req := operations.StableConversationStateControllerDeleteRequest{ + UserID: o.id, ProjectID: scope.ProjectID, EnvironmentAlias: scope.EnvironmentAlias, + Version: operations.StableConversationStateControllerDeleteVersion(o.version), + } + if _, err := s.Conversation.State.Delete(ctx, req, rawAnswer(opts)...); err != nil { + return err + } + } + } + if len(o.vars) == 0 { + return nil + } + _, err := setVariables(ctx, s, opts, scope, o.id, o.version, o.vars) + return err +} + +// setVariables merges vars into session id's variables. +func setVariables(ctx context.Context, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, id, version string, vars map[string]any) (*operations.StableConversationStateControllerUpdateVariablesResponse, error) { + req := operations.StableConversationStateControllerUpdateVariablesRequest{ + UserID: id, ProjectID: scope.ProjectID, EnvironmentAlias: scope.EnvironmentAlias, + Version: operations.StableConversationStateControllerUpdateVariablesVersion(version), + Body: components.StableConversationUpdateVariablesRequest{Variables: vars}, + } + return s.Conversation.State.UpdateVariables(ctx, req, rawAnswer(opts)...) +} + +// readState is session id's state as the API answers it, +// {"state":{"stack":…,"variables":…}}, or nil when the API has none: a 404, +// or a dry run. +func readState(ctx context.Context, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, id, version string) (map[string]any, error) { + req := operations.StableConversationStateControllerGetRequest{ + UserID: id, ProjectID: scope.ProjectID, EnvironmentAlias: scope.EnvironmentAlias, + Version: operations.StableConversationStateControllerGetVersion(version), + } + res, err := s.Conversation.State.Get(ctx, req, rawAnswer(opts)...) + if err != nil { + if output.StatusCode(err) == 404 { + return nil, nil + } + return nil, err + } + var answer map[string]any + if !output.PeekJSON(res.HTTPMeta.Response, &answer) { + return nil, nil + } + return answer, nil +} + +// stateOf is the state in a state answer. +func stateOf(answer map[string]any) map[string]any { + state, _ := answer["state"].(map[string]any) + return state +} + +// hasState is whether state holds anything: a conversation, variables or +// storage. A user the API hasn't met has an empty one. +func hasState(state map[string]any) bool { + for _, key := range []string{"stack", "variables", "storage"} { + switch v := state[key].(type) { + case []any: + if len(v) > 0 { + return true + } + case map[string]any: + if len(v) > 0 { + return true + } + } + } + return false +} + +// variablesOf is the variables --variables and --var give, --var on top. +// A --var value is text, unless it is a JSON number, true, false or null. +func variablesOf(cmd *cobra.Command) (map[string]any, error) { + vars := map[string]any{} + if flagutil.FlagChanged(cmd, variablesFlag) { + given, _ := cmd.Flags().GetString(variablesFlag) + dec := json.NewDecoder(strings.NewReader(given)) + dec.UseNumber() // an ID-sized number keeps its digits + var object map[string]any + if err := dec.Decode(&object); err != nil || object == nil { + return nil, badVariables(cmd, "--"+variablesFlag+` takes a JSON object keyed by variable name, such as {"tier":"gold"}`, err) + } + for k, v := range object { + vars[k] = v + } + } + pairs, _ := cmd.Flags().GetStringArray(varFlag) + for _, pair := range pairs { + name, value, ok := strings.Cut(pair, "=") + if name = strings.TrimSpace(name); !ok || name == "" { + return nil, badVariables(cmd, "--"+varFlag+" takes name=value, such as --var tier=gold; got "+quoted(pair), nil) + } + vars[name] = varValue(value) + } + return vars, nil +} + +// varValue is a --var value: a JSON number, true, false or null as that, +// and anything else as text. +func varValue(s string) any { + if !json.Valid([]byte(s)) { + return s + } + dec := json.NewDecoder(strings.NewReader(s)) + dec.UseNumber() + var v any + if dec.Decode(&v) != nil { + return s + } + switch v.(type) { + case json.Number, bool, nil: + return v + } + return s +} + +// badVariables explains variables vf couldn't read. Nothing was sent. +func badVariables(cmd *cobra.Command, why string, err error) error { + if err == nil { + err = errors.New(why) + } + x := output.Explanation{ + Type: "invalid_flag_value", + Title: "vf couldn't read the variables, so nothing was sent", + Why: []string{why + "."}, + } + return output.Report(cmd, x, err) +} diff --git a/internal/cli/conversation/sessionstate.go b/internal/cli/conversation/sessionstate.go new file mode 100644 index 00000000..7b8f2991 --- /dev/null +++ b/internal/cli/conversation/sessionstate.go @@ -0,0 +1,192 @@ +// This file is not generated by Speakeasy. It is `vf session update` and +// `vf session get`: set and read a session's variables. +// +// They are `conversation state update-variables` and `state get` for the +// current session, with the version it talks to, so they need no user ID +// and no --version-param. update takes the variables as start does, --var +// name=value or --variables JSON, and merges them in. get shows a person +// the session, its version and its variables; JSON prints the state as the +// API answers it, with the session's ID beside it. + +package conversation + +import ( + "encoding/json" + "errors" + "fmt" + "slices" + "sort" + "strings" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/ui" + "github.com/voiceflow/cli/internal/usage" +) + +const sessionHelp = "The session to act on. Without it, the current one: the one the last 'vf session start' began." + +func addSessionUpdate(parent *cobra.Command) { + cmd := &cobra.Command{ + Use: "update", + Short: "Set variables in the session", + Long: "Set variables in the current session, keeping the others. The agent reads them from its next turn.", + Example: " vf session update -p -e --var tier=gold", + RunE: runSessionUpdate, + } + addSessionFlags(cmd, sessionScopeMeta, sessionHelp) + addVariableFlags(cmd) // sessionstart.go + parent.AddCommand(cmd) +} + +func runSessionUpdate(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + scope, err := scopeOf(cmd, sessionScopeMeta) + if err != nil { + return err + } + vars, err := variablesOf(cmd) + if err != nil { + return err + } + if len(vars) == 0 { + x := output.Explanation{ + Type: "nothing_to_update", + Title: "Couldn't set variables in the session · nothing to change", + Why: []string{"No --var or --variables gave a variable to set."}, + Next: []string{"`" + sessionCommand("update", scope, givenSession(cmd)) + " --var tier=gold` sets one"}, + } + return output.Report(cmd, x, output.ErrNothingToUpdate) + } + rec, ok := sessionOf(cmd, scope) + if !ok { + return noSession(cmd, scope) + } + s, opts, err := sdkFor(cmd) + if err != nil { + return err + } + res, err := setVariables(cmd.Context(), s, opts, scope, rec.ID, rec.Version, vars) + if err != nil { + return output.Error(cmd, err) + } + var answer map[string]any + if client.IsDryRun(cmd) || !output.PeekJSON(res.HTTPMeta.Response, &answer) { + return output.Result(cmd, res) + } + if output.ForAPerson(cmd) { + names := make([]string, 0, len(vars)) + for name := range vars { + names = append(names, name) + } + sort.Strings(names) + out := cmd.OutOrStdout() + fmt.Fprintln(out, output.UI(cmd, out).Status(ui.StatusDone, "Updated "+strings.Join(names, ", ")+" in session "+rec.ID)) + return nil + } + if answer == nil { + answer = map[string]any{} + } + answer["session"] = rec.ID + return output.Result(cmd, answer) +} + +func addSessionGet(parent *cobra.Command) { + cmd := &cobra.Command{ + Use: "get", + Short: "Show the session and its variables", + Long: "Show the current session: its ID, the version it talks to, and its variables. -o json prints its whole state, as the API keeps it.", + Example: " vf session get -p -e ", + RunE: runSessionGet, + } + addSessionFlags(cmd, getMeta, sessionHelp) + parent.AddCommand(cmd) +} + +// getMeta are get's scope flags, and the version, for a session vf didn't +// start: it knows the version of one it did. +var getMeta = append(slices.Clip(sessionScopeMeta), flagutil.FlagMeta{ + FlagName: "version-param", Shorthand: "v", FieldPath: "Version", Kind: flagutil.FlagKindEnum, + EnumValues: []string{"draft", "published"}, + Description: "The version the session talks to. vf knows it for a session it started; for another, it is the draft unless you say published. (options: draft, published)", +}) + +func runSessionGet(cmd *cobra.Command, args []string) error { + if usage.UsageRequested(cmd) { + return usage.EmitSchema(cmd, cmd.OutOrStdout()) + } + scope, err := scopeOf(cmd, getMeta) + if err != nil { + return err + } + rec, ok := sessionOf(cmd, scope) + if !ok { + return noSession(cmd, scope) + } + if scope.Version != "" { + rec.Version = scope.Version + } + s, opts, err := sdkFor(cmd) + if err != nil { + return err + } + answer, err := readState(cmd.Context(), s, opts, scope, rec.ID, rec.Version) + if err != nil { + return output.Error(cmd, err) + } + if client.IsDryRun(cmd) { + return nil + } + if answer == nil { + return output.Error(cmd, errors.New("the API has no state for session "+rec.ID)) + } + if !output.ForAPerson(cmd) { + answer["session"] = rec.ID + return output.Result(cmd, answer) + } + out := cmd.OutOrStdout() + u := output.UI(cmd, out) + current, _ := sessions.Current(scope.ProjectID, scope.EnvironmentAlias) + id := rec.ID + if current.ID == rec.ID { + id += u.Muted(" (the current one)") + } + fmt.Fprintln(out, u.Bold("Session ")+id) + fmt.Fprintln(out, u.Bold("Version ")+rec.Version) + vars, _ := stateOf(answer)["variables"].(map[string]any) + if len(vars) == 0 { + fmt.Fprintln(out, u.Bold("Variables ")+u.Muted("none")) + return nil + } + fmt.Fprintln(out, u.Bold("Variables")) + names := make([]string, 0, len(vars)) + width := 0 + for name := range vars { + names = append(names, name) + width = max(width, len(name)) + } + sort.Strings(names) + for _, name := range names { + fmt.Fprintf(out, " %-*s %s\n", width, name, shown(vars[name])) + } + return nil +} + +// shown is a variable's value as get shows it: text as it is, anything +// else as JSON. +func shown(v any) string { + if s, ok := v.(string); ok { + return s + } + b, err := json.Marshal(v) + if err != nil { + return fmt.Sprint(v) + } + return string(b) +} diff --git a/internal/cli/conversation/version.go b/internal/cli/conversation/version.go index 01d90348..233741c9 100644 --- a/internal/cli/conversation/version.go +++ b/internal/cli/conversation/version.go @@ -6,14 +6,14 @@ // three flags every turn, and leaving --version-param out opened a // draft/published picker each time (round-5 sweep, human-newcomer:F6, // agent-builder:F12). Now it defaults to draft, and its help says what each -// version is. A turn with the draft is compiled first (autocompile.go), -// whether draft was given or defaulted. +// version is. The draft is compiled when compile rule B says to +// (autocompile.go), whether draft was given or defaulted. package conversation import "github.com/voiceflow/cli/internal/flagutil" -const sendVersionHelp = "Which version to talk to: draft, your latest edits, compiled before each turn; " + +const sendVersionHelp = "Which version to talk to: draft, your latest edits, which vf compiles when a conversation starts and after it edits them; " + "or published, what your live users talk to since the last 'vf environment publish'. (options: draft, published)" // draftUnlessPublished makes send's --version-param default to draft. It diff --git a/internal/cli/conversationcancel_test.go b/internal/cli/conversationcancel_test.go index 930e6306..8c526060 100644 --- a/internal/cli/conversationcancel_test.go +++ b/internal/cli/conversationcancel_test.go @@ -94,7 +94,7 @@ func TestCtrlCAfterTheMessageWentOutSaysItMayHaveReachedTheAgent(t *testing.T) { said := homeLine(t, ctx, "conversation", "send", "-p", "6b0e33f2297e8fc83d574d93", "-u", "pu-2", "-e", "main", "--text", "Do you ship to Canada?") got := requests() - if len(got) != 2 || got[0] != "compile" || !strings.Contains(got[1], `"payload":"Do you ship to Canada?"`) { + if len(got) != 1 || !strings.Contains(got[0], `"payload":"Do you ship to Canada?"`) { // a turn mid-conversation doesn't compile (rule B) t.Fatalf("the API got %q", got) } flat := strings.Join(strings.Fields(said), " ") @@ -106,7 +106,7 @@ func TestCtrlCAfterTheMessageWentOutSaysItMayHaveReachedTheAgent(t *testing.T) { if strings.Contains(said, "Canceled") || strings.Contains(flat, "Nothing was sent") { t.Errorf("says the turn was canceled:\n%s", said) } - want := `vf conversation state get --user-id pu-2 --project-id 6b0e33f2297e8fc83d574d93 --environment-alias main --version-param draft --jq ".state.variables | {last_utterance, last_response}"` + want := `vf session get --session pu-2 --project-id 6b0e33f2297e8fc83d574d93 --environment-alias main --jq ".state.variables | {last_utterance, last_response}"` if line := shownCommand(t, said); line != want { t.Errorf("gives `%s`, want `%s`", line, want) } @@ -132,7 +132,7 @@ func TestCtrlCBeforeTheMessageWentOutSaysNothingWasSent(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() requests := ctrlCServer(t, "compile", cancel) - said := homeLine(t, ctx, "conversation", "send", "-p", "p1", "-u", "pu-2", "-e", "main", "--text", "Do you ship to Canada?") + said := homeLine(t, ctx, "conversation", "send", "-p", "p1", "-u", "pu-2", "-e", "main", "-a", `{"type":"launch"}`) // a launch compiles first (rule B) if got := requests(); len(got) != 1 || got[0] != "compile" { t.Errorf("the API got %q", got) } @@ -174,7 +174,7 @@ func TestCtrlCAfterAScriptWentOut(t *testing.T) { args []string want string }{ - {[]string{"-u", "+15551234567"}, "vf conversation state get --user-id +15551234567 --project-id p1 --environment-alias main --version-param draft"}, + {[]string{"-u", "+15551234567"}, "vf session get --session +15551234567 --project-id p1 --environment-alias main --jq"}, {nil, "vf transcript search --project-id p1 --environment-alias main"}, } { ctx, cancel := context.WithCancel(context.Background()) @@ -206,7 +206,7 @@ func TestTheCommandACanceledTurnGivesRuns(t *testing.T) { t.Errorf("%q: `%s`: %v", user, line, problems) } words, err := cmdcheck.Words(line) - if err != nil || !strings.Contains(strings.Join(words, "\x00"), "\x00--user-id\x00"+user+"\x00") || !strings.Contains(line, "--version-param published") { + if err != nil || !strings.Contains(strings.Join(words, "\x00"), "\x00--session\x00"+user+"\x00") || !strings.Contains(line, "--version-param published") { t.Errorf("%q: `%s` names another user or version: %q", user, line, words) } } diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go new file mode 100644 index 00000000..e047a16f --- /dev/null +++ b/internal/cli/session_test.go @@ -0,0 +1,496 @@ +// This file is not generated by Speakeasy. It covers `vf session` +// (conversation/session*.go) against a fake API: what each command sends, +// in what order, what it prints, and compile rule B across commands. + +package cli + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "sync" + "testing" + "time" + + "github.com/voiceflow/cli/internal/cmdcheck" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sessions" +) + +// sessionAPI is the API as a session meets it. It records each request in +// a few words, "compile", "launch", "text hi", "variables {…}", with the +// user ID it was for. +type sessionAPI struct { + t *testing.T + url string + mu sync.Mutex + seen []string + users []string + // state is the answer to a state GET. + state string + // searches answers each transcript search in turn, the last again and + // again. + searches []string +} + +func newSessionAPI(t *testing.T) *sessionAPI { + t.Helper() + api := &sessionAPI{t: t, state: noneState, searches: []string{`{"transcripts":[],"returned":0,"hasMore":false}`}} + srv := httptest.NewServer(http.HandlerFunc(api.serve)) + t.Cleanup(srv.Close) + api.url = srv.URL + return api +} + +var greeting = map[string]any{"needsRecompile": false, "traces": []any{ + map[string]any{"type": "text", "payload": map[string]any{"message": "Hi! How can I help?"}}, + map[string]any{"type": "choice", "payload": map[string]any{"buttons": []any{ + map[string]any{"name": "Book a table", "request": map[string]any{"type": "path-book", "payload": map[string]any{"label": "Book a table"}}}, + map[string]any{"name": "Hours", "request": map[string]any{"type": "path-hours", "payload": map[string]any{"label": "Hours"}}}, + }}}, + map[string]any{"type": "debug", "payload": map[string]any{"message": "tokens"}}, +}} + +func (api *sessionAPI) serve(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + w.Header().Set("Content-Type", "application/json") + user := "" + if _, rest, ok := strings.Cut(r.URL.Path, "/conversation-state/"); ok { + user, _, _ = strings.Cut(rest, "/") + } else if _, rest, ok := strings.Cut(r.URL.Path, "/conversation/"); ok { + user = rest + } + say := func(what string) { + api.mu.Lock() + api.seen = append(api.seen, what) + api.users = append(api.users, user) + api.mu.Unlock() + } + switch { + case strings.HasSuffix(r.URL.Path, "/compile"): + say("compile") + io.WriteString(w, `{"message":"Environment compiled","durationMs":5}`) + case strings.HasSuffix(r.URL.Path, "/variables"): + var req struct{ Variables json.RawMessage } + _ = json.Unmarshal(body, &req) + say("variables " + string(req.Variables)) + io.WriteString(w, `{"message":"Variables updated"}`) + case strings.Contains(r.URL.Path, "/conversation-state/") && r.Method == http.MethodDelete: + say("state delete") + io.WriteString(w, `{"message":"State deleted"}`) + case strings.Contains(r.URL.Path, "/conversation-state/"): + say("state get") + io.WriteString(w, api.state) + case strings.Contains(r.URL.Path, "/conversation/"): + var req struct { + Action struct { + Type string `json:"type"` + Payload json.RawMessage `json:"payload"` + } `json:"action"` + Version string `json:"version"` + } + _ = json.Unmarshal(body, &req) + switch typ := req.Action.Type; { + case typ == "launch": + say("launch" + strings.TrimPrefix(string(req.Action.Payload), "null")) + json.NewEncoder(w).Encode(greeting) + case typ == "text": + var text string + _ = json.Unmarshal(req.Action.Payload, &text) + say("text " + text) + io.WriteString(w, `{"needsRecompile":false,"traces":[{"type":"text","payload":{"message":"We're open 9 to 5."}}]}`) + case typ == "end": + say("end") + io.WriteString(w, `{"needsRecompile":false,"traces":[{"type":"end"}]}`) + default: + say(typ) + io.WriteString(w, `{"needsRecompile":false,"traces":[{"type":"text","payload":{"message":"Booked."}}]}`) + } + case strings.HasSuffix(r.URL.Path, "/transcript/search"): + say("search") + api.mu.Lock() + answer := api.searches[0] + if len(api.searches) > 1 { + api.searches = api.searches[1:] + } + api.mu.Unlock() + io.WriteString(w, answer) + default: + say(r.Method + " " + r.URL.Path) + io.WriteString(w, `{"message":"Agent updated."}`) + } +} + +// requests are the requests since the last call, in a few words each, and +// the user IDs they were for. +func (api *sessionAPI) requests() (seen, users []string) { + api.mu.Lock() + defer api.mu.Unlock() + seen, users = api.seen, api.users + api.seen, api.users = nil, nil + return seen, users +} + +// session runs `vf session …` in home, at -p p1 -e main. +func (api *sessionAPI) session(home string, agent bool, args ...string) (stdout, stderr string, err error) { + api.t.Helper() + return runInHome(api.t, home, api.url, agent, append(append([]string{"session"}, args...), "-p", "p1", "-e", "main")...) +} + +var sessionIDRE = regexp.MustCompile(`s-[a-z0-9]{8}`) + +func TestASessionStartsTalksAndEnds(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + + out, errOut, err := api.session(home, false, "start") + if err != nil { + t.Fatalf("start: %v\n%s%s", err, out, errOut) + } + seen, users := api.requests() + if got := strings.Join(seen, ", "); got != "compile, launch" { + t.Errorf("start sent %q, want a compile, then the launch", got) + } + id := sessionIDRE.FindString(out) + if id == "" || users[1] != id { + t.Fatalf("start named session %q, launched %q:\n%s", id, users, out) + } + for _, want := range []string{"Agent Hi! How can I help?", "[buttons: Book a table | Hours]", "Session " + id + " (the current one)"} { + if !strings.Contains(out, want) { + t.Errorf("start: missing %q:\n%s", want, out) + } + } + if !strings.Contains(errOut, "Next:") || !strings.Contains(errOut, `vf session send -p p1 -e main ""`) { + t.Errorf("start: no Next line to send:\n%s", errOut) + } + + out, errOut, err = api.session(home, false, "send", "What", "are", "your", "hours?") + if err != nil { + t.Fatalf("send: %v\n%s%s", err, out, errOut) + } + seen, users = api.requests() + if got := strings.Join(seen, ", "); got != "text What are your hours?" || users[0] != id { + t.Errorf("send sent %q as %v, want the message, with no compile, as %s", got, users, id) + } + if strings.TrimSpace(out) != "Agent We're open 9 to 5." { + t.Errorf("send printed:\n%s", out) + } + + api.searches = []string{`{"transcripts":[{"id":"t-1","sessionID":"` + id + `","createdAt":"` + time.Now().UTC().Format(time.RFC3339) + `","endedAt":null,"creatorURL":""}],"returned":1,"hasMore":false}`} + out, errOut, err = api.session(home, false, "end") + if err != nil { + t.Fatalf("end: %v\n%s%s", err, out, errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "end, search" { + t.Errorf("end sent %q", seen) + } + if !strings.Contains(out, "Ended session "+id+" | transcript t-1") || !strings.Contains(errOut, "vf evaluation run -e -t t-1 -p p1") { + t.Errorf("end printed:\n%s%s", out, errOut) + } + + // The session ended: nothing is current. + _, errOut, err = api.session(home, false, "get") + if code := output.ExitCode(err); code != output.ExitUsage || !strings.Contains(errOut, "No session is going in main") { + t.Errorf("get after end: exit %d\n%s", code, errOut) + } +} + +// Compile rule B: a session's turn compiles the draft first only after vf +// edited it. A start always compiles; a read never marks the draft. +func TestATurnCompilesOnlyAfterAnEdit(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + scope := []string{"-p", "p1", "-e", "main"} + step := func(name, want string, args ...string) { + t.Helper() + _, errOut, err := runInHome(t, home, api.url, false, append(args, scope...)...) + if err != nil { + t.Fatalf("%s: %v\n%s", name, err, errOut) + } + var turn []string + seen, _ := api.requests() + for _, s := range seen { + if s == "compile" || strings.HasPrefix(s, "text") || s == "launch" { + turn = append(turn, s) + } + } + if got := strings.Join(turn, ", "); got != want { + t.Errorf("%s: sent %q, want %q", name, got, want) + } + } + step("start", "compile, launch", "session", "start") + step("a turn", "text hi", "session", "send", "hi") + step("an edit", "", "agent", "update", "--instructions", "Be brief.") + step("the turn after it", "compile, text hi", "session", "send", "hi") + step("the next turn", "text hi", "session", "send", "hi") + step("another edit", "", "agent", "update", "--instructions", "Be briefer.") + step("vf environment compile", "compile", "environment", "compile") + step("a turn after the compile", "text hi", "session", "send", "hi") + step("a read", "", "agent", "get") + step("a turn after the read", "text hi", "session", "send", "hi") + step("conversation send after an edit", "", "agent", "update", "--instructions", "Be kind.") + step("conversation send", "compile, text hi", "conversation", "send", "-u", "u1", "--text", "hi") + step("--no-compile after an edit", "", "agent", "update", "--instructions", "Be kind.") + step("--no-compile", "text hi", "session", "send", "hi", "--no-compile") + step("a published session never compiles", "launch", "session", "start", "-v", "published") + step("after an edit either", "", "agent", "update", "--instructions", "Be kind.") + step("a published turn", "text hi", "session", "send", "hi") +} + +// A reused ID starts over clean: its conversation ended, its state deleted, +// the variables set, then the launch, in that order. An ID with no state +// has nothing to end or delete, and a generated one isn't looked up. +func TestStartWithAnIDUsedBefore(t *testing.T) { + for _, c := range []struct { + name, state string + args []string + want string + }{ + {"a conversation going", goingState, []string{"-s", "+15551234567"}, "compile, state get, end, state delete, variables {\"name\":\"Ana\",\"tier\":\"gold\",\"visits\":3}, launch"}, + {"variables left", `{"state":{"stack":[],"storage":{},"variables":{"tier":"silver"}}}`, []string{"-u", "+15551234567"}, "compile, state get, state delete, variables {\"name\":\"Ana\",\"tier\":\"gold\",\"visits\":3}, launch"}, + {"an ID the API hasn't met", noneState, []string{"-s", "+15551234567"}, "compile, state get, variables {\"name\":\"Ana\",\"tier\":\"gold\",\"visits\":3}, launch"}, + {"a new ID", goingState, nil, "compile, variables {\"name\":\"Ana\",\"tier\":\"gold\",\"visits\":3}, launch"}, + } { + t.Run(c.name, func(t *testing.T) { + api := newSessionAPI(t) + api.state = c.state + args := append([]string{"start", "--variables", `{"name":"Ana","tier":"silver"}`, "--var", "tier=gold", "--var", "visits=3"}, c.args...) + out, errOut, err := api.session(t.TempDir(), false, args...) + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + seen, users := api.requests() + if got := strings.Join(seen, ", "); got != c.want { + t.Errorf("sent %q\nwant %q", got, c.want) + } + if c.args != nil { + for i, u := range users[1:] { + if u != "+15551234567" && seen[i+1] != "compile" { + t.Errorf("%s went to %q", seen[i+1], u) + } + } + if !strings.Contains(out, "Session +15551234567 (the current one)") { + t.Errorf("printed:\n%s", out) + } + } + }) + } +} + +// A send with no session going starts one first, and says so. +func TestASendWithNoSessionStartsOne(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + out, errOut, err := api.session(home, false, "send", "hi") + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + seen, users := api.requests() + if got := strings.Join(seen, ", "); got != "compile, launch, text hi" || users[1] != users[2] { + t.Errorf("sent %q as %v", got, users) + } + id := sessionIDRE.FindString(out) + for _, want := range []string{"Started session " + id + " (the current one)", "Agent Hi! How can I help?", "You hi", "Agent We're open 9 to 5."} { + if id == "" || !strings.Contains(out, want) { + t.Errorf("missing %q:\n%s", want, out) + } + } + if s, ok := sessions.Current("p1", "main"); !ok || s.ID != id { + t.Errorf("current = %+v, want %s", s, id) + } + + // -o json: the turn's answer, with the session and the launch beside it. + home = t.TempDir() + out, _, err = api.session(home, false, "send", "hi", "-o", "json") + if err != nil { + t.Fatal(err) + } + var answer struct { + Session string + Launch struct{ Traces []any } + Traces []any + } + if err := json.Unmarshal([]byte(out), &answer); err != nil || !sessionIDRE.MatchString(answer.Session) || len(answer.Launch.Traces) != 3 || len(answer.Traces) != 1 { + t.Errorf("-o json: %v\n%s", err, out) + } +} + +// Scripts and agents read the session from the answer: -q .session is the +// bare ID, and agent mode's TOON says the session beside what was said. +func TestStartGivesTheSessionToScriptsAndAgents(t *testing.T) { + api := newSessionAPI(t) + out, errOut, err := api.session(t.TempDir(), false, "start", "-q", ".session") + if err != nil || !regexp.MustCompile(`^s-[a-z0-9]{8}\n$`).MatchString(out) || strings.Contains(errOut, "Next") { + t.Errorf("-q .session: %v %q %q", err, out, errOut) + } + out, _, err = api.session(t.TempDir(), true, "start") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"Hi! How can I help?", "session: s-", "version: draft", "projectID: p1", "environment: main", "tracesHidden"} { + if !strings.Contains(out, want) { + t.Errorf("agent mode: missing %q:\n%s", want, out) + } + } + out, _, _ = api.session(t.TempDir(), false, "start", "-o", "json", "--persona", "Ana") + if seen, _ := api.requests(); !strings.Contains(strings.Join(seen, ", "), `launch{"persona":"Ana"}`) { + t.Errorf("--persona: sent %q", seen) + } + if !strings.Contains(out, `"traces"`) || !strings.Contains(out, `"version":"draft"`) { + t.Errorf("-o json:\n%s", out) + } +} + +// --button presses a button the last reply offered, by its label: its own +// request goes out. A label it didn't offer sends nothing, and says which +// it did. +func TestAButtonIsPressedByItsLabel(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + if _, errOut, err := api.session(home, false, "start"); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + api.requests() + out, errOut, err := api.session(home, false, "send", "--button", "book a table") + if seen, _ := api.requests(); err != nil || strings.Join(seen, ", ") != "path-book" || !strings.Contains(out, "Booked.") { + t.Errorf("sent %q: %v\n%s%s", seen, err, out, errOut) + } + // The reply to that offered no buttons. + _, errOut, err = api.session(home, false, "send", "--button", "Hours") + if seen, _ := api.requests(); err == nil || len(seen) > 0 || !strings.Contains(errOut, "offered no button \"Hours\"") { + t.Errorf("a button not offered: sent %q, %v\n%s", seen, err, errOut) + } +} + +func TestUpdateSetsTheSessionsVariables(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + _, _, err := api.session(home, false, "update", "--var", "tier=gold") + if code := output.ExitCode(err); code != output.ExitUsage { + t.Errorf("update with no session: exit %d", code) + } + if _, errOut, err := api.session(home, false, "start"); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + api.requests() + out, errOut, err := api.session(home, false, "update", "--var", "tier=gold", "--var", "vip=true", "--var", "zip=02139x") + if seen, _ := api.requests(); err != nil || strings.Join(seen, ", ") != `variables {"tier":"gold","vip":true,"zip":"02139x"}` { + t.Errorf("sent %q: %v\n%s", seen, err, errOut) + } + if !regexp.MustCompile(`Updated tier, vip, zip in session s-[a-z0-9]{8}`).MatchString(out) { + t.Errorf("printed:\n%s", out) + } + _, errOut, err = api.session(home, false, "update") + if code := output.ExitCode(err); code != output.ExitUsage || !strings.Contains(errOut, "nothing to change") { + t.Errorf("update with no variable: exit %d\n%s", code, errOut) + } +} + +func TestGetShowsTheSessionAndItsVariables(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + api.state = `{"state":{"stack":[],"storage":{},"variables":{"tier":"gold","visits":3}}}` + out, errOut, err := api.session(home, false, "get", "-s", "s-other") + if err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + for _, want := range []string{"Session s-other", "Version draft", "tier gold", "visits 3"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q:\n%s", want, out) + } + } + out, _, _ = api.session(home, false, "get", "-u", "s-other", "-q", ".state.variables.tier") + if out != "gold\n" { + t.Errorf("-q: %q", out) + } +} + +// end looks for the transcript again while the API doesn't have it yet, +// and takes the newest the session made since it started: a reused ID has +// older ones. +func TestEndFindsTheSessionsTranscript(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + if _, errOut, err := api.session(home, false, "start", "-s", "s-reused"); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + api.requests() + now := time.Now().UTC() + old := `{"id":"t-old","sessionID":"s-reused","createdAt":"` + now.Add(-time.Hour).Format(time.RFC3339) + `","endedAt":null,"creatorURL":""}` + fresh := `{"id":"t-new","sessionID":"s-reused","createdAt":"` + now.Format(time.RFC3339) + `","endedAt":null,"creatorURL":""}` + api.searches = []string{ + `{"transcripts":[` + old + `],"returned":1,"hasMore":false}`, + `{"transcripts":[` + fresh + `,` + old + `],"returned":2,"hasMore":false}`, + } + out, errOut, err := api.session(home, true, "end", "-o", "json") + if err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "end, search, search" { + t.Errorf("sent %q", seen) + } + var result struct { + Session string + Ended bool + TranscriptID *string + } + if err := json.Unmarshal([]byte(out), &result); err != nil || result.Session != "s-reused" || !result.Ended || result.TranscriptID == nil || *result.TranscriptID != "t-new" { + t.Errorf("%v\n%s", err, out) + } +} + +// Every Next line a session command prints runs as written. +func TestEverySessionNextLineRuns(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + tree := testRoot(t) + _, startErr, _ := api.session(home, false, "start") + api.searches = []string{`{"transcripts":[{"id":"t-1","sessionID":"x","createdAt":"2026-12-01T00:00:00Z","endedAt":null,"creatorURL":""}],"returned":1,"hasMore":false}`} + _, endErr, _ := api.session(home, false, "end", "-s", "x") + _, noneErr, _ := api.session(t.TempDir(), false, "get") + _, buttonErr, _ := api.session(home, false, "send", "--button", "Nope") + checked := 0 + for _, text := range []string{startErr, endErr, noneErr, buttonErr} { + for _, line := range append(quotedCommands(text), nextLines(text)...) { + checked++ + for _, problem := range cmdcheck.Check(tree, line, cmdcheck.Options{Keep: []string{"project-id"}, Complete: true}) { + t.Errorf("`%s` %s", line, problem) + } + } + } + if checked < 5 { + t.Errorf("checked only %d lines:\n%s\n%s\n%s\n%s", checked, startErr, endErr, noneErr, buttonErr) + } +} + +// nextLines are the commands under a "Next:" line in text, each without +// what it does. +func nextLines(text string) []string { + var lines []string + _, block, ok := strings.Cut(text, "Next:\n") + if !ok { + return nil + } + for _, row := range strings.Split(block, "\n") { + row = strings.TrimSpace(row) + if !strings.HasPrefix(row, "vf ") { + break + } + command, _, _ := strings.Cut(row, " ") + lines = append(lines, command) + } + return lines +} + +// quotedCommands are the commands an error's steps lead with, as plain +// output prints them: in 'single quotes'. +func quotedCommands(text string) []string { + var lines []string + for _, m := range regexp.MustCompile(`(?m)^\s*(?:- )?'(vf [^']*)'`).FindAllStringSubmatch(text, -1) { + lines = append(lines, m[1]) + } + return lines +} diff --git a/internal/cli/strayargs_test.go b/internal/cli/strayargs_test.go index e4512248..6e40cae4 100644 --- a/internal/cli/strayargs_test.go +++ b/internal/cli/strayargs_test.go @@ -18,8 +18,9 @@ import ( // ownArgs are the commands that declare their arguments themselves. var ownArgs = map[string]bool{ - "vf docs search": true, // - "vf docs get": true, // + "vf docs search": true, // + "vf docs get": true, // + "vf session send": true, // } // Every command that takes no arguments rejects a stray word, rather than diff --git a/internal/output/exitcode.go b/internal/output/exitcode.go index 61df571a..5b84fc06 100644 --- a/internal/output/exitcode.go +++ b/internal/output/exitcode.go @@ -55,7 +55,7 @@ var ExitCodesHelp = strings.Join([]string{ func ExitCodeFor(errorType string, status int) int { switch errorType { case "missing_flag", "unknown_flag", "unknown_command", "invalid_flag_value", - "invalid_body", "usage_error", "stdin_empty", "stdin_timeout", "nothing_to_update": + "invalid_body", "usage_error", "stdin_empty", "stdin_timeout", "nothing_to_update", "no_session": return ExitUsage case "authentication_error", "auth_session_ended", "auth_session_renew_failed", "auth_login_failed", "auth_signup_failed", "auth_login_interactive": From b1c91e3671d6d3a56ba3fcbb66a883cdc32843ed Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:03:49 -0500 Subject: [PATCH 03/15] feat(session): vf session run-script, which records its session and can --end it Why: a script is the quickest way to put an agent through a conversation to evaluate, and it lived apart from the session commands: its user ID went unremembered, so going on from its last turn meant copying the ID, and evaluating it meant an end action in JSON and a transcript search. Design: run-script moves into the session group as it was, same flags and output, and compiles the draft first as start does. -s names the session beside -u. After the script its session becomes the current one, so `vf session send` goes on from the last turn. --end ends it after the script and gives the transcript: the one the script's answer names, or else the one end's search finds. `vf conversation run-script` is left as it was. Change: conversation/sessionscript.go registers run-script under session and adds -s and --end; runscript.go gets two one-line hooks; end's tail is shared (endSession, sayEnded) between end and run-script --end. Tests: sessionscript_test.go. --- internal/cli/conversation/autocompile.go | 3 +- internal/cli/conversation/runscript.go | 6 +- internal/cli/conversation/session.go | 1 + internal/cli/conversation/sessionend.go | 69 ++++++++--- internal/cli/conversation/sessionscript.go | 131 +++++++++++++++++++++ internal/cli/session_test.go | 15 +++ internal/cli/sessionscript_test.go | 89 ++++++++++++++ 7 files changed, 292 insertions(+), 22 deletions(-) create mode 100644 internal/cli/conversation/sessionscript.go create mode 100644 internal/cli/sessionscript_test.go diff --git a/internal/cli/conversation/autocompile.go b/internal/cli/conversation/autocompile.go index 347e2187..357b97cd 100644 --- a/internal/cli/conversation/autocompile.go +++ b/internal/cli/conversation/autocompile.go @@ -106,6 +106,7 @@ type turnWait struct { ctx context.Context sent func() bool // the turn's request has started going out (canceled.go) compiled time.Duration // how long the compile took; 0 for none + began time.Time // when the wait began, before any compile: a transcript the turn makes is no older stopOnce sync.Once } @@ -144,7 +145,7 @@ func startTurn(cmd *cobra.Command, s *sdk.VoiceflowSDK, compiles bool, projectID message, hint = compilingMessage, compilingHint } quiet := client.WithoutSpinner(cmd.Context()) - w := &turnWait{cmd: cmd, line: spinLine(cmd, message, hint)} + w := &turnWait{cmd: cmd, line: spinLine(cmd, message, hint), began: time.Now()} w.ctx, w.sent = tracingSent(quiet) // canceled.go: a Ctrl-C says whether the turn went out if !compiles { return w, nil diff --git a/internal/cli/conversation/runscript.go b/internal/cli/conversation/runscript.go index 0cfaec10..b987e390 100644 --- a/internal/cli/conversation/runscript.go +++ b/internal/cli/conversation/runscript.go @@ -50,6 +50,7 @@ func runRunScriptCmd(cmd *cobra.Command, args []string) error { if usage.UsageRequested(cmd) { return usage.EmitSchema(cmd, cmd.OutOrStdout()) } + sessionAsUserID(cmd) // sessionscript.go: -s names the session, as --user-id does if interactive.ShouldPrompt(cmd, runScriptCmdMeta) { if err := interactive.PromptAndSetFlags(cmd, runScriptCmdMeta); err != nil { return err @@ -88,8 +89,5 @@ func runRunScriptCmd(cmd *cobra.Command, args []string) error { return scriptFailed(cmd, wait, req, err) // canceled.go: a Ctrl-C says whether the script went out } - if err := output.Result(cmd, res); err != nil { - return err - } - return nil + return scriptDone(cmd, s, wait, req, res) // sessionscript.go: in vf session, the script becomes the current session, and --end ends it } diff --git a/internal/cli/conversation/session.go b/internal/cli/conversation/session.go index 54ecc03e..0ed6e7dc 100644 --- a/internal/cli/conversation/session.go +++ b/internal/cli/conversation/session.go @@ -90,6 +90,7 @@ func addSessionGroup(parent *cobra.Command) { addSessionUpdate(group) // sessionstate.go addSessionGet(group) // sessionstate.go addSessionEnd(group) // sessionend.go + addSessionScript(group) // sessionscript.go parent.AddCommand(group) } diff --git a/internal/cli/conversation/sessionend.go b/internal/cli/conversation/sessionend.go index 73455f74..3800cfcc 100644 --- a/internal/cli/conversation/sessionend.go +++ b/internal/cli/conversation/sessionend.go @@ -67,41 +67,76 @@ func runSessionEnd(cmd *cobra.Command, args []string) error { if err != nil { return err } - req := sendRequest(scope, rec.ID, rec.Version, endAction("Ended with vf session end")) - res, err := s.Conversation.Send(client.WithSpinnerMessage(cmd.Context(), "Ending the session…"), *req, rawAnswer(opts)...) + res, transcript, err := endSession(cmd, s, opts, scope, rec, "Ended with vf session end", "") if err != nil { - return output.Error(cmd, err) + return err } if client.IsDryRun(cmd) { return output.Result(cmd, res) } + if !output.ForAPerson(cmd) { + result := map[string]any{"session": rec.ID} + ended(result, transcript) + return output.Result(cmd, result) + } + sayEnded(cmd, scope, rec.ID, transcript) + return nil +} + +// endSession sends session rec's end action, forgets it as the current +// session, and finds its transcript, unless known names it already. The +// transcript is "" when the API has none yet. A dry run only shows the +// end action. +func endSession(cmd *cobra.Command, s *sdk.VoiceflowSDK, opts []operations.Option, scope sessionScope, rec sessions.Session, reason, known string) (*operations.StableConversationControllerSendResponse, string, error) { + req := sendRequest(scope, rec.ID, rec.Version, endAction(reason)) + res, err := s.Conversation.Send(client.WithSpinnerMessage(cmd.Context(), "Ending the session…"), *req, rawAnswer(opts)...) + if err != nil { + return nil, "", output.Error(cmd, err) + } + if client.IsDryRun(cmd) { + return res, "", nil + } _ = sessions.End(scope.ProjectID, scope.EnvironmentAlias, rec.ID) + if known != "" { + return res, known, nil + } found, err := FindTranscript(client.WithSpinnerMessage(cmd.Context(), "Finding its transcript…"), s, opts, scope.ProjectID, scope.EnvironmentAlias, rec.ID, rec.StartedAt) if err != nil { - return output.Error(cmd, err) + return nil, "", output.Error(cmd, err) + } + if found == nil { + return res, "", nil } - result := map[string]any{"session": rec.ID, "ended": true, "transcriptID": nil} - if found != nil { - result["transcriptID"] = found.ID + return res, found.ID, nil +} + +// ended says in result that the session ended, and its transcript: its ID, +// or null and why. +func ended(result map[string]any, transcript string) { + result["ended"] = true + result["transcriptID"] = nil + if transcript != "" { + result["transcriptID"] = transcript } else { result["reason"] = notFoundYet } - if !output.ForAPerson(cmd) { - return output.Result(cmd, result) - } +} + +// sayEnded tells a person session id ended, and gives its transcript with +// the evaluation to run on it. +func sayEnded(cmd *cobra.Command, scope sessionScope, id, transcript string) { out := cmd.OutOrStdout() u := output.UI(cmd, out) - if found == nil { - fmt.Fprintln(out, u.Status(ui.StatusDone, "Ended session "+rec.ID)) - warn(cmd, notFoundYet+" `"+transcriptSearch(scope, rec.ID)+"` lists it once it is.") - return nil + if transcript == "" { + fmt.Fprintln(out, u.Status(ui.StatusDone, "Ended session "+id)) + warn(cmd, notFoundYet+" '"+transcriptSearch(scope, id)+"' lists it once it is.") + return } - fmt.Fprintln(out, u.Status(ui.StatusDone, "Ended session "+rec.ID+" "+u.Glyph(ui.Separator)+" transcript "+found.ID)) + fmt.Fprintln(out, u.Status(ui.StatusDone, "Ended session "+id+" "+u.Glyph(ui.Separator)+" transcript "+transcript)) writeNext(cmd, ui.Tip{ - Command: "vf evaluation run -e -t " + found.ID + session.Scope(scope.ProjectID, ""), + Command: "vf evaluation run -e -t " + transcript + session.Scope(scope.ProjectID, ""), Does: "Run an evaluation on it", }) - return nil } // notFoundYet says the transcript wasn't there when vf looked. diff --git a/internal/cli/conversation/sessionscript.go b/internal/cli/conversation/sessionscript.go new file mode 100644 index 00000000..b4c8f756 --- /dev/null +++ b/internal/cli/conversation/sessionscript.go @@ -0,0 +1,131 @@ +// This file is not generated by Speakeasy. It is `vf session run-script`: +// `conversation run-script`, in the session group, as a session. +// +// It runs as run-script always has: the same flags and output, the draft +// compiled first (autocompile.go). As a session, -s names its ID beside +// -u, the script's session becomes the current one, so `vf session send` +// goes on from its last turn, and --end ends it after the script and finds +// its transcript, as `vf session end` does: a script run to evaluate needs +// no second command. `conversation run-script` is left as it was. + +package conversation + +import ( + "encoding/json" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/ui" +) + +const endFlag = "end" + +const scriptLong = `Run a list of user messages as one new conversation, and make it the current session. + +With the draft, vf compiles it first, so the script runs your latest edits. 'vf session send' goes on from the script's last turn; --end ends the session after the script instead, and finds its transcript, for 'vf evaluation run'.` + +const scriptExample = ` vf session run-script -p -e --messages '["What are your hours?","Book a table for two"]' + vf session run-script -p -e --messages '["Hi","Cancel my order"]' --end` + +// addSessionScript adds run-script to the session group: conversation's, +// with -s for the session and --end. +func addSessionScript(group *cobra.Command) { + // Its metadata was checked when conversation's run-script was + // registered, before this one. + _ = initRunScriptCmd(group) // runscript.go + for _, cmd := range group.Commands() { + if cmd.Name() != "run-script" { + continue + } + cmd.Short = "Run a list of messages as a fresh session" + cmd.Long = scriptLong + cmd.Example = scriptExample + cmd.Flags().StringP(sessionFlag, "s", "", "The session ID to run as: another name for --user-id. Leave both out for a new one.") + cmd.Flags().Bool(endFlag, false, "End the session after the script, and find its transcript, as 'vf session end' does.") + } +} + +// sessionAsUserID has -s name the user the script runs as, as -u does. +func sessionAsUserID(cmd *cobra.Command) { + if id, _ := cmd.Flags().GetString(sessionFlag); id != "" && flagutil.FlagChanged(cmd, sessionFlag) { + _ = cmd.Flags().Set("user-id", id) + } +} + +// scriptDone prints a script's answer. In the session group it also makes +// the script's session the current one and, with --end, ends it and finds +// its transcript. +func scriptDone(cmd *cobra.Command, s *sdk.VoiceflowSDK, wait *turnWait, req *operations.StableConversationControllerRunScriptRequest, res *operations.StableConversationControllerRunScriptResponse) error { + if cmd.Parent() == nil || cmd.Parent().Name() != "session" || client.IsDryRun(cmd) || res == nil { + return output.Result(cmd, res) + } + answer := scriptAnswer(res) + id, _ := answer["userID"].(string) + if id == "" { + return output.Result(cmd, res) + } + scope := sessionScope{ProjectID: req.ProjectID, EnvironmentAlias: req.EnvironmentAlias, Version: "draft"} + if req.Body.Version != nil { + scope.Version = string(*req.Body.Version) + } + rec := sessions.Session{ID: id, Version: scope.Version, StartedAt: wait.began} + if err := sessions.Start(scope.ProjectID, scope.EnvironmentAlias, rec); err != nil { + warn(cmd, "vf couldn't remember the session ("+err.Error()+"): name it with -s "+id+" on each command.") + } + end, _ := cmd.Flags().GetBool(endFlag) + if !end { + if err := output.Result(cmd, res); err != nil || !output.ForAPerson(cmd) { + return err + } + sayCurrent(cmd, "Session", id) + writeNext(cmd, + ui.Tip{Command: sessionCommand("send", scope, "") + ` ""`, Does: "Go on from the script's last turn"}, + ui.Tip{Command: sessionCommand("end", scope, ""), Does: "End it, and find its transcript"}, + ) + return nil + } + opts, err := output.PrepareCallOpts(cmd) + if err != nil { + return err + } + known, _ := answer["transcriptID"].(string) + _, transcript, err := endSession(cmd, s, opts, scope, rec, "Ended with vf session run-script --end", known) + if err != nil { + return err + } + if !output.ForAPerson(cmd) { + answer["session"] = id + ended(answer, transcript) + return output.Result(cmd, answer) + } + if typed := res.StableConversationScriptResponse; typed != nil && transcript != "" { + typed.TranscriptID = &transcript + } + if err := output.Result(cmd, res); err != nil { + return err + } + sayEnded(cmd, scope, id, transcript) + return nil +} + +// scriptAnswer is a script's answer as JSON values. +func scriptAnswer(res *operations.StableConversationControllerRunScriptResponse) map[string]any { + var answer map[string]any + if typed := res.StableConversationScriptResponse; typed != nil { + if raw, err := json.Marshal(typed); err == nil { + _ = json.Unmarshal(raw, &answer) + } + } else { + output.PeekJSON(res.HTTPMeta.Response, &answer) + } + if answer == nil { + answer = map[string]any{} + } + return answer +} diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index e047a16f..bad3d4d1 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -34,6 +34,9 @@ type sessionAPI struct { // searches answers each transcript search in turn, the last again and // again. searches []string + // scriptTranscript is the transcript ID a script's answer gives: nil + // when the runtime reported none. + scriptTranscript any } func newSessionAPI(t *testing.T) *sessionAPI { @@ -84,6 +87,18 @@ func (api *sessionAPI) serve(w http.ResponseWriter, r *http.Request) { case strings.Contains(r.URL.Path, "/conversation-state/"): say("state get") io.WriteString(w, api.state) + case strings.HasSuffix(r.URL.Path, "/conversation/script"): + var req struct{ UserID string } + _ = json.Unmarshal(body, &req) + if user = req.UserID; user == "" { + user = "u-api" // the API picks one + } + say("script") + api.mu.Lock() + transcript := api.scriptTranscript + api.mu.Unlock() + json.NewEncoder(w).Encode(map[string]any{"userID": user, "transcriptID": transcript, "needsRecompile": false, "notSent": []any{}, + "turns": []any{map[string]any{"user": "hi", "agent": []any{"We're open 9 to 5."}}}}) case strings.Contains(r.URL.Path, "/conversation/"): var req struct { Action struct { diff --git a/internal/cli/sessionscript_test.go b/internal/cli/sessionscript_test.go new file mode 100644 index 00000000..215c67bf --- /dev/null +++ b/internal/cli/sessionscript_test.go @@ -0,0 +1,89 @@ +// This file is not generated by Speakeasy. It covers +// conversation/sessionscript.go: `vf session run-script` runs as +// conversation's does, then makes the script's session the current one, +// and --end ends it and gives its transcript. The fake API is +// session_test.go's. + +package cli + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/voiceflow/cli/internal/sessions" +) + +func TestAScriptBecomesTheCurrentSession(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + out, errOut, err := api.session(home, false, "run-script", "-m", `["hi"]`) + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "compile, script" { + t.Errorf("sent %q", seen) + } + if !strings.Contains(out, "We're open 9 to 5.") || !strings.Contains(out, "Session u-api (the current one)") || !strings.Contains(errOut, "vf session send -p p1 -e main") { + t.Errorf("printed:\n%s%s", out, errOut) + } + if _, _, err := api.session(home, false, "send", "hello"); err != nil { + t.Fatal(err) + } + if seen, users := api.requests(); strings.Join(seen, ", ") != "text hello" || users[0] != "u-api" { + t.Errorf("send after the script sent %q as %v", seen, users) + } + + // -s names the session, as -u does. + if _, errOut, err := api.session(home, false, "run-script", "-m", `["hi"]`, "-s", "+15551234567"); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + if _, users := api.requests(); len(users) < 2 || users[1] != "+15551234567" { + t.Errorf("-s ran as %v", users) + } + + // conversation run-script is as it was: no session to remember. + home = t.TempDir() + if _, errOut, err := runInHome(t, home, api.url, false, "conversation", "run-script", "-m", `["hi"]`, "-p", "p1", "-e", "main"); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + if _, ok := sessions.Current("p1", "main"); ok { + t.Error("conversation run-script made a session current") + } +} + +// --end gives the transcript the script's answer named, or else the one a +// search finds. +func TestAScriptWithEndGivesItsTranscript(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + api.searches = []string{`{"transcripts":[{"id":"t-found","sessionID":"u-api","createdAt":"` + time.Now().UTC().Format(time.RFC3339) + `","endedAt":null,"creatorURL":""}],"returned":1,"hasMore":false}`} + out, errOut, err := api.session(home, false, "run-script", "-m", `["hi"]`, "--end") + if err != nil { + t.Fatalf("%v\n%s%s", err, out, errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "compile, script, end, search" { + t.Errorf("sent %q", seen) + } + if !strings.Contains(out, "Ended session u-api | transcript t-found") || !strings.Contains(errOut, "vf evaluation run -e -t t-found -p p1") { + t.Errorf("printed:\n%s%s", out, errOut) + } + if _, ok := sessions.Current("p1", "main"); ok { + t.Error("an ended script is still the current session") + } + + api.scriptTranscript = "t-named" + out, _, err = api.session(home, false, "run-script", "-m", `["hi"]`, "--end", "-o", "json") + if seen, _ := api.requests(); err != nil || strings.Join(seen, ", ") != "compile, script, end" { + t.Errorf("sent %q: %v", seen, err) + } + var answer struct { + Session, TranscriptID string + Ended bool + Turns []any + } + if err := json.Unmarshal([]byte(out), &answer); err != nil || answer.Session != "u-api" || answer.TranscriptID != "t-named" || !answer.Ended || len(answer.Turns) != 1 { + t.Errorf("%v\n%s", err, out) + } +} From 4d634480d6266f2e3d5a25e458a1cb70661c395c Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:10:23 -0500 Subject: [PATCH 04/15] feat(session): list vf session where vf conversation was, and keep conversation running Why: with both groups listed, a newcomer met two ways to talk to the agent and picked the one that needs a user ID, a version and JSON on every turn. The session group does what conversation did. Design: conversation is hidden from 'vf --help', the home menu and the --usage listing, and its help, and its send, run-script and state commands' help, say which session command does the same. Its commands still run as they did, for the scripts that use them, and the home prompt still offers a hidden command's flags once it is typed in full. --usage lists the session group. Change: retireConversation in conversation/session.go, called from the existing hook line; prompt/complete.go findChild resolves a hidden command typed in full. Tests: sessionhide_test.go; the -y count in --usage and the misspelt-group mistake leave out the hidden group. --- internal/cli/confirm_test.go | 7 +++- internal/cli/conversation/root.go | 2 +- internal/cli/conversation/session.go | 28 ++++++++++++- internal/cli/sessionhide_test.go | 60 ++++++++++++++++++++++++++++ internal/cli/suggested_test.go | 3 +- internal/prompt/complete.go | 6 ++- 6 files changed, 98 insertions(+), 8 deletions(-) create mode 100644 internal/cli/sessionhide_test.go diff --git a/internal/cli/confirm_test.go b/internal/cli/confirm_test.go index 835cad57..aae4d153 100644 --- a/internal/cli/confirm_test.go +++ b/internal/cli/confirm_test.go @@ -222,8 +222,11 @@ func TestUsageListsYes(t *testing.T) { if err != nil { t.Fatal(err) } - if n := strings.Count(out, `flag "-y --yes" help="`+yesHelp+`"`); n != len(deletes(t)) { - t.Errorf("vf --usage should list -y/--yes under every delete, found %d", n) + listed := slices.DeleteFunc(deletes(t), func(c *cobra.Command) bool { + return strings.HasPrefix(c.CommandPath(), "vf conversation ") // hidden: vf session replaces it + }) + if n := strings.Count(out, `flag "-y --yes" help="`+yesHelp+`"`); n != len(listed) { + t.Errorf("vf --usage should list -y/--yes under every delete it lists (%d), found %d", len(listed), n) } if !strings.Contains(out, `flag "-y --yes" help="`+mergeYesHelp+`"`) { t.Errorf("vf --usage should list -y/--yes under environment merge") diff --git a/internal/cli/conversation/root.go b/internal/cli/conversation/root.go index 257e7753..afaebe1c 100644 --- a/internal/cli/conversation/root.go +++ b/internal/cli/conversation/root.go @@ -34,7 +34,7 @@ func InitConversationRoot(parent *cobra.Command) error { return err } - addSessionGroup(parent) // session.go: vf session, a conversation at a time + addSessionGroup(parent, ConversationCmd) // session.go: vf session, a conversation at a time; vf conversation, hidden, still runs parent.AddCommand(ConversationCmd) return nil } diff --git a/internal/cli/conversation/session.go b/internal/cli/conversation/session.go index 0ed6e7dc..fef3971c 100644 --- a/internal/cli/conversation/session.go +++ b/internal/cli/conversation/session.go @@ -72,8 +72,10 @@ type sessionScope struct { Version string } -// addSessionGroup adds `vf session` under parent. -func addSessionGroup(parent *cobra.Command) { +// addSessionGroup adds `vf session` under parent, and retires +// conversation, the group it takes over from. +func addSessionGroup(parent, conversation *cobra.Command) { + retireConversation(conversation) group := &cobra.Command{ Use: "session", Short: "Start a session with the agent, send turns, end it", @@ -94,6 +96,28 @@ func addSessionGroup(parent *cobra.Command) { parent.AddCommand(group) } +// retireConversation hides `vf conversation` from 'vf --help', the home +// menu and --usage: `vf session` does what it did, without a user ID and a +// version on every turn. Its commands still run as they did, for the +// scripts that use them, and their help says what to use instead. +func retireConversation(conversation *cobra.Command) { + conversation.Hidden = true + conversation.Short = "Talk to an agent with a user ID on every turn; 'vf session' replaces it" + conversation.Long = "Talk to an agent, giving the user ID and the version on every turn. " + + "'vf session' does this a conversation at a time and remembers the session for you: " + + "'vf session start', 'vf session send', 'vf session end'. These commands still run as they did." + instead := map[string]string{ + "send": "'vf session send' does this in the current session, with no user ID to give: 'vf session send What are your hours?'", + "run-script": "'vf session run-script' runs it as a session that 'vf session send' can go on from, and --end ends it and gives its transcript.", + "state": "'vf session get' and 'vf session update' read and set the current session's variables.", + } + for _, cmd := range conversation.Commands() { + if s, ok := instead[cmd.Name()]; ok { + cmd.Long += "\n\n" + s + } + } +} + // addSessionFlags gives cmd the scope's flags, meta, and -s, with -u as its // other name. func addSessionFlags(cmd *cobra.Command, meta []flagutil.FlagMeta, sessionHelp string) { diff --git a/internal/cli/sessionhide_test.go b/internal/cli/sessionhide_test.go new file mode 100644 index 00000000..6d1c271b --- /dev/null +++ b/internal/cli/sessionhide_test.go @@ -0,0 +1,60 @@ +// This file is not generated by Speakeasy. It covers retireConversation +// (conversation/session.go): `vf session` is listed where `vf conversation` +// was, and conversation, hidden, still runs and says what replaced it. + +package cli + +import ( + "regexp" + "strings" + "testing" + + "github.com/voiceflow/cli/internal/prompt" +) + +func TestSessionIsListedWhereConversationWas(t *testing.T) { + url := newSessionAPI(t).url + home := t.TempDir() + help, _, err := runInHome(t, home, url, false, "--help") + if err != nil { + t.Fatal(err) + } + listed := regexp.MustCompile(`(?m)^\s+(\S+)\s`) + names := map[string]bool{} + for _, m := range listed.FindAllStringSubmatch(help, -1) { + names[m[1]] = true + } + if !names["session"] || names["conversation"] { + t.Errorf("vf --help: session listed %v, conversation listed %v:\n%s", names["session"], names["conversation"], help) + } + + usage, _, err := runInHome(t, home, url, false, "--usage") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(usage, `cmd "session" help=`) || strings.Contains(usage, `cmd "conversation" help=`) { + t.Error("vf --usage should list session, and not conversation") + } + + root, err := NewRootCommand() + if err != nil { + t.Fatal(err) + } + var menu []string + for _, s := range prompt.Commands(root, nil)("") { + menu = append(menu, s.Label) + } + if got := strings.Join(menu, " "); !strings.Contains(" "+got+" ", " session ") || strings.Contains(" "+got+" ", " conversation ") { + t.Errorf("the home menu: %s", got) + } + + // Hidden, it still runs, and its help says what replaced it. + out, _, err := runInHome(t, home, url, false, "conversation", "send", "--help") + if err != nil || !strings.Contains(strings.Join(strings.Fields(out), " "), "'vf session send' does this in the current session") { + t.Errorf("conversation send --help: %v\n%s", err, out) + } + out, _, err = runInHome(t, home, url, false, "conversation", "--help") + if err != nil || !strings.Contains(out, "'vf session' does this a conversation at a time") { + t.Errorf("conversation --help: %v\n%s", err, out) + } +} diff --git a/internal/cli/suggested_test.go b/internal/cli/suggested_test.go index f378bdd3..030296fa 100644 --- a/internal/cli/suggested_test.go +++ b/internal/cli/suggested_test.go @@ -239,7 +239,8 @@ func mistakesFor(c *cobra.Command, csv, server string) []mistake { ms = append(ms, mistake{"an unquoted message", line(path, args(rest), []string{"--text", "Hello", "there"}, global), append(names(rest), "text"), true}) } ms = append(ms, mistake{"a misspelt command", line(path[:len(path)-1], []string{misspell(c.Parent(), path[len(path)-1])}, args(all), global), names(all), true}) - if len(path) > 1 { + // A hidden group, such as conversation, isn't one vf offers for a typo. + if group, _, err := c.Root().Find(path[:1]); len(path) > 1 && err == nil && !group.Hidden { ms = append(ms, mistake{"a misspelt group", line([]string{misspell(c.Root(), path[0])}, path[1:], args(all), global), names(all), true}) } if len(all) > 0 && len(all[0].name) > 3 { diff --git a/internal/prompt/complete.go b/internal/prompt/complete.go index b44f5cdc..8a2e1a8d 100644 --- a/internal/prompt/complete.go +++ b/internal/prompt/complete.go @@ -370,8 +370,10 @@ func lookupFlag(cmd *cobra.Command, raw, name string) *pflag.Flag { } func findChild(cmd *cobra.Command, name string) *cobra.Command { - for _, c := range visibleChildren(cmd) { - if c.Name() == name || c.HasAlias(name) { + for _, c := range cmd.Commands() { + // A hidden command the menu doesn't offer, such as `conversation`, + // still runs, so typed in full its flags are offered. + if (c.Name() == name || c.HasAlias(name)) && !hiddenFromMenu[c.Name()] { return c } } From 10f21bc8338f2305e4128618a51dd1705c4f6608 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:22:55 -0500 Subject: [PATCH 05/15] feat(session): vf evaluation run --session, and transcript search --session Why: to score a session, you needed its transcript ID: from 'vf session end', or from a transcript search by a session ID nobody had said was the user ID (round 7: agent-migrator F2). An evaluation on a conversation still open said to send an end action in JSON with 'vf conversation send'. 'vf transcript search --session' failed as an unknown flag. Design: evaluation run --session (-s) finds the transcript as 'vf session end' does: the newest with that session ID created since vf started the session, or the newest of all for a session vf didn't start. -t still works; both is a usage error. No transcript is not_found (exit 4), with the search that lists the session's. A dry run doesn't search; its -t says whose transcript it would be. transcript_not_ended's step is now 'vf session end -s -p -e ', with -v published for a published transcript, so session end takes -v as session get does. transcript search takes --session as another name for --session-id. Change: evaluation/session.go (one hook line in run.go), notended.go's help and step; transcript/session.go (one hook line in search.go); session end takes versionMeta; TranscriptWait/TranscriptPoll exported so tests shorten them; session end's hint uses --session. Tests: evalsession_test.go, evalnotended_test.go, session_test.go. --- internal/cli/conversation/sessionend.go | 19 +- internal/cli/conversation/sessionend_test.go | 6 +- internal/cli/conversation/sessionstate.go | 10 +- internal/cli/evalnotended_test.go | 14 +- internal/cli/evalsession_test.go | 180 +++++++++++++++++++ internal/cli/evaluation/notended.go | 44 +++-- internal/cli/evaluation/run.go | 1 + internal/cli/evaluation/session.go | 125 +++++++++++++ internal/cli/session_test.go | 41 +++++ internal/cli/transcript/search.go | 1 + internal/cli/transcript/session.go | 31 ++++ 11 files changed, 426 insertions(+), 46 deletions(-) create mode 100644 internal/cli/evalsession_test.go create mode 100644 internal/cli/evaluation/session.go create mode 100644 internal/cli/transcript/session.go diff --git a/internal/cli/conversation/sessionend.go b/internal/cli/conversation/sessionend.go index 3800cfcc..b1f11b6b 100644 --- a/internal/cli/conversation/sessionend.go +++ b/internal/cli/conversation/sessionend.go @@ -31,9 +31,9 @@ import ( "github.com/voiceflow/cli/internal/usage" ) -// transcriptWait is how long vf looks for a session's transcript, and -// transcriptPoll how long it waits between looks. -var transcriptWait, transcriptPoll = 5 * time.Second, 500 * time.Millisecond +// TranscriptWait is how long vf looks for a session's transcript, and +// TranscriptPoll how long it waits between looks. Tests shorten them. +var TranscriptWait, TranscriptPoll = 5 * time.Second, 500 * time.Millisecond // clockSlack is how much earlier than the session's recorded start its // transcript may say it began: this computer's clock and the API's differ. @@ -47,7 +47,7 @@ func addSessionEnd(parent *cobra.Command) { Example: " vf session end -p -e ", RunE: runSessionEnd, } - addSessionFlags(cmd, sessionScopeMeta, sessionHelp) + addSessionFlags(cmd, versionMeta, sessionHelp) parent.AddCommand(cmd) } @@ -55,7 +55,7 @@ func runSessionEnd(cmd *cobra.Command, args []string) error { if usage.UsageRequested(cmd) { return usage.EmitSchema(cmd, cmd.OutOrStdout()) } - scope, err := scopeOf(cmd, sessionScopeMeta) + scope, err := scopeOf(cmd, versionMeta) if err != nil { return err } @@ -63,6 +63,9 @@ func runSessionEnd(cmd *cobra.Command, args []string) error { if !ok { return noSession(cmd, scope) } + if scope.Version != "" { + rec.Version = scope.Version + } s, opts, err := sdkFor(cmd) if err != nil { return err @@ -144,7 +147,7 @@ const notFoundYet = "The API had no transcript for the session yet." // transcriptSearch is the command that lists session id's transcripts. func transcriptSearch(scope sessionScope, id string) string { - return "vf transcript search --session-id " + shellWord(id) + session.Scope(scope.ProjectID, "") + " --environment-alias " + shellWord(scope.EnvironmentAlias) + return "vf transcript search --session " + shellWord(id) + session.Scope(scope.ProjectID, "") + " --environment-alias " + shellWord(scope.EnvironmentAlias) } // FindTranscript is session id's transcript: of the project's transcripts @@ -157,7 +160,7 @@ func FindTranscript(ctx context.Context, s *sdk.VoiceflowSDK, opts []operations. body.EnvironmentAlias = &alias } req := operations.StableTranscriptControllerSearchV2Request{ProjectID: projectID, Body: body} - deadline := time.Now().Add(transcriptWait) + deadline := time.Now().Add(TranscriptWait) for { res, err := s.Transcript.Search(ctx, req, opts...) if err != nil { @@ -172,7 +175,7 @@ func FindTranscript(ctx context.Context, s *sdk.VoiceflowSDK, opts []operations. select { case <-ctx.Done(): return nil, ctx.Err() - case <-time.After(transcriptPoll): + case <-time.After(TranscriptPoll): } } } diff --git a/internal/cli/conversation/sessionend_test.go b/internal/cli/conversation/sessionend_test.go index 45b7b291..ef3cf93c 100644 --- a/internal/cli/conversation/sessionend_test.go +++ b/internal/cli/conversation/sessionend_test.go @@ -47,9 +47,9 @@ func summary(id, session string, created time.Time) string { } func quickLooks(t *testing.T, wait time.Duration) { - savedWait, savedPoll := transcriptWait, transcriptPoll - transcriptWait, transcriptPoll = wait, 10*time.Millisecond - t.Cleanup(func() { transcriptWait, transcriptPoll = savedWait, savedPoll }) + savedWait, savedPoll := TranscriptWait, TranscriptPoll + TranscriptWait, TranscriptPoll = wait, 10*time.Millisecond + t.Cleanup(func() { TranscriptWait, TranscriptPoll = savedWait, savedPoll }) } func TestFindTranscriptLooksAgainUntilItIsThere(t *testing.T) { diff --git a/internal/cli/conversation/sessionstate.go b/internal/cli/conversation/sessionstate.go index 7b8f2991..233188c9 100644 --- a/internal/cli/conversation/sessionstate.go +++ b/internal/cli/conversation/sessionstate.go @@ -105,13 +105,13 @@ func addSessionGet(parent *cobra.Command) { Example: " vf session get -p -e ", RunE: runSessionGet, } - addSessionFlags(cmd, getMeta, sessionHelp) + addSessionFlags(cmd, versionMeta, sessionHelp) parent.AddCommand(cmd) } -// getMeta are get's scope flags, and the version, for a session vf didn't -// start: it knows the version of one it did. -var getMeta = append(slices.Clip(sessionScopeMeta), flagutil.FlagMeta{ +// versionMeta are get's and end's scope flags, and the version, for a +// session vf didn't start: it knows the version of one it did. +var versionMeta = append(slices.Clip(sessionScopeMeta), flagutil.FlagMeta{ FlagName: "version-param", Shorthand: "v", FieldPath: "Version", Kind: flagutil.FlagKindEnum, EnumValues: []string{"draft", "published"}, Description: "The version the session talks to. vf knows it for a session it started; for another, it is the draft unless you say published. (options: draft, published)", @@ -121,7 +121,7 @@ func runSessionGet(cmd *cobra.Command, args []string) error { if usage.UsageRequested(cmd) { return usage.EmitSchema(cmd, cmd.OutOrStdout()) } - scope, err := scopeOf(cmd, getMeta) + scope, err := scopeOf(cmd, versionMeta) if err != nil { return err } diff --git a/internal/cli/evalnotended_test.go b/internal/cli/evalnotended_test.go index 49229605..d1df8415 100644 --- a/internal/cli/evalnotended_test.go +++ b/internal/cli/evalnotended_test.go @@ -62,8 +62,8 @@ func TestEvaluationRunOnAnOpenTranscriptSaysHowToEndIt(t *testing.T) { for _, c := range []struct { name, version, want string }{ - {"draft", "draft", `vf conversation send --project-id p1 --environment-alias main --user-id ci-runA --action '{"type":"end"}'`}, - {"published", "published", `vf conversation send --project-id p1 --environment-alias main --user-id ci-runA --version-param published --action '{"type":"end"}'`}, + {"draft", "draft", `vf session end -s ci-runA -p p1 -e main`}, + {"published", "published", `vf session end -s ci-runA -p p1 -e main -v published`}, } { url := evalServer(t, http.StatusBadRequest, notEndedAnswer, openTranscript(c.version)) @@ -105,8 +105,8 @@ func TestEvaluationRunOnAnOpenTranscriptSaysHowToEndIt(t *testing.T) { } } -// When vf can't look the transcript up, the step still names the end action -// and where to find the user ID it needs. +// When vf can't look the transcript up, the step still names the session end +// and where to find the session ID it needs. func TestEvaluationRunOnAnOpenTranscriptItCantLookUp(t *testing.T) { url := evalServer(t, http.StatusBadRequest, notEndedAnswer, "") _, stderr, err := runArgs(t, url, false, evalRun...) @@ -115,7 +115,7 @@ func TestEvaluationRunOnAnOpenTranscriptItCantLookUp(t *testing.T) { } for _, want := range []string{ `vf transcript get --project-id p1 --transcript-id tr1`, - `--action '{"type":"end"}'`, + `vf session end -s -p p1 -e `, } { if !strings.Contains(stderr, want) { t.Errorf("want %q in:\n%s", want, stderr) @@ -136,14 +136,14 @@ func TestEvaluationRunOtherFailuresAreUnchanged(t *testing.T) { if err == nil { t.Fatal("the run should fail") } - if strings.Contains(stderr, "transcript_not_ended") || strings.Contains(stderr, "conversation send") { + if strings.Contains(stderr, "transcript_not_ended") || strings.Contains(stderr, "session end") { t.Errorf("another 400 shouldn't be read as an open transcript:\n%s", stderr) } } func TestEvaluationRunHelpSaysTheTranscriptMustHaveEnded(t *testing.T) { run := find(t, testRoot(t), "evaluation", "run") - for _, want := range []string{"must have ended", `--action '{"type":"end"}'`} { + for _, want := range []string{"must have ended", "vf session end -s ", "--session "} { if !strings.Contains(run.Long, want) { t.Errorf("evaluation run's help should say %q:\n%s", want, run.Long) } diff --git a/internal/cli/evalsession_test.go b/internal/cli/evalsession_test.go new file mode 100644 index 00000000..7737f0e4 --- /dev/null +++ b/internal/cli/evalsession_test.go @@ -0,0 +1,180 @@ +// This file is not generated by Speakeasy. It covers evaluation/session.go, +// `vf evaluation run --session`, and transcript/session.go, `vf transcript +// search --session`: a session's transcript is found by the session's ID, +// as `vf session end` finds it. + +package cli + +import ( + "encoding/json" + "strconv" + "strings" + "testing" + "time" + + "github.com/voiceflow/cli/internal/cli/conversation" + "github.com/voiceflow/cli/internal/cmdcheck" +) + +// searchRow is a transcript in a search answer: its ID, its session's, and how +// long before now it was created. +type searchRow struct { + id, session string + ago time.Duration +} + +// searchAnswer is a transcript search's answer with those transcripts. +func searchAnswer(transcripts ...searchRow) string { + var rows []string + for _, f := range transcripts { + at := time.Now().Add(-f.ago).UTC().Format(time.RFC3339) + rows = append(rows, `{"id":"`+f.id+`","sessionID":"`+f.session+`","createdAt":"`+at+`","endedAt":null,"creatorURL":""}`) + } + return `{"transcripts":[` + strings.Join(rows, ",") + `],"returned":` + strconv.Itoa(len(rows)) + `,"hasMore":false}` +} + +// evaluate runs `vf evaluation run -e e1 -p p1` with args, as an agent. +func evaluate(t *testing.T, api *sessionAPI, home string, args ...string) (stdout, stderr string, err error) { + t.Helper() + return runInHome(t, home, api.url, true, append([]string{"evaluation", "run", "-e", "e1", "-p", "p1", "-o", "json"}, args...)...) +} + +func TestEvaluationRunFindsTheSessionsTranscript(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + out, errOut, err := api.session(home, false, "start") + if err != nil { + t.Fatalf("start: %v\n%s%s", err, out, errOut) + } + id := sessionIDRE.FindString(out) + api.requests() + + // An older transcript of the same ID, from before vf started this + // session, and a newer one of another session, aren't its own. + api.searches = []string{searchAnswer(searchRow{"t-other", "s-other000", 0}, searchRow{"t-new", id, time.Second}, searchRow{"t-old", id, time.Hour})} + out, errOut, err = evaluate(t, api, home, "--session", id) + if err != nil { + t.Fatalf("evaluation run --session: %v\n%s%s", err, out, errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "search, evaluate t-new" { + t.Errorf("sent %q, want a search, then the run on t-new", seen) + } + if !strings.Contains(out, `"transcriptID":"t-new"`) { + t.Errorf("the run's result:\n%s", out) + } + + // A session vf didn't start: the newest transcript with its ID. + api.searches = []string{searchAnswer(searchRow{"t-a1", "ci-runA", 2 * time.Hour}, searchRow{"t-a2", "ci-runA", time.Hour})} + if out, errOut, err = evaluate(t, api, home, "-s", "ci-runA"); err != nil { + t.Fatalf("evaluation run -s ci-runA: %v\n%s%s", err, out, errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "search, evaluate t-a2" { + t.Errorf("sent %q, want the run on the newest, t-a2", seen) + } + + // -t still names a transcript, and not with --session too. + if _, _, err = evaluate(t, api, home, "-t", "t-9"); err != nil { + t.Fatalf("evaluation run -t: %v", err) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "evaluate t-9" { + t.Errorf("-t sent %q", seen) + } + _, errOut, err = evaluate(t, api, home, "-t", "t-9", "--session", id) + if err == nil || !strings.Contains(errOut, "usage_error") { + t.Errorf("-t with --session should be a usage error: %v\n%s", err, errOut) + } + if seen, _ := api.requests(); len(seen) > 0 { + t.Errorf("-t with --session sent %q", seen) + } +} + +func TestEvaluationRunOnAnOpenSessionSaysToEndIt(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + api.openRuns = true + api.transcript = openTranscript("draft") + api.searches = []string{searchAnswer(searchRow{"tr1", "ci-runA", 0})} + _, errOut, err := evaluate(t, api, home, "--session", "ci-runA") + if err == nil { + t.Fatal("the run should fail") + } + var env struct { + ErrorType string `json:"error_type"` + Hints []string `json:"hints"` + } + if err := json.Unmarshal([]byte(errOut), &env); err != nil { + t.Fatalf("stderr isn't the envelope: %v\n%s", err, errOut) + } + want := "vf session end -s ci-runA -p p1 -e main" + if env.ErrorType != "transcript_not_ended" || !strings.Contains(strings.Join(env.Hints, "\n"), "'"+want+"'") { + t.Errorf("want transcript_not_ended with `%s`:\n%s", want, errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "search, evaluate tr1, transcript get" { + t.Errorf("sent %q", seen) + } +} + +func TestEvaluationRunOnASessionWithNoTranscript(t *testing.T) { + savedWait := conversation.TranscriptWait + conversation.TranscriptWait = 0 + t.Cleanup(func() { conversation.TranscriptWait = savedWait }) + api := newSessionAPI(t) + home := t.TempDir() + + _, errOut, err := evaluate(t, api, home, "--session", "s-nothing0") + if err == nil { + t.Fatal("the run should fail") + } + var env struct { + ErrorType string `json:"error_type"` + ExitCode int `json:"exit_code"` + Hints []string `json:"hints"` + } + if err := json.Unmarshal([]byte(errOut), &env); err != nil { + t.Fatalf("stderr isn't the envelope: %v\n%s", err, errOut) + } + hints := strings.Join(env.Hints, "\n") + if env.ErrorType != "not_found" || env.ExitCode != 4 || !strings.Contains(hints, "'vf transcript search --session s-nothing0 -p p1'") { + t.Errorf("want not_found, exit 4, and the search that lists its transcripts:\n%s", errOut) + } + if seen, _ := api.requests(); strings.Join(seen, ", ") != "search" { + t.Errorf("sent %q, want only the search", seen) + } + + // A person gets the same step, and it runs as written. + _, errOut, _ = runInHome(t, home, api.url, false, "evaluation", "run", "-e", "e1", "-p", "p1", "--session", "s-nothing0") + if !strings.Contains(errOut, "vf transcript search --session s-nothing0 -p p1") { + t.Errorf("a person should get the search:\n%s", errOut) + } + api.requests() + root := testRoot(t) + for _, line := range cmdcheck.Commands(errOut) { + if problems := cmdcheck.Check(root, line, cmdcheck.Options{Complete: true}); len(problems) > 0 { + t.Errorf("`%s` %v", line, problems) + } + } + + // A dry run doesn't look: -t says whose transcript it would be. + _, errOut, err = runInHome(t, home, api.url, false, "evaluation", "run", "-e", "e1", "-p", "p1", "--session", "s-nothing0", "--dry-run") + if err != nil || !strings.Contains(errOut, `"transcriptID": "(the transcript of session s-nothing0)"`) { + t.Errorf("dry run: %v\n%s", err, errOut) + } + if seen, _ := api.requests(); len(seen) > 0 { + t.Errorf("a dry run sent %q", seen) + } +} + +func TestTranscriptSearchTakesSession(t *testing.T) { + api := newSessionAPI(t) + home := t.TempDir() + for _, flag := range []string{"--session", "--session-id"} { + _, errOut, err := runInHome(t, home, api.url, false, "transcript", "search", "-p", "p1", flag, "s-abc12345", "--dry-run") + if err != nil || !strings.Contains(errOut, `"sessionID": "s-abc12345"`) && !strings.Contains(errOut, `"sessionID":"s-abc12345"`) { + t.Errorf("transcript search %s: %v\n%s", flag, err, errOut) + } + } + help, _, err := runInHome(t, home, api.url, false, "transcript", "search", "--help") + if err != nil || !strings.Contains(strings.Join(strings.Fields(help), " "), "--session is another name for it") { + t.Errorf("transcript search --help should name --session: %v\n%s", err, help) + } +} diff --git a/internal/cli/evaluation/notended.go b/internal/cli/evaluation/notended.go index 7beb1701..f8ba0edc 100644 --- a/internal/cli/evaluation/notended.go +++ b/internal/cli/evaluation/notended.go @@ -9,13 +9,14 @@ // error_type validation_error. Nothing named the end action (round-6 sweep // R6 #5, agent-ci:F2, human-poweruser:F11). // -// Now that 400 has error_type transcript_not_ended, and its step is the end -// action for the conversation the transcript records: vf looks the -// transcript up for its user ID (sessionID), environment and version, and -// gives `vf conversation send … --action '{"type":"end"}'` with those -// filled in (conversation/endaction.go gives the end its reason). When the -// lookup fails, the step says where those values are. evaluation run's help -// says the transcript must have ended. +// Now that 400 has error_type transcript_not_ended, and its step ends the +// session the transcript records: vf looks the transcript up for its +// session ID (sessionID, the conversation's user ID), environment and +// version, and gives `vf session end -s ` with those filled in. It +// gave `vf conversation send … --action '{"type":"end"}'` until round 8 +// made the session commands the way to talk to an agent. When the lookup +// fails, the step says where those values are. evaluation run's help says +// the transcript must have ended. // // Hooked in by two lines in run.go; internal/cli/evalnotended_test.go // covers both. @@ -40,18 +41,16 @@ import ( const transcriptNotEnded = "transcript_not_ended" -// endAction is the action that ends a conversation, as --action takes it. -const endAction = `'{"type":"end"}'` - const runLong = `Run an evaluation on one transcript, and print its result. -The transcript's conversation must have ended. To end a conversation you had -with 'vf conversation send', send the end action with the same --user-id and ---environment-alias: - vf conversation send --project-id --environment-alias --user-id --action '{"type":"end"}' +The transcript's conversation must have ended. 'vf session end' ends a +session and gives its transcript's ID for -t; or name the session with +--session, and vf finds its transcript: + vf session end -s -p -e + vf evaluation run -e -p --session Until it has ended, the run fails with error type transcript_not_ended.` -const transcriptHelp = "The transcript to evaluate; 'vf transcript search' lists them. Its conversation must have ended. [required]" +const transcriptHelp = "The transcript to evaluate; 'vf session end' gives a session's, and 'vf transcript search' lists them. Its conversation must have ended. Or name its session with --session. [required]" // sayTheTranscriptMustHaveEnded puts the rule in evaluation run's help. func sayTheTranscriptMustHaveEnded(cmd *cobra.Command) { @@ -74,24 +73,23 @@ func runFailed(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableEv return output.Report(cmd, x, err) } -// endTheConversation is the step that ends the transcript's conversation, -// with the user ID, environment and version the transcript records. +// endTheConversation is the step that ends the transcript's conversation: +// its session, in the environment and version the transcript records. func endTheConversation(cmd *cobra.Command, s *sdk.VoiceflowSDK, req *operations.StableEvaluationControllerRunRequest) []string { transcript, ok := lookUp(cmd, s, req.ProjectID, req.Body.TranscriptID) if !ok || transcript.SessionID == "" || transcript.EnvironmentAlias == nil || *transcript.EnvironmentAlias == "" { return []string{ - fmt.Sprintf("`vf transcript get --project-id %s --transcript-id %s` shows the conversation's user ID (sessionID) and environment (environmentAlias)", + fmt.Sprintf("`vf transcript get --project-id %s --transcript-id %s` shows the conversation's session ID (sessionID) and environment (environmentAlias)", quote(req.ProjectID), quote(req.Body.TranscriptID)), - fmt.Sprintf("End it, then run this again: `vf conversation send --project-id %s --environment-alias --user-id --action %s`", - quote(req.ProjectID), endAction), + fmt.Sprintf("End it, then run this again: `vf session end -s -p %s -e `", quote(req.ProjectID)), } } version := "" if transcript.Version != nil && *transcript.Version == components.StableTranscriptSummaryVersionPublished { - version = " --version-param published" + version = " -v published" } - return []string{fmt.Sprintf("End the conversation, then run this again: `vf conversation send --project-id %s --environment-alias %s --user-id %s%s --action %s`", - quote(req.ProjectID), quote(*transcript.EnvironmentAlias), quote(transcript.SessionID), version, endAction)} + return []string{fmt.Sprintf("End the session, then run this again: `vf session end -s %s -p %s -e %s%s`", + quote(transcript.SessionID), quote(req.ProjectID), quote(*transcript.EnvironmentAlias), version)} } // lookUp reads the transcript's summary. ok is false when it can't. diff --git a/internal/cli/evaluation/run.go b/internal/cli/evaluation/run.go index ddd28b7f..87f46f7d 100644 --- a/internal/cli/evaluation/run.go +++ b/internal/cli/evaluation/run.go @@ -36,6 +36,7 @@ func initRunCmd(parent *cobra.Command) error { } cmd.Flags().String("body", "", "Request body as JSON (alternative to individual flags). Can also be provided via stdin.") sayTheTranscriptMustHaveEnded(cmd) // notended.go: the transcript's conversation must have ended + takesASession(cmd) // session.go: --session finds the session's transcript for -t parent.AddCommand(cmd) return nil } diff --git a/internal/cli/evaluation/session.go b/internal/cli/evaluation/session.go new file mode 100644 index 00000000..c439e5c3 --- /dev/null +++ b/internal/cli/evaluation/session.go @@ -0,0 +1,125 @@ +// This file is not generated by Speakeasy. It is `vf evaluation run +// --session`: run an evaluation on a session's transcript without looking +// its ID up first. +// +// An evaluation takes a transcript ID, and a session's came from 'vf session +// end' or from a transcript search by the session's ID, which nothing said +// was the conversation's user ID (round 7: agent-migrator F2). --session +// finds it as 'vf session end' does: of the project's transcripts with +// that session ID, the newest created since vf started the session, or the +// newest of all for a session vf didn't start. If its conversation hasn't +// ended, the run fails with transcript_not_ended, and notended.go gives +// 'vf session end -s ' as the step. -t still names a transcript. +// +// Hooked in by one line in run.go; internal/cli/evalsession_test.go covers +// it. + +package evaluation + +import ( + "errors" + "slices" + + "github.com/spf13/cobra" + + "github.com/voiceflow/cli/internal/cli/conversation" + "github.com/voiceflow/cli/internal/client" + "github.com/voiceflow/cli/internal/flagutil" + "github.com/voiceflow/cli/internal/interactive" + "github.com/voiceflow/cli/internal/output" + "github.com/voiceflow/cli/internal/sdk/models/operations" + "github.com/voiceflow/cli/internal/session" + "github.com/voiceflow/cli/internal/sessions" + "github.com/voiceflow/cli/internal/usage" +) + +const ( + sessionFlag = "session" + transcriptFlag = "transcript-id" +) + +// takesASession gives evaluation run --session, which finds the transcript +// before the run. +func takesASession(cmd *cobra.Command) { + cmd.Flags().StringP(sessionFlag, "s", "", + "The session whose transcript to evaluate, instead of -t: vf finds the newest transcript with its ID, as 'vf session end' does.") + run := cmd.RunE + cmd.RunE = func(cmd *cobra.Command, args []string) error { + if !usage.UsageRequested(cmd) { + if err := transcriptOfSession(cmd); err != nil { + return err + } + } + return run(cmd, args) + } +} + +// transcriptOfSession sets -t to the transcript of the session --session +// names. A dry run doesn't look: its -t says whose transcript it would be. +func transcriptOfSession(cmd *cobra.Command) error { + id, _ := cmd.Flags().GetString(sessionFlag) + if id == "" { + return nil + } + if flagutil.FlagChanged(cmd, transcriptFlag) { + x := output.Explanation{ + Type: "usage_error", + Title: "Give -t or --session, not both", + Why: []string{"-t names the transcript to evaluate, and --session names a session for vf to find its transcript."}, + } + return output.Report(cmd, x, errors.New(x.Title)) + } + meta := slices.DeleteFunc(slices.Clone(runCmdMeta), func(m flagutil.FlagMeta) bool { return m.FlagName == transcriptFlag }) + if interactive.ShouldPrompt(cmd, meta) { + if err := interactive.PromptAndSetFlags(cmd, meta); err != nil { + return err + } + } + req, err := flagutil.BuildRequest[operations.StableEvaluationControllerRunRequest](cmd, meta, "", "") + if err != nil { + return err + } + transcript := "(the transcript of session " + id + ")" + if !client.IsDryRun(cmd) { + if transcript, err = findTranscript(cmd, req.ProjectID, id); err != nil { + return err + } + } + return cmd.Flags().Set(transcriptFlag, transcript) +} + +// findTranscript is the ID of session id's transcript in the project. +func findTranscript(cmd *cobra.Command, projectID, id string) (string, error) { + env, rec, _ := sessions.Find(projectID, id) + s, err := client.NewClient(cmd) + if err != nil { + return "", err + } + opts, err := output.PrepareCallOpts(cmd) + if err != nil { + return "", err + } + ctx := client.WithSpinnerMessage(cmd.Context(), "Finding session "+id+"'s transcript…") + found, err := conversation.FindTranscript(ctx, s, opts, projectID, env, id, rec.StartedAt) + if err != nil { + return "", output.Error(cmd, err) + } + if found != nil { + return found.ID, nil + } + search := "vf transcript search --session " + quote(id) + session.Scope(projectID, "") + if env != "" { + search += " --environment-alias " + quote(env) + } + x := output.Explanation{ + Type: "not_found", + Title: "Session " + id + " has no transcript yet", + Why: []string{"The API files a conversation's transcript under its session ID from its first turn, " + + "and had none for " + id + " in project " + projectID + "."}, + Next: []string{ + "`" + search + "` lists the session's transcripts", + "Or name the transcript to evaluate with -t", + }, + } + return "", output.Report(cmd, x, errors.New(x.Title)) +} diff --git a/internal/cli/session_test.go b/internal/cli/session_test.go index bad3d4d1..0737858c 100644 --- a/internal/cli/session_test.go +++ b/internal/cli/session_test.go @@ -37,6 +37,12 @@ type sessionAPI struct { // scriptTranscript is the transcript ID a script's answer gives: nil // when the runtime reported none. scriptTranscript any + // transcript is the answer to a transcript get; openRuns says an + // evaluation run finds the transcript's conversation still open. + transcript string + openRuns bool + // version is the version the last turn asked for. + version string } func newSessionAPI(t *testing.T) *sessionAPI { @@ -108,6 +114,9 @@ func (api *sessionAPI) serve(w http.ResponseWriter, r *http.Request) { Version string `json:"version"` } _ = json.Unmarshal(body, &req) + api.mu.Lock() + api.version = req.Version + api.mu.Unlock() switch typ := req.Action.Type; { case typ == "launch": say("launch" + strings.TrimPrefix(string(req.Action.Payload), "null")) @@ -133,6 +142,22 @@ func (api *sessionAPI) serve(w http.ResponseWriter, r *http.Request) { } api.mu.Unlock() io.WriteString(w, answer) + case strings.HasPrefix(r.URL.Path, "/v1/stable/evaluation/") && strings.HasSuffix(r.URL.Path, "/run"): + var req struct { + TranscriptID string `json:"transcriptID"` + } + _ = json.Unmarshal(body, &req) + say("evaluate " + req.TranscriptID) + if api.openRuns { + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, notEndedAnswer) + return + } + w.WriteHeader(http.StatusCreated) + io.WriteString(w, `{"result":{"cost":0.001,"value":true,"reason":"Polite.","transcriptID":"`+req.TranscriptID+`"}}`) + case strings.HasPrefix(r.URL.Path, "/v2/stable/transcript/") && r.Method == http.MethodGet: + say("transcript get") + io.WriteString(w, api.transcript) default: say(r.Method + " " + r.URL.Path) io.WriteString(w, `{"message":"Agent updated."}`) @@ -455,6 +480,22 @@ func TestEndFindsTheSessionsTranscript(t *testing.T) { if err := json.Unmarshal([]byte(out), &result); err != nil || result.Session != "s-reused" || !result.Ended || result.TranscriptID == nil || *result.TranscriptID != "t-new" { t.Errorf("%v\n%s", err, out) } + + // A session vf didn't start talks to the draft, unless -v says + // published, as evaluation run's step for a published transcript does. + api.searches = []string{searchAnswer(searchRow{"t-ci", "ci-runA", 0})} + for _, version := range []string{"draft", "published"} { + args := []string{"end", "-s", "ci-runA", "-o", "json"} + if version == "published" { + args = append(args, "-v", "published") + } + if _, errOut, err := api.session(home, true, args...); err != nil { + t.Fatalf("%v\n%s", err, errOut) + } + if api.requests(); api.version != version { + t.Errorf("end %v ended the %s conversation, want %s", args, api.version, version) + } + } } // Every Next line a session command prints runs as written. diff --git a/internal/cli/transcript/search.go b/internal/cli/transcript/search.go index dc481eee..880dfa04 100644 --- a/internal/cli/transcript/search.go +++ b/internal/cli/transcript/search.go @@ -38,6 +38,7 @@ func initSearchCmd(parent *cobra.Command) error { RunE: runSearchCmd, } flagutil.RegisterFlags(cmd, searchCmdMeta) + takesSession(cmd) // session.go: --session is another name for --session-id if err := flagutil.ValidateMeta[operations.StableTranscriptControllerSearchV2Request](searchCmdMeta); err != nil { return fmt.Errorf("invalid metadata for search: %w", err) } diff --git a/internal/cli/transcript/session.go b/internal/cli/transcript/session.go new file mode 100644 index 00000000..bc6f9c61 --- /dev/null +++ b/internal/cli/transcript/session.go @@ -0,0 +1,31 @@ +// This file is not generated by Speakeasy. It makes --session another name +// for `vf transcript search --session-id`. +// +// The session commands name a session with -s/--session, and its ID is +// what transcripts file the conversation under as sessionID. Searching for +// one with --session failed as an unknown flag, though it is the same ID +// (round 8 brief). Both names now work; the help lists --session-id and +// says --session is the same. +// +// Hooked in by one line in search.go; internal/cli/evalsession_test.go +// covers it. + +package transcript + +import ( + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// takesSession makes --session another name for --session-id. +func takesSession(cmd *cobra.Command) { + cmd.Flags().SetNormalizeFunc(func(_ *pflag.FlagSet, name string) pflag.NormalizedName { + if name == "session" { + return "session-id" + } + return pflag.NormalizedName(name) + }) + if f := cmd.Flags().Lookup("session-id"); f != nil { + f.Usage += " --session is another name for it: the ID 'vf session' gives, the conversation's user ID." + } +} From 8cfe2b4e4d41de613cd4b4012e203aae8ac28df7 Mon Sep 17 00:00:00 2001 From: Braden Ream <51544548+Bradenream@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:27:36 -0500 Subject: [PATCH 06/15] docs(session): the README, docs and home menu talk to the agent with vf session Why: the README's quickstart, its notes and its command listing, and the npm README, still talked to the agent with 'vf conversation send', a user ID, a version and an action in JSON per turn, and said vf compiles the draft before every turn. Typing "chat", "talk" or "conversation" at the home prompt found nothing, now that conversation is hidden. Design: the quickstart starts a session, sends a message and ends it. The notes give the session's version, the current session, -s and the --session flags, and compile rule B: a compile when a session starts and before a turn after vf's own edits; to try an edit cleanly, start a new session. The listing and docs/vf.md list the session group, with its pages generated by cmd/gendocs (the other pages are left as they are). "chat", "talk", "session" and "conversation" find start, send, end and run-script in the home menu. Change: README.md, npm/cli/README.md, docs/vf.md, docs/vf_session*.md, prompt/intents.go. Test: sessionhide_test.go checks the menu for those words. --- README.md | 43 ++++++++++------------ docs/vf.md | 2 +- docs/vf_session.md | 49 +++++++++++++++++++++++++ docs/vf_session_end.md | 49 +++++++++++++++++++++++++ docs/vf_session_get.md | 49 +++++++++++++++++++++++++ docs/vf_session_run-script.md | 59 ++++++++++++++++++++++++++++++ docs/vf_session_send.md | 63 ++++++++++++++++++++++++++++++++ docs/vf_session_start.md | 58 +++++++++++++++++++++++++++++ docs/vf_session_update.md | 50 +++++++++++++++++++++++++ internal/cli/sessionhide_test.go | 13 +++++++ internal/prompt/intents.go | 12 ++++++ npm/cli/README.md | 10 ++--- 12 files changed, 427 insertions(+), 30 deletions(-) create mode 100644 docs/vf_session.md create mode 100644 docs/vf_session_end.md create mode 100644 docs/vf_session_get.md create mode 100644 docs/vf_session_run-script.md create mode 100644 docs/vf_session_send.md create mode 100644 docs/vf_session_start.md create mode 100644 docs/vf_session_update.md diff --git a/README.md b/README.md index 4652bc48..32d49355 100644 --- a/README.md +++ b/README.md @@ -89,26 +89,26 @@ WORKSPACE_ID=$(vf workspace list --output-format json | jq -r '.workspaces[0].id PROJECT_ID=$(vf project create --name "My Agent" --type webchat \ --workspace-id "$WORKSPACE_ID" --output-format json | jq -r '.project.id') -# 3. Start a conversation (fresh projects have one environment, alias "main") -vf conversation send --user-id quickstart-user --project-id "$PROJECT_ID" \ - --environment-alias main --version-param draft \ - --action '{"type":"launch"}' --output-format json - -# 4. Say something — same user-id continues the same conversation -vf conversation send --user-id quickstart-user --project-id "$PROJECT_ID" \ - --environment-alias main --version-param draft \ - --action '{"type":"text","payload":"What can you help me with?"}' --output-format json +# 3. Start a session: a conversation with the agent +# (fresh projects have one environment, alias "main") +vf session start --project-id "$PROJECT_ID" --environment-alias main + +# 4. Say something: the session goes on until you end it +vf session send --project-id "$PROJECT_ID" --environment-alias main "What can you help me with?" + +# 5. End it; vf finds its transcript, for an evaluation +vf session end --project-id "$PROJECT_ID" --environment-alias main ``` -The agent's replies arrive as `text` traces in the response. +At a terminal vf prints what the agent said. With `--output-format json` each turn prints the API's answer, the agent's replies as `text` traces, and the session's ID. A new project starts from a **template**, so it answers immediately but introduces itself as a placeholder brand ("Acme Corp support") and its instructions still contain fill-in-the-blank prompts. Getting to *your* agent is the next step, not the last one: edit the instructions (`vf agent update`), add knowledge (`vf document create-url`), run tests (`vf test run create`), and publish (`vf environment publish`). Worth knowing before you script against the CLI: -- **`--version-param draft` runs what you are editing; `published` runs the live version.** A new project is created with a first release already in place, so either works immediately — you do not have to publish anything first. -- **`--action '{"type":"launch"}'` is optional.** Sending a `text` action straight away works; the runtime starts the conversation itself. The launch step is shown because it makes the first turn explicit. -- **A conversation with the draft runs your latest edits.** The draft runs as last compiled, so vf compiles it before every turn with it: each `conversation send`, in a conversation old or new, and `conversation run-script`. A compile takes about half a second. If the draft won't compile, vf says why and sends nothing (`error_type` `compile_failed`, exit 1). An edit made while a turn runs can miss that turn; vf then compiles again after it and warns. `--no-compile` talks to the last build as it is; the published version is never compiled. +- **A session talks to the draft, what you are editing; `vf session start -v published` talks to the live version.** A new project is created with a first release already in place, so either works immediately — you do not have to publish anything first. +- **vf remembers the current session** for each project and environment, so `send`, `get`, `update` and `end` need no ID, and a `send` with none going starts one. `-s ` names another. A session's ID is its conversation's user ID: `vf transcript search --session ` lists its transcripts, and `vf evaluation run --session ` evaluates its newest. `vf session run-script` runs a list of messages as a fresh session. (`vf conversation`, which took a user ID, a version and an action in JSON on every turn, still runs for the scripts that use it.) +- **A session with the draft runs your latest edits.** The draft runs as last compiled, so vf compiles it when a session starts (`session start`, `session run-script`, a `send` that starts one), and before a turn after vf itself edited the draft (`vf agent update`, `vf playbook update`, …). Other turns don't compile. A compile takes about half a second. If the draft won't compile, vf says why and sends nothing (`error_type` `compile_failed`, exit 1). An edit made elsewhere, or while a turn runs, can miss that turn; vf then compiles after it and warns, so the next turn runs it. A conversation already going can still be swayed by its earlier replies: to try an edit cleanly, start a new session. `--no-compile` talks to the last build as it is; the published version is never compiled. - **Pass `--output-format json` explicitly when piping.** Inside AI coding agents (`CLAUDECODE`, `CURSOR_AGENT`, …) the default output is TOON, not JSON. - **Capture values with `--jq`**: `ID=$(vf project create … --jq .project.id)`. A string result prints raw, as `jq -r` prints it; anything else prints as JSON. - **`vf whoami` is offline** — it shows which credential source is configured but does not validate the token. `vf workspace list` is the real check. @@ -604,17 +604,14 @@ which names the coding agent running the CLI (`claude_code`, `codex`, …) or is * [`query`](docs/vf_knowledge-base_query.md) - Query knowledge base -### [conversation](docs/vf_conversation.md) - -* [`send`](docs/vf_conversation_send.md) - Send -* [`run-script`](docs/vf_conversation_run-script.md) - Run script - -#### [state](docs/vf_conversation_state.md) +### [session](docs/vf_session.md) -* [`get`](docs/vf_conversation_state_get.md) - Get state -* [`update`](docs/vf_conversation_state_update.md) - Update state -* [`delete`](docs/vf_conversation_state_delete.md) - Delete state -* [`update-variables`](docs/vf_conversation_state_update-variables.md) - Update variables +* [`start`](docs/vf_session_start.md) - Start a fresh conversation with the agent +* [`send`](docs/vf_session_send.md) - Say the next thing to the agent +* [`update`](docs/vf_session_update.md) - Set variables in the session +* [`get`](docs/vf_session_get.md) - Show the session and its variables +* [`end`](docs/vf_session_end.md) - End the session, and find its transcript +* [`run-script`](docs/vf_session_run-script.md) - Run a list of messages as a fresh session ### [credits](docs/vf_credits.md) diff --git a/docs/vf.md b/docs/vf.md index b6ead473..6f3b60c3 100644 --- a/docs/vf.md +++ b/docs/vf.md @@ -36,7 +36,6 @@ vf [flags] * [vf api-tool](vf_api-tool.md) - Manage API tools: HTTP requests the agent can make * [vf auth](vf_auth.md) - Manage authentication credentials * [vf configure](vf_configure.md) - Configure authentication credentials and preferences -* [vf conversation](vf_conversation.md) - Talk to an agent: send messages, run scripts * [vf document](vf_document.md) - Manage knowledge base documents and sitemaps * [vf environment](vf_environment.md) - Publish, clone, merge and compare environments * [vf evaluation](vf_evaluation.md) - Create and run evaluations that score transcripts @@ -47,6 +46,7 @@ vf [flags] * [vf mcp-tool](vf_mcp-tool.md) - List, inspect and run MCP server tools * [vf playbook](vf_playbook.md) - Build playbooks: instructions, tools and exit paths * [vf project](vf_project.md) - Create, list and manage projects +* [vf session](vf_session.md) - Start a session with the agent, send turns, end it * [vf tool](vf_tool.md) - Manage the tools an agent and its playbooks use * [vf transcript](vf_transcript.md) - Search and read conversation transcripts * [vf variable](vf_variable.md) - Manage the variables an agent reads and sets diff --git a/docs/vf_session.md b/docs/vf_session.md new file mode 100644 index 00000000..0d6bd904 --- /dev/null +++ b/docs/vf_session.md @@ -0,0 +1,49 @@ +## vf session + +Start a session with the agent, send turns, end it + +### Synopsis + +Talk to the agent one conversation at a time, as a person would. + +'vf session start' begins a fresh conversation, 'vf session send' says the next thing, and 'vf session end' ends it and finds its transcript, for 'vf evaluation run'. vf remembers the session each start began as the current one for its project and environment, so a turn takes only the message. A send with none going starts one. + +The session ID is the conversation's user ID: -s names a session, and -u still works. + +``` +vf session [flags] +``` + +### Options + +``` + -h, --help help for session +``` + +### Options inherited from parent commands + +``` + --agent-mode Enable structured errors and default TOON output for AI coding agents. Automatically enabled when a known agent environment is detected (CLAUDE_CODE, CURSOR_AGENT, etc.). Use --agent-mode=false to disable. + --color string Control colored output: auto (color when output is a TTY), always, or never. Respects NO_COLOR and FORCE_COLOR env vars. (default "auto") + -d, --debug Log request and response diagnostics to stderr + --dry-run Preview the request that would be sent without executing it (output to stderr) + -H, --header stringArray Set a custom HTTP request header (format: "Key: Value"). Can be specified multiple times. + --include-headers Include HTTP response headers in the output + -q, --jq string Filter the response with a jq expression, e.g. '.project.id' or '.items[] | .id'. A string prints raw, as jq -r prints it; anything else prints as JSON ('| tojson' keeps a string quoted). Overrides -o: the filter reads the JSON response, and its output is the same whatever -o says + --no-interactive Disable all interactive features (auto-prompting, the home prompt, TUI forms) + -o, --output-format string Specify the output format. Options: pretty, json, yaml, table, toon. (default "pretty") + --server-url string Override the default server URL + --timeout string HTTP request timeout (e.g., 30s, 5m, 100ms) + --token string Voiceflow bearer token + --usage Print the CLI Usage schema in KDL format +``` + +### SEE ALSO + +* [vf](vf.md) - Build, test, and operate Voiceflow AI agents from your terminal +* [vf session end](vf_session_end.md) - End the session, and find its transcript +* [vf session get](vf_session_get.md) - Show the session and its variables +* [vf session run-script](vf_session_run-script.md) - Run a list of messages as a fresh session +* [vf session send](vf_session_send.md) - Say the next thing to the agent +* [vf session start](vf_session_start.md) - Start a fresh conversation with the agent +* [vf session update](vf_session_update.md) - Set variables in the session diff --git a/docs/vf_session_end.md b/docs/vf_session_end.md new file mode 100644 index 00000000..c29f16d6 --- /dev/null +++ b/docs/vf_session_end.md @@ -0,0 +1,49 @@ +## vf session end + +End the session, and find its transcript + +### Synopsis + +End the current session's conversation, and find its transcript, for 'vf evaluation run'. The session is no longer the current one. + +``` +vf session end [flags] +``` + +### Examples + +``` + vf session end -p -e +``` + +### Options + +``` + -e, --environment-alias string The environment's alias, such as main or dev; 'vf environment list' lists them. [required] + -h, --help help for end + -p, --project-id string The project's ID: in Creator, under the agent's Settings → General, or from 'vf project list'. [required] + -s, --session string The session to act on. Without it, the current one: the one the last 'vf session start' began. + -v, --version-param string The version the session talks to. vf knows it for a session it started; for another, it is the draft unless you say published. (options: draft, published) +``` + +### Options inherited from parent commands + +``` + --agent-mode Enable structured errors and default TOON output for AI coding agents. Automatically enabled when a known agent environment is detected (CLAUDE_CODE, CURSOR_AGENT, etc.). Use --agent-mode=false to disable. + --color string Control colored output: auto (color when output is a TTY), always, or never. Respects NO_COLOR and FORCE_COLOR env vars. (default "auto") + -d, --debug Log request and response diagnostics to stderr + --dry-run Preview the request that would be sent without executing it (output to stderr) + -H, --header stringArray Set a custom HTTP request header (format: "Key: Value"). Can be specified multiple times. + --include-headers Include HTTP response headers in the output + -q, --jq string Filter the response with a jq expression, e.g. '.project.id' or '.items[] | .id'. A string prints raw, as jq -r prints it; anything else prints as JSON ('| tojson' keeps a string quoted). Overrides -o: the filter reads the JSON response, and its output is the same whatever -o says + --no-interactive Disable all interactive features (auto-prompting, the home prompt, TUI forms) + -o, --output-format string Specify the output format. Options: pretty, json, yaml, table, toon. (default "pretty") + --server-url string Override the default server URL + --timeout string HTTP request timeout (e.g., 30s, 5m, 100ms) + --token string Voiceflow bearer token + --usage Print the CLI Usage schema in KDL format +``` + +### SEE ALSO + +* [vf session](vf_session.md) - Start a session with the agent, send turns, end it diff --git a/docs/vf_session_get.md b/docs/vf_session_get.md new file mode 100644 index 00000000..33039743 --- /dev/null +++ b/docs/vf_session_get.md @@ -0,0 +1,49 @@ +## vf session get + +Show the session and its variables + +### Synopsis + +Show the current session: its ID, the version it talks to, and its variables. -o json prints its whole state, as the API keeps it. + +``` +vf session get [flags] +``` + +### Examples + +``` + vf session get -p -e +``` + +### Options + +``` + -e, --environment-alias string The environment's alias, such as main or dev; 'vf environment list' lists them. [required] + -h, --help help for get + -p, --project-id string The project's ID: in Creator, under the agent's Settings → General, or from 'vf project list'. [required] + -s, --session string The session to act on. Without it, the current one: the one the last 'vf session start' began. + -v, --version-param string The version the session talks to. vf knows it for a session it started; for another, it is the draft unless you say published. (options: draft, published) +``` + +### Options inherited from parent commands + +``` + --agent-mode Enable structured errors and default TOON output for AI coding agents. Automatically enabled when a known agent environment is detected (CLAUDE_CODE, CURSOR_AGENT, etc.). Use --agent-mode=false to disable. + --color string Control colored output: auto (color when output is a TTY), always, or never. Respects NO_COLOR and FORCE_COLOR env vars. (default "auto") + -d, --debug Log request and response diagnostics to stderr + --dry-run Preview the request that would be sent without executing it (output to stderr) + -H, --header stringArray Set a custom HTTP request header (format: "Key: Value"). Can be specified multiple times. + --include-headers Include HTTP response headers in the output + -q, --jq string Filter the response with a jq expression, e.g. '.project.id' or '.items[] | .id'. A string prints raw, as jq -r prints it; anything else prints as JSON ('| tojson' keeps a string quoted). Overrides -o: the filter reads the JSON response, and its output is the same whatever -o says + --no-interactive Disable all interactive features (auto-prompting, the home prompt, TUI forms) + -o, --output-format string Specify the output format. Options: pretty, json, yaml, table, toon. (default "pretty") + --server-url string Override the default server URL + --timeout string HTTP request timeout (e.g., 30s, 5m, 100ms) + --token string Voiceflow bearer token + --usage Print the CLI Usage schema in KDL format +``` + +### SEE ALSO + +* [vf session](vf_session.md) - Start a session with the agent, send turns, end it diff --git a/docs/vf_session_run-script.md b/docs/vf_session_run-script.md new file mode 100644 index 00000000..457c1dc8 --- /dev/null +++ b/docs/vf_session_run-script.md @@ -0,0 +1,59 @@ +## vf session run-script + +Run a list of messages as a fresh session + +### Synopsis + +Run a list of user messages as one new conversation, and make it the current session. + +With the draft, vf compiles it first, so the script runs your latest edits. 'vf session send' goes on from the script's last turn; --end ends the session after the script instead, and finds its transcript, for 'vf evaluation run'. + +``` +vf session run-script [flags] +``` + +### Examples + +``` + vf session run-script -p -e --messages '["What are your hours?","Book a table for two"]' + vf session run-script -p -e --messages '["Hi","Cancel my order"]' --end +``` + +### Options + +``` + --body string Request body as JSON (alternative to individual flags). --body - reads it from stdin; piped stdin is read on its own only when no body flag is given. --body @file reads it from a file. + --end End the session after the script, and find its transcript, as 'vf session end' does. + -e, --environment-alias string The environment's alias, such as main or dev; 'vf environment list' lists them. [required] + -h, --help help for run-script + -l, --launch string How the conversation starts; payload is its only field. Leave it out for a plain launch. JSON: { payload: { persona?: string, … } } + -m, --messages string The user messages to send, in order, after the launch. A message is typed text, as a string or { "text": "…" }, or a button press, as { "button": "