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

ProviderDimensions.ts

281 lines9.9 KB

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