oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package conversation
2
3import (
4 "amadan.net/oficina/equipo/internal/equipo/conversation/chatstate"
5 "context"
6 "crypto/rand"
7 "encoding/json"
8 "strconv"
9 "time"
10
11 "amadan.net/oficina/equipo/internal/coordinator"
12 "amadan.net/oficina/equipo/internal/equipo/ownermode"
13 "amadan.net/oficina/equipo/internal/equipo/planning"
14 "amadan.net/oficina/equipo/internal/equipo/team"
15 "amadan.net/oficina/equipo/internal/runnerproto"
16 "gorm.io/gorm"
17)
18
19type CoordinatorToolCall = runnerproto.CoordinatorToolCall
20type CoordinatorToolResult = runnerproto.CoordinatorToolResult
21
22type ToolOperations struct {
23 Planning func(*gorm.DB) *planning.Store
24 AmbiguousProject string
25 ProjectHeading string
26}
27
28func (e *Engine) readToolTask(tx *gorm.DB, person, id string, sel runnerproto.Selection) (int64, any, error) {
29 var t planning.Task
30 if err := tx.First(&t, "id=?", id).Error; err != nil {
31 return 0, nil, e.StoreError(err)
32 }
33 if _, err := e.CheckProject(tx, person, t.ProjectID, sel); err != nil {
34 return 0, nil, err
35 }
36 plan, err := e.Tools.Planning(tx).Plan(t)
37 return t.Revision, map[string]any{"id": t.ID, "description": t.Description, "state": t.State, "project_id": t.ProjectID, "revision": t.Revision, "plan": plan}, err
38}
39func result(id string, revision int64, value any) (CoordinatorToolResult, error) {
40 raw, err := json.Marshal(value)
41 if len(raw) > 65536 {
42 return CoordinatorToolResult{}, runnerproto.ErrInvalid
43 }
44 return CoordinatorToolResult{ResourceID: id, Revision: revision, Value: raw}, err
45}
46func (e *Engine) CallCoordinatorTool(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, call CoordinatorToolCall) (CoordinatorToolResult, error) {
47 call, err := coordinator.Canonical(call)
48 if err != nil {
49 return CoordinatorToolResult{}, err
50 }
51 args, _ := coordinator.Validate(call)
52 var out CoordinatorToolResult
53 err = e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
54 b, row, err := e.validateCoordinatorClaim(ctx, tx, p, c)
55 if err != nil {
56 return err
57 }
58 if row.State != "running" || row.ProviderSessionID == "" {
59 return e.Conflict
60 }
61 if err = e.Core.ValidateHandle(ctx, c.Scope, c.Handle); err != nil {
62 return err
63 }
64 cs := e.Conversation(tx)
65 actor := Actor{Address: b.Person}
66 // Scope and policy checks also run on replay, before saved content is returned.
67 if err = e.toolScope(tx, cs, row, c.Brief.Selection, args); err != nil {
68 return err
69 }
70 m := Mutation{RequestID: call.RequestID}
71 resource := toolResource(c, row)
72 if ok, err := cs.CoordinatorReplay(actor, "coordinator.tool", resource, m, call, &out); ok || err != nil {
73 return err
74 }
75 var count int64
76 if err = tx.Model(&requestRecord{}).Where("principal=? AND operation='coordinator.tool' AND resource=?", actor.Address, resource).Count(&count).Error; err != nil {
77 return err
78 }
79 if count >= 128 {
80 return e.Invalid
81 }
82 switch a := args.(type) {
83 case *coordinator.EquipoStatus:
84 projects, readErr := e.projects(tx, b.Person, c.Brief.Selection)
85 if readErr != nil {
86 return readErr
87 }
88 status, readErr := ownermode.Status(ctx, tx, e.Core, b.CoordinatorBinding, b.TeamID, e.Now(), projects, row.State)
89 if readErr != nil {
90 return readErr
91 }
92 out, err = result(b.ID, b.Revision, status)
93 if err != nil {
94 return err
95 }
96 case *coordinator.ProposeProject:
97 safe := *a
98 if err = json.Unmarshal(e.Redact(mustCoordinatorJSON(a)), &safe); err != nil {
99 return err
100 }
101 out, err = cs.proposeProject(row, safe, e.Tools.ProjectHeading)
102 if err != nil {
103 return err
104 }
105 case *coordinator.ReadProject:
106 rev, source, err := e.Project(tx, p.Person, a.ProjectID, c.Brief.Selection)
107 if err != nil {
108 return err
109 }
110 source.Payload = e.Redact(source.Payload)
111 source.Ref.Hash = team.ContentDigest(source.Payload)
112 out, err = result(strconv.FormatInt(a.ProjectID, 10), rev, source)
113 if err != nil {
114 return err
115 }
116 case *coordinator.ReadTask:
117 source, err := e.toolTaskSource(tx, p.Person, a.TaskID, c.Brief.Selection)
118 if err != nil {
119 return err
120 }
121 out, err = result(a.TaskID, source.Ref.Revision, source)
122 if err != nil {
123 return err
124 }
125 case *coordinator.ProposePlan:
126 if a.Plan.ProjectID == 0 {
127 projects, projectErr := e.projects(tx, p.Person, c.Brief.Selection)
128 if projectErr != nil {
129 return projectErr
130 }
131 options := []coordinator.QuestionOption{}
132 for _, project := range projects {
133 if len(options) == 32 {
134 break
135 }
136 options = append(options, coordinator.QuestionOption{ID: strconv.FormatInt(project.ID, 10), Label: project.Label})
137 }
138 out, err = cs.ask(row, call.RequestID, coordinator.AskPerson{MessageID: a.MessageID, Question: e.Tools.AmbiguousProject, Options: options}, e.Now())
139 if err != nil {
140 return err
141 }
142 } else {
143 plan, err := e.Tools.Planning(tx).ProposeCoordinator(planning.DelegatedPrincipal{BindingID: b.ID, Person: b.Person}, a.Plan.TaskPlan(), Mutation{RequestID: resource + ":" + call.RequestID}, func(tx *gorm.DB, _ Actor, kind, id string) error { return e.Audit(tx, b, kind, id) })
144 if err != nil {
145 return err
146 }
147 var card cardRecord
148 var thread Thread
149 if err = tx.Where("stream_id=? AND resource_id=? AND kind='task'", row.ConversationID, plan.TaskID).First(&card).Error; err != nil {
150 return err
151 }
152 if err = tx.Model(&messageRecord{}).Where("id=?", card.ID).Select("author_kind", "author_id").Updates(map[string]any{"author_kind": "coordinator", "author_id": "coordinator:" + b.ID}).Error; err != nil {
153 return err
154 }
155 if err = tx.Where("task_id=?", plan.TaskID).First(&thread).Error; err != nil {
156 return err
157 }
158 out, err = result(plan.TaskID, plan.Revision, map[string]any{"plan": plan, "card_id": card.ID, "thread_id": thread.ID, "message_id": a.MessageID, "author": "coordinator:" + b.ID, "delegating_person": b.Person})
159 if err != nil {
160 return err
161 }
162 }
163 case *coordinator.AskPerson:
164 safe := *a
165 if err = json.Unmarshal(e.Redact(mustCoordinatorJSON(a)), &safe); err != nil {
166 return err
167 }
168 out, err = cs.ask(row, call.RequestID, safe, e.Now())
169 if err != nil {
170 return err
171 }
172 case *coordinator.RouteToTask:
173 routed := *cs
174 routed.deps = cs.deps
175 routed.deps.Audit = func(tx *gorm.DB, _ Actor, kind, id string) error { return e.Audit(tx, b, kind, id) }
176 msg, err := routed.RouteMessage(actor, a.MessageID, a.TaskID, Mutation{RequestID: resource + ":" + call.RequestID})
177 if err != nil {
178 return err
179 }
180 out, err = result(msg.ID, msg.Revision, msg)
181 if err != nil {
182 return err
183 }
184 case *coordinator.PostMessage:
185 var body string
186 if err = json.Unmarshal(e.Redact(mustCoordinatorJSON(a.Body)), &body); err != nil {
187 return err
188 }
189 msg, err := cs.appendMessage(row.ConversationID, row.ConversationID, "", "coordinator", "coordinator:"+b.ID, body, "commentary")
190 if err != nil {
191 return err
192 }
193 if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("reply_message_id").Updates(map[string]any{"reply_message_id": msg.ID}).Error; err != nil {
194 return err
195 }
196 if err = chatstate.AnchorProjects(tx, row.Person, row.BindingID, row.Generation, row.ConversationID, msg.Body, msg.Sequence); err != nil {
197 return err
198 }
199 msg.SourceRefs = a.SourceRefs
200 if err = tx.Model(&messageRecord{}).Where("id=?", msg.ID).Select("source_refs").Updates(map[string]any{"source_refs": string(mustCoordinatorJSON(a.SourceRefs))}).Error; err != nil {
201 return err
202 }
203 out, err = result(msg.ID, msg.Revision, map[string]any{"message": msg, "source_refs": a.SourceRefs})
204 if err != nil {
205 return err
206 }
207 case *coordinator.SuggestPreference, *coordinator.SuggestDraft:
208 out, err = cs.suggest(row, call.Name, json.RawMessage(e.Redact(mustCoordinatorJSON(args))))
209 if err != nil {
210 return err
211 }
212 default:
213 return e.Invalid
214 }
215 if err = e.Audit(tx, b, "coordinator.tool."+call.Name, out.ResourceID); err != nil {
216 return err
217 }
218 var audits []int64
219 if err = tx.Table("audit_events").Where("actor=? AND record_id=?", "coordinator:"+b.ID, out.ResourceID).Order("id").Limit(128).Pluck("id", &audits).Error; err != nil {
220 return err
221 }
222 out.Value, err = json.Marshal(map[string]any{"tool": call.Name, "result": out.Value, "audit_ids": audits})
223 if err != nil || len(out.Value) > 65536 {
224 return e.Invalid
225 }
226 return cs.SaveCoordinatorResult(actor, "coordinator.tool", resource, m, call, out)
227 })
228 return out, err
229}
230func (e *Engine) toolScope(tx *gorm.DB, cs *Store, row TurnRecord, sel runnerproto.Selection, args any) error {
231 message := func(id string) error {
232 var msg messageRecord
233 if err := tx.Where("id=? AND conversation_id=? AND author_kind='person' AND author_id=?", id, row.ConversationID, row.Person).First(&msg).Error; err != nil {
234 return e.StoreError(err)
235 }
236 // Prior requests are not silently repurposed by a later admitted turn.
237 if id != row.MessageID {
238 return e.Forbidden
239 }
240 return nil
241 }
242 project := func(id int64) error { _, err := e.CheckProject(tx, row.Person, id, sel); return err }
243 task := func(id string) error {
244 if e.Tools.Planning == nil {
245 return e.Unavailable
246 }
247 _, _, err := e.readToolTask(tx, row.Person, id, sel)
248 return err
249 }
250 switch a := args.(type) {
251 case *coordinator.ProposeProject:
252 return checkReported(tx, row.Person, a.Repository, e.Invalid)
253 case *coordinator.ReadProject:
254 return project(a.ProjectID)
255 case *coordinator.ReadTask:
256 return task(a.TaskID)
257 case *coordinator.ProposePlan:
258 if err := message(a.MessageID); err != nil {
259 return err
260 }
261 if a.Plan.ProjectID > 0 {
262 return project(a.Plan.ProjectID)
263 }
264 case *coordinator.AskPerson:
265 return message(a.MessageID)
266 case *coordinator.RouteToTask:
267 if err := message(a.MessageID); err != nil {
268 return err
269 }
270 return task(a.TaskID)
271 case *coordinator.SuggestPreference:
272 return message(a.SourceMessageID)
273 case *coordinator.SuggestDraft:
274 for _, id := range a.SourceMessageIDs {
275 if err := message(id); err != nil {
276 return err
277 }
278 }
279 case *coordinator.PostMessage:
280 for _, ref := range a.SourceRefs {
281 var source runnerproto.SourceSnapshot
282 var err error
283 switch ref.Kind {
284 case "project":
285 id, parseErr := strconv.ParseInt(ref.ID, 10, 64)
286 if parseErr != nil || id <= 0 {
287 return e.Invalid
288 }
289 _, source, err = e.Project(tx, row.Person, id, sel)
290 if err == nil {
291 source.Payload = e.Redact(source.Payload)
292 source.Ref.Hash = team.ContentDigest(source.Payload)
293 }
294 case "task":
295 source, err = e.toolTaskSource(tx, row.Person, ref.ID, sel)
296 default:
297 return e.Invalid
298 }
299 if err != nil {
300 return err
301 }
302 if ref != source.Ref {
303 return e.Conflict
304 }
305 }
306 }
307 return nil
308}
309func (s *Store) ask(row TurnRecord, request string, a coordinator.AskPerson, now time.Time) (CoordinatorToolResult, error) {
310 var pending []QuestionRecord
311 if err := s.tx.Where("binding_id=? AND generation=? AND state='pending' AND turn_id IN (SELECT id FROM coordinator_turns WHERE conversation_id=?)", row.BindingID, row.Generation, row.ConversationID).Find(&pending).Error; err != nil {
312 return CoordinatorToolResult{}, err
313 }
314 var duplicate *coordinator.ClarificationQuestion
315 for _, old := range pending {
316 var q coordinator.ClarificationQuestion
317 if err := json.Unmarshal([]byte(old.Payload), &q); err != nil {
318 return CoordinatorToolResult{}, err
319 }
320 if old.TurnID == row.ID && q.Prompt == a.Question && runnerproto.EventHash(q.Options) == runnerproto.EventHash(a.Options) && now.Before(q.ExpiresAt) && duplicate == nil {
321 duplicate = &q
322 continue
323 }
324 q.State, q.Revision = "superseded", old.Revision+1
325 if err := s.tx.Model(&QuestionRecord{}).Where("id=?", q.ID).Select("state", "revision", "payload").Updates(map[string]any{"state": q.State, "revision": q.Revision, "payload": string(mustCoordinatorJSON(q))}).Error; err != nil {
326 return CoordinatorToolResult{}, err
327 }
328 if err := s.tx.Model(&cardRecord{}).Where("resource_id=? AND kind='clarification'", q.ID).Select("revision").Updates(map[string]any{"revision": q.Revision}).Error; err != nil {
329 return CoordinatorToolResult{}, err
330 }
331 }
332 if duplicate != nil {
333 return result(duplicate.ID, duplicate.Revision, duplicate)
334 }
335 q := coordinator.ClarificationQuestion{ID: rand.Text(), MessageID: a.MessageID, TurnID: row.ID, Prompt: a.Question, Options: a.Options, State: "pending", Revision: 1, Generation: row.Generation, ExpiresAt: now.Add(24 * time.Hour)}
336 raw, err := json.Marshal(q)
337 if err != nil {
338 return CoordinatorToolResult{}, err
339 }
340 rec := QuestionRecord{ID: q.ID, BindingID: row.BindingID, TurnID: row.ID, Person: row.Person, RequestID: request, State: q.State, Payload: string(raw), Generation: row.Generation, Revision: 1}
341 if err = s.tx.Create(&rec).Error; err != nil {
342 return CoordinatorToolResult{}, err
343 }
344 msg, err := s.appendMessage(row.ConversationID, row.ConversationID, "", "coordinator", "coordinator:"+row.BindingID, a.Question, "clarification")
345 if err != nil {
346 return CoordinatorToolResult{}, err
347 }
348 if err = s.tx.Create(&cardRecord{ID: msg.ID, StreamID: row.ConversationID, Kind: "clarification", ResourceID: q.ID, Revision: 1, Sequence: msg.Sequence}).Error; err != nil {
349 return CoordinatorToolResult{}, err
350 }
351 return result(q.ID, 1, q)
352}
353func (s *Store) suggest(row TurnRecord, kind string, value any) (CoordinatorToolResult, error) {
354 raw, err := json.Marshal(value)
355 if err != nil {
356 return CoordinatorToolResult{}, err
357 }
358 msg, err := s.appendMessage(row.ConversationID, row.ConversationID, "", "coordinator", "coordinator:"+row.BindingID, string(raw), "suggestion")
359 if err != nil {
360 return CoordinatorToolResult{}, err
361 }
362 if err = s.tx.Create(&cardRecord{ID: msg.ID, StreamID: row.ConversationID, Kind: kind, ResourceID: msg.ID, Revision: 1, Sequence: msg.Sequence}).Error; err != nil {
363 return CoordinatorToolResult{}, err
364 }
365 return result(msg.ID, 1, value)
366}
367func (s *Store) AnswerClarification(actor Actor, id, optionID, text string, m Mutation, now time.Time) error {
368 b, err := s.Binding(actor)
369 if err != nil {
370 return err
371 }
372 var rec QuestionRecord
373 if err = s.tx.Where("id=? AND binding_id=? AND person=?", id, b.ID, actor.Address).First(&rec).Error; err != nil {
374 return s.deps.NotFound
375 }
376 var q coordinator.ClarificationQuestion
377 if err = json.Unmarshal([]byte(rec.Payload), &q); err != nil {
378 return err
379 }
380 var turn TurnRecord
381 if err = s.tx.First(&turn, "id=?", rec.TurnID).Error; err != nil {
382 return err
383 }
384 if rec.Generation != b.Generation || turn.Generation != b.Generation || (turn.State != "running" && turn.State != "delivered") || !now.Before(q.ExpiresAt) {
385 return s.deps.Conflict
386 }
387 input := struct {
388 Option, Text string
389 Revision int64
390 }{optionID, text, m.Revision}
391 var saved struct{ MessageID, TurnID string }
392 if ok, err := s.CoordinatorReplay(actor, "clarification.answer", id, m, input, &saved); ok || err != nil {
393 return err
394 }
395 if rec.State != "pending" || m.Revision != rec.Revision {
396 return s.deps.Conflict
397 }
398 body := text
399 if optionID != "" {
400 if text != "" {
401 return s.deps.Invalid
402 }
403 found := false
404 for _, o := range q.Options {
405 if o.ID == optionID {
406 body = o.Label
407 found = true
408 }
409 }
410 if !found {
411 return s.deps.Invalid
412 }
413 } else if !coordinator.Text(text, 8192) {
414 return s.deps.Invalid
415 }
416 q.State = "answered"
417 q.Revision++
418 raw, err := json.Marshal(q)
419 if err != nil {
420 return err
421 }
422 if err = s.tx.Model(&QuestionRecord{}).Where("id=?", id).Select("state", "revision", "payload").Updates(map[string]any{"state": q.State, "revision": q.Revision, "payload": string(raw)}).Error; err != nil {
423 return err
424 }
425 if err = s.tx.Model(&cardRecord{}).Where("resource_id=? AND kind='clarification'", id).Select("revision").Updates(map[string]any{"revision": q.Revision}).Error; err != nil {
426 return err
427 }
428 msg, err := s.appendMessage(turn.ConversationID, turn.ConversationID, "", "person", actor.Address, body, "coordinator")
429 if err != nil {
430 return err
431 }
432 next, err := s.QueueCoordinator(actor, msg.ID, turn.ProjectID, Mutation{RequestID: "clarification:" + id})
433 if err != nil {
434 return err
435 }
436 if err = s.deps.Audit(s.tx, actor, "clarification.answer", id); err != nil {
437 return err
438 }
439 saved.MessageID, saved.TurnID = msg.ID, next.ID
440 return s.SaveCoordinatorResult(actor, "clarification.answer", id, m, input, saved)
441}
442
443func (e *Engine) toolTaskSource(tx *gorm.DB, person, id string, sel runnerproto.Selection) (runnerproto.SourceSnapshot, error) {
444 rev, value, err := e.readToolTask(tx, person, id, sel)
445 if err != nil {
446 return runnerproto.SourceSnapshot{}, err
447 }
448 raw, err := json.Marshal(value)
449 if err != nil {
450 return runnerproto.SourceSnapshot{}, err
451 }
452 raw = e.Redact(raw)
453 return runnerproto.SourceSnapshot{Ref: team.SourceRef{Kind: "task", ID: id, Revision: rev, Hash: team.ContentDigest(raw)}, Payload: raw}, nil
454}
455