|
| 1 | +/** |
| 2 | + * Dashboard client for the Codex CLI update workflow (#2811). The server owns every decision: |
| 3 | + * the read-only plan, the planId it binds, admission, the install and its readback |
| 4 | + * (src/server/management/codex-cli-update-routes.ts). This module only reads those DTOs and |
| 5 | + * posts the one confirmed request; it never regenerates a plan or retries an ambiguous result. |
| 6 | + */ |
| 7 | + |
| 8 | +export type CodexCliProvenance = "npm-global" | "app-bundle" | "version-manager" | "standalone-unverified" | "unknown"; |
| 9 | +export type CodexCliSessionState = "none" | "active" | "unknown" | "not-evaluated"; |
| 10 | +export type CodexCliJobStatus = "queued" | "running" | "applied" | "not_applied" | "refused" | "ambiguous"; |
| 11 | + |
| 12 | +export interface CodexCliUpdatePlanView { |
| 13 | + applicable: boolean; |
| 14 | + refusal: string | null; |
| 15 | + planId: string | null; |
| 16 | + provenance: CodexCliProvenance; |
| 17 | + managed: boolean; |
| 18 | + installedVersion: string | null; |
| 19 | + targetVersion: string | null; |
| 20 | + location: string | null; |
| 21 | + session: { state: CodexCliSessionState; matches: number | null }; |
| 22 | + command: readonly string[] | null; |
| 23 | +} |
| 24 | + |
| 25 | +export interface CodexCliUpdateJobView { |
| 26 | + jobId: string; |
| 27 | + status: CodexCliJobStatus; |
| 28 | + ownerState: "active" | "unknown" | "finished"; |
| 29 | + planId: string; |
| 30 | + reason: string | null; |
| 31 | +} |
| 32 | + |
| 33 | +/** A refused or failed request. `retryable` is true only where the same requestId may be sent again. */ |
| 34 | +export class CodexCliUpdateError extends Error { |
| 35 | + readonly code: string; |
| 36 | + readonly status: number; |
| 37 | + readonly retryable: boolean; |
| 38 | + constructor(code: string, status: number, retryable: boolean) { |
| 39 | + super(code); |
| 40 | + this.code = code; |
| 41 | + this.status = status; |
| 42 | + this.retryable = retryable; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +const PROVENANCE = new Set(["npm-global", "app-bundle", "version-manager", "standalone-unverified", "unknown"]); |
| 47 | +const SESSION = new Set(["none", "active", "unknown", "not-evaluated"]); |
| 48 | +const STATUS = new Set(["queued", "running", "applied", "not_applied", "refused", "ambiguous"]); |
| 49 | +const OWNER = new Set(["active", "unknown", "finished"]); |
| 50 | +/** Failures after which resending the same request is idempotent: the server returns the job it already admitted, if any, and never admits a second. */ |
| 51 | +const RETRYABLE_APPLY = new Set(["job_store_busy", "admission_failed", "network"]); |
| 52 | + |
| 53 | +const str = (value: unknown): string | null => typeof value === "string" ? value : null; |
| 54 | + |
| 55 | +export function readPlan(value: unknown): CodexCliUpdatePlanView | null { |
| 56 | + if (!value || typeof value !== "object") return null; |
| 57 | + const row = value as Record<string, unknown>; |
| 58 | + const session = row.session as Record<string, unknown> | undefined; |
| 59 | + if (typeof row.applicable !== "boolean" || typeof row.managed !== "boolean" |
| 60 | + || !PROVENANCE.has(row.provenance as string) || !session || !SESSION.has(session.state as string)) return null; |
| 61 | + const command = Array.isArray(row.command) && row.command.every(part => typeof part === "string") ? row.command as string[] : null; |
| 62 | + return { |
| 63 | + applicable: row.applicable, refusal: str(row.refusal), planId: str(row.planId), |
| 64 | + provenance: row.provenance as CodexCliProvenance, managed: row.managed, |
| 65 | + installedVersion: str(row.installedVersion), targetVersion: str(row.targetVersion), location: str(row.location), |
| 66 | + session: { state: session.state as CodexCliSessionState, matches: typeof session.matches === "number" ? session.matches : null }, |
| 67 | + command, |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +export function readJob(value: unknown): CodexCliUpdateJobView | null { |
| 72 | + if (!value || typeof value !== "object") return null; |
| 73 | + const row = value as Record<string, unknown>; |
| 74 | + if (typeof row.jobId !== "string" || !STATUS.has(row.status as string) || !OWNER.has(row.ownerState as string) |
| 75 | + || typeof row.planId !== "string") return null; |
| 76 | + return { jobId: row.jobId, status: row.status as CodexCliJobStatus, ownerState: row.ownerState as CodexCliUpdateJobView["ownerState"], |
| 77 | + planId: row.planId, reason: str(row.reason) }; |
| 78 | +} |
| 79 | + |
| 80 | +/** Apply is offered only for an applicable plan with a bound id, after the operator confirmed it. */ |
| 81 | +export function canApply(plan: CodexCliUpdatePlanView | null, confirmed: boolean): boolean { |
| 82 | + return !!plan && plan.applicable && plan.refusal === null && plan.planId !== null && confirmed; |
| 83 | +} |
| 84 | + |
| 85 | +/** A job is settled once its status is final and no owner is still writing it. */ |
| 86 | +export function isTerminalJob(job: CodexCliUpdateJobView): boolean { |
| 87 | + return job.status !== "queued" && job.status !== "running" && job.ownerState !== "active"; |
| 88 | +} |
| 89 | + |
| 90 | +async function errorCode(res: Response, fallback: string): Promise<string> { |
| 91 | + try { |
| 92 | + const body = await res.json() as { error?: unknown }; |
| 93 | + return typeof body.error === "string" ? body.error : fallback; |
| 94 | + } catch { return fallback; } |
| 95 | +} |
| 96 | + |
| 97 | +export async function fetchCodexCliUpdatePlan(apiBase: string, signal: AbortSignal): Promise<CodexCliUpdatePlanView> { |
| 98 | + const res = await fetch(`${apiBase}/api/codex/cli-update/plan`, { signal, cache: "no-store" }); |
| 99 | + if (!res.ok) throw new CodexCliUpdateError(await errorCode(res, "plan_unavailable"), res.status, false); |
| 100 | + const plan = readPlan(await res.json()); |
| 101 | + if (!plan) throw new CodexCliUpdateError("plan_unavailable", res.status, false); |
| 102 | + return plan; |
| 103 | +} |
| 104 | + |
| 105 | +export async function applyCodexCliUpdate(apiBase: string, request: { requestId: string; planId: string }, signal: AbortSignal): Promise<CodexCliUpdateJobView> { |
| 106 | + let res: Response; |
| 107 | + try { |
| 108 | + res = await fetch(`${apiBase}/api/codex/cli-update/apply`, { |
| 109 | + method: "POST", signal, headers: { "Content-Type": "application/json" }, |
| 110 | + body: JSON.stringify({ requestId: request.requestId, planId: request.planId, confirmed: true }), |
| 111 | + }); |
| 112 | + } catch (error) { |
| 113 | + if (signal.aborted) throw error; |
| 114 | + throw new CodexCliUpdateError("network", 0, true); |
| 115 | + } |
| 116 | + if (!res.ok) { |
| 117 | + const code = await errorCode(res, "admission_failed"); |
| 118 | + throw new CodexCliUpdateError(code, res.status, RETRYABLE_APPLY.has(code)); |
| 119 | + } |
| 120 | + const job = readJob(((await res.json()) as { job?: unknown }).job); |
| 121 | + if (!job) throw new CodexCliUpdateError("job_result_unknown", res.status, false); |
| 122 | + return job; |
| 123 | +} |
| 124 | + |
| 125 | +export async function fetchCodexCliUpdateJob(apiBase: string, jobId: string, signal: AbortSignal): Promise<CodexCliUpdateJobView> { |
| 126 | + let res: Response; |
| 127 | + try { |
| 128 | + res = await fetch(`${apiBase}/api/codex/cli-update/jobs/${encodeURIComponent(jobId)}`, { signal, cache: "no-store" }); |
| 129 | + } catch (error) { |
| 130 | + if (signal.aborted) throw error; |
| 131 | + throw new CodexCliUpdateError("network", 0, true); |
| 132 | + } |
| 133 | + if (!res.ok) { |
| 134 | + const code = await errorCode(res, "job_state_unavailable"); |
| 135 | + throw new CodexCliUpdateError(code, res.status, code !== "job_not_found"); |
| 136 | + } |
| 137 | + const job = readJob(await res.json()); |
| 138 | + if (!job) throw new CodexCliUpdateError("job_state_unavailable", res.status, true); |
| 139 | + return job; |
| 140 | +} |
| 141 | + |
| 142 | +/** The terminal equivalents the panel offers when the dashboard cannot apply or read a job. */ |
| 143 | +export function codexCliApplyCommand(planId: string | null): string { |
| 144 | + return planId ? `ocx system codex-cli-update apply --plan-id ${planId} --yes` : "ocx system codex-cli-update plan"; |
| 145 | +} |
| 146 | + |
| 147 | +export function codexCliStatusCommand(jobId: string): string { |
| 148 | + return `ocx system codex-cli-update status ${jobId} --json`; |
| 149 | +} |
| 150 | + |
| 151 | +/** |
| 152 | + * A fresh request id. `crypto.randomUUID` exists only in secure contexts; `getRandomValues` |
| 153 | + * does not need one. Null means no id could be made, and the caller must not send. |
| 154 | + */ |
| 155 | +export function newCodexCliRequestId(): string | null { |
| 156 | + const api = globalThis.crypto; |
| 157 | + try { |
| 158 | + if (api && typeof api.randomUUID === "function") return api.randomUUID(); |
| 159 | + } catch { /* not a secure context: fall through */ } |
| 160 | + if (api && typeof api.getRandomValues === "function") { |
| 161 | + const bytes = api.getRandomValues(new Uint8Array(16)); |
| 162 | + bytes[6] = (bytes[6]! & 0x0f) | 0x40; |
| 163 | + bytes[8] = (bytes[8]! & 0x3f) | 0x80; |
| 164 | + const hex = [...bytes].map(byte => byte.toString(16).padStart(2, "0")).join(""); |
| 165 | + return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join("-"); |
| 166 | + } |
| 167 | + return null; |
| 168 | +} |
0 commit comments