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