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