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