// Package dataplane holds what flows between the operator and the turns // it runs: the events that wait for a Session, the transcripts that let // a turn resume, and the requests a turn makes. None of it is a // resource. plans/operator-build.md, "The data plane API", is the // design. // // The operator owns a Store and serves it to Jobs over HTTP. The // operator's control loops implement Control, so a request from a turn // becomes a write to a Session's or an Account's status there, and // nowhere else. package dataplane import ( "context" "encoding/json" "errors" "fmt" "io" "strings" "time" "tangled.org/guid.foo/simmer/api/v1alpha1" ) // SessionRef names one Session. type SessionRef struct { Namespace string `json:"namespace"` Name string `json:"name"` } func (r SessionRef) String() string { return r.Namespace + "/" + r.Name } // Event is one occurrence of a Signal, as it waits in a Session's inbox. type Event struct { // ID is unique per event, so a redelivered event is recognized. ID string `json:"id"` // Signal names the Signal it arrived on. Signal string `json:"signal"` // Keys are the keys the Signal computed for the event. Keys []string `json:"keys"` // Description is the Signal's describe output, or the payload as // JSON when the Signal has no describe expression. Description string `json:"description"` // Payload is the event as it arrived. Payload json.RawMessage `json:"payload"` ReceivedAt time.Time `json:"receivedAt"` // Holders are the other Sessions that held one of the event's keys // when the router delivered it, so an agent knows who else works on // the same thing. The list goes stale, and the holders route // answers the current one. Holders []Holder `json:"holders,omitempty"` } // Holder is a Session that holds a key. type Holder struct { Namespace string `json:"namespace"` Name string `json:"name"` Mandate string `json:"mandate"` Duty string `json:"duty,omitempty"` Skill string `json:"skill"` } // String is the holder as the prompt and simmer holders print it. func (h Holder) String() string { return fmt.Sprintf("%s/%s, of the Mandate %s, runs the skill %s", h.Namespace, h.Name, h.Mandate, h.Skill) } // HoldersAnswer is the body of the holders route. type HoldersAnswer struct { Holders []Holder `json:"holders"` } // Store keeps each Session's inbox and transcript on the operator's // volume. A turn takes events at least once: Take moves the inbox into // the turn's taken set, Ack sets that set aside when the turn succeeds, // and any taken set left from a failed or interrupted turn comes back // first in the next Take. A set aside stays for the turn's after hook // to read until Drop, and it is not pending. type Store interface { // Deliver appends an event to the Session's inbox. Deliver(session SessionRef, event Event) error // Pending counts the events that the next turn would take: the // inbox plus any taken set that was never acknowledged. Pending(session SessionRef) (int, error) // Take gives a turn its events and marks them taken by that turn. Take(session SessionRef, turn int) ([]Event, error) // Ack sets aside the events a turn took, after it succeeded. Ack(session SessionRef, turn int) error // Drop removes the events that Ack set aside for a turn. Drop(session SessionRef, turn int) error // Kept answers the events a turn took: the set Ack set aside, or // the taken set of a turn that was not acknowledged. Kept(session SessionRef, turn int) ([]Event, error) // Waiting answers the events that the next turn would take, oldest // first, and takes none of them. Waiting(session SessionRef) ([]Event, error) // Transcript opens the Session's transcript archive. It returns // ErrNoTranscript when there is none yet. Transcript(session SessionRef) (io.ReadCloser, error) // PutTranscript replaces the Session's transcript archive. PutTranscript(session SessionRef, archive io.Reader) error // Forget removes everything kept for a Session that is gone. Forget(session SessionRef) error // Sessions lists each Session that the Store keeps anything for. Sessions() ([]SessionRef, error) } // Turn is what a Job needs to run one turn of a Session. type Turn struct { Session SessionRef `json:"session"` // UID is the Session's uid, which is also the Claude Code session // id, so every turn resumes the same conversation. UID string `json:"uid"` // Number counts the Session's turns from 1. Number int `json:"number"` Skill string `json:"skill"` // Repositories are clone URLs. The first is the working directory. Repositories []string `json:"repositories"` // Plugins are clone URLs of repositories that each hold a Claude // Code plugin at their root. Plugins []string `json:"plugins,omitempty"` // MCPServers maps each server's name to how to reach it. MCPServers map[string]v1alpha1.McpServerSpec `json:"mcpServers"` // Resume is true when a transcript exists, so the turn resumes. Resume bool `json:"resume"` // Keys are the keys the Session holds when the turn starts. Keys []string `json:"keys"` // FollowUp is the follow-up the Session holds when the turn starts, // when an event woke it first. It is nil when there is none. FollowUp *v1alpha1.FollowUp `json:"followUp,omitempty"` Events []Event `json:"events"` } // The hooks a HookContext names. const ( HookBefore = "before" HookAfter = "after" ) // HookContext is what a hook's Job reads of its Session and turn. // plans/hooks.md, "What a hook reads", is the design. type HookContext struct { // Hook is HookBefore or HookAfter. Hook string `json:"hook"` Namespace string `json:"namespace"` Session string `json:"session"` Mandate string `json:"mandate"` Skill string `json:"skill"` Origin *v1alpha1.Origin `json:"origin,omitempty"` // Turn numbers the turn that the hook runs before or after. For the // after hook of a Session that fails without a turn, it numbers the // last turn, and is 0 when there was none. Turn int `json:"turn"` // Outcome is how the turn ended. It is empty for a before hook, and // Failed for a Session that fails without a turn. Outcome v1alpha1.Outcome `json:"outcome"` // Reason is set only on the after hook that ends a failed Session, // such as MaxTurns or TurnsFailed. Reason string `json:"reason"` Keys []string `json:"keys"` // Events are the turn's events, with their payloads. A before hook // and the after hook of a Session that fails without a turn get the // events that wait for the next turn. Events []Event `json:"events"` } // RateLimitInfo is the rate_limit_info of a Claude Code // rate_limit_event, as stream-json prints it. FiveHour has no reset // time when the plan has no five-hour limit. type RateLimitInfo struct { UnifiedWindows struct { FiveHour RateLimitWindow `json:"five_hour"` SevenDay RateLimitWindow `json:"seven_day"` } `json:"unifiedWindows"` } // RateLimitWindow is one window: the fraction used, and when it resets // as Unix seconds. type RateLimitWindow struct { Utilization float64 `json:"utilization"` ResetsAt int64 `json:"resetsAt"` } // FollowUpRequest is the body of PUT on the follow-up route: how long // from now the Session's follow-up falls due, as a Go duration string, // and its reason. The operator takes the time by its own clock. type FollowUpRequest struct { After string `json:"after"` Reason string `json:"reason"` } // FollowUpAnswer is the answer to PUT on the follow-up route: when the // follow-up falls due. type FollowUpAnswer struct { At time.Time `json:"at"` } // The bounds of a follow-up that hold in every Mandate. The longest // follow-up is the Mandate's sessions.maxFollowUp. The CRD holds the // reason to the same length. const ( MinFollowUp = 10 * time.Minute MaxFollowUpReason = 500 ) // ErrFollowUpOutOfBounds means a follow-up's duration or reason is out // of its bounds, so the request must change. ErrFollowUpRefused means // the Session may set no follow-up now, whatever the request. var ( ErrFollowUpOutOfBounds = errors.New("the follow-up is out of bounds") ErrFollowUpRefused = errors.New("the Session may set no follow-up") ) // TokensRequest is the body of the tokens route: the token total and // the cost of Claude Code's result, which count every turn of the // conversation, and whether the turn resumed the conversation or // started it. The cost is in notional US dollars: what the tokens would // cost at the provider's API prices. type TokensRequest struct { Tokens int64 `json:"tokens"` CostUSD float64 `json:"costUSD"` Resumed bool `json:"resumed"` } // DutyRef names one Duty. type DutyRef struct { Namespace string `json:"namespace"` Name string `json:"name"` } func (r DutyRef) String() string { return r.Namespace + "/" + r.Name } // ScheduleIdentity is who may call a Duty's start route: a pod of its // Mandate that runs as the Mandate's ServiceAccount. type ScheduleIdentity struct { Mandate string ServiceAccount string } // StartAnswer is the answer to the start route. type StartAnswer struct { // Session names the Session that runs the duty: the one the // request started, or the active one that a schedule started // earlier, when Started is false. Session string `json:"session"` Started bool `json:"started"` Message string `json:"message"` } // ErrUnknownDuty means the Duty does not exist or has no schedule. // ErrNotTheSchedule means the caller's Job is not one that the Duty's // CronJob made. ErrStartRefused means the Duty may start no Session // now: it or its Mandate is not Ready, or a Stop exists. var ( ErrUnknownDuty = errors.New("no such scheduled duty") ErrNotTheSchedule = errors.New("the Job is not one that the duty's CronJob made") ErrStartRefused = errors.New("the Duty starts no Session now") ) // Control is the operator's side of the data plane. The HTTP server has // already checked that the caller is a running Job pod of the Session, // or of the duty's schedule, before it calls any of these but // ServiceAccount, HookServiceAccount, and Schedule. type Control interface { // ServiceAccount names the ServiceAccount that the Session's turns // run as, which is its Mandate's. The server lets in only a pod // that runs as it. It returns ErrUnknownSession for a Session that // does not exist or has ended. ServiceAccount(ctx context.Context, session SessionRef) (string, error) // HookServiceAccount names the ServiceAccount that the hooks of the // Session's Duty run as, which can differ from its turns'. The // server lets a hook's pod in only as it. HookServiceAccount(ctx context.Context, session SessionRef) (string, error) // Turn describes the Session's next turn, without its events: the // server takes those from the Store and adds them. It returns // ErrUnknownSession for a Session that does not exist or has // finished. Turn(ctx context.Context, session SessionRef) (Turn, error) // Follow adds a key to the Session's status. Follow(ctx context.Context, session SessionRef, key string) error // Release removes a key from the Session's status. Release(ctx context.Context, session SessionRef, key string) error // Holders answers every other Session that holds a key now, in any // Mandate. Holders(ctx context.Context, session SessionRef, key string) ([]Holder, error) // SessionUsage records a reading from a turn, on the Account that // the Session's Mandate draws on. SessionUsage(ctx context.Context, session SessionRef, info RateLimitInfo) error // SessionTokens records the token total and the cost of Claude // Code's result at the end of the Session's running turn, which // count every turn of the conversation. The running turn's own // share of the cost is charged to its Allowance. SessionTokens(ctx context.Context, session SessionRef, tokens TokensRequest) error // SetFollowUp sets or replaces the Session's follow-up, due after // the duration from now by the operator's clock, and answers when it // falls due. It returns ErrFollowUpOutOfBounds for a duration past // the Mandate's maxFollowUp, and ErrFollowUpRefused when the // follow-up's turn would pass maxFollowUps or maxTurns. SetFollowUp(ctx context.Context, session SessionRef, after time.Duration, reason string) (time.Time, error) // CancelFollowUp removes the Session's follow-up, if it has one. CancelFollowUp(ctx context.Context, session SessionRef) error // Hook answers the context of the Session's hook that runs in the // Job. It returns ErrUnknownSession when the Job is not one of the // Session's hooks. Hook(ctx context.Context, session SessionRef, job string) (HookContext, error) // AccountUsage records a reading from a probe Job. AccountUsage(ctx context.Context, account string, info RateLimitInfo) error // Schedule answers who may call the start route of a Duty with a // schedule: its Mandate and the ServiceAccount that its schedule's // Jobs run as. It returns ErrUnknownDuty when the Duty does not // exist or has no schedule. Schedule(ctx context.Context, duty DutyRef) (ScheduleIdentity, error) // Start starts a Session of the Duty for a pod of the Job named // job, unless a Session that a schedule started for the Duty is // still active. It returns ErrNotTheSchedule when the Job is not // one that the Duty's CronJob made, ErrUnknownDuty as Schedule // does, and ErrStartRefused when the Duty or its Mandate is not // Ready or a Stop exists. Start(ctx context.Context, duty DutyRef, job string) (StartAnswer, error) } // ErrNoTranscript means a Session has no transcript yet, so its next // turn is its first. var ErrNoTranscript = errors.New("no transcript") // ErrUnknownSession means the Session does not exist or has finished. var ErrUnknownSession = errors.New("unknown session") // RepositoryName is the last part of a clone URL without .git, as // `git clone` names its directory: infra for both // ssh://git@forge:2222/example/infra.git and // git@forge:example/infra.git. func RepositoryName(repository string) (string, error) { trimmed := strings.TrimSuffix(repository, "/") name := strings.TrimSuffix(trimmed[strings.LastIndexAny(trimmed, "/:")+1:], ".git") if name == "" || name == "." || name == ".." { return "", fmt.Errorf("%q names no repository", repository) } return name, nil }