oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package equipo
2
3import (
4 "context"
5 "io"
6 "net/http"
7 "net/url"
8 "time"
9)
10
11// Turn states (wire.Turn*). A turn ends replied, failed or cancelled.
12const (
13 TurnQueued = "queued"
14 TurnRunning = "running"
15 TurnWaiting = "waiting"
16 TurnReplied = "replied"
17 TurnFailed = "failed"
18 TurnCancelled = "cancelled"
19)
20
21// TurnTeamUpdate is the kind of turn the Assistant takes by itself when a
22// job it handed on changes. It is quiet: Base shows no status, activity or
23// Stop for it.
24const TurnTeamUpdate = "team_update"
25
26// InFlight reports whether a turn in state has not ended.
27func InFlight(state string) bool {
28 return state == TurnQueued || state == TurnRunning || state == TurnWaiting
29}
30
31// Message is one line of the conversation; Role is person or assistant.
32// Attachments are the files the person sent with it, in their order
33// (Clean keeps those Base passes on); Lookups, on the Assistant's reply,
34// what it looked up on the web for it, in the order it did (Clean keeps
35// them within bounds).
36type Message struct {
37 ID string `json:"id"`
38 Role string `json:"role"`
39 Text string `json:"text"`
40 TurnID string `json:"turn_id"`
41 CreatedAt time.Time `json:"created_at"`
42 Attachments []Attachment `json:"attachments,omitempty"`
43 Lookups []Lookup `json:"lookups,omitempty"`
44}
45
46// Turn is the Assistant's answer to the person's messages.
47type Turn struct {
48 ID string `json:"id"`
49 Kind string `json:"kind"`
50 State string `json:"state"`
51 Reason string `json:"reason"`
52}
53
54// Card is something in the conversation to act on, drawn from its fields
55// alone: the question, a button per option (its label, answering with its
56// value), a link per link, and once it has one, a line saying how it
57// ended (Result). Base knows no kind's words of its own. A job card's
58// question is the job's title, Result its short status, Detail one
59// sentence more and StartedAt when it began; Job is the job card a
60// go-ahead or Publish card belongs to. A paused job's Result and Detail
61// are already in the person's time zone ("Paused until 21:00"), and
62// CarryOn says the person may start it again now (CarryOnNow): a paused
63// job, or a stopped one held while building was off, once it is on again.
64type Card struct {
65 ID string `json:"id"`
66 Revision int64 `json:"revision"`
67 Kind string `json:"kind"`
68 State string `json:"state"`
69 Question string `json:"question"`
70 Options []Option `json:"options"`
71 Links []Link `json:"links"`
72 Result string `json:"result"`
73 Job string `json:"job,omitempty"`
74 Detail string `json:"detail,omitempty"`
75 StartedAt *time.Time `json:"started_at,omitempty"`
76 CarryOn bool `json:"carry_on,omitempty"`
77 // Turn is the turn that raised a connect card, as its event said
78 // (WithTurn); never read from the card's own fields.
79 Turn string `json:"turn_id,omitempty"`
80}
81
82// Option is one answer a card offers: Label on the button, Value sent.
83type Option struct {
84 Value string `json:"value"`
85 Label string `json:"label"`
86}
87
88// Link is a link a card shows. Rel, when set, says what it is to
89// (LinkEquipo).
90type Link struct {
91 Label string `json:"label"`
92 URL string `json:"url"`
93 Rel string `json:"rel,omitempty"`
94}
95
96// The kinds of card the Assistant raises.
97const (
98 CardQuestion = "question"
99 CardConfirm = "confirm"
100 CardOutcome = "outcome"
101 CardConnect = "connect"
102 // CardJob is a job card: one per piece of work handed on, updated in
103 // place.
104 CardJob = "job"
105)
106
107// A job card's states.
108const (
109 JobWorking = "working"
110 JobAsking = "asking"
111 JobReady = "ready"
112 JobDone = "done"
113 JobStopped = "stopped"
114 // JobPaused is a job held for a while (its allowance or spending limit
115 // reached, its runner offline) that carries on by itself.
116 JobPaused = "paused"
117)
118
119// LinkEquipo is the rel of a job card's link to the job's page in Equipo.
120const LinkEquipo = "equipo"
121
122// LinkOficinaConnect is the rel of a card's link that starts connecting the
123// person's Oficina account. It goes to Base itself (OficinaConnectPath), so
124// it opens in the same tab.
125const LinkOficinaConnect = "oficina_connect"
126
127// OficinaConnectPath is the path on Base a LinkOficinaConnect link has.
128const OficinaConnectPath = "/ask/oficina/connect"
129
130// Clean is the card as Base passes it on: its own fields only, never-null
131// options and links, and a link only if it is an http(s) URL (WebURL),
132// with a rel only if it is LinkEquipo (or, for CleanAt, Base's own connect link). A job card has no options, and is
133// kept only in a state Base knows; Detail and StartedAt are kept on a job
134// card only, CarryOn only on a paused one, and Job only when it looks like a card id (validJob). ok is
135// false for every other kind of card.
136func (c Card) Clean() (Card, bool) { return c.CleanAt("") }
137
138// CleanAt is Clean for Base at origin base (no trailing slash): a link with
139// rel LinkOficinaConnect keeps it only when it goes to exactly base plus
140// OficinaConnectPath. With base "" none does.
141func (c Card) CleanAt(base string) (Card, bool) {
142 switch c.Kind {
143 case CardQuestion, CardConfirm, CardOutcome, CardConnect:
144 case CardJob:
145 switch c.State {
146 case JobWorking, JobAsking, JobReady, JobDone, JobStopped, JobPaused:
147 default:
148 return Card{}, false
149 }
150 default:
151 return Card{}, false
152 }
153 out := Card{ID: c.ID, Revision: c.Revision, Kind: c.Kind, State: c.State, Question: c.Question,
154 Options: []Option{}, Links: []Link{}, Result: c.Result}
155 if c.Kind == CardJob {
156 out.Detail, out.StartedAt = c.Detail, c.StartedAt
157 out.CarryOn = c.CarryOn && (c.State == JobPaused || c.State == JobStopped)
158 } else {
159 for _, o := range c.Options {
160 out.Options = append(out.Options, Option{Value: o.Value, Label: o.Label})
161 }
162 }
163 if validJob(c.Job) {
164 out.Job = c.Job
165 }
166 for _, l := range c.Links {
167 if u := WebURL(l.URL); u != "" {
168 link := Link{Label: l.Label, URL: u}
169 if l.Rel == LinkEquipo || l.Rel == LinkOficinaConnect && base != "" && u == base+OficinaConnectPath {
170 link.Rel = l.Rel
171 }
172 out.Links = append(out.Links, link)
173 }
174 }
175 return out, true
176}
177
178// WithTurn is a connect card with Turn set to turn, the turn its event
179// says raised it, when turn looks like an id (validJob). Every other card,
180// and a turn that does not look like one, is c as it is.
181func (c Card) WithTurn(turn string) Card {
182 if c.Kind == CardConnect && validJob(turn) {
183 c.Turn = turn
184 }
185 return c
186}
187
188// validJob reports whether id is 1 to 128 of [A-Za-z0-9_-].
189func validJob(id string) bool {
190 if id == "" || len(id) > 128 {
191 return false
192 }
193 for _, r := range id {
194 if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '-') {
195 return false
196 }
197 }
198 return true
199}
200
201// Go is a job card's first link without a rel: where to see the work.
202func (c Card) Go() (Link, bool) {
203 if c.Kind == CardJob {
204 for _, l := range c.Links {
205 if l.Rel == "" {
206 return l, true
207 }
208 }
209 }
210 return Link{}, false
211}
212
213// Equipo is a job card's link to the job's page in Equipo.
214func (c Card) Equipo() (Link, bool) {
215 if c.Kind == CardJob {
216 for _, l := range c.Links {
217 if l.Rel == LinkEquipo {
218 return l, true
219 }
220 }
221 }
222 return Link{}, false
223}
224
225// Open reports whether the card waits for an answer.
226func (c Card) Open() bool { return c.State == "open" }
227
228// Shown reports whether a conversation read afresh shows the card: a job
229// card always; any other while it is open, and afterwards if it says how
230// it ended.
231func (c Card) Shown() bool { return c.Kind == CardJob || c.Open() || c.Result != "" }
232
233// WebURL is raw if it is an absolute http or https URL with a host and no
234// user info, else "".
235func WebURL(raw string) string {
236 u, err := url.Parse(raw)
237 if raw == "" || err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil {
238 return ""
239 }
240 return u.String()
241}
242
243// assistant is the prefix of the Assistant's routes: every chat call goes
244// there, never to the Coordinator's.
245const assistant = "/api/v1/assistant"
246
247// Snapshot is the part of GET /api/v1/assistant/snapshot Base shows: who
248// the bearer speaks for, the conversation's tail, its turns, its cards,
249// the event cursor they were read at (so the stream picks up exactly
250// after them), whether the person has a runner that can answer, and
251// whether it can take files (CanAttach; an older Equipo never says so).
252type Snapshot struct {
253 Me struct {
254 Address string `json:"address"`
255 } `json:"me"`
256 Messages []Message `json:"messages"`
257 Turns []Turn `json:"turns"`
258 Cards []Card `json:"cards"`
259 Cursor int64 `json:"cursor"`
260 Available bool `json:"available"`
261 CanAttach bool `json:"can_attach"`
262}
263
264// Sent is POST messages's answer.
265type Sent struct {
266 Message Message `json:"message"`
267 Turn Turn `json:"turn"`
268}
269
270// Answered is POST cards/{id}/answer's answer. An answer that starts no
271// turn (an outcome card's) has an empty Message and a zero Turn.
272type Answered struct {
273 Card Card `json:"card"`
274 Message Message `json:"message"`
275 Turn Turn `json:"turn"`
276}
277
278// JobStates is the query that opts in to the job states Base draws
279// beyond the five every Equipo sends: without it, Equipo sends a paused
280// job as working (same result and detail, no carry_on), since an older
281// Base drops a state it does not know.
282const JobStates = "job_states=" + JobPaused
283
284// Snapshot reads the person's conversation in one go.
285func (c *Client) Snapshot(ctx context.Context, token string) (Snapshot, error) {
286 var out Snapshot
287 _, err := c.call(ctx, http.MethodGet, assistant+"/snapshot?"+JobStates, token, "", nil, nil, &out)
288 return out, err
289}
290
291// SetTimeZone tells Equipo the person's IANA time zone, which the times in
292// the copy it writes for them are in (a paused job's "Paused until
293// 21:00"), only if they have none yet (only_if_unset): a zone one of the
294// person's own devices reported wins over Base's. Equipo answers 422
295// invalid_input to a zone it does not know.
296func (c *Client) SetTimeZone(ctx context.Context, token, zone string) error {
297 in := map[string]any{"time_zone": zone, "only_if_unset": true}
298 _, err := c.call(ctx, http.MethodPut, assistant+"/time-zone", token, NewKey(), nil, in, nil)
299 return err
300}
301
302// Send sends the person's message, with the files uploaded for it (their
303// ids, in order; text may be empty when there are any): ErrNoRunner or
304// ErrRunnerTooOld when the person has no runner that can answer, and
305// ErrAttachmentsUnavailable when files came and the runner can't take
306// them. key makes a retry safe: Equipo keeps one message per key (and its
307// files). It goes as the body's idempotency_key, and as the
308// Idempotency-Key header every mutation carries. Without files the body
309// is what it always was.
310func (c *Client) Send(ctx context.Context, token, text, key string, files []string) (Sent, error) {
311 var out Sent
312 var in any = map[string]string{"text": text, "idempotency_key": key}
313 if len(files) > 0 {
314 in = map[string]any{"text": text, "idempotency_key": key, "attachments": files}
315 }
316 _, err := c.call(ctx, http.MethodPost, assistant+"/messages", token, key, nil, in, &out)
317 return out, err
318}
319
320// Cancel stops a turn that has not ended.
321func (c *Client) Cancel(ctx context.Context, token, turnID, key string) error {
322 _, err := c.call(ctx, http.MethodPost, assistant+"/turns/"+url.PathEscape(turnID)+"/cancel", token, key, nil, struct{}{}, nil)
323 return err
324}
325
326// Answer answers card id with an option's value, at the card's revision.
327func (c *Client) Answer(ctx context.Context, token, id, choice string, revision int64, key string) (Answered, error) {
328 var out Answered
329 in := map[string]any{"choice": choice, "revision": revision}
330 _, err := c.call(ctx, http.MethodPost, assistant+"/cards/"+url.PathEscape(id)+"/answer", token, key, nil, in, &out)
331 return out, err
332}
333
334// CarryOnNow starts paused job card id again now, at the card's revision:
335// what "Carry on now" asks, offered while the card's CarryOn is set. The
336// answer is the card as it is now (200 {"card": …}); the same key again
337// gives the same answer. A 409 says why it cannot: card_stale (the card
338// moved on), not_paused or carry_on_unavailable. key goes as the body's
339// idempotency_key and the Idempotency-Key header.
340func (c *Client) CarryOnNow(ctx context.Context, token, id string, revision int64, key string) (Card, error) {
341 var out struct {
342 Card Card `json:"card"`
343 }
344 in := map[string]any{"revision": revision, "idempotency_key": key}
345 _, err := c.call(ctx, http.MethodPost, assistant+"/cards/"+url.PathEscape(id)+"/carry_on", token, key, nil, in, &out)
346 return out.Card, err
347}
348
349// RegisterHost tells Equipo where the person's Base operations live
350// (origin) and the token Base minted for them (hostToken), which the
351// Assistant presents when it calls them. A second call replaces the
352// first.
353func (c *Client) RegisterHost(ctx context.Context, token, origin, hostToken string) error {
354 in := map[string]string{"origin": origin, "token": hostToken}
355 _, err := c.call(ctx, http.MethodPut, assistant+"/host", token, NewKey(), nil, in, nil)
356 return err
357}
358
359// Events opens the person's event stream after cursor after ("" for from
360// now). It gives up when the headers take longer than StreamHeaderTimeout.
361// The caller reads and closes the body; cancelling ctx ends the stream.
362func (c *Client) Events(ctx context.Context, token, after string) (*http.Response, error) {
363 u := c.origin + assistant + "/events?" + JobStates
364 if after != "" {
365 u += "&after=" + url.QueryEscape(after)
366 }
367 ctx, cancel := context.WithCancel(ctx)
368 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
369 if err != nil {
370 cancel()
371 return nil, err
372 }
373 req.Header.Set("Accept", "text/event-stream")
374 req.Header.Set("Authorization", "Bearer "+token)
375 setCapabilities(ctx, req)
376 late := time.AfterFunc(c.StreamHeaderTimeout, cancel)
377 res, err := c.http.Do(req)
378 if !late.Stop() && err == nil {
379 res.Body.Close()
380 err = context.DeadlineExceeded
381 }
382 if err != nil {
383 cancel()
384 return nil, err
385 }
386 if res.StatusCode != http.StatusOK {
387 res.Body.Close()
388 cancel()
389 return nil, &Error{Status: res.StatusCode}
390 }
391 res.Body = cancelOnClose{res.Body, cancel}
392 return res, nil
393}
394
395type cancelOnClose struct {
396 io.ReadCloser
397 cancel context.CancelFunc
398}
399
400func (b cancelOnClose) Close() error {
401 b.cancel()
402 return b.ReadCloser.Close()
403}
404
405// OficinaConnect asks Equipo where the person consents to connecting their
406// Oficina account; they come back to returnTo.
407func (c *Client) OficinaConnect(ctx context.Context, token, returnTo string) (string, error) {
408 var out struct {
409 URL string `json:"url"`
410 }
411 in := map[string]string{"return_to": returnTo}
412 _, err := c.call(ctx, http.MethodPost, assistant+"/oficina/connect", token, NewKey(), nil, in, &out)
413 return out.URL, err
414}
415
416// OficinaFinish hands Equipo what the person came back with. The status is
417// connected, denied, expired or unavailable.
418func (c *Client) OficinaFinish(ctx context.Context, token, state, code string) (string, error) {
419 var out struct {
420 Status string `json:"status"`
421 }
422 in := map[string]string{"state": state, "code": code}
423 _, err := c.call(ctx, http.MethodPost, assistant+"/oficina/connect/finish", token, NewKey(), nil, in, &out)
424 return out.Status, err
425}
426