@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, 06:00 UTC

main
ts 424 lines 14.4 KB
Raw
1 import { readFileSync } from "node:fs";
2 import { Command, Flag } from "effect/cli";
3 import * as Argument from "effect/cli/Argument";
4 import * as Clock from "effect/Clock";
5 import * as ConfigProvider from "effect/ConfigProvider";
6 import * as Console from "effect/Console";
7 import * as Effect from "effect/Effect";
8 import * as Match from "effect/Match";
9 import * as Option from "effect/Option";
10 import * as Redacted from "effect/Redacted";
11 import * as Alchemist from "../../../Alchemist/index.ts";
12 import { getEnv } from "../../../Auth/Env.ts";
13 import { resolveProfileName } from "../../../Auth/Resolve.ts";
14 import * as Interaction from "../../../Interaction.ts";
15 import { loadConfigProvider } from "../../../Util/ConfigProvider.ts";
16 import { formatElapsed } from "../../Format.ts";
17 import { exitDeclined, failWithHelp, UserInputError } from "../errors.ts";
18 import { config, envFile, profile, yes } from "../flags.ts";
19 import { instrumentCommand } from "../instrument.ts";
20 import {
21 deleteProfileFlow,
22 editProfileFlow,
23 profileTui,
24 renameProfileFlow,
25 showProfileFlow,
26 } from "./flows.ts";
27 import { profileHub } from "./hub.ts";
28
29 const profileName = Argument.String("name").pipe(Argument.withDescription("Profile name"));
30
31 const newProfileName = Argument.String("new-name").pipe(
32 Argument.withDescription("New profile name"),
33 Argument.optional,
34 );
35
36 const refreshProviders = Flag.String("provider").pipe(
37 Flag.withDescription("Refresh only this connected provider (repeatable; defaults to all)"),
38 Flag.atLeast(0),
39 );
40
41 const showCommand = Command.make(
42 "show",
43 { profile, envFile, main: config },
44 instrumentCommand("profile.show", (a: { profile: string | undefined }) => ({
45 "alchemy.profile": a.profile ?? "",
46 }))(
47 Effect.fn(function* ({ profile, envFile, main }) {
48 const activeProfile = yield* resolveProfileName(envFile, undefined);
49 const profileName = profile ?? activeProfile;
50 yield* showProfileFlow({
51 profileName,
52 activeProfile,
53 envFile,
54 main,
55 });
56 }),
57 ),
58 ).pipe(
59 Command.withDescription("Show connected providers, authentication status, and account details"),
60 );
61
62 const listCommand = Command.make(
63 "list",
64 { envFile },
65 instrumentCommand("profile.list")(
66 Effect.fn(function* () {
67 const entries = yield* Alchemist.Profile.list();
68 const cli = yield* Interaction.Interaction;
69 if (cli.terminal.input) {
70 const { profileListNode } = yield* profileTui;
71 yield* cli.output.print(profileListNode(entries));
72 } else {
73 yield* Console.log(
74 [
75 `Profiles (${entries.length})`,
76 ...entries.map((entry) => {
77 const providers = entry.providers
78 .map(({ name, method }) => `${name} (${method})`)
79 .join(", ");
80 return `${entry.active ? "*" : "-"} ${entry.name}${providers === "" ? "" : `: ${providers}`}`;
81 }),
82 ].join("\n"),
83 );
84 }
85 }),
86 ),
87 ).pipe(Command.withDescription("List profiles and their connected providers"));
88
89 const createCommand = Command.make(
90 "create",
91 { name: profileName },
92 instrumentCommand("profile.create", (a: { name: string }) => ({
93 "alchemy.profile": a.name,
94 }))(
95 Effect.fn(function* ({ name }) {
96 yield* Alchemist.Profile.create({ name });
97 yield* Interaction.success(
98 `Created profile '${name}'. Run \`alchemy profile edit --profile ${name}\` to connect accounts.`,
99 );
100 }),
101 ),
102 ).pipe(Command.withDescription("Create an empty authentication profile"));
103
104 const renameCommand = Command.make(
105 "rename",
106 { name: profileName, newName: newProfileName },
107 instrumentCommand("profile.rename", (a: { name: string; newName: Option.Option<string> }) => ({
108 "alchemy.profile": a.name,
109 "alchemy.profile.new_name": Option.getOrUndefined(a.newName) ?? "",
110 }))(
111 Effect.fn(function* ({ name, newName }) {
112 if (Option.isSome(newName)) {
113 yield* Alchemist.Profile.rename({
114 name,
115 newName: newName.value.trim(),
116 });
117 yield* Interaction.success(`Renamed profile '${name}' to '${newName.value.trim()}'.`);
118 return;
119 }
120 yield* renameProfileFlow(name, undefined);
121 }),
122 ),
123 ).pipe(Command.withDescription("Rename a profile and move all credentials stored for it"));
124
125 const addProviders = Flag.String("add").pipe(
126 Flag.withDescription("Connect a provider to the profile (repeatable)"),
127 Flag.atLeast(0),
128 );
129
130 const reconfigureProviders = Flag.String("reconfigure").pipe(
131 Flag.withDescription("Re-run a connected provider's configuration (repeatable)"),
132 Flag.atLeast(0),
133 );
134
135 const removeProviders = Flag.String("remove").pipe(
136 Flag.withDescription("Log out a connected provider and disconnect it (repeatable)"),
137 Flag.atLeast(0),
138 );
139
140 const methodFlag = Flag.String("method").pipe(
141 Flag.withDescription(
142 "Configure non-interactively using this method (each provider documents its methods and fields in `alchemy profile edit --help`)",
143 ),
144 Flag.optional,
145 Flag.map(Option.getOrUndefined),
146 );
147
148 const setFlag = Flag.String("set").pipe(
149 Flag.withDescription(
150 "Field for non-interactive configure: name=value, name=env:VAR, or name=- to read the value from stdin (repeatable)",
151 ),
152 Flag.atLeast(0),
153 );
154
155 /**
156 * Resolve `--set` entries into concrete values. Three forms keep secrets
157 * out of shell history: a literal, `env:VAR` (read from the environment /
158 * --env-file), and `-` (read from stdin; at most one field may use it).
159 */
160 const resolveSetValues = Effect.fn(function* (
161 sets: ReadonlyArray<string>,
162 envFile: Option.Option<string>,
163 ) {
164 const values: Record<string, string> = {};
165 let stdinUsed = false;
166 const configProvider = yield* loadConfigProvider(envFile);
167 for (const entry of sets) {
168 const separator = entry.indexOf("=");
169 if (separator <= 0) {
170 return yield* new UserInputError({
171 message: `Invalid --set '${entry}'. Expected name=value, name=env:VAR, or name=-.`,
172 });
173 }
174 const key = entry.slice(0, separator);
175 const raw = entry.slice(separator + 1);
176 if (key in values) {
177 return yield* new UserInputError({ message: `Duplicate --set for '${key}'.` });
178 }
179 if (raw === "-") {
180 if (stdinUsed) {
181 return yield* new UserInputError({
182 message: "Only one --set field may read from stdin.",
183 });
184 }
185 if (process.stdin.isTTY) {
186 return yield* new UserInputError({
187 message: `--set ${key}=- reads from stdin, but stdin is a terminal. Pipe the value in.`,
188 });
189 }
190 stdinUsed = true;
191 // Reading fd 0 to EOF is inherently synchronous whole-input
192 // consumption; there is no FileSystem-service surface for stdin.
193 values[key] = yield* Effect.try({
194 try: () => readFileSync(0, "utf8").trim(),
195 catch: (cause) =>
196 new UserInputError({
197 message: `Could not read stdin for --set ${key}=-: ${cause instanceof Error ? cause.message : String(cause)}`,
198 }),
199 });
200 } else if (raw.startsWith("env:")) {
201 const variable = raw.slice(4);
202 const value = yield* getEnv(variable).pipe(
203 Effect.provide(ConfigProvider.layer(configProvider)),
204 Effect.mapError((e) => new UserInputError({ message: e.message })),
205 );
206 if (value === undefined || value.length === 0) {
207 return yield* new UserInputError({
208 message: `--set ${key}=env:${variable}: '${variable}' is not set.`,
209 });
210 }
211 values[key] = value;
212 } else {
213 values[key] = raw;
214 }
215 }
216 return values;
217 });
218
219 const editCommand = Command.make(
220 "edit",
221 {
222 profile,
223 add: addProviders,
224 reconfigure: reconfigureProviders,
225 remove: removeProviders,
226 method: methodFlag,
227 set: setFlag,
228 envFile,
229 main: config,
230 },
231 instrumentCommand(
232 "profile.edit",
233 (a: {
234 profile: string | undefined;
235 add: ReadonlyArray<string>;
236 reconfigure: ReadonlyArray<string>;
237 remove: ReadonlyArray<string>;
238 }) => ({
239 "alchemy.profile": a.profile ?? "",
240 "alchemy.add": a.add.join(","),
241 "alchemy.re_configure": a.reconfigure.join(","),
242 "alchemy.remove": a.remove.join(","),
243 }),
244 )(
245 Effect.fn(function* ({ profile, add, reconfigure, remove, method, set, envFile, main }) {
246 const selectedProfile = yield* resolveProfileName(envFile, profile);
247 let configureInput: { method?: string; values: Record<string, string> } | undefined;
248 if (method !== undefined || set.length > 0) {
249 if (add.length + reconfigure.length !== 1 || remove.length > 0) {
250 return yield* new UserInputError({
251 message:
252 "--method/--set configure exactly one provider: pass a single --add or --reconfigure (and no --remove).",
253 });
254 }
255 configureInput = {
256 method,
257 values: yield* resolveSetValues(set, envFile),
258 };
259 }
260 if (configureInput !== undefined) {
261 const provider = (add[0] ?? reconfigure[0])!;
262 yield* Alchemist.Profile.configure({
263 profile: selectedProfile,
264 provider,
265 entrypoint: main,
266 envFile: Option.getOrUndefined(envFile),
267 action: add.length === 1 ? "add" : "reconfigure",
268 method: configureInput.method ?? "",
269 values: Object.fromEntries(
270 Object.entries(configureInput.values).map(([key, value]) => [
271 key,
272 Redacted.make(value),
273 ]),
274 ),
275 });
276 yield* Interaction.success(
277 `${add.length === 1 ? "Added" : "Updated"} '${provider}' in profile '${selectedProfile}'.`,
278 );
279 return;
280 }
281 if (add.length === 0 && reconfigure.length === 0 && remove.length > 0) {
282 for (const provider of remove) {
283 yield* Alchemist.Profile.removeProvider({
284 profile: selectedProfile,
285 provider,
286 entrypoint: main,
287 envFile: Option.getOrUndefined(envFile),
288 });
289 yield* Interaction.success(`Removed '${provider}' from profile '${selectedProfile}'.`);
290 }
291 return;
292 }
293 yield* editProfileFlow({
294 selectedProfile,
295 add,
296 reconfigure,
297 remove,
298 envFile,
299 main,
300 configureInput,
301 });
302 }),
303 ),
304 ).pipe(Command.withDescription("Add, reconfigure, or remove provider accounts in a profile"));
305
306 const refreshCommand = Command.make(
307 "refresh",
308 {
309 profile,
310 providers: refreshProviders,
311 envFile,
312 main: config,
313 },
314 instrumentCommand(
315 "profile.refresh",
316 (a: { profile: string | undefined; providers: ReadonlyArray<string> }) => ({
317 "alchemy.profile": a.profile ?? "",
318 "alchemy.providers": a.providers.join(","),
319 }),
320 )(
321 Effect.fn(function* ({ profile, providers, envFile, main }) {
322 const selectedProfile = yield* resolveProfileName(envFile, profile);
323 const refreshStarted = new Map<string, number>();
324 yield* Alchemist.Profile.refresh({
325 profile: selectedProfile,
326 providers,
327 entrypoint: main,
328 envFile: Option.getOrUndefined(envFile),
329 }).pipe(
330 Alchemist.onEvent(
331 Match.type<Alchemist.Event>().pipe(
332 Match.discriminators("type")({
333 "provider.refresh.started": (event) =>
334 Clock.currentTimeMillis.pipe(
335 Effect.tap((now) => Effect.sync(() => refreshStarted.set(event.provider, now))),
336 Effect.andThen(Interaction.info(`Refreshing ${event.provider}`)),
337 ),
338 "provider.refresh.completed": (event) =>
339 Clock.currentTimeMillis.pipe(
340 Effect.flatMap((now) => {
341 const from = refreshStarted.get(event.provider);
342 return Interaction.success(
343 `Refreshed ${event.provider}${from === undefined ? "" : ` (${formatElapsed(now - from)})`}`,
344 );
345 }),
346 ),
347 }),
348 Match.orElse(() => Effect.void),
349 ),
350 ),
351 );
352 yield* Interaction.success(`Refreshed profile '${selectedProfile}'.`);
353 }),
354 ),
355 ).pipe(
356 Command.withDescription("Refresh credentials for connected providers without reconfiguring them"),
357 );
358
359 const currentCommand = Command.make(
360 "current",
361 { envFile },
362 instrumentCommand("profile.current")(
363 Effect.fn(function* () {
364 const selected = yield* Alchemist.Profile.current();
365 const source =
366 selected.source === "configuration"
367 ? "ALCHEMY_PROFILE"
368 : selected.source === "default"
369 ? "built-in default"
370 : "command line";
371 const cli = yield* Interaction.Interaction;
372 if (cli.terminal.input) {
373 const { currentProfileNode } = yield* profileTui;
374 yield* cli.output.print(currentProfileNode(selected.name, source));
375 } else {
376 yield* Console.log(`${selected.name} (${source})`);
377 }
378 }),
379 ),
380 ).pipe(Command.withDescription("Show the effective profile and how it was selected"));
381
382 const deleteCommand = Command.make(
383 "delete",
384 { name: profileName, envFile, main: config, yes },
385 instrumentCommand("profile.delete", (a: { name: string; yes: boolean }) => ({
386 "alchemy.profile": a.name,
387 "alchemy.yes": a.yes,
388 }))(
389 Effect.fn(function* ({ name, envFile, main, yes }) {
390 const deleted = yield* deleteProfileFlow({ name, envFile, main, yes });
391 // Declined or nothing-to-delete: exit non-zero so scripts don't read
392 // the run as "profile removed". (The dashboard confirms in its own UI
393 // and calls the shared delete core, so it is unaffected.)
394 if (!deleted) yield* exitDeclined;
395 }),
396 ),
397 ).pipe(Command.withDescription("Delete a profile and all credentials stored for it"));
398
399 export const profileCommand = Command.make(
400 "profile",
401 { envFile, main: config },
402 instrumentCommand("profile")(
403 Effect.fn(function* ({ envFile, main }) {
404 if (!(yield* Interaction.Interaction).terminal.input) {
405 // No terminal to drive the hub — show the subcommand help instead,
406 // which documents the flag-driven equivalents of every hub action.
407 return yield* failWithHelp(["alchemy", "profile"]);
408 }
409 yield* profileHub({ envFile, main });
410 }),
411 ),
412 ).pipe(
413 Command.withDescription("Manage authentication profiles and accounts"),
414 Command.withSubcommands([
415 createCommand,
416 renameCommand,
417 editCommand,
418 refreshCommand,
419 listCommand,
420 showCommand,
421 currentCommand,
422 deleteCommand,
423 ]),
424 );