Files
zero/internal/cli/exec_writer.go
6fb0231df8 TUI scrollback re-architecture, Lime chat surface, and deep-audit fixes (#158)
* docs(design): add Lime TUI prototype and rebuild spec

* tui: remove the zeroline skin system

One design remains in the tree ahead of the Lime rebuild: the zeroline
package, its TUI view/skin plumbing (Options.Skin/ThemeVariant/ThemeDark,
model skin branches, theme picker), and the zeroline CLI subcommand are
gone. /theme keeps its shell-only message.

* tui: replace the cyan palette with the Lime token table

theme.go is rebuilt around the Lime design tokens (docs/design/
zero_tui_lime.html): near-black panels, one lime accent, solid tint
stand-ins for the prototype's rgba overlays. Existing render sites map
onto the new role styles (ink/line/userPrompt/toolName/toolArg) without
layout changes; no hex exists outside theme.go.

* tui: build the Lime chat-surface components

Title bar with brand badge + context window, empty state replacing the
deleted splash (block-art 0, tagline, 1-3 starter suggestions), stream
blocks (user prompt gutter, muted interim with cursor, final-answer
accent rail, done line, bordered notes), tool cards with diff/read/
bash/grep bodies and MiniDot run spinner, borderless composer with
run-state hints, and the grouped status line. Final answers are marked
at append time; resolved tool calls collapse into their result cards.

* tui: fix Stage 2 review findings

Adversarial review of the chat-surface commit confirmed 15 issues, all
fixed here:
- wrapPlainText sliced wide runes by rune count: CJK/emoji prose could
  panic the TUI or emit lines ~2x the measure; split at width instead
- a cancelled run's streamingText leaked into the next turn's interim
  block; cancelRun now clears it
- orphaned tool-call cards (cancelled/errored turns) re-animated with
  the spinner on any later run; the glyph is now scoped to the call's
  own runID
- starter-suggestion digit capture was active while the chips were off
  screen (/clear mid-run); the guard now mirrors the render condition
- prompt submits while a deferred Ctrl+C quit is draining could start a
  run the quit would orphan; submission is blocked while exiting
- the running placeholder advertised ctrl+c (which quits) as the
  interrupt key; it now says esc
- read-card parser expected 'N: text' but read_file emits 'N | text',
  so the gutter and L-range never rendered on real output
- toolCard borders were one column short of the body rows
- diff tint bands now span the full row; NEW FILE renders green on
  addBg; preamble/no-newline lines are unnumbered meta and no longer
  shift hunk numbering
- card bodies and system notes paint the panel surface; the head gains
  the separate faintest arg column (grep target + pattern)
- title-bar overflow now truncates the minimal candidate instead of
  rendering the deleted design's 'ZERO … READY' line
- untracked the stray snake-game.html (left on disk, ignored)

* tui: restyle the interactive surfaces for Lime

Permission prompts render as the amber permission card (PERMISSION
badge, risk readout, key chips); resolved prompts collapse to one line
(allowed once/always/denied · tool) and unprompted allows fold into the
tool card's [auto] tag. Ask-user and spec-review prompts share the card
language with line borders. Autocomplete and picker overlays move onto
the panel/selection tints with the accent ❯ marker; model-picker rows
gain the provider dot and ctx · KEY_ENV metadata from the registry and
provider catalog. /resume renders its list as stacked session cards
(id + age, title, meta). Key handling is untouched everywhere.

* tui: adaptive width tiers, doc updates, final polish

Width tiers re-evaluate from the live width: ≥100 renders the full
spec; 80–99 drops the tool-arg column, header ctx, and the status
'interactive' group; 58–79 drops the diff/read gutters, bares the
badge, and keeps provider+tokens+mode; <58 renders a single-segment
header, rail-less cards, and a mode-only status line. Table-driven
tests cover {58,70,80,100,120} plus a frame-wide invariant that no
emitted line exceeds the terminal at any tier. Card bodies expand tabs
so width math holds. Dead splash-chip machinery (startupCommandNames,
startupOrder) is gone; README's TUI section now describes Lime.

* tui: fix final-review findings across Stages 3-4

A second adversarial review confirmed 14 issues, all addressed:
- permission collapse and tool-card pairing are now run-scoped (rcKey):
  providers with repeating synthetic ToolCallIDs (Gemini gemini_tool_N)
  could attribute a decision or result to a different run's call
- rehydrated always-grants no longer mislabel as 'allowed once'
  (GrantMatched fallback)
- the width invariant now actually holds everywhere: empty-state
  tagline/hint, ask-user rows, permission detail blobs, pending image
  chips, and the sessions trailing hint are wrapped or fitted; the
  invariant test renders the empty state and all of those rows at
  widths 24-120
- every card (permission, ask-user, spec-review, sessions, notes)
  drops side borders on tiny terminals, not just tool cards
- /resume card fields are sanitized against separator bytes from
  user-controlled titles
- the picker's selected row paints its gap so the selBg band is solid
- dead splash helpers (normalizedStartupWidth, countLines, nonEmpty,
  unreachable rowWelcome branch) and stale /theme comments are gone
- README no longer claims transcript scrolling keys or Tab-accept
  behavior that never existed; chatWidth documents its 24-col floor

Tag tui-lime-s4 moves to this commit.

* audit: deep-audit report, TUI scrollback re-architecture, and cross-module fixes

TUI: settled-row flush frontier prints history to native terminal
scrollback (tea.Println, ordered + ack-serialized); View() renders only
the live tail. Full diffs (400-line flush cap) and OSC 8 file:// links
land in history; streamed interim text, cancellation markers, ask_user
exchanges, and composer input history are preserved; run-scoped dedup
keys fix Gemini's repeating tool-call ids; /exit, Ctrl+C-after-Esc, and
cross-session late flushes no longer orphan or contaminate checkpoints.

Cross-module: zero search panic + offset mapping, usage report
robustness, 529 retry, SSE keep-alive watchdog, registry corrections,
update --check on dev builds, MCP ping + mcp list --json secret
redaction, sandbox.network config knob, doctor apiKey presence, atomic
config writes, C1-safe notifications, rune-safe truncation everywhere,
gofmt + vet CI gates, dead glamour dependency dropped.

Full audit report: docs/audit/2026-06-10-deep-audit.md (175 findings).

Co-Authored-By: Claude Fable 5 <[email protected]>

* tui: hide malformed ask_user tool errors

* fix tui malformed tool retries

* fix max-turn finalization

* upgrade tui agent guardrails

* fix coderabbit guardrail findings

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Vasanthdev2004 <[email protected]>
2026-06-10 17:18:30 +05:30

454 lines
12 KiB
Go

package cli
import (
"encoding/json"
"io"
"strings"
"time"
"unicode/utf8"
"github.com/Gitlawb/zero/internal/agent"
"github.com/Gitlawb/zero/internal/sessions"
"github.com/Gitlawb/zero/internal/streamjson"
"github.com/Gitlawb/zero/internal/tools"
)
const streamJSONToolResultOutputLimit = 10 * 1024
type execRunMetadata struct {
Provider string
Model string
APIModel string
}
type execEventWriter struct {
stdout io.Writer
stderr io.Writer
format execOutputFormat
runID string
sessionID string
streamedText *strings.Builder
err error
}
func (writer *execEventWriter) runStart(cwd string, metadata execRunMetadata, permissionMode agent.PermissionMode) {
switch writer.format {
case execOutputJSON:
writer.writeJSON(map[string]any{
"type": "run_start",
"cwd": cwd,
"provider": metadata.Provider,
"model": metadata.Model,
"api_model": metadata.APIModel,
"permission_mode": string(permissionMode),
})
case execOutputStreamJSON:
writer.writeStreamJSON(streamjson.Event{
Type: streamjson.EventRunStart,
RunID: writer.runID,
SessionID: writer.sessionID,
Cwd: cwd,
Provider: metadata.Provider,
Model: metadata.Model,
APIModel: metadata.APIModel,
})
}
}
func (writer *execEventWriter) warning(message string) {
if writer.format == execOutputJSON {
writer.writeJSON(map[string]any{"type": "warning", "message": message})
return
}
if writer.format == execOutputStreamJSON {
writer.writeStreamJSON(streamjson.Event{Type: streamjson.EventWarning, RunID: writer.runID, Message: message})
return
}
writer.writeStderr("[zero] WARNING: " + message + "\n")
}
func (writer *execEventWriter) text(delta string) {
writer.streamedText.WriteString(delta)
if writer.format == execOutputJSON {
writer.writeJSON(map[string]any{"type": "text", "delta": delta})
return
}
if writer.format == execOutputStreamJSON {
writer.writeStreamJSON(streamjson.Event{Type: streamjson.EventText, RunID: writer.runID, Delta: delta})
return
}
writer.writeStdout(delta)
}
func (writer *execEventWriter) toolCall(call agent.ToolCall, registry *tools.Registry) {
if writer.format == execOutputJSON {
writer.writeJSON(map[string]any{
"type": "tool_call",
"id": call.ID,
"name": call.Name,
"arguments": call.Arguments,
})
return
}
if writer.format == execOutputStreamJSON {
writer.writeStreamJSON(streamjson.Event{
Type: streamjson.EventToolCall,
RunID: writer.runID,
ID: call.ID,
Name: call.Name,
Args: parseToolCallArgs(call.Arguments),
SideEffect: streamJSONSideEffect(call.Name, registry),
})
return
}
writer.writeStderr("[tool] " + call.Name + "\n")
}
func (writer *execEventWriter) checkpoint(event sessions.Event) {
var payload sessions.CheckpointPayload
if len(event.Payload) > 0 {
_ = json.Unmarshal(event.Payload, &payload)
}
files := make([]string, 0, len(payload.Files))
for _, f := range payload.Files {
files = append(files, f.Path)
}
switch writer.format {
case execOutputStreamJSON:
writer.writeStreamJSON(streamjson.Event{
Type: streamjson.EventCheckpoint,
RunID: writer.runID,
Checkpoint: &streamjson.CheckpointInfo{Sequence: event.Sequence, Tool: payload.Tool, Files: files},
})
case execOutputJSON:
writer.writeJSON(map[string]any{
"type": "checkpoint",
"sequence": event.Sequence,
"tool": payload.Tool,
"files": files,
})
}
// Plain text mode stays silent: checkpoints are background safety, not output.
}
func (writer *execEventWriter) toolResult(result agent.ToolResult) {
if writer.format == execOutputJSON {
payload := map[string]any{
"type": "tool_result",
"tool_call_id": result.ToolCallID,
"name": result.Name,
"status": string(result.Status),
"output": result.Output,
}
if len(result.Meta) > 0 {
payload["meta"] = result.Meta
}
if result.Redacted {
payload["redacted"] = true
}
if len(result.ChangedFiles) > 0 {
payload["changed_files"] = result.ChangedFiles
}
if result.Display.Summary != "" || result.Display.Kind != "" {
payload["display"] = map[string]string{"summary": result.Display.Summary, "kind": result.Display.Kind}
}
writer.writeJSON(payload)
return
}
if writer.format == execOutputStreamJSON {
output, truncated := truncateForStreamJSONOutput(result.Output)
event := streamjson.Event{
Type: streamjson.EventToolResult,
RunID: writer.runID,
ID: result.ToolCallID,
Name: result.Name,
Status: string(result.Status),
Output: output,
Truncated: &truncated,
ChangedFiles: result.ChangedFiles,
Meta: result.Meta,
}
if result.Redacted {
redacted := true
event.Redacted = &redacted
}
if result.Display.Summary != "" || result.Display.Kind != "" {
event.Display = &streamjson.Display{Summary: result.Display.Summary, Kind: result.Display.Kind}
}
writer.writeStreamJSON(event)
return
}
writer.writeStderr("[result] " + truncateForStatus(result.Output) + "\n")
}
func (writer *execEventWriter) permission(event agent.PermissionEvent) {
if writer.format == execOutputJSON {
payload := map[string]any{
"type": "permission",
"tool_call_id": event.ToolCallID,
"name": event.ToolName,
"action": string(event.Action),
"permission": event.Permission,
"permission_granted": event.PermissionGranted,
"permission_mode": string(event.PermissionMode),
"autonomy": event.Autonomy,
"side_effect": event.SideEffect,
"reason": event.Reason,
"decision_reason": event.DecisionReason,
"risk": event.Risk,
}
if event.Violation != nil {
payload["violation"] = event.Violation
}
if event.GrantMatched {
payload["grant_matched"] = true
}
if event.Grant != nil {
payload["grant"] = event.Grant
}
writer.writeJSON(payload)
return
}
if writer.format == execOutputStreamJSON {
risk := event.Risk
permissionGranted := event.PermissionGranted
writer.writeStreamJSON(streamjson.Event{
Type: streamJSONPermissionEventType(event),
RunID: writer.runID,
SessionID: writer.sessionID,
ID: event.ToolCallID,
Name: event.ToolName,
Action: string(event.Action),
Permission: event.Permission,
PermissionGranted: &permissionGranted,
PermissionMode: string(event.PermissionMode),
Autonomy: event.Autonomy,
SideEffect: event.SideEffect,
Reason: event.Reason,
DecisionReason: event.DecisionReason,
Risk: &risk,
Violation: event.Violation,
GrantMatched: event.GrantMatched,
Grant: event.Grant,
})
return
}
if event.Action != agent.PermissionActionAllow {
writer.writeStderr("[permission] " + event.ToolName + " " + string(event.Action) + ": " + event.Reason + "\n")
}
}
func streamJSONPermissionEventType(event agent.PermissionEvent) streamjson.EventType {
if event.Action == agent.PermissionActionPrompt {
return streamjson.EventPermissionRequest
}
if event.Action == agent.PermissionActionAllow || event.Action == agent.PermissionActionDeny {
return streamjson.EventPermissionDecision
}
return streamjson.EventPermission
}
func (writer *execEventWriter) usage(usage agent.Usage) {
if writer.format == execOutputJSON {
writer.writeJSON(map[string]any{
"type": "usage",
"prompt_tokens": usage.PromptTokens,
"completion_tokens": usage.CompletionTokens,
"total_tokens": usage.TotalTokens(),
})
return
}
if writer.format == execOutputStreamJSON {
promptTokens := usage.EffectiveInputTokens()
completionTokens := usage.EffectiveOutputTokens()
totalTokens := usage.TotalTokens()
writer.writeStreamJSON(streamjson.Event{
Type: streamjson.EventUsage,
RunID: writer.runID,
PromptTokens: &promptTokens,
CompletionTokens: &completionTokens,
TotalTokens: &totalTokens,
})
}
}
func (writer *execEventWriter) final(answer string) {
if writer.format == execOutputJSON {
writer.writeJSON(map[string]any{"type": "final", "text": answer})
writer.writeJSON(map[string]any{"type": "done", "exit_code": exitSuccess})
return
}
if writer.format == execOutputStreamJSON {
writer.writeStreamJSON(streamjson.Event{Type: streamjson.EventFinal, RunID: writer.runID, Text: answer})
return
}
if writer.streamedText.Len() == 0 && answer != "" {
writer.writeStdout(answer)
writer.streamedText.WriteString(answer)
}
if writer.streamedText.Len() > 0 && !strings.HasSuffix(writer.streamedText.String(), "\n") {
writer.writeStdout("\n")
}
}
func (writer *execEventWriter) errorEvent(code string, message string, recoverable bool) {
if writer.format == execOutputStreamJSON {
writer.writeStreamJSON(streamjson.Event{
Type: streamjson.EventError,
RunID: writer.runID,
Code: code,
Message: message,
Recoverable: &recoverable,
})
return
}
if writer.format == execOutputJSON {
writer.writeJSON(map[string]any{"type": "error", "code": code, "message": message})
return
}
writer.writeStderr("[zero] " + message + "\n")
}
func (writer *execEventWriter) runEnd(status string, exitCode int) {
if writer.format != execOutputStreamJSON {
return
}
writer.writeStreamJSON(streamjson.Event{
Type: streamjson.EventRunEnd,
RunID: writer.runID,
Status: status,
ExitCode: &exitCode,
})
}
func (writer *execEventWriter) writeStreamJSON(event streamjson.Event) {
if writer.err != nil {
return
}
line, err := streamjson.FormatEvent(event)
if err != nil {
writer.err = err
return
}
writer.writeStdout(line + "\n")
}
func (writer *execEventWriter) writeJSON(payload map[string]any) {
if writer.err != nil {
return
}
writer.err = writeJSONLine(writer.stdout, payload)
}
func (writer *execEventWriter) writeStdout(value string) {
if writer.err != nil {
return
}
_, writer.err = io.WriteString(writer.stdout, value)
}
func (writer *execEventWriter) writeStderr(value string) {
if writer.err != nil {
return
}
_, writer.err = io.WriteString(writer.stderr, value)
}
func writeJSONLine(w io.Writer, payload map[string]any) error {
data, err := json.Marshal(payload)
if err != nil {
return err
}
if _, err := w.Write(append(data, '\n')); err != nil {
return err
}
return nil
}
func parseToolCallArgs(arguments string) any {
if strings.TrimSpace(arguments) == "" {
return nil
}
var args any
if err := json.Unmarshal([]byte(arguments), &args); err != nil {
return arguments
}
return args
}
func streamJSONSideEffect(name string, registry *tools.Registry) string {
tool, ok := registry.Get(name)
if !ok {
return "unknown"
}
switch tool.Safety().SideEffect {
case tools.SideEffectRead:
return "read"
case tools.SideEffectWrite:
return "write"
case tools.SideEffectShell:
return "shell"
case tools.SideEffectNetwork:
return "network"
case tools.SideEffectNone:
return "none"
default:
return "unknown"
}
}
func truncateForStatus(value string) string {
compact := strings.Join(strings.Fields(value), " ")
if len(compact) > 200 {
return cutRuneBoundary(compact, 200) + "..."
}
return compact
}
func truncateForStreamJSONOutput(value string) (string, bool) {
if len(value) <= streamJSONToolResultOutputLimit {
return value, false
}
// Rune-boundary cut: stream-json is a machine-readable protocol and a
// mid-rune byte slice would emit invalid UTF-8 into it.
return cutRuneBoundary(value, streamJSONToolResultOutputLimit) + "\n[truncated]", true
}
// cutRuneBoundary truncates s to at most n bytes without splitting a UTF-8
// rune (the cut lands on the last rune boundary at or before n).
func cutRuneBoundary(s string, n int) string {
if n <= 0 {
return ""
}
if len(s) <= n {
return s
}
for n > 0 && !utf8.RuneStart(s[n]) {
n--
}
return s[:n]
}
func writeStreamJSONError(stdout io.Writer, code string, message string, recoverable bool, exitCode int) int {
runID, err := streamjson.CreateRunID(timeNow())
if err != nil {
return exitCrash
}
writer := execEventWriter{
stdout: stdout,
format: execOutputStreamJSON,
runID: runID,
}
writer.errorEvent(code, message, recoverable)
writer.runEnd("error", exitCode)
if writer.err != nil {
return exitCrash
}
return exitCode
}
func timeNow() time.Time {
return time.Now()
}