-
Notifications
You must be signed in to change notification settings - Fork 388
Expand file tree
/
Copy pathagent.go
More file actions
1355 lines (1174 loc) · 38.2 KB
/
Copy pathagent.go
File metadata and controls
1355 lines (1174 loc) · 38.2 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 agent
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/Agent-Field/agentfield/sdk/go/ai"
"github.com/Agent-Field/agentfield/sdk/go/client"
"github.com/Agent-Field/agentfield/sdk/go/did"
"github.com/Agent-Field/agentfield/sdk/go/types"
)
type executionContextKey struct{}
// ExecutionContext captures the headers AgentField sends with each execution request.
type ExecutionContext struct {
RunID string
ExecutionID string
ParentExecutionID string
SessionID string
ActorID string
WorkflowID string
ParentWorkflowID string
RootWorkflowID string
Depth int
AgentNodeID string
ReasonerName string
StartedAt time.Time
// DID fields (optional, populated if VCEnabled)
CallerDID string
TargetDID string
AgentNodeDID string
}
func init() {
rand.Seed(time.Now().UnixNano())
}
// HandlerFunc processes a reasoner invocation.
type HandlerFunc func(ctx context.Context, input map[string]any) (any, error)
// ReasonerOption applies metadata to a reasoner registration.
type ReasonerOption func(*Reasoner)
// WithInputSchema overrides the auto-generated input schema.
func WithInputSchema(raw json.RawMessage) ReasonerOption {
return func(r *Reasoner) {
if len(raw) > 0 {
r.InputSchema = raw
}
}
}
// WithOutputSchema overrides the default output schema.
func WithOutputSchema(raw json.RawMessage) ReasonerOption {
return func(r *Reasoner) {
if len(raw) > 0 {
r.OutputSchema = raw
}
}
}
// WithCLI marks this reasoner as CLI-accessible.
func WithCLI() ReasonerOption {
return func(r *Reasoner) {
r.CLIEnabled = true
}
}
// WithDefaultCLI marks the reasoner as the default CLI handler.
func WithDefaultCLI() ReasonerOption {
return func(r *Reasoner) {
r.CLIEnabled = true
r.DefaultCLI = true
}
}
// WithCLIFormatter registers a custom formatter for CLI output.
func WithCLIFormatter(formatter func(context.Context, any, error)) ReasonerOption {
return func(r *Reasoner) {
r.CLIFormatter = formatter
}
}
// WithDescription adds a human-readable description for help/list commands.
func WithDescription(desc string) ReasonerOption {
return func(r *Reasoner) {
r.Description = desc
}
}
// Reasoner represents a single handler exposed by the agent.
type Reasoner struct {
Name string
Handler HandlerFunc
InputSchema json.RawMessage
OutputSchema json.RawMessage
CLIEnabled bool
DefaultCLI bool
CLIFormatter func(context.Context, any, error)
Description string
}
// Config drives Agent behaviour.
type Config struct {
// NodeID is the unique identifier for this agent node. Required.
// Must be a non-empty identifier suitable for registration (alphanumeric
// characters, hyphens are recommended). Example: "my-agent-1".
NodeID string
// Version identifies the agent implementation version. Required.
// Typically in semver or short string form (e.g. "v1.2.3" or "1.0.0").
Version string
// TeamID groups related agents together for organization. Optional.
// Default: "default" (if empty, New() sets it to "default").
TeamID string
// AgentFieldURL is the base URL of the AgentField control plane server.
// Optional for local-only or serverless usage, required when registering
// with a control plane or making cross-node calls. Default: empty.
// Format: a valid HTTP/HTTPS URL, e.g. "https://agentfield.example.com".
AgentFieldURL string
// ListenAddress is the network address the agent HTTP server binds to.
// Optional. Default: ":8001" (if empty, New() sets it to ":8001").
// Format: "host:port" or ":port" (e.g. ":8001" or "0.0.0.0:8001").
ListenAddress string
// PublicURL is the public-facing base URL reported to the control plane.
// Optional. Default: "http://localhost" + ListenAddress (if empty,
// New() constructs a default using ListenAddress).
// Format: a valid HTTP/HTTPS URL.
PublicURL string
// Token is the bearer token used for authenticating to the control plane.
// Optional. Default: empty (no auth). When set, the token is sent as
// an Authorization: Bearer <token> header on control-plane requests.
Token string
// DeploymentType describes how the agent runs (affects execution behavior).
// Optional. Default: "long_running". Common values: "long_running",
// "serverless". Use a descriptive string for custom modes.
DeploymentType string
// LeaseRefreshInterval controls how frequently the agent refreshes its
// lease/heartbeat with the control plane. Optional.
// Default: 2m (2 minutes). Valid: any positive time.Duration.
LeaseRefreshInterval time.Duration
// DisableLeaseLoop disables automatic periodic lease refreshes.
// Optional. Default: false.
DisableLeaseLoop bool
// Logger is used for agent logging output. Optional.
// Default: a standard logger writing to stdout with the "[agent] " prefix
// (if nil, New() creates a default logger).
Logger *log.Logger
// AIConfig configures LLM/AI capabilities for the agent.
// Optional. If nil, AI features are disabled. Provide a valid
// *ai.Config to enable AI-related APIs.
AIConfig *ai.Config
// CLIConfig controls CLI-specific behaviour and help text.
// Optional. If nil, CLI behavior uses sensible defaults.
CLIConfig *CLIConfig
// MemoryBackend allows plugging in a custom memory storage backend.
// Optional. If nil, an in-memory backend is used (data lost on restart).
MemoryBackend MemoryBackend
// VCEnabled enables Decentralized Identity and Verifiable Credentials.
// When true, the agent registers with the DID system and can generate
// credentials for compliance audit trails. When false (default), all DID
// operations are disabled and return empty results. Optional; default: false.
VCEnabled bool
}
// CLIConfig controls CLI behaviour and presentation.
type CLIConfig struct {
AppName string
AppDescription string
DisableColors bool
DefaultOutputFormat string
HelpPreamble string
HelpEpilog string
EnvironmentVars []string
}
// Agent manages registration, lease renewal, and HTTP routing.
type Agent struct {
cfg Config
client *client.Client
httpClient *http.Client
reasoners map[string]*Reasoner
aiClient *ai.Client // AI/LLM client
memory *Memory // Memory system for state management
did *did.DIDManager // DID manager for identity and credentials
serverMu sync.RWMutex
server *http.Server
stopLease chan struct{}
logger *log.Logger
router http.Handler
handlerOnce sync.Once
initMu sync.Mutex
initialized bool
leaseLoopOnce sync.Once
defaultCLIReasoner string
}
// New constructs an Agent.
func New(cfg Config) (*Agent, error) {
if cfg.NodeID == "" {
return nil, errors.New("config.NodeID is required")
}
if cfg.Version == "" {
return nil, errors.New("config.Version is required")
}
if cfg.TeamID == "" {
cfg.TeamID = "default"
}
if cfg.ListenAddress == "" {
cfg.ListenAddress = ":8001"
}
if cfg.PublicURL == "" {
cfg.PublicURL = "http://localhost" + cfg.ListenAddress
}
if strings.TrimSpace(cfg.DeploymentType) == "" {
cfg.DeploymentType = "long_running"
}
if cfg.LeaseRefreshInterval <= 0 {
cfg.LeaseRefreshInterval = 2 * time.Minute
}
if cfg.Logger == nil {
cfg.Logger = log.New(os.Stdout, "[agent] ", log.LstdFlags)
}
httpClient := &http.Client{
Timeout: 15 * time.Second,
}
// Initialize AI client if config provided
var aiClient *ai.Client
var err error
if cfg.AIConfig != nil {
aiClient, err = ai.NewClient(cfg.AIConfig)
if err != nil {
return nil, fmt.Errorf("initialize AI client: %w", err)
}
}
a := &Agent{
cfg: cfg,
httpClient: httpClient,
reasoners: make(map[string]*Reasoner),
aiClient: aiClient,
memory: NewMemory(cfg.MemoryBackend),
stopLease: make(chan struct{}),
logger: cfg.Logger,
}
if strings.TrimSpace(cfg.AgentFieldURL) != "" {
c, err := client.New(cfg.AgentFieldURL, client.WithHTTPClient(httpClient), client.WithBearerToken(cfg.Token))
if err != nil {
return nil, err
}
a.client = c
}
// Initialize DID/VC if enabled
if cfg.VCEnabled && strings.TrimSpace(cfg.AgentFieldURL) != "" {
headers := make(map[string]string)
if cfg.Token != "" {
headers["Authorization"] = "Bearer " + cfg.Token
}
didClient, err := did.NewDIDClient(
cfg.AgentFieldURL,
headers,
)
if err != nil {
a.logger.Printf("warning: failed to create DID client: %v", err)
a.did = did.NewDIDManager(nil, cfg.NodeID)
} else {
a.did = did.NewDIDManager(didClient, cfg.NodeID)
// Extract reasoners for registration
reasoners := make([]map[string]any, 0, len(a.reasoners))
for name := range a.reasoners {
reasoners = append(reasoners, map[string]any{"id": name})
}
// Register agent; non-fatal if fails
if err := a.did.RegisterAgent(context.Background(), reasoners, []map[string]any{}); err != nil {
a.logger.Printf("warning: DID registration failed: %v", err)
}
}
} else {
// VCEnabled=false: create disabled manager
a.did = did.NewDIDManager(nil, cfg.NodeID)
}
return a, nil
}
func contextWithExecution(ctx context.Context, exec ExecutionContext) context.Context {
return context.WithValue(ctx, executionContextKey{}, exec)
}
func executionContextFrom(ctx context.Context) ExecutionContext {
if ctx == nil {
return ExecutionContext{}
}
if val, ok := ctx.Value(executionContextKey{}).(ExecutionContext); ok {
return val
}
return ExecutionContext{}
}
// ChildContext creates a new execution context for a nested local call.
func (ec ExecutionContext) ChildContext(agentNodeID, reasonerName string) ExecutionContext {
runID := ec.RunID
if runID == "" {
runID = ec.WorkflowID
}
if runID == "" {
runID = generateRunID()
}
workflowID := ec.WorkflowID
if workflowID == "" {
workflowID = runID
}
rootWorkflowID := ec.RootWorkflowID
if rootWorkflowID == "" {
rootWorkflowID = workflowID
}
return ExecutionContext{
RunID: runID,
ExecutionID: generateExecutionID(),
ParentExecutionID: ec.ExecutionID,
SessionID: ec.SessionID,
ActorID: ec.ActorID,
WorkflowID: workflowID,
ParentWorkflowID: workflowID,
RootWorkflowID: rootWorkflowID,
Depth: ec.Depth + 1,
AgentNodeID: agentNodeID,
ReasonerName: reasonerName,
StartedAt: time.Now(),
}
}
func generateRunID() string {
return fmt.Sprintf("run_%d_%06d", time.Now().UnixNano(), rand.Intn(1_000_000))
}
func generateExecutionID() string {
return fmt.Sprintf("exec_%d_%06d", time.Now().UnixNano(), rand.Intn(1_000_000))
}
func cloneInputMap(input map[string]any) map[string]any {
if input == nil {
return nil
}
copied := make(map[string]any, len(input))
for k, v := range input {
copied[k] = v
}
return copied
}
func stringFromMap(m map[string]any, keys ...string) string {
for _, key := range keys {
if val, ok := m[key]; ok {
if str, ok := val.(string); ok && strings.TrimSpace(str) != "" {
return strings.TrimSpace(str)
}
}
}
return ""
}
func rawToMap(raw json.RawMessage) map[string]any {
if len(raw) == 0 {
return map[string]any{}
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return map[string]any{}
}
return out
}
// RegisterReasoner makes a handler available at /reasoners/{name}.
func (a *Agent) RegisterReasoner(name string, handler HandlerFunc, opts ...ReasonerOption) {
if handler == nil {
panic("nil handler supplied")
}
meta := &Reasoner{
Name: name,
Handler: handler,
InputSchema: json.RawMessage(`{"type":"object","additionalProperties":true}`),
OutputSchema: json.RawMessage(`{"type":"object","additionalProperties":true}`),
}
for _, opt := range opts {
opt(meta)
}
if meta.DefaultCLI {
if a.defaultCLIReasoner != "" && a.defaultCLIReasoner != name {
a.logger.Printf("warn: default CLI reasoner already set to %s, ignoring default flag on %s", a.defaultCLIReasoner, name)
meta.DefaultCLI = false
} else {
a.defaultCLIReasoner = name
}
}
a.reasoners[name] = meta
}
// Initialize registers the agent with the AgentField control plane without starting a listener.
func (a *Agent) Initialize(ctx context.Context) error {
a.initMu.Lock()
defer a.initMu.Unlock()
if a.initialized {
return nil
}
if a.client == nil {
return errors.New("AgentFieldURL is required when running in server mode")
}
if len(a.reasoners) == 0 {
return errors.New("no reasoners registered")
}
if err := a.registerNode(ctx); err != nil {
return fmt.Errorf("register node: %w", err)
}
if err := a.markReady(ctx); err != nil {
a.logger.Printf("warn: initial status update failed: %v", err)
}
a.startLeaseLoop()
a.initialized = true
return nil
}
// Run intelligently routes between CLI and server modes.
func (a *Agent) Run(ctx context.Context) error {
args := os.Args[1:]
if len(args) == 0 && !a.hasCLIReasoners() {
return a.Serve(ctx)
}
if len(args) > 0 && args[0] == "serve" {
return a.Serve(ctx)
}
return a.runCLI(ctx, args)
}
// Serve starts the agent HTTP server, registers with the control plane, and blocks until ctx is cancelled.
func (a *Agent) Serve(ctx context.Context) error {
if err := a.Initialize(ctx); err != nil {
return err
}
if err := a.startServer(); err != nil {
return fmt.Errorf("start server: %w", err)
}
// listen for shutdown.
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
select {
case <-ctx.Done():
return a.shutdown(context.Background())
case sig := <-sigCh:
a.logger.Printf("received signal %s, shutting down", sig)
return a.shutdown(context.Background())
}
}
func (a *Agent) registerNode(ctx context.Context) error {
now := time.Now().UTC()
reasoners := make([]types.ReasonerDefinition, 0, len(a.reasoners))
for _, reasoner := range a.reasoners {
reasoners = append(reasoners, types.ReasonerDefinition{
ID: reasoner.Name,
InputSchema: reasoner.InputSchema,
OutputSchema: reasoner.OutputSchema,
})
}
payload := types.NodeRegistrationRequest{
ID: a.cfg.NodeID,
TeamID: a.cfg.TeamID,
BaseURL: strings.TrimSuffix(a.cfg.PublicURL, "/"),
Version: a.cfg.Version,
Reasoners: reasoners,
Skills: []types.SkillDefinition{},
CommunicationConfig: types.CommunicationConfig{
Protocols: []string{"http"},
HeartbeatInterval: "0s",
},
HealthStatus: "healthy",
LastHeartbeat: now,
RegisteredAt: now,
Metadata: map[string]any{
"deployment": map[string]any{
"environment": "development",
"platform": "go",
},
"sdk": map[string]any{
"language": "go",
},
},
Features: map[string]any{},
DeploymentType: a.cfg.DeploymentType,
}
_, err := a.client.RegisterNode(ctx, payload)
if err != nil {
return err
}
a.logger.Printf("node %s registered with AgentField", a.cfg.NodeID)
return nil
}
func (a *Agent) markReady(ctx context.Context) error {
score := 100
_, err := a.client.UpdateStatus(ctx, a.cfg.NodeID, types.NodeStatusUpdate{
Phase: "ready",
HealthScore: &score,
})
return err
}
func (a *Agent) startServer() error {
server := &http.Server{
Addr: a.cfg.ListenAddress,
Handler: a.Handler(),
}
a.serverMu.Lock()
a.server = server
a.serverMu.Unlock()
go func() {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
a.logger.Printf("server error: %v", err)
}
}()
a.logger.Printf("listening on %s", a.cfg.ListenAddress)
return nil
}
// Handler exposes the agent as an http.Handler for serverless or custom hosting scenarios.
func (a *Agent) Handler() http.Handler {
return a.handler()
}
// ServeHTTP implements http.Handler directly.
func (a *Agent) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.Handler().ServeHTTP(w, r)
}
// Execute runs a specific reasoner by name.
func (a *Agent) Execute(ctx context.Context, reasonerName string, input map[string]any) (any, error) {
reasoner, ok := a.reasoners[reasonerName]
if !ok {
return nil, fmt.Errorf("unknown reasoner %q", reasonerName)
}
if input == nil {
input = make(map[string]any)
}
return reasoner.Handler(ctx, input)
}
// HandleServerlessEvent allows custom serverless entrypoints to normalize arbitrary
// platform events (Lambda, Vercel, Supabase, etc.) before delegating to the agent.
// The adapter can rewrite the incoming event into the generic payload that
// handleExecute expects: keys like path, target/reasoner, input, execution_context.
func (a *Agent) HandleServerlessEvent(ctx context.Context, event map[string]any, adapter func(map[string]any) map[string]any) (map[string]any, int, error) {
if adapter != nil {
event = adapter(event)
}
path := stringFromMap(event, "path", "rawPath")
reasoner := stringFromMap(event, "reasoner", "target", "skill")
if reasoner == "" && path != "" {
cleaned := strings.Trim(path, "/")
parts := strings.Split(cleaned, "/")
if len(parts) >= 2 && (parts[0] == "execute" || parts[0] == "reasoners" || parts[0] == "skills") {
reasoner = parts[1]
} else if len(parts) == 1 {
reasoner = parts[0]
}
}
if reasoner == "" {
return map[string]any{"error": "missing target or reasoner"}, http.StatusBadRequest, nil
}
input := extractInputFromServerless(event)
execCtx := a.buildExecutionContextFromServerless(&http.Request{Header: http.Header{}}, event, reasoner)
ctx = contextWithExecution(ctx, execCtx)
handler, ok := a.reasoners[reasoner]
if !ok {
return map[string]any{"error": "reasoner not found"}, http.StatusNotFound, nil
}
result, err := handler.Handler(ctx, input)
if err != nil {
return map[string]any{"error": err.Error()}, http.StatusInternalServerError, nil
}
// Normalize to map for consistent JSON responses.
if payload, ok := result.(map[string]any); ok {
return payload, http.StatusOK, nil
}
return map[string]any{"result": result}, http.StatusOK, nil
}
func (a *Agent) handler() http.Handler {
a.handlerOnce.Do(func() {
mux := http.NewServeMux()
mux.HandleFunc("/health", a.healthHandler)
mux.HandleFunc("/discover", a.handleDiscover)
mux.HandleFunc("/execute", a.handleExecute)
mux.HandleFunc("/execute/", a.handleExecute)
mux.HandleFunc("/reasoners/", a.handleReasoner)
a.router = mux
})
return a.router
}
func (a *Agent) healthHandler(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
}
func (a *Agent) handleDiscover(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
writeJSON(w, http.StatusOK, a.discoveryPayload())
}
func (a *Agent) discoveryPayload() map[string]any {
reasoners := make([]map[string]any, 0, len(a.reasoners))
for _, reasoner := range a.reasoners {
reasoners = append(reasoners, map[string]any{
"id": reasoner.Name,
"input_schema": rawToMap(reasoner.InputSchema),
"output_schema": rawToMap(reasoner.OutputSchema),
"tags": []string{},
})
}
deployment := strings.TrimSpace(a.cfg.DeploymentType)
if deployment == "" {
deployment = "long_running"
}
return map[string]any{
"node_id": a.cfg.NodeID,
"version": a.cfg.Version,
"deployment_type": deployment,
"reasoners": reasoners,
"skills": []map[string]any{},
}
}
func (a *Agent) handleExecute(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
targetName := strings.TrimPrefix(r.URL.Path, "/execute")
targetName = strings.TrimPrefix(targetName, "/")
var payload map[string]any
if r.Body != nil {
defer r.Body.Close()
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil && !errors.Is(err, io.EOF) {
http.Error(w, fmt.Sprintf("invalid JSON: %v", err), http.StatusBadRequest)
return
}
}
if payload == nil {
payload = make(map[string]any)
}
reasonerName := strings.TrimSpace(targetName)
if reasonerName == "" {
reasonerName = stringFromMap(payload, "reasoner", "target", "skill")
}
if reasonerName == "" {
http.Error(w, "missing target or reasoner", http.StatusBadRequest)
return
}
reasoner, ok := a.reasoners[reasonerName]
if !ok {
http.NotFound(w, r)
return
}
input := extractInputFromServerless(payload)
execCtx := a.buildExecutionContextFromServerless(r, payload, reasonerName)
ctx := contextWithExecution(r.Context(), execCtx)
result, err := reasoner.Handler(ctx, input)
if err != nil {
a.logger.Printf("reasoner %s failed: %v", reasonerName, err)
writeJSON(w, http.StatusInternalServerError, map[string]any{"error": err.Error()})
return
}
writeJSON(w, http.StatusOK, result)
}
func extractInputFromServerless(payload map[string]any) map[string]any {
if payload == nil {
return map[string]any{}
}
if raw, ok := payload["input"]; ok {
if m, ok := raw.(map[string]any); ok {
return m
}
return map[string]any{"value": raw}
}
filtered := make(map[string]any)
for k, v := range payload {
switch strings.ToLower(k) {
case "target", "reasoner", "skill", "type", "target_type", "path", "execution_context", "executioncontext", "context":
continue
default:
filtered[k] = v
}
}
return filtered
}
func (a *Agent) buildExecutionContextFromServerless(r *http.Request, payload map[string]any, reasonerName string) ExecutionContext {
execCtx := ExecutionContext{
RunID: strings.TrimSpace(r.Header.Get("X-Run-ID")),
ExecutionID: strings.TrimSpace(r.Header.Get("X-Execution-ID")),
ParentExecutionID: strings.TrimSpace(r.Header.Get("X-Parent-Execution-ID")),
SessionID: strings.TrimSpace(r.Header.Get("X-Session-ID")),
ActorID: strings.TrimSpace(r.Header.Get("X-Actor-ID")),
WorkflowID: strings.TrimSpace(r.Header.Get("X-Workflow-ID")),
AgentNodeID: a.cfg.NodeID,
ReasonerName: reasonerName,
StartedAt: time.Now(),
}
if ctxMap, ok := payload["execution_context"].(map[string]any); ok {
if execCtx.ExecutionID == "" {
execCtx.ExecutionID = stringFromMap(ctxMap, "execution_id", "executionId")
}
if execCtx.RunID == "" {
execCtx.RunID = stringFromMap(ctxMap, "run_id", "runId")
}
if execCtx.WorkflowID == "" {
execCtx.WorkflowID = stringFromMap(ctxMap, "workflow_id", "workflowId")
}
if execCtx.ParentExecutionID == "" {
execCtx.ParentExecutionID = stringFromMap(ctxMap, "parent_execution_id", "parentExecutionId")
}
if execCtx.SessionID == "" {
execCtx.SessionID = stringFromMap(ctxMap, "session_id", "sessionId")
}
if execCtx.ActorID == "" {
execCtx.ActorID = stringFromMap(ctxMap, "actor_id", "actorId")
}
}
if execCtx.RunID == "" {
execCtx.RunID = generateRunID()
}
if execCtx.ExecutionID == "" {
execCtx.ExecutionID = generateExecutionID()
}
if execCtx.WorkflowID == "" {
execCtx.WorkflowID = execCtx.RunID
}
if execCtx.RootWorkflowID == "" {
execCtx.RootWorkflowID = execCtx.WorkflowID
}
if execCtx.ParentWorkflowID == "" && execCtx.ParentExecutionID != "" {
execCtx.ParentWorkflowID = execCtx.RootWorkflowID
}
return execCtx
}
func (a *Agent) handleReasoner(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
name := strings.TrimPrefix(r.URL.Path, "/reasoners/")
if name == "" {
http.NotFound(w, r)
return
}
reasoner, ok := a.reasoners[name]
if !ok {
http.NotFound(w, r)
return
}
defer r.Body.Close()
var input map[string]any
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, fmt.Sprintf("invalid JSON: %v", err), http.StatusBadRequest)
return
}
execCtx := ExecutionContext{
RunID: r.Header.Get("X-Run-ID"),
ExecutionID: r.Header.Get("X-Execution-ID"),
ParentExecutionID: r.Header.Get("X-Parent-Execution-ID"),
SessionID: r.Header.Get("X-Session-ID"),
ActorID: r.Header.Get("X-Actor-ID"),
WorkflowID: r.Header.Get("X-Workflow-ID"),
AgentNodeID: a.cfg.NodeID,
ReasonerName: name,
StartedAt: time.Now(),
}
if execCtx.WorkflowID == "" {
execCtx.WorkflowID = execCtx.RunID
}
if execCtx.RootWorkflowID == "" {
execCtx.RootWorkflowID = execCtx.WorkflowID
}
// Populate DID fields if VCEnabled
if a.cfg.VCEnabled && a.did != nil {
// CallerDID: resolved from ReasonerName in the execution context.
// In the handler context, ReasonerName is the target reasoner.
// Per AC3, use GetFunctionDID(ec.ReasonerName) which falls back to agent DID.
execCtx.CallerDID = a.did.GetFunctionDID(execCtx.ReasonerName)
// TargetDID: resolved from the target function name (the reasoner being invoked).
// Per AC4, targetFunctionName is derived from routing logic (the URL path).
execCtx.TargetDID = a.did.GetFunctionDID(name)
// AgentNodeDID: the agent's own DID per AC4.
execCtx.AgentNodeDID = a.did.GetAgentDID()
}
ctx := contextWithExecution(r.Context(), execCtx)
// In serverless mode we want a synchronous execution so the control plane can return
// the result immediately; skip the async path even if an execution ID is present.
if a.cfg.DeploymentType != "serverless" && execCtx.ExecutionID != "" && strings.TrimSpace(a.cfg.AgentFieldURL) != "" {
go a.executeReasonerAsync(reasoner, cloneInputMap(input), execCtx)
writeJSON(w, http.StatusAccepted, map[string]any{
"status": "processing",
"execution_id": execCtx.ExecutionID,
"run_id": execCtx.RunID,
"reasoner_name": name,
})
return
}
result, err := reasoner.Handler(ctx, input)
if err != nil {
a.logger.Printf("reasoner %s failed: %v", name, err)
response := map[string]any{
"error": err.Error(),
}
writeJSON(w, http.StatusInternalServerError, response)
return
}
writeJSON(w, http.StatusOK, result)
}
func (a *Agent) executeReasonerAsync(reasoner *Reasoner, input map[string]any, execCtx ExecutionContext) {
ctx := contextWithExecution(context.Background(), execCtx)
start := time.Now()
defer func() {
if rec := recover(); rec != nil {
errMsg := fmt.Sprintf("panic: %v", rec)
payload := map[string]any{
"status": "failed",
"error": errMsg,
"execution_id": execCtx.ExecutionID,
"run_id": execCtx.RunID,
"completed_at": time.Now().UTC().Format(time.RFC3339),
"duration_ms": time.Since(start).Milliseconds(),
"reasoner_name": reasoner.Name,
}
if err := a.sendExecutionStatus(execCtx.ExecutionID, payload); err != nil {
a.logger.Printf("failed to send panic status: %v", err)
}
}
}()
result, err := reasoner.Handler(ctx, input)
payload := map[string]any{
"execution_id": execCtx.ExecutionID,
"run_id": execCtx.RunID,
"completed_at": time.Now().UTC().Format(time.RFC3339),
"duration_ms": time.Since(start).Milliseconds(),
"reasoner_name": reasoner.Name,
}
if err != nil {
payload["status"] = "failed"
payload["error"] = err.Error()
} else {
payload["status"] = "succeeded"
payload["result"] = result
}
if err := a.sendExecutionStatus(execCtx.ExecutionID, payload); err != nil {
a.logger.Printf("async status update failed: %v", err)
}
}
func (a *Agent) sendExecutionStatus(executionID string, payload map[string]any) error {
base := strings.TrimSpace(a.cfg.AgentFieldURL)
if executionID == "" || base == "" {
return fmt.Errorf("missing execution id or AgentField URL")
}
callbackURL := strings.TrimSuffix(base, "/") + "/api/v1/executions/" + url.PathEscape(executionID) + "/status"
payloadBytes, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("encode status payload: %w", err)
}
return a.postExecutionStatus(context.Background(), callbackURL, payloadBytes)
}
func (a *Agent) postExecutionStatus(ctx context.Context, callbackURL string, payload []byte) error {
var lastErr error
for attempt := 0; attempt < 5; attempt++ {
attemptCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
req, err := http.NewRequestWithContext(attemptCtx, http.MethodPost, callbackURL, bytes.NewReader(payload))
if err != nil {
cancel()
return fmt.Errorf("create status request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := a.httpClient.Do(req)
if err != nil {
lastErr = err
} else {
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
cancel()
return nil
}
lastErr = fmt.Errorf("status update returned %d", resp.StatusCode)
}
cancel()