forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool.ts
More file actions
1460 lines (1263 loc) · 33.7 KB
/
tool.ts
File metadata and controls
1460 lines (1263 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Per-tool display rules shared across `opencode run` output paths.
//
// Each known tool (bash, edit, write, task, etc.) has a ToolRule that controls
// five display hooks:
//
// view → visibility policy for progress/final scrollback entries and
// whether completed finals can render as structured snapshots
// run → inline summary for the non-interactive `run` command output
// scroll → text formatting for start/progress/final scrollback entries
// permission → display info for the permission UI (icon, title, diff)
// snap → structured snapshot (code block, diff, task card) for rich
// scrollback entries
//
// Tools not in TOOL_RULES get fallback formatting.
import os from "os"
import path from "path"
import stripAnsi from "strip-ansi"
import type { ToolPart } from "@opencode-ai/sdk/v2"
import type * as Tool from "@/tool/tool"
import type { ApplyPatchTool } from "@/tool/apply_patch"
import type { ShellTool as BashTool } from "@/tool/shell"
import type { EditTool } from "@/tool/edit"
import type { GlobTool } from "@/tool/glob"
import type { GrepTool } from "@/tool/grep"
import type { InvalidTool } from "@/tool/invalid"
import type { LspTool } from "@/tool/lsp"
import type { PlanExitTool } from "@/tool/plan"
import type { QuestionTool } from "@/tool/question"
import type { ReadTool } from "@/tool/read"
import type { SkillTool } from "@/tool/skill"
import type { TaskTool } from "@/tool/task"
import type { TodoWriteTool } from "@/tool/todo"
import type { WebFetchTool } from "@/tool/webfetch"
import { webSearchProviderLabel, type WebSearchTool } from "@/tool/websearch"
import type { WriteTool } from "@/tool/write"
import { LANGUAGE_EXTENSIONS } from "@/lsp/language"
import * as Locale from "@/util/locale"
import type { RunDiffStyle, RunEntryBody, StreamCommit, ToolSnapshot } from "./types"
export type ToolView = {
output: boolean
final: boolean
snap?: "code" | "diff" | "structured"
}
export type ToolPhase = "start" | "progress" | "final"
export type ToolDict = Record<string, unknown>
export type ToolFrame = {
raw: string
name: string
input: ToolDict
meta: ToolDict
state: ToolDict
status: string
error: string
}
export type ToolInline = {
icon: string
title: string
description?: string
mode?: "inline" | "block"
body?: string
}
export type ToolPermissionInfo = {
icon: string
title: string
lines: string[]
diff?: string
file?: string
}
export type ToolProps<T = Tool.Info> = {
input: Partial<Tool.InferParameters<T>>
metadata: Partial<Tool.InferMetadata<T>>
frame: ToolFrame
}
type ToolPermissionProps<T = Tool.Info> = {
input: Partial<Tool.InferParameters<T>>
metadata: Partial<Tool.InferMetadata<T>>
patterns: string[]
}
type ToolPermissionCtx = {
input: ToolDict
meta: ToolDict
patterns: string[]
}
type ToolDefs = {
invalid: typeof InvalidTool
bash: typeof BashTool
write: typeof WriteTool
edit: typeof EditTool
apply_patch: typeof ApplyPatchTool
batch: Tool.Info
task: typeof TaskTool
todowrite: typeof TodoWriteTool
question: typeof QuestionTool
read: typeof ReadTool
glob: typeof GlobTool
grep: typeof GrepTool
list: Tool.Info
lsp: typeof LspTool
webfetch: typeof WebFetchTool
websearch: typeof WebSearchTool
skill: typeof SkillTool
plan_exit: typeof PlanExitTool
}
type ToolName = keyof ToolDefs
type ToolRule<T = Tool.Info> = {
view: ToolView
run: (props: ToolProps<T>) => ToolInline
scroll?: Partial<Record<ToolPhase, (props: ToolProps<T>) => string>>
permission?: (props: ToolPermissionProps<T>) => ToolPermissionInfo
snap?: (props: ToolProps<T>) => ToolSnapshot | undefined
}
type ToolRegistry = {
[K in ToolName]: ToolRule<ToolDefs[K]>
}
type AnyToolRule = ToolRule
function dict(v: unknown): ToolDict {
if (!v || typeof v !== "object" || Array.isArray(v)) {
return {}
}
return { ...v }
}
function props<T = Tool.Info>(frame: ToolFrame): ToolProps<T> {
return {
input: Object.assign(Object.create(null), frame.input),
metadata: Object.assign(Object.create(null), frame.meta),
frame,
}
}
function permission<T = Tool.Info>(ctx: ToolPermissionCtx): ToolPermissionProps<T> {
return {
input: Object.assign(Object.create(null), ctx.input),
metadata: Object.assign(Object.create(null), ctx.meta),
patterns: ctx.patterns,
}
}
function text(v: unknown): string {
return typeof v === "string" ? v : ""
}
function num(v: unknown): number | undefined {
if (typeof v !== "number" || !Number.isFinite(v)) {
return undefined
}
return v
}
function list<T>(v: unknown): T[] {
if (!Array.isArray(v)) {
return []
}
return v
}
function info(data: ToolDict, skip: string[] = []): string {
const list = Object.entries(data).filter(([key, val]) => {
if (skip.includes(key)) {
return false
}
return typeof val === "string" || typeof val === "number" || typeof val === "boolean"
})
if (list.length === 0) {
return ""
}
return `[${list.map(([key, val]) => `${key}=${String(val)}`).join(", ")}]`
}
function span(state: ToolDict): string {
const time = dict(state.time)
const start = num(time.start)
const end = num(time.end)
if (start === undefined || end === undefined || end <= start) {
return ""
}
return Locale.duration(end - start)
}
function fail(ctx: ToolFrame): string {
const error = toolError(ctx)
if (error) {
return `✖ ${ctx.name} failed: ${error}`
}
return `✖ ${ctx.name} failed`
}
function toolError(ctx: ToolFrame): string {
if (ctx.error) {
return ctx.error
}
const state = text(ctx.state.error).trim()
if (state) {
return state
}
return ctx.raw.trim()
}
function fallbackStart(ctx: ToolFrame): string {
const extra = info(ctx.input)
if (!extra) {
return `⚙ ${ctx.name}`
}
return `⚙ ${ctx.name} ${extra}`
}
function fallbackFinal(ctx: ToolFrame): string {
if (ctx.status === "error") {
return fail(ctx)
}
if (ctx.status && ctx.status !== "completed") {
return ctx.raw.trim()
}
const time = span(ctx.state)
if (!time) {
return `${ctx.name} completed`
}
return `${ctx.name} completed · ${time}`
}
export function toolPath(input?: string, opts: { home?: boolean } = {}): string {
if (!input) {
return ""
}
const cwd = process.cwd()
const home = os.homedir()
const abs = path.isAbsolute(input) ? input : path.resolve(cwd, input)
const rel = path.relative(cwd, abs)
if (!rel) {
return "."
}
if (!rel.startsWith("..")) {
return rel.replaceAll("\\", "/")
}
if (opts.home && home && (abs === home || abs.startsWith(home + path.sep))) {
return abs.replace(home, "~").replaceAll("\\", "/")
}
return abs.replaceAll("\\", "/")
}
function fallbackInline(ctx: ToolFrame): ToolInline {
const title = text(ctx.state.title) || (Object.keys(ctx.input).length > 0 ? JSON.stringify(ctx.input) : "Unknown")
return {
icon: "⚙",
title: `${ctx.name} ${title}`,
}
}
function count(n: number, label: string): string {
return `${n} ${label}${n === 1 ? "" : "es"}`
}
function runGlob(p: ToolProps<typeof GlobTool>): ToolInline {
const root = p.input.path ?? ""
const title = `Glob "${p.input.pattern ?? ""}"`
const suffix = root ? `in ${toolPath(root)}` : ""
const matches = p.metadata.count
const description = matches === undefined ? suffix : `${suffix}${suffix ? " · " : ""}${count(matches, "match")}`
return {
icon: "✱",
title,
...(description && { description }),
}
}
function runGrep(p: ToolProps<typeof GrepTool>): ToolInline {
const root = p.input.path ?? ""
const title = `Grep "${p.input.pattern ?? ""}"`
const suffix = root ? `in ${toolPath(root)}` : ""
const matches = p.metadata.matches
const description = matches === undefined ? suffix : `${suffix}${suffix ? " · " : ""}${count(matches, "match")}`
return {
icon: "✱",
title,
...(description && { description }),
}
}
function runList(p: ToolProps): ToolInline {
const dir = text(dict(p.input).path)
return {
icon: "→",
title: dir ? `List ${toolPath(dir)}` : "List",
}
}
function runRead(p: ToolProps<typeof ReadTool>): ToolInline {
const file = toolPath(p.input.filePath)
const description = info(p.frame.input, ["filePath"]) || undefined
return {
icon: "→",
title: `Read ${file}`,
...(description && { description }),
}
}
function runWrite(p: ToolProps<typeof WriteTool>): ToolInline {
return {
icon: "←",
title: `Write ${toolPath(p.input.filePath)}`,
mode: "block",
body: p.frame.status === "completed" ? text(p.frame.state.output) : undefined,
}
}
function runWebfetch(p: ToolProps<typeof WebFetchTool>): ToolInline {
const url = p.input.url ?? ""
return {
icon: "%",
title: url ? `WebFetch ${url}` : "WebFetch",
}
}
function runEdit(p: ToolProps<typeof EditTool>): ToolInline {
return {
icon: "←",
title: `Edit ${toolPath(p.input.filePath)}`,
mode: "block",
body: p.metadata.diff,
}
}
function runWebSearch(p: ToolProps<typeof WebSearchTool>): ToolInline {
const title = webSearchProviderLabel(p.metadata.provider)
return {
icon: "◈",
title: p.input.query ? `${title} "${p.input.query}"` : title,
}
}
function runTask(p: ToolProps<typeof TaskTool>): ToolInline {
const kind = Locale.titlecase(p.input.subagent_type || "unknown")
const desc = p.input.description
const icon = p.frame.status === "error" ? "✗" : p.frame.status === "running" ? "•" : "✓"
return {
icon,
title: desc || `${kind} Task`,
description: desc ? `${kind} Agent` : undefined,
}
}
function runTodo(p: ToolProps<typeof TodoWriteTool>): ToolInline {
return {
icon: "#",
title: "Todos",
mode: "block",
body: list<{ status?: string; content?: string }>(p.frame.input.todos)
.flatMap((item) => {
const body = typeof item?.content === "string" ? item.content : ""
if (!body) {
return []
}
const mark = item.status === "completed" ? "[✓]" : item.status === "in_progress" ? "[•]" : "[ ]"
return [`${mark} ${body}`]
})
.join("\n"),
}
}
function runSkill(p: ToolProps<typeof SkillTool>): ToolInline {
return {
icon: "→",
title: `Skill "${p.input.name ?? ""}"`,
}
}
function runPatch(p: ToolProps<typeof ApplyPatchTool>): ToolInline {
const files = p.metadata.files?.length ?? 0
if (files === 0) {
return {
icon: "%",
title: "Patch",
}
}
return {
icon: "%",
title: `Patch ${files} file${files === 1 ? "" : "s"}`,
}
}
function runQuestion(p: ToolProps<typeof QuestionTool>): ToolInline {
const total = list(p.frame.input.questions).length
return {
icon: "→",
title: `Asked ${total} question${total === 1 ? "" : "s"}`,
}
}
function runInvalid(p: ToolProps<typeof InvalidTool>): ToolInline {
return {
icon: "✗",
title: text(p.frame.state.title) || "Invalid Tool",
mode: "block",
body: p.frame.status === "completed" ? text(p.frame.state.output) : undefined,
}
}
function runBatch(p: ToolProps): ToolInline {
const calls = list(dict(p.input).tool_calls).length
return {
icon: "#",
title: text(p.frame.state.title) || (calls > 0 ? `Batch ${calls} tool${calls === 1 ? "" : "s"}` : "Batch"),
mode: "block",
body: p.frame.status === "completed" ? text(p.frame.state.output) : undefined,
}
}
function lspTitle(
input: {
operation?: string
filePath?: string
line?: number
character?: number
},
opts: { home?: boolean } = {},
): string {
const op = input.operation || "request"
const file = input.filePath ? toolPath(input.filePath, opts) : ""
const line = typeof input.line === "number" ? input.line : undefined
const char = typeof input.character === "number" ? input.character : undefined
const pos = line !== undefined && char !== undefined ? `:${line}:${char}` : ""
if (!file) {
return `LSP ${op}`
}
return `LSP ${op} ${file}${pos}`
}
function runLsp(p: ToolProps<typeof LspTool>): ToolInline {
return {
icon: "→",
title: text(p.frame.state.title) || lspTitle(p.input),
}
}
function runPlanExit(p: ToolProps<typeof PlanExitTool>): ToolInline {
return {
icon: "→",
title: text(p.frame.state.title) || "Switching to build agent",
mode: "block",
body: p.frame.status === "completed" ? text(p.frame.state.output) : undefined,
}
}
type PatchFile = Tool.InferMetadata<typeof ApplyPatchTool>["files"][number]
function patchTitle(file: PatchFile): string {
const rel = file.relativePath
const from = file.filePath
if (file.type === "add") {
return `# Created ${rel || toolPath(from)}`
}
if (file.type === "delete") {
return `# Deleted ${rel || toolPath(from)}`
}
if (file.type === "move") {
return `# Moved ${toolPath(from)} -> ${rel || toolPath(file.movePath)}`
}
return `# Patched ${rel || toolPath(from)}`
}
function snapWrite(p: ToolProps<typeof WriteTool>): ToolSnapshot | undefined {
const file = p.input.filePath || ""
const content = p.input.content || ""
if (!file && !content) {
return undefined
}
return {
kind: "code",
title: `# Wrote ${toolPath(file)}`,
content,
file,
}
}
function snapEdit(p: ToolProps<typeof EditTool>): ToolSnapshot | undefined {
const file = p.input.filePath || ""
const diff = p.metadata.diff || ""
if (!file || !diff.trim()) {
return undefined
}
return {
kind: "diff",
items: [
{
title: `# Edited ${toolPath(file)}`,
diff,
file,
},
],
}
}
function snapPatch(p: ToolProps<typeof ApplyPatchTool>): ToolSnapshot | undefined {
const files = list<PatchFile>(p.frame.meta.files)
if (files.length === 0) {
return undefined
}
const items = files.flatMap((file) => {
if (!file || typeof file !== "object") {
return []
}
const diff = typeof file.patch === "string" ? file.patch : ""
if (!diff.trim()) {
return []
}
const name = file.movePath || file.filePath || file.relativePath
return [
{
title: patchTitle(file),
diff,
file: name,
deletions: typeof file.deletions === "number" ? file.deletions : 0,
},
]
})
if (items.length === 0) {
return undefined
}
return {
kind: "diff",
items,
}
}
function snapTask(p: ToolProps<typeof TaskTool>): ToolSnapshot {
const kind = Locale.titlecase(p.input.subagent_type || "general")
const desc = p.input.description
const title = text(p.frame.state.title)
const rows = [desc || title].filter((item): item is string => Boolean(item))
return {
kind: "task",
title: `# ${kind} Task`,
rows,
tail: "",
}
}
function snapTodo(p: ToolProps<typeof TodoWriteTool>): ToolSnapshot {
const items = list<{ status?: string; content?: string }>(p.frame.input.todos).flatMap((item) => {
const content = typeof item?.content === "string" ? item.content : ""
if (!content) {
return []
}
return [
{
status: typeof item.status === "string" ? item.status : "",
content,
},
]
})
return {
kind: "todo",
items,
tail: "",
}
}
function snapQuestion(p: ToolProps<typeof QuestionTool>): ToolSnapshot {
const answers = list<unknown[]>(p.frame.meta.answers)
const items = list<{ question?: string }>(p.frame.input.questions).map((item, i) => {
const answer = list<string>(answers[i]).filter((entry) => typeof entry === "string")
return {
question: item.question || `Question ${i + 1}`,
answer: answer.length > 0 ? answer.join(", ") : "(no answer)",
}
})
return {
kind: "question",
items,
tail: "",
}
}
function scrollBashStart(p: ToolProps<typeof BashTool>): string {
const cmd = p.input.command ?? ""
const desc = p.input.description || "Shell"
const wd = p.input.workdir ?? ""
const dir = wd && wd !== "." ? toolPath(wd) : ""
const title = dir && !desc.includes(dir) ? `${desc} in ${dir}` : desc
if (!cmd) {
return `# ${title}`
}
return `# ${title}\n$ ${cmd}`
}
function scrollBashProgress(p: ToolProps<typeof BashTool>): string {
const out = stripAnsi(p.frame.raw)
const cmd = (p.input.command ?? "").trim()
const fmt = (text: string) => {
const body = text.replace(/^\n+/, "").replace(/\n+$/, "")
return body ? `\n${body}` : ""
}
if (!cmd) {
return out.replace(/\n+$/, "")
}
const wdRaw = (p.input.workdir ?? "").trim()
const wd = wdRaw ? toolPath(wdRaw) : ""
const lines = out.split("\n")
const first = (lines[0] || "").trim()
const second = (lines[1] || "").trim()
if (wd && (first === wd || first === wdRaw) && second === cmd) {
return fmt(lines.slice(2).join("\n"))
}
if (first === cmd || first === `$ ${cmd}`) {
return fmt(lines.slice(1).join("\n"))
}
if (wd && (first === `${wd} ${cmd}` || first === `${wdRaw} ${cmd}`)) {
return fmt(lines.slice(1).join("\n"))
}
return fmt(out)
}
function scrollBashFinal(p: ToolProps<typeof BashTool>): string {
const code = p.metadata.exit ?? num(p.frame.meta.exitCode) ?? num(p.frame.meta.exit_code)
const time = span(p.frame.state)
if (code === undefined) {
if (!time) {
return "bash completed"
}
return `bash completed · ${time}`
}
return `bash completed (exit ${code})${time ? ` · ${time}` : ""}`
}
function scrollReadStart(p: ToolProps<typeof ReadTool>): string {
const file = toolPath(p.input.filePath)
const extra = info(p.frame.input, ["filePath"])
const tail = extra ? ` ${extra}` : ""
return `→ Read ${file}${tail}`.trim()
}
function scrollWriteStart(_: ToolProps<typeof WriteTool>): string {
return ""
}
function scrollEditStart(_: ToolProps<typeof EditTool>): string {
return ""
}
function scrollPatchStart(_: ToolProps<typeof ApplyPatchTool>): string {
return ""
}
function patchLine(file: PatchFile): string {
const type = file.type
const rel = file.relativePath
const from = file.filePath
if (type === "add") {
return `+ Created ${rel || toolPath(from)}`
}
if (type === "delete") {
return `- Deleted ${rel || toolPath(from)}`
}
if (type === "move") {
return `→ Moved ${toolPath(from)} → ${rel || toolPath(file.movePath)}`
}
return `~ Patched ${rel || toolPath(from)}`
}
function scrollPatchFinal(p: ToolProps<typeof ApplyPatchTool>): string {
if (p.frame.status === "error") {
return fail(p.frame)
}
const files = list<PatchFile>(p.frame.meta.files)
if (files.length === 0) {
const time = span(p.frame.state)
if (!time) {
return "patch"
}
return `patch · ${time}`
}
const show_updates = !files.some((file) => file?.type && file.type !== "update")
const shown = files.filter((file) => show_updates || file.type !== "update")
const rows = shown.slice(0, 6).map(patchLine)
if (shown.length > 6) {
rows.push(`... and ${shown.length - 6} more`)
}
if (rows.length > 0) {
return rows.join("\n")
}
return patchLine(files[0]!)
}
function scrollTaskStart(_: ToolProps<typeof TaskTool>): string {
return ""
}
function taskResult(output: string): string | undefined {
if (!output.trim()) {
return undefined
}
const match = output.match(/<task_result>\s*([\s\S]*?)\s*<\/task_result>/)
if (match) {
return match[1].trim() || undefined
}
const next = output
.split("\n")
.filter((line) => !line.startsWith("task_id:"))
.join("\n")
.trim()
return next || undefined
}
function scrollTaskFinal(p: ToolProps<typeof TaskTool>): string {
if (p.frame.status === "error") {
return fail(p.frame)
}
const kind = Locale.titlecase(p.input.subagent_type || "general")
const row = p.input.description || text(p.frame.state.title)
if (!row) {
return `# ${kind} Task`
}
return `# ${kind} Task\n${row}`
}
function scrollTodoStart(_: ToolProps<typeof TodoWriteTool>): string {
return ""
}
function scrollTodoFinal(p: ToolProps<typeof TodoWriteTool>): string {
const items = list<{ status?: string }>(p.input.todos)
const time = span(p.frame.state)
if (items.length === 0) {
if (!time) {
return "0 todos"
}
return `0 todos · ${time}`
}
const doneN = items.filter((item) => item.status === "completed").length
const runN = items.filter((item) => item.status === "in_progress").length
const left = items.length - doneN - runN
const tail = [`${items.length} total`]
if (doneN > 0) {
tail.push(`${doneN} done`)
}
if (runN > 0) {
tail.push(`${runN} active`)
}
if (left > 0) {
tail.push(`${left} pending`)
}
if (time) {
tail.push(time)
}
return tail.join(" · ")
}
function scrollQuestionStart(_: ToolProps<typeof QuestionTool>): string {
return ""
}
function scrollQuestionFinal(p: ToolProps<typeof QuestionTool>): string {
const q = p.input.questions ?? []
const a = p.metadata.answers ?? []
const time = span(p.frame.state)
if (q.length === 0) {
if (!time) {
return "0 questions"
}
return `0 questions · ${time}`
}
const rows: string[] = []
for (const [i, item] of q.slice(0, 4).entries()) {
const prompt = item.question
const reply = a[i] ?? []
rows.push(`? ${prompt || `Question ${i + 1}`}`)
rows.push(` ${reply.length > 0 ? reply.join(", ") : "(no answer)"}`)
}
if (q.length > 4) {
rows.push(`... and ${q.length - 4} more`)
}
return rows.join("\n")
}
function scrollLspStart(p: ToolProps<typeof LspTool>): string {
return `→ ${lspTitle(p.input)}`
}
function scrollSkillStart(p: ToolProps<typeof SkillTool>): string {
return `→ Skill "${p.input.name ?? ""}"`
}
function scrollGlobStart(p: ToolProps<typeof GlobTool>): string {
const pattern = p.input.pattern ?? ""
const head = pattern ? `✱ Glob "${pattern}"` : "✱ Glob"
const dir = p.input.path ?? ""
if (!dir) {
return head
}
return `${head} in ${toolPath(dir)}`
}
function scrollGlobFinal(p: ToolProps<typeof GlobTool>): string {
return toolError(p.frame) || fail(p.frame)
}
function scrollGrepStart(p: ToolProps<typeof GrepTool>): string {
const pattern = p.input.pattern ?? ""
const head = pattern ? `✱ Grep "${pattern}"` : "✱ Grep"
const dir = p.input.path ?? ""
if (!dir) {
return head
}
return `${head} in ${toolPath(dir)}`
}
function scrollListStart(p: ToolProps): string {
const dir = text(dict(p.input).path)
if (!dir) {
return "→ List"
}
return `→ List ${toolPath(dir)}`
}
function scrollWebfetchStart(p: ToolProps<typeof WebFetchTool>): string {
const url = p.input.url ?? ""
if (!url) {
return "% WebFetch"
}
return `% WebFetch ${url}`
}
function scrollWebSearchStart(p: ToolProps<typeof WebSearchTool>): string {
const title = webSearchProviderLabel(p.metadata.provider)
const query = p.input.query ?? ""
if (!query) {
return `◈ ${title}`
}
return `◈ ${title} "${query}"`
}
function permEdit(p: ToolPermissionProps<typeof EditTool>): ToolPermissionInfo {
const input = p.input as { filePath?: string; filepath?: string; diff?: string }
const file = input.filePath || input.filepath || p.patterns[0] || ""
return {
icon: "→",
title: `Edit ${toolPath(file, { home: true })}`,
lines: [],
diff: p.metadata.diff ?? input.diff,
file,
}
}
function permRead(p: ToolPermissionProps<typeof ReadTool>): ToolPermissionInfo {
const file = p.input.filePath || p.patterns[0] || ""
return {
icon: "→",
title: `Read ${toolPath(file, { home: true })}`,
lines: file ? [`Path: ${toolPath(file, { home: true })}`] : [],
}
}
function permGlob(p: ToolPermissionProps<typeof GlobTool>): ToolPermissionInfo {
const pattern = p.input.pattern || p.patterns[0] || ""
return {
icon: "✱",
title: `Glob "${pattern}"`,
lines: pattern ? [`Pattern: ${pattern}`] : [],
}
}
function permGrep(p: ToolPermissionProps<typeof GrepTool>): ToolPermissionInfo {
const pattern = p.input.pattern || p.patterns[0] || ""
return {
icon: "✱",
title: `Grep "${pattern}"`,
lines: pattern ? [`Pattern: ${pattern}`] : [],
}
}
function permList(p: ToolPermissionProps): ToolPermissionInfo {
const dir = text(dict(p.input).path) || p.patterns[0] || ""
return {
icon: "→",
title: `List ${toolPath(dir, { home: true })}`,
lines: dir ? [`Path: ${toolPath(dir, { home: true })}`] : [],
}
}
function permBash(p: ToolPermissionProps<typeof BashTool>): ToolPermissionInfo {
const title = p.input.description || "Shell command"
const cmd = p.input.command || ""
return {
icon: "#",
title,
lines: cmd ? [`$ ${cmd}`] : p.patterns.map((item) => `- ${item}`),
}
}
function permTask(p: ToolPermissionProps<typeof TaskTool>): ToolPermissionInfo {
const type = p.input.subagent_type || "general"
const desc = p.input.description
return {
icon: "#",
title: `${Locale.titlecase(type)} Task`,
lines: desc ? [`◉ ${desc}`] : [],
}
}
function permWebfetch(p: ToolPermissionProps<typeof WebFetchTool>): ToolPermissionInfo {
const url = p.input.url || ""
return {
icon: "%",
title: `WebFetch ${url}`,
lines: url ? [`URL: ${url}`] : [],
}
}
function permWebSearch(p: ToolPermissionProps<typeof WebSearchTool>): ToolPermissionInfo {
const query = p.input.query || ""
const title = webSearchProviderLabel(p.metadata.provider)
return {
icon: "◈",
title: query ? `${title} "${query}"` : title,