Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

presentation.ts

325 lines10.9 KB

1import type { AssetResource, OrchestrationV2TurnItem, ThreadId } from "@t3tools/contracts";
2import {
3 resolveT3McpToolSummaryAction,
4 type T3McpToolSummaryAction,
5} from "@t3tools/shared/t3McpToolPresentation";
6import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
7​
8import { classifyMarkdownImageSource, markdownImageSourceFragment } from "../markdownImages.js";
9​
10import {
11 summarizeT3ToolCalls,
12 type T3ToolSummaryCall,
13} from "@t3tools/client-runtime/t3ToolSummary";
14​
15export type WorkLogToolLifecycleStatus =
16 | "inProgress"
17 | "completed"
18 | "failed"
19 | "declined"
20 | "stopped";
21​
22export interface WorkLogPresentationEntry {
23 readonly id: string;
24 readonly createdAt: string;
25 readonly label: string;
26 readonly tone: "thinking" | "tool" | "info" | "error";
27 readonly command?: string;
28 readonly rawCommand?: string;
29 readonly detail?: string;
30 readonly changedFiles?: ReadonlyArray<string>;
31 readonly toolTitle?: string;
32 readonly toolData?: unknown;
33 readonly requestKind?: string;
34 readonly itemType?: OrchestrationV2TurnItem["type"];
35 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
36 readonly structuredPayload?: OrchestrationV2TurnItem;
38​
39export type ToolGroupAction =
40 | "read"
41 | "edit"
42 | "command"
43 | "code-search"
44 | "search"
45 | "other"
46 | "update";
47​
48export type ToolGroupSummaryKind =
49 | ToolGroupAction
50 | "dynamic-tool"
51 | "agent-tool"
52 | "tone-tool"
53 | "mixed";
54​
55export function normalizeCompactToolLabel(value: string): string {
56 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
58​
59export function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
60 return (
61 entry.tone === "tool" ||
62 entry.tone === "thinking" ||
63 entry.tone === "error" ||
64 entry.command !== undefined ||
65 entry.requestKind !== undefined
66 );
68​
69function toolDetailTextLooksLikeFailure(text: string): boolean {
70 const normalized = text.toLowerCase();
71 return (
72 normalized.includes("file not found") ||
73 normalized.includes("no files found") ||
74 normalized.includes("enoent") ||
75 normalized.includes("no such file or directory") ||
76 normalized.includes("no such file") ||
77 (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
78 normalized.includes("commandnotfoundexception") ||
79 normalized.includes("is not recognized as the name of a cmdlet") ||
80 (normalized.includes("is not recognized") && normalized.includes("the term '")) ||
81 normalized.includes("a parameter cannot be found that matches parameter name") ||
82 normalized.includes("command not found") ||
83 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
84 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
85 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
86 );
88​
89export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
90 if (
91 entry.tone === "error" ||
92 entry.toolLifecycleStatus === "failed" ||
93 entry.toolLifecycleStatus === "declined"
94 ) {
95 return true;
96 }
97 return (
98 workLogEntryIsToolLike(entry) &&
99 entry.detail !== undefined &&
100 toolDetailTextLooksLikeFailure(entry.detail)
101 );
103​
104export function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
105 return (
106 entry.itemType === "file_search" ||
107 (entry.itemType === "web_search" &&
108 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label)))
109 );
111​
112export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
113 if (entry.requestKind === "file-read") return "read";
114 if (
115 entry.itemType === "dynamic_tool" &&
116 /^read(?:\s+file)?$/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label))
117 ) {
118 return "read";
119 }
120 if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit";
121 if (entry.itemType === "command_execution" || entry.command) return "command";
122 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
123 if (entry.itemType === "web_search") return "search";
124 return workLogEntryIsToolLike(entry) ? "other" : "update";
126​
127export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
128 const detail = entry.detail?.trim();
129 return toolGroupAction(entry) === "read" &&
130 detail !== undefined &&
131 !/[\r\n]/.test(detail) &&
132 isWorkspaceImagePreviewPath(detail)
133 ? detail
134 : null;
136​
137export interface ViewedImageAsset {
138 readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "workspace-file" }>;
139 readonly alt: string;
140 readonly srcFragment: string;
142​
143const ABSOLUTE_IMAGE_SOURCE_PATTERN = /^(?:file:|[\\/]|[a-z]:[\\/])/i;
144const T3_ATTACHMENT_IMAGE_PATH_PATTERN =
145 /(?:^|[\\/])(?:dev|userdata)[\\/]attachments[\\/]([a-z0-9_-]{1,128})\.[a-z0-9]{1,10}$/i;
146​
147export function resolveViewedImageAsset(
148 source: string,
149 input: {
150 readonly threadId: ThreadId;
151 readonly workspaceRoot?: string | null | undefined;
152 },
153): ViewedImageAsset | null {
154 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
155 if (imageSource._tag !== "WorkspaceFile") return null;
156​
157 const path =
158 input.workspaceRoot == null && imageSource.path.startsWith("./")
159 ? imageSource.path.slice(2)
160 : imageSource.path;
161 const attachmentId = ABSOLUTE_IMAGE_SOURCE_PATTERN.test(source)
162 ? (T3_ATTACHMENT_IMAGE_PATH_PATTERN.exec(path)?.[1] ?? null)
163 : null;
164​
165 return {
166 resource: attachmentId
167 ? { _tag: "attachment", attachmentId }
168 : { _tag: "workspace-file", threadId: input.threadId, path },
169 alt: path.split(/[\\/]/).at(-1) ?? "image",
170 srcFragment: markdownImageSourceFragment(source),
171 };
173​
174function toolGroupActionCount(
175 action: ToolGroupAction,
176 entries: ReadonlyArray<WorkLogPresentationEntry>,
177): number {
178 if (action !== "edit") return entries.length;
179 const changedFiles = new Set<string>();
180 let editsWithoutFileDetails = 0;
181 for (const entry of entries) {
182 if (!entry.changedFiles || entry.changedFiles.length === 0) {
183 editsWithoutFileDetails += 1;
184 } else {
185 for (const file of entry.changedFiles) changedFiles.add(file);
186 }
187 }
188 return changedFiles.size + editsWithoutFileDetails;
190​
191function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
192 switch (action) {
193 case "read":
194 return `Read ${count} ${count === 1 ? "file" : "files"}`;
195 case "edit":
196 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
197 case "command":
198 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
199 case "search":
200 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
201 case "code-search":
202 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
203 case "other":
204 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
205 case "update":
206 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
207 }
209​
210function t3ToolSummaryCall(entry: WorkLogPresentationEntry): T3ToolSummaryCall {
211 const item = entry.structuredPayload;
212 const data =
213 entry.toolData !== null && typeof entry.toolData === "object"
214 ? (entry.toolData as Record<string, unknown>)
215 : undefined;
216 return {
217 input: item?.type === "dynamic_tool" ? item.input : data?.input,
218 output: item?.type === "dynamic_tool" ? item.output : data?.output,
219 outcome:
220 entry.toolLifecycleStatus === "failed" ||
221 entry.toolLifecycleStatus === "declined" ||
222 entry.tone === "error"
223 ? "failed"
224 : entry.toolLifecycleStatus === "completed"
225 ? "completed"
226 : "unfinished",
227 };
229​
230function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction): number {
231 switch (action) {
232 case "command":
233 case "edit":
234 case "delegate":
235 case "task-cancel":
236 case "thread-create":
237 case "thread-send":
238 case "thread-interrupt":
239 case "schedule-create":
240 case "schedule-update":
241 case "schedule-delete":
242 return 0;
243 case "other":
244 case "update":
245 return 2;
246 default:
247 return 1;
248 }
250​
251/** Summarizes at most two action categories; every omitted call still counts in the remainder. */
252export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): {
253 summary: string;
254 hasFailure: boolean;
255} {
256 const groups = new Map<
257 ToolGroupAction | T3McpToolSummaryAction,
258 {
259 action: ToolGroupAction;
260 t3Action: T3McpToolSummaryAction | null;
261 entries: WorkLogPresentationEntry[];
262 }
263 >();
264 for (const entry of entries) {
265 const item = entry.structuredPayload;
266 const t3Action = resolveT3McpToolSummaryAction(
267 (item?.type === "dynamic_tool" ? item.toolName : null) ?? entry.toolTitle ?? entry.label,
268 );
269 const action = toolGroupAction(entry);
270 const key = t3Action ?? action;
271 const group = groups.get(key);
272 if (group) group.entries.push(entry);
273 else groups.set(key, { action, t3Action, entries: [entry] });
274 }
275 const summaries = [...groups].map(([action, group], index) => ({
276 index,
277 count: group.entries.length,
278 priority: summaryActionPriority(action),
279 ...(group.t3Action
280 ? summarizeT3ToolCalls(group.t3Action, group.entries.map(t3ToolSummaryCall))
281 : {
282 label: toolGroupActionLabel(
283 group.action,
284 toolGroupActionCount(group.action, group.entries),
285 ),
286 failedCount: group.entries.filter(workEntryDisplayIndicatesToolFailure).length,
287 }),
288 }));
289 const selected = [...summaries]
290 .sort((a, b) => a.priority - b.priority || a.index - b.index)
291 .slice(0, 2)
292 .sort((a, b) => a.index - b.index);
293 const labels = selected.map(({ label }) => label);
294 const remainingCount = entries.length - selected.reduce((count, group) => count + group.count, 0);
295 if (remainingCount > 0) {
296 labels.push(`Performed ${remainingCount} other ${remainingCount === 1 ? "action" : "actions"}`);
297 }
298 const sentenceLabels = labels.map((label, index) =>
299 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
300 );
301 const summary =
302 sentenceLabels.length < 3
303 ? sentenceLabels.join(" and ")
304 : `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
305 return { summary, hasFailure: summaries.some((group) => group.failedCount > 0) };
307​
308export function toolGroupSummaryKind(
309 entries: ReadonlyArray<WorkLogPresentationEntry>,
310): ToolGroupSummaryKind {
311 const actions = new Set(entries.map(toolGroupAction));
312 if (actions.size !== 1) return "mixed";
313 const action = actions.values().next().value!;
314 if (action !== "other") return action;
315 const fallbackKinds = new Set(
316 entries.map((entry): ToolGroupSummaryKind => {
317 if (entry.itemType === "dynamic_tool") return "dynamic-tool";
318 if (entry.itemType === "subagent") return "agent-tool";
319 if (entry.tone === "thinking") return "agent-tool";
320 if (entry.tone === "tool") return "tone-tool";
321 return "other";
322 }),
323 );
324 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";