-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathai.go
More file actions
1720 lines (1534 loc) · 50.9 KB
/
Copy pathai.go
File metadata and controls
1720 lines (1534 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ai
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
goruntime "runtime"
"runtime/debug"
"slices"
"strings"
"sync"
"time"
"github.com/google/jsonschema-go/jsonschema"
"github.com/google/uuid"
"github.com/modelcontextprotocol/go-sdk/mcp"
aiv1 "github.com/rilldata/rill/proto/gen/rill/ai/v1"
"github.com/rilldata/rill/runtime"
"github.com/rilldata/rill/runtime/drivers"
"github.com/rilldata/rill/runtime/pkg/activity"
"github.com/rilldata/rill/runtime/pkg/graceful"
"github.com/rilldata/rill/runtime/pkg/observability"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
)
// maxMessageSizeBytes is the maximum allowed size of a message's contents.
// Exceeding it will result in an error.
const maxMessageSizeBytes = 100 * 1024 // 100 KB
// reservedInputTokens is headroom subtracted from the model's input token limit to make room for
// tool definitions, model output (some providers share one context window between input and output),
// and token estimation error.
const reservedInputTokens = 64_000
// Tracer for instrumenting requests.
var tracer = otel.Tracer("github.com/rilldata/rill/runtime/ai")
// Runner tracks available tools and manages the lifecycle of AI sessions.
type Runner struct {
Runtime *runtime.Runtime
Activity *activity.Client
Tools map[string]*CompiledTool
}
// NewRunner creates a new Runner.
func NewRunner(rt *runtime.Runtime, activity *activity.Client) *Runner {
r := &Runner{
Runtime: rt,
Activity: activity,
Tools: make(map[string]*CompiledTool),
}
RegisterTool(r, &RouterAgent{Runtime: rt})
RegisterTool(r, &AnalystAgent{Runtime: rt})
RegisterTool(r, &DeveloperAgent{Runtime: rt})
RegisterTool(r, &FeedbackAgent{Runtime: rt})
RegisterTool(r, &ListMetricsViews{Runtime: rt})
RegisterTool(r, &GetMetricsView{Runtime: rt})
RegisterTool(r, &GetCanvas{Runtime: rt})
RegisterTool(r, &QueryMetricsViewSummary{Runtime: rt})
RegisterTool(r, &QueryMetricsView{Runtime: rt})
RegisterTool(r, &CreateChart{Runtime: rt})
RegisterTool(r, &DevelopFile{Runtime: rt})
RegisterTool(r, &ListFiles{Runtime: rt})
RegisterTool(r, &SearchFiles{Runtime: rt})
RegisterTool(r, &ReadFile{Runtime: rt})
RegisterTool(r, &WriteFile{Runtime: rt})
RegisterTool(r, &ProjectStatus{Runtime: rt})
RegisterTool(r, &QuerySQL{Runtime: rt})
RegisterTool(r, &ListTables{Runtime: rt})
RegisterTool(r, &ShowTable{Runtime: rt})
RegisterTool(r, &ListBuckets{Runtime: rt})
RegisterTool(r, &ListBucketObjects{Runtime: rt})
RegisterTool(r, &Navigate{})
return r
}
// SessionOptions provides options for initializing a new session.
type SessionOptions struct {
InstanceID string
SessionID string
CreateIfNotExists bool
Claims *runtime.SecurityClaims
UserAgent string
}
// Session creates or loads an AI session.
func (r *Runner) Session(ctx context.Context, opts *SessionOptions) (res *Session, resErr error) {
// Load instance metadata to get project instructions
instance, err := r.Runtime.Instance(ctx, opts.InstanceID)
if err != nil {
return nil, fmt.Errorf("failed to get instance %q: %w", opts.InstanceID, err)
}
// Open catalog
catalog, release, err := r.Runtime.Catalog(ctx, opts.InstanceID)
if err != nil {
return nil, err
}
defer release()
// Create or load the session in the catalog
var session *drivers.AISession
var messages []*Message
if opts.SessionID != "" {
session, err = catalog.FindAISession(ctx, opts.SessionID)
if err != nil {
return nil, fmt.Errorf("failed to find session %q: %w", opts.SessionID, err)
}
// Check access: you can access anonymous sessions, your own sessions, and shared sessions.
// For shared sessions, if you are not the owner, you can only see messages up to the SharedUntilMessageID (inclusive).
// For sessions without an owner (unauthenticated users using a public project), we don't check access and rely on security by obscurity (generally a decent trade-off, but specifically introduced to get citation links over MCP working for unauthenticated demos).
// It's important to respect SkipChecks to ensure access in Rill Developer (where auth is disabled, but SkipChecks is true).
var retrieveUntilMessageID string
if session.OwnerID != "" && session.OwnerID != opts.Claims.UserID && !opts.Claims.SkipChecks {
if session.SharedUntilMessageID == "" {
return nil, fmt.Errorf("%w: access denied to session %q", runtime.ErrForbidden, session.ID)
}
retrieveUntilMessageID = session.SharedUntilMessageID
}
ms, err := catalog.FindAIMessages(ctx, opts.SessionID)
if err != nil {
return nil, fmt.Errorf("failed to find messages for session %q: %w", opts.SessionID, err)
}
for _, m := range ms {
messages = append(messages, &Message{
ID: m.ID,
ParentID: m.ParentID,
SessionID: m.SessionID,
Time: m.CreatedOn,
Index: m.Index,
Role: Role(m.Role),
Type: MessageType(m.Type),
Tool: m.Tool,
ContentType: MessageContentType(m.ContentType),
Content: m.Content,
})
// only load messages up to and including that retrieveUntilMessageID; messages are ordered by "Index" ascending.
if m.ID == retrieveUntilMessageID {
break
}
}
}
if opts.SessionID == "" {
session = &drivers.AISession{
ID: uuid.NewString(),
InstanceID: opts.InstanceID,
OwnerID: opts.Claims.UserID,
Title: "",
UserAgent: opts.UserAgent,
CreatedOn: time.Now(),
UpdatedOn: time.Now(),
}
err = catalog.InsertAISession(ctx, session)
if err != nil {
return nil, fmt.Errorf("failed to create session: %w", err)
}
}
// Setup logger
logger := r.Runtime.Logger.Named("ai").With(
zap.String("instance_id", opts.InstanceID),
zap.String("ai_session_id", session.ID),
zap.String("user_id", opts.Claims.UserID),
)
// Setup scoped activity client
attrs := []attribute.KeyValue{
attribute.String("instance_id", instance.ID),
attribute.String("ai_session_id", session.ID),
attribute.String(activity.AttrKeyUserID, opts.Claims.UserID),
}
for k, v := range instance.Annotations {
attrs = append(attrs, attribute.String(k, v))
}
activityClient := r.Activity.With(attrs...)
// Create the session
base := &BaseSession{
id: session.ID,
instanceID: opts.InstanceID,
claims: opts.Claims,
runner: r,
logger: logger,
activity: activityClient,
projectInstructions: instance.AIInstructions,
managedAI: instance.ResolveAIConnector() == instance.AdminConnector,
acquireLLM: func(ctx context.Context) (drivers.AIService, func(), error) {
return r.Runtime.AI(ctx, opts.InstanceID)
},
acquireCatalog: func(ctx context.Context) (drivers.CatalogStore, func(), error) {
return r.Runtime.Catalog(ctx, opts.InstanceID)
},
dto: session,
messages: messages,
subscribers: make(map[chan *Message]struct{}),
}
return &Session{
BaseSession: base,
}, nil
}
// ForkSession creates a new session cloned from an existing session.
func (r *Runner) ForkSession(ctx context.Context, opts *SessionOptions) (string, error) {
if opts.SessionID == "" {
return "", errors.New("cannot fork session: SessionID is empty")
}
session, err := r.Session(ctx, opts)
if err != nil {
return "", fmt.Errorf("failed to load session to fork: %w", err)
}
forked := &drivers.AISession{
ID: uuid.NewString(),
InstanceID: opts.InstanceID,
OwnerID: opts.Claims.UserID,
Title: session.CatalogSession().Title + " (forked)",
UserAgent: opts.UserAgent,
ForkedFromSessionID: session.ID(),
CreatedOn: time.Now(),
UpdatedOn: time.Now(),
}
catalog, release, err := r.Runtime.Catalog(ctx, opts.InstanceID)
if err != nil {
return "", fmt.Errorf("failed to open catalog: %w", err)
}
defer release()
err = catalog.InsertAISession(ctx, forked)
if err != nil {
return "", fmt.Errorf("failed to fork session: %w", err)
}
// Map of old message IDs to new message IDs
oldToNewMessageID := make(map[string]string)
oldToNewMessageID[""] = ""
// Clone messages
for _, m := range session.Messages() {
id := uuid.NewString()
oldToNewMessageID[m.ID] = id
pid, ok := oldToNewMessageID[m.ParentID]
if !ok {
return "", fmt.Errorf("failed to clone message %q: parent message %q not found", m.ID, m.ParentID)
}
newMsg := &drivers.AIMessage{
ID: id,
ParentID: pid,
SessionID: forked.ID,
CreatedOn: time.Now(),
UpdatedOn: time.Now(),
Index: m.Index,
Role: string(m.Role),
Type: string(m.Type),
Tool: m.Tool,
ContentType: string(m.ContentType),
Content: m.Content,
}
err = catalog.InsertAIMessage(ctx, newMsg)
if err != nil {
return "", fmt.Errorf("failed to clone message %q: %w", m.ID, err)
}
}
return forked.ID, nil
}
// Tool is an interface for an AI tool.
type Tool[In, Out any] interface {
Spec() *mcp.Tool
CheckAccess(context.Context) (bool, error)
Handler(ctx context.Context, args In) (Out, error)
}
// CompiledTool is the internal representation of a registered tool.
type CompiledTool struct {
Name string
Spec *mcp.Tool
CheckAccess func(context.Context) (bool, error)
UnmarshalArgs func(content string) (any, error)
UnmarshalResult func(content string) (any, error)
JSONHandler func(ctx context.Context, input json.RawMessage) (json.RawMessage, error)
RegisterWithMCPServer func(srv *mcp.Server)
}
// AsProto converts the CompiledTool to a protocol buffer representation.
func (t *CompiledTool) AsProto() (*aiv1.Tool, error) {
var meta *structpb.Struct
if t.Spec.Meta != nil {
var err error
meta, err = structpb.NewStruct(t.Spec.Meta)
if err != nil {
return nil, fmt.Errorf("failed to convert meta for tool %q: %w", t.Name, err)
}
}
var inputSchema string
if t.Spec.InputSchema != nil {
inputSchemaBytes, err := json.Marshal(t.Spec.InputSchema)
if err != nil {
return nil, fmt.Errorf("failed to marshal input schema for tool %q: %w", t.Name, err)
}
inputSchema = string(inputSchemaBytes)
// OpenAI currently does not accept object schemas without explicit properties.
// So for now, we skip such schemas.
if s, ok := t.Spec.InputSchema.(*jsonschema.Schema); ok && s != nil && s.Properties == nil {
inputSchema = ""
}
}
var outputSchema string
if t.Spec.OutputSchema != nil {
outputSchemaBytes, err := json.Marshal(t.Spec.OutputSchema)
if err != nil {
return nil, fmt.Errorf("failed to marshal output schema for tool %q: %w", t.Name, err)
}
outputSchema = string(outputSchemaBytes)
// For consistency with input schema, skip object schemas without explicit properties.
if s, ok := t.Spec.OutputSchema.(*jsonschema.Schema); ok && s != nil && s.Properties == nil {
outputSchema = ""
}
}
return &aiv1.Tool{
Name: t.Spec.Name,
DisplayName: t.Spec.Title,
Description: t.Spec.Description,
Meta: meta,
InputSchema: inputSchema,
OutputSchema: outputSchema,
}, nil
}
// RegisterTool registers a new tool with the Runner.
func RegisterTool[In, Out any](s *Runner, t Tool[In, Out]) {
spec := t.Spec()
if spec.InputSchema == nil {
var err error
spec.InputSchema, err = schemaFor[In](false)
if err != nil {
panic(fmt.Sprintf("failed to infer input schema for tool %q: %v", spec.Name, err))
}
}
if spec.OutputSchema == nil {
var err error
spec.OutputSchema, err = schemaFor[Out](true)
if err != nil {
panic(fmt.Sprintf("failed to infer output schema for tool %q: %v", spec.Name, err))
}
}
s.Tools[spec.Name] = &CompiledTool{
Name: spec.Name,
Spec: spec,
CheckAccess: t.CheckAccess,
UnmarshalArgs: func(content string) (any, error) {
var args In
if err := json.Unmarshal([]byte(content), &args); err != nil {
return nil, err
}
return args, nil
},
UnmarshalResult: func(content string) (any, error) {
var result Out
if err := json.Unmarshal([]byte(content), &result); err != nil {
return nil, err
}
return result, nil
},
JSONHandler: func(ctx context.Context, input json.RawMessage) (json.RawMessage, error) {
var args In
if err := json.Unmarshal(input, &args); err != nil {
return nil, err
}
result, err := t.Handler(ctx, args)
if err != nil {
return nil, err
}
data, err := json.Marshal(result)
if err != nil {
return nil, fmt.Errorf("failed to marshal result for tool %q: %w", spec.Name, err)
}
return data, nil
},
RegisterWithMCPServer: func(srv *mcp.Server) {
mcp.AddTool(srv, spec, func(ctx context.Context, req *mcp.CallToolRequest, args In) (*mcp.CallToolResult, Out, error) {
s := GetSession(ctx)
var res Out
_, err := s.CallToolWithOptions(ctx, &CallToolOptions{
Role: RoleAssistant,
Tool: spec.Name,
Out: &res,
Args: args,
})
return nil, res, err
})
},
}
}
// schemaFor generates a JSON schema for a given type.
// If ignoreIfAny is true, it will return a nil schema if T has type any (use for MCP output schema, where no schema means unstructured result).
// It is loosely derived from similar logic in github.com/modelcontextprotocol/go-sdk.
func schemaFor[T any](ignoreIfAny bool) (*jsonschema.Schema, error) {
if reflect.TypeFor[T]() == reflect.TypeFor[any]() {
if ignoreIfAny {
return nil, nil
}
return &jsonschema.Schema{Type: "object"}, nil
}
tt := reflect.TypeFor[T]()
if tt.Kind() == reflect.Pointer {
tt = tt.Elem()
}
schema, err := jsonschema.ForType(tt, &jsonschema.ForOptions{})
if err != nil {
return nil, err
}
return schema, nil
}
// Role is the role of the actor that created a message.
type Role string
const (
RoleSystem Role = "system"
RoleUser Role = "user"
RoleAssistant Role = "assistant"
RoleTool Role = "tool"
)
// MessageType is the type of message being sent.
type MessageType string
const (
MessageTypeCall MessageType = "call"
MessageTypeProgress MessageType = "progress"
MessageTypeResult MessageType = "result"
)
// MessageContentType is the type of content contained in a message.
type MessageContentType string
const (
MessageContentTypeText MessageContentType = "text"
MessageContentTypeJSON MessageContentType = "json"
MessageContentTypeError MessageContentType = "error"
)
// Message represents a message in an AI session.
// Unlike lower-level LLM messages, the messages here include a call hierarchy, enabling tracking of calls and results inside tool calls.
//
// Mental model:
// - Messages represent user input, tool calls/results, LLM thinking, LLM responses.
// - Messages can be called by users, deterministic code, or LLMs.
// - LLM invocations retrieve messages from current scope for context.
type Message struct {
// ID is unique for each message.
ID string `json:"id" yaml:"id"`
// ParentID is the ID of the parent message, usually the current tool call.
ParentID string `json:"parent_id" yaml:"parent_id"`
// SessionID is the ID of the session this message belongs to.
SessionID string `json:"session_id" yaml:"session_id"`
// Time the message was created.
Time time.Time `json:"time" yaml:"time"`
// Index of the message in the session. Used to order messages returned at the same time.
Index int `json:"index" yaml:"index"`
// Role is the actor that created the message.
Role Role `json:"role" yaml:"role"`
// Type is the type of the message.
// For any given call, there will be only one "result" or "error" message.
Type MessageType `json:"type" yaml:"type"`
// Tool is the name of the tool that emitted the message, if any.
Tool string `json:"tool"`
// ContentType is the type of the Content string.
ContentType MessageContentType `json:"content_type" yaml:"content_type"`
// Content is the content of the message.
Content string `json:"content" yaml:"content"`
// dirty is true if the Message has not yet been persisted.
dirty bool
}
// sessionCtxKey is used for saving a session in a context.
type sessionCtxKey struct{}
// GetSession retrieves a session from a context.
func GetSession(ctx context.Context) *Session {
return ctx.Value(sessionCtxKey{}).(*Session)
}
// WithSession adds a session to a context.
func WithSession(ctx context.Context, s *Session) context.Context {
return context.WithValue(ctx, sessionCtxKey{}, s)
}
// BaseSession contains the session implementation that is not specific to the current call.
type BaseSession struct {
id string
instanceID string
claims *runtime.SecurityClaims
runner *Runner
logger *zap.Logger
activity *activity.Client
projectInstructions string
managedAI bool // true if completions use the Rill-managed AI connector (billable tokens); false for bring-your-own-model
acquireLLM func(ctx context.Context) (drivers.AIService, func(), error)
acquireCatalog func(ctx context.Context) (drivers.CatalogStore, func(), error)
mu sync.RWMutex
dto *drivers.AISession
dtoDirty bool
messages []*Message
messagesDirty bool
subscribers map[chan *Message]struct{}
}
func (s *BaseSession) Flush(ctx context.Context) error {
// Flushes may happen after a context cancellation. Make sure we have at least a bit of time to save.
ctx, cancel := graceful.WithMinimumDuration(ctx, 5*time.Second)
defer cancel()
// Exit early if nothing to flush
if !s.dtoDirty && !s.messagesDirty {
return nil
}
// Open the catalog
catalog, release, err := s.acquireCatalog(ctx)
if err != nil {
return err
}
defer release()
// Update session metadata
if s.dtoDirty {
err = catalog.UpdateAISession(ctx, s.dto)
if err != nil {
return err
}
s.dtoDirty = false
}
// Flush messages
if s.messagesDirty {
for _, msg := range s.messages {
if !msg.dirty {
continue
}
err = catalog.InsertAIMessage(ctx, &drivers.AIMessage{
ID: msg.ID,
ParentID: msg.ParentID,
SessionID: msg.SessionID,
CreatedOn: msg.Time,
UpdatedOn: msg.Time,
Index: msg.Index,
Role: string(msg.Role),
Type: string(msg.Type),
Tool: msg.Tool,
ContentType: string(msg.ContentType),
Content: msg.Content,
})
if err != nil {
return err
}
content := "<redacted>"
if msg.ContentType == MessageContentTypeError {
content = msg.Content
}
s.activity.Record(ctx, activity.EventTypeLog, "ai_message",
attribute.String("message_id", msg.ID),
attribute.String("parent_message_id", msg.ParentID),
attribute.String("user_agent", s.dto.UserAgent),
attribute.String("role", string(msg.Role)),
attribute.String("message_type", string(msg.Type)),
attribute.String("tool", msg.Tool),
attribute.String("content_type", string(msg.ContentType)),
attribute.String("content", content),
)
}
s.messagesDirty = false
}
return nil
}
func (s *BaseSession) ID() string {
return s.id
}
func (s *BaseSession) InstanceID() string {
return s.instanceID
}
func (s *BaseSession) CatalogSession() *drivers.AISession {
return s.dto
}
func (s *BaseSession) Claims() *runtime.SecurityClaims {
return s.claims
}
func (s *BaseSession) Title() string {
return s.dto.Title
}
func (s *BaseSession) Shared() bool {
return s.dto.SharedUntilMessageID != ""
}
func (s *BaseSession) Forked() bool {
return s.dto.ForkedFromSessionID != ""
}
func (s *BaseSession) UpdateTitle(ctx context.Context, title string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.dto.Title = title
s.dtoDirty = true
return nil
}
func (s *BaseSession) UpdateUserAgent(ctx context.Context, userAgent string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.dto.UserAgent = userAgent
s.dtoDirty = true
return nil
}
func (s *BaseSession) UpdateSharedUntilMessageID(ctx context.Context, messageID string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.dto.SharedUntilMessageID = messageID
s.dtoDirty = true
return nil
}
func (s *BaseSession) Subscribe() chan *Message {
ch := make(chan *Message)
s.mu.Lock()
s.subscribers[ch] = struct{}{}
s.mu.Unlock()
return ch
}
func (s *BaseSession) Unsubscribe(ch chan *Message) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.subscribers, ch)
close(ch)
}
func (s *BaseSession) WithParent(messageID string) *Session {
return &Session{
BaseSession: s,
ParentID: messageID,
}
}
func (s *BaseSession) ProjectInstructions() string {
return s.projectInstructions
}
func (s *BaseSession) SetLLM(acquireLLM func(ctx context.Context) (drivers.AIService, func(), error)) {
s.acquireLLM = acquireLLM
}
func (s *BaseSession) NextIndex() int {
return len(s.messages)
}
func (s *BaseSession) Message(predicates ...Predicate) (*Message, bool) {
for _, msg := range s.messages {
match := true
for _, p := range predicates {
if !p(msg) {
match = false
break
}
}
if match {
return msg, true
}
}
return nil, false
}
func (s *BaseSession) LatestMessage(predicates ...Predicate) (*Message, bool) {
for i := len(s.messages) - 1; i >= 0; i-- {
msg := s.messages[i]
match := true
for _, p := range predicates {
if !p(msg) {
match = false
break
}
}
if match {
return msg, true
}
}
return nil, false
}
func (s *BaseSession) Messages(predicates ...Predicate) []*Message {
if len(predicates) == 0 {
return slices.Clone(s.messages)
}
var res []*Message
for _, msg := range s.messages {
match := true
for _, p := range predicates {
if !p(msg) {
match = false
break
}
}
if match {
res = append(res, msg)
}
}
return res
}
func (s *BaseSession) MessagesWithResults(predicates ...Predicate) []*Message {
msgs := s.Messages(predicates...)
return s.ExpandMessages(msgs, func(m *Message) []*Message {
if m.Type != MessageTypeCall {
return []*Message{m}
}
resMsg, ok := s.Message(FilterByParent(m.ID), FilterByType(MessageTypeResult))
if !ok {
// Skip the call if there isn't a corresponding result.
return nil
}
return []*Message{m, resMsg}
})
}
func (s *BaseSession) MessagesWithChildren(predicates ...Predicate) []*Message {
msgs := s.Messages(predicates...)
msgs = s.ExpandMessages(msgs, func(m *Message) []*Message {
// If it's not a call, just return the message itself
res := []*Message{m}
if m.Type != MessageTypeCall {
return res
}
// Find it's children and return them too
subMsgs := s.Messages(FilterByParent(m.ID))
res = append(res, subMsgs...)
// For each child that's a call, add its result too
for _, sm := range subMsgs {
if sm.Type == MessageTypeCall {
subResMsg, ok := s.Message(FilterByParent(sm.ID), FilterByType(MessageTypeResult))
if ok {
res = append(res, subResMsg)
}
}
}
return res
})
// Sort by index to maintain order
slices.SortFunc(msgs, func(a, b *Message) int {
return a.Index - b.Index
})
return msgs
}
func (s *BaseSession) MessagesWithDescendents(predicates ...Predicate) []*Message {
ids := make(map[string]struct{})
for _, initial := range s.Messages(predicates...) {
ids[initial.ID] = struct{}{}
}
var res []*Message
for _, m := range s.messages {
if _, ok := ids[m.ID]; ok {
res = append(res, m)
} else if _, ok := ids[m.ParentID]; ok {
ids[m.ID] = struct{}{}
res = append(res, m)
}
}
return res
}
func (s *BaseSession) ExpandMessages(msgs []*Message, fn func(m *Message) []*Message) []*Message {
var res []*Message
for _, msg := range msgs {
newMsgs := fn(msg)
res = append(res, newMsgs...)
}
return res
}
func (s *BaseSession) LatestRootCall() *Message {
calls := s.Messages(FilterByRoot())
if len(calls) == 0 {
return nil
}
return calls[len(calls)-1]
}
type Predicate func(*Message) bool
func FilterByID(id string) Predicate {
return func(m *Message) bool {
return m.ID == id
}
}
func FilterByParent(parentID string) Predicate {
return func(m *Message) bool {
return m.ParentID == parentID
}
}
func FilterByRoot() Predicate {
return func(m *Message) bool {
return m.ParentID == ""
}
}
func FilterByType(typ MessageType) Predicate {
return func(m *Message) bool {
return m.Type == typ
}
}
func FilterByTool(tool string) Predicate {
return func(m *Message) bool {
return m.Tool == tool
}
}
// Session wraps a BaseSession with a reference to the current call's parent message.
type Session struct {
*BaseSession
ParentID string
}
// AddMessageOptions provides options for Session.AddMessage.
type AddMessageOptions struct {
Role Role
Type MessageType
Tool string
ContentType MessageContentType
Content string
}
// AddMessage adds a message linked to the current session's parent call.
func (s *Session) AddMessage(opts *AddMessageOptions) *Message {
msg := &Message{
ID: uuid.NewString(),
ParentID: s.ParentID,
SessionID: s.id,
Time: time.Now(),
Index: s.NextIndex(),
Role: opts.Role,
Type: opts.Type,
Tool: opts.Tool,
ContentType: opts.ContentType,
Content: opts.Content,
dirty: true,
}
s.mu.Lock()
defer s.mu.Unlock()
s.messages = append(s.messages, msg)
s.messagesDirty = true
for sub := range s.subscribers {
sub <- msg
}
return msg
}
func (s *Session) RootID() string {
root := s.ParentID
if root == "" {
panic("no parent ID set")
}
for range 100 { // Fail-safe, not expected to reach the limit
msg, ok := s.Message(FilterByID(root))
if !ok {
panic(fmt.Errorf("failed to find referenced message with ID %q", root))
}
if msg.ParentID == "" {
break
}
root = msg.ParentID
}
return root
}
func (s *Session) Tool(toolName string) (*CompiledTool, bool) {
t, ok := s.runner.Tools[toolName]
return t, ok
}
// CallResult contains the messages created during a tool call.
type CallResult struct {
Call *Message
Result *Message
}
// CallOptions provides options for Session.Call.
type CallOptions struct {
Role Role
Name string
Unwrap bool
Out any
Args any
Handler func(context.Context) (any, error)
}
// Call is the primary implementation for execution of tool calls.
// NOTE: This will be the primary implementation site for durable execution.
func (s *Session) Call(ctx context.Context, opts *CallOptions) (*CallResult, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
var argsJSON json.RawMessage
argsJSON, err := json.Marshal(opts.Args)
if err != nil {
return nil, fmt.Errorf("failed to marshal args: %w", err)
}
if len(argsJSON) > maxMessageSizeBytes {
return nil, fmt.Errorf("call args size %d exceeds maximum of %d bytes", len(argsJSON), maxMessageSizeBytes)
}
var callMsg *Message
callSession := s
callCtx := ctx
if !opts.Unwrap {
callMsg = s.AddMessage(&AddMessageOptions{
Role: opts.Role,
Type: MessageTypeCall,
Tool: opts.Name,
ContentType: MessageContentTypeJSON,
Content: string(argsJSON),
})
callSession = s.WithParent(callMsg.ID)
callCtx = WithSession(ctx, callSession)
}
handlerOut, handlerErr := func() (handlerOut any, handlerErr error) {
// Instrumentation and logging
callCtx, span := tracer.Start(callCtx, "ai.Session.Call", trace.WithAttributes(
attribute.String("ai_session_id", s.id),
attribute.String("tool", opts.Name),
attribute.String("args", string(argsJSON)),
semconv.EnduserID(s.claims.UserID),
))
s.logger.Info("tool call started", zap.String("tool", opts.Name))
start := time.Now()
// Gracefully handle panics in the tool handler
defer func() {
// Recover panics and handle as internal errors
if err := recover(); err != nil {
// Get stacktrace
stack := make([]byte, 64<<10)
stack = stack[:goruntime.Stack(stack, false)]
// Return an internal error