package protocol import ( "fmt" "strings" ) const ( RunPipeline = "run_pipeline" RunStarted = "run_started" ListRuns = "list_runs" Runs = "runs" GetRun = "get_run" Run = "run" CancelRun = "cancel_run" RetryRun = "retry_run" DecideRun = "decide_run" SetRunTitle = "set_run_title" GetRunEvidence = "get_run_evidence" RunEvidence = "run_evidence" RepairSessionExport = "repair_session_export" // DeleteRuns removes terminal runs and everything the server stores for // them; the reply is RunsDeleted and other subscribers receive RunsRemoved. DeleteRuns = "delete_runs" RunsDeleted = "runs_deleted" RunsRemoved = "runs_removed" ) // RunsDeletedResult is the runs_deleted reply to delete_runs. Deleted lists the // run ids removed, Refused every requested id that was kept with the reason // (an active run, an unknown id, ...), and FreedBytes the summed size_bytes of // the deleted runs as measured immediately before deletion. All three are // always present. type RunsDeletedResult struct { RemainingFileBytes int64 `json:"remaining_file_bytes,omitempty"` Deleted []int64 `json:"deleted"` Refused []RunDeleteRefusal `json:"refused"` FreedBytes int64 `json:"freed_bytes"` } // RunDeleteRefusal is one requested run id delete_runs did not remove. type RunDeleteRefusal struct { RunID int64 `json:"run_id"` Reason string `json:"reason"` } // Waiting statuses. A human stage pauses its run without a live goroutine, so // the run and its step persist these statuses and the decision path resumes // them. Store, server, CLI and TUI read the one pair below, never a literal. const ( RunStatusQueued = "queued" RunStatusWaiting = "waiting" RunStatusRunning = "running" RunStatusCanceled = "canceled" StepStatusRunning = "running" StepStatusWaiting = "waiting" // NotifyWaiting is the notification event a human stage emits when it parks // the run. It is the same value the `on=` policy accepts. NotifyWaiting = "waiting" ) // Waiting evidence keys. A human stage records its operator instructions and // its ordered selectable options in the step output, so inspect and the TUI are // self-contained without re-reading the pinned graph. const ( WaitingPromptKey = "prompt" WaitingOptionsKey = "options" ) // Decision evidence keys. A decided human step records the operator's chosen // option and optional feedback in its output, so the choice stays visible in // inspect and the TUI. They are the one definition of those keys. const ( DecisionOptionKey = "option" DecisionFeedbackKey = "feedback" ) // NewWaitingEvidence builds the self-contained evidence a human stage persists // at wait time: the operator instructions and the ordered options to choose. func NewWaitingEvidence(prompt string, options []string) map[string]any { ordered := make([]any, len(options)) for i, option := range options { ordered[i] = option } return map[string]any{WaitingPromptKey: prompt, WaitingOptionsKey: ordered} } // WaitingPrompt reads the recorded operator instructions from a waiting step's // output, or "" when none were recorded. func WaitingPrompt(output map[string]any) string { prompt, _ := output[WaitingPromptKey].(string) return prompt } // WaitingOptions reads the recorded selectable options from a waiting step's // output, accepting the string and generic forms JSON decoding produces. func WaitingOptions(output map[string]any) []string { switch options := output[WaitingOptionsKey].(type) { case []string: return options case []any: result := make([]string, 0, len(options)) for _, option := range options { if text, ok := option.(string); ok { result = append(result, text) } } return result } return nil } // DecisionEvidence reads the recorded choice and feedback from a decided human // step's output, or empty strings when none were recorded. It is the read side // of DecisionOptionKey/DecisionFeedbackKey. func DecisionEvidence(output map[string]any) (option, feedback string) { option, _ = output[DecisionOptionKey].(string) feedback, _ = output[DecisionFeedbackKey].(string) return option, feedback } type SessionEvidence struct { Sequence int `json:"sequence"` SessionID string `json:"session_id"` Backend string `json:"backend"` Directory string `json:"directory"` Data string `json:"data,omitempty"` Diagnostic string `json:"diagnostic,omitempty"` } // SessionExport is the recorded evidence of one stage's session file export: // the html file name written under the step's artifacts directory, its byte // size, the decoded message count, the source, whether the export was truncated // and a sanitized diagnostic. It is observed server-side evidence, not a model // claim. A record written before the HTML-only change also carried markdown and // markdown_bytes; readers ignore those fields. // Status explicitly describes evidence completeness, independently from the // stage outcome. Directory and capture time preserve export provenance. type SessionExport struct { Directory string `json:"directory,omitempty"` RecordedAt string `json:"recorded_at,omitempty"` Attempts int `json:"attempts,omitempty"` Status string `json:"status,omitempty"` SessionID string `json:"session_id,omitempty"` Backend string `json:"backend,omitempty"` Source string `json:"source,omitempty"` HTML string `json:"html,omitempty"` HTMLBytes int64 `json:"html_bytes,omitempty"` Messages int `json:"messages"` Truncated bool `json:"truncated,omitempty"` Diagnostic string `json:"diagnostic,omitempty"` } // SessionExportRecovery describes the runtime's bounded durable repair job. type SessionExportRecovery struct { Status string `json:"status"` Attempts int `json:"attempts"` NextAt int64 `json:"next_attempt_at_ms"` Diagnostic string `json:"diagnostic,omitempty"` } type RunSummary struct { Scheduled bool `json:"scheduled"` ScheduleID int64 `json:"schedule_id,omitempty"` ScheduleName string `json:"schedule_name,omitempty"` GraphEvidence *RunGraphEvidence `json:"graph_evidence,omitempty"` NotifyMode string `json:"notify_mode,omitempty"` ID int64 `json:"id"` PipelineID int64 `json:"pipeline_id"` Name string `json:"name"` // Title is the operator-facing, bounded single-line description of what the // run is for, generated from its prompt. It is never empty for a new run; // historical rows predating the title column may omit it. Title string `json:"title,omitempty"` Version int `json:"version"` ContentHash string `json:"content_hash"` Status string `json:"status"` // ExportPendingSequence distinguishes a quiescent export handoff from a // human decision while Status is waiting. It never implies agent execution. ExportPendingSequence int `json:"export_pending_sequence,omitempty"` CancelRequested bool `json:"cancel_requested,omitempty"` CleanupUnconfirmed bool `json:"cleanup_unconfirmed,omitempty"` Executing bool `json:"executing"` Outcome string `json:"outcome"` CurrentStage string `json:"current_stage"` Workspace string `json:"workspace,omitempty"` CreatedAt string `json:"created_at"` FinishedAt string `json:"finished_at"` Diagnostic string `json:"diagnostic"` ResultPreview string `json:"result_preview,omitempty"` CompletedSteps int `json:"completed_steps"` // Model and StageModels are the launch-time overrides this run records so it // stays reproducible: Model covers every model stage and StageModels overrides // individual stages by key. They are empty for a run that used the pinned // models and for historical rows. Model string `json:"model,omitempty"` StageModels map[string]string `json:"stage_models,omitempty"` OutputFormat string `json:"output_format,omitempty"` // SizeBytes is the bytes on disk attributable to the run: its artifact tree // (turn documents, inputs, outputs, session exports), server-created Pi // session directories and an estimate of its database rows. It is cached // server-side; 0 means not measured yet (a background backfill fills it). SizeBytes int64 `json:"size_bytes"` // Usage is the totalled reported usage of the run's model stages. The run // list sums it with one SQL aggregate per batch over the stored per-stage // usage rows; the run detail sums the same rows in one pass over its loaded // steps (TotalUsage). It is absent for a run with no model usage recorded // (including historical runs and servers predating the list aggregate), so // a client shows nothing rather than zero. A total is partial when // TokensKnownStages < Stages. Usage *RunUsage `json:"usage,omitempty"` } // RunGraphVisit contains only routing and lifecycle facts, never private step // inputs, outputs, diagnostics, sessions or transcripts. Repeated loop visits // are compacted to the latest stage visit and the latest visit of each route. type RunGraphVisit struct { Sequence int `json:"sequence"` Stage string `json:"stage"` Status string `json:"status"` Outcome string `json:"outcome"` Target string `json:"target"` } type RunGraphEvidence struct { Complete bool `json:"complete"` Visits []RunGraphVisit `json:"visits"` } // Label is the operator-facing name of a run: the generated Title when the // server stored one, otherwise the pipeline Name (historical rows predate // titles). It is the single definition shared by the CLI and TUI. func (r RunSummary) Label() string { if title := strings.TrimSpace(r.Title); title != "" { return title } return r.Name } type RunStep struct { Control *ControlEvidence `json:"control,omitempty"` FileChanges *StageFileChanges `json:"file_changes,omitempty"` Verdict *StageVerdict `json:"verdict,omitempty"` SessionExport *SessionExport `json:"session_export,omitempty"` SessionExportRepairs []*SessionExport `json:"session_export_repairs,omitempty"` SessionExportRecovery *SessionExportRecovery `json:"session_export_recovery,omitempty"` Usage *StageUsage `json:"usage,omitempty"` Notifications []NotificationReceipt `json:"notifications,omitempty"` Artifacts []StageArtifact `json:"artifacts,omitempty"` Sequence int `json:"sequence"` Stage string `json:"stage"` Status string `json:"status"` Outcome string `json:"outcome"` Target string `json:"target"` Input map[string]any `json:"input"` Output map[string]any `json:"output"` Diagnostic string `json:"diagnostic"` SessionID string `json:"session_id"` AgentActive bool `json:"agent_active"` Transcript string `json:"transcript"` // Provider and Model are the effective provider/model this visit actually ran // with, recorded for every model stage (including failures). They are empty // for non-model stages and historical steps. Provider string `json:"provider,omitempty"` Model string `json:"model,omitempty"` // ArtifactsSkipped and ArtifactsTruncated count files excluded from the // bounded per-step scan (over the file/size cap) and by the total budget. ArtifactsSkipped int `json:"artifacts_skipped,omitempty"` ArtifactsTruncated int `json:"artifacts_truncated,omitempty"` StartedAt string `json:"started_at"` FinishedAt string `json:"finished_at"` } // StageArtifact is one file a stage left in its artifacts directory. It is // observed server-side evidence, not a model's claim. An empty Artifacts slice // means no files were recorded (including historical steps). type StageArtifact struct { Name string `json:"name"` SizeBytes int64 `json:"size_bytes"` ContentType string `json:"content_type"` URL string `json:"url"` // Group is the server's presentation classification (ArtifactGroupDeliverable // or ArtifactGroupDebug, see ClassifyArtifacts). Every listing the server // returns sets it; an older server omits it, so clients keep a filename // fallback. Group string `json:"group,omitempty"` } // LegacySessionMarkdownArtifact is the retired markdown session export file name. // Nothing writes it any more, but a run recorded before the HTML-only change // still lists session.md among its stored artifacts: it is dated evidence that is // never presented, so every listing hides it rather than showing it beside the // session html. This is the one definition of the retired name, shared by the // stage export and the clients. const LegacySessionMarkdownArtifact = "session.md" // PresentedArtifacts is one step's recorded artifacts as they are presented: the // files with the retired markdown session export filtered out. It is the single // rule every Go artifact listing derives from, so a stage's artifacts never show // a session markdown beside the session html and a recorded count can never // disagree with the tiles. It never mutates the step and returns nil when nothing // is presented; the stored record still carries the legacy file. Pure, // O(artifacts) per step. func (s RunStep) PresentedArtifacts() []StageArtifact { if len(s.Artifacts) == 0 { return nil } presented := make([]StageArtifact, 0, len(s.Artifacts)) for _, artifact := range s.Artifacts { if artifact.Name == LegacySessionMarkdownArtifact { continue } presented = append(presented, artifact) } if len(presented) == 0 { return nil } return presented } // StageUsage is the usage one model stage actually reported, carried from the // stage's already-measured budget accounting rather than a second measurement or // a transcript parse. TokensTotal/TokensKnown are the reported total; TokensIn // and TokensOut are set only when the harness reported the input/output split // (SplitKnown), so a harness that reports only a total (Pi) never has its total // presented as input tokens. CostUSD is present only when CostKnown: a stage // whose provider reported no cost carries CostKnown=false and no fabricated or // zero cost. type StageUsage struct { TokensIn int64 `json:"tokens_in,omitempty"` TokensOut int64 `json:"tokens_out,omitempty"` TokensTotal int64 `json:"tokens_total"` TokensKnown bool `json:"tokens_known"` SplitKnown bool `json:"split_known,omitempty"` CostUSD float64 `json:"cost_usd,omitempty"` CostKnown bool `json:"cost_known"` // TokensReasoning, CacheRead and CacheWrite are the remaining components of // a split report (TokensTotal = in + out + reasoning + cache read + cache // write). They are recorded only when CacheKnown; a row stored before they // were kept has CacheKnown=false, so its absent counts are unknown, not zero. TokensReasoning int64 `json:"tokens_reasoning,omitempty"` CacheRead int64 `json:"cache_read,omitempty"` CacheWrite int64 `json:"cache_write,omitempty"` CacheKnown bool `json:"cache_known,omitempty"` } // RunUsage is the totalled reported usage of a run's model stages. It is summed // in one pass over the run's already-loaded steps, so reading it adds no query. // A stage that reported no cost is counted in CostUnknownStages and contributes // no cost; a stage that reported only a total contributes to TokensTotal but not // to the in/out split, and SplitKnown is true only when every stage that // reported tokens also reported the split. type RunUsage struct { TokensTotal int64 `json:"tokens_total"` TokensIn int64 `json:"tokens_in,omitempty"` TokensOut int64 `json:"tokens_out,omitempty"` SplitKnown bool `json:"split_known"` CostUSD float64 `json:"cost_usd,omitempty"` Stages int `json:"stages"` TokensKnownStages int `json:"tokens_known_stages"` SplitUnknownStages int `json:"split_unknown_stages,omitempty"` CostKnownStages int `json:"cost_known_stages"` CostUnknownStages int `json:"cost_unknown_stages,omitempty"` // TokensReasoning, CacheRead and CacheWrite sum the stages that recorded the // component split (CacheKnownStages). CacheKnown is true only when every // token-reporting stage did, so fresh (total minus cache read) versus cached // is never presented from a partial split. TokensReasoning int64 `json:"tokens_reasoning,omitempty"` CacheRead int64 `json:"cache_read,omitempty"` CacheWrite int64 `json:"cache_write,omitempty"` CacheKnown bool `json:"cache_known,omitempty"` CacheKnownStages int `json:"cache_known_stages,omitempty"` } // RunWarnings derives the run-level warnings from its steps: every visit whose // retained file-change capture was partial or unavailable is named, because // such evidence is not a complete workspace diff and must never be read as "no // edits". Steps with no capture (historical, human or server-skip visits) are // not flagged here; their File changes section already says "not recorded". func RunWarnings(steps []RunStep) []string { var visits []string for _, step := range steps { if step.FileChanges == nil || step.FileChanges.Status == "complete" { continue } visits = append(visits, fmt.Sprintf("%s #%d (%s)", step.Stage, step.Sequence, step.FileChanges.Status)) } if len(visits) == 0 { return nil } const shown = 8 list := visits extra := "" if len(list) > shown { extra = fmt.Sprintf(" and %d more", len(list)-shown) list = list[:shown] } return []string{fmt.Sprintf("File-change capture was incomplete for %d visit(s): %s%s. Recorded file changes are not a complete workspace diff, and no stage is auto-skipped after such a visit.", len(visits), strings.Join(list, ", "), extra)} } // TotalUsage sums the per-stage usage of a run's steps into one run total. It is // the one definition of the run total, so per-run inspection cannot drift from // the history-wide aggregate over the same rows. func TotalUsage(steps []RunStep) *RunUsage { total := &RunUsage{} splitComplete := true for i := range steps { usage := steps[i].Usage if usage == nil { continue } total.Stages++ if usage.TokensKnown { total.TokensKnownStages++ total.TokensTotal += usage.TokensTotal if usage.SplitKnown { total.TokensIn += usage.TokensIn total.TokensOut += usage.TokensOut } else { splitComplete = false total.SplitUnknownStages++ } if usage.CacheKnown { total.CacheKnownStages++ total.TokensReasoning += usage.TokensReasoning total.CacheRead += usage.CacheRead total.CacheWrite += usage.CacheWrite } } if usage.CostKnown { total.CostKnownStages++ total.CostUSD += usage.CostUSD } else { total.CostUnknownStages++ } } if total.Stages == 0 { return nil } total.SplitKnown = total.TokensKnownStages > 0 && splitComplete total.CacheKnown = total.TokensKnownStages > 0 && total.CacheKnownStages == total.TokensKnownStages return total } type MemoryRead struct { Source string `json:"source"` Sequence int `json:"sequence"` // zero denotes original run input } type ControlEvidence struct { Visit int `json:"visit"` MaxVisits int `json:"max_visits"` LimitReached bool `json:"limit_reached,omitempty"` ModelTarget string `json:"model_target,omitempty"` Memory map[string]MemoryRead `json:"memory,omitempty"` } // StageFileChanges is observed workspace evidence, not a model's claim of authorship. // Nil means no capture was retained (including historical steps). type StageFileChanges struct { Omitted int `json:"omitted,omitempty"` Scope string `json:"scope,omitempty"` Status string `json:"status"` // complete, partial, unavailable Files []FileChange `json:"files"` Skipped int `json:"skipped"` Diagnostic string `json:"diagnostic,omitempty"` } type FileChange struct { Path string `json:"path"` Kind string `json:"kind"` // added, modified, deleted Patch string `json:"patch,omitempty"` Binary bool `json:"binary,omitempty"` Truncated bool `json:"truncated,omitempty"` // NoPatch marks a change listed without any patch: the content exceeded the // capture budget (compared by hash) or the change was seen only in Git // status. Truncated is also set so older readers show "patch omitted". NoPatch bool `json:"no_patch,omitempty"` // NoPatchReason says why a content change has no (complete) patch: // "binary", "file_size" (text over 1 MiB), "budget" (snapshot text budget), // "lines" (over 5,000 combined lines), "evidence_size" (per-visit retained // evidence limit), "git_status" (seen only in Git status) or "baseline" // (stage-start content unrecoverable). Empty when a patch was recorded. NoPatchReason string `json:"no_patch_reason,omitempty"` BeforeMode string `json:"before_mode,omitempty"` AfterMode string `json:"after_mode,omitempty"` } type NotificationReceipt struct { Destination string `json:"destination"` Status string `json:"status"` Filename string `json:"filename,omitempty"` MessageID string `json:"message_id,omitempty"` AttachmentURL string `json:"attachment_url,omitempty"` Diagnostic string `json:"diagnostic,omitempty"` } type RunDetail struct { RunSummary Notifications []RunNotificationReceipt `json:"notifications,omitempty"` Graph Graph `json:"graph"` RetryOf int64 `json:"retry_of,omitempty"` RetryMode string `json:"retry_mode,omitempty"` RetrySource int64 `json:"retry_source,omitempty"` RetrySourceVersion int `json:"retry_source_version,omitempty"` RetrySourceHash string `json:"retry_source_hash,omitempty"` Workspace string `json:"workspace"` AllowTools bool `json:"allow_tools"` WritePaths []string `json:"write_paths"` Input map[string]any `json:"input"` Output map[string]any `json:"output"` Steps []RunStep `json:"steps"` // Warnings are run-level, read-time notes an operator should see before // trusting the evidence, e.g. that a visit's file-change capture was partial. // Derived from Steps by RunWarnings; absent when there is nothing to flag. Warnings []string `json:"warnings,omitempty"` // TitleSource is "model" when Title came from the shared summariser or // "fallback" when it was derived from the prompt; TitleModel names the model // that produced a model title. They are retained so a diagnosis can tell the // two apart and see which model was used. TitleSource string `json:"title_source,omitempty"` TitleModel string `json:"title_model,omitempty"` // Environment records the workspace's own environment (direnv/mise) the // run's stages, stage services and checks ran with: files and variable // names only, never values. Absent for runs that predate it. Environment *RunEnvironment `json:"environment,omitempty"` } // RunEnvironment is the directory environment a run resolved for its // workspace. It never carries a variable's value. type RunEnvironment struct { Directory string `json:"directory"` Files []string `json:"files,omitempty"` Sources []string `json:"sources,omitempty"` Set []string `json:"set,omitempty"` Unset []string `json:"unset,omitempty"` // Dropped are inherited server credentials removed because the directory // chooses the Claude account (for example it sets CLAUDE_CONFIG_DIR). Dropped []string `json:"dropped,omitempty"` Warnings []string `json:"warnings,omitempty"` // ServiceKey names the OpenCode stage service environment; empty when the // directory changes nothing. ServiceKey string `json:"service_key,omitempty"` ResolvedAt string `json:"resolved_at,omitempty"` } // RunNotificationReceipt records publisher attempts, not device reception. type RunNotificationReceipt struct { Sequence int `json:"sequence"` Event string `json:"event"` Channel string `json:"channel"` Status string `json:"status"` Attempts int `json:"attempts"` Diagnostic string `json:"diagnostic,omitempty"` MessageID string `json:"message_id,omitempty"` }