Files
archie/ui/src/lib/api.ts
T
sam 787a213db6 Merge branch 'main' into worktree-agent-ac0944b265396932d
# Conflicts:
#	modules/governance/accounts_api.go
2026-11-22 15:42:43 +11:00

1324 lines
53 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 { errors } from "../copy/errors/index.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. */
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. Only a text/plain body is read:
// a proxy's HTML error page must not pass through as the reason.
async function errorMessage(res: Response): Promise<string> {
const type = res.headers.get("Content-Type") ?? "";
// The single binary answers with an RFC 9457 problem whose detail is the
// reason.
if (type.includes("application/problem+json")) {
try {
const detail = ((await res.json()) as { detail?: unknown }).detail;
if (typeof detail === "string" && detail) return detail.slice(0, 200);
} catch {
// Unreadable problem; fall through to the status.
}
return `${res.status} ${res.statusText}`;
}
if (type.includes("text/plain")) {
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 = describeError(err, errors.common.actionFailed);
if (status === 401) return { kind: "session-expired", message };
if (status !== undefined && status >= 400 && status < 500)
return { kind: "refused", message };
return { kind: "broken", message };
}
// describeError is the only place a caught error becomes text. The server's
// own reason wins because it is what the operator can act on; anything without
// a message falls back to the caller's catalogue entry, never to String(err).
export function describeError(err: unknown, fallback: string): string {
if (err instanceof ApiError && err.status === 401)
return errors.common.sessionExpired;
if (err instanceof Error && err.message) return err.message;
return fallback;
}
// 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> {
let res: Response;
try {
res = await fetch(path, init);
} catch (cause) {
// A caller's own abort (stopping a chat turn) is not a failure to report.
if (cause instanceof Error && cause.name === "AbortError") throw cause;
throw new ApiError(errors.common.network, 0);
}
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 = {
// The archie binary's module API; the wire types are below the object.
runs: (limit = 200, workflow?: string) => request<Run[]>("/api/runs" + qs({ limit, workflow })),
run: (id: string) => request<RunTrail>(`/api/runs/${encodeURIComponent(id)}`),
/** Queues a parked run again from the step that parked it, or from `from`. */
retryRun: (id: string, from?: string) =>
request<Run>(`/api/runs/${encodeURIComponent(id)}/retry`, { method: "POST", body: from ? { from } : {} }),
/** Asks a run that has not ended to stop, along with the runs it called. */
cancelRun: (id: string) => request<Run>(`/api/runs/${encodeURIComponent(id)}/cancel`, { method: "POST", body: {} }),
approvals: () => request<Approval[]>("/api/approvals"),
answerApproval: (id: string, approved: boolean, assertion?: ApprovalAssertion) =>
request<Approval>(`/api/approvals/${encodeURIComponent(id)}/answer`, { method: "POST", body: { approved, assertion } }),
/** Starts the passkey confirmation that approving an irreversible action needs. */
beginApprovalConfirmation: (id: string) =>
request<ApprovalConfirmation>(`/api/approvals/${encodeURIComponent(id)}/confirmation`, { method: "POST", body: {} }),
events: (params: { limit?: number; source?: string; type?: string; matched?: string } = {}) =>
request<EventRecord[]>("/api/events" + qs(params)),
event: (id: string) => request<EventDetail>(`/api/events/${encodeURIComponent(id)}`),
eventSources: () => request<EventSource_[]>("/api/sources"),
putEventSource: (name: string, connector: string, verification?: SourceVerification) =>
request<{ source: string; token?: string; secret?: string; url: string }>(`/api/sources/${encodeURIComponent(name)}`, { method: "PUT", body: { connector, ...verification } }),
sourceCapture: (name: string, capture: boolean) =>
request<EventSource_>(`/api/sources/${encodeURIComponent(name)}/capture`, { method: "PUT", body: { capture } }),
/** The runs a trigger started, newest first. */
triggerDispatches: (name: string) =>
request<TriggerRun[]>(`/api/triggers/${encodeURIComponent(name)}/dispatches`),
approveTrigger: (name: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(name)}/approve`, { method: "POST" }),
pauseTrigger: (name: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(name)}/pause`, { method: "POST" }),
/** A resumed trigger waits for approval again. */
resumeTrigger: (name: string) =>
request<Trigger>(`/api/triggers/${encodeURIComponent(name)}/resume`, { method: "POST" }),
deleteTrigger: (name: string) =>
request<void>(`/api/triggers/${encodeURIComponent(name)}`, { method: "DELETE", parse: false }),
/** The runs a stored delivery started. */
captureDispatches: (id: string) =>
request<TriggerRun[]>(`/api/captures/${encodeURIComponent(id)}/dispatches`),
putSourceKeyFields: (name: string, paths: string[]) =>
request<{ key_fields: string[] }>(`/api/sources/${encodeURIComponent(name)}/key-fields`, { method: "PUT", body: { paths } }),
triggers: () => request<Trigger[]>("/api/triggers"),
putTrigger: (name: string, trigger: TriggerInput) =>
request<{ trigger: string }>(`/api/triggers/${encodeURIComponent(name)}`, { method: "PUT", body: trigger }),
workflowList: () => request<WorkflowVersion[]>("/api/workflows"),
workflow: (name: string, version?: number) =>
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}` + qs({ version })),
/** Publishes a document as the next version; `expectedVersion` makes the save fail with 409 when another is stored. */
putWorkflow: (name: string, body: string, expectedVersion?: number) =>
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}`, { method: "PUT", body: { body, expected_version: expectedVersion } }),
deleteWorkflow: (name: string) => request<void>(`/api/workflows/${encodeURIComponent(name)}`, { method: "DELETE", parse: false }),
setWorkflowEnabled: (name: string, enabled: boolean) =>
request<WorkflowVersion>(`/api/workflows/${encodeURIComponent(name)}/enabled`, { method: "PUT", body: { enabled } }),
runWorkflow: (name: string, input?: Record<string, unknown>) =>
request<Run>(`/api/workflows/${encodeURIComponent(name)}/runs`, { method: "POST", body: { input } }),
workflowDrafts: () => request<WorkflowDraft[]>("/api/workflow-drafts"),
/** A workflow's draft, or null when it has none. */
workflowDraft: async (name: string) => {
try {
return await request<WorkflowDraft>(`/api/workflows/${encodeURIComponent(name)}/draft`);
} catch (cause) {
if (cause instanceof ApiError && cause.status === 404) return null;
throw cause;
}
},
/** Saves a draft; `revision` is the one last read, 0 for none, and a stale one fails with 409. */
putWorkflowDraft: (name: string, body: string, revision: number) =>
request<WorkflowDraft>(`/api/workflows/${encodeURIComponent(name)}/draft`, { method: "PUT", body: { body, revision } }),
discardWorkflowDraft: (name: string) => request<void>(`/api/workflows/${encodeURIComponent(name)}/draft`, { method: "DELETE", parse: false }),
testWorkflowDraft: (name: string, input?: Record<string, unknown>) =>
request<Run>(`/api/workflows/${encodeURIComponent(name)}/draft/test-run`, { method: "POST", body: { input } }),
workflowStats: () => request<WorkflowStats[]>("/api/workflow-stats"),
workflowStepTypes: () => request<StepType[]>("/api/workflow-step-types"),
extensionKinds: () => request<ExtensionKindInfo[]>("/api/extension-kinds"),
extensions: (kind: ExtensionKind) => request<Extension[]>(`/api/${kind}`),
allExtensions: () => request<Extension[]>("/api/extensions"),
removeAnyExtension: (name: string) =>
request<{ name: string; state: string }>(`/api/extensions/${encodeURIComponent(name)}`, { method: "DELETE" }),
catalogue: () => request<CatalogueEntry[]>("/api/extensions/catalogue"),
installCatalogue: (name: string) =>
request<ExtensionLifecycle>(`/api/extensions/catalogue/${encodeURIComponent(name)}/install`, { method: "POST", timeoutMs: 120_000 }),
acceptGrants: (name: string, body?: ExtensionGrantsInput) =>
request<ExtensionLifecycle>(`/api/extensions/${encodeURIComponent(name)}/accept`, { method: "POST", body: body ?? {} }),
updateExtension: (name: string) =>
request<ExtensionLifecycle>(`/api/extensions/${encodeURIComponent(name)}/update`, { method: "POST", timeoutMs: 120_000 }),
approveExtensionUpdate: (name: string) =>
request<ExtensionLifecycle>(`/api/extensions/${encodeURIComponent(name)}/approve-update`, { method: "POST" }),
rollbackExtension: (name: string) =>
request<ExtensionLifecycle>(`/api/extensions/${encodeURIComponent(name)}/rollback`, { method: "POST" }),
setExtensionPolicy: (name: string, policy: "manual" | "auto") =>
request<ExtensionLifecycle>(`/api/extensions/${encodeURIComponent(name)}/update-policy`, { method: "PUT", body: { policy } }),
setExtensionEnabled: (name: string, enabled: boolean) =>
request<ExtensionLifecycle>(`/api/extensions/${encodeURIComponent(name)}/enabled`, { method: "PUT", body: { enabled } }),
putExtensionSettings: (name: string, settings: Record<string, string>) =>
request<ExtensionLifecycle>(`/api/extensions/${encodeURIComponent(name)}/settings`, { method: "PUT", body: { settings }, timeoutMs: 60_000 }),
catalogueSource: () => request<CatalogueSourceView>("/api/extensions/catalogue-source"),
putCatalogueSource: (source: CatalogueSourceInput) =>
request<CatalogueSourceView>("/api/extensions/catalogue-source", { method: "PUT", body: source }),
acceptExtension: (kind: ExtensionKind, name: string, body: ExtensionInput) =>
request<{ name: string; state: string }>(`/api/${kind}/${encodeURIComponent(name)}`, { method: "PUT", body, timeoutMs: 60_000 }),
removeExtension: (kind: ExtensionKind, name: string) =>
request<{ name: string; state: string }>(`/api/${kind}/${encodeURIComponent(name)}`, { method: "DELETE" }),
credentials: () => request<Credential[]>("/api/credentials"),
credentialKinds: () => request<CredentialKind[]>("/api/credential-kinds"),
putCredential: (name: string, kind: string, fields: Record<string, CredentialField>) =>
request<{ name: string; kind: string; restarted: string[] }>(`/api/credentials/${encodeURIComponent(name)}`, { method: "PUT", body: { kind, fields }, timeoutMs: 60_000 }),
instructions: () => request<{ text: string }>("/api/settings/instructions"),
saveInstructions: (text: string) =>
request<{ text: string }>("/api/settings/instructions", { method: "PUT", body: { text } }),
modelProviders: () => request<Record<string, ModelProvider>>("/api/settings/model-providers"),
putModelProvider: (name: string, provider: ModelProvider) =>
request<ModelProvider>(`/api/settings/model-providers/${encodeURIComponent(name)}`, { method: "PUT", body: provider }),
deleteModelProvider: (name: string) =>
request<void>(`/api/settings/model-providers/${encodeURIComponent(name)}`, { method: "DELETE", parse: false }),
modelClasses: () => request<ModelClass[]>("/api/settings/model-classes"),
modelPolicy: () => request<ModelPolicy>("/api/settings/model-policy"),
putModelPolicy: (policy: ModelPolicy) =>
request<ModelPolicy>("/api/settings/model-policy", { method: "PUT", body: policy }),
agentModels: () => request<Record<string, AgentModel>>("/api/settings/agent-models"),
putAgentModel: (alias: string, model: AgentModel) =>
request<AgentModel>("/api/settings/agent-model" + qs({ alias }), { method: "PUT", body: model }),
deleteAgentModel: (alias: string) =>
request<void>("/api/settings/agent-model" + qs({ alias }), { method: "DELETE", parse: false }),
testAgentModel: (model: AgentModel) =>
request<{ answer: string; model: string }>("/api/settings/agent-model/test", { method: "POST", body: model, timeoutMs: 60_000 }),
policyText: (kind: PolicyKind, version?: number) =>
request<PolicyText>(`/api/policies/${kind}` + qs({ version })),
putPolicyText: (kind: PolicyKind, body: string) =>
request<PolicyText>(`/api/policies/${kind}`, { method: "PUT", body: { body } }),
judges: () => request<Judge[]>("/api/controls/judges"),
actionClasses: () => request<ActionClass[]>("/api/classes"),
actionClass: (id: string) => request<ActionClassDetail>(`/api/classes/${encodeURIComponent(id)}`),
resetActionClass: (id: string) =>
request<ActionClass>(`/api/classes/${encodeURIComponent(id)}/reset`, { method: "POST" }),
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: (name:string,days:number) => request<{token:string}>("/api/tokens",{method:"POST",body:{name,days}}),
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}}),
checkSecret: (ref: { engine: string; key: string }) => request<{ resolved: boolean; process: string }>("/api/secret-references/check", { method: "POST", body: ref }),
notes: () => request<MemoryNotes>("/api/memory/notes"),
rememberNote: (text: string) => request<MemoryNote>("/api/memory/notes", { method: "POST", body: { text } }),
correctNote: (id: string, text: string) =>
request<MemoryNote>(`/api/memory/notes/${encodeURIComponent(id)}`, { method: "PATCH", body: { text } }),
setNoteDisabled: (id: string, disabled: boolean) =>
request<void>(`/api/memory/notes/${encodeURIComponent(id)}/disabled`, { method: "POST", body: { disabled }, parse: false }),
forgetNote: (id: string) =>
request<void>(`/api/memory/notes/${encodeURIComponent(id)}`, { method: "DELETE", body: {}, parse: false }),
sharedNotes: () => request<MemoryNotes>("/api/memory/shared"),
publishNote: (text: string) => request<MemoryNote>("/api/memory/shared", { method: "POST", body: { text } }),
revokeSharedNote: (id: string) =>
request<void>(`/api/memory/shared/${encodeURIComponent(id)}`, { method: "DELETE", body: {}, parse: false }),
noteVersions: (id: string) =>
request<MemoryVersions>(`/api/memory/shared/${encodeURIComponent(id)}/versions`),
rollbackNote: (id: string, version: number) =>
request<MemoryNote>(`/api/memory/shared/${encodeURIComponent(id)}/rollback`, { method: "POST", body: { version } }),
noteProposals: () => request<MemoryNotes>("/api/memory/proposals"),
publishProposal: (id: string) =>
request<MemoryNote>(`/api/memory/proposals/${encodeURIComponent(id)}/publish`, { method: "POST", body: {} }),
health: <T = unknown>() => request<T>("/health/detailed"),
systemHealth: () => request<SystemHealth>("/api/system/health"),
bootstrap: () => request<Bootstrap>("/api/system/bootstrap"),
policies: <T = unknown>() => request<T>("/api/access/policies"),
denials: <T = unknown>(params: QueryParams = {}) =>
request<T>("/api/access/denials" + qs(params)),
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"),
// orgSelect sets the org the caller's tasks, workflows and settings act in;
// the server refuses one the caller is not a member of.
orgSelect: (id: string) =>
request<void>("/api/orgs/current", { method: "PUT", body: { id }, parse: false }),
// 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)}`),
// renameOrg changes the org's display name; expected_version refuses a save
// made from a name someone else has since changed.
renameOrg: <T = unknown>(id: string, change: { name: string; expected_version: number }) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}`, { method: "PATCH", body: change }),
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,
}),
renameOrgWorkspace: <T = unknown>(
id: string,
workspace: string,
change: { name: string; expected_version: number },
) =>
request<T>(
`/api/orgs/${encodeURIComponent(id)}/workspaces/${encodeURIComponent(workspace)}`,
{ method: "PATCH", body: change },
),
// orgHistory lists the org's appended name changes, newest first.
orgHistory: <T = unknown>(id: string) =>
request<T>(`/api/orgs/${encodeURIComponent(id)}/history`),
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 },
),
/** Suspending stops a member acting at once; their memberships stay. */
suspendOrgMember: (id: string, identity: string) =>
request<void>(
`/api/orgs/${encodeURIComponent(id)}/members/${encodeURIComponent(identity)}/suspend`,
{ method: "POST", parse: false },
),
reactivateOrgMember: (id: string, identity: string) =>
request<void>(
`/api/orgs/${encodeURIComponent(id)}/members/${encodeURIComponent(identity)}/reactivate`,
{ method: "POST", 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 }),
channelLinks: () => request<ChannelLinks>("/api/account/channels"),
/** Issues a single-use code and returns the URL that sends it to the channel. */
beginChannelLink: (connector: string) =>
request<ChannelLinkStart>(`/api/account/channels/${encodeURIComponent(connector)}/link`, { method: "POST" }),
unlinkChannel: (connector: string, subject: string) =>
request<void>(`/api/account/channels/${encodeURIComponent(connector)}/${encodeURIComponent(subject)}`, {
method: "DELETE",
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"),
// usage reads the org's model usage for the last days. The server derives
// the org from the caller and clamps days to 1..365.
usage: <T = unknown>(days = 30) => request<T>("/api/usage" + qs({ days })),
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)),
taskTranscript: <T = unknown>(id: string, params?: QueryParams) =>
request<T>(`/api/tasks/${encodeURIComponent(id)}/transcript` + 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"),
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>() => request<T>("/api/event-types"),
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>() => request<T>("/api/mappings"),
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" }),
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: () => request<ChatSessions>("/api/chat/sessions"),
chatCreateSession: () => request<ChatSessionView>("/api/chat/sessions", { method: "POST" }),
chatRenameSession: (id: string, title: string) =>
request<ChatSessionView>(`/api/chat/sessions/${encodeURIComponent(id)}`, { method: "PATCH", body: { title } }),
chatDeleteSession: (id: string) =>
request<void>(`/api/chat/sessions/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }),
chatTurns: (id: string) => request<ChatTurnRecord[]>(`/api/chat/sessions/${encodeURIComponent(id)}/turns`),
chatSend: (id: string, body: { text: string; page?: string; page_label?: string }) =>
request<ChatTurnRecord>(`/api/chat/sessions/${encodeURIComponent(id)}/turns`, { method: "POST", body }),
chatCancelTurn: (id: string) =>
request<ChatTurnRecord>(`/api/chat/turns/${encodeURIComponent(id)}/cancel`, { method: "POST" }),
// 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. `after` is the last event seq already read.
chatTurnEvents: (id: string, after: number, opts: { signal?: AbortSignal } = {}) =>
send(`/api/chat/turns/${encodeURIComponent(id)}/events${after ? qs({ after }) : ""}`, {
headers: { Accept: "text/event-stream" },
signal: opts.signal,
}),
};
/** One note, in one memory class. A note is readable only in its scope: a
* person's own notes, or the ones an administrator published to the org. */
export interface MemoryNote {
id: string;
class: string;
scope: "person" | "shared";
state: "pending" | "published";
purpose: string;
text: string;
owner_id?: string;
shared_by?: string;
version: number;
disabled: boolean;
created_at: string;
}
/** The notes a memory read returns. */
export interface MemoryNotes {
notes: MemoryNote[];
}
/** One published version of a shared note, which can be published again. */
export interface MemoryNoteVersion {
version: number;
text: string;
purpose: string;
publisher_id: string;
published_at: string;
}
export interface MemoryVersions {
versions: MemoryNoteVersion[];
}
/** GET /api/chat/sessions: the conversations and the model that answers. */
export interface ChatSessions {
sessions: ChatSessionView[];
active_model?: string;
model_error?: string;
}
export interface ChatSessionView {
session_id: string;
title: string;
created_at: string;
updated_at: string;
}
/** One turn of a conversation, with what it did, as the chat API records it. */
export interface ChatTurnRecord {
id: string;
session_id: string;
seq: number;
state: "queued" | "running" | "succeeded" | "failed" | "cancelled";
text: string;
page?: string;
page_label?: string;
reply: string;
reasoning?: string;
error?: string;
tool_calls: { id: string; name: string; parameters: string; text: string; failed?: boolean; duration_ms: number; text_offset: number }[];
approvals: ChatApprovalRecord[];
actions: ChatActionRecord[];
navigate: { path: string; label: string }[];
created_at: string;
finished_at?: string;
}
/** An action judgement held in a chat turn and put to people. */
export interface ChatApprovalRecord {
request_id: string;
action: string;
summary: string;
level: string;
deadline: string;
}
/** What became of a held action once its approval was answered. */
export interface ChatActionRecord {
request_id: string;
state: string;
result?: string;
}
export interface Run {
id: string;
workflow: string;
workflow_version: number;
state: string;
attempts: number;
error?: string;
/** What the run's ending says: a finish step's detail, or why a step parked it. */
detail?: string;
created_at: string;
finished_at?: string;
result?: unknown;
/** A test run of a draft, which changes nothing. */
dry?: boolean;
}
/** A channel account linked to the signed-in account. */
export interface ChannelLink {
connector: string;
subject: string;
name: string;
linked_at: string;
}
/** The connectors that can link, and the channel accounts already linked. */
export interface ChannelLinks {
connectors: string[];
linked: ChannelLink[];
}
/** A link code ready to open in a channel. */
export interface ChannelLinkStart {
url: string;
expires_at: string;
}
/** A passkey assertion made for one approval request. */
export interface ApprovalAssertion {
token: string;
credential: unknown;
}
/** One module's or dependency's readiness. */
export interface HealthCheck {
name: string;
healthy: boolean;
error?: string;
}
/** One accepted package: a connector, secret engine, guard or MCP server. */
export interface ConnectorHealth {
name: string;
contract: string;
healthy: boolean;
error?: string;
failed_at?: string;
}
export interface RunCounts {
queued: number;
running: number;
waiting: number;
waiting_approval: number;
parked: number;
}
/** What the binary reports about itself: GET /api/system/health. */
export interface SystemHealth {
version: string;
healthy: boolean;
checked_at: string;
checks: HealthCheck[];
connectors: ConnectorHealth[];
runner: { healthy: boolean; workers: number; error?: string; error_at?: string };
waiting?: { approvals: number; runs: RunCounts };
last_failure?: { source: string; cause: string; at: string; run_id?: string };
}
/** The values only the config file sets: GET /api/system/bootstrap. */
export interface Bootstrap {
listen: string;
database_host: string;
schemas: number;
admin_token_set: boolean;
sealing_identity_set: boolean;
}
export interface ApprovalConfirmation {
token: string;
options: { publicKey: Record<string, unknown> };
}
export interface Approval {
id: string;
run_id: string;
step: number;
kind: string;
action: string;
target: string;
level: string;
summary: string;
state: string;
requested_at: string;
deadline?: string;
answered_at?: string;
answered_by?: string;
answered_via?: string;
}
interface Decision {
id: string;
level: string;
reason?: string;
refused_by?: string;
dry?: boolean;
change_request?: boolean;
change_request_rule?: string;
at: string;
action: { connector: string; name: string; target?: { Kind?: string; ID?: string; Environment?: string } };
verdicts?: { guard: string; advisory: boolean; ceiling?: string; failed?: string }[];
}
export interface RunAction {
decision: Decision;
rejudged?: Decision;
approval?: Approval;
effect?: { state: string; output?: string; error?: string; at?: string };
}
export interface RunEntry {
seq: number;
kind: string;
name?: string;
at?: string;
text?: string;
output?: string;
error?: string;
unknown?: boolean;
/** The top-level step of the definition that made the entry. */
step?: string;
tool_calls?: { id?: string; name: string; input: string }[];
/** What a step recorded, when it is not an agent's own call. */
value?: unknown;
reasoning?: string;
/** The model request exactly as sent: messages, tools and sampling settings. */
request?: { messages?: { role: string; content?: string }[] };
usage?: { prompt_tokens?: number; completion_tokens?: number; cached_tokens?: number };
finish_reason?: string;
input?: string;
call_id?: string;
}
/** How far one top-level step of a run's definition got. */
export interface RunStage {
name: string;
type: string;
state: "pending" | "running" | "waiting" | "succeeded" | "failed" | "skipped" | "cancelled";
started_at?: string;
ended_at?: string;
error?: string;
}
export interface RunTrail {
run: Run;
origin?: { event_id?: string; source?: string; type?: string; trigger?: string; received_at?: string };
actions?: RunAction[];
entries?: RunEntry[];
/** The document the run executes: its version, or the draft a test run tested. */
definition?: string;
stages: RunStage[];
}
export interface EventRecord {
id: string;
source: string;
type: string;
matched: boolean;
received_at: string;
occurred_at?: string;
dispatched_at?: string;
linked_to?: string;
fields?: unknown;
/** How the delivery was verified; empty for an event a connector streamed. */
verification?: "signed" | "token" | "unsigned" | "";
}
/** A run a trigger started for a stored event. */
export interface TriggerRun {
event_id: string;
run_id: string;
trigger?: string;
created_at?: string;
}
export interface EventDetail {
body: unknown;
runs?: { run_id: string; trigger: string }[];
}
// Named with a trailing underscore: EventSource is the browser's SSE class.
export interface SourceVerification {
verification: "token" | "hmac" | "none";
hmac_header?: string;
hmac_prefix?: string;
/** Write-only: sealed on save and never returned. */
hmac_secret?: string;
}
export interface EventSource_ {
name: string;
connector: string;
key_fields?: string[];
token_set: boolean;
verification: "token" | "hmac" | "none";
hmac_header?: string;
hmac_prefix?: string;
hmac_secret_set: boolean;
display_name?: string;
/** The header a sender repeats on every retry of one delivery. */
delivery_header?: string;
signing: "signed" | "token" | "unsigned_pending_approval" | "unsigned";
/** Whether the source keeps each delivery's headers and payload. */
capture: boolean;
/** A signing secret the request issued; shown once. */
secret?: string;
}
export interface Trigger {
name: string;
source?: string;
event_type?: string;
every?: string;
workflow: string;
filter?: Record<string, string>;
enabled: boolean;
status: "pending_approval" | "armed" | "paused";
event_type_id?: string;
mapping_id?: string;
/** The source takes deliveries with no verification. */
unsigned: boolean;
}
export interface TriggerInput {
source?: string;
event_type?: string;
every?: string;
workflow: string;
filter?: Record<string, string>;
disabled: boolean;
event_type_id?: string;
mapping_id?: string;
/** Save waiting for approval. */
pending?: boolean;
}
export interface WorkflowVersion {
name: string;
version: number;
body: string;
steps?: string[];
created_at: string;
created_by?: string;
/** False for a workflow nothing may start. */
enabled: boolean;
}
/** The unpublished edit of a workflow. */
export interface WorkflowDraft {
name: string;
body: string;
/** The published version it began from, 0 for a workflow not yet published. */
base_version: number;
/** Counts the draft's writes; a save names the one it last read. */
revision: number;
updated_by: string;
updated_at: string;
}
export interface WorkflowStats {
workflow: string;
total: number;
succeeded: number;
/** Runs that failed, parked or were declined. */
failed: number;
/** Runs that have not ended. */
active: number;
/** The share of ended runs that succeeded; absent until one has ended. */
success_rate?: number;
last_run: { id: string; state: string; at: string };
}
export interface StepType {
name: string;
title: string;
needs_repository: boolean;
settings?: unknown;
}
export type ExtensionGroup = "platform" | "integration" | "agent";
/** An accepted-package kind, as the server lists it: the path segment of its API. */
export type ExtensionKind = string;
export interface ExtensionKindInfo {
kind: ExtensionKind;
label: string;
singular: string;
group: ExtensionGroup;
}
export interface SettingField {
key: string;
label?: string;
description?: string;
type?: string;
options?: string[];
required?: boolean;
secret?: boolean;
}
/** One event type, action, delivery or lookup a connector declared. */
export interface Capability {
name: string;
description: string;
schema: unknown;
}
/** What a connector declared when it last loaded. */
export interface Capabilities {
events: Capability[];
actions: Capability[];
deliveries: Capability[];
lookups: Capability[];
listens: boolean;
target_facts: boolean;
}
export interface Extension {
name: string;
state: string;
error?: string;
path?: string;
url?: string;
args?: string[];
digest?: string;
version?: string;
contract?: string;
group?: ExtensionGroup;
egress: string[];
env: string[];
settings: Record<string, string>;
settings_schema: SettingField[];
credentials: Record<string, string>;
/** An MCP server's declared tools, as it was accepted with them. */
tools?: unknown;
/** An MCP server's declared privileged effects; absent until declared. */
effects?: ServerEffects;
/** A connector's declarations; absent until it has loaded. */
capabilities?: Capabilities;
/** Whether an accepted package runs. */
enabled?: boolean;
/** Installed from the catalogue rather than accepted by path. */
managed?: boolean;
display_name?: string;
description?: string;
declared?: Grants | null;
accepted?: Grants | null;
pending?: PendingUpdate | null;
can_rollback?: boolean;
update_policy?: "manual" | "auto";
}
/** What an extension may use: hosts it reaches, host variables it sees and
* credential slots it is configured with. */
export interface Grants {
egress: string[];
env: string[];
credentials: string[];
}
export interface PendingUpdate {
version: string;
digest: string;
added: Grants;
}
export interface ExtensionLifecycle {
name: string;
version: string;
digest: string;
pending: boolean;
enabled: boolean;
}
export interface ExtensionGrantsInput {
egress?: string[];
env?: string[];
credentials?: Record<string, string>;
settings?: Record<string, string>;
}
/** One extension a signed catalogue offers. */
export interface CatalogueEntry {
name: string;
display_name: string;
description: string;
contract: string;
group: ExtensionGroup;
version: string;
digest: string;
grants: Grants;
installed: boolean;
installed_version?: string;
update_available: boolean;
}
/** Where the catalogue is read from and the key that signs it. */
export interface CatalogueSource {
location: string;
public_key: string;
newest?: string;
}
export interface CatalogueSourceView {
configured: boolean;
source?: CatalogueSource;
}
export interface CatalogueSourceInput {
location: string;
public_key: string;
}
export interface ServerEffects {
privilege_change: boolean;
secret_access: boolean;
}
export interface ExtensionInput {
path?: string;
sha256?: string;
url?: string;
args?: string[];
egress?: string[];
env?: string[];
settings?: Record<string, string>;
credentials?: Record<string, string>;
tools?: unknown;
effects?: ServerEffects;
}
export interface Credential {
name: string;
kind: string;
/** Per field: "stored", or "engine:key" for one a secret engine resolves. */
fields: Record<string, string>;
}
export interface CredentialKind {
kind: string;
required: string[];
optional?: string[];
}
export interface CredentialField {
value?: string;
engine?: string;
key?: string;
}
export interface AgentModel {
provider: string;
model: string;
/** Read from the provider, never sent when saving an alias. */
class?: string;
base_url?: string;
api_key_credential?: string;
}
/** An endpoint models are called on. */
export interface ModelProvider {
name: string;
class: string;
base_url?: string;
api_key_credential?: string;
}
export interface ModelClass {
class: string;
default_base_url?: string;
}
/** Which aliases workflows and chat may use; null lets them use any. */
export interface ModelPolicy {
workflow_aliases: string[] | null;
chat_aliases: string[] | null;
}
export type PolicyKind = "hard-rules" | "change-request";
export interface PolicyText {
body: string;
version: number;
created_at?: string;
created_by?: string;
versions?: { version: number; created_at: string; created_by?: string }[];
}
export interface Judge {
name: string;
version?: string;
advisory: boolean;
latest?: { answer?: string; at?: string; model?: string; trusted?: boolean; advisory_reason?: string };
}
export interface ActionClass {
id: string;
connector: string;
action: string;
target_kind?: string;
environment?: string;
level: string;
default: string;
count: number;
decisions: number;
last_decided_at?: string;
tightened_at?: string;
tightened_because?: string;
reset_at?: string;
}
export interface ActionClassDetail extends ActionClass {
history?: { at: string; level: string; run_id?: string; target?: string; approval?: string; answered_by?: string; refused_by?: string }[];
raises?: { id: string; from: string; to: string; state: string; proposed_at: string }[];
resets?: { at: string; by: string; from: string; to: string }[];
}
/**
* 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();
}