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

t3ToolSummary.ts

412 lines13.9 KB

1import type { T3McpToolSummaryAction } from "@t3tools/shared/t3McpToolPresentation";
2​
3export interface T3ToolSummaryCall {
4 readonly input: unknown;
5 readonly output: unknown;
6 readonly outcome: "completed" | "failed" | "unfinished";
7}
8​
9function asRecord(value: unknown): Record<string, unknown> | undefined {
10 return value !== null && typeof value === "object" && !Array.isArray(value)
11 ? (value as Record<string, unknown>)
12 : undefined;
14​
15function id(value: unknown): string | undefined {
16 return typeof value === "string" && value.trim() !== "" ? value : undefined;
18​
19interface ToolResult {
20 readonly data?: Record<string, unknown>;
21 readonly failed: boolean;
23​
24/** Reads the structured/JSON MCP result envelopes retained by the provider adapters. */
25function readResult(value: unknown, depth = 0): ToolResult {
26 if (depth > 4) return { failed: false };
27 if (typeof value === "string") {
28 try {
29 return readResult(JSON.parse(value), depth + 1);
30 } catch {
31 return { failed: false };
32 }
33 }
34 if (Array.isArray(value)) {
35 let data: ToolResult["data"];
36 let failed = false;
37 for (const block of value) {
38 const record = asRecord(block);
39 const text = record?.text ?? asRecord(record?.content)?.text;
40 const result = readResult(asRecord(text)?.text ?? text, depth + 1);
41 data ??= result.data;
42 failed ||= result.failed;
43 }
44 return { ...(data ? { data } : {}), failed };
45 }
46 const record = asRecord(value);
47 if (!record) return { failed: false };
48 const failed =
49 record.isError === true ||
50 record.is_error === true ||
51 (typeof record._tag === "string" && /(?:Error|Failure)$/.test(record._tag)) ||
52 record.error != null;
53 const content = record.structuredContent ?? record.content;
54 if (content !== undefined) {
55 const result = readResult(content, depth + 1);
56 return { ...(result.data ? { data: result.data } : {}), failed: failed || result.failed };
57 }
58 return { data: record, failed };
60​
61function readInput(value: unknown): Record<string, unknown> | undefined {
62 const input = readResult(value).data;
63 // Cursor retains its MCP args envelope; other adapters retain the arguments directly.
64 return input && typeof input.toolName === "string" ? asRecord(input.args) : input;
66​
67/** MCP errors can be returned as data even when the provider completed the tool call. */
68export function t3ToolResultIndicatesFailure(output: unknown): boolean {
69 return readResult(output).failed;
71​
72function countEntities(ids: ReadonlyArray<string | undefined>): number {
73 return (
74 new Set(ids.filter((value) => value !== undefined)).size +
75 ids.filter((value) => value === undefined).length
76 );
78​
79function quantity(count: number, noun: string, plural = `${noun}s`): string {
80 return `${count} ${count === 1 ? noun : plural}`;
82​
83/** Counts successful effects separately from failed or unfinished tool calls. */
84export function summarizeT3ToolCalls(
85 action: T3McpToolSummaryAction,
86 calls: ReadonlyArray<T3ToolSummaryCall>,
87): { label: string; failedCount: number } {
88 const results = calls.map((call) => {
89 const result = readResult(call.output);
90 return {
91 input: readInput(call.input),
92 output: result.data,
93 outcome: result.failed ? ("failed" as const) : call.outcome,
94 };
95 });
96 const completed = results.filter((call) => call.outcome === "completed");
97 const failedCount = results.filter((call) => call.outcome === "failed").length;
98 const selected = completed.length > 0 ? completed : results;
99 const times = quantity(selected.length, "time");
100 const phrase = (past: string, infinitive: string, object: string) =>
101 `${completed.length > 0 ? past : `Tried to ${infinitive}`} ${object}`;
102 const entityIds = (key: string) =>
103 selected.map((call) => id(call.output?.[key]) ?? id(call.input?.[key]));
104 const projectIds = selected.map(
105 (call) => id(call.output?.id) ?? id(call.output?.projectId) ?? id(call.input?.projectId),
106 );
107 const threadIds = selected.map(
108 (call) =>
109 id(call.output?.threadId) ??
110 id(asRecord(call.output?.thread)?.threadId) ??
111 id(call.input?.threadId),
112 );
113 let label: string;
114 switch (action) {
115 case "thread-send": {
116 const messages = countEntities(selected.map((call) => id(call.output?.messageId)));
117 const targetsKnown = threadIds.every((value) => value !== undefined);
118 const threads = new Set(threadIds).size;
119 const object = targetsKnown
120 ? messages === threads && messages > 1
121 ? `messages to ${quantity(threads, "thread")}`
122 : `${quantity(messages, "message")} to ${quantity(threads, "thread")}`
123 : quantity(messages, "message");
124 label = phrase("Sent", "send", object);
125 break;
126 }
127 case "thread-create": {
128 const createdIds: string[] = [];
129 const resultsKnown =
130 completed.length > 0 &&
131 completed.every((call) => {
132 const threads = Array.isArray(call.output?.threads) ? call.output.threads : [call.output];
133 return threads.every((thread) => {
134 const record = asRecord(thread);
135 if (record?.status === "rolled_back") return true;
136 const threadId = id(record?.threadId);
137 if (!threadId) return false;
138 createdIds.push(threadId);
139 return true;
140 });
141 });
142 label = resultsKnown
143 ? `Created ${quantity(new Set(createdIds).size, "thread")}`
144 : `Requested thread creation ${times}`;
145 break;
146 }
147 case "delegate":
148 label = phrase("Delegated", "delegate", quantity(countEntities(entityIds("taskId")), "task"));
149 break;
150 case "thread-read":
151 case "thread-wait": {
152 const targets = threadIds.every((value) => value !== undefined)
153 ? quantity(new Set(threadIds).size, "thread")
154 : `threads ${times}`;
155 label =
156 action === "thread-read"
157 ? phrase("Read", "read", targets)
158 : phrase("Waited on", "wait on", targets);
159 break;
160 }
161 case "thread-list":
162 label = phrase("Listed", "list", `threads ${times}`);
163 break;
164 case "thread-interrupt":
165 label = phrase(
166 "Requested interrupts for",
167 "interrupt",
168 quantity(countEntities(threadIds), "thread"),
169 );
170 break;
171 case "task-status":
172 label = phrase("Checked", "check", `task status ${times}`);
173 break;
174 case "task-cancel":
175 label = phrase(
176 "Requested cancellation of",
177 "cancel",
178 quantity(countEntities(entityIds("taskId")), "task"),
179 );
180 break;
181 case "schedule-create":
182 label = phrase(
183 "Scheduled",
184 "schedule",
185 quantity(countEntities(entityIds("scheduledTaskId")), "task"),
186 );
187 break;
188 case "schedule-list":
189 label = phrase("Listed", "list", `scheduled tasks ${times}`);
190 break;
191 case "schedule-update":
192 label = phrase(
193 "Updated",
194 "update",
195 quantity(countEntities(entityIds("scheduledTaskId")), "scheduled task"),
196 );
197 break;
198 case "schedule-delete":
199 // A successful delete can report deleted:false; it still represents a deletion request.
200 label = phrase(
201 "Requested deletion of",
202 "delete",
203 quantity(countEntities(entityIds("scheduledTaskId")), "scheduled task"),
204 );
205 break;
206 case "schedule-run":
207 label = phrase("Requested", "request", quantity(selected.length, "scheduled task run"));
208 break;
209 case "thread-configuration":
210 label = phrase("Checked", "check", `thread configuration ${times}`);
211 break;
212 case "thread-configure":
213 label = phrase("Set", "set", `thread model ${times}`);
214 break;
215 case "thread-fork":
216 label = phrase("Requested", "request", quantity(selected.length, "thread fork"));
217 break;
218 case "thread-merge":
219 label = phrase("Requested", "request", quantity(selected.length, "context merge"));
220 break;
221 case "thread-search":
222 label = phrase("Searched", "search", `threads ${times}`);
223 break;
224 case "thread-transfers":
225 label = phrase("Checked", "check", `thread transfers ${times}`);
226 break;
227 case "thread-organize":
228 label = phrase("Organized", "organize", `threads ${times}`);
229 break;
230 case "thread-update":
231 label = phrase("Updated", "update", quantity(countEntities(threadIds), "thread"));
232 break;
233 case "queue-list":
234 label = phrase("Listed", "list", `queued messages ${times}`);
235 break;
236 case "queue-read":
237 label = phrase(
238 "Read",
239 "read",
240 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
241 );
242 break;
243 case "queue-edit":
244 label = phrase(
245 "Edited",
246 "edit",
247 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
248 );
249 break;
250 case "queue-cancel":
251 label = phrase(
252 "Requested cancellation of",
253 "cancel",
254 quantity(countEntities(entityIds("queuedRunId")), "queued run"),
255 );
256 break;
257 case "queue-reorder":
258 label = phrase(
259 "Reordered",
260 "reorder",
261 quantity(countEntities(entityIds("queuedRunId")), "queued run"),
262 );
263 break;
264 case "queue-steer":
265 label = phrase(
266 "Requested steering with",
267 "steer with",
268 quantity(countEntities(entityIds("queuedRunId")), "queued message"),
269 );
270 break;
271 case "question-list":
272 label = phrase("Listed", "list", `pending questions ${times}`);
273 break;
274 case "question-read":
275 label = phrase(
276 "Read",
277 "read",
278 quantity(countEntities(entityIds("requestId")), "pending question request"),
279 );
280 break;
281 case "question-respond":
282 label = phrase(
283 "Answered",
284 "answer",
285 quantity(countEntities(entityIds("requestId")), "pending question request"),
286 );
287 break;
288 case "secret-request":
289 label = phrase("Asked for", "ask for", quantity(selected.length, "secret"));
290 break;
291 case "worktree-handoff":
292 label = phrase(
293 "Handed off to",
294 "hand off to",
295 quantity(countEntities(entityIds("worktreePath")), "worktree"),
296 );
297 break;
298 case "worktree-list":
299 label = phrase("Listed", "list", `workspace branches ${times}`);
300 break;
301 case "worktree-status":
302 label = phrase("Checked", "check", `worktree status ${times}`);
303 break;
304 case "project-list":
305 label = phrase("Listed", "list", `projects ${times}`);
306 break;
307 case "project-read":
308 label = phrase("Read", "read", quantity(countEntities(projectIds), "project"));
309 break;
310 case "project-create":
311 label = phrase("Registered", "register", quantity(countEntities(projectIds), "project"));
312 break;
313 case "project-update":
314 label = phrase("Updated", "update", quantity(countEntities(projectIds), "project"));
315 break;
316 case "project-delete":
317 label = phrase("Deleted", "delete", quantity(countEntities(projectIds), "project"));
318 break;
319 case "project-clone":
320 label = phrase(
321 "Cloned",
322 "clone",
323 quantity(countEntities(entityIds("cwd")), "repository", "repositories"),
324 );
325 break;
326 case "environment-read":
327 label = phrase("Checked", "check", `environment preferences ${times}`);
328 break;
329 case "environment-update":
330 label = phrase("Updated", "update", `environment preferences ${times}`);
331 break;
332 case "attachment-prepare":
333 label = phrase(
334 "Prepared",
335 "prepare",
336 quantity(countEntities(entityIds("attachmentId")), "attachment upload"),
337 );
338 break;
339 case "attachment-discard":
340 label = phrase(
341 "Discarded",
342 "discard",
343 quantity(countEntities(entityIds("attachmentId")), "pending attachment"),
344 );
345 break;
346 case "attachment-send": {
347 // A message can contain several attachments. Count retries by message identity.
348 const messages = new Map<string, (typeof selected)[number]>();
349 selected.forEach((call, index) =>
350 messages.set(id(call.output?.messageId) ?? `call-${index}`, call),
351 );
352 const attachmentCount = [...messages.values()].reduce(
353 (count, call) =>
354 count + (Array.isArray(call.input?.attachments) ? call.input.attachments.length : 0),
355 0,
356 );
357 const countsKnown = [...messages.values()].every(
358 (call) => Array.isArray(call.input?.attachments) && call.input.attachments.length > 0,
359 );
360 const targets = threadIds.every((value) => value !== undefined)
361 ? ` to ${quantity(new Set(threadIds).size, "thread")}`
362 : "";
363 label = phrase(
364 "Sent",
365 "send",
366 countsKnown
367 ? `${quantity(attachmentCount, "attachment")}${targets}`
368 : `attachments${targets} ${times}`,
369 );
370 break;
371 }
372 case "link-pr":
373 label = phrase("Linked", "link", quantity(selected.length, "pull request"));
374 break;
375 case "unlink-pr":
376 label = phrase("Unlinked", "unlink", quantity(selected.length, "pull request"));
377 break;
378 case "watch-pr":
379 label = phrase("Watching", "watch", quantity(selected.length, "pull request"));
380 break;
381 case "unwatch-pr":
382 label = phrase(
383 "Stopped watching",
384 "stop watching",
385 quantity(selected.length, "pull request"),
386 );
387 break;
388 case "list-prs":
389 label = phrase(
390 "Checked",
391 "check",
392 `linked pull requests${selected.length === 1 ? "" : ` ${times}`}`,
393 );
394 break;
395 case "browser":
396 label = phrase("Used", "use", `browser ${times}`);
397 break;
398 case "device":
399 label = phrase("Used", "use", `device controls ${times}`);
400 break;
401 case "html-preview":
402 label = phrase("Previewed", "preview", quantity(selected.length, "HTML page"));
403 break;
404 case "html-render":
405 label = phrase("Rendered", "render", quantity(selected.length, "HTML page"));
406 break;
407 case "capabilities":
408 label = phrase("Checked", "check", `orchestration capabilities ${times}`);
409 break;
410 }
411 return { label, failedCount };