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

environment.ts

323 lines11.8 KB

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