Files
archie/ui/src/lib/api.ts
T
sam 0f75475b91 feat(ui): schedules table, runs page and Schedule trigger
Schedules list as a table with enable, run now, edit, duplicate, delete and
view runs; built-ins only enable, retime and run. The runs page links each
run's tasks through its capture's dispatches. The Start node gains a Schedule
trigger that picks or creates a schedule and binds the schedule source to the
workflow. Times show in a per-browser display zone set under Appearance; the
cron time zone and run retention are edited on the Schedules page.
2026-10-26 00:57:52 +11:00

502 lines
23 KiB
TypeScript

// Single place that knows how to talk to archied. Every feature folder goes
// through api.* below, and every api.* method goes through send(), so the CSRF
// header, the Content-Type, the request timeout, and the error shape live in
// this one file.
import { streamStateFor, type StreamState } from "./stream-state.ts";
import { streamURL } from "./stream-url.ts";
import { randomUUID } from "./uuid.ts";
// DEFAULT_TIMEOUT_MS bounds a request so a daemon that accepts the connection
// but never answers cannot leave the UI in a loading state with no way back.
// The retry affordances rely on fetch settling, so bound it.
const DEFAULT_TIMEOUT_MS = 15000;
/** Query values are omitted when empty, so the server sees an absent filter.
* An array becomes a repeated parameter, as filters like `categories` expect. */
export type QueryValue =
| string
| number
| boolean
| readonly (string | number)[]
| null
| undefined;
export type QueryParams = Record<string, QueryValue>;
/** Opaque payloads are passed through unchanged; the server owns their shape. */
export type Payload = Record<string, unknown>;
// qs builds a query string, omitting empty values so the server sees an
// absent filter rather than an empty one.
function qs(params?: QueryParams): string {
const q = new URLSearchParams();
for (const [k, v] of Object.entries(params || {})) {
if (v === "" || v == null) continue;
if (Array.isArray(v)) {
for (const item of v) {
if (item !== "" && item != null) q.append(k, String(item));
}
} else {
q.set(k, String(v));
}
}
const s = q.toString();
return s ? `?${s}` : "";
}
// errorMessage prefers what the server actually said. archied answers these
// with http.Error, i.e. a plain-text reason -- "task is not awaiting
// approval", "max retries reached (3/3)", "Content-Type must be
// application/json" -- and discarding it in favour of "409 Conflict" throws
// away the only part an operator can act on.
async function errorMessage(res: Response): Promise<string> {
try {
const body = (await res.text()).trim();
if (body) return body.split("\n")[0].slice(0, 200);
} catch {
// Body already consumed or unreadable; fall through to the status.
}
return `${res.status} ${res.statusText}`;
}
let authenticationStateHandler: ((required: boolean) => void) | undefined;
/** Let the app shell own authentication state without coupling requests to UI. */
export function setAuthenticationStateHandler(
handler: (required: boolean) => void,
): void {
authenticationStateHandler = handler;
}
export class ApiError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.name = "ApiError";
this.status = status;
}
}
/** How a failed operator action should render. */
export type ActionErrorKind = "session-expired" | "refused" | "broken";
// classifyActionError turns a failed operator action into a rendering
// decision. archied's own handlers already return distinguishable status
// codes for a refused mutation (400/403/409/415 -- bad input, missing CSRF,
// cross-origin, conflicting state, a body that is not JSON) versus a broken
// one (5xx, or no status at all when fetch itself failed -- network drop,
// timeout); 401 additionally means the session -- archied's own token cookie,
// or an upstream forward-auth proxy sitting in front of it -- has expired
// rather than that the action was rejected or the daemon is unwell.
export function classifyActionError(err: unknown): {
kind: ActionErrorKind;
message: string;
} {
const status = err instanceof ApiError ? err.status : undefined;
const message =
err instanceof Error && err.message ? err.message : "Action failed";
if (status === 401) return { kind: "session-expired", message };
if (status !== undefined && status >= 400 && status < 500)
return { kind: "refused", message };
return { kind: "broken", message };
}
// send is the only fetch() in the dashboard. It converts a non-ok response
// into an ApiError carrying the server's own explanation and a usable status,
// and hands the raw Response back so the streaming caller can read the body
// itself.
async function send(path: string, init: RequestInit): Promise<Response> {
const res = await fetch(path, init);
authenticationStateHandler?.(res.status === 401);
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res;
}
interface RequestOptions {
method?: string;
body?: unknown;
timeoutMs?: number;
parse?: boolean;
}
// request performs a JSON request. Every mutating method must declare a JSON
// body: archied's handlers run authorizeTaskMutation first, and it answers 415
// unless Content-Type is application/json -- including for a mutation that has
// no body to send, because that requirement is what makes a simple cross-origin
// form post inexpressible. Sending the header on every mutation, rather than
// only where a payload happens to exist, is what keeps a bodyless DELETE or
// approve from being refused.
async function request<T = unknown>(
path: string,
opts: RequestOptions = {},
): Promise<T> {
const {
method = "GET",
body,
timeoutMs = DEFAULT_TIMEOUT_MS,
parse = true,
} = opts;
const headers: Record<string, string> = { Accept: "application/json" };
const init: RequestInit = {
method,
headers,
signal: AbortSignal.timeout(timeoutMs),
};
if (method !== "GET") {
headers["Content-Type"] = "application/json";
headers["X-Archie-CSRF"] = "1";
}
if (body !== undefined) init.body = JSON.stringify(body);
const res = await send(path, init);
return (parse ? await res.json() : undefined) as T;
}
export const api = {
recoveryCode: () => request<{code:string}>("/api/account/recovery",{method:"POST",body:{}}),
recoverAccount: (email:string,code:string,password:string) => request<void>("/api/auth/recover",{method:"POST",body:{email,code,password},parse:false}),
authStatus: <T = unknown>() => request<T>("/api/auth/status"),
setupAccount: (body: unknown) => request("/api/auth/setup", {method:"POST",body}),
signIn: (email: string,password: string) => request("/api/auth/login",{method:"POST",body:{email,password}}),
signOut: () => request<void>("/api/auth/logout",{method:"POST",body:{},parse:false}),
createAccount: (body: unknown) => request("/api/accounts",{method:"POST",body}),
changePassword: (current_password: string,new_password: string) => request<void>("/api/account/password",{method:"POST",body:{current_password,new_password},parse:false}),
authentication: <T = unknown>() => request<T>("/api/authentication"),
saveAuthentication: (body: unknown) => request<void>("/api/authentication",{method:"PUT",body,parse:false}),
tokens: <T = unknown>() => request<T>("/api/tokens"),
createToken: () => request<{token:string}>("/api/tokens",{method:"POST",body:{}}),
revokeToken: (id:string) => request<void>(`/api/tokens/${encodeURIComponent(id)}`,{method:"DELETE",body:{},parse:false}),
passkeys: () => request<{passkeys:{id:string;name:string}[]}>("/api/account/passkeys"),
deletePasskey: (id:string) => request<void>(`/api/account/passkeys/${encodeURIComponent(id)}`,{method:"DELETE",body:{},parse:false}),
beginPasskey: <T = unknown>(registration:boolean) => request<T>(registration?"/api/account/passkeys/begin":"/api/auth/passkey/begin",{method:"POST",body:{}}),
finishPasskey: (registration:boolean,credential:unknown,name:string) => request(registration?"/api/account/passkeys/finish":"/api/auth/passkey/finish",{method:"POST",body:{credential,name}}),
secretEngines: <T = unknown>() => request<T>("/api/secret-engines"),
checkSecret: (ref: { engine: string; key: string }) => request<{ resolved: boolean; process: string }>("/api/secret-references/check", { method: "POST", body: ref }),
health: <T = unknown>() => request<T>("/health/detailed"),
services: <T = unknown>() => request<T>("/api/services"),
policies: <T = unknown>() => request<T>("/api/access/policies"),
putPolicy: (policy: unknown) =>
request<{ version: number }>("/api/access/policies", { method: "PUT", body: policy }),
deletePolicy: (policy: unknown) =>
request<void>("/api/access/policies", { method: "DELETE", body: policy, parse: false }),
schedules: <T = unknown>() => request<T>("/api/schedules"),
// scheduleSave creates or replaces the schedule with this id.
scheduleSave: <T = unknown>(id: string, schedule: unknown) =>
request<T>(`/api/schedules/${encodeURIComponent(id)}`, { method: "PUT", body: schedule }),
scheduleDelete: (id: string) =>
request<void>(`/api/schedules/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
scheduleRunNow: <T = unknown>(id: string) =>
request<T>(`/api/schedules/${encodeURIComponent(id)}/runs`, { method: "POST", body: {} }),
scheduleRuns: <T = unknown>(id: string) =>
request<T>(`/api/schedules/${encodeURIComponent(id)}/runs`),
orgs: <T = unknown>() => request<T>("/api/orgs"),
// orgCreate makes an org with its default workspace and first owner; only
// an instance admin may.
orgCreate: <T = unknown>(org: { id: string; name: string; owner_identity: string }) =>
request<T>("/api/orgs", { method: "POST", body: org }),
org: <T = unknown>(id: string) => request<T>(`/api/orgs/${encodeURIComponent(id)}`),
orgWorkspaces: <T = unknown>(id: string) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/workspaces`),
createOrgWorkspace: <T = unknown>(
id: string,
workspace: { id: string; name: string; environment?: string },
) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/workspaces`, {
method: "POST",
body: workspace,
}),
orgAgents: <T = unknown>(id: string) => request<T>(`/api/orgs/${encodeURIComponent(id)}/agents`),
orgMembers: <T = unknown>(id: string) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/members`),
addOrgMember: <T = unknown>(
id: string,
member: { subject?: string; email?: string; role: string },
) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/members`, {
method: "POST",
body: member,
}),
setOrgMember: <T = unknown>(
id: string,
identity: string,
member: { role: string; workspace?: string },
) =>
request<T>(
`/api/orgs/${encodeURIComponent(id)}/members/${encodeURIComponent(identity)}`,
{ method: "PUT", body: member },
),
removeOrgMember: (id: string, identity: string, workspace?: string) =>
request<void>(
`/api/orgs/${encodeURIComponent(id)}/members/${encodeURIComponent(identity)}` +
qs({ workspace }),
{ method: "DELETE", parse: false },
),
assignOrgAgent: <T = unknown>(id: string, identity: string) =>
request<T>(
`/api/orgs/${encodeURIComponent(id)}/agents/${encodeURIComponent(identity)}`,
{ method: "PUT" },
),
alerts: <T = unknown>() => request<T>("/api/alerts"),
dismissAlert: (id: number) =>
request<void>(`/api/alerts/${id}/dismiss`, { method: "POST", parse: false }),
identities: <T = unknown>() => request<T>("/api/identities"),
identityCreate: <T = unknown>(identity: { display_name: string; kind: string }) =>
request<T>("/api/identities", { method: "POST", body: identity }),
// identityCommand runs one lifecycle command (rename, suspend, reactivate,
// retire) against the version the caller last read.
identityCommand: <T = unknown>(id: string, command: string, body: { expected_version: number; display_name: string }) =>
request<T>(`/api/identities/${encodeURIComponent(id)}/${encodeURIComponent(command)}`, { method: "POST", body }),
summary: <T = unknown>() => request<T>("/api/summary"),
tasks: <T = unknown>() => request<T>("/api/tasks"),
// taskPage reads one page of the board; next is the cursor for the page
// after it, or null when this page was the last.
taskPage: async <T = unknown>(params: QueryParams) => {
const res = await send("/api/tasks" + qs(params), {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
});
return {
tasks: (await res.json()) as T[],
next: res.headers.get("X-Next-Cursor"),
};
},
taskMeta: <T = unknown>() => request<T>("/api/task-meta"),
task: <T = unknown>(id: string) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}`),
taskAttempts: <T = unknown>(id: string) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/attempts`),
taskChanges: <T = unknown>(id: string, params?: QueryParams) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/changes` + qs(params)),
taskDebug: <T = unknown>(id: string, params?: QueryParams) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/debug` + qs(params)),
// taskAction posts an operator action. A review-gate answer may carry a
// payload: the instructions a rereview requires, and the finding keys an
// approve posts (an absent selection means every offered finding). A retry
// carries the worktree mode the operator chose, and may name the step it
// resumes from. Every other action sends
// none.
taskAction: <T = unknown>(
id: string,
action: string,
payload?: {
instructions?: string;
findings?: string[];
retry_mode?: string;
resume_from?: string;
current_definition?: boolean;
},
) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/action`, {
method: "POST",
body: { action, ...payload },
}),
setup: <T = unknown>() => request<T>("/api/setup"),
capabilities: <T = unknown>() => request<T>("/api/capabilities"),
workflows: <T = unknown>() => request<T>("/api/workflows"),
workflowEnabled: (id: string, enabled: boolean) =>
request<void>(`/api/workflows/${encodeURIComponent(id)}/enabled`, {
method: "PUT",
body: { enabled },
parse: false,
}),
checkRepository: <T = unknown>(input: { owner: string; repository: string; identity_id: string }) => request<T>("/api/control-plane/resources/repository-policies/check", { method: "POST", body: input, timeoutMs: 35000 }),
repositories: <T = unknown>() => request<T>("/api/repositories"),
workRequest: <T = unknown>(workRequest: Payload) =>
request<T>("/api/work-requests", { method: "POST", body: workRequest }),
skills: <T = unknown>() => request<T>("/api/skills"),
channels: <T = unknown>() => request<T>("/api/channels"),
curators: <T = unknown>() => request<T>("/api/curators"),
channelReload: <T = unknown>(id: string) =>
request<T>(`/api/channels/${encodeURIComponent(id)}/reload`, {
method: "POST",
body: {},
}),
config: <T = unknown>() => request<T>("/api/config"),
// The audit feed is filtered and paginated on the server; export is a
// browser navigation, so its URL is built here beside the request.
audit: <T = unknown>(params: QueryParams = {}) => request<T>("/api/audit" + qs(params)),
auditExportURL: (format: "csv" | "json", params: QueryParams = {}) =>
"/api/audit/export" + qs({ ...params, format }),
logs: <T = unknown>(params?: QueryParams) =>
request<T>("/api/logs" + qs(params)),
taskLogs: <T = unknown>(id: string, params?: QueryParams) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/logs` + qs(params)),
// A download is a navigation, not a fetch: the browser must own the
// Content-Disposition filename and stream the body to disk rather than hold
// a whole log in memory. The URL builder is the client-side contract, and
// log-row keeps it beside the panel that uses it.
taskLogDownloadURL: (id: string, attempt?: number | null) =>
`/api/tasks/${encodeURIComponent(id)}/logs/download` +
(attempt == null ? "" : `?attempt=${attempt}`),
// Versions + updates. The install's synchronous phase (clone + build +
// install) legitimately runs for minutes; its timeout is therefore minutes,
// not the 15s default, and the watchdog owns everything after the restart.
version: <T = unknown>() => request<T>("/api/version"),
updateSnapshot: <T = unknown>() => request<T>("/api/chat/update"),
updateDefer: (snapshot: unknown) =>
request("/api/chat/update/defer", { method: "POST", body: { snapshot } }),
updateInstall: <T = unknown>(snapshot: unknown) =>
request<T>("/api/chat/update/install", {
method: "POST",
body: { snapshot },
timeoutMs: 15 * 60_000,
}),
captures: <T = unknown>(limit?: number) =>
request<T>("/api/captures" + qs({ limit })),
eventTypes: <T = unknown>(workspace?: string) =>
request<T>("/api/event-types" + qs({ workspace })),
eventTypeCreate: <T = unknown>(eventType: Payload) =>
request<T>("/api/event-types", { method: "POST", body: eventType }),
eventTypeUpdate: <T = unknown>(id: string, eventType: Payload) =>
request<T>(`/api/event-types/${encodeURIComponent(id)}`, {
method: "PUT",
body: eventType,
}),
eventTypeDelete: (id: string) =>
request<void>(`/api/event-types/${encodeURIComponent(id)}`, {
method: "DELETE",
parse: false,
}),
mappings: <T = unknown>(workspace?: string) =>
request<T>("/api/mappings" + qs({ workspace })),
mappingCreate: <T = unknown>(mapping: Payload) =>
request<T>("/api/mappings", { method: "POST", body: mapping }),
mappingUpdate: <T = unknown>(id: string, mapping: Payload) =>
request<T>(`/api/mappings/${encodeURIComponent(id)}`, {
method: "PATCH",
body: mapping,
}),
// A delete answers 204, so there is no body to parse.
mappingDelete: (id: string) =>
request<void>(`/api/mappings/${encodeURIComponent(id)}`, {
method: "DELETE",
parse: false,
}),
mappingPreview: <T = unknown>(captureId: string, fields: unknown) =>
request<T>("/api/mappings/preview", {
method: "POST",
body: { capture_id: captureId, fields },
}),
bindings: <T = unknown>(workspace?: string) =>
request<T>("/api/bindings" + qs({ workspace })),
dispatches: <T = unknown>(kind: "bindings" | "captures" | "tasks", id: string) =>
request<T>(`/api/${kind}/${encodeURIComponent(id)}/dispatches`),
bindingCreate: <T = unknown>(binding: Payload) =>
request<T>("/api/bindings", { method: "POST", body: binding }),
bindingUpdate: <T = unknown>(id: string, binding: Payload) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}`, {
method: "PATCH",
body: binding,
}),
bindingDelete: (id: string) =>
request<void>(`/api/bindings/${encodeURIComponent(id)}`, {
method: "DELETE",
parse: false,
}),
bindingApprove: <T = unknown>(id: string) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}/approve`, {
method: "POST",
}),
// bindingPause stops an armed binding; bindingResume returns it to pending
// approval.
bindingPause: <T = unknown>(id: string) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}/pause`, { method: "POST" }),
bindingResume: <T = unknown>(id: string) =>
request<T>(`/api/bindings/${encodeURIComponent(id)}/resume`, { method: "POST" }),
harnessBindings: <T = unknown>() => request<T>("/api/harness/bindings"),
sources: <T = unknown>(workspace?: string) =>
request<T>("/api/sources" + qs({ workspace })),
// sourceCreate makes a source in one of the org's workspaces; an empty
// workspace is the default one.
sourceCreate: <T = unknown>(path: string, workspace = "") =>
request<T>("/api/sources", { method: "POST", body: { path, workspace } }),
sourceSigning: <T = unknown>(path: string, signed: boolean) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/signing`, {
method: "POST",
body: { signed },
}),
sourceApproveUnsigned: <T = unknown>(path: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/approve-unsigned`, {
method: "POST",
}),
sourceName: <T = unknown>(path: string, name: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/name`, { method: "PUT", body: { name } }),
sourceDeliveryHeader: <T = unknown>(path: string, header: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/delivery-header`, { method: "PUT", body: { header } }),
sourceDelete: (path: string) =>
request<void>(`/api/sources/${encodeURIComponent(path)}`, { method: "DELETE", parse: false }),
sourceSecret: <T = unknown>(path: string) =>
request<T>(`/api/sources/${encodeURIComponent(path)}/secret`, {
method: "POST",
}),
chatSessions: <T = unknown>() => request<T>("/api/chat/sessions"),
chatAnswer: (id: string, answer: string) =>
request("/api/chat/answer", { method: "POST", body: { id, answer } }),
chatMessages: <T = unknown>(id: string) =>
request<T>(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
chatTurns: <T = unknown>(id: string) =>
request<T>(`/api/chat/sessions/${encodeURIComponent(id)}/turns`),
chatCancel: <T = unknown>(sessionID: string) =>
request<T>("/api/chat/cancel", {
method: "POST",
body: { session_id: sessionID },
}),
// The page the operator was on when they asked, so a chat answer can be
// about what they were looking at. History routing makes that the pathname.
chatMessage: <T = unknown>(channelID: string, text: string) =>
request<T>("/api/chat/message", {
method: "POST",
body: {
channel_id: channelID,
source_id: randomUUID(),
text,
page: location.pathname + location.search || "/",
},
}),
// A server-sent event stream cannot be parsed as JSON and outlives a normal
// request, so the caller owns the abort controller and the timeout, and
// reads the body itself. Only the URL, headers, and failure shape are shared.
chatStream: (payload: unknown, opts: { signal?: AbortSignal } = {}) =>
send("/api/chat/stream", {
method: "POST",
headers: {
Accept: "text/event-stream",
"Content-Type": "application/json",
"X-Archie-CSRF": "1",
},
body: JSON.stringify(payload),
signal: opts.signal,
}),
};
/**
* Subscribe to archied's event stream. Returns an unsubscribe function.
* Reconnection is the browser's job via EventSource, but a closed stream is
* surfaced to the caller so the UI can show it rather than silently freezing.
*/
export interface StreamFrame {
topic: string;
data: unknown;
}
/** One EventSource per tab. Re-creating it on Logs entry/exit carries the
* last multi-topic cursor in ?since; native reconnects use Last-Event-ID. */
export function subscribeEvents(
onFrame: (frame: StreamFrame, cursor: string) => void,
onStateChange: (state: StreamState) => void,
cursor = "",
logs = false,
): () => void {
const src = new EventSource(streamURL(cursor, logs));
src.onopen = () => onStateChange("live");
src.onerror = () => onStateChange(streamStateFor(src.readyState));
src.onmessage = (event) => {
try {
onFrame(JSON.parse(event.data) as StreamFrame, event.lastEventId);
} catch {
/* a malformed frame should not kill the stream */
}
};
return () => src.close();
}