Documentation
¶
Overview ¶
Package acdctx is the public Go surface of Accordion Context (spec §19.2 mode 6 and §19.9 "Harnesses e SDKs").
It offers two ways to use the context-compaction model without running the proxy as a separate process:
- Library flow: Open a Client and drive the turn loop yourself. Turn returns the visible window and an optional nudge, Compress records summaries, Decompress and Recall bring original messages back. See Client.
- HTTP middleware: NewTransport returns an http.RoundTripper that compacts Anthropic, OpenAI (Chat Completions and Responses) and Gemini requests in flight, so an SDK user only swaps the HTTP client. Handler embeds the same proxy handler in an existing server.
Both use the same store, session and kernel code as the proxy, so the compaction behaves the same in every mode. Internal types are not exported; the public Message, Role and Kind types map to them.
Index ¶
- Variables
- type Client
- func (c *Client) Close() error
- func (c *Client) Compress(ctx context.Context, args CompressArgs) (Result, error)
- func (c *Client) Decompress(ctx context.Context, blockID string) (DecompressResult, error)
- func (c *Client) ProjectID() string
- func (c *Client) Recall(ctx context.Context, ref string) (string, error)
- func (c *Client) Turn(ctx context.Context, msgs []Message, tokenCount int) (TurnResult, error)
- type CompressArgs
- type CompressRange
- type DecompressResult
- type FoldRange
- type Kind
- type Message
- type Options
- type Proxy
- type RecallHint
- type RecallKind
- type Result
- type Role
- type Transport
- type TurnResult
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClosed = errors.New("acdctx: client is closed")
ErrClosed is returned by a Client after Close.
var ErrNoConversation = errors.New("acdctx: no conversation yet; call Turn first")
ErrNoConversation is returned by Compress, Decompress and Recall before the first Turn.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the library handle: one store, one project and the active conversation. It is safe for concurrent use; Turn, Compress, Decompress and Recall are serialized per client.
func Open ¶
Open opens the database, resolves the project of opts.Cwd and loads the configuration. The caller must Close the client.
func (*Client) Compress ¶
Compress records summaries of finished ranges (spec §10). It applies to the conversation of the last Turn. Invalid input writes nothing.
func (*Client) Decompress ¶
Decompress expands one level of folding for blockID: the block becomes inactive and its direct sources become visible again (spec §13.1). Nothing is deleted.
func (*Client) Recall ¶
Recall returns the original text of a message ref such as "m00042" (spec §13).
func (*Client) Turn ¶
Turn ingests the transcript msgs (the full conversation so far) and plans the turn. tokenCount is the current context size in tokens, as the caller measures it; it drives the nudge (spec §8). The returned window is what to send to the model; Nudge, when not empty, should be added to the next user message.
Example ¶
ExampleClient_Turn shows the library flow of a custom agent: ingest the transcript, read the window, then compress a finished range and read the window again.
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
"github.com/fsvxavier/accordion-context/pkg/acdctx"
)
func main() {
dir, err := os.MkdirTemp("", "acdctx-example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()
c, err := acdctx.Open(ctx, acdctx.Options{
DBPath: dir + "/acd-ctx.db", Cwd: dir, ConfigPath: dir + "/none.yaml", Model: "claude-example",
})
if err != nil {
log.Fatal(err)
}
defer c.Close()
msgs := []acdctx.Message{
{Role: acdctx.RoleUser, Kind: acdctx.KindText, Text: "Refactor the parser. " + strings.Repeat("details ", 400)},
}
for i := 2; i <= 24; i++ {
role := acdctx.RoleAssistant
if i%2 == 1 {
role = acdctx.RoleUser
}
msgs = append(msgs, acdctx.Message{Role: role, Kind: acdctx.KindText, Text: strings.Repeat("step ", 500)})
}
turn, err := c.Turn(ctx, msgs, 9_000)
if err != nil {
log.Fatal(err)
}
fmt.Println("before:", len(turn.Visible) > 0)
_, err = c.Compress(ctx, acdctx.CompressArgs{Ranges: []acdctx.CompressRange{{
StartRef: "m00002", EndRef: "m00013",
Summary: "The parser steps 2 to 13 were applied and the tests passed.",
Topic: "parser",
}}})
if err != nil {
log.Fatal(err)
}
turn, err = c.Turn(ctx, msgs, 6_000)
if err != nil {
log.Fatal(err)
}
fmt.Println("after compress, fewer messages:", len(turn.Visible) < 25)
}
Output: before: true after compress, fewer messages: true
type CompressArgs ¶
type CompressArgs struct {
Ranges []CompressRange
Folds []FoldRange
CloseIntents []int64
}
CompressArgs is the input of Compress.
type CompressRange ¶
CompressRange summarizes the messages from StartRef to EndRef (inclusive).
type DecompressResult ¶
type DecompressResult struct {
Target string // the block that became inactive
Reactivated []string // its direct sources, visible again
Redirected bool // the requested block was folded; its active ancestor was expanded
}
DecompressResult reports what Decompress expanded.
type FoldRange ¶
FoldRange merges active blocks of Tier-1 from StartBlock to EndBlock into one block of Tier (2 or 3).
type Message ¶
type Message struct {
Seq int64
Ref string // "m00042", stable reference used by Compress and Recall
Role Role
Kind Kind
ToolName string
ToolCallID string
Text string
Tokens int // estimated size, set on output
CCRStored bool // the text was shortened and the original is stored
}
Message is one entry of the conversation. Ref is set on messages returned by Turn; the input Tokens field is ignored because the library estimates it.
type Options ¶
type Options struct {
// DBPath is the SQLite database file. Required. Its directory is created.
DBPath string
// Cwd is the working directory of the agent. It selects the project (spec
// §18.2). Empty means the process working directory.
Cwd string
// ConfigPath is the global configuration file. Empty means the user config path.
ConfigPath string
// Model is the model name recorded on the library session.
Model string
// ContextLimit is the context window in tokens. Zero means 200000.
ContextLimit int
// ConversationID, when set, names the library conversation explicitly. Otherwise
// the first user message identifies it, as the proxy does.
ConversationID string
// Upstreams lists the origins (scheme://host[:port]) whose compaction-eligible
// requests the middleware and handler compact. Other origins pass through
// untouched. Empty means the Anthropic, OpenAI and Gemini origins.
Upstreams []string
// MaxLoop bounds the server-side tool rounds per request. Zero means 4.
MaxLoop int
// ListenHost is an extra Host header name accepted by Handler, for embedding
// in a server that is not reached through localhost. Empty for none.
ListenHost string
// Logger receives diagnostics. Nil discards them.
Logger *slog.Logger
}
Options configures Open, NewTransport and Handler. Zero fields take defaults.
type Proxy ¶
type Proxy struct {
// contains filtered or unexported fields
}
Proxy is the proxy handler, for embedding in an existing HTTP server. Mount it at the root or behind http.StripPrefix. It serves the same paths as the proxy binary.
type RecallHint ¶
type RecallHint struct {
Kind RecallKind
BlockID string // pass to Decompress
Ref string // folded message ref, when the hint names one
Path string // re-read target path, when one was found
Text string
}
RecallHint points from folded content to the active block that covers it.
type RecallKind ¶
type RecallKind string
RecallKind names the signal behind a RecallHint.
const ( RecallReread RecallKind = "reread" // a tool call repeats a folded one RecallRef RecallKind = "ref" // the latest text cites a folded message ref RecallBlock RecallKind = "block" // the latest text cites a folded block id )
Recall signals (spec §13.2).
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
Transport is an http.RoundTripper that compacts model requests in flight. Requests to the endpoints of Anthropic Messages, OpenAI Chat Completions and Responses, and Gemini generateContent, on an origin listed in Options.Upstreams, go through the proxy's compaction loop. Everything else goes to the base transport unchanged.
func NewTransport ¶
func NewTransport(base http.RoundTripper, opts Options) (*Transport, error)
NewTransport wraps base (nil means http.DefaultTransport) with compaction. Use it as the Transport of an SDK's HTTP client. Close releases the database.
Example ¶
ExampleNewTransport shows an SDK user swapping the HTTP client only. The upstream is a local fake, so the example runs offline.
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"strings"
"github.com/fsvxavier/accordion-context/pkg/acdctx"
)
func main() {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, `{"type":"message","role":"assistant","model":"claude-example",`+
`"content":[{"type":"text","text":"done"}],"stop_reason":"end_turn",`+
`"usage":{"input_tokens":3,"output_tokens":1}}`)
}))
defer upstream.Close()
dir, err := os.MkdirTemp("", "acdctx-example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
tr, err := acdctx.NewTransport(nil, acdctx.Options{
DBPath: dir + "/acd-ctx.db", Cwd: dir, ConfigPath: dir + "/none.yaml",
Upstreams: []string{upstream.URL},
})
if err != nil {
log.Fatal(err)
}
defer tr.Close()
client := &http.Client{Transport: tr}
body := `{"model":"claude-example","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`
resp, err := client.Post(upstream.URL+"/v1/messages", "application/json", strings.NewReader(body))
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
answer, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, strings.Contains(string(answer), `"done"`))
}
Output: 200 true
type TurnResult ¶
type TurnResult struct {
// Visible is the window to send to the model, in order.
Visible []Message
// Nudge is a note asking the model to compress finished ranges, or "". Append it
// to the next user message when it is not empty.
Nudge string
// Hints are ephemeral recall pointers for this turn.
Hints []RecallHint
// Row is the decision row of spec §8.3 that produced the nudge decision.
Row string
}
TurnResult is the plan of one turn.