agentproc

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 25 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

AgentProc Go SDK

The Go implementation of the AgentProc protocol (wire 0.4), kept at observable parity with the Python, Node, and Rust SDKs — verified by the shared spec/conformance/ fixture suite, which this package's tests drive directly (cases.json, scenarios.json, executors.json, sdk.json, diagnostics.json, and the posture matrix).

go get github.com/jeffkit/agentproc/sdk/go

Bridge side — run a profile

package main

import (
	"context"
	"fmt"

	agentproc "github.com/jeffkit/agentproc/sdk/go"
)

func main() {
	result, err := agentproc.Run(context.Background(), map[string]any{
		"command": "python3",
		"args":    []string{"{{PROFILE_DIR}}/bridge.py"},
		"env":     map[string]string{"MY_API_KEY": "${MY_API_KEY}"},
		"cwd":     "/path/to/workspace",
	}, &agentproc.RunOptions{
		Message:   "hello",
		SessionID: "", // previous session id, "" = new session
		ProfileDir: "/path/to/profile-dir",
		OnPartial: func(text string, role *string) {
			fmt.Println("partial:", text)
		},
	})
	if err != nil {
		panic(err) // profile validation error
	}
	fmt.Println(result.Reply, result.SessionID, result.ExitCode)
}

The runner implements the full spawn-path contract: three-layer child env (infra set → profile env with ${VAR} expansion + env_allowlist → extras), {{SESSION_ID}} / {{PROFILE_DIR}} placeholders, earliest-expiry time limit (timeout_secs / budget_secs / deadline), SIGTERM → kill_grace_secs → SIGKILL against the whole process group, the bounded post-exit drain (a grandchild holding the pipe cannot hang the turn), exit-code normalisation (128 + signal), error-event precedence, first-non-empty session ids with wire validation, and the spawn-path permission channel.

Cooperative cancel: cancel the context.Context — the runner performs the graded kill and returns ExitCancelled (125) with TimedOut=false.

Agent side — write an agent

package main

import (
	"os"

	agentproc "github.com/jeffkit/agentproc/sdk/go"
)

func main() {
	handler := func(ctx *agentproc.Context) (*agentproc.AgentResult, error) {
		if err := ctx.SendPartial("thinking…", "thinking"); err != nil {
			return nil, err
		}
		return &agentproc.AgentResult{Response: "answer", SessionID: "s-1"}, nil
	}
	os.Exit(agentproc.Serve(handler))
}

Serve reads the turn object from stdin, calls the handler once per turn, and emits the NDJSON events. Return &agentproc.ProtocolError{...} for a fatal, user-visible error (emitted as an error event + exit 1); use ctx.SendError for a non-terminal error (the handler may still return a body, which the bridge discards per the spec). ctx.SendPermissionRequest / ctx.ReadPermissionResponse drive the optional permission channel.

In-process executors

Like the other SDKs, the runner can execute a profile through a named in-process executor — spawning the target CLI directly, no bridge subprocess. The built-in registry mirrors the Python/Node one (claude-code with the stdio permission channel, codex, cursor, gemini-cli, qwen-code, codebuddy, opencode, kimi-code, grok-build, agy, aider, deepseek, dsh, pi), adds Go's recursive (the native plain-mode executor mirroring plaita-nodes' "recursive-direct": plain stdout, trailing JSON result object, native resume <session>), and applications can register their own:

func init() {
	agentproc.RegisterExecutor("my-cli", func() agentproc.Executor {
		return &MyCLIExecutor{}
	})
}

Stateful executors implement TurnFactory (MakeTurn() per turn); the stdin prompt channel is the InitialStdinBuilder interface; plain-text CLIs declare Plain() = true and surface a minted session id via SessionIDGetter. When a plain CLI's stdout is an envelope rather than the reply itself (e.g. recursive's trailing JSON result object carrying session_id / usage / is_error), implement the optional PlainOutputParser interface — the runner hands it the assembled plain stdout after drain, and its ParseResult overrides the reply and contributes session, usage, and a terminal error (is_error fails the turn even on exit 0). The runner refuses to spawn (error + non-zero exit, never a silent --dangerously-skip-permissions) when permission: true meets an executor without SupportsPermission(), or when AGENTPROC_AUTO_APPROVE is off and the argv carries an auto-approve flag.

Workspace run lock

For hosts that can be hard-killed (SIGKILL / OOM) — worker runtimes, long- lived bridges — set RunOptions.RunLockKey (usually the workspace absolute path). After spawn the runner records pid + argv + the host's own pid under ~/.agentproc/run-locks/ (the "last will"); on normal completion the lock is cleared after the group kill. A takeover calls CleanupStaleRun(key, grace) before starting a new agent on the same workspace: dead pid → stale, release; live pid with verified identity (group leader + matching command) and a dead spawner → orphan, the whole group is killed, then release; a live spawner → RunLockBusy (never kill a healthy agent whose host is still running — the issue #9 rule); unverifiable → RunLockBusy, human decision.

CLI

go install github.com/jeffkit/agentproc/sdk/go/cmd/agentproc@latest builds the agentproc binary (port of the Python/Node CLI); prebuilt binaries for linux/darwin (amd64, arm64) and windows (amd64) are attached to the GitHub Releases tagged agentproc-cli/v*, so a Go toolchain is optional. --version reports the release tag: release builds inject it via -ldflags, go install …@vX.Y.Z reads it from the embedded build info, and source builds fall back to the SDKVersion constant:

agentproc --profile ./hub/echo-agent/profile.yaml --prompt "hi" [--cwd dir] [--raw] [--no-stream]
agentproc hub list
agentproc hub run claude-code -p "explain this" --env ANTHROPIC_API_KEY=$KEY
agentproc hub show codex
agentproc hub install agy

Output semantics match the reference CLIs: protocol events on stderr (NDJSON), the reply body on stdout, agentproc:session:<id> / agentproc:error:<msg> trailers, exit 0 / 1 / 2 (usage) / 130 (SIGINT) / 143 (SIGTERM — the agent group is killed first in every interrupt case). --timeout 0 disables the time limit, matching the profile field. Interactive permission profiles prompt y/N on a TTY and deny without one.

Scope notes

  • Hub divergence: the Go CLI has no bundled profile copy (a Go module cannot embed files outside its subtree) — hub commands resolve via the jsDelivr CDN and cache at ~/.agentproc/cache/hub/ (24h TTL), so first use needs network. AGENTPROC_HUB_REF pins an exact upstream version and invalidates the cache per ref.
  • Modules: gopkg.in/yaml.v3 (profile parsing) is the only dependency.

Tests

go test ./...   # includes the shared conformance fixtures

Documentation

Overview

Package agentproc is the Go implementation of the AgentProc protocol (spec/protocol.md, wire protocol 0.4).

The SDK covers both sides of the process boundary:

  • Bridge side (agentproc.Run): load a profile, spawn the agent process, deliver the turn on stdin, read the NDJSON event stream from stdout, assemble the reply, enforce timeouts / budgets / deadlines with a process-group kill, and surface session ids, usage, and errors.
  • Agent side (agentproc.Serve): write an agent as a Go function; Serve reads the turn object from stdin, calls the handler, and emits the protocol events on stdout.

The protocol is the source of truth (spec/protocol.md). Wire 0.4 is NDJSON in both directions: one {"type":"turn",...} line on stdin (then optional permission_response frames when permission is on), and one JSON object per line on stdout discriminated by "type": partial | result | error | permission_request.

Index

Constants

View Source
const (
	DefaultTimeoutSecs   = 1800
	DefaultKillGraceSecs = 5
)

DefaultTimeoutSecs / DefaultKillGraceSecs mirror the reference runners.

View Source
const (
	KindPartial           = "partial"
	KindResult            = "result"
	KindError             = "error"
	KindPermissionRequest = "permission_request"
	KindMalformed         = "malformed"
)

Event kinds returned by ClassifyLine. The set is closed (wire 0.4): partial, result, error, permission_request, plus malformed for anything that is not a valid JSON object event. Legacy wire 0.3 "session"/"text" events are malformed in 0.4.

View Source
const (
	ExitSuccess   = 0
	ExitError     = 1
	ExitTimeout   = 124 // bridge-imposed timeout (GNU timeout convention)
	ExitCancelled = 125 // cooperative cancel (host extension, matches the Python SDK)
	ExitSigint    = 130 // interrupted by SIGINT
	ExitSigterm   = 143 // terminated by SIGTERM
)

Spec exit codes (spec/protocol.md "Exit Codes").

View Source
const HubCacheTTLSecs = 24 * 60 * 60

HubCacheTTLSecs is the default cache freshness window (24 hours).

View Source
const HubRepo = "jeffkit/agentproc"

HubRepo is the GitHub repo id the hub profiles live in.

View Source
const PROTOCOL_VERSION = "0.4"

PROTOCOL_VERSION is the wire protocol this runner speaks (spec/protocol.md v0.4). Single literal definition — the SDK entry point re-exports it, the way the Python and Node SDKs import it from their runner modules.

View Source
const RunLockDirEnv = "AGENTPROC_RUN_LOCK_DIR"

RunLockDirEnv overrides the lock directory (tests / sandboxed hosts).

View Source
const SDKVersion = "0.1.4"

SDKVersion is the Go SDK's own version track (independent from the Python, Node, and Rust packages, which are released separately).

Variables

View Source
var AutoApproveFlags = []string{
	"--dangerously-skip-permissions",
	"--yolo",
	"--always-approve",
	"--yes-always",
	"--approve",
	"--auto",
}

AutoApproveFlags are the argv tokens that mean "auto-approve everything". Single source of truth is auto_approve_flags in spec/conformance/cases.json; the conformance driver asserts the two lists are equal item for item.

View Source
var EnvInfraVars = []string{
	"PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "LC_CTYPE",
	"LC_MESSAGES", "TERM", "TMPDIR", "TZ", "PWD",

	"SystemRoot", "TEMP", "TMP", "USERPROFILE", "USERNAME", "PATHEXT",
	"COMSPEC", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA", "NUMBER_OF_PROCESSORS",
	"PROCESSOR_ARCHITECTURE", "OS",
}

ENV_INFRA_VARS mirror (wire 0.3): the operational variables a bridge copies from its own environment into the child. None of them are credential-bearing. The infra set is always the base of the child env — there is no "inherit everything" mode in 0.3+.

View Source
var FailureDiagnosticPatterns = []*regexp.Regexp{
	regexp.MustCompile(`(?i)transient HTTP error`),
	regexp.MustCompile(`\b429\b`),
	regexp.MustCompile(`\b5\d{2}\b`),
	regexp.MustCompile(`thread '[^']*' panicked`),
	regexp.MustCompile(`(?i)\bpanic(?:ked)?\b`),
	regexp.MustCompile(`(?i)\b(?:error|exception|fatal|failed|failure)\b`),
}

FailureDiagnosticPattern mirrors FAILURE_DIAGNOSTIC_PATTERNS — the diagnostic-line shapes preferred when reporting a non-zero executor exit (plaita#121): the *head* of stderr is often a startup banner while the real cause (an LLM transient HTTP error, a panic, …) sits further down.

View Source
var StderrDiagnostics = []StderrDiagnosticRule{
	{
		ID:      "python-open-file",
		Pattern: `(?:can'?t|cannot) open file '([^']+)': \[Errno 2\] No such file or directory`,
		Hint:    "agent script not found: {1}. Check the profile's command path (likely a {{PROFILE_DIR}} issue or a typo).",
	},
	{
		ID:      "node-cannot-find-module",
		Pattern: `Cannot find module '([^']+)'`,
		Hint:    "agent script not found: {1}. Check the profile's command path (likely a {{PROFILE_DIR}} issue or a typo).",
	},
	{
		ID:      "bash-line-no-such-file",
		Pattern: `(?:^|\n)[^:]+: line \d+: ([^:]+): No such file or directory`,
		Hint:    "agent script not found: {1}. Check the profile's command path.",
	},
	{
		ID:      "generic-enoent",
		Pattern: `errno 2|enoent|no such file or directory`,
		Flags:   "i",
		Hint:    "agent reported a missing file. Check the profile's command and cwd.",
	},
}

StderrDiagnostics is the embedded mirror of spec/conformance/diagnostics.json.

Functions

func AppendHistory

func AppendHistory(sessionID string, entries []HistoryEntry, baseDir string) error

AppendHistory appends entries to a session's JSONL history file. A no-op when sessionID is empty or entries is empty.

func AutoApproveEnabled

func AutoApproveEnabled() bool

AutoApproveEnabled reports whether executors may bake auto-approve flags into argv. Read from the runner process's own environment (the spec makes AGENTPROC_AUTO_APPROVE a process-side knob, not a profile field): "0" / "false", case-insensitive and whitespace-trimmed, turns it off.

func BuildBaseEnv

func BuildBaseEnv() map[string]string

BuildBaseEnv builds the child process base env — the infra set, always, copied from the bridge's own environment (names only when set).

func ClearRunLock

func ClearRunLock(key string)

ClearRunLock removes the lock on normal completion (best-effort).

func ComposeEnv

func ComposeEnv(profileEnv map[string]string, allowlist []string, extraEnv map[string]string, substCtx map[string]string, onStderr func(line string)) map[string]string

ComposeEnv is the single shared three-layer child-env policy (both the spawn path and the executor path MUST use this — spec: "no third composition implementation"):

  1. infra set (BuildBaseEnv),
  2. the profile env block (${VAR} expanded against the bridge's full environment, env_allowlist-filtered — a blocked name expands to the empty string but the key is still set),
  3. extraEnv from the CLI --env flag (later layers override earlier).

profileEnv values may carry {{...}} placeholders, which are substituted with substCtx before ${VAR} expansion. onStderr (when given) receives the env_allowlist blocking warnings.

func DiagnoseStderrFailure

func DiagnoseStderrFailure(stderrText string) string

DiagnoseStderrFailure is a best-effort pattern check against the agent's accumulated stderr. It catches "bridge file not found" failures that the wrapped interpreter writes to its own stderr before exiting non-zero. Returns a friendly hint, or "" if nothing recognisable.

func ExecutorNames

func ExecutorNames() []string

ExecutorNames lists the registered executor names in registration order (built-ins first, mirroring the Python/Node registry listing).

func ExpandEnvRef

func ExpandEnvRef(value string, env map[string]string, allowlist map[string]bool, onBlocked func(name string)) string

ExpandEnvRef expands ${VAR} references in value against env.

When allowlist is non-nil, a reference whose name is NOT in the set expands to the empty string and onBlocked (when given) is called with the name — the spec's "env_allowlist blocked ${NAME}; expanded to empty" warning. When allowlist is nil, all references expand normally (unknown names expand to empty, POSIX-shell semantics — never to the literal ${VAR}).

func ExpandPath

func ExpandPath(p string) string

ExpandPath expands a leading "~" / "~/" to the current user's home.

func ExtractFailureDiagnostics

func ExtractFailureDiagnostics(stderrText string, maxTailLines int) string

ExtractFailureDiagnostics picks the useful failure signal out of an executor's stderr. Returns the diagnostic-looking lines (order preserved, de-duplicated, capped at failureMaxDiagnosticLines) when any matches FailureDiagnosticPatterns; otherwise the last maxTailLines lines prefixed with an explicit "not necessarily the cause" marker. Falls back to "(no stderr)" for empty input so callers keep the historical wording.

func FormatPermissionResponse

func FormatPermissionResponse(decision map[string]any) string

FormatPermissionResponse renders a {"type":"permission_response",...} line for stdin from a bridge-side decision. behavior is "allow" or anything else (which is rendered as "deny", mirroring the reference runners). An UpdatedInput that is non-nil and an object is echoed as "updated_input" — when the bridge omits it the agent MUST fall back to the request's original input, so the runner never auto-fills it.

func HubCacheDir

func HubCacheDir(name string) string

HubCacheDir is the local cache path for a profile.

func HubRef

func HubRef() string

HubRef returns the git ref to fetch from — AGENTPROC_HUB_REF when set (tag, branch or commit sha; the fetch-and-exec trust pin from the spec), "main" otherwise.

func IsValidPermissionRequest

func IsValidPermissionRequest(obj any) bool

IsValidPermissionRequest reports whether obj carries the required permission_request fields: a non-blank request_id without whitespace or control characters, a non-empty tool_name, and an object input.

func IsValidSessionID

func IsValidSessionID(value any) bool

IsValidSessionID reports whether value is a wire-valid session id: non-empty, no path separators or control characters, and not "." or "..".

func IsValidSessionIDString

func IsValidSessionIDString(s string) bool

IsValidSessionIDString is IsValidSessionID for a value already known to be a string.

func ListProfiles

func ListProfiles(refresh bool, onLog func(string)) ([]HubProfile, *HubError)

ListProfiles lists the hub's profiles: the disk-cached tree for names, then each profile.yaml for metadata.

func LockPathFor

func LockPathFor(key string) string

LockPathFor resolves the lock file path for a key (the workspace absolute path), hashed into the central lock directory.

func ParseDeadline

func ParseDeadline(value any) (float64, error)

ParseDeadline parses a profile deadline into epoch seconds; 0 when absent. Timezone-aware ISO-8601 only; a naive timestamp or unparseable value is a profile validation error (spec: bridges MUST NOT silently ignore it).

func ParseJSONLine

func ParseJSONLine(line string) map[string]any

ParseJSONLine parses one stdout line as a JSON object; nil on failure (empty line, invalid JSON, or valid JSON that is not an object).

func PostureRefusal

func PostureRefusal(cliName string, supportsPermission, permission, autoApproveEnabled bool, argv []string) string

PostureRefusal returns why this turn must not be spawned, or "" to proceed. Two refusal rules (spec "Runner contract" step 9): a profile permission channel the executor cannot serve, and an auto-approve argv while AGENTPROC_AUTO_APPROVE is off. Refusal is an error + non-zero exit — never a silent fallback to an auto-approve flag.

func RegisterExecutor

func RegisterExecutor(name string, factory func() Executor)

RegisterExecutor installs an executor factory under a profile `executor:` name. Registering an existing name replaces it. Call from an init() for application-local executors; the built-in registry (claude-code, codex, …) is registered the same way.

func Serve

func Serve(handler Handler) int

Serve reads the turn object from stdin, calls the handler, writes the protocol events to stdout, and returns the process exit code. Wire 0.4: exit 0 success, 1 error. Typical main:

os.Exit(agentproc.Serve(handler))

func SessionFilePath

func SessionFilePath(sessionID string, baseDir string) (string, error)

SessionFilePath resolves the JSONL history file path for a session, creating the sessions directory if needed. Returns an error when sessionID is empty or not a storage-safe filename component (see IsValidSessionIDString — a "/" in the id would path-traverse out of the sessions directory).

func Substitute

func Substitute(value string, ctx map[string]string) string

Substitute replaces the {{SESSION_ID}} / {{SESSION_NAME}} / {{PROFILE_DIR}} placeholders. {{MESSAGE}} is intentionally not substituted — the message travels via stdin only (never argv, never env).

func WriteRunLock

func WriteRunLock(key string, pid int, argv []string, spawner int)

WriteRunLock records a running agent (best-effort: a failure only costs orphan visibility, never blocks the turn). spawner <= 0 means this process — it must be the one that spawned the agent, so a takeover can ask "is the host that launched it still alive?"

Types

type AgentResult

type AgentResult struct {
	// Response is the final reply body.
	Response string
	// SessionID is persisted by the bridge and passed back next turn.
	SessionID string
}

AgentResult is the handler's return value. Returning a nil *AgentResult (with a nil error) means everything was already signalled via SendPartial / SendError — no result event is emitted.

type CleanupStaleRunResult

type CleanupStaleRunResult struct {
	Action  string // clean | stale | killed | unsupported
	Reason  string `json:",omitempty"`
	PID     int    `json:",omitempty"`
	Command string `json:",omitempty"`
}

CleanupStaleRunResult is the outcome of a kill-before-start probe.

func CleanupStaleRun

func CleanupStaleRun(key string, graceSecs float64) (CleanupStaleRunResult, error)

CleanupStaleRun probes and cleans the orphan agent process group recorded for key (kill-before-start). Ambiguous states (identity unverifiable / refused kill / still alive after SIGKILL) return *RunLockBusy — the lock is kept, nothing is blind-killed.

type Context

type Context struct {
	Message         string
	SessionID       string
	SessionName     string
	ProtocolVersion string
	Attachments     []any
	Permission      bool
	// contains filtered or unexported fields
}

Context is the per-turn input passed to a Serve handler, plus the outbound event channel. All writes happen at call time (flushed immediately).

func (*Context) ReadPermissionResponse

func (c *Context) ReadPermissionResponse() map[string]any

ReadPermissionResponse blocks until the next permission_response frame arrives on stdin (or EOF). Returns nil at EOF or on a malformed line. Only meaningful when ctx.Permission is true — in the default permission:false mode the bridge closes stdin after the turn line, so this returns nil immediately.

func (*Context) SendError

func (c *Context) SendError(text string) error

SendError writes a {"type":"error","message":...} line to stdout. Honored regardless of streaming mode, and non-terminal: the handler may continue and return a body (the bridge discards a result that follows an error). For a fatal path, return a *ProtocolError instead. An empty text writes nothing.

func (*Context) SendPartial

func (c *Context) SendPartial(text string, role ...string) error

SendPartial writes a {"type":"partial","text":...} line to stdout and flushes at call time; the bridge forwards it to the user without waiting for the process to exit. The optional role (e.g. "output" / "thinking") is forwarded as-is and MAY be rendered differently by the bridge. An empty text writes nothing.

func (*Context) SendPermissionRequest

func (c *Context) SendPermissionRequest(req PermissionRequest) error

SendPermissionRequest sends a tool-permission request to the bridge. Only valid when ctx.Permission is true (the profile set permission: true and the bridge enabled the channel). The matching decision arrives on stdin — read it with ReadPermissionResponse.

type Event

type Event struct {
	Kind      string
	Value     string
	Role      *string
	SessionID string
	Usage     map[string]any
	Obj       map[string]any
}

Event is one classified stdout line.

  • Kind: one of the Kind* constants.
  • Value: the partial/result "text" (or "" when missing or not a string), the error "message", the raw line for malformed, or (for permission_request) unused — the decoded object is in Obj.
  • Role: the partial's "role" field; nil when absent or not a string.
  • SessionID: the optional non-empty "session_id" carried by the event ("" when absent). Not validated here — validity is a runner concern.
  • Usage: the optional "usage" object on result/error events.
  • Obj: the whole decoded object (permission_request only).

func ClassifyLine

func ClassifyLine(line string) Event

ClassifyLine classifies one stdout line into a typed event (wire 0.4).

A conformant bridge treats every stdout line as JSON: partial / result / error / permission_request by "type", everything else (non-JSON, non-object, missing or unknown "type" — including legacy "session"/"text") as malformed, which is logged and ignored — never appended to the reply body.

type Executor

type Executor interface {
	// CLIName is the CLI binary name, used in error messages.
	CLIName() string
	// InstallHint is appended to "CLI not found" errors.
	InstallHint() string
	// Plain is true when the CLI emits plain text (not NDJSON): the entire
	// stdout becomes the reply body and ParseEvent is never called.
	Plain() bool
	// SupportsPermission reports a mid-turn approval channel. The runner
	// refuses to run a profile with permission: true against an executor
	// that does not declare it.
	SupportsPermission() bool
	// BuildArgs builds the target CLI's argv. The returned argv is passed to
	// the OS without a shell; an empty return is a hard error.
	BuildArgs(message, sessionID string, env map[string]string, ctx TurnCtx) ([]string, error)
	// ParseEvent translates one decoded JSON object from the CLI's stdout.
	// Return nil for events the executor does not recognise. Unused when
	// Plain is true.
	ParseEvent(event map[string]any) *ParseResult
}

Executor is a named, in-process implementation of the bridge side of the protocol (spec "In-process executors"). The runner spawns the target CLI directly — no bridge subprocess, no shell — and decodes its output with ParseEvent (or, for plain CLI executors, treats stdout as the body).

type Handler

type Handler func(ctx *Context) (*AgentResult, error)

Handler is the agent's per-turn function. Return a *AgentResult (or nil when everything was signalled via ctx), and a *ProtocolError to fail the turn with a user-readable message.

type HistoryEntry

type HistoryEntry struct {
	Role      string `json:"role"`
	Content   string `json:"content"`
	Timestamp string `json:"timestamp"`
}

HistoryEntry is one line of a session's JSONL history (a convenience the Python SDK also ships; storage shape is SDK-local, not wire).

func LoadHistory

func LoadHistory(sessionID string, baseDir string) ([]HistoryEntry, error)

LoadHistory loads the conversation history for a session; nil when the session is empty or no file exists yet.

type HubError

type HubError struct {
	Message string
	Hint    string
	Status  int // HTTP status; 0 for network errors
}

HubError is a hub fetch failure with a human-readable remediation hint. The CLI prints Message + Hint to stderr instead of a stack trace.

func FetchProfile

func FetchProfile(name string, refresh bool, onLog func(string)) (string, *HubError)

FetchProfile fetches a profile directory to the local cache and returns its path. Resolution: fresh cache (younger than 24h, same hub ref) → jsDelivr CDN. `_shared/` is populated alongside.

func InstallProfile

func InstallProfile(name string, targetDir string, refresh bool, onLog func(string)) (string, *HubError)

InstallProfile copies a cached profile into targetDir/<name>/, along with `_shared/` (the bridge scripts import it via a sibling path).

func ShowReadme

func ShowReadme(name string, refresh bool, onLog func(string)) (string, *HubError)

ShowReadme returns the README.md content for a profile (fetches if needed).

func (*HubError) Error

func (e *HubError) Error() string

type HubProfile

type HubProfile struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	CLI         string `json:"cli"`
	Tested      string `json:"tested"`
}

HubProfile is one hub entry's metadata (parsed from its profile.yaml).

type InitialStdinBuilder

type InitialStdinBuilder interface {
	BuildInitialStdin(message, sessionID string) (*string, error)
}

InitialStdinBuilder is the optional buildInitialStdin hook: a non-nil return makes the runner pipe the CLI's stdin, write the payload plus one "\n", and close it — the interface's way of keeping the user message out of argv (spec "Message delivery and argv"). A nil payload leaves the CLI's stdin on the null device.

type JournalEntry

type JournalEntry struct {
	Seq        int     `json:"seq"`
	Ts         string  `json:"ts"`
	Kind       string  `json:"kind,omitempty"`
	Line       string  `json:"line,omitempty"`
	Decision   string  `json:"decision,omitempty"`
	BudgetSecs float64 `json:"budget_secs,omitempty"`
}

JournalEntry is one opt-in journal record (spec "Event traceability"): classified events carry Kind/Line/Seq; bridge-level decisions carry Decision (timeout | sigterm_process_group | sigkill_process_group).

type ParseResult

type ParseResult struct {
	// PartialText is a streaming chunk (forwarded as {"type":"partial"} and
	// accumulated for the final body).
	PartialText *string
	// FinalText is the terminal reply body; &"" (pointer to empty) is an
	// explicit "no text body this event" and counts as the turn's result.
	FinalText *string
	// SessionID is a session id to persist (first non-empty wins).
	SessionID string
	// Error is a terminal error message (the turn fails even on exit 0).
	Error string
	// Usage is token/cost stats attached to the run result.
	Usage map[string]any
}

ParseResult is what ParseEvent returns for one decoded CLI stdout event. All fields optional; a nil *ParseResult means "this event contributes nothing". PartialText and Error MUST NOT both be set — an error is terminal.

type PermissionDecision

type PermissionDecision struct {
	// Behavior is "allow" or "deny" (anything but "allow" denies).
	Behavior string
	// UpdatedInput, when non-nil, overrides the request's input on allow.
	// When nil the response omits updated_input and the agent MUST fall back
	// to the request's original input — the runner never auto-fills it.
	UpdatedInput map[string]any
	// Message is the deny reason surfaced to the model or user.
	Message string
}

PermissionDecision is the bridge's answer to one permission_request.

type PermissionRequest

type PermissionRequest struct {
	RequestID   string
	ToolName    string
	Input       json.RawMessage
	Description string
	ToolUseID   string
}

PermissionRequest is the agent's ask for tool-execution authorization (spec "Optional tool permission"). RequestID, ToolName, and Input are required; Description and ToolUseID are optional.

type PlainOutputParser added in v0.1.4

type PlainOutputParser interface {
	ParsePlainOutput(stdout string) *ParseResult
}

PlainOutputParser is an optional Executor extension for Plain() executors whose stdout is not the reply itself but an envelope carrying it — e.g. recursive's native plain mode, where the trailing JSON result object holds the reply text plus session_id / usage / is_error. After the child exits and the pipes are drained, the runner hands the assembled plain stdout to ParsePlainOutput once; a non-nil result overrides the reply (FinalText) and contributes SessionID (wire-validated), Usage, and a terminal Error (a turn that reports is_error fails even on exit 0).

type Profile

type Profile struct {
	// Command is the executable (argv[0]) — one token, never split. Required
	// unless Executor is set to a name the SDK recognises.
	Command string
	// Executor is the optional in-process executor name (SDK-specific registry).
	Executor string
	// Args is argv[1..]; defaults to empty.
	Args []string
	// Cwd is the working directory; "" = the bridge's process cwd. Relative
	// paths are resolved against the profile's own directory at run time.
	Cwd string
	// Env is the extra environment block (secrets / config), ${VAR}-expanded.
	Env map[string]string
	// EnvAllowlist, when non-nil, shrinks ${VAR} expansion in Env to exactly
	// these names (blocked names expand to empty + a stderr warning). nil =
	// expand against the full bridge environment.
	EnvAllowlist []string
	// Permission enables the optional tool-permission channel (opt-in).
	Permission bool
	// TimeoutSecs is the per-turn wall-clock timeout; 0 = no host-side limit.
	// Default DefaultTimeoutSecs (1800) when absent from the profile.
	TimeoutSecs int
	// KillGraceSecs is the SIGTERM → SIGKILL grace period. Default
	// DefaultKillGraceSecs (5).
	KillGraceSecs int
	// BudgetSecs is the optional per-turn wall-clock budget (earliest-expiry
	// wins with TimeoutSecs and Deadline); nil = absent.
	BudgetSecs *float64
	// Deadline is the optional absolute ISO-8601 timestamp (timezone-aware).
	// Kept raw: a value that is present but not a valid timestamp string is
	// a profile validation error at Run time (spec: MUST NOT be silently
	// ignored), never dropped during normalization.
	Deadline any
	// Streaming forwards {"type":"partial"} events in real time. Default true.
	Streaming bool
}

Profile is a validated, normalized agent profile (spec/protocol.md "Profile YAML"). Build one programmatically, or parse YAML with ProfileFromYAML / a raw map with NormalizeProfile.

func NormalizeProfile

func NormalizeProfile(raw map[string]any) (*Profile, error)

NormalizeProfile validates and normalizes a raw profile dict (from YAML, JSON, or programmatic construction).

func ProfileFromYAML

func ProfileFromYAML(raw []byte) (*Profile, error)

ProfileFromYAML parses profile YAML text (or JSON — YAML is a superset) into a Profile. A top-level "agentproc:" wrapper key is unwrapped like the reference SDKs do.

type ProtocolError

type ProtocolError struct{ Message string }

ProtocolError is the fatal error path: a handler that returns one gets its message emitted as {"type":"error",...} and the process exits non-zero. (The non-fatal path is ctx.SendError — non-terminal, the handler may continue and return a body, which the bridge discards per the spec's "result after error" rule.)

func (*ProtocolError) Error

func (e *ProtocolError) Error() string

type RunLockBusy

type RunLockBusy struct {
	Key     string
	Message string
}

RunLockBusy is returned when the workspace appears to still have a live, identity-verified agent running — refuse to start (fail-safe).

func (*RunLockBusy) Error

func (e *RunLockBusy) Error() string

type RunOptions

type RunOptions struct {
	// Message is the user message; delivered on stdin only.
	Message string
	// SessionID resumes an agent session ("" = new session).
	SessionID string
	// SessionName is the human-readable session name ("" = "default").
	SessionName string
	// Streaming overrides the profile's streaming hint. nil = use profile.
	Streaming *bool
	// ExtraEnv is the CLI --env layer (overrides profile env).
	ExtraEnv map[string]string
	// Attachments is the turn's attachment list (presence-as-feature: the
	// key is included in the turn object only when non-empty).
	Attachments []any
	// Cwd overrides the profile cwd.
	Cwd string
	// ProfileDir is the profile's own directory ({{PROFILE_DIR}} expansion
	// and relative-cwd resolution).
	ProfileDir string
	// TimeoutSecs overrides the profile timeout. nil = use the profile value;
	// a non-nil 0 explicitly disables the host-side limit (matching the
	// Python/Node `timeout_secs=0` semantics).
	TimeoutSecs *int
	// RunLockKey (usually the workspace absolute path) turns on the "last
	// will" run lock: after spawn the runner records pid + argv + this
	// process's pid, so a takeover can kill-before-start the orphan group a
	// hard-killed host left behind (CleanupStaleRun). The lock is cleared
	// after the group kill on normal completion; early returns keep it on
	// purpose (self-healing: the recorded pid is dead by then).
	RunLockKey string
	// OnJournal is the opt-in journal hook (nil = no journaling).
	OnJournal func(JournalEntry)
	// OnPartial is called as each partial is forwarded. role is nil when the
	// event carries none (the runner MUST NOT synthesise "output").
	OnPartial func(text string, role *string)
	// OnSession is called once, when the first non-empty valid session id
	// is learned.
	OnSession func(sessionID string)
	// OnError is called when a terminal error is observed.
	OnError func(message string)
	// OnProtocolLine is called for every raw stdout line (debug traces).
	OnProtocolLine func(line string)
	// OnStderr is called for each stderr line and for runner warnings.
	// Callbacks may fire concurrently (stderr pump goroutine + main loop,
	// OnPermission on its dispatcher) — implementations must be
	// goroutine-safe or serialize themselves.
	OnStderr func(line string)
	// OnPermission answers a permission_request. nil = no approver wired:
	// the agent stays blocked until the turn timeout.
	OnPermission func(request map[string]any) *PermissionDecision
}

RunOptions configures one run.

type RunResult

type RunResult struct {
	// Reply is the user-visible reply body (spec reply-assembly rules).
	Reply string
	// SessionID is the first non-empty valid session id observed (or "").
	SessionID string
	// Error is the terminal error message ("" on success).
	Error string
	// ExitCode is the spec-normalized exit code.
	ExitCode int
	// TimedOut is true when the bridge killed the turn on its time limit.
	TimedOut bool
	// Usage is the terminal event's usage object (first non-empty wins).
	Usage map[string]any
	// StartedAt is the ISO-8601 UTC turn-start instant, millisecond precision
	// (spec "Event traceability").
	StartedAt string
	// Duration is bridge-measured wall-clock seconds covering spawn-to-exit.
	Duration float64
}

RunResult is the outcome of one agent turn.

func Run

func Run(ctx context.Context, profileRaw map[string]any, opts *RunOptions) (*RunResult, error)

Run executes one agent turn per the AgentProc spec (spawn path, or the in-process executor path when the profile names a registered executor).

Profile validation errors (including an invalid deadline) return a non-nil error; turn-level failures come back in the RunResult (Error + ExitCode). ctx cancellation performs the cooperative cancel: the process group gets the graded kill (SIGTERM → kill grace → SIGKILL) and the result carries ExitCancelled (125) with TimedOut=false.

func RunViaExecutor

func RunViaExecutor(ctx context.Context, executor Executor, opts *RunOptions, profile *Profile) *RunResult

RunViaExecutor runs a turn through an in-process executor (no bridge subprocess). Mirrors the Python run_via_executor / Node runViaExecutor: same env composition, same posture refusals, same reply-assembly rules — only the target CLI is spawned directly by the runner.

type SessionIDGetter

type SessionIDGetter interface {
	GetSessionID() string
}

SessionIDGetter is the optional getSessionId hook for plain executors: the session id this turn's BuildArgs minted or reused, read by the runner once after the CLI exits.

type StderrDiagnosticRule

type StderrDiagnosticRule struct {
	ID      string `json:"id"`
	Pattern string `json:"pattern"`
	Flags   string `json:"flags,omitempty"`
	Hint    string `json:"hint"`
	Sample  string `json:"sample,omitempty"`
	Expect  string `json:"expect,omitempty"`
}

StderrDiagnosticRule is one (pattern, hint) post-mortem rule. This is the runtime-embedded copy of spec/conformance/diagnostics.json — the single source of truth; the conformance test asserts the two stay in sync. Rules are evaluated in order; first match wins. A "{n}" token in the hint is replaced by capture group n; "{{PROFILE_DIR}}" is a literal, not a format token (only numeric {n} tokens are substituted).

type TurnCtx

type TurnCtx struct {
	Permission bool
}

TurnCtx carries the profile's permission value into BuildArgs (spec "Executor interface" — the ctx argument).

type TurnFactory

type TurnFactory interface {
	MakeTurn() *TurnHandlers
}

TurnFactory is the optional makeHandlers equivalent: stateful executors (per-turn parse state, a session id minted in BuildArgs) implement it and the runner calls MakeTurn() once per turn, using the returned handlers for that turn only. Executors without it are used directly and MUST be stateless / re-entrant.

type TurnHandlers

type TurnHandlers struct {
	BuildArgs         func(message, sessionID string, env map[string]string, ctx TurnCtx) ([]string, error)
	ParseEvent        func(event map[string]any) *ParseResult
	GetSessionID      func() string
	BuildInitialStdin func(message, sessionID string) (*string, error)
}

TurnHandlers is the closed turn-local handler set. The runner reads it off TurnFactory.MakeTurn() when implemented, else synthesises it from the executor's own methods (plus the optional interfaces above).

Directories

Path Synopsis
cmd
agentproc command
Command agentproc — run any AgentProc profile against a message (Go CLI).
Command agentproc — run any AgentProc profile against a message (Go CLI).
internal
sdkharness command
Command sdkharness is the SDK-entry conformance harness (Go side): it maps a scenario kind from spec/conformance/sdk.json to a handler and runs it under agentproc.Serve.
Command sdkharness is the SDK-entry conformance harness (Go side): it maps a scenario kind from spec/conformance/sdk.json to a handler and runs it under agentproc.Serve.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL