@sixb/cli 0.1.24 → 0.1.26

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.
Files changed (76) hide show
  1. package/README.md +5 -5
  2. package/dist/commands/agent.d.ts +16 -0
  3. package/dist/commands/agent.d.ts.map +1 -0
  4. package/dist/commands/dev-runner.d.ts +0 -1
  5. package/dist/commands/dev-runner.d.ts.map +1 -1
  6. package/dist/commands/worker-group.d.ts +0 -1
  7. package/dist/commands/worker-group.d.ts.map +1 -1
  8. package/dist/commands/worker.d.ts +0 -1
  9. package/dist/commands/worker.d.ts.map +1 -1
  10. package/dist/lib/command-line.d.ts +16 -6
  11. package/dist/lib/command-line.d.ts.map +1 -1
  12. package/dist/lib/deploy-release.d.ts.map +1 -1
  13. package/dist/lib/github-ci.d.ts.map +1 -1
  14. package/dist/lib/runtime.d.ts +0 -1
  15. package/dist/lib/runtime.d.ts.map +1 -1
  16. package/dist/lib/worker-registry.d.ts +0 -1
  17. package/dist/lib/worker-registry.d.ts.map +1 -1
  18. package/dist/tui/app.d.ts +19 -0
  19. package/dist/tui/app.d.ts.map +1 -0
  20. package/dist/tui/brand.d.ts +7 -0
  21. package/dist/tui/brand.d.ts.map +1 -0
  22. package/dist/tui/computer.d.ts +3 -0
  23. package/dist/tui/computer.d.ts.map +1 -0
  24. package/dist/tui/connection.d.ts +45 -0
  25. package/dist/tui/connection.d.ts.map +1 -0
  26. package/dist/tui/folders.d.ts +7 -0
  27. package/dist/tui/folders.d.ts.map +1 -0
  28. package/dist/tui/format.d.ts +33 -0
  29. package/dist/tui/format.d.ts.map +1 -0
  30. package/dist/tui/index.d.ts +12 -0
  31. package/dist/tui/index.d.ts.map +1 -0
  32. package/dist/tui/palette.d.ts +25 -0
  33. package/dist/tui/palette.d.ts.map +1 -0
  34. package/dist/tui/parts.d.ts +66 -0
  35. package/dist/tui/parts.d.ts.map +1 -0
  36. package/dist/tui/runner.d.ts +52 -0
  37. package/dist/tui/runner.d.ts.map +1 -0
  38. package/dist/tui/settings.d.ts +44 -0
  39. package/dist/tui/settings.d.ts.map +1 -0
  40. package/dist/tui/slash.d.ts +14 -0
  41. package/dist/tui/slash.d.ts.map +1 -0
  42. package/dist/tui/theme.d.ts +39 -0
  43. package/dist/tui/theme.d.ts.map +1 -0
  44. package/dist/tui/transcript.d.ts +52 -0
  45. package/dist/tui/transcript.d.ts.map +1 -0
  46. package/dist/tui/ui.d.ts +35 -0
  47. package/dist/tui/ui.d.ts.map +1 -0
  48. package/package.json +17 -15
  49. package/src/commands/agent.ts +337 -0
  50. package/src/commands/dev-runner.ts +0 -4
  51. package/src/commands/worker-group.ts +0 -4
  52. package/src/commands/worker.ts +0 -4
  53. package/src/index.tsx +57 -5
  54. package/src/lib/command-line.ts +52 -15
  55. package/src/lib/deploy-release.ts +0 -11
  56. package/src/lib/github-ci.ts +3 -1
  57. package/src/lib/runtime.ts +0 -2
  58. package/src/lib/worker-registry.ts +0 -2
  59. package/src/tui/app.tsx +1198 -0
  60. package/src/tui/brand.tsx +51 -0
  61. package/src/tui/computer.ts +54 -0
  62. package/src/tui/connection.ts +149 -0
  63. package/src/tui/folders.ts +41 -0
  64. package/src/tui/format.ts +260 -0
  65. package/src/tui/index.tsx +353 -0
  66. package/src/tui/palette.tsx +183 -0
  67. package/src/tui/parts.ts +254 -0
  68. package/src/tui/runner.ts +173 -0
  69. package/src/tui/settings.ts +127 -0
  70. package/src/tui/slash.ts +32 -0
  71. package/src/tui/theme.ts +111 -0
  72. package/src/tui/transcript.tsx +555 -0
  73. package/src/tui/ui.tsx +148 -0
  74. package/dist/lib/agent-turn-timeout.d.ts +0 -8
  75. package/dist/lib/agent-turn-timeout.d.ts.map +0 -1
  76. package/src/lib/agent-turn-timeout.ts +0 -46
@@ -0,0 +1,1198 @@
1
+ /** @jsxImportSource @opentui/react */
2
+ import { homedir } from "node:os"
3
+ import type { KeyEvent, ScrollBoxRenderable, SyntaxStyle } from "@opentui/core"
4
+ import {
5
+ useKeyboard,
6
+ useRenderer,
7
+ useSelectionHandler,
8
+ useTerminalDimensions,
9
+ } from "@opentui/react"
10
+ import {
11
+ cancelAgentRun,
12
+ createAgentActivitySocket,
13
+ createAgentRunSocket,
14
+ createAgentThread,
15
+ decideAgentApproval,
16
+ type GetAgentThreadResponses,
17
+ getAgentThread,
18
+ listAgentThreadApprovals,
19
+ listAgentThreadMessages,
20
+ listAgentThreadRuns,
21
+ listAgentThreads,
22
+ listModels,
23
+ moveAgentThreadToComputer,
24
+ postAgentThreadMessage,
25
+ setAgentThreadApprovalMode,
26
+ } from "@sixb/client"
27
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
28
+ import { Logo } from "./brand"
29
+ import type { Connection } from "./connection"
30
+ import { conversationsIn, folderOf, rememberFolder } from "./folders"
31
+ import { shortPath } from "./format"
32
+ import { Palette, type PaletteItem } from "./palette"
33
+ import { type LiveRun, liveRun, reduceLive, type ShownMessage, shownMessage } from "./parts"
34
+ import { type LocalRunner, owns, runsOnThisComputer } from "./runner"
35
+ import {
36
+ APPROVAL_MODES,
37
+ type ApprovalMode,
38
+ approvalLabel,
39
+ type LanguageModel,
40
+ messageSelection,
41
+ modelLabel,
42
+ placeLabel,
43
+ type ReasoningLevel,
44
+ type Settings,
45
+ saveSettings,
46
+ } from "./settings"
47
+ import { pickSlash, type SlashCommand, slashMatches } from "./slash"
48
+ import type { TuiColors } from "./theme"
49
+ import { APPROVAL_CHOICES, type Approval, type Run, Transcript, Working } from "./transcript"
50
+ import { BOLD, Composer, KeyHints, type StatusItem } from "./ui"
51
+
52
+ type Thread = GetAgentThreadResponses[200]
53
+ type Screen = { readonly kind: "home" } | { readonly kind: "thread"; readonly threadId: string }
54
+ type Dialog = "commands" | "threads" | "models" | "permissions" | null
55
+
56
+ /** The person's mode in a conversation, as the server keeps it for them there. */
57
+ interface ThreadApproval {
58
+ readonly threadId: string
59
+ /** Unknown until the thread is read. */
60
+ readonly mode?: ApprovalMode
61
+ /** Chosen here and not the thread's yet: the next message carries it. */
62
+ readonly chosen: boolean
63
+ }
64
+
65
+ export interface WorkspaceProps {
66
+ readonly connection: Connection
67
+ readonly runner: LocalRunner
68
+ /** This computer's id: a conversation on a computer runs on one of its owner's. */
69
+ readonly computerId: string
70
+ readonly colors: TuiColors
71
+ readonly syntax: SyntaxStyle
72
+ readonly version: string
73
+ readonly initialSettings: Settings
74
+ readonly onExit: () => void
75
+ }
76
+
77
+ /** Everything once connected: the home screen or a conversation, and the dialogs over them. */
78
+ export function Workspace(props: WorkspaceProps) {
79
+ const { connection, colors } = props
80
+ const [screen, setScreen] = useState<Screen>({ kind: "home" })
81
+ const [settings, setSettingsState] = useState(props.initialSettings)
82
+ const [models, setModels] = useState<readonly LanguageModel[]>([])
83
+ const [dialog, setDialog] = useState<Dialog>(null)
84
+ const [notice, setNotice] = useState<{
85
+ readonly text: string
86
+ readonly tone: "info" | "error"
87
+ } | null>(null)
88
+ const [quitArmed, setQuitArmed] = useState(false)
89
+
90
+ const setSettings = useCallback((change: (current: Settings) => Settings) => {
91
+ setSettingsState((current) => {
92
+ const next = change(current)
93
+ void saveSettings(next)
94
+ return next
95
+ })
96
+ }, [])
97
+ const say = useCallback(
98
+ (text: string, tone: "info" | "error" = "info") => setNotice({ text, tone }),
99
+ []
100
+ )
101
+ useEffect(() => {
102
+ if (!notice) return
103
+ const timer = setTimeout(() => setNotice(null), 4_000)
104
+ return () => clearTimeout(timer)
105
+ }, [notice])
106
+
107
+ useEffect(() => {
108
+ void listModels({ client: connection.client }).then(({ data }) =>
109
+ setModels(data?.language ?? [])
110
+ )
111
+ }, [connection])
112
+
113
+ // Selecting text copies it, as the terminal would without the app's mouse.
114
+ const renderer = useRenderer()
115
+ const copied = useRef<ReturnType<typeof setTimeout> | null>(null)
116
+ useSelectionHandler((selection) => {
117
+ const text = selection.getSelectedText()
118
+ if (!text.trim()) return
119
+ if (copied.current) clearTimeout(copied.current)
120
+ copied.current = setTimeout(() => {
121
+ void copy(text, renderer).then((done) => {
122
+ if (done) say("Copied")
123
+ })
124
+ }, 300)
125
+ })
126
+
127
+ // This folder's conversations run here whatever screen is open: a message sent from the web app,
128
+ // or a turn going on after approvals decided there, and those that queued while sixb was closed.
129
+ const { runner } = props
130
+ useEffect(() => {
131
+ void conversationsIn(runner.folder).then((threadIds) => {
132
+ for (const threadId of threadIds) void runner.claimIfHere(threadId)
133
+ })
134
+ const socket = createAgentActivitySocket({
135
+ client: connection.client,
136
+ onActivity: (event) => {
137
+ if (event.status === "queued") void runner.claimIfHere(event.threadId, event.runId)
138
+ },
139
+ })
140
+ return () => socket.close()
141
+ }, [connection, runner])
142
+
143
+ // In a conversation, the mode is the thread's, as the web reads it: "always" on a card raises it,
144
+ // and a mode chosen in the app applies here too. New conversations start in the settings' mode.
145
+ const [threadApproval, setThreadApproval] = useState<ThreadApproval | null>(null)
146
+ const openThreadId = screen.kind === "thread" ? screen.threadId : null
147
+ const approval = threadApproval?.threadId === openThreadId ? threadApproval : null
148
+ const approvalMode = openThreadId === null ? settings.approvalMode : approval?.mode
149
+
150
+ // A choice still on its way to the server keeps showing, except after "always", which raised
151
+ // the mode there.
152
+ const readApproval = useCallback((thread: Thread, raised: boolean) => {
153
+ setThreadApproval((current) =>
154
+ current?.threadId === thread.id && current.chosen && !raised
155
+ ? current
156
+ : {
157
+ threadId: thread.id,
158
+ ...(thread.approvalMode ? { mode: thread.approvalMode } : {}),
159
+ chosen: false,
160
+ }
161
+ )
162
+ }, [])
163
+
164
+ const chooseApproval = useCallback(
165
+ (mode: ApprovalMode) => {
166
+ say(`Permissions: ${approvalLabel(mode)}`)
167
+ // It is where the next new conversation starts, as the web makes it the person's default.
168
+ setSettings((current) => ({ ...current, approvalMode: mode }))
169
+ if (openThreadId === null) return
170
+
171
+ // In a conversation, it becomes the person's mode there, on every device, as in the web.
172
+ const threadId = openThreadId
173
+ setThreadApproval({ threadId, mode, chosen: true })
174
+ void setAgentThreadApprovalMode({
175
+ client: connection.client,
176
+ path: { threadId },
177
+ body: { approvalMode: mode },
178
+ }).then(({ data, error }) => {
179
+ // Not kept there, the choice stays one the next message carries.
180
+ if (error || !data) return say(errorText(error), "error")
181
+
182
+ setThreadApproval((current) =>
183
+ current?.threadId === threadId && current.chosen && current.mode === mode
184
+ ? { threadId, mode: data.approvalMode ?? mode, chosen: false }
185
+ : current
186
+ )
187
+ })
188
+ },
189
+ [connection, openThreadId, say, setSettings]
190
+ )
191
+
192
+ const cyclePermissions = useCallback(() => {
193
+ // A conversation not read yet has no mode to step from.
194
+ if (!approvalMode) return
195
+
196
+ const at = APPROVAL_MODES.findIndex((entry) => entry.mode === approvalMode)
197
+ chooseApproval(APPROVAL_MODES[(at + 1) % APPROVAL_MODES.length]?.mode ?? "manual")
198
+ }, [approvalMode, chooseApproval])
199
+
200
+ // Ctrl+t steps through the effort levels of the model in effect, then back to its default.
201
+ const cycleEffort = useCallback(() => {
202
+ setSettings((current) => {
203
+ const model = effortModel(models, current)
204
+ const levels: readonly ReasoningLevel[] = (model?.reasoningLevels ?? []).filter(
205
+ (level) => level !== "provider-default"
206
+ )
207
+ const at = current.reasoning ? levels.indexOf(current.reasoning) : -1
208
+ const next = levels[at + 1]
209
+ const { reasoning: _reasoning, ...rest } = current
210
+ say(`Effort: ${next ?? "default"}`)
211
+ return next ? { ...rest, reasoning: next } : rest
212
+ })
213
+ }, [models, setSettings, say])
214
+
215
+ useKeyboard((key: KeyEvent) => {
216
+ if (key.ctrl && key.name === "c") {
217
+ if (quitArmed) return props.onExit()
218
+ setQuitArmed(true)
219
+ setTimeout(() => setQuitArmed(false), 2_000)
220
+ return
221
+ }
222
+ if (dialog) return
223
+ if (key.ctrl && key.name === "p") return setDialog("commands")
224
+ if (key.ctrl && key.name === "n") return setScreen({ kind: "home" })
225
+ if (key.ctrl && key.name === "l") return setDialog("threads")
226
+ if (key.ctrl && key.name === "o") return setDialog("models")
227
+ if (key.ctrl && key.name === "t") return cycleEffort()
228
+ if (key.shift && key.name === "tab") return cyclePermissions()
229
+ })
230
+
231
+ const status = (place: string): StatusItem[] => {
232
+ const model = modelLabel(models, settings)
233
+ return [
234
+ { text: place, color: colors.blue, bold: true },
235
+ { text: model.name, color: colors.text },
236
+ ...(model.reasoning ? [{ text: model.reasoning, color: colors.muted }] : []),
237
+ // Amber is for what deserves your attention: here, an agent that asks before nothing.
238
+ ...(approvalMode
239
+ ? [
240
+ {
241
+ text: approvalLabel(approvalMode),
242
+ color:
243
+ approvalMode === "auto"
244
+ ? colors.amber
245
+ : approvalMode === "accept-edits"
246
+ ? colors.text
247
+ : colors.muted,
248
+ },
249
+ ]
250
+ : []),
251
+ ]
252
+ }
253
+
254
+ const slashCommands: readonly SlashCommand[] = [
255
+ {
256
+ name: "new",
257
+ description: "Start a new conversation",
258
+ run: () => setScreen({ kind: "home" }),
259
+ },
260
+ { name: "conversations", description: "Open a conversation", run: () => setDialog("threads") },
261
+ {
262
+ name: "model",
263
+ description: "Choose the model and its effort",
264
+ run: () => setDialog("models"),
265
+ },
266
+ {
267
+ name: "permissions",
268
+ description: "What the agent may do without asking",
269
+ run: () => setDialog("permissions"),
270
+ },
271
+ {
272
+ name: "cloud",
273
+ description: "Run new conversations in the cloud",
274
+ run: () => setSettings((current) => ({ ...current, place: "cloud" })),
275
+ },
276
+ {
277
+ name: "here",
278
+ description: `Run new conversations on ${placeLabel("computer")}, in this folder`,
279
+ run: () => setSettings((current) => ({ ...current, place: "computer" })),
280
+ },
281
+ { name: "quit", description: "Quit sixb", run: props.onExit },
282
+ ]
283
+
284
+ const common = {
285
+ ...props,
286
+ settings,
287
+ models,
288
+ status,
289
+ say,
290
+ slashCommands,
291
+ dialogOpen: dialog !== null,
292
+ }
293
+
294
+ return (
295
+ <box flexDirection="column" flexGrow={1} backgroundColor={colors.background}>
296
+ {screen.kind === "home" ? (
297
+ <Home
298
+ {...common}
299
+ onPlace={() =>
300
+ setSettings((current) => {
301
+ const place = current.place === "computer" ? "cloud" : "computer"
302
+ say(
303
+ place === "cloud"
304
+ ? "New conversations run in the cloud"
305
+ : `New conversations run on ${placeLabel(place)}`
306
+ )
307
+ return { ...current, place }
308
+ })
309
+ }
310
+ onOpen={(threadId) => setScreen({ kind: "thread", threadId })}
311
+ />
312
+ ) : (
313
+ <ThreadView
314
+ key={screen.threadId}
315
+ {...common}
316
+ threadId={screen.threadId}
317
+ approval={approval}
318
+ onThreadRead={readApproval}
319
+ />
320
+ )}
321
+ {notice || quitArmed ? (
322
+ <box
323
+ position="absolute"
324
+ right={2}
325
+ top={1}
326
+ backgroundColor={colors.surface}
327
+ paddingLeft={2}
328
+ paddingRight={2}
329
+ zIndex={5}
330
+ >
331
+ <text fg={quitArmed ? colors.text : notice?.tone === "error" ? colors.red : colors.text}>
332
+ {quitArmed ? "Press ctrl+c again to quit" : notice?.text}
333
+ </text>
334
+ </box>
335
+ ) : null}
336
+ {dialog === "commands" ? (
337
+ <Palette
338
+ colors={colors}
339
+ title="Commands"
340
+ placeholder="Search"
341
+ onClose={() => setDialog(null)}
342
+ items={commandItems({
343
+ settings,
344
+ approvalMode,
345
+ models,
346
+ newConversation: () => setScreen({ kind: "home" }),
347
+ open: setDialog,
348
+ setPlace: (place) => setSettings((current) => ({ ...current, place })),
349
+ cycleEffort,
350
+ quit: props.onExit,
351
+ })}
352
+ />
353
+ ) : null}
354
+ {dialog === "threads" ? (
355
+ <ThreadsDialog
356
+ connection={connection}
357
+ colors={colors}
358
+ onClose={() => setDialog(null)}
359
+ onOpen={(threadId) => setScreen({ kind: "thread", threadId })}
360
+ />
361
+ ) : null}
362
+ {dialog === "models" ? (
363
+ <Palette
364
+ colors={colors}
365
+ title="Model"
366
+ placeholder="Search models"
367
+ onClose={() => setDialog(null)}
368
+ items={modelItems(models, settings, (model, reasoning) =>
369
+ setSettings((current) => {
370
+ const { model: _model, reasoning: _reasoning, ...rest } = current
371
+ return {
372
+ ...rest,
373
+ ...(model ? { model: { provider: model.provider, modelId: model.modelId } } : {}),
374
+ ...(reasoning ? { reasoning } : {}),
375
+ }
376
+ })
377
+ )}
378
+ />
379
+ ) : null}
380
+ {dialog === "permissions" ? (
381
+ <Palette
382
+ colors={colors}
383
+ title="What can the agent do without asking?"
384
+ placeholder="Search"
385
+ onClose={() => setDialog(null)}
386
+ items={APPROVAL_MODES.map((entry) => ({
387
+ id: entry.mode,
388
+ label: entry.label,
389
+ detail: entry.description,
390
+ current: entry.mode === approvalMode,
391
+ run: () => chooseApproval(entry.mode),
392
+ }))}
393
+ />
394
+ ) : null}
395
+ </box>
396
+ )
397
+ }
398
+
399
+ interface ScreenProps extends WorkspaceProps {
400
+ readonly settings: Settings
401
+ readonly models: readonly LanguageModel[]
402
+ readonly status: (place: string) => StatusItem[]
403
+ readonly say: (text: string, tone?: "info" | "error") => void
404
+ readonly slashCommands: readonly SlashCommand[]
405
+ readonly dialogOpen: boolean
406
+ }
407
+
408
+ /** The commands matching what is typed, listed above the composer. */
409
+ function SlashMenu({
410
+ colors,
411
+ menu,
412
+ above,
413
+ }: {
414
+ readonly colors: TuiColors
415
+ readonly menu: SlashMenuState
416
+ /** How many rows below the menu the composer and its hints take. */
417
+ readonly above: number
418
+ }) {
419
+ const { matches, selected } = menu
420
+ if (matches.length === 0) return null
421
+ const width = Math.max(...matches.map((command) => command.name.length)) + 4
422
+ return (
423
+ <box
424
+ position="absolute"
425
+ left={0}
426
+ right={0}
427
+ bottom={above}
428
+ zIndex={5}
429
+ backgroundColor={colors.surface}
430
+ paddingTop={1}
431
+ paddingBottom={1}
432
+ flexDirection="column"
433
+ >
434
+ {matches.map((command, index) => {
435
+ const chosen = index === selected
436
+ return (
437
+ <box
438
+ key={command.name}
439
+ backgroundColor={chosen ? colors.raised : colors.surface}
440
+ paddingLeft={3}
441
+ paddingRight={3}
442
+ >
443
+ <text>
444
+ <span fg={chosen ? colors.blue : colors.text} attributes={chosen ? BOLD : 0}>
445
+ {`/${command.name}`.padEnd(width)}
446
+ </span>
447
+ <span fg={chosen ? colors.text : colors.muted}>{command.description}</span>
448
+ </text>
449
+ </box>
450
+ )
451
+ })}
452
+ </box>
453
+ )
454
+ }
455
+
456
+ /** The slash menu over a composer: what the text names, and which of it up and down chose. */
457
+ interface SlashMenuState {
458
+ readonly matches: readonly SlashCommand[]
459
+ readonly selected: number
460
+ /** Move the choice; false when no menu is open, so the key does what it otherwise would. */
461
+ move(step: number): boolean
462
+ /** Run the chosen command when the text is one; false sends the text to the agent. */
463
+ run(text: string): boolean
464
+ }
465
+
466
+ function useSlashMenu(commands: readonly SlashCommand[], typed: string): SlashMenuState {
467
+ const matches = slashMatches(commands, typed)
468
+ // A choice belongs to the text it was made for: typing more starts again at the top.
469
+ const [pick, setPick] = useState({ typed: "", index: 0 })
470
+ const selected = pick.typed === typed ? Math.min(pick.index, Math.max(0, matches.length - 1)) : 0
471
+ return {
472
+ matches,
473
+ selected,
474
+ move(step) {
475
+ if (matches.length === 0) return false
476
+ setPick({ typed, index: (selected + step + matches.length) % matches.length })
477
+ return true
478
+ },
479
+ run(text) {
480
+ const command = pickSlash(commands, text, selected)
481
+ if (!command) return false
482
+ command.run()
483
+ return true
484
+ },
485
+ }
486
+ }
487
+
488
+ /** Where every conversation starts: the mark, the composer, and where it will run. */
489
+ function Home(
490
+ props: ScreenProps & { readonly onPlace: () => void; readonly onOpen: (threadId: string) => void }
491
+ ) {
492
+ const { connection, runner, colors, settings, models, version } = props
493
+ const { width } = useTerminalDimensions()
494
+ const composerWidth = Math.min(76, width - 8)
495
+ // The hints that fit beside the folder, the most useful kept.
496
+ // Tab is a switch: its hint names where it switches to.
497
+ const tabTo = settings.place === "computer" ? "cloud" : placeLabel("computer").toLowerCase()
498
+ const hints: (readonly [string, string])[] =
499
+ composerWidth >= 72
500
+ ? [
501
+ ["tab", tabTo],
502
+ ["shift+tab", "permissions"],
503
+ ["ctrl+p", "commands"],
504
+ ]
505
+ : [
506
+ ["tab", tabTo],
507
+ ["ctrl+p", "commands"],
508
+ ]
509
+ const hintsWidth = hints.reduce((sum, [key, label]) => sum + key.length + label.length + 3, 0)
510
+ const [sending, setSending] = useState(false)
511
+ const [typed, setTyped] = useState("")
512
+ const slash = useSlashMenu(props.slashCommands, typed)
513
+ // Which instance this is matters most when it isn't this computer's.
514
+ const host = new URL(connection.apiUrl).host
515
+ const remote = !/^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(host)
516
+
517
+ useKeyboard((key: KeyEvent) => {
518
+ if (props.dialogOpen) return
519
+ if (key.name === "up" && slash.move(-1)) return
520
+ if (key.name === "down" && slash.move(1)) return
521
+ if (key.name === "tab" && !key.shift && !key.ctrl) props.onPlace()
522
+ })
523
+
524
+ const send = async (text: string): Promise<boolean> => {
525
+ if (slash.run(text)) return true
526
+ if (sending) return false
527
+ setSending(true)
528
+ try {
529
+ const { data: created } = await createAgentThread({
530
+ client: connection.client,
531
+ body: {
532
+ title: clip(text.split("\n")[0]?.trim() || "Conversation", 72),
533
+ ...(settings.place === "computer" ? { runsOn: "computer" as const } : {}),
534
+ },
535
+ throwOnError: true,
536
+ })
537
+
538
+ // It starts in the mode chosen here, the person's in it from then on: its next messages
539
+ // carry none, as the web keeps a mode chosen before the thread existed.
540
+ await setAgentThreadApprovalMode({
541
+ client: connection.client,
542
+ path: { threadId: created.thread.id },
543
+ body: { approvalMode: settings.approvalMode },
544
+ throwOnError: true,
545
+ })
546
+
547
+ const { data: posted } = await postAgentThreadMessage({
548
+ client: connection.client,
549
+ path: { threadId: created.thread.id },
550
+ body: {
551
+ text,
552
+ ...requesterSettings(),
553
+ ...messageSelection(models, settings),
554
+ },
555
+ throwOnError: true,
556
+ })
557
+ if (created.thread.runsOn === "computer") {
558
+ await rememberFolder(created.thread.id, runner.folder)
559
+ void runner.claim(posted.run.id)
560
+ }
561
+ props.onOpen(created.thread.id)
562
+ return true
563
+ } catch (error) {
564
+ props.say(errorText(error), "error")
565
+ return false
566
+ } finally {
567
+ setSending(false)
568
+ }
569
+ }
570
+
571
+ return (
572
+ <box flexDirection="column" flexGrow={1}>
573
+ <box flexGrow={1} flexDirection="column" alignItems="center" justifyContent="center">
574
+ <Logo colors={colors} />
575
+ <box height={2} flexShrink={0} />
576
+ <box width={composerWidth} flexDirection="column">
577
+ <SlashMenu colors={colors} menu={slash} above={6} />
578
+ <Composer
579
+ colors={colors}
580
+ focused={!props.dialogOpen}
581
+ onChange={setTyped}
582
+ placeholder="Ask anything…"
583
+ status={props.status(placeLabel(settings.place))}
584
+ onSubmit={send}
585
+ />
586
+ <box flexDirection="row" justifyContent="space-between">
587
+ {remote ? (
588
+ <text wrapMode="none">
589
+ <span fg={colors.text}>{connection.project.id}</span>
590
+ <span fg={colors.muted}>{` · ${host}`}</span>
591
+ </text>
592
+ ) : (
593
+ <text fg={colors.faint} wrapMode="none">
594
+ {settings.place === "computer"
595
+ ? shortPath(runner.folder, homedir(), composerWidth - hintsWidth - 2)
596
+ : "Runs in the cloud"}
597
+ </text>
598
+ )}
599
+ <KeyHints colors={colors} items={hints} />
600
+ </box>
601
+ </box>
602
+ </box>
603
+ <box
604
+ flexDirection="row"
605
+ justifyContent="space-between"
606
+ paddingLeft={2}
607
+ paddingRight={2}
608
+ paddingBottom={1}
609
+ >
610
+ <text wrapMode="none">
611
+ {remote ? (
612
+ <span fg={colors.muted}>
613
+ {settings.place === "computer"
614
+ ? shortPath(runner.folder, homedir(), 48)
615
+ : "Runs in the cloud"}
616
+ </span>
617
+ ) : (
618
+ <>
619
+ <span fg={colors.muted}>{connection.project.id}</span>
620
+ <span fg={colors.faint}>{` · ${host}`}</span>
621
+ </>
622
+ )}
623
+ {connection.user ? <span fg={colors.faint}>{` · ${connection.user.name}`}</span> : null}
624
+ </text>
625
+ <text fg={colors.faint}>{version.replace(/^sixb v/, "")}</text>
626
+ </box>
627
+ </box>
628
+ )
629
+ }
630
+
631
+ /** The model whose effort the person sets: the one chosen, else the project's default without tiers. */
632
+ function effortModel(
633
+ models: readonly LanguageModel[],
634
+ settings: Settings
635
+ ): LanguageModel | undefined {
636
+ const tiers = models.some((model) => model.tier !== undefined)
637
+ return settings.model
638
+ ? models.find(
639
+ (model) =>
640
+ model.provider === settings.model?.provider && model.modelId === settings.model.modelId
641
+ )
642
+ : tiers
643
+ ? undefined
644
+ : (models.find((model) => model.isDefault) ?? models[0])
645
+ }
646
+
647
+ /** How long a card that just appeared ignores its keys, so typing that was under way doesn't decide it. */
648
+ const APPROVAL_GRACE_MS = 700
649
+
650
+ /** A conversation: its transcript, the turn at work, what waits on you, and the composer. */
651
+ function ThreadView(
652
+ props: ScreenProps & {
653
+ readonly threadId: string
654
+ readonly approval: ThreadApproval | null
655
+ /** The thread as read; `raised` after "always", which raised its mode there. */
656
+ readonly onThreadRead: (thread: Thread, raised: boolean) => void
657
+ }
658
+ ) {
659
+ const { connection, runner, colors, syntax, settings, models, threadId } = props
660
+ const { client } = connection
661
+ const { width } = useTerminalDimensions()
662
+ const [thread, setThread] = useState<Thread | null>(null)
663
+ const [messages, setMessages] = useState<readonly ShownMessage[]>([])
664
+ const [runs, setRuns] = useState<readonly Run[]>([])
665
+ const [approvals, setApprovals] = useState<readonly Approval[]>([])
666
+ const [live, setLive] = useState<LiveRun | null>(null)
667
+ const [stopArmed, setStopArmed] = useState(false)
668
+ const [typed, setTyped] = useState("")
669
+ const slash = useSlashMenu(props.slashCommands, typed)
670
+ const scroll = useRef<ScrollBoxRenderable>(null)
671
+
672
+ const mine = thread !== null && owns(connection, thread)
673
+ const onComputer = thread?.runsOn === "computer"
674
+
675
+ const { onThreadRead } = props
676
+ const reload = useCallback(async () => {
677
+ const [threadResult, messageResult, runResult, approvalResult] = await Promise.all([
678
+ getAgentThread({ client, path: { threadId } }),
679
+ listAgentThreadMessages({
680
+ client,
681
+ path: { threadId },
682
+ query: { limit: "200", order: "asc" },
683
+ }),
684
+ listAgentThreadRuns({ client, path: { threadId }, query: { limit: "200", order: "asc" } }),
685
+ listAgentThreadApprovals({ client, path: { threadId }, query: { status: "pending" } }),
686
+ ])
687
+ if (threadResult.data) {
688
+ setThread(threadResult.data)
689
+ onThreadRead(threadResult.data, false)
690
+ }
691
+ if (messageResult.data) {
692
+ setMessages(messageResult.data.messages.flatMap((message) => shownMessage(message) ?? []))
693
+ }
694
+ if (runResult.data) setRuns(runResult.data.runs)
695
+ if (approvalResult.data) setApprovals(approvalResult.data.approvals)
696
+ return threadResult.data
697
+ }, [client, threadId, onThreadRead])
698
+
699
+ const activeRunId = thread?.activeRunId ?? null
700
+
701
+ // The folder its turns work in on this computer; null until read.
702
+ const [workFolder, setWorkFolder] = useState<string | undefined | null>(null)
703
+ useEffect(() => {
704
+ void folderOf(threadId).then(setWorkFolder)
705
+ }, [threadId])
706
+ // Another of the owner's computers runs it: its folder here, if any, is where it worked before.
707
+ const otherComputer = thread !== null && !runsOnThisComputer(thread, props.computerId)
708
+ const here = workFolder === runner.folder && !otherComputer
709
+ // This computer runs the conversation's turns when it is the owner's, and this its folder.
710
+ const runsHere = onComputer && mine && here
711
+ // Only a queued turn: a running one is another sixb's, or one whose sixb closed, which the API
712
+ // ends interrupted rather than running its commands again.
713
+ const queued = runs.find((run) => run.id === activeRunId)?.status === "queued"
714
+ useEffect(() => {
715
+ if (activeRunId && runsHere && queued) void runner.claim(activeRunId)
716
+ }, [activeRunId, runsHere, queued, runner])
717
+ // Its turns move to this computer, which alone claims them from now on, and to this folder.
718
+ const moveHere = async () => {
719
+ const { error } = await moveAgentThreadToComputer({
720
+ client,
721
+ path: { threadId },
722
+ body: { computerId: props.computerId },
723
+ })
724
+ if (error) return props.say(errorText(error), "error")
725
+ await rememberFolder(threadId, runner.folder)
726
+ setWorkFolder(runner.folder)
727
+ void reload()
728
+ props.say("Its turns now run in this folder")
729
+ }
730
+
731
+ useEffect(() => {
732
+ void reload()
733
+ const socket = createAgentActivitySocket({
734
+ client,
735
+ onActivity: (event) => {
736
+ if (event.threadId === threadId) void reload()
737
+ },
738
+ onApprovalActivity: (event) => {
739
+ if (event.threadId === threadId) void reload()
740
+ },
741
+ })
742
+ return () => socket.close()
743
+ }, [client, threadId, reload])
744
+
745
+ // The running turn streams in as it works; its stored answer replaces it once it ends.
746
+ useEffect(() => {
747
+ if (!activeRunId) return
748
+ setLive((current) => (current?.runId === activeRunId ? current : liveRun(activeRunId)))
749
+ const socket = createAgentRunSocket({
750
+ client,
751
+ runId: activeRunId,
752
+ onEvent: (event) => {
753
+ setLive((current) =>
754
+ reduceLive(current?.runId === activeRunId ? current : liveRun(activeRunId), event)
755
+ )
756
+ if (event.type === "agent.message.finalized" || event.type === "agent.run.finished")
757
+ void reload()
758
+ },
759
+ })
760
+ return () => socket.close()
761
+ }, [client, activeRunId, reload])
762
+
763
+ const pending = approvals[0]
764
+ const working =
765
+ activeRunId !== null &&
766
+ runs.find((run) => run.id === activeRunId)?.finishReason !== "awaiting_approval"
767
+
768
+ const stop = async () => {
769
+ if (!activeRunId) return
770
+ if (!stopArmed) {
771
+ setStopArmed(true)
772
+ setTimeout(() => setStopArmed(false), 2_000)
773
+ return
774
+ }
775
+ setStopArmed(false)
776
+ await cancelAgentRun({ client, path: { threadId }, body: { runId: activeRunId } })
777
+ runner.hearStop(activeRunId)
778
+ }
779
+
780
+ // A card that appears mid-sentence must not take the next letters typed as its answer: its keys
781
+ // count once it has been seen, and once per decision.
782
+ const [choice, setChoice] = useState(0)
783
+ const [deciding, setDeciding] = useState(false)
784
+ const shownAt = useRef(0)
785
+ const pendingId = pending?.id
786
+ useEffect(() => {
787
+ if (pendingId === undefined) return
788
+ shownAt.current = Date.now()
789
+ setChoice(0)
790
+ }, [pendingId])
791
+
792
+ const decide = async (index: number) => {
793
+ const option = APPROVAL_CHOICES[index]
794
+ if (!pending || !option || deciding) return
795
+ setDeciding(true)
796
+ try {
797
+ const { error } = await decideAgentApproval({
798
+ client,
799
+ path: { threadId, approvalId: pending.id },
800
+ body: { decision: option.decision, ...(option.always ? { always: true as const } : {}) },
801
+ })
802
+ if (error) props.say(errorText(error), "error")
803
+ const read = await reload()
804
+ // "Always" raised the mode there: the thread's wins over a choice still on its way.
805
+ if (read && option.always) onThreadRead(read, true)
806
+ } finally {
807
+ setDeciding(false)
808
+ }
809
+ }
810
+
811
+ useKeyboard((key: KeyEvent) => {
812
+ if (props.dialogOpen) return
813
+ if (pending && !key.ctrl && !key.meta) {
814
+ const settled = Date.now() - shownAt.current > APPROVAL_GRACE_MS
815
+ if (key.name === "left" || key.name === "up") {
816
+ return setChoice((value) => (value + APPROVAL_CHOICES.length - 1) % APPROVAL_CHOICES.length)
817
+ }
818
+ if (key.name === "right" || key.name === "down" || key.name === "tab") {
819
+ return setChoice((value) => (value + 1) % APPROVAL_CHOICES.length)
820
+ }
821
+ if (key.name === "return" && settled) return void decide(choice)
822
+ const shortcut = APPROVAL_CHOICES.findIndex((option) => option.key === key.name)
823
+ if (shortcut >= 0 && settled) return void decide(shortcut)
824
+ if (shortcut >= 0 || key.name === "return") return
825
+ }
826
+ if (key.name === "up" && slash.move(-1)) return
827
+ if (key.name === "down" && slash.move(1)) return
828
+ if (key.name === "escape") return void stop()
829
+ if (key.ctrl && key.name === "f" && onComputer && mine && !here && workFolder !== null) {
830
+ return void moveHere()
831
+ }
832
+ if (key.name === "pageup") scroll.current?.scrollBy(-10)
833
+ if (key.name === "pagedown") scroll.current?.scrollBy(10)
834
+ })
835
+
836
+ const send = async (text: string): Promise<boolean> => {
837
+ if (slash.run(text)) return true
838
+ if (!thread) return false
839
+ if (onComputer && mine && !here) {
840
+ props.say("It works in another folder: press ctrl+f to move it here first.")
841
+ return false
842
+ }
843
+ if (activeRunId) {
844
+ props.say("The agent is still working. Press esc twice to stop it.")
845
+ return false
846
+ }
847
+ const { data, error } = await postAgentThreadMessage({
848
+ client,
849
+ path: { threadId },
850
+ body: {
851
+ text,
852
+ // The thread's mode applies, unless one chosen here has not reached it yet.
853
+ ...(props.approval?.chosen && props.approval.mode
854
+ ? { approvalMode: props.approval.mode }
855
+ : {}),
856
+ ...requesterSettings(),
857
+ ...messageSelection(models, settings),
858
+ },
859
+ })
860
+ if (error || !data) {
861
+ props.say(errorText(error), "error")
862
+ return false
863
+ }
864
+ if (runsHere) void runner.claim(data.run.id)
865
+ setLive(liveRun(data.run.id))
866
+ void reload()
867
+ return true
868
+ }
869
+
870
+ const modelNames = useMemo(
871
+ () => new Map(models.map((model) => [`${model.provider}:${model.modelId}`, model.name])),
872
+ [models]
873
+ )
874
+ const elsewhere = onComputer && thread && !mine
875
+ const runningSince = runs.find((run) => run.id === activeRunId)?.startedAt
876
+
877
+ return (
878
+ <box flexDirection="column" flexGrow={1} paddingTop={1}>
879
+ <box
880
+ flexDirection="row"
881
+ justifyContent="space-between"
882
+ paddingLeft={3}
883
+ paddingRight={3}
884
+ paddingBottom={1}
885
+ >
886
+ <text wrapMode="none" flexGrow={1} flexShrink={1}>
887
+ <span fg={colors.blue}>{"▰ "}</span>
888
+ <span fg={colors.text} attributes={BOLD}>
889
+ {clip(thread?.title ?? "Conversation", width - connection.project.id.length - 16)}
890
+ </span>
891
+ </text>
892
+ <text fg={colors.faint} flexShrink={0}>
893
+ {connection.project.id}
894
+ </text>
895
+ </box>
896
+ <scrollbox
897
+ ref={scroll}
898
+ flexGrow={1}
899
+ flexShrink={1}
900
+ stickyScroll
901
+ stickyStart="bottom"
902
+ paddingLeft={2}
903
+ paddingRight={2}
904
+ backgroundColor={colors.background}
905
+ verticalScrollbarOptions={{ visible: false }}
906
+ horizontalScrollbarOptions={{ visible: false }}
907
+ >
908
+ <Transcript
909
+ colors={colors}
910
+ syntax={syntax}
911
+ messages={messages}
912
+ runs={runs}
913
+ live={live}
914
+ approvals={approvals}
915
+ modelNames={modelNames}
916
+ computerRuns={onComputer}
917
+ width={width}
918
+ approvalChoice={choice}
919
+ {...(onComputer ? { folder: runner.folder } : {})}
920
+ />
921
+ {working && live?.working !== false ? (
922
+ <box paddingTop={1}>
923
+ <Working
924
+ colors={colors}
925
+ since={runningSince ? Date.parse(runningSince) : Date.now()}
926
+ stopping={stopArmed}
927
+ label={
928
+ stopArmed
929
+ ? "Press esc again to stop"
930
+ : live?.compacting
931
+ ? "Condensing earlier turns"
932
+ : queuedLabel(runs, activeRunId, {
933
+ onComputer,
934
+ mine,
935
+ runsHere: activeRunId !== null && runner.runs(activeRunId),
936
+ })
937
+ }
938
+ />
939
+ </box>
940
+ ) : null}
941
+ <box height={1} />
942
+ </scrollbox>
943
+ <box flexDirection="column" flexShrink={0} paddingLeft={2} paddingRight={2} paddingBottom={1}>
944
+ {elsewhere ? (
945
+ <text fg={colors.amber} paddingBottom={1}>
946
+ {"This conversation runs on its owner's computer: you can read it here."}
947
+ </text>
948
+ ) : onComputer && mine && workFolder !== null && !here ? (
949
+ <text paddingBottom={1}>
950
+ <span fg={colors.amber}>
951
+ {otherComputer
952
+ ? "It works on another computer."
953
+ : workFolder
954
+ ? `It works in ${shortPath(workFolder, homedir(), 48)}.`
955
+ : "It started on another computer."}
956
+ </span>
957
+ <span fg={colors.muted}>{" Its turns run there: "}</span>
958
+ <span fg={colors.text}>ctrl+f</span>
959
+ <span fg={colors.muted}> moves it to this folder</span>
960
+ </text>
961
+ ) : null}
962
+ <SlashMenu colors={colors} menu={slash} above={8} />
963
+ <Composer
964
+ colors={colors}
965
+ focused={!props.dialogOpen && !pending && !elsewhere}
966
+ onChange={setTyped}
967
+ accent={pending ? colors.amber : undefined}
968
+ placeholder={pending ? "Decide on the request above first" : "Ask anything…"}
969
+ status={props.status(onComputer ? placeLabel("computer") : placeLabel("cloud"))}
970
+ onSubmit={send}
971
+ />
972
+ <box flexDirection="row" justifyContent="space-between" paddingTop={1}>
973
+ <text fg={colors.faint}>
974
+ {onComputer ? shortPath(runner.folder, homedir(), 40) : "Runs in the cloud"}
975
+ </text>
976
+ <text>
977
+ <span fg={colors.text}>ctrl+p</span>
978
+ <span fg={colors.muted}> commands</span>
979
+ </text>
980
+ </box>
981
+ </box>
982
+ </box>
983
+ )
984
+ }
985
+
986
+ function queuedLabel(
987
+ runs: readonly Run[],
988
+ runId: string | null,
989
+ where: { readonly onComputer: boolean; readonly mine: boolean; readonly runsHere: boolean }
990
+ ): string {
991
+ const run = runs.find((entry) => entry.id === runId)
992
+ if (run?.status === "queued") {
993
+ return where.onComputer && !where.mine ? "Waiting for its owner's computer" : "Starting"
994
+ }
995
+ // Yours, running, and not here: another sixb runs it, or one that closed, whose turn ends
996
+ // interrupted once its lease lapses.
997
+ if (where.onComputer && where.mine && !where.runsHere) return "Working in another sixb"
998
+ return "Working"
999
+ }
1000
+
1001
+ function ThreadsDialog({
1002
+ connection,
1003
+ colors,
1004
+ onClose,
1005
+ onOpen,
1006
+ }: {
1007
+ readonly connection: Connection
1008
+ readonly colors: TuiColors
1009
+ readonly onClose: () => void
1010
+ readonly onOpen: (threadId: string) => void
1011
+ }) {
1012
+ const [threads, setThreads] = useState<readonly Thread[] | null>(null)
1013
+ useEffect(() => {
1014
+ void listAgentThreads({
1015
+ client: connection.client,
1016
+ query: { limit: "100", order: "desc" },
1017
+ }).then(({ data }) => setThreads(data?.threads ?? []))
1018
+ }, [connection])
1019
+ return (
1020
+ <Palette
1021
+ colors={colors}
1022
+ title="Conversations"
1023
+ placeholder={threads === null ? "Loading…" : "Search conversations"}
1024
+ onClose={onClose}
1025
+ items={(threads ?? [])
1026
+ .filter((thread) => thread.kind === "conversation")
1027
+ .map((thread) => ({
1028
+ id: thread.id,
1029
+ label: thread.title ?? "Untitled",
1030
+ detail: [
1031
+ thread.runsOn === "computer" ? placeLabel("computer") : "Cloud",
1032
+ ago(thread.lastMessageAt ?? thread.createdAt),
1033
+ ].join(" · "),
1034
+ run: () => onOpen(thread.id),
1035
+ }))}
1036
+ />
1037
+ )
1038
+ }
1039
+
1040
+ function commandItems(input: {
1041
+ readonly settings: Settings
1042
+ readonly approvalMode: ApprovalMode | undefined
1043
+ readonly models: readonly LanguageModel[]
1044
+ readonly newConversation: () => void
1045
+ readonly open: (dialog: Dialog) => void
1046
+ readonly setPlace: (place: Settings["place"]) => void
1047
+ readonly cycleEffort: () => void
1048
+ readonly quit: () => void
1049
+ }): PaletteItem[] {
1050
+ const { settings } = input
1051
+ return [
1052
+ {
1053
+ id: "new",
1054
+ group: "Conversation",
1055
+ label: "New conversation",
1056
+ keys: "ctrl+n",
1057
+ run: input.newConversation,
1058
+ },
1059
+ {
1060
+ id: "threads",
1061
+ group: "Conversation",
1062
+ label: "Open a conversation",
1063
+ keys: "ctrl+l",
1064
+ run: () => input.open("threads"),
1065
+ },
1066
+ {
1067
+ id: "model",
1068
+ group: "Agent",
1069
+ label: "Model",
1070
+ detail: modelLabel(input.models, settings).name,
1071
+ keys: "ctrl+o",
1072
+ run: () => input.open("models"),
1073
+ },
1074
+ {
1075
+ id: "effort",
1076
+ group: "Agent",
1077
+ label: "Effort",
1078
+ detail: modelLabel(input.models, settings).reasoning ?? "default",
1079
+ keys: "ctrl+t",
1080
+ run: input.cycleEffort,
1081
+ },
1082
+ {
1083
+ id: "permissions",
1084
+ group: "Agent",
1085
+ label: "Permissions",
1086
+ ...(input.approvalMode ? { detail: approvalLabel(input.approvalMode) } : {}),
1087
+ keys: "shift+tab",
1088
+ run: () => input.open("permissions"),
1089
+ },
1090
+ {
1091
+ id: "place",
1092
+ group: "Agent",
1093
+ label:
1094
+ settings.place === "computer"
1095
+ ? "Run new conversations in the cloud"
1096
+ : `Run new conversations on ${placeLabel("computer")}`,
1097
+ keys: "tab",
1098
+ run: () => input.setPlace(settings.place === "computer" ? "cloud" : "computer"),
1099
+ },
1100
+ { id: "quit", group: "Sixb", label: "Quit", keys: "ctrl+c", run: input.quit },
1101
+ ]
1102
+ }
1103
+
1104
+ function modelItems(
1105
+ models: readonly LanguageModel[],
1106
+ settings: Settings,
1107
+ choose: (
1108
+ model: LanguageModel | null,
1109
+ reasoning?: LanguageModel["reasoningLevels"][number]
1110
+ ) => void
1111
+ ): PaletteItem[] {
1112
+ const tiers = models.some((model) => model.tier !== undefined)
1113
+ const chosen = settings.model
1114
+ const items: PaletteItem[] = tiers
1115
+ ? [
1116
+ {
1117
+ id: "auto",
1118
+ group: "Models",
1119
+ label: "Auto",
1120
+ detail: "the best model for each message",
1121
+ current: !chosen,
1122
+ run: () => choose(null),
1123
+ },
1124
+ ]
1125
+ : []
1126
+ for (const model of models) {
1127
+ const current = chosen
1128
+ ? chosen.provider === model.provider && chosen.modelId === model.modelId
1129
+ : !tiers && model.isDefault
1130
+ items.push({
1131
+ id: `${model.provider}:${model.modelId}`,
1132
+ group: "Models",
1133
+ label: model.name,
1134
+ detail: [model.tier, model.publisher.name].filter(Boolean).join(" · "),
1135
+ current,
1136
+ run: () => choose(model),
1137
+ })
1138
+ }
1139
+ // How hard the model in effect thinks, when it lets you choose.
1140
+ const inEffect = models.find((model) =>
1141
+ chosen
1142
+ ? chosen.provider === model.provider && chosen.modelId === model.modelId
1143
+ : !tiers && model.isDefault
1144
+ )
1145
+ for (const level of inEffect?.reasoningLevels ?? []) {
1146
+ if (level === "provider-default" || !inEffect) continue
1147
+ items.push({
1148
+ id: `effort:${level}`,
1149
+ group: "Effort",
1150
+ label: level,
1151
+ current: settings.reasoning === level,
1152
+ run: () => choose(inEffect, level),
1153
+ })
1154
+ }
1155
+ return items
1156
+ }
1157
+
1158
+ /** The person's own time zone and language, as the app's composer sends them. */
1159
+ function requesterSettings(): { readonly timeZone: string; readonly locale: string } {
1160
+ const { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions()
1161
+ return { timeZone, locale }
1162
+ }
1163
+
1164
+ function errorText(error: unknown): string {
1165
+ if (error instanceof Error) return error.message
1166
+ if (error && typeof error === "object" && "error" in error) return String(error.error)
1167
+ return String(error)
1168
+ }
1169
+
1170
+ function ago(iso: string): string {
1171
+ const seconds = Math.max(0, (Date.now() - Date.parse(iso)) / 1_000)
1172
+ if (seconds < 60) return "just now"
1173
+ if (seconds < 3_600) return `${Math.floor(seconds / 60)}m ago`
1174
+ if (seconds < 86_400) return `${Math.floor(seconds / 3_600)}h ago`
1175
+ return `${Math.floor(seconds / 86_400)}d ago`
1176
+ }
1177
+
1178
+ /** Text cut to `max` characters at a word, with an ellipsis. */
1179
+ function clip(text: string, max: number): string {
1180
+ if (text.length <= max) return text
1181
+ const cut = text.slice(0, Math.max(1, max - 1))
1182
+ const space = cut.lastIndexOf(" ")
1183
+ return `${space > max / 2 ? cut.slice(0, space) : cut}…`
1184
+ }
1185
+
1186
+ /** Put text on the clipboard: pbcopy on macOS, whose Terminal ignores OSC 52; OSC 52 elsewhere. */
1187
+ async function copy(
1188
+ text: string,
1189
+ renderer: { copyToClipboardOSC52(text: string): boolean }
1190
+ ): Promise<boolean> {
1191
+ if (process.platform === "darwin") {
1192
+ const child = Bun.spawn(["pbcopy"], { stdin: "pipe", stdout: "ignore", stderr: "ignore" })
1193
+ child.stdin.write(text)
1194
+ child.stdin.end()
1195
+ return (await child.exited) === 0
1196
+ }
1197
+ return renderer.copyToClipboardOSC52(text)
1198
+ }