1// Package ext is the Go SDK for writing zut extensions.
2//
3// An extension is a subprocess that talks to zut over its stdin/stdout
4// in newline-delimited JSON. This package wraps the wire format so
5// extension authors can write straightforward Go without reimplementing
6// the protocol.
7//
8// Minimal example (registers /hello and replies with a static prompt):
9//
10// package main
11//
12// import "github.com/bnema/zut/packages/agent/ext"
13//
14// func main() {
15// ext := ext.New("hello", "1.0.0")
16// ext.Command("hello", "say hi", func(args string) ext.Response {
17// return ext.Prompt("Greet me in three different languages.")
18// })
19// ext.Run()
20// }
21//
22// Build it, drop the binary + an extension.json next to it under
23// `$ZUT_HOME/extensions/hello/`, and zut picks it up on next launch.
24//
25// Use OnHello when registration or configuration depends on host metadata
26// such as HostInfo.CWD, Provider, Model, ZutVersion, ExtensionDir, or DataDir.
27// Run sends hello, waits for hello_ack, runs OnHello, announces registrations,
28// then sends ready.
29//
30// The same wire format also has reference clients in TypeScript and
31// Python under examples/extensions/. Use whichever language fits.
32package ext
33
34import (
35 "bufio"
36 "encoding/base64"
37 "encoding/json"
38 "fmt"
39 "io"
40 "os"
41 "sync"
42
43 "github.com/bnema/zut/packages/agent/extproto"
44)
45
46func base64Encode(b []byte) string { return base64.StdEncoding.EncodeToString(b) }
47
48// CommandHandler is invoked when the user runs the extension's
49// registered slash command. args is everything the user typed after
50// the command name (already trimmed). Return a Response describing
51// what zut should do next.
52type CommandHandler func(args string) Response
53
54// ToolHandler is invoked when the LLM calls a tool the extension
55// registered. args is the raw JSON object the model produced; the
56// handler is responsible for parsing/validating it. Return a
57// ToolResult describing what zut should send back to the model.
58type ToolHandler func(args json.RawMessage) ToolResult
59
60// EventHandler is called for each lifecycle event the extension
61// subscribed to via Subscribe. The handler is invoked synchronously
62// on the read goroutine; keep it quick or hand off to your own
63// worker.
64type EventHandler func(ev Event)
65
66// Event is a lifecycle notification from zut. The fields populated
67// depend on Name (the host's event_name string):
68//
69// session_start : Session
70// session_opened : Session + extension-owned State snapshot
71// session_switched : Session + extension-owned State snapshot
72// session_forked : Session + extension-owned State snapshot
73// session_compacted: Session + extension-owned State snapshot
74// turn_start : Step
75// turn_end : Stop, optional Error
76// tool_call : ToolID, ToolName, ToolArgs
77// tool_confirmation_requested: ToolID, ToolName, ToolPreview
78// assistant_message : Text
79type Event struct {
80 Name string
81
82 Session *extproto.SessionContext
83 State json.RawMessage
84
85 Step int
86 Stop string
87 Error string
88
89 ToolID string
90 ToolName string
91 ToolArgs json.RawMessage
92 ToolPreview string
93
94 Text string
95}
96
97// InterceptHandler decides whether a tool call may proceed. Return
98// (allow=true) to permit, (allow=false, reason) to refuse. The
99// reason is shown to the model as the tool's error text.
100//
101// This is the original 2-value handler. For richer control (arg
102// rewrites, turn_start / assistant_message interception, etc.)
103// register via InterceptToolCallX, InterceptTurnStart, or
104// InterceptAssistantMessage.
105type InterceptHandler func(toolName string, args json.RawMessage) (allow bool, reason string)
106
107// ToolCallDecision is the richer reply an InterceptToolCallHandler
108// can return. Zero value means "allow, pass through".
109type ToolCallDecision struct {
110 // Block refuses the call. The model sees Reason as the tool's
111 // error text and typically proposes a different action.
112 Block bool
113 // Reason is the refusal text shown to the model on Block, or a
114 // logged note when passing through (optional).
115 Reason string
116 // ModifiedArgs, when non-nil and Block is false, replaces the
117 // JSON args the tool actually runs with. Lets guards redact /
118 // augment / patch the model's request without rewriting the
119 // transcript. Must encode to a JSON object.
120 ModifiedArgs json.RawMessage
121}
122
123// ToolCallHandler is the richer form of an interceptor. Use this
124// when you want to rewrite args instead of only blocking.
125type ToolCallHandler func(toolName string, args json.RawMessage) ToolCallDecision
126
127// TurnStartDecision controls whether the next model call runs. Zero
128// value means "allow".
129type TurnStartDecision struct {
130 Block bool
131 Reason string
132 // Context is hidden, per-turn context sent only in the next provider
133 // request. It is not recorded as a user or assistant message.
134 Context string
135}
136
137// TurnStartHandler is called before every turn's model call. Return
138// Block=true with Reason to abort the turn (shown to the user as a
139// status line). Useful for rate-limiting and business-hour gates.
140type TurnStartHandler func(step int) TurnStartDecision
141
142// AssistantMessageDecision controls the final assistant-text
143// rendering. Zero value means "allow, show as-is".
144type AssistantMessageDecision struct {
145 // Block suppresses the message from the user entirely. The
146 // transcript still records the model's original output so the
147 // model sees what it said on the next turn.
148 Block bool
149 // Reason is logged when blocking (optional).
150 Reason string
151 // ReplaceText, when non-empty and Block is false, is what the
152 // user sees. The model's original text still lives in the
153 // transcript.
154 ReplaceText string
155}
156
157// AssistantMessageHandler is called after the model's final text is
158// assembled but before it's shown. Use it to scrub secrets, expand
159// templates, enforce tone, or suppress responses entirely.
160type AssistantMessageHandler func(text string) AssistantMessageDecision
161
162// ToolResult is the extension's reply to a tool invocation. Build
163// one with TextResult, ImageResult, or directly when you need to
164// combine multiple blocks.
165type ToolResult struct {
166 Content []ToolContent
167 IsError bool
168 ActivateTools []string
169 // Details is opaque JSON kept out of provider-visible tool results. The
170 // host may persist it with the active session and return it on the next
171 // session lifecycle event.
172 Details json.RawMessage
173}
174
175// JSONDetails encodes an extension-owned value for ToolResult.Details. Invalid
176// values return nil, causing the host to ignore the metadata.
177func JSONDetails(value any) json.RawMessage {
178 data, err := json.Marshal(value)
179 if err != nil || !json.Valid(data) {
180 return nil
181 }
182 return data
183}
184
185// AlertRequest asks the host to surface a structured alert. The host owns
186// the rendering policy; extensions never write terminal bytes directly.
187type AlertRequest = extproto.AlertRequest
188
189const AlertKindBell = extproto.AlertKindBell
190
191// ToolContent is one block of tool output. Either Text is set, or
192// MimeType+Data (base64-encoded). Use the Text/Image helpers below.
193type ToolContent struct {
194 Type string // "text" | "image"
195 Text string
196 MimeType string
197 Data string // base64
198}
199
200// Text returns a text content block.
201func Text(s string) ToolContent { return ToolContent{Type: "text", Text: s} }
202
203// Image returns an image content block. data must already be
204// base64-encoded; use ImageBytes to encode raw bytes.
205func Image(mimeType, base64Data string) ToolContent {
206 return ToolContent{Type: "image", MimeType: mimeType, Data: base64Data}
207}
208
209// ImageBytes returns an image content block from raw bytes,
210// encoding them to base64 for the wire.
211func ImageBytes(mimeType string, data []byte) ToolContent {
212 return ToolContent{Type: "image", MimeType: mimeType, Data: base64Encode(data)}
213}
214
215// TextResult returns a tool result with one text block, success.
216func TextResult(s string) ToolResult { return ToolResult{Content: []ToolContent{Text(s)}} }
217
218// TextErrorResult returns a tool result with one text block, marked
219// as an error to the model.
220func TextErrorResult(s string) ToolResult {
221 return ToolResult{Content: []ToolContent{Text(s)}, IsError: true}
222}
223
224// Response tells zut how to react to a command invocation. Construct
225// one with Prompt(), Insert(), Display(), or Noop().
226type Panel struct {
227 ID string
228 Title string
229 Lines []string
230 Footer string
231}
232
233type Response struct {
234 Action string // "prompt", "insert", "display", "open_panel", "noop"
235 Prompt string
236 Insert string
237 Display string
238 OpenPanel *Panel
239 Error string
240}
241
242// Prompt returns a Response that submits text as a fresh user message
243// to the agent (running it through the model loop as if the user had
244// typed and pressed enter).
245func Prompt(text string) Response { return Response{Action: "prompt", Prompt: text} }
246
247// Insert returns a Response that drops text into the editor at the
248// cursor without submitting.
249func Insert(text string) Response { return Response{Action: "insert", Insert: text} }
250
251// Display returns a Response that adds a one-shot styled note to the
252// chat without invoking the model. Useful for showing a result without
253// burning tokens.
254func Display(text string) Response { return Response{Action: "display", Display: text} }
255
256// OpenPanel returns a Response that opens an interactive extension-owned
257// panel inside zut.
258func OpenPanel(id, title string, lines []string, footer string) Response {
259 return Response{Action: "open_panel", OpenPanel: &Panel{ID: id, Title: title, Lines: lines, Footer: footer}}
260}
261
262// Noop returns a Response that signals "I handled it, no UI change".
263// Use after pushing your own state or notifications.
264func Noop() Response { return Response{Action: "noop"} }
265
266// Errorf returns a Response that surfaces the error in the chat as a
267// red status line.
268func Errorf(format string, args ...any) Response {
269 return Response{Action: "noop", Error: fmt.Sprintf(format, args...)}
270}
271
272// Extension is one zut extension. Construct with New, register
273// commands, then call Run.
274type Extension struct {
275 name string
276 version string
277
278 in io.Reader
279 out io.Writer
280 stderr io.Writer
281 writeMu sync.Mutex
282
283 mu sync.Mutex
284 commands map[string]CommandHandler
285 descriptions []descTuple // ordered so register frames arrive in registration order
286 tools map[string]ToolHandler
287 toolDefs []toolDef // ordered so register frames arrive in registration order
288 eventHandlers map[string]EventHandler
289 eventNames []string // declared subscription order
290
291 interceptTool InterceptHandler
292 interceptToolRich ToolCallHandler
293 interceptOn bool
294 interceptTurn TurnStartHandler
295 interceptAssistant AssistantMessageHandler
296 panelKeys map[string]func(key, text string)
297 panelCloses map[string]func()
298 onHello func(HostInfo)
299
300 // Caps reported in the hello frame.
301 caps []string
302
303 // hostInfo is filled in once HelloAck arrives.
304 host HostInfo
305}
306
307type descTuple struct {
308 name, desc string
309}
310
311type toolDef struct {
312 name string
313 description string
314 schema json.RawMessage
315 deferred bool
316}
317
318// HostInfo is what the host (zut) tells us in HelloAck. Useful for
319// extensions that want to behave differently per provider.
320type HostInfo struct {
321 ProtocolVersion int
322 ZutVersion string
323 Provider string
324 Model string
325 CWD string
326 ExtensionDir string
327 DataDir string
328 Session *extproto.SessionContext
329}
330
331// New constructs an Extension with the given identifier. name should
332// match the name field in extension.json.
333func New(name, version string) *Extension {
334 return &Extension{
335 name: name,
336 version: version,
337 in: os.Stdin,
338 out: os.Stdout,
339 stderr: os.Stderr,
340 commands: map[string]CommandHandler{},
341 tools: map[string]ToolHandler{},
342 eventHandlers: map[string]EventHandler{},
343 panelKeys: map[string]func(key, text string){},
344 panelCloses: map[string]func(){},
345 caps: []string{"commands", "tools", "events", "alerts", "panels", "session_state", "status", "widgets"},
346 }
347}
348
349// Host returns the HostInfo received during the hello handshake.
350// Returns the zero value if Run hasn't started yet.
351func (e *Extension) Host() HostInfo { return e.host }
352
353// OnHello registers a callback that runs after zut acknowledges the
354// hello frame and before commands/tools are announced. Use it when
355// registrations depend on host metadata such as CWD or ZutHome-derived
356// paths. The callback may call Command, Tool, On, and interceptor
357// registration methods.
358func (e *Extension) OnHello(fn func(HostInfo)) {
359 e.mu.Lock()
360 e.onHello = fn
361 e.mu.Unlock()
362}
363
364// Logf writes a line to the extension's stderr, which zut captures to
365// $ZUT_HOME/logs/ext-<name>.log. Use this for debug output: anything
366// you print to stdout would corrupt the JSON wire protocol.
367func (e *Extension) Logf(format string, args ...any) {
368 fmt.Fprintf(e.stderr, "["+e.name+"] "+format+"\n", args...)
369}
370
371// OnPanelKey registers callbacks for panel key + close events.
372func (e *Extension) OnPanelKey(panelID string, onKey func(key, text string), onClose func()) {
373 e.mu.Lock()
374 defer e.mu.Unlock()
375 if onKey != nil {
376 e.panelKeys[panelID] = onKey
377 }
378 if onClose != nil {
379 e.panelCloses[panelID] = onClose
380 }
381}
382
383// OpenPanel opens an interactive panel spontaneously from extension code
384// without requiring a slash command. Safe to call from a tool handler goroutine
385// or any background context. The panel receives panel_key events via OnPanelKey
386// and can be dismissed with ClosePanel, exactly as with command-response panels.
387func (e *Extension) OpenPanel(id, title string, lines []string, footer string) {
388 _ = e.send(extproto.OpenPanelFromExt{
389 Type: "open_panel",
390 Panel: extproto.PanelSpec{ID: id, Title: title, Lines: lines, Footer: footer},
391 })
392}
393
394// RenderPanel pushes a fresh frame for panelID.
395func (e *Extension) RenderPanel(panelID, title string, lines []string, footer string) {
396 _ = e.send(extproto.PanelRenderFromExt{Type: "panel_render", PanelID: panelID, Title: title, Lines: lines, Footer: footer})
397}
398
399// ClosePanel tells zut to close panelID.
400func (e *Extension) ClosePanel(panelID string) {
401 _ = e.send(extproto.PanelCloseFromExt{Type: "panel_close", PanelID: panelID})
402}
403
404// Command registers a slash-command handler. Call this BEFORE Run().
405// Once Run is going, when the user runs /name in zut, fn is invoked
406// with the remaining args.
407//
408// Naming conflicts with built-in commands (e.g. /help) are silently
409// shadowed by the built-in; check the user's "ext logs" if a command
410// you registered isn't taking effect.
411func (e *Extension) Command(name, description string, fn CommandHandler) {
412 e.mu.Lock()
413 e.commands[name] = fn
414 e.descriptions = append(e.descriptions, descTuple{name: name, desc: description})
415 e.mu.Unlock()
416}
417
418// Tool registers an LLM-callable tool. schema is a JSON Schema
419// object describing the tool's args (the same shape Anthropic /
420// OpenAI accept). Call this BEFORE Run(); zut folds extension tools
421// into the agent's registry once the extension's ready frame fires.
422//
423// Naming conflicts with built-in tools (read, write, edit, bash, lsp,
424// skill) are silently shadowed by the built-in.
425func (e *Extension) Tool(name, description string, schema json.RawMessage, fn ToolHandler) {
426 e.registerTool(name, description, schema, false, fn)
427}
428
429// DeferredTool registers a tool whose definition stays hidden until another
430// tool result names it in ActivateTools.
431func (e *Extension) DeferredTool(name, description string, schema json.RawMessage, fn ToolHandler) {
432 e.registerTool(name, description, schema, true, fn)
433}
434
435func (e *Extension) registerTool(name, description string, schema json.RawMessage, deferred bool, fn ToolHandler) {
436 e.mu.Lock()
437 e.tools[name] = fn
438 e.toolDefs = append(e.toolDefs, toolDef{name: name, description: description, schema: schema, deferred: deferred})
439 e.mu.Unlock()
440}
441
442// On subscribes to a lifecycle event. fn is called for each
443// notification; the same name can only have one handler (later
444// registrations replace earlier ones). Recognised names include:
445// session_start, session_opened, session_switched, session_forked,
446// session_compacted, turn_start, turn_end, tool_call,
447// tool_confirmation_requested, assistant_message.
448func (e *Extension) On(name string, fn EventHandler) {
449 e.mu.Lock()
450 if _, exists := e.eventHandlers[name]; !exists {
451 e.eventNames = append(e.eventNames, name)
452 }
453 e.eventHandlers[name] = fn
454 e.mu.Unlock()
455}
456
457// InterceptToolCall registers a guard that runs immediately before
458// each tool call. Returning (false, reason) refuses the call; the
459// model sees reason as the tool error text. Multiple extensions can
460// install interceptors; if any one refuses, the call is blocked.
461//
462// Use this to build permission gates: refuse `bash` calls containing
463// `rm -rf`, ask the user for confirmation on dangerous patterns,
464// audit-log every call, etc.
465//
466// For the richer form (arg rewrites, structured decisions) use
467// InterceptToolCallX.
468func (e *Extension) InterceptToolCall(fn InterceptHandler) {
469 e.mu.Lock()
470 e.interceptTool = fn
471 e.interceptOn = true
472 e.mu.Unlock()
473}
474
475// InterceptToolCallX is the richer variant. Return a ToolCallDecision
476// to block, allow, or rewrite args mid-flight. If both
477// InterceptToolCall and InterceptToolCallX are set, the X form wins.
478func (e *Extension) InterceptToolCallX(fn ToolCallHandler) {
479 e.mu.Lock()
480 e.interceptToolRich = fn
481 e.interceptOn = true
482 e.mu.Unlock()
483}
484
485// InterceptTurnStart registers a guard that runs before every turn's
486// model call. Return Block=true with Reason to abort the turn.
487// Useful for deny-by-default gates and usage quotas.
488func (e *Extension) InterceptTurnStart(fn TurnStartHandler) {
489 e.mu.Lock()
490 e.interceptTurn = fn
491 e.mu.Unlock()
492}
493
494// InterceptAssistantMessage registers a guard that runs after the
495// model's final text is assembled but before it's shown. Return
496// Block=true to suppress entirely, or ReplaceText to rewrite what
497// the user sees. The model's original output stays in the transcript.
498func (e *Extension) InterceptAssistantMessage(fn AssistantMessageHandler) {
499 e.mu.Lock()
500 e.interceptAssistant = fn
501 e.mu.Unlock()
502}
503
504// Notify pushes an info-level status note into zut's chat without
505// requiring a slash command from the user.
506func (e *Extension) Notify(level, message string) {
507 _ = e.send(extproto.NotifyFromExt{
508 Type: "notify",
509 Level: level,
510 Message: message,
511 })
512}
513
514// SetStatus replaces one persistent status item owned by this extension.
515// Passing an empty text clears the item.
516func (e *Extension) SetStatus(key, text string) {
517 _ = e.send(extproto.StatusFromExt{Type: "status", Key: key, Text: text})
518}
519
520// ClearStatus removes one persistent status item owned by this extension.
521func (e *Extension) ClearStatus(key string) { e.SetStatus(key, "") }
522
523const (
524 // WidgetPositionAboveInput keeps a widget in the persistent chrome above
525 // the editor. It is the default for empty and unknown positions.
526 WidgetPositionAboveInput = extproto.WidgetPositionAboveInput
527 // WidgetPositionRightBar keeps a widget in the host-owned side rail when
528 // the terminal is wide enough; narrow terminals fall back above the input.
529 WidgetPositionRightBar = extproto.WidgetPositionRightBar
530)
531
532// SetWidget replaces one persistent widget owned by this extension. Use
533// WidgetPositionAboveInput or WidgetPositionRightBar for the position.
534func (e *Extension) SetWidget(id, position, title string, lines []string) {
535 _ = e.send(extproto.WidgetFromExt{Type: "widget", ID: id, Position: position, Title: title, Lines: lines})
536}
537
538// ClearWidget removes one persistent widget owned by this extension.
539func (e *Extension) ClearWidget(id string) {
540 _ = e.send(extproto.ClearWidgetFromExt{Type: "widget_clear", ID: id})
541}
542
543// Alert asks the host to surface a structured alert. It is fire-and-forget;
544// hosts that do not support the requested kind may ignore it.
545func (e *Extension) Alert(alert AlertRequest) {
546 _ = e.send(extproto.AlertFromExt{
547 Type: "alert",
548 AlertRequest: alert,
549 })
550}
551
552// Run starts the protocol loop. Blocks until stdin closes (zut has
553// shut us down). Returns the first fatal error, or nil on clean exit.
554func (e *Extension) Run() error {
555 scanner := bufio.NewScanner(e.in)
556 scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
557
558 // Send hello first. zut answers with hello_ack immediately; read it
559 // synchronously so extensions can use HostInfo while registering
560 // commands/tools before the ready frame.
561 if err := e.send(extproto.HelloFromExt{
562 Type: "hello",
563 ProtocolVersion: extproto.ProtocolVersion,
564 Name: e.name,
565 Version: e.version,
566 Capabilities: e.caps,
567 }); err != nil {
568 return err
569 }
570 if !scanner.Scan() {
571 return scanner.Err()
572 }
573 var ack extproto.HelloAckFromHost
574 if err := json.Unmarshal(scanner.Bytes(), &ack); err != nil {
575 return fmt.Errorf("parse hello_ack: %w", err)
576 }
577 if ack.Type != "hello_ack" {
578 return fmt.Errorf("first host frame must be hello_ack (got %q)", ack.Type)
579 }
580 if ack.ProtocolVersion != extproto.ProtocolVersion {
581 return fmt.Errorf("unsupported host protocol version %d (want %d)", ack.ProtocolVersion, extproto.ProtocolVersion)
582 }
583 e.host = HostInfo{
584 ProtocolVersion: ack.ProtocolVersion,
585 ZutVersion: ack.ZutVersion,
586 Provider: ack.Provider,
587 Model: ack.Model,
588 CWD: ack.CWD,
589 ExtensionDir: ack.ExtensionDir,
590 DataDir: ack.DataDir,
591 Session: ack.Session,
592 }
593 e.mu.Lock()
594 onHello := e.onHello
595 e.mu.Unlock()
596 if onHello != nil {
597 onHello(e.host)
598 }
599
600 // Re-announce all commands (covers Command calls made before Run and
601 // from OnHello, and is also fine for those made after via Command()'s
602 // direct send).
603 e.mu.Lock()
604 descs := append([]descTuple(nil), e.descriptions...)
605 toolDefs := append([]toolDef(nil), e.toolDefs...)
606 eventNames := append([]string(nil), e.eventNames...)
607 interceptTool := e.interceptOn
608 interceptTurn := e.interceptTurn != nil
609 interceptAsst := e.interceptAssistant != nil
610 e.mu.Unlock()
611 for _, d := range descs {
612 _ = e.send(extproto.RegisterCommandFromExt{
613 Type: "register_command",
614 Name: d.name,
615 Description: d.desc,
616 })
617 }
618 for _, td := range toolDefs {
619 _ = e.send(extproto.RegisterToolFromExt{
620 Type: "register_tool",
621 Name: td.name,
622 Description: td.description,
623 Schema: td.schema,
624 Deferred: td.deferred,
625 })
626 }
627 var intercepts []string
628 if interceptTool {
629 intercepts = append(intercepts, "tool_call")
630 }
631 if interceptTurn {
632 intercepts = append(intercepts, "turn_start")
633 }
634 if interceptAsst {
635 intercepts = append(intercepts, "assistant_message")
636 }
637 if len(eventNames) > 0 || len(intercepts) > 0 {
638 _ = e.send(extproto.SubscribeFromExt{
639 Type: "subscribe",
640 Events: eventNames,
641 Intercept: intercepts,
642 })
643 }
644 // Sentinel: tells the host that all initial registrations have
645 // been flushed and the agent registry can be built. Never block
646 // on this; if the host doesn't act on it, registrations still
647 // land in time for the typical use case.
648 _ = e.send(extproto.ReadyFromExt{Type: "ready"})
649
650 for scanner.Scan() {
651 line := scanner.Bytes()
652 var frame extproto.Frame
653 if err := json.Unmarshal(line, &frame); err != nil {
654 e.Logf("malformed frame from host: %v", err)
655 continue
656 }
657 switch frame.Type {
658 case "hello_ack":
659 // Already handled before registrations; ignore duplicates.
660 case "command_invoked":
661 var ci extproto.CommandInvokedFromHost
662 if err := json.Unmarshal(line, &ci); err != nil {
663 continue
664 }
665 e.mu.Lock()
666 fn := e.commands[ci.Name]
667 e.mu.Unlock()
668 if fn == nil {
669 e.respond(ci.ID, Errorf("no handler for /%s", ci.Name))
670 continue
671 }
672 // Run the handler on its own goroutine so a slow handler
673 // doesn't block subsequent commands. Order isn't promised.
674 go func(id string, fn CommandHandler, args string) {
675 defer func() {
676 if r := recover(); r != nil {
677 e.respond(id, Errorf("panic: %v", r))
678 }
679 }()
680 resp := fn(args)
681 e.respond(id, resp)
682 }(ci.ID, fn, ci.Args)
683 case "tool_call":
684 var tc extproto.ToolCallFromHost
685 if err := json.Unmarshal(line, &tc); err != nil {
686 continue
687 }
688 e.mu.Lock()
689 fn := e.tools[tc.Name]
690 e.mu.Unlock()
691 if fn == nil {
692 e.respondTool(tc.ID, TextErrorResult(fmt.Sprintf("no handler for tool %q", tc.Name)))
693 continue
694 }
695 go func(id string, fn ToolHandler, args json.RawMessage) {
696 defer func() {
697 if r := recover(); r != nil {
698 e.respondTool(id, TextErrorResult(fmt.Sprintf("panic: %v", r)))
699 }
700 }()
701 res := fn(args)
702 e.respondTool(id, res)
703 }(tc.ID, fn, tc.Args)
704 case "event":
705 var ef extproto.EventFromHost
706 if err := json.Unmarshal(line, &ef); err != nil {
707 continue
708 }
709 e.mu.Lock()
710 handler := e.eventHandlers[ef.Event]
711 e.mu.Unlock()
712 if handler != nil {
713 func() {
714 defer func() {
715 if r := recover(); r != nil {
716 e.Logf("event %s handler panicked: %v", ef.Event, r)
717 }
718 }()
719 handler(Event{
720 Name: ef.Event, Session: ef.Session, State: append(json.RawMessage(nil), ef.State...),
721 Step: ef.Step, Stop: ef.Stop,
722 Error: ef.Error, ToolID: ef.ToolID, ToolName: ef.ToolName,
723 ToolArgs: ef.ToolArgs, ToolPreview: ef.ToolPreview, Text: ef.Text,
724 })
725 }()
726 }
727 case "event_intercept":
728 var ei extproto.EventInterceptFromHost
729 if err := json.Unmarshal(line, &ei); err != nil {
730 continue
731 }
732 go e.dispatchIntercept(ei)
733 case "panel_key":
734 var pk extproto.PanelKeyFromHost
735 if err := json.Unmarshal(line, &pk); err != nil {
736 continue
737 }
738 e.mu.Lock()
739 h := e.panelKeys[pk.PanelID]
740 e.mu.Unlock()
741 if h != nil {
742 go h(pk.Key, pk.Text)
743 }
744 case "panel_close":
745 var pc extproto.PanelCloseFromHost
746 if err := json.Unmarshal(line, &pc); err != nil {
747 continue
748 }
749 e.mu.Lock()
750 h := e.panelCloses[pc.PanelID]
751 e.mu.Unlock()
752 if h != nil {
753 go h()
754 }
755 case "shutdown":
756 _ = e.send(extproto.ShutdownAckFromExt{Type: "shutdown_ack"})
757 return nil
758 default:
759 e.Logf("unknown frame type %q", frame.Type)
760 }
761 }
762 return scanner.Err()
763}
764
765// respond serialises a CommandResponseFromExt for the given id.
766func (e *Extension) respond(id string, r Response) {
767 if r.Action == "" {
768 r.Action = "noop"
769 }
770 var panel *extproto.PanelSpec
771 if r.OpenPanel != nil {
772 panel = &extproto.PanelSpec{ID: r.OpenPanel.ID, Title: r.OpenPanel.Title, Lines: r.OpenPanel.Lines, Footer: r.OpenPanel.Footer}
773 }
774 _ = e.send(extproto.CommandResponseFromExt{
775 Type: "command_response",
776 ID: id,
777 Action: r.Action,
778 Prompt: r.Prompt,
779 Insert: r.Insert,
780 Display: r.Display,
781 OpenPanel: panel,
782 Error: r.Error,
783 })
784}
785
786// respondTool serialises a ToolResultFromExt for the given id.
787func (e *Extension) respondTool(id string, r ToolResult) {
788 blocks := make([]extproto.ContentBlock, 0, len(r.Content))
789 for _, c := range r.Content {
790 blocks = append(blocks, extproto.ContentBlock{
791 Type: c.Type,
792 Text: c.Text,
793 MimeType: c.MimeType,
794 Data: c.Data,
795 })
796 }
797 _ = e.send(extproto.ToolResultFromExt{
798 Type: "tool_result",
799 ID: id,
800 Content: blocks,
801 IsError: r.IsError,
802 ActivateTools: r.ActivateTools,
803 Details: append(json.RawMessage(nil), r.Details...),
804 })
805}
806
807// send marshals v + LF and writes it under a mutex (so concurrent
808// goroutines don't interleave bytes on stdout).
809func (e *Extension) send(v any) error {
810 b, err := extproto.Encode(v)
811 if err != nil {
812 return err
813 }
814 e.writeMu.Lock()
815 defer e.writeMu.Unlock()
816 _, err = e.out.Write(b)
817 return err
818}
819
820// dispatchIntercept runs the per-event handler (tool_call / turn_start
821// / assistant_message) on its own goroutine, catches panics, and
822// always emits exactly one event_intercept_response. Called from the
823// Run loop.
824func (e *Extension) dispatchIntercept(ei extproto.EventInterceptFromHost) {
825 defer func() {
826 if r := recover(); r != nil {
827 _ = e.send(extproto.EventInterceptResponseFromExt{
828 Type: "event_intercept_response",
829 ID: ei.ID,
830 Block: true,
831 Reason: fmt.Sprintf("intercept panic: %v", r),
832 })
833 }
834 }()
835
836 resp := extproto.EventInterceptResponseFromExt{
837 Type: "event_intercept_response",
838 ID: ei.ID,
839 }
840
841 switch ei.Event {
842 case "tool_call":
843 e.mu.Lock()
844 rich := e.interceptToolRich
845 plain := e.interceptTool
846 e.mu.Unlock()
847 if rich != nil {
848 d := rich(ei.ToolName, ei.ToolArgs)
849 resp.Block = d.Block
850 resp.Reason = d.Reason
851 if !d.Block && len(d.ModifiedArgs) > 0 && json.Valid(d.ModifiedArgs) {
852 resp.ModifiedArgs = d.ModifiedArgs
853 }
854 } else if plain != nil {
855 allow, reason := plain(ei.ToolName, ei.ToolArgs)
856 resp.Block = !allow
857 resp.Reason = reason
858 }
859 case "turn_start":
860 e.mu.Lock()
861 fn := e.interceptTurn
862 e.mu.Unlock()
863 if fn != nil {
864 d := fn(ei.Step)
865 resp.Block = d.Block
866 resp.Reason = d.Reason
867 if !d.Block {
868 resp.Context = d.Context
869 }
870 }
871 case "assistant_message":
872 e.mu.Lock()
873 fn := e.interceptAssistant
874 e.mu.Unlock()
875 if fn != nil {
876 d := fn(ei.Text)
877 resp.Block = d.Block
878 resp.Reason = d.Reason
879 if !d.Block && d.ReplaceText != "" && d.ReplaceText != ei.Text {
880 resp.ReplaceText = d.ReplaceText
881 }
882 }
883 }
884
885 _ = e.send(resp)
886}