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