The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Domain from "@alchemy.run/domain"; |
| 2 | import { CallRejected, toCli } from "@alchemy.run/domain/Cli"; |
| 3 | import { InMemory } from "@alchemy.run/domain/InMemory"; |
| 4 | import { describe, expect, it } from "@alchemy.run/test"; |
| 5 | import * as Cause from "effect/Cause"; |
| 6 | import * as Command from "effect/cli/Command"; |
| 7 | import * as Console from "effect/Console"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Exit from "effect/Exit"; |
| 10 | import * as FileSystem from "effect/FileSystem"; |
| 11 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 12 | import * as Headers from "effect/http/Headers"; |
| 13 | import * as HttpEffect from "effect/http/HttpEffect"; |
| 14 | import * as Layer from "effect/Layer"; |
| 15 | import * as Option from "effect/Option"; |
| 16 | import * as Path from "effect/Path"; |
| 17 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 18 | import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; |
| 19 | import * as Runtime from "effect/Runtime"; |
| 20 | import * as Schema from "effect/Schema"; |
| 21 | import * as Stdio from "effect/Stdio"; |
| 22 | import * as Terminal from "effect/Terminal"; |
| 23 | |
| 24 | // ---------------------------------------------------------------- a wallet domain |
| 25 | |
| 26 | const WalletId = Schema.String.pipe(Schema.brand("WalletId")); |
| 27 | |
| 28 | class Owner extends Domain.RequestContext<Owner>()("Test/Owner", Schema.String) {} |
| 29 | class Unauthenticated extends Domain.Rejection("Unauthenticated") {} |
| 30 | class Session extends RpcMiddleware.Service<Session, { provides: Owner }>()("Test/Session", { |
| 31 | error: Unauthenticated, |
| 32 | }) {} |
| 33 | /** A bearer token names the owner. */ |
| 34 | const SessionLive = Layer.succeed(Session, (effect, { headers }) => |
| 35 | Option.match(Headers.get(headers, "authorization"), { |
| 36 | onNone: () => Effect.fail(new Unauthenticated()), |
| 37 | onSome: (value) => Effect.provideService(effect, Owner, value.replace(/^Bearer /, "")), |
| 38 | }), |
| 39 | ); |
| 40 | |
| 41 | class Deposited extends Domain.Event("Deposited", { |
| 42 | amount: Schema.Int, |
| 43 | balance: Schema.Int, |
| 44 | note: Schema.optional(Schema.String), |
| 45 | }) {} |
| 46 | class OverLimit extends Domain.Rejection("OverLimit", { limit: Schema.Int }) {} |
| 47 | |
| 48 | class Deposit extends Domain.Command("Deposit", { |
| 49 | target: WalletId, |
| 50 | input: { |
| 51 | amount: Schema.Int.annotate({ description: "Cents to add" }), |
| 52 | note: Schema.optional(Schema.String), |
| 53 | method: Schema.optional(Schema.Literals(["cash", "card"])), |
| 54 | express: Schema.optional(Schema.Boolean), |
| 55 | tags: Schema.optional(Schema.Array(Schema.String)), |
| 56 | }, |
| 57 | middleware: [Session], |
| 58 | events: [Deposited], |
| 59 | rejects: [OverLimit], |
| 60 | reply: { balance: Schema.Int }, |
| 61 | }) {} |
| 62 | |
| 63 | class Wallet extends Domain.Aggregate("Wallet", { |
| 64 | id: WalletId, |
| 65 | state: Schema.Struct({ balance: Schema.Int }), |
| 66 | initial: { balance: 0 }, |
| 67 | commands: [Deposit], |
| 68 | decide: { |
| 69 | Deposit: (s, cmd) => |
| 70 | cmd.amount > 100 |
| 71 | ? new OverLimit({ limit: 100 }) |
| 72 | : [new Deposited({ amount: cmd.amount, balance: s.balance + cmd.amount, note: cmd.note })], |
| 73 | }, |
| 74 | evolve: { Deposited: (_, e) => ({ balance: e.balance }) }, |
| 75 | reply: { Deposit: (s) => ({ balance: s.balance }) }, |
| 76 | read: { middleware: [Session] }, |
| 77 | }) {} |
| 78 | |
| 79 | class Balance extends Domain.View("Balance", { |
| 80 | from: [Wallet], |
| 81 | key: Wallet, |
| 82 | middleware: [Session], |
| 83 | state: Schema.Struct({ balance: Schema.Int }), |
| 84 | initial: { balance: 0 }, |
| 85 | evolve: { Deposited: (_, e) => ({ balance: e.balance }) }, |
| 86 | }) {} |
| 87 | |
| 88 | class Wallets extends Domain.Model("Wallets", { aggregates: [Wallet], views: [Balance] }) {} |
| 89 | |
| 90 | class WalletApi extends Domain.Api("WalletApi", { model: Wallets, aggregates: ["Wallet"] }) {} |
| 91 | |
| 92 | // ---------------------------------------------------------------- the CLI over HTTP |
| 93 | |
| 94 | /** The CLI's environment, with no terminal: what a script or an agent runs it in. */ |
| 95 | const CliEnvironment = Layer.mergeAll( |
| 96 | FileSystem.layerNoop({}), |
| 97 | Path.layer, |
| 98 | Stdio.layerTest({}), |
| 99 | Layer.succeed( |
| 100 | Terminal.Terminal, |
| 101 | Terminal.make({ |
| 102 | columns: Effect.succeed(120), |
| 103 | rows: Effect.succeed(24), |
| 104 | size: Effect.die("unused"), |
| 105 | readInput: Effect.die("unused"), |
| 106 | readLine: Effect.die("unused"), |
| 107 | display: () => Effect.void, |
| 108 | }), |
| 109 | ), |
| 110 | Layer.succeed( |
| 111 | ChildProcessSpawner.ChildProcessSpawner, |
| 112 | ChildProcessSpawner.make(() => Effect.die("unused")), |
| 113 | ), |
| 114 | ); |
| 115 | |
| 116 | interface Run { |
| 117 | readonly stdout: string; |
| 118 | readonly stderr: string; |
| 119 | /** The exit code `runMain` gives the process for this run. */ |
| 120 | readonly code: number; |
| 121 | readonly exit: Exit.Exit<void, unknown>; |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Serve the Api in process and run the CLI against it over the Api's HTTP |
| 126 | * protocol: every call is encoded, sent as a request to the Api's `fetch`, |
| 127 | * and decoded, as it is against a deployed Worker. |
| 128 | */ |
| 129 | const cliOver = Effect.gen(function* () { |
| 130 | const server = yield* WalletApi; |
| 131 | const handler = HttpEffect.toWebHandler(server.fetch as never); |
| 132 | const fetch = ((input: RequestInfo | URL, init?: RequestInit) => |
| 133 | handler(new Request(input, init))) as typeof globalThis.fetch; |
| 134 | return ( |
| 135 | cli: ReturnType<typeof toCli<typeof WalletApi>>, |
| 136 | args: ReadonlyArray<string>, |
| 137 | transport: typeof globalThis.fetch = fetch, |
| 138 | ) => |
| 139 | Effect.gen(function* () { |
| 140 | const stdout: Array<string> = []; |
| 141 | const stderr: Array<string> = []; |
| 142 | const console: Console.Console = { |
| 143 | ...globalThis.console, |
| 144 | log: (...line: ReadonlyArray<unknown>) => void stdout.push(line.join(" ")), |
| 145 | error: (...line: ReadonlyArray<unknown>) => void stderr.push(line.join(" ")), |
| 146 | }; |
| 147 | const exit = yield* Command.runWith(cli, { version: "1.0.0" })(args).pipe( |
| 148 | Effect.provide(Domain.protocolHttp("http://wallet.test/")), |
| 149 | Effect.provide(FetchHttpClient.layer), |
| 150 | Effect.provideService(FetchHttpClient.Fetch, transport), |
| 151 | Effect.provide(CliEnvironment), |
| 152 | Effect.provideService(Console.Console, console), |
| 153 | Effect.exit, |
| 154 | ); |
| 155 | let code = -1; |
| 156 | Runtime.defaultTeardown(exit, (c) => (code = c)); |
| 157 | return { stdout: stdout.join("\n"), stderr: stderr.join("\n"), code, exit } satisfies Run; |
| 158 | }); |
| 159 | }); |
| 160 | |
| 161 | const WalletsLive = Layer.mergeAll(Wallets.layer(Layer.empty), SessionLive).pipe( |
| 162 | Layer.provide(InMemory), |
| 163 | ); |
| 164 | const hosted = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 165 | effect.pipe(Effect.provide(WalletsLive)) as Effect.Effect<A, E>; |
| 166 | |
| 167 | const asSam = toCli(WalletApi, { |
| 168 | name: "wallet", |
| 169 | headers: { authorization: "Bearer sam" }, |
| 170 | }); |
| 171 | |
| 172 | const json = (text: string): unknown => JSON.parse(text); |
| 173 | |
| 174 | // ---------------------------------------------------------------- tests |
| 175 | |
| 176 | describe("Domain toCli", { tags: ["unit", "local"] }, () => { |
| 177 | it.live("runs a command from flags and prints its receipt as JSON", () => |
| 178 | hosted( |
| 179 | Effect.gen(function* () { |
| 180 | const run = yield* cliOver; |
| 181 | const deposit = yield* run(asSam, [ |
| 182 | "deposit", |
| 183 | "--target", |
| 184 | "w-1", |
| 185 | "--amount", |
| 186 | "40", |
| 187 | "--note", |
| 188 | "rent", |
| 189 | "--method", |
| 190 | "card", |
| 191 | ]); |
| 192 | expect(deposit.code).toBe(0); |
| 193 | expect(deposit.stderr).toBe(""); |
| 194 | expect(json(deposit.stdout)).toEqual({ |
| 195 | reply: { balance: 40 }, |
| 196 | stream: "Wallet/w-1", |
| 197 | version: 1, |
| 198 | }); |
| 199 | |
| 200 | // The write reached the domain: the aggregate and the view read it back. |
| 201 | const wallets = yield* Wallet; |
| 202 | expect((yield* wallets.state(Wallet.ref("w-1"))).balance).toBe(40); |
| 203 | const get = yield* run(asSam, [ |
| 204 | "balance", |
| 205 | "get", |
| 206 | "--key", |
| 207 | "w-1", |
| 208 | "--at-least", |
| 209 | JSON.stringify({ stream: "Wallet/w-1", version: 1 }), |
| 210 | ]); |
| 211 | expect(get.code).toBe(0); |
| 212 | expect(json(get.stdout)).toEqual({ balance: 40 }); |
| 213 | const events = yield* run(asSam, ["balance", "list", "--key", "w-1", "--order", "desc"]); |
| 214 | expect(json(events.stdout)).toMatchObject({ |
| 215 | entries: [{ event: { _tag: "Deposited", amount: 40, note: "rent" } }], |
| 216 | cursor: null, |
| 217 | }); |
| 218 | }), |
| 219 | ), |
| 220 | ); |
| 221 | |
| 222 | it.live("exits non-zero with a typed rejection as JSON on stderr", () => |
| 223 | hosted( |
| 224 | Effect.gen(function* () { |
| 225 | const run = yield* cliOver; |
| 226 | const refused = yield* run(asSam, ["deposit", "--target", "w-1", "--amount", "500"]); |
| 227 | expect(refused.code).toBe(1); |
| 228 | expect(refused.stdout).toBe(""); |
| 229 | expect(json(refused.stderr)).toEqual({ _tag: "OverLimit", limit: 100 }); |
| 230 | const failure = Exit.isFailure(refused.exit) ? refused.exit.cause : undefined; |
| 231 | expect(String(failure)).toContain("CallRejected"); |
| 232 | |
| 233 | // The middleware's error is typed too: no bearer, no session. |
| 234 | const anonymous = yield* run(toCli(WalletApi, { name: "wallet" }), [ |
| 235 | "wallet", |
| 236 | "get", |
| 237 | "--key", |
| 238 | "w-1", |
| 239 | ]); |
| 240 | expect(anonymous.code).toBe(1); |
| 241 | expect(json(anonymous.stderr)).toEqual({ _tag: "Unauthenticated" }); |
| 242 | }), |
| 243 | ), |
| 244 | ); |
| 245 | |
| 246 | it.live("checks input against the schema before it calls the Api", () => |
| 247 | hosted( |
| 248 | Effect.gen(function* () { |
| 249 | const run = yield* cliOver; |
| 250 | const fraction = yield* run(asSam, ["deposit", "--target", "w-1", "--amount", "1.5"]); |
| 251 | expect(fraction.code).toBe(1); |
| 252 | expect(fraction.stdout).toBe(""); |
| 253 | expect(fraction.stderr).toContain("amount"); |
| 254 | const missing = yield* run(asSam, ["deposit", "--amount", "5"]); |
| 255 | expect(missing.code).toBe(1); |
| 256 | expect(missing.stderr).toContain("target"); |
| 257 | const wallets = yield* Wallet; |
| 258 | expect((yield* wallets.state(Wallet.ref("w-1"))).balance).toBe(0); |
| 259 | }), |
| 260 | ), |
| 261 | ); |
| 262 | |
| 263 | it.live("fails as a usage error when the call does not reach the Api", () => |
| 264 | hosted( |
| 265 | Effect.gen(function* () { |
| 266 | const run = yield* cliOver; |
| 267 | const offline = (() => Promise.reject(new TypeError("Unable to connect"))) as never; |
| 268 | const lost = yield* run(asSam, ["wallet", "get", "--key", "w-1"], offline); |
| 269 | expect(lost.code).toBe(1); |
| 270 | expect(lost.stdout).toBe(""); |
| 271 | expect(lost.stderr).toContain("Wallet.get did not reach the Api"); |
| 272 | }), |
| 273 | ), |
| 274 | ); |
| 275 | |
| 276 | it.live("takes the whole input as --json, and flags win over it", () => |
| 277 | hosted( |
| 278 | Effect.gen(function* () { |
| 279 | const run = yield* cliOver; |
| 280 | const deposit = yield* run(asSam, [ |
| 281 | "deposit", |
| 282 | "--json", |
| 283 | JSON.stringify({ target: "w-2", amount: 7, tags: ["a", "b"] }), |
| 284 | "--amount", |
| 285 | "9", |
| 286 | "--express", |
| 287 | ]); |
| 288 | expect(deposit.code).toBe(0); |
| 289 | expect(json(deposit.stdout)).toMatchObject({ reply: { balance: 9 } }); |
| 290 | // `--json` alone carries the input fields, as the flags do. |
| 291 | const fromJson = yield* run(asSam, [ |
| 292 | "deposit", |
| 293 | "--json", |
| 294 | JSON.stringify({ target: "w-4", amount: 4, note: "from json" }), |
| 295 | ]); |
| 296 | expect(fromJson.code).toBe(0); |
| 297 | expect(json(fromJson.stdout)).toMatchObject({ reply: { balance: 4 } }); |
| 298 | // The call's own wire JSON, with its nested `input`, works too. |
| 299 | const fromWire = yield* run(asSam, [ |
| 300 | "deposit", |
| 301 | "--json", |
| 302 | JSON.stringify({ target: "w-5", input: { amount: 6, note: "wire" } }), |
| 303 | ]); |
| 304 | expect(fromWire.code).toBe(0); |
| 305 | expect(json(fromWire.stdout)).toMatchObject({ reply: { balance: 6 } }); |
| 306 | const bad = yield* run(asSam, ["deposit", "--json", "{not json"]); |
| 307 | expect(bad.code).toBe(1); |
| 308 | expect(bad.stderr).toContain("--json"); |
| 309 | }), |
| 310 | ), |
| 311 | ); |
| 312 | |
| 313 | it.live("reads headers from an Effect on each run", () => |
| 314 | hosted( |
| 315 | Effect.gen(function* () { |
| 316 | const run = yield* cliOver; |
| 317 | const fromEnv = toCli(WalletApi, { |
| 318 | name: "wallet", |
| 319 | headers: Effect.sync(() => ({ authorization: "Bearer kim" })), |
| 320 | }); |
| 321 | const deposit = yield* run(fromEnv, ["deposit", "--target", "w-3", "--amount", "3"]); |
| 322 | expect(deposit.code).toBe(0); |
| 323 | const wallet = yield* run(fromEnv, ["wallet", "get", "--key", "w-3"]); |
| 324 | expect(json(wallet.stdout)).toEqual({ balance: 3 }); |
| 325 | }), |
| 326 | ), |
| 327 | ); |
| 328 | |
| 329 | it.live("lists what the Api serves and its request/response operations in --help", () => |
| 330 | hosted( |
| 331 | Effect.gen(function* () { |
| 332 | const run = yield* cliOver; |
| 333 | const root = yield* run(asSam, ["--help"]); |
| 334 | expect(root.code).toBe(0); |
| 335 | // One subcommand per entry, in kebab-case, with what it is. |
| 336 | expect(root.stdout).toMatch(/^\s+deposit\s+Send the Deposit command\.$/m); |
| 337 | expect(root.stdout).toMatch(/^\s+wallet\s+Read the Wallet aggregate\.$/m); |
| 338 | expect(root.stdout).toMatch(/^\s+balance\s+Read the Balance view\.$/m); |
| 339 | |
| 340 | const balance = yield* run(asSam, ["balance", "--help"]); |
| 341 | expect(balance.stdout).toMatch(/^\s+get\s+Print the key's current state\.$/m); |
| 342 | expect(balance.stdout).toMatch(/^\s+list\s+Print a page of the key's entries\.$/m); |
| 343 | expect(balance.stdout).toMatch( |
| 344 | /^\s+snapshot\s+Print the key's current state and the cursor it is valid at\.$/m, |
| 345 | ); |
| 346 | // Live reads are streams: not commands of the CLI. |
| 347 | expect(balance.stdout).not.toMatch(/\bwatch\b/); |
| 348 | expect(balance.stdout).not.toMatch(/\bevents\b/); |
| 349 | |
| 350 | const deposit = yield* run(asSam, ["deposit", "--help"]); |
| 351 | for (const flag of ["--target", "--amount", "--note", "--method", "--express", "--tags"]) { |
| 352 | expect(deposit.stdout).toContain(flag); |
| 353 | } |
| 354 | expect(deposit.stdout).toContain("--command-id"); |
| 355 | expect(deposit.stdout).toContain("--json"); |
| 356 | expect(deposit.stdout).toContain("Cents to add"); |
| 357 | }), |
| 358 | ), |
| 359 | ); |
| 360 | |
| 361 | it.live("a command whose input names a field target takes its input as --input JSON", () => |
| 362 | hosted( |
| 363 | Effect.gen(function* () { |
| 364 | class Rename extends Domain.Command("Rename", { |
| 365 | target: WalletId, |
| 366 | // `target` here is the input's own field, not the wallet. |
| 367 | input: { target: Schema.String }, |
| 368 | }) {} |
| 369 | class Names extends Domain.Aggregate("Names", { |
| 370 | id: WalletId, |
| 371 | state: Schema.Struct({}), |
| 372 | initial: {}, |
| 373 | commands: [Rename], |
| 374 | decide: { Rename: () => [] }, |
| 375 | evolve: {}, |
| 376 | }) {} |
| 377 | class Renames extends Domain.Model("Renames", { aggregates: [Names] }) {} |
| 378 | class RenameApi extends Domain.Api("RenameApi", { model: Renames }) {} |
| 379 | const run = yield* cliOver; |
| 380 | const help = yield* run(toCli(RenameApi, { name: "rename" }) as typeof asSam, [ |
| 381 | "rename", |
| 382 | "--help", |
| 383 | ]); |
| 384 | expect(help.code).toBe(0); |
| 385 | expect(help.stdout).toContain("--target"); |
| 386 | expect(help.stdout).toContain("--input"); |
| 387 | }), |
| 388 | ), |
| 389 | ); |
| 390 | |
| 391 | it.live("an Api whose names clash on the command line fails with a DefinitionError", () => |
| 392 | hosted( |
| 393 | Effect.gen(function* () { |
| 394 | const run = yield* cliOver; |
| 395 | /** The defect a run of the CLI dies with. */ |
| 396 | const defectOf = (cli: unknown) => |
| 397 | run(cli as typeof asSam, []).pipe( |
| 398 | Effect.map(({ exit }) => (Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined)), |
| 399 | ); |
| 400 | class Clash extends Domain.Command("deposit", { |
| 401 | target: WalletId, |
| 402 | events: [Deposited], |
| 403 | }) {} |
| 404 | class Clashing extends Domain.Aggregate("Clashing", { |
| 405 | id: WalletId, |
| 406 | state: Schema.Struct({}), |
| 407 | initial: {}, |
| 408 | commands: [Clash], |
| 409 | decide: { deposit: () => [] }, |
| 410 | evolve: { Deposited: (s) => s }, |
| 411 | }) {} |
| 412 | class Clashes extends Domain.Model("Clashes", { aggregates: [Wallet, Clashing] }) {} |
| 413 | class ClashApi extends Domain.Api("ClashApi", { model: Clashes, views: [] }) {} |
| 414 | expect(yield* defectOf(toCli(ClashApi, { name: "clash" }))).toMatchObject({ |
| 415 | _tag: "DefinitionError", |
| 416 | message: "ClashApi: `Deposit` and `deposit` are both the command deposit", |
| 417 | }); |
| 418 | class Reserved extends Domain.Command("Reserved", { |
| 419 | target: WalletId, |
| 420 | input: { json: Schema.String }, |
| 421 | }) {} |
| 422 | class Reserving extends Domain.Aggregate("Reserving", { |
| 423 | id: WalletId, |
| 424 | state: Schema.Struct({}), |
| 425 | initial: {}, |
| 426 | commands: [Reserved], |
| 427 | decide: { Reserved: () => [] }, |
| 428 | evolve: {}, |
| 429 | }) {} |
| 430 | class Reserves extends Domain.Model("Reserves", { aggregates: [Reserving] }) {} |
| 431 | class ReservedApi extends Domain.Api("ReservedApi", { model: Reserves }) {} |
| 432 | expect(yield* defectOf(toCli(ReservedApi, { name: "reserved" }))).toMatchObject({ |
| 433 | _tag: "DefinitionError", |
| 434 | message: expect.stringContaining("--json, which the CLI reserves"), |
| 435 | }); |
| 436 | }), |
| 437 | ), |
| 438 | ); |
| 439 | |
| 440 | it("is an Effect CLI command named after the binary", () => { |
| 441 | expect(asSam.name).toBe("wallet"); |
| 442 | expect(toCli(WalletApi).name).toBe("wallet-api"); |
| 443 | expect(CallRejected).toBeDefined(); |
| 444 | }); |
| 445 | }); |