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