v0.19.0 d7aa01a

sdk.go RawHistoryFolder

1// Package sdk is the public Go SDK for embedding the zut agent
2// runtime in third-party programs. It is the only stable, importable
3// surface the project exposes; everything under internal/ is subject
4// to change without notice.
5//
6// Lifecycle:
7//
8//	rt, err := sdk.New(sdk.Config{Provider: "anthropic", Model: "claude-sonnet-4-5"})
9//	if err != nil { ... }
10//	defer rt.Close()
11//
12//	events, err := rt.Prompt(ctx, "fix the failing test", nil)
13//	if err != nil { ... }
14//	for ev := range events {
15//	    fmt.Printf("%s: %+v\n", ev.Type(), ev)
16//	}
17//
18// Concurrency model: one prompt at a time per Runtime. Spawn one
19// Runtime per project / cwd. The Cancel call interrupts the active
20// prompt; subsequent prompts work normally.
21//
22// For a non-Go consumer, run `zut rpc` and speak the same JSON
23// schema over stdin/stdout. See docs/rpc.md.
24package sdk
25
26import (
27	"context"
28	"errors"
29	"fmt"
30	"sync"
31
32	"github.com/bnema/zut/packages/agent"
33	"github.com/bnema/zut/packages/agent/subagents"
34	agenttools "github.com/bnema/zut/packages/agent/tools"
35	"github.com/bnema/zut/packages/core"
36	"github.com/bnema/zut/packages/provider"
37)
38
39// Config configures a Runtime. All fields are optional; sensible
40// defaults are read from $ZUT_HOME/config.json, env vars, and the
41// resolver chain (the same one the cli uses).
42type Config struct {
43	// Provider is "anthropic" or "openai". Empty = use the user's
44	// default from config.json or env.
45	Provider string
46
47	// Model is the model id. Empty = use the provider's default.
48	Model string
49
50	// CWD is the working directory the agent operates in. Tools are
51	// confined to this directory when Lock is true. Empty = current
52	// process cwd.
53	CWD string
54
55	// SystemPrompt overrides the built-in system prompt.
56	SystemPrompt string
57
58	// AppendSystemPrompt is appended to the built-in (or overridden)
59	// system prompt. Useful for project-specific instructions.
60	AppendSystemPrompt []string
61
62	// Reasoning sets the reasoning effort for models that support it
63	// ("minimum", "low", "medium", "high", "xhigh", "max"). Empty disables it.
64	Reasoning string
65
66	// Temperature sets the sampling temperature. Nil = provider default.
67	Temperature *float32
68
69	// MaxSteps caps the agent loop iterations per Prompt call.
70	// 0 leaves the loop unlimited.
71	MaxSteps int
72
73	// APIKey overrides the credential lookup chain.
74	APIKey string
75
76	// BaseURL overrides the provider base url (for tests / proxies).
77	BaseURL string
78
79	// Tools is the list of tools to enable. Nil/empty = all ordinary built-in
80	// tools (read, write, edit, bash, create_worktree, grep, lsp). web_search is
81	// excluded unless this list explicitly contains "web_search". Pass an
82	// empty-but-non-nil slice
83	// (e.g. []string{}) plus NoTools=true to disable everything.
84	Tools []string
85
86	// NoTools disables every tool. Useful for chat-only embeddings.
87	NoTools bool
88
89	// Lock confines tools to CWD. Same effect as the /jail command.
90	Lock bool
91}
92
93// Runtime is one zut agent session. Safe for use from one goroutine
94// at a time per Runtime; create separate Runtimes for parallel work.
95type Runtime struct {
96	mu       sync.Mutex
97	agent    *core.Agent
98	provider string
99	model    string
100	cwd      string
101
102	// activeCancel is set while a Prompt or Compact is running.
103	activeCancel context.CancelFunc
104	activeDone   chan struct{}
105
106	// closed signals that Close has been called.
107	closed bool
108}
109
110// New constructs a Runtime from cfg. Returns an error if no
111// credential is available for the requested provider.
112func New(cfg Config) (*Runtime, error) {
113	webSearchPolicy := subagents.WebSearchDeny
114	for _, name := range cfg.Tools {
115		if name == "web_search" {
116			webSearchPolicy = subagents.WebSearchAllow
117			break
118		}
119	}
120	args := agent.Args{
121		Mode:               agent.ModeJSON, // headless
122		Provider:           cfg.Provider,
123		Model:              cfg.Model,
124		CWD:                cfg.CWD,
125		APIKey:             cfg.APIKey,
126		BaseURL:            cfg.BaseURL,
127		SystemPrompt:       cfg.SystemPrompt,
128		AppendSystemPrompt: cfg.AppendSystemPrompt,
129		Reasoning:          cfg.Reasoning,
130		Temperature:        cfg.Temperature,
131		MaxSteps:           cfg.MaxSteps,
132		Tools:              cfg.Tools,
133		NoTools:            cfg.NoTools,
134		WebSearchPolicy:    webSearchPolicy,
135		NoSess:             true, // SDK callers manage persistence themselves
136	}
137	r, err := agent.Resolve(args, true)
138	if err != nil {
139		return nil, err
140	}
141	if cfg.Lock && r.Sandbox != nil {
142		r.Sandbox.Lock()
143	}
144	ag := r.NewAgent()
145	return &Runtime{
146		agent:    ag,
147		provider: r.Provider,
148		model:    r.Model,
149		cwd:      r.CWD,
150	}, nil
151}
152
153// Provider returns the active provider id.
154func (r *Runtime) Provider() string { r.mu.Lock(); defer r.mu.Unlock(); return r.provider }
155
156// Model returns the active model id.
157func (r *Runtime) Model() string { r.mu.Lock(); defer r.mu.Unlock(); return r.model }
158
159// CWD returns the working directory the agent operates in.
160func (r *Runtime) CWD() string { r.mu.Lock(); defer r.mu.Unlock(); return r.cwd }
161
162// Messages returns a copy of the current transcript.
163func (r *Runtime) Messages() []Message {
164	if r.agent == nil {
165		return nil
166	}
167	src := r.agent.Messages()
168	out := make([]Message, len(src))
169	for i, m := range src {
170		out[i] = Message{
171			Role:    string(m.Role),
172			Content: convertContent(m.Content),
173			Time:    m.Time.Format("2006-01-02T15:04:05Z"),
174		}
175	}
176	return out
177}
178
179// SetMessages replaces the transcript. Use to seed history from a
180// session file or to clear with nil.
181func (r *Runtime) SetMessages(msgs []Message) {
182	if r.agent == nil {
183		return
184	}
185	out := make([]provider.Message, 0, len(msgs))
186	for _, m := range msgs {
187		out = append(out, provider.Message{
188			Role:    provider.Role(m.Role),
189			Content: rebuildContent(m.Content),
190		})
191	}
192	r.agent.SetMessages(out)
193}
194
195// Cost returns the cumulative usage and dollar cost for this Runtime.
196func (r *Runtime) Cost() Usage {
197	if r.agent == nil {
198		return Usage{}
199	}
200	u := r.agent.Cost()
201	return Usage{
202		Input:      u.InputTokens,
203		Output:     u.OutputTokens,
204		Reasoning:  sdkReasoningTokens(u),
205		CacheRead:  u.CacheReadTokens,
206		CacheWrite: u.CacheWriteTokens,
207		CostUSD:    u.CostUSD,
208	}
209}
210
211// Prompt sends a user message and runs the agent loop. Returns a
212// channel that emits one Event per agent action, closed when the
213// turn finishes (cleanly or with error). Only one Prompt may be
214// active at a time per Runtime; concurrent calls return ErrBusy.
215func (r *Runtime) Prompt(ctx context.Context, text string, images []Image) (<-chan Event, error) {
216	r.mu.Lock()
217	if r.closed {
218		r.mu.Unlock()
219		return nil, ErrClosed
220	}
221	if r.activeCancel != nil {
222		r.mu.Unlock()
223		return nil, ErrBusy
224	}
225	if r.agent == nil {
226		r.mu.Unlock()
227		return nil, fmt.Errorf("sdk: no agent (login first via /login or set credentials)")
228	}
229	subCtx, cancel := context.WithCancel(ctx)
230	done := make(chan struct{})
231	r.activeCancel = cancel
232	r.activeDone = done
233	r.mu.Unlock()
234
235	imgBlocks := make([]provider.ImageBlock, 0, len(images))
236	for _, img := range images {
237		imgBlocks = append(imgBlocks, provider.ImageBlock{MimeType: img.MimeType, Data: img.Data})
238	}
239
240	out := make(chan Event, 16)
241	go func() {
242		defer close(out)
243		defer func() {
244			r.mu.Lock()
245			r.activeCancel = nil
246			r.activeDone = nil
247			close(done)
248			r.mu.Unlock()
249		}()
250		err := r.agent.Prompt(subCtx, text, imgBlocks, func(ev core.AgentEvent) {
251			out <- toEvent(ev)
252		})
253		if err != nil && !errors.Is(err, context.Canceled) {
254			out <- Event{Type: "error", Error: err.Error()}
255		}
256	}()
257	return out, nil
258}
259
260// Cancel interrupts the active Prompt, if any. Safe to call when no
261// prompt is in flight (no-op).
262func (r *Runtime) Cancel() {
263	r.mu.Lock()
264	cancel := r.activeCancel
265	r.mu.Unlock()
266	if cancel != nil {
267		cancel()
268	}
269}
270
271// Compact summarises the current transcript into a single synthetic
272// user message, freeing up context. Blocks until done.
273func (r *Runtime) Compact(ctx context.Context, customInstructions string) (CompactResult, error) {
274	if r.agent == nil {
275		return CompactResult{}, fmt.Errorf("sdk: no agent")
276	}
277	r.mu.Lock()
278	if r.activeCancel != nil {
279		r.mu.Unlock()
280		return CompactResult{}, ErrBusy
281	}
282	subCtx, cancel := context.WithCancel(ctx)
283	done := make(chan struct{})
284	r.activeCancel = cancel
285	r.activeDone = done
286	r.mu.Unlock()
287	defer func() {
288		r.mu.Lock()
289		r.activeCancel = nil
290		r.activeDone = nil
291		close(done)
292		r.mu.Unlock()
293	}()
294
295	summary, err := r.agent.Compact(subCtx, 4, nil)
296	if err != nil {
297		return CompactResult{}, err
298	}
299	return CompactResult{Summary: summary, Messages: r.Messages()}, nil
300}
301
302// SetModel switches the active model. Same provider only; for cross-
303// provider switches, create a new Runtime.
304func (r *Runtime) SetModel(model string) error {
305	r.mu.Lock()
306	defer r.mu.Unlock()
307	if r.agent == nil {
308		return fmt.Errorf("sdk: no agent")
309	}
310	if _, err := provider.FindModel(r.provider, model); err != nil {
311		return err
312	}
313	r.agent.Model = model
314	r.model = model
315	return nil
316}
317
318// SetReasoning changes the reasoning level used by subsequent prompts.
319func (r *Runtime) SetReasoning(level string) error {
320	r.mu.Lock()
321	defer r.mu.Unlock()
322	if r.agent == nil {
323		return fmt.Errorf("sdk: no agent")
324	}
325	reasoning := provider.NormalizeReasoning(level)
326	switch reasoning {
327	case "", "minimum", "low", "medium", "high", "xhigh", "max":
328		r.agent.Reasoning = reasoning
329		return nil
330	default:
331		return fmt.Errorf("sdk: reasoning must be off|minimum|low|medium|high|xhigh|max")
332	}
333}
334
335// State returns a snapshot of the runtime's current state. Useful for
336// driving UIs.
337func (r *Runtime) State() State {
338	r.mu.Lock()
339	defer r.mu.Unlock()
340	return State{
341		Provider:     r.provider,
342		Model:        r.model,
343		Reasoning:    r.agent.Reasoning,
344		CWD:          r.cwd,
345		Busy:         r.activeCancel != nil,
346		MessageCount: len(r.Messages()),
347	}
348}
349
350// Close releases resources held by the Runtime. Cancels any active
351// prompt. Subsequent calls return ErrClosed.
352func (r *Runtime) Close() error {
353	r.mu.Lock()
354	if r.closed {
355		r.mu.Unlock()
356		return nil
357	}
358	r.closed = true
359	cancel := r.activeCancel
360	done := r.activeDone
361	r.mu.Unlock()
362	if cancel != nil {
363		cancel()
364	}
365	if done != nil {
366		<-done
367	}
368	r.mu.Lock()
369	ag := r.agent
370	r.mu.Unlock()
371	if ag != nil {
372		return agenttools.CloseLSPManagers(ag.ToolsSnapshot())
373	}
374	return nil
375}
376
377// ListModels returns every model known to the runtime for the
378// current provider (catalog + live discovery if cached).
379func (r *Runtime) ListModels() []ModelInfo {
380	models := provider.ModelsForProvider(r.Provider())
381	out := make([]ModelInfo, 0, len(models))
382	for _, m := range models {
383		out = append(out, ModelInfo{
384			ID:            m.ID,
385			Provider:      m.Provider,
386			ContextWindow: m.ContextWindow,
387			MaxOutput:     m.MaxOutput,
388			Reasoning:     m.Reasoning,
389		})
390	}
391	return out
392}
393
394// ---- public errors ----
395
396// ErrBusy is returned when a Prompt or Compact is started while
397// another is in flight on the same Runtime.
398var ErrBusy = errors.New("sdk: runtime is busy")
399
400// ErrClosed is returned by methods on a Runtime after Close.
401var ErrClosed = errors.New("sdk: runtime is closed")

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 477

↑↓ moveenter openesc close