Repository navigation
Expand file tree
/
Copy pathkernel.go
More file actions
1480 lines (1335 loc) · 55 KB
/
Copy pathkernel.go
File metadata and controls
1480 lines (1335 loc) · 55 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 toroid
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/yashbonde/toroid-kernel/llm"
"github.com/yashbonde/toroid-kernel/tools"
)
// DefaultModel is the gateway route used when the caller omits a primary model.
const DefaultModel = "llmgateway/deepseek/deepseek-v4p1-flash"
// DefaultContextSize is the kernel window when the gateway supplies no limit.
const DefaultContextSize = 200_000
// Thinking controls the model's thinking budget.
type Thinking string
const (
ThinkingNone Thinking = "none" // disable thinking
ThinkingLow Thinking = "low" // gateway reasoning_effort=low
ThinkingHigh Thinking = "high" // gateway reasoning_effort=high
)
// Kernel is the agentic orchestrator. It owns the tool loop (turns), history,
// compaction, subagents, events, and persistence; each turn's LLM call is one
// llm-step performed by the Step layer against the LiteLLM gateway.
type Kernel struct {
Cfg Config
Step Step // one-llm-step backend; defaults to GatewayStep over the llm client
Hooks *HookRegistry
Tools *tools.Registry
Store *Store
seq atomic.Uint64
SystemPromptPrefix string
SystemPrompt string
History []llm.Message
Sessions map[string]Usage // sessionID -> summed tokens + cost (self + subagents)
usageMu sync.Mutex
// reservedUSD is budget promised to subagents that are still running. Their
// spend does not reach runningCostUSD until they finish, so without a
// reservation two concurrent children each read the same headroom and the
// transcript cap is exceeded by however many run at once.
reservedUSD float64
currentTokens int
runningCostUSD float64
mcpClients []io.Closer // open connections to configured MCP servers, closed in Close()
// message queue — callers enqueue messages that are injected at the next
// safe interruption point (turn boundary), causing the loop to continue
// with the queued messages appended to history.
messageQueue []string
queueMu sync.Mutex
// reqSeq counts outbound LLM requests so parent_session_id is attached to
// the first one only (see nextRequestMetadata).
reqSeq atomic.Uint64
// newSubKernel builds the child kernel for a subagent run. It is a field so
// tests can substitute a kernel with a scripted Step; nil means NewKernel.
newSubKernel func(context.Context, Config) (*Kernel, error)
// run-state — supports background agents (§12.4). runMu serializes the agent
// loop so Stream and Wake never mutate history concurrently; running reports
// whether a loop is currently active; lastWriter is reused when an idle
// kernel is woken by a background completion; bgSeq numbers background tasks.
runMu sync.Mutex
wakeMu sync.Mutex
running atomic.Bool
lastWriter io.Writer
bgSeq atomic.Uint64
}
// Config holds all options for creating a Kernel.
type Config struct {
// Model is the primary agent model (provider/model form). All models are
// reached through the LiteLLM gateway ("llmgateway/<name>"); ids with other
// prefixes are passed to the gateway verbatim for it to route.
Model string `json:"model" description:"primary llm model name" default:"llmgateway/deepseek/deepseek-v4p1-flash"`
// ModelMetadataWait bounds the combined wait for optional gateway limits
// and catalog discovery. Zero waits for the probes' normal deadlines.
ModelMetadataWait time.Duration `json:"-"`
// SmallerModel is an optional cheaper model for cost-sensitive work:
// conversation compaction and subagents (sync + async). Empty means those
// paths use Model.
SmallerModel string `json:"smaller_model,omitempty" description:"cheaper model for compaction and subagents; empty = use Model"`
// APIKey is the gateway bearer token. Defaults to $LLM_GATEWAY_KEY.
APIKey string `json:"api_key,omitempty" description:"API key for the gateway"`
SessionID string `json:"session_id,omitempty" description:"unique identifier for the session"`
WorkDir string `json:"work_dir" description:"working directory" default:"current directory"`
// MaxIter caps tool-call steps per turn. With prompt caching every extra
// step re-reads the prefix at cache price, so a deep loop is affordable;
// the repeat-call guard still stops genuine spins early.
MaxIter int `json:"max_iter" description:"max tool-call iterations" default:"100"`
MaxTokens int `json:"max_tokens,omitempty" description:"max output tokens per llm-step; 0 = provider default"`
MaxRepeatCalls int `json:"max_repeat_calls" description:"stop after this many consecutive identical tool calls with identical results (loop guard); 0 disables" default:"3"`
Thinking Thinking `json:"thinking" description:"thinking budget: none | low | high" default:"none"`
ThinkingWriter io.Writer `json:"-"`
// Tools
IncludeComputerTools bool `json:"include_computer_tools" description:"if true, include the computer tools"`
// IncludeSubagentTools opts into synchronous and background delegation.
// It is separate from the core file/shell tools so ordinary runs keep a
// smaller, more relevant tool prefix.
IncludeSubagentTools bool `json:"include_subagent_tools,omitempty" description:"register subagent and subagent_async tools"`
// DisableBackground restricts delegation and shell tools to work that
// finishes within the caller's lifetime (e.g. an HTTP request).
DisableBackground bool `json:"disable_background,omitempty"`
// Internet opts into the Firecrawl web search/scrape capability in the
// compiled system prompt.
Internet bool `json:"internet,omitempty" description:"enable internet search and scraping via Firecrawl in the system prompt" default:"false"`
Tools *tools.Registry `json:"tools,omitempty" description:"custom tools"`
// Skills: if unset or true, scan ~/.toroid/skills/*.md at startup for
// skill metadata (name + description only) and register the skill tool
// so the model can load a skill's full body on demand.
LoadSkills *bool `json:"load_skills,omitempty" description:"scan ~/.toroid/skills/ for skill metadata at startup and register the skill tool" default:"true"`
// MCP: remote Model Context Protocol servers to connect at startup. Each
// server's tools are discovered via tools/list and registered into the
// kernel's registry, name-prefixed per server to avoid collisions.
MCPServers []tools.MCPServerConfig `json:"mcp_servers,omitempty" description:"remote MCP servers to connect and register tools from"`
// MaxSubagentDepth bounds delegation nesting (root = 0, its subagent = 1).
// 0 uses DefaultMaxSubagentDepth.
MaxSubagentDepth int `json:"max_subagent_depth,omitempty" description:"maximum subagent nesting depth; 0 = default (3)" default:"3"`
// Depth is this kernel's own position in that tree. Set by the kernel when
// it spawns a subagent; callers leave it zero.
Depth int `json:"depth,omitempty" description:"delegation depth of this kernel; set internally"`
// Trace/span hierarchy
TraceID string `json:"trace_id,omitempty"` // inherited from parent; root sets TraceID = SessionID
ParentSpanID string `json:"parent_span_id,omitempty"` // parent kernel's SessionID
PreviousTraceID string `json:"previous_trace_id,omitempty"` // previous trace id when compaction is triggered
// Persistence
Save bool `json:"save" description:"persist events, costs and metadata to the SQLite store" default:"false"`
// Session management
Resume bool `json:"resume" description:"if true, load existing session history and continue" default:"false"`
// compaction / context hygiene — defaults favour earlier prune and a
// modest effective window so long agentic turns do not re-pay max context
// every step until the 300k ceiling.
CompactionBufferSize int `json:"compaction_buffer_size" description:"tokens reserved below TotalContextSize before auto-compact fires" default:"50000"`
TotalContextSize int `json:"total_context_size" description:"total context window size" default:"200000"`
// MaxTranscriptSpendUSD caps cumulative LLM spend across this kernel's
// transcript. A non-positive value disables the limit.
MaxTranscriptSpendUSD float64 `json:"max_transcript_spend_usd,omitempty" description:"maximum cumulative transcript spend in USD; 0 disables"`
// logging flags
AttachLoggerHooks *bool `json:"attach_logger_hooks,omitempty" description:"automatically attach logger hooks" default:"false"`
ShowHistory *bool `json:"show_history" description:"print history" default:"false"`
}
func resolveProviderBaseURL(cfg Config) (baseURL string, resolvedAPIKey string) {
baseURL = os.Getenv(GatewayBaseURLEnv)
resolvedAPIKey = cfg.APIKey
switch {
case strings.HasPrefix(cfg.Model, "openai/"):
baseURL = OpenAIBaseURL
if resolvedAPIKey == "" {
resolvedAPIKey = os.Getenv(OpenAIKeyEnv)
}
}
if resolvedAPIKey == "" {
resolvedAPIKey = os.Getenv(GatewayKeyEnv)
}
return
}
func resolveWorkDir(sessionID string) (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
return RunnerDir(cwd, sessionID)
}
func applyConfigDefaults(cfg Config) Config {
if cfg.TotalContextSize <= 0 {
cfg.TotalContextSize = DefaultContextSize
}
if cfg.CompactionBufferSize <= 0 {
cfg.CompactionBufferSize = 50000
}
if cfg.MaxIter <= 0 {
cfg.MaxIter = 100
}
if cfg.SmallerModel == "" {
cfg.SmallerModel = "deepseek-v4-flash"
}
return cfg
}
// NewKernel creates and wires up a new Kernel.
func NewKernel(ctx context.Context, cfg Config) (*Kernel, error) {
if cfg.Model == "" {
cfg.Model = DefaultModel
}
baseURL, apiKey := resolveProviderBaseURL(cfg)
cfg.APIKey = apiKey
if cfg.SessionID == "" {
cfg.SessionID = NewSessionID()
}
if cfg.WorkDir == "" {
wd, err := resolveWorkDir(cfg.SessionID)
if err != nil {
return nil, err
}
cfg.WorkDir = wd
}
// Root kernel: TraceID == SessionID
if cfg.TraceID == "" {
cfg.TraceID = cfg.SessionID
}
limits, catalog := startKernelMetadata(ctx, cfg, baseURL, apiKey)
probeCtx := ctx
if cfg.ModelMetadataWait > 0 {
var cancel context.CancelFunc
probeCtx, cancel = context.WithTimeout(ctx, cfg.ModelMetadataWait)
defer cancel()
}
lim := limits.wait(probeCtx)
gatewayModels := catalog.wait(probeCtx)
if lim.inputContext() == 0 {
lim.MaxInputTokens = FindGatewayModel(gatewayModels, cfg.Model).ContextLength
}
applyModelLimits(&cfg, lim)
if err := ctx.Err(); err != nil {
return nil, err
}
cfg = applyConfigDefaults(cfg)
// Kernel object
k := &Kernel{
Cfg: cfg,
Hooks: &HookRegistry{},
Sessions: map[string]Usage{},
currentTokens: 0,
Tools: tools.NewRegistry(),
}
// register all tools
if cfg.IncludeComputerTools {
k.Tools.Register(tools.NewReadTool(k, toolDescription("read")))
k.Tools.Register(tools.NewWriteTool(k, toolDescription("write")))
k.Tools.Register(tools.NewBashTool(k, toolDescription("bash")))
k.Tools.Register(tools.NewEditTool(k, toolDescription("edit")))
k.Tools.Register(tools.NewMultiEditTool(k, toolDescription("multiedit")))
}
if cfg.IncludeSubagentTools {
k.Tools.Register(tools.NewSubagentTool(k, toolDescription("subagent")))
if !cfg.DisableBackground {
k.Tools.Register(newSubagentAsyncTool(k, toolDescription("subagent_async")))
}
}
if cfg.Tools != nil {
for _, t := range cfg.Tools.Tools() {
k.Tools.Register(t)
}
}
ApplyDefaultDataTypes(&cfg) // cfg OR default_cfg
// Skills: scan ~/.toroid/skills/ for metadata only (progressive
// disclosure). Full skill bodies are loaded lazily via the skill tool,
// either by the model recognizing a relevant skill or by the user naming
// one explicitly in their prompt.
var skills []SkillMeta
if cfg.LoadSkills == nil || *cfg.LoadSkills {
skills, _ = discoverSkills()
if len(skills) > 0 {
k.Tools.Register(tools.NewSkillTool(k, toolDescription("skill")))
}
}
// MCP: connect each configured remote server and register its tools.
// Connections stay open for the kernel's lifetime and are closed in Close().
for _, sc := range cfg.MCPServers {
client, err := tools.ConnectMCPServer(ctx, k, k.Tools, sc)
if err != nil {
return nil, fmt.Errorf("mcp server %q: %w", sc.BaseURL, err)
}
k.mcpClients = append(k.mcpClients, client)
}
// Initialize the SQLite trace Store (only when save is set)
if cfg.Save {
store, err := NewStore()
if err != nil {
return nil, err
}
k.Store = store
startedAt := time.Now().UnixNano()
if cfg.Resume {
existing, err := k.restoreSpan(store, cfg)
if err != nil {
return nil, err
}
if existing {
startedAt = 0
}
}
_ = store.SaveSpanMeta(SpanMeta{
SpanID: cfg.SessionID,
TraceID: cfg.TraceID,
ParentSpanID: cfg.ParentSpanID,
Model: cfg.Model,
StartedAt: startedAt,
})
if cfg.TraceID == cfg.SessionID {
_ = store.SaveTraceMeta(TraceMeta{
TraceID: cfg.TraceID,
PreviousTraceID: cfg.PreviousTraceID,
StartedAt: startedAt,
})
} else if !cfg.Resume {
// Restore conversation history by replaying stored events (post-last-compaction only).
if msgs, err2 := ReconstructHistory(cfg.TraceID, cfg.SessionID, "", cfg.WorkDir, cfg.Model); err2 == nil && len(msgs) > 0 {
k.History = msgs
k.Logf("[resume] reconstructed %d history messages from events for trace %s", len(msgs), cfg.TraceID)
} else if err2 != nil {
k.LogErr("[resume] failed to reconstruct history: %v", err2)
}
}
}
// Compile one stable system prefix after every startup capability is known.
k.SystemPromptPrefix, k.SystemPrompt = buildSystemPrompt(cfg.WorkDir, skills, len(cfg.MCPServers) > 0,
cfg.IncludeSubagentTools, cfg.Internet, cfg.Model, cfg.SmallerModel, cfg.TotalContextSize, cfg.CompactionBufferSize, gatewayModels)
// Step is the one-llm-step backend over the in-repo wire client (OpenAI
// chat completions via LiteLLM gateway or OpenAI direct). Tests may replace
// it with a FauxStep. The kernel owns the tool loop — Step performs
// individual LLM calls.
var wire llm.Chat = llm.NewClient(baseURL, cfg.APIKey)
step := NewGatewayStep(wire)
step.pricing = func(ctx context.Context, id string) *GatewayModelPricing {
return FindGatewayModel(CachedGatewayModels(ctx, baseURL, apiKey), id).Pricing
}
k.Step = step
// Default AttachLoggerHooks if nil
if cfg.AttachLoggerHooks != nil && *cfg.AttachLoggerHooks {
k.OnAll(func(ctx context.Context, e Event) error {
if e.Kind == EventReasoning {
return nil
}
k.Logf(string(e.Kind) + " " + fmt.Sprintf("%v", e.Payload))
return nil
})
}
// Live reasoning output for hosts that want it.
if cfg.Thinking != ThinkingNone && cfg.ThinkingWriter != nil {
k.On(EventReasoning, func(_ context.Context, e Event) error {
if p, ok := e.Payload.(*ReasoningPayload); ok {
_, err := fmt.Fprint(cfg.ThinkingWriter, p.Text)
return err
}
return nil
})
}
k.Cfg = cfg
return k, nil
}
// fireTurnStarted emits EventTurnStarted just before the kernel issues the
// turn's llm-step: model, message count, tool names, schema name — what
// EventLLMStep used to carry as a separate event kind, folded in here because
// the two always fired together, at the same point, every time.
func (k *Kernel) fireTurnStarted(ctx context.Context, metadata llm.RequestMetadata, model string, c Context, schema string) {
names := make([]string, 0, len(c.Tools))
for _, t := range c.Tools {
names = append(names, t.Name)
}
payload := TurnPayload{
Model: model,
ContextWindow: k.Cfg.TotalContextSize,
Messages: len(c.Messages),
Tools: names,
Schema: schema,
}
_ = k.FireInTurn(ctx, string(EventTurnStarted), metadata, &payload)
}
// fireTurnCompleted emits EventTurnCompleted with the turn's outcome: what
// EventTurnCompleted, EventAssistantTurn (content), and EventTurnCost (usage)
// used to report as three separate events at overlapping moments are now one.
// content is the turn's full structured content, already JSON-serialized by
// the caller (media-stripped for persistence).
func (k *Kernel) fireTurnCompleted(ctx context.Context, metadata llm.RequestMetadata, stopReason string, toolCalls int, content json.RawMessage, usage Usage, totalCostUSD float64) {
payload := TurnPayload{
StopReason: stopReason,
ToolCalls: toolCalls,
Content: content,
TurnUsage: usage,
TurnCostUSD: usage.Cost,
TotalCostUSD: totalCostUSD,
}
_ = k.FireInTurn(ctx, string(EventTurnCompleted), metadata, &payload)
}
func (k *Kernel) fireTurnFailed(ctx context.Context, metadata llm.RequestMetadata, err error) {
payload := TurnPayload{StopReason: StopReasonError}
if ctx.Err() != nil {
payload.StopReason = StopReasonAborted
}
if err != nil {
payload.Error = err.Error()
}
_ = k.FireInTurn(ctx, string(EventTurnFailed), metadata, &payload)
}
// fireGuard emits EventGuardTriggered — the single event kind covering every
// loop guard (previously silent, Logf-only, five separate inline blocks):
// the inspection, validation, and completion nudges, the repeat-call loop
// guard, and MaxIter.
func (k *Kernel) fireGuard(ctx context.Context, metadata llm.RequestMetadata, name, reason string) {
_ = k.FireInTurn(ctx, string(EventGuardTriggered), metadata, &GuardTriggeredPayload{Name: name, Reason: reason})
}
// recordUsage adds a single LLM call's usage to session cost accounting and
// returns the running total, so the caller can fold it into TurnCompleted's
// payload instead of this firing its own event.
func (k *Kernel) recordUsage(u Usage) float64 {
runningCost := k.UpdateUse(u, "")
if k.Store != nil {
_ = k.Store.AppendCost(k.Cfg.TraceID, k.Cfg.SessionID, u.Cost, runningCost)
}
return runningCost
}
// Implement tools.Agent interface
func (k *Kernel) WorkDir() string { return k.Cfg.WorkDir }
func (k *Kernel) SessionID() string { return k.Cfg.SessionID }
func (k *Kernel) Model() string { return k.Cfg.Model }
// TraceID is the transcript this kernel belongs to. A root kernel's equals its
// SessionID; a subagent inherits its parent's, so the whole delegation tree
// shares one trace.
func (k *Kernel) TraceID() string { return k.Cfg.TraceID }
// reserveBudget claims the transcript's remaining headroom for one subagent and
// reports how much it may spend. Checking and claiming happen under one lock, so
// concurrent children divide the cap instead of each seeing all of it. The first
// caller takes what is left; a second concurrent caller is refused rather than
// allowed to double the transcript's spend.
func (k *Kernel) reserveBudget(cap float64) (float64, bool) {
k.usageMu.Lock()
defer k.usageMu.Unlock()
remaining := cap - k.runningCostUSD - k.reservedUSD
if remaining <= 0 {
return 0, false
}
k.reservedUSD += remaining
return remaining, true
}
// releaseBudget returns an unspent reservation to the transcript. The child's
// actual spend has by then been added to runningCostUSD, so the headroom the
// next caller sees is correct.
func (k *Kernel) releaseBudget(amount float64) {
k.usageMu.Lock()
k.reservedUSD -= amount
if k.reservedUSD < 0 {
k.reservedUSD = 0
}
k.usageMu.Unlock()
}
// UsageSnapshot copies this kernel's per-session accounting. It is the reliable
// source of a run's spend: Run reports usage through EventStop, which a failed
// run never reaches, so a caller relying on that payload alone loses the cost of
// everything the run did before it failed.
func (k *Kernel) UsageSnapshot() map[string]Usage {
k.usageMu.Lock()
defer k.usageMu.Unlock()
out := make(map[string]Usage, len(k.Sessions))
for sid, u := range k.Sessions {
out[sid] = u
}
return out
}
// RunningCostUSD returns the cumulative LLM cost so far in this session.
func (k *Kernel) RunningCostUSD() float64 {
k.usageMu.Lock()
defer k.usageMu.Unlock()
return k.runningCostUSD
}
// ContextUsage returns (used tokens, total context window size).
func (k *Kernel) ContextUsage() (int, int) {
k.usageMu.Lock()
defer k.usageMu.Unlock()
return k.currentTokens, k.Cfg.TotalContextSize
}
func (k *Kernel) Logf(msg string, args ...any) {
LogInfo("["+k.Cfg.TraceID+"] "+msg, args...)
}
func (k *Kernel) LogErr(msg string, args ...any) {
LogError("["+k.Cfg.TraceID+"] "+msg, args...)
}
// Fire records an event scoped to the transcript only — used outside a turn
// (SessionStart, UserPromptSubmit, Stop, MasterIdle, SessionEnd, compaction,
// subagent start/stop). Use FireInTurn for anything happening inside a turn.
func (k *Kernel) Fire(ctx context.Context, kind string, payload any) error {
return k.fireEvent(ctx, kind, "", "", "", payload)
}
// FireInTurn records an event carrying full chat/turn/llm-step scope on its
// envelope — used for everything fired inside a turn (TurnStarted,
// TurnCompleted, TurnFailed, Reasoning, PreToolUse, PostToolUse,
// PostToolUseFailure, GuardTriggered, QueueInterrupt), so a consumer can fold
// the whole event, not just Turn* payloads, back into the scope tree.
func (k *Kernel) FireInTurn(ctx context.Context, kind string, metadata llm.RequestMetadata, payload any) error {
return k.fireEvent(ctx, kind, metadata.ChatID, metadata.TurnID, metadata.TraceID, payload)
}
func (k *Kernel) fireEvent(ctx context.Context, kind, chatID, turnID, llmStepID string, payload any) error {
event := Event{
Kind: EventKind(kind),
SessionID: k.Cfg.SessionID,
TraceID: k.Cfg.TraceID,
SpanID: k.Cfg.SessionID,
TranscriptID: k.Cfg.TraceID,
ChatID: chatID,
TurnID: turnID,
LLMStepID: llmStepID,
EmitTS: time.Now().UnixNano(),
Seq: k.seq.Add(1),
Payload: payload,
}
if k.Store != nil {
if err := k.Store.appendLiveEvent(&event); err != nil {
return err
}
}
return k.Hooks.Fire(ctx, event)
}
func (k *Kernel) UpdateUse(u Usage, key string) float64 {
k.usageMu.Lock()
defer k.usageMu.Unlock()
id := key
if id == "" {
id = k.Cfg.SessionID
}
// Accumulate — a session's entry is the SUM of its llm-steps, not the last
// one, so Stop/Run usage payloads and subagent rollups report real totals.
s, seen := k.Sessions[id]
s.Input += u.Input
s.Output += u.Output
s.Reasoning += u.Reasoning
s.CacheRead += u.CacheRead
s.CacheWrite += u.CacheWrite
s.Cost += u.Cost
if !seen {
s.PricingOK = u.PricingOK
} else {
s.PricingOK = s.PricingOK && u.PricingOK
}
k.Sessions[id] = s
k.runningCostUSD += u.Cost
// u is a single step's usage: its input-side tokens (fresh + cache-read +
// cache-write are disjoint slices of the prompt) are the size of the request
// that step sent, plus what it generated — a valid snapshot of context-window
// occupancy. Never feed a summed multi-step total (double-counts re-reads).
k.currentTokens = int(u.Input + u.CacheRead + u.CacheWrite + u.Output)
return k.runningCostUSD
}
// overContextThreshold reports whether context-window occupancy has reached the
// point where we should compact. Shared by the pre-turn check and the in-loop
// check so both use identical logic.
func (k *Kernel) overContextThreshold() bool {
k.usageMu.Lock()
defer k.usageMu.Unlock()
// A non-positive context size means "unbounded" — never report over threshold.
// Without this guard a zero TotalContextSize makes the threshold 0 and fires on
// every turn (spurious compaction). NewKernel applies a default, but guard here
// too so the invariant holds regardless of how Cfg was constructed.
if k.Cfg.TotalContextSize <= 0 {
return false
}
return k.currentTokens > 0 && k.currentTokens >= k.Cfg.TotalContextSize-k.Cfg.CompactionBufferSize
}
// Enqueue adds a message to the kernel's message queue. It is safe to call
// from any goroutine, including while Stream is running. The message will be
// injected into the conversation at the next turn boundary, causing the loop
// to continue with the message appended to history.
func (k *Kernel) Enqueue(msg string) {
k.queueMu.Lock()
k.messageQueue = append(k.messageQueue, msg)
k.queueMu.Unlock()
}
// BackgroundEnabled reports whether background bash commands may start. It
// requires the same delegation opt-in as subagents: both inject completion
// notices through the queue, so they share one capability gate.
func (k *Kernel) BackgroundEnabled() bool {
return k.Cfg.IncludeSubagentTools && !k.Cfg.DisableBackground
}
// EnqueueBackgroundNotice delivers a background-command completion notice via
// the same queue + wake-up path as a finished background subagent.
func (k *Kernel) EnqueueBackgroundNotice(id, notice string) {
k.Enqueue(fmt.Sprintf("[background command %s finished]\n%s", id, notice))
_ = k.tryResume(context.Background())
}
// drainQueue pops all queued messages and returns them.
func (k *Kernel) drainQueue() []string {
k.queueMu.Lock()
msgs := k.messageQueue
k.messageQueue = nil
k.queueMu.Unlock()
return msgs
}
// On registers a hook for an event kind.
func (k *Kernel) On(kind EventKind, fn HookFn) {
k.Hooks.On(kind, fn)
}
func (k *Kernel) OnAll(fn HookFn) {
for _, kind := range []EventKind{
EventSessionStart,
EventUserPromptSubmit,
EventPreToolUse,
EventPostToolUse,
EventPostToolUseFailure,
EventSubagentStart,
EventSubagentStop,
EventMasterIdle,
EventReasoning,
EventTurnStarted,
EventTurnCompleted,
EventTurnFailed,
EventGuardTriggered,
EventStop,
EventPreCompact,
EventPostCompact,
EventQueueInterrupt,
EventSessionEnd,
} {
k.On(kind, fn)
}
}
// Run runs the agent loop and returns the final text response.
// RunOption configures a single Run or Stream call.
type RunOption func(*runOptions)
type runOptions struct {
schema Schema
schemaName string
schemaDescription string
maxTurnSpendUSD float64
onTextDelta func(turnID, text string) error
attachments []Attachment
}
// WithAttachments adds local paths to this user turn and embeds selected images.
func WithAttachments(items []Attachment) RunOption {
return func(o *runOptions) { o.attachments = append([]Attachment(nil), items...) }
}
// WithSchema enables structured generation for this Run/Stream call.
// The model will produce a JSON object matching the given schema instead of
// free text. Run returns the raw JSON; Stream writes it to the writer.
func WithSchema(schema Schema, name, description string) RunOption {
return func(o *runOptions) {
o.schema = schema
o.schemaName = name
o.schemaDescription = description
}
}
// WithTextDeltas streams each main-loop model step and delivers its text as
// it arrives. The normal writer still receives assembled turn text. Compaction
// and child kernels do not send their internal output to this callback.
func WithTextDeltas(fn func(turnID, text string) error) RunOption {
return func(o *runOptions) { o.onTextDelta = fn }
}
// WithMaxTurnSpendUSD caps LLM spend for one Run or Stream call. A
// non-positive value disables the limit.
func WithMaxTurnSpendUSD(usd float64) RunOption {
return func(o *runOptions) { o.maxTurnSpendUSD = usd }
}
type spendBudget struct {
turnStartUSD float64
turnMaxUSD float64
hit bool
}
func (b *spendBudget) reached(k *Kernel) bool {
total := k.RunningCostUSD()
b.hit = b.hit ||
(b.turnMaxUSD > 0 && total-b.turnStartUSD >= b.turnMaxUSD) ||
(k.Cfg.MaxTranscriptSpendUSD > 0 && total >= k.Cfg.MaxTranscriptSpendUSD)
return b.hit
}
func (k *Kernel) Run(ctx context.Context, prompt string, opts ...RunOption) (string, UsagePayload, error) {
var buf strings.Builder
var usage UsagePayload
k.On(EventStop, func(ctx context.Context, e Event) error {
usage = *e.Payload.(*UsagePayload)
return nil
})
err := k.Stream(ctx, prompt, &buf, opts...)
return buf.String(), usage, err
}
// Stream runs the agent loop and streams the response to the writer.
func (k *Kernel) Stream(ctx context.Context, prompt string, w io.Writer, opts ...RunOption) error {
// One chat = one Stream/Run: give all of this run's turns a shared gateway
// trace id so the upstream groups them under a single trace (preserved if the
// context already carries one, e.g. a subagent running inside a parent chat).
ctx = WithGatewayTrace(ctx)
ctx = k.withRequestChat(ctx)
var ro runOptions
for _, o := range opts {
o(&ro)
}
// A loop may already be running — a background delegation completing wakes
// one without any caller asking. Hand it the prompt through the queue rather
// than racing it for History.
if !k.claimLoop() {
if len(ro.attachments) > 0 {
return fmt.Errorf("cannot queue attachments while a turn is running")
}
k.Enqueue(prompt)
return nil
}
// Everything below mutates History. Release the claim on any path that does
// not reach streamCurrent, which owns the flag from there on.
entered := false
defer func() {
if !entered {
k.running.Store(false)
}
}()
budget := &spendBudget{
turnStartUSD: k.RunningCostUSD(),
turnMaxUSD: ro.maxTurnSpendUSD,
}
// Fire session start only once. System prompt is sent as the single leading
// system message by the Step layer — do not also put it in History (double
// bill + cache bust).
if len(k.History) == 0 {
_ = k.Fire(ctx, string(EventSessionStart), nil)
}
// Auto-compact if approaching context limit; important to do this before adding user prompt
if !budget.reached(k) && k.overContextThreshold() {
k.Logf("auto-compacting: currentTokens=%d threshold=%d", k.currentTokens, k.Cfg.TotalContextSize-k.Cfg.CompactionBufferSize)
if err := k.Compact(ctx); err != nil {
return err
}
}
// append user message; important to do this before history validation.
// parseUserMessage inlines any markdown image refs as file parts and returns
// the portable (~-rooted) prompt to persist for cross-process resume.
userMsg, storedPrompt, mediaWarnings := parseUserMessage(prompt, k.Cfg.WorkDir, ResolveModel(k.Cfg.Model))
if err := appendAttachments(&userMsg, ro.attachments, k.Cfg.WorkDir, ResolveModel(k.Cfg.Model)); err != nil {
return err
}
k.History = append(k.History, userMsg)
_ = k.Fire(ctx, string(EventUserPromptSubmit), &UserPromptPayload{Prompt: storedPrompt, Attachments: ro.attachments})
// Surface any media that could not be inlined (unsupported model, oversized)
// so a dropped image is visible rather than silently missing (M8).
for _, w := range mediaWarnings {
k.LogErr("multimodal: %s", w)
}
// history validation — last message must be the user turn we just appended.
if len(k.History) == 0 || k.History[len(k.History)-1].Role != llm.RoleUser {
role := llm.Role("")
if len(k.History) > 0 {
role = k.History[len(k.History)-1].Role
}
k.LogErr("Last history item must be a user message. Got: '%s'", role)
panic("Last item is not a user message.")
}
// When schema is set, discard the free-text output from the agent loop;
// only the structured JSON from the object llm-step goes to the caller's writer.
loopWriter := w
if ro.schema != nil {
loopWriter = io.Discard
}
// streamCurrent owns the running flag from here: it clears it on every exit.
entered = true
if err := k.streamCurrent(ctx, loopWriter, budget, ro.onTextDelta); err != nil {
return err
}
if ro.schema != nil {
if budget.reached(k) {
return nil
}
// The structured-output pass is one more llm-step in the SAME chat (M7).
// After the agentic loop the last message is assistant, so append a user
// turn asking the model to emit structured output. Run it through the Step
// layer so its usage is priced and billed like any other llm-step.
schemaMsgs := append(k.History, llm.NewUserMessage("Now return your findings in the required JSON format."))
res, err := k.Step.CompleteObject(ctx, ResolveModel(k.Cfg.Model), Context{
SystemPrefix: k.SystemPromptPrefix,
System: k.SystemPrompt,
Messages: schemaMsgs,
Metadata: k.nextRequestMetadata(ctx),
}, ro.schema, ro.schemaName, ro.schemaDescription, k.stepOpts())
if err != nil {
return err
}
// Bill the object llm-step and roll it into transcript totals (M7).
k.recordUsage(res.Usage)
budget.reached(k)
b, err := json.Marshal(res.Object)
if err != nil {
return err
}
_, err = w.Write(b)
return err
}
return nil
}
// streamCurrent runs the agent loop over the current in-memory history until it
// stops (no pending queued messages). Stream prepares history (compaction,
// appending the user message, pruning) and then calls this; Wake calls it after
// injecting a background completion. runMu serializes the loop so the two never
// race on history.
func (k *Kernel) streamCurrent(ctx context.Context, w io.Writer, budget *spendBudget, onDelta func(string, string) error) error {
k.runMu.Lock()
k.running.Store(true)
k.lastWriter = w
if err := k.streamViaStep(ctx, w, budget, onDelta); err != nil {
k.running.Store(false)
k.runMu.Unlock()
return err
}
if k.Cfg.ShowHistory != nil && *k.Cfg.ShowHistory {
PrettyPrintHistory(k)
}
// Fire stop with usage
usageSnapshot := make(map[string]Usage)
k.usageMu.Lock()
for sid, v := range k.Sessions {
usageSnapshot[sid] = v
}
k.usageMu.Unlock()
_ = k.Fire(ctx, string(EventStop), &UsagePayload{Tokens: usageSnapshot})
// Record span (and, for a root kernel, trace) end time so the persisted
// graph carries OTEL-style start/end timestamps.
if k.Store != nil {
now := time.Now().UnixNano()
_ = k.Store.SaveSpanMeta(SpanMeta{SpanID: k.Cfg.SessionID, TraceID: k.Cfg.TraceID, EndedAt: now})
if k.Cfg.TraceID == k.Cfg.SessionID {
_ = k.Store.SaveTraceMeta(TraceMeta{TraceID: k.Cfg.TraceID, EndedAt: now})
}
}
// Mark not-running and release runMu *before* asking tryResume whether to
// resume: tryResume may itself re-enter streamCurrent (a background
// goroutine's result arrived while we were finishing this turn), and that
// recursive call needs to acquire runMu fresh, not find it still held by
// this call's own now-finished execution.
k.running.Store(false)
k.runMu.Unlock()
return k.tryResume(ctx)
}
// Close releases kernel-held resources. It flushes the trace store; the shared
// SQLite handle itself is process-global and is released on exit. Safe to call
// multiple times and on a nil-store kernel.
func (k *Kernel) Close() error {
for _, c := range k.mcpClients {
_ = c.Close()
}
if k.Store != nil {
return k.Store.Close()
}
return nil
}
// stepOpts returns StepOptions derived from kernel config. When cfg.MaxTokens
// is > 0 it sets the per-step output-token cap; zero leaves it to the provider.
func (k *Kernel) stepOpts() StepOptions {
opts := StepOptions{Thinking: k.Cfg.Thinking}
if k.Cfg.MaxTokens > 0 {
mt := int64(k.Cfg.MaxTokens)
opts.MaxOutputTokens = &mt
}
return opts
}
// trimForCompact shrinks history in place just before the compaction summarize
// call: tool-call args are cleared, tool results truncated, and media/reasoning
// parts stripped — the summary needs none of them, and un-stripped images would
// make the one call meant to REDUCE cost re-pay for every blob in the
// transcript. History is never mutated mid-chat outside compaction: rewriting
// an already-sent message changes the byte prefix and busts the prompt cache.
func (k *Kernel) trimForCompact(maxResultChars int) {
for j := range k.History {
msg := &k.History[j]
kept := msg.Parts[:0]
for _, part := range msg.Parts {
switch p := part.(type) {
case llm.ReasoningPart:
continue // never needed for the summary
case llm.ToolCallPart:
p.Arguments = "{}"
kept = append(kept, p)
case llm.ToolResultPart:
if len(p.Content) > maxResultChars {
p.Content = p.Content[:maxResultChars] + "… [trimmed]"
}
if len(p.Files) > 0 {
p.Files = nil
p.Content += " [media omitted]"
}
kept = append(kept, p)
case llm.FilePart:
kept = append(kept, llm.TextPart{Text: "[media omitted]"})
default:
kept = append(kept, part)
}
}
msg.Parts = kept
}
}
// Compact summarizes the current history and resets it.
func (k *Kernel) Compact(ctx context.Context) error {
if len(k.History) == 0 {
return nil
}
// Shrink fat tool results (and strip media/reasoning) before paying for a
// full-history summarize call.
k.trimForCompact(2000)
messagesBefore := len(k.History)
tokensBefore := k.currentTokens
_ = k.Fire(ctx, string(EventPreCompact), &CompactPayload{
MessageCount: messagesBefore,
TokenCount: tokensBefore,
})
prompt, err := readPrompt("compact.kernel.tmpl")
if err != nil {
return err
}
// Summarization is one llm-step on the cost-sensitive model, billed from the
// model catalog like any other. Cross-model
// handoff (M9): when the compact model differs from the main chat model,
// adapt history for the target's wire API — a no-op while all in-scope
// models share openai-completions.
compactModelID := k.Cfg.Model
if k.Cfg.SmallerModel != "" {
compactModelID = k.Cfg.SmallerModel
}