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
| 1 | import { Query, type UnwrapPlan } from "@distilled.cloud/core/query"; |
| 2 | import { |
| 3 | Railway, |
| 4 | type CloudAgent as RailwayCloudAgent, |
| 5 | type CloudAgentStatus, |
| 6 | } from "@distilled.cloud/railway"; |
| 7 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 8 | import { isResolved } from "alchemy/Diff"; |
| 9 | import * as Provider from "alchemy/Provider"; |
| 10 | import { Resource } from "alchemy/Resource"; |
| 11 | import * as Data from "effect/Data"; |
| 12 | import * as Effect from "effect/Effect"; |
| 13 | import { waitUntilDeleted } from "./GraphQL.ts"; |
| 14 | import { createRailwayName, matchesAlchemyPhysicalName, sanitizeRailwayName } from "./Metadata.ts"; |
| 15 | import { ownedProjects, projectEnvironmentIds } from "./Project.ts"; |
| 16 | import type { Providers } from "./Providers.ts"; |
| 17 | |
| 18 | const agentFields = <E>(agent: Query<RailwayCloudAgent, E>) => ({ |
| 19 | id: agent.id, |
| 20 | name: agent.name, |
| 21 | environmentId: agent.environmentId, |
| 22 | projectId: agent.projectId, |
| 23 | status: agent.status, |
| 24 | domain: agent.domain, |
| 25 | domains: agent.domains.pipe( |
| 26 | Query.map((item) => ({ domain: item.domain, port: item.port, prefix: item.prefix })), |
| 27 | ), |
| 28 | consoleTargetId: agent.consoleTargetId, |
| 29 | createdAt: agent.createdAt, |
| 30 | }); |
| 31 | type CloudRow = UnwrapPlan<ReturnType<typeof agentFields>>; |
| 32 | |
| 33 | /** |
| 34 | * A resource-valued prop: the resource itself, or an Effect that produces |
| 35 | * it (so `yield* Project(...)` and `Project(...)` both type-check). |
| 36 | */ |
| 37 | type Ref<T> = T | Effect.Effect<T, never, Providers>; |
| 38 | |
| 39 | /** |
| 40 | * Environment identity a cloud agent is created in. Accepts a |
| 41 | * `Railway.Project` (its primary environment), a `Railway.Environment`, |
| 42 | * or an `{ environmentId }` stub. |
| 43 | */ |
| 44 | export type CloudAgentEnvironment = { readonly environmentId: string; readonly projectId?: string }; |
| 45 | |
| 46 | export interface CloudAgentProps { |
| 47 | /** |
| 48 | * Environment the agent VM lives in. Accepts a `Railway.Project` |
| 49 | * (primary environment), a `Railway.Environment`, or `{ environmentId }`. |
| 50 | * Changing it replaces the agent. |
| 51 | */ |
| 52 | environment: Ref<CloudAgentEnvironment>; |
| 53 | /** |
| 54 | * Agent name. Unique per environment for this user. If omitted, a |
| 55 | * unique name is generated from the stack, stage and logical ID. |
| 56 | * Changing it replaces the agent — Railway has no rename API. |
| 57 | */ |
| 58 | name?: string; |
| 59 | /** |
| 60 | * Variables written to the agent at create time. Values may be |
| 61 | * Railway reference templates (`Railway.ref(...)`). Create-only; |
| 62 | * ignored on update. Never persisted in attributes. |
| 63 | */ |
| 64 | variables?: Record<string, string>; |
| 65 | } |
| 66 | |
| 67 | export type CloudAgent = Resource< |
| 68 | "Railway.CloudAgent", |
| 69 | CloudAgentProps, |
| 70 | { |
| 71 | /** Railway cloud agent id. */ |
| 72 | cloudAgentId: string; |
| 73 | /** Physical agent name. */ |
| 74 | name: string; |
| 75 | /** Environment the agent lives in. */ |
| 76 | environmentId: string; |
| 77 | /** Parent Railway project id. */ |
| 78 | projectId: string; |
| 79 | /** Observed lifecycle status (`STARTING`, `RUNNING`, `SLEEPING`, …). */ |
| 80 | status: CloudAgentStatus; |
| 81 | /** |
| 82 | * Public hostname serving port 8080. Stable across sleep and wake; |
| 83 | * `undefined` while the machine is asleep. |
| 84 | */ |
| 85 | domain: string | undefined; |
| 86 | /** Every public domain on the machine, one per port. */ |
| 87 | domains: ReadonlyArray<{ domain: string; port: number; prefix: string }>; |
| 88 | /** Console / exec target id. `undefined` while unavailable. */ |
| 89 | consoleTargetId: string | undefined; |
| 90 | /** RFC3339 creation timestamp. */ |
| 91 | createdAt: string; |
| 92 | }, |
| 93 | never, |
| 94 | Providers |
| 95 | >; |
| 96 | |
| 97 | /** |
| 98 | * A Railway.CloudAgent is a persistent coding-agent VM in an |
| 99 | * environment. Sleep keeps the disk; wake re-runs the entrypoint. |
| 100 | * Cloud agents are Priority Boarding and bill at VM rates while |
| 101 | * running. |
| 102 | * |
| 103 | * @see https://docs.railway.com/cloud-agents |
| 104 | * |
| 105 | * ### Create a CloudAgent |
| 106 | * Pass the Project (or an Environment). Alchemy generates a unique |
| 107 | * name unless you pass one. `domain` is the public URL for port 8080. |
| 108 | * |
| 109 | * **Example:** Next to a Project |
| 110 | * ```typescript |
| 111 | * const site = yield* Railway.Project("Site"); |
| 112 | * const agent = yield* Railway.CloudAgent("Coder", { |
| 113 | * environment: site, |
| 114 | * }); |
| 115 | * ``` |
| 116 | * |
| 117 | * :::caution[Changing `environment` or `name` replaces the agent] |
| 118 | * Railway has no cloud-agent update API. A new VM is created, then |
| 119 | * the old one is deleted — the disk is not copied. |
| 120 | * ::: |
| 121 | * |
| 122 | * ### A stable name |
| 123 | * Pass `name` when you need a stable agent name. Changing it later |
| 124 | * replaces the agent. |
| 125 | * |
| 126 | * **Example:** Explicit name |
| 127 | * ```typescript |
| 128 | * const agent = yield* Railway.CloudAgent("Coder", { |
| 129 | * environment: site, |
| 130 | * name: "reviews", |
| 131 | * }); |
| 132 | * ``` |
| 133 | * |
| 134 | * ### Variables |
| 135 | * `variables` are create-only. Pair them with a new agent — Railway |
| 136 | * does not update variables on an existing VM. Values may reference |
| 137 | * other services via `Railway.ref`. |
| 138 | * |
| 139 | * **Example:** Variables at create |
| 140 | * ```typescript |
| 141 | * const agent = yield* Railway.CloudAgent("Coder", { |
| 142 | * environment: site, |
| 143 | * variables: { |
| 144 | * DATABASE_URL: Railway.ref(db, "DATABASE_URL"), |
| 145 | * }, |
| 146 | * }); |
| 147 | * ``` |
| 148 | * |
| 149 | * ### Sleep and wake |
| 150 | * Sleep stops compute billing and keeps the disk. Wake re-runs the |
| 151 | * entrypoint with files in place. These are not reconciler steps — |
| 152 | * call {@link sleepCloudAgent} / {@link wakeCloudAgent}. |
| 153 | * |
| 154 | * **Example:** Sleep then wake |
| 155 | * ```typescript |
| 156 | * yield* Railway.sleepCloudAgent(agent); |
| 157 | * yield* Railway.wakeCloudAgent(agent); |
| 158 | * ``` |
| 159 | * |
| 160 | * ### Module-scope declarations |
| 161 | * Resource-valued props accept the resource or an Effect producing it. |
| 162 | * |
| 163 | * **Example:** Module-scope CloudAgent |
| 164 | * ```typescript |
| 165 | * // src/agent.ts |
| 166 | * import * as Railway from "@alchemy.run/railway"; |
| 167 | * |
| 168 | * export const Site = Railway.Project("Site"); |
| 169 | * export const Coder = Railway.CloudAgent("Coder", { |
| 170 | * environment: Site, |
| 171 | * }); |
| 172 | * ``` |
| 173 | * |
| 174 | * @resource |
| 175 | * @product Cloud Agent |
| 176 | */ |
| 177 | export const CloudAgent = Resource<CloudAgent>("Railway.CloudAgent"); |
| 178 | |
| 179 | export class CloudAgentNotCreated extends Data.TaggedError("Railway.CloudAgentNotCreated")<{ |
| 180 | resourceName: string; |
| 181 | environmentId: string; |
| 182 | }> {} |
| 183 | |
| 184 | export class CloudAgentEnvironmentRequired extends Data.TaggedError( |
| 185 | "Railway.CloudAgentEnvironmentRequired", |
| 186 | )<{ message: string }> {} |
| 187 | |
| 188 | const toAttrs = ( |
| 189 | agent: CloudRow, |
| 190 | fallback?: { name?: string; environmentId?: string; projectId?: string }, |
| 191 | ): CloudAgent["Attributes"] => ({ |
| 192 | cloudAgentId: agent.id, |
| 193 | name: agent.name || fallback?.name || "", |
| 194 | environmentId: agent.environmentId || fallback?.environmentId || "", |
| 195 | projectId: agent.projectId || fallback?.projectId || "", |
| 196 | status: agent.status, |
| 197 | domain: agent.domain ?? undefined, |
| 198 | domains: agent.domains.map((item) => ({ |
| 199 | domain: item.domain, |
| 200 | port: item.port, |
| 201 | prefix: item.prefix, |
| 202 | })), |
| 203 | consoleTargetId: agent.consoleTargetId ?? undefined, |
| 204 | createdAt: agent.createdAt, |
| 205 | }); |
| 206 | |
| 207 | const resolveName = (id: string, name: string | undefined, existing?: string) => |
| 208 | Effect.gen(function* () { |
| 209 | if (name !== undefined) return sanitizeRailwayName(name); |
| 210 | if (existing !== undefined) return existing; |
| 211 | return yield* createRailwayName(id); |
| 212 | }); |
| 213 | |
| 214 | const isGone = (agent: CloudRow | undefined) => agent === undefined || agent.status === "DELETING"; |
| 215 | |
| 216 | const environmentIdOf = (value: unknown): string | undefined => { |
| 217 | if (value === null || typeof value !== "object") return undefined; |
| 218 | const rec = value as { environmentId?: unknown }; |
| 219 | return typeof rec.environmentId === "string" && rec.environmentId.length > 0 |
| 220 | ? rec.environmentId |
| 221 | : undefined; |
| 222 | }; |
| 223 | |
| 224 | const projectIdOf = (value: unknown): string | undefined => { |
| 225 | if (value === null || typeof value !== "object") return undefined; |
| 226 | const rec = value as { projectId?: unknown }; |
| 227 | return typeof rec.projectId === "string" && rec.projectId.length > 0 ? rec.projectId : undefined; |
| 228 | }; |
| 229 | |
| 230 | const cloudAgents = Query.fn((environmentId: string) => |
| 231 | Railway.cloudAgents({ environmentId, mine: true }).pipe(Query.map(agentFields)), |
| 232 | ); |
| 233 | |
| 234 | const listAgents = (environmentId: string) => |
| 235 | cloudAgents(environmentId).pipe( |
| 236 | Effect.catchTag(["RailwayForbidden", "RailwayPlanLimitExceeded"], () => |
| 237 | Effect.succeed([] as CloudRow[]), |
| 238 | ), |
| 239 | ); |
| 240 | |
| 241 | const cloudAgentCreate = Query.fn( |
| 242 | (input: { environmentId: string; name: string; variables?: Record<string, string> }) => |
| 243 | agentFields(Railway.cloudAgentCreate({ input })), |
| 244 | ); |
| 245 | |
| 246 | const cloudAgentSleep = Query.fn((id: string) => agentFields(Railway.cloudAgentSleep({ id }))); |
| 247 | |
| 248 | const cloudAgentWake = Query.fn((id: string) => agentFields(Railway.cloudAgentWake({ id }))); |
| 249 | |
| 250 | const cloudAgentDelete = Query.fn((id: string) => Railway.cloudAgentDelete({ id })); |
| 251 | |
| 252 | const findById = (environmentId: string, id: string) => |
| 253 | listAgents(environmentId).pipe(Effect.map((items) => items.find((agent) => agent.id === id))); |
| 254 | |
| 255 | const findByName = (environmentId: string, name: string) => |
| 256 | listAgents(environmentId).pipe( |
| 257 | Effect.map((items) => items.find((agent) => !isGone(agent) && agent.name === name)), |
| 258 | ); |
| 259 | |
| 260 | const waitUntilGone = (environmentId: string, cloudAgentId: string) => |
| 261 | waitUntilDeleted( |
| 262 | "CloudAgent", |
| 263 | cloudAgentId, |
| 264 | findById(environmentId, cloudAgentId).pipe(Effect.map((agent) => isGone(agent))), |
| 265 | ); |
| 266 | |
| 267 | const cloudAgentIdOf = (agent: { readonly cloudAgentId: string } | string): string => |
| 268 | typeof agent === "string" ? agent : agent.cloudAgentId; |
| 269 | |
| 270 | /** |
| 271 | * Sleep a running cloud agent. Compute billing stops; the disk is |
| 272 | * kept. Waking re-runs the entrypoint. |
| 273 | */ |
| 274 | export const sleepCloudAgent = Effect.fn(function* ( |
| 275 | agent: { readonly cloudAgentId: string } | string, |
| 276 | ) { |
| 277 | return yield* cloudAgentSleep(cloudAgentIdOf(agent)); |
| 278 | }); |
| 279 | |
| 280 | /** |
| 281 | * Wake a sleeping cloud agent. Crashed or failed agents cannot be |
| 282 | * woken — create a new one instead. |
| 283 | */ |
| 284 | export const wakeCloudAgent = Effect.fn(function* ( |
| 285 | agent: { readonly cloudAgentId: string } | string, |
| 286 | ) { |
| 287 | return yield* cloudAgentWake(cloudAgentIdOf(agent)); |
| 288 | }); |
| 289 | |
| 290 | export const CloudAgentProvider = () => |
| 291 | Provider.succeed(CloudAgent, { |
| 292 | stables: ["cloudAgentId", "environmentId", "projectId", "createdAt"], |
| 293 | nuke: { dependsOn: ["Railway.Project"] }, |
| 294 | |
| 295 | diff: Effect.fn(function* ({ news, output }) { |
| 296 | if (news === undefined || !isResolved(news)) return undefined; |
| 297 | if (output === undefined) return undefined; |
| 298 | const nextEnvironmentId = environmentIdOf(news.environment); |
| 299 | const environmentChanged = |
| 300 | nextEnvironmentId !== undefined && nextEnvironmentId !== output.environmentId; |
| 301 | const nameChanged = news.name !== undefined && sanitizeRailwayName(news.name) !== output.name; |
| 302 | if (environmentChanged || nameChanged) { |
| 303 | return { action: "replace" as const }; |
| 304 | } |
| 305 | return undefined; |
| 306 | }), |
| 307 | |
| 308 | read: Effect.fn(function* ({ id, olds, output }) { |
| 309 | const name = yield* resolveName(id, olds?.name, output?.name); |
| 310 | const environmentId = |
| 311 | output?.environmentId ?? |
| 312 | (olds !== undefined ? environmentIdOf(olds.environment) : undefined); |
| 313 | if (environmentId === undefined) return undefined; |
| 314 | const found = |
| 315 | (output?.cloudAgentId !== undefined |
| 316 | ? yield* findById(environmentId, output.cloudAgentId) |
| 317 | : undefined) ?? (yield* findByName(environmentId, name)); |
| 318 | if (found === undefined || isGone(found)) return undefined; |
| 319 | const attrs = toAttrs(found, { |
| 320 | name, |
| 321 | environmentId, |
| 322 | projectId: |
| 323 | output?.projectId ?? (olds !== undefined ? projectIdOf(olds.environment) : undefined), |
| 324 | }); |
| 325 | if (output !== undefined) return attrs; |
| 326 | return matchesAlchemyPhysicalName(found.name) ? attrs : Unowned(attrs); |
| 327 | }), |
| 328 | |
| 329 | list: Effect.fn(function* () { |
| 330 | const projects = yield* ownedProjects(); |
| 331 | const rows = yield* Effect.forEach(projects, (project) => |
| 332 | Effect.gen(function* () { |
| 333 | const envIds = yield* projectEnvironmentIds(project); |
| 334 | const nested = yield* Effect.forEach(envIds, (environmentId) => |
| 335 | listAgents(environmentId).pipe( |
| 336 | Effect.map((agents) => |
| 337 | agents |
| 338 | .filter((agent) => !isGone(agent) && matchesAlchemyPhysicalName(agent.name)) |
| 339 | .map((agent) => toAttrs(agent, { environmentId, projectId: project.projectId })), |
| 340 | ), |
| 341 | ), |
| 342 | ); |
| 343 | return nested.flat(); |
| 344 | }), |
| 345 | ); |
| 346 | const seen = new Set<string>(); |
| 347 | const unique: CloudAgent["Attributes"][] = []; |
| 348 | for (const row of rows.flat()) { |
| 349 | if (seen.has(row.cloudAgentId)) continue; |
| 350 | seen.add(row.cloudAgentId); |
| 351 | unique.push(row); |
| 352 | } |
| 353 | return unique; |
| 354 | }), |
| 355 | |
| 356 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 357 | const props = news ?? ({} as CloudAgentProps); |
| 358 | const environmentId = environmentIdOf(props.environment) ?? output?.environmentId; |
| 359 | if (environmentId === undefined) { |
| 360 | return yield* new CloudAgentEnvironmentRequired({ |
| 361 | message: "CloudAgent requires a resolved Railway.Project or Railway.Environment", |
| 362 | }); |
| 363 | } |
| 364 | const name = yield* resolveName(id, props.name, output?.name); |
| 365 | const projectId = projectIdOf(props.environment) ?? output?.projectId ?? ""; |
| 366 | |
| 367 | let current = |
| 368 | output?.cloudAgentId !== undefined |
| 369 | ? yield* findById(environmentId, output.cloudAgentId) |
| 370 | : undefined; |
| 371 | if (current === undefined || isGone(current)) { |
| 372 | current = yield* findByName(environmentId, name); |
| 373 | } |
| 374 | |
| 375 | if (current === undefined || isGone(current)) { |
| 376 | const created = yield* cloudAgentCreate({ |
| 377 | environmentId, |
| 378 | name, |
| 379 | ...(props.variables !== undefined ? { variables: props.variables } : {}), |
| 380 | }).pipe(Effect.catchTag("RailwayValidationError", () => Effect.undefined)); |
| 381 | current = |
| 382 | created !== undefined && !isGone(created) |
| 383 | ? created |
| 384 | : yield* findByName(environmentId, name); |
| 385 | } |
| 386 | |
| 387 | if (current === undefined || isGone(current)) { |
| 388 | return yield* new CloudAgentNotCreated({ resourceName: name, environmentId }); |
| 389 | } |
| 390 | |
| 391 | return toAttrs(current, { name, environmentId, projectId }); |
| 392 | }), |
| 393 | |
| 394 | delete: Effect.fn(function* ({ output }) { |
| 395 | const cloudAgentId = output.cloudAgentId; |
| 396 | if (cloudAgentId.length === 0) return; |
| 397 | yield* cloudAgentDelete(cloudAgentId); |
| 398 | if (output.environmentId.length > 0) { |
| 399 | yield* waitUntilGone(output.environmentId, cloudAgentId); |
| 400 | } |
| 401 | }), |
| 402 | }); |