@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 207 lines 7.06 KB
Raw
1 import * as Console from "effect/Console";
2 import * as Effect from "effect/Effect";
3 import * as Option from "effect/Option";
4 import * as Redacted from "effect/Redacted";
5 import * as Alchemist from "../../../Alchemist/index.ts";
6 import * as Interaction from "../../../Interaction.ts";
7 import { glyphsFor } from "../../../Util/Theme.ts";
8 import { confirmOrDecline } from "../confirm.ts";
9 import { isPromptCancellation } from "../errors.ts";
10
11 export const profileTui = Effect.promise(() => import("../../../Cli/components/view/Profile.tsx"));
12
13 export type EditAction = "add" | "reconfigure" | "remove";
14 export interface EditOutcome {
15 readonly provider: string;
16 readonly action: EditAction;
17 readonly outcome: "done" | "skipped";
18 }
19
20 export const showProfileFlow = Effect.fn(function* (options: {
21 profileName: string;
22 activeProfile: string;
23 envFile: Option.Option<string>;
24 main: string;
25 }) {
26 const profile = yield* Alchemist.Profile.get({
27 name: options.profileName,
28 includeProviderStatus: true,
29 entrypoint: options.main,
30 envFile: Option.getOrUndefined(options.envFile),
31 });
32 yield* Console.log(
33 [
34 `${profile.active ? "*" : "-"} ${profile.name}`,
35 ...profile.providers.map((provider) =>
36 [
37 ` ${provider.name} (${provider.method}) — ${provider.status}`,
38 ...provider.details.map(({ key, value }) => ` ${key}: ${value}`),
39 ...(provider.diagnostic ? [` ${provider.diagnostic.message}`] : []),
40 ].join("\n"),
41 ),
42 ].join("\n"),
43 );
44 });
45
46 export const renameProfileFlow = Effect.fn(function* (
47 name: string,
48 suppliedNewName: string | undefined,
49 ) {
50 const newName = (
51 suppliedNewName ??
52 (yield* Interaction.text({
53 message: `Rename profile '${name}' to`,
54 placeholder: `${name}-new`,
55 validate: (value) => (value.trim().length > 0 ? undefined : "Profile name is required"),
56 }))
57 ).trim();
58 yield* Alchemist.Profile.rename({ name, newName });
59 yield* Interaction.success(`Renamed profile '${name}' to '${newName}'.`);
60 return newName;
61 });
62
63 export const deleteProfileFlow = Effect.fn(function* (options: {
64 name: string;
65 envFile: Option.Option<string>;
66 main: string;
67 yes: boolean;
68 }) {
69 // Existence check only — skip the provider-status probe (it imports the
70 // stack entrypoint and reaches provider APIs).
71 const exists = yield* Alchemist.Profile.get({
72 name: options.name,
73 includeProviderStatus: false,
74 }).pipe(Effect.option);
75 if (Option.isNone(exists)) {
76 yield* Console.log(`Profile ${options.name}: Not found. Nothing was deleted.`);
77 return false;
78 }
79 // Declining short-circuits with exit code 1; the boolean only reports the
80 // not-found early return above to the caller.
81 yield* confirmOrDecline({
82 yes: options.yes,
83 message: `Delete profile '${options.name}' and all its stored credentials? This cannot be undone.`,
84 confirmLabel: "Delete",
85 cancelLabel: "Cancel",
86 });
87 yield* Alchemist.Profile.deleteProfile({ name: options.name });
88 yield* Interaction.success(`Deleted profile '${options.name}' and its credentials.`);
89 return true;
90 });
91
92 export const editProfileFlow = Effect.fn(function* (options: {
93 selectedProfile: string;
94 add: ReadonlyArray<string>;
95 reconfigure: ReadonlyArray<string>;
96 remove: ReadonlyArray<string>;
97 envFile: Option.Option<string>;
98 main: string;
99 configureInput?: {
100 method?: string;
101 values: Record<string, string>;
102 };
103 }) {
104 let plan: Array<{ provider: string; action: EditAction }> = [
105 ...options.add.map((provider) => ({ provider, action: "add" as const })),
106 ...options.reconfigure.map((provider) => ({
107 provider,
108 action: "reconfigure" as const,
109 })),
110 ...options.remove.map((provider) => ({
111 provider,
112 action: "remove" as const,
113 })),
114 ];
115
116 if (plan.length === 0) {
117 // Only connected names/methods are needed for the cycle prompt; the
118 // status probe would import the entrypoint and reach provider APIs.
119 const profile = yield* Alchemist.Profile.get({
120 name: options.selectedProfile,
121 includeProviderStatus: false,
122 });
123 const available = yield* Alchemist.Profile.providers({
124 profile: options.selectedProfile,
125 entrypoint: options.main,
126 envFile: Option.getOrUndefined(options.envFile),
127 });
128 const connected = new Map(profile.providers.map((item) => [item.name, item]));
129 const names = [...new Set([...connected.keys(), ...available.map(({ name }) => name)])].sort();
130 const prompt = yield* Interaction.Interaction;
131 const { editStateStyle } = yield* profileTui;
132 const { cycleSelectScreen } = yield* Effect.promise(
133 () => import("../../../Cli/components/view/Prompts.tsx"),
134 );
135 const glyphs = glyphsFor(prompt.terminal.unicode);
136 const state = (
137 key: keyof typeof editStateStyle,
138 value: { provider: string; action: EditAction } | null,
139 ) => ({
140 value,
141 icon: glyphs[editStateStyle[key].icon],
142 label: editStateStyle[key].label,
143 variant: editStateStyle[key].variant,
144 });
145 const choices = names.map((provider) =>
146 connected.has(provider)
147 ? {
148 label: provider,
149 description: connected.get(provider)!.method,
150 states: [
151 state("keep", null),
152 state("reconfigure", { provider, action: "reconfigure" }),
153 state("remove", { provider, action: "remove" }),
154 ],
155 }
156 : {
157 label: provider,
158 states: [state("skip", null), state("add", { provider, action: "add" })],
159 },
160 );
161 plan = (yield* prompt.prompt.screen(
162 cycleSelectScreen({
163 message: `Manage accounts in profile '${options.selectedProfile}'`,
164 options: choices,
165 requireChange: true,
166 }),
167 )).filter((item) => item !== null);
168 }
169
170 const outcomes: EditOutcome[] = [];
171 for (const step of plan) {
172 const run =
173 step.action === "remove"
174 ? Alchemist.Profile.removeProvider({
175 profile: options.selectedProfile,
176 provider: step.provider,
177 entrypoint: options.main,
178 envFile: Option.getOrUndefined(options.envFile),
179 })
180 : Alchemist.Profile.configure({
181 profile: options.selectedProfile,
182 provider: step.provider,
183 entrypoint: options.main,
184 envFile: Option.getOrUndefined(options.envFile),
185 action: step.action,
186 method: options.configureInput?.method,
187 values:
188 options.configureInput === undefined
189 ? undefined
190 : Object.fromEntries(
191 Object.entries(options.configureInput.values).map(([key, value]) => [
192 key,
193 Redacted.make(value),
194 ]),
195 ),
196 }).pipe(Effect.asVoid);
197 const result = yield* Effect.result(run);
198 if (result._tag === "Success") {
199 outcomes.push({ ...step, outcome: "done" });
200 } else if (isPromptCancellation(result.failure)) {
201 outcomes.push({ ...step, outcome: "skipped" });
202 } else {
203 return yield* result.failure;
204 }
205 }
206 return outcomes;
207 });