跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

ui.go

198 行 · 5.3 KB历史下载
1// Package ui asks questions on the terminal and prints agent-vm's boxed
2// notices, as 0.2's lib/ui.sh did.
3package ui
4
5import (
6 "fmt"
7 "io"
8 "os"
9 "regexp"
10 "strings"
11
12 "golang.org/x/term"
13)
14
15// UI asks on the controlling terminal and writes questions to Stderr.
16type UI struct {
17 Stderr io.Writer
18 // OpenTTY opens the terminal answers are read from (the process's
19 // own when nil; tests set their own).
20 OpenTTY func() (io.ReadCloser, error)
21 // StderrIsTerminal: where the questions go is seen by someone.
22 StderrIsTerminal bool
23 // Width of the terminal, for boxes; 0 asks the terminal.
24 Width int
25}
26
27// New is the UI of this process.
28func New() *UI {
29 return &UI{Stderr: os.Stderr, StderrIsTerminal: term.IsTerminal(int(os.Stderr.Fd()))}
30}
31
32func (u *UI) open() (io.ReadCloser, error) {
33 if u.OpenTTY != nil {
34 return u.OpenTTY()
35 }
36 return openTTY()
37}
38
39// HaveTTY reports whether a terminal can be opened: a device node that
40// exists does not say it (CI, cron), only opening it does.
41func (u *UI) HaveTTY() bool {
42 f, err := u.open()
43 if err != nil {
44 return false
45 }
46 f.Close()
47 return true
48}
49
50// CanAsk reports whether a question can be asked and seen: a terminal to
51// read the answer from, and stderr on a terminal too, or a caller capturing
52// stderr would wait on a question nobody sees.
53func (u *UI) CanAsk() bool {
54 return u.HaveTTY() && u.StderrIsTerminal
55}
56
57// line reads one line from the terminal, a byte at a time so that nothing
58// after it is taken from whoever reads next. "" when there is none.
59func (u *UI) line() string {
60 f, err := u.open()
61 if err != nil {
62 return ""
63 }
64 defer f.Close()
65 var b strings.Builder
66 var c [1]byte
67 for {
68 n, err := f.Read(c[:])
69 if n == 1 {
70 if c[0] == '\n' {
71 break
72 }
73 b.WriteByte(c[0])
74 }
75 if err != nil {
76 break
77 }
78 }
79 return strings.TrimSuffix(b.String(), "\r")
80}
81
82// Ask asks for a value, def when the answer is empty.
83func (u *UI) Ask(prompt, def string) string {
84 fmt.Fprintf(u.Stderr, " %s [%s]: ", prompt, def)
85 if r := u.line(); r != "" {
86 return r
87 }
88 return def
89}
90
91// AskYN asks a yes/no question; an empty answer is def.
92func (u *UI) AskYN(prompt string, def bool) bool {
93 ind, d := "[y/N]", "N"
94 if def {
95 ind, d = "[Y/n]", "Y"
96 }
97 fmt.Fprintf(u.Stderr, " %s %s: ", prompt, ind)
98 r := u.line()
99 if r == "" {
100 r = d
101 }
102 return r[0] == 'y' || r[0] == 'Y'
103}
104
105var positiveRe = regexp.MustCompile(`^[1-9][0-9]*$`)
106
107// AskInt asks for a positive integer, at most max when max > 0, until it
108// gets one: a typo such as "10G" is caught here.
109func (u *UI) AskInt(prompt string, def, max int) int {
110 for {
111 r := u.Ask(prompt, fmt.Sprint(def))
112 var n int
113 if positiveRe.MatchString(r) {
114 if _, err := fmt.Sscan(r, &n); err == nil && (max == 0 || n <= max) {
115 return n
116 }
117 }
118 if max > 0 {
119 fmt.Fprintf(u.Stderr, " (a number from 1 to %d; got: %s)\n", max, r)
120 } else {
121 fmt.Fprintf(u.Stderr, " (must be a positive integer, e.g. 10; got: %s)\n", r)
122 }
123 }
124}
125
126// AskChoice lists options, numbered from 1, and returns the number picked.
127func (u *UI) AskChoice(prompt string, def int, options ...string) int {
128 for i, o := range options {
129 fmt.Fprintf(u.Stderr, " %d) %s\n", i+1, o)
130 }
131 return u.AskInt(prompt, def, len(options))
132}
133
134// Wrap word-wraps s to width columns. Lines indented by two spaces are
135// commands, kept whole so they can be copied.
136func Wrap(s string, width int) string {
137 var out []string
138 for _, l := range strings.Split(strings.TrimSuffix(s, "\n"), "\n") {
139 if strings.HasPrefix(l, " ") || len(l) <= width {
140 out = append(out, l)
141 continue
142 }
143 line := ""
144 for _, w := range strings.Fields(l) {
145 switch {
146 case line == "":
147 line = w
148 case len(line)+1+len(w) <= width:
149 line += " " + w
150 default:
151 out = append(out, line)
152 line = w
153 }
154 }
155 out = append(out, line)
156 }
157 return strings.Join(out, "\n") + "\n"
158}
159
160// Box prints body on Stderr as a boxed notice, for the warnings and offers
161// of setup and of a start: one paragraph per line, wrapped to the terminal
162// (72 columns at most). No right border: it would need every line padded to
163// its display width, unknown for non-ASCII text.
164func (u *UI) Box(title, body string) {
165 width := u.Width
166 if width == 0 {
167 width = 72
168 if f, err := u.open(); err == nil {
169 if fd, ok := f.(interface{ Fd() uintptr }); ok {
170 if w, _, err := term.GetSize(int(fd.Fd())); err == nil {
171 width = w
172 }
173 }
174 f.Close()
175 }
176 }
177 width = min(max(width, 30), 72)
178 rule := strings.Repeat("-", width)
179 n := max(width-len(title)-4, 1)
180 var b strings.Builder
181 fmt.Fprintf(&b, "\n+- %s %s\n|\n", title, rule[:n])
182 for _, l := range strings.Split(strings.TrimSuffix(Wrap(body, width-2), "\n"), "\n") {
183 b.WriteString(strings.TrimRight("| "+l, " ") + "\n")
184 }
185 fmt.Fprintf(&b, "|\n+%s\n", rule[:width-1])
186 fmt.Fprint(u.Stderr, b.String())
187}
188
189// ResetTermModes turns off the input modes a full-screen program in the VM
190// may have left on when it was killed or its connection dropped: mouse
191// tracking, focus reports, bracketed paste, the kitty keyboard protocol and
192// xterm's modifyOtherKeys, each of which types escape sequences into the
193// host shell otherwise. Also shows the cursor. Only on a terminal.
194func ResetTermModes(stdout *os.File) {
195 if term.IsTerminal(int(stdout.Fd())) {
196 fmt.Fprint(stdout, "\033[?1000l\033[?1002l\033[?1003l\033[?1006l\033[?1015l\033[?1004l\033[?2004l\033[<u\033[>4;0m\033[?25h")
197 }
198}