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

FeedbackTrace.ts

157 lines5.9 KB

1import type { OrchestrationV2Run, OrchestrationV2TurnItem } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3​
4import { FEEDBACK_TRACE_TURNS, type FeedbackTrace, resolveT3ToolName } from "./FeedbackReport.ts";
5import { scrubFeedbackText } from "./scrubFeedback.ts";
6​
7const MAX_ENTRIES = 80;
8const MAX_TEXT_CHARS = 1_000;
9// Keeps one `agent.feedback` event small next to the 20 a telemetry batch holds.
10const FEEDBACK_TRACE_MAX_BYTES = 16_000;
11​
12export const FEEDBACK_TRACE_ITEM_TYPES = [
13 "user_message",
14 "assistant_message",
15 "dynamic_tool",
16 "command_execution",
17 "file_change",
18 "file_search",
19 "web_search",
20 "subagent",
21] as const satisfies ReadonlyArray<OrchestrationV2TurnItem["type"]>;
22​
23// Claude and Codex namespace or mark tools from other MCP servers; other harnesses name them
24// like built-ins, so there every tool that is not T3's could be one.
25const NAMES_BUILT_IN_TOOLS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
26const BUILT_IN_NAME = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/u;
27/** Every tool from the user's other MCP servers, whose names describe their setup. */
28const OTHER_TOOL = "mcp";
29​
30type Entry = FeedbackTrace["entries"][number];
31​
32const toolName = (
33 item: OrchestrationV2TurnItem,
34 t3Tools: ReadonlyArray<string>,
35 namesBuiltIns: boolean,
36): string => {
37 if (item.type === "command_execution") return "shell";
38 if (item.type !== "dynamic_tool") return item.type;
39 const name = item.toolName ?? "";
40 const t3 = resolveT3ToolName(name, t3Tools);
41 if (t3 !== undefined) return t3;
42 return namesBuiltIns &&
43 item.toolSource?.kind !== "integration" &&
44 !/^mcp/iu.test(name) &&
45 BUILT_IN_NAME.test(name)
46 ? name
47 : OTHER_TOOL;
48};
49​
50const outcome = (item: OrchestrationV2TurnItem): NonNullable<Entry["outcome"]> => {
51 if (item.status === "failed") return "error";
52 if (item.status !== "completed") return "unfinished";
53 return item.type === "command_execution" &&
54 ((item.exitCode ?? 0) !== 0 || item.outputIndicatesFailure === true)
55 ? "error"
56 : "ok";
57};
58​
59const bytes = (trace: FeedbackTrace) => Buffer.byteLength(JSON.stringify(trace));
60​
61/** Started turns outlined for a report spanning `turns`. No more than the entry cap could fit. */
62export const feedbackTraceWindow = (turns: number) =>
63 Math.min(Math.max(FEEDBACK_TRACE_TURNS, turns), MAX_ENTRIES);
64​
65/**
66 * The outline of the last few started turns: who spoke and which tools ran, with no text, input,
67 * or output. With `withText`, also the scrubbed message text of the last `turns` of them.
68 */
69export const buildFeedbackTrace = (input: {
70 readonly runs: ReadonlyArray<OrchestrationV2Run>;
71 readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
72 readonly turns: number;
73 readonly withText: boolean;
74 readonly sensitive: ReadonlyArray<string>;
75 readonly t3Tools: ReadonlyArray<string>;
76 readonly driverOf: (run: OrchestrationV2Run) => string | undefined;
77 readonly submittingRunId: OrchestrationV2Run["id"];
78}): FeedbackTrace => {
79 const window = feedbackTraceWindow(input.turns);
80 const started = input.runs
81 .filter((run) => run.startedAt !== null)
82 .toSorted((a, b) => a.ordinal - b.ordinal);
83 const runs = started.slice(-window);
84 const firstTextTurn = input.withText ? runs.length - input.turns + 1 : Infinity;
85 const turnOf = new Map(runs.map((run, index) => [run.id, { turn: index + 1, run }] as const));
86 // The `t3_feedback` call making this report is still running; listed, it reads as a hung call.
87 const submitting = (item: OrchestrationV2TurnItem) =>
88 item.runId === input.submittingRunId &&
89 item.type === "dynamic_tool" &&
90 outcome(item) === "unfinished" &&
91 resolveT3ToolName(item.toolName ?? "", input.t3Tools) === "t3_feedback";
92 // Asked for more turns than the window holds, in a thread long enough to have them.
93 let truncated = input.turns > window && started.length >= window;
94 const entries = input.items
95 .filter(
96 (item) =>
97 item.parentItemId === null &&
98 item.runId !== null &&
99 turnOf.has(item.runId) &&
100 !submitting(item),
101 )
102 .map((item) => ({ item, ...turnOf.get(item.runId!)! }))
103 .toSorted((a, b) => a.turn - b.turn || a.item.ordinal - b.item.ordinal)
104 .map(({ item, turn, run }): Entry => {
105 if (item.type === "user_message" || item.type === "assistant_message") {
106 const length = Array.from(item.text).length;
107 const message: Entry = {
108 turn,
109 type: item.type === "user_message" ? "user" : "assistant",
110 length,
111 };
112 if (turn < firstTextTurn) return message;
113 const { text, cut } = scrubFeedbackText(item.text, input.sensitive, MAX_TEXT_CHARS);
114 if (cut) truncated = true;
115 return { ...message, text };
116 }
117 const started = item.startedAt;
118 const completed = item.completedAt;
119 return {
120 turn,
121 type: "tool",
122 tool: toolName(item, input.t3Tools, NAMES_BUILT_IN_TOOLS.has(input.driverOf(run) ?? "")),
123 outcome: outcome(item),
124 ...(started !== null && completed !== null
125 ? {
126 durationMs: Math.max(
127 0,
128 DateTime.toEpochMillis(completed) - DateTime.toEpochMillis(started),
129 ),
130 }
131 : {}),
132 };
133 });
134​
135 // Tool calls go first, oldest first, so the messages of every turn stay.
136 while (entries.length > MAX_ENTRIES) {
137 const tool = entries.findIndex((entry) => entry.type === "tool");
138 entries.splice(tool === -1 ? 0 : tool, 1);
139 truncated = true;
140 }
141 const trace = (): FeedbackTrace => ({
142 turns: runs.length,
143 textTurns: new Set(entries.filter((entry) => entry.text !== undefined).map((e) => e.turn)).size,
144 truncated,
145 entries,
146 });
147 while (bytes(trace()) > FEEDBACK_TRACE_MAX_BYTES) {
148 truncated = true;
149 const withText = entries.findIndex((entry) => entry.text !== undefined);
150 if (withText === -1) entries.shift();
151 else {
152 const { text: _dropped, ...rest } = entries[withText]!;
153 entries[withText] = rest;
154 }
155 }
156 return trace();
157};