| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | ) |
| 14 | |
| 15 | // Exactly-once across attempts. A turn that moves to another connection |
| 16 | // runs again as a new attempt in a new session, and that model may call |
| 17 | // the same tools again. The instance's mutation ledger is the one |
| 18 | // authority on what the turn already did: every call goes to it, and it |
| 19 | // answers a repeat, exact or reworded, from what the turn made (Astra |
| 20 | // round 1: a second ledger here, answering exact repeats locally, could |
| 21 | // disagree with it about which task is which). The runner records each |
| 22 | // write here only to tell a new attempt what earlier ones did. |
| 23 | |
| 24 | const effectSchema = ` |
| 25 | CREATE TABLE IF NOT EXISTS turn_effects (turn_id TEXT NOT NULL, attempt INTEGER NOT NULL, seq INTEGER NOT NULL, name TEXT NOT NULL, args TEXT NOT NULL, call_id TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0, result TEXT NOT NULL DEFAULT '', is_error INTEGER NOT NULL DEFAULT 0, replayed_in INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (turn_id, attempt, seq)); |
| 26 | ` |
| 27 | |
| 28 | func writeTool(name string) bool { return slices.Contains(wire.WriteTools, name) } |
| 29 | |
| 30 | func canonArgs(raw json.RawMessage) string { |
| 31 | var v any |
| 32 | if json.Unmarshal(raw, &v) == nil { |
| 33 | raw, _ = json.Marshal(v) |
| 34 | } |
| 35 | return string(raw) |
| 36 | } |
| 37 | |
| 38 | // startEffect records a write before it runs. |
| 39 | func (s *State) startEffect(ctx context.Context, turn string, attempt int64, name string, args json.RawMessage, callID string) (int64, error) { |
| 40 | var seq int64 |
| 41 | err := s.tx(ctx, func(t *sql.Tx) error { |
| 42 | if err := t.QueryRow("SELECT coalesce(max(seq),0)+1 FROM turn_effects WHERE turn_id=? AND attempt=?", turn, attempt).Scan(&seq); err != nil { |
| 43 | return err |
| 44 | } |
| 45 | _, err := t.Exec("INSERT INTO turn_effects(turn_id, attempt, seq, name, args, call_id) VALUES(?,?,?,?,?,?)", turn, attempt, seq, name, canonArgs(args), callID) |
| 46 | return err |
| 47 | }) |
| 48 | return seq, err |
| 49 | } |
| 50 | |
| 51 | // endEffect records a write's result. |
| 52 | func (s *State) endEffect(ctx context.Context, turn string, attempt, seq int64, result string, isError bool) error { |
| 53 | _, err := s.db.ExecContext(context.WithoutCancel(ctx), "UPDATE turn_effects SET done=1, result=?, is_error=? WHERE turn_id=? AND attempt=? AND seq=?", result, isError, turn, attempt, seq) |
| 54 | return err |
| 55 | } |
| 56 | |
| 57 | // doneEarlier lists what earlier attempts of the turn already did, for |
| 58 | // the new attempt's prompt. |
| 59 | func (s *State) doneEarlier(ctx context.Context, turn string, attempt int64) []string { |
| 60 | rows, err := s.db.QueryContext(ctx, "SELECT name, done, result, is_error FROM turn_effects WHERE turn_id=? AND attempt<? ORDER BY attempt, seq", turn, attempt) |
| 61 | if err != nil { |
| 62 | return nil |
| 63 | } |
| 64 | defer rows.Close() |
| 65 | var out []string |
| 66 | for rows.Next() { |
| 67 | var name, result string |
| 68 | var done, isError bool |
| 69 | if rows.Scan(&name, &done, &result, &isError) != nil { |
| 70 | return out |
| 71 | } |
| 72 | switch { |
| 73 | case !done: |
| 74 | out = append(out, name+": sent; its result is replayed if you call it again") |
| 75 | case isError: |
| 76 | out = append(out, name+": refused: "+clip(strings.TrimSpace(result), 200)) |
| 77 | default: |
| 78 | out = append(out, name+": "+clip(strings.TrimSpace(result), 300)) |
| 79 | } |
| 80 | } |
| 81 | return out |
| 82 | } |
| 83 | |
| 84 | // errNotRecorded: an effect could not be recorded, so it does not run. |
| 85 | var errNotRecorded = errors.New("tool effect not recorded") |
| 86 | |
| 87 | // ledgered runs a write tool through the instance, which holds the turn |
| 88 | // to what it already did, and records it before and after it runs so a |
| 89 | // later attempt is told. |
| 90 | func (b *bridge) ledgered(ctx context.Context, turn string, attempt int64, name, base string, args json.RawMessage, run func(base string, args json.RawMessage) (string, bool)) (string, bool) { |
| 91 | seq, err := b.State.startEffect(ctx, turn, attempt, name, args, base) |
| 92 | if err != nil { |
| 93 | b.log("tool effect", fmt.Errorf("%w: %v", errNotRecorded, err)) |
| 94 | return toolTimeout, true |
| 95 | } |
| 96 | text, isError := run(base, args) |
| 97 | // No answer is not a result: the instance's ledger answers a repeat. |
| 98 | if !(isError && text == toolTimeout) { |
| 99 | b.log("tool effect", b.State.endEffect(ctx, turn, attempt, seq, text, isError)) |
| 100 | } |
| 101 | return text, isError |
| 102 | } |
| 103 | |