package daemon import ( "context" "io" "net/http" "albedo/cli/internal/daemon/protocol" ) type ContextSection struct { ID, Label, Kind, Source, Preview string ItemCount, ByteCount, Pages int } type CompactionState struct { TriggerTokens, InputLimitTokens, ProviderInputTokens, ProviderCachedInputTokens, BeforeItems, AfterItems *int Strategy, Source string Status CompactionStatus // Size is how big the prepared request is, nil while its strategy has no size for it. Size *Size } // Size is how many tokens something takes, in the two parts the daemon keeps // apart: what a provider measured and what was estimated for the rest. type Size struct { Tokens int Measured *MeasuredSize Estimated *EstimatedSize } // MeasuredSize is a provider's number: counted for this very request by its // count endpoint (Counted), or taken from the usage it reported for earlier // calls. type MeasuredSize struct { Tokens int Counted bool } // EstimatedSize is albedo's estimate from lengths, with the correction it // learned from the route's reported usage, nil when it had none. type EstimatedSize struct { Tokens int Correction *SizeCorrection } // SizeCorrection is provider tokens per thousand estimated ones. A // provisional one rests on Reports reports; a calibrated one is a moving // average over the route's reports. type SizeCorrection struct { PerMille int Calibrated bool Reports int } // CompactionStatus is whether the session's compaction has applied. type CompactionStatus string const ( CompactionNotConfigured CompactionStatus = "not_configured" CompactionNotNeeded CompactionStatus = "not_needed" CompactionApplied CompactionStatus = "compacted" CompactionUnknown CompactionStatus = "unknown" ) type ContextSnapshot struct { SnapshotID string Compaction CompactionState CapturedAt *int64 ContextWindowTokens *int State, Reason, Provider, Model, Protocol string Sections []ContextSection } type ContextPage struct { SnapshotID, Section, Content, Omitted string Page, Pages int } func GetContextSnapshot(ctx context.Context, conn *Connection, id string) (ContextSnapshot, error) { var result ContextSnapshot err := executeRead(ctx, conn, operation{Capability: "context", Name: "read prepared context", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewGetContextRequest(base, id) }, Policy: readRecovery}, func(data []byte) error { var w protocol.ContextSummary if err := decodeRequired(data, &w); err != nil { return err } if w.State != "ready" && w.State != "pending" { return fieldError("context state") } if w.State == "ready" && value(w.SnapshotID) == "" { return fieldError("context snapshot ID") } c := w.Compaction switch CompactionStatus(c.Status) { case CompactionNotConfigured, CompactionNotNeeded, CompactionApplied, CompactionUnknown: default: return fieldError("compaction status") } result = ContextSnapshot{SnapshotID: value(w.SnapshotID), CapturedAt: timestampMilliseconds(value(w.CapturedAt)), ContextWindowTokens: intPointer(w.ContextWindowTokens), State: w.State, Provider: value(w.Provider), Model: value(w.Model), Protocol: value(w.Protocol), Compaction: CompactionState{TriggerTokens: intPointer(c.TriggerTokens), InputLimitTokens: intPointer(c.InputLimitTokens), ProviderInputTokens: intPointer(c.ProviderInputTokens), ProviderCachedInputTokens: intPointer(c.ProviderCachedInputTokens), BeforeItems: intPointer(c.BeforeItems), AfterItems: intPointer(c.AfterItems), Strategy: value(c.Strategy), Status: CompactionStatus(c.Status), Source: value(c.Source)}} if c.Size != nil { size, err := sizeOf(*c.Size) if err != nil { return err } result.Compaction.Size = &size } if w.Reason != nil { result.Reason = w.Reason.Detail } for _, section := range w.Sections { result.Sections = append(result.Sections, ContextSection{ID: section.ID, Label: section.Label, Kind: section.Kind, Source: value(section.Source), Preview: section.Preview.Text, ItemCount: int(section.ItemCount), ByteCount: int(section.UTF8Bytes), Pages: int(section.PageCount)}) } return nil }) return result, err } // sizeOf reads a size from the wire, refusing a source or correction state it // does not know rather than showing it as something else. func sizeOf(w protocol.Size) (Size, error) { size := Size{Tokens: int(w.Tokens)} if m := w.Measured; m != nil { if m.Source != "count_endpoint" && m.Source != "reported_usage" { return Size{}, fieldError("size source") } size.Measured = &MeasuredSize{Tokens: int(m.Tokens), Counted: m.Source == "count_endpoint"} } if e := w.Estimated; e != nil { size.Estimated = &EstimatedSize{Tokens: int(e.Tokens)} if c := e.Correction; c != nil { if c.State != "provisional" && c.State != "calibrated" { return Size{}, fieldError("size correction") } size.Estimated.Correction = &SizeCorrection{PerMille: int(c.PerMille), Calibrated: c.State == "calibrated", Reports: int(value(c.Reports))} } } return size, nil } func GetContextPage(ctx context.Context, conn *Connection, id, snapshotID, section string, page int) (ContextPage, error) { if snapshotID == "" { return ContextPage{}, fieldError("context snapshot ID") } params := protocol.GetContextSectionParams{Page: int64(page)} var result ContextPage err := executeRead(ctx, conn, operation{Capability: "context", Name: "read prepared context section", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewGetContextSectionRequest(base, id, snapshotID, section, ¶ms) }, Policy: readRecovery}, func(data []byte) error { var w protocol.ContextSectionPage if err := decodeRequired(data, &w); err != nil { return err } if w.SnapshotID != snapshotID || w.SectionID != section || w.Page != int64(page) || len(w.Text) > 32768 || w.PageCount < 1 || w.Page >= w.PageCount { return fieldError("context section") } result = ContextPage{SnapshotID: w.SnapshotID, Section: w.SectionID, Content: w.Text, Omitted: value(w.Omitted), Page: int(w.Page), Pages: int(w.PageCount)} return nil }) return result, err } func (c *ChatClient) ContextWindow(ctx context.Context) (*int, error) { snapshot, err := GetContextSnapshot(ctx, c.conn, c.agentID) return snapshot.ContextWindowTokens, err }