Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's (forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b, cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/, schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread, Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron` (now a pointer), MCP run_cron_job / set_cron_job / browse cron, the scheduled-jobs core skill, guestDefaults.cronLimits. The core keeps thin contracts: - runs.guest bridge (runs/guestjob.py): a guest's job run as that guest, confined by the core from their record; the plugin only names it. - runs.start's cron stamp → meta.cron. - delivery of a guest job's result (push, mail, mailHtml) off the stamp. - « Discuter »: POST /api/cron-runs/discuss. - runs.cron provider readers (plugins/cron_bridge.py): budget, auto-archive, agents catalog, the agents page's Schedule. - core/cronexpr.py, agents/runconfig.py; context.write create for a new agent definition; ui.pages[].unless; setRoute keeps a Settings page under /settings/p/. - carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json, cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's decision, superseded). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1367 lines
54 KiB
TypeScript
1367 lines
54 KiB
TypeScript
import type {
|
||
AccountCheckResult,
|
||
ComputerEnroll,
|
||
AccountsHealthResponse,
|
||
AccountsResponse,
|
||
GuestClaude,
|
||
LoginCodeResult,
|
||
LoginState,
|
||
PendingLogin,
|
||
AgentsResponse,
|
||
AskRecord,
|
||
CodeModeStatus,
|
||
ClaudeHooksResponse,
|
||
ConversationDetail,
|
||
ConversationSummary,
|
||
BannerStatus,
|
||
GenProgressSnapshot,
|
||
AskFormRecord,
|
||
FreshContextSettings,
|
||
ModelsResponse,
|
||
ModelPresetResponse,
|
||
OpenRouterModelsResponse,
|
||
NotifyLogEntry,
|
||
NotifMigrateBody,
|
||
NotifStateBodyState,
|
||
NotifStateResponse,
|
||
ProjectDetail,
|
||
ProjectSummary,
|
||
SearchConv,
|
||
ServiceIndexEntry,
|
||
ServicesIndexResponse,
|
||
SkillsResponse,
|
||
UsageLimitsResponse,
|
||
Worker,
|
||
GhLogin,
|
||
WorkerLabSync,
|
||
RepoPluginsView,
|
||
MachineAttention,
|
||
MachinesWakeable,
|
||
MachineWakeResult,
|
||
WorkersResponse,
|
||
Profile,
|
||
ProfilePatchBody,
|
||
ProfilesResponse,
|
||
ConversationRefsResponse,
|
||
Resource,
|
||
ConvLook,
|
||
} from "./types";
|
||
import type { Harness } from "@/lib/models";
|
||
import { msg, t } from "@/i18n";
|
||
import { track } from "@/lib/telemetry";
|
||
|
||
let reauthenticating = false;
|
||
|
||
/**
|
||
* Marker on the re-authentication navigation, in both the URL and the service
|
||
* worker's `navigateFallbackDenylist` (see vite.config.ts). It is what makes
|
||
* that navigation reach the network — see `reauthenticate()`.
|
||
*/
|
||
export const REAUTH_PARAM = "reauth";
|
||
/** Survives the navigation, so a 401 that outlives it can't bounce forever. */
|
||
const REAUTH_MARK = "ai-agent:reauth-at";
|
||
const REAUTH_COOLDOWN_MS = 30_000;
|
||
|
||
/**
|
||
* Send the browser to the Authelia portal after the session expired.
|
||
*
|
||
* The obvious move — `location.reload()` — silently does nothing here, and used
|
||
* to leave the app wedged in a reload loop. We are a PWA: the worker registers a
|
||
* `navigateFallback` to the precached `/index.html`, and workbox's
|
||
* NavigationRoute claims *every* request whose mode is `navigate`. A reload is
|
||
* one, so it was answered from the cache and never reached Traefik — meaning the
|
||
* 302 to the portal was never issued. The shell rebooted logged out, its queries
|
||
* 401'd, and it reloaded again.
|
||
*
|
||
* So make the navigation one the worker is told to ignore: `?reauth=<ts>` is in
|
||
* the denylist, so this document request goes to the network, Authelia answers
|
||
* 302, and the user lands back here via `rd` once they log in. The timestamp
|
||
* also guarantees the URL really changes and defeats any HTTP cache.
|
||
*/
|
||
function reauthenticate(): void {
|
||
if (reauthenticating) return;
|
||
// A 401 that survives a round trip is not an expired session (an endpoint
|
||
// that 401s for its own reasons, a proxy misconfiguration). Bouncing the
|
||
// browser on every one of those would be the old loop with extra steps.
|
||
try {
|
||
const last = Number(sessionStorage.getItem(REAUTH_MARK) ?? 0);
|
||
if (Date.now() - last < REAUTH_COOLDOWN_MS) return;
|
||
sessionStorage.setItem(REAUTH_MARK, String(Date.now()));
|
||
} catch {
|
||
/* storage blocked (private mode): the in-page flag below still guards */
|
||
}
|
||
reauthenticating = true;
|
||
const url = new URL(window.location.href);
|
||
url.searchParams.set(REAUTH_PARAM, String(Date.now()));
|
||
window.location.replace(url.toString());
|
||
}
|
||
|
||
/** Clear the bounce guard once we know the session is good again. */
|
||
function clearReauthMark(): void {
|
||
try {
|
||
if (sessionStorage.getItem(REAUTH_MARK) !== null) sessionStorage.removeItem(REAUTH_MARK);
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
}
|
||
|
||
/**
|
||
* fetch wrapper that recovers from an expired Authelia session.
|
||
*
|
||
* Our API calls carry `Accept: application/json`, so when the session cookie
|
||
* expires the forward-auth middleware answers them with a bare **401** instead
|
||
* of the 302 login redirect it sends for top-level document navigations. A raw
|
||
* fetch would then surface a useless "401" error in the UI, so hand those to
|
||
* `reauthenticate()`.
|
||
*/
|
||
export async function apiFetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
|
||
// A re-authentication navigation is already under way and this page is on its
|
||
// way out. Every query still in flight would otherwise retry against a
|
||
// backend that can only 401, which is what filled the logs.
|
||
if (reauthenticating) return new Response(null, { status: 401 });
|
||
const r = await fetch(input, init);
|
||
if (r.status === 401) {
|
||
if (await isLoginRequired(r)) toLogin();
|
||
else reauthenticate();
|
||
} else if (r.status === 403 && (await isRemoteLocked(r))) {
|
||
// The owner's internet address with *Internet access* switched off: the
|
||
// login page says so (backend remoteaccess/).
|
||
toLogin();
|
||
} else if (r.ok) clearReauthMark();
|
||
return r;
|
||
}
|
||
|
||
async function isRemoteLocked(r: Response): Promise<boolean> {
|
||
try {
|
||
const j = await r.clone().json();
|
||
return j?.detail?.kind === "remote_locked";
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The backend's own 401 — the guest host with no (valid) session — rather than
|
||
* an expired Authelia session: `{"detail": {"kind": "login_required"}}`.
|
||
*/
|
||
async function isLoginRequired(r: Response): Promise<boolean> {
|
||
try {
|
||
const j = await r.clone().json();
|
||
return j?.detail?.kind === "login_required";
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Send a signed-out guest to the built-in login, back here afterwards. Not
|
||
* from `/connect/<id>` (an AI app asking to connect — business/aiApps): it is
|
||
* meant for whoever has no session there yet, and offers the sign-in itself.
|
||
*/
|
||
function toLogin(): void {
|
||
const path = window.location.pathname;
|
||
if (reauthenticating || path === "/login" || path.startsWith("/connect/") || path.startsWith("/remote/"))
|
||
return;
|
||
reauthenticating = true;
|
||
const next = window.location.pathname + window.location.search;
|
||
window.location.assign(`/login?next=${encodeURIComponent(next)}`);
|
||
}
|
||
|
||
/** `&account=…` for the endpoints that split by Claude account (see
|
||
* `lib/accounts.tsx`: "all", an account id, or unset = the server's totals). */
|
||
function accountQs(account?: string | null, sep = "&"): string {
|
||
return account ? `${sep}account=${encodeURIComponent(account)}` : "";
|
||
}
|
||
|
||
/* ── plan usage (backend/usage/) — owner only: a guest gets 403 ─────────── */
|
||
|
||
/** The latest official /usage % per account (5h + week windows), whether that
|
||
* reading is stale, and the calibration (plan units / list $ per 1 %) in force. */
|
||
export async function fetchUsageLimits(): Promise<UsageLimitsResponse> {
|
||
const r = await apiFetch("/api/usage/limits", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw await apiError("usage limits", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** A guest's own Claude login's /usage % — the same shape, their login only
|
||
* (empty while none is connected or read yet). Guest only. */
|
||
export async function fetchMyUsage(): Promise<UsageLimitsResponse> {
|
||
const r = await apiFetch("/api/me/usage", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw await apiError("usage limits", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** The owner's floating plugin status banner (`provides: app.banner`), or
|
||
* null — refetched on the SSE `banner` event and polled while it shows
|
||
* (StatusBanner, `useAppBanner`). */
|
||
export async function fetchAppBanner(): Promise<BannerStatus | null> {
|
||
const r = await apiFetch("/api/app-banner", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(`app-banner: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
/** What waits for the owner on each of his machines, from the plugins
|
||
* providing `machine.attention` (backend `plugins/machine_attention.py`) —
|
||
* refetched on the SSE `machine-attention` event. Owner only. */
|
||
export async function fetchMachineAttention(): Promise<MachineAttention> {
|
||
const r = await apiFetch("/api/machines/attention", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw await apiError("machine attention", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Which of the owner's workers the plugin providing `machine.wake` can wake
|
||
* (backend `plugins/machine_wake.py`) — refetched on the SSE `machine-wake`
|
||
* event. Owner only. */
|
||
export async function fetchMachinesWakeable(): Promise<MachinesWakeable> {
|
||
const r = await apiFetch("/api/machines/wakeable", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw await apiError("wakeable machines", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** *⚡ Wake*: the `machine.wake` plugin sends the worker its magic packet; the
|
||
* hub then probes it for a minute, so the `workers` SSE flips it online. */
|
||
export async function wakeMachine(id: string): Promise<MachineWakeResult> {
|
||
const r = await apiFetch(`/api/machines/${encodeURIComponent(id)}/wake`, { method: "POST" });
|
||
if (!r.ok) throw await apiError("wake", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Every live local-model run's llm-server reading, by session id (backend
|
||
* runs/genprogress.py) — kept live by the SSE `gen-progress` event. */
|
||
export async function fetchGenProgress(): Promise<GenProgressSnapshot> {
|
||
const r = await apiFetch("/api/gen-progress", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(`gen-progress: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
/** The models a session can run on — one composer tag each (see lib/models.tsx). */
|
||
/** The Claude account profiles (hard-coded server-side); `health` adds each
|
||
* one's live login (`claude auth status` via the sidecar — slower). */
|
||
export async function fetchAccounts(health = false): Promise<AccountsResponse> {
|
||
const r = await apiFetch(`/api/accounts${health ? "?health=1" : ""}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(`accounts: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
export async function fetchModels(): Promise<ModelsResponse> {
|
||
const r = await apiFetch("/api/models", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(t("models: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** Settings → Models: change one model's preset (null clears a field). */
|
||
export async function patchModelPreset(
|
||
key: string,
|
||
patch: Partial<Record<"harness" | "effort" | "thinking" | "fast" | "favorite" | "guests", string | boolean | null>>,
|
||
): Promise<ModelPresetResponse> {
|
||
const r = await apiFetch("/api/model-presets", {
|
||
method: "PATCH",
|
||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||
body: JSON.stringify({ key, patch }),
|
||
});
|
||
if (!r.ok) throw await apiError("model preset", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Every OpenRouter model a pi.dev session can run on, with its prices — the
|
||
* model browser's catalogue (sourced from APPE; see backend/plugins/providers.py appe_catalogue). */
|
||
export async function fetchOpenRouterModels(): Promise<OpenRouterModelsResponse> {
|
||
const r = await apiFetch("/api/models/openrouter", {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(`openrouter models: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
export interface ConversationsPage {
|
||
conversations: ConversationSummary[];
|
||
/** Total conversations matching the filter (pre-pagination). */
|
||
count: number;
|
||
/** Cursor for the next page, or null/absent when the list is exhausted. */
|
||
nextBefore?: string | null;
|
||
pricing: { model: string; inputPerMTok: number };
|
||
}
|
||
|
||
/**
|
||
* One page of the conversation list. `before` is the previous page's
|
||
* `nextBefore` cursor; `archived: "all"` includes hidden conversations;
|
||
* `full` adds the per-card usage/byToolSub blocks (analytics only — heavy);
|
||
* `limit: 0` disables pagination (everything in one response); `sessions`
|
||
* resolves just those session ids (archived included, no paging) instead of a
|
||
* page — a targeted lookup for cards that only know a session id.
|
||
*/
|
||
export async function fetchConversations(opts?: {
|
||
before?: string | null;
|
||
archived?: "false" | "all";
|
||
full?: boolean;
|
||
limit?: number;
|
||
sessions?: string[];
|
||
}): Promise<ConversationsPage> {
|
||
const q = new URLSearchParams();
|
||
if (opts?.before) q.set("before", opts.before);
|
||
if (opts?.archived) q.set("archived", opts.archived);
|
||
if (opts?.full) q.set("full", "1");
|
||
if (opts?.limit !== undefined) q.set("limit", String(opts.limit));
|
||
if (opts?.sessions?.length) q.set("sessions", opts.sessions.join(","));
|
||
const qs = q.toString();
|
||
const r = await apiFetch(`/api/conversations${qs ? `?${qs}` : ""}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("conversations: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** One conversation's list card — what SSE row-patching pulls. */
|
||
export async function fetchConversationSummary(id: string): Promise<ConversationSummary> {
|
||
const r = await apiFetch(`/api/conversation-summary?id=${encodeURIComponent(id)}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("conversation-summary: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** A conversation that recorded notify-done pushes (notification feed source). */
|
||
export interface NotifConversation {
|
||
id: string;
|
||
title: string;
|
||
endedAt?: string | null;
|
||
projects: string[];
|
||
services: string[];
|
||
/** The Claude account the conversation ran on (unset = the default). */
|
||
account?: string | null;
|
||
/** Its profile — Guests for a guest's, else its runner's (what the profile
|
||
* scope filters by). */
|
||
profile?: string | null;
|
||
/** Who started it: a guest's id (unset = the owner) — the Guests home's
|
||
* guest chips filter by it. */
|
||
owner?: string | null;
|
||
/** Its main resources now (≤3) — the pills of a push that carries none. */
|
||
resources?: Resource[] | null;
|
||
/** Its card look — the notification card wears its tile (lib/look.tsx). */
|
||
look?: ConvLook | null;
|
||
notifications: {
|
||
title?: string | null;
|
||
body?: string | null;
|
||
type?: string | null;
|
||
url?: string | null;
|
||
image?: string | null;
|
||
at?: string | null;
|
||
spoken?: string | null;
|
||
/** The conversation's main resources when it was sent. */
|
||
resources?: Resource[] | null;
|
||
}[];
|
||
}
|
||
|
||
/**
|
||
* The sound a notification made on the desk phone — its per-type jazz jingle
|
||
* followed by the spoken line — rendered to a WAV by the phone service. Pushes
|
||
* that carried no spoken line are read from their title + message instead. Used
|
||
* by the notification card's replay button; returns an object URL the caller
|
||
* owns (revoke it when done).
|
||
*/
|
||
export async function fetchNotifAudio(n: {
|
||
type?: string;
|
||
spoken?: string;
|
||
title?: string;
|
||
body?: string;
|
||
}): Promise<string> {
|
||
const r = await apiFetch("/api/notifications/audio", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
type: n.type ?? "",
|
||
spoken: n.spoken ?? "",
|
||
title: n.title ?? "",
|
||
message: n.body ?? "",
|
||
}),
|
||
});
|
||
if (!r.ok) throw new Error(t("notification audio: {status}", { status: r.status }));
|
||
return URL.createObjectURL(await r.blob());
|
||
}
|
||
|
||
/** One page of the light notification-feed source (conversations that
|
||
* recorded pushes — replaces walking the whole list), newest push first. */
|
||
export interface NotificationsPage {
|
||
conversations: NotifConversation[];
|
||
/** Conversations on this page. */
|
||
count?: number | null;
|
||
/** …and across every page. */
|
||
total?: number | null;
|
||
/** The next (older) page's cursor (`<at>|<convId>`); null on the last page. */
|
||
nextBefore?: string | null;
|
||
}
|
||
|
||
/**
|
||
* A page of the feed (`GET /api/notifications?limit=&before=&new=`): `limit`
|
||
* conversations by their newest push, older than `before` (the previous
|
||
* page's `nextBefore`). `onlyNew`: just the conversations with a push still
|
||
* on the owner's New list (the server ignores it for a guest).
|
||
*/
|
||
export async function fetchNotificationsPage(opts: {
|
||
limit: number;
|
||
before?: string;
|
||
onlyNew?: boolean;
|
||
}): Promise<NotificationsPage> {
|
||
const qs = new URLSearchParams({ limit: String(opts.limit) });
|
||
if (opts.before) qs.set("before", opts.before);
|
||
if (opts.onlyNew) qs.set("new", "1");
|
||
const r = await apiFetch(`/api/notifications?${qs}`, { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(t("notifications: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/**
|
||
* Mirror the client's notification read-state to the server ledger so other
|
||
* clients — notably the desk phone, which fetches *unread* notifications to read
|
||
* aloud — agree on what's been seen. Fire-and-forget: a failure here must never
|
||
* disrupt the UI (the client store is still the source of truth for the PWA).
|
||
* `seed` adopts ids as the baseline (first sync); otherwise they're marked read.
|
||
*/
|
||
export async function postNotifSeen(
|
||
ids: string[],
|
||
opts?: { seed?: boolean; all?: boolean },
|
||
): Promise<void> {
|
||
const path = opts?.seed ? "/api/notifications/seed" : "/api/notifications/seen";
|
||
try {
|
||
await apiFetch(path, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ ids, all: opts?.all ?? false }),
|
||
});
|
||
} catch {
|
||
/* best-effort */
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The owner's per-notification state (`GET /api/notifications/state`). `null`
|
||
* when this caller has none to read — a guest (the route is not on their
|
||
* surface: 403), or a backend / mock without it (404) — so the store keeps
|
||
* the lists in its ui-state. Throws on anything worth retrying (offline, 5xx).
|
||
*/
|
||
export async function fetchNotifState(): Promise<NotifStateResponse | null> {
|
||
const r = await apiFetch("/api/notifications/state", { headers: { Accept: "application/json" } });
|
||
if (r.status === 403 || r.status === 404) return null;
|
||
if (!r.ok) throw new Error(`notifications/state: ${r.status}`);
|
||
const out = (await r.json()) as NotifStateResponse;
|
||
return out.enabled ? out : null;
|
||
}
|
||
|
||
/**
|
||
* Move notifications forward on the server — `read` (expanded) or `dismissed`
|
||
* (swiped) — which also takes their pushes off the owner's other devices and
|
||
* tells every open tab (SSE `notif-state`; `by` = this tab, to skip its echo).
|
||
* Resolves false when the write didn't land, so the caller can retry.
|
||
*/
|
||
export async function postNotifState(ids: string[], state: NotifStateBodyState, by: string): Promise<boolean> {
|
||
try {
|
||
const r = await apiFetch("/api/notifications/state", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ ids, state, by }),
|
||
});
|
||
return r.ok;
|
||
} catch {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The one-time import of the New / unread lists this user's ui-state kept
|
||
* before the server held them. Only the first call counts (any tab, any
|
||
* device); every call answers the resulting state.
|
||
*/
|
||
export async function migrateNotifState(body: NotifMigrateBody): Promise<NotifStateResponse> {
|
||
const r = await apiFetch("/api/notifications/state/migrate", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(body),
|
||
});
|
||
if (!r.ok) throw new Error(`notifications/state/migrate: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
export async function fetchSearchIndex(): Promise<SearchConv[]> {
|
||
const r = await apiFetch("/api/search-index", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(t("search-index: {status}", { status: r.status }));
|
||
return (await r.json()).conversations;
|
||
}
|
||
|
||
/**
|
||
* One conversation's full thread. With `since` (the `rev` of the response the
|
||
* caller already holds) the backend answers a **delta**: `thread` carries only
|
||
* the items from `threadFrom` on, the rest is sent whole — see useConversation,
|
||
* which splices it onto the cached thread.
|
||
*/
|
||
export async function fetchConversation(id: string, since?: string, signal?: AbortSignal): Promise<ConversationDetail> {
|
||
const qs = since ? `&since=${encodeURIComponent(since)}` : "";
|
||
const r = await apiFetch(`/api/conversation?id=${encodeURIComponent(id)}${qs}`, {
|
||
headers: { Accept: "application/json" },
|
||
signal,
|
||
});
|
||
if (!r.ok) throw new Error(t("conversation: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/**
|
||
* Set a conversation's archived flag (hide/unhide it from the default drawer
|
||
* list). Keyed by the conversation id / session id the meta sidecar uses.
|
||
*/
|
||
export async function setConversationArchived(id: string, archived: boolean): Promise<void> {
|
||
const r = await apiFetch("/api/conversation-meta", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||
body: JSON.stringify({ id, archived }),
|
||
});
|
||
if (!r.ok) throw new Error(t("archive: {status}", { status: r.status }));
|
||
}
|
||
|
||
/**
|
||
* Set a conversation's custom display title (shown instead of the parsed
|
||
* one). An empty string clears the override, falling back to the auto title
|
||
* (a work conversation's resource title, else the AI one). `titleSource:
|
||
* "user"` is what keeps a run's `conv title` from overwriting it.
|
||
*/
|
||
export async function renameConversation(id: string, title: string): Promise<void> {
|
||
const r = await apiFetch("/api/conversation-meta", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||
body: JSON.stringify({ id, title, titleSource: "user" }),
|
||
});
|
||
if (!r.ok) throw new Error(t("rename: {status}", { status: r.status }));
|
||
}
|
||
|
||
/** Pick a conversation's card colour ("" = back to auto). A conversation
|
||
* about an issue + PR re-colours that whole subject (backend look/color). */
|
||
export async function setConversationColor(id: string, color: string): Promise<void> {
|
||
const r = await apiFetch("/api/look/color", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||
body: JSON.stringify({ id, color }),
|
||
});
|
||
if (!r.ok) throw new Error(t("look color: {status}", { status: r.status }));
|
||
}
|
||
|
||
/** Set what a conversation does — its card's action icon ("" = back to Haiku's). */
|
||
export async function setConversationAction(id: string, action: string): Promise<void> {
|
||
const r = await apiFetch("/api/conversation-meta", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||
body: JSON.stringify({ id, look: { action } }),
|
||
});
|
||
if (!r.ok) throw new Error(t("look action: {status}", { status: r.status }));
|
||
}
|
||
|
||
/** Bulk-archive every conversation older than the start of yesterday (UTC). */
|
||
/** Archive everything that ended before yesterday, except the `keep` session ids (the pinned ones). */
|
||
export async function archiveOldConversations(keep: string[] = []): Promise<{ archived: number; cutoff: string }> {
|
||
const r = await apiFetch("/api/conversations/archive-old", {
|
||
method: "POST",
|
||
headers: { Accept: "application/json", "Content-Type": "application/json" },
|
||
body: JSON.stringify({ keep }),
|
||
});
|
||
if (!r.ok) throw new Error(t("archive-old: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** Events that are live readings, not changes — `gen-progress` ticks every few
|
||
* seconds while a local model writes. Only a subscriber asking for `ticks`
|
||
* gets them; the pages that reload on any event would otherwise reload with
|
||
* every token count. */
|
||
const TICK_EVENTS = new Set(["gen-progress"]);
|
||
|
||
/**
|
||
* Subscribe to the backend's Server-Sent Events stream. Fires `onEvent` for
|
||
* each `{type: "meta" | "transcript", …}` change and reports connection state
|
||
* via `onLive`. The browser's EventSource reconnects automatically.
|
||
*/
|
||
export function subscribeEvents(
|
||
onEvent: (data: unknown) => void,
|
||
onLive?: (live: boolean) => void,
|
||
opts?: { ticks?: boolean },
|
||
): EventSource {
|
||
const es = new EventSource("/api/events");
|
||
es.onopen = () => onLive?.(true);
|
||
es.onerror = () => onLive?.(false);
|
||
es.onmessage = (e) => {
|
||
let data: unknown;
|
||
try {
|
||
data = JSON.parse(e.data);
|
||
} catch {
|
||
data = null;
|
||
}
|
||
const type = (data as { type?: string } | null)?.type;
|
||
if (!opts?.ticks && type && TICK_EVENTS.has(type)) return;
|
||
onEvent(data);
|
||
};
|
||
return es;
|
||
}
|
||
|
||
/**
|
||
* Kick off a new headless `claude -p` session on the host (via the sidecar).
|
||
* Returns the freshly-minted session id; the caller watches the conversation
|
||
* list until a transcript with this id syncs, then navigates to it.
|
||
*/
|
||
export async function spawnConversation(
|
||
prompt: string,
|
||
model?: string,
|
||
harness?: Harness,
|
||
/** false ⇒ run the harness with thinking disabled. Undefined = its default. */
|
||
thinking?: boolean,
|
||
/** claude only: `--effort` level (low…max). Undefined = the CLI's default. */
|
||
effort?: string,
|
||
opts?: {
|
||
/** The account to bill (the composer's account chip) — one the runner
|
||
* holds. Unset ⇒ the runner's ★ login (Settings → Profiles). */
|
||
account?: string;
|
||
/** Project slugs the composer had tagged (they tag, they don't route). */
|
||
projects?: string[];
|
||
/** The runner: a paired worker's id, "local" for the lab's own sidecar.
|
||
* Unset ⇒ the profile's default runner (offline ⇒ refused). */
|
||
worker?: string;
|
||
/** The profile the prompt is sent from (the home switch). */
|
||
profile?: string;
|
||
/** The composer's *+ New project* pick: the run starts a project from one
|
||
* of the owner's templates (a *New project* form) instead of working in
|
||
* one — a guest sends it with `projects: []`. */
|
||
newProject?: boolean;
|
||
/** The composer's Chrome chip: launch with `--chrome` (the run drives
|
||
* the browser paired to its account — the lab's, or a worker's own). */
|
||
chrome?: boolean;
|
||
/** The composer's *Code β* chip: start in Claude Code's Code Mode (beta)
|
||
* — sticky for the conversation's life (lib/codeMode.ts). */
|
||
codeMode?: boolean;
|
||
},
|
||
): Promise<{ sessionId: string; pid?: number }> {
|
||
const r = await apiFetch("/api/spawn", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
prompt, model, harness, thinking, effort,
|
||
account: opts?.account, projects: opts?.projects, worker: opts?.worker,
|
||
profile: opts?.profile,
|
||
...(opts?.newProject ? { newProject: true } : {}),
|
||
...(opts?.chrome ? { chrome: true } : {}),
|
||
...(opts?.codeMode ? { codeMode: true } : {}),
|
||
}),
|
||
});
|
||
if (!r.ok) throw await apiError(msg("spawn"), r);
|
||
return r.json();
|
||
}
|
||
|
||
/**
|
||
* Continue an existing conversation with a new user turn (via the host sidecar).
|
||
* Runs `claude -p <prompt> --resume <sessionId>` in the session's original cwd;
|
||
* because resume reuses the session id, the new turns append to the same
|
||
* transcript and stream into the open conversation. `cwd` must match where the
|
||
* session originally ran (resume is directory-scoped).
|
||
*/
|
||
export async function resumeConversation(
|
||
sessionId: string,
|
||
prompt: string,
|
||
opts?: {
|
||
cwd?: string | null;
|
||
model?: string | null;
|
||
harness?: Harness | null;
|
||
/** Unset ⇒ the session keeps the thinking setting it last ran with. */
|
||
thinking?: boolean | null;
|
||
/** Unset ⇒ the session keeps the effort level it last ran with. */
|
||
effort?: string | null;
|
||
/** Continue a worker session a terminal may still hold (the confirm
|
||
* behind a `terminal_live` refusal). */
|
||
takeover?: boolean;
|
||
/** Stop a live run and send now, instead of queueing the prompt into its
|
||
* inbox (the queued echo's *Stop & send now*). */
|
||
now?: boolean;
|
||
/** Unset ⇒ the session keeps the `--chrome` it last ran with. */
|
||
chrome?: boolean | null;
|
||
/** Only into a live run's inbox, never starting one (`delivered: null`
|
||
* then) — a queued message's Cancel note. */
|
||
inboxOnly?: boolean;
|
||
/** Compact the session first — the reply box's *fresh context*
|
||
* (`lib/freshContext.ts`, backend `runs/fresh.py`). */
|
||
fresh?: boolean;
|
||
},
|
||
): Promise<{
|
||
sessionId: string;
|
||
pid?: number;
|
||
/** Set when a live run took the message without a restart: `"inbox"` (its
|
||
* inbox socket — read after the current tool call) or `"hold"` (relayed by
|
||
* the Stop guard). Absent for a plain resume. */
|
||
delivered?: string | null;
|
||
}> {
|
||
const r = await apiFetch("/api/resume", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
sessionId,
|
||
prompt,
|
||
cwd: opts?.cwd ?? undefined,
|
||
model: opts?.model ?? undefined,
|
||
harness: opts?.harness ?? undefined,
|
||
thinking: opts?.thinking ?? undefined,
|
||
effort: opts?.effort ?? undefined,
|
||
takeover: opts?.takeover || undefined,
|
||
now: opts?.now || undefined,
|
||
inboxOnly: opts?.inboxOnly || undefined,
|
||
chrome: opts?.chrome ?? undefined,
|
||
fresh: opts?.fresh || undefined,
|
||
}),
|
||
});
|
||
if (!r.ok) throw await apiError(msg("resume"), r);
|
||
if (opts?.fresh) track("composer.freshContext");
|
||
return r.json();
|
||
}
|
||
|
||
/**
|
||
* Branch a NEW conversation off an existing one at a user message (edit &
|
||
* resubmit). The fork's history is the source transcript up to — excluding —
|
||
* user message `mi`; `prompt` (the edited text) is sent as its next turn.
|
||
* Returns the fork's freshly-minted session id; the caller polls the
|
||
* conversation list for it and navigates there, like a spawn.
|
||
*/
|
||
export async function forkConversation(
|
||
id: string,
|
||
mi: number,
|
||
prompt: string,
|
||
opts?: { model?: string | null; harness?: Harness | null },
|
||
): Promise<{ sessionId: string; pid?: number }> {
|
||
const r = await apiFetch("/api/fork", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
id,
|
||
mi,
|
||
prompt,
|
||
model: opts?.model ?? undefined,
|
||
harness: opts?.harness ?? undefined,
|
||
}),
|
||
});
|
||
if (!r.ok) throw await apiError(msg("fork"), r);
|
||
return r.json();
|
||
}
|
||
|
||
/**
|
||
* Interrupt a running session this viewer spawned (via the host sidecar). Sends
|
||
* the run's process group a SIGINT — like pressing Esc in a terminal — so Claude
|
||
* stops the current turn and records an interruption marker in its transcript.
|
||
*/
|
||
export async function interruptConversation(
|
||
sessionId: string,
|
||
): Promise<{ sessionId: string; ok: boolean }> {
|
||
const r = await apiFetch("/api/interrupt", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ sessionId }),
|
||
});
|
||
if (!r.ok) throw await apiError(msg("interrupt"), r);
|
||
return r.json();
|
||
}
|
||
|
||
/**
|
||
* An error from a sidecar-backed endpoint (spawn/resume/fork/interrupt, account
|
||
* login). The backend answers `detail: {message, kind, hint?, account?}` —
|
||
* `kind` says *why* (`auth` = the account's Claude login is missing/expired,
|
||
* `rate_limit`, `cli_outdated`, `bad_code`, …) so the UI can offer the fix
|
||
* (a "Log in" button) instead of printing raw JSON.
|
||
*/
|
||
export class ApiError extends Error {
|
||
status: number;
|
||
kind: string;
|
||
hint?: string;
|
||
account?: string;
|
||
constructor(
|
||
message: string,
|
||
o: { status: number; kind?: string; hint?: string | null; account?: string | null },
|
||
) {
|
||
super(message);
|
||
this.name = "ApiError";
|
||
this.status = o.status;
|
||
this.kind = o.kind || "unknown";
|
||
this.hint = o.hint || undefined;
|
||
this.account = o.account || undefined;
|
||
}
|
||
}
|
||
|
||
/** Read a failed response into an {@link ApiError} (structured or plain detail). */
|
||
export async function apiError(label: string, r: Response): Promise<ApiError> {
|
||
const text = await r.text().catch(() => "");
|
||
let detail: unknown = text;
|
||
try {
|
||
detail = (JSON.parse(text) as { detail?: unknown }).detail ?? text;
|
||
} catch {
|
||
/* not JSON — keep the text */
|
||
}
|
||
if (detail && typeof detail === "object" && "message" in detail) {
|
||
const d = detail as { message: string; kind?: string; hint?: string; account?: string };
|
||
return new ApiError(d.message, { status: r.status, ...d });
|
||
}
|
||
const extra = typeof detail === "string" ? detail : JSON.stringify(detail);
|
||
return new ApiError(`${t("{what}: {status}", { what: t(label), status: r.status })}${extra ? ` ${extra}` : ""}`, { status: r.status });
|
||
}
|
||
|
||
/* ── remote workers (backend/workers.py) ─────────────────────────────────── */
|
||
|
||
/** Paired remote runners + their live status. */
|
||
/** One skill a run on a worker can use (its sidecar's /skills). */
|
||
export interface WorkerSkill {
|
||
name: string;
|
||
title: string;
|
||
description: string;
|
||
triggerWords: string[];
|
||
source: "project" | "user";
|
||
path: string;
|
||
}
|
||
|
||
export interface WorkerSkillsResponse {
|
||
skills: WorkerSkill[];
|
||
count: number;
|
||
worker: string;
|
||
}
|
||
|
||
/** The skills a run on `workerId` can use — what the composer lists for it. */
|
||
export async function fetchWorkerSkills(workerId: string): Promise<WorkerSkillsResponse> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(workerId)}/skills`);
|
||
if (!r.ok) throw new Error(`worker skills: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
export async function fetchProfiles(): Promise<ProfilesResponse> {
|
||
const r = await apiFetch("/api/profiles", { cache: "no-store" });
|
||
if (!r.ok) throw new Error(`profiles: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
/** Edit a profile (Settings → Profiles). A project or runner claimed here
|
||
* leaves the profile that had it; `workers` is the whole runner list,
|
||
* default first (a runner always sits in some profile). */
|
||
export async function patchProfile(
|
||
id: string,
|
||
// `accounts`: the profile's ★ account per provider (`{vendorId: accountId}`;
|
||
// a missing vendor = each machine's own). Not in the generated body until
|
||
// the next OpenAPI dump.
|
||
changes: ProfilePatchBody & { accounts?: Record<string, string> },
|
||
): Promise<Profile> {
|
||
const r = await apiFetch(`/api/profiles/${encodeURIComponent(id)}`, {
|
||
method: "PATCH",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(changes),
|
||
});
|
||
if (!r.ok) throw await apiError("profile", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Edit one runner within its profile: its ★ login per harness or provider (`""` clears
|
||
* one), its start dir (`""` = its own default), make it the profile's
|
||
* default runner, or move it to another profile. Answers that profile. */
|
||
export async function patchRunner(
|
||
runner: string,
|
||
changes: { accounts?: Record<string, string | null>; cwd?: string; default?: boolean; profile?: string },
|
||
): Promise<Profile> {
|
||
const r = await apiFetch(`/api/profiles/runners/${encodeURIComponent(runner)}`, {
|
||
method: "PATCH",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(changes),
|
||
});
|
||
if (!r.ok) throw await apiError("runner", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** A card per conversation `ids` names (backend `conversations/refs.py`): ids,
|
||
* session ids, ≥ 6-char prefixes or viewer links — what the composer's
|
||
* conversation pill and a sent message's chips show. */
|
||
export async function fetchConversationRefs(ids: string[]): Promise<ConversationRefsResponse> {
|
||
const r = await apiFetch(`/api/conversation-refs?ids=${encodeURIComponent(ids.join(","))}`);
|
||
if (!r.ok) throw new Error(t("conversation refs: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
export async function fetchWorkers(): Promise<WorkersResponse> {
|
||
const r = await apiFetch("/api/workers", { cache: "no-store" });
|
||
if (!r.ok) throw new Error(`workers: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
/** Pair with a worker from the string its installer printed. `account`
|
||
* overrides the login → account match (needed when the login matches none). */
|
||
export async function pairWorker(
|
||
pairing: string,
|
||
opts?: {
|
||
account?: string;
|
||
name?: string;
|
||
profile?: string;
|
||
default?: boolean;
|
||
/** "proxy" (the Homelab's logins, through the hub) | "own" (the machine's). */
|
||
claudeMode?: string;
|
||
claudeAccounts?: string[];
|
||
},
|
||
): Promise<Worker> {
|
||
const r = await apiFetch("/api/workers", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ pairing, account: opts?.account || undefined,
|
||
claudeMode: opts?.claudeMode || undefined,
|
||
claudeAccounts: opts?.claudeAccounts,
|
||
name: opts?.name || undefined,
|
||
profile: opts?.profile || undefined,
|
||
default: opts?.default ?? false }),
|
||
});
|
||
if (!r.ok) throw await apiError("pair", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** *Pair a worker* → *It dials out*: a one-time code (an hour) and the line
|
||
* that installs a worker on a machine off the tailnet. It runs on its own
|
||
* Claude login (`account`) and joins `profile` once paired through the link. */
|
||
export async function enrollWorker(opts: {
|
||
account: string;
|
||
cwd?: string;
|
||
opencode?: boolean;
|
||
name?: string;
|
||
profile?: string;
|
||
default?: boolean;
|
||
}): Promise<ComputerEnroll> {
|
||
const r = await apiFetch("/api/workers/enroll", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ account: opts.account, cwd: opts.cwd || undefined,
|
||
opencode: !!opts.opencode, name: opts.name || undefined,
|
||
profile: opts.profile || undefined, default: !!opts.default }),
|
||
});
|
||
if (!r.ok) throw await apiError("enroll", r);
|
||
return r.json();
|
||
}
|
||
|
||
export async function patchWorker(
|
||
id: string,
|
||
changes: {
|
||
name?: string;
|
||
account?: string;
|
||
autoRoute?: boolean;
|
||
autoUpdate?: boolean;
|
||
claudeMode?: string;
|
||
claudeAccounts?: string[];
|
||
opencodeProxyAccounts?: string[];
|
||
},
|
||
): Promise<Worker> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}`, {
|
||
method: "PATCH",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(changes),
|
||
});
|
||
if (!r.ok) throw await apiError("worker", r);
|
||
return r.json();
|
||
}
|
||
|
||
export async function probeWorker(id: string): Promise<Worker> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}/probe`, { method: "POST" });
|
||
if (!r.ok) throw await apiError("probe", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** *Update now*: move the worker to the hub's own commit. Asynchronous — the
|
||
* worker reports `updating`, then `current` (or `failed`) on its next probes. */
|
||
export async function updateWorker(id: string): Promise<Worker> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}/update`, { method: "POST" });
|
||
if (!r.ok) throw await apiError("update", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** The Setup checklist's *Install* / *Update* / *Install all missing*
|
||
* (backend workers/tools.py) — asynchronous: the worker's `toolJobs` follow
|
||
* the batch (the hub probes it every 3 s while it runs). */
|
||
export async function installWorkerTools(id: string, tools: string[], action: "install" | "update" = "install"): Promise<Worker> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}/tools`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ tools, action }),
|
||
});
|
||
if (!r.ok) throw await apiError("install", r);
|
||
return r.json(); // the SSE `workers` event refreshes the lists
|
||
}
|
||
|
||
/** gh's device-code sign-in on a worker: start (a code for github.com/login/device), follow, cancel. */
|
||
export const workerGhLogin = (id: string) => {
|
||
const url = `/api/workers/${encodeURIComponent(id)}/gh-login`;
|
||
const go = async (method: string): Promise<GhLogin> => {
|
||
const r = await apiFetch(url, { method });
|
||
if (!r.ok) throw await apiError("gh sign-in", r);
|
||
return r.json();
|
||
};
|
||
return { start: () => go("POST"), state: () => go("GET"), cancel: () => go("DELETE") };
|
||
};
|
||
|
||
/** The worker's *Lab skills & agents* checklist (backend workers/labsync.py). */
|
||
export async function fetchWorkerLabSync(id: string): Promise<WorkerLabSync> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}/labsync`);
|
||
if (!r.ok) throw await apiError("lab sync", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Save its ticks/unticks (``skill:<name>`` / ``agent:<name>`` → bool); the hub pushes at once. */
|
||
export async function saveWorkerLabSync(id: string, overrides: Record<string, boolean>): Promise<WorkerLabSync> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}/labsync`, {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ overrides }),
|
||
});
|
||
if (!r.ok) throw await apiError("lab sync", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** *Sync now*: send the bundle whatever the probe's retry delay. */
|
||
export async function pushWorkerLabSync(id: string): Promise<WorkerLabSync> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}/labsync/push`, { method: "POST" });
|
||
if (!r.ok) throw await apiError("sync", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Repo plugins × workers and the account picks (backend workers/repoplugins.py). */
|
||
export async function fetchRepoPlugins(): Promise<RepoPluginsView> {
|
||
const r = await apiFetch("/api/repo-plugins");
|
||
if (!r.ok) throw await apiError("repo plugins", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** An account's picks (`<plugin>@<marketplace>` ids); its online workers get them at once. */
|
||
export async function saveRepoPluginPicks(account: string, plugins: string[]): Promise<RepoPluginsView> {
|
||
const r = await apiFetch(`/api/repo-plugins/accounts/${encodeURIComponent(account)}`, {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ plugins }),
|
||
});
|
||
if (!r.ok) throw await apiError("repo plugins", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** A worker's ticks/unticks (`<plugin>@<marketplace>` → bool); the hub applies them at once. */
|
||
export async function saveWorkerRepoPlugins(id: string, overrides: Record<string, boolean>): Promise<RepoPluginsView> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}/repo-plugins`, {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ overrides }),
|
||
});
|
||
if (!r.ok) throw await apiError("repo plugins", r);
|
||
return r.json();
|
||
}
|
||
|
||
export async function unpairWorker(id: string): Promise<void> {
|
||
const r = await apiFetch(`/api/workers/${encodeURIComponent(id)}`, { method: "DELETE" });
|
||
if (!r.ok) throw await apiError("unpair", r);
|
||
}
|
||
|
||
/** `?worker=<id>`: the sign-in runs on that worker — its own machine's Claude
|
||
* login (a Mac in `own` mode: the Keychain), not the Homelab's copy. */
|
||
function onWorker(worker?: string | null): string {
|
||
return worker ? `?worker=${encodeURIComponent(worker)}` : "";
|
||
}
|
||
|
||
/** Start a headless `claude auth login` for an account; resolves to the
|
||
* sign-in URL to open (the code it ends on goes to {@link submitLoginCode}). */
|
||
export async function startAccountLogin(
|
||
account: string,
|
||
email?: string | null,
|
||
worker?: string | null,
|
||
): Promise<PendingLogin> {
|
||
const r = await apiFetch(`/api/accounts/${encodeURIComponent(account)}/login${onWorker(worker)}`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email: email || undefined }),
|
||
});
|
||
if (!r.ok) throw await apiError("login", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Where an opencode account's device-code login stands — `pending` while the
|
||
* code waits to be entered, then `complete` / `failed` (the Settings card
|
||
* polls it; there is no code to paste back). */
|
||
export async function fetchLoginState(account: string): Promise<LoginState> {
|
||
const r = await apiFetch(`/api/accounts/${encodeURIComponent(account)}/login`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw await apiError("login", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Finish the pending login with the pasted `code#state`. */
|
||
export async function submitLoginCode(account: string, code: string, worker?: string | null): Promise<LoginCodeResult> {
|
||
const r = await apiFetch(`/api/accounts/${encodeURIComponent(account)}/login/code${onWorker(worker)}`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ code }),
|
||
});
|
||
if (!r.ok) throw await apiError("login", r);
|
||
return r.json();
|
||
}
|
||
|
||
/** Each account's login health (backend accounts/health.py) — kept current
|
||
* server-side and pushed as an `accounts` SSE event when it moves. A guest
|
||
* gets the default account's status only. */
|
||
export async function fetchLoginHealth(): Promise<AccountsHealthResponse> {
|
||
const r = await apiFetch("/api/accounts/health", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(t("login health: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** *Check again*: a one-turn probe on the account, then its fresh health. */
|
||
export async function checkAccount(account: string): Promise<AccountCheckResult> {
|
||
const r = await apiFetch(`/api/accounts/${encodeURIComponent(account)}/check`, { method: "POST" });
|
||
if (!r.ok) throw await apiError(msg("check"), r);
|
||
return r.json();
|
||
}
|
||
|
||
// ── a guest's own Claude login (backend accounts/guest.py) ───────────────────
|
||
export async function startGuestClaudeLogin(email?: string | null): Promise<PendingLogin> {
|
||
const r = await apiFetch("/api/me/claude/login", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ email: email || undefined }),
|
||
});
|
||
if (!r.ok) throw await apiError(msg("connect"), r);
|
||
return r.json();
|
||
}
|
||
|
||
export async function submitGuestClaudeCode(code: string): Promise<GuestClaude> {
|
||
const r = await apiFetch("/api/me/claude/login/code", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ code }),
|
||
});
|
||
if (!r.ok) throw await apiError(msg("connect"), r);
|
||
return r.json();
|
||
}
|
||
|
||
export async function cancelGuestClaudeLogin(): Promise<void> {
|
||
const r = await apiFetch("/api/me/claude/login", { method: "DELETE" });
|
||
if (!r.ok) throw await apiError(msg("cancel"), r);
|
||
}
|
||
|
||
/** Which login a guest's runs bill (their composer's account chip): "own" =
|
||
* their own Claude first, the host's as the fallback; "host" = the host's
|
||
* account, within their budget and models. */
|
||
export async function setGuestClaudeBill(bill: "own" | "host"): Promise<GuestClaude> {
|
||
const r = await apiFetch("/api/me/claude/bill", {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ bill }),
|
||
});
|
||
if (!r.ok) throw await apiError(msg("switch account"), r);
|
||
return r.json();
|
||
}
|
||
|
||
export async function logoutGuestClaude(): Promise<GuestClaude> {
|
||
const r = await apiFetch("/api/me/claude/logout", { method: "POST" });
|
||
if (!r.ok) throw await apiError(msg("disconnect"), r);
|
||
return r.json();
|
||
}
|
||
|
||
export async function cancelAccountLogin(account: string, worker?: string | null): Promise<void> {
|
||
const r = await apiFetch(`/api/accounts/${encodeURIComponent(account)}/login${onWorker(worker)}`, { method: "DELETE" });
|
||
if (!r.ok) throw await apiError(msg("cancel login"), r);
|
||
}
|
||
|
||
export async function logoutAccount(account: string, worker?: string | null): Promise<LoginCodeResult> {
|
||
const r = await apiFetch(`/api/accounts/${encodeURIComponent(account)}/logout${onWorker(worker)}`, { method: "POST" });
|
||
if (!r.ok) throw await apiError(msg("logout"), r);
|
||
return r.json();
|
||
}
|
||
|
||
/** One stored composer attachment, as returned by {@link uploadFiles}. */
|
||
export interface UploadedFile {
|
||
name: string;
|
||
size: number;
|
||
contentType: string;
|
||
/** Repo-relative path injected into the prompt (the session reads it). */
|
||
repoPath: string;
|
||
/** Backend serve route the thread viewer renders the file from. */
|
||
url: string;
|
||
}
|
||
|
||
/**
|
||
* Upload composer attachments to the backend, which stores them under the
|
||
* service's data dir and returns, per file, the repo-relative path to inject
|
||
* into the prompt plus a serve URL for inline preview.
|
||
*/
|
||
export async function uploadFiles(files: File[]): Promise<UploadedFile[]> {
|
||
const fd = new FormData();
|
||
for (const f of files) fd.append("files", f);
|
||
const r = await apiFetch("/api/upload", { method: "POST", body: fd });
|
||
if (!r.ok) {
|
||
const body = await r.text().catch(() => "");
|
||
throw new Error(t("upload: {status} {detail}", { status: r.status, detail: body }));
|
||
}
|
||
return (await r.json()).files;
|
||
}
|
||
|
||
// ── the standalone ask-form tool's forms, as the hub mirrors them ───────────
|
||
export async function fetchAskForms(session?: string, status?: string): Promise<AskFormRecord[]> {
|
||
const params = new URLSearchParams();
|
||
if (session) params.set("session", session);
|
||
if (status) params.set("status", status);
|
||
const qs = params.size ? `?${params}` : "";
|
||
const r = await apiFetch(`/api/ask-form/forms${qs}`, { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(t("ask-form: {status}", { status: r.status }));
|
||
return (await r.json()).forms as AskFormRecord[];
|
||
}
|
||
|
||
export async function fetchAskForm(id: string): Promise<AskFormRecord> {
|
||
const r = await apiFetch(`/api/ask-form/forms/${encodeURIComponent(id)}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("ask-form: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** Have the hub re-read one ask-form form off its machine now (backend
|
||
* askform/service.py `recheck`) — the app heard it answered. */
|
||
export async function recheckAskForm(id: string): Promise<AskFormRecord> {
|
||
const r = await apiFetch(`/api/ask-form/forms/${encodeURIComponent(id)}/recheck`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("ask-form: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** Revoke an open form (or close a multi one) on the machine that holds it. */
|
||
export async function endAskForm(id: string, close = false): Promise<AskFormRecord> {
|
||
const r = await apiFetch(`/api/ask-form/forms/${encodeURIComponent(id)}/${close ? "close" : "revoke"}`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(await r.text().catch(() => `ask-form ${close ? "close" : "revoke"}: ${r.status}`));
|
||
return r.json();
|
||
}
|
||
|
||
export async function fetchSkills(account?: string | null): Promise<SkillsResponse> {
|
||
const r = await apiFetch(`/api/skills${accountQs(account, "?")}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("skills: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
// ── agents catalog (/agents) ─────────────────────────────────────────────────
|
||
export async function fetchAgents(account?: string | null): Promise<AgentsResponse> {
|
||
const r = await apiFetch(`/api/agents${accountQs(account, "?")}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("agents: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
export async function fetchProjects(account?: string | null): Promise<ProjectSummary[]> {
|
||
const r = await apiFetch(`/api/projects${accountQs(account, "?")}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("projects: {status}", { status: r.status }));
|
||
return (await r.json()).projects;
|
||
}
|
||
|
||
export async function fetchProject(
|
||
slug: string,
|
||
account?: string | null,
|
||
): Promise<ProjectDetail> {
|
||
const r = await apiFetch(`/api/project?slug=${encodeURIComponent(slug)}${accountQs(account)}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("project: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** The homelab services, from the services plugin (owner only; `[]` when no
|
||
* plugin provides `services.index`). Ask only while one does —
|
||
* `useServices` gates on it. */
|
||
export async function fetchServicesIndex(): Promise<ServiceIndexEntry[]> {
|
||
const r = await apiFetch("/api/plugins/services-index", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(`services: ${r.status}`);
|
||
return ((await r.json()) as ServicesIndexResponse).services ?? [];
|
||
}
|
||
|
||
/** The native Claude Code hooks registered in the workspace repo (read-only). */
|
||
export async function fetchClaudeHooks(): Promise<ClaudeHooksResponse> {
|
||
const r = await apiFetch("/api/claude-hooks", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(`claude hooks: ${r.status}`);
|
||
return r.json();
|
||
}
|
||
|
||
/**
|
||
* Settings → Fresh context: when the reply box nudges toward compacting a
|
||
* conversation instead of replaying all of it, and the measured assumptions
|
||
* its estimate runs on (`lib/freshContext.ts`).
|
||
*/
|
||
export async function fetchFreshContext(): Promise<FreshContextSettings> {
|
||
const r = await apiFetch("/api/fresh-context", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(`fresh-context: ${r.status}`);
|
||
return (await r.json()) as FreshContextSettings;
|
||
}
|
||
|
||
export async function saveFreshContext(
|
||
body: Partial<Omit<FreshContextSettings, "assumptions">>,
|
||
): Promise<FreshContextSettings> {
|
||
const r = await apiFetch("/api/fresh-context", {
|
||
method: "PUT",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(body),
|
||
});
|
||
if (!r.ok) throw new Error(await r.text().catch(() => `fresh-context save: ${r.status}`));
|
||
return (await r.json()) as FreshContextSettings;
|
||
}
|
||
|
||
// ── the lab browser (Settings → Browser, the conversation's Browser panel) ──
|
||
/** Where the composer's *Code β* chip can start a run (backend runs/codemode.py). */
|
||
export async function fetchCodeMode(): Promise<CodeModeStatus> {
|
||
const r = await apiFetch("/api/code-mode", { headers: { Accept: "application/json" } });
|
||
if (!r.ok) throw new Error(`code-mode: ${r.status}`);
|
||
return (await r.json()) as CodeModeStatus;
|
||
}
|
||
|
||
/**
|
||
* Answer a pending ask (a `notify-ask` choice question) from the browser —
|
||
* the same endpoint the Home Assistant integration POSTs a tapped button to,
|
||
* so the waiting agent's long-poll wakes with the label either way. Used by the
|
||
* home page's "Waiting for feedback" section, which renders the options as
|
||
* buttons so a question doesn't have to be answered from the phone.
|
||
*/
|
||
export async function answerAsk(id: string, index: number, label: string): Promise<AskRecord> {
|
||
const r = await apiFetch(`/api/ask/${encodeURIComponent(id)}/answer`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ index, label }),
|
||
});
|
||
if (!r.ok) throw new Error(await r.text().catch(() => `ask answer: ${r.status}`));
|
||
return r.json();
|
||
}
|
||
|
||
/** Tap one of a push's buttons (a plugin's hub/notify `actions` — auto-ship's
|
||
* Merge & deploy): what the phone's Home Assistant button and the browsers'
|
||
* service worker send. The first tap wins; a later one is a no-op. */
|
||
export async function actOnPush(id: string, index: number): Promise<void> {
|
||
const r = await apiFetch(`/api/notify/${encodeURIComponent(id)}/action`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ index }),
|
||
});
|
||
if (!r.ok) throw new Error(await r.text().catch(() => `push action: ${r.status}`));
|
||
}
|
||
|
||
/** One ask's current state (no long-poll) — backs the in-thread ask card. */
|
||
export async function fetchAsk(id: string): Promise<AskRecord> {
|
||
const r = await apiFetch(`/api/ask/${encodeURIComponent(id)}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(t("ask: {status}", { status: r.status }));
|
||
return r.json();
|
||
}
|
||
|
||
/** The first-class notification/ask log (the hub's source-of-truth record). */
|
||
export async function fetchNotifyLog(limit = 200): Promise<NotifyLogEntry[]> {
|
||
const r = await apiFetch(`/api/notify-log?limit=${limit}`, {
|
||
headers: { Accept: "application/json" },
|
||
});
|
||
if (!r.ok) throw new Error(`notify-log: ${r.status}`);
|
||
return (await r.json()).notifications as NotifyLogEntry[];
|
||
}
|