@sixb/cli 0.1.25 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/commands/agent.d.ts +16 -0
- package/dist/commands/agent.d.ts.map +1 -0
- package/dist/commands/api.d.ts.map +1 -1
- package/dist/commands/check.d.ts.map +1 -1
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/dev-runner.d.ts +0 -1
- package/dist/commands/dev-runner.d.ts.map +1 -1
- package/dist/commands/dev.d.ts.map +1 -1
- package/dist/commands/env.d.ts +31 -0
- package/dist/commands/env.d.ts.map +1 -0
- package/dist/commands/worker-group.d.ts +0 -1
- package/dist/commands/worker-group.d.ts.map +1 -1
- package/dist/commands/worker.d.ts +0 -1
- package/dist/commands/worker.d.ts.map +1 -1
- package/dist/lib/command-line.d.ts +41 -6
- package/dist/lib/command-line.d.ts.map +1 -1
- package/dist/lib/deploy-release.d.ts +2 -0
- package/dist/lib/deploy-release.d.ts.map +1 -1
- package/dist/lib/deploy-source.d.ts +2 -0
- package/dist/lib/deploy-source.d.ts.map +1 -1
- package/dist/lib/env-config.d.ts +17 -0
- package/dist/lib/env-config.d.ts.map +1 -0
- package/dist/lib/env-file.d.ts +16 -0
- package/dist/lib/env-file.d.ts.map +1 -0
- package/dist/lib/github-ci.d.ts.map +1 -1
- package/dist/lib/hidden-prompt.d.ts +19 -0
- package/dist/lib/hidden-prompt.d.ts.map +1 -0
- package/dist/lib/runtime.d.ts +0 -1
- package/dist/lib/runtime.d.ts.map +1 -1
- package/dist/lib/worker-registry.d.ts +0 -1
- package/dist/lib/worker-registry.d.ts.map +1 -1
- package/dist/tui/app.d.ts +27 -0
- package/dist/tui/app.d.ts.map +1 -0
- package/dist/tui/brand.d.ts +7 -0
- package/dist/tui/brand.d.ts.map +1 -0
- package/dist/tui/computer.d.ts +8 -0
- package/dist/tui/computer.d.ts.map +1 -0
- package/dist/tui/connection.d.ts +45 -0
- package/dist/tui/connection.d.ts.map +1 -0
- package/dist/tui/context.d.ts +13 -0
- package/dist/tui/context.d.ts.map +1 -0
- package/dist/tui/format.d.ts +118 -0
- package/dist/tui/format.d.ts.map +1 -0
- package/dist/tui/index.d.ts +12 -0
- package/dist/tui/index.d.ts.map +1 -0
- package/dist/tui/markdown.d.ts +18 -0
- package/dist/tui/markdown.d.ts.map +1 -0
- package/dist/tui/palette.d.ts +25 -0
- package/dist/tui/palette.d.ts.map +1 -0
- package/dist/tui/parts.d.ts +74 -0
- package/dist/tui/parts.d.ts.map +1 -0
- package/dist/tui/runner.d.ts +75 -0
- package/dist/tui/runner.d.ts.map +1 -0
- package/dist/tui/settings.d.ts +56 -0
- package/dist/tui/settings.d.ts.map +1 -0
- package/dist/tui/slash.d.ts +14 -0
- package/dist/tui/slash.d.ts.map +1 -0
- package/dist/tui/theme.d.ts +39 -0
- package/dist/tui/theme.d.ts.map +1 -0
- package/dist/tui/transcript.d.ts +52 -0
- package/dist/tui/transcript.d.ts.map +1 -0
- package/dist/tui/ui.d.ts +42 -0
- package/dist/tui/ui.d.ts.map +1 -0
- package/dist/ui/deploy-screens.d.ts +3 -1
- package/dist/ui/deploy-screens.d.ts.map +1 -1
- package/dist/ui/env-screens.d.ts +37 -0
- package/dist/ui/env-screens.d.ts.map +1 -0
- package/package.json +19 -17
- package/src/commands/agent.ts +344 -0
- package/src/commands/api.ts +2 -1
- package/src/commands/check.ts +5 -1
- package/src/commands/deploy.ts +29 -3
- package/src/commands/dev-runner.ts +3 -5
- package/src/commands/dev.ts +3 -0
- package/src/commands/env.ts +422 -0
- package/src/commands/worker-group.ts +0 -4
- package/src/commands/worker.ts +0 -4
- package/src/index.tsx +95 -5
- package/src/lib/command-line.ts +111 -16
- package/src/lib/deploy-release.ts +3 -11
- package/src/lib/deploy-source.ts +10 -0
- package/src/lib/env-config.ts +96 -0
- package/src/lib/env-file.ts +104 -0
- package/src/lib/github-ci.ts +3 -1
- package/src/lib/hidden-prompt.ts +97 -0
- package/src/lib/runtime.ts +0 -2
- package/src/lib/worker-registry.ts +0 -2
- package/src/tui/app.tsx +1334 -0
- package/src/tui/brand.tsx +51 -0
- package/src/tui/computer.ts +91 -0
- package/src/tui/connection.ts +149 -0
- package/src/tui/context.tsx +149 -0
- package/src/tui/format.ts +477 -0
- package/src/tui/index.tsx +364 -0
- package/src/tui/markdown.ts +91 -0
- package/src/tui/palette.tsx +183 -0
- package/src/tui/parts.ts +274 -0
- package/src/tui/runner.ts +256 -0
- package/src/tui/settings.ts +176 -0
- package/src/tui/slash.ts +32 -0
- package/src/tui/theme.ts +111 -0
- package/src/tui/transcript.tsx +637 -0
- package/src/tui/ui.tsx +177 -0
- package/src/ui/deploy-screens.ts +12 -1
- package/src/ui/env-screens.ts +81 -0
- package/dist/lib/agent-turn-timeout.d.ts +0 -8
- package/dist/lib/agent-turn-timeout.d.ts.map +0 -1
- package/src/lib/agent-turn-timeout.ts +0 -46
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
/** @jsxImportSource @opentui/react */
|
|
2
|
+
import { appendFileSync } from "node:fs"
|
|
3
|
+
import { realpath } from "node:fs/promises"
|
|
4
|
+
import { tmpdir } from "node:os"
|
|
5
|
+
import { join } from "node:path"
|
|
6
|
+
import { format } from "node:util"
|
|
7
|
+
import { createCliRenderer, type KeyEvent, RGBA, SyntaxStyle } from "@opentui/core"
|
|
8
|
+
import { createRoot, useKeyboard } from "@opentui/react"
|
|
9
|
+
import { useCallback, useEffect, useState } from "react"
|
|
10
|
+
import { glyph } from "../ui/theme"
|
|
11
|
+
import { Workspace } from "./app"
|
|
12
|
+
import { Logo } from "./brand"
|
|
13
|
+
import { thisComputerId } from "./computer"
|
|
14
|
+
import {
|
|
15
|
+
type Connection,
|
|
16
|
+
connect,
|
|
17
|
+
type PendingSignIn,
|
|
18
|
+
type SignedOut,
|
|
19
|
+
startSignIn,
|
|
20
|
+
} from "./connection"
|
|
21
|
+
import { LocalRunner, stopOnHangUp } from "./runner"
|
|
22
|
+
import { loadSettings, type Settings } from "./settings"
|
|
23
|
+
import { type TuiColors, tuiColors } from "./theme"
|
|
24
|
+
import { BOLD, Composer, useSpinner } from "./ui"
|
|
25
|
+
|
|
26
|
+
/** How long quitting waits for a turn running here to record its end. */
|
|
27
|
+
const STOP_WAIT_MS = 10_000
|
|
28
|
+
/** How long quitting waits to tell the project this sixb closed: it lapses on its own anyway. */
|
|
29
|
+
const SESSION_CLOSE_WAIT_MS = 2_000
|
|
30
|
+
|
|
31
|
+
/** Where the app writes what would otherwise draw over it: its runner's notes and errors. */
|
|
32
|
+
export const TUI_LOG = join(tmpdir(), "sixb-tui.log")
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `sixb` with no command: the full-screen app. It connects as the CLI's current profile and opens
|
|
36
|
+
* on a new conversation that runs in the folder it was started in.
|
|
37
|
+
*/
|
|
38
|
+
export async function runTui(options: {
|
|
39
|
+
readonly version: string
|
|
40
|
+
readonly apiUrl?: string
|
|
41
|
+
readonly profile?: string
|
|
42
|
+
}): Promise<void> {
|
|
43
|
+
// Read before the screen is taken, so that a failure reads as any command's.
|
|
44
|
+
const computerId = await thisComputerId()
|
|
45
|
+
const restoreConsole = captureConsole()
|
|
46
|
+
const renderer = await createCliRenderer({
|
|
47
|
+
screenMode: "alternate-screen",
|
|
48
|
+
exitOnCtrlC: false,
|
|
49
|
+
useMouse: true,
|
|
50
|
+
targetFps: 60,
|
|
51
|
+
})
|
|
52
|
+
// The tab's name while sixb has it. A terminal draws its tab's icon itself: the mark stands in.
|
|
53
|
+
renderer.setTerminalTitle(`${glyph.mark} Sixb`)
|
|
54
|
+
// The terminal says whether it is light or dark; SIXB_THEME decides where it can't.
|
|
55
|
+
const forced = process.env.SIXB_THEME
|
|
56
|
+
const mode =
|
|
57
|
+
forced === "light" || forced === "dark"
|
|
58
|
+
? forced
|
|
59
|
+
: await renderer.waitForThemeMode(150).catch(() => null)
|
|
60
|
+
// The terminal's own colors, where it says them: the app paints over neither.
|
|
61
|
+
const reported = forced
|
|
62
|
+
? null
|
|
63
|
+
: await renderer
|
|
64
|
+
.getPalette({ timeout: 200, size: 16 })
|
|
65
|
+
.then(({ defaultBackground, defaultForeground }) =>
|
|
66
|
+
defaultBackground && defaultForeground
|
|
67
|
+
? { background: defaultBackground, foreground: defaultForeground }
|
|
68
|
+
: null
|
|
69
|
+
)
|
|
70
|
+
.catch(() => null)
|
|
71
|
+
const colors = tuiColors(mode, reported)
|
|
72
|
+
renderer.setBackgroundColor("transparent")
|
|
73
|
+
const syntax = createSyntax(colors, renderer)
|
|
74
|
+
const root = createRoot(renderer)
|
|
75
|
+
// As the project keeps it, and the local sandbox compares it: its real path.
|
|
76
|
+
const folder = await realpath(process.cwd())
|
|
77
|
+
const settings = await loadSettings(folder)
|
|
78
|
+
let runner: LocalRunner | null = null
|
|
79
|
+
// The renderer gives its screen back on these signals; sixb then ends its turns and exits.
|
|
80
|
+
const unhook = stopOnHangUp(
|
|
81
|
+
() => runner,
|
|
82
|
+
(signal) => process.exit(signal === "SIGHUP" ? 129 : 143)
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
await new Promise<void>((resolve) => {
|
|
87
|
+
root.render(
|
|
88
|
+
<App
|
|
89
|
+
colors={colors}
|
|
90
|
+
syntax={syntax}
|
|
91
|
+
version={options.version}
|
|
92
|
+
settings={settings}
|
|
93
|
+
computerId={computerId}
|
|
94
|
+
connectWith={(apiUrl) => connect(apiUrl ? { ...options, apiUrl } : options)}
|
|
95
|
+
runnerFor={(connection) => {
|
|
96
|
+
runner ??= new LocalRunner(connection, folder, (error) => console.error(error))
|
|
97
|
+
return runner
|
|
98
|
+
}}
|
|
99
|
+
onExit={resolve}
|
|
100
|
+
/>
|
|
101
|
+
)
|
|
102
|
+
})
|
|
103
|
+
} finally {
|
|
104
|
+
unhook()
|
|
105
|
+
root.unmount()
|
|
106
|
+
// An empty title gives the tab back its own name.
|
|
107
|
+
renderer.setTerminalTitle("")
|
|
108
|
+
renderer.destroy()
|
|
109
|
+
await renderer.closed
|
|
110
|
+
syntax.destroy()
|
|
111
|
+
restoreConsole()
|
|
112
|
+
// A turn running here ends interrupted, its end recorded, once the terminal is back; an API
|
|
113
|
+
// that stops answering gets a bounded wait, and ctrl+c ends it.
|
|
114
|
+
const running = runner as LocalRunner | null
|
|
115
|
+
if (running?.busy) {
|
|
116
|
+
process.stderr.write(" Stopping the turn running here…\n")
|
|
117
|
+
process.once("SIGINT", () => process.exit(130))
|
|
118
|
+
await Promise.race([running.stop(), Bun.sleep(STOP_WAIT_MS)])
|
|
119
|
+
}
|
|
120
|
+
// Its conversations read as offline at once, rather than once the session lapses.
|
|
121
|
+
await Promise.race([running?.closeSession(), Bun.sleep(SESSION_CLOSE_WAIT_MS)])
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function App(props: {
|
|
126
|
+
readonly colors: TuiColors
|
|
127
|
+
readonly syntax: SyntaxStyle
|
|
128
|
+
readonly version: string
|
|
129
|
+
readonly settings: Settings
|
|
130
|
+
readonly computerId: string
|
|
131
|
+
readonly connectWith: (apiUrl?: string) => Promise<Connection | SignedOut>
|
|
132
|
+
readonly runnerFor: (connection: Connection) => LocalRunner
|
|
133
|
+
readonly onExit: () => void
|
|
134
|
+
}) {
|
|
135
|
+
const [state, setState] = useState<Connection | SignedOut | null>(null)
|
|
136
|
+
const { connectWith } = props
|
|
137
|
+
const reconnect = useCallback(
|
|
138
|
+
(apiUrl?: string) => {
|
|
139
|
+
setState(null)
|
|
140
|
+
void connectWith(apiUrl).then(setState)
|
|
141
|
+
},
|
|
142
|
+
[connectWith]
|
|
143
|
+
)
|
|
144
|
+
useEffect(() => reconnect(), [reconnect])
|
|
145
|
+
|
|
146
|
+
if (state === null) return <Splash colors={props.colors} onExit={props.onExit} />
|
|
147
|
+
if ("reason" in state) {
|
|
148
|
+
return (
|
|
149
|
+
<Connect
|
|
150
|
+
colors={props.colors}
|
|
151
|
+
signedOut={state}
|
|
152
|
+
onConnect={reconnect}
|
|
153
|
+
onExit={props.onExit}
|
|
154
|
+
/>
|
|
155
|
+
)
|
|
156
|
+
}
|
|
157
|
+
return (
|
|
158
|
+
<Workspace
|
|
159
|
+
connection={state}
|
|
160
|
+
runner={props.runnerFor(state)}
|
|
161
|
+
computerId={props.computerId}
|
|
162
|
+
colors={props.colors}
|
|
163
|
+
syntax={props.syntax}
|
|
164
|
+
version={props.version}
|
|
165
|
+
initialSettings={props.settings}
|
|
166
|
+
onExit={props.onExit}
|
|
167
|
+
/>
|
|
168
|
+
)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function Splash({ colors, onExit }: { readonly colors: TuiColors; readonly onExit: () => void }) {
|
|
172
|
+
const spinner = useSpinner(true)
|
|
173
|
+
useKeyboard((key: KeyEvent) => {
|
|
174
|
+
if (key.ctrl && key.name === "c") onExit()
|
|
175
|
+
})
|
|
176
|
+
return (
|
|
177
|
+
<box
|
|
178
|
+
flexGrow={1}
|
|
179
|
+
alignItems="center"
|
|
180
|
+
justifyContent="center"
|
|
181
|
+
flexDirection="column"
|
|
182
|
+
backgroundColor={colors.background}
|
|
183
|
+
>
|
|
184
|
+
<Logo colors={colors} />
|
|
185
|
+
<box height={2} />
|
|
186
|
+
<text>
|
|
187
|
+
<span fg={colors.blue}>{`${spinner} `}</span>
|
|
188
|
+
<span fg={colors.muted}>Connecting</span>
|
|
189
|
+
</text>
|
|
190
|
+
</box>
|
|
191
|
+
)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Signed out, or the project is unreachable: sign in with the browser, as `sixb login` does. */
|
|
195
|
+
function Connect({
|
|
196
|
+
colors,
|
|
197
|
+
signedOut,
|
|
198
|
+
onConnect,
|
|
199
|
+
onExit,
|
|
200
|
+
}: {
|
|
201
|
+
readonly colors: TuiColors
|
|
202
|
+
readonly signedOut: SignedOut
|
|
203
|
+
/** Connect again, to `apiUrl` when the person gave another address. */
|
|
204
|
+
readonly onConnect: (apiUrl?: string) => void
|
|
205
|
+
readonly onExit: () => void
|
|
206
|
+
}) {
|
|
207
|
+
const [pending, setPending] = useState<PendingSignIn | null>(null)
|
|
208
|
+
const [error, setError] = useState<string | null>(null)
|
|
209
|
+
const spinner = useSpinner(pending !== null)
|
|
210
|
+
const unreachable = signedOut.reason === "unreachable"
|
|
211
|
+
|
|
212
|
+
const signIn = async (): Promise<void> => {
|
|
213
|
+
setError(null)
|
|
214
|
+
try {
|
|
215
|
+
const started = await startSignIn(signedOut.apiUrl)
|
|
216
|
+
setPending(started)
|
|
217
|
+
await Bun.$`open ${started.url}`.quiet().nothrow()
|
|
218
|
+
await started.complete(AbortSignal.timeout(10 * 60_000))
|
|
219
|
+
onConnect()
|
|
220
|
+
} catch (caught) {
|
|
221
|
+
setPending(null)
|
|
222
|
+
setError(caught instanceof Error ? caught.message : String(caught))
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
useKeyboard((key: KeyEvent) => {
|
|
227
|
+
if (key.ctrl && key.name === "c") return onExit()
|
|
228
|
+
if (key.name === "escape" && pending) return setPending(null)
|
|
229
|
+
if (key.name === "return" && !unreachable && !pending) void signIn()
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
const headline = unreachable
|
|
233
|
+
? `Sixb isn't answering at ${signedOut.apiUrl}`
|
|
234
|
+
: signedOut.reason === "session-ended"
|
|
235
|
+
? "Your sign-in has ended"
|
|
236
|
+
: `Sign in to ${new URL(signedOut.apiUrl).host}`
|
|
237
|
+
return (
|
|
238
|
+
<box
|
|
239
|
+
flexGrow={1}
|
|
240
|
+
alignItems="center"
|
|
241
|
+
justifyContent="center"
|
|
242
|
+
flexDirection="column"
|
|
243
|
+
backgroundColor={colors.background}
|
|
244
|
+
>
|
|
245
|
+
<Logo colors={colors} />
|
|
246
|
+
<box height={2} />
|
|
247
|
+
<text fg={colors.text} attributes={BOLD}>
|
|
248
|
+
{headline}
|
|
249
|
+
</text>
|
|
250
|
+
<box height={1} />
|
|
251
|
+
<box width={64} flexDirection="column" alignItems="center">
|
|
252
|
+
{pending ? (
|
|
253
|
+
<>
|
|
254
|
+
<text>
|
|
255
|
+
<span fg={colors.muted}>Confirm this code in your browser </span>
|
|
256
|
+
<span fg={colors.blue} attributes={BOLD}>
|
|
257
|
+
{pending.userCode}
|
|
258
|
+
</span>
|
|
259
|
+
</text>
|
|
260
|
+
<box height={1} />
|
|
261
|
+
<text>
|
|
262
|
+
<span fg={colors.blue}>{`${spinner} `}</span>
|
|
263
|
+
<span fg={colors.muted}>Waiting for you to approve it</span>
|
|
264
|
+
<span fg={colors.faint}>{" esc cancel"}</span>
|
|
265
|
+
</text>
|
|
266
|
+
</>
|
|
267
|
+
) : unreachable ? (
|
|
268
|
+
<>
|
|
269
|
+
<text fg={colors.muted}>Start it, or connect to another address.</text>
|
|
270
|
+
<box height={1} />
|
|
271
|
+
<box width={64}>
|
|
272
|
+
<Composer
|
|
273
|
+
colors={colors}
|
|
274
|
+
focused
|
|
275
|
+
allowEmpty
|
|
276
|
+
placeholder={signedOut.apiUrl}
|
|
277
|
+
status={[{ text: "Enter to connect", color: colors.muted }]}
|
|
278
|
+
onSubmit={(text) => {
|
|
279
|
+
onConnect(text || signedOut.apiUrl)
|
|
280
|
+
return true
|
|
281
|
+
}}
|
|
282
|
+
/>
|
|
283
|
+
</box>
|
|
284
|
+
</>
|
|
285
|
+
) : (
|
|
286
|
+
<text>
|
|
287
|
+
<span fg={colors.text}>enter</span>
|
|
288
|
+
<span fg={colors.muted}> sign in with your browser </span>
|
|
289
|
+
<span fg={colors.text}>ctrl+c</span>
|
|
290
|
+
<span fg={colors.muted}> quit</span>
|
|
291
|
+
</text>
|
|
292
|
+
)}
|
|
293
|
+
{error ? (
|
|
294
|
+
<box paddingTop={1}>
|
|
295
|
+
<text fg={colors.red}>{error}</text>
|
|
296
|
+
</box>
|
|
297
|
+
) : unreachable && signedOut.message ? (
|
|
298
|
+
<box paddingTop={1}>
|
|
299
|
+
<text fg={colors.faint}>{signedOut.message}</text>
|
|
300
|
+
</box>
|
|
301
|
+
) : null}
|
|
302
|
+
</box>
|
|
303
|
+
</box>
|
|
304
|
+
)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Markdown and code in the app's colors. */
|
|
308
|
+
function createSyntax(
|
|
309
|
+
colors: TuiColors,
|
|
310
|
+
renderer: { readonly nativeScene?: unknown }
|
|
311
|
+
): SyntaxStyle {
|
|
312
|
+
const hex = (value: string) => RGBA.fromHex(value)
|
|
313
|
+
return SyntaxStyle.fromStyles(
|
|
314
|
+
{
|
|
315
|
+
default: { fg: hex(colors.text) },
|
|
316
|
+
"markup.heading": { fg: hex(colors.text), bold: true },
|
|
317
|
+
"markup.strong": { fg: hex(colors.text), bold: true },
|
|
318
|
+
"markup.italic": { fg: hex(colors.text), italic: true },
|
|
319
|
+
"markup.strikethrough": { fg: hex(colors.muted) },
|
|
320
|
+
"markup.quote": { fg: hex(colors.muted), italic: true },
|
|
321
|
+
"markup.list": { fg: hex(colors.blue) },
|
|
322
|
+
"markup.link": { fg: hex(colors.blue), underline: true },
|
|
323
|
+
"markup.link.label": { fg: hex(colors.blue) },
|
|
324
|
+
"markup.link.url": { fg: hex(colors.faint) },
|
|
325
|
+
"markup.raw": { fg: hex(colors.code) },
|
|
326
|
+
"markup.raw.block": { fg: hex(colors.text) },
|
|
327
|
+
keyword: { fg: hex(colors.blue) },
|
|
328
|
+
string: { fg: hex(colors.green) },
|
|
329
|
+
number: { fg: hex(colors.amber) },
|
|
330
|
+
comment: { fg: hex(colors.faint), italic: true },
|
|
331
|
+
function: { fg: hex(colors.water[0] ?? colors.blue) },
|
|
332
|
+
type: { fg: hex(colors.water[1] ?? colors.blue) },
|
|
333
|
+
punctuation: { fg: hex(colors.muted) },
|
|
334
|
+
},
|
|
335
|
+
renderer.nativeScene as Parameters<typeof SyntaxStyle.fromStyles>[1]
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** While the app owns the screen, what code logs goes to a file instead of over it. */
|
|
340
|
+
function captureConsole(): () => void {
|
|
341
|
+
const methods = ["log", "info", "warn", "error", "debug"] as const
|
|
342
|
+
const originals = methods.map((method) => console[method])
|
|
343
|
+
for (const method of methods) {
|
|
344
|
+
console[method] = (...args: unknown[]) => {
|
|
345
|
+
try {
|
|
346
|
+
appendFileSync(TUI_LOG, `${new Date().toISOString()} ${method} ${format(...args)}\n`)
|
|
347
|
+
} catch {}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
// Warnings and anything else written to stderr would draw over the screen too.
|
|
351
|
+
const writeError = process.stderr.write.bind(process.stderr)
|
|
352
|
+
process.stderr.write = ((chunk: string | Uint8Array) => {
|
|
353
|
+
try {
|
|
354
|
+
appendFileSync(TUI_LOG, typeof chunk === "string" ? chunk : Buffer.from(chunk))
|
|
355
|
+
} catch {}
|
|
356
|
+
return true
|
|
357
|
+
}) as typeof process.stderr.write
|
|
358
|
+
return () => {
|
|
359
|
+
methods.forEach((method, index) => {
|
|
360
|
+
console[method] = originals[index] as (typeof console)[typeof method]
|
|
361
|
+
})
|
|
362
|
+
process.stderr.write = writeError
|
|
363
|
+
}
|
|
364
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The markdown of an answer still being written, as it can be drawn without moving: what is on
|
|
3
|
+
* screen only ever grows. Raw markdown that the next characters would turn into something else is
|
|
4
|
+
* closed early or held back:
|
|
5
|
+
*
|
|
6
|
+
* - an emphasis or code span the last line opened is closed, so `**sum` is drawn bold now rather
|
|
7
|
+
* than as `**sum` that loses its two stars when `**` arrives;
|
|
8
|
+
* - a link waits for its label, then shows as that label until its address is complete: a
|
|
9
|
+
* terminal without clickable links draws the address after it, which would grow mid-line;
|
|
10
|
+
* - a last line holding only a block's marker (`##`, `-`, `2`, `>`) waits for its text;
|
|
11
|
+
* - a table waits until it is complete: its columns are sized to its widest cell, so every row
|
|
12
|
+
* could resize the ones above it;
|
|
13
|
+
* - so does a quote, whose text OpenTUI draws raw until it is highlighted.
|
|
14
|
+
*
|
|
15
|
+
* Inside an open code fence everything is code, drawn as it arrives.
|
|
16
|
+
*/
|
|
17
|
+
export function steadyMarkdown(text: string): string {
|
|
18
|
+
// A line that just ended may still be followed by more of its block, a table's next row.
|
|
19
|
+
const lines = text.trimStart().replace(/\n$/, "").split("\n")
|
|
20
|
+
const last = lines.at(-1) ?? ""
|
|
21
|
+
const fences = lines.filter((line) => /^\s*(?:```|~~~)/.test(line)).length
|
|
22
|
+
if (fences % 2 === 1) {
|
|
23
|
+
// `` may be the fence that closes it, which is no line of the code.
|
|
24
|
+
if (/^\s*(?:`{1,2}|~{1,2})$/.test(last)) lines.pop()
|
|
25
|
+
return lines.join("\n")
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (BLOCK_MARKER_ONLY.test(last)) lines.pop()
|
|
29
|
+
else lines[lines.length - 1] = closeInline(holdLink(last))
|
|
30
|
+
|
|
31
|
+
// The last block, the lines after the last blank one, when it is a table or a quote.
|
|
32
|
+
let start = lines.length
|
|
33
|
+
while (start > 0 && lines[start - 1]?.trim()) start -= 1
|
|
34
|
+
const block = lines.slice(start).map((line) => line.trimStart()[0])
|
|
35
|
+
if (block.every((first) => first === "|") || block.every((first) => first === ">")) {
|
|
36
|
+
lines.splice(start)
|
|
37
|
+
}
|
|
38
|
+
return lines.join("\n").trimEnd()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A line that is only the start of a block: a heading's, a list item's or a quote's marker. */
|
|
42
|
+
const BLOCK_MARKER_ONLY = /^\s*(?:#{1,6}|[-*+]|\d{1,9}[.)]?|>|`{1,2}|~{1,2}|[-*_=]{2})\s*$/
|
|
43
|
+
|
|
44
|
+
/** `line` without a link whose label is not finished, and with one whose address is not as its label. */
|
|
45
|
+
function holdLink(line: string): string {
|
|
46
|
+
const outsideCode = (at: number) => (line.slice(0, at).split("`").length - 1) % 2 === 0
|
|
47
|
+
const label = /!?\[[^\]]*\]?$/.exec(line)
|
|
48
|
+
if (label && outsideCode(label.index)) return line.slice(0, label.index).trimEnd()
|
|
49
|
+
const address = /!?\[([^\]]*)\]\([^)\s]*$/.exec(line)
|
|
50
|
+
if (address && outsideCode(address.index)) return `${line.slice(0, address.index)}${address[1]}`
|
|
51
|
+
return line
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Emphasis and code markers, longest first: `**` is one marker, not two `*`. */
|
|
55
|
+
const MARKERS = ["`", "**", "~~", "*"] as const
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* `line` with each emphasis or code span it leaves open closed, the innermost first; an opener
|
|
59
|
+
* with nothing after it yet is dropped instead.
|
|
60
|
+
*/
|
|
61
|
+
function closeInline(line: string): string {
|
|
62
|
+
const open: { readonly marker: string; readonly at: number }[] = []
|
|
63
|
+
// A list item's `* ` is its bullet, not emphasis.
|
|
64
|
+
let at = /^\s*\*\s/.test(line) ? line.indexOf("*") + 1 : 0
|
|
65
|
+
while (at < line.length) {
|
|
66
|
+
if (line[at] === "\\") {
|
|
67
|
+
at += 2
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
const inCode = open.at(-1)?.marker === "`"
|
|
71
|
+
const marker = MARKERS.find((each) => line.startsWith(each, at) && (!inCode || each === "`"))
|
|
72
|
+
if (!marker) {
|
|
73
|
+
at += 1
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
const next = line[at + marker.length]
|
|
77
|
+
if (open.at(-1)?.marker === marker) open.pop()
|
|
78
|
+
// An opener is followed by text, as markdown's is: `a * b` multiplies. One at the end of the
|
|
79
|
+
// line may still be.
|
|
80
|
+
else if (marker === "`" || next === undefined || /\S/.test(next)) open.push({ marker, at })
|
|
81
|
+
at += marker.length
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let closed = line
|
|
85
|
+
for (const { marker, at: opened } of open.reverse()) {
|
|
86
|
+
closed = closed.slice(opened + marker.length).trim()
|
|
87
|
+
? `${closed.trimEnd()}${marker}`
|
|
88
|
+
: closed.slice(0, opened).trimEnd()
|
|
89
|
+
}
|
|
90
|
+
return closed
|
|
91
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/** @jsxImportSource @opentui/react */
|
|
2
|
+
import { type KeyEvent, RGBA } from "@opentui/core"
|
|
3
|
+
import { useKeyboard, useTerminalDimensions } from "@opentui/react"
|
|
4
|
+
import { useState } from "react"
|
|
5
|
+
import type { TuiColors } from "./theme"
|
|
6
|
+
import { BOLD } from "./ui"
|
|
7
|
+
|
|
8
|
+
export interface PaletteItem {
|
|
9
|
+
readonly id: string
|
|
10
|
+
readonly label: string
|
|
11
|
+
/** Quiet text after the label: a model's tier, a conversation's age. */
|
|
12
|
+
readonly detail?: string
|
|
13
|
+
/** A shortcut that does the same, shown on the right. */
|
|
14
|
+
readonly keys?: string
|
|
15
|
+
readonly group?: string
|
|
16
|
+
/** The current choice, marked. */
|
|
17
|
+
readonly current?: boolean
|
|
18
|
+
run(): void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A list to pick from, filtered as you type: commands, conversations, models. Opens centered over
|
|
23
|
+
* the screen; esc closes it.
|
|
24
|
+
*/
|
|
25
|
+
export function Palette({
|
|
26
|
+
colors,
|
|
27
|
+
title,
|
|
28
|
+
items,
|
|
29
|
+
placeholder,
|
|
30
|
+
onClose,
|
|
31
|
+
}: {
|
|
32
|
+
readonly colors: TuiColors
|
|
33
|
+
readonly title: string
|
|
34
|
+
readonly items: readonly PaletteItem[]
|
|
35
|
+
readonly placeholder: string
|
|
36
|
+
readonly onClose: () => void
|
|
37
|
+
}) {
|
|
38
|
+
const { width, height } = useTerminalDimensions()
|
|
39
|
+
const [query, setQuery] = useState("")
|
|
40
|
+
const [selected, setSelected] = useState(() =>
|
|
41
|
+
Math.max(
|
|
42
|
+
0,
|
|
43
|
+
items.findIndex((item) => item.current)
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
const words = query.toLowerCase().split(/\s+/).filter(Boolean)
|
|
47
|
+
const matches = items.filter((item) => {
|
|
48
|
+
const haystack = `${item.label} ${item.detail ?? ""} ${item.group ?? ""}`.toLowerCase()
|
|
49
|
+
return words.every((word) => haystack.includes(word))
|
|
50
|
+
})
|
|
51
|
+
const index = Math.min(selected, Math.max(0, matches.length - 1))
|
|
52
|
+
const boxWidth = Math.min(72, width - 8)
|
|
53
|
+
const rows = Math.max(4, Math.min(matches.length, height - 14, 14))
|
|
54
|
+
const first = Math.min(Math.max(0, index - rows + 1), Math.max(0, matches.length - rows))
|
|
55
|
+
|
|
56
|
+
useKeyboard((key: KeyEvent) => {
|
|
57
|
+
if (key.name === "escape" || (key.ctrl && key.name === "c")) return onClose()
|
|
58
|
+
if (key.name === "up" || (key.ctrl && key.name === "p")) {
|
|
59
|
+
return setSelected((value) => Math.max(0, Math.min(value, matches.length - 1) - 1))
|
|
60
|
+
}
|
|
61
|
+
if (key.name === "down" || (key.ctrl && key.name === "n")) {
|
|
62
|
+
return setSelected((value) => Math.min(matches.length - 1, value + 1))
|
|
63
|
+
}
|
|
64
|
+
if (key.name === "return") {
|
|
65
|
+
const item = matches[index]
|
|
66
|
+
if (item) {
|
|
67
|
+
onClose()
|
|
68
|
+
item.run()
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
// Each row on one line: the label keeps its room first, then its detail gets what is left.
|
|
74
|
+
const visible = matches.slice(first, first + rows)
|
|
75
|
+
const rowsWithHeaders = visible.map((item, offset) => ({
|
|
76
|
+
item,
|
|
77
|
+
active: first + offset === index,
|
|
78
|
+
header:
|
|
79
|
+
item.group && item.group !== (offset === 0 ? undefined : visible[offset - 1]?.group)
|
|
80
|
+
? item.group
|
|
81
|
+
: undefined,
|
|
82
|
+
}))
|
|
83
|
+
const headerRows = rowsWithHeaders.reduce(
|
|
84
|
+
(sum, row, offset) => sum + (row.header ? (offset === 0 ? 1 : 2) : 0),
|
|
85
|
+
0
|
|
86
|
+
)
|
|
87
|
+
const listRows = matches.length === 0 ? 1 : visible.length + headerRows
|
|
88
|
+
const inner = boxWidth - 6
|
|
89
|
+
return (
|
|
90
|
+
<>
|
|
91
|
+
<box
|
|
92
|
+
position="absolute"
|
|
93
|
+
left={0}
|
|
94
|
+
top={0}
|
|
95
|
+
width={width}
|
|
96
|
+
height={height}
|
|
97
|
+
backgroundColor={RGBA.fromValues(0, 0, 0, 0.45)}
|
|
98
|
+
zIndex={9}
|
|
99
|
+
/>
|
|
100
|
+
<box
|
|
101
|
+
position="absolute"
|
|
102
|
+
left={Math.floor((width - boxWidth) / 2)}
|
|
103
|
+
top={Math.max(2, Math.floor(height / 5))}
|
|
104
|
+
width={boxWidth}
|
|
105
|
+
height={listRows + 6}
|
|
106
|
+
backgroundColor={colors.surface}
|
|
107
|
+
flexDirection="column"
|
|
108
|
+
paddingTop={1}
|
|
109
|
+
paddingBottom={1}
|
|
110
|
+
zIndex={10}
|
|
111
|
+
>
|
|
112
|
+
<box flexDirection="row" justifyContent="space-between" paddingLeft={3} paddingRight={3}>
|
|
113
|
+
<text fg={colors.text} attributes={BOLD}>
|
|
114
|
+
{title}
|
|
115
|
+
</text>
|
|
116
|
+
<text fg={colors.faint}>esc</text>
|
|
117
|
+
</box>
|
|
118
|
+
<box paddingLeft={3} paddingRight={3} paddingTop={1} paddingBottom={1}>
|
|
119
|
+
<input
|
|
120
|
+
focused
|
|
121
|
+
placeholder={placeholder}
|
|
122
|
+
textColor={colors.text}
|
|
123
|
+
focusedTextColor={colors.text}
|
|
124
|
+
placeholderColor={colors.faint}
|
|
125
|
+
backgroundColor={colors.surface}
|
|
126
|
+
focusedBackgroundColor={colors.surface}
|
|
127
|
+
onInput={(value: string) => {
|
|
128
|
+
setQuery(value)
|
|
129
|
+
setSelected(0)
|
|
130
|
+
}}
|
|
131
|
+
/>
|
|
132
|
+
</box>
|
|
133
|
+
{matches.length === 0 ? (
|
|
134
|
+
<box paddingLeft={3}>
|
|
135
|
+
<text fg={colors.muted}>Nothing matches.</text>
|
|
136
|
+
</box>
|
|
137
|
+
) : null}
|
|
138
|
+
{rowsWithHeaders.map(({ item, active, header }, offset) => {
|
|
139
|
+
const keys = item.keys ? item.keys.length + 2 : 0
|
|
140
|
+
const mark = item.current ? 3 : 0
|
|
141
|
+
const detailRoom = item.detail ? Math.min(item.detail.length + 2, 26) : 0
|
|
142
|
+
const label = fit(item.label, inner - keys - mark - detailRoom)
|
|
143
|
+
const detail = item.detail ? fit(item.detail, inner - keys - mark - label.length - 2) : ""
|
|
144
|
+
return (
|
|
145
|
+
<box key={item.id} flexDirection="column">
|
|
146
|
+
{header ? (
|
|
147
|
+
<box paddingLeft={3} paddingTop={offset === 0 ? 0 : 1}>
|
|
148
|
+
<text fg={colors.blue}>{header}</text>
|
|
149
|
+
</box>
|
|
150
|
+
) : null}
|
|
151
|
+
<box
|
|
152
|
+
flexDirection="row"
|
|
153
|
+
justifyContent="space-between"
|
|
154
|
+
backgroundColor={active ? colors.raised : colors.surface}
|
|
155
|
+
paddingLeft={3}
|
|
156
|
+
paddingRight={3}
|
|
157
|
+
>
|
|
158
|
+
<text>
|
|
159
|
+
<span fg={colors.text} attributes={active ? BOLD : 0}>
|
|
160
|
+
{label}
|
|
161
|
+
</span>
|
|
162
|
+
{item.current ? <span fg={colors.blue}>{" ●"}</span> : null}
|
|
163
|
+
{detail && item.keys ? <span fg={colors.faint}>{` ${detail}`}</span> : null}
|
|
164
|
+
</text>
|
|
165
|
+
{item.keys ? (
|
|
166
|
+
<text fg={colors.faint}>{item.keys}</text>
|
|
167
|
+
) : detail ? (
|
|
168
|
+
<text fg={colors.faint}>{detail}</text>
|
|
169
|
+
) : null}
|
|
170
|
+
</box>
|
|
171
|
+
</box>
|
|
172
|
+
)
|
|
173
|
+
})}
|
|
174
|
+
</box>
|
|
175
|
+
</>
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Text cut to `room` columns, with an ellipsis; nothing when there is no room. */
|
|
180
|
+
function fit(text: string, room: number): string {
|
|
181
|
+
if (room < 4) return ""
|
|
182
|
+
return text.length > room ? `${text.slice(0, room - 1)}…` : text
|
|
183
|
+
}
|