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