@sixb/cli 0.1.26 → 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 (76) hide show
  1. package/dist/commands/agent.d.ts.map +1 -1
  2. package/dist/commands/api.d.ts.map +1 -1
  3. package/dist/commands/check.d.ts.map +1 -1
  4. package/dist/commands/deploy.d.ts.map +1 -1
  5. package/dist/commands/dev-runner.d.ts.map +1 -1
  6. package/dist/commands/dev.d.ts.map +1 -1
  7. package/dist/commands/env.d.ts +31 -0
  8. package/dist/commands/env.d.ts.map +1 -0
  9. package/dist/lib/command-line.d.ts +26 -1
  10. package/dist/lib/command-line.d.ts.map +1 -1
  11. package/dist/lib/deploy-release.d.ts +2 -0
  12. package/dist/lib/deploy-release.d.ts.map +1 -1
  13. package/dist/lib/deploy-source.d.ts +2 -0
  14. package/dist/lib/deploy-source.d.ts.map +1 -1
  15. package/dist/lib/env-config.d.ts +17 -0
  16. package/dist/lib/env-config.d.ts.map +1 -0
  17. package/dist/lib/env-file.d.ts +16 -0
  18. package/dist/lib/env-file.d.ts.map +1 -0
  19. package/dist/lib/hidden-prompt.d.ts +19 -0
  20. package/dist/lib/hidden-prompt.d.ts.map +1 -0
  21. package/dist/tui/app.d.ts +8 -0
  22. package/dist/tui/app.d.ts.map +1 -1
  23. package/dist/tui/computer.d.ts +5 -0
  24. package/dist/tui/computer.d.ts.map +1 -1
  25. package/dist/tui/context.d.ts +13 -0
  26. package/dist/tui/context.d.ts.map +1 -0
  27. package/dist/tui/format.d.ts +85 -0
  28. package/dist/tui/format.d.ts.map +1 -1
  29. package/dist/tui/index.d.ts.map +1 -1
  30. package/dist/tui/markdown.d.ts +18 -0
  31. package/dist/tui/markdown.d.ts.map +1 -0
  32. package/dist/tui/parts.d.ts +8 -0
  33. package/dist/tui/parts.d.ts.map +1 -1
  34. package/dist/tui/runner.d.ts +37 -14
  35. package/dist/tui/runner.d.ts.map +1 -1
  36. package/dist/tui/settings.d.ts +13 -1
  37. package/dist/tui/settings.d.ts.map +1 -1
  38. package/dist/tui/transcript.d.ts +1 -1
  39. package/dist/tui/transcript.d.ts.map +1 -1
  40. package/dist/tui/ui.d.ts +7 -0
  41. package/dist/tui/ui.d.ts.map +1 -1
  42. package/dist/ui/deploy-screens.d.ts +3 -1
  43. package/dist/ui/deploy-screens.d.ts.map +1 -1
  44. package/dist/ui/env-screens.d.ts +37 -0
  45. package/dist/ui/env-screens.d.ts.map +1 -0
  46. package/package.json +19 -19
  47. package/src/commands/agent.ts +17 -10
  48. package/src/commands/api.ts +2 -1
  49. package/src/commands/check.ts +5 -1
  50. package/src/commands/deploy.ts +29 -3
  51. package/src/commands/dev-runner.ts +3 -1
  52. package/src/commands/dev.ts +3 -0
  53. package/src/commands/env.ts +422 -0
  54. package/src/index.tsx +39 -1
  55. package/src/lib/command-line.ts +59 -1
  56. package/src/lib/deploy-release.ts +3 -0
  57. package/src/lib/deploy-source.ts +10 -0
  58. package/src/lib/env-config.ts +96 -0
  59. package/src/lib/env-file.ts +104 -0
  60. package/src/lib/hidden-prompt.ts +97 -0
  61. package/src/tui/app.tsx +315 -179
  62. package/src/tui/computer.ts +37 -0
  63. package/src/tui/context.tsx +149 -0
  64. package/src/tui/format.ts +218 -1
  65. package/src/tui/index.tsx +13 -2
  66. package/src/tui/markdown.ts +91 -0
  67. package/src/tui/parts.ts +23 -3
  68. package/src/tui/runner.ts +113 -30
  69. package/src/tui/settings.ts +54 -5
  70. package/src/tui/transcript.tsx +90 -8
  71. package/src/tui/ui.tsx +40 -11
  72. package/src/ui/deploy-screens.ts +12 -1
  73. package/src/ui/env-screens.ts +81 -0
  74. package/dist/tui/folders.d.ts +0 -7
  75. package/dist/tui/folders.d.ts.map +0 -1
  76. package/src/tui/folders.ts +0 -41
@@ -1,6 +1,8 @@
1
1
  import { randomUUID } from "node:crypto"
2
2
  import { mkdir, readFile, writeFile } from "node:fs/promises"
3
+ import { hostname, type as osType } from "node:os"
3
4
  import { dirname, join } from "node:path"
5
+ import { CONTROL_CHARACTER } from "@sixb/core/internal/agent-run-storage-provider"
4
6
  import { resolveConfigPath } from "../lib/profiles"
5
7
 
6
8
  // This computer's id, which every claim of a turn names: a conversation that runs on its owner's
@@ -24,6 +26,41 @@ export function thisComputerId(): Promise<string> {
24
26
  return id
25
27
  }
26
28
 
29
+ /** This computer: its id, and what its owner calls it, as the web shows where a thread runs. */
30
+ export async function thisComputer(): Promise<{ readonly id: string; readonly name: string }> {
31
+ const [id, name] = await Promise.all([thisComputerId(), thisComputerName()])
32
+ return { id, name }
33
+ }
34
+
35
+ let computerName: Promise<string> | undefined
36
+
37
+ /** The name its owner gave the computer: its Mac name, else its host name. */
38
+ function thisComputerName(): Promise<string> {
39
+ computerName ??= readComputerName().then((name) =>
40
+ // Shown back as written: no control characters, and short.
41
+ (name.replace(new RegExp(CONTROL_CHARACTER, "g"), "").trim() || "This computer").slice(0, 120)
42
+ )
43
+ return computerName
44
+ }
45
+
46
+ async function readComputerName(): Promise<string> {
47
+ if (osType() === "Darwin") {
48
+ try {
49
+ const scutil = Bun.spawn(["scutil", "--get", "ComputerName"], {
50
+ stdout: "pipe",
51
+ stderr: "ignore",
52
+ })
53
+ const timer = setTimeout(() => scutil.kill(), 2_000)
54
+ const name = await new Response(scutil.stdout).text()
55
+ clearTimeout(timer)
56
+ if ((await scutil.exited) === 0 && name.trim()) return name
57
+ } catch {
58
+ // Not every Mac answers: its host name stands in.
59
+ }
60
+ }
61
+ return hostname().replace(/\.local$/, "")
62
+ }
63
+
27
64
  async function readOrName(path: string): Promise<string> {
28
65
  const stored = await read(path)
29
66
  if (stored) return stored
@@ -0,0 +1,149 @@
1
+ /** @jsxImportSource @opentui/react */
2
+ import { type KeyEvent, RGBA } from "@opentui/core"
3
+ import { useKeyboard, useTerminalDimensions } from "@opentui/react"
4
+ import { glyph } from "../ui/theme"
5
+ import { type ContextUse, contextBreakdown } from "./format"
6
+ import type { TuiColors } from "./theme"
7
+ import { BOLD } from "./ui"
8
+
9
+ /** What the room kept for the model's answer reads as, in the bar and its row. */
10
+ const RESERVED_TILE = "╌"
11
+
12
+ /**
13
+ * `/context`: what the conversation uses of its model's window, part by part. Opens centered over
14
+ * the screen like the palettes; esc or enter closes it.
15
+ */
16
+ export function ContextPanel({
17
+ colors,
18
+ context,
19
+ modelName,
20
+ onClose,
21
+ }: {
22
+ readonly colors: TuiColors
23
+ readonly context: ContextUse | null
24
+ readonly modelName?: string
25
+ readonly onClose: () => void
26
+ }) {
27
+ const { width, height } = useTerminalDimensions()
28
+ useKeyboard((key: KeyEvent) => {
29
+ if (key.name === "escape" || key.name === "return" || (key.ctrl && key.name === "c")) {
30
+ onClose()
31
+ }
32
+ })
33
+
34
+ const boxWidth = Math.min(64, width - 4)
35
+ const inner = boxWidth - 6
36
+ // A row: its label, its tokens and share in 12 columns, then its share's tiles.
37
+ const labelColumns = Math.min(24, Math.max(12, inner - 12 - 12))
38
+ const rowTiles = Math.max(0, inner - labelColumns - 12)
39
+ const breakdown = context ? contextBreakdown(context, { bar: inner, row: rowTiles }) : undefined
40
+ const toneColor =
41
+ breakdown?.tone === "over"
42
+ ? colors.red
43
+ : breakdown?.tone === "near"
44
+ ? colors.amber
45
+ : colors.blue
46
+
47
+ const lines = breakdown ? breakdown.rows.length + breakdown.notes.length + 7 : 2
48
+ return (
49
+ <>
50
+ <box
51
+ position="absolute"
52
+ left={0}
53
+ top={0}
54
+ width={width}
55
+ height={height}
56
+ backgroundColor={RGBA.fromValues(0, 0, 0, 0.45)}
57
+ zIndex={9}
58
+ />
59
+ <box
60
+ position="absolute"
61
+ left={Math.floor((width - boxWidth) / 2)}
62
+ top={Math.max(1, Math.floor((height - lines - 4) / 3))}
63
+ width={boxWidth}
64
+ backgroundColor={colors.surface}
65
+ flexDirection="column"
66
+ paddingTop={1}
67
+ paddingBottom={1}
68
+ paddingLeft={3}
69
+ paddingRight={3}
70
+ zIndex={10}
71
+ >
72
+ <box flexDirection="row" justifyContent="space-between">
73
+ <text fg={colors.text} attributes={BOLD}>
74
+ Context
75
+ </text>
76
+ <text fg={colors.faint}>esc</text>
77
+ </box>
78
+ {breakdown ? (
79
+ <>
80
+ <box flexDirection="row" justifyContent="space-between" paddingTop={1}>
81
+ <text wrapMode="none" flexShrink={1}>
82
+ <span fg={colors.text}>{breakdown.headline}</span>
83
+ {modelName ? <span fg={colors.faint}>{` · ${modelName}`}</span> : null}
84
+ </text>
85
+ <text fg={breakdown.tone === "quiet" ? colors.muted : toneColor} flexShrink={0}>
86
+ {breakdown.share}
87
+ </text>
88
+ </box>
89
+ <text wrapMode="none">
90
+ <span fg={toneColor}>{glyph.mark.repeat(breakdown.bar.used)}</span>
91
+ <span fg={colors.faint}>{glyph.tile.repeat(breakdown.bar.free)}</span>
92
+ <span fg={colors.faint}>{RESERVED_TILE.repeat(breakdown.bar.reserved)}</span>
93
+ </text>
94
+ {breakdown.warning ? (
95
+ <text wrapMode="none" fg={toneColor}>
96
+ {fit(breakdown.warning, inner)}
97
+ </text>
98
+ ) : null}
99
+ <box flexDirection="column" paddingTop={1}>
100
+ {breakdown.rows.map((row) => (
101
+ <box key={row.label} flexDirection="row">
102
+ <text
103
+ wrapMode="none"
104
+ width={labelColumns}
105
+ fg={row.kind === "part" ? colors.text : colors.muted}
106
+ >
107
+ {fit(row.label, labelColumns - 1)}
108
+ </text>
109
+ <text wrapMode="none" width={12} fg={colors.muted}>
110
+ {`${row.tokens.padStart(5)} ${(row.share ?? "").padStart(4)} `}
111
+ </text>
112
+ <text wrapMode="none" fg={colors.faint}>
113
+ {row.kind === "free"
114
+ ? glyph.tile
115
+ : row.kind === "reserved"
116
+ ? RESERVED_TILE
117
+ : ""}
118
+ <span fg={colors.muted}>
119
+ {glyph.mark.repeat(Math.min(row.tiles, rowTiles))}
120
+ </span>
121
+ </text>
122
+ </box>
123
+ ))}
124
+ </box>
125
+ {breakdown.notes.length > 0 ? (
126
+ <box flexDirection="column" paddingTop={1}>
127
+ {breakdown.notes.map((note) => (
128
+ <text key={note} wrapMode="none" fg={colors.muted}>
129
+ {fit(note, inner)}
130
+ </text>
131
+ ))}
132
+ </box>
133
+ ) : null}
134
+ </>
135
+ ) : (
136
+ <text fg={colors.muted} paddingTop={1}>
137
+ Nothing yet: the context is measured after the first answer.
138
+ </text>
139
+ )}
140
+ </box>
141
+ </>
142
+ )
143
+ }
144
+
145
+ /** Text cut to `room` columns, with an ellipsis. */
146
+ function fit(text: string, room: number): string {
147
+ if (text.length <= room) return text
148
+ return room <= 1 ? "" : `${text.slice(0, room - 1)}…`
149
+ }
package/src/tui/format.ts CHANGED
@@ -218,6 +218,223 @@ function compact(value: unknown): string {
218
218
  return json && json.length > 160 ? `${json.slice(0, 157)}…` : (json ?? "")
219
219
  }
220
220
 
221
+ /** Why a run failed, in a line; a conversation too long for its model says how to go on. */
222
+ export function runFailureText(error: { readonly code: string; readonly message: string }): string {
223
+ if (error.code === "agent.context_limit_exceeded") {
224
+ return "This conversation is too long for the model: /new starts another, /model picks a larger one."
225
+ }
226
+ return error.message
227
+ }
228
+
229
+ /** A part of what a conversation uses, as the API names it. */
230
+ export type ContextPartName =
231
+ | "system"
232
+ | "instructions"
233
+ | "memory"
234
+ | "skills"
235
+ | "ontology"
236
+ | "tools"
237
+ | "summary"
238
+ | "messages"
239
+ | "toolResults"
240
+ | "files"
241
+
242
+ /** What the status line and `/context` need of a conversation's context against its limits. */
243
+ export interface ContextUse {
244
+ /** The model the limits are this one's. */
245
+ readonly model?: { readonly provider: string; readonly modelId: string }
246
+ readonly windowTokens?: number
247
+ readonly limitTokens: number
248
+ readonly usedTokens?: number
249
+ readonly parts?: readonly { readonly part: ContextPartName; readonly tokens: number }[]
250
+ readonly lastCall?: { readonly inputTokens: number; readonly cacheReadInputTokens?: number }
251
+ readonly lastCompaction?: {
252
+ readonly createdAt: string
253
+ readonly estimatedInputTokensBefore: number
254
+ readonly estimatedInputTokensAfter: number
255
+ }
256
+ }
257
+
258
+ /** How full the context is: amber from 80% of the model's limit, red past it. */
259
+ export type ContextTone = "quiet" | "near" | "over"
260
+
261
+ function contextTone(used: number, limit: number): ContextTone {
262
+ const share = used / limit
263
+ return share > 1 ? "over" : share >= 0.8 ? "near" : "quiet"
264
+ }
265
+
266
+ /**
267
+ * The context as the status line shows it, `ctx 38k/100k · 92% cached`, then shorter where room is
268
+ * short: `ctx 38k/100k`, then `ctx 21%`. Undefined before the first answer.
269
+ */
270
+ export function contextStatus(context: ContextUse):
271
+ | {
272
+ readonly text: string
273
+ readonly short: string
274
+ readonly shortest: string
275
+ readonly tone: ContextTone
276
+ }
277
+ | undefined {
278
+ const used = context.usedTokens
279
+ if (used === undefined) return undefined
280
+
281
+ const call = context.lastCall
282
+ const cached =
283
+ call?.cacheReadInputTokens !== undefined && call.inputTokens > 0
284
+ ? ` · ${Math.round((call.cacheReadInputTokens / call.inputTokens) * 100)}% cached`
285
+ : ""
286
+ const short = `ctx ${tokenCount(used)}/${tokenCount(context.limitTokens)}`
287
+
288
+ return {
289
+ text: `${short}${cached}`,
290
+ short,
291
+ shortest: `ctx ${Math.round((used / context.limitTokens) * 100)}%`,
292
+ tone: contextTone(used, context.limitTokens),
293
+ }
294
+ }
295
+
296
+ /**
297
+ * What of the context fits at the end of a status line whose items take `columns` of `room`: it
298
+ * whole, without the cache share, its share alone, or nothing, so the line never wraps.
299
+ */
300
+ export function fittedContextText(
301
+ context: { readonly text: string; readonly short: string; readonly shortest: string },
302
+ columns: number,
303
+ room: number
304
+ ): string | undefined {
305
+ const separator = columns > 0 ? 3 : 0
306
+ return [context.text, context.short, context.shortest].find(
307
+ (text) => columns + separator + text.length <= room
308
+ )
309
+ }
310
+
311
+ const CONTEXT_PART_LABELS: Readonly<Record<ContextPartName, string>> = {
312
+ system: "Sixb instructions",
313
+ instructions: "Project instructions",
314
+ memory: "Memory",
315
+ skills: "Skills",
316
+ ontology: "Ontology",
317
+ tools: "Tools",
318
+ summary: "Earlier summary",
319
+ messages: "Messages",
320
+ toolResults: "Tool results",
321
+ files: "Files and images",
322
+ }
323
+
324
+ /** One row of `/context`: a part, the room left, or the room kept for the answer. */
325
+ export interface ContextRow {
326
+ readonly label: string
327
+ readonly tokens: string
328
+ /** Its share of what the conversation uses; none for the room left or kept. */
329
+ readonly share?: string
330
+ /** A part's tiles: its share of what the conversation uses, out of the row's. */
331
+ readonly tiles: number
332
+ readonly kind: "part" | "free" | "reserved"
333
+ }
334
+
335
+ /**
336
+ * What `/context` shows: the use against the limit, the window as one bar of `columns.bar` tiles
337
+ * (used, free, kept for the answer), then a row per part with its share in up to `columns.row`
338
+ * tiles, the room left and the room kept for the answer, and when it was last condensed.
339
+ * Undefined before the first answer.
340
+ */
341
+ export function contextBreakdown(
342
+ context: ContextUse,
343
+ columns: { readonly bar: number; readonly row: number },
344
+ now = Date.now()
345
+ ):
346
+ | {
347
+ readonly headline: string
348
+ readonly share: string
349
+ readonly tone: ContextTone
350
+ /** What a conversation near or past its limit is about to go through. */
351
+ readonly warning?: string
352
+ readonly bar: { readonly used: number; readonly free: number; readonly reserved: number }
353
+ readonly rows: readonly ContextRow[]
354
+ readonly notes: readonly string[]
355
+ }
356
+ | undefined {
357
+ const used = context.usedTokens
358
+ if (used === undefined) return undefined
359
+
360
+ const window = context.windowTokens ?? context.limitTokens
361
+ const reserved = Math.max(0, window - context.limitTokens)
362
+ const free = Math.max(0, context.limitTokens - used)
363
+ const span = Math.max(window, used + reserved)
364
+ const scaled = (tokens: number, room: number) =>
365
+ tokens <= 0 ? 0 : Math.max(1, Math.round((tokens / span) * room))
366
+
367
+ // The bar's three runs fill it exactly: rounding gives its error to the room left.
368
+ const usedTiles = Math.min(columns.bar, scaled(used, columns.bar))
369
+ const reservedTiles = Math.min(columns.bar - usedTiles, scaled(reserved, columns.bar))
370
+ const percent = (share: number) =>
371
+ share > 0 && share < 0.01 ? "<1%" : `${Math.round(share * 100)}%`
372
+
373
+ const parts = (context.parts ?? []).map(
374
+ ({ part, tokens }): ContextRow => ({
375
+ label: CONTEXT_PART_LABELS[part],
376
+ tokens: tokenCount(tokens),
377
+ share: percent(used > 0 ? tokens / used : 0),
378
+ tiles: used > 0 ? Math.max(1, Math.round((tokens / used) * columns.row)) : 0,
379
+ kind: "part",
380
+ })
381
+ )
382
+ const call = context.lastCall
383
+ const compaction = context.lastCompaction
384
+ const tone = contextTone(used, context.limitTokens)
385
+
386
+ return {
387
+ headline: `${tokenCount(used)} of ${tokenCount(context.limitTokens)} tokens`,
388
+ share: percent(used / context.limitTokens),
389
+ tone,
390
+ ...(tone === "near"
391
+ ? { warning: "Almost full: earlier messages are condensed soon." }
392
+ : tone === "over"
393
+ ? { warning: "Full: earlier messages are condensed next turn." }
394
+ : {}),
395
+ bar: {
396
+ used: usedTiles,
397
+ free: columns.bar - usedTiles - reservedTiles,
398
+ reserved: reservedTiles,
399
+ },
400
+ rows: [
401
+ ...parts,
402
+ { label: "Free space", tokens: tokenCount(free), tiles: 0, kind: "free" },
403
+ { label: "Kept for the answer", tokens: tokenCount(reserved), tiles: 0, kind: "reserved" },
404
+ ],
405
+ notes: [
406
+ ...(compaction
407
+ ? [
408
+ `Condensed ${ago(Date.parse(compaction.createdAt), now)} · ${tokenCount(compaction.estimatedInputTokensBefore)} → ${tokenCount(compaction.estimatedInputTokensAfter)}`,
409
+ ]
410
+ : []),
411
+ ...(call?.cacheReadInputTokens !== undefined && call.inputTokens > 0
412
+ ? [
413
+ `${percent(call.cacheReadInputTokens / call.inputTokens)} of the last call read from cache`,
414
+ ]
415
+ : []),
416
+ ],
417
+ }
418
+ }
419
+
420
+ /** `just now`, `12m ago`, `3h ago`, `2d ago`. */
421
+ function ago(then: number, now: number): string {
422
+ const minutes = Math.round((now - then) / 60_000)
423
+ if (!Number.isFinite(minutes) || minutes < 1) return "just now"
424
+ if (minutes < 60) return `${minutes}m ago`
425
+ const hours = Math.round(minutes / 60)
426
+ if (hours < 24) return `${hours}h ago`
427
+ return `${Math.round(hours / 24)}d ago`
428
+ }
429
+
430
+ /** `950`, `9.5k`, `38k`, `984k`, `1.2M`. */
431
+ function tokenCount(tokens: number): string {
432
+ if (tokens < 1_000) return String(Math.round(tokens))
433
+ if (tokens < 10_000) return `${Math.round(tokens / 100) / 10}k`
434
+ if (tokens < 999_500) return `${Math.round(tokens / 1_000)}k`
435
+ return `${Math.round(tokens / 100_000) / 10}M`
436
+ }
437
+
221
438
  /** `1m 04s`, `12.4s`, `820ms`. */
222
439
  export function duration(ms: number): string {
223
440
  if (ms < 1_000) return `${Math.round(ms)}ms`
@@ -249,7 +466,7 @@ export function plural(count: number, noun: string): string {
249
466
  */
250
467
  export function friendlyPath(text: string, folder?: string): string {
251
468
  let shown = text.replace(
252
- /\/(?:private\/)?(?:var|tmp)\/[^\s"']*?\/sixb-agent\/[^/\s"']+\//g,
469
+ /\/(?:private\/)?(?:var|tmp)\/[^\s"']*?\/sixb-agent\/[^/\s"']+\/(?:\.sixb\/agent\/)?/g,
253
470
  "run/"
254
471
  )
255
472
  if (folder) {
package/src/tui/index.tsx CHANGED
@@ -1,11 +1,13 @@
1
1
  /** @jsxImportSource @opentui/react */
2
2
  import { appendFileSync } from "node:fs"
3
+ import { realpath } from "node:fs/promises"
3
4
  import { tmpdir } from "node:os"
4
5
  import { join } from "node:path"
5
6
  import { format } from "node:util"
6
7
  import { createCliRenderer, type KeyEvent, RGBA, SyntaxStyle } from "@opentui/core"
7
8
  import { createRoot, useKeyboard } from "@opentui/react"
8
9
  import { useCallback, useEffect, useState } from "react"
10
+ import { glyph } from "../ui/theme"
9
11
  import { Workspace } from "./app"
10
12
  import { Logo } from "./brand"
11
13
  import { thisComputerId } from "./computer"
@@ -23,6 +25,8 @@ import { BOLD, Composer, useSpinner } from "./ui"
23
25
 
24
26
  /** How long quitting waits for a turn running here to record its end. */
25
27
  const STOP_WAIT_MS = 10_000
28
+ /** How long quitting waits to tell the project this sixb closed: it lapses on its own anyway. */
29
+ const SESSION_CLOSE_WAIT_MS = 2_000
26
30
 
27
31
  /** Where the app writes what would otherwise draw over it: its runner's notes and errors. */
28
32
  export const TUI_LOG = join(tmpdir(), "sixb-tui.log")
@@ -45,6 +49,8 @@ export async function runTui(options: {
45
49
  useMouse: true,
46
50
  targetFps: 60,
47
51
  })
52
+ // The tab's name while sixb has it. A terminal draws its tab's icon itself: the mark stands in.
53
+ renderer.setTerminalTitle(`${glyph.mark} Sixb`)
48
54
  // The terminal says whether it is light or dark; SIXB_THEME decides where it can't.
49
55
  const forced = process.env.SIXB_THEME
50
56
  const mode =
@@ -66,8 +72,9 @@ export async function runTui(options: {
66
72
  renderer.setBackgroundColor("transparent")
67
73
  const syntax = createSyntax(colors, renderer)
68
74
  const root = createRoot(renderer)
69
- const settings = await loadSettings()
70
- const folder = process.cwd()
75
+ // As the project keeps it, and the local sandbox compares it: its real path.
76
+ const folder = await realpath(process.cwd())
77
+ const settings = await loadSettings(folder)
71
78
  let runner: LocalRunner | null = null
72
79
  // The renderer gives its screen back on these signals; sixb then ends its turns and exits.
73
80
  const unhook = stopOnHangUp(
@@ -96,6 +103,8 @@ export async function runTui(options: {
96
103
  } finally {
97
104
  unhook()
98
105
  root.unmount()
106
+ // An empty title gives the tab back its own name.
107
+ renderer.setTerminalTitle("")
99
108
  renderer.destroy()
100
109
  await renderer.closed
101
110
  syntax.destroy()
@@ -108,6 +117,8 @@ export async function runTui(options: {
108
117
  process.once("SIGINT", () => process.exit(130))
109
118
  await Promise.race([running.stop(), Bun.sleep(STOP_WAIT_MS)])
110
119
  }
120
+ // Its conversations read as offline at once, rather than once the session lapses.
121
+ await Promise.race([running?.closeSession(), Bun.sleep(SESSION_CLOSE_WAIT_MS)])
111
122
  }
112
123
  }
113
124
 
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The markdown of an answer still being written, as it can be drawn without moving: what is on
3
+ * screen only ever grows. Raw markdown that the next characters would turn into something else is
4
+ * closed early or held back:
5
+ *
6
+ * - an emphasis or code span the last line opened is closed, so `**sum` is drawn bold now rather
7
+ * than as `**sum` that loses its two stars when `**` arrives;
8
+ * - a link waits for its label, then shows as that label until its address is complete: a
9
+ * terminal without clickable links draws the address after it, which would grow mid-line;
10
+ * - a last line holding only a block's marker (`##`, `-`, `2`, `>`) waits for its text;
11
+ * - a table waits until it is complete: its columns are sized to its widest cell, so every row
12
+ * could resize the ones above it;
13
+ * - so does a quote, whose text OpenTUI draws raw until it is highlighted.
14
+ *
15
+ * Inside an open code fence everything is code, drawn as it arrives.
16
+ */
17
+ export function steadyMarkdown(text: string): string {
18
+ // A line that just ended may still be followed by more of its block, a table's next row.
19
+ const lines = text.trimStart().replace(/\n$/, "").split("\n")
20
+ const last = lines.at(-1) ?? ""
21
+ const fences = lines.filter((line) => /^\s*(?:```|~~~)/.test(line)).length
22
+ if (fences % 2 === 1) {
23
+ // `` may be the fence that closes it, which is no line of the code.
24
+ if (/^\s*(?:`{1,2}|~{1,2})$/.test(last)) lines.pop()
25
+ return lines.join("\n")
26
+ }
27
+
28
+ if (BLOCK_MARKER_ONLY.test(last)) lines.pop()
29
+ else lines[lines.length - 1] = closeInline(holdLink(last))
30
+
31
+ // The last block, the lines after the last blank one, when it is a table or a quote.
32
+ let start = lines.length
33
+ while (start > 0 && lines[start - 1]?.trim()) start -= 1
34
+ const block = lines.slice(start).map((line) => line.trimStart()[0])
35
+ if (block.every((first) => first === "|") || block.every((first) => first === ">")) {
36
+ lines.splice(start)
37
+ }
38
+ return lines.join("\n").trimEnd()
39
+ }
40
+
41
+ /** A line that is only the start of a block: a heading's, a list item's or a quote's marker. */
42
+ const BLOCK_MARKER_ONLY = /^\s*(?:#{1,6}|[-*+]|\d{1,9}[.)]?|>|`{1,2}|~{1,2}|[-*_=]{2})\s*$/
43
+
44
+ /** `line` without a link whose label is not finished, and with one whose address is not as its label. */
45
+ function holdLink(line: string): string {
46
+ const outsideCode = (at: number) => (line.slice(0, at).split("`").length - 1) % 2 === 0
47
+ const label = /!?\[[^\]]*\]?$/.exec(line)
48
+ if (label && outsideCode(label.index)) return line.slice(0, label.index).trimEnd()
49
+ const address = /!?\[([^\]]*)\]\([^)\s]*$/.exec(line)
50
+ if (address && outsideCode(address.index)) return `${line.slice(0, address.index)}${address[1]}`
51
+ return line
52
+ }
53
+
54
+ /** Emphasis and code markers, longest first: `**` is one marker, not two `*`. */
55
+ const MARKERS = ["`", "**", "~~", "*"] as const
56
+
57
+ /**
58
+ * `line` with each emphasis or code span it leaves open closed, the innermost first; an opener
59
+ * with nothing after it yet is dropped instead.
60
+ */
61
+ function closeInline(line: string): string {
62
+ const open: { readonly marker: string; readonly at: number }[] = []
63
+ // A list item's `* ` is its bullet, not emphasis.
64
+ let at = /^\s*\*\s/.test(line) ? line.indexOf("*") + 1 : 0
65
+ while (at < line.length) {
66
+ if (line[at] === "\\") {
67
+ at += 2
68
+ continue
69
+ }
70
+ const inCode = open.at(-1)?.marker === "`"
71
+ const marker = MARKERS.find((each) => line.startsWith(each, at) && (!inCode || each === "`"))
72
+ if (!marker) {
73
+ at += 1
74
+ continue
75
+ }
76
+ const next = line[at + marker.length]
77
+ if (open.at(-1)?.marker === marker) open.pop()
78
+ // An opener is followed by text, as markdown's is: `a * b` multiplies. One at the end of the
79
+ // line may still be.
80
+ else if (marker === "`" || next === undefined || /\S/.test(next)) open.push({ marker, at })
81
+ at += marker.length
82
+ }
83
+
84
+ let closed = line
85
+ for (const { marker, at: opened } of open.reverse()) {
86
+ closed = closed.slice(opened + marker.length).trim()
87
+ ? `${closed.trimEnd()}${marker}`
88
+ : closed.slice(0, opened).trimEnd()
89
+ }
90
+ return closed
91
+ }
package/src/tui/parts.ts CHANGED
@@ -43,6 +43,8 @@ export interface ShownMessage {
43
43
  readonly parts: readonly Part[]
44
44
  /** How the held calls before it ended: not shown, but the calls' own lines say it. */
45
45
  readonly outcomes: readonly ApprovalOutcome[]
46
+ /** Its run condensed the conversation first; `contextFull` when the provider refused it whole. */
47
+ readonly compaction?: { readonly contextFull: boolean }
46
48
  readonly createdAt: string
47
49
  }
48
50
 
@@ -109,6 +111,9 @@ export function shownMessage(message: StoredMessage): ShownMessage | null {
109
111
  runId: message.runId,
110
112
  parts,
111
113
  outcomes,
114
+ ...(message.compaction
115
+ ? { compaction: { contextFull: message.compaction.reason === "overflow" } }
116
+ : {}),
112
117
  createdAt: message.createdAt,
113
118
  }
114
119
  }
@@ -128,8 +133,12 @@ export interface LiveRun {
128
133
  readonly parts: readonly Part[]
129
134
  readonly keys: readonly string[]
130
135
  readonly step: number
136
+ /** How many parts came before the current step: a step asked again drops the ones after. */
137
+ readonly stepStart: number
131
138
  readonly working: boolean
132
139
  readonly compacting: boolean
140
+ /** The condensing follows a request the provider refused as too long: the turn goes on after. */
141
+ readonly contextFull: boolean
133
142
  /** Set once the run's answer is stored: the transcript then shows it. */
134
143
  readonly finalized: boolean
135
144
  readonly finished?: { readonly status: string; readonly error?: string }
@@ -141,8 +150,10 @@ export function liveRun(runId: string): LiveRun {
141
150
  parts: [],
142
151
  keys: [],
143
152
  step: 0,
153
+ stepStart: 0,
144
154
  working: true,
145
155
  compacting: false,
156
+ contextFull: false,
146
157
  finalized: false,
147
158
  }
148
159
  }
@@ -152,10 +163,10 @@ export function reduceLive(state: LiveRun, event: AgentRunStreamEvent): LiveRun
152
163
  case "agent.run.started":
153
164
  return { ...state, working: true }
154
165
  case "agent.compaction.started":
155
- return { ...state, compacting: true }
166
+ return { ...state, compacting: true, contextFull: event.reason === "overflow" }
156
167
  case "agent.compaction.completed":
157
168
  case "agent.compaction.failed":
158
- return { ...state, compacting: false }
169
+ return { ...state, compacting: false, contextFull: false }
159
170
  case "agent.ui.chunk":
160
171
  return reduceChunk(state, event.chunk)
161
172
  case "agent.message.finalized":
@@ -165,6 +176,7 @@ export function reduceLive(state: LiveRun, event: AgentRunStreamEvent): LiveRun
165
176
  ...state,
166
177
  working: false,
167
178
  compacting: false,
179
+ contextFull: false,
168
180
  finished: {
169
181
  status: event.status,
170
182
  ...(event.error ? { error: event.error.message } : {}),
@@ -178,7 +190,15 @@ export function reduceLive(state: LiveRun, event: AgentRunStreamEvent): LiveRun
178
190
  function reduceChunk(state: LiveRun, chunk: ModelUiChunk): LiveRun {
179
191
  switch (chunk.type) {
180
192
  case "start-step":
181
- return { ...state, step: state.step + 1 }
193
+ // A step asked again drops what its first call streamed.
194
+ if (chunk.retry) {
195
+ return {
196
+ ...state,
197
+ parts: state.parts.slice(0, state.stepStart),
198
+ keys: state.keys.slice(0, state.stepStart),
199
+ }
200
+ }
201
+ return { ...state, step: state.step + 1, stepStart: state.parts.length }
182
202
  case "text-delta": {
183
203
  if (!chunk.delta) return state
184
204
  const key = `text#${state.step}#${chunk.id}`