@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, 06:00 UTC

main
ts 515 lines 20.1 KB
Raw
1 import * as CliError from "effect/cli/CliError";
2 import * as Command from "effect/cli/Command";
3 import * as Flag from "effect/cli/Flag";
4 import * as Console from "effect/Console";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import type * as Headers from "effect/http/Headers";
8 import * as Option from "effect/Option";
9 import type * as Rpc from "effect/rpc/Rpc";
10 import type * as RpcGroup from "effect/rpc/RpcGroup";
11 import * as Runtime from "effect/Runtime";
12 import * as Schema from "effect/Schema";
13 import * as SchemaAST from "effect/SchemaAST";
14 import type * as Scope from "effect/Scope";
15 import type { Servable } from "./Api.ts";
16 import {
17 DefinitionError,
18 DuplicateCommand,
19 DuplicateFlag,
20 ReservedFlag,
21 } from "./DefinitionError.ts";
22 import { type Operation, operationsOf } from "./ReadRpcs.ts";
23
24 /**
25 * A command line for an Api: one subcommand per thing it serves, run as a client of the
26 * deployed Api over its HTTP protocol. Not part of the Domain core: import it
27 * from `@alchemy.run/domain/Cli`, so an app that builds no CLI never loads
28 * `effect/cli`.
29 */
30
31 /** What {@link toCli} reads from an Api class. */
32 export interface Cliable {
33 readonly apiName: string;
34 readonly serves: ReadonlyArray<Servable>;
35 readonly group: RpcGroup.RpcGroup<Rpc.Any>;
36 readonly client: Effect.Effect<unknown, never, any>;
37 }
38
39 /** The services an Api's client needs, less the scope each run opens itself. */
40 export type ClientServices<A extends Cliable> =
41 A["client"] extends Effect.Effect<any, any, infer R> ? Exclude<R, Scope.Scope> : never;
42
43 /**
44 * The Api answered with a typed failure: a declared rejection, or the error
45 * of the middleware that guards the call. The CLI has already written
46 * `error` (its wire JSON) to stderr, so `runMain` exits with code 1 and
47 * prints nothing more.
48 */
49 export class CallRejected extends Data.TaggedError("CallRejected")<{
50 /** The RPC that rejected the call (`Deposit`, `Balance.get`). */
51 readonly rpc: string;
52 /** The failure as wire JSON, as the Api's RPC server encodes it. */
53 readonly error: unknown;
54 }> {
55 override readonly [Runtime.errorReported] = false;
56 }
57
58 /** How {@link toCli} builds the command line. */
59 export interface Options<E = never, R = never> {
60 /** The root command: the name a person types. Default: the Api's name in kebab-case. */
61 readonly name?: string;
62 /** The root command's help text. */
63 readonly description?: string;
64 /**
65 * Headers sent with every call, such as a bearer token for the session
66 * middleware that runs on the server. An Effect runs once per call, so it
67 * can read the token from the environment (`Config.redacted("TOKEN")`).
68 */
69 readonly headers?: Headers.Input | Effect.Effect<Headers.Input, E, R>;
70 }
71
72 /** The errors a command of the CLI fails with. */
73 export type Failure<E = never> = CallRejected | CliError.UserError | E;
74
75 // ---------------------------------------------------------------- naming
76
77 /**
78 * The command-line name of a command, view, stream, aggregate, operation or field: kebab-case
79 * (`AccountSummary` → `account-summary`, `commandId` → `command-id`).
80 */
81 export const kebab = (name: string): string =>
82 name
83 .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
84 .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2")
85 .replace(/[\s_.]+/g, "-")
86 .toLowerCase();
87
88 /** Flags every command has, or that the Effect CLI reads before any command. */
89 const RESERVED = new Set(["json", "help", "version", "wizard", "completions", "log-level"]);
90
91 // ---------------------------------------------------------------- flags
92
93 /** How a field of the wire input is typed on the command line. */
94 type FieldKind =
95 | { readonly _tag: "string" }
96 | { readonly _tag: "number" }
97 | { readonly _tag: "boolean" }
98 | { readonly _tag: "choice"; readonly literals: ReadonlyArray<string> }
99 | { readonly _tag: "json" };
100
101 interface Field {
102 /** The payload field (`commandId`), or the field of a command's `input` (`amount`). */
103 readonly name: string;
104 /** `input` for a field of a command's input, which the wire nests under `input`. */
105 readonly within?: "input";
106 /** Its flag (`command-id`). */
107 readonly flag: string;
108 readonly kind: FieldKind;
109 readonly required: boolean;
110 readonly description: string | undefined;
111 }
112
113 const membersOf = (ast: SchemaAST.AST): ReadonlyArray<SchemaAST.AST> =>
114 SchemaAST.isUnion(ast) ? ast.types.flatMap(membersOf) : [ast];
115
116 /**
117 * A string, a number, a boolean or a set of string literals takes a typed
118 * flag. Anything else (a struct, an array, a date) takes its JSON.
119 */
120 const kindOf = (ast: SchemaAST.AST): FieldKind => {
121 const members = membersOf(ast).filter((member) => !SchemaAST.isUndefined(member));
122 if (members.length === 1) {
123 const [member] = members as [SchemaAST.AST];
124 if (SchemaAST.isString(member)) return { _tag: "string" };
125 if (SchemaAST.isNumber(member)) return { _tag: "number" };
126 if (SchemaAST.isBoolean(member)) return { _tag: "boolean" };
127 }
128 const literals = members.flatMap((member) =>
129 SchemaAST.isLiteral(member) && typeof member.literal === "string" ? [member.literal] : [],
130 );
131 return members.length > 0 && literals.length === members.length
132 ? { _tag: "choice", literals }
133 : { _tag: "json" };
134 };
135
136 const descriptionOfField = (ast: SchemaAST.AST): string | undefined =>
137 SchemaAST.resolveDescription(ast) ??
138 membersOf(ast)
139 .map((member) => SchemaAST.resolveDescription(member))
140 .find((description) => description !== undefined);
141
142 /**
143 * The fields of a call's payload, as the wire carries them (the encoded
144 * side). A command's `input` is flattened into flags of its own fields
145 * (`--amount`), next to `--target` and `--command-id`. A field whose flag
146 * the CLI reserves, or that another field takes, is a definition problem.
147 */
148 const fieldsOf = (
149 where: string,
150 payload: Schema.Top,
151 command: boolean,
152 problems: Array<DefinitionError>,
153 ): ReadonlyArray<Field> => {
154 const ast = SchemaAST.toEncoded(payload.ast);
155 if (!SchemaAST.isObjects(ast)) return [];
156 const flags = new Map<string, string>();
157 const fieldOf = (property: SchemaAST.PropertySignature, within?: "input"): Array<Field> => {
158 const name = String(property.name);
159 const flag = kebab(name);
160 const taken = flags.get(flag);
161 if (RESERVED.has(flag) || taken !== undefined) {
162 problems.push(
163 new DefinitionError({
164 reason:
165 taken === undefined
166 ? new ReservedFlag({ call: where, field: name, flag })
167 : new DuplicateFlag({ call: where, field: name, flag, taken }),
168 }),
169 );
170 return [];
171 }
172 flags.set(flag, name);
173 const field = {
174 name,
175 flag,
176 kind: kindOf(property.type),
177 required: !SchemaAST.isOptional(property.type),
178 description: descriptionOfField(property.type),
179 };
180 return [within === undefined ? field : { ...field, within }];
181 };
182 const outer = new Set(ast.propertySignatures.map((property) => kebab(String(property.name))));
183 return ast.propertySignatures.flatMap((property) => {
184 const input = command && property.name === "input" ? property.type : undefined;
185 // An input field named like `target` keeps the whole input as `--input`'s JSON.
186 const flat =
187 input !== undefined &&
188 SchemaAST.isObjects(input) &&
189 input.propertySignatures.every((field) => {
190 const flag = kebab(String(field.name));
191 return flag === "input" || !outer.has(flag);
192 });
193 return flat
194 ? (input as SchemaAST.Objects).propertySignatures.flatMap((field) => fieldOf(field, "input"))
195 : fieldOf(property);
196 });
197 };
198
199 const sentence = (text: string) => (/[.!?]$/.test(text) ? text : `${text}.`);
200
201 const flagOf = (field: Field): Flag.Flag<Option.Option<unknown>> => {
202 const { kind, flag } = field;
203 const base: Flag.Flag<unknown> =
204 kind._tag === "string"
205 ? Flag.String(flag)
206 : kind._tag === "number"
207 ? Flag.Finite(flag)
208 : kind._tag === "boolean"
209 ? Flag.Boolean(flag)
210 : kind._tag === "choice"
211 ? Flag.Literals(flag, kind.literals)
212 : Flag.String(flag).pipe(Flag.withMetavar("json"));
213 const help = [
214 field.description === undefined ? undefined : sentence(field.description),
215 kind._tag === "json" ? "A JSON value." : undefined,
216 field.required ? "Required." : undefined,
217 ]
218 .filter((part) => part !== undefined)
219 .join(" ");
220 return base.pipe(
221 (flag) => (help === "" ? flag : Flag.withDescription(flag, help)),
222 Flag.optional,
223 );
224 };
225
226 const JsonFlag = Flag.String("json").pipe(
227 Flag.withMetavar("json"),
228 Flag.withDescription("The flags as one JSON object. Flags given as well override its fields."),
229 Flag.optional,
230 );
231
232 // ---------------------------------------------------------------- calls
233
234 const isRecord = (value: unknown): value is Record<string, unknown> =>
235 value !== null && typeof value === "object" && !Array.isArray(value);
236
237 /** A JSON flag's value: its JSON, or the text itself when it is not JSON (a date, an id). */
238 const parseValue = (text: string): unknown => {
239 try {
240 return JSON.parse(text);
241 } catch {
242 return text;
243 }
244 };
245
246 /** The first message along an error's causes. */
247 const messageOf = (error: unknown): string => {
248 for (let at = error, depth = 0; at !== undefined && depth < 5; depth++) {
249 const { message, reason, cause } = at as {
250 message?: unknown;
251 reason?: { message?: unknown; cause?: unknown };
252 cause?: unknown;
253 };
254 const own = [reason?.message, message].find(
255 (m): m is string => typeof m === "string" && m.trim() !== "",
256 );
257 if (own !== undefined && !/^\w+: ?$/.test(own)) return own;
258 at = reason?.cause ?? cause;
259 }
260 return String(error);
261 };
262
263 const userError = (message: string, cause?: unknown) =>
264 CliError.UserError.make({ cause: cause ?? message, userMessage: message });
265
266 /** Invoke one call through the Api's typed client, with the decoded payload. */
267 const invoke = (
268 client: unknown,
269 op: Operation,
270 payload: Record<string, unknown>,
271 headers: Headers.Input | undefined,
272 ): Effect.Effect<unknown, unknown> => {
273 const served = (client as Record<string, unknown>)[op.name];
274 if (op.operation === "send") {
275 const { target, input, commandId } = payload;
276 const send = served as (
277 target: unknown,
278 input: unknown,
279 options: unknown,
280 ) => Effect.Effect<unknown, unknown>;
281 return send(target, input, { headers, ...(commandId === undefined ? {} : { commandId }) });
282 }
283 const { key, ...options } = payload;
284 const read = (served as Record<string, (key: unknown, options: unknown) => unknown>)[
285 op.operation
286 ]!;
287 return read(key, { ...options, headers }) as Effect.Effect<unknown, unknown>;
288 };
289
290 /**
291 * The CLI runs every request/response call. Live reads (`watch`, `events`)
292 * are streams, so they stay out.
293 */
294 const published = (op: Operation): boolean => !op.stream;
295
296 /**
297 * A subcommand's help text: a command's Schema `description` annotation, or
298 * what it is (`Send the Deposit command.`, `Read the Balance view.`).
299 */
300 const descriptionOf = (op: Operation): string =>
301 (op.served.kind === "Command" ? SchemaAST.resolveDescription(op.served.ast) : undefined) ??
302 (op.served.kind === "Command"
303 ? `Send the ${op.name} command.`
304 : `Read the ${op.name} ${op.served.kind.toLowerCase()}.`);
305
306 /** What each read prints, for its help. */
307 const READS: Record<string, string> = {
308 get: "Print the key's current state.",
309 peek: "Print the key's latest entry.",
310 list: "Print a page of the key's entries.",
311 snapshot: "Print the key's current state and the cursor it is valid at.",
312 };
313
314 const commandOf = <E, R>(
315 api: Cliable,
316 op: Operation,
317 name: string,
318 options: Options<E, R>,
319 problems: Array<DefinitionError>,
320 ): Command.Command<string, unknown, {}, Failure<E>, R> => {
321 const { rpc } = op;
322 const command = op.operation === "send";
323 const fields = fieldsOf(`${api.apiName} ${rpc._tag}`, rpc.payloadSchema, command, problems);
324 const decodePayload = Schema.decodeUnknownEffect(Schema.toCodecJson(rpc.payloadSchema));
325 const encodeSuccess = Schema.encodeUnknownEffect(Schema.toCodecJson(rpc.successSchema));
326 // Errors decode with no services, so they encode with none.
327 const failures = [rpc.errorSchema, ...[...rpc.middlewares].map((m) => m.error)].filter(
328 (schema): schema is Schema.Codec<unknown, unknown> =>
329 schema !== undefined && !SchemaAST.isNever(schema.ast),
330 );
331 const inputFields = new Set(
332 fields.flatMap((field) => (field.within === undefined ? [] : [field.name])),
333 );
334 const config: Record<string, Flag.Flag<Option.Option<unknown>>> = { json: JsonFlag };
335 for (const field of fields) {
336 config[field.within === undefined ? field.name : `input.${field.name}`] = flagOf(field);
337 }
338
339 /** A typed failure goes to stderr as its wire JSON; anything else did not reach the Api. */
340 const failed = (error: unknown): Effect.Effect<never, CallRejected | CliError.UserError> => {
341 const schema = failures.find((schema) => Schema.is(schema)(error));
342 if (!schema) {
343 return Effect.fail(
344 userError(`${rpc._tag} did not reach the Api: ${messageOf(error)}`, error),
345 );
346 }
347 return Schema.encodeUnknownEffect(Schema.toCodecJson(schema))(error).pipe(
348 Effect.orDie,
349 Effect.tap((wire) => Console.error(JSON.stringify(wire, null, 2))),
350 Effect.flatMap((wire) => Effect.fail(new CallRejected({ rpc: rpc._tag, error: wire }))),
351 );
352 };
353
354 const handler = Effect.fn(function* (parsed: Record<string, Option.Option<unknown>>) {
355 const wire: Record<string, unknown> = {};
356 // A command's input flags fill `input`, over what `--json` gave it.
357 const input: Record<string, unknown> = {};
358 const json = parsed.json as Option.Option<string>;
359 if (Option.isSome(json)) {
360 const value = yield* Effect.try({
361 try: () => JSON.parse(json.value) as unknown,
362 catch: (cause) => userError(`--json is not valid JSON: ${String(cause)}`, cause),
363 });
364 if (!isRecord(value)) return yield* userError("--json must be a JSON object");
365 // Its fields are the flags' fields: a command's input fields go to
366 // `input`, given flat or as the wire's own `input` object.
367 for (const [key, field] of Object.entries(value)) {
368 if (inputFields.has(key)) input[key] = field;
369 else if (key === "input" && inputFields.size > 0 && isRecord(field))
370 Object.assign(input, field);
371 else wire[key] = field;
372 }
373 }
374 for (const field of fields) {
375 const value = parsed[field.within === undefined ? field.name : `input.${field.name}`]!;
376 if (Option.isNone(value)) continue;
377 const decoded = field.kind._tag === "json" ? parseValue(value.value as string) : value.value;
378 if (field.within === undefined) wire[field.name] = decoded;
379 else input[field.name] = decoded;
380 }
381 if (fields.some((field) => field.within !== undefined)) wire.input = input;
382 const payload = yield* decodePayload(wire).pipe(
383 Effect.mapError((error) => userError(`Invalid input for ${name}: ${error.message}`, error)),
384 );
385 const headers =
386 options.headers === undefined
387 ? undefined
388 : Effect.isEffect(options.headers)
389 ? yield* options.headers
390 : options.headers;
391 const client = yield* api.client;
392 const success = yield* invoke(client, op, payload as Record<string, unknown>, headers).pipe(
393 Effect.catch(failed),
394 );
395 const out = yield* encodeSuccess(success).pipe(Effect.orDie);
396 yield* Console.log(JSON.stringify(out, null, 2));
397 }, Effect.scoped);
398
399 return Command.make(name, config, handler as never) as never;
400 };
401
402 /**
403 * An Effect CLI command for an Api: a client that calls the deployed Api over
404 * its HTTP protocol, so a person or an agent in a terminal can run any
405 * request/response call. The tree is read from what the Api serves:
406 *
407 * - each command, view, stream and aggregate is a subcommand named in kebab-case (`AccountSummary` →
408 * `account-summary`). A command runs as that subcommand; a view, an
409 * aggregate or a stream has one subcommand per call (`get`, `list`,
410 * `snapshot`, `peek`). Live reads (`watch`, `events`) are left out.
411 * - each payload field is a flag in kebab-case (`--target`, `--command-id`,
412 * `--key`), and a command's input fields are flags of their own
413 * (`--amount`). A string, a number, a boolean or a set of string literals
414 * takes a typed flag; any other field takes its JSON (`--at-least
415 * '{"stream":"Account/a-1","version":3}'`). `--json` takes the flags as
416 * one object (`{"target":"a-1","amount":1000}`), and flags override it.
417 * - two of them with one command name, or a field whose flag another field
418 * or the CLI takes, fail every run with a `DefinitionError`.
419 * - the input is decoded against the call's schema before anything is sent;
420 * an invalid input fails as a `CliError.UserError`.
421 * - the result is printed to stdout as JSON (its wire form). A typed
422 * failure (a rejection, or the error of the middleware that guards the
423 * call) is printed to stderr as JSON and fails the run with
424 * {@link CallRejected}, so the process exits with code 1.
425 *
426 * Provide the protocol to the command (`Domain.protocolHttp(url)` and an
427 * `HttpClient`), and the platform's CLI services to run it.
428 *
429 * **Example:** A CLI for an Api
430 * ```typescript
431 * import { toCli } from "@alchemy.run/domain/Cli";
432 * import * as Domain from "@alchemy.run/domain";
433 * import { BunRuntime, BunServices } from "@effect/platform-bun";
434 * import * as Command from "effect/cli/Command";
435 * import * as Config from "effect/Config";
436 * import * as Effect from "effect/Effect";
437 * import * as FetchHttpClient from "effect/http/FetchHttpClient";
438 * import * as Redacted from "effect/Redacted";
439 * import { CustomerApi } from "./CustomerApi.ts";
440 *
441 * const bank = toCli(CustomerApi, {
442 * name: "bank",
443 * headers: Config.redacted("BANK_TOKEN").pipe(
444 * Effect.map((token) => ({ authorization: `Bearer ${Redacted.value(token)}` })),
445 * ),
446 * });
447 *
448 * Command.run(bank, { version: "1.0.0" }).pipe(
449 * Effect.provide(Domain.protocolHttp("https://bank.example.com/api")),
450 * Effect.provide(FetchHttpClient.layer),
451 * Effect.provide(BunServices.layer),
452 * BunRuntime.runMain,
453 * );
454 * // $ bank deposit-money --target a-1 --amount 1000
455 * // $ bank account-summary get --key a-1
456 * ```
457 */
458 export const toCli = <A extends Cliable, E = never, R = never>(
459 api: A,
460 options: Options<E, R> = {},
461 ): Command.Command<string, unknown, {}, Failure<E>, ClientServices<A> | R> => {
462 // A name the CLI cannot give fails every run, like the model's own definition problems.
463 const problems: Array<DefinitionError> = [];
464 const byName = new Map<string, Array<Operation>>();
465 for (const op of operationsOf(api.serves)) {
466 const ops = byName.get(op.name) ?? [];
467 ops.push(op);
468 byName.set(op.name, ops);
469 }
470 const names = new Map<string, string>();
471 const subcommands: Array<Command.Command<string, unknown, {}, Failure<E>, R>> = [];
472 for (const [served, all] of byName) {
473 const name = kebab(served);
474 const taken = names.get(name);
475 if (taken !== undefined) {
476 problems.push(
477 new DefinitionError({
478 reason: new DuplicateCommand({
479 api: api.apiName,
480 first: taken,
481 second: served,
482 command: name,
483 }),
484 }),
485 );
486 continue;
487 }
488 names.set(name, served);
489 const ops = all.filter(published);
490 if (ops.length === 0) continue;
491 let command: Command.Command<string, unknown, {}, Failure<E>, R>;
492 if (all[0]!.operation === "send") {
493 command = commandOf(api, ops[0]!, name, options, problems);
494 } else {
495 command = Command.make(name).pipe(
496 Command.withSubcommands(
497 ops.map((op) =>
498 commandOf(api, op, op.operation, options, problems).pipe(
499 Command.withDescription(READS[op.operation] ?? op.operation),
500 ),
501 ) as never,
502 ),
503 ) as never;
504 }
505 subcommands.push(Command.withDescription(command, descriptionOf(all[0]!)));
506 }
507 const rootName = options.name ?? kebab(api.apiName);
508 const root =
509 problems.length > 0
510 ? Command.make(rootName, {}, () => problems[0]!.pipe(Effect.die))
511 : Command.make(rootName).pipe(Command.withSubcommands(subcommands as never));
512 return (
513 options.description === undefined ? root : Command.withDescription(root, options.description)
514 ) as never;
515 };