v0.38.1 969e52a

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	"strings"
31	"sync"
32
33	"github.com/bnema/zut/packages/agent"
34	"github.com/bnema/zut/packages/agent/subagents"
35	agenttools "github.com/bnema/zut/packages/agent/tools"
36	"github.com/bnema/zut/packages/core"
37	"github.com/bnema/zut/packages/provider"
38)
39
40// Config configures a Runtime. All fields are optional; sensible
41// defaults are read from $ZUT_HOME/config.json, env vars, and the
42// resolver chain (the same one the cli uses).
43type Config struct {
44	// Provider is a configured provider id such as "anthropic", "openai",
45	// or "opencode-go". Empty = use the user's default from config.json or env.
46	Provider string
47
48	// Model is the model id. Empty = use the provider's default.
49	Model string
50
51	// CWD is the working directory the agent operates in. Tools are
52	// confined to this directory when Lock is true. Empty = current
53	// process cwd.
54	CWD string
55
56	// SystemPrompt overrides the built-in system prompt.
57	SystemPrompt string
58
59	// AppendSystemPrompt is appended to the built-in (or overridden)
60	// system prompt. Useful for project-specific instructions.
61	AppendSystemPrompt []string
62
63	// Reasoning sets the reasoning effort for models that support it
64	// ("minimum", "low", "medium", "high", "xhigh", "max"). Empty disables it.
65	Reasoning string
66
67	// Temperature sets the sampling temperature. Nil = provider default.
68	Temperature *float32
69
70	// MaxSteps caps the agent loop iterations per Prompt call.
71	// 0 leaves the loop unlimited.
72	MaxSteps int
73
74	// APIKey overrides the credential lookup chain.
75	APIKey string
76
77	// BaseURL overrides the provider base url (for tests / proxies).
78	BaseURL string
79
80	// Tools is the list of tools to enable. Nil/empty enables the ordinary
81	// built-ins: read, write, edit, bash, python, create_worktree, grep, glob, ast, lsp,
82	// update_goal, and update_plan. The public-web capability is excluded unless this list
83	// explicitly contains "web_search"; that selector enables web_search,
84	// web_open, web_find, and web_click. Pass NoTools=true to disable everything.
85	Tools []string
86
87	// NoTools disables every tool. Useful for chat-only embeddings.
88	NoTools bool
89
90	// Lock confines tools to CWD. Same effect as the /jail command.
91	Lock bool
92}
93
94// Runtime is one zut agent session. Safe for use from one goroutine
95// at a time per Runtime; create separate Runtimes for parallel work.
96type Runtime struct {
97	mu       sync.Mutex
98	agent    *core.Agent
99	provider string
100	model    string
101	cwd      string
102	// modelCatalog is a private metadata snapshot for dynamic providers.
103	modelCatalog              []provider.Model
104	modelCatalogAuthoritative bool
105
106	// activeCancel is set while a Prompt or Compact is running.
107	activeCancel context.CancelFunc
108	activeDone   chan struct{}
109
110	// closed signals that Close has been called.
111	closed bool
112}
113
114// New constructs a Runtime from cfg. Returns an error if no
115// credential is available for the requested provider.
116func New(cfg Config) (*Runtime, error) {
117	return NewContext(context.Background(), cfg)
118}
119
120// NewContext constructs a Runtime from cfg and uses ctx for credential
121// resolution and initial model catalog discovery. Canceling ctx stops setup
122// and any refresh started for this runtime.
123func NewContext(ctx context.Context, cfg Config) (*Runtime, error) {
124	if ctx == nil {
125		ctx = context.Background()
126	}
127	webSearchPolicy := subagents.WebSearchDeny
128	for _, name := range cfg.Tools {
129		if name == "web_search" {
130			webSearchPolicy = subagents.WebSearchAllow
131			break
132		}
133	}
134	args := agent.Args{
135		Mode:               agent.ModeJSON, // headless
136		Provider:           cfg.Provider,
137		Model:              cfg.Model,
138		CWD:                cfg.CWD,
139		APIKey:             cfg.APIKey,
140		BaseURL:            cfg.BaseURL,
141		SystemPrompt:       cfg.SystemPrompt,
142		AppendSystemPrompt: cfg.AppendSystemPrompt,
143		Reasoning:          cfg.Reasoning,
144		Temperature:        cfg.Temperature,
145		MaxSteps:           cfg.MaxSteps,
146		Tools:              cfg.Tools,
147		NoTools:            cfg.NoTools,
148		WebSearchPolicy:    webSearchPolicy,
149		NoSess:             true, // SDK callers manage persistence themselves
150	}
151	r, err := agent.ResolveSDK(ctx, args)
152	if err != nil {
153		return nil, err
154	}
155	if cfg.Lock && r.Sandbox != nil {
156		r.Sandbox.Lock()
157	}
158	ag := r.NewAgent()
159	return &Runtime{
160		agent:                     ag,
161		provider:                  r.Provider,
162		model:                     r.Model,
163		cwd:                       r.CWD,
164		modelCatalog:              r.ModelCatalogSnapshot(),
165		modelCatalogAuthoritative: r.ModelCatalogIsAuthoritative(),
166	}, nil
167}
168
169// Provider returns the active provider id.
170func (r *Runtime) Provider() string { r.mu.Lock(); defer r.mu.Unlock(); return r.provider }
171
172// Model returns the active model id.
173func (r *Runtime) Model() string { r.mu.Lock(); defer r.mu.Unlock(); return r.model }
174
175// CWD returns the working directory the agent operates in.
176func (r *Runtime) CWD() string { r.mu.Lock(); defer r.mu.Unlock(); return r.cwd }
177
178// Messages returns a copy of the current transcript.
179func (r *Runtime) Messages() []Message {
180	if r.agent == nil {
181		return nil
182	}
183	src := r.agent.Messages()
184	out := make([]Message, len(src))
185	for i, m := range src {
186		out[i] = Message{
187			Role:    string(m.Role),
188			Content: convertContent(m.Content),
189			Time:    m.Time.Format("2006-01-02T15:04:05Z"),
190		}
191	}
192	return out
193}
194
195// SetMessages replaces the transcript. Use to seed history from a
196// session file or to clear with nil.
197func (r *Runtime) SetMessages(msgs []Message) {
198	if r.agent == nil {
199		return
200	}
201	out := make([]provider.Message, 0, len(msgs))
202	for _, m := range msgs {
203		out = append(out, provider.Message{
204			Role:    provider.Role(m.Role),
205			Content: rebuildContent(m.Content),
206		})
207	}
208	r.agent.SetMessages(out)
209}
210
211// Cost returns the cumulative usage and dollar cost for this Runtime.
212func (r *Runtime) Cost() Usage {
213	if r.agent == nil {
214		return Usage{}
215	}
216	u := r.agent.Cost()
217	return Usage{
218		Input:               u.InputTokens,
219		Output:              u.OutputTokens,
220		Reasoning:           sdkReasoningTokens(u),
221		CacheRead:           u.CacheReadTokens,
222		CacheWrite:          u.CacheWriteTokens,
223		CacheMeasuredPrompt: u.CacheMeasuredPromptTokens,
224		CacheMeasuredRead:   u.CacheMeasuredReadTokens,
225		CostUSD:             u.CostUSD,
226	}
227}
228
229// Prompt sends a user message and runs the agent loop. Returns a
230// channel that emits one Event per agent action, closed when the
231// turn finishes (cleanly or with error). Only one Prompt may be
232// active at a time per Runtime; concurrent calls return ErrBusy.
233func (r *Runtime) Prompt(ctx context.Context, text string, images []Image) (<-chan Event, error) {
234	r.mu.Lock()
235	if r.closed {
236		r.mu.Unlock()
237		return nil, ErrClosed
238	}
239	if r.activeCancel != nil {
240		r.mu.Unlock()
241		return nil, ErrBusy
242	}
243	if r.agent == nil {
244		r.mu.Unlock()
245		return nil, fmt.Errorf("sdk: no agent (login first via /login or set credentials)")
246	}
247	subCtx, cancel := context.WithCancel(ctx)
248	done := make(chan struct{})
249	r.activeCancel = cancel
250	r.activeDone = done
251	r.mu.Unlock()
252
253	imgBlocks := make([]provider.ImageBlock, 0, len(images))
254	for _, img := range images {
255		imgBlocks = append(imgBlocks, provider.ImageBlock{MimeType: img.MimeType, Data: img.Data})
256	}
257
258	out := make(chan Event, 16)
259	go func() {
260		defer close(out)
261		defer func() {
262			r.mu.Lock()
263			r.activeCancel = nil
264			r.activeDone = nil
265			close(done)
266			r.mu.Unlock()
267		}()
268		err := r.agent.Prompt(subCtx, text, imgBlocks, func(ev core.AgentEvent) {
269			out <- toEvent(ev)
270		})
271		if err != nil && !errors.Is(err, context.Canceled) {
272			out <- Event{Type: "error", Error: err.Error()}
273		}
274	}()
275	return out, nil
276}
277
278// Cancel interrupts the active Prompt, if any. Safe to call when no
279// prompt is in flight (no-op).
280func (r *Runtime) Cancel() {
281	r.mu.Lock()
282	cancel := r.activeCancel
283	r.mu.Unlock()
284	if cancel != nil {
285		cancel()
286	}
287}
288
289// Compact summarises the current transcript into a single synthetic
290// user message, freeing up context. Blocks until done.
291func (r *Runtime) Compact(ctx context.Context, customInstructions string) (CompactResult, error) {
292	if r.agent == nil {
293		return CompactResult{}, fmt.Errorf("sdk: no agent")
294	}
295	r.mu.Lock()
296	if r.activeCancel != nil {
297		r.mu.Unlock()
298		return CompactResult{}, ErrBusy
299	}
300	subCtx, cancel := context.WithCancel(ctx)
301	done := make(chan struct{})
302	r.activeCancel = cancel
303	r.activeDone = done
304	r.mu.Unlock()
305	defer func() {
306		r.mu.Lock()
307		r.activeCancel = nil
308		r.activeDone = nil
309		close(done)
310		r.mu.Unlock()
311	}()
312
313	summary, err := r.agent.Compact(subCtx, 4, nil)
314	if err != nil {
315		return CompactResult{}, err
316	}
317	return CompactResult{Summary: summary, Messages: r.Messages()}, nil
318}
319
320// SetModel switches the active model. Same provider only; for cross-
321// provider switches, create a new Runtime.
322func (r *Runtime) SetModel(model string) error {
323	r.mu.Lock()
324	defer r.mu.Unlock()
325	if r.agent == nil {
326		return fmt.Errorf("sdk: no agent")
327	}
328	if r.activeCancel != nil {
329		return ErrBusy
330	}
331	model = strings.TrimSpace(model)
332	if model == "" {
333		return fmt.Errorf("sdk: model must not be empty")
334	}
335
336	var metadata provider.Model
337	found := false
338	if r.provider == provider.ProviderOpenCodeGo {
339		for _, candidate := range r.modelCatalog {
340			if candidate.ID == model {
341				metadata = candidate
342				found = true
343				break
344			}
345		}
346		if !found && r.modelCatalogAuthoritative {
347			return fmt.Errorf("unknown model %q (provider=%q)", model, r.provider)
348		}
349		if !found {
350			metadata = provider.DynamicOpenCodeGoModel(r.provider, model, "")
351		}
352	} else {
353		var err error
354		metadata, err = provider.FindModel(r.provider, model)
355		if err != nil {
356			return err
357		}
358		found = true
359	}
360	if found || r.provider == provider.ProviderOpenCodeGo {
361		if setter, ok := r.agent.Client.(provider.ModelMetadataSetter); ok {
362			setter.SetModelMetadata(metadata)
363		}
364		if metadata.ContextWindow > 0 {
365			r.agent.ContextWindow = metadata.ContextWindow
366		}
367		if metadata.MaxOutput > 0 {
368			r.agent.MaxTokens = metadata.MaxOutput
369		}
370	}
371	r.agent.Model = model
372	r.model = model
373	return nil
374}
375
376// SetReasoning changes the reasoning level used by subsequent prompts.
377func (r *Runtime) SetReasoning(level string) error {
378	r.mu.Lock()
379	defer r.mu.Unlock()
380	if r.agent == nil {
381		return fmt.Errorf("sdk: no agent")
382	}
383	reasoning := provider.NormalizeReasoning(level)
384	switch reasoning {
385	case "", "minimum", "low", "medium", "high", "xhigh", "max":
386		r.agent.Reasoning = reasoning
387		return nil
388	default:
389		return fmt.Errorf("sdk: reasoning must be off|minimum|low|medium|high|xhigh|max")
390	}
391}
392
393// State returns a snapshot of the runtime's current state. Useful for
394// driving UIs.
395func (r *Runtime) State() State {
396	r.mu.Lock()
397	defer r.mu.Unlock()
398	return State{
399		Provider:     r.provider,
400		Model:        r.model,
401		Reasoning:    r.agent.Reasoning,
402		CWD:          r.cwd,
403		Busy:         r.activeCancel != nil,
404		MessageCount: len(r.Messages()),
405	}
406}
407
408// Close releases resources held by the Runtime. Cancels any active
409// prompt. Subsequent calls return ErrClosed.
410func (r *Runtime) Close() error {
411	r.mu.Lock()
412	if r.closed {
413		r.mu.Unlock()
414		return nil
415	}
416	r.closed = true
417	cancel := r.activeCancel
418	done := r.activeDone
419	r.mu.Unlock()
420	if cancel != nil {
421		cancel()
422	}
423	if done != nil {
424		<-done
425	}
426	r.mu.Lock()
427	ag := r.agent
428	r.mu.Unlock()
429	if ag != nil {
430		return agenttools.CloseLSPManagers(ag.ToolsSnapshot())
431	}
432	return nil
433}
434
435// ListModels returns every model known to the runtime for the
436// current provider (catalog + live discovery if cached).
437func (r *Runtime) ListModels() []ModelInfo {
438	r.mu.Lock()
439	providerName := r.provider
440	models := append([]provider.Model(nil), r.modelCatalog...)
441	r.mu.Unlock()
442	if providerName != provider.ProviderOpenCodeGo {
443		models = provider.ModelsForProvider(providerName)
444	}
445	out := make([]ModelInfo, 0, len(models))
446	for _, m := range models {
447		out = append(out, ModelInfo{
448			ID:            m.ID,
449			Provider:      m.Provider,
450			ContextWindow: m.ContextWindow,
451			MaxOutput:     m.MaxOutput,
452			Reasoning:     m.Reasoning,
453		})
454	}
455	return out
456}
457
458// ---- public errors ----
459
460// ErrBusy is returned when a Prompt or Compact is started while
461// another is in flight on the same Runtime.
462var ErrBusy = errors.New("sdk: runtime is busy")
463
464// ErrClosed is returned by methods on a Runtime after Close.
465var 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