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// Conflicts with active built-in tool names (read, write, edit, bash,
424// create_worktree, grep, lsp, web_search, and skill) are silently shadowed by
425// the built-in. The native web_search and grep names are reserved even when
426// those built-ins are disabled, so an extension cannot claim or replace them.
427func (e *Extension) Tool(name, description string, schema json.RawMessage, fn ToolHandler) {
428 e.registerTool(name, description, schema, false, fn)
429}
430
431// DeferredTool registers a tool whose definition stays hidden until another
432// tool result names it in ActivateTools.
433func (e *Extension) DeferredTool(name, description string, schema json.RawMessage, fn ToolHandler) {
434 e.registerTool(name, description, schema, true, fn)
435}
436
437func (e *Extension) registerTool(name, description string, schema json.RawMessage, deferred bool, fn ToolHandler) {
438 e.mu.Lock()
439 e.tools[name] = fn
440 e.toolDefs = append(e.toolDefs, toolDef{name: name, description: description, schema: schema, deferred: deferred})
441 e.mu.Unlock()
442}
443
444// On subscribes to a lifecycle event. fn is called for each
445// notification; the same name can only have one handler (later
446// registrations replace earlier ones). Recognised names include:
447// session_start, session_opened, session_switched, session_forked,
448// session_compacted, turn_start, turn_end, tool_call,
449// tool_confirmation_requested, assistant_message.
450func (e *Extension) On(name string, fn EventHandler) {
451 e.mu.Lock()
452 if _, exists := e.eventHandlers[name]; !exists {
453 e.eventNames = append(e.eventNames, name)
454 }
455 e.eventHandlers[name] = fn
456 e.mu.Unlock()
457}
458
459// InterceptToolCall registers a guard that runs immediately before
460// each tool call. Returning (false, reason) refuses the call; the
461// model sees reason as the tool error text. Multiple extensions can
462// install interceptors; if any one refuses, the call is blocked.
463//
464// Use this to build permission gates: refuse `bash` calls containing
465// `rm -rf`, ask the user for confirmation on dangerous patterns,
466// audit-log every call, etc.
467//
468// For the richer form (arg rewrites, structured decisions) use
469// InterceptToolCallX.
470func (e *Extension) InterceptToolCall(fn InterceptHandler) {
471 e.mu.Lock()
472 e.interceptTool = fn
473 e.interceptOn = true
474 e.mu.Unlock()
475}
476
477// InterceptToolCallX is the richer variant. Return a ToolCallDecision
478// to block, allow, or rewrite args mid-flight. If both
479// InterceptToolCall and InterceptToolCallX are set, the X form wins.
480func (e *Extension) InterceptToolCallX(fn ToolCallHandler) {
481 e.mu.Lock()
482 e.interceptToolRich = fn
483 e.interceptOn = true
484 e.mu.Unlock()
485}
486
487// InterceptTurnStart registers a guard that runs before every turn's
488// model call. Return Block=true with Reason to abort the turn.
489// Useful for deny-by-default gates and usage quotas.
490func (e *Extension) InterceptTurnStart(fn TurnStartHandler) {
491 e.mu.Lock()
492 e.interceptTurn = fn
493 e.mu.Unlock()
494}
495
496// InterceptAssistantMessage registers a guard that runs after the
497// model's final text is assembled but before it's shown. Return
498// Block=true to suppress entirely, or ReplaceText to rewrite what
499// the user sees. The model's original output stays in the transcript.
500func (e *Extension) InterceptAssistantMessage(fn AssistantMessageHandler) {
501 e.mu.Lock()
502 e.interceptAssistant = fn
503 e.mu.Unlock()
504}
505
506// Notify pushes an info-level status note into zut's chat without
507// requiring a slash command from the user.
508func (e *Extension) Notify(level, message string) {
509 _ = e.send(extproto.NotifyFromExt{
510 Type: "notify",
511 Level: level,
512 Message: message,
513 })
514}
515
516// SetStatus replaces one persistent status item owned by this extension.
517// Passing an empty text clears the item.
518func (e *Extension) SetStatus(key, text string) {
519 _ = e.send(extproto.StatusFromExt{Type: "status", Key: key, Text: text})
520}
521
522// ClearStatus removes one persistent status item owned by this extension.
523func (e *Extension) ClearStatus(key string) { e.SetStatus(key, "") }
524
525const (
526 // WidgetPositionAboveInput keeps a widget in the persistent chrome above
527 // the editor. It is the default for empty and unknown positions.
528 WidgetPositionAboveInput = extproto.WidgetPositionAboveInput
529 // WidgetPositionRightBar keeps a widget in the host-owned side rail when
530 // the terminal is wide enough; narrow terminals fall back above the input.
531 WidgetPositionRightBar = extproto.WidgetPositionRightBar
532)
533
534// SetWidget replaces one persistent widget owned by this extension. Use
535// WidgetPositionAboveInput or WidgetPositionRightBar for the position.
536func (e *Extension) SetWidget(id, position, title string, lines []string) {
537 _ = e.send(extproto.WidgetFromExt{Type: "widget", ID: id, Position: position, Title: title, Lines: lines})
538}
539
540// ClearWidget removes one persistent widget owned by this extension.
541func (e *Extension) ClearWidget(id string) {
542 _ = e.send(extproto.ClearWidgetFromExt{Type: "widget_clear", ID: id})
543}
544
545// Alert asks the host to surface a structured alert. It is fire-and-forget;
546// hosts that do not support the requested kind may ignore it.
547func (e *Extension) Alert(alert AlertRequest) {
548 _ = e.send(extproto.AlertFromExt{
549 Type: "alert",
550 AlertRequest: alert,
551 })
552}
553
554// Run starts the protocol loop. Blocks until stdin closes (zut has
555// shut us down). Returns the first fatal error, or nil on clean exit.
556func (e *Extension) Run() error {
557 scanner := bufio.NewScanner(e.in)
558 scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
559
560 // Send hello first. zut answers with hello_ack immediately; read it
561 // synchronously so extensions can use HostInfo while registering
562 // commands/tools before the ready frame.
563 if err := e.send(extproto.HelloFromExt{
564 Type: "hello",
565 ProtocolVersion: extproto.ProtocolVersion,
566 Name: e.name,
567 Version: e.version,
568 Capabilities: e.caps,
569 }); err != nil {
570 return err
571 }
572 if !scanner.Scan() {
573 return scanner.Err()
574 }
575 var ack extproto.HelloAckFromHost
576 if err := json.Unmarshal(scanner.Bytes(), &ack); err != nil {
577 return fmt.Errorf("parse hello_ack: %w", err)
578 }
579 if ack.Type != "hello_ack" {
580 return fmt.Errorf("first host frame must be hello_ack (got %q)", ack.Type)
581 }
582 if ack.ProtocolVersion != extproto.ProtocolVersion {
583 return fmt.Errorf("unsupported host protocol version %d (want %d)", ack.ProtocolVersion, extproto.ProtocolVersion)
584 }
585 e.host = HostInfo{
586 ProtocolVersion: ack.ProtocolVersion,
587 ZutVersion: ack.ZutVersion,
588 Provider: ack.Provider,
589 Model: ack.Model,
590 CWD: ack.CWD,
591 ExtensionDir: ack.ExtensionDir,
592 DataDir: ack.DataDir,
593 Session: ack.Session,
594 }
595 e.mu.Lock()
596 onHello := e.onHello
597 e.mu.Unlock()
598 if onHello != nil {
599 onHello(e.host)
600 }
601
602 // Re-announce all commands (covers Command calls made before Run and
603 // from OnHello, and is also fine for those made after via Command()'s
604 // direct send).
605 e.mu.Lock()
606 descs := append([]descTuple(nil), e.descriptions...)
607 toolDefs := append([]toolDef(nil), e.toolDefs...)
608 eventNames := append([]string(nil), e.eventNames...)
609 interceptTool := e.interceptOn
610 interceptTurn := e.interceptTurn != nil
611 interceptAsst := e.interceptAssistant != nil
612 e.mu.Unlock()
613 for _, d := range descs {
614 _ = e.send(extproto.RegisterCommandFromExt{
615 Type: "register_command",
616 Name: d.name,
617 Description: d.desc,
618 })
619 }
620 for _, td := range toolDefs {
621 _ = e.send(extproto.RegisterToolFromExt{
622 Type: "register_tool",
623 Name: td.name,
624 Description: td.description,
625 Schema: td.schema,
626 Deferred: td.deferred,
627 })
628 }
629 var intercepts []string
630 if interceptTool {
631 intercepts = append(intercepts, "tool_call")
632 }
633 if interceptTurn {
634 intercepts = append(intercepts, "turn_start")
635 }
636 if interceptAsst {
637 intercepts = append(intercepts, "assistant_message")
638 }
639 if len(eventNames) > 0 || len(intercepts) > 0 {
640 _ = e.send(extproto.SubscribeFromExt{
641 Type: "subscribe",
642 Events: eventNames,
643 Intercept: intercepts,
644 })
645 }
646 // Sentinel: tells the host that all initial registrations have
647 // been flushed and the agent registry can be built. Never block
648 // on this; if the host doesn't act on it, registrations still
649 // land in time for the typical use case.
650 _ = e.send(extproto.ReadyFromExt{Type: "ready"})
651
652 for scanner.Scan() {
653 line := scanner.Bytes()
654 var frame extproto.Frame
655 if err := json.Unmarshal(line, &frame); err != nil {
656 e.Logf("malformed frame from host: %v", err)
657 continue
658 }
659 switch frame.Type {
660 case "hello_ack":
661 // Already handled before registrations; ignore duplicates.
662 case "command_invoked":
663 var ci extproto.CommandInvokedFromHost
664 if err := json.Unmarshal(line, &ci); err != nil {
665 continue
666 }
667 e.mu.Lock()
668 fn := e.commands[ci.Name]
669 e.mu.Unlock()
670 if fn == nil {
671 e.respond(ci.ID, Errorf("no handler for /%s", ci.Name))
672 continue
673 }
674 // Run the handler on its own goroutine so a slow handler
675 // doesn't block subsequent commands. Order isn't promised.
676 go func(id string, fn CommandHandler, args string) {
677 defer func() {
678 if r := recover(); r != nil {
679 e.respond(id, Errorf("panic: %v", r))
680 }
681 }()
682 resp := fn(args)
683 e.respond(id, resp)
684 }(ci.ID, fn, ci.Args)
685 case "tool_call":
686 var tc extproto.ToolCallFromHost
687 if err := json.Unmarshal(line, &tc); err != nil {
688 continue
689 }
690 e.mu.Lock()
691 fn := e.tools[tc.Name]
692 e.mu.Unlock()
693 if fn == nil {
694 e.respondTool(tc.ID, TextErrorResult(fmt.Sprintf("no handler for tool %q", tc.Name)))
695 continue
696 }
697 go func(id string, fn ToolHandler, args json.RawMessage) {
698 defer func() {
699 if r := recover(); r != nil {
700 e.respondTool(id, TextErrorResult(fmt.Sprintf("panic: %v", r)))
701 }
702 }()
703 res := fn(args)
704 e.respondTool(id, res)
705 }(tc.ID, fn, tc.Args)
706 case "event":
707 var ef extproto.EventFromHost
708 if err := json.Unmarshal(line, &ef); err != nil {
709 continue
710 }
711 e.mu.Lock()
712 handler := e.eventHandlers[ef.Event]
713 e.mu.Unlock()
714 if handler != nil {
715 func() {
716 defer func() {
717 if r := recover(); r != nil {
718 e.Logf("event %s handler panicked: %v", ef.Event, r)
719 }
720 }()
721 handler(Event{
722 Name: ef.Event, Session: ef.Session, State: append(json.RawMessage(nil), ef.State...),
723 Step: ef.Step, Stop: ef.Stop,
724 Error: ef.Error, ToolID: ef.ToolID, ToolName: ef.ToolName,
725 ToolArgs: ef.ToolArgs, ToolPreview: ef.ToolPreview, Text: ef.Text,
726 })
727 }()
728 }
729 case "event_intercept":
730 var ei extproto.EventInterceptFromHost
731 if err := json.Unmarshal(line, &ei); err != nil {
732 continue
733 }
734 go e.dispatchIntercept(ei)
735 case "panel_key":
736 var pk extproto.PanelKeyFromHost
737 if err := json.Unmarshal(line, &pk); err != nil {
738 continue
739 }
740 e.mu.Lock()
741 h := e.panelKeys[pk.PanelID]
742 e.mu.Unlock()
743 if h != nil {
744 go h(pk.Key, pk.Text)
745 }
746 case "panel_close":
747 var pc extproto.PanelCloseFromHost
748 if err := json.Unmarshal(line, &pc); err != nil {
749 continue
750 }
751 e.mu.Lock()
752 h := e.panelCloses[pc.PanelID]
753 e.mu.Unlock()
754 if h != nil {
755 go h()
756 }
757 case "shutdown":
758 _ = e.send(extproto.ShutdownAckFromExt{Type: "shutdown_ack"})
759 return nil
760 default:
761 e.Logf("unknown frame type %q", frame.Type)
762 }
763 }
764 return scanner.Err()
765}
766
767// respond serialises a CommandResponseFromExt for the given id.
768func (e *Extension) respond(id string, r Response) {
769 if r.Action == "" {
770 r.Action = "noop"
771 }
772 var panel *extproto.PanelSpec
773 if r.OpenPanel != nil {
774 panel = &extproto.PanelSpec{ID: r.OpenPanel.ID, Title: r.OpenPanel.Title, Lines: r.OpenPanel.Lines, Footer: r.OpenPanel.Footer}
775 }
776 _ = e.send(extproto.CommandResponseFromExt{
777 Type: "command_response",
778 ID: id,
779 Action: r.Action,
780 Prompt: r.Prompt,
781 Insert: r.Insert,
782 Display: r.Display,
783 OpenPanel: panel,
784 Error: r.Error,
785 })
786}
787
788// respondTool serialises a ToolResultFromExt for the given id.
789func (e *Extension) respondTool(id string, r ToolResult) {
790 blocks := make([]extproto.ContentBlock, 0, len(r.Content))
791 for _, c := range r.Content {
792 blocks = append(blocks, extproto.ContentBlock{
793 Type: c.Type,
794 Text: c.Text,
795 MimeType: c.MimeType,
796 Data: c.Data,
797 })
798 }
799 _ = e.send(extproto.ToolResultFromExt{
800 Type: "tool_result",
801 ID: id,
802 Content: blocks,
803 IsError: r.IsError,
804 ActivateTools: r.ActivateTools,
805 Details: append(json.RawMessage(nil), r.Details...),
806 })
807}
808
809// send marshals v + LF and writes it under a mutex (so concurrent
810// goroutines don't interleave bytes on stdout).
811func (e *Extension) send(v any) error {
812 b, err := extproto.Encode(v)
813 if err != nil {
814 return err
815 }
816 e.writeMu.Lock()
817 defer e.writeMu.Unlock()
818 _, err = e.out.Write(b)
819 return err
820}
821
822// dispatchIntercept runs the per-event handler (tool_call / turn_start
823// / assistant_message) on its own goroutine, catches panics, and
824// always emits exactly one event_intercept_response. Called from the
825// Run loop.
826func (e *Extension) dispatchIntercept(ei extproto.EventInterceptFromHost) {
827 defer func() {
828 if r := recover(); r != nil {
829 _ = e.send(extproto.EventInterceptResponseFromExt{
830 Type: "event_intercept_response",
831 ID: ei.ID,
832 Block: true,
833 Reason: fmt.Sprintf("intercept panic: %v", r),
834 })
835 }
836 }()
837
838 resp := extproto.EventInterceptResponseFromExt{
839 Type: "event_intercept_response",
840 ID: ei.ID,
841 }
842
843 switch ei.Event {
844 case "tool_call":
845 e.mu.Lock()
846 rich := e.interceptToolRich
847 plain := e.interceptTool
848 e.mu.Unlock()
849 if rich != nil {
850 d := rich(ei.ToolName, ei.ToolArgs)
851 resp.Block = d.Block
852 resp.Reason = d.Reason
853 if !d.Block && len(d.ModifiedArgs) > 0 && json.Valid(d.ModifiedArgs) {
854 resp.ModifiedArgs = d.ModifiedArgs
855 }
856 } else if plain != nil {
857 allow, reason := plain(ei.ToolName, ei.ToolArgs)
858 resp.Block = !allow
859 resp.Reason = reason
860 }
861 case "turn_start":
862 e.mu.Lock()
863 fn := e.interceptTurn
864 e.mu.Unlock()
865 if fn != nil {
866 d := fn(ei.Step)
867 resp.Block = d.Block
868 resp.Reason = d.Reason
869 if !d.Block {
870 resp.Context = d.Context
871 }
872 }
873 case "assistant_message":
874 e.mu.Lock()
875 fn := e.interceptAssistant
876 e.mu.Unlock()
877 if fn != nil {
878 d := fn(ei.Text)
879 resp.Block = d.Block
880 resp.Reason = d.Reason
881 if !d.Block && d.ReplaceText != "" && d.ReplaceText != ei.Text {
882 resp.ReplaceText = d.ReplaceText
883 }
884 }
885 }
886
887 _ = e.send(resp)
888}