oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "slices"
8 "strings"
9 "unicode/utf8"
10
11 "amadan.net/oficina/equipo/internal/wire"
12 "gorm.io/gorm"
13)
14
15// Lanes (spec 2026-11-12-equipo-assistant-design.md §3, and the jobs
16// design's job threads). Every turn, message, event, card and tool call
17// is in one lane: empty is the person's own Coordinator conversation,
18// wire.LaneAssistant the Assistant, and job:<hand-off> a hand-off's own
19// Coordinator thread. Each lane queues and dispatches on its own, so all
20// run at once on the person's runner, and each lane's routes read only
21// its own rows: an id from another lane is unknown.
22
23// ErrNoRunner: the person has no primary runner, so nothing answers the
24// Assistant (409 no_runner).
25var ErrNoRunner = errors.New("chat: no runner")
26
27// personLane selects the person's own Coordinator conversation: what
28// /api/v1/* and /conversation read. Rows from before lanes have none.
29const personLane = "coalesce(lane, '') = ''"
30
31// coordinatorRole selects every Coordinator row of the person's: their
32// own conversation and every job thread. Coordinator logic (tools, cards
33// they answer, hand-offs, turn ends) reads it; their conversation never
34// does.
35const coordinatorRole = "(coalesce(lane, '') = '' OR lane LIKE 'job:%')"
36
37// LaneStore is the person API of one lane other than the Coordinator's.
38type LaneStore struct {
39 s *Store
40 lane string
41}
42
43// Lane is the store's view of lane.
44func (s *Store) Lane(lane string) *LaneStore { return &LaneStore{s: s, lane: lane} }
45
46// Send records a person message in the lane. Only a person whose primary
47// runner can carry the lane's turns may send (ErrNoRunner,
48// ErrRunnerTooOld); a message already sent answers as it did. The
49// Assistant's lane takes files too, as the Coordinator's does, but only
50// with a primary last seen at ProtocolAssistantFiles
51// (ErrAttachmentsUnavailable): never on a guess that fenceLanes would
52// fail later. Every other lane takes words only.
53func (l *LaneStore) Send(ctx context.Context, person string, in wire.SendMessage) (out wire.Sent, created bool, err error) {
54 files := len(in.Attachments) > 0
55 if in.Text = strings.TrimSpace(in.Text); in.Text == "" && !files || len(in.Text) > wire.MaxMessageBytes || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) || files && l.lane != wire.LaneAssistant || in.ProjectID != "" || !validKey(in.IdempotencyKey) {
56 return out, false, ErrInvalid
57 }
58 if err := checkFiles(in.Attachments); err != nil {
59 return out, false, err
60 }
61 key := in.IdempotencyKey
62 err = l.s.tx(ctx, func(t *txn) error {
63 if err := l.s.authority.CurrentPerson(ctx, t.db); err != nil {
64 return err
65 }
66 var sent int64
67 if err := t.db.Model(&messageRecord{}).Where("person = ? AND idempotency_key = ? AND coalesce(lane, '') = ?", person, key, l.lane).Count(&sent).Error; err != nil {
68 return err
69 }
70 if sent == 0 {
71 check := t.laneRunner
72 if files {
73 check = t.filesRunner
74 }
75 if err := check(person); err != nil {
76 return err
77 }
78 }
79 var err error
80 if out, created, err = t.sendOrigin(l.lane, person, key, in.Text, in.Attachments, originComposer, nil); err != nil || !created {
81 return err
82 }
83 return t.s.authority.Audit(t.db, person, auditAssistantSend, out.Message.ID)
84 })
85 return out, created, err
86}
87
88// The Assistant's writes are audited by id alone, never their words.
89const (
90 auditAssistantSend = "assistant.send"
91 auditAssistantAnswer = "assistant.answer"
92 auditAssistantCancel = "assistant.cancel"
93)
94
95// laneRunner refuses a person whose primary runner cannot carry an
96// Assistant turn: none, or one that last spoke an older protocol. A
97// primary never seen yet may; if it connects older, Connect fails its
98// turns (runner_too_old).
99func (t *txn) laneRunner(person string) error { return t.runnerAt(person, wire.ProtocolAssistant) }
100
101// jobRunner refuses a person whose primary runner cannot carry a job
102// thread's turns (protocol 22) as laneRunner does: fenceLanes fails them
103// if a primary never seen connects older.
104func (t *txn) jobRunner(person string) error { return t.runnerAt(person, wire.ProtocolJobs) }
105
106// runnerAt refuses a person with no primary, or one that last spoke a
107// protocol before least. A primary never seen yet may.
108func (t *txn) runnerAt(person string, least int) error {
109 protocol, seen, err := t.primaryProtocol(person)
110 if err != nil || !seen {
111 return err
112 }
113 if protocol < least {
114 return ErrRunnerTooOld
115 }
116 return nil
117}
118
119// ErrAttachmentsUnavailable: the person's primary runner cannot read the
120// Assistant's files (409 attachments_unavailable). Words still go.
121var ErrAttachmentsUnavailable = errors.New("chat: attachments unavailable")
122
123// filesRunner refuses an Assistant send with files unless the person's
124// primary was last seen at ProtocolAssistantFiles or later: none is
125// ErrNoRunner; one older, or never seen, is ErrAttachmentsUnavailable.
126// Stricter than runnerAt on purpose: a send with files is never taken on
127// a guess and then failed by fenceLanes. The snapshot's can_attach is
128// this check.
129func (t *txn) filesRunner(person string) error {
130 protocol, seen, err := t.primaryProtocol(person)
131 if err != nil {
132 return err
133 }
134 if !seen || protocol < wire.ProtocolAssistantFiles {
135 return ErrAttachmentsUnavailable
136 }
137 return nil
138}
139
140// primaryProtocol is the protocol the person's primary last spoke, and
141// whether it was ever seen. No primary is ErrNoRunner.
142func (t *txn) primaryProtocol(person string) (int, bool, error) {
143 primary, err := t.s.authority.PrimaryRunner(t.db, person)
144 if err != nil {
145 return 0, false, err
146 }
147 if primary == "" {
148 return 0, false, ErrNoRunner
149 }
150 var r runnerSessionRecord
151 err = t.db.Select("protocol").Where("runner_id = ?", primary).First(&r).Error
152 if errors.Is(err, gorm.ErrRecordNotFound) {
153 return 0, false, nil
154 }
155 if err != nil {
156 return 0, false, err
157 }
158 return r.Protocol, true, nil
159}
160
161// fenceLanes fails the person's turns in flight that their primary
162// cannot carry when it connects older: every lane but their own below
163// the Assistant's protocol, the job threads below protocol 22, and the
164// Assistant's turns with files below protocol 33 (wire.Encode would
165// refuse them). The runner would drop every frame of them. Their message
166// commands, and their files' attachment commands, leave the mailbox, so
167// none is ever sent; the lane's next turn then goes.
168func (t *txn) fenceLanes(l Lease) error {
169 if l.Protocol >= wire.ProtocolAssistantFiles || l.Role != wire.RolePrimary {
170 return nil
171 }
172 if primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person); err != nil || primary != l.Runner.RunnerID {
173 return err
174 }
175 lanes := assistantWithFiles
176 switch {
177 case l.Protocol < wire.ProtocolAssistant:
178 lanes = "coalesce(lane, '') <> ''"
179 case l.Protocol < wire.ProtocolJobs:
180 lanes = "lane LIKE 'job:%' OR " + assistantWithFiles
181 }
182 var rows []turnRecord
183 if err := t.db.Where("person = ? AND ("+lanes+") AND state IN ?", l.Runner.Person, wire.InFlight).Order("created_at, id").Find(&rows).Error; err != nil {
184 return err
185 }
186 next := map[string]bool{}
187 for i := range rows {
188 r := &rows[i]
189 if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", r.Person, wire.FrameMessage, `%"turn_id":"`+r.ID+`"%`).Update("acked_at", t.now()).Error; err != nil {
190 return err
191 }
192 var files []string
193 if err := t.db.Model(&fileRecord{}).Where("person = ? AND message_id IN (SELECT id FROM chat_messages WHERE turn_id = ?)", r.Person, r.ID).Pluck("id", &files).Error; err != nil {
194 return err
195 }
196 for _, id := range files {
197 // Ids are at_ and [a-z0-9]: nothing in them is a LIKE pattern.
198 if err := t.db.Model(&commandRecord{}).Where("person = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", r.Person, wire.FrameAttachment, `%"id":"`+id+`"%`).Update("acked_at", t.now()).Error; err != nil {
199 return err
200 }
201 }
202 r.State, r.Reason = wire.TurnFailed, reasonRunnerTooOld
203 if err := t.saveTurn(r); err != nil {
204 return err
205 }
206 next[r.Lane] = true
207 }
208 if next[wire.LaneAssistant] {
209 return t.dispatchNext(l.Runner.Person, wire.LaneAssistant)
210 }
211 return nil
212}
213
214// assistantWithFiles selects the Assistant's turns whose messages carry
215// files.
216const assistantWithFiles = "lane = '" + wire.LaneAssistant + "' AND EXISTS (SELECT 1 FROM chat_messages m JOIN chat_attachments a ON a.message_id = m.id WHERE m.turn_id = chat_turns.id)"
217
218// reasonRunnerTooOld ends a lane turn its runner cannot carry.
219const reasonRunnerTooOld = "runner_too_old"
220
221// Messages pages the lane's history backwards from before, oldest first.
222func (l *LaneStore) Messages(ctx context.Context, person, before string, limit int) (wire.MessagePage, error) {
223 return l.s.messages(ctx, l.lane, person, before, limit)
224}
225
226// Events reads the lane's events after cursor (the cursor every lane
227// shares).
228func (l *LaneStore) Events(ctx context.Context, person string, after int64, limit int) ([]wire.Event, error) {
229 return l.s.events(ctx, l.lane, person, after, limit)
230}
231
232// Cancel asks for one of the lane's turns to end.
233func (l *LaneStore) Cancel(ctx context.Context, person, id string) (int64, wire.Turn, error) {
234 return l.s.cancel(ctx, l.lane, person, id)
235}
236
237// Snapshot reads the lane as a client first shows it, and whether the
238// person's runner can answer in it.
239func (l *LaneStore) Snapshot(ctx context.Context, person string) (out wire.AssistantSnapshot, err error) {
240 err = l.s.read(ctx, func(tx *gorm.DB) error {
241 if err := l.s.authority.CurrentPerson(ctx, tx); err != nil {
242 return err
243 }
244 var e error
245 if out.Me, e = l.s.authority.Me(tx, person); e != nil {
246 return e
247 }
248 if out.Cursor, e = maxEvent(tx); e != nil {
249 return e
250 }
251 if out.Messages, out.Turns, e = laneTail(tx, l.lane, person); e != nil {
252 return e
253 }
254 t := &txn{s: l.s, db: tx}
255 switch e = t.laneRunner(person); {
256 case e == nil:
257 out.Available = true
258 case !errors.Is(e, ErrNoRunner) && !errors.Is(e, ErrRunnerTooOld):
259 return e
260 }
261 if l.lane == wire.LaneAssistant {
262 switch e = t.filesRunner(person); {
263 case e == nil:
264 out.CanAttach = true
265 case !errors.Is(e, ErrNoRunner) && !errors.Is(e, ErrAttachmentsUnavailable):
266 return e
267 }
268 }
269 rows, e := t.laneCards(person, l.lane)
270 if e == nil && l.lane == wire.LaneAssistant {
271 rows, e = t.withActiveJobs(person, rows)
272 }
273 if e != nil {
274 return e
275 }
276 out.Cards = make([]wire.AssistantCard, 0, len(rows))
277 for i := len(rows) - 1; i >= 0; i-- {
278 v, e := t.assistantCardView(rows[i])
279 if e != nil {
280 return e
281 }
282 out.Cards = append(out.Cards, v)
283 }
284 return nil
285 })
286 return out, err
287}
288
289// withActiveJobs is the Assistant lane's newest cards (rows, newest
290// first) with every unfinished job card (working, asking, ready, or
291// stopped short of the end) and
292// each card open under one (D2), however old, newest first: newer cards
293// never push a job that still moves, or its go-ahead, off the snapshot.
294func (t *txn) withActiveJobs(person string, rows []cardRecord) ([]cardRecord, error) {
295 // Ruling R27: stopped too while its request is not cancelled and a
296 // task it follows is unfinished (a research approval, a retry).
297 active := t.db.Model(&cardRecord{}).Select("handoff_id").Where("person = ? AND lane = ? AND kind = ?", person, wire.LaneAssistant, wire.CardJob).
298 Where("(state IN ? OR state = ? AND handoff_id IN (SELECT h.id FROM chat_handoffs h JOIN chat_handoff_tasks ht ON ht.handoff_id = h.id JOIN chat_tasks k ON k.id = ht.task_id WHERE h.state <> ? AND k.stage NOT IN ?))",
299 []string{wire.JobWorking, wire.JobAsking, wire.JobReady}, wire.JobStopped, handoffCancelled, []string{wire.StageDone, wire.StageCancelled})
300 var more []cardRecord
301 err := t.db.Where("person = ? AND lane = ? AND (held IS NULL OR held = ?)", person, wire.LaneAssistant, false).
302 Where("(kind = ? OR state = ? AND coalesce(source_card, '') <> '') AND handoff_id IN (?)", wire.CardJob, wire.CardOpen, active).
303 Find(&more).Error
304 if err != nil {
305 return nil, err
306 }
307 for _, c := range more {
308 if !slices.ContainsFunc(rows, func(r cardRecord) bool { return r.ID == c.ID }) {
309 rows = append(rows, c)
310 }
311 }
312 slices.SortStableFunc(rows, func(a, b cardRecord) int {
313 if c := b.CreatedAt.Compare(a.CreatedAt); c != 0 {
314 return c
315 }
316 return strings.Compare(b.ID, a.ID)
317 })
318 return rows, nil
319}
320
321// Answer answers one of the lane's question cards. The answer becomes
322// the person's next message in the lane. A stale revision or a card
323// already answered is a conflict carrying the card as it is. A job card
324// is nobody's to answer: not found, as any card that asks nothing.
325func (l *LaneStore) Answer(ctx context.Context, person, id string, in wire.AnswerCard) (out wire.AssistantAnswered, current wire.AssistantCard, err error) {
326 in.Choice = strings.TrimSpace(in.Choice)
327 if in.Choice == "" || len(in.Choice) > wire.MaxMessageBytes || !utf8.ValidString(in.Choice) || strings.ContainsRune(in.Choice, 0) || in.Note != "" {
328 return out, current, ErrInvalid
329 }
330 err = l.s.tx(ctx, func(t *txn) error {
331 if err := l.s.authority.CurrentPerson(ctx, t.db); err != nil {
332 return err
333 }
334 var c cardRecord
335 if err := t.db.Where("id = ? AND person = ? AND coalesce(lane, '') = ?", id, person, l.lane).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) {
336 return ErrNotFound
337 } else if err != nil {
338 return err
339 }
340 if c.SourceCard != "" {
341 // A team card's: answered through its own path.
342 var e error
343 out, current, e = t.answerOutcome(person, c, in)
344 return e
345 }
346 if c.Kind != wire.CardQuestion {
347 return ErrNotFound
348 }
349 if c.State != wire.CardOpen || c.Revision != in.Revision {
350 v, err := t.assistantCardView(c)
351 if err != nil {
352 return err
353 }
354 current = v
355 return ErrCardConflict
356 }
357 var options []string
358 _ = json.Unmarshal([]byte(c.Options), &options)
359 if len(options) > 0 && !slices.Contains(options, in.Choice) {
360 return ErrInvalid
361 }
362 // The answer is a new message in the lane: it needs a runner that
363 // can carry it, now (the primary may have gone, or come back older,
364 // since the card was raised).
365 if err := t.laneRunner(person); err != nil {
366 return err
367 }
368 origin := originGenerated
369 if len(options) == 0 {
370 origin = originComposer
371 }
372 sent, _, err := t.sendOrigin(l.lane, person, "card:"+c.ID, in.Choice, nil, origin, func(m messageRecord) error {
373 c.State, c.Choice, c.AnswerMessage = wire.CardAnswered, in.Choice, m.ID
374 return t.saveCard(&c)
375 })
376 if err != nil {
377 return err
378 }
379 if err := t.s.authority.Audit(t.db, person, auditAssistantAnswer, c.ID); err != nil {
380 return err
381 }
382 out.Card, err = t.assistantCardView(c)
383 out.Message, out.Turn = sent.Message, sent.Turn
384 return err
385 })
386 return out, current, err
387}
388
389// assistantCardView is a card as the Assistant's lane shows it: generic
390// fields only, Options and Links never null. A question's options are
391// their own labels; its result is the person's answer. A card pointing
392// at a team card keeps its own options, links and result (outcome.go); a
393// job card its status, detail and links, with its start (jobs.go).
394func (t *txn) assistantCardView(c cardRecord) (wire.AssistantCard, error) {
395 v := wire.AssistantCard{ID: c.ID, Revision: c.Revision, Kind: c.Kind, State: c.State, Question: c.Question, Options: []wire.CardOption{}, Links: []wire.CardLink{}, Result: c.Choice}
396 if c.SourceCard != "" {
397 if err := t.mirrorView(&v, c); err != nil {
398 return v, err
399 }
400 return v, t.goLiveOptions(&v, c.Person)
401 }
402 if c.Kind == wire.CardJob {
403 return v, t.jobCardView(&v, c)
404 }
405 if c.Kind == wire.CardConnect {
406 return v, connectCardView(&v, c)
407 }
408 var options []string
409 if c.Options != "" {
410 if err := json.Unmarshal([]byte(c.Options), &options); err != nil {
411 return v, err
412 }
413 }
414 for _, o := range options {
415 v.Options = append(v.Options, wire.CardOption{Value: o, Label: o})
416 }
417 return v, nil
418}
419
420// assistTool serves an Assistant turn's tools: ask_person and the
421// notebook. look, describe and use call a provider, outside the
422// transaction (remoteCall), so never reach here; every Coordinator tool
423// is unknown here. A team_update turn only looks and tells.
424func (t *txn) assistTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) {
425 if r.Kind == wire.TurnTeamUpdate && !slices.Contains(wire.TeamUpdateTools, v.Name) {
426 return refused("unknown_tool", toolUnknown), nil
427 }
428 switch v.Name {
429 case wire.ToolAskPerson:
430 return t.askTool(r, v)
431 case wire.ToolWriteNote, wire.ToolReadNotes:
432 return noteTool(v), nil
433 }
434 return refused("unknown_tool", toolUnknown), nil
435}
436
437// turnLane is the lane of one of the person's turns ("" when unknown).
438func (t *txn) turnLane(person, turn string) (string, error) {
439 var lanes []string
440 err := t.db.Model(&turnRecord{}).Where("id = ? AND person = ?", turn, person).Pluck("coalesce(lane, '')", &lanes).Error
441 if err != nil || len(lanes) == 0 {
442 return "", err
443 }
444 return lanes[0], nil
445}
446