v0.0.63 616eed3

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
147
148type rpcServer struct {
149	ctx      context.Context
150	args     Args
151	agent    *core.Agent
152	provider string
153	model    string
154	out      io.Writer
155	version  string
156
157	writeMu      sync.Mutex
158	turnMu       sync.Mutex // serialises one prompt at a time
159	activeCancel context.CancelFunc
160	authed       bool
161
162	// inFlight tracks long-running command goroutines so run() can
163	// wait for them before returning when stdin closes. Without this,
164	// piping a single 'prompt' command into 'zot rpc' would race the
165	// process exit against the agent loop and the prompt would never
166	// produce output.
167	inFlight sync.WaitGroup
168}
169
170// run reads NDJSON commands from in and dispatches them. Returns when
171// in is closed AND every in-flight long-running command (prompt /
172// compact) has finished, so a quick `echo cmd | zot rpc` invocation
173// still produces full output before the process exits.
174func (s *rpcServer) run(in io.Reader) error {
175	requireToken := os.Getenv("ZOTCORE_RPC_TOKEN") != ""
176	s.authed = !requireToken
177
178	sc := bufio.NewScanner(in)
179	sc.Buffer(make([]byte, 0, 64*1024), 16*1024*1024)
180	for sc.Scan() {
181		line := strings.TrimSpace(sc.Text())
182		if line == "" {
183			continue
184		}
185		var head struct {
186			Type string `json:"type"`
187			ID   string `json:"id,omitempty"`
188		}
189		if err := json.Unmarshal([]byte(line), &head); err != nil {
190			s.writeError("", "", fmt.Sprintf("malformed json: %v", err))
191			continue
192		}
193		if !s.authed {
194			if head.Type != "hello" {
195				s.writeError(head.ID, head.Type, "auth required: send hello with token first")
196				continue
197			}
198			var hello struct {
199				Token string `json:"token"`
200			}
201			_ = json.Unmarshal([]byte(line), &hello)
202			if hello.Token != os.Getenv("ZOTCORE_RPC_TOKEN") {
203				s.writeError(head.ID, head.Type, "invalid token")
204				return fmt.Errorf("rpc: bad auth token")
205			}
206			s.authed = true
207			s.writeResponse(head.ID, head.Type, map[string]any{
208				"protocol_version": 1,
209				"version":          s.version,
210				"provider":         s.provider,
211				"model":            s.model,
212			})
213			continue
214		}
215		s.dispatch(head.Type, head.ID, []byte(line))
216	}
217	err := sc.Err()
218	s.inFlight.Wait()
219	return err
220}
221
222// dispatch routes a command. Long-running commands (prompt, compact)
223// run on their own goroutine so the read loop stays responsive.
224func (s *rpcServer) dispatch(cmd, id string, raw []byte) {
225	switch cmd {
226	case "hello":
227		s.writeResponse(id, cmd, map[string]any{
228			"protocol_version": 1,
229			"version":          s.version,
230			"provider":         s.provider,
231			"model":            s.model,
232		})
233	case "prompt":
234		var req struct {
235			Message string `json:"message"`
236			Images  []struct {
237				MimeType string `json:"mime_type"`
238				Data     []byte `json:"data"`
239			} `json:"images"`
240		}
241		if err := json.Unmarshal(raw, &req); err != nil {
242			s.writeError(id, cmd, err.Error())
243			return
244		}
245		s.inFlight.Add(1)
246		go func() {
247			defer s.inFlight.Done()
248			s.runPrompt(id, req.Message, req.Images)
249		}()
250
251	case "abort":
252		if c := s.takeCancel(); c != nil {
253			c()
254		}
255		s.writeResponse(id, cmd, nil)
256
257	case "compact":
258		s.inFlight.Add(1)
259		go func() {
260			defer s.inFlight.Done()
261			s.runCompact(id)
262		}()
263
264	case "get_state":
265		s.writeResponse(id, cmd, s.snapshotState())
266
267	case "get_messages":
268		s.writeResponse(id, cmd, map[string]any{
269			"messages": messagesToJSON(s.agent.Messages()),
270		})
271
272	case "clear":
273		s.agent.SetMessages(nil)
274		s.writeResponse(id, cmd, nil)
275
276	case "set_model":
277		var req struct {
278			Model string `json:"model"`
279		}
280		if err := json.Unmarshal(raw, &req); err != nil {
281			s.writeError(id, cmd, err.Error())
282			return
283		}
284		if _, err := provider.FindModel(s.provider, req.Model); err != nil {
285			s.writeError(id, cmd, err.Error())
286			return
287		}
288		s.agent.Model = req.Model
289		s.model = req.Model
290		s.writeResponse(id, cmd, map[string]any{"model": req.Model})
291
292	case "get_models":
293		out := []map[string]any{}
294		for _, m := range provider.ModelsForProvider(s.provider) {
295			out = append(out, map[string]any{
296				"id":             m.ID,
297				"provider":       m.Provider,
298				"context_window": m.ContextWindow,
299				"max_output":     m.MaxOutput,
300				"reasoning":      m.Reasoning,
301			})
302		}
303		s.writeResponse(id, cmd, map[string]any{"models": out})
304
305	case "ping":
306		s.writeResponse(id, cmd, map[string]any{"pong": true})
307
308	default:
309		s.writeError(id, cmd, "unknown command")
310	}
311}
312
313// runPrompt executes a single prompt turn and streams events out.
314// Holds turnMu so a second concurrent prompt blocks until this one
315// finishes; the user can abort with the abort command.
316func (s *rpcServer) runPrompt(id, message string, images []struct {
317	MimeType string `json:"mime_type"`
318	Data     []byte `json:"data"`
319}) {
320	s.turnMu.Lock()
321	defer s.turnMu.Unlock()
322
323	subCtx, cancel := context.WithCancel(s.ctx)
324	s.setCancel(cancel)
325	defer s.setCancel(nil)
326
327	s.writeResponse(id, "prompt", map[string]any{"started": true})
328
329	imgs := make([]provider.ImageBlock, 0, len(images))
330	for _, im := range images {
331		imgs = append(imgs, provider.ImageBlock{MimeType: im.MimeType, Data: im.Data})
332	}
333
334	err := s.agent.Prompt(subCtx, message, imgs, func(ev core.AgentEvent) {
335		// EvDone is emitted by the agent loop and we re-emit our own
336		// 'done' below; suppressing it here avoids duplicate frames.
337		if _, ok := ev.(core.EvDone); ok {
338			return
339		}
340		s.writeEvent(modes.EventToJSON(ev))
341	})
342	// Don't emit a stand-alone error event for cancellation; the prior
343	// turn_end with stop=aborted already carries that signal.
344	if err != nil && !errors.Is(err, context.Canceled) {
345		s.writeEvent(map[string]any{"type": "error", "message": err.Error()})
346	}
347	s.writeEvent(map[string]any{"type": "done"})
348}
349
350// runCompact mirrors runPrompt but for compaction.
351func (s *rpcServer) runCompact(id string) {
352	s.turnMu.Lock()
353	defer s.turnMu.Unlock()
354
355	subCtx, cancel := context.WithCancel(s.ctx)
356	s.setCancel(cancel)
357	defer s.setCancel(nil)
358
359	s.writeResponse(id, "compact", map[string]any{"started": true})
360	summary, err := s.agent.Compact(subCtx, 4, nil)
361	if err != nil {
362		if !errors.Is(err, context.Canceled) {
363			s.writeEvent(map[string]any{"type": "error", "message": err.Error()})
364		}
365		return
366	}
367	s.writeEvent(map[string]any{
368		"type":    "compact_done",
369		"summary": summary,
370	})
371}
372
373// snapshotState builds the get_state response.
374func (s *rpcServer) snapshotState() map[string]any {
375	cum := s.agent.Cost()
376	return map[string]any{
377		"provider":      s.provider,
378		"model":         s.model,
379		"cwd":           s.args.CWD,
380		"message_count": len(s.agent.Messages()),
381		"busy":          s.activeCancel != nil,
382		"usage": map[string]any{
383			"input":       cum.InputTokens,
384			"output":      cum.OutputTokens,
385			"cache_read":  cum.CacheReadTokens,
386			"cache_write": cum.CacheWriteTokens,
387			"cost_usd":    cum.CostUSD,
388		},
389	}
390}
391
392// ---- write helpers (single-line JSON, mutex-guarded) ----
393
394func (s *rpcServer) writeResponse(id, cmd string, data any) {
395	frame := map[string]any{
396		"type":    "response",
397		"command": cmd,
398		"success": true,
399	}
400	if id != "" {
401		frame["id"] = id
402	}
403	if data != nil {
404		frame["data"] = data
405	}
406	s.write(frame)
407}
408
409func (s *rpcServer) writeError(id, cmd, msg string) {
410	frame := map[string]any{
411		"type":    "response",
412		"command": cmd,
413		"success": false,
414		"error":   msg,
415	}
416	if id != "" {
417		frame["id"] = id
418	}
419	s.write(frame)
420}
421
422func (s *rpcServer) writeEvent(payload map[string]any) {
423	s.write(payload)
424}
425
426func (s *rpcServer) write(v any) {
427	b, err := json.Marshal(v)
428	if err != nil {
429		return
430	}
431	s.writeMu.Lock()
432	defer s.writeMu.Unlock()
433	_, _ = s.out.Write(b)
434	_, _ = s.out.Write([]byte("\n"))
435}
436
437func (s *rpcServer) setCancel(c context.CancelFunc) {
438	s.writeMu.Lock()
439	s.activeCancel = c
440	s.writeMu.Unlock()
441}
442
443func (s *rpcServer) takeCancel() context.CancelFunc {
444	s.writeMu.Lock()
445	defer s.writeMu.Unlock()
446	c := s.activeCancel
447	s.activeCancel = nil
448	return c
449}
450
451// messagesToJSON serialises a transcript using the same schema as the
452// --json event mode for cross-format consistency.
453func messagesToJSON(msgs []provider.Message) []map[string]any {
454	out := make([]map[string]any, 0, len(msgs))
455	for _, m := range msgs {
456		out = append(out, map[string]any{
457			"role":    string(m.Role),
458			"content": modes.ContentToJSON(m.Content),
459			"time":    m.Time,
460		})
461	}
462	return out
463}

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