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 "log/slog"
8 "net"
9 "net/url"
10 "regexp"
11 "slices"
12 "strconv"
13 "strings"
14 "sync"
15 "time"
16 "unicode/utf8"
17
18 "amadan.net/oficina/equipo/internal/equipo/assist"
19 "amadan.net/oficina/equipo/internal/wire"
20 "gorm.io/gorm"
21 "gorm.io/plugin/dbresolver"
22)
23
24// The Assistant's look, describe and use (spec §4) call a provider, which
25// may be another host: never inside a transaction. The tool call's
26// transaction authorises the call against the turn and roster, as every
27// tool's does, and stores it pending; ServeRemoteCalls makes the call
28// and, in one transaction, stores the result, marks it done, audits it
29// and queues it for the runner, only while the turn still runs at that
30// attempt.
31//
32// A use is held to the turn's ledger: its ledger key is the turn,
33// operation and input. A second call with the same key in the turn, by
34// another call id or in a later attempt, is answered with the first's
35// result, replayed, or waits for it while it is out; the provider is
36// called once. A failure is not in the ledger: a later call runs again.
37// Nor is a read (Ruling R11): the ledger stops a write being made twice,
38// not a read seeing what changed since, so a read-only operation runs
39// again on each new call id (a call waiting on one runs once it is
40// done); only a delivery retry of the same call id gets what it got.
41// The provider gets the key's UUIDv5 (assist.Key), never a call id.
42
43// Operations is the registry behind look, describe and use: the four
44// methods of *assist.Registry.
45type Operations interface {
46 Look(ctx context.Context, person, query string) (string, error)
47 Describe(ctx context.Context, person, operation string) (assist.Operation, error)
48 Invoke(ctx context.Context, person, operation string, input json.RawMessage, key string) (json.RawMessage, error)
49 Forget(person string)
50}
51
52// SetOperations sets the Assistant's registry.
53func (s *Store) SetOperations(o Operations) { s.ops.Store(&o) }
54
55func (s *Store) operations() Operations {
56 if p := s.ops.Load(); p != nil {
57 return *p
58 }
59 return nil
60}
61
62// The states of an Assistant call to a provider (toolCallRecord.State).
63const (
64 callPending = "pending"
65 callWaiting = "waiting"
66 callDone = "done"
67)
68
69const (
70 auditAssistantUse = "assistant.use"
71 auditAssistantHost = "assistant.host"
72 // hostDomain binds a sealed host token to its use.
73 hostDomain = "assistant.host"
74 // remotePoll is how often ServeRemoteCalls looks for calls it was not
75 // woken for: one a restart left, or another process stored.
76 remotePoll = 5 * time.Second
77 // remoteParallel bounds the calls out at once.
78 remoteParallel = 8
79 // toolFrame is the most a result may take as a tool_result frame,
80 // inside the runner's 64 KB tool frame with room for the call id and
81 // person around it.
82 toolFrame = 63 << 10
83)
84
85// ErrHostNotAllowed: the origin is not on EQUIPO_ASSISTANT_HOSTS (403
86// host_not_allowed).
87var ErrHostNotAllowed = errors.New("chat: host not allowed")
88
89// ErrHostUnverified: Base did not honour the offered token (409
90// host_unverified); ErrHostElsewhere: the person's Base is another one,
91// which still honours them (409 host_elsewhere). Either way the earlier
92// registration and board stand (spec 2026-11-26-assistant-abilities §5.3).
93var (
94 ErrHostUnverified = errors.New("chat: host unverified")
95 ErrHostElsewhere = errors.New("chat: host elsewhere")
96)
97
98// assistantHostRecord is where a person's Base operations live, with the
99// token Base minted for them, sealed.
100type assistantHostRecord struct {
101 Person string `gorm:"primaryKey"`
102 Origin string
103 Token string
104 Revision int64
105 UpdatedAt time.Time
106 // Capabilities is the newest Base-Capabilities the person's Base
107 // sent (noteCapabilities): presentation only, never authority.
108 Capabilities string
109}
110
111func (assistantHostRecord) TableName() string { return "chat_assistant_hosts" }
112
113// SetHost registers the person's Base host, replacing any before: an
114// https origin with no path (http on loopback), on the operator's
115// allowlist, and a token of 20 to 512 visible ASCII characters. The
116// token is stored sealed and never given back. It counts only once Base
117// honours it (spec 2026-11-26-assistant-abilities §5.3): the board is
118// fetched with it first, outside the transaction, and the host and the
119// board are committed together on a 200, or on a legacy Base's 404 with
120// its operations' 200 while that origin has never answered the board.
121// Anything else is ErrHostUnverified. A person moves to another origin
122// only once the one they have no longer honours them (its last answer a
123// 401) or the operator has taken it off the list; else ErrHostElsewhere.
124func (l *LaneStore) SetHost(ctx context.Context, person string, in wire.AssistantHost) (out wire.AssistantHost, err error) {
125 origin, ok := hostOrigin(in.Origin)
126 if !ok || !hostToken(in.Token) {
127 return out, ErrInvalid
128 }
129 if !slices.Contains(l.s.authority.AssistantHosts, origin) {
130 return out, ErrHostNotAllowed
131 }
132 if l.s.authority.Seal == nil {
133 return out, ErrUnavailable
134 }
135 sealed, err := l.s.authority.Seal(hostDomain, in.Token)
136 if err != nil {
137 return out, err
138 }
139 m := l.s.personLock(person)
140 m.Lock()
141 defer m.Unlock()
142 var seen []bool
143 if err := l.s.read(ctx, func(tx *gorm.DB) error {
144 t := &txn{s: l.s, ctx: ctx, db: tx}
145 if err := t.hostElsewhere(person, origin); err != nil {
146 return err
147 }
148 return tx.Model(&abilitiesRecord{}).Where("person = ? AND origin = ?", person, origin).Pluck("coalesce(authoritative_seen, 0)", &seen).Error
149 }); err != nil {
150 return out, err
151 }
152 seq := l.s.nextFetchSeq()
153 board, outcome, ferr := l.s.fetchBoard(ctx, origin, in.Token, len(seen) == 0 || !seen[0])
154 if outcome != fetchOK && outcome != fetchLegacy {
155 l.s.logAbilities(person, ferr)
156 return out, ErrHostUnverified
157 }
158 err = l.s.tx(ctx, func(t *txn) error {
159 if err := l.s.authority.CurrentPerson(ctx, t.db); err != nil {
160 return err
161 }
162 if err := t.hostElsewhere(person, origin); err != nil {
163 return err
164 }
165 var h assistantHostRecord
166 if err := t.db.Where("person = ?", person).Limit(1).Find(&h).Error; err != nil {
167 return err
168 }
169 h.Person, h.Origin, h.Token, h.Revision, h.UpdatedAt = person, origin, sealed, h.Revision+1, t.now()
170 if err := t.db.Save(&h).Error; err != nil {
171 return err
172 }
173 if _, err := t.applyBoard(person, origin, seq, board, outcome); err != nil {
174 return err
175 }
176 out = wire.AssistantHost{Origin: origin, Revision: h.Revision}
177 return t.s.authority.Audit(t.db, person, auditAssistantHost, origin)
178 })
179 if err == nil {
180 if ops := l.s.operations(); ops != nil {
181 ops.Forget(person)
182 }
183 }
184 return out, err
185}
186
187// hostElsewhere refuses registering origin while the person's host is
188// another origin that is still allowed and whose last answer wasn't a 401
189// (spec §5.3, "One Base at a time").
190func (t *txn) hostElsewhere(person, origin string) error {
191 var h assistantHostRecord
192 if err := t.db.Where("person = ?", person).Limit(1).Find(&h).Error; err != nil {
193 return err
194 }
195 if h.Person == "" || h.Origin == origin || !slices.Contains(t.s.authority.AssistantHosts, h.Origin) {
196 return nil
197 }
198 var r abilitiesRecord
199 if err := t.db.Where("person = ? AND origin = ?", person, h.Origin).Limit(1).Find(&r).Error; err != nil {
200 return err
201 }
202 if r.RevokedAt != nil {
203 return nil
204 }
205 return ErrHostElsewhere
206}
207
208// Host is where the person's Base operations live and the token to call
209// them with; not ok when they registered none, or the operator has since
210// taken the origin off the allowlist.
211func (s *Store) Host(ctx context.Context, person string) (origin, token string, ok bool, err error) {
212 var h assistantHostRecord
213 if err = s.read(ctx, func(tx *gorm.DB) error { return tx.Where("person = ?", person).Limit(1).Find(&h).Error }); err != nil || h.Person == "" {
214 return "", "", false, err
215 }
216 if !slices.Contains(s.authority.AssistantHosts, h.Origin) {
217 return "", "", false, nil
218 }
219 if s.authority.Open == nil {
220 return "", "", false, ErrUnavailable
221 }
222 if err = s.authority.Open(hostDomain, h.Token, &token); err != nil {
223 return "", "", false, err
224 }
225 return h.Origin, token, true, nil
226}
227
228// hostOrigin is raw as a host origin, lowercased: https and a hostname
229// with no path, query or user; http only on loopback.
230func hostOrigin(raw string) (string, bool) {
231 if raw == "" || len(raw) > 300 || strings.ContainsAny(raw, "# \t\r\n\\") {
232 return "", false
233 }
234 u, err := url.Parse(raw)
235 if err != nil || u.User != nil || u.Opaque != "" || u.Path != "" || u.RawPath != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Hostname() == "" {
236 return "", false
237 }
238 if port := u.Port(); port != "" {
239 if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 {
240 return "", false
241 }
242 }
243 host := strings.ToLower(u.Hostname())
244 switch scheme := strings.ToLower(u.Scheme); {
245 case scheme == "https":
246 case scheme == "http" && (host == "localhost" || net.ParseIP(host) != nil && net.ParseIP(host).IsLoopback()):
247 default:
248 return "", false
249 }
250 return strings.ToLower(u.Scheme + "://" + u.Host), true
251}
252
253// hostToken: 20 to 512 visible ASCII characters, so it goes in a header
254// as it is.
255func hostToken(s string) bool {
256 if len(s) < 20 || len(s) > 512 {
257 return false
258 }
259 for i := 0; i < len(s); i++ {
260 if s[i] < 0x21 || s[i] > 0x7e {
261 return false
262 }
263 }
264 return true
265}
266
267// remoteTool: the Assistant's tools that call a provider.
268func remoteTool(name string) bool {
269 return name == wire.ToolLook || name == wire.ToolDescribe || name == wire.ToolUse
270}
271
272// remoteArgs are look's, describe's and use's arguments.
273type remoteArgs struct {
274 Query string
275 Operation string
276 Input json.RawMessage
277}
278
279var operationName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$`)
280
281func remoteInput(name string, raw json.RawMessage) (remoteArgs, bool) {
282 var a remoteArgs
283 switch name {
284 case wire.ToolLook:
285 var in struct {
286 Query string `json:"query"`
287 }
288 if wire.Strict(raw, &in) != nil || len(in.Query) > 200 || !utf8.ValidString(in.Query) || strings.ContainsRune(in.Query, 0) {
289 return a, false
290 }
291 a.Query = strings.TrimSpace(in.Query)
292 case wire.ToolDescribe:
293 var in struct {
294 Operation string `json:"operation"`
295 }
296 if wire.Strict(raw, &in) != nil || !operationName.MatchString(in.Operation) {
297 return a, false
298 }
299 a.Operation = in.Operation
300 case wire.ToolUse:
301 var in struct {
302 Operation string `json:"operation"`
303 Input json.RawMessage `json:"input"`
304 }
305 if wire.Strict(raw, &in) != nil || !operationName.MatchString(in.Operation) || !strings.HasPrefix(strings.TrimSpace(string(in.Input)), "{") {
306 return a, false
307 }
308 a.Operation, a.Input = in.Operation, in.Input
309 default:
310 return a, false
311 }
312 return a, true
313}
314
315// remoteCall records look, describe or use in an Assistant turn. It is
316// authorised against the turn now and stored pending, with nothing
317// queued: ServeRemoteCalls answers it. A use already made in the turn is
318// answered with its result, replayed; one still out waits for it. A
319// pending call keeps its arguments (Args) until it is done, so the next
320// process can make it after a restart.
321func (t *txn) remoteCall(l Lease, v *wire.ToolCall, args, lane string) error {
322 row := toolCallRecord{CallID: v.CallID, Person: l.Runner.Person, TurnID: v.TurnID, Attempt: v.Attempt, ArgsHash: args, Name: v.Name, CreatedAt: t.now(), Lane: lane}
323 in, ok := remoteInput(v.Name, v.Args)
324 if !ok {
325 return t.answerCall(row, refused("invalid", toolBadInput))
326 }
327 row.Operation = in.Operation
328 r, err := t.ownTurn(l, v.TurnID)
329 if errors.Is(err, ErrNotFound) || errors.Is(err, ErrForbidden) || err == nil && (wire.Terminal(r.State) || v.Attempt != r.Attempt) {
330 return t.answerCall(row, refused("turn_ended", toolTurnEnded))
331 }
332 if err != nil {
333 return err
334 }
335 if v.Name == wire.ToolUse {
336 row.LedgerKey = r.ID + "\x00" + in.Operation + "\x00" + argsHash(in.Input)
337 var earlier []toolCallRecord
338 if err := t.db.Where("turn_id = ? AND person = ? AND ledger_key = ?", r.ID, row.Person, row.LedgerKey).Order("created_at").Find(&earlier).Error; err != nil {
339 return err
340 }
341 if i := slices.IndexFunc(earlier, func(e toolCallRecord) bool { return e.State == callDone }); i >= 0 {
342 var res wire.ToolResult
343 if err := json.Unmarshal([]byte(earlier[i].Result), &res); err != nil {
344 return err
345 }
346 res.Replayed = true
347 return t.answerCall(row, res)
348 }
349 if len(earlier) > 0 {
350 // Its arguments are kept too: a read it waits on hands it
351 // back to be made itself (finishCall).
352 row.State, row.Args = callWaiting, string(v.Args)
353 return t.db.Create(&row).Error
354 }
355 }
356 row.State, row.Args, t.pending = callPending, string(v.Args), true
357 return t.db.Create(&row).Error
358}
359
360// repeatPending answers a call id repeated while its call is out:
361// nothing now (its result comes when the call is done), or, for other
362// arguments, a refusal.
363func (t *txn) repeatPending(v *wire.ToolCall, prior toolCallRecord, args string) error {
364 if prior.TurnID == v.TurnID && prior.Attempt == v.Attempt && prior.Name == v.Name && prior.ArgsHash == args {
365 return nil
366 }
367 res := refused("invalid", toolBadInput)
368 res.CallID, res.Person = v.CallID, prior.Person
369 return t.command(prior.Person, wire.FrameToolResult, res)
370}
371
372// answerCall stores a call answered now, done, audits a use and queues
373// its result. A failure is kept out of the ledger.
374func (t *txn) answerCall(row toolCallRecord, res wire.ToolResult) error {
375 res.CallID, res.Person = row.CallID, row.Person
376 raw, _ := json.Marshal(res)
377 row.Result, row.State = string(raw), callDone
378 if res.IsError {
379 row.LedgerKey = ""
380 }
381 if err := t.db.Create(&row).Error; err != nil {
382 return err
383 }
384 if err := t.auditUse(row, res); err != nil {
385 return err
386 }
387 return t.command(row.Person, wire.FrameToolResult, res)
388}
389
390// auditUse records a use by operation and outcome: never its input or
391// output.
392func (t *txn) auditUse(row toolCallRecord, res wire.ToolResult) error {
393 if row.Name != wire.ToolUse {
394 return nil
395 }
396 outcome := "ok"
397 switch {
398 case res.Replayed:
399 outcome = "replayed"
400 case res.IsError:
401 outcome = res.Code
402 }
403 return t.s.authority.Audit(t.db, row.Person, auditAssistantUse, strings.TrimSpace(row.Operation+" "+outcome))
404}
405
406// ServeRemoteCalls makes the Assistant's pending calls until ctx ends,
407// several at once. It is woken after a commit that stored one and looks
408// every five seconds besides. A call cut off by ctx is left pending, for
409// the next process. A result it could not store is kept and stored on a
410// later pass, without calling the provider again (a restart loses it:
411// the next process calls again, a write with the same key).
412func (s *Store) ServeRemoteCalls(ctx context.Context) {
413 var (
414 wg sync.WaitGroup
415 mu sync.Mutex
416 busy = map[string]bool{}
417 unsaved = map[string]finished{}
418 )
419 defer wg.Wait()
420 slots := make(chan struct{}, remoteParallel)
421 tick := time.NewTicker(remotePoll)
422 defer tick.Stop()
423 for {
424 var rows []toolCallRecord
425 if err := s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Where("state = ?", callPending).Order("created_at").Limit(100).Find(&rows).Error; err != nil {
426 if ctx.Err() == nil {
427 s.logCall("assistant calls not read", toolCallRecord{}, err)
428 }
429 } else {
430 if len(rows) < 100 {
431 // A kept result whose call is no longer pending was
432 // stored by another process.
433 mu.Lock()
434 for id := range unsaved {
435 if !slices.ContainsFunc(rows, func(r toolCallRecord) bool { return r.CallID == id }) {
436 delete(unsaved, id)
437 }
438 }
439 mu.Unlock()
440 }
441 for _, row := range rows {
442 mu.Lock()
443 taken := busy[row.CallID]
444 busy[row.CallID] = true
445 mu.Unlock()
446 if taken {
447 continue
448 }
449 select {
450 case slots <- struct{}{}:
451 case <-ctx.Done():
452 return
453 }
454 wg.Add(1)
455 go func() {
456 defer wg.Done()
457 mu.Lock()
458 kept, has := unsaved[row.CallID]
459 mu.Unlock()
460 var prior *finished
461 if has {
462 prior = &kept
463 }
464 again, keep := s.remoteCall(ctx, row, prior)
465 <-slots
466 mu.Lock()
467 delete(busy, row.CallID)
468 if keep != nil {
469 unsaved[row.CallID] = *keep
470 } else {
471 delete(unsaved, row.CallID)
472 }
473 mu.Unlock()
474 if again {
475 s.wakeRemote()
476 }
477 }()
478 }
479 }
480 select {
481 case <-ctx.Done():
482 return
483 case <-s.remote:
484 case <-tick.C:
485 }
486 }
487}
488
489// SetLogger is where ServeRemoteCalls reports what it could not do: by
490// call id and operation, never a call's input, output or a token.
491func (s *Store) SetLogger(l *slog.Logger) { s.logger.Store(l) }
492
493func (s *Store) logCall(msg string, row toolCallRecord, err error) {
494 if l := s.logger.Load(); l != nil {
495 l.Warn(msg, "call", row.CallID, "operation", row.Operation, "err", err)
496 }
497}
498
499// finished is a call's result not yet stored; read: the call was a
500// read-only operation's, which keeps no ledger.
501type finished struct {
502 res wire.ToolResult
503 called bool
504 read bool
505}
506
507func (s *Store) wakeRemote() {
508 select {
509 case s.remote <- struct{}{}:
510 default:
511 }
512}
513
514// remoteCall makes one pending call, unless nothing waiting on it can
515// still be answered, and stores what it returned; with kept, it only
516// stores that. again: it was left pending for the next pass to make (a
517// retry came in meanwhile). keep: what could not be stored, for a later
518// pass to store.
519func (s *Store) remoteCall(ctx context.Context, row toolCallRecord, kept *finished) (again bool, keep *finished) {
520 if kept != nil {
521 return s.store(ctx, row, *kept)
522 }
523 live := false
524 if err := s.read(ctx, func(tx *gorm.DB) error {
525 t := &txn{s: s, ctx: ctx, db: tx}
526 rows, err := t.callGroup(row)
527 if err != nil {
528 return err
529 }
530 for i := 0; i < len(rows) && !live; i++ {
531 if live, err = t.deliverable(rows[i]); err != nil {
532 return err
533 }
534 }
535 return nil
536 }); err != nil {
537 if ctx.Err() == nil {
538 s.logCall("assistant call not checked", row, err)
539 }
540 return false, nil
541 }
542 res, read := refused("turn_ended", toolTurnEnded), false
543 if live {
544 res, read = s.runRemote(ctx, row)
545 if ctx.Err() != nil {
546 return false, nil
547 }
548 }
549 return s.store(ctx, row, finished{res: res, called: live, read: read})
550}
551
552// store stores a call's result (finishCall), or reports why not and
553// gives it back to keep.
554func (s *Store) store(ctx context.Context, row toolCallRecord, f finished) (again bool, keep *finished) {
555 again, err := s.finishCall(ctx, row, f)
556 if err != nil {
557 if ctx.Err() == nil {
558 s.logCall("assistant call not stored", row, err)
559 }
560 return false, &f
561 }
562 return again, nil
563}
564
565// callGroup is the call and every call still waiting on its ledger key.
566func (t *txn) callGroup(row toolCallRecord) ([]toolCallRecord, error) {
567 var rows []toolCallRecord
568 q := t.db.Where("call_id = ? AND state = ?", row.CallID, callPending)
569 if row.LedgerKey != "" {
570 q = t.db.Where("turn_id = ? AND person = ? AND ledger_key = ? AND state IN ?", row.TurnID, row.Person, row.LedgerKey, []string{callPending, callWaiting})
571 }
572 return rows, q.Order("created_at").Find(&rows).Error
573}
574
575// deliverable: the call's turn still runs at its attempt, for a person
576// with a primary runner.
577func (t *txn) deliverable(row toolCallRecord) (bool, error) {
578 var r turnRecord
579 if err := t.db.Where("id = ? AND person = ?", row.TurnID, row.Person).Limit(1).Find(&r).Error; err != nil || r.ID == "" || wire.Terminal(r.State) || r.Attempt != row.Attempt {
580 return false, err
581 }
582 primary, err := t.s.authority.PrimaryRunner(t.db, row.Person)
583 return primary != "", err
584}
585
586// finishCall stores a call's result on it and every call waiting on it,
587// done, audits each use, and queues the result for each whose turn still
588// runs at its attempt. A call another process finished is left as it is;
589// so is one not made (called false) that a retry is now waiting on
590// (again). A read's result is its call's alone and leaves the ledger:
591// the calls waiting on it are made themselves (again).
592func (s *Store) finishCall(ctx context.Context, row toolCallRecord, f finished) (again bool, err error) {
593 res, called := f.res, f.called
594 err = s.tx(ctx, func(t *txn) error {
595 rows, err := t.callGroup(row)
596 if err != nil || !slices.ContainsFunc(rows, func(r toolCallRecord) bool { return r.CallID == row.CallID }) {
597 return err
598 }
599 if f.read {
600 var rest []toolCallRecord
601 for _, r := range rows {
602 if r.CallID != row.CallID {
603 rest = append(rest, r)
604 }
605 }
606 for _, r := range rest {
607 if err := t.db.Model(&toolCallRecord{}).Where("call_id = ?", r.CallID).Updates(map[string]any{"state": callPending, "ledger_key": ""}).Error; err != nil {
608 return err
609 }
610 }
611 again = len(rest) > 0
612 rows = slices.DeleteFunc(rows, func(r toolCallRecord) bool { return r.CallID != row.CallID })
613 }
614 if !called {
615 for _, r := range rows {
616 if ok, err := t.deliverable(r); err != nil || ok {
617 again = ok
618 return err
619 }
620 }
621 }
622 for _, r := range rows {
623 out := res
624 out.Replayed = r.CallID != row.CallID && !res.IsError
625 out.CallID, out.Person = r.CallID, r.Person
626 raw, _ := json.Marshal(out)
627 r.Result, r.State, r.Args = string(raw), callDone, ""
628 if res.IsError || f.read {
629 r.LedgerKey = ""
630 }
631 if err := t.db.Save(&r).Error; err != nil {
632 return err
633 }
634 if err := t.auditUse(r, out); err != nil {
635 return err
636 }
637 if ok, err := t.deliverable(r); err != nil {
638 return err
639 } else if ok {
640 if err := t.command(r.Person, wire.FrameToolResult, out); err != nil {
641 return err
642 }
643 }
644 }
645 return nil
646 })
647 return again, err
648}
649
650// runRemote makes the call through the registry, outside any
651// transaction. A use is described first: what Decide refuses is never
652// invoked. The registry derives the key the provider gets from the
653// ledger key. read: the use was of a read-only operation.
654func (s *Store) runRemote(ctx context.Context, row toolCallRecord) (res wire.ToolResult, read bool) {
655 ops := s.operations()
656 in, ok := remoteInput(row.Name, json.RawMessage(row.Args))
657 if ops == nil || !ok {
658 return refused("unavailable", toolOpUnavailable), false
659 }
660 // What the person may be offered and run (spec
661 // 2026-11-26-assistant-abilities §6.1): read once, here; the send
662 // gate reads it again right before the request.
663 sw, err := s.switchesNow(ctx, row.Person)
664 if err != nil {
665 return refused("unavailable", toolOpUnavailable), false
666 }
667 kind, err := s.turnKind(ctx, row)
668 if err != nil {
669 return refused("unavailable", toolOpUnavailable), false
670 }
671 filtered := assist.WithFilter(ctx, abilityFilter{sw: sw, noLookups: kind != wire.TurnPerson})
672 switch row.Name {
673 case wire.ToolLook:
674 text, err := ops.Look(withCall(filtered, row), row.Person, in.Query)
675 if err != nil {
676 return s.opFailed(ctx, row.Person, err), false
677 }
678 return wire.ToolResult{Code: "listed", Text: fitLook(text)}, false
679 case wire.ToolDescribe:
680 op, err := ops.Describe(filtered, row.Person, in.Operation)
681 if err != nil {
682 return s.opFailed(ctx, row.Person, err), false
683 }
684 raw, err := json.Marshal(op)
685 if err != nil {
686 return refused("unavailable", toolOpUnavailable), false
687 }
688 return fitFrame(wire.ToolResult{Code: "described", Text: string(raw)}), false
689 }
690 op, err := ops.Describe(ctx, row.Person, in.Operation)
691 if err != nil {
692 return s.opFailed(ctx, row.Person, err), false
693 }
694 if run, code := assist.Decide(op); !run {
695 return opRefused(code, ""), false
696 }
697 switch key, ok := abilityFor(op); {
698 case !ok:
699 return refused(wire.CodeAbilityUnmapped, toolAbilityUnmapped), false
700 case key != "" && !sw.Can(key):
701 return s.abilityRefusal(sw, key), false
702 }
703 // A turn the person did not start (a team_update) only looks, but for
704 // answering or nudging the job it tells (updateWrites).
705 if !op.ReadOnly {
706 asked, err := s.asked(ctx, row, op)
707 if err != nil {
708 return refused("unavailable", toolOpUnavailable), false
709 }
710 if !asked {
711 return opRefused("not_asked", ""), false
712 }
713 }
714 gated := assist.WithGate(withCall(filtered, row), s.sendGate(ctx, row.Person, op))
715 out, err := ops.Invoke(gated, row.Person, in.Operation, in.Input, row.LedgerKey)
716 if err != nil {
717 return s.opFailed(ctx, row.Person, err), op.ReadOnly
718 }
719 return fitFrame(wire.ToolResult{Code: "used", Text: string(out)}), op.ReadOnly
720}
721
722// asked: the call's turn is one the person started, or the turn queued
723// after they connected the Oficina apps (carryOn), which carries on
724// their request; or op
725// is one of the team's updateWrites in a team_update turn (which job it
726// may touch is the operation's own check).
727func (s *Store) asked(ctx context.Context, row toolCallRecord, op assist.Operation) (bool, error) {
728 var kinds []string
729 var resumed int64
730 err := s.read(ctx, func(tx *gorm.DB) error {
731 if err := tx.Model(&turnRecord{}).Where("id = ? AND person = ?", row.TurnID, row.Person).Pluck("coalesce(kind, '')", &kinds).Error; err != nil {
732 return err
733 }
734 return tx.Model(&connectTurnRecord{}).Where("turn_id = ? AND person = ? AND card_id IN (SELECT id FROM chat_cards WHERE person = ? AND kind = ? AND name = ?)", row.TurnID, row.Person, row.Person, wire.CardConnect, OficinaProvider).Count(&resumed).Error
735 })
736 if err != nil || len(kinds) != 1 {
737 return false, err
738 }
739 update := kinds[0] == wire.TurnTeamUpdate && op.Provider == teamProvider{}.Name() && slices.Contains(updateWrites, op.Name)
740 return kinds[0] == wire.TurnPerson || kinds[0] == wire.TurnTeamUpdate && resumed == 1 || update, nil
741}
742
743// opFailed is a provider's or the registry's failure as a result. An
744// operation unknown to a person with no host registered is one that is
745// not connected: their Base was never asked.
746func (s *Store) opFailed(ctx context.Context, person string, err error) wire.ToolResult {
747 var own teamRefusal
748 if errors.As(err, &own) {
749 return refused(own.code, own.text)
750 }
751 // The instance's own refusal (an ability off, the operation changed):
752 // its code and its words, as the instance wrote them.
753 var inst assist.Refusal
754 if errors.As(err, &inst) {
755 if inst.Message == "" {
756 inst.Message = toolOpUnavailable
757 }
758 return refused(inst.Code, inst.Message)
759 }
760 var f assist.Failure
761 if !errors.As(err, &f) {
762 return refused("unavailable", toolOpUnavailable)
763 }
764 if f.Code == "unknown_operation" {
765 if _, _, ok, herr := s.Host(ctx, person); herr == nil && !ok {
766 f.Code = "not_connected"
767 }
768 }
769 return opRefused(f.Code, f.Message)
770}
771
772var failureCode = regexp.MustCompile(`^[a-z0-9_]{1,64}$`)
773
774// opRefused is a refusal by code: the instance's words for its own
775// refusals, the provider's (reference only) for the rest.
776func opRefused(code, message string) wire.ToolResult {
777 if text, ok := opTexts[code]; ok {
778 return refused(code, text)
779 }
780 if !failureCode.MatchString(code) {
781 code = "provider_error"
782 }
783 if r := []rune(strings.TrimSpace(message)); len(r) > 300 {
784 message = string(r[:300])
785 }
786 return refused(code, toolOpFailed+strings.TrimSpace(message))
787}
788
789// fitFrame refuses a result too large for the tool frame.
790func fitFrame(res wire.ToolResult) wire.ToolResult {
791 if frameSize(res.Text) > toolFrame {
792 return refused("too_large", toolTooLarge)
793 }
794 return res
795}
796
797// fitLook cuts look's list at a line, with a note, to fit the frame.
798func fitLook(text string) string {
799 if frameSize(text) <= toolFrame {
800 return text
801 }
802 budget, n := toolFrame-frameSize("\n"+toolLookCut), frameSize("")
803 lines := strings.Split(text, "\n")
804 keep := 0
805 for _, line := range lines {
806 if n += escaped(line) + 2; n > budget {
807 break
808 }
809 keep++
810 }
811 if keep == 0 {
812 return toolLookCut
813 }
814 return strings.Join(lines[:keep], "\n") + "\n" + toolLookCut
815}
816
817// frameSize is the size of a result with text as its tool_result.
818func frameSize(text string) int {
819 raw, _ := json.Marshal(wire.ToolResult{Code: "described", Text: text})
820 return len(raw)
821}
822
823// escaped is the size of s inside a JSON string.
824func escaped(s string) int {
825 raw, _ := json.Marshal(s)
826 return len(raw) - 2
827}
828