@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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