@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, 04:45 UTC

main
ts 313 lines 11.4 KB
Raw
1 import {
2 AuthMcpClientAccess,
3 EnvironmentId,
4 peerLinkFailureKind,
5 type PeerLinkSummary,
6 } from "@t3tools/contracts";
7 import * as Console from "effect/Console";
8 import * as DateTime from "effect/DateTime";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Layer from "effect/Layer";
12 import * as References from "effect/References";
13 import * as Option from "effect/Option";
14 import * as Schema from "effect/Schema";
15 import * as Stdio from "effect/Stdio";
16 import * as Stream from "effect/Stream";
17 import * as Argument from "effect/cli/Argument";
18 import * as Command from "effect/cli/Command";
19 import * as Flag from "effect/cli/Flag";
20 import * as GlobalFlag from "effect/cli/GlobalFlag";
21 import * as FetchHttpClient from "effect/http/FetchHttpClient";
22
23 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
24 import * as ServerConfig from "../config.ts";
25 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
26 import * as PeerLinks from "../peer/PeerLinks.ts";
27 import * as ServerSettings from "../serverSettings.ts";
28 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
29 import * as SqlitePersistence from "../persistence/Sqlite.ts";
30 import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts";
31
32 /**
33 * Links live in this environment's database and secret store, so these
34 * commands work whether or not its server is running.
35 */
36 const runWithPeerLinks = Effect.fn("environment.runWithPeerLinks")(function* <A, E>(
37 flags: CliAuthLocationFlags,
38 run: (links: PeerLinks.PeerLinks["Service"]) => Effect.Effect<A, E>,
39 options?: { readonly quietLogs?: boolean },
40 ) {
41 const logLevel = yield* GlobalFlag.LogLevel;
42 const config = yield* resolveCliAuthConfig(flags, logLevel, options);
43 return yield* PeerLinks.PeerLinks.pipe(
44 Effect.flatMap(run),
45 Effect.provide(
46 PeerLinks.layer.pipe(
47 Layer.provide(
48 Layer.mergeAll(
49 ServerSecretStore.layer,
50 SqlitePersistence.layerCliConfig,
51 FetchHttpClient.layer,
52 ),
53 ),
54 Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
55 Layer.provide(
56 ServerSettings.layer.pipe(
57 Layer.provide(
58 Layer.mergeAll(
59 ServerSecretStore.layer,
60 SqlitePersistence.layerCliConfig,
61 ManagedPolicy.layer,
62 ),
63 ),
64 ),
65 ),
66 Layer.provide(ServerConfig.layer(config)),
67 Layer.provide(
68 Layer.succeed(References.MinimumLogLevel, options?.quietLogs ? "Error" : config.logLevel),
69 ),
70 ),
71 ),
72 );
73 });
74
75 const jsonFlag = Flag.Boolean("json").pipe(
76 Flag.withDescription("Emit JSON instead of human-readable output."),
77 Flag.withDefault(false),
78 );
79
80 const encodeLinks = Schema.encodeEffect(
81 Schema.fromJsonString(Schema.Array(Schema.toEncoded(Schema.Unknown))),
82 );
83
84 const formatLinks = (links: ReadonlyArray<PeerLinkSummary>) =>
85 links.length === 0
86 ? "No linked environments.\n"
87 : `${links
88 .map(
89 (link) =>
90 `${link.label} (${link.environmentId})\n ${link.status}, access ${link.access}, expires ${DateTime.formatIso(link.expiresAt)}\n ${link.urls.join(", ")}${link.lastError === null ? "" : `\n last error: ${link.lastError}`}`,
91 )
92 .join("\n\n")}\n`;
93
94 export class EnvironmentLinkUsageError extends Schema.TaggedError<EnvironmentLinkUsageError>()(
95 "EnvironmentLinkUsageError",
96 { detail: Schema.String },
97 ) {
98 override get message(): string {
99 return this.detail;
100 }
101 }
102
103 export class EnvironmentLinkBatchError extends Schema.TaggedError<EnvironmentLinkBatchError>()(
104 "EnvironmentLinkBatchError",
105 { failed: Schema.Number, total: Schema.Number },
106 ) {
107 override get message(): string {
108 return `${this.failed} of ${this.total} environments were not linked.`;
109 }
110 }
111
112 /** Pairings a batch opens at once, so a fleet is not signed in to all at the same moment. */
113 const LINK_BATCH_CONCURRENCY = 4;
114
115 const FAILURE_KIND_LABELS = {
116 unreachable: "unreachable",
117 code_refused: "code refused",
118 wrong_environment: "wrong environment answered",
119 other: "failed",
120 } as const;
121
122 /**
123 * How a result line names its entry: the address's origin, since a username,
124 * password, path or query in it may be a credential and stdout is kept in logs.
125 */
126 const linkBatchEntryName = (entry: { readonly line: number; readonly url: string }) => {
127 const parsed = URL.parse(entry.url);
128 return parsed !== null && (parsed.protocol === "https:" || parsed.protocol === "http:")
129 ? parsed.origin
130 : `line ${entry.line}`;
131 };
132
133 /** One `<url> <pairing-code>` per line; blank lines and `#` comments are skipped. */
134 const parseLinkBatch = (text: string) =>
135 text.split(/\r?\n/).flatMap((raw, index) => {
136 const fields = raw.trim().split(/\s+/);
137 if (raw.trim().length === 0 || raw.trim().startsWith("#")) return [];
138 const [url, pairingCode] = fields;
139 return [
140 url !== undefined && pairingCode !== undefined && fields.length === 2
141 ? { line: index + 1, url, pairingCode }
142 : { line: index + 1, url: url ?? "", pairingCode: null },
143 ];
144 });
145
146 const linkBatch = Effect.fn("environment.linkBatch")(function* (
147 links: PeerLinks.PeerLinks["Service"],
148 text: string,
149 access: AuthMcpClientAccess,
150 ) {
151 const entries = parseLinkBatch(text);
152 if (entries.length === 0) {
153 return yield* new EnvironmentLinkUsageError({
154 detail: "Nothing to link: expected lines of `<url> <pairing-code>`.",
155 });
156 }
157 // Results never include a pairing code, only where it was sent.
158 const outcomes = yield* Effect.forEach(
159 entries,
160 (entry) =>
161 entry.pairingCode === null
162 ? Effect.succeed({
163 linked: false,
164 text: `line ${entry.line}: failed: expected \`<url> <pairing-code>\``,
165 })
166 : links.linkUnlessLinked({ url: entry.url, pairingCode: entry.pairingCode, access }).pipe(
167 Effect.map(({ link, alreadyLinked }) => ({
168 linked: true,
169 text: alreadyLinked
170 ? `${linkBatchEntryName(entry)}: already linked as ${link.label} (${link.environmentId}), left as it is`
171 : `${linkBatchEntryName(entry)}: linked ${link.label} (${link.environmentId}) with ${link.access} access`,
172 })),
173 Effect.catch((error) =>
174 Effect.succeed({
175 linked: false,
176 text: `${linkBatchEntryName(entry)}: ${FAILURE_KIND_LABELS[peerLinkFailureKind(error)]}: ${error.message}`,
177 }),
178 ),
179 ),
180 { concurrency: LINK_BATCH_CONCURRENCY },
181 );
182 const failed = outcomes.filter((outcome) => !outcome.linked).length;
183 yield* Console.log(
184 `${outcomes.map((outcome) => outcome.text).join("\n")}\n\n${outcomes.length - failed} of ${outcomes.length} linked.\n`,
185 );
186 if (failed > 0) {
187 return yield* new EnvironmentLinkBatchError({ failed, total: outcomes.length });
188 }
189 });
190
191 const readLinkBatch = Effect.fn("environment.readLinkBatch")(function* (from: string) {
192 if (from === "-") {
193 return yield* Stdio.Stdio.pipe(
194 Effect.flatMap((stdio) => stdio.stdin.pipe(Stream.decodeText(), Stream.mkString)),
195 );
196 }
197 const fs = yield* FileSystem.FileSystem;
198 return yield* fs.readFileString(from);
199 });
200
201 const environmentLinkCommand = Command.make("link", {
202 ...authLocationFlags,
203 url: Argument.String("url").pipe(
204 Argument.withDescription(
205 "Where the other environment answers: its T3 Connect, Tailscale, LAN or loopback address.",
206 ),
207 Argument.optional,
208 ),
209 alternateUrl: Flag.String("url").pipe(
210 Flag.withDescription("Another address for the same environment, tried after the first."),
211 Flag.atLeast(0),
212 ),
213 pairingCode: Flag.String("pairing-code").pipe(
214 Flag.withDescription("A pairing code from the other environment (`t3 pair` there)."),
215 Flag.optional,
216 ),
217 from: Flag.String("from").pipe(
218 Flag.withDescription(
219 "Link several environments: a file with one `<url> <pairing-code>` per line, or - for stdin. Environments already linked are left as they are.",
220 ),
221 Flag.optional,
222 ),
223 access: Flag.Literals("access", AuthMcpClientAccess.literals).pipe(
224 Flag.withDescription(
225 "What this environment's agents may do there: read-only, or the broadest runtime mode.",
226 ),
227 Flag.withDefault("approval-required" as const),
228 ),
229 }).pipe(
230 Command.withDescription(
231 "Link another T3 Code environment, so agents here can work there. It shows up there under Authorized clients in Settings → Sharing & access, where it can be revoked.",
232 ),
233 Command.withHandler((flags) =>
234 Effect.gen(function* () {
235 if (Option.isSome(flags.from)) {
236 if (Option.isSome(flags.url) || Option.isSome(flags.pairingCode)) {
237 return yield* new EnvironmentLinkUsageError({
238 detail: "--from takes its addresses and pairing codes from the file.",
239 });
240 }
241 const text = yield* readLinkBatch(flags.from.value);
242 return yield* runWithPeerLinks(flags, (links) => linkBatch(links, text, flags.access));
243 }
244 if (Option.isNone(flags.url) || Option.isNone(flags.pairingCode)) {
245 return yield* new EnvironmentLinkUsageError({
246 detail: "Give an address and --pairing-code, or --from <file>.",
247 });
248 }
249 const url = flags.url.value;
250 const pairingCode = flags.pairingCode.value;
251 return yield* runWithPeerLinks(flags, (links) =>
252 Effect.gen(function* () {
253 const linked = yield* links.link({
254 url,
255 alternateUrls: flags.alternateUrl,
256 pairingCode,
257 access: flags.access,
258 });
259 yield* Console.log(
260 `Linked ${linked.label} (${linked.environmentId}) with ${linked.access} access, until ${DateTime.formatIso(linked.expiresAt)}.\n`,
261 );
262 }),
263 );
264 }),
265 ),
266 );
267
268 const environmentListCommand = Command.make("list", { ...authLocationFlags, json: jsonFlag }).pipe(
269 Command.withDescription("List linked environments and whether each answers now."),
270 Command.withHandler((flags) =>
271 runWithPeerLinks(
272 flags,
273 (links) =>
274 Effect.gen(function* () {
275 const listed = yield* links.list;
276 yield* Console.log(flags.json ? `${yield* encodeLinks(listed)}\n` : formatLinks(listed));
277 }),
278 { quietLogs: flags.json },
279 ),
280 ),
281 );
282
283 const environmentUnlinkCommand = Command.make("unlink", {
284 ...authLocationFlags,
285 environmentId: Argument.String("environment-id").pipe(
286 Argument.withDescription("The linked environment's id, from `t3 environment list`."),
287 ),
288 }).pipe(
289 Command.withDescription(
290 "Forget a linked environment here. Revoke it in that environment's Sharing & access to end its session there too.",
291 ),
292 Command.withHandler((flags) =>
293 runWithPeerLinks(flags, (links) =>
294 Effect.gen(function* () {
295 const removed = yield* links.unlink(EnvironmentId.make(flags.environmentId));
296 yield* Console.log(
297 removed
298 ? `Forgot ${flags.environmentId}. Revoke it in that environment's Sharing & access to end its session there.\n`
299 : `No linked environment ${flags.environmentId}.\n`,
300 );
301 }),
302 ),
303 ),
304 );
305
306 export const environmentCommand = Command.make("environment").pipe(
307 Command.withDescription("Link other T3 Code environments, so agents here can work there."),
308 Command.withSubcommands([
309 environmentLinkCommand,
310 environmentListCommand,
311 environmentUnlinkCommand,
312 ]),
313 );