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

ProviderDimensions.ts

210 lines7.7 KB

1import type {
2 ModelSelection,
3 OrchestrationV2ThreadShell,
4 ServerProvider,
5} from "@t3tools/contracts";
6​
7/**
8 * Drivers whose model catalogs are published by the vendor. Other drivers
9 * (OpenCode, Pi, ACP agents) list models from the user's own configuration,
10 * such as local Ollama tags, so their model names stay out of analytics.
11 */
12const VENDOR_CATALOG_DRIVERS: ReadonlySet<string> = new Set([
13 "codex",
14 "claudeAgent",
15 "cursor",
16 "grok",
17 "antigravity",
18]);
19​
20export interface ProviderDimensions {
21 readonly provider: string;
22 readonly model?: string;
24​
25/**
26 * Anonymous provider and model for a model selection. Instance ids are
27 * user-defined, so only the driver kind is reported. The model is reported
28 * only when it comes from a vendor catalog and is not a user-added custom model.
29 */
30export function providerDimensions(
31 providers: ReadonlyArray<ServerProvider>,
32 selection: Pick<ModelSelection, "instanceId" | "model">,
33): ProviderDimensions {
34 const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
35 if (provider === undefined) return { provider: "unknown" };
36 const model = provider.models.find((candidate) => candidate.slug === selection.model);
37 return VENDOR_CATALOG_DRIVERS.has(provider.driver) && model !== undefined && !model.isCustom
38 ? { provider: provider.driver, model: model.slug }
39 : { provider: provider.driver };
41​
42/** The thread fields agent analytics reads. Ids are used for lookups, never reported. */
43export type AgentThread = Pick<
44 OrchestrationV2ThreadShell,
45 "modelSelection" | "runtimeMode" | "interactionMode" | "createdBy" | "creationSource" | "lineage"
46>;
47​
48type Fields = Readonly<Record<string, unknown>>;
49​
50const asFields = (value: unknown): Fields =>
51 typeof value === "object" && value !== null ? (value as Fields) : {};
52​
53const stringField = (fields: Fields, key: string) =>
54 typeof fields[key] === "string" ? (fields[key] as string) : undefined;
55​
56/** A string from the tool input only when it is one of the schema's literals. */
57const oneOf = (value: string | undefined, allowed: ReadonlyArray<string>) =>
58 value !== undefined && allowed.includes(value) ? value : undefined;
59​
60/**
61 * Whether two resolved providers differ. Unresolved selections compare as
62 * unknown rather than as a cross-provider handoff.
63 */
64export const crossProvider = (caller: string, target: string) =>
65 caller === "unknown" || target === "unknown" ? undefined : caller !== target;
66​
67const defined = (entries: Readonly<Record<string, unknown>>) =>
68 Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== undefined));
69​
70/**
71 * How deep a thread sits in a delegation tree: 0 for a top-level thread, 1 for
72 * its subagent, and so on. Forks are top-level threads of their own. Depth is
73 * counted by walking parents, capped so a corrupt lineage cannot loop.
74 */
75export const MAX_REPORTED_DEPTH = 5;
76​
77/**
78 * Who started the work that made this call. Scheduled runs keep the task
79 * creator's provenance, so the run's message marks them instead.
80 */
81export function callerOrigin(input: {
82 readonly thread: Pick<AgentThread, "createdBy">;
83 readonly scheduledRun: boolean;
84}) {
85 if (input.scheduledRun) return "scheduler";
86 if (input.thread.createdBy === "agent") return "agent";
87 return input.thread.createdBy === "system" ? "system" : "user";
89​
90/**
91 * Settings the agent chose for a handoff, read only from closed enums and
92 * booleans in the tool's arguments and result. Prompts, titles, and ids are
93 * never read.
94 */
95export function handoffSettings(tool: string, args: unknown, result: unknown): Fields {
96 const input = asFields(args);
97 const output = asFields(result);
98 switch (tool) {
99 case "delegate_task":
100 return defined({
101 targetChosen: input.target !== undefined,
102 // Rejected calls are recorded too, so input strings must match a literal.
103 mode: oneOf(stringField(input, "mode"), ["async", "wait"]) ?? "async",
104 ...(output.waitTimedOut === true ? { waitTimedOut: true } : {}),
105 });
106 case "create_threads": {
107 const threads = Array.isArray(input.threads) ? input.threads : [];
108 return {
109 batchSize: threads.length,
110 targetChosen: threads.some((thread) => asFields(thread).target !== undefined),
111 };
112 }
113 case "t3_thread_launch":
114 return defined({
115 targetChosen: input.modelSelection !== undefined,
116 workspace:
117 input.scratch === true
118 ? "scratch"
119 : (oneOf(stringField(asFields(input.workspaceStrategy), "type"), [
120 "root",
121 "worktree",
122 "existing_worktree",
123 ]) ?? "root"),
124 });
125 case "t3_thread_send":
126 return defined({ delivery: stringField(output, "delivery") });
127 case "t3_thread_send_attachments":
128 return { delivery: "auto" };
129 case "schedule_task":
130 return { bindToCurrentThread: input.bindToCurrentThread !== false };
131 default:
132 return {};
133 }
135​
136/** Outcome of a tool call, with the stable failure code when the call failed. */
137export function toolOutcome(
138 result:
139 | { readonly isError?: boolean | undefined; readonly structuredContent?: unknown }
140 | undefined,
141) {
142 if (result === undefined) return { outcome: "error", errorCode: "exception" };
143 const content = asFields(result.structuredContent);
144 // T3 tool failures are declared errors whose structured content carries a
145 // closed `code`; the MCP layer does not always set isError for them.
146 const code = stringField(content, "code") ?? stringField(asFields(content.error), "_tag");
147 if (result.isError === true || (content._tag !== undefined && code !== undefined)) {
148 return { outcome: "error", errorCode: code ?? "unknown" };
149 }
150 return { outcome: "ok" };
152​
153/**
154 * Event properties for an agent tool call: the calling agent, and when the call
155 * handed work to other threads, the agents running them. Each target counts
156 * once, so a create_threads batch on two providers reports both.
157 */
158export function agentToolProperties(input: {
159 readonly tool: string;
160 readonly providers: ReadonlyArray<ServerProvider>;
161 readonly caller: AgentThread | undefined;
162 readonly callerProviderInstanceId?: ModelSelection["instanceId"];
163 readonly callerDepth?: number;
164 readonly callerScheduledRun?: boolean;
165 readonly targets: ReadonlyArray<AgentThread>;
166 readonly outcome: Fields;
167 readonly settings?: Fields;
168 readonly durationMs?: number;
169}): ReadonlyArray<Readonly<Record<string, unknown>>> {
170 const caller =
171 input.caller !== undefined
172 ? providerDimensions(input.providers, input.caller.modelSelection)
173 : input.callerProviderInstanceId !== undefined
174 ? {
175 provider: providerDimensions(input.providers, {
176 instanceId: input.callerProviderInstanceId,
177 model: "",
178 }).provider,
179 }
180 : { provider: "unknown" };
181 const base = defined({
182 tool: input.tool,
183 callerProvider: caller.provider,
184 callerModel: caller.model,
185 callerOrigin:
186 input.caller === undefined
187 ? undefined
188 : callerOrigin({
189 thread: input.caller,
190 scheduledRun: input.callerScheduledRun === true,
191 }),
192 callerDepth:
193 input.callerDepth === undefined ? undefined : Math.min(input.callerDepth, MAX_REPORTED_DEPTH),
194 durationMs: input.durationMs,
195 ...input.outcome,
196 ...input.settings,
197 });
198 if (input.targets.length === 0) return [base];
199 return input.targets.map((thread) => {
200 const target = providerDimensions(input.providers, thread.modelSelection);
201 return defined({
202 ...base,
203 targetProvider: target.provider,
204 targetModel: target.model,
205 targetRuntimeMode: thread.runtimeMode,
206 targetInteractionMode: thread.interactionMode,
207 crossProvider: crossProvider(caller.provider, target.provider),
208 });
209 });