Documentation
¶
Overview ¶
Package opencode implements the Agent interface for OpenCode.
Index ¶
- Constants
- Variables
- func ExtractAllUserPrompts(data []byte) ([]string, error)
- func ExtractModifiedFiles(data []byte) ([]string, error)
- func ExtractTextFromParts(parts []Part) string
- func NewOpenCodeAgent() agent.Agent
- func OnlySyntheticText(parts []Part) bool
- func SanitizePathForOpenCode(path string) string
- func SliceFromMessage(data []byte, startMessageIndex int) ([]byte, error)
- type Cache
- type ExportMessage
- type ExportSession
- type MessageInfo
- type OpenCodeAgent
- func (a *OpenCodeAgent) AreHooksInstalled(ctx context.Context) (bool, error)
- func (a *OpenCodeAgent) CalculateTokenUsage(transcriptData []byte, fromOffset int) (*agent.TokenUsage, error)
- func (a *OpenCodeAgent) CheckHookConfig(ctx context.Context) agent.HookConfigState
- func (a *OpenCodeAgent) ChunkTranscript(_ context.Context, content []byte, maxSize int) ([][]byte, error)
- func (a *OpenCodeAgent) Description() string
- func (a *OpenCodeAgent) DetectPresence(ctx context.Context) (bool, error)
- func (a *OpenCodeAgent) ExtractModifiedFilesFromOffset(_ context.Context, path string, startOffset int) ([]string, int, error)
- func (a *OpenCodeAgent) ExtractPrompts(sessionRef string, fromOffset int) ([]string, error)
- func (a *OpenCodeAgent) FetchSubagentTranscript(ctx context.Context, agentID, toolUseID string, ...) (string, error)
- func (a *OpenCodeAgent) FetchTranscript(ctx context.Context, sessionID string) (string, error)
- func (a *OpenCodeAgent) FormatResumeCommand(sessionID string) string
- func (a *OpenCodeAgent) GenerateText(ctx context.Context, prompt, model string) (string, error)
- func (a *OpenCodeAgent) GetSessionDir(repoPath string) (string, error)
- func (a *OpenCodeAgent) GetSessionID(input *agent.HookInput) string
- func (a *OpenCodeAgent) GetTranscriptPosition(path string) (int, error)
- func (a *OpenCodeAgent) HookConfigRelPath() string
- func (a *OpenCodeAgent) HookNames() []string
- func (a *OpenCodeAgent) InjectionEvent() agent.EventType
- func (a *OpenCodeAgent) InstallHooks(ctx context.Context, force bool) (int, error)
- func (a *OpenCodeAgent) LiveSubagentModifiedFiles(ctx context.Context, childID, _ string, since time.Time) ([]string, error)
- func (a *OpenCodeAgent) Name() types.AgentName
- func (a *OpenCodeAgent) NewUsageCounter() agent.UsageCounter
- func (a *OpenCodeAgent) ParseHookEvent(ctx context.Context, hookName string, stdin io.Reader) (*agent.Event, error)
- func (a *OpenCodeAgent) PrepareTranscript(ctx context.Context, sessionRef string) error
- func (a *OpenCodeAgent) ProtectedDirs() []string
- func (a *OpenCodeAgent) ProtectedFiles() []string
- func (a *OpenCodeAgent) ReadSession(input *agent.HookInput) (*agent.AgentSession, error)
- func (a *OpenCodeAgent) ReadTranscript(sessionRef string) ([]byte, error)
- func (a *OpenCodeAgent) ReassembleTranscript(chunks [][]byte) ([]byte, error)
- func (a *OpenCodeAgent) RenderContextInjection(inj agent.ContextInjection) ([]byte, error)
- func (a *OpenCodeAgent) ResolveSessionFile(sessionDir, agentSessionID string) string
- func (a *OpenCodeAgent) SubagentUsageOutsideParent()
- func (a *OpenCodeAgent) Type() types.AgentType
- func (a *OpenCodeAgent) UninstallHooks(ctx context.Context) error
- func (a *OpenCodeAgent) WriteSession(ctx context.Context, session *agent.AgentSession) error
- type Part
- type SessionInfo
- type Time
- type Tokens
- type ToolFileInfo
- type ToolState
- type ToolStateMetadata
Constants ¶
const ( HookNameSessionStart = "session-start" HookNameSessionEnd = "session-end" HookNameTurnStart = "turn-start" HookNameTurnEnd = "turn-end" HookNameCompaction = "compaction" HookNameSubagentStart = "subagent-start" HookNameSubagentStop = "subagent-stop" )
Hook name constants — these become CLI subcommands under `entire hooks opencode`.
Variables ¶
var FileModificationTools = []string{
"edit",
"write",
"apply_patch",
}
FileModificationTools are tools in OpenCode that modify files on disk. These match the actual tool names from OpenCode's source (packages/opencode/src/tool/):
- edit: edit.ts — exact string replacement in existing files
- write: write.ts — create or overwrite files
- apply_patch: apply_patch.ts — unified diff patches (used by gpt-* models except gpt-4)
Tool selection is mutually exclusive: apply_patch is enabled for gpt-* (non-gpt-4, non-oss) models; edit+write are enabled for all other models (Claude, Gemini, gpt-4, etc.). The batch tool (experimental) creates separate transcript parts per sub-call, so its children are already captured by this list.
Functions ¶
func ExtractAllUserPrompts ¶
ExtractAllUserPrompts extracts all user prompts from raw export JSON transcript bytes. This is a package-level function used by the condensation path. Messages that consist entirely of <system-reminder> tags (e.g. from oh-my-opencode) are excluded. Mixed messages have their system-reminder sections stripped.
func ExtractModifiedFiles ¶
ExtractModifiedFiles extracts modified file paths from raw export JSON transcript bytes. This is the bytes-based equivalent of ExtractModifiedFilesFromOffset, used by ReadSession.
func ExtractTextFromParts ¶
ExtractTextFromParts extracts text content from message parts.
func NewOpenCodeAgent ¶
NewOpenCodeAgent creates a new OpenCode agent instance.
func OnlySyntheticText ¶ added in v0.11.6
OnlySyntheticText reports whether every text part is synthetic: a user message OpenCode wrote itself (a background task's `<task … state=…>` result), not a prompt. A real prompt carrying synthetic attachment text alongside the user's own words is kept.
func SanitizePathForOpenCode ¶
SanitizePathForOpenCode converts a path to a safe directory name. Replaces any non-alphanumeric character with a dash (same approach as Claude).
func SliceFromMessage ¶
SliceFromMessage returns an OpenCode export transcript scoped to messages starting from startMessageIndex. This is the OpenCode equivalent of transcript.SliceFromLine — for OpenCode's JSON format, scoping is done by message index rather than line offset. Returns the original data if startMessageIndex <= 0. Returns nil, nil if startMessageIndex exceeds the number of messages.
Types ¶
type ExportMessage ¶
type ExportMessage struct {
Info MessageInfo `json:"info"`
Parts []Part `json:"parts"`
}
ExportMessage represents a single message in the export format. Each message contains info (metadata) and parts (content).
type ExportSession ¶
type ExportSession struct {
Info SessionInfo `json:"info"`
Messages []ExportMessage `json:"messages"`
}
ExportSession represents the top-level structure of `opencode export` output. This is OpenCode's native format for session data.
func ParseExportSession ¶
func ParseExportSession(data []byte) (*ExportSession, error)
ParseExportSession parses export JSON content into an ExportSession structure.
type MessageInfo ¶
type MessageInfo struct {
ID string `json:"id"`
SessionID string `json:"sessionID,omitempty"`
Role string `json:"role"` // "user" or "assistant"
Time Time `json:"time"`
Tokens *Tokens `json:"tokens,omitempty"`
Cost float64 `json:"cost,omitempty"`
}
MessageInfo contains message metadata.
type OpenCodeAgent ¶
type OpenCodeAgent struct {
// CommandRunner overrides text-generation subprocess creation when non-nil.
CommandRunner agent.TextCommandRunner
}
func (*OpenCodeAgent) AreHooksInstalled ¶
func (a *OpenCodeAgent) AreHooksInstalled(ctx context.Context) (bool, error)
AreHooksInstalled checks if the Entire plugin file exists and contains the marker.
A missing config file is an answer, not a failure: that file is where the state lives, so its absence means no hooks. Anything that stops us reading the answer — an unreadable file, malformed config — is returned as an error, since "we could not tell" and "there are none" are different things to a caller deciding whether hooks can be left alone.
func (*OpenCodeAgent) CalculateTokenUsage ¶
func (a *OpenCodeAgent) CalculateTokenUsage(transcriptData []byte, fromOffset int) (*agent.TokenUsage, error)
CalculateTokenUsage computes token usage from assistant messages starting at the given offset.
func (*OpenCodeAgent) CheckHookConfig ¶ added in v0.10.0
func (a *OpenCodeAgent) CheckHookConfig(ctx context.Context) agent.HookConfigState
CheckHookConfig reports whether the installed plugin matches what InstallHooks would write today. Read-only diagnostic for `entire status` and `entire doctor`; same committed-and-stale exposure as Pi's extension, since .opencode/plugin/entire.ts is likewise a generated file repos commit so every clone is covered.
func (*OpenCodeAgent) ChunkTranscript ¶
func (a *OpenCodeAgent) ChunkTranscript(_ context.Context, content []byte, maxSize int) ([][]byte, error)
ChunkTranscript splits an OpenCode export JSON transcript by distributing messages across chunks. OpenCode uses JSON format with {"info": {...}, "messages": [...]} structure. Info and messages are carried as raw JSON, so fields the typed export structs do not model (such as the OpenCode 2 originals resume imports) survive.
func (*OpenCodeAgent) Description ¶
func (a *OpenCodeAgent) Description() string
func (*OpenCodeAgent) DetectPresence ¶
func (a *OpenCodeAgent) DetectPresence(ctx context.Context) (bool, error)
func (*OpenCodeAgent) ExtractModifiedFilesFromOffset ¶
func (a *OpenCodeAgent) ExtractModifiedFilesFromOffset(_ context.Context, path string, startOffset int) ([]string, int, error)
ExtractModifiedFilesFromOffset extracts files modified by tool calls from the given message offset.
func (*OpenCodeAgent) ExtractPrompts ¶
func (a *OpenCodeAgent) ExtractPrompts(sessionRef string, fromOffset int) ([]string, error)
ExtractPrompts extracts user prompts from an OpenCode export transcript starting at the given message offset.
func (*OpenCodeAgent) FetchSubagentTranscript ¶ added in v0.11.6
func (a *OpenCodeAgent) FetchSubagentTranscript(ctx context.Context, agentID, toolUseID string, startedAt, completedAt time.Time) (string, error)
FetchSubagentTranscript exports a task record's child session, scoped to that call like the stop hook's export. The record's AgentID is the child session ID, which `opencode export` accepts directly.
func (*OpenCodeAgent) FetchTranscript ¶ added in v0.10.3
FetchTranscript materializes the session's transcript via `opencode export` and returns the cached path. Unlike PrepareTranscript (which only refreshes an existing file), this works for sessions Entire never tracked — e.g. sessions spawned by an external host, where no hook ever cached an export.
func (*OpenCodeAgent) FormatResumeCommand ¶
func (a *OpenCodeAgent) FormatResumeCommand(sessionID string) string
func (*OpenCodeAgent) GenerateText ¶ added in v0.11.0
GenerateText runs OpenCode without repository context or tool access. An empty model preserves OpenCode's own default; explicit models use provider/model IDs.
func (*OpenCodeAgent) GetSessionDir ¶
func (a *OpenCodeAgent) GetSessionDir(repoPath string) (string, error)
GetSessionDir returns the directory where Entire stores OpenCode session transcripts. Transcripts are ephemeral handoff files between the TS plugin and the Go hook handler. Once checkpointed, the data lives on git refs and the file is disposable. Stored in os.TempDir()/entire-opencode/<sanitized-path>/ to avoid squatting on OpenCode's own directories (~/.opencode/ is project-level, not home-level).
func (*OpenCodeAgent) GetSessionID ¶
func (a *OpenCodeAgent) GetSessionID(input *agent.HookInput) string
func (*OpenCodeAgent) GetTranscriptPosition ¶
func (a *OpenCodeAgent) GetTranscriptPosition(path string) (int, error)
GetTranscriptPosition returns the number of messages in the transcript.
func (*OpenCodeAgent) HookConfigRelPath ¶ added in v0.10.6
func (a *OpenCodeAgent) HookConfigRelPath() string
HookConfigRelPath implements agent.HookConfigLocator.
func (*OpenCodeAgent) HookNames ¶
func (a *OpenCodeAgent) HookNames() []string
HookNames returns the hook verbs this agent supports.
func (*OpenCodeAgent) InjectionEvent ¶ added in v0.7.7
func (a *OpenCodeAgent) InjectionEvent() agent.EventType
InjectionEvent reports that OpenCode injects model context at TurnStart. The embedded plugin reads the turn-start hook's stdout and applies the injection via experimental.chat.system.transform.
func (*OpenCodeAgent) InstallHooks ¶
InstallHooks writes the Entire plugin file to .opencode/plugin/entire.ts, moving it from .opencode/plugins if an earlier CLI wrote it there. Returns 1 if anything changed, 0 if already up-to-date (idempotent). If the file exists but content differs (e.g., an older render), it is rewritten.
func (*OpenCodeAgent) LiveSubagentModifiedFiles ¶ added in v0.12.0
func (a *OpenCodeAgent) LiveSubagentModifiedFiles(ctx context.Context, childID, _ string, since time.Time) ([]string, error)
LiveSubagentModifiedFiles exports a running child to a private staging file and returns the files its task call has modified so far. Unlike exportSubagent it writes neither the shared export cache nor the call's declared file: the call may stop while this export runs, and its stop writes the complete transcript to those names.
func (*OpenCodeAgent) Name ¶
func (a *OpenCodeAgent) Name() types.AgentName
func (*OpenCodeAgent) NewUsageCounter ¶ added in v0.13.2
func (a *OpenCodeAgent) NewUsageCounter() agent.UsageCounter
NewUsageCounter sums every assistant message's tokens in the session export, which OpenCode rewrites rather than appends, so it is read whole. OutputTokens includes reasoning once (see OutputWithReasoning). A message still in flight carries all-zero tokens (OpenCode fills them at step finish, after the step's tools run); it counts as a call with no tokens until a later read sees the final values. Child sessions are top-level sessions of their own, so there are no children.
func (*OpenCodeAgent) ParseHookEvent ¶
func (a *OpenCodeAgent) ParseHookEvent(ctx context.Context, hookName string, stdin io.Reader) (*agent.Event, error)
ParseHookEvent translates OpenCode hook calls into normalized lifecycle events.
func (*OpenCodeAgent) PrepareTranscript ¶
func (a *OpenCodeAgent) PrepareTranscript(ctx context.Context, sessionRef string) error
PrepareTranscript ensures the OpenCode transcript file is up-to-date by calling `opencode export`. OpenCode's transcript is created/updated via `opencode export`, but condensation may need fresh data mid-turn (e.g., during mid-turn commits or resumed sessions where the cached file is stale). This method always refreshes the transcript to ensure the latest agent activity is captured.
func (*OpenCodeAgent) ProtectedDirs ¶
func (a *OpenCodeAgent) ProtectedDirs() []string
func (*OpenCodeAgent) ProtectedFiles ¶ added in v0.5.6
func (a *OpenCodeAgent) ProtectedFiles() []string
func (*OpenCodeAgent) ReadSession ¶
func (a *OpenCodeAgent) ReadSession(input *agent.HookInput) (*agent.AgentSession, error)
func (*OpenCodeAgent) ReadTranscript ¶
func (a *OpenCodeAgent) ReadTranscript(sessionRef string) ([]byte, error)
ReadTranscript reads the transcript for a session. The sessionRef is expected to be a path to the export JSON file.
func (*OpenCodeAgent) ReassembleTranscript ¶
func (a *OpenCodeAgent) ReassembleTranscript(chunks [][]byte) ([]byte, error)
ReassembleTranscript merges OpenCode export JSON chunks by combining their message arrays.
func (*OpenCodeAgent) RenderContextInjection ¶ added in v0.7.7
func (a *OpenCodeAgent) RenderContextInjection(inj agent.ContextInjection) ([]byte, error)
RenderContextInjection emits a {"inject_context":"..."} envelope on stdout for the plugin to apply. Returns (nil, nil) for empty text.
func (*OpenCodeAgent) ResolveSessionFile ¶
func (a *OpenCodeAgent) ResolveSessionFile(sessionDir, agentSessionID string) string
func (*OpenCodeAgent) SubagentUsageOutsideParent ¶ added in v0.12.1
func (a *OpenCodeAgent) SubagentUsageOutsideParent()
SubagentUsageOutsideParent marks OpenCode as agent.ChildSessionSubagents: a task's child is a session of its own, and the parent's messages never include its usage.
func (*OpenCodeAgent) Type ¶
func (a *OpenCodeAgent) Type() types.AgentType
func (*OpenCodeAgent) UninstallHooks ¶
func (a *OpenCodeAgent) UninstallHooks(ctx context.Context) error
UninstallHooks removes the Entire plugin file, from the legacy directory too.
func (*OpenCodeAgent) WriteSession ¶
func (a *OpenCodeAgent) WriteSession(ctx context.Context, session *agent.AgentSession) error
type Part ¶
type Part struct {
ID string `json:"id,omitempty"` // Part ID (e.g., "prt_..."), added in OpenCode 1.2.x
Type string `json:"type"` // "text", "tool", etc.
Text string `json:"text,omitempty"`
// Synthetic marks text OpenCode wrote into the conversation itself, such
// as a background task's result injected as a user message.
Synthetic bool `json:"synthetic,omitempty"`
Tool string `json:"tool,omitempty"`
CallID string `json:"callID,omitempty"`
State *ToolState `json:"state,omitempty"`
}
Part represents a message part (text, tool, etc.).
type SessionInfo ¶
type SessionInfo struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
CreatedAt int64 `json:"createdAt,omitempty"`
UpdatedAt int64 `json:"updatedAt,omitempty"`
}
SessionInfo contains session metadata from the export.
type Tokens ¶
type Tokens struct {
Input int `json:"input"`
Output int `json:"output"`
Reasoning int `json:"reasoning"`
Cache Cache `json:"cache"`
Total int `json:"total"`
}
Tokens holds token usage from assistant messages.
func (Tokens) OutputWithReasoning ¶ added in v0.13.2
OutputWithReasoning returns output tokens with reasoning counted once. OpenCode 1.3.16 and later store reasoning apart from output; earlier versions stored the provider's output, which for some providers already includes it. A total (recorded since 1.1.57) of input + output + cache marks reasoning as inside output. Any other total, or no total (zero-usage messages, or messages written before 1.1.57), is assumed to store reasoning apart, so it is added.
type ToolFileInfo ¶ added in v0.4.8
type ToolFileInfo struct {
FilePath string `json:"filePath"`
RelativePath string `json:"relativePath,omitempty"`
}
ToolFileInfo represents a file affected by a tool operation.
type ToolState ¶
type ToolState struct {
Status string `json:"status"` // "pending", "running", "completed", "error"
Input map[string]any `json:"input,omitempty"`
Output string `json:"output,omitempty"`
Metadata *ToolStateMetadata `json:"metadata,omitempty"`
}
ToolState represents tool execution state.
type ToolStateMetadata ¶ added in v0.4.8
type ToolStateMetadata struct {
Files []ToolFileInfo `json:"files,omitempty"`
}
ToolStateMetadata holds metadata from tool execution results.