v0.1.58 25a4caf

rpc.go RawHistoryFolder

1package agent
2
3import (
4	"bufio"
5	"context"
6	"encoding/json"
7	"errors"
8	"fmt"
9	"io"
10	"os"
11	"strings"
12	"sync"
13	"time"
14
15	"github.com/patriceckhart/zot/internal/agent/extensions"
16	"github.com/patriceckhart/zot/internal/agent/modes"
17	"github.com/patriceckhart/zot/internal/core"
18	"github.com/patriceckhart/zot/internal/extproto"
19	"github.com/patriceckhart/zot/internal/provider"
20)
21
22// runRPCMode implements the JSON-over-stdin/stdout RPC protocol.
23//
24// Wire format: one JSON object per line in both directions.
25//
26// Commands (stdin):
27//
28//	{"id":"1","type":"prompt","message":"hello","images":[]}
29//	{"id":"2","type":"abort"}
30//	{"id":"3","type":"compact"}
31//	{"id":"4","type":"get_state"}
32//	{"id":"5","type":"set_model","model":"claude-opus-4-5"}
33//	{"id":"6","type":"get_messages"}
34//	{"id":"7","type":"clear"}
35//	{"id":"8","type":"get_models"}
36//
37// Responses (stdout): {"type":"response","id":"1","command":"prompt","success":true}
38// Events (stdout): one JSON object per AgentEvent (same schema as --json mode).
39//
40// Auth: if $ZOTCORE_RPC_TOKEN is set, the first command must be
41// {"type":"hello","token":"..."} or the connection is closed.
42func runRPCMode(ctx context.Context, args Args, version string) error {
43	if args.NoYolo {
44		fmt.Fprintln(os.Stderr, "warning: --no-yolo has no effect in rpc mode (no interactive prompt available); tools will run without confirmation")
45	}
46	r, err := Resolve(args, true)
47	if err != nil {
48		return err
49	}
50
51	// Extensions: same lifecycle as interactive mode, minus the
52	// host-hooks integration. Notify/Display calls from extensions
53	// emit RPC events instead of TUI lines so any consumer can react.
54	extHooks := &rpcExtHooks{}
55	extMgr := extensions.New(ZotHome(), r.CWD, version, r.Provider, r.Model, extHooks)
56	for _, e := range extMgr.LoadExplicit(ctx, args.Exts) {
57		fmt.Fprintln(os.Stderr, "extension load:", e)
58	}
59	if !args.NoExt {
60		for _, e := range extMgr.Discover(ctx) {
61			fmt.Fprintln(os.Stderr, "extension load:", e)
62		}
63	}
64	extMgr.WaitForReady(3 * time.Second)
65	defer extMgr.Stop(2 * time.Second)
66	r.MergeExtensionTools(&extToolAdapter{mgr: extMgr})
67
68	ag := r.NewAgent()
69	ag.BeforeToolExecute = func(call provider.ToolCallBlock) (bool, string, json.RawMessage) {
70		r := extMgr.InterceptToolCall(ctx, call.ID, call.Name, call.Arguments)
71		if r.Block {
72			return false, r.Reason, nil
73		}
74		return true, "", r.ModifiedArgs
75	}
76	ag.BeforeTurn = func(step int) (bool, string) {
77		r := extMgr.InterceptTurnStart(ctx, step)
78		return !r.Block, r.Reason
79	}
80	ag.BeforeAssistantMessage = func(text string) (bool, string, string) {
81		r := extMgr.InterceptAssistantMessage(ctx, text)
82		if r.Block {
83			return false, r.Reason, ""
84		}
85		return true, "", r.ReplaceText
86	}
87	ag.OnEvent = func(ev core.AgentEvent) { fanoutAgentEvent(extMgr, ev) }
88
89	// /reload-ext hot-reload callback (also triggered via rpc
90	// `reload_ext` if/when added). Rebuilds the tool registry on the
91	// current agent so freshly-registered extension tools become
92	// callable without restarting the rpc process.
93	adapter := &extToolAdapter{mgr: extMgr}
94	extMgr.SetOnReload(func() {
95		resolved, err := Resolve(args, true)
96		if err != nil {
97			return
98		}
99		resolved.MergeExtensionTools(adapter)
100		ag.SetTools(resolved.ToolRegistry)
101	})
102
103	extMgr.EmitEvent(extproto.EventFromHost{Event: "session_start"})
104
105	server := &rpcServer{
106		ctx:      ctx,
107		args:     args,
108		agent:    ag,
109		provider: r.Provider,
110		model:    r.Model,
111		out:      os.Stdout,
112		version:  version,
113	}
114	extHooks.server = server
115	return server.run(os.Stdin)
116}
117
118// rpcExtHooks implements extensions.HostHooks for the headless RPC
119// loop. Notify and Display surface as `event` frames so any RPC
120// client can render them; Submit and Insert are no-ops because the
121// RPC loop has no editor and the prompt comes from the client.
122type rpcExtHooks struct {
123	server *rpcServer
124}
125
126func (h *rpcExtHooks) Notify(extName, level, message string) {
127	if h.server != nil {
128		h.server.writeEvent(map[string]any{
129			"type":      "ext_notify",
130			"extension": extName,
131			"level":     level,
132			"message":   message,
133		})
134	}
135}
136func (h *rpcExtHooks) Display(extName, text string) {
137	if h.server != nil {
138		h.server.writeEvent(map[string]any{
139			"type":      "ext_display",
140			"extension": extName,
141			"text":      text,
142		})
143	}
144}
145func (h *rpcExtHooks) Submit(string)                                        {} // ignored in rpc mode
146func (h *rpcExtHooks) Insert(string)                                        {} // ignored in rpc mode
147func (h *rpcExtHooks) OpenPanel(string, extproto.PanelSpec)                 {}
148func (h *rpcExtHooks) UpdatePanel(string, string, string, []string, string) {}
149func (h *rpcExtHooks) ClosePanel(string, string)                            {}
150
151type rpcServer struct {
152	ctx      context.Context
153	args     Args
154	agent    *core.Agent
155	provider string
156	model    string
157	out      io.Writer
158	version  string
159
160	writeMu      sync.Mutex
161	turnMu       sync.Mutex // serialises one prompt at a time
162	activeCancel context.CancelFunc
163	authed       bool
164
165	// inFlight tracks long-running command goroutines so run() can
166	// wait for them before returning when stdin closes. Without this,
167	// piping a single 'prompt' command into 'zot rpc' would race the
168	// process exit against the agent loop and the prompt would never
169	// produce output.
170	inFlight sync.WaitGroup
171}
172
173// run reads NDJSON commands from in and dispatches them. Returns when
174// in is closed AND every in-flight long-running command (prompt /
175// compact) has finished, so a quick `echo cmd | zot rpc` invocation
176// still produces full output before the process exits.
177func (s *rpcServer) run(in io.Reader) error {
178	requireToken := os.Getenv("ZOTCORE_RPC_TOKEN") != ""
179	s.authed = !requireToken
180
181	sc := bufio.NewScanner(in)
182	sc.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)
183	for sc.Scan() {
184		line := strings.TrimSpace(sc.Text())
185		if line == "" {
186			continue
187		}
188		var head struct {
189			Type string `json:"type"`
190			ID   string `json:"id,omitempty"`
191		}
192		if err := json.Unmarshal([]byte(line), &head); err != nil {
193			s.writeError("", "", fmt.Sprintf("malformed json: %v", err))
194			continue
195		}
196		if !s.authed {
197			if head.Type != "hello" {
198				s.writeError(head.ID, head.Type, "auth required: send hello with token first")
199				continue
200			}
201			var hello struct {
202				Token string `json:"token"`
203			}
204			_ = json.Unmarshal([]byte(line), &hello)
205			if hello.Token != os.Getenv("ZOTCORE_RPC_TOKEN") {
206				s.writeError(head.ID, head.Type, "invalid token")
207				return fmt.Errorf("rpc: bad auth token")
208			}
209			s.authed = true
210			s.writeResponse(head.ID, head.Type, map[string]any{
211				"protocol_version": 1,
212				"version":          s.version,
213				"provider":         s.provider,
214				"model":            s.model,
215			})
216			continue
217		}
218		s.dispatch(head.Type, head.ID, []byte(line))
219	}
220	err := sc.Err()
221	s.inFlight.Wait()
222	return err
223}
224
225// dispatch routes a command. Long-running commands (prompt, compact)
226// run on their own goroutine so the read loop stays responsive.
227func (s *rpcServer) dispatch(cmd, id string, raw []byte) {
228	switch cmd {
229	case "hello":
230		s.writeResponse(id, cmd, map[string]any{
231			"protocol_version": 1,
232			"version":          s.version,
233			"provider":         s.provider,
234			"model":            s.model,
235		})
236	case "prompt":
237		var req struct {
238			Message string `json:"message"`
239			Images  []struct {
240				MimeType string `json:"mime_type"`
241				Data     []byte `json:"data"`
242			} `json:"images"`
243		}
244		if err := json.Unmarshal(raw, &req); err != nil {
245			s.writeError(id, cmd, err.Error())
246			return
247		}
248		s.inFlight.Add(1)
249		go func() {
250			defer s.inFlight.Done()
251			s.runPrompt(id, req.Message, req.Images)
252		}()
253
254	case "abort":
255		if c := s.takeCancel(); c != nil {
256			c()
257		}
258		s.writeResponse(id, cmd, nil)
259
260	case "compact":
261		s.inFlight.Add(1)
262		go func() {
263			defer s.inFlight.Done()
264			s.runCompact(id)
265		}()
266
267	case "get_state":
268		s.writeResponse(id, cmd, s.snapshotState())
269
270	case "get_messages":
271		s.writeResponse(id, cmd, map[string]any{
272			"messages": messagesToJSON(s.agent.Messages()),
273		})
274
275	case "clear":
276		s.agent.SetMessages(nil)
277		s.writeResponse(id, cmd, nil)
278
279	case "set_model":
280		var req struct {
281			Model string `json:"model"`
282		}
283		if err := json.Unmarshal(raw, &req); err != nil {
284			s.writeError(id, cmd, err.Error())
285			return
286		}
287		if _, err := provider.FindModel(s.provider, req.Model); err != nil {
288			s.writeError(id, cmd, err.Error())
289			return
290		}
291		s.agent.Model = req.Model
292		s.model = req.Model
293		s.writeResponse(id, cmd, map[string]any{"model": req.Model})
294
295	case "get_models":
296		out := []map[string]any{}
297		for _, m := range provider.ModelsForProvider(s.provider) {
298			out = append(out, map[string]any{
299				"id":             m.ID,
300				"provider":       m.Provider,
301				"context_window": m.ContextWindow,
302				"max_output":     m.MaxOutput,
303				"reasoning":      m.Reasoning,
304			})
305		}
306		s.writeResponse(id, cmd, map[string]any{"models": out})
307
308	case "ping":
309		s.writeResponse(id, cmd, map[string]any{"pong": true})
310
311	default:
312		s.writeError(id, cmd, "unknown command")
313	}
314}
315
316// runPrompt executes a single prompt turn and streams events out.
317// Holds turnMu so a second concurrent prompt blocks until this one
318// finishes; the user can abort with the abort command.
319func (s *rpcServer) runPrompt(id, message string, images []struct {
320	MimeType string `json:"mime_type"`
321	Data     []byte `json:"data"`
322}) {
323	s.turnMu.Lock()
324	defer s.turnMu.Unlock()
325
326	subCtx, cancel := context.WithCancel(s.ctx)
327	s.setCancel(cancel)
328	defer s.setCancel(nil)
329
330	s.writeResponse(id, "prompt", map[string]any{"started": true})
331
332	imgs := make([]provider.ImageBlock, 0, len(images))
333	for _, im := range images {
334		imgs = append(imgs, provider.ImageBlock{MimeType: im.MimeType, Data: im.Data})
335	}
336
337	err := s.agent.Prompt(subCtx, message, imgs, func(ev core.AgentEvent) {
338		// EvDone is emitted by the agent loop and we re-emit our own
339		// 'done' below; suppressing it here avoids duplicate frames.
340		if _, ok := ev.(core.EvDone); ok {
341			return
342		}
343		s.writeEvent(modes.EventToJSON(ev))
344	})
345	// Don't emit a stand-alone error event for cancellation; the prior
346	// turn_end with stop=aborted already carries that signal.
347	if err != nil && !errors.Is(err, context.Canceled) {
348		s.writeEvent(map[string]any{"type": "error", "message": err.Error()})
349	}
350	s.writeEvent(map[string]any{"type": "done"})
351}
352
353// runCompact mirrors runPrompt but for compaction.
354func (s *rpcServer) runCompact(id string) {
355	s.turnMu.Lock()
356	defer s.turnMu.Unlock()
357
358	subCtx, cancel := context.WithCancel(s.ctx)
359	s.setCancel(cancel)
360	defer s.setCancel(nil)
361
362	s.writeResponse(id, "compact", map[string]any{"started": true})
363	summary, err := s.agent.Compact(subCtx, 4, nil)
364	if err != nil {
365		if !errors.Is(err, context.Canceled) {
366			s.writeEvent(map[string]any{"type": "error", "message": err.Error()})
367		}
368		return
369	}
370	s.writeEvent(map[string]any{
371		"type":    "compact_done",
372		"summary": summary,
373	})
374}
375
376// snapshotState builds the get_state response.
377func (s *rpcServer) snapshotState() map[string]any {
378	cum := s.agent.Cost()
379	return map[string]any{
380		"provider":      s.provider,
381		"model":         s.model,
382		"cwd":           s.args.CWD,
383		"message_count": len(s.agent.Messages()),
384		"busy":          s.activeCancel != nil,
385		"usage": map[string]any{
386			"input":       cum.InputTokens,
387			"output":      cum.OutputTokens,
388			"cache_read":  cum.CacheReadTokens,
389			"cache_write": cum.CacheWriteTokens,
390			"cost_usd":    cum.CostUSD,
391		},
392	}
393}
394
395// ---- write helpers (single-line JSON, mutex-guarded) ----
396
397func (s *rpcServer) writeResponse(id, cmd string, data any) {
398	frame := map[string]any{
399		"type":    "response",
400		"command": cmd,
401		"success": true,
402	}
403	if id != "" {
404		frame["id"] = id
405	}
406	if data != nil {
407		frame["data"] = data
408	}
409	s.write(frame)
410}
411
412func (s *rpcServer) writeError(id, cmd, msg string) {
413	frame := map[string]any{
414		"type":    "response",
415		"command": cmd,
416		"success": false,
417		"error":   msg,
418	}
419	if id != "" {
420		frame["id"] = id
421	}
422	s.write(frame)
423}
424
425func (s *rpcServer) writeEvent(payload map[string]any) {
426	s.write(payload)
427}
428
429func (s *rpcServer) write(v any) {
430	b, err := json.Marshal(v)
431	if err != nil {
432		return
433	}
434	s.writeMu.Lock()
435	defer s.writeMu.Unlock()
436	_, _ = s.out.Write(b)
437	_, _ = s.out.Write([]byte("\n"))
438}
439
440func (s *rpcServer) setCancel(c context.CancelFunc) {
441	s.writeMu.Lock()
442	s.activeCancel = c
443	s.writeMu.Unlock()
444}
445
446func (s *rpcServer) takeCancel() context.CancelFunc {
447	s.writeMu.Lock()
448	defer s.writeMu.Unlock()
449	c := s.activeCancel
450	s.activeCancel = nil
451	return c
452}
453
454// messagesToJSON serialises a transcript using the same schema as the
455// --json event mode for cross-format consistency.
456func messagesToJSON(msgs []provider.Message) []map[string]any {
457	out := make([]map[string]any, 0, len(msgs))
458	for _, m := range msgs {
459		out = append(out, map[string]any{
460			"role":    string(m.Role),
461			"content": modes.ContentToJSON(m.Content),
462			"time":    m.Time,
463		})
464	}
465	return out
466}

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 476

↑↓ moveenter openesc close