package equipo import ( "context" "io" "net/http" "net/url" "time" ) // Turn states (wire.Turn*). A turn ends replied, failed or cancelled. const ( TurnQueued = "queued" TurnRunning = "running" TurnWaiting = "waiting" TurnReplied = "replied" TurnFailed = "failed" TurnCancelled = "cancelled" ) // TurnTeamUpdate is the kind of turn the Assistant takes by itself when a // job it handed on changes. It is quiet: Base shows no status, activity or // Stop for it. const TurnTeamUpdate = "team_update" // InFlight reports whether a turn in state has not ended. func InFlight(state string) bool { return state == TurnQueued || state == TurnRunning || state == TurnWaiting } // Message is one line of the conversation; Role is person or assistant. // Attachments are the files the person sent with it, in their order // (Clean keeps those Base passes on); Lookups, on the Assistant's reply, // what it looked up on the web for it, in the order it did (Clean keeps // them within bounds). type Message struct { ID string `json:"id"` Role string `json:"role"` Text string `json:"text"` TurnID string `json:"turn_id"` CreatedAt time.Time `json:"created_at"` Attachments []Attachment `json:"attachments,omitempty"` Lookups []Lookup `json:"lookups,omitempty"` } // Turn is the Assistant's answer to the person's messages. type Turn struct { ID string `json:"id"` Kind string `json:"kind"` State string `json:"state"` Reason string `json:"reason"` } // Card is something in the conversation to act on, drawn from its fields // alone: the question, a button per option (its label, answering with its // value), a link per link, and once it has one, a line saying how it // ended (Result). Base knows no kind's words of its own. A job card's // question is the job's title, Result its short status, Detail one // sentence more and StartedAt when it began; Job is the job card a // go-ahead or Publish card belongs to. A paused job's Result and Detail // are already in the person's time zone ("Paused until 21:00"), and // CarryOn says the person may start it again now (CarryOnNow): a paused // job, or a stopped one held while building was off, once it is on again. type Card struct { ID string `json:"id"` Revision int64 `json:"revision"` Kind string `json:"kind"` State string `json:"state"` Question string `json:"question"` Options []Option `json:"options"` Links []Link `json:"links"` Result string `json:"result"` Job string `json:"job,omitempty"` Detail string `json:"detail,omitempty"` StartedAt *time.Time `json:"started_at,omitempty"` CarryOn bool `json:"carry_on,omitempty"` // Turn is the turn that raised a connect card, as its event said // (WithTurn); never read from the card's own fields. Turn string `json:"turn_id,omitempty"` } // Option is one answer a card offers: Label on the button, Value sent. type Option struct { Value string `json:"value"` Label string `json:"label"` } // Link is a link a card shows. Rel, when set, says what it is to // (LinkEquipo). type Link struct { Label string `json:"label"` URL string `json:"url"` Rel string `json:"rel,omitempty"` } // The kinds of card the Assistant raises. const ( CardQuestion = "question" CardConfirm = "confirm" CardOutcome = "outcome" CardConnect = "connect" // CardJob is a job card: one per piece of work handed on, updated in // place. CardJob = "job" ) // A job card's states. const ( JobWorking = "working" JobAsking = "asking" JobReady = "ready" JobDone = "done" JobStopped = "stopped" // JobPaused is a job held for a while (its allowance or spending limit // reached, its runner offline) that carries on by itself. JobPaused = "paused" ) // LinkEquipo is the rel of a job card's link to the job's page in Equipo. const LinkEquipo = "equipo" // LinkOficinaConnect is the rel of a card's link that starts connecting the // person's Oficina account. It goes to Base itself (OficinaConnectPath), so // it opens in the same tab. const LinkOficinaConnect = "oficina_connect" // OficinaConnectPath is the path on Base a LinkOficinaConnect link has. const OficinaConnectPath = "/ask/oficina/connect" // Clean is the card as Base passes it on: its own fields only, never-null // options and links, and a link only if it is an http(s) URL (WebURL), // with a rel only if it is LinkEquipo (or, for CleanAt, Base's own connect link). A job card has no options, and is // kept only in a state Base knows; Detail and StartedAt are kept on a job // card only, CarryOn only on a paused one, and Job only when it looks like a card id (validJob). ok is // false for every other kind of card. func (c Card) Clean() (Card, bool) { return c.CleanAt("") } // CleanAt is Clean for Base at origin base (no trailing slash): a link with // rel LinkOficinaConnect keeps it only when it goes to exactly base plus // OficinaConnectPath. With base "" none does. func (c Card) CleanAt(base string) (Card, bool) { switch c.Kind { case CardQuestion, CardConfirm, CardOutcome, CardConnect: case CardJob: switch c.State { case JobWorking, JobAsking, JobReady, JobDone, JobStopped, JobPaused: default: return Card{}, false } default: return Card{}, false } out := Card{ID: c.ID, Revision: c.Revision, Kind: c.Kind, State: c.State, Question: c.Question, Options: []Option{}, Links: []Link{}, Result: c.Result} if c.Kind == CardJob { out.Detail, out.StartedAt = c.Detail, c.StartedAt out.CarryOn = c.CarryOn && (c.State == JobPaused || c.State == JobStopped) } else { for _, o := range c.Options { out.Options = append(out.Options, Option{Value: o.Value, Label: o.Label}) } } if validJob(c.Job) { out.Job = c.Job } for _, l := range c.Links { if u := WebURL(l.URL); u != "" { link := Link{Label: l.Label, URL: u} if l.Rel == LinkEquipo || l.Rel == LinkOficinaConnect && base != "" && u == base+OficinaConnectPath { link.Rel = l.Rel } out.Links = append(out.Links, link) } } return out, true } // WithTurn is a connect card with Turn set to turn, the turn its event // says raised it, when turn looks like an id (validJob). Every other card, // and a turn that does not look like one, is c as it is. func (c Card) WithTurn(turn string) Card { if c.Kind == CardConnect && validJob(turn) { c.Turn = turn } return c } // validJob reports whether id is 1 to 128 of [A-Za-z0-9_-]. func validJob(id string) bool { if id == "" || len(id) > 128 { return false } for _, r := range id { if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '-') { return false } } return true } // Go is a job card's first link without a rel: where to see the work. func (c Card) Go() (Link, bool) { if c.Kind == CardJob { for _, l := range c.Links { if l.Rel == "" { return l, true } } } return Link{}, false } // Equipo is a job card's link to the job's page in Equipo. func (c Card) Equipo() (Link, bool) { if c.Kind == CardJob { for _, l := range c.Links { if l.Rel == LinkEquipo { return l, true } } } return Link{}, false } // Open reports whether the card waits for an answer. func (c Card) Open() bool { return c.State == "open" } // Shown reports whether a conversation read afresh shows the card: a job // card always; any other while it is open, and afterwards if it says how // it ended. func (c Card) Shown() bool { return c.Kind == CardJob || c.Open() || c.Result != "" } // WebURL is raw if it is an absolute http or https URL with a host and no // user info, else "". func WebURL(raw string) string { u, err := url.Parse(raw) if raw == "" || err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil { return "" } return u.String() } // assistant is the prefix of the Assistant's routes: every chat call goes // there, never to the Coordinator's. const assistant = "/api/v1/assistant" // Snapshot is the part of GET /api/v1/assistant/snapshot Base shows: who // the bearer speaks for, the conversation's tail, its turns, its cards, // the event cursor they were read at (so the stream picks up exactly // after them), whether the person has a runner that can answer, and // whether it can take files (CanAttach; an older Equipo never says so). type Snapshot struct { Me struct { Address string `json:"address"` } `json:"me"` Messages []Message `json:"messages"` Turns []Turn `json:"turns"` Cards []Card `json:"cards"` Cursor int64 `json:"cursor"` Available bool `json:"available"` CanAttach bool `json:"can_attach"` } // Sent is POST messages's answer. type Sent struct { Message Message `json:"message"` Turn Turn `json:"turn"` } // Answered is POST cards/{id}/answer's answer. An answer that starts no // turn (an outcome card's) has an empty Message and a zero Turn. type Answered struct { Card Card `json:"card"` Message Message `json:"message"` Turn Turn `json:"turn"` } // JobStates is the query that opts in to the job states Base draws // beyond the five every Equipo sends: without it, Equipo sends a paused // job as working (same result and detail, no carry_on), since an older // Base drops a state it does not know. const JobStates = "job_states=" + JobPaused // Snapshot reads the person's conversation in one go. func (c *Client) Snapshot(ctx context.Context, token string) (Snapshot, error) { var out Snapshot _, err := c.call(ctx, http.MethodGet, assistant+"/snapshot?"+JobStates, token, "", nil, nil, &out) return out, err } // SetTimeZone tells Equipo the person's IANA time zone, which the times in // the copy it writes for them are in (a paused job's "Paused until // 21:00"), only if they have none yet (only_if_unset): a zone one of the // person's own devices reported wins over Base's. Equipo answers 422 // invalid_input to a zone it does not know. func (c *Client) SetTimeZone(ctx context.Context, token, zone string) error { in := map[string]any{"time_zone": zone, "only_if_unset": true} _, err := c.call(ctx, http.MethodPut, assistant+"/time-zone", token, NewKey(), nil, in, nil) return err } // Send sends the person's message, with the files uploaded for it (their // ids, in order; text may be empty when there are any): ErrNoRunner or // ErrRunnerTooOld when the person has no runner that can answer, and // ErrAttachmentsUnavailable when files came and the runner can't take // them. key makes a retry safe: Equipo keeps one message per key (and its // files). It goes as the body's idempotency_key, and as the // Idempotency-Key header every mutation carries. Without files the body // is what it always was. func (c *Client) Send(ctx context.Context, token, text, key string, files []string) (Sent, error) { var out Sent var in any = map[string]string{"text": text, "idempotency_key": key} if len(files) > 0 { in = map[string]any{"text": text, "idempotency_key": key, "attachments": files} } _, err := c.call(ctx, http.MethodPost, assistant+"/messages", token, key, nil, in, &out) return out, err } // Cancel stops a turn that has not ended. func (c *Client) Cancel(ctx context.Context, token, turnID, key string) error { _, err := c.call(ctx, http.MethodPost, assistant+"/turns/"+url.PathEscape(turnID)+"/cancel", token, key, nil, struct{}{}, nil) return err } // Answer answers card id with an option's value, at the card's revision. func (c *Client) Answer(ctx context.Context, token, id, choice string, revision int64, key string) (Answered, error) { var out Answered in := map[string]any{"choice": choice, "revision": revision} _, err := c.call(ctx, http.MethodPost, assistant+"/cards/"+url.PathEscape(id)+"/answer", token, key, nil, in, &out) return out, err } // CarryOnNow starts paused job card id again now, at the card's revision: // what "Carry on now" asks, offered while the card's CarryOn is set. The // answer is the card as it is now (200 {"card": …}); the same key again // gives the same answer. A 409 says why it cannot: card_stale (the card // moved on), not_paused or carry_on_unavailable. key goes as the body's // idempotency_key and the Idempotency-Key header. func (c *Client) CarryOnNow(ctx context.Context, token, id string, revision int64, key string) (Card, error) { var out struct { Card Card `json:"card"` } in := map[string]any{"revision": revision, "idempotency_key": key} _, err := c.call(ctx, http.MethodPost, assistant+"/cards/"+url.PathEscape(id)+"/carry_on", token, key, nil, in, &out) return out.Card, err } // RegisterHost tells Equipo where the person's Base operations live // (origin) and the token Base minted for them (hostToken), which the // Assistant presents when it calls them. A second call replaces the // first. func (c *Client) RegisterHost(ctx context.Context, token, origin, hostToken string) error { in := map[string]string{"origin": origin, "token": hostToken} _, err := c.call(ctx, http.MethodPut, assistant+"/host", token, NewKey(), nil, in, nil) return err } // Events opens the person's event stream after cursor after ("" for from // now). It gives up when the headers take longer than StreamHeaderTimeout. // The caller reads and closes the body; cancelling ctx ends the stream. func (c *Client) Events(ctx context.Context, token, after string) (*http.Response, error) { u := c.origin + assistant + "/events?" + JobStates if after != "" { u += "&after=" + url.QueryEscape(after) } ctx, cancel := context.WithCancel(ctx) req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) if err != nil { cancel() return nil, err } req.Header.Set("Accept", "text/event-stream") req.Header.Set("Authorization", "Bearer "+token) setCapabilities(ctx, req) late := time.AfterFunc(c.StreamHeaderTimeout, cancel) res, err := c.http.Do(req) if !late.Stop() && err == nil { res.Body.Close() err = context.DeadlineExceeded } if err != nil { cancel() return nil, err } if res.StatusCode != http.StatusOK { res.Body.Close() cancel() return nil, &Error{Status: res.StatusCode} } res.Body = cancelOnClose{res.Body, cancel} return res, nil } type cancelOnClose struct { io.ReadCloser cancel context.CancelFunc } func (b cancelOnClose) Close() error { b.cancel() return b.ReadCloser.Close() } // OficinaConnect asks Equipo where the person consents to connecting their // Oficina account; they come back to returnTo. func (c *Client) OficinaConnect(ctx context.Context, token, returnTo string) (string, error) { var out struct { URL string `json:"url"` } in := map[string]string{"return_to": returnTo} _, err := c.call(ctx, http.MethodPost, assistant+"/oficina/connect", token, NewKey(), nil, in, &out) return out.URL, err } // OficinaFinish hands Equipo what the person came back with. The status is // connected, denied, expired or unavailable. func (c *Client) OficinaFinish(ctx context.Context, token, state, code string) (string, error) { var out struct { Status string `json:"status"` } in := map[string]string{"state": state, "code": code} _, err := c.call(ctx, http.MethodPost, assistant+"/oficina/connect/finish", token, NewKey(), nil, in, &out) return out.Status, err }