import { env } from "cloudflare:workers";
import { z } from "zod";
import { all, first, run } from "../db";
import { HttpError } from "../errors";
import { enforceRateLimit, requestIp } from "../limits";
import { loadRepoById } from "../repos";
import { credentialAllows, requestCredential } from "../token-scope";
import { loadJobExecution, runnerStub } from "./jobs";
import type { WorkflowJobRow } from "./jobs";
import type { LogRow } from "./runner-do";
import { randomId } from "../crypto";
import { claimOnce } from "./runner-claim";
import { checkRunnerBells } from "./job-doorbell";
import {
deleteRunnerRow,
MAX_RUNNER_JOBS,
needsRotation,
purgeExpiredRegistrations,
registerRunner,
rotateRunnerToken,
runnerForToken,
summarizeRunner,
} from "./runner-registration";
import type { RunnerRow } from "./runner-registration";
const STALE_RUNNER_MS = 3 * 60 * 1000;
const LAST_SEEN_WRITE_MS = 15 * 1000;
const LONG_POLL_MAX_MS = 25 * 1000;
const CLAIM_RETRY_MS = 2 * 1000;
const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
const MAX_ARTIFACT_BYTES = 1024 * 1024 * 1024;
const MAX_ARTIFACTS_PER_JOB = 20;
const MAX_REGISTER_BODY_BYTES = 16 * 1024;
const ROTATE_HEADER = "x-gitfor-rotate";
const registerBody = z.object({
token: z.string().min(1).max(200),
name: z.string().min(1).max(64),
labels: z.array(z.string().max(32)).max(20).default([]),
os: z.string().max(16),