@sixb/cli 0.2.0 → 0.2.2

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 (67) hide show
  1. package/dist/commands/agent.d.ts +4 -1
  2. package/dist/commands/agent.d.ts.map +1 -1
  3. package/dist/commands/connect.d.ts +13 -0
  4. package/dist/commands/connect.d.ts.map +1 -0
  5. package/dist/commands/db-migrate.d.ts.map +1 -1
  6. package/dist/commands/db-prepare.d.ts.map +1 -1
  7. package/dist/commands/desktop.d.ts.map +1 -1
  8. package/dist/lib/command-line.d.ts +11 -1
  9. package/dist/lib/command-line.d.ts.map +1 -1
  10. package/dist/{tui → lib}/connection.d.ts +11 -1
  11. package/dist/{tui → lib}/connection.d.ts.map +1 -1
  12. package/dist/lib/desktop.d.ts +4 -0
  13. package/dist/lib/desktop.d.ts.map +1 -1
  14. package/dist/lib/dev-supervisor.d.ts.map +1 -1
  15. package/dist/lib/profiles.d.ts +5 -0
  16. package/dist/lib/profiles.d.ts.map +1 -1
  17. package/dist/lib/runtime.d.ts.map +1 -1
  18. package/dist/runner/allowed-folders.d.ts +17 -0
  19. package/dist/runner/allowed-folders.d.ts.map +1 -0
  20. package/dist/runner/computer-connection.d.ts +70 -0
  21. package/dist/runner/computer-connection.d.ts.map +1 -0
  22. package/dist/runner/computer.d.ts.map +1 -0
  23. package/dist/runner/desktop-runner-main.d.ts +2 -0
  24. package/dist/runner/desktop-runner-main.d.ts.map +1 -0
  25. package/dist/runner/desktop-runner.d.ts +43 -0
  26. package/dist/runner/desktop-runner.d.ts.map +1 -0
  27. package/dist/runner/keep-awake.d.ts +11 -0
  28. package/dist/runner/keep-awake.d.ts.map +1 -0
  29. package/dist/runner/local-runner.d.ts +131 -0
  30. package/dist/runner/local-runner.d.ts.map +1 -0
  31. package/dist/tui/app.d.ts +2 -2
  32. package/dist/tui/app.d.ts.map +1 -1
  33. package/dist/tui/format.d.ts +29 -0
  34. package/dist/tui/format.d.ts.map +1 -1
  35. package/dist/tui/index.d.ts.map +1 -1
  36. package/dist/tui/settings.d.ts +5 -8
  37. package/dist/tui/settings.d.ts.map +1 -1
  38. package/package.json +17 -17
  39. package/src/commands/agent.ts +122 -39
  40. package/src/commands/connect.ts +197 -0
  41. package/src/commands/db-migrate.ts +1 -0
  42. package/src/commands/db-prepare.ts +1 -0
  43. package/src/commands/desktop.ts +2 -1
  44. package/src/index.tsx +13 -0
  45. package/src/lib/command-line.ts +22 -3
  46. package/src/{tui → lib}/connection.ts +64 -17
  47. package/src/lib/desktop.ts +8 -1
  48. package/src/lib/dev-supervisor.ts +7 -2
  49. package/src/lib/profiles.ts +15 -1
  50. package/src/lib/runtime.ts +1 -0
  51. package/src/lib/storage-migration.ts +1 -0
  52. package/src/runner/allowed-folders.ts +126 -0
  53. package/src/runner/computer-connection.ts +184 -0
  54. package/src/runner/desktop-runner-main.ts +9 -0
  55. package/src/runner/desktop-runner.ts +217 -0
  56. package/src/runner/keep-awake.ts +50 -0
  57. package/src/runner/local-runner.ts +427 -0
  58. package/src/tui/app.tsx +168 -12
  59. package/src/tui/format.ts +203 -6
  60. package/src/tui/index.tsx +14 -13
  61. package/src/tui/settings.ts +12 -44
  62. package/dist/tui/computer.d.ts.map +0 -1
  63. package/dist/tui/runner.d.ts +0 -75
  64. package/dist/tui/runner.d.ts.map +0 -1
  65. package/src/tui/runner.ts +0 -256
  66. /package/dist/{tui → runner}/computer.d.ts +0 -0
  67. /package/src/{tui → runner}/computer.ts +0 -0
package/src/tui/app.tsx CHANGED
@@ -26,14 +26,25 @@ import {
26
26
  setAgentThreadApprovalMode,
27
27
  } from "@sixb/client"
28
28
  import { useCallback, useEffect, useMemo, useRef, useState } from "react"
29
+ import type { Connection } from "../lib/connection"
30
+ import { isFolderAllowed, setFoldersAllowed, watchAllowedFolders } from "../runner/allowed-folders"
31
+ import { thisComputer } from "../runner/computer"
32
+ import { type LocalRunner, owns } from "../runner/local-runner"
29
33
  import { Logo } from "./brand"
30
- import { thisComputer } from "./computer"
31
- import type { Connection } from "./connection"
32
34
  import { ContextPanel } from "./context"
33
- import { type ContextUse, contextStatus, fittedContextText, shortPath } from "./format"
35
+ import {
36
+ type BackgroundCommand,
37
+ backgroundEnded,
38
+ backgroundStrip,
39
+ type ContextUse,
40
+ commandLabel,
41
+ contextStatus,
42
+ elapsed,
43
+ fittedContextText,
44
+ shortPath,
45
+ } from "./format"
34
46
  import { Palette, type PaletteItem } from "./palette"
35
47
  import { type LiveRun, liveRun, reduceLive, type ShownMessage, shownMessage } from "./parts"
36
- import { type LocalRunner, owns } from "./runner"
37
48
  import {
38
49
  APPROVAL_MODES,
39
50
  type ApprovalMode,
@@ -43,14 +54,13 @@ import {
43
54
  modelLabel,
44
55
  placeLabel,
45
56
  type ReasoningLevel,
46
- rememberWebMessages,
47
57
  type Settings,
48
58
  saveSettings,
49
59
  } from "./settings"
50
60
  import { pickSlash, type SlashCommand, slashMatches } from "./slash"
51
61
  import type { TuiColors } from "./theme"
52
62
  import { APPROVAL_CHOICES, type Approval, type Run, Transcript, Working } from "./transcript"
53
- import { BOLD, Composer, ComposerDraft, KeyHints, type StatusItem } from "./ui"
63
+ import { BOLD, Composer, ComposerDraft, KeyHints, type StatusItem, useNow } from "./ui"
54
64
 
55
65
  type Thread = GetAgentThreadResponses[200]
56
66
  type Screen = { readonly kind: "home" } | { readonly kind: "thread"; readonly threadId: string }
@@ -137,6 +147,28 @@ export function Workspace(props: WorkspaceProps) {
137
147
  runner.openSession()
138
148
  return () => void runner.closeSession()
139
149
  }, [settings.continueFromWeb, runner])
150
+ // The choice is per project, so it can first be read now that this one is known. Another sixb may
151
+ // forget this folder, or choose it: that holds here too, with no restart.
152
+ useEffect(() => {
153
+ let stop: (() => void) | null = null
154
+ let unmounted = false
155
+ const follow = () =>
156
+ void isFolderAllowed(connection, runner.folder).then((continueFromWeb) =>
157
+ setSettingsState((current) => ({ ...current, continueFromWeb }))
158
+ )
159
+ follow()
160
+ void watchAllowedFolders(follow).then(
161
+ (unwatch) => {
162
+ if (unmounted) unwatch()
163
+ else stop = unwatch
164
+ },
165
+ () => {}
166
+ )
167
+ return () => {
168
+ unmounted = true
169
+ stop?.()
170
+ }
171
+ }, [connection, runner])
140
172
  useEffect(
141
173
  () => runner.onElsewhere(() => say("A message sent from elsewhere runs here")),
142
174
  [runner, say]
@@ -145,13 +177,37 @@ export function Workspace(props: WorkspaceProps) {
145
177
  const socket = createAgentActivitySocket({
146
178
  client: connection.client,
147
179
  onActivity: (event) => {
148
- if (event.status === "queued" && event.runsOn === "computer") {
180
+ if (event.cancelRequested) runner.hearStop(event.runId)
181
+ else if (event.status === "queued" && event.runsOn === "computer") {
149
182
  void runner.claimIfHere(event.threadId, event.runId)
150
183
  }
151
184
  },
185
+ // Something changed for this folder, such as a stop asked for from the web: the session's
186
+ // renewal answers it now rather than in twenty seconds.
187
+ onComputerActivity: (event) => {
188
+ if (event.computerId === props.computerId && event.folder === runner.folder) {
189
+ runner.renewSession()
190
+ }
191
+ },
152
192
  })
153
193
  return () => socket.close()
154
- }, [connection, runner])
194
+ }, [connection, runner, props.computerId])
195
+
196
+ // A background command that ends says so, whichever conversation is open.
197
+ useEffect(() => {
198
+ const key = (command: { readonly threadId: string; readonly id: string }) =>
199
+ `${command.threadId}:${command.id}`
200
+ let known = new Map(runner.backgroundCommands().map((command) => [key(command), command]))
201
+ return runner.onBackground(() => {
202
+ const commands = runner.backgroundCommands()
203
+ for (const command of commands) {
204
+ if (known.get(key(command))?.status !== "running" || command.status === "running") continue
205
+ const ended = backgroundEnded(command)
206
+ say(ended.text, ended.failed ? "error" : "info")
207
+ }
208
+ known = new Map(commands.map((command) => [key(command), command]))
209
+ })
210
+ }, [runner, say])
155
211
 
156
212
  // In a conversation, the mode is the thread's, as the web reads it: "always" on a card raises it,
157
213
  // and a mode chosen in the app applies here too. New conversations start in the settings' mode.
@@ -364,6 +420,17 @@ export function Workspace(props: WorkspaceProps) {
364
420
  newConversation: () => setScreen({ kind: "home" }),
365
421
  open: setDialog,
366
422
  setPlace: (place) => setSettings((current) => ({ ...current, place })),
423
+ toggleKeepAwake: () =>
424
+ setSettings((current) => {
425
+ const keepAwake = !current.keepAwake
426
+ runner.keepsAwake = keepAwake
427
+ say(
428
+ keepAwake
429
+ ? "From the next turn, this computer stays awake while one runs here"
430
+ : "From the next turn, this computer may sleep while one runs here"
431
+ )
432
+ return { ...current, keepAwake }
433
+ }),
367
434
  toggleContinueFromWeb: () =>
368
435
  setSettings((current) => {
369
436
  const continueFromWeb = !current.continueFromWeb
@@ -372,7 +439,7 @@ export function Workspace(props: WorkspaceProps) {
372
439
  ? "Messages from the web run in this folder"
373
440
  : "Messages from the web wait, in this folder, until you turn this back on"
374
441
  )
375
- void rememberWebMessages(runner.folder, continueFromWeb).catch(() =>
442
+ void setFoldersAllowed(connection, [runner.folder], continueFromWeb).catch(() =>
376
443
  say("Could not keep this choice for next time", "error")
377
444
  )
378
445
  return { ...current, continueFromWeb }
@@ -700,6 +767,7 @@ function ThreadView(
700
767
  const [stopArmed, setStopArmed] = useState(false)
701
768
  const [typed, setTyped] = useState("")
702
769
  const [contextOpen, setContextOpen] = useState(false)
770
+ const [stopOpen, setStopOpen] = useState(false)
703
771
  // A conversation adds what only it can show: what it uses of its model's context.
704
772
  const slashCommands = useMemo(
705
773
  () => [
@@ -718,6 +786,23 @@ function ThreadView(
718
786
  const mine = thread !== null && owns(connection, thread)
719
787
  const onComputer = thread?.runsOn === "computer"
720
788
 
789
+ // The commands its turns left running here, ticking while they run.
790
+ const [background, setBackground] = useState<readonly BackgroundCommand[]>(() =>
791
+ runner.backgroundCommands(threadId)
792
+ )
793
+ useEffect(() => {
794
+ setBackground(runner.backgroundCommands(threadId))
795
+ return runner.onBackground(() => setBackground(runner.backgroundCommands(threadId)))
796
+ }, [runner, threadId])
797
+ const runningBackground = background.filter((command) => command.status === "running")
798
+ const now = useNow(1_000, runningBackground.length > 0)
799
+ const stopBackground = (command: BackgroundCommand) =>
800
+ void runner
801
+ .stopBackground({ threadId, id: command.id, startedAt: command.startedAt })
802
+ .then((stopped) => {
803
+ if (!stopped) props.say(`${commandLabel(command.command)} had ended already`)
804
+ })
805
+
721
806
  const { onThreadRead } = props
722
807
  // Measured against the model the next message goes to; without a choice, the latest turn's.
723
808
  const metered = messageSelection(models, settings).model
@@ -782,7 +867,8 @@ function ThreadView(
782
867
  const queued = runs.find((run) => run.id === activeRunId)?.status === "queued"
783
868
  const { continueFromWeb } = props.settings
784
869
  useEffect(() => {
785
- if (activeRunId && runsHere && queued && continueFromWeb) void runner.claim(activeRunId)
870
+ if (activeRunId && runsHere && queued && continueFromWeb)
871
+ void runner.claimElsewhere(activeRunId)
786
872
  }, [activeRunId, runsHere, queued, continueFromWeb, runner])
787
873
  // Its turns move to this computer, which alone claims them from now on, and to this folder.
788
874
  const moveHere = async () => {
@@ -887,7 +973,7 @@ function ThreadView(
887
973
  }
888
974
 
889
975
  useKeyboard((key: KeyEvent) => {
890
- if (props.dialogOpen || contextOpen) return
976
+ if (props.dialogOpen || contextOpen || stopOpen) return
891
977
  if (pending && !key.ctrl && !key.meta) {
892
978
  const settled = Date.now() - shownAt.current > APPROVAL_GRACE_MS
893
979
  if (key.name === "left" || key.name === "up") {
@@ -904,6 +990,7 @@ function ThreadView(
904
990
  if (key.name === "up" && slash.move(-1)) return
905
991
  if (key.name === "down" && slash.move(1)) return
906
992
  if (key.name === "escape") return void stop()
993
+ if (key.ctrl && key.name === "x" && runningBackground.length > 0) return setStopOpen(true)
907
994
  if (key.ctrl && key.name === "f" && onComputer && mine && !here) {
908
995
  return void moveHere()
909
996
  }
@@ -1065,10 +1152,18 @@ function ThreadView(
1065
1152
  <span fg={colors.muted}> moves it to this folder</span>
1066
1153
  </text>
1067
1154
  ) : null}
1155
+ {runningBackground.length > 0 ? (
1156
+ <BackgroundLine
1157
+ colors={colors}
1158
+ commands={runningBackground}
1159
+ now={now}
1160
+ width={width - 4}
1161
+ />
1162
+ ) : null}
1068
1163
  <SlashMenu colors={colors} menu={slash} above={8} />
1069
1164
  <Composer
1070
1165
  colors={colors}
1071
- focused={!props.dialogOpen && !contextOpen && !pending && !elsewhere}
1166
+ focused={!props.dialogOpen && !contextOpen && !stopOpen && !pending && !elsewhere}
1072
1167
  onChange={setTyped}
1073
1168
  accent={pending ? colors.amber : undefined}
1074
1169
  placeholder={pending ? "Decide on the request above first" : "Ask anything…"}
@@ -1085,6 +1180,20 @@ function ThreadView(
1085
1180
  </text>
1086
1181
  </box>
1087
1182
  </box>
1183
+ {stopOpen ? (
1184
+ <Palette
1185
+ colors={colors}
1186
+ title="Stop a background command"
1187
+ placeholder="Search"
1188
+ onClose={() => setStopOpen(false)}
1189
+ items={runningBackground.map((command) => ({
1190
+ id: `${command.id}:${command.startedAt}`,
1191
+ label: commandLabel(command.command, 48),
1192
+ detail: `running for ${elapsed(now - Date.parse(command.startedAt))}`,
1193
+ run: () => stopBackground(command),
1194
+ }))}
1195
+ />
1196
+ ) : null}
1088
1197
  {contextOpen ? (
1089
1198
  <ContextPanel
1090
1199
  colors={colors}
@@ -1099,6 +1208,45 @@ function ThreadView(
1099
1208
  )
1100
1209
  }
1101
1210
 
1211
+ /**
1212
+ * The background commands running for the conversation, over the composer: each with how long it
1213
+ * has run, and the key that stops one.
1214
+ */
1215
+ function BackgroundLine({
1216
+ colors,
1217
+ commands,
1218
+ now,
1219
+ width,
1220
+ }: {
1221
+ readonly colors: TuiColors
1222
+ readonly commands: readonly BackgroundCommand[]
1223
+ readonly now: number
1224
+ readonly width: number
1225
+ }) {
1226
+ const hint = "ctrl+x stop"
1227
+ const { shown, more } = backgroundStrip(commands, now, width - hint.length - 3)
1228
+
1229
+ return (
1230
+ <box flexDirection="row" justifyContent="space-between" paddingBottom={1} paddingLeft={1}>
1231
+ <text wrapMode="none" flexShrink={1}>
1232
+ {shown.map((entry, index) => (
1233
+ <span key={`${index}:${entry.label}`}>
1234
+ {index > 0 ? " " : ""}
1235
+ <span fg={colors.green}>{"● "}</span>
1236
+ <span fg={colors.text}>{entry.label}</span>
1237
+ <span fg={colors.muted}>{` ${entry.time}`}</span>
1238
+ </span>
1239
+ ))}
1240
+ {more > 0 ? <span fg={colors.muted}>{` +${more} more`}</span> : null}
1241
+ </text>
1242
+ <text flexShrink={0}>
1243
+ <span fg={colors.text}>ctrl+x</span>
1244
+ <span fg={colors.muted}> stop</span>
1245
+ </text>
1246
+ </box>
1247
+ )
1248
+ }
1249
+
1102
1250
  export function activityLabel(
1103
1251
  runs: readonly Run[],
1104
1252
  runId: string | null,
@@ -1173,6 +1321,7 @@ function commandItems(input: {
1173
1321
  readonly setPlace: (place: Settings["place"]) => void
1174
1322
  /** Whether your messages from the web, or another device, run in this folder. */
1175
1323
  readonly toggleContinueFromWeb: () => void
1324
+ readonly toggleKeepAwake: () => void
1176
1325
  readonly cycleEffort: () => void
1177
1326
  readonly quit: () => void
1178
1327
  }): PaletteItem[] {
@@ -1233,6 +1382,13 @@ function commandItems(input: {
1233
1382
  detail: settings.continueFromWeb ? "run here" : "off",
1234
1383
  run: input.toggleContinueFromWeb,
1235
1384
  },
1385
+ {
1386
+ id: "keep-awake",
1387
+ group: "Agent",
1388
+ label: "Keep computer awake during turns",
1389
+ detail: settings.keepAwake ? "on" : "off",
1390
+ run: input.toggleKeepAwake,
1391
+ },
1236
1392
  { id: "quit", group: "Sixb", label: "Quit", keys: "ctrl+c", run: input.quit },
1237
1393
  ]
1238
1394
  }
package/src/tui/format.ts CHANGED
@@ -34,9 +34,21 @@ export function toolLine(
34
34
  switch (part.name) {
35
35
  case "bash": {
36
36
  const command = text(input?.command)
37
+ // Started in the background: it runs on, and its id is what later calls name.
38
+ if (input?.run_in_background === true) {
39
+ const id = text(output?.id)
40
+ return {
41
+ verb: "bash",
42
+ command: command.trim(),
43
+ detail: firstLine(command) + (command.includes("\n") ? " …" : ""),
44
+ note: id ? `in the background · ${id}` : "in the background",
45
+ ...error,
46
+ }
47
+ }
37
48
  const exitCode = typeof output?.exitCode === "number" ? output.exitCode : undefined
49
+ const timedOut = output?.timedOut === true
38
50
  const stdout = text(output?.stdout)
39
- const stderr = text(output?.stderr)
51
+ const stderr = timedOut ? withoutAgentNotice(text(output?.stderr)) : text(output?.stderr)
40
52
  const shown = exitCode !== undefined && exitCode !== 0 && stderr ? stderr : stdout || stderr
41
53
  const heldIds = heldApprovalIds(stdout)
42
54
  const decided = heldIds.flatMap((id) => outcomes.get(id) ?? [])
@@ -50,9 +62,23 @@ export function toolLine(
50
62
  ? { note: "held for your approval", held }
51
63
  : heldIds.length > 0
52
64
  ? decidedLine(decided)
53
- : exitCode !== undefined && exitCode !== 0
54
- ? { note: `exit ${exitCode}`, failed: true }
55
- : {}),
65
+ : timedOut
66
+ ? { note: `timed out after ${commandTimeoutText(input?.timeoutMs)}`, failed: true }
67
+ : exitCode !== undefined && exitCode !== 0
68
+ ? { note: `exit ${exitCode}`, failed: true }
69
+ : {}),
70
+ ...error,
71
+ }
72
+ }
73
+ case "bash_output":
74
+ case "bash_stop": {
75
+ const output_ = text(output?.output)
76
+ const status = text(output?.status)
77
+ return {
78
+ verb: part.name === "bash_stop" ? "stop" : "output",
79
+ detail: [text(input?.id), firstLine(text(output?.command))].filter(Boolean).join(" "),
80
+ ...(output_.trim() ? { preview: lines(output_) } : {}),
81
+ ...(status ? backgroundNote(status, output?.exitCode) : {}),
56
82
  ...error,
57
83
  }
58
84
  }
@@ -69,6 +95,22 @@ export function toolLine(
69
95
  }
70
96
  case "view_file":
71
97
  return { verb: "view", detail: text(input?.path), ...error }
98
+ case "web_search": {
99
+ const results = Array.isArray(output?.results) ? output.results.length : undefined
100
+ return {
101
+ verb: "search",
102
+ detail: firstLine(text(input?.query)),
103
+ ...(results !== undefined ? { note: plural(results, "result") } : {}),
104
+ ...error,
105
+ }
106
+ }
107
+ case "web_fetch":
108
+ return {
109
+ verb: "fetch",
110
+ detail: webAddress(text(input?.url)),
111
+ ...fetchNote(output),
112
+ ...(failed ? fetchFailure(part.error) : {}),
113
+ }
72
114
  case "publish_artifact":
73
115
  case "publish_artifact_version":
74
116
  return {
@@ -115,6 +157,24 @@ export function toolLine(
115
157
  }
116
158
  }
117
159
 
160
+ /** How long a command had, as the bash tool gives it: 2 minutes unless it asked, 10 at most. */
161
+ function commandTimeoutText(timeoutMs: unknown): string {
162
+ const ms =
163
+ typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
164
+ ? Math.min(Math.floor(timeoutMs), 10 * 60_000)
165
+ : 2 * 60_000
166
+ if (ms % 60_000 === 0) return `${ms / 60_000} min`
167
+ return ms % 1000 === 0 ? `${ms / 1000} s` : `${ms} ms`
168
+ }
169
+
170
+ /**
171
+ * A timed-out command's stderr without the line the bash tool adds for the model (how long it
172
+ * had, how to ask for more): the note beside the line says it for people.
173
+ */
174
+ function withoutAgentNotice(stderr: string): string {
175
+ return stderr.replace(/(^|\n)\[SixbAgent\] [^\n]*$/, "")
176
+ }
177
+
118
178
  /**
119
179
  * The approvals a `bash` output says it waits for. `sixb` prints the API's answer to a call it held
120
180
  * as one JSON line naming the approval, but the output is the model's to shape: as in the web
@@ -133,6 +193,66 @@ function heldApprovalIds(stdout: string): string[] {
133
193
  })
134
194
  }
135
195
 
196
+ /** An address as host and path: the scheme, query and fragment say nothing on one line. */
197
+ function webAddress(value: string): string {
198
+ try {
199
+ const url = new URL(value)
200
+ return url.pathname === "/" ? url.host : `${url.host}${url.pathname}`
201
+ } catch {
202
+ return firstLine(value)
203
+ }
204
+ }
205
+
206
+ function webHost(value: string): string {
207
+ try {
208
+ return new URL(value).host
209
+ } catch {
210
+ return firstLine(value)
211
+ }
212
+ }
213
+
214
+ /** What came of a page read: the site it pointed to instead, an answer, or the file it filled. */
215
+ function fetchNote(output: Record<string, unknown> | undefined): Pick<ToolLine, "note"> {
216
+ const redirect = record(output?.redirect)
217
+ if (redirect) return { note: `→ ${webHost(text(redirect.url))}` }
218
+ if (typeof output?.answer === "string") return { note: "answered" }
219
+ if (typeof output?.path === "string" && typeof output.bytes === "number") {
220
+ return { note: `saved ${byteSize(output.bytes)}` }
221
+ }
222
+ return {}
223
+ }
224
+
225
+ /**
226
+ * A failed read as a short reason beside the address, which a full error would squeeze off the
227
+ * line, and the error itself under it, as a failed command's output.
228
+ */
229
+ function fetchFailure(error: string | undefined): Pick<ToolLine, "note" | "failed" | "preview"> {
230
+ const detail = firstLine(error ?? "").replace(/^\[\w+\]\s*/, "")
231
+ const note = /^Blocked:/.test(detail)
232
+ ? "blocked"
233
+ : /\bECONNREFUSED\b/.test(detail)
234
+ ? "refused"
235
+ : /^Timed out\b/.test(detail)
236
+ ? "timed out"
237
+ : "failed"
238
+
239
+ return { note, failed: true, ...(detail ? { preview: [detail] } : {}) }
240
+ }
241
+
242
+ function byteSize(bytes: number): string {
243
+ if (bytes < 1024) return `${bytes} B`
244
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`
245
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
246
+ }
247
+
248
+ /** How a background command stands, beside its line. */
249
+ function backgroundNote(status: string, exitCode: unknown): Pick<ToolLine, "note" | "failed"> {
250
+ if (status === "running") return { note: "running" }
251
+ if (status === "stopped") return { note: "stopped" }
252
+ if (typeof exitCode !== "number") return { note: "exited" }
253
+ return exitCode === 0 ? { note: "exit 0" } : { note: `exit ${exitCode}`, failed: true }
254
+ }
255
+
136
256
  /** How decided calls ended, as the web chat's approval card names it. */
137
257
  function decidedLine(outcomes: readonly ApprovalOutcome[]): Pick<ToolLine, "note" | "failed"> {
138
258
  const ended = outcomes.map(outcomeNote)
@@ -186,8 +306,11 @@ function partialInput(inputText: string | undefined): Record<string, unknown> |
186
306
  try {
187
307
  return record(JSON.parse(inputText))
188
308
  } catch {
189
- const command = /"(?:command|path|task|key)"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(inputText)
190
- return command ? { command: command[1], path: command[1], task: command[1] } : undefined
309
+ const command = /"(?:command|path|task|key|query|url)"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(inputText)
310
+ const value = command?.[1]
311
+ return value !== undefined
312
+ ? { command: value, path: value, task: value, query: value, url: value }
313
+ : undefined
191
314
  }
192
315
  }
193
316
 
@@ -443,6 +566,80 @@ export function duration(ms: number): string {
443
566
  return `${Math.floor(total / 60)}m ${String(total % 60).padStart(2, "0")}s`
444
567
  }
445
568
 
569
+ /** A clock that ticks by the second: `8s`, `2m 14s`, `1h 03m`. */
570
+ export function elapsed(ms: number): string {
571
+ const seconds = Math.max(0, Math.floor(ms / 1_000))
572
+ const hours = Math.floor(seconds / 3_600)
573
+ const minutes = Math.floor((seconds % 3_600) / 60)
574
+ if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`
575
+ if (minutes > 0) return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`
576
+ return `${seconds}s`
577
+ }
578
+
579
+ /** A background command as `sixb` reports it. */
580
+ export interface BackgroundCommand {
581
+ readonly id: string
582
+ readonly command: string
583
+ readonly status: "running" | "exited" | "stopped"
584
+ readonly exitCode?: number
585
+ readonly startedAt: string
586
+ readonly endedAt?: string
587
+ }
588
+
589
+ /** A command's first line, cut to `max` characters. */
590
+ export function commandLabel(command: string, max = 40): string {
591
+ const line = firstLine(command)
592
+ const cut = line.length > max ? `${line.slice(0, max - 1)}…` : line
593
+ return cut + (command.trim().includes("\n") && cut === line ? " …" : "")
594
+ }
595
+
596
+ /**
597
+ * The running background commands as the line over the composer lists them, `● bun run dev 2m
598
+ * 14s`, as many as fit in `room` columns, oldest first; `more` counts the rest.
599
+ */
600
+ export function backgroundStrip(
601
+ commands: readonly BackgroundCommand[],
602
+ now: number,
603
+ room: number
604
+ ): {
605
+ readonly shown: readonly { readonly label: string; readonly time: string }[]
606
+ readonly more: number
607
+ } {
608
+ const running = commands
609
+ .filter((command) => command.status === "running")
610
+ .sort((a, b) => a.startedAt.localeCompare(b.startedAt))
611
+ const shown: { label: string; time: string }[] = []
612
+ let used = 0
613
+ for (const [index, command] of running.entries()) {
614
+ const entry = {
615
+ label: commandLabel(command.command, 32),
616
+ time: elapsed(now - Date.parse(command.startedAt)),
617
+ }
618
+ // `● label time`, then three spaces; the rest is said as `+2 more`.
619
+ const width = entry.label.length + entry.time.length + 3 + (shown.length > 0 ? 3 : 0)
620
+ const rest = running.length - index - 1
621
+ const suffix = rest > 0 ? ` +${rest} more`.length : 0
622
+ if (shown.length > 0 && used + width + suffix > room) break
623
+ shown.push(entry)
624
+ used += width
625
+ }
626
+ return { shown, more: running.length - shown.length }
627
+ }
628
+
629
+ /** What the screen says as a background command ends: its notice, and whether it failed. */
630
+ export function backgroundEnded(command: BackgroundCommand): {
631
+ readonly text: string
632
+ readonly failed: boolean
633
+ } {
634
+ const label = commandLabel(command.command, 48)
635
+ const ran = command.endedAt
636
+ ? ` after ${elapsed(Date.parse(command.endedAt) - Date.parse(command.startedAt))}`
637
+ : ""
638
+ if (command.status === "stopped") return { text: `${label} stopped${ran}`, failed: false }
639
+ const code = command.exitCode ?? 0
640
+ return { text: `${label} exited with code ${code}${ran}`, failed: code !== 0 }
641
+ }
642
+
446
643
  /** A path with the home directory as `~`, and its middle elided past `max` characters. */
447
644
  export function shortPath(path: string, home: string, max = 48): string {
448
645
  const homed = path.startsWith(home) ? `~${path.slice(home.length)}` : path
package/src/tui/index.tsx CHANGED
@@ -7,23 +7,23 @@ import { format } from "node:util"
7
7
  import { createCliRenderer, type KeyEvent, RGBA, SyntaxStyle } from "@opentui/core"
8
8
  import { createRoot, useKeyboard } from "@opentui/react"
9
9
  import { useCallback, useEffect, useState } from "react"
10
- import { glyph } from "../ui/theme"
11
- import { Workspace } from "./app"
12
- import { Logo } from "./brand"
13
- import { thisComputerId } from "./computer"
14
10
  import {
15
11
  type Connection,
16
12
  connect,
17
13
  type PendingSignIn,
18
14
  type SignedOut,
19
15
  startSignIn,
20
- } from "./connection"
21
- import { LocalRunner, stopOnHangUp } from "./runner"
16
+ } from "../lib/connection"
17
+ import { thisComputerId } from "../runner/computer"
18
+ import { LocalRunner, stopOnHangUp, stopOnQuit } from "../runner/local-runner"
19
+ import { glyph } from "../ui/theme"
20
+ import { Workspace } from "./app"
21
+ import { Logo } from "./brand"
22
22
  import { loadSettings, type Settings } from "./settings"
23
23
  import { type TuiColors, tuiColors } from "./theme"
24
24
  import { BOLD, Composer, useSpinner } from "./ui"
25
25
 
26
- /** How long quitting waits for a turn running here to record its end. */
26
+ /** How long quitting waits for a turn running here to record its end, and its commands to stop. */
27
27
  const STOP_WAIT_MS = 10_000
28
28
  /** How long quitting waits to tell the project this sixb closed: it lapses on its own anyway. */
29
29
  const SESSION_CLOSE_WAIT_MS = 2_000
@@ -74,7 +74,7 @@ export async function runTui(options: {
74
74
  const root = createRoot(renderer)
75
75
  // As the project keeps it, and the local sandbox compares it: its real path.
76
76
  const folder = await realpath(process.cwd())
77
- const settings = await loadSettings(folder)
77
+ const settings = await loadSettings()
78
78
  let runner: LocalRunner | null = null
79
79
  // The renderer gives its screen back on these signals; sixb then ends its turns and exits.
80
80
  const unhook = stopOnHangUp(
@@ -94,6 +94,7 @@ export async function runTui(options: {
94
94
  connectWith={(apiUrl) => connect(apiUrl ? { ...options, apiUrl } : options)}
95
95
  runnerFor={(connection) => {
96
96
  runner ??= new LocalRunner(connection, folder, (error) => console.error(error))
97
+ runner.keepsAwake = settings.keepAwake
97
98
  return runner
98
99
  }}
99
100
  onExit={resolve}
@@ -109,13 +110,13 @@ export async function runTui(options: {
109
110
  await renderer.closed
110
111
  syntax.destroy()
111
112
  restoreConsole()
112
- // A turn running here ends interrupted, its end recorded, once the terminal is back; an API
113
- // that stops answering gets a bounded wait, and ctrl+c ends it.
113
+ // A turn running here ends interrupted, its end recorded, once the terminal is back, and the
114
+ // background commands its turns left stop; an API that stops answering gets a bounded wait,
115
+ // and ctrl+c ends it.
114
116
  const running = runner as LocalRunner | null
115
- if (running?.busy) {
116
- process.stderr.write(" Stopping the turn running here…\n")
117
+ if (running) {
117
118
  process.once("SIGINT", () => process.exit(130))
118
- await Promise.race([running.stop(), Bun.sleep(STOP_WAIT_MS)])
119
+ await stopOnQuit(running, STOP_WAIT_MS, (text) => process.stderr.write(` ${text}\n`))
119
120
  }
120
121
  // Its conversations read as offline at once, rather than once the session lapses.
121
122
  await Promise.race([running?.closeSession(), Bun.sleep(SESSION_CLOSE_WAIT_MS)])