Something went wrong. Try again.
small gleam coding and (not yet) persistent agent daemon with a detachable cli forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540package acp
import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt"
"albedo/cli/internal/daemon" "albedo/cli/internal/daemon/protocol")
type activityKind uint8
const ( promptActivity activityKind = iota compactActivity)
type activityPhase uint8
const ( activityPending activityPhase = iota activityRunning activityFinishing)
type activity struct { kind activityKind handle *daemon.OperationHandle request request blocks []json.RawMessage phase activityPhase cancelRequested bool cancelSent bool}
func (a *activity) running() bool { return a.phase == activityRunning || a.phase == activityFinishing}
type observation uint8
const ( observing observation = iota preparing buffering lost)
type stopReason string
const ( stopEndTurn stopReason = "end_turn" stopMaxTokens stopReason = "max_tokens" stopMaxRequests stopReason = "max_turn_requests" stopRefusal stopReason = "refusal" stopCancelled stopReason = "cancelled")
type promptResult struct { StopReason stopReason `json:"stopReason"`}
func promptEnded() promptResult { return promptResult{StopReason: stopEndTurn} }func promptCancelled() promptResult { return promptResult{StopReason: stopCancelled} }
type effect interface { apply(*session)}
type respondEffect struct { request request result any failure error}
func (e respondEffect) apply(s *session) { s.adapter.respond(e.request.ID, e.result, e.failure) }
type finishEffect struct { activity *activity request request result any failure error}
func (e finishEffect) apply(s *session) { s.finishWithBarrier(e) }
type submitEffect struct{ activity *activity }
func (e submitEffect) apply(s *session) { s.submit(e.activity) }
type admitEffect struct{ activity *activity }
func (e admitEffect) apply(s *session) { s.admit(e.activity) }
type compactEffect struct{ activity *activity }
func (e compactEffect) apply(s *session) { go s.compact(e.activity) }
type cancelEffect struct { activity *activity id string}
func (e cancelEffect) apply(s *session) { s.cancelInput(e.id, e.activity) }
type diagnosticEffect struct{ message string }
func (e diagnosticEffect) apply(s *session) { if s.adapter.diagnostics != nil { fmt.Fprintln(s.adapter.diagnostics, e.message) }}
type clearReconciliationEffect struct{}
func (clearReconciliationEffect) apply(s *session) { s.clearReconciliation() }
type fetchWindowEffect struct{ generation int }
func (e fetchWindowEffect) apply(s *session) { go s.fetchContextWindow(e.generation) }
type updateEffect struct{ update any }
func (e updateEffect) apply(s *session) { s.update(e.update) }
type sessionState struct { observation observation active *activity queued *activity turn string inherited []string failure *rpcError}
func (st *sessionState) promptRefusal() *rpcError { switch st.observation { case lost: return uncertain(resumeForPrompt) case preparing, buffering: return refuseBusy("Session setup is in progress") } return nil}
func (st *sessionState) blocked() bool { return st.turn != "" || len(st.inherited) > 0}
func (st *sessionState) turnPending() bool { if st.observation != observing || st.queued != nil { return true } if st.active != nil { return st.active.phase != activityFinishing } return st.blocked()}
func (st *sessionState) configRefusal() *rpcError { if st.observation == lost { return uncertain(resumeForConfig) } if st.observation != observing { return refuseBusy("Session setup is in progress") } if st.turnPending() { return refuseBusy("Wait for the current turn before changing its configuration") } return nil}
func (st *sessionState) beginConfig() { st.observation = preparing }
func (st *sessionState) endConfig(closed bool) []effect { if closed { return st.markLost("observation_uncertain", "Session closed while changing configuration") } if st.observation == preparing { st.observation = observing } return nil}
func (st *sessionState) acceptPrompt(message request, blocks []json.RawMessage) ([]effect, *rpcError) { if refusal := st.promptRefusal(); refusal != nil { return nil, refusal } next := &activity{kind: promptActivity, request: message, blocks: blocks} if st.active != nil { if st.active.cancelRequested || st.active.phase == activityFinishing { return st.enqueue(next) } return nil, refuseBusy("A prompt is already active") } if st.blocked() { return st.enqueue(next) } st.active = next return []effect{admitEffect{activity: next}}, nil}
func (st *sessionState) enqueue(next *activity) ([]effect, *rpcError) { if st.queued != nil { return nil, refuseBusy("An activity is already waiting") } st.queued = next return nil, nil}
func startEffect(a *activity) effect { if a.kind == compactActivity { return compactEffect{activity: a} } return admitEffect{activity: a}}
func (st *sessionState) acceptCompact(message request) ([]effect, *rpcError) { if refusal := st.promptRefusal(); refusal != nil { return nil, refusal } next := &activity{kind: compactActivity, request: message} if st.active != nil || st.blocked() { return st.enqueue(next) } st.active = next return []effect{startEffect(next)}, nil}
func (st *sessionState) submitted(a *activity, err error) []effect { if st.active != a || a.phase == activityFinishing { return nil } if err != nil { if _, ambiguous := err.(*daemon.UncertainOutcomeError); ambiguous && a.running() { return nil } return st.markLost("observation_uncertain", err.Error()) } return st.admitted(a)}
func (st *sessionState) admitted(a *activity) []effect { if st.active != a || a.phase == activityFinishing { return nil } a.phase = activityRunning if a.cancelRequested && !a.cancelSent { a.cancelSent = true return []effect{cancelEffect{activity: a, id: a.handle.ID()}} } return nil}
func (st *sessionState) cancel() []effect { effects := []effect{} if st.queued != nil { effects = append(effects, respondEffect{request: st.queued.request, result: promptCancelled()}) st.queued = nil } if st.active != nil && st.active.kind == compactActivity { effects = append(effects, respondEffect{request: st.active.request, result: promptCancelled()}) st.active = nil } if st.active != nil { a := st.active a.cancelRequested = true if a.running() && a.phase != activityFinishing && !a.cancelSent && a.handle != nil { a.cancelSent = true effects = append(effects, cancelEffect{activity: a, id: a.handle.ID()}) } } for _, id := range st.inherited { effects = append(effects, cancelEffect{id: id}) } return effects}
type cancellationResult string
const ( cancelSettled cancellationResult = "cancelled" cancelNotPending cancellationResult = "not_pending" cancelInterruptRequested cancellationResult = "interrupt_requested" cancelSharedRunning cancellationResult = "shared_running")
func (result cancellationResult) delivered(input protocol.Input) bool { switch result { case cancelSettled: return true case cancelNotPending: return input.Delivery != nil && cancellationResult(*input.Delivery) == cancelSettled } return false}
func (st *sessionState) cancelled(id string, a *activity, err error, receipt protocol.InputCancellation) []effect { if a != nil && (st.active != a || a.phase == activityFinishing) { return nil } if err != nil { return st.markLost("observation_uncertain", "Cancellation could not be reconciled") } result := cancellationResult(receipt.Result) switch { case result.delivered(receipt.Input): st.inherited = removeID(st.inherited, id) if a == nil { return st.admitQueued() } return st.finish(a, stopCancelled, nil) case result == cancelNotPending, result == cancelInterruptRequested: return nil case result == cancelSharedRunning: return st.markLost("observation_uncertain", "Daemon violated exclusive ACP input contract") default: return st.markLost("observation_uncertain", "Unknown cancellation result") }}
func (st *sessionState) finish(a *activity, reason stopReason, failure error) []effect { if st.active != a || a.phase == activityFinishing { return nil } if a.cancelRequested && failure != nil { reason, failure = stopCancelled, nil } a.phase = activityFinishing result := any(nil) if failure == nil { result = promptResult{StopReason: reason} } return []effect{finishEffect{activity: a, request: a.request, result: result, failure: failure}}}
func (st *sessionState) responseWritten(a *activity) []effect { if st.active != a { return nil } st.active = nil st.turn = "" st.failure = nil return append([]effect{clearReconciliationEffect{}}, st.admitQueued()...)}
func (st *sessionState) admitQueued() []effect { if st.active != nil || st.queued == nil || st.observation != observing || st.blocked() { return nil } next := st.queued st.queued = nil st.active = next return []effect{startEffect(next)}}
func (st *sessionState) markLost(reason, message string) []effect { st.observation = lost st.failure = problem(-32603, reason, message) effects := []effect{clearReconciliationEffect{}} if st.active == nil && st.queued == nil { effects = append(effects, diagnosticEffect{message: message}) } if st.queued != nil { effects = append(effects, respondEffect{request: st.queued.request, failure: st.failure}) st.queued = nil } if st.active != nil { effects = append(effects, st.finish(st.active, "", st.failure)...) } return effects}
func (st *sessionState) turnMembership(turnID string, submissionIDs []string) []effect { if st.turn != "" && turnID != st.turn { return nil } owned := false if st.active != nil && st.active.handle != nil { owned = contains(submissionIDs, st.active.handle.ID()) } if !owned { for _, id := range st.inherited { if contains(submissionIDs, id) { owned = true break } } } if !owned { return nil } st.turn = turnID if st.active == nil || st.active.handle == nil || !contains(submissionIDs, st.active.handle.ID()) { return nil } return st.admitted(st.active)}
func (st *sessionState) turnCompleted(turnID string, submissionIDs []string, outcome daemon.TurnOutcome) []effect { if st.turn != turnID { return nil } st.inherited = removeAll(st.inherited, submissionIDs) if st.active == nil { st.turn = "" st.failure = nil return append([]effect{clearReconciliationEffect{}}, st.admitQueued()...) } switch outcome { case daemon.OutcomeInterrupted: return st.finish(st.active, stopCancelled, nil) case daemon.OutcomeFailed: failure := st.failure if failure == nil { failure = internalError("The turn failed") } return st.finish(st.active, "", failure) default: return st.finish(st.active, stopEndTurn, nil) }}
func (st *sessionState) completeCompact(a *activity, result daemon.CompactionResult, err error, sessionID string, compactionEnabled bool) []effect { if st.active != a || a.kind != compactActivity { return nil } st.active = nil effects := []effect{clearReconciliationEffect{}} if err != nil { effects = append(effects, respondEffect{request: a.request, failure: err}) return append(effects, st.admitQueued()...) } if result.Failure != nil { id := compactionID(sessionID, a.request.ID) detail := boundedText(result.Failure.Detail, 4096) if compactionEnabled { effects = append(effects, updateEffect{update: compactionUpdate{Kind: updateCompaction, ID: id, Status: compactionFailed, Error: detail}}) } effects = append(effects, updateEffect{update: chunkOf(updateAgentChunk, id, "Context compaction failed: "+detail)}) } effects = append(effects, respondEffect{request: a.request, result: promptEnded()}) return append(effects, st.admitQueued()...)}
func compactionID(sessionID string, requestID json.RawMessage) string { sum := sha256.Sum256([]byte(sessionID + "\x00" + string(requestID))) return "acp-compaction-" + hex.EncodeToString(sum[:12])}
func contains(values []string, want string) bool { for _, value := range values { if value == want { return true } } return false}
func removeAll(values, excluded []string) []string { kept := make([]string, 0, len(values)) for _, value := range values { if !contains(excluded, value) { kept = append(kept, value) } } return kept}
type windowPhase uint8
const ( windowUnknown windowPhase = iota windowFetching windowKnown windowUnavailable)
type contextWindow struct { phase windowPhase tokens int generation int}
type usageState struct { window contextWindow pending []*daemon.Usage}
const maxPendingUsage = 16
func (u *usageState) add(info *daemon.Usage) (int, bool) { if info == nil { return 0, false } if len(u.pending) == maxPendingUsage { u.pending = u.pending[1:] } u.pending = append(u.pending, info) if u.window.phase == windowUnavailable { u.window.generation++ u.window.phase = windowUnknown } if u.window.phase != windowUnknown { return 0, false } u.window.phase = windowFetching return u.window.generation, true}
func (u *usageState) resolve(tokens *int, generation int) []*daemon.Usage { if u.window.generation != generation { return nil } if tokens == nil || *tokens < 0 { u.window.phase = windowUnavailable u.pending = nil return nil } u.window.phase = windowKnown u.window.tokens = *tokens pending := u.pending u.pending = nil return pending}
func (u *usageState) invalidate() { u.window.generation++ u.window.phase = windowUnknown u.window.tokens = 0 u.pending = nil}
func (u *usageState) take() []*daemon.Usage { pending := u.pending u.pending = nil return pending}