# Gojent — Complete Documentation Corpus > Strongly typed, streaming-first Go agent runtime with zero third-party dependencies in the root module. > Index: https://gojent.com/llms.txt > Go Reference: https://pkg.go.dev/github.com/ijaidev/gojent --- Source: https://gojent.com/docs/quickstart Markdown: https://gojent.com/docs/quickstart.md Section: Getting Started Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/agent --- # Quickstart Gojent is a strongly typed, streaming-first Go agent runtime built around explicit contracts, one-way module dependencies, and zero third-party dependencies in the root module. Use this quickstart to install the runtime, execute a key-free agent with `mockllm`, and connect a real provider with typed tools and session persistence. ## Requirements > **Beta (`v0.x`):** Gojent is pre-`v1.0.0`. Minor releases may introduce breaking changes while APIs settle—pin explicit module versions in `go.mod` and check [Versioning and submodule tags](/docs/guides/development#versioning-and-submodule-tags) and [`CHANGELOG.md`](https://github.com/ijaidev/gojent/blob/main/CHANGELOG.md) before upgrading. Gojent requires **Go 1.25.5** or newer. Install the root module to get `core/agent`, `core/llm`, `core/tool`, `core/session`, `tools`, and the deterministic `providers/mockllm` model: ```bash go get github.com/ijaidev/gojent@latest ``` Optional providers, durable session stores, and the MCP client live in separate Go modules so the root module stays dependency-free: ```bash go get github.com/ijaidev/gojent/providers/google go get github.com/ijaidev/gojent/providers/openai go get github.com/ijaidev/gojent/providers/anthropic go get github.com/ijaidev/gojent/stores/sqlite go get github.com/ijaidev/gojent/stores/postgres go get github.com/ijaidev/gojent/mcp ``` ## Run a key-free agent Start with `providers/mockllm` to verify the runtime loop locally without API credentials or external network calls: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/providers/mockllm" ) func main() { model := mockllm.New("Gojent is a small, typed agent runtime for Go.") assistant, err := agent.New(agent.Config{ Name: "assistant", Instructions: "Answer in one sentence.", Model: model, }) if err != nil { log.Fatal(err) } response, err := assistant.Generate(context.Background(), "What is Gojent?") if err != nil { log.Fatal(err) } fmt.Println(response.Text) } ``` Running this program prints the deterministic response from `mockllm`: ```text Gojent is a small, typed agent runtime for Go. ``` ## Add a typed tool and a real provider Tool inputs and outputs are ordinary Go structs. `tool.MustNew` generates a JSON Schema from struct tags (`json`, `description`, `enum`) and validates model arguments before your handler runs: ```go package main import ( "context" "fmt" "log" "os" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/session" "github.com/ijaidev/gojent/core/tool" "github.com/ijaidev/gojent/providers/google" ) type WeatherInput struct { City string `json:"city" description:"City name, e.g. Tokyo"` } type WeatherOutput struct { City string `json:"city"` TemperatureC float64 `json:"temperature_c"` } func main() { ctx := context.Background() model, err := google.New(ctx, google.Config{ Model: "gemini-2.5-flash", APIKey: os.Getenv("GEMINI_API_KEY"), }) if err != nil { log.Fatal(err) } weather := tool.MustNew(tool.Config[WeatherInput, WeatherOutput]{ ID: "get_weather", Description: "Get the current weather for a city.", Annotations: tool.Annotations{ReadOnly: true}, Execute: func(_ context.Context, in WeatherInput) (WeatherOutput, error) { return WeatherOutput{City: in.City, TemperatureC: 21.5}, nil }, }) assistant, err := agent.New(agent.Config{ Name: "assistant", Description: "A concise weather assistant", Instructions: "Use the weather tool when asked about current conditions.", Model: model, Tools: []tool.Tool{weather}, Store: session.NewMemory(), }) if err != nil { log.Fatal(err) } response, err := assistant.Generate(ctx, "What is the weather in Tokyo?", agent.WithSession("demo", "user-1"), ) if err != nil { log.Fatal(err) } fmt.Println(response.Text) } ``` Swap `google.New` for `openai.New`, `openai.NewChatCompletion`, or `anthropic.New` without changing agent, tool, or session code—all adapters implement the same `llm.Model` contract. ## Next steps - Understand the four extension seams and boundaries in [Architecture](/docs/architecture). - Define schema-validated tools in [Typed Tools](/docs/core/tools) or enforce tool gating in [Policies & Approvals](/docs/core/policies). - Explore [Model Providers](/docs/modules/providers) for OpenAI, Anthropic, and Google configuration. - Browse the full exported Go API on [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent). --- Source: https://gojent.com/docs/architecture Markdown: https://gojent.com/docs/architecture.md Section: Getting Started Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/agent --- # Architecture Gojent is an intentionally small Go agent runtime composed of four standard-library-only core packages (`core/agent`, `core/llm`, `core/tool`, `core/session`), ready-made `tools`, and optional child modules for providers, durable stores, and MCP. Rather than shipping a workflow engine or hidden global state, an agent is an immutable Go value, a run is a method call, and composition is ordinary Go code. ## Interfaces only at the seams The core exposes four small extension points and keeps the execution loop itself private: - [`llm.Model`](https://pkg.go.dev/github.com/ijaidev/gojent/core/llm#Model) (optionally [`llm.Streamer`](https://pkg.go.dev/github.com/ijaidev/gojent/core/llm#Streamer)), with `Info()` mandatory so the runner checks declared capabilities instead of probing. - [`tool.Tool`](https://pkg.go.dev/github.com/ijaidev/gojent/core/tool#Tool) for typed, schema-validated capabilities. - [`session.Store`](https://pkg.go.dev/github.com/ijaidev/gojent/core/session#Store) for loading and atomically appending transcripts. - [`agent.Policy`](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Policy), [`agent.Approver`](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Approver), and [`agent.Sink`](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Sink) for runtime gating and observation. `Generate` and `Stream` are public adapters over the private loop. Cross-cutting concerns such as tracing, caching, metrics, or redaction belong in wrappers around these seams rather than new core hooks. See [Extending Gojent](/docs/guides/extending) for seam middleware examples. ## Immutable agents, per-run configuration An `agent.Agent` represents reusable behavior: instructions, a model, sorted tools, and optional defaults. Once constructed with `agent.New`, a run cannot mutate the agent, making a single `*agent.Agent` safe for concurrent executions. Per-run configuration lives in `agent.RunOptions`, the single public per-run config type: - `Generate` and `Stream` accept functional `agent.Option` values (such as `agent.WithSession` or `agent.WithMaxSteps`). - `GenerateWith`, `StreamWith`, `GenerateMessagesWith`, and `StreamMessagesWith` accept a complete `agent.RunOptions` struct directly. - `(*Agent).ApplyAgentOptions` resolves precedence (`package defaults < agent.Config < RunOptions`) with field-by-field overrides for `Budget` and `RetryPolicy`. ## Fail closed Gojent rejects ambiguous or unsupported states explicitly instead of silently degrading: - **Policy gates:** Without a policy, tools execute directly. Once a policy is attached, `agent.DecisionUnknown` (zero value) and any out-of-range `Decision` resolve to `agent.Deny`, and `agent.Ask` without an `Approver` is denied. See [Policies & Approvals](/docs/core/policies). - **Provider capabilities:** Adapters declare capabilities in `llm.Info.Features` and reject unsupported options (such as stop sequences or strict JSON Schema on unsupported endpoints) with `llm.ErrUnsupported` rather than dropping fields. - **Sealed message parts:** `llm.Message` uses sealed content parts with a format version; unknown JSON part types fail closed with `llm.ErrUnknownPartType`. ## Atomic persistence A `session.Store` implements exactly two methods: `Load` and `Append`. During each step, the runner persists the assistant tool-call message and all of its corresponding tool results in one atomic `Append` call, ensuring a process crash cannot leave a transcript with dangling unanswered tool calls. See [Sessions & Stores](/docs/core/sessions). ## Package layout and one-way boundaries Dependency direction is strictly one-way and enforced by `just arch-check`: | Package / Module | Responsibility | Dependency Posture | | --- | --- | --- | | `core/agent` | Immutable `Agent`, execution loop, policies, events | Root module (stdlib-only) | | `core/llm` | `Model`, canonical `Message`/`Request`/`Response`, streams, errors | Root module (stdlib-only) | | `core/tool` | `Tool`, typed `Config`, JSON Schema generation and validation | Root module (stdlib-only) | | `core/session` | `Session` identity, two-method `Store`, `Memory` | Root module (stdlib-only) | | `tools` | Ready-made filesystem, exec, web, and task tools | Root module (stdlib-only) | | `providers/mockllm` | Deterministic in-memory model for tests and examples | Root module (stdlib-only) | | `providers/anthropic`, `google`, `openai` | Provider SDK adapters behind `llm.Model` | Separate `go.mod` modules | | `stores/sqlite`, `postgres` | Durable `session.Store` backends | Separate `go.mod` modules | | `mcp` | Client adapter for stdio and Streamable HTTP MCP servers | Separate `go.mod` module | | `codjent` | Sample ACP v2 coding agent and provider manager TUI | Separate `go.mod` module | Root packages never import child modules, and sibling provider or store modules never import one another. ## Non-goals The core runtime deliberately excludes: - a workflow engine, graph DSL, or node editor; - a UI or hosted service (`codjent` is an optional sample outside the core); - a vector database or retrieval framework; - provider-specific concepts in core contracts; - third-party dependencies in the root `go.mod`. Optional integrations live in separate modules fetched with `go get`. Browse the complete root package index on [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent). --- Source: https://gojent.com/docs/core/tools Markdown: https://gojent.com/docs/core/tools.md Section: Core Runtime Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/tool --- # Typed Tools A Gojent tool is a typed Go function paired with metadata (`tool.Spec`) implementing the `tool.Tool` interface. `tool.New` and `tool.MustNew` generate a JSON Schema directly from your Go input struct and validate model-supplied arguments before your handler ever runs. ## Define a typed tool Specify input and output types via `tool.Config[In, Out]` and pass it to `tool.New` (returns an error) or `tool.MustNew` (panics on invalid configuration, suited for startup wiring): ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/tool" ) type SearchInput struct { Query string `json:"query" description:"Search query"` Limit int `json:"limit,omitempty" description:"Maximum results, 1-20"` Scope string `json:"scope,omitempty" enum:"docs,code,all" description:"Search scope"` } type SearchResult struct { Title string `json:"title"` URL string `json:"url"` } func main() { search, err := tool.New(tool.Config[SearchInput, SearchResult]{ ID: "search", Description: "Search the knowledge base.", Annotations: tool.Annotations{ReadOnly: true, Idempotent: true}, Execute: func(_ context.Context, in SearchInput) (SearchResult, error) { return SearchResult{Title: "Result for " + in.Query, URL: "https://example.com"}, nil }, }) if err != nil { log.Fatal(err) } fmt.Println(search.Spec().Name) } ``` ### Supported struct tags and custom validation Struct tags on `In` drive schema generation: - `json` sets the JSON property name, and `,omitempty` marks the property optional (`required` otherwise). - `description` becomes the JSON Schema `description` shown to the model. - `enum` constrains accepted values, for example `enum:"low,medium,high"`. If your input type implements [`tool.Validator`](https://pkg.go.dev/github.com/ijaidev/gojent/core/tool#Validator) (`Validate() error`), the runtime invokes `Validate()` after JSON decoding and schema validation and before calling `Execute`. When targeting providers that enforce strict JSON Schemas, configure **both** `Config.Strict: true` (marks the tool specification strict) and `Config.SchemaOptions: []tool.SchemaOption{tool.WithStrictSchema(true)}` (emits a strict JSON Schema with `additionalProperties: false` and all properties required). ## Runtime execution guarantees When an agent invokes tools, the runtime enforces five isolation and scheduling guarantees: 1. **Pre-handler validation:** Explicit JSON arguments (including `{}`) are validated against the generated JSON Schema before decoding; mismatches return `tool.ErrInvalidInput` to the model and your `Execute` handler never runs. Empty or `null` arguments mean "no arguments" and skip schema validation (passing the zero value of `In`), so implement [`tool.Validator`](https://pkg.go.dev/github.com/ijaidev/gojent/core/tool#Validator) when a field must be rejected even if the model sends `null` or empty arguments—`Validate()` always runs before `Execute`. 2. **Bounded parallel execution:** Tools default to `tool.ExecutionParallel`, allowing contiguous parallel-safe tool calls in the same assistant message to run concurrently up to `MaxParallelTools` (`agent.DefaultMaxParallelTools` is `8`; set `1` via `agent.Config.MaxParallelTools` or `agent.WithMaxParallelTools` to force sequential execution). Calls marked `tool.ExecutionSequential` act as ordering barriers, and every result is recorded in exact original call order. 3. **Panic and cancellation containment:** Panics inside a tool handler are recovered and surfaced as tool errors rather than crashing the process. Context cancellation and timeouts are reported cleanly. 4. **Default tool timeout:** Each tool call is bounded by `agent.DefaultToolTimeout` (**2 minutes**) when `ToolTimeout` is zero. Override it on `agent.Config.ToolTimeout` or per run with `agent.WithToolTimeout`; set a negative duration to disable the timeout. Wrap long-running orchestration or subagent tools with `agent.WithoutDefaultToolTimeout` to exempt them from the default tool timeout while preserving enclosing `Budget.MaxDuration` and context cancellation. 5. **Atomic persistence:** Tool results are grouped into one user message (`llm.ToolResultsMessage`) and persisted together with the assistant tool-call message in a single `Store.Append` call. ## Side-effect annotations `tool.Annotations` describes a tool's behavioral side effects so an `agent.Policy` or `agent.Approver` can gate execution without inspecting the tool implementation: ```go no-compile type Annotations struct { ReadOnly bool // does not mutate state Destructive bool // may delete or overwrite data Idempotent bool // repeating the call has the same effect OpenWorld bool // talks to an unbounded external system } ``` Keep annotations honest—for example, mark read/search tools `ReadOnly: true, Idempotent: true` and file-mutating or shell tools `Destructive: true`. See [Policies & Approvals](/docs/core/policies) for gating on annotations. ## Results and multimodal output Returning any typed `Out` struct makes it available both as structured `Result.Data` and as JSON text for the model. To return files, images, audio, or custom `llm.Part` slices, return `tool.Result` (or use `tool.NewFileResult`): ```go package main import ( "context" "fmt" "github.com/ijaidev/gojent/core/llm" "github.com/ijaidev/gojent/core/tool" ) func main() { readPreview := tool.MustNew(tool.Config[struct{}, tool.Result]{ ID: "read_preview", Description: "Return a rendered preview part.", Annotations: tool.Annotations{ReadOnly: true}, Execute: func(_ context.Context, _ struct{}) (tool.Result, error) { return tool.Result{ Content: []llm.Part{llm.NewTextPart("rendered")}, }, nil }, }) fmt.Println(readPreview.Spec().Name) } ``` Explore ready-made filesystem, exec, web, and task tools in [Ready-Made Tools](/docs/modules/tools), or inspect the full API on [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/tool). --- Source: https://gojent.com/docs/core/streaming Markdown: https://gojent.com/docs/core/streaming.md Section: Core Runtime Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/agent --- # Streaming & Runs `Agent.Stream` executes the agent loop asynchronously and returns a `*agent.Run` handle whose `Events()` channel delivers ordered runtime events until `agent.RunEnd`. Both `Generate` and `Stream` wrap the same underlying loop, adapting model streaming when available or falling back seamlessly to `Generate`. ## Stream vs. Generate Choose the adapter that fits your caller: - **`Generate` / `GenerateWith` / `GenerateMessages`:** Blocks until the run finishes and returns `(*agent.Response, error)`. You can still observe live events during `Generate` by passing `agent.WithSink(...)`. - **`Stream` / `StreamWith` / `StreamMessages`:** Starts the run in a background goroutine and immediately returns `(*agent.Run, error)` for incremental UI rendering, cancellation, and waiting. ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/session" "github.com/ijaidev/gojent/providers/mockllm" ) func main() { ctx := context.Background() model := mockllm.New("Interfaces specify behavior without coupling callers to concrete types.") assistant, err := agent.New(agent.Config{ Name: "assistant", Model: model, }) if err != nil { log.Fatal(err) } run, err := assistant.Stream(ctx, "Explain Go interfaces briefly.", agent.WithStore(session.NewMemory()), agent.WithSession("demo", "user-1"), ) if err != nil { log.Fatal(err) } for event := range run.Events() { switch event := event.(type) { case agent.TextDelta: fmt.Print(event.Text) case agent.RunEnd: if event.Err != nil { log.Print(event.Err) } } } response, err := run.Wait(ctx) if err != nil { log.Fatal(err) } fmt.Printf("\nTokens: %d\n", response.Usage.TotalTokens) } ``` ## Run lifecycle: Events, Wait, and Cancel Understanding the `*agent.Run` contract avoids goroutine leaks and blocked dispatchers: - **`Run.Events()`** returns `<-chan agent.Event`, which terminates with `agent.RunEnd` and closes afterward on normal, drained completion. If the run or context is canceled before events are drained, the channel may close before `agent.RunEnd` is delivered—call `Run.Wait` with a live context when you need the final `(*agent.Response, error)` after cancellation. Events are observations only and cannot alter execution. - **`Run.Wait(ctx)`** blocks until the run finishes or `ctx` expires and returns the final `(*agent.Response, error)`. **`Wait` does not drain `Events()`**—if you ignore `Events()` without draining or canceling, the internal event dispatcher can block. Always either drain `run.Events()` or call `run.Cancel(...)` (or `run.Close()`) when abandoning a run. - **`Run.Cancel(cause)`** cancels the run with an explicit cause (`agent.ErrRunCanceled` when `cause` is `nil`). `Run.Close()` calls `Cancel(agent.ErrRunCanceled)` to satisfy `io.Closer`. - **`Run.Response()`** returns the cached response and error non-blockingly once the run has completed. ## Model streaming and TextDelta.Replace When a model also implements `llm.Streamer`, the runner calls `Stream(ctx, req)` and translates canonical `llm.StreamEvent` values into `agent.TextDelta`, `agent.ThinkingDelta`, and `agent.ToolCallDelta`. If the model only implements `llm.Model`, the runner falls back to `Generate` automatically. When `TextDelta.Replace` (or `ThinkingDelta.Replace`) is `true`, `Text` is a **full snapshot** of that content part rather than an incremental suffix—replace your accumulated buffer for `(Step, Index)` instead of appending. See [Observability](/docs/core/observability) for the full event catalog, or [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Run) for the `Run` reference. --- Source: https://gojent.com/docs/core/sessions Markdown: https://gojent.com/docs/core/sessions.md Section: Core Runtime Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/session --- # Sessions & Stores `core/session` defines conversation identity (`session.Session`), context propagation (`session.NewContext` / `session.FromContext`), and the minimal two-method `session.Store` contract (`Load` and atomic `Append`). Keeping persistence intentionally narrow allows in-memory testing and durable SQL backends to share one contract without leaking database concepts into the core. ## The two-method Store contract A `session.Store` has exactly two methods: ```go no-compile type Store interface { Load(ctx context.Context, session Session) ([]llm.Message, error) Append(ctx context.Context, session Session, messages ...llm.Message) error } ``` `Append` must be **atomic**: either every passed message is persisted or none is. During each step, the runner persists the assistant message (including any tool calls) together with all corresponding tool results in a single `Append` call. A crash mid-turn therefore cannot leave a stored transcript with unanswered tool calls. Durability features beyond transcript storage—such as checkpoints, leases, search indexes, or conversation titles—belong in store modules or your application layer rather than `core/session`. ## Session identity and tenant isolation `session.Session` pairs a conversation `ID` with an owner or tenant `ResourceID`: ```go no-compile type Session struct { ID string `json:"id"` ResourceID string `json:"resource_id,omitempty"` } ``` Even when a `Store` is configured once on `agent.Config.Store`, the `Session` identity is always supplied **per run** (`agent.WithSession(id, resourceID)` or `RunOptions.Session`). If a store is configured without a session, the runner fails fast with `agent.ErrSessionRequired`; an empty `ID` returns `agent.ErrSessionIDRequired`. Stores must scope queries by both `ID` and `ResourceID` so two tenants that happen to use the same conversation `ID` never see each other's messages. During execution, the runner also attaches the active `Session` to `ctx` via `session.NewContext`, allowing tools and `HeaderFunc` callbacks to read it with `session.FromContext(ctx)`. ## Ephemeral vs. durable stores Use `session.NewMemory()` for unit tests and ephemeral processes, or connect `stores/sqlite` / `stores/postgres` when transcripts must survive restarts: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/session" "github.com/ijaidev/gojent/providers/mockllm" ) func main() { ctx := context.Background() store := session.NewMemory() defer func() { _ = store.Close() }() assistant, err := agent.New(agent.Config{ Name: "assistant", Model: mockllm.New("First reply.", "Follow-up reply."), Store: store, }) if err != nil { log.Fatal(err) } _, err = assistant.Generate(ctx, "Hello", agent.WithSession("thread-1", "tenant-a")) if err != nil { log.Fatal(err) } resp, err := assistant.Generate(ctx, "Continue", agent.WithSession("thread-1", "tenant-a")) if err != nil { log.Fatal(err) } fmt.Println(resp.Text) } ``` See [Session Stores](/docs/modules/stores) for `stores/sqlite` and `stores/postgres` configuration, or [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/session) for full API details. --- Source: https://gojent.com/docs/core/policies Markdown: https://gojent.com/docs/core/policies.md Section: Core Runtime Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/agent --- # Policies & Approvals Gojent policies (`agent.Policy`) govern model and tool calls at runtime with fail-closed semantics: once a policy is installed, any unrecognized decision or unapproved `agent.Ask` verdict resolves to `agent.Deny`. Use policies together with `agent.Approver` to require human confirmation for destructive operations, enforce security boundaries, or abort a run immediately. ## How fail-closed enforcement works Without a policy configured on `agent.Config` or `agent.RunOptions`, tool calls execute directly. As soon as a policy is attached, the runner enforces every verdict defensively: - `agent.DecisionUnknown` (the zero value) and any out-of-range `Decision` value are treated as `agent.Deny`. - `agent.Ask` delegates to the configured `agent.Approver`. If no approver is configured or `Approver.Approve` returns `(false, nil)`, the call is denied and the model can recover. If `Approver.Approve` returns a non-nil error, the error propagates out of the tool gate and aborts the run without recording `llm.ToolStatusDenied` or emitting `agent.ErrToolDenied`. - Denied tool calls never invoke the tool handler; the runtime records a denied tool result (`llm.ToolStatusDenied`) and emits `agent.ErrToolDenied` on `ToolEnd.Err` so the model can recover without leaving unanswered tool calls in the session transcript. - `agent.Terminate` aborts the run immediately with `agent.ErrTerminated` and prevents dangling assistant tool-call messages from being persisted. ## Tool decisions `BeforeTool` inspects the step index, requested `tool.Call`, and tool metadata (`tool.Spec`, including `tool.Annotations`) and returns one of four explicit decisions: | Decision | Effect | | --- | --- | | `agent.Allow` | Execute the tool handler. | | `agent.Deny` | Skip execution and report the denial to the model. | | `agent.Ask` | Require `Approver.Approve` to return `true`; deny if no approver is attached. | | `agent.Terminate` | Abort the run immediately with `agent.ErrTerminated`. | ## Gate destructive tools with Hooks and Approver `agent.Hooks` implements `agent.Policy` using optional function fields, making it concise for single-purpose gates such as requiring approval whenever a tool declares `Annotations.Destructive`: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/llm" "github.com/ijaidev/gojent/core/tool" "github.com/ijaidev/gojent/providers/mockllm" ) func main() { ctx := context.Background() cleanup := tool.MustNew(tool.Config[struct{}, string]{ ID: "clean_build", Description: "Remove build artifacts.", Annotations: tool.Annotations{Destructive: true}, Execute: func(_ context.Context, _ struct{}) (string, error) { return "cleaned", nil }, }) turn := 0 model := mockllm.New().ApplyOptions( mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) { turn++ if turn == 1 { return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{ CallID: "c1", Name: "clean_build", Input: []byte(`{}`), })}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool}, }), nil } return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewTextPart("")}, llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Build directory cleaned."}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop}, }), nil }), ) assistant, err := agent.New(agent.Config{ Name: "maintainer", Model: model, Tools: []tool.Tool{cleanup}, }) if err != nil { log.Fatal(err) } opts := agent.RunOptions{ Policy: agent.Hooks{ OnBeforeTool: func(_ context.Context, req *agent.ToolRequest) (agent.Decision, error) { if req.Spec.Annotations.Destructive { return agent.Ask, nil } return agent.Allow, nil }, }, Approver: agent.ApproverFunc(func(_ context.Context, req agent.ToolRequest) (bool, error) { // Present req.Call and req.Spec to a human operator and return their choice. return req.Call.Name == "clean_build", nil }), } response, err := assistant.GenerateWith(ctx, "Clean up the build directory.", opts) if err != nil { log.Fatal(err) } fmt.Println(response.Text) } ``` Because approval is evaluated inside the runtime loop rather than exposed as a tool, a model cannot bypass or spoof the approval check. ## Compose policies with PolicyChain Use `agent.PolicyChain` to layer multiple independent policies (for example, an organization-wide deny list followed by a workspace approval hook): ```go package main import ( "context" "fmt" "github.com/ijaidev/gojent/core/agent" ) func main() { denyOpenWorld := agent.Hooks{ OnBeforeTool: func(_ context.Context, req *agent.ToolRequest) (agent.Decision, error) { if req.Spec.Annotations.OpenWorld { return agent.Deny, nil } return agent.Allow, nil }, } approveDestructive := agent.Hooks{ OnBeforeTool: func(_ context.Context, req *agent.ToolRequest) (agent.Decision, error) { if req.Spec.Annotations.Destructive { return agent.Ask, nil } return agent.Allow, nil }, } chain := agent.PolicyChain{ denyOpenWorld, approveDestructive, } fmt.Println(len(chain)) } ``` `PolicyChain` applies strict composition rules: - `BeforeModel` and `BeforeTool` execute in slice order. - `AfterModel` and `AfterTool` execute in reverse order, matching standard middleware unwinding. - For `BeforeTool`, the **most restrictive decision wins** in precedence order: `agent.Terminate` > `agent.Ask` > `agent.Deny` (including `DecisionUnknown`) > `agent.Allow`. - If any policy returns an error from `BeforeTool`, `PolicyChain` immediately returns `agent.Deny` alongside the error. ## Inspect model requests and responses A full `agent.Policy` implementation also intercepts model turns via `BeforeModel` and `AfterModel`: ```go no-compile type Policy interface { BeforeModel(ctx context.Context, req *ModelRequest) error AfterModel(ctx context.Context, result *ModelResult) error BeforeTool(ctx context.Context, req *ToolRequest) (Decision, error) AfterTool(ctx context.Context, result *ToolResult) error } ``` `BeforeModel` and `AfterModel` may inspect or rewrite `req.Request` and `result.Response`, or return an error to abort the run. Keep observation-only telemetry in `agent.Sink` rather than in a policy: sinks observe events without altering execution, whereas policies decide. ## Agent defaults and run overrides Behavior that should apply to every run belongs on `agent.Config`. A run overrides it with `RunOptions`; unset values inherit the agent configuration: ```go package main import ( "context" "fmt" "log" "time" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/session" "github.com/ijaidev/gojent/providers/mockllm" ) func main() { ctx := context.Background() temperature := 0.2 assistant, err := agent.New(agent.Config{ Name: "reviewer", Model: mockllm.New("Repository analysis complete."), Store: session.NewMemory(), Budget: agent.Budget{MaxSteps: 16, MaxDuration: 10 * time.Minute}, Retry: agent.RetryPolicy{MaxAttempts: 3}, ToolTimeout: 30 * time.Second, Temperature: &temperature, }) if err != nil { log.Fatal(err) } // This run raises only the step limit. The duration cap, store, retry // policy, temperature, and tool timeout still apply. response, err := assistant.Generate(ctx, "Analyze this repository.", agent.WithMaxSteps(32), agent.WithSession("review-1", "user-1"), ) if err != nil { log.Fatal(err) } fmt.Println(response.Text) } ``` Precedence is **package defaults < `agent.Config` < `RunOptions`**. `Budget` and `RetryPolicy` merge field by field, so overriding one field keeps the others. `Session` is always per-run—an agent `Store` still requires a session on each call. `Sink` and `Media` also stay per-run because they belong to a specific execution. Package defaults: - `agent.DefaultMaxSteps` is `8` when `Budget.MaxSteps` is zero. - `agent.DefaultToolTimeout` is `2 * time.Minute` when `ToolTimeout` is zero (negative values disable the timeout). - `RetryPolicy.MaxAttempts` counts total attempts, including the first; zero or one disables retries. `(*Agent).ApplyAgentOptions` applies this exact layering to a `RunOptions` value. The runtime calls it for every run, so custom wrappers or engines can reuse it instead of duplicating merge rules. See [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Policy) for full symbol reference. --- Source: https://gojent.com/docs/core/structured-output Markdown: https://gojent.com/docs/core/structured-output.md Section: Core Runtime Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/agent --- # Structured Output Gojent generates strict JSON Schemas from Go struct types and decodes model responses into strongly typed values via `agent.GenerateStructured[T]` or `agent.WithOutputSchema[T]`. Providers that cannot honor strict JSON Schema fail closed with `llm.ErrUnsupported` instead of silently relaxing constraints. ## Decode directly with GenerateStructured `agent.GenerateStructured[T]` attaches a strict schema derived from `T`, runs `Generate`, and unmarshals the final assistant text into `T`: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/providers/mockllm" ) type WeatherReport struct { City string `json:"city" description:"City name"` Temperature float64 `json:"temperature_c" description:"Current temperature in Celsius"` Conditions []string `json:"conditions" description:"Short condition labels"` } func main() { ctx := context.Background() model := mockllm.New(`{"city":"Tokyo","temperature_c":21.5,"conditions":["clear"]}`) assistant, err := agent.New(agent.Config{ Name: "weather", Model: model, }) if err != nil { log.Fatal(err) } report, response, err := agent.GenerateStructured[WeatherReport]( ctx, assistant, "Report the weather in Tokyo.", ) if err != nil { log.Fatal(err) } fmt.Printf("%s: %.1f°C (%d tokens)\n", report.City, report.Temperature, response.Usage.TotalTokens) } ``` ## Use WithOutputSchema and Response.Unmarshal When you want to pass additional options or decode manually (for example after `Stream` + `Wait`), attach `agent.WithOutputSchema[T](opts...)` and call `response.Unmarshal(&target)`: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/providers/mockllm" ) type Summary struct { Headline string `json:"headline" description:"One-line summary"` } func main() { ctx := context.Background() assistant, err := agent.New(agent.Config{ Name: "summarizer", Model: mockllm.New("```json\n{\"headline\":\"All checks passed\"}\n```"), }) if err != nil { log.Fatal(err) } response, err := assistant.Generate(ctx, "Summarize the build.", agent.WithOutputSchema[Summary](), ) if err != nil { log.Fatal(err) } var out Summary if err := response.Unmarshal(&out); err != nil { log.Fatal(err) } fmt.Println(out.Headline) } ``` `Response.Unmarshal` tolerates a single Markdown JSON code fence around the payload. Pass `tool.SchemaOption` values to `WithOutputSchema[T](opts...)` to customize schema generation. ## Strict capability enforcement Because `WithOutputSchema[T]` sets `Strict: true` on `llm.ResponseFormat`, the runner checks `model.Info().Features.StrictJSONSchema` before sending the request. Adapters that do not advertise strict JSON Schema support (such as the current Anthropic Messages adapter) reject the request with `llm.ErrUnsupported` rather than silently dropping the schema. See [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#GenerateStructured) for `GenerateStructured` and `Response` details. --- Source: https://gojent.com/docs/core/subagents Markdown: https://gojent.com/docs/core/subagents.md Section: Core Runtime Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/agent --- # Subagents & Composition `Agent.AsTool`, `Agent.AsToolWith`, and `agent.AsTypedTool` expose an `*agent.Agent` as a standard `tool.Tool` so a parent agent can delegate subtasks through ordinary tool calls. Gojent contains no sequential, parallel, or loop graph DSL—concurrent and multi-step orchestration uses goroutines, channels, and standard Go functions. ## Expose a subagent with AsTool Calling `researcher.AsTool()` wraps `researcher` into a tool named after `researcher.Name()` (sanitized for tool-name rules) accepting `agent.SubagentInput{Prompt: "..."}`. By default, `AsTool` and `AsToolWith` return `agent.SubagentResult` in `tool.Result.Data` alongside the child's final `resp.Text`—omitting the full child message transcript to avoid quadratic context growth across delegation chains—and wrap the tool with `agent.WithoutDefaultToolTimeout` so `DefaultToolTimeout` does not cut off multi-step child runs (enclosing `Budget.MaxDuration` and context cancellation still apply): ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/llm" "github.com/ijaidev/gojent/core/tool" "github.com/ijaidev/gojent/providers/mockllm" ) func main() { researcher, err := agent.New(agent.Config{ Name: "researcher", Description: "Finds primary sources", Instructions: "Find and cite primary sources.", Model: mockllm.New("Primary source confirmed."), }) if err != nil { log.Fatal(err) } turn := 0 writerModel := mockllm.New().ApplyOptions( mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) { turn++ if turn == 1 { return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{ CallID: "c1", Name: "researcher", Input: []byte(`{"prompt":"Summarize Gojent's core packages."}`), })}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool}, }), nil } return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewTextPart("")}, llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Article drafted from primary sources."}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop}, }), nil }), ) writer, err := agent.New(agent.Config{ Name: "writer", Instructions: "Draft an article using the researcher's findings.", Model: writerModel, Tools: []tool.Tool{researcher.AsTool()}, }) if err != nil { log.Fatal(err) } resp, err := writer.Generate(context.Background(), "Write a brief note on Gojent.") if err != nil { log.Fatal(err) } fmt.Println(resp.Text) } ``` ## Customize behavior with AsToolConfig and AsTypedTool Use `Agent.AsToolWith(agent.AsToolConfig{...})` to override tool metadata, set child `RunOptions`, supply a custom `FormatResult`, cap nesting with `MaxDepth`, or opt out of shared budgets (`IsolateBudget`), policy inheritance (`DisablePolicyInheritance`), or event forwarding (`DisableEventForwarding`). For structured contracts, `agent.AsTypedTool[In, Out]` validates `In` against its generated schema (and `tool.Validator`), constrains the child with `WithOutputSchema[Out]`, validates and decodes the child's JSON into `Out`, and returns `Out` in `tool.Result.Data`: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/llm" "github.com/ijaidev/gojent/core/tool" "github.com/ijaidev/gojent/providers/mockllm" ) type ReviewInput struct { Target string `json:"target" description:"Package or file to review"` } type ReviewOutput struct { Approved bool `json:"approved"` Summary string `json:"summary"` } func main() { reviewer, err := agent.New(agent.Config{ Name: "reviewer", Instructions: "Return a structured review verdict.", Model: mockllm.New(`{"approved":true,"summary":"Checks pass."}`), }) if err != nil { log.Fatal(err) } // Custom formatting on AsToolWith when you want to inspect the full *agent.Response. compactTool := reviewer.AsToolWith(agent.AsToolConfig{ Name: "review_summary", Description: "Review a change and return a one-line summary.", MaxDepth: 2, Options: agent.RunOptions{Budget: agent.Budget{MaxSteps: 6}}, FormatResult: func(_ context.Context, _ *agent.Response, summary agent.SubagentResult) (tool.Result, error) { return tool.Result{ Data: summary, Content: []llm.Part{llm.NewTextPart(fmt.Sprintf("%s (%d steps)", summary.Text, summary.Steps))}, }, nil }, }) // Typed schema-enforced delegation with AsTypedTool. typedTool, err := agent.AsTypedTool(reviewer, agent.TypedSubagentConfig[ReviewInput, ReviewOutput]{ Name: "typed_review", Description: "Run a structured review and return ReviewOutput.", Prompt: func(in ReviewInput) (string, error) { return "Review " + in.Target, nil }, }) if err != nil { log.Fatal(err) } turn := 0 leadModel := mockllm.New().ApplyOptions( mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) { turn++ if turn == 1 { return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{ CallID: "c1", Name: "typed_review", Input: []byte(`{"target":"core/agent"}`), })}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool}, }), nil } return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewTextPart("")}, llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Review approved."}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop}, }), nil }), ) lead, err := agent.New(agent.Config{ Name: "lead", Model: leadModel, Tools: []tool.Tool{compactTool, typedTool}, }) if err != nil { log.Fatal(err) } resp, err := lead.Generate(context.Background(), "Review core/agent.") if err != nil { log.Fatal(err) } fmt.Println(resp.Text) } ``` ## Delegation guarantees: ancestry, budgets, policies, and events When a subagent runs inside an enclosing parent run's `context.Context` (whether via `AsTool`, `AsTypedTool`, or `(*agent.Agent).Generate`/`Stream`), the runner enforces four cross-run guarantees by default: - **Ancestry and depth bounds:** Every run derives a `agent.RunAncestry` (`RunID`, `ParentRunID`, `ParentCallID`, `ParentSessionID`, `AgentPath`, `Depth`) retrievable via `agent.AncestryFromContext(ctx)`. Nesting depth is bounded by `agent.DefaultMaxSubagentDepth` (`4`) or the tightest ancestor `MaxSubagentDepth` ceiling; exceeding it fails immediately with `agent.ErrMaxDepthExceeded`. - **Shared budgets and usage roll-up:** Child runs share `MaxToolCalls` and `MaxTotalTokens` budgets with their parent chain, and child model usage rolls up into parent `Response.Usage` and `SubagentResult.Usage`. Set `AsToolConfig.IsolateBudget` (or `agent.WithIsolateBudget(true)`) to give a child an independent budget and usage counter. - **Fail-closed policy and approver inheritance:** Unless `DisablePolicyInheritance` (or `agent.WithDisablePolicyInheritance(true)`) is set, a child inherits the parent's `Policy` and `Approver`. If the child also defines its own `Policy`, both execute with fail-closed precedence (`Terminate` > `Deny`/`DecisionUnknown` > `Ask` > `Allow`) so a child policy can narrow permissions but never relax a parent's denial. - **Live event forwarding:** Child events wrap into `agent.SubagentEvent` (carrying `ParentRunID`, `ParentCallID`, `RunID`, `Agent`, `AgentPath`, `Depth`, `Session`, and the inner `Event`) and forward to the parent's `Sink` unless `DisableEventForwarding` (or `agent.WithDisableEventForwarding(true)`) is set. ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/llm" "github.com/ijaidev/gojent/core/tool" "github.com/ijaidev/gojent/providers/mockllm" ) func main() { inspect := tool.MustNew(tool.Config[struct{}, string]{ ID: "inspect", Description: "Return ancestry depth.", Annotations: tool.Annotations{ReadOnly: true}, Execute: func(ctx context.Context, _ struct{}) (string, error) { ancestry, ok := agent.AncestryFromContext(ctx) if !ok { return "no ancestry", nil } return fmt.Sprintf("depth=%d path=%v", ancestry.Depth, ancestry.AgentPath), nil }, }) childTurn := 0 childModel := mockllm.New().ApplyOptions( mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) { childTurn++ if childTurn == 1 { return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{ CallID: "c_leaf", Name: "inspect", Input: []byte(`{}`), })}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool}, }), nil } return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewTextPart("")}, llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Child inspected."}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop}, }), nil }), ) child, err := agent.New(agent.Config{ Name: "inspector", Model: childModel, Tools: []tool.Tool{inspect}, }) if err != nil { log.Fatal(err) } parentTurn := 0 parentModel := mockllm.New().ApplyOptions( mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) { parentTurn++ if parentTurn == 1 { return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{ CallID: "c_sub", Name: "inspector", Input: []byte(`{"prompt":"check ancestry"}`), })}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool}, }), nil } return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewTextPart("")}, llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Done."}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop}, }), nil }), ) parent, err := agent.New(agent.Config{ Name: "orchestrator", Model: parentModel, Tools: []tool.Tool{child.AsTool()}, }) if err != nil { log.Fatal(err) } forwarded := 0 resp, err := parent.Generate( context.Background(), "Run inspector.", agent.WithSink(agent.SinkFunc(func(ev agent.Event) { if _, ok := ev.(agent.SubagentEvent); ok { forwarded++ } })), ) if err != nil { log.Fatal(err) } fmt.Println(resp.Text, "forwarded:", forwarded > 0) } ``` ## Ordinary Go composition Because an `*agent.Agent` is immutable and safe for concurrent runs, fan-out, pipelines, and conditional branching require no framework primitives—call `Generate` or `Stream` inside standard goroutines, `sync.WaitGroup`, or `errgroup`, and pass the parent `ctx` so cancellation propagates cleanly. For managed background subagents, multi-turn resume, and git-worktree isolation, see [Ready-Made Tools](/docs/modules/tools). See [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Agent.AsTool) for full signatures. --- Source: https://gojent.com/docs/core/observability Markdown: https://gojent.com/docs/core/observability.md Section: Core Runtime Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/agent --- # Observability `agent.Sink` and `agent.SinkFunc` receive every execution lifecycle event for a run without altering control flow. Unlike `agent.Policy`, sinks are strictly observational; a panicking sink is recovered by the runtime and cannot disrupt execution or block other sinks. ## Attach a Sink to a run Pass `agent.WithSink` (or set `RunOptions.Sink`) on `Generate` or `Stream` to observe text deltas, tool invocations, step boundaries, and terminal errors: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/providers/mockllm" ) func main() { assistant, err := agent.New(agent.Config{ Name: "assistant", Model: mockllm.New("Repository summary ready."), }) if err != nil { log.Fatal(err) } sink := agent.SinkFunc(func(event agent.Event) { switch event := event.(type) { case agent.TextDelta: fmt.Print(event.Text) case agent.ToolStart: log.Printf("tool %s: %s", event.Call.Name, event.Call.Arguments) case agent.ToolEnd: log.Printf("tool %s finished with error: %v", event.Call.Name, event.Err) } }) response, err := assistant.Generate(context.Background(), "Summarize this repository.", agent.WithSink(sink), ) if err != nil { log.Fatal(err) } fmt.Printf("\nTotal tokens: %d\n", response.Usage.TotalTokens) } ``` ## Runtime event lifecycle Every run emits typed values implementing the sealed `agent.Event` interface: | Event | When emitted | | --- | --- | | `RunStart` | Once at the start of a run (`RunID`, `Agent`, `Session`, `At`). | | `StepStart` | Before each model call (`Step`). | | `MessageStart` | Before streamed assistant output for a step. | | `TextDelta` | Text fragment (`Step`, `Index`, `Text`, `Replace`). | | `ThinkingDelta` | Reasoning fragment (`Step`, `Index`, `Text`, `Replace`). | | `ToolCallDelta` | Streamed tool-call fragment (`ID`, `Name`, `Arguments`). | | `MessageEnd` | Completed assistant `*llm.Message` for a step. | | `ToolStart` | Before a tool call is evaluated (`Call`, `Spec`). | | `ToolUpdate` | Reserved for tools/schedulers reporting progress (not emitted by default runner). | | `ToolEnd` | Paired **once for every `ToolStart`**, including denied, failed, or policy-aborted calls. | | `StepEnd` | After a step's model call and tool executions (`Usage`, `Err`). | | `RunEnd` | Always the final event (`Response`, `Err`); `Response` may be non-nil on budget limits. | Sinks must not block indefinitely in `Emit`; forward to a buffered channel or asynchronous queue when doing slow I/O. Because the runner isolates panics per sink, a panicking user sink never stops the internal `Run.Events()` stream from receiving `RunEnd`. ## Wrapping seams for metrics Policies decide and sinks observe. For latency histograms, token accounting, OpenTelemetry spans, or persistence error counters, wrap `llm.Model`, `tool.Tool`, or `session.Store` directly—see [Extending Gojent](/docs/guides/extending) for a concrete wrapper pattern and [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Event) for all event structs. --- Source: https://gojent.com/docs/modules/tools Markdown: https://gojent.com/docs/modules/tools.md Section: Modules Package: https://pkg.go.dev/github.com/ijaidev/gojent/tools --- # Ready-Made Tools The root `tools` package and its subpackages (`tools/fs`, `tools/exec`, `tools/subagent`, `tools/web`, `tools/task`) ship ready-made, standard-library-only `tool.Tool` implementations for local workspaces, managed subagent lifecycles, web retrieval, and planning. Filesystem and command tools support symlink-resolved root containment, command tools can promote long-running processes to the background, and subagent tools manage multi-turn delegation with optional git-worktree isolation. ## Wire up the standard tool sets Construct tool sets with explicit root directories and close managed command runners when finished: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/tools" "github.com/ijaidev/gojent/tools/exec" "github.com/ijaidev/gojent/tools/fs" "github.com/ijaidev/gojent/tools/web" ) func main() { fsTools, err := tools.StandardFilesystemTools(fs.Config{BaseDir: "/workspace"}) if err != nil { log.Fatal(err) } webTools, err := tools.StandardWebTools(web.FetchConfig{}) if err != nil { log.Fatal(err) } managedExec, err := tools.NewExecTools(exec.ManagerConfig{BaseDir: "/workspace"}) if err != nil { log.Fatal(err) } defer func() { _ = managedExec.Close(context.Background()) }() execTools := managedExec.All() tracker, taskTools, err := tools.StandardTaskTools() if err != nil { log.Fatal(err) } fmt.Println(len(fsTools), len(webTools), len(execTools), len(taskTools), tracker != nil) } ``` ## Filesystem sandboxing and search (`tools/fs`) `tools.StandardFilesystemTools` returns four core tools: `read_file`, `write_file`, `edit_file`, and `list_files`. For bounded, standard-library-only file-name and content search, also register `fs.NewGlobFilesTool` and `fs.NewGrepFilesTool`: - **Root containment:** When `BaseDir` or `AdditionalDirs` is configured, relative paths resolve against `BaseDir`, and every read, write, edit, list, glob, and grep access is verified **after symlink resolution** against all configured roots so a symlinked entry cannot escape the sandbox. - **Annotations:** Inspection tools (`read_file`, `list_files`, `glob_files`, `grep_files`) are annotated `ReadOnly: true, Idempotent: true`, whereas `write_file` and `edit_file` are annotated `Destructive: true`. ## Managed command execution (`tools/exec`) `tools.NewExecTools(exec.ManagerConfig{...})` creates a process `Manager` and exposes five tools (`execute_command`, `process_status`, `read_process_output`, `wait_process`, and `kill_process`): - **Foreground-to-background promotion:** `execute_command` waits up to the foreground timeout (default 30 seconds), then promotes a still-running command to the background instead of killing it. Pass `background: true` in the tool call to start in the background immediately. - **Opaque process handles:** Background processes are referenced by opaque handles rather than raw OS PIDs. Always call `managedExec.Close(ctx)` to terminate remaining processes on shutdown. - **Working directory containment and host permissions:** `ManagerConfig.BaseDir` and `ManagerConfig.AdditionalDirs` constrain working directories after symlink resolution (even when `BaseDir` is empty). However, commands execute with the host user's OS permissions—always gate command tools with an [agent.Policy and Approver](/docs/core/policies) before exposing them to a model. - **Live observer without polling:** Set `ManagerConfig.Observer` (`exec.ProcessObserver`) to receive synchronous `start`, copied stdout/stderr `output`, and `exit` `ProcessEvent` values. Observer panics are recovered so they never disrupt buffered reads or manager shutdown. - **Foreground-only alternative:** `tools.StandardExecTools(exec.Config{...})` remains available when you only want a single synchronous `execute_command` tool without background process management. ## Managed subagent lifecycle (`tools/subagent`) `tools.NewSubagentTools(subagent.ManagerConfig{...})` builds a `*subagent.Manager` from registered `subagent.Profile` definitions and exposes six lifecycle tools (`subagent_spawn`, `subagent_send`, `subagent_wait`, `subagent_status`, `subagent_cancel`, and `subagent_cleanup`), plus `subagent_define` when `ManagerConfig.Dynamic != nil`: - **Sync, background, and timeout promotion:** `subagent_spawn` and `subagent_send` can wait for turn completion, start immediately in the background (`background: true`), or wait up to `wait_seconds` (or `ManagerConfig.DefaultForegroundWait`) before promoting the active subagent to background (`Snapshot.Promoted`). - **Multi-turn resume and bounded waits:** `subagent_send` preserves child conversation history in `ManagerConfig.Store` (defaulting to `session.NewMemory()`), queuing follow-up prompts if the child is running or starting a new turn if idle. `subagent_wait` waits for `"all"` (default) or `"any"` subagent IDs up to `timeout_seconds` (capped by `ManagerConfig.MaxWait`, default 5 minutes) and returns `WaitResult` cleanly on timeout (`TimedOut: true`). - **Cascading cancellation and cleanup:** `subagent_cancel` cancels a subagent and recursively cancels all descendants; always call `subTools.Close(ctx)` on shutdown to stop active workers. - **Git worktree isolation:** Attach `subagent.NewGitWorktreeProvider(subagent.GitWorktreeConfig{RepoDir: ...})` as `ManagerConfig.Workspace` to run `subagent.WorkspaceWorktree` profiles in isolated git worktrees and temporary branches, report dirty/ahead status via `Inspect`, and remove retained worktrees with `subagent_cleanup`. - **Opt-in capability-attenuated `DynamicConfig`:** Setting `ManagerConfig.Dynamic` enables `subagent_define` (`Manager.Define`) while failing closed (`subagent.ErrCapabilityDenied`) whenever a requested tool, `AllowWorktree`, `AllowNested`, or `MaxBudget` exceeds the configured ceiling (`MaxProfiles` defaults to 16). ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/core/llm" "github.com/ijaidev/gojent/providers/mockllm" "github.com/ijaidev/gojent/tools" "github.com/ijaidev/gojent/tools/subagent" ) func main() { ctx := context.Background() subTools, err := tools.NewSubagentTools(subagent.ManagerConfig{ DefaultModel: mockllm.New("Subagent findings confirmed."), Profiles: []subagent.Profile{ { Name: "explorer", Description: "Read-only researcher", Instructions: "Inspect and summarize concisely.", Workspace: subagent.WorkspaceInherit, }, }, Dynamic: &subagent.DynamicConfig{ MaxProfiles: 4, MaxBudget: agent.Budget{MaxSteps: 4}, }, }) if err != nil { log.Fatal(err) } defer func() { _ = subTools.Close(ctx) }() turn := 0 leadModel := mockllm.New().ApplyOptions( mockllm.WithCustomStreamHandler(func(ctx context.Context, _ *llm.Request) (llm.Stream, error) { turn++ if turn == 1 { return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewToolCallPart(llm.ToolCall{ CallID: "s1", Name: "subagent_spawn", Input: []byte(`{"profile":"explorer","prompt":"Check status."}`), })}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonTool}, }), nil } return llm.NewSliceStream(ctx, []llm.StreamEvent{ llm.MessageStart{Model: "mock-llm"}, llm.PartStart{Index: 0, Part: llm.NewTextPart("")}, llm.PartDelta{Index: 0, Kind: llm.PartTypeText, Text: "Delegation complete."}, llm.PartEnd{Index: 0}, llm.MessageEnd{Status: llm.MessageStatusCompleted, FinishReason: llm.FinishReasonStop}, }), nil }), ) lead, err := agent.New(agent.Config{ Name: "lead", Model: leadModel, Tools: subTools.All(), }) if err != nil { log.Fatal(err) } resp, err := lead.Generate(ctx, "Delegate a quick check.") if err != nil { log.Fatal(err) } fmt.Println(resp.Text, "tools:", len(subTools.All())) } ``` ## Web and task tools (`tools/web`, `tools/task`) - **`tools.StandardWebTools` / `web.NewWebSearchTool`:** Provides `web_fetch` (bounded HTTP fetch with optional HTML-to-text extraction) and `web_search` backed by your `web.SearchProvider` implementation. - **`tools.StandardTaskTools`:** Returns an in-memory, thread-safe `*task.Tracker` and `task_create`, `task_list`, and `task_update` tools for multi-step agent planning. Browse the full `tools` API on [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/tools). --- Source: https://gojent.com/docs/modules/providers Markdown: https://gojent.com/docs/modules/providers.md Section: Modules Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/llm --- # Model Providers Gojent ships provider adapters in isolated child Go modules so vendor SDK dependencies stay out of the root module. Every adapter implements `llm.Model` and `llm.Streamer`, reports capabilities through `llm.Info`, classifies failures as `*llm.Error` with `llm.Kind`, and rejects unsupported options with `llm.ErrUnsupported`. ## Available providers | Provider | Module | Constructor | Default Env Credentials | | --- | --- | --- | --- | | Google Gemini | `providers/google` | `google.New` | `GEMINI_API_KEY` or `GOOGLE_API_KEY` | | OpenAI Responses | `providers/openai` | `openai.New` | `OPENAI_API_KEY` | | OpenAI Chat Completions | `providers/openai` | `openai.NewChatCompletion` | `OPENAI_API_KEY` | | Anthropic Messages | `providers/anthropic` | `anthropic.New` | `ANTHROPIC_API_KEY` | | Deterministic mock | `providers/mockllm` | `mockllm.New` | None (root module) | ```go package main import ( "context" "fmt" "log" "os" "github.com/ijaidev/gojent/core/llm" "github.com/ijaidev/gojent/providers/anthropic" "github.com/ijaidev/gojent/providers/google" "github.com/ijaidev/gojent/providers/openai" ) func main() { ctx := context.Background() gemini, err := google.New(ctx, google.Config{ Model: "gemini-2.5-flash", APIKey: os.Getenv("GEMINI_API_KEY"), }) if err != nil { log.Fatal(err) } gpt, err := openai.New(ctx, openai.Config{ Model: "gpt-5", APIKey: os.Getenv("OPENAI_API_KEY"), }) if err != nil { log.Fatal(err) } claude, err := anthropic.New(ctx, anthropic.Config{ Model: "claude-sonnet-4-5", APIKey: os.Getenv("ANTHROPIC_API_KEY"), }) if err != nil { log.Fatal(err) } models := []llm.Model{gemini, gpt, claude} for _, m := range models { fmt.Println(m.Info().Provider, m.ModelID()) } } ``` ## Headers, dynamic per-call headers, and custom endpoints Every provider adapter accepts static `Headers` and dynamic `HeaderFunc` on its `Config`: - **Static `Headers`:** Copied at construction so mutating your `http.Header` map later does not alter the model. - **Dynamic `HeaderFunc`:** `func(ctx context.Context) (http.Header, error)` runs once per `Generate` or `Stream` call after request validation and before network I/O. Returned values override static `Headers` with the same name, making it safe to inject per-run correlation or session headers derived from `ctx`. - **Custom base URLs and clients:** `openai.Config` and `openai.ChatCompletionConfig` accept `BaseURL` (for OpenAI-compatible gateways, proxies, or local servers such as Ollama/LM Studio) or a custom `*openai.Client`; `anthropic.Config` accepts `BaseURL` or `*anthropic.Client`; `google.Config` accepts `ClientConfig` (including Vertex AI settings or HTTP options) or a pre-configured `*genai.Client`. ## Capabilities and error classification Capabilities are explicit rather than silently ignored: - **`llm.Info`:** Inspect `model.Info().Features` to check `Streaming`, `Tools`, `ParallelToolCalls`, `StrictJSONSchema`, `Reasoning`, `Vision`, `AudioIn`, `Video`, `Documents`, and `PromptCaching` before sending a request. - **`llm.ErrUnsupported`:** When a request asks for something an adapter cannot honor (for example `StrictJSONSchema` on Anthropic, stop sequences on OpenAI Responses, or server-state IDs on stateless adapters), the adapter returns `llm.ErrUnsupported`. - **`*llm.Error` and `llm.Kind`:** Provider failures are classified into `KindAuth`, `KindRateLimit`, `KindOverloaded`, `KindInvalid`, `KindContextOverflow`, `KindSafety`, `KindTimeout`, `KindCanceled`, or `KindProvider`. Check `llm.AsError(err)` or `err.Kind` instead of matching vendor error strings; `RetryPolicy` uses `(*llm.Error).Retryable()` automatically. See [Extending Gojent](/docs/guides/extending) to build and test a custom `llm.Model`, or inspect `core/llm` on [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/llm). --- Source: https://gojent.com/docs/modules/stores Markdown: https://gojent.com/docs/modules/stores.md Section: Modules Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/session --- # Session Stores Gojent separates persistence backends into isolated child modules (`stores/sqlite`, `stores/postgres`) while keeping `session.Memory` in `core/session`. Every store implements the same two-method `session.Store` contract (`Load` and atomic `Append`) with strict `ResourceID` tenant isolation. ## Choose a store backend | Store | Package | Use Case | Build / Driver Notes | | --- | --- | --- | --- | | In-memory | `core/session` (`session.NewMemory`) | Unit tests, ephemeral CLI runs | Stdlib-only (root module) | | SQLite | `stores/sqlite` (`sqlite.New`) | Local durable agents, embedded apps | Uses `mattn/go-sqlite3`; **requires CGO enabled** | | PostgreSQL | `stores/postgres` (`postgres.New`) | Multi-instance services | Uses `lib/pq` (or `NewWithDB` for an existing `*sql.DB`) | ## SQLite store (`stores/sqlite`) Install the module with `go get github.com/ijaidev/gojent/stores/sqlite`. Because `stores/sqlite` wraps `github.com/mattn/go-sqlite3`, ensure a C compiler is available and `CGO_ENABLED=1` at build time: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/providers/mockllm" "github.com/ijaidev/gojent/stores/sqlite" ) func main() { ctx := context.Background() // Use "file:gojent.db" on disk or ":memory:" for ephemeral SQLite storage. store, err := sqlite.New(":memory:") if err != nil { log.Fatal(err) } defer func() { _ = store.Close() }() assistant, err := agent.New(agent.Config{ Name: "assistant", Model: mockllm.New("Restored from SQLite."), Store: store, }) if err != nil { log.Fatal(err) } response, err := assistant.Generate(ctx, "Continue where we left off.", agent.WithSession("thread-1", "user-1"), ) if err != nil { log.Fatal(err) } fmt.Println(response.Text) } ``` `sqlite.New` automatically enables WAL mode (for file-backed databases), configures a 5-second busy timeout by default (`sqlite.WithBusyTimeout`), and runs schema migration (`sqlite.WithAutoMigrate(false)` disables auto-migration). ## PostgreSQL store (`stores/postgres`) Install with `go get github.com/ijaidev/gojent/stores/postgres`. Use `postgres.New(dsn, opts...)` to open and migrate a connection pool, or `postgres.NewWithDB(db, opts...)` to share an existing `*sql.DB` handle: ```go package main import ( "context" "database/sql" "fmt" "github.com/ijaidev/gojent/core/session" "github.com/ijaidev/gojent/stores/postgres" ) func openPostgresStore(ctx context.Context, db *sql.DB) (session.Store, error) { store, err := postgres.NewWithDB(db, postgres.WithAutoMigrate(false)) if err != nil { return nil, err } if err := store.Migrate(ctx); err != nil { return nil, err } return store, nil } func main() { fmt.Println(postgres.DefaultDriverName) _ = openPostgresStore } ``` Verify custom store implementations against Gojent's conformance suite in `core/session/sessiontest`—see [Extending Gojent](/docs/guides/extending) and [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/session). --- Source: https://gojent.com/docs/modules/mcp Markdown: https://gojent.com/docs/modules/mcp.md Section: Modules Package: https://pkg.go.dev/github.com/ijaidev/gojent/mcp --- # MCP Client The `mcp` module (`github.com/ijaidev/gojent/mcp`) is a client-only adapter that connects Gojent applications to Model Context Protocol (MCP) servers over stdio or Streamable HTTP and exposes their tools as standard `tool.Tool` values. It never serves MCP itself, and your configured `agent.Policy` and `agent.Approver` remain the final authority for every tool call. ## Connect a stdio server and register tools Install the module with `go get github.com/ijaidev/gojent/mcp`. Configure servers with `mcp.ServerConfig`, connect once with `client.Connect`, inspect `ServerStatus`, and pass `client.Tools()` into `agent.Config.Tools`: ```go package main import ( "context" "fmt" "log" "github.com/ijaidev/gojent/core/agent" "github.com/ijaidev/gojent/mcp" "github.com/ijaidev/gojent/providers/mockllm" ) func connectStdioMCP(ctx context.Context) error { client := mcp.New() defer func() { _ = client.Close() }() statuses, err := client.Connect(ctx, []mcp.ServerConfig{{ Name: "workspace", Command: "my-mcp-server", Args: []string{"--root", "/workspace"}, Env: []string{"WORKSPACE=/workspace"}, AllowedTools: []string{"read_file", "search"}, DeniedTools: []string{"write_file"}, }}) if err != nil { return err } for _, status := range statuses { if status.Status != mcp.StatusConnected { return status.Err } } mcpTools, err := client.Tools() if err != nil { return err } assistant, err := agent.New(agent.Config{ Name: "mcp-agent", Model: mockllm.New("Ready."), Tools: mcpTools, }) if err != nil { return err } resp, err := assistant.Generate(ctx, "List workspace files.") if err != nil { return err } fmt.Println(resp.Text) return nil } func main() { if err := connectStdioMCP(context.Background()); err != nil { log.Fatal(err) } } ``` ### Naming, filtering, origin lookup, and instructions - **Minimal child environment:** `Env` is the complete allowlist passed to a stdio child process (plus a small platform minimum); no other host environment variables leak into the subprocess. - **Tool filtering and collision checks:** `AllowedTools` and `DeniedTools` match the server's declared MCP tool names before normalization (empty `AllowedTools` permits all tools; `DeniedTools` wins over `AllowedTools`). Surviving tools are normalized to `_` using ASCII normalization, and collisions fail with `mcp.ErrToolNameCollision` before any model call. - **Exact origin recovery:** `client.ToolOrigin(name)` returns the exact configured `serverName` and raw MCP tool name for any normalized tool in `client.Tools()`, tracking live refreshes and reconnects without string splitting. - **Server instructions:** `client.Instructions()` exposes each server's initialization instructions to your host application; Gojent never injects untrusted server instructions into an agent's system prompt automatically. - **Advisory annotations & schema passthrough:** MCP tool annotations map onto advisory `tool.Annotations`, but Gojent's `Policy` and `Approver` remain the final gate. MCP servers validate their own input schemas rather than using Gojent's struct-tag schema subset. ## Streamable HTTP, AuthHook, and SSRF protections Replace `Command` with `URL` to connect a Streamable HTTP server, optionally adding static `Headers`, a custom `HTTPClient`, or an `AuthHook`: ```go package main import ( "context" "log" "net/http" "github.com/ijaidev/gojent/mcp" ) type tokenAuth struct{ token string } func (a tokenAuth) Apply(_ context.Context, req *http.Request) error { req.Header.Set("Authorization", "Bearer "+a.token) return nil } func (a tokenAuth) Challenge(_ context.Context, _ *http.Request, _ *http.Response) error { return mcp.ErrAuthRequired } func connectHTTPMCP(ctx context.Context, apiKey string) (*mcp.Client, []mcp.ServerStatus, error) { client := mcp.New() statuses, err := client.Connect(ctx, []mcp.ServerConfig{{ Name: "remote", URL: "https://mcp.example.com/mcp", Headers: map[string]string{"X-API-Key": apiKey}, Auth: tokenAuth{token: "secret-token"}, }}) if err != nil { _ = client.Close() return nil, nil, err } return client, statuses, nil } func main() { client, statuses, err := connectHTTPMCP(context.Background(), "api-key") if err != nil { log.Fatal(err) } defer func() { _ = client.Close() }() for _, status := range statuses { if status.Status != mcp.StatusConnected { log.Fatal(status.Err) } } if _, err := client.Tools(); err != nil { log.Fatal(err) } } ``` Security and transport guarantees on HTTP servers: - **HTTPS and redirect rules:** Plain `http://` is accepted only for loopback hosts. Scheme changes and non-loopback cross-origin redirects are refused before forwarding headers or bodies; loopback-to-loopback redirects remain allowed with credential headers stripped. A custom `HTTPClient` owns its own redirect and SSRF policy. - **`AuthHook` and credential redaction:** `AuthHook.Apply` runs on every request and `AuthHook.Challenge` handles HTTP `401`/`403` to refresh and retry once; unobtainable credentials report `mcp.StatusAuthRequired`. The adapter never logs or returns header values, and HTTP errors (including `*url.Error`) redact userinfo, query parameters, and fragments while preserving `errors.Is`/`errors.As` inspection. ## Timeouts, result caps, elicitation, and live refresh - **`Timeouts` and `MaxResultBytes`:** `ServerConfig.Timeouts` bounds `Connect` (default `30s`), `Catalog` (`30s`), and `Call` (`2m`); negative values disable individual deadlines, while the caller's `ctx` remains an upper bound. `MaxResultBytes` (default `mcp.DefaultMaxResultBytes`, 4 MiB) caps combined text, file data, file metadata, and structured payloads delivered to the model, truncating at UTF-8 boundaries and appending `mcp.TruncationMarker`. `isError` responses surface as tool errors. - **Elicitation (`WithElicitationHandler`):** Servers requesting host form or URL input during a tool call invoke your `ElicitationHandler` up to bounded rounds; declining, canceling, or omitting a handler declines immediately without blocking and surfaces a tool error. - **Catalog refresh & `Reconnect`:** Register `mcp.WithCatalogChangeHandler` to react to server `tools`, `resources`, or `prompts` list-changed notifications. A running `*agent.Agent` retains the tools it was constructed with; rebuild new agents/runs from `client.Tools()` when notified. Call `client.Reconnect(ctx, serverName)` to replace one server's session cleanly without disrupting other connected servers. ```go package main import ( "log" "github.com/ijaidev/gojent/mcp" ) func main() { client := mcp.New(mcp.WithCatalogChangeHandler(func(change mcp.CatalogChange) { if change.Err != nil { log.Printf("%s %s refresh failed: %v", change.Server, change.Kind, change.Err) return } // Rebuild future runs using client.Tools(), client.Resources(), or client.Prompts(). })) defer func() { _ = client.Close() }() } ``` ## Resources and prompts host APIs Resources and prompts are **host APIs**, never model tools. Lists follow pagination automatically, `ReadResource` maps payloads to `llm.TextPart` and `llm.FilePart`, and `GetPrompt` returns `llm.Message` slices ready to pass to `(*agent.Agent).GenerateMessages` or `StreamMessages`: ```go package main import ( "context" "github.com/ijaidev/gojent/mcp" ) func loadHostContext(ctx context.Context, client *mcp.Client) error { resources, err := client.Resources(ctx, "workspace") if err != nil { return err } if len(resources) > 0 { contents, err := client.ReadResource(ctx, "workspace", resources[0].URI) if err != nil { return err } // contents[*].Part is an llm.TextPart or llm.FilePart. _ = contents } templates, err := client.ResourceTemplates(ctx, "workspace") if err != nil { return err } _ = templates prompts, err := client.Prompts(ctx, "workspace") if err != nil { return err } if len(prompts) > 0 { prompt, err := client.GetPrompt(ctx, "workspace", prompts[0].Name, map[string]string{"topic": "Go"}) if err != nil { return err } // Pass prompt.Messages to (*agent.Agent).GenerateMessages. _ = prompt } return nil } func main() { _ = loadHostContext } ``` See the runnable demo in [`mcp/examples/stdio`](https://github.com/ijaidev/gojent/tree/main/mcp/examples/stdio) and full Go documentation on [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/mcp). --- Source: https://gojent.com/docs/modules/codjent Markdown: https://gojent.com/docs/modules/codjent.md Section: Modules Package: https://pkg.go.dev/github.com/ijaidev/gojent/codjent --- # Codjent Sample App Codjent (`github.com/ijaidev/gojent/codjent`) is an ACP-first local coding agent built on the Gojent runtime to exercise the loop, typed tools, MCP client, policies, managed subagents, and persistence end to end. **Codjent is a sample application, not a supported product**—it omits authentication, multi-tenant isolation, and hosted deployment features, and exists as a concrete reference you can inspect or copy from. ## Install and run Codjent lives in its own Go module (`codjent/`) and requires Go 1.25 or newer: ```bash go install github.com/ijaidev/gojent/codjent/cmd/codjent@latest codjent # open the Bubble Tea provider & model manager TUI codjent acp # serve ACP v2 over stdio for external clients such as T3 Code ``` Or run directly from a repository checkout: ```bash just --justfile codjent/justfile run # interactive provider manager TUI just --justfile codjent/justfile acp # ACP v2 stdio server ``` On first run, press `a` in the TUI to configure a provider preset (or `c` for a custom OpenAI/Anthropic-compatible endpoint), paste an API key, review pre-selected models, and press `Ctrl+S` to save to SQLite. For backwards compatibility, setting `GEMINI_API_KEY` or `GOOGLE_API_KEY` seeds a Google provider automatically. ## Key capabilities - **Bubble Tea provider & model manager (`codjent`):** Embedded preset and model catalog from `models.dev` and OpenRouter (OpenAI Responses/Chat Completions, Anthropic, Google Gemini, OpenRouter, OpenCode, DeepSeek, Groq, xAI, Mistral, Ollama, LM Studio), live `/models` discovery (`Ctrl+F`), manual model entry (`Ctrl+A`), masked write-only keys, static/dynamic custom headers, and cross-process SQLite catalog sync (`PRAGMA data_version`). - **ACP v2 stdio server (`codjent acp`):** Newline-delimited JSON-RPC 2.0 over stdin/stdout (diagnostics on stderr) supporting `initialize`, `session/new`, `session/set_config_option`, `session/prompt` (text, PNG/JPEG/WebP images, resources), `session/cancel`, `session/list`, `session/resume`, `session/fork`, `session/delete`, and `session/close`. - **Workspace tools & approvals:** Sandboxed filesystem read/write/edit/list/glob/grep tools, foreground-to-background `execute_command` with live output streaming (`terminal_update` / `terminal_output_chunk`), client-supplied stdio/HTTP MCP servers, workspace skills (`/.agents/skills/*/SKILL.md`), `/compact` summarization, and `session/request_permission` approval gates with inline diffs. ## Subagents, thread lineage, and ACP v2 sessions Every root session in `codjent acp` wires a session-scoped `tools/subagent` host backed by SQLite thread persistence: - **Persisted thread lineage:** An additive, idempotent SQLite migration adds `parent_thread_id`, `subagent_profile`, `subagent_description`, and `subagent_branch` (indexed by `idx_threads_parent`) to `threads`. Child threads are omitted by default from top-level listings (`session/list`, `ListThreads`), and `session/delete` (`DeleteThread`) recursively deletes all descendant threads and messages in SQLite. - **Built-in profiles and dynamic definition:** Codjent defines two built-in Go profiles—`explorer` (read-only `read_file`, `list_files`, `glob_files`, `grep_files`, `AllowNested: false`) and `worker` (filesystem, search, and managed `exec` tools, `AllowNested: true`)—plus capability-attenuated runtime `subagent_define` capped at `worker` tools and 16 dynamic profiles per session. Workspace or home-directory agent files are **not** loaded. - **Git worktree isolation:** Subagents using `workspace: "worktree"` run inside isolated git worktrees and temporary branches via `subagent.GitWorktreeProvider` (keeping `additionalDirectories` isolated), with per-worktree `exec` managers closed on session shutdown and `subagent_cleanup` gated in `ask` mode. - **Native ACP v2 subagent sessions:** - Child sessions are announced to their immediate parent via `subagent_update` before child updates or tool links, receive prompts via `session_message`, and are linked from `subagent_spawn`/`subagent_send`/`subagent_wait`/`subagent_status`/`subagent_cancel` tool results via `type: "session"` content items (both live and during `session/resume` `replayFrom: "start"`). - Clients can cancel an active child session directly with `session/cancel`, while client-initiated `session/prompt`, `session/resume`, `session/fork`, `session/delete`, `session/close`, and `session/set_config_option` targeting a child session are rejected with JSON-RPC `-32602`. - Under `ask` mode, mutating tool calls inside child and nested grandchild runs trigger `session/request_permission` on the child's `sessionId` while inheriting parent/ancestor `plan` mode blocks and session-memory rejections. ## Internal layout and configuration Codjent follows the same one-way dependency rules as the rest of Gojent: - `codjent/internal/app`: Thread/run lifecycle, approval gate, subagent host (`NewSessionSubagents`), event log, and transcript persistence contract. - `codjent/internal/store/sqlite`: `app.Store` and provider catalog persistence (using `modernc.org/sqlite`). - `codjent/internal/provider`: Provider seam, SQLite-backed dynamic catalog, and embedded/cached presets. - `codjent/internal/acp`: Stdlib-only ACP v2 stdio server calling `app`, never imported by `app` or `tui`. - `codjent/internal/tui`: Bubble Tea UI, never imported by `app` or `acp`. Environment variables such as `CODJENT_DATA_DIR`, `CODJENT_WORKSPACE`, `CODJENT_PROVIDER`, `CODJENT_MODEL`, `CODJENT_ACCESS_MODE`, and `CODJENT_MAX_STEPS` configure defaults; see [`codjent/README.md`](https://github.com/ijaidev/gojent/blob/main/codjent/README.md) for the full variable table and ACP command flags. --- Source: https://gojent.com/docs/guides/extending Markdown: https://gojent.com/docs/guides/extending.md Section: Guides Package: https://pkg.go.dev/github.com/ijaidev/gojent/core/llm --- # Extending Gojent Gojent keeps its execution loop private and opens four small interfaces at the seams (`llm.Model`/`llm.Streamer`, `tool.Tool`, `session.Store`, and `agent.Policy`/`Approver`/`Sink`). You can plug in custom model backends, durable storage engines, and cross-cutting middleware without modifying core code, then prove compatibility with the built-in `llmtest` and `sessiontest` conformance suites. ## Implement a custom model A model adapter implements three methods on `llm.Model`, and optionally adds `llm.Streamer` for incremental streaming: ```go no-compile type Model interface { ModelID() string Info() Info Generate(ctx context.Context, req *Request) (*Response, error) } type Streamer interface { Model Stream(ctx context.Context, req *Request) (Stream, error) } ``` Keep `Info()` accurate: the runner inspects `Info().Features` before building requests instead of probing for optional behavior, and adapters must return `llm.ErrUnsupported` when asked for a capability they do not support. Verify any custom `llm.Model` with [`core/llm/llmtest`](https://pkg.go.dev/github.com/ijaidev/gojent/core/llm/llmtest), which checks context cancellation and verifies that `Generate` and `Stream` agree on text, reasoning, tool calls, usage, and finish reasons: ```go package custommodel_test import ( "testing" "github.com/ijaidev/gojent/core/llm" "github.com/ijaidev/gojent/core/llm/llmtest" "github.com/ijaidev/gojent/providers/mockllm" ) func TestCustomModelConformance(t *testing.T) { llmtest.Run(t, func(_ *testing.T) llm.Model { return mockllm.New("conformance response") }, llmtest.Case{ Name: "BasicText", Request: &llm.Request{Messages: []llm.Message{llm.UserMessage("hello")}}, Text: "conformance response", FinishReason: llm.FinishReasonStop, }) } ``` ## Implement a custom session store Implement `Load` and atomic `Append` on `session.Store`: return messages in chronological order, isolate conversations by both `ID` and `ResourceID`, and deep-copy values if your backend reuses buffers. Verify your implementation against [`core/session/sessiontest`](https://pkg.go.dev/github.com/ijaidev/gojent/core/session/sessiontest), which tests empty sessions, chronological ordering, tenant isolation, atomic batch appends, replay state survival, session validation, and context cancellation: ```go package customstore_test import ( "testing" "github.com/ijaidev/gojent/core/session" "github.com/ijaidev/gojent/core/session/sessiontest" ) func TestCustomStoreConformance(t *testing.T) { sessiontest.Run(t, func(t *testing.T) session.Store { s := session.NewMemory() t.Cleanup(func() { _ = s.Close() }) return s }) } ``` ## Wrap seams for middleware Instead of adding framework hooks to the core loop, compose behavior by wrapping `llm.Model`, `tool.Tool`, or `session.Store`: ```go package middleware import ( "context" "log" "time" "github.com/ijaidev/gojent/core/llm" ) type loggingModel struct { next llm.Model } func (m loggingModel) ModelID() string { return m.next.ModelID() } func (m loggingModel) Info() llm.Info { return m.next.Info() } func (m loggingModel) Generate(ctx context.Context, req *llm.Request) (*llm.Response, error) { start := time.Now() resp, err := m.next.Generate(ctx, req) log.Printf("model=%s duration=%s err=%v", m.next.ModelID(), time.Since(start), err) return resp, err } ``` If the wrapped model also supports streaming, implement `llm.Streamer` on the wrapper (or delegate conditionally) so streaming runs continue to stream incrementally. See [core/llm](https://pkg.go.dev/github.com/ijaidev/gojent/core/llm) and [core/session](https://pkg.go.dev/github.com/ijaidev/gojent/core/session) on `pkg.go.dev`. --- Source: https://gojent.com/docs/guides/development Markdown: https://gojent.com/docs/guides/development.md Section: Guides --- # Development & Releases Gojent is structured as a multi-module Go repository with a standard-library-only root module and independent child modules for providers, durable stores, MCP, and `codjent`. Development relies on `just` recipes that delegate across every module and enforce formatting, tidiness, linting, dependency boundaries, and compiled documentation snippets. ## Local workspace setup Go **1.25.5** or newer and `just` **1.58** or newer are required. `go.work` and `go.work.sum` are intentionally untracked; initialize your local workspace once after cloning: ```bash just workspace ``` ## Repository checks and module recipes Run root recipes to check the entire workspace, or target a single module with `just --justfile /justfile `: ```bash just test # unit tests with -race across all modules just vet # go vet across all modules just build # go build across all modules just lint # golangci-lint across all modules just arch-check # verify root stdlib-only and one-way module boundaries just doc-check # compile all Go snippets in docs/ and README.md just tidy # go mod tidy across all modules just check # fmt-check, tidy-check, vet, build, lint, arch-check, test, scripts-test ``` Run a single module's test suite during focused work: ```bash just --justfile providers/google/justfile test just --justfile mcp/justfile test ``` The PostgreSQL conformance and integration suite is opt-in against a running PostgreSQL instance: ```bash GOJENT_POSTGRES_DSN='postgres://postgres:postgres@localhost:5432/gojent_test?sslmode=disable' \ just --justfile stores/postgres/justfile test-integration ``` For the documentation website under `site/`, run `just --justfile site/justfile install` and `just --justfile site/justfile check`. ## Versioning and submodule tags The root module and every child module are versioned independently: - Tag the root module as `vX.Y.Z`. - Tag child modules with their directory prefix so `go get` resolves them cleanly: - `mcp/vX.Y.Z` - `providers/google/vX.Y.Z`, `providers/openai/vX.Y.Z`, `providers/anthropic/vX.Y.Z` - `stores/sqlite/vX.Y.Z`, `stores/postgres/vX.Y.Z` - `codjent/vX.Y.Z` Optional modules declare a released root module version in their `go.mod`. Whenever the root core API changes, bump that `go.mod` requirement and tidy dependent modules before tagging them so downstream consumers do not resolve an older core. Gojent is currently in **beta (`v0.x`)**: until `v1.0.0`, minor versions may introduce breaking changes, called out explicitly in each module's `CHANGELOG.md`. ## Changelog and release automation - Maintain user-facing release notes under `## Unreleased` in the touched module's `CHANGELOG.md` (`CHANGELOG.md` for root, `mcp/CHANGELOG.md`, `providers/*/CHANGELOG.md`, `stores/*/CHANGELOG.md`, `codjent/CHANGELOG.md`). - Tag pushes for released modules generate draft GitHub Releases from the matching changelog section—see [`CONTRIBUTING.md`](https://github.com/ijaidev/gojent/blob/main/CONTRIBUTING.md) for the complete release checklist.