Documentation
¶
Overview ¶
Package agents holds what the coding agents the runtime drives (Claude Code in internal/agents/claude, Codex in internal/agents/codex) have in common: the session a pane runs, the work-state events their hooks translate to, the snapshot of a transcript's tail, the stats of a finished turn, and the pieces of a launch line.
Index ¶
- Constants
- Variables
- func ANSICQuote(s string) string
- func ArgvNames(argv []string, word string) bool
- func AsStr(v any) string
- func BareAgentArgs(content, panelType string) (string, bool)
- func CheckLaunch(l *Launch) error
- func Decode(data []byte) (any, error)
- func DisplayName(provider string) string
- func FormatStartEnv(env []EnvVar, keyPrefix string) (string, error)
- func InitialPromptText(prompt string) string
- func IsKnownEffort(e string) bool
- func IsUUID(s string) bool
- func JSString(v any) string
- func Lines(b []byte) [][]byte
- func MillisSince(now, t time.Time) float64
- func NotificationNeedsInput(notificationType string) bool
- func PanelOf(provider string) string
- func PromptFromFile(file string) string
- func ProviderOfPanel(panelType string) string
- func ReadTail(f *os.File, size, n int64) ([]byte, error)
- func ResolvePromptFiles(provider string, files []string, dataDir, dataDirDisplay string) ([]string, error)
- func SessionIDFromTranscript(jsonlPath string) string
- func ShellQuote(s string) string
- func Stringify(v any) string
- func Truthy(v any) bool
- func WithInitialPrompt(provider, command, prompt, promptFile string) string
- func WriteLongPrompt(dir, text string) (string, error)
- type AgentState
- type Counts
- type CurrentAction
- type EnvVar
- type Event
- type EventKind
- type HistoryEntry
- type HistoryStats
- type LRU
- type Launch
- type Match
- type Obj
- type Recovered
- type RecoveryDeps
- type SessionInfo
- type SessionStatus
- type Snapshot
- type TabAgent
- type TabReader
- type Unavailable
Constants ¶
const ( Claude = "claude" Codex = "codex" ClaudePanel = "claude-code" CodexPanel = "codex-cli" )
Provider ids and panel types.
const ( // MaxInitialPrompt caps an initial prompt, in UTF-16 units. MaxInitialPrompt = 20_000 // InlinePromptMax: a longer prompt is not typed into the shell (a 16 KB typed line stalled zsh) but read from a file. InlinePromptMax = 2_000 )
const StartEnvLimit = 8
StartEnvLimit is the most entries a launch's environment prefix may have.
const StartPromptFilesLimit = 4
StartPromptFilesLimit is the most instruction files a launch may add.
Variables ¶
var ( ErrLaunchModel = errors.New("Invalid launch model") ErrLaunchEffort = errors.New("Invalid launch effort") )
var Efforts = []string{"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra", "ultracode"}
Efforts are every reasoning level the CLIs know, weakest first.
var HookEventKinds = []EventKind{SessionStart, PromptSubmit, Notification, Stop, StopFailure, Interrupt, PreCompact, PostCompact}
HookEventKinds are the events a hook may name: the state machine maps session-start → idle, prompt-submit → busy, notification → needs-input (when NotificationNeedsInput), stop and stop-failure → ready-for-review, interrupt → idle, the compact pair → the compacting flag only.
var ModelIDRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}(\[1m\])?$`)
ModelIDRe: a model id is typed into a shell, so it stays this strict (aliases, full ids, the [1m] suffix).
Functions ¶
func ANSICQuote ¶
ANSICQuote quotes s as $'…' so a multi-line prompt stays on one typed line (bash and zsh read it).
func ArgvNames ¶
ArgvNames tells whether word is in the program's file name or the interpreted script's path.
func AsStr ¶
AsStr is v when it is a string, else "" (JavaScript's `typeof v === 'string' ? v : ”`).
func BareAgentArgs ¶
BareAgentArgs: text sent to an agent tab that is a bare `claude …` (`codex …`) for the tab's own agent is replaced by the platform's launch line plus these arguments. False when the text is not such a command.
func CheckLaunch ¶
CheckLaunch re-checks a stored choice right before it becomes shell text: a bad value stops the launch.
func Decode ¶
Decode parses one JSON text as JSON.parse does (whitespace around it allowed, nothing else), objects as *Obj, numbers as float64.
func DisplayName ¶
DisplayName is how the platform names an agent CLI.
func FormatStartEnv ¶
FormatStartEnv renders `KEY='value' ` per entry, in order. Keys must be keyPrefix followed by 1-40 of [A-Z_]; values need no quoting. The error is the message for the caller (a 400).
func InitialPromptText ¶
InitialPromptText is the prompt as it is passed: trimmed and capped.
func IsUUID ¶
IsUUID: session ids the CLIs accept for a resume (and the only ones typed into a shell).
func Lines ¶
Lines splits text read from a transcript into its non-blank lines (JavaScript's split('\n') kept where trim() leaves something); invalid UTF-8 reads as U+FFFD as Node's decoder makes it.
func MillisSince ¶
MillisSince is the age of t in milliseconds as Date.now() - mtimeMs counts it.
func NotificationNeedsInput ¶
NotificationNeedsInput: only a notification asking for permission (or one without a type) needs the person; the others (idle reminders, auth, elicitation…) change nothing.
func PromptFromFile ¶
PromptFromFile is the shell argument that reads a prompt file once and deletes it.
func ProviderOfPanel ¶
ProviderOfPanel is the agent a tab's panel type runs, "" for a panel that runs none (a terminal).
func ResolvePromptFiles ¶
func ResolvePromptFiles(provider string, files []string, dataDir, dataDirDisplay string) ([]string, error)
ResolvePromptFiles checks instruction files for a launch: Claude only, at most StartPromptFilesLimit, each an absolute path that resolves (symlinks followed) to a regular file inside dataDir. dataDirDisplay names dataDir in the messages (`~/.<name>`). The error is the message for the caller (a 400).
func SessionIDFromTranscript ¶
SessionIDFromTranscript is the session a Claude transcript belongs to: its file name, when that is a UUID. A tab that lost its stored id but kept its transcript path still knows its session.
func WithInitialPrompt ¶
WithInitialPrompt appends the initial prompt to a launch line: `-- <arg>` for Claude, `--prompt <arg>` for the Codex launcher. promptFile, when set, is where WriteLongPrompt put a long prompt.
func WriteLongPrompt ¶
WriteLongPrompt writes a prompt too long to type (over InlinePromptMax units of the text InitialPromptText gives) to a private file initial-<uuid>.txt in dir; "" when the prompt goes inline.
Types ¶
type AgentState ¶
type AgentState struct {
ProviderID string `json:"providerId"`
SessionID *string `json:"sessionId"`
JSONLPath *string `json:"jsonlPath"`
Summary *string `json:"summary"`
}
AgentState is the agent part of a layout tab (`tab.agentState`).
type Counts ¶
type Counts struct {
// contains filtered or unexported fields
}
Counts are counts by name, written in the order the names were first counted (JavaScript's object order).
func (Counts) MarshalJSON ¶
MarshalJSON writes {name: count} in order.
func (*Counts) UnmarshalJSON ¶
UnmarshalJSON reads {name: count}, keeping the order.
type CurrentAction ¶
CurrentAction is what the agent is doing now: a tool call (ToolName set) or the text it is writing.
func Tool ¶
func Tool(name, summary string) *CurrentAction
Tool is a current action for a tool call.
type EnvVar ¶
type EnvVar struct{ Key, Value string }
EnvVar is one entry of a launch's environment prefix.
type Event ¶
type Event struct {
Kind EventKind `json:"kind"`
// NotificationType of a notification, "" when the hook gave none.
NotificationType string `json:"notificationType,omitempty"`
// Summary of a summary-update (nil clears it); Message of a last-user-message.
Summary *string `json:"summary,omitempty"`
Message string `json:"message,omitempty"`
}
Event is one work-state event.
type EventKind ¶
type EventKind string
EventKind is a work-state event an agent's hooks (or the runtime's own watchers) report.
const ( SessionStart EventKind = "session-start" PromptSubmit EventKind = "prompt-submit" Notification EventKind = "notification" Stop EventKind = "stop" StopFailure EventKind = "stop-failure" Interrupt EventKind = "interrupt" PreCompact EventKind = "pre-compact" PostCompact EventKind = "post-compact" SummaryUpdate EventKind = "summary-update" LastUserMsg EventKind = "last-user-message" )
type HistoryEntry ¶
type HistoryEntry struct {
TabID string
ProviderID string
AgentSessionID *string
ClaudeSessionID *string
CompletedAt float64
}
HistoryEntry is the part of a session-history entry recovery reads.
type HistoryStats ¶
type HistoryStats struct {
ToolUsage Counts `json:"toolUsage"`
TouchedFiles []string `json:"touchedFiles"`
LastAssistantText *string `json:"lastAssistantText"`
LastUserText *string `json:"lastUserText"`
FirstUserTs *float64 `json:"firstUserTs"`
LastAssistantTs *float64 `json:"lastAssistantTs"`
TurnDurationMs *float64 `json:"turnDurationMs"`
}
HistoryStats is what a finished turn's transcript tail gives the session history.
func EmptyHistoryStats ¶
func EmptyHistoryStats() HistoryStats
EmptyHistoryStats is the stats of an unreadable or empty transcript.
type LRU ¶
LRU is a small cache keyed by path: insertion order is eviction order and a hit moves the entry to the end.
type Launch ¶
Launch is the model and reasoning effort a conversation starts with; nil means the CLI's own default ("Auto"). Same shape as catalog.Choice, so either converts to the other.
func ReadLaunchShape ¶
ReadLaunchShape reads a choice from request or stored values by shape only (model, effort as decoded from JSON). nil, true when both are absent; false when one is malformed.
type Match ¶
type Match int
Match is how a process is recognised as an agent's.
const ( // MatchSubstring: the agent's name anywhere in the command line, as the previous runtime did. `vim CLAUDE.md` does // not match (case), but `less ~/.claude/x` or a shell the agent started under ~/.claude does. MatchSubstring Match = iota // MatchArgv: the agent's name in the program's file name, or, for an interpreter (node, python…), in the script's // path. Covers the CLIs, their versioned binaries, an npm install's cli.js, a launcher script and `exec -a claude`; // a file argument of another program (an editor, a pager, a shell's script) does not count. MatchArgv )
type Obj ¶
type Obj struct {
// contains filtered or unexported fields
}
Obj is a JSON object that remembers the order its keys came in: a transcript line's tool input is summarised by its first key, and counts keyed by tool name are written in the order the tools were met, as JavaScript does.
func (*Obj) Keys ¶
Keys are the keys in JavaScript's order: array indices ascending, then the rest as they came.
func (*Obj) MarshalJSON ¶
MarshalJSON writes the object in its key order.
type Recovered ¶
Recovered is a session found for a tab.
func RecoverTabSession ¶
func RecoverTabSession(t TabAgent, p TabReader, deps RecoveryDeps) *Recovered
RecoverTabSession is the session a tab stands for, from the first source with a transcript on disk: the transcript path the tab kept (its file name is the id), the session id it kept, the newest session of its own history. Nil when the tab never had one; an unreadable history is not an error.
type RecoveryDeps ¶
type RecoveryDeps struct {
Exists func(path string) bool
// FindTranscript is a session's transcript in whatever project folder holds it, "" when none.
FindTranscript func(sessionID string) string
History func() ([]HistoryEntry, error)
}
RecoveryDeps is what recovery looks at on disk.
type SessionInfo ¶
type SessionInfo struct {
Status SessionStatus
// SessionID is the conversation's id, "" when not known.
SessionID string
// RawSessionID is the id exactly as the agent recorded it (a JSON value, a string in practice); nil when none.
RawSessionID any
// JSONLPath is the transcript, "" when it is not on disk (yet).
JSONLPath string
PID int
// StartedAt is the session's start in epoch milliseconds, when the agent recorded it.
StartedAt *float64
Cwd string
}
SessionInfo is the agent session a pane runs.
func (SessionInfo) MarshalJSON ¶
func (s SessionInfo) MarshalJSON() ([]byte, error)
MarshalJSON writes the session as the timeline reads it: {status, sessionId, jsonlPath, pid, startedAt, cwd}.
type SessionStatus ¶
type SessionStatus string
SessionStatus is what detection found in a pane.
const ( Running SessionStatus = "running" NotRunning SessionStatus = "not-running" NotInstalled SessionStatus = "not-installed" NotInitialized SessionStatus = "not-initialized" )
type Snapshot ¶
type Snapshot struct {
// Idle: the turn is over (or the agent has been quiet for longer than StaleMs while waiting).
Idle bool `json:"idle"`
// Stale: the last entry leaves the turn open, so Idle is a guess from the file's age.
Stale bool `json:"stale"`
LastAssistantSnippet *string `json:"lastAssistantSnippet"`
CurrentAction *CurrentAction `json:"currentAction"`
// Reset: a prompt is newer than the last answer, so the answer shown belongs to an older turn.
Reset bool `json:"reset"`
// LastEntryTs is the deciding (Claude) or newest (Codex) entry's time in epoch ms.
LastEntryTs *float64 `json:"lastEntryTs"`
StaleMs int64 `json:"staleMs"`
Interrupted bool `json:"interrupted"`
}
Snapshot is what the tail of a transcript says about the agent's turn.
type TabAgent ¶
type TabAgent struct {
ID string
AgentState *AgentState
ClaudeSessionID *string
ClaudeJSONLPath *string
ClaudeSummary *string
}
TabAgent is what a layout tab holds about its agent: the provider-neutral state and the fields older layouts kept for Claude.
type TabReader ¶
type TabReader interface {
ProviderID() string
ReadSessionID(t TabAgent) string
ReadJSONLPath(t TabAgent) string
}
TabReader reads a tab's stored session the way one provider does.
type Unavailable ¶
type Unavailable struct {
Unavailable is why an agent CLI cannot start (answered with 409).
Directories
¶
| Path | Synopsis |
|---|---|
|
Package claude is the runtime's side of Claude Code: whether it runs in a pane and which conversation, what its transcript says about the turn, what its hooks mean, and the command line that starts or resumes it.
|
Package claude is the runtime's side of Claude Code: whether it runs in a pane and which conversation, what its transcript says about the turn, what its hooks mean, and the command line that starts or resumes it. |
|
Package codex is the runtime's side of the OpenAI Codex CLI: whether it runs in a pane and which session, what its rollout transcript says about the turn, what its hook payloads mean, and the launcher line and arguments that start or resume it.
|
Package codex is the runtime's side of the OpenAI Codex CLI: whether it runs in a pane and which session, what its rollout transcript says about the turn, what its hook payloads mean, and the launcher line and arguments that start or resume it. |