@sixb/cli 0.2.3 → 0.2.5

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.
package/src/tui/format.ts CHANGED
@@ -15,16 +15,24 @@ export interface ToolLine {
15
15
  readonly held?: boolean
16
16
  /** A shell command, shown whole as the call's panel. */
17
17
  readonly command?: string
18
+ /** The preview is diff lines, `+` added and `-` removed, colored as such. */
19
+ readonly diff?: boolean
20
+ /** The preview rows start with paths, shown as the person reads them. */
21
+ readonly paths?: boolean
18
22
  }
19
23
 
20
24
  const PREVIEW_LINES = 4
21
25
 
22
26
  const NO_OUTCOMES: ReadonlyMap<string, ApprovalOutcome> = new Map()
23
27
 
24
- /** `outcomes` says how the held calls ended, by approval id: a decided call is no longer held. */
28
+ /**
29
+ * `outcomes` says how the held calls ended, by approval id: a decided call is no longer held.
30
+ * `folder` is the one a computer's turns work in: a search names where it looked relative to it.
31
+ */
25
32
  export function toolLine(
26
33
  part: ToolPart,
27
- outcomes: ReadonlyMap<string, ApprovalOutcome> = NO_OUTCOMES
34
+ outcomes: ReadonlyMap<string, ApprovalOutcome> = NO_OUTCOMES,
35
+ folder?: string
28
36
  ): ToolLine {
29
37
  const input = record(part.input) ?? partialInput(part.inputText)
30
38
  const output = record(part.output)
@@ -70,6 +78,31 @@ export function toolLine(
70
78
  ...error,
71
79
  }
72
80
  }
81
+ case "wait":
82
+ case "stop": {
83
+ // Background commands by their id, sub-agents by their key; with a sub-agent, the result is
84
+ // rich, its JSON in its text.
85
+ const ids = Array.isArray(input?.ids) ? input.ids.map(text) : [text(input?.id)]
86
+ const value = record(richValue(output))
87
+ const commands = Array.isArray(value?.commands) ? value.commands.map(record) : []
88
+ const results = Array.isArray(value?.results) ? value.results.map(record) : []
89
+ const [command] = commands
90
+ const one = commands.length + results.length === 1
91
+ const written = one ? text(command?.output) : ""
92
+ const childStatus = one && !command ? text(results[0]?.status) : ""
93
+ return {
94
+ verb: part.name,
95
+ // One command reads as bash_output's did: its id, then what it runs.
96
+ detail: [...ids, one && command ? firstLine(text(command.command)) : ""]
97
+ .filter(Boolean)
98
+ .join(" "),
99
+ ...(written.trim() ? { preview: lines(written) } : {}),
100
+ ...(one && command ? backgroundNote(text(command.status), command.exitCode) : {}),
101
+ ...(childStatus ? childNote(childStatus) : {}),
102
+ ...error,
103
+ }
104
+ }
105
+ // What `wait` and `stop` were called for a background command: earlier threads hold them.
73
106
  case "bash_output":
74
107
  case "bash_stop": {
75
108
  const output_ = text(output?.output)
@@ -83,6 +116,19 @@ export function toolLine(
83
116
  }
84
117
  }
85
118
  case "read": {
119
+ // A file shown as itself, an image or a PDF, reads as view_file did.
120
+ if (output?.kind === "agentToolResult") {
121
+ return { verb: "view", detail: text(input?.path), ...error }
122
+ }
123
+ if (Array.isArray(output?.entries)) {
124
+ const entries = `${output.entries.length} ${output.entries.length === 1 ? "entry" : "entries"}`
125
+ return {
126
+ verb: "list",
127
+ detail: text(input?.path),
128
+ note: output.truncated === true ? `${entries}+` : entries,
129
+ ...error,
130
+ }
131
+ }
86
132
  const lineCount = typeof output?.endLine === "number" && typeof output.startLine === "number"
87
133
  return {
88
134
  verb: "read",
@@ -93,6 +139,106 @@ export function toolLine(
93
139
  ...error,
94
140
  }
95
141
  }
142
+ case "edit": {
143
+ const changed = text(output?.diff)
144
+ .split("\n")
145
+ .filter((line) => /^[+-]/.test(line))
146
+
147
+ // The diff is cut on a large edit, so the edit counts its lines; an output stored before it
148
+ // did carries only the diff.
149
+ const added =
150
+ typeof output?.added === "number"
151
+ ? output.added
152
+ : changed.filter((line) => line.startsWith("+")).length
153
+ const removed =
154
+ typeof output?.removed === "number"
155
+ ? output.removed
156
+ : changed.filter((line) => line.startsWith("-")).length
157
+
158
+ return {
159
+ verb: "edit",
160
+ detail: text(input?.path),
161
+ ...(output?.diff !== undefined
162
+ ? { note: `+${added} −${removed}`, diff: true, preview: limited(changed) }
163
+ : {}),
164
+ ...error,
165
+ }
166
+ }
167
+ case "write": {
168
+ const linesWritten = typeof output?.lines === "number" ? output.lines : undefined
169
+ return {
170
+ verb: output?.created === false ? "rewrite" : "write",
171
+ detail: text(input?.path),
172
+ ...(linesWritten !== undefined ? { note: plural(linesWritten, "line") } : {}),
173
+ ...error,
174
+ }
175
+ }
176
+ case "glob": {
177
+ const files = Array.isArray(output?.files) ? output.files.map(text) : undefined
178
+ const found = files?.length ?? 0
179
+
180
+ return {
181
+ verb: "glob",
182
+ detail: searchDetail(input, text(input?.pattern), folder),
183
+ ...(files
184
+ ? {
185
+ note: searchNote(
186
+ output,
187
+ found === 0
188
+ ? "no files"
189
+ : output?.truncated === true
190
+ ? `${found}+ files`
191
+ : plural(found, "file")
192
+ ),
193
+ ...(found > 0 ? { preview: limitedRows(files, "file", "files"), paths: true } : {}),
194
+ }
195
+ : {}),
196
+ ...error,
197
+ }
198
+ }
199
+ case "grep": {
200
+ const matches = Array.isArray(output?.matches) ? output.matches.map(record) : undefined
201
+ const shown = matches?.length ?? 0
202
+ const counted = Object.values(record(output?.more) ?? {}).filter(
203
+ (count): count is number => typeof count === "number"
204
+ )
205
+ const total = counted.reduce((sum, count) => sum + count, shown)
206
+
207
+ const files = typeof output?.files === "number" ? output.files : 0
208
+ const found = `${total} ${total === 1 ? "match" : "matches"}`
209
+
210
+ return {
211
+ verb: "grep",
212
+ detail: searchDetail(input, input?.pattern ? `"${text(input.pattern)}"` : "", folder),
213
+ ...(matches
214
+ ? {
215
+ note: searchNote(
216
+ output,
217
+ total === 0
218
+ ? "no matches"
219
+ : output?.truncated === true
220
+ ? `${total}+ matches`
221
+ : `${found} in ${plural(files, "file")}`
222
+ ),
223
+ ...(shown > 0
224
+ ? {
225
+ preview: limitedRows(
226
+ matches.map(
227
+ (match) => `${text(match?.path)}:${match?.line} ${text(match?.text).trim()}`
228
+ ),
229
+ "match",
230
+ "matches",
231
+ total
232
+ ),
233
+ paths: true,
234
+ }
235
+ : {}),
236
+ }
237
+ : {}),
238
+ ...error,
239
+ }
240
+ }
241
+ // Earlier threads hold calls to it.
96
242
  case "view_file":
97
243
  return { verb: "view", detail: text(input?.path), ...error }
98
244
  case "web_search": {
@@ -112,11 +258,14 @@ export function toolLine(
112
258
  ...(failed ? fetchFailure(part.error) : {}),
113
259
  }
114
260
  case "publish_artifact":
261
+ // What `publish_artifact` with an id was called: earlier threads hold calls to them.
115
262
  case "update_artifact":
116
- // What `update_artifact` was called: earlier threads hold calls to it.
117
263
  case "publish_artifact_version":
118
264
  return {
119
- verb: part.name === "publish_artifact" ? "publish" : "update",
265
+ verb:
266
+ part.name === "publish_artifact" && !text(input?.id).startsWith("art_")
267
+ ? "publish"
268
+ : "update",
120
269
  detail: text(input?.title) || text(input?.path) || text(input?.artifactId),
121
270
  ...(output?.artifactId ? { note: `artifact:${text(output.artifactId)}` } : {}),
122
271
  ...error,
@@ -134,6 +283,7 @@ export function toolLine(
134
283
  detail: [text(input?.key), firstLine(text(input?.task))].filter(Boolean).join(" "),
135
284
  ...error,
136
285
  }
286
+ // What `wait` was called for sub-agents: earlier threads hold calls to it.
137
287
  case "wait_agent": {
138
288
  const runIds = Array.isArray(input?.runIds) ? input.runIds.length : 0
139
289
  return {
@@ -148,12 +298,32 @@ export function toolLine(
148
298
  detail: [text(input?.key), firstLine(text(input?.text))].filter(Boolean).join(" "),
149
299
  ...error,
150
300
  }
151
- case "ask_parent":
301
+ case "ask":
302
+ // What `ask` was called for a sub-agent: earlier threads hold calls to it.
303
+ case "ask_parent": {
304
+ const questions = askedQuestions(input)
305
+ // One question reads on the line; several, each with its choices numbered, under it. A row's
306
+ // runs of spaces collapse to one, so the choices are kept apart by a dot.
307
+ const [first] = questions
152
308
  return {
153
309
  verb: "ask",
154
- detail: firstLine(text(input?.question) || text(input?.text)),
310
+ detail:
311
+ questions.length === 1 && first ? first.question : plural(questions.length, "question"),
312
+ ...(questions.length > 1 || first?.choices.length
313
+ ? {
314
+ preview: questions.map((question) =>
315
+ [
316
+ ...(questions.length > 1 ? [question.question] : []),
317
+ question.choices.map((choice, index) => `${index + 1}. ${choice}`).join(" · "),
318
+ ]
319
+ .filter(Boolean)
320
+ .join(" ")
321
+ ),
322
+ }
323
+ : {}),
155
324
  ...error,
156
325
  }
326
+ }
157
327
  default:
158
328
  return {
159
329
  verb: part.name,
@@ -262,6 +432,14 @@ function backgroundNote(status: string, exitCode: unknown): Pick<ToolLine, "note
262
432
  return exitCode === 0 ? { note: "exit 0" } : { note: `exit ${exitCode}`, failed: true }
263
433
  }
264
434
 
435
+ /** How a sub-agent a `wait` or a `stop` named stands, beside its line. */
436
+ function childNote(status: string): Pick<ToolLine, "note" | "failed"> {
437
+ if (status === "succeeded") return { note: "done" }
438
+ if (status === "cancelled") return { note: "stopped" }
439
+ if (status === "failed") return { note: "failed", failed: true }
440
+ return { note: status.replaceAll("_", " ") }
441
+ }
442
+
265
443
  /** How decided calls ended, as the web chat's approval card names it. */
266
444
  function decidedLine(outcomes: readonly ApprovalOutcome[]): Pick<ToolLine, "note" | "failed"> {
267
445
  const ended = outcomes.map(outcomeNote)
@@ -303,6 +481,19 @@ function parseJson(value: string): unknown {
303
481
  }
304
482
  }
305
483
 
484
+ /** A rich result's value, its JSON text parsed; any other output as it is. */
485
+ function richValue(output: Record<string, unknown> | undefined): unknown {
486
+ if (output?.kind !== "agentToolResult" || !Array.isArray(output.content)) return output
487
+ const [first] = output.content
488
+ const textPart = record(first)
489
+ if (typeof textPart?.text !== "string") return undefined
490
+ try {
491
+ return JSON.parse(textPart.text)
492
+ } catch {
493
+ return undefined
494
+ }
495
+ }
496
+
306
497
  function record(value: unknown): Record<string, unknown> | undefined {
307
498
  return value && typeof value === "object" && !Array.isArray(value)
308
499
  ? (value as Record<string, unknown>)
@@ -315,11 +506,16 @@ function partialInput(inputText: string | undefined): Record<string, unknown> |
315
506
  try {
316
507
  return record(JSON.parse(inputText))
317
508
  } catch {
318
- const command = /"(?:command|path|task|key|query|url)"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(inputText)
319
- const value = command?.[1]
320
- return value !== undefined
321
- ? { command: value, path: value, task: value, query: value, url: value }
322
- : undefined
509
+ const found = /"(command|path|task|key|query|url|pattern)"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(
510
+ inputText
511
+ )
512
+ const [, key, value] = found ?? []
513
+ if (value === undefined) return undefined
514
+
515
+ // A search's pattern is only its pattern: it is no path its line would say it looked in.
516
+ if (key === "pattern") return { pattern: value }
517
+
518
+ return { command: value, path: value, task: value, query: value, url: value }
323
519
  }
324
520
  }
325
521
 
@@ -335,6 +531,113 @@ function firstLine(value: string): string {
335
531
  return value.trim().split("\n")[0]?.trim() ?? ""
336
532
  }
337
533
 
534
+ export interface AskedQuestion {
535
+ readonly question: string
536
+ readonly choices: readonly string[]
537
+ readonly multiple: boolean
538
+ }
539
+
540
+ /** The questions of an `ask` call, or of an earlier `ask_parent` call's one question. */
541
+ function askedQuestions(input: Record<string, unknown> | undefined): AskedQuestion[] {
542
+ if (typeof input?.question === "string") {
543
+ return [{ question: input.question.trim(), choices: [], multiple: false }]
544
+ }
545
+ if (!Array.isArray(input?.questions)) return []
546
+ return input.questions.flatMap((value) => {
547
+ const question = record(value)
548
+ if (typeof question?.question !== "string") return []
549
+ const choices = Array.isArray(question.choices)
550
+ ? question.choices.filter((choice): choice is string => typeof choice === "string")
551
+ : []
552
+ return [{ question: question.question.trim(), choices, multiple: question.multiple === true }]
553
+ })
554
+ }
555
+
556
+ /** What a reply asked the user with its last `ask`: its questions, or none. */
557
+ export function askedInReply(
558
+ message: { readonly role: string; readonly parts: readonly Part[] } | null | undefined
559
+ ): readonly AskedQuestion[] {
560
+ if (message?.role !== "assistant") return []
561
+ const asked = [...message.parts]
562
+ .reverse()
563
+ .find(
564
+ (part): part is ToolPart =>
565
+ part.kind === "tool" && part.name === "ask" && part.state === "done"
566
+ )
567
+ return askedQuestions(record(asked?.input))
568
+ }
569
+
570
+ /**
571
+ * A reply of a number to the Agent's question, its last reply's one question with choices, is the
572
+ * choice under that number: "2" answers "2026". Anything else is sent as typed.
573
+ */
574
+ export function pickedAnswer(
575
+ messages: readonly { readonly role: string; readonly parts: readonly Part[] }[],
576
+ text: string
577
+ ): string {
578
+ const number = text.trim()
579
+ if (!/^\d+$/.test(number)) return text
580
+ const questions = askedInReply(messages.at(-1))
581
+ if (questions.length !== 1) return text
582
+ return questions[0]?.choices[Number(number) - 1] ?? text
583
+ }
584
+
585
+ /** At most a few rows, with how many more there were. */
586
+ function limited(rows: readonly string[]): string[] {
587
+ return rows.length > PREVIEW_LINES
588
+ ? [...rows.slice(0, PREVIEW_LINES), `… ${plural(rows.length - PREVIEW_LINES, "more line")}`]
589
+ : [...rows]
590
+ }
591
+
592
+ /**
593
+ * The first rows, then the rest counted by what they are: `… 8 more files`. `total` counts what
594
+ * the rows stand for when some were never listed, as a file's matches past the ones grep shows.
595
+ */
596
+ function limitedRows(
597
+ rows: readonly string[],
598
+ one: string,
599
+ many: string,
600
+ total = rows.length
601
+ ): string[] {
602
+ const shown = rows.slice(0, PREVIEW_LINES)
603
+ const left = total - shown.length
604
+ return left > 0 ? [...shown, `… ${left} more ${left === 1 ? one : many}`] : shown
605
+ }
606
+
607
+ /**
608
+ * A search as the call wrote it: its pattern, the files it was limited to, and where it looked, as
609
+ * the person reads it. The folder the agent works in goes unsaid, however the call named it.
610
+ */
611
+ function searchDetail(
612
+ input: Record<string, unknown> | undefined,
613
+ pattern: string,
614
+ folder: string | undefined
615
+ ): string {
616
+ const path = givenText(input?.path)
617
+ const include = givenText(input?.include)
618
+ const place = path.replace(/(.)\/+$/, "$1")
619
+ const working =
620
+ place === "." ||
621
+ (folder !== undefined && [folder, folder.replace(/^\/private/, "")].includes(place))
622
+
623
+ return [
624
+ ...(pattern ? [pattern] : []),
625
+ ...(include ? [include] : []),
626
+ ...(path && !working ? [`in ${friendlyPath(path, folder)}`] : []),
627
+ ].join(" ")
628
+ }
629
+
630
+ /** What a search found, and that it stopped early when it did. */
631
+ function searchNote(output: Record<string, unknown> | undefined, found: string): string {
632
+ return output?.incomplete === true ? `${found} · stopped early` : found
633
+ }
634
+
635
+ /** A string the call gave: models send `"null"` and `"undefined"` for nothing. */
636
+ function givenText(value: unknown): string {
637
+ const given = text(value).trim()
638
+ return given === "null" || given === "undefined" ? "" : given
639
+ }
640
+
338
641
  function lines(value: string): string[] {
339
642
  const all = value.replace(/\s+$/, "").split("\n")
340
643
  return all.length > PREVIEW_LINES
@@ -221,7 +221,7 @@ function AgentParts({
221
221
  <ToolRow
222
222
  key={key}
223
223
  colors={colors}
224
- line={shownLine(toolLine(part, outcomes), folder)}
224
+ line={shownLine(toolLine(part, outcomes, folder), folder)}
225
225
  state={part.state}
226
226
  width={width}
227
227
  />
@@ -387,7 +387,7 @@ function ToolRow({
387
387
  {line.preview?.map((row, index) => (
388
388
  <text key={`${index}-${row.slice(0, 12)}`}>
389
389
  <span fg={colors.faint}>{index === 0 ? " ⎿ " : " "}</span>
390
- <span fg={colors.faint}>{oneLine(row, room)}</span>
390
+ <span fg={line.diff ? diffColor(colors, row) : colors.faint}>{oneLine(row, room)}</span>
391
391
  </text>
392
392
  ))}
393
393
  </box>
@@ -455,6 +455,13 @@ function CommandPanel({
455
455
 
456
456
  const COMMAND_LINES = 3
457
457
 
458
+ /** A diff row's color: added green, removed red, anything else faint. */
459
+ function diffColor(colors: TuiColors, row: string): string {
460
+ if (row.startsWith("+")) return colors.green
461
+ if (row.startsWith("-")) return colors.red
462
+ return colors.faint
463
+ }
464
+
458
465
  /** Under a turn's answer: where it ran, on which model, and how long it took. */
459
466
  function RunMeta({
460
467
  colors,
@@ -606,6 +613,9 @@ function shownLine(line: ToolLine, folder?: string): ToolLine {
606
613
  ...line,
607
614
  detail: friendlyPath(line.detail, folder),
608
615
  ...(line.command === undefined ? {} : { command: friendlyPath(line.command, folder) }),
616
+ ...(line.paths && line.preview
617
+ ? { preview: line.preview.map((row) => friendlyPath(row, folder)) }
618
+ : {}),
609
619
  }
610
620
  }
611
621