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

environment.ts

164 lines6.1 KB

1import { AuthMcpClientAccess, EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";
2import * as Console from "effect/Console";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as References from "effect/References";
7import * as Schema from "effect/Schema";
8import * as Argument from "effect/cli/Argument";
9import * as Command from "effect/cli/Command";
10import * as Flag from "effect/cli/Flag";
11import * as GlobalFlag from "effect/cli/GlobalFlag";
12import * as FetchHttpClient from "effect/http/FetchHttpClient";
13​
14import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
15import * as ServerConfig from "../config.ts";
16import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
17import * as PeerLinks from "../peer/PeerLinks.ts";
18import * as ServerSettings from "../serverSettings.ts";
19import * as SqlitePersistence from "../persistence/Sqlite.ts";
20import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts";
21​
22/**
23 * Links live in this environment's database and secret store, so these
24 * commands work whether or not its server is running.
25 */
26const runWithPeerLinks = Effect.fn("environment.runWithPeerLinks")(function* <A, E>(
27 flags: CliAuthLocationFlags,
28 run: (links: PeerLinks.PeerLinks["Service"]) => Effect.Effect<A, E>,
29 options?: { readonly quietLogs?: boolean },
30) {
31 const logLevel = yield* GlobalFlag.LogLevel;
32 const config = yield* resolveCliAuthConfig(flags, logLevel, options);
33 return yield* PeerLinks.PeerLinks.pipe(
34 Effect.flatMap(run),
35 Effect.provide(
36 PeerLinks.layer.pipe(
37 Layer.provide(
38 Layer.mergeAll(
39 ServerSecretStore.layer,
40 SqlitePersistence.layerConfig,
41 FetchHttpClient.layer,
42 ),
43 ),
44 Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
45 Layer.provide(
46 ServerSettings.layer.pipe(
47 Layer.provide(Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig)),
48 ),
49 ),
50 Layer.provide(ServerConfig.layer(config)),
51 Layer.provide(
52 Layer.succeed(References.MinimumLogLevel, options?.quietLogs ? "Error" : config.logLevel),
53 ),
54 ),
55 ),
56 );
57});
58​
59const jsonFlag = Flag.Boolean("json").pipe(
60 Flag.withDescription("Emit JSON instead of human-readable output."),
61 Flag.withDefault(false),
62);
63​
64const encodeLinks = Schema.encodeEffect(
65 Schema.fromJsonString(Schema.Array(Schema.toEncoded(Schema.Unknown))),
66);
67​
68const formatLinks = (links: ReadonlyArray<PeerLinkSummary>) =>
69 links.length === 0
70 ? "No linked environments.\n"
71 : `${links
72 .map(
73 (link) =>
74 `${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}`}`,
75 )
76 .join("\n\n")}\n`;
77​
78const environmentLinkCommand = Command.make("link", {
79 ...authLocationFlags,
80 url: Argument.String("url").pipe(
81 Argument.withDescription(
82 "Where the other environment answers: its T3 Connect, Tailscale, LAN or loopback address.",
83 ),
84 ),
85 alternateUrl: Flag.String("url").pipe(
86 Flag.withDescription("Another address for the same environment, tried after the first."),
87 Flag.atLeast(0),
88 ),
89 pairingCode: Flag.String("pairing-code").pipe(
90 Flag.withDescription("A pairing code from the other environment (`t3 pair` there)."),
91 ),
92 access: Flag.Literals("access", AuthMcpClientAccess.literals).pipe(
93 Flag.withDescription(
94 "What this environment's agents may do there: read-only, or the broadest runtime mode.",
95 ),
96 Flag.withDefault("approval-required" as const),
97 ),
98}).pipe(
99 Command.withDescription(
100 "Link another T3 Code environment, so agents here can work there. It shows up there under Settings → Connections, where it can be revoked.",
101 ),
102 Command.withHandler((flags) =>
103 runWithPeerLinks(flags, (links) =>
104 Effect.gen(function* () {
105 const linked = yield* links.link({
106 url: flags.url,
107 alternateUrls: flags.alternateUrl,
108 pairingCode: flags.pairingCode,
109 access: flags.access,
110 });
111 yield* Console.log(
112 `Linked ${linked.label} (${linked.environmentId}) with ${linked.access} access, until ${DateTime.formatIso(linked.expiresAt)}.\n`,
113 );
114 }),
115 ),
116 ),
117);
118​
119const environmentListCommand = Command.make("list", { ...authLocationFlags, json: jsonFlag }).pipe(
120 Command.withDescription("List linked environments and whether each answers now."),
121 Command.withHandler((flags) =>
122 runWithPeerLinks(
123 flags,
124 (links) =>
125 Effect.gen(function* () {
126 const listed = yield* links.list;
127 yield* Console.log(flags.json ? `${yield* encodeLinks(listed)}\n` : formatLinks(listed));
128 }),
129 { quietLogs: flags.json },
130 ),
131 ),
132);
133​
134const environmentUnlinkCommand = Command.make("unlink", {
135 ...authLocationFlags,
136 environmentId: Argument.String("environment-id").pipe(
137 Argument.withDescription("The linked environment's id, from `t3 environment list`."),
138 ),
139}).pipe(
140 Command.withDescription(
141 "Forget a linked environment here. Revoke it in that environment's Connections to end its session there too.",
142 ),
143 Command.withHandler((flags) =>
144 runWithPeerLinks(flags, (links) =>
145 Effect.gen(function* () {
146 const removed = yield* links.unlink(EnvironmentId.make(flags.environmentId));
147 yield* Console.log(
148 removed
149 ? `Forgot ${flags.environmentId}. Revoke it in that environment's Connections to end its session there.\n`
150 : `No linked environment ${flags.environmentId}.\n`,
151 );
152 }),
153 ),
154 ),
155);
156​
157export const environmentCommand = Command.make("environment").pipe(
158 Command.withDescription("Link other T3 Code environments, so agents here can work there."),
159 Command.withSubcommands([
160 environmentLinkCommand,
161 environmentListCommand,
162 environmentUnlinkCommand,
163 ]),
164);