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

mcpInjection.ts

316 lines9.5 KB

1import { tokenizeCliArgs } from "@t3tools/shared/cliArgs";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4​
5import type { McpProviderSessionConfig } from "@t3tools/provider-core/server/mcpSession";
6import {
7 PI_T3_MCP_EXTENSION_FILENAME,
8 PI_T3_MCP_EXTENSION_SOURCE,
9 T3_MCP_BEARER_ENV,
10 T3_MCP_URL_ENV,
11 T3_PI_RUNTIME_MODE_ENV,
12} from "./mcpExtensionSource.ts";
13​
14const RESERVED_PI_LAUNCH_ARGUMENTS = new Set([
15 "--continue",
16 "-c",
17 "--export",
18 "--fork",
19 "--help",
20 "-h",
21 "--list-models",
22 "--mode",
23 "--no-session",
24 "--print",
25 "-p",
26 "--resume",
27 "-r",
28 "--session",
29 "--session-id",
30 "--version",
31 "-v",
32]);
33​
34const PI_ARGUMENTS_WITH_VALUES = new Set([
35 "--api-key",
36 "--append-system-prompt",
37 "--exclude-tools",
38 "-xt",
39 "--extension",
40 "-e",
41 "--model",
42 "--models",
43 "--name",
44 "-n",
45 "--prompt-template",
46 "--provider",
47 "--session-dir",
48 "--skill",
49 "--system-prompt",
50 "--theme",
51 "--thinking",
52 "--tools",
53 "-t",
54 "--tui-mode",
55 "--use-theme",
56]);
57​
58const PI_ARGUMENTS_WITHOUT_VALUES = new Set([
59 "--approve",
60 "-a",
61 "--no-approve",
62 "-na",
63 "--no-builtin-tools",
64 "-nbt",
65 "--no-context-files",
66 "-nc",
67 "--no-extensions",
68 "-ne",
69 "--no-prompt-templates",
70 "-np",
71 "--no-skills",
72 "-ns",
73 "--no-themes",
74 "--no-tools",
75 "-nt",
76 "--offline",
77 "--verbose",
78]);
79​
80export type PiLaunchArgsResolution =
81 | { readonly ok: true; readonly args: ReadonlyArray<string> }
82 | { readonly ok: false; readonly message: string };
83​
84function reservedPiArgument(arg: string): string | undefined {
85 for (const reserved of RESERVED_PI_LAUNCH_ARGUMENTS) {
86 if (arg === reserved || (reserved.startsWith("--") && arg.startsWith(`${reserved}=`))) {
87 return reserved;
88 }
89 }
90 return undefined;
92​
93function normalizePiBuiltInEqualsArguments(args: ReadonlyArray<string>): ReadonlyArray<string> {
94 return args.flatMap((arg) => {
95 const equalsIndex = arg.indexOf("=");
96 if (equalsIndex <= 0) return [arg];
97 const option = arg.slice(0, equalsIndex);
98 return PI_ARGUMENTS_WITH_VALUES.has(option) ? [option, arg.slice(equalsIndex + 1)] : [arg];
99 });
101​
102/**
103 * Pi launch arguments may configure resources, models, tools, trust, and
104 * storage. T3 owns RPC mode and session identity, so arguments that select a
105 * different execution mode or native session are rejected before spawn.
106 */
107export function resolvePiLaunchArgs(launchArgs: string): PiLaunchArgsResolution {
108 // Pi parses equals-form tokens only as extension flags, even when their name
109 // matches a built-in option. Split known built-ins while leaving arbitrary
110 // extension flags in their native form.
111 const args = normalizePiBuiltInEqualsArguments(tokenizeCliArgs(launchArgs));
112 let hasProvider = false;
113 let hasModel = false;
114 for (let index = 0; index < args.length; index += 1) {
115 const arg = args[index];
116 if (arg === undefined) continue;
117 const reserved = reservedPiArgument(arg);
118 if (reserved !== undefined) {
119 return {
120 ok: false,
121 message: `Pi launch argument '${reserved}' is controlled by T3 Code and cannot be overridden.`,
122 };
123 }
124 if (arg === "--") {
125 return {
126 ok: false,
127 message: "Pi launch arguments cannot include positional prompts.",
128 };
129 }
130 if (PI_ARGUMENTS_WITH_VALUES.has(arg)) {
131 const value = args[index + 1];
132 if (value === undefined) {
133 return { ok: false, message: `Pi launch argument '${arg}' requires a value.` };
134 }
135 if (arg === "--provider") hasProvider = true;
136 if (arg === "--model") hasModel = true;
137 index += 1;
138 continue;
139 }
140 if (PI_ARGUMENTS_WITHOUT_VALUES.has(arg) || (arg.startsWith("--") && arg.includes("="))) {
141 continue;
142 }
143 if (arg.startsWith("--")) {
144 // Pi extensions may register arbitrary long flags. Treat one following
145 // non-flag token as that extension flag's value.
146 if (
147 args[index + 1] !== undefined &&
148 !args[index + 1]!.startsWith("-") &&
149 !args[index + 1]!.startsWith("@")
150 ) {
151 index += 1;
152 }
153 continue;
154 }
155 if (arg.startsWith("-")) {
156 return { ok: false, message: `Pi launch argument '${arg}' is not supported by T3 Code.` };
157 }
158 return {
159 ok: false,
160 message: `Pi launch arguments cannot include positional prompt '${arg}'.`,
161 };
162 }
163 // Pi 1.0 exits at startup on `--provider` without `--model`; older versions
164 // silently ran another provider's default model. Rejecting it here makes
165 // every spawn site report the reason instead of a bare exit code.
166 if (hasProvider && !hasModel) {
167 return { ok: false, message: "Pi launch argument '--provider' requires '--model'." };
168 }
169 return { ok: true, args };
171​
172function bearerTokenFromAuthorizationHeader(header: string): string {
173 return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : header;
175​
176function normalizedPiPath(value: string): string {
177 return value.replace(/\\/g, "/").replace(/\/+$/, "");
179​
180function hasExplicitExtension(args: ReadonlyArray<string>, extensionPath: string): boolean {
181 const wanted = normalizedPiPath(extensionPath);
182 for (let index = 0; index < args.length; index += 1) {
183 const arg = args[index];
184 if (arg !== "--extension" && arg !== "-e") continue;
185 const configured = args[index + 1];
186 if (configured !== undefined && normalizedPiPath(configured) === wanted) return true;
187 index += 1;
188 }
189 return false;
191​
192function withoutExplicitExtensions(args: ReadonlyArray<string>): ReadonlyArray<string> {
193 const filtered: string[] = [];
194 for (let index = 0; index < args.length; index += 1) {
195 const arg = args[index];
196 if (arg === undefined) continue;
197 if (arg === "--extension" || arg === "-e") {
198 index += 1;
199 continue;
200 }
201 if (arg.startsWith("--extension=") || arg.startsWith("-e=")) continue;
202 filtered.push(arg);
203 }
204 return filtered;
206​
207function withoutToolSelectionArgs(args: ReadonlyArray<string>): ReadonlyArray<string> {
208 const filtered: string[] = [];
209 for (let index = 0; index < args.length; index += 1) {
210 const arg = args[index];
211 if (arg === undefined) continue;
212 if (arg === "--tools" || arg === "-t" || arg === "--exclude-tools" || arg === "-xt") {
213 index += 1;
214 continue;
215 }
216 if (
217 arg === "--no-tools" ||
218 arg === "-nt" ||
219 arg === "--no-builtin-tools" ||
220 arg === "-nbt" ||
221 arg.startsWith("--tools=") ||
222 arg.startsWith("-t=") ||
223 arg.startsWith("--exclude-tools=") ||
224 arg.startsWith("-xt=")
225 ) {
226 continue;
227 }
228 filtered.push(arg);
229 }
230 return filtered;
232​
233function piT3McpExtensionDestPath(cacheDir: string): string {
234 return `${cacheDir.replace(/\\/g, "/")}/${PI_T3_MCP_EXTENSION_FILENAME}`;
236​
237export const materializePiT3McpExtension = Effect.fn("materializePiT3McpExtension")(function* (
238 cacheDir: string,
239) {
240 const fs = yield* FileSystem.FileSystem;
241 yield* fs.makeDirectory(cacheDir, { recursive: true });
242 const dest = piT3McpExtensionDestPath(cacheDir);
243 const existing = yield* fs.readFileString(dest).pipe(Effect.orElseSucceed(() => ""));
244 if (existing !== PI_T3_MCP_EXTENSION_SOURCE) {
245 yield* fs.writeFileString(dest, PI_T3_MCP_EXTENSION_SOURCE);
246 }
247 return dest;
248});
249​
250export function buildPiRpcLaunch(input: {
251 readonly launchArgs: ReadonlyArray<string>;
252 readonly environment: NodeJS.ProcessEnv;
253 readonly mcpSession: McpProviderSessionConfig | undefined;
254 readonly extensionPath: string | undefined;
255 readonly ephemeral?: boolean;
256 readonly disableExtensions?: boolean;
257 readonly disableTools?: boolean;
258 readonly runtimeMode?: "approval-required" | "auto-accept-edits" | "auto" | "full-access";
259}): {
260 readonly args: ReadonlyArray<string>;
261 readonly env: NodeJS.ProcessEnv;
262 readonly hasT3Mcp: boolean;
263} {
264 const hasT3Extension = input.disableExtensions !== true && input.extensionPath !== undefined;
265 const hasT3Mcp = hasT3Extension && input.mcpSession !== undefined;
266 const extensionSafeArgs =
267 input.disableExtensions === true
268 ? withoutExplicitExtensions(input.launchArgs)
269 : input.launchArgs;
270 const launchArgs =
271 input.disableTools === true ? withoutToolSelectionArgs(extensionSafeArgs) : extensionSafeArgs;
272 const args = [
273 "--mode",
274 "rpc",
275 ...(input.ephemeral === true ? ["--no-session"] : []),
276 ...launchArgs,
277 // Restrictions follow user launch args so a configured --tools or
278 // --extension cannot silently re-enable unattended text-generation code.
279 ...(input.disableExtensions === true ? ["--no-extensions"] : []),
280 ...(input.disableTools === true ? ["--no-tools"] : []),
281 ];
282 if (
283 hasT3Extension &&
284 input.extensionPath !== undefined &&
285 !hasExplicitExtension(args, input.extensionPath)
286 ) {
287 args.push("--extension", input.extensionPath);
288 }
289 const environment = { ...input.environment };
290 // These values belong to the current T3 session. Never let a Pi child reuse
291 // credentials inherited from the server or a parent provider process.
292 delete environment[T3_MCP_URL_ENV];
293 delete environment[T3_MCP_BEARER_ENV];
294​
295 return {
296 args,
297 env: {
298 ...environment,
299 ...(hasT3Extension && input.runtimeMode !== undefined
300 ? {
301 [T3_PI_RUNTIME_MODE_ENV]:
302 input.runtimeMode === "auto" ? "approval-required" : input.runtimeMode,
303 }
304 : {}),
305 ...(hasT3Mcp && input.mcpSession !== undefined
306 ? {
307 [T3_MCP_URL_ENV]: input.mcpSession.endpoint,
308 [T3_MCP_BEARER_ENV]: bearerTokenFromAuthorizationHeader(
309 input.mcpSession.authorizationHeader,
310 ),
311 }
312 : {}),
313 },
314 hasT3Mcp,
315 };