Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | 15x 15x 15x 2209x 2209x 53x 53x 53x 2209x 4x 4x 4x 2209x 14x 14x 2209x 3x 3x 3x 2209x 3x 3x 3x 2209x 3x 3x 3x 2209x 3x 3x 2209x 7x 7x 2209x 6x 6x 2209x 3x 3x 3x 2209x 3x 3x 3x 2209x 6x 6x 2209x 5x 5x 5x 2209x 3x 3x 2209x 3x 2209x 3x 2209x 3x 2209x 3x 3x 2209x 3x 3x 3x 3x 2209x 12x | import type {
Swarm,
SwarmAdvice,
SwarmApproval,
SwarmDispatch,
SwarmFollowUp,
SwarmInput,
SwarmRefusal,
SwarmRun,
SwarmRunSummary,
SwarmThread,
Topology,
} from "@/objects/Swarm";
import { Dictionary } from "@/types/ext";
import { AxiosRequestConfig, isAxiosError } from "axios";
import { dispositionFilename, saveBlob } from "@/util/download";
import { HistoricalAPIRouter } from "../HistoricalApiRouter";
/** Why swarms cannot be used here: the deployment has them switched off
* (svc-core answers every swarm route 404 until `SWARMS_ENABLED`). */
export type SwarmsUnavailable = "off";
export type TopologyCatalogue =
| { topologies: Topology[]; unavailable: null }
| { topologies: []; unavailable: SwarmsUnavailable };
/**
* A refusal from a swarm route, as it describes itself: a 422's
* `{message, fields}` (each reason beside its field), a 409's sentence, or a
* used-up budget's 403 (`{rule, message, code: "budget"}`).
*/
function refusalOf(e: unknown): SwarmRefusal | null {
if (!isAxiosError(e)) return null;
const status = e.response?.status;
const detail = e.response?.data?.detail;
if ((status !== 422 && status !== 409 && status !== 403) || !detail) return null;
if (typeof detail === "object" && "message" in detail) {
const { message, fields } = detail as Partial<SwarmRefusal>;
return { message: String(message), fields: fields ?? {} };
}
return { message: String(detail), fields: {} };
}
/** A run action's reply: the run as it now stands, or why it was refused. */
async function asRun(
call: () => Promise<{ data: SwarmRun }>,
): Promise<{ run: SwarmRun } | { refused: SwarmRefusal }> {
try {
const res = await call();
return { run: res.data };
} catch (e) {
const refused = refusalOf(e);
if (refused) return { refused };
throw e;
}
}
/**
* Swarms (svc-core `/app/swarms`, docs/guides/swarms.md): the shapes a swarm
* can take, swarms themselves (with their edit history), and their runs —
* dispatch, the plan's approval, a worker's questions, Stop, and the answer
* as a PDF.
*/
export class SwarmRouter extends HistoricalAPIRouter {
constructor(
host: string,
token: string | null = null,
default_config: AxiosRequestConfig | null = null,
headers: Dictionary<string> = {},
) {
super("swarms", host, token, default_config, headers);
}
/** Every shape a swarm can take — or, where swarms are switched off,
* that they are. */
topologies = async (): Promise<TopologyCatalogue> => {
try {
const res = await this.api.get<Topology[]>(this.endpoint("topologies"));
return {
topologies: Array.isArray(res.data) ? res.data : [],
unavailable: null,
};
} catch (e) {
if (isAxiosError(e) && e.response?.status === 404) {
return { topologies: [], unavailable: "off" };
}
throw e;
}
};
/** The swarms of the request's workspace. Empty where swarms are off. */
list = async (): Promise<Swarm[]> => {
try {
const res = await this.api.get<Swarm[]>(this.endpoint(""));
return super.validRes(res) && Array.isArray(res.data) ? res.data : [];
} catch (e) {
if (isAxiosError(e) && e.response?.status === 404) return [];
throw e;
}
};
getById = async (id: string): Promise<Swarm | null> => {
const res = await this.api.get<Swarm>(this.endpoint(id));
return super.validRes(res) ? res.data : null;
};
/** A new swarm in the request's workspace; a 422 names what is wrong with
* its shape, settings or roster. */
create = async (
body: SwarmInput,
): Promise<{ swarm: Swarm } | { refused: SwarmRefusal }> => {
try {
const res = await this.api.post<Swarm>(this.endpoint(""), body);
return { swarm: res.data };
} catch (e) {
const refused = refusalOf(e);
if (refused) return { refused };
throw e;
}
};
update = async (
id: string,
body: Partial<SwarmInput>,
): Promise<{ swarm: Swarm } | { refused: SwarmRefusal }> => {
try {
const res = await this.api.patch<Swarm>(this.endpoint(id), body);
return { swarm: res.data };
} catch (e) {
const refused = refusalOf(e);
if (refused) return { refused };
throw e;
}
};
/** Delete a swarm; refused (409) while a run of it is going. */
remove = async (id: string): Promise<true | { refused: SwarmRefusal }> => {
try {
await this.api.delete(this.endpoint(id));
return true;
} catch (e) {
const refused = refusalOf(e);
if (refused) return { refused };
throw e;
}
};
/** The caller's newest runs of one swarm. */
listRuns = async (id: string): Promise<SwarmRunSummary[]> => {
const res = await this.api.get<SwarmRunSummary[]>(this.endpoint(`${id}/runs`));
return super.validRes(res) && Array.isArray(res.data) ? res.data : [];
};
/** The caller's threads of one swarm — a run and its follow-ups, one
* item — the newest activity first. */
listThreads = async (id: string): Promise<SwarmThread[]> => {
const res = await this.api.get<SwarmThread[]>(this.endpoint(`${id}/threads`));
return super.validRes(res) && Array.isArray(res.data) ? res.data : [];
};
/** What the record says about the swarm's shape: advice read from the
* caller's runs of it and the evaluations that ran it. */
advice = async (id: string): Promise<SwarmAdvice[]> => {
const res = await this.api.get<{ advice: SwarmAdvice[] }>(
this.endpoint(`${id}/advice`),
);
return super.validRes(res) && Array.isArray(res.data?.advice) ? res.data.advice : [];
};
/** The caller's newest runs of any swarm, in the request's workspace. */
myRuns = async (): Promise<SwarmRunSummary[]> => {
try {
const res = await this.api.get<SwarmRunSummary[]>(this.endpoint("runs"));
return super.validRes(res) && Array.isArray(res.data) ? res.data : [];
} catch (e) {
if (isAxiosError(e) && e.response?.status === 404) return [];
throw e;
}
};
/** The caller's threads of any swarm, in the request's workspace. */
myThreads = async (): Promise<SwarmThread[]> => {
try {
const res = await this.api.get<SwarmThread[]>(this.endpoint("threads"));
return super.validRes(res) && Array.isArray(res.data) ? res.data : [];
} catch (e) {
if (isAxiosError(e) && e.response?.status === 404) return [];
throw e;
}
};
getRun = async (runId: string): Promise<SwarmRun | null> => {
const res = await this.api.get<SwarmRun>(this.endpoint(`runs/${runId}`));
return super.validRes(res) ? res.data : null;
};
/** Send a swarm on a task. A 422 names what cannot run; a 409 that the
* caller has as many runs going as they may; a 403 that a budget of the
* workspace is used up. */
start = async (
id: string,
body: SwarmDispatch,
): Promise<{ run: SwarmRun } | { refused: SwarmRefusal }> => {
try {
const res = await this.api.post<SwarmRun>(this.endpoint(`${id}/runs`), body);
return { run: res.data };
} catch (e) {
const refused = refusalOf(e);
if (refused) return { refused };
throw e;
}
};
/** Follow up one of the caller's runs: the swarm, as it is now, sent on
* the next request of the run's thread. A 409 says the run is not its
* thread's latest request any more, or as many runs are going as may. */
followUp = (runId: string, body: SwarmFollowUp) =>
asRun(() =>
this.api.post<SwarmRun>(this.endpoint(`runs/${runId}/follow-up`), body),
);
/** Approve the lead's plan, with any pieces dropped or reassigned and the
* budget changed. */
approve = (runId: string, body: SwarmApproval = {}) =>
asRun(() => this.api.post<SwarmRun>(this.endpoint(`runs/${runId}/approve`), body));
/** Decline the lead's plan: nothing more is spent. */
reject = (runId: string) =>
asRun(() => this.api.post<SwarmRun>(this.endpoint(`runs/${runId}/reject`), {}));
/** Stop: no new work starts, and the run answers from what is done. */
stop = (runId: string) =>
asRun(() => this.api.post<SwarmRun>(this.endpoint(`runs/${runId}/stop`), {}));
/** Answer a worker's questions; its piece runs again with the answers. */
respond = (
runId: string,
taskId: string,
body: { answers: Record<string, string[]> },
) =>
asRun(() =>
this.api.post<SwarmRun>(
this.endpoint(`runs/${runId}/tasks/${taskId}/respond`),
body,
),
);
/** Save the run's answer as a PDF, rendered by svc-core from what the run
* stored. Resolves false when the download failed. */
downloadRunDocument = async (
runId: string,
index = 0,
fallbackName = "swarm.pdf",
): Promise<boolean> => {
const res = await this.api
.get(this.endpoint(`runs/${runId}/document.pdf`, { index }), {
responseType: "blob",
withCredentials: true,
})
.catch(() => null);
Iif (res?.status !== 200) return false;
saveBlob(
res.data as Blob,
dispositionFilename(res.headers?.["content-disposition"]) ?? fallbackName,
);
return true;
};
/** Where an image a document in the run's answer shows is served. */
runImageUrl = (runId: string, asset: string): string =>
this.api.endpoint(
this.endpoint(`runs/${runId}/images/${encodeURIComponent(asset)}`),
);
}
|