Files
PaperClipAI/server/src/services/railway.ts
T
DottaandClaude Opus 5.5 35563b7de5 fix(railway): report restricted environments instead of a consent error (#22214)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for work
> - The Railway connection gives agents governed deployment tools, such as `list-deployments`
> - Railway Environment RBAC lets non-admin members see a restricted environment, but Railway denies reads of its services, deployments, and logs
> - The client maps this denial to `railway_api_authorization_required` and tells the user to reconnect or to use IDs from a consented workspace
> - That advice is wrong for this case: workspace consent is correct, and reconnecting does not change the result
> - This pull request identifies the restricted environment and reports the correct remedy
> - The benefit is that agents and operators get a clear, actionable error instead of an incorrect reconnect loop

## Linked Issues or Issue Description

(B) No public issue exists. Bug description:

**What happened?**
An agent called `paperclip-railway-list-deployments` for a service. In the same session, `list-projects`, `list-services`, and `list-environments` succeeded for the same project. The deployment-history call failed every time with `railway_api_authorization_required` and the message "Use IDs from a workspace selected during consent, or reconnect". The project-level reads prove that workspace consent is correct. The denied environment is restricted for the connected member, so the message sends the user to the wrong fix.

**Expected behavior**
When Railway denies the environment-scoped target check because the environment is restricted, the tool must report a distinct error. The error must say that a Railway project admin must grant access. It must not tell the user to reconnect.

**Steps to reproduce**
1. Connect Railway with a member (non-admin) account in a workspace that has a restricted environment.
2. Call `paperclip-railway-list-environments` for the project. The restricted environment is in the list.
3. Call `paperclip-railway-list-deployments` (or `service-status`) for a service in that environment.
4. Railway returns `Not Authorized`, and Paperclip reports a workspace consent error.

**Paperclip version or commit**
`master` at 8282d386da.

## What Changed

- `server/src/services/railway.ts`: When the target query fails with an authorization denial, the client reads the project's environments with `canAccess`. If the requested environment has `canAccess: false`, the client throws `railway_environment_restricted` (HTTP 403) with the admin-access remedy. In all other cases, the client throws the original error. If the access check fails, the client also throws the original error. The access check is a read query. No mutation runs after a denied target check.
- `server/src/services/railway.ts`: `list-environments` now returns `canAccess` for each environment, so agents can choose an accessible environment before they call a target tool.
- `server/src/__tests__/railway.test.ts`: Adds a regression test for the restricted, accessible, and unknown cases.
- `doc/connections/RAILWAY.md`: Adds a recovery entry for the new error code.

## Verification

- Failing before the fix: `cd server && npx vitest run src/__tests__/railway.test.ts`. The new test "reports a restricted environment instead of a workspace consent error when Railway denies the target" failed. It expected `code: "railway_environment_restricted"`, but it received `code: "railway_api_authorization_required"`. The other 28 tests passed.
- Passing after the fix: the same file passes (29/29).
- Related suites pass: `npx vitest run src/__tests__/railway.test.ts src/__tests__/railway-connection.test.ts src/__tests__/railway-ssh.test.ts src/__tests__/connector-tool-policy.test.ts` (4 files, 63 tests).
- Scoped `tsc --noEmit` with the server `tsconfig.json` for the changed files passes.
- Not run: the full server typecheck and `pnpm verify`. In the test sandbox, they used more than the 8 GB memory limit. CI must confirm them.
- Public reference for the provider behavior: https://docs.railway.com/enterprise/environment-rbac

## Risks

- Low risk. The change applies only after Railway has already denied the target check. It adds one read query in that case.
- If Railway removes or renames `canAccess`, the access check fails, and the client throws the original error, as before this change.
- The access check reads the first 100 environments of the project. If a project has more environments, the client throws the original error.
- `list-environments` output gets one more field.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), agentic coding with tool use (shell, file edits, test execution).

## Checklist

- [x] I have included a thinking path that traces from project context to this change
- [x] I have specified the model used (with version and capability details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)



Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:26:56 -06:00

345 lines
24 KiB
TypeScript

import { z } from "zod";
import { redactSensitiveText } from "../redaction.js";
import { initializeMcpHttpSession, mcpHttpRequestInit, parseMcpHttpResponseBody } from "./mcp-http.js";
export const RAILWAY_MCP_URL = "https://mcp.railway.com";
export const RAILWAY_API_URL = "https://backboard.railway.com/graphql/v2";
export const RAILWAY_TOOL_PREFIX = "paperclip-railway-";
/** Reserve time for target checks while staying inside the gateway's 60s cap. */
export function railwayCommandBudgetMs(parameters: unknown): number {
const seconds = parameters && typeof parameters === "object" ? (parameters as Record<string, unknown>).timeoutSeconds : undefined;
const requested = typeof seconds === "number" && Number.isFinite(seconds) ? seconds : 30;
return Math.min(60_000, (Math.max(1, requested) + 10) * 1000);
}
export const RAILWAY_BLOCKED_TOOLS = new Set([
"railway-agent", "accept-deploy",
// A separate repository preflight cannot bind serviceInstanceDeployV2 to the
// approved repository. Keep old catalog entries/calls blocked until Railway
// provides an atomic repository + revision mutation.
`${RAILWAY_TOOL_PREFIX}deploy-revision`,
]);
export function normalizeRailwayToolName(name: string): string {
return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[:._-]+/g, "-");
}
export function isRailwayToolBlocked(name: string): boolean {
return RAILWAY_BLOCKED_TOOLS.has(normalizeRailwayToolName(name));
}
/** Both branding and an exact endpoint are required for the built-in API bridge. */
export function isRailwayConnection(connection: {
transport: string; authKind: string; credentialSource?: string;
config: Record<string, unknown>;
}): boolean {
return connection.transport === "mcp_remote" && connection.authKind === "oauth"
&& connection.credentialSource === "paperclip_vault"
&& connection.config.sourceTemplateKey === "railway"
&& connection.config.connectionMethodKey === "mcp-oauth"
&& isRailwayEndpoint(connection.config.url);
}
export function isRailwayEndpoint(value: unknown): boolean {
return value === RAILWAY_MCP_URL || value === `${RAILWAY_MCP_URL}/`;
}
const id = z.string().uuid();
const paging = { first: z.number().int().min(1).max(100).default(25), after: z.string().max(512).optional() };
const target = { projectId: id, environmentId: id, serviceId: id };
const deploymentTarget = { ...target, deploymentId: id };
const timestamp = z.string().datetime({ offset: true }).optional();
const schema = {
"list-projects": z.object({ workspaceId: id, ...paging }).strict(),
"list-services": z.object({ projectId: id, ...paging }).strict(),
"list-environments": z.object({ projectId: id, ...paging }).strict(),
"service-status": z.object(target).strict(),
"list-deployments": z.object({ ...target, ...paging }).strict(),
"deployment-status": z.object(deploymentTarget).strict(),
"read-logs": z.object({ ...deploymentTarget, kind: z.enum(["build", "runtime"]).default("runtime"), limit: z.number().int().min(1).max(500).default(100), startDate: timestamp, endDate: timestamp, filter: z.string().max(500).optional() }).strict(),
redeploy: z.object(deploymentTarget).strict(),
restart: z.object(deploymentTarget).strict(),
rollback: z.object(deploymentTarget).strict(),
"run-command": z.object({ ...deploymentTarget, deploymentInstanceId: id, command: z.string().min(1).max(8192), timeoutSeconds: z.number().int().min(1).max(60).default(30) }).strict(),
};
type Operation = keyof typeof schema;
const titles: Record<Operation, string> = {
"list-projects": "List projects (direct)",
"list-services": "List services (direct)",
"list-environments": "List environments",
"service-status": "Get service status",
"list-deployments": "List deployments",
"deployment-status": "Get deployment status",
"read-logs": "Read deployment logs",
redeploy: "Redeploy a deployment",
restart: "Restart a deployment",
rollback: "Roll back to a deployment",
"run-command": "Run a container command",
};
const descriptions: Record<Operation, string> = {
"list-projects": "List Railway projects in an explicit authorized workspace, with bounded pagination. Use the hosted list-workspaces action to find workspace IDs.",
"list-services": "List services in one Railway project. Use service-status to inspect a specific environment.",
"list-environments": "List environments in one Railway project.",
"service-status": "Inspect a service's running and latest deployments in an explicit project and environment.",
"list-deployments": "List deployments for one explicit project, environment, and service.",
"deployment-status": "Inspect an exact deployment and its container instance IDs.",
"read-logs": "Read at most 500 build or runtime log lines for an exact deployment. Output is bounded; logs may contain sensitive application data.",
redeploy: "Redeploy an exact deployment using its previous image. This changes a running service.",
restart: "Restart an exact deployment without rebuilding. This interrupts a running service.",
rollback: "Roll back to an exact eligible deployment. This changes a running service.",
"run-command": "Run a bounded noninteractive shell command in an exact deployed container using this connection's configured SSH key. Broad privileged access: commands can read secrets and mutate application data. Requires Container access setup. Timeout closes SSH; remote child termination is not guaranteed.",
};
const reads = new Set<Operation>(["list-projects", "list-services", "list-environments", "service-status", "list-deployments", "deployment-status", "read-logs"]);
export const RAILWAY_TOOLS = Object.entries(schema).map(([operation, validator]) => ({
name: `${RAILWAY_TOOL_PREFIX}${operation}`,
title: titles[operation as Operation],
description: descriptions[operation as Operation],
inputSchema: z.toJSONSchema(validator, { target: "draft-7", io: "input" }) as Record<string, unknown>,
annotations: { readOnlyHint: reads.has(operation as Operation), destructiveHint: !reads.has(operation as Operation), idempotentHint: reads.has(operation as Operation), openWorldHint: true },
}));
export function railwayRisk(name: string): "read" | "write" | "destructive" {
name = normalizeRailwayToolName(name);
if (isRailwayToolBlocked(name)) return "destructive";
const operation = name.slice(RAILWAY_TOOL_PREFIX.length) as Operation;
if (name.startsWith(RAILWAY_TOOL_PREFIX) && operation in schema) return reads.has(operation) ? "read" : "destructive";
if (["whoami", "list-projects", "list-services", "list-feature-flags", "get-feature-flag"].includes(name)) return "read";
if (["redeploy", "accept-deploy", "railway-agent", "delete-feature-flag"].includes(name)) return "destructive";
return "write";
}
export function classifyRailwayToolRisk(tool: { name: string; annotations?: Record<string, unknown> }): "read" | "write" | "destructive" {
const risk = railwayRisk(tool.name);
const annotations = tool.annotations ?? {};
return risk === "read" && (annotations.readOnlyHint === false || annotations.writeHint === true)
? "write" : risk;
}
export class RailwayError extends Error {
constructor(readonly code: string, message: string, readonly status = 502) { super(message); this.name = "RailwayError"; }
}
export interface RailwaySshInput {
deploymentInstanceId: string; command: string; timeoutSeconds: number; signal: AbortSignal;
}
export interface RailwayClientOptions {
authorization: string;
request: (url: string, init: RequestInit) => Promise<Response>;
signal: AbortSignal;
runCommand?: (input: RailwaySshInput) => Promise<unknown>;
}
const pageInfo = "pageInfo { hasNextPage endCursor }";
const deploymentFields = "id projectId environmentId serviceId status createdAt url canRedeploy canRollback";
const instanceFields = "id environmentId serviceId serviceName source { repo } latestDeployment { id status } activeDeployments { id status }";
/** All query documents are authored here. Caller input is only ever variables. */
export const RAILWAY_QUERIES = {
projects: `query PaperclipRailwayProjects($workspaceId:String!,$first:Int!,$after:String) { projects(workspaceId:$workspaceId,first:$first,after:$after) { edges { node { id name workspaceId } } ${pageInfo} } }`,
services: `query PaperclipRailwayServices($projectId:String!,$first:Int!,$after:String) { project(id:$projectId) { id services(first:$first,after:$after) { edges { node { id name projectId } } ${pageInfo} } } }`,
environments: `query PaperclipRailwayEnvironments($projectId:String!,$first:Int!,$after:String) { project(id:$projectId) { id environments(first:$first,after:$after) { edges { node { id name projectId canAccess } } ${pageInfo} } } }`,
target: `query PaperclipRailwayTarget($projectId:String!,$environmentId:String!,$serviceId:String!) { project(id:$projectId) { id } environment(id:$environmentId) { id projectId } service(id:$serviceId) { id projectId } serviceInstance(environmentId:$environmentId,serviceId:$serviceId) { ${instanceFields} } }`,
deployment: `query PaperclipRailwayDeployment($deploymentId:String!) { deployment(id:$deploymentId) { ${deploymentFields} instances { id } } }`,
deployments: `query PaperclipRailwayDeployments($input:DeploymentListInput!,$first:Int!,$after:String) { deployments(input:$input,first:$first,after:$after) { edges { node { ${deploymentFields} } } ${pageInfo} } }`,
buildLogs: `query PaperclipRailwayBuildLogs($deploymentId:String!,$limit:Int!,$startDate:DateTime,$endDate:DateTime,$filter:String) { buildLogs(deploymentId:$deploymentId,limit:$limit,startDate:$startDate,endDate:$endDate,filter:$filter) { timestamp message severity } }`,
runtimeLogs: `query PaperclipRailwayRuntimeLogs($deploymentId:String!,$limit:Int!,$startDate:DateTime,$endDate:DateTime,$filter:String) { deploymentLogs(deploymentId:$deploymentId,limit:$limit,startDate:$startDate,endDate:$endDate,filter:$filter) { timestamp message severity } }`,
redeploy: `mutation PaperclipRailwayRedeploy($deploymentId:String!) { deploymentRedeploy(id:$deploymentId,usePreviousImageTag:true) { id status } }`,
restart: `mutation PaperclipRailwayRestart($deploymentId:String!) { deploymentRestart(id:$deploymentId) }`,
rollback: `mutation PaperclipRailwayRollback($deploymentId:String!) { deploymentRollback(id:$deploymentId) }`,
};
function record(value: unknown): Record<string, any> {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, any> : {};
}
async function boundedResponseText(response: Response, signal: AbortSignal): Promise<string> {
const reader = response.body?.getReader();
if (!reader) throw new RailwayError("railway_invalid_response", "Railway returned an empty response.");
const chunks: Uint8Array[] = [];
let size = 0;
try {
for (;;) {
signal.throwIfAborted();
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > 1024 * 1024) throw new RailwayError("railway_output_limit", "Railway's response exceeded the limit. Request fewer results or a shorter log interval.");
chunks.push(value);
}
} finally { await reader.cancel().catch(() => {}); }
return Buffer.concat(chunks).toString("utf8");
}
/** Discover a consented workspace without requesting account-wide API access. */
export async function discoverRailwayWorkspace(options: RailwayClientOptions): Promise<string> {
const send = (init: RequestInit) => options.request(RAILWAY_MCP_URL, { ...init, redirect: "error", signal: options.signal });
const headers = { Authorization: options.authorization };
const list = (requestHeaders: Record<string, string>) => send(mcpHttpRequestInit(requestHeaders, {
id: "paperclip-railway-workspace-probe", method: "tools/call", params: { name: "list-workspaces", arguments: {} },
}));
let response = await list(headers);
if (response.status === 400) {
await response.body?.cancel();
response = await list(await initializeMcpHttpSession({ send, headers, requestId: "paperclip-railway-workspace-probe" }));
}
if (!response.ok) {
await response.body?.cancel();
throw new RailwayError("railway_workspace_discovery_failed", "Railway's hosted connection is connected, but workspace access could not be checked. Refresh actions to try again.");
}
const body = await boundedResponseText(response, options.signal);
let data: Record<string, any>;
try {
const payload = record(parseMcpHttpResponseBody(body, response.headers.get("content-type")));
const result = record(payload.result);
if (payload.error || result.isError) throw new Error("Workspace discovery failed");
data = record(result.structuredContent ?? JSON.parse(result.content?.find((item: any) => item.type === "text")?.text ?? "{}"));
} catch { throw new RailwayError("railway_workspace_discovery_failed", "Railway could not list authorized workspaces. Refresh actions or reconnect and select a workspace."); }
const workspaceId = Array.isArray(data.workspaces) ? data.workspaces.find((workspace) => id.safeParse(workspace?.id).success)?.id : undefined;
if (!workspaceId) throw new RailwayError("railway_workspace_required", "No authorized Railway workspace was found. Reconnect Railway and select a workspace to enable direct operations.", 403);
return workspaceId;
}
export function createRailwayClient(options: RailwayClientOptions) {
if (!/^Bearer [^\r\n]+$/.test(options.authorization)) throw new RailwayError("railway_authorization_required", "Reconnect Railway to authorize API access.", 401);
const secret = options.authorization.slice(7);
const redact = (value: unknown) => JSON.parse(redactSensitiveText(JSON.stringify(value).split(secret).join("[REDACTED]")));
async function query(document: string, variables: Record<string, unknown>): Promise<Record<string, any>> {
options.signal.throwIfAborted();
let response: Response;
try {
response = await options.request(RAILWAY_API_URL, { method: "POST", redirect: "error", signal: options.signal, headers: { "content-type": "application/json", Authorization: options.authorization }, body: JSON.stringify({ query: document, variables }) });
} catch (error) {
if (options.signal.aborted) throw options.signal.reason;
throw new RailwayError("railway_request_failed", "Railway could not be reached. A deployment request may have succeeded; inspect deployment status before retrying.");
}
if (response.status === 401 || response.status === 403) {
await response.body?.cancel();
throw new RailwayError("railway_api_authorization_required", "Railway rejected API access. Reconnect with access to the required workspace or project. Hosted connection tokens are used only if Railway accepts them for API access.", response.status);
}
if (!response.ok) {
await response.body?.cancel();
throw new RailwayError(response.status === 429 ? "railway_rate_limited" : "railway_api_unavailable", response.status === 429 ? "Railway is rate limiting requests. Wait before trying again." : "Railway is unavailable. Check deployment status before retrying a deployment operation.");
}
const body = await boundedResponseText(response, options.signal);
let payload: Record<string, any>;
try { payload = record(JSON.parse(body)); }
catch { throw new RailwayError("railway_invalid_response", "Railway returned an invalid API response."); }
if (payload.errors) {
// Provider errors can echo variables, credentials or application secrets.
if (Array.isArray(payload.errors) && payload.errors.some((error) => ["UNAUTHENTICATED", "FORBIDDEN"].includes(error?.extensions?.code) || ["Not Authorized", "Unauthorized", "Forbidden"].includes(error?.message))) {
throw new RailwayError("railway_api_authorization_required", "Railway denied this API request. Use IDs from a workspace selected during consent, or reconnect to grant access to the required workspace.", 403);
}
throw new RailwayError("railway_api_error", "Railway could not complete the request. Check target IDs, resource permissions, and deployment eligibility. Inspect status before retrying a mutation.");
}
if (!payload.data || typeof payload.data !== "object") throw new RailwayError("railway_invalid_response", "Railway returned no API data.");
return payload.data;
}
async function environmentRestricted(args: Record<string, any>): Promise<boolean> {
try {
let after: string | undefined;
for (let page = 0; page < 10; page++) {
const data = await query(RAILWAY_QUERIES.environments, { projectId: args.projectId, first: 100, after });
const environments = record(record(data.project).environments);
const match = Array.isArray(environments.edges) ? environments.edges.find((edge) => edge?.node?.id === args.environmentId) : undefined;
if (match) return match.node.canAccess === false;
const pageInfo = record(environments.pageInfo);
if (!pageInfo.hasNextPage || typeof pageInfo.endCursor !== "string") return false;
after = pageInfo.endCursor;
}
return false;
} catch (error) {
if (options.signal.aborted) throw error;
return false;
}
}
async function validateTarget(args: Record<string, any>) {
let data: Record<string, any>;
try {
data = await query(RAILWAY_QUERIES.target, { projectId: args.projectId, environmentId: args.environmentId, serviceId: args.serviceId });
} catch (error) {
if (error instanceof RailwayError && error.code === "railway_api_authorization_required" && error.status === 403 && await environmentRestricted(args)) {
throw new RailwayError("railway_environment_restricted", "This Railway environment is restricted. The connected account can see it but cannot read its services, deployments, or logs. Ask a Railway project admin for access to the environment, or use an environment the account can access. Reconnecting does not change this.", 403);
}
throw error;
}
if (data.project?.id !== args.projectId || data.environment?.id !== args.environmentId || data.environment?.projectId !== args.projectId || data.service?.id !== args.serviceId || data.service?.projectId !== args.projectId || data.serviceInstance?.environmentId !== args.environmentId || data.serviceInstance?.serviceId !== args.serviceId) {
throw new RailwayError("railway_target_mismatch", "The service and environment do not belong to the selected Railway project.", 403);
}
return data.serviceInstance;
}
async function validateDeployment(args: Record<string, any>) {
const data = await query(RAILWAY_QUERIES.deployment, { deploymentId: args.deploymentId });
const d = record(data.deployment);
if (d.id !== args.deploymentId || d.projectId !== args.projectId || d.environmentId !== args.environmentId || d.serviceId !== args.serviceId) throw new RailwayError("railway_target_mismatch", "The deployment does not belong to the selected Railway target.", 403);
return d;
}
return {
async probe(workspaceId: string) {
if (!id.safeParse(workspaceId).success) throw new RailwayError("railway_workspace_required", "Choose an authorized Railway workspace before checking API access.", 400);
await query(RAILWAY_QUERIES.projects, { workspaceId, first: 1 });
},
async call(name: string, parameters: unknown): Promise<unknown> {
if (isRailwayToolBlocked(name)) throw new RailwayError("railway_action_blocked", "This Railway action cannot bind its effects to an approved target. Use redeploy, restart, or rollback for an existing deployment.", 403);
const operation = name.slice(RAILWAY_TOOL_PREFIX.length) as Operation;
if (!name.startsWith(RAILWAY_TOOL_PREFIX) || !Object.hasOwn(schema, operation)) throw new RailwayError("railway_unknown_tool", "Unknown Railway operation.", 400);
const parsed = schema[operation].safeParse(parameters);
if (!parsed.success) throw new RailwayError("railway_invalid_arguments", "Invalid Railway operation arguments. Use the exact IDs and limits in the action schema.", 400);
const args = parsed.data as Record<string, any>;
let result: unknown;
if (operation === "list-projects") result = await query(RAILWAY_QUERIES.projects, args);
else if (operation === "list-services" || operation === "list-environments") result = await query(operation === "list-services" ? RAILWAY_QUERIES.services : RAILWAY_QUERIES.environments, args);
else {
const instance = await validateTarget(args);
const deployment = args.deploymentId ? await validateDeployment(args) : null;
switch (operation) {
case "service-status": result = instance; break;
case "deployment-status": result = deployment; break;
case "list-deployments": result = await query(RAILWAY_QUERIES.deployments, { input: { projectId: args.projectId, environmentId: args.environmentId, serviceId: args.serviceId }, first: args.first, after: args.after }); break;
case "read-logs": {
if (args.startDate && args.endDate && Date.parse(args.startDate) > Date.parse(args.endDate)) throw new RailwayError("railway_invalid_arguments", "Log start time must precede end time.", 400);
const data = await query(args.kind === "build" ? RAILWAY_QUERIES.buildLogs : RAILWAY_QUERIES.runtimeLogs, { deploymentId: args.deploymentId, limit: args.limit, startDate: args.startDate, endDate: args.endDate, filter: args.filter });
const lines = data[args.kind === "build" ? "buildLogs" : "deploymentLogs"];
if (!Array.isArray(lines)) throw new RailwayError("railway_invalid_response", "Railway returned invalid log data.");
let bytes = 0;
let messageTruncated = false;
const bounded = [];
for (const line of lines.slice(0, args.limit)) {
const message = String(line.message ?? "");
if (message.length > 8192) messageTruncated = true;
const safe = redact({ timestamp: line.timestamp, severity: line.severity, message: message.slice(0, 8192) });
bytes += Buffer.byteLength(JSON.stringify(safe));
if (bytes > 64 * 1024) break;
bounded.push(safe);
}
result = { deploymentId: args.deploymentId, kind: args.kind, lines: bounded, truncated: messageTruncated || bounded.length < lines.length, limitReached: lines.length >= args.limit }; break;
}
case "redeploy":
if (!deployment?.canRedeploy) throw new RailwayError("railway_deployment_ineligible", "Railway does not allow this deployment to be redeployed.", 409);
result = await query(RAILWAY_QUERIES.redeploy, { deploymentId: args.deploymentId });
if (!id.safeParse(record(record(result).deploymentRedeploy).id).success) throw new RailwayError("railway_operation_unconfirmed", "Railway did not confirm a resulting deployment. Inspect deployment status before retrying.");
break;
case "restart":
result = await query(RAILWAY_QUERIES.restart, { deploymentId: args.deploymentId });
if (record(result).deploymentRestart !== true) throw new RailwayError("railway_operation_unconfirmed", "Railway did not confirm the restart. Inspect deployment status before retrying.");
result = { ...record(result), targetDeploymentId: args.deploymentId };
break;
case "rollback":
if (!deployment?.canRollback) throw new RailwayError("railway_deployment_ineligible", "Railway does not allow rollback to this deployment.", 409);
result = await query(RAILWAY_QUERIES.rollback, { deploymentId: args.deploymentId });
if (record(result).deploymentRollback !== true) throw new RailwayError("railway_operation_unconfirmed", "Railway did not confirm the rollback. Inspect deployment status before retrying.");
result = { ...record(result), targetDeploymentId: args.deploymentId };
break;
case "run-command":
if (!Array.isArray(deployment?.instances) || !deployment.instances.some((entry: { id: string }) => entry.id === args.deploymentInstanceId) || deployment.status !== "SUCCESS") throw new RailwayError("railway_target_mismatch", "The container instance is not part of the selected running deployment.", 403);
if (!options.runCommand) throw new RailwayError("railway_ssh_setup_required", "Configure Container access on this Railway connection before running commands.", 422);
result = await options.runCommand({ deploymentInstanceId: args.deploymentInstanceId, command: args.command, timeoutSeconds: args.timeoutSeconds, signal: options.signal }); break;
}
}
return redact(result ?? null);
},
};
}