dive
CLAUDE.md133 starsChanged 3 months agoApache-2.0View on GitHub
Dive is a Go library for building AI agents and integrating with leading LLMs. Library-first approach — the CLI in experimental/cmd/dive/ is secondary.
In this repositoryOne other file it gives its agents.
- llms.txtllms.txt
The file
We split this CLAUDE.md into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 12
Use github.com/deepnoodle-ai/wonton/assert for all tests
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
Project Overview
Dive is a Go library for building AI agents and integrating with leading LLMs.
Library-first approach — the CLI in experimental/cmd/dive/ is secondary.
Commands
go test ./...— Run all testscd experimental/cmd/dive && go build— Build the CLI (optional)- Use
github.com/deepnoodle-ai/wonton/assertfor all tests
Architecture
Core Types
- Agent (
agent.go): Created viaNewAgent(AgentOptions), returns*Agent. Manages tool execution and conversation. - Extension (
agent.go):Extensioninterface (Tools,Hooks,Rules) for composable agent capabilities. Set onAgentOptions.Extensions. Extensions provide tools, hooks, and system prompt rules that are merged duringNewAgent. - Session (
dive.go):Sessioninterface (ID,Messages,SaveTurn). Set onAgentOptions.Sessionor per-call viaWithSession. Thesessionpackage providesNew()(in-memory) and store-backed implementations. - LLM (
llm/llm.go):LLMandStreamingLLMinterfaces abstract over providers. - Tool (
tool.go):ToolandTypedTool[T]interfaces.FuncTool[T]()creates tools from functions with auto-generated schemas.Toolsetinterface provides dynamic tool resolution per LLM request. Tool panics are auto-recovered. All toolkit constructors return*dive.TypedToolAdapter[T](satisfiesdive.Tool).ToolDeclarer(DeclaredTools) marks a provider-defined toolset such asanthropic.ComputerToolset: calls route to the declared tools by name, which are left out of the request while the declarer is present.ToolAnnotations.HaltsBatch(automatic for calls withToolsetName) runs a batch in order and answers later halting calls after a failure with an error,ToolCallResult.Error == ErrBatchHalted. - Hooks (
hooks.go):Hooksstruct groups hook slices onAgentOptions. Hook types:SessionStartHook,PreGenerationHook,PostGenerationHook,PreToolUseHook,PostToolUseHook,PostToolUseFailureHook,StopHook,PreIterationHook,OnSuspendHook. All hooks receive*HookContext. PreToolUse hooks can setHookContext.UpdatedInputto rewrite the tool args.SessionStartHookfires once at the start of a fresh conversation (no prior messages, non-resume) and returns a*SessionStartResultto seed it (durable or ephemeral viaPersist). - Tracer (
tracer.go):Tracerinterface for observation (tracing, metrics, audit logging). Three methods (StartAgentRun,StartChat,StartToolCall) return(ctx, span); the agent threads ctx through downstream calls so spans nest naturally.NopTracer(default) andMultiTracerlive in core; the OpenTelemetry adapter isotel.NewTracerin thedive/otelmodule. - Turn outcome (
outcome.go,turn.go): once the turn begins (just before PreGeneration), every exit goes throughturn.end, which reads oneturnRecord. An error exit returns(resp, err)withStatus == ResponseStatusIncomplete,resp.Turn.Outcomeclassifying the error, anderrwrapping*GenerationError{Response: resp}; a failed partial resume returns(nil, err).Response.Turn(messages saved, usage, outcome or suspension,Persistence) is set for every status, andResponseItemTypeTurnEndedis the last item emitted. A tool batch that stops early (toolbatch.go) returns its partial batch;closeToolBatchanswers each call it did not finish as not run or unknown,Outcome.ToolCallsrecords their states, and a parallel call still running gets aBackgroundTaskHandlefor its late result.WithSoftCancel(softcancel.go) stops at the next step boundary. The loop reads each response's stop reason (llm.ClassifyStopReason): an output or context limit, a refusal, a provider stop and the iteration limit run no tool call, and a pause is resent. An incomplete turn is closed (closeturn.go: every call answered, aturn-incompletereminder whose details hold the outcome), passed toOnIncompleteTurnhooks and saved;WithContinuepicks it up;IncompleteTurns.Discardrestores the old error behaviour. Every turn has an ID (TurnID(ctx)), a status and per-call states onTurn; aTurnStoresession (Load,CheckpointTurn, revisions;session.Sessionis one, insession/turns.go) stores the record, and the agent saves through it in place of the other writes, folding aWithContinueinto the open turn.Agent.CancelSuspendedTurncloses a suspended turn without a model call.DurabilityOptions(durability.go) adds step checkpoints (arunningrecord at each model response and tool call; a turn found running on load is closed withprocess_exit) and session claims (SessionClaimer,session/claims.go) for several processes on one session. Design:docs/design/incomplete-turns.md. - Suspend/Resume (
tool.go,response.go,dive.go): A tool can pause the agent mid-turn by returningNewSuspendResult(prompt, metadata)orNewSuspendResultWithReason(prompt, reason, metadata)(setsToolResult.Suspend).SuspendReasonclassifies why:SuspendReasonInput(default) orSuspendReasonAuth.CreateResponsereturns(*Response, nil)withStatus == ResponseStatusSuspendedandResponse.Suspension *SuspensionState. Resume viaWithToolResults(session-backed) orWithResume(state, results)(stateless).SuspendableSessionis an optionalSessionextension for auto-persistence;Agent.CancelSuspendedTurncloses a suspended turn andsession.Session.RemoveLastTurndeletes one. A resent result already accepted is skipped (ErrConflictingToolResultif it differs);WithResumeRequestchecks the turn ID and revision first.OnSuspendhooks fire before persistence. Seedocs/guides/suspend-resume.md.
Packages
session/— Persistent conversation state:Sessionstruct (implementsdive.Session,dive.TurnStoreanddive.SessionClaimer),Storeinterface,MemoryStore,FileStore(step checkpoints appended assteplines, claims in{id}.claim), Fork (up to the last completed turn by default), Compact, Turns, RemoveLastTurn.providers/— LLM providers (Anthropic, OpenAI, Google, Grok, Mistral, Ollama, OpenRouter). Registry-based (providers/registry.go), self-registering viainit(). Shared encoder helpers inproviders/toolresult.go(ToolResultBlocks,ToolResultImageMediaType,LiftToolResultImages/LiftErrorToolResultImages) rewrite only the request, never the caller's history. Every encoder appliesllm.AnswerUnansweredToolCallsthe same way; adapters report raw stop reasons thatllm.ClassifyStopReasonmaps to anllm.StopKind.toolkit/— Built-in tools (Bash, ReadFile, WriteFile, Edit, Glob, Grep, ListDirectory, TextEditor, WebSearch, Fetch, AskUser).toolkit/orchestration/— Subagent spawning + background control, aligned with Claude Code's tool model:Agentspawns a subagent (EXECUTION);TaskStop/Monitortrack and cancel background runs (CONTROL).NewAgentTooltakes aSubagents map[string]*subagent.Definitionplus either aModel(uses the built-inDefaultAgentFactory) or anAgentFactory(the seam for worktree/session/sandbox/hooks/model policy). Background spawns + monitors register in a sharedRunstracker thatTaskStopcancels bytask_id. Subagents are single-use; background results arrive automatically (no polling tool). Seedocs/guides/subagents.md.subagent/— Subagent catalog:Definition(prompt, allowed/disallowed tools, model), built-in read-onlyExplore/PlanandGeneralPurpose,FilterTools, and aLoader(markdown + YAML frontmatter). Catalogs are plainmap[string]*Definition;DescribeTypes()renders the tool description.permission/— Rule-based tool permission management with modes, specifier patterns, and session allowlists.skill/— Unified skills and slash commands.skill.Loaderimplementsdive.Extension— pass it toAgentOptions.Extensionsto wire up the Skill tool, catalog hook, and content hook. Three-layer architecture: rules in system prompt, a typed contextual<system-reminder name="skills">prepended model-only as stable prompt-prefix context, and the Skill tool as a trigger with content via PostToolUseHook. Provider-based loading (filesystem,.agents/skills/), variable expansion, trigger matching. New integrations useReminder,WithModelOnlyReminder,NewReminderMessage, andHookContext.AppendReminder;SetSystemReminderis the legacy plain-text compatibility path.a2a/— A2A (Agent-to-Agent) server and client adapter using the officiala2a-go/v2SDK (separate Go module:github.com/deepnoodle-ai/dive/a2a).Serverexposes a Dive agent as an A2A endpoint (JSON-RPC or REST).RemoteAgentcalls remote A2A agents with zero SDK imports needed by callers (returns*TaskResult).CardOptionsfor static cards;AgentCardProviderfor dynamic cards. Suspend/resume maps toinput-requiredstate. Seedocs/guides/a2a.md.otel/— OpenTelemetry tracer adapter (separate Go module:github.com/deepnoodle-ai/dive/otel).experimental/— Functional but unstable APIs: settings, sandbox, mcp, compaction, todo, toolkit.
Design Philosophy
Dive aligns its tool interfaces and behaviors with Claude Code, leveraging Anthropic's tuning of Claude for these tool patterns.
Hook Flow
SessionLoad → SessionStart (first turn only) → PreGeneration → [PreIteration → LLM → PreToolUse → Execute → PostToolUse]* → Stop → PostGeneration → SessionSave
On suspend: OnSuspend → PostGeneration → SaveSuspendedTurn → return Status=Suspended.
On incomplete (error, cancellation, hook abort, or a model stop at a limit): close the turn → OnIncompleteTurn → SaveTurn / SaveResumedTurn → return Status=Incomplete. Session writes at the end of a call use a context without the run's cancellation.
A call halted by an earlier failure in its batch skips PreToolUse/PostToolUse/PostToolUseFailure but still emits tool_call/tool_call_result events.
Session load/save is automatic when AgentOptions.Session or WithSession is set. PreToolUse hooks return nil (allow) or error (deny). All hooks run; any error denies the tool. Stop hooks can return Continue: true to re-enter the loop. OnSuspend hooks run before persistence; an abort ends the turn incomplete with the suspending calls recorded as unknown.
Documentation
Guides in docs/guides/ (core) and docs/guides/experimental/.
Changelog
CHANGELOG.md follows Keep a Changelog. Keep
entries to one to three lines: bold summary, then the new value, breaking
change, or migration. How a bug was found belongs in the commit message.
Example
package main
import (
"context"
"fmt"
"log"
"github.com/deepnoodle-ai/dive"
"github.com/deepnoodle-ai/dive/providers/anthropic"
)
func main() {
agent, err := dive.NewAgent(dive.AgentOptions{
Name: "Research Assistant",
SystemPrompt: "You are an enthusiastic and deeply curious researcher.",
Model: anthropic.New(),
})
if err != nil {
log.Fatal(err)
}
response, err := agent.CreateResponse(context.Background(), dive.WithInput("What is the capital of France?"))
if err != nil {
log.Fatal(err)
}
fmt.Println(response.OutputText())
}Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

