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