Open History to see the last commit
1import type {
2 ModelSelection,
3 OrchestrationV2ThreadShell,
4 ServerProvider,
5} from "@t3tools/contracts";
6
7import { BUNDLED_MODEL_MANIFEST } from "../provider/ModelManifest.ts";
8
9export interface ProviderDimensions {
10 readonly provider: string;
11 readonly model?: string;
12}
13
14/**
15 * Anonymous provider and model for a model selection. Instance ids are
16 * user-defined, so only the driver kind is reported.
17 */
18export function providerDimensions(
19 providers: ReadonlyArray<ServerProvider>,
20 selection: Pick<ModelSelection, "instanceId" | "model">,
21): ProviderDimensions {
22 const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
23 if (provider === undefined) return { provider: "unknown" };
24 if (selection.model === "") return { provider: provider.driver };
25 return {
26 provider: provider.driver,
27 model: modelLabel(providers, provider.driver, selection.model),
28 };
29}
30
31const DATED_SNAPSHOT = /-\d{8}$/u;
32// Some agents report the model they ran with the effort level appended, as in `gemini-4-neon-low`.
33const EFFORT_SUFFIX = /-(?:minimal|low|medium|high|xhigh|max)$/u;
34
35const MANIFEST_LABELS: ReadonlyMap<string, string> = new Map(
36 Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) =>
37 catalog.models.flatMap((model) =>
38 [model.slug, ...(model.aliases ?? [])].map((name) => [name, model.slug] as const),
39 ),
40 ),
41);
42
43// Drivers whose model lists come from the vendor. OpenCode, Pi, fx, and ACP agents list
44// the user's own configuration, such as local Ollama tags or GGUF paths.
45const VENDOR_CATALOG_DRIVERS: ReadonlySet<string> = new Set([
46 "codex",
47 "claudeAgent",
48 "cursor",
49 "grok",
50 "antigravity",
51 "kiro",
52 "muse",
53]);
54
55// A custom endpoint, gateway, or Bedrock serves whatever names its owner chose.
56const listsVendorModels = ({ driver, auth }: ServerProvider) =>
57 VENDOR_CATALOG_DRIVERS.has(driver) &&
58 auth.endpoint === undefined &&
59 auth.type !== "customEndpoint" &&
60 auth.type !== "bedrock";
61
62/**
63 * The model name analytics reports. A routed id, alias, or dated snapshot that the
64 * bundled manifest or a vendor's own model list knows, such as `anthropic/claude-opus-5-5`
65 * or `antigravity-default`, maps to its catalog slug. Any other id can name a user, a
66 * deployment, or a local file, so it reports only the driver as `custom:<driver>`.
67 */
68export function modelLabel(
69 providers: ReadonlyArray<ServerProvider>,
70 driver: string,
71 model: string,
72): string {
73 return catalogSlug(providers, model) ?? `custom:${driver}`;
74}
75
76function catalogSlug(providers: ReadonlyArray<ServerProvider>, model: string) {
77 const leaf = model.slice(model.lastIndexOf("/") + 1);
78 const candidates = [
79 model,
80 leaf,
81 leaf.replace(DATED_SNAPSHOT, ""),
82 leaf.replace(EFFORT_SUFFIX, ""),
83 ];
84 for (const candidate of candidates) {
85 const label = MANIFEST_LABELS.get(candidate);
86 if (label !== undefined) return label;
87 }
88 for (const provider of providers) {
89 if (!listsVendorModels(provider)) continue;
90 const match = provider.models.find(
91 (entry) =>
92 !entry.isCustom &&
93 (candidates.includes(entry.slug) ||
94 entry.aliases?.some((alias) => candidates.includes(alias)) === true),
95 );
96 if (match !== undefined) return match.slug;
97 }
98 return undefined;
99}
100
101/** The thread fields agent analytics reads. Ids are used for lookups, never reported. */
102export type AgentThread = Pick<
103 OrchestrationV2ThreadShell,
104 "modelSelection" | "runtimeMode" | "interactionMode" | "createdBy" | "creationSource" | "lineage"
105>;
106
107type Fields = Readonly<Record<string, unknown>>;
108
109const asFields = (value: unknown): Fields =>
110 typeof value === "object" && value !== null ? (value as Fields) : {};
111
112const stringField = (fields: Fields, key: string) =>
113 typeof fields[key] === "string" ? (fields[key] as string) : undefined;
114
115/** A string from the tool input only when it is one of the schema's literals. */
116const oneOf = (value: string | undefined, allowed: ReadonlyArray<string>) =>
117 value !== undefined && allowed.includes(value) ? value : undefined;
118
119/**
120 * Whether two resolved providers differ. Unresolved selections compare as
121 * unknown rather than as a cross-provider handoff.
122 */
123export const crossProvider = (caller: string, target: string) =>
124 caller === "unknown" || target === "unknown" ? undefined : caller !== target;
125
126const defined = (entries: Readonly<Record<string, unknown>>) =>
127 Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== undefined));
128
129/**
130 * How deep a thread sits in a delegation tree: 0 for a top-level thread, 1 for
131 * its subagent, and so on. Forks are top-level threads of their own. Depth is
132 * counted by walking parents, capped so a corrupt lineage cannot loop.
133 */
134export const MAX_REPORTED_DEPTH = 5;
135
136/**
137 * Who started the work that made this call. Scheduled runs keep the task
138 * creator's provenance, so the run's message marks them instead.
139 */
140function callerOrigin(input: {
141 readonly thread: Pick<AgentThread, "createdBy">;
142 readonly scheduledRun: boolean;
143}) {
144 if (input.scheduledRun) return "scheduler";
145 if (input.thread.createdBy === "agent") return "agent";
146 return input.thread.createdBy === "system" ? "system" : "user";
147}
148
149/**
150 * Settings for a handoff, recorded only as closed enums and booleans derived
151 * from the tool's arguments and result. Prompts, titles, and ids are never
152 * recorded.
153 */
154export function handoffSettings(tool: string, args: unknown, result: unknown): Fields {
155 const input = asFields(args);
156 const output = asFields(result);
157 switch (tool) {
158 case "delegate_task":
159 return defined({
160 targetChosen: input.target !== undefined,
161 // Rejected calls are recorded too, so input strings must match a literal.
162 mode: oneOf(stringField(input, "mode"), ["async", "wait"]) ?? "async",
163 ...(output.waitTimedOut === true ? { waitTimedOut: true } : {}),
164 });
165 case "create_threads": {
166 const threads = Array.isArray(input.threads) ? input.threads : [];
167 return {
168 batchSize: threads.length,
169 targetChosen: threads.some((thread) => asFields(thread).target !== undefined),
170 };
171 }
172 case "t3_thread_launch":
173 return defined({
174 targetChosen: input.modelSelection !== undefined,
175 workspace:
176 input.scratch === true
177 ? "scratch"
178 : (oneOf(stringField(asFields(input.workspaceStrategy), "type"), [
179 "root",
180 "worktree",
181 "existing_worktree",
182 ]) ?? "root"),
183 });
184 case "t3_thread_send":
185 return defined({
186 delivery: oneOf(stringField(output, "delivery"), [
187 "started",
188 "queued",
189 "steered",
190 "restarted",
191 ]),
192 });
193 case "t3_thread_send_attachments":
194 return { delivery: "auto" };
195 case "schedule_task": {
196 // Omitting the input lets the server decide, so read the saved task.
197 const bound = output.boundThreadId;
198 return bound === null || typeof bound === "string"
199 ? { bindToCurrentThread: bound !== null }
200 : {};
201 }
202 default:
203 return {};
204 }
205}
206
207const ERROR_CODE_SHAPE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
208
209/** Outcome of a tool call, with the stable failure code when the call failed. */
210export function toolOutcome(
211 result:
212 | { readonly isError?: boolean | undefined; readonly structuredContent?: unknown }
213 | undefined,
214) {
215 if (result === undefined) return { outcome: "error", errorCode: "exception" };
216 const content = asFields(result.structuredContent);
217 // T3 tool failures are declared errors whose structured content carries a
218 // closed `code`; the MCP layer does not always set isError for them.
219 const code = stringField(content, "code") ?? stringField(asFields(content.error), "_tag");
220 if (result.isError === true || (content._tag !== undefined && code !== undefined)) {
221 // Codes and tags are identifiers; anything else may be a message or a value, which stays in
222 // local traces rather than analytics.
223 return {
224 outcome: "error",
225 errorCode: code !== undefined && ERROR_CODE_SHAPE.test(code) ? code : "unknown",
226 };
227 }
228 return { outcome: "ok" };
229}
230
231/**
232 * Event properties for an agent tool call: the calling agent, and when the call
233 * handed work to other threads, the agents running them. Each target counts
234 * once, so a create_threads batch on two providers reports both.
235 */
236export function agentToolProperties(input: {
237 readonly tool: string;
238 readonly providers: ReadonlyArray<ServerProvider>;
239 readonly caller: AgentThread | undefined;
240 readonly callerProviderInstanceId?: ModelSelection["instanceId"];
241 readonly callerDepth?: number;
242 readonly callerScheduledRun?: boolean;
243 readonly targets: ReadonlyArray<AgentThread>;
244 readonly outcome: Fields;
245 readonly settings?: Fields;
246 readonly durationMs?: number;
247}): ReadonlyArray<Readonly<Record<string, unknown>>> {
248 const caller =
249 input.caller !== undefined
250 ? providerDimensions(input.providers, input.caller.modelSelection)
251 : input.callerProviderInstanceId !== undefined
252 ? {
253 provider: providerDimensions(input.providers, {
254 instanceId: input.callerProviderInstanceId,
255 model: "",
256 }).provider,
257 }
258 : { provider: "unknown" };
259 const base = defined({
260 tool: input.tool,
261 callerProvider: caller.provider,
262 callerModel: caller.model,
263 callerOrigin:
264 input.caller === undefined
265 ? undefined
266 : callerOrigin({
267 thread: input.caller,
268 scheduledRun: input.callerScheduledRun === true,
269 }),
270 callerDepth:
271 input.callerDepth === undefined ? undefined : Math.min(input.callerDepth, MAX_REPORTED_DEPTH),
272 durationMs: input.durationMs,
273 ...input.outcome,
274 ...input.settings,
275 });
276 if (input.targets.length === 0) return [base];
277 return input.targets.map((thread) => {
278 const target = providerDimensions(input.providers, thread.modelSelection);
279 return defined({
280 ...base,
281 targetProvider: target.provider,
282 targetModel: target.model,
283 targetRuntimeMode: thread.runtimeMode,
284 targetInteractionMode: thread.interactionMode,
285 crossProvider: crossProvider(caller.provider, target.provider),
286 });
287 });
288}