@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,477 @@
1
+ import type { ApprovalOutcome, Part } from "./parts"
2
+
3
+ type ToolPart = Extract<Part, { readonly kind: "tool" }>
4
+
5
+ /** A tool call as one line: what it did, then what it acted on. */
6
+ export interface ToolLine {
7
+ readonly verb: string
8
+ readonly detail: string
9
+ /** A few lines of what came back, when they say something the line does not. */
10
+ readonly preview?: readonly string[]
11
+ /** A short outcome beside the line: `exit 1`, `3 lines`. */
12
+ readonly note?: string
13
+ readonly failed?: boolean
14
+ /** A call the API held for the person's approval: neither done nor failed. */
15
+ readonly held?: boolean
16
+ /** A shell command, shown whole as the call's panel. */
17
+ readonly command?: string
18
+ }
19
+
20
+ const PREVIEW_LINES = 4
21
+
22
+ const NO_OUTCOMES: ReadonlyMap<string, ApprovalOutcome> = new Map()
23
+
24
+ /** `outcomes` says how the held calls ended, by approval id: a decided call is no longer held. */
25
+ export function toolLine(
26
+ part: ToolPart,
27
+ outcomes: ReadonlyMap<string, ApprovalOutcome> = NO_OUTCOMES
28
+ ): ToolLine {
29
+ const input = record(part.input) ?? partialInput(part.inputText)
30
+ const output = record(part.output)
31
+ const failed = part.state === "error"
32
+ const error = failed ? { note: firstLine(part.error ?? "failed"), failed } : {}
33
+
34
+ switch (part.name) {
35
+ case "bash": {
36
+ const command = text(input?.command)
37
+ const exitCode = typeof output?.exitCode === "number" ? output.exitCode : undefined
38
+ const stdout = text(output?.stdout)
39
+ const stderr = text(output?.stderr)
40
+ const shown = exitCode !== undefined && exitCode !== 0 && stderr ? stderr : stdout || stderr
41
+ const heldIds = heldApprovalIds(stdout)
42
+ const decided = heldIds.flatMap((id) => outcomes.get(id) ?? [])
43
+ const held = heldIds.length > decided.length
44
+ return {
45
+ verb: "bash",
46
+ command: command.trim(),
47
+ detail: firstLine(command) + (command.includes("\n") ? " …" : ""),
48
+ ...(shown && heldIds.length === 0 ? { preview: lines(shown) } : {}),
49
+ ...(held
50
+ ? { note: "held for your approval", held }
51
+ : heldIds.length > 0
52
+ ? decidedLine(decided)
53
+ : exitCode !== undefined && exitCode !== 0
54
+ ? { note: `exit ${exitCode}`, failed: true }
55
+ : {}),
56
+ ...error,
57
+ }
58
+ }
59
+ case "read": {
60
+ const lineCount = typeof output?.endLine === "number" && typeof output.startLine === "number"
61
+ return {
62
+ verb: "read",
63
+ detail: text(input?.path),
64
+ ...(lineCount
65
+ ? { note: `lines ${output?.startLine}–${output?.endLine}${output?.truncated ? "+" : ""}` }
66
+ : {}),
67
+ ...error,
68
+ }
69
+ }
70
+ case "view_file":
71
+ return { verb: "view", detail: text(input?.path), ...error }
72
+ case "publish_artifact":
73
+ case "publish_artifact_version":
74
+ return {
75
+ verb: "publish",
76
+ detail: text(input?.title) || text(input?.path) || text(input?.artifactId),
77
+ ...(output?.artifactId ? { note: `artifact:${text(output.artifactId)}` } : {}),
78
+ ...error,
79
+ }
80
+ case "spawn_agent":
81
+ return {
82
+ verb: "agent",
83
+ detail: [text(input?.key), firstLine(text(input?.task))].filter(Boolean).join(" "),
84
+ ...error,
85
+ }
86
+ case "wait_agent": {
87
+ const runIds = Array.isArray(input?.runIds) ? input.runIds.length : 0
88
+ return {
89
+ verb: "wait",
90
+ detail: runIds === 1 ? "for its agent" : `for ${runIds || "its"} agents`,
91
+ ...error,
92
+ }
93
+ }
94
+ case "message_agent":
95
+ return {
96
+ verb: "message",
97
+ detail: [text(input?.key), firstLine(text(input?.text))].filter(Boolean).join(" "),
98
+ ...error,
99
+ }
100
+ case "ask_parent":
101
+ return {
102
+ verb: "ask",
103
+ detail: firstLine(text(input?.question) || text(input?.text)),
104
+ ...error,
105
+ }
106
+ default:
107
+ return {
108
+ verb: part.name,
109
+ detail: compact(part.input ?? part.inputText),
110
+ ...(part.state === "done" && part.output !== undefined
111
+ ? { preview: lines(compact(part.output)) }
112
+ : {}),
113
+ ...error,
114
+ }
115
+ }
116
+ }
117
+
118
+ /**
119
+ * The approvals a `bash` output says it waits for. `sixb` prints the API's answer to a call it held
120
+ * as one JSON line naming the approval, but the output is the model's to shape: as in the web
121
+ * chat, only a line that names a record counts, wherever it sits.
122
+ */
123
+ function heldApprovalIds(stdout: string): string[] {
124
+ return stdout.split("\n").flatMap((line) => {
125
+ const trimmed = line.trim()
126
+ if (!trimmed.startsWith("{")) return []
127
+
128
+ const parsed = record(parseJson(trimmed))
129
+ if (parsed?.status !== "awaiting_approval") return []
130
+
131
+ const approval = record(parsed.approval)
132
+ return typeof approval?.id === "string" && approval.id ? [approval.id] : []
133
+ })
134
+ }
135
+
136
+ /** How decided calls ended, as the web chat's approval card names it. */
137
+ function decidedLine(outcomes: readonly ApprovalOutcome[]): Pick<ToolLine, "note" | "failed"> {
138
+ const ended = outcomes.map(outcomeNote)
139
+ const failed = ended.some((entry) => entry.failed)
140
+ return {
141
+ note: [...new Set(ended.map((entry) => entry.note))].join(", "),
142
+ ...(failed ? { failed } : {}),
143
+ }
144
+ }
145
+
146
+ function outcomeNote(outcome: ApprovalOutcome): { readonly note: string; readonly failed?: true } {
147
+ switch (outcome.status) {
148
+ case "approved": {
149
+ const ran = outcome.outcome
150
+ if (ran?.kind === "error" && ran.error.code === "agent.approval_authority_lost") {
151
+ return { note: "approved, but it didn't run", failed: true }
152
+ }
153
+ if (ran?.kind === "error" || (ran?.kind === "action-run" && ran.status === "failed")) {
154
+ return { note: "approved, but it failed", failed: true }
155
+ }
156
+ return { note: "approved" }
157
+ }
158
+ case "denied":
159
+ return { note: "denied" }
160
+ case "superseded":
161
+ return { note: "set aside" }
162
+ case "cancelled":
163
+ return { note: "stopped" }
164
+ case "expired":
165
+ return { note: "expired" }
166
+ }
167
+ }
168
+
169
+ function parseJson(value: string): unknown {
170
+ try {
171
+ return JSON.parse(value)
172
+ } catch {
173
+ return undefined
174
+ }
175
+ }
176
+
177
+ function record(value: unknown): Record<string, unknown> | undefined {
178
+ return value && typeof value === "object" && !Array.isArray(value)
179
+ ? (value as Record<string, unknown>)
180
+ : undefined
181
+ }
182
+
183
+ /** The input so far, while the model still writes it, read where it already parses. */
184
+ function partialInput(inputText: string | undefined): Record<string, unknown> | undefined {
185
+ if (!inputText) return undefined
186
+ try {
187
+ return record(JSON.parse(inputText))
188
+ } 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
191
+ }
192
+ }
193
+
194
+ function text(value: unknown): string {
195
+ return typeof value === "string"
196
+ ? value
197
+ : value === undefined || value === null
198
+ ? ""
199
+ : String(value)
200
+ }
201
+
202
+ function firstLine(value: string): string {
203
+ return value.trim().split("\n")[0]?.trim() ?? ""
204
+ }
205
+
206
+ function lines(value: string): string[] {
207
+ const all = value.replace(/\s+$/, "").split("\n")
208
+ return all.length > PREVIEW_LINES
209
+ ? [...all.slice(0, PREVIEW_LINES), `… ${plural(all.length - PREVIEW_LINES, "more line")}`]
210
+ : all
211
+ }
212
+
213
+ /** A value on one line, for a tool with no line of its own. */
214
+ function compact(value: unknown): string {
215
+ if (value === undefined) return ""
216
+ if (typeof value === "string") return firstLine(value)
217
+ const json = JSON.stringify(value)
218
+ return json && json.length > 160 ? `${json.slice(0, 157)}…` : (json ?? "")
219
+ }
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
+
438
+ /** `1m 04s`, `12.4s`, `820ms`. */
439
+ export function duration(ms: number): string {
440
+ if (ms < 1_000) return `${Math.round(ms)}ms`
441
+ if (ms < 59_950) return `${(ms / 1_000).toFixed(1)}s`
442
+ const total = Math.round(ms / 1_000)
443
+ return `${Math.floor(total / 60)}m ${String(total % 60).padStart(2, "0")}s`
444
+ }
445
+
446
+ /** A path with the home directory as `~`, and its middle elided past `max` characters. */
447
+ export function shortPath(path: string, home: string, max = 48): string {
448
+ const homed = path.startsWith(home) ? `~${path.slice(home.length)}` : path
449
+ if (homed.length <= max) return homed
450
+ const parts = homed.split("/")
451
+ const last = parts.at(-1) ?? ""
452
+ const head = parts.slice(0, 2).join("/")
453
+ const elided = `${head}/…/${last}`
454
+ if (elided.length <= max) return elided
455
+ return last.length + 2 <= max ? `…/${last}` : ""
456
+ }
457
+
458
+ /** `1 more line`, `3 more lines`. */
459
+ export function plural(count: number, noun: string): string {
460
+ return `${count} ${noun}${count === 1 ? "" : "s"}`
461
+ }
462
+
463
+ /**
464
+ * A path as the person reads it: relative to the folder the agent works in, and the run's own
465
+ * files, kept outside it, as `run/…`.
466
+ */
467
+ export function friendlyPath(text: string, folder?: string): string {
468
+ let shown = text.replace(
469
+ /\/(?:private\/)?(?:var|tmp)\/[^\s"']*?\/sixb-agent\/[^/\s"']+\/(?:\.sixb\/agent\/)?/g,
470
+ "run/"
471
+ )
472
+ if (folder) {
473
+ const prefixes = [folder, folder.replace(/^\/private/, "")].map((prefix) => `${prefix}/`)
474
+ for (const prefix of prefixes) shown = shown.split(prefix).join("")
475
+ }
476
+ return shown
477
+ }