| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "net/http" |
| 8 | "regexp" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "testing" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo" |
| 15 | "amadan.net/oficina/equipo/internal/equipo/assist" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | ) |
| 18 | |
| 19 | // keyedProvider is an in-process provider with one write that takes a |
| 20 | // client idempotency key: Base's contract cannot offer one yet (its |
| 21 | // operations have no key field), so the ledger's write path is shown |
| 22 | // through this. |
| 23 | type keyedProvider struct { |
| 24 | mu sync.Mutex |
| 25 | keys []string |
| 26 | inputs []string |
| 27 | hold chan struct{} |
| 28 | fail bool |
| 29 | } |
| 30 | |
| 31 | func (p *keyedProvider) Name() string { return "svc:ledger" } |
| 32 | |
| 33 | // failNext makes the next call fail after it is counted. |
| 34 | func (p *keyedProvider) failNext() { |
| 35 | p.mu.Lock() |
| 36 | p.fail = true |
| 37 | p.mu.Unlock() |
| 38 | } |
| 39 | |
| 40 | func (p *keyedProvider) List(context.Context, string) ([]assist.Operation, error) { |
| 41 | return []assist.Operation{{Name: "ledger_write", Description: "Write one line to the test ledger.", App: "Ledger", Idempotent: true, KeyField: "client_id", Input: json.RawMessage(`{"type":"object","properties":{"line":{"type":"string"}}}`)}}, nil |
| 42 | } |
| 43 | |
| 44 | func (p *keyedProvider) Invoke(ctx context.Context, _, _ string, input json.RawMessage, key string) (json.RawMessage, error) { |
| 45 | p.mu.Lock() |
| 46 | p.keys, p.inputs = append(p.keys, key), append(p.inputs, string(input)) |
| 47 | hold, fail := p.hold, p.fail |
| 48 | p.fail = false |
| 49 | p.mu.Unlock() |
| 50 | if fail { |
| 51 | return nil, assist.Failure{Code: "unavailable", Message: "The ledger timed out."} |
| 52 | } |
| 53 | if hold != nil { |
| 54 | select { |
| 55 | case <-hold: |
| 56 | case <-ctx.Done(): |
| 57 | return nil, ctx.Err() |
| 58 | } |
| 59 | } |
| 60 | return json.RawMessage(`{"written":true}`), nil |
| 61 | } |
| 62 | |
| 63 | func (p *keyedProvider) calls() ([]string, []string) { |
| 64 | p.mu.Lock() |
| 65 | defer p.mu.Unlock() |
| 66 | return slices.Clone(p.keys), slices.Clone(p.inputs) |
| 67 | } |
| 68 | |
| 69 | // holdNext keeps every call waiting until release. |
| 70 | func (p *keyedProvider) holdNext() (release func()) { |
| 71 | c := make(chan struct{}) |
| 72 | p.mu.Lock() |
| 73 | p.hold = c |
| 74 | p.mu.Unlock() |
| 75 | var once sync.Once |
| 76 | return func() { |
| 77 | once.Do(func() { |
| 78 | p.mu.Lock() |
| 79 | p.hold = nil |
| 80 | p.mu.Unlock() |
| 81 | close(c) |
| 82 | }) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | // opsRig is an Assistant rig whose instance allows a fake Base as its |
| 87 | // host, with the person's primary at the Assistant's protocol (or the |
| 88 | // rig's, newOpsRigAt). |
| 89 | type opsRig struct { |
| 90 | *toolRig |
| 91 | base *FakeBase |
| 92 | a *AssistantClient |
| 93 | protocol int |
| 94 | // boardRev counts the boards setBoard has given (build_off tests). |
| 95 | boardRev int64 |
| 96 | // lookupAnswer, when set, is the person's model answering a lookup |
| 97 | // step that arrives while a call waits (lookup_e2e_test.go). |
| 98 | lookupAnswer func(wire.LookupStep) wire.LookupResult |
| 99 | } |
| 100 | |
| 101 | func newOpsRig(t *testing.T, providers ...assist.Provider) *opsRig { |
| 102 | return newOpsRigAt(t, wire.ProtocolAssistant, providers...) |
| 103 | } |
| 104 | |
| 105 | // newOpsRigAt is newOpsRig whose runners speak protocol. |
| 106 | func newOpsRigAt(t *testing.T, protocol int, providers ...assist.Provider) *opsRig { |
| 107 | base := StartFakeBase(t) |
| 108 | r := newRigWith(t, func(i *Instance) { |
| 109 | i.AssistantHosts = []string{base.Origin} |
| 110 | i.Providers = providers |
| 111 | }) |
| 112 | runner := r.dialAt(protocol) |
| 113 | return &opsRig{toolRig: &toolRig{rig: r, runner: runner}, base: base, a: r.client.Assistant(), protocol: protocol} |
| 114 | } |
| 115 | |
| 116 | // other is a second owner on the same instance, with their own primary. |
| 117 | func (o *opsRig) other(address string) *opsRig { |
| 118 | o.t.Helper() |
| 119 | if err := o.inst.Store.SetMember(context.Background(), equipo.Actor{Address: Owner}, address, equipo.RoleOwner, true, 0); err != nil { |
| 120 | o.t.Fatal(err) |
| 121 | } |
| 122 | client := NewClient(o.inst.URL, o.inst.DeviceTokenFor(o.t, address)) |
| 123 | cred := o.inst.EnrolRunnerFor(o.t, address) |
| 124 | runner, err := DialRunnerHello(o.ctx, o.inst.URL, cred.Token, primaryAt(wire.Hello{Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, o.protocol)) |
| 125 | if err != nil { |
| 126 | o.t.Fatal(err) |
| 127 | } |
| 128 | o.t.Cleanup(runner.Close) |
| 129 | return &opsRig{toolRig: &toolRig{rig: o.rig, runner: runner}, base: o.base, a: client.Assistant(), protocol: o.protocol} |
| 130 | } |
| 131 | |
| 132 | // connect registers the fake Base as the person's host with token. |
| 133 | func (o *opsRig) connect(token string) wire.AssistantHost { |
| 134 | o.t.Helper() |
| 135 | out, err := o.a.PutHost(o.ctx, o.base.Origin, token) |
| 136 | if err != nil { |
| 137 | o.t.Fatal(err) |
| 138 | } |
| 139 | return out |
| 140 | } |
| 141 | |
| 142 | // begin sends an Assistant message and makes its turn the rig's. |
| 143 | func (o *opsRig) begin(text string) string { |
| 144 | o.t.Helper() |
| 145 | sent, err := o.a.Send(o.ctx, text, "a-"+rand.Text()) |
| 146 | if err != nil { |
| 147 | o.t.Fatal(err) |
| 148 | } |
| 149 | f, _, err := o.runner.Expect(o.ctx, wire.FrameMessage) |
| 150 | if err != nil { |
| 151 | o.t.Fatal(err) |
| 152 | } |
| 153 | if err := o.runner.Send(o.ctx, "ack-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { |
| 154 | o.t.Fatal(err) |
| 155 | } |
| 156 | o.turn, o.attempt = sent.Turn.ID, 0 |
| 157 | return sent.Turn.ID |
| 158 | } |
| 159 | |
| 160 | // send sends one tool_call in the rig's turn and returns its call id. |
| 161 | func (o *opsRig) send(id, name string, args any) string { |
| 162 | o.t.Helper() |
| 163 | raw, _ := json.Marshal(args) |
| 164 | o.seq++ |
| 165 | attempt := max(o.attempt, 1) |
| 166 | call := o.turn + "/" + itoa(int(attempt)) + "/" + id |
| 167 | if err := o.runner.Send(o.ctx, "r-tc-"+id+"-"+itoa(o.seq), wire.FrameToolCall, wire.ToolCall{CallID: call, TurnID: o.turn, Attempt: attempt, Name: name, Args: raw}); err != nil { |
| 168 | o.t.Fatal(err) |
| 169 | } |
| 170 | return call |
| 171 | } |
| 172 | |
| 173 | // await reads frames until each call has its one tool_result, acking |
| 174 | // each; a second result for one of them, or one for another call, fails. |
| 175 | func (o *opsRig) await(calls ...string) map[string]wire.ToolResult { |
| 176 | o.t.Helper() |
| 177 | got := map[string]wire.ToolResult{} |
| 178 | for len(got) < len(calls) { |
| 179 | f, body, err := o.runner.Next(o.ctx) |
| 180 | if err != nil { |
| 181 | o.t.Fatalf("waiting for %v: %v", calls, err) |
| 182 | } |
| 183 | if step, ok := body.(*wire.LookupStep); ok && o.lookupAnswer != nil { |
| 184 | r := o.lookupAnswer(*step) |
| 185 | r.Lookup, r.Attempt, r.Nonce, r.Stage = step.Lookup, step.Attempt, step.Nonce, step.Stage |
| 186 | if err := o.runner.Send(o.ctx, "lr-"+f.ID, wire.FrameLookupResult, r); err != nil { |
| 187 | o.t.Fatal(err) |
| 188 | } |
| 189 | continue |
| 190 | } |
| 191 | res, ok := body.(*wire.ToolResult) |
| 192 | if !ok { |
| 193 | if f.Type != wire.FrameAck { |
| 194 | o.held = append(o.held, heldFrame{f, body, o.runner.Received[len(o.runner.Received)-1]}) |
| 195 | } |
| 196 | continue |
| 197 | } |
| 198 | if err := o.runner.Send(o.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { |
| 199 | o.t.Fatal(err) |
| 200 | } |
| 201 | if _, twice := got[res.CallID]; twice || !slices.Contains(calls, res.CallID) { |
| 202 | o.t.Fatalf("an extra result for %s (waiting for %v): %+v", res.CallID, calls, res) |
| 203 | } |
| 204 | if res.Person != o.person() { |
| 205 | o.t.Fatalf("a result for %s: %+v", res.Person, res) |
| 206 | } |
| 207 | got[res.CallID] = *res |
| 208 | } |
| 209 | return got |
| 210 | } |
| 211 | |
| 212 | func (o *opsRig) person() string { |
| 213 | me, err := o.a.Snapshot(o.ctx) |
| 214 | if err != nil { |
| 215 | o.t.Fatal(err) |
| 216 | } |
| 217 | return me.Me.Address |
| 218 | } |
| 219 | |
| 220 | // tool sends one call and waits for its result. |
| 221 | func (o *opsRig) tool(id, name string, args any) wire.ToolResult { |
| 222 | o.t.Helper() |
| 223 | call := o.send(id, name, args) |
| 224 | return o.await(call)[call] |
| 225 | } |
| 226 | |
| 227 | func (o *opsRig) use(id, operation string, input any) wire.ToolResult { |
| 228 | o.t.Helper() |
| 229 | return o.tool(id, wire.ToolUse, map[string]any{"operation": operation, "input": input}) |
| 230 | } |
| 231 | |
| 232 | // results is how many tool_result commands the instance queued for call. |
| 233 | func (o *opsRig) results(call string) int { |
| 234 | o.t.Helper() |
| 235 | return o.rows("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameToolResult, `%"call_id":"`+call+`"%`) |
| 236 | } |
| 237 | |
| 238 | func (o *opsRig) state(call string) string { |
| 239 | o.t.Helper() |
| 240 | var s string |
| 241 | if err := o.inst.DB.Writer().QueryRow("SELECT coalesce(max(state), 'none') FROM chat_tool_calls WHERE call_id = ?", call).Scan(&s); err != nil { |
| 242 | o.t.Fatal(err) |
| 243 | } |
| 244 | return s |
| 245 | } |
| 246 | |
| 247 | // TestContractHostAllowlist: PUT /api/v1/assistant/host takes an origin |
| 248 | // on the operator's allowlist and a printable token, never echoes the |
| 249 | // token and stores it sealed. A second PUT replaces the first. |
| 250 | func TestContractHostAllowlist(t *testing.T) { |
| 251 | base := StartFakeBase(t) |
| 252 | r := newRigWith(t, func(i *Instance) { |
| 253 | i.AssistantHosts = []string{"https://base.example.com", base.Origin} |
| 254 | }) |
| 255 | url := r.inst.URL + "/api/v1/assistant/host" |
| 256 | rows := (&toolRig{rig: r}).rows |
| 257 | put := func(origin, token string) (int, wire.Error, []byte) { |
| 258 | t.Helper() |
| 259 | body, _ := json.Marshal(map[string]string{"origin": origin, "token": token}) |
| 260 | status, _, raw := raw(t, http.MethodPut, url, r.client.Token, nil, string(body)) |
| 261 | var e wire.Error |
| 262 | _ = json.Unmarshal(raw, &e) |
| 263 | return status, e, raw |
| 264 | } |
| 265 | token := "tok-" + strings.Repeat("a", 30) |
| 266 | // An allowed origin (case aside) that doesn't honour the token, here |
| 267 | // one that doesn't answer at all, doesn't count (abilities §5.3). |
| 268 | status, e, body := put("https://Base.Example.com", token) |
| 269 | if status != 409 || e.Code != wire.CodeHostUnverified || strings.Contains(string(body), token) { |
| 270 | t.Fatalf("first put %d %s", status, body) |
| 271 | } |
| 272 | var out wire.AssistantHost |
| 273 | second := "second-" + strings.Repeat("b", 30) |
| 274 | base.Accept(second) |
| 275 | if status, _, body = put(base.Origin, second); status != 200 || json.Unmarshal(body, &out) != nil || out.Origin != base.Origin || out.Revision != 1 || strings.Contains(string(body), second) || strings.Contains(string(body), `"token"`) { |
| 276 | t.Fatalf("second put %d %s", status, body) |
| 277 | } |
| 278 | if n := rows("SELECT count(*) FROM chat_assistant_hosts"); n != 1 { |
| 279 | t.Fatalf("%d host rows", n) |
| 280 | } |
| 281 | var stored, origin string |
| 282 | if err := r.inst.DB.Writer().QueryRow("SELECT token, origin FROM chat_assistant_hosts").Scan(&stored, &origin); err != nil { |
| 283 | t.Fatal(err) |
| 284 | } |
| 285 | if stored == "" || strings.Contains(stored, second) || strings.Contains(stored, token) || origin != base.Origin { |
| 286 | t.Fatalf("stored token %q origin %q", stored, origin) |
| 287 | } |
| 288 | // The instance reads it back as it was given. |
| 289 | if o, tok, ok, err := r.inst.Store.Chat().Host(r.ctx, Owner); err != nil || !ok || o != base.Origin || tok != second { |
| 290 | t.Fatalf("host %q %v %v", o, ok, err) |
| 291 | } |
| 292 | |
| 293 | for _, c := range []struct{ origin, token string }{ |
| 294 | {"http://base.example.com", token}, |
| 295 | {"https://base.example.com/api", token}, |
| 296 | {"https://base.example.com/", token}, |
| 297 | {"https://base.example.com?x=1", token}, |
| 298 | {"https://base.example.com#x", token}, |
| 299 | {"https://user@base.example.com", token}, |
| 300 | {"https://base.example.com:99999", token}, |
| 301 | {"ftp://base.example.com", token}, |
| 302 | {"base.example.com", token}, |
| 303 | {"", token}, |
| 304 | {"https://base.example.com", strings.Repeat("a", 19)}, |
| 305 | {"https://base.example.com", strings.Repeat("a", 513)}, |
| 306 | {"https://base.example.com", strings.Repeat("a", 20) + "\x01"}, |
| 307 | {"https://base.example.com", strings.Repeat("a", 20) + " b"}, |
| 308 | {"https://base.example.com", strings.Repeat("a", 20) + "é"}, |
| 309 | } { |
| 310 | if status, e, body := put(c.origin, c.token); status != 422 || e.Code != "invalid_input" { |
| 311 | t.Fatalf("%q %q: %d %s", c.origin, c.token, status, body) |
| 312 | } |
| 313 | } |
| 314 | base.Accept(strings.Repeat("a", 20)) |
| 315 | base.Accept(strings.Repeat("a", 512)) |
| 316 | if status, _, _ := put(base.Origin, strings.Repeat("a", 20)); status != 200 { |
| 317 | t.Fatalf("a 20-character token %d", status) |
| 318 | } |
| 319 | if status, _, _ := put(base.Origin, strings.Repeat("a", 512)); status != 200 { |
| 320 | t.Fatalf("a 512-character token %d", status) |
| 321 | } |
| 322 | if status, e, body := put("https://other.example.com", token); status != 403 || e.Code != "host_not_allowed" || e.CopyKey != "api.host_not_allowed" { |
| 323 | t.Fatalf("not on the allowlist %d %s", status, body) |
| 324 | } |
| 325 | if status, _, _ := raw(t, http.MethodPut, url, "", nil, `{"origin":"https://base.example.com","token":"`+token+`"}`); status != 401 { |
| 326 | t.Fatalf("no bearer %d", status) |
| 327 | } |
| 328 | if status, _, _ := raw(t, http.MethodPut, url, "", r.inst.Cookie(), `{"origin":"https://base.example.com","token":"`+token+`"}`); status != 401 { |
| 329 | t.Fatalf("a session cookie %d", status) |
| 330 | } |
| 331 | // Neither the log nor the audit ever sees a token. |
| 332 | if logs := r.inst.Logs(); strings.Contains(logs, token) || strings.Contains(logs, second) { |
| 333 | t.Fatal("a host token in the log") |
| 334 | } |
| 335 | if n := rows("SELECT count(*) FROM audit_events WHERE record_id LIKE ? OR record_id LIKE ?", "%"+token[:12]+"%", "%"+second[:12]+"%"); n != 0 { |
| 336 | t.Fatalf("%d audits carry a token", n) |
| 337 | } |
| 338 | if n := rows("SELECT count(*) FROM audit_events WHERE kind = 'assistant.host' AND actor = ?", Owner); n != 3 { |
| 339 | t.Fatalf("%d host audits", n) |
| 340 | } |
| 341 | |
| 342 | // With EQUIPO_ASSISTANT_HOSTS unset, every origin is refused. |
| 343 | closed := newRig(t) |
| 344 | for _, origin := range []string{"https://base.example.com", base.Origin} { |
| 345 | body, _ := json.Marshal(map[string]string{"origin": origin, "token": token}) |
| 346 | status, _, raw := raw(t, http.MethodPut, closed.inst.URL+"/api/v1/assistant/host", closed.client.Token, nil, string(body)) |
| 347 | if status != 403 || !strings.Contains(string(raw), `"host_not_allowed"`) { |
| 348 | t.Fatalf("unset allowlist %s: %d %s", origin, status, raw) |
| 349 | } |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | // TestContractLook: look, describe and use reach the person's Base |
| 354 | // outside the tool call's transaction: the call gets no result at once, |
| 355 | // and its result arrives when Base answers. |
| 356 | func TestContractLook(t *testing.T) { |
| 357 | o := newOpsRig(t) |
| 358 | o.connect(o.base.Token) |
| 359 | o.begin("What can I do?") |
| 360 | release := o.base.Hold("") |
| 361 | call := o.send("l1", wire.ToolLook, map[string]any{}) |
| 362 | o.until("Base listed", func() bool { return o.base.Calls("") == 1 }) |
| 363 | if n := o.results(call); n != 0 || o.state(call) != "pending" { |
| 364 | t.Fatalf("a result before Base answered: %d %s", n, o.state(call)) |
| 365 | } |
| 366 | release() |
| 367 | res := o.await(call)[call] |
| 368 | if res.IsError || !strings.HasPrefix(res.Text, "Base (base)\n") || !strings.Contains(res.Text, "\n- base_apps: List the person's apps") || !strings.Contains(res.Text, "\n- base_people: ") || !strings.Contains(res.Text, "\n- base_settings: ") { |
| 369 | t.Fatalf("look %+v", res) |
| 370 | } |
| 371 | if o.state(call) != "done" || !slices.Equal(o.base.Tokens(""), []string{o.base.Token}) { |
| 372 | t.Fatalf("state %s tokens %v", o.state(call), o.base.Tokens("")) |
| 373 | } |
| 374 | if res = o.tool("l2", wire.ToolLook, map[string]any{"query": "people"}); res.IsError || !strings.Contains(res.Text, "base_people") || strings.Contains(res.Text, "base_apps") { |
| 375 | t.Fatalf("look for people %+v", res) |
| 376 | } |
| 377 | |
| 378 | res = o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "base_apps"}) |
| 379 | var op struct { |
| 380 | Name string `json:"name"` |
| 381 | ReadOnly bool `json:"read_only"` |
| 382 | Destructive bool `json:"destructive"` |
| 383 | Idempotent bool `json:"idempotent"` |
| 384 | External bool `json:"external"` |
| 385 | Input json.RawMessage `json:"input_schema"` |
| 386 | } |
| 387 | if res.IsError || json.Unmarshal([]byte(res.Text), &op) != nil || op.Name != "base_apps" || !op.ReadOnly || op.Destructive || !op.Idempotent || op.External || !strings.Contains(string(op.Input), `"type":"object"`) { |
| 388 | t.Fatalf("describe %+v", res) |
| 389 | } |
| 390 | if res = o.tool("d2", wire.ToolDescribe, map[string]any{"operation": "base_nothing"}); !res.IsError || res.Code != "unknown_operation" { |
| 391 | t.Fatalf("describe unknown %+v", res) |
| 392 | } |
| 393 | if res = o.tool("d3", wire.ToolDescribe, map[string]any{}); !res.IsError || res.Code != "invalid" { |
| 394 | t.Fatalf("describe nothing %+v", res) |
| 395 | } |
| 396 | |
| 397 | res = o.use("u1", "base_apps", map[string]any{}) |
| 398 | if res.IsError || res.Text != `{"installed":[{"id":"shop","name":"Shop","address":"https://shop.example.com"}],"store":[],"oficina":[]}` || res.Replayed { |
| 399 | t.Fatalf("use %+v", res) |
| 400 | } |
| 401 | if o.base.Calls("base_apps") != 1 || !slices.Equal(o.base.Inputs("base_apps"), []string{"{}"}) || !slices.Equal(o.base.Keys("base_apps"), []string{""}) { |
| 402 | t.Fatalf("Base saw %d calls %v keys %v", o.base.Calls("base_apps"), o.base.Inputs("base_apps"), o.base.Keys("base_apps")) |
| 403 | } |
| 404 | // A failure Base reports comes back with its code. |
| 405 | o.base.Fail("base_people", "rate_limited") |
| 406 | if res = o.use("u2", "base_people", map[string]any{}); !res.IsError || res.Code != "rate_limited" { |
| 407 | t.Fatalf("Base failing %+v", res) |
| 408 | } |
| 409 | if res = o.tool("u3", wire.ToolUse, map[string]any{"operation": "base_apps"}); !res.IsError || res.Code != "invalid" { |
| 410 | t.Fatalf("use with no input %+v", res) |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | // TestContractHostIsPerPerson: each person's calls carry the token they |
| 415 | // registered, and only theirs; with none registered nothing is sent. |
| 416 | func TestContractHostIsPerPerson(t *testing.T) { |
| 417 | o := newOpsRig(t) |
| 418 | other := o.other("second@example.com") |
| 419 | other.begin("What are my apps?") |
| 420 | if res := other.use("u1", "base_apps", map[string]any{}); !res.IsError || res.Code != "not_connected" { |
| 421 | t.Fatalf("nobody connected %+v", res) |
| 422 | } |
| 423 | if o.base.Calls("") != 0 || o.base.Calls("base_apps") != 0 { |
| 424 | t.Fatalf("Base saw %d lists and %d calls with no host", o.base.Calls(""), o.base.Calls("base_apps")) |
| 425 | } |
| 426 | o.connect(o.base.Token) |
| 427 | if res := other.use("u2", "base_apps", map[string]any{"again": true}); !res.IsError || res.Code != "not_connected" { |
| 428 | t.Fatalf("someone else connected %+v", res) |
| 429 | } |
| 430 | if o.base.Calls("") != 0 { |
| 431 | t.Fatalf("another person's host was used: %v", o.base.Tokens("")) |
| 432 | } |
| 433 | second := o.base.Mint() |
| 434 | other.connect(second) |
| 435 | |
| 436 | o.begin("What are my apps?") |
| 437 | if res := o.use("u1", "base_apps", map[string]any{}); res.IsError { |
| 438 | t.Fatalf("first person %+v", res) |
| 439 | } |
| 440 | if res := other.use("u3", "base_apps", map[string]any{}); res.IsError { |
| 441 | t.Fatalf("second person %+v", res) |
| 442 | } |
| 443 | if got := o.base.Tokens("base_apps"); !slices.Equal(got, []string{o.base.Token, second}) { |
| 444 | t.Fatalf("tokens %v", got) |
| 445 | } |
| 446 | if got := o.base.Tokens(""); !slices.Equal(got, []string{o.base.Token, second}) { |
| 447 | t.Fatalf("list tokens %v", got) |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | var uuidV5 = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) |
| 452 | |
| 453 | // TestContractAssistantRetryRunsOnce: a keyed write runs once per turn, |
| 454 | // operation and input, whatever the call id or attempt; the key the |
| 455 | // provider gets is derived, never the call or turn id. |
| 456 | func TestContractAssistantRetryRunsOnce(t *testing.T) { |
| 457 | keyed := &keyedProvider{} |
| 458 | o := newOpsRig(t, keyed) |
| 459 | o.connect(o.base.Token) |
| 460 | turn := o.begin("Write milk down.") |
| 461 | milk := map[string]any{"line": "milk"} |
| 462 | first := o.use("w1", "ledger_write", milk) |
| 463 | again := o.use("w2", "ledger_write", milk) |
| 464 | o.runner.Send(o.ctx, "r-wait", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnWaiting, Reason: "limited"}) |
| 465 | o.runner.Send(o.ctx, "r-run2", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 2, State: wire.TurnRunning}) |
| 466 | o.until("attempt 2", func() bool { |
| 467 | return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND attempt = 2 AND state = ?", turn, wire.TurnRunning) == 1 |
| 468 | }) |
| 469 | o.attempt = 2 |
| 470 | moved := o.use("w3", "ledger_write", milk) |
| 471 | keys, inputs := keyed.calls() |
| 472 | if first.IsError || first.Replayed || first.Text != `{"written":true}` || len(keys) != 1 { |
| 473 | t.Fatalf("first %+v, %d calls", first, len(keys)) |
| 474 | } |
| 475 | for _, res := range []wire.ToolResult{again, moved} { |
| 476 | if !res.Replayed || res.Text != first.Text || res.Code != first.Code || res.IsError != first.IsError { |
| 477 | t.Fatalf("replay %+v, first %+v", res, first) |
| 478 | } |
| 479 | } |
| 480 | if !uuidV5.MatchString(keys[0]) || strings.Contains(keys[0], turn) || strings.Contains(keys[0], "w1") || !strings.Contains(inputs[0], `"client_id":"`+keys[0]+`"`) { |
| 481 | t.Fatalf("key %q input %s", keys[0], inputs[0]) |
| 482 | } |
| 483 | for _, call := range []string{turn + "/1/w1", turn + "/1/w2", turn + "/2/w3"} { |
| 484 | if strings.Contains(inputs[0], call) || strings.Contains(keys[0], call) { |
| 485 | t.Fatalf("a call id reached the provider: %s", call) |
| 486 | } |
| 487 | } |
| 488 | // Other input is another write, with another key. |
| 489 | if res := o.use("w4", "ledger_write", map[string]any{"line": "eggs"}); res.IsError || res.Replayed { |
| 490 | t.Fatalf("eggs %+v", res) |
| 491 | } |
| 492 | if keys, _ = keyed.calls(); len(keys) != 2 || keys[1] == keys[0] || !uuidV5.MatchString(keys[1]) { |
| 493 | t.Fatalf("keys %v", keys) |
| 494 | } |
| 495 | // A retry while the first is still out waits for it: one call, two |
| 496 | // results. |
| 497 | release := keyed.holdNext() |
| 498 | bread := map[string]any{"operation": "ledger_write", "input": map[string]any{"line": "bread"}} |
| 499 | w5 := o.send("w5", wire.ToolUse, bread) |
| 500 | o.until("the write out", func() bool { k, _ := keyed.calls(); return len(k) == 3 }) |
| 501 | w6 := o.send("w6", wire.ToolUse, bread) |
| 502 | o.until("the retry waiting", func() bool { return o.state(w6) == "waiting" }) |
| 503 | release() |
| 504 | got := o.await(w5, w6) |
| 505 | if got[w5].Replayed || !got[w6].Replayed || got[w5].Text != got[w6].Text || got[w5].IsError { |
| 506 | t.Fatalf("held write %+v, retry %+v", got[w5], got[w6]) |
| 507 | } |
| 508 | if keys, _ = keyed.calls(); len(keys) != 3 { |
| 509 | t.Fatalf("%d calls", len(keys)) |
| 510 | } |
| 511 | // A write that failed (it may have landed: a timeout) is not in the |
| 512 | // ledger, so a retry runs again, and with the same key, for the |
| 513 | // provider to make it once. |
| 514 | keyed.failNext() |
| 515 | jam := map[string]any{"line": "jam"} |
| 516 | if res := o.use("w7", "ledger_write", jam); !res.IsError || res.Code != "unavailable" { |
| 517 | t.Fatalf("failed write %+v", res) |
| 518 | } |
| 519 | if res := o.use("w8", "ledger_write", jam); res.IsError || res.Replayed { |
| 520 | t.Fatalf("retried write %+v", res) |
| 521 | } |
| 522 | if keys, _ = keyed.calls(); len(keys) != 5 || keys[3] != keys[4] { |
| 523 | t.Fatalf("keys after a failure %v", keys) |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | // TestContractUseRefusals: what deletes, reaches outside, or writes with |
| 528 | // no client key waits, and Base is sent nothing. |
| 529 | func TestContractUseRefusals(t *testing.T) { |
| 530 | o := newOpsRig(t) |
| 531 | o.base.Add( |
| 532 | assist.Operation{Name: "base_remove_app", Description: "Remove an app.", Destructive: true, App: "Base"}, |
| 533 | assist.Operation{Name: "base_invite", Description: "Email someone an invitation.", External: true, App: "Base"}, |
| 534 | assist.Operation{Name: "base_rename_app", Description: "Rename an app.", App: "Base"}, |
| 535 | ) |
| 536 | o.connect(o.base.Token) |
| 537 | o.begin("Tidy my apps.") |
| 538 | for _, c := range []struct{ op, code string }{{"base_remove_app", "not_yet"}, {"base_invite", "not_yet"}, {"base_rename_app", "write_not_supported"}, {"base_remove_app", "not_yet"}} { |
| 539 | res := o.use(c.op, c.op, map[string]any{"app": "Shop"}) |
| 540 | if !res.IsError || res.Code != c.code || res.Replayed || res.Text == "" { |
| 541 | t.Fatalf("%s %+v", c.op, res) |
| 542 | } |
| 543 | if n := o.base.Calls(c.op); n != 0 { |
| 544 | t.Fatalf("%s reached Base %d times", c.op, n) |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | // TestContractRemoteCallSurvivesRestart: a call out when the instance |
| 550 | // restarts is made again by the next process, and its result is |
| 551 | // delivered once. |
| 552 | func TestContractRemoteCallSurvivesRestart(t *testing.T) { |
| 553 | o := newOpsRig(t) |
| 554 | o.connect(o.base.Token) |
| 555 | turn := o.begin("What are my apps?") |
| 556 | release := o.base.Hold("base_apps") |
| 557 | defer release() |
| 558 | call := o.send("u1", wire.ToolUse, map[string]any{"operation": "base_apps", "input": map[string]any{}}) |
| 559 | o.until("the call out", func() bool { return o.base.Calls("base_apps") == 1 }) |
| 560 | o.inst.Restart(t) |
| 561 | runner, err := DialRunnerHello(o.ctx, o.inst.URL, o.rig.runner, primaryAt(wire.Hello{Generation: o.runner.Welcome.Generation, Repos: []string{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": "test"}}, wire.ProtocolAssistant)) |
| 562 | if err != nil { |
| 563 | t.Fatal(err) |
| 564 | } |
| 565 | t.Cleanup(runner.Close) |
| 566 | o.runner = runner |
| 567 | runner.Send(o.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: turn, Attempt: 1, State: wire.TurnRunning}}}) |
| 568 | o.until("the call made again", func() bool { return o.base.Calls("base_apps") == 2 }) |
| 569 | if o.state(call) != "pending" || o.results(call) != 0 { |
| 570 | t.Fatalf("before Base answered: %s, %d results", o.state(call), o.results(call)) |
| 571 | } |
| 572 | release() |
| 573 | if res := o.await(call)[call]; res.IsError || !strings.Contains(res.Text, "Shop") { |
| 574 | t.Fatalf("after restart %+v", res) |
| 575 | } |
| 576 | // A later call's result is the next thing: nothing more for the first. |
| 577 | fence := o.send("n1", wire.ToolReadNotes, map[string]any{}) |
| 578 | o.await(fence) |
| 579 | if n := o.results(call); n != 1 || o.state(call) != "done" { |
| 580 | t.Fatalf("%d results, %s", n, o.state(call)) |
| 581 | } |
| 582 | } |
| 583 | |
| 584 | // TestContractUseAudited: every use is audited, by operation and outcome |
| 585 | // only: never its input or output. A read asked again runs again (R11); |
| 586 | // a write asked again is replayed. |
| 587 | func TestContractUseAudited(t *testing.T) { |
| 588 | o := newOpsRig(t, &keyedProvider{}) |
| 589 | o.base.Add(assist.Operation{Name: "base_remove_app", Description: "Remove an app.", Destructive: true, App: "Base"}) |
| 590 | o.connect(o.base.Token) |
| 591 | o.begin("Look after my apps.") |
| 592 | o.use("u1", "base_apps", map[string]any{"marker": "zebra-417"}) |
| 593 | o.use("u2", "base_apps", map[string]any{"marker": "zebra-417"}) |
| 594 | o.use("w1", "ledger_write", map[string]any{"line": "zebra-417"}) |
| 595 | o.use("w2", "ledger_write", map[string]any{"line": "zebra-417"}) |
| 596 | o.use("u3", "base_remove_app", map[string]any{"marker": "zebra-417"}) |
| 597 | o.base.Fail("base_people", "rate_limited") |
| 598 | o.use("u4", "base_people", map[string]any{"marker": "zebra-417"}) |
| 599 | o.tool("l1", wire.ToolLook, map[string]any{"query": "apps"}) |
| 600 | o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "base_apps"}) |
| 601 | rows, err := o.inst.DB.Writer().Query("SELECT actor, record_id FROM audit_events WHERE kind = 'assistant.use' ORDER BY id") |
| 602 | if err != nil { |
| 603 | t.Fatal(err) |
| 604 | } |
| 605 | defer rows.Close() |
| 606 | var got []string |
| 607 | for rows.Next() { |
| 608 | var actor, record string |
| 609 | if err := rows.Scan(&actor, &record); err != nil { |
| 610 | t.Fatal(err) |
| 611 | } |
| 612 | if actor != Owner { |
| 613 | t.Fatalf("actor %q", actor) |
| 614 | } |
| 615 | got = append(got, record) |
| 616 | } |
| 617 | if want := []string{"base_apps ok", "base_apps ok", "ledger_write ok", "ledger_write replayed", "base_remove_app not_yet", "base_people rate_limited"}; !slices.Equal(got, want) { |
| 618 | t.Fatalf("audits %q, want %q", got, want) |
| 619 | } |
| 620 | if n := o.rows("SELECT count(*) FROM audit_events WHERE record_id LIKE '%zebra%' OR record_id LIKE '%Shop%' OR record_id LIKE '%apps\":%'"); n != 0 { |
| 621 | t.Fatalf("%d audits carry a payload", n) |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | // TestContractRemoteCallEndsWithTurn: a turn that ends while its call is |
| 626 | // out gets no result; the call is recorded done. |
| 627 | func TestContractRemoteCallEndsWithTurn(t *testing.T) { |
| 628 | o := newOpsRig(t) |
| 629 | o.connect(o.base.Token) |
| 630 | turn := o.begin("What are my apps?") |
| 631 | release := o.base.Hold("base_apps") |
| 632 | defer release() |
| 633 | call := o.send("u1", wire.ToolUse, map[string]any{"operation": "base_apps", "input": map[string]any{}}) |
| 634 | o.until("the call out", func() bool { return o.base.Calls("base_apps") == 1 }) |
| 635 | if _, err := o.a.Cancel(o.ctx, turn); err != nil { |
| 636 | t.Fatal(err) |
| 637 | } |
| 638 | if _, _, err := o.runner.Expect(o.ctx, wire.FrameCancel); err != nil { |
| 639 | t.Fatal(err) |
| 640 | } |
| 641 | o.runner.Send(o.ctx, "r-cancelled", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"}) |
| 642 | o.until("cancelled", func() bool { |
| 643 | return o.rows("SELECT count(*) FROM chat_turns WHERE id = ? AND state = ?", turn, wire.TurnCancelled) == 1 |
| 644 | }) |
| 645 | release() |
| 646 | o.until("the call done", func() bool { return o.state(call) == "done" }) |
| 647 | if n := o.results(call); n != 0 { |
| 648 | t.Fatalf("%d results for an ended turn", n) |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | // TestContractAssistantResultsFitTheFrame: every look, describe and use |
| 653 | // result fits the 64 KB tool frame. A long list is cut short with a note; |
| 654 | // a schema or output too large to send is refused. |
| 655 | func TestContractAssistantResultsFitTheFrame(t *testing.T) { |
| 656 | const frame = 64 << 10 |
| 657 | o := newOpsRig(t) |
| 658 | var many []assist.Operation |
| 659 | for i := range 200 { |
| 660 | many = append(many, assist.Operation{Name: "base_" + itoa(i) + "_" + strings.Repeat("n", 250), Description: strings.Repeat("d", 200), ReadOnly: true, App: "Many"}) |
| 661 | } |
| 662 | o.base.Add(many...) |
| 663 | o.base.Add(assist.Operation{Name: "base_schema", Description: "A large schema.", ReadOnly: true, App: "Base", Input: json.RawMessage(`{"type":"object","description":"` + strings.Repeat("s", 66<<10) + `"}`)}) |
| 664 | o.base.Add(assist.Operation{Name: "base_quotes", Description: "A quoted answer.", ReadOnly: true, App: "Base"}) |
| 665 | // Under the registry's 48 KB, but twice that once escaped in a frame. |
| 666 | o.base.Answer("base_quotes", `{"s":"`+strings.Repeat(`\"`, 23<<10)+`"}`) |
| 667 | o.connect(o.base.Token) |
| 668 | o.begin("Show me everything.") |
| 669 | size := func(res wire.ToolResult) int { raw, _ := json.Marshal(res); return len(raw) } |
| 670 | |
| 671 | look := o.tool("l1", wire.ToolLook, map[string]any{}) |
| 672 | if look.IsError || size(look) > frame || !strings.HasPrefix(look.Text, "Base (base)\n- base_apps") || !strings.HasSuffix(look.Text, "use look with a query to narrow it.") { |
| 673 | t.Fatalf("look of %d bytes: %.200q ... %q", size(look), look.Text, look.Text[max(0, len(look.Text)-120):]) |
| 674 | } |
| 675 | if res := o.tool("d1", wire.ToolDescribe, map[string]any{"operation": "base_schema"}); !res.IsError || res.Code != "too_large" || size(res) > frame { |
| 676 | t.Fatalf("describe a large schema %+v", res.Code) |
| 677 | } |
| 678 | if res := o.use("u1", "base_quotes", map[string]any{}); !res.IsError || res.Code != "too_large" || size(res) > frame { |
| 679 | t.Fatalf("use with a large answer %d %+v", size(res), res.Code) |
| 680 | } |
| 681 | if res := o.use("u2", "base_apps", map[string]any{}); res.IsError { |
| 682 | t.Fatalf("a small answer %+v", res) |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | // TestContractUseReadRunsAgain (Ruling R11): a read asked again in the |
| 687 | // turn, while the first is out or after, runs again; it is never |
| 688 | // another call's result, replayed. |
| 689 | func TestContractUseReadRunsAgain(t *testing.T) { |
| 690 | o := newOpsRig(t) |
| 691 | o.connect(o.base.Token) |
| 692 | o.begin("What are my apps?") |
| 693 | apps := map[string]any{"operation": "base_apps", "input": map[string]any{}} |
| 694 | release := o.base.Hold("base_apps") |
| 695 | first := o.send("r1", wire.ToolUse, apps) |
| 696 | o.until("the read out", func() bool { return o.base.Calls("base_apps") == 1 }) |
| 697 | second := o.send("r2", wire.ToolUse, apps) |
| 698 | o.until("the second waiting", func() bool { return o.state(second) == "waiting" }) |
| 699 | release() |
| 700 | got := o.await(first, second) |
| 701 | if got[first].IsError || got[second].IsError || got[first].Replayed || got[second].Replayed { |
| 702 | t.Fatalf("reads %+v", got) |
| 703 | } |
| 704 | if n := o.base.Calls("base_apps"); n != 2 { |
| 705 | t.Fatalf("%d calls to Base for two reads", n) |
| 706 | } |
| 707 | if third := o.use("r3", "base_apps", map[string]any{}); third.IsError || third.Replayed || o.base.Calls("base_apps") != 3 { |
| 708 | t.Fatalf("third %+v, %d calls", third, o.base.Calls("base_apps")) |
| 709 | } |
| 710 | } |
| 711 | |