dev

package module
v0.7.27 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 12 Imported by: 1 module, 0 packages

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

README

github.com/hanzoai/dev/go

The dev loop (HIP-1330), for a Go host.

The loop is the Rust core in this repository, built as a wasm module and embedded here. This package runs it in the calling process under wazero: no cgo, and no Rust toolchain in the build that imports it. The core reasons and the host acts. The core asks for work as Actions, and the host performs them and reports what happened as Events.

import dev "github.com/hanzoai/dev/go"

The calls

Open(ctx) (*Core, error)                          compile the module, once per process
(*Core).New(ctx, Config) (*Session, error)        start a session in an instance of its own
(*Core).Restore(ctx, state) (*Session, error)     rebuild one from a snapshot
(*Session).Step(ctx, Event) ([]Action, error)     one event in, the actions it asks for out
(*Session).Snapshot(ctx) ([]byte, error)          the core's state, for Restore
(*Session).Close(ctx) error                       drop the session and its instance
(*Core).Close(ctx) error                          release the runtime

A Core is safe for concurrent use. A Session is not: it runs one call at a time, and a call made while another is running answers ErrBusy.

A call runs under its ctx, and each call into the instance under the 5s hanzoai/wasm allows one. A call either one ends stops where it stands and ends its session: it answers ErrHandle, which matches context.Canceled or context.DeadlineExceeded too, and every call after it answers ErrHandle. Restore the last snapshot to carry on. An answer from the core that the package cannot read ends the session the same way, since the core has already taken the event. A Step that answers an error answers no actions.

The statuses of crates/ffi/include/dev.h are errors to match with errors.Is: ErrHandle, ErrMalformed, ErrPoison, ErrPanic, ErrNull, ErrBusy and ErrFull. A trap in the core, such as a panic or a refused allocation, answers ErrPanic and then ErrPoison for that session only. Other sessions keep running. A closed session answers ErrHandle.

The types

The types are crates/protocol, field for field. A Rust enum is a struct whose fields are its variants: a pointer for a variant that carries a value, a bool for one that does not. Exactly one is set. A union that sets none, or two, is refused as ErrMalformed before the core sees it.

dev.Event{Turn: &dev.Turn{ID: 1, Prompt: "fix the build"}}
dev.Event{Exec: &dev.Output{ID: a.ID, Text: out, Failed: code != 0}}
dev.Event{Timer: true}

Reading one refuses what serde refuses of a union: a name it does not have, two names, null for a variant's value, or no union at all where a struct holds one. Any other member that is missing, or null, reads as its zero value, which serde refuses unless the member is an Option.

Text crosses as UTF-8. A host that has read bytes that are not UTF-8 must turn them into text before it steps with them.

A loop

The model here is a stand-in: it asks for one file, and then answers.

ctx := context.Background()
core, err := dev.Open(ctx)
if err != nil {
	log.Fatal(err)
}
defer core.Close(ctx)

s, err := core.New(ctx, dev.Config{Model: new("zen5")})
if err != nil {
	log.Fatal(err)
}
defer s.Close(ctx)

events := []dev.Event{{Turn: &dev.Turn{ID: 1, Prompt: "What does main.go do?"}}}
for len(events) > 0 {
	actions, err := s.Step(ctx, events[0])
	if err != nil {
		log.Fatal(err)
	}
	events = events[1:]
	for _, a := range actions {
		switch op := a.Op; {
		case op.Model != nil:
			events = append(events, dev.Event{Model: &dev.Answer{ID: a.ID, Reply: model(op.Model)}})
		case op.Read != nil:
			events = append(events, dev.Event{File: &dev.Output{ID: a.ID, Text: "package main\n"}})
		case op.Emit != nil:
			fmt.Println(*op.Emit)
		case op.Save:
			// Write s.Snapshot(ctx) beside the journal, at a.ID.
		case op.Done != nil:
			fmt.Println("done", op.Done.Turn)
		}
	}
}

func model(ask *dev.Ask) dev.Reply {
	if last := ask.Messages[len(ask.Messages)-1]; last.Tool == nil {
		return dev.Reply{Calls: []dev.Call{{Read: &dev.Read{Path: "main.go"}}}}
	}
	return dev.Reply{Text: new("It declares package main and does nothing.")}
}

example_test.go runs the same loop as a test.

Persisting a session

A session is three facts, kept apart: the core's snapshot, the workspace, and the host's journal of actions. Every action carries an id. When the host records dispatch and completion under that id, a result can be replayed instead of an effect run twice. The core refuses a turn id it has already accepted and a result for an id it is not waiting on, so replaying an event is safe.

A restored snapshot continues the id sequence where it stopped. Its checksum catches damage in storage, and it is not a signature: a host that keeps snapshots where others can write must authenticate them itself. Intact bytes do not prove the snapshot agrees with the journal either. One older than the journal mints ids the host has already dispatched, so reconcile the two before dispatching again.

The module

dev.wasm is make wasm at the repository root, copied here. Its imports are environ_get, environ_sizes_get, fd_write and proc_exit, and nothing else. The core cannot reach a file, a socket, a clock or a source of randomness, and a test checks that list. dev.wasm.sum is the sha256 of every file make wasm built it from, and of the module itself. CI runs make wasm-check, which fails when the tree no longer matches it.

Each session gets at most 64 MiB of memory. Every ask and every snapshot copies the conversation several times over, so a session holds about 14 MiB of conversation, and about 8 MiB in any one event. A call past that traps with ErrPanic, and a session restored from its snapshot meets the same wall: start a new session before one reaches it.

Documentation

Overview

Package dev runs the dev reasoning core (HIP-1330) inside the calling process.

The core is this repository's loop — crates/core behind the C ABI of crates/ffi — built as a wasm module, which this package embeds and runs under wazero: no cgo, and no Rust toolchain in a build that imports it. A Core compiles the module once. A Session is one instance of it, with memory of its own, holding one conversation: step it with an Event, perform the Actions it answers with, and step it again with what they observed.

The module imports environ_get, environ_sizes_get, fd_write and proc_exit, and nothing else. It reaches no file, socket, clock or source of randomness, so every effect an Action names is the host's to perform or refuse.

Example

A host drives the loop: it steps the session with an event, performs the actions that come back, and steps it again with what they observed. Here the model is a stand-in that reads one file and then answers.

package main

import (
	"context"
	"fmt"
	"log"

	dev "github.com/hanzoai/dev/go"
)

// A host drives the loop: it steps the session with an event, performs the
// actions that come back, and steps it again with what they observed. Here
// the model is a stand-in that reads one file and then answers.
func main() {
	ctx := context.Background()
	core, err := dev.Open(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer core.Close(ctx)

	s, err := core.New(ctx, dev.Config{Model: new("zen5")})
	if err != nil {
		log.Fatal(err)
	}
	defer s.Close(ctx)

	var state []byte
	events := []dev.Event{{Turn: &dev.Turn{ID: 1, Prompt: "What does main.go do?"}}}
	for len(events) > 0 {
		actions, err := s.Step(ctx, events[0])
		if err != nil {
			log.Fatal(err)
		}
		events = events[1:]
		for _, a := range actions {
			switch op := a.Op; {
			case op.Model != nil:
				events = append(events, dev.Event{Model: &dev.Answer{ID: a.ID, Reply: model(op.Model)}})
			case op.Read != nil:
				fmt.Println("read", op.Read.Path)
				events = append(events, dev.Event{File: &dev.Output{ID: a.ID, Text: "package main\n\nfunc main() {}\n"}})
			case op.Emit != nil:
				fmt.Println(*op.Emit)
			case op.Save:
				// A real host writes this beside its journal, at this action's id.
				if state, err = s.Snapshot(ctx); err != nil {
					log.Fatal(err)
				}
			case op.Done != nil:
				fmt.Println("done", op.Done.Turn)
			}
		}
	}
	fmt.Println(len(state) > 0)
}

// model stands in for a provider: it asks for main.go, and answers once the
// file is in the conversation.
func model(ask *dev.Ask) dev.Reply {
	if last := ask.Messages[len(ask.Messages)-1]; last.Tool == nil {
		return dev.Reply{Calls: []dev.Call{{Read: &dev.Read{Path: "main.go"}}}}
	}
	return dev.Reply{Text: new("It declares package main and does nothing.")}
}
Output:
read main.go
It declares package main and does nothing.
done 1
true

Index

Examples

Constants

View Source
const ABI = 1

ABI is the version of the C ABI, and of the payload encoding behind it, that this package speaks. Open refuses a module that answers dev_abi with any other.

Variables

View Source
var (
	ErrHandle    = errors.New("dev: the handle names no live session")
	ErrMalformed = errors.New("dev: the payload is not a message of this protocol")
	ErrPoison    = errors.New("dev: a previous call on this session panicked")
	ErrPanic     = errors.New("dev: this call panicked; the session is now poisoned")
	ErrNull      = errors.New("dev: a pointer the caller must supply was null")
	ErrBusy      = errors.New("dev: the session is inside another call")
	ErrFull      = errors.New("dev: no slot is left for another session")
)

The status codes of crates/ffi/include/dev.h. Match them with errors.Is.

Functions

This section is empty.

Types

type Action

type Action struct {
	ID uint64 `json:"id"`
	Op Op     `json:"op"`
}

Action is what the core asks the host to do, under the id the host's ledger records it by and its result names.

func (*Action) UnmarshalJSONFrom

func (a *Action) UnmarshalJSONFrom(dec *jsontext.Decoder) error

type Agent

type Agent struct {
	Text  *string    `json:"text"`
	Calls []Dispatch `json:"calls"`
}

Agent is what the model said and the calls it made, each under the id the core minted for it, a call it refused included.

type Answer

type Answer struct {
	ID    uint64 `json:"id"`
	Reply Reply  `json:"reply"`
}

Answer is a model's reply to the ask dispatched under ID.

type Ask

type Ask struct {
	Model *string `json:"model"`
	// Prelude is the session's standing instructions, ahead of the
	// conversation.
	Prelude  *string   `json:"prelude"`
	Messages []Message `json:"messages"`
}

Ask is a request for the model: the whole conversation, every time.

type Browse

type Browse struct {
	URL  string  `json:"url"`
	Body *string `json:"body"`
}

Browse is a browser request, with a Body when it sends one.

type Call

type Call struct {
	Read   *Read
	Write  *Write
	Patch  *Patch
	Exec   *Exec
	Git    *Git
	Browse *Browse
}

Call is a tool call, already typed: the host maps a provider's function call onto one, and the core never dispatches on a string.

func (Call) MarshalJSONTo

func (c Call) MarshalJSONTo(enc *jsontext.Encoder) error

func (*Call) UnmarshalJSONFrom

func (c *Call) UnmarshalJSONFrom(dec *jsontext.Decoder) error

type Cancel

type Cancel struct {
	Turn uint64 `json:"turn"`
}

Cancel names the turn to stop, by the id its Turn carried.

type Config

type Config struct {
	// Model is named in every Model ask; the host routes it.
	Model *string `json:"model"`
	// Prelude is the standing instructions every ask carries.
	Prelude *string `json:"prelude"`
}

Config is what a session is born with.

type Core

type Core struct {
	// contains filtered or unexported fields
}

Core is the compiled module. Open one per process, and New or Restore a Session from it per conversation. A Core is safe for concurrent use.

func Open

func Open(ctx context.Context) (*Core, error)

Open compiles the embedded module, the one slow call, and checks that it speaks ABI.

func (*Core) Close

func (c *Core) Close(ctx context.Context) error

Close releases the runtime. A Session started from it has nothing left to run in, and answers ErrHandle from then on, or ErrPoison if it had already trapped.

func (*Core) New

func (c *Core) New(ctx context.Context, cfg Config) (*Session, error)

New starts a session.

func (*Core) Restore

func (c *Core) Restore(ctx context.Context, state []byte) (*Session, error)

Restore rebuilds a session from its Snapshot, in an instance of its own.

A snapshot damaged in storage — truncated, corrupted, or written under another ABI — answers ErrMalformed. The checksum is not a signature: a host that stores snapshots where others can write must authenticate them itself. Intact bytes are not proof that the sequence agrees with the host's journal either: a snapshot older than the journal mints again ids the host has already dispatched under, so reconcile the two before dispatching.

type Dispatch

type Dispatch struct {
	ID   uint64 `json:"id"`
	Call Call   `json:"call"`
}

Dispatch is a call the core sent out, under the id its result will name.

func (*Dispatch) UnmarshalJSONFrom

func (d *Dispatch) UnmarshalJSONFrom(dec *jsontext.Decoder) error

type Done

type Done struct {
	Turn    uint64  `json:"turn"`
	Outcome Outcome `json:"outcome"`
}

Done is the end of the turn Turn asked for.

func (*Done) UnmarshalJSONFrom

func (d *Done) UnmarshalJSONFrom(dec *jsontext.Decoder) error

type Event

type Event struct {
	// Turn is a person asking for work.
	Turn *Turn
	// Model answers the ask dispatched under its id.
	Model *Answer
	// Exec is a command dispatched under its id exiting.
	Exec *Output
	// File is a read, write or patch dispatched under its id finishing.
	File *Output
	// Git is a git command dispatched under its id exiting.
	Git *Output
	// Browse is a browser request dispatched under its id returning.
	Browse *Output
	// Timer is time passing; a long turn should checkpoint.
	Timer bool
	// Cancel stops the turn it names.
	Cancel *Cancel
}

Event is what the host tells the core.

func (Event) MarshalJSONTo

func (e Event) MarshalJSONTo(enc *jsontext.Encoder) error

func (*Event) UnmarshalJSONFrom

func (e *Event) UnmarshalJSONFrom(dec *jsontext.Decoder) error

type Exec

type Exec struct {
	Argv []string `json:"argv"`
	Cwd  *string  `json:"cwd"`
}

Exec runs a command, in Cwd when it names one.

type Git

type Git struct {
	Argv []string `json:"argv"`
}

Git runs git.

type Message

type Message struct {
	// User is a person asking for work.
	User *string
	// Agent is the model speaking, asking for tools, or both.
	Agent *Agent
	// Tool is a tool answering the call dispatched under its id.
	Tool *Tool
}

Message is one entry of the conversation the core carries. An Agent entry carries its calls under the ids they were dispatched with, and a Tool entry names the id it answers, so a provider that wants the call ahead of its result can be driven straight from the transcript.

func (Message) MarshalJSONTo

func (m Message) MarshalJSONTo(enc *jsontext.Encoder) error

func (*Message) UnmarshalJSONFrom

func (m *Message) UnmarshalJSONFrom(dec *jsontext.Decoder) error

type Op

type Op struct {
	Model  *Ask
	Read   *Read
	Write  *Write
	Patch  *Patch
	Exec   *Exec
	Git    *Git
	Browse *Browse
	// Emit is text to show whoever is watching.
	Emit *string
	// Save asks the host to persist the core's snapshot at this point in the
	// sequence.
	Save bool
	// Done ends a turn.
	Done *Done
}

Op is the ten things a core can ask for.

func (Op) MarshalJSONTo

func (o Op) MarshalJSONTo(enc *jsontext.Encoder) error

func (*Op) UnmarshalJSONFrom

func (o *Op) UnmarshalJSONFrom(dec *jsontext.Decoder) error

type Outcome

type Outcome struct {
	Complete  bool
	Cancelled bool
}

Outcome is why a turn ended.

func (Outcome) MarshalJSONTo

func (o Outcome) MarshalJSONTo(enc *jsontext.Encoder) error

func (*Outcome) UnmarshalJSONFrom

func (o *Outcome) UnmarshalJSONFrom(dec *jsontext.Decoder) error

type Output

type Output struct {
	ID     uint64 `json:"id"`
	Text   string `json:"text"`
	Failed bool   `json:"failed"`
}

Output is the result of an effect, naming the action it answers.

type Patch

type Patch struct {
	Path string `json:"path"`
	Diff string `json:"diff"`
}

Patch is a diff and the one file it edits: the host applies Diff to Path and to nothing else.

type Read

type Read struct {
	Path string `json:"path"`
}

Read asks for a file's text.

A path in this protocol is relative to the workspace the host mounted for the session. The core refuses a call whose path would leave it, so no Action names one; resolving a path against the real tree, symlinks and all, is still the host's.

type Reply

type Reply struct {
	Text  *string `json:"text"`
	Calls []Call  `json:"calls"`
}

Reply is text, tool calls, or both.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is one conversation, in a wasm instance of its own: the unit of isolation. What a session does to its memory, a panic included, reaches no other.

That memory is capped at 64 MiB, and every ask and every Snapshot copies the whole conversation several times over while it runs. So a session holds about 14 MiB of conversation, and about 8 MiB in any one event; a call past that traps, and answers ErrPanic. A session restored from its snapshot holds the same conversation and meets the same wall, so start a new session before one reaches it.

A Session is not safe for concurrent use. It runs one call at a time and does not queue: a call that arrives while another is running answers ErrBusy, as DEV_BUSY does in C, and never reaches the instance.

A call runs under its ctx, and each call into the instance under the 5s hanzoai/wasm allows one. A call either one ends is stopped where it stands, and the session with it: it answers ErrHandle, which matches context.Canceled or context.DeadlineExceeded too, and every call after answers ErrHandle. Restore the last Snapshot to carry on.

func (*Session) Close

func (s *Session) Close(ctx context.Context) error

Close closes the session's instance, and the session and every byte it held go with it. A call after Close answers ErrHandle, and a second Close answers nil.

func (*Session) Snapshot

func (s *Session) Snapshot(ctx context.Context) ([]byte, error)

Snapshot is the core's own state, one of the three facts a session is (HIP-1330): packed under the ABI with a checksum, for Restore.

func (*Session) Step

func (s *Session) Step(ctx context.Context, event Event) ([]Action, error)

Step feeds the core one event and returns the actions it answers with, in the order it asks for them. An event it cannot read answers ErrMalformed and changes nothing.

An answer this package cannot read is another matter: the core has taken the event by then, and what it asked for is lost to the host. That ends the session, as an ended context does: ErrHandle, and ErrHandle for every call after. Restore the last Snapshot and step the event again. A Step that answers an error answers no actions.

type Tool

type Tool struct {
	ID     uint64 `json:"id"`
	Text   string `json:"text"`
	Failed bool   `json:"failed"`
}

Tool is the answer to the call dispatched under ID.

type Turn

type Turn struct {
	ID     uint64 `json:"id"`
	Prompt string `json:"prompt"`
}

Turn is a prompt, under the id the host's journal gave the request. Ids rise and are never zero: the core refuses one at or below the highest it has accepted, so a redelivered turn asks for nothing.

type Write

type Write struct {
	Path string `json:"path"`
	Text string `json:"text"`
}

Write replaces a file's text.

Directories

Path Synopsis
Package frame is the Dev environment protocol on top of the dev loop.
Package frame is the Dev environment protocol on top of the dev loop.
cmd/framed command
Command framed serves one Dev environment-protocol session over stdio, for a client that cannot speak ZAP: frames in and out are a u32 little-endian length and then one frame, as a ZAP session carries them.
Command framed serves one Dev environment-protocol session over stdio, for a client that cannot speak ZAP: frames in and out are a u32 little-endian length and then one frame, as a ZAP session carries them.

Jump to

Keyboard shortcuts

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