mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-28 09:09:57 +01:00
Protocol 3: claim request ids and the fast lane, heartbeat phases, helper slots, busy count and last error, the per-user call limit
This commit is contained in:
1 parent
eeb45653f8
commit
aaa9fae512
7 files changed
+60
-13
No files matched your search
@@ -17,7 +17,7 @@ async function repoChoices(db: DatabaseSync, req: Req): Promise<string[]> {
|
||||
}
|
||||
|
||||
export const settings = async (db: DatabaseSync, req: Req): Promise<UserSettingsReply> =>
|
||||
({ reserve: userReserve(db, req.user.login), repos: userRepos(db, req.user.login), repoChoices: await repoChoices(db, req) });
|
||||
({ reserve: userReserve(db, req.user.login), repos: userRepos(db, req.user.login), maxCalls: null, repoChoices: await repoChoices(db, req) });
|
||||
|
||||
export async function setSettings(db: DatabaseSync, req: Req): Promise<UserSettingsReply> {
|
||||
if (req.user.role === "viewer") throw new HttpError(403, "viewers have no settings to change");
|
||||
|
||||
+3
-1
@@ -249,7 +249,9 @@ export function parseClaim(raw: unknown): Claim {
|
||||
if (c.repos !== undefined && (!Array.isArray(c.repos) || c.repos.length > 500 || !c.repos.every((x) => short(x, 100)))) throw new HttpError(400, "repos must be a list of repo names");
|
||||
if (c.sessions !== undefined && (!Array.isArray(c.sessions) || c.sessions.length > 500 || !c.sessions.every((x) => Number.isInteger(x)))) throw new HttpError(400, "sessions must be a list of call ids");
|
||||
if (c.root !== undefined && (typeof c.root !== "string" || !validRoot(c.root))) throw new HttpError(400, "root must be an absolute path of plain characters (letters, digits, . _ + @ -) without . or .. components");
|
||||
return { protocol: PROTOCOL_VERSION, helperVersion: c.helperVersion, harness: c.harness as HarnessId, harnessVersion: c.harnessVersion, tiers, ...(efforts && { efforts }), ...(c.repos !== undefined && { repos: c.repos as string[] }), ...(c.sessions !== undefined && { sessions: c.sessions as number[] }), ...(c.root !== undefined && { root: c.root as string }) };
|
||||
if (typeof c.requestId !== "string" || !/^[A-Za-z0-9_-]{8,64}$/.test(c.requestId)) throw new HttpError(400, "requestId must be 8 to 64 letters, digits, - or _");
|
||||
if (c.fastLane !== undefined && typeof c.fastLane !== "boolean") throw new HttpError(400, "fastLane must be a boolean");
|
||||
return { requestId: c.requestId, ...(c.fastLane === true && { fastLane: true }), protocol: PROTOCOL_VERSION, helperVersion: c.helperVersion, harness: c.harness as HarnessId, harnessVersion: c.harnessVersion, tiers, ...(efforts && { efforts }), ...(c.repos !== undefined && { repos: c.repos as string[] }), ...(c.sessions !== undefined && { sessions: c.sessions as number[] }), ...(c.root !== undefined && { root: c.root as string }) };
|
||||
}
|
||||
|
||||
/** Whether dotted version `v` is older than `min` (numeric parts compared in order; a part that is not a number counts as 0). */
|
||||
|
||||
+13
-1
@@ -49,7 +49,19 @@ export function parseStatus(raw: unknown): HelperStatus {
|
||||
usage = { fiveHour: parseWindow(u.fiveHour, "fiveHour"), weekly: parseWindow(u.weekly, "weekly"), at: u.at };
|
||||
}
|
||||
const reason = typeof s.reason === "string" ? s.reason.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, REASON_MAX) : "";
|
||||
const count = (v: unknown, name: string): number => {
|
||||
if (typeof v !== "number" || !Number.isInteger(v) || v < 0 || v > 64) throw new HttpError(400, `${name} must be a whole number from 0 to 64`);
|
||||
return v;
|
||||
};
|
||||
const slots = count(s.slots, "slots"), busy = count(s.busy, "busy");
|
||||
let lastError: HelperStatus["lastError"];
|
||||
if (s.lastError !== undefined && s.lastError !== null) {
|
||||
const e = s.lastError as Record<string, unknown>;
|
||||
if (typeof e !== "object" || typeof e.text !== "string" || !isoTime(e.at)) throw new HttpError(400, "lastError must be { text, at }");
|
||||
lastError = { text: e.text.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, REASON_MAX), at: e.at };
|
||||
}
|
||||
return {
|
||||
slots, busy: Math.min(busy, slots), ...(lastError && { lastError }),
|
||||
readiness: s.readiness as Readiness, ...(isoTime(s.until) && { until: s.until }), ...(reason && { reason }),
|
||||
harness: s.harness as HarnessId, models, reserve: { fiveHour: r.fiveHour as number, weekly: r.weekly as number }, ...(usage && { usage }),
|
||||
};
|
||||
@@ -77,7 +89,7 @@ export function listHelpers(db: DatabaseSync, login: string, nowMs: number = Dat
|
||||
// The server's own cool-off of the token shows even before the helper has reported it.
|
||||
const cooled = r.cooloff_until !== null && Number(r.cooloff_until) > nowMs && r.readiness !== "cooled-off";
|
||||
return {
|
||||
tokenId: Number(r.id), label: r.label,
|
||||
tokenId: Number(r.id), label: r.label, slots: null, busy: null, lastError: null,
|
||||
...(cooled ? { readiness: "cooled-off" as const, until: new Date(Number(r.cooloff_until)).toISOString(), reason: COOLOFF_REASON } : { readiness: r.readiness, until: r.until, reason: r.reason }),
|
||||
fresh: reported !== null && nowMs - reported <= STATUS_FRESH_MS,
|
||||
lastSeen: Number.isFinite(seen) ? new Date(seen).toISOString() : null,
|
||||
|
||||
+30
-4
@@ -4,7 +4,7 @@
|
||||
// No Node imports: the helper keeps its own copy of these shapes and the dashboard build may import this file.
|
||||
|
||||
/** Bumped on any change to these shapes; the server refuses a claim from a helper of another version. */
|
||||
export const PROTOCOL_VERSION = 2;
|
||||
export const PROTOCOL_VERSION = 3;
|
||||
|
||||
/** API routes on the dashboard origin. Agent-token routes take `Authorization: Bearer <agent token>`; lease routes take `Authorization: Bearer <lease secret>`. */
|
||||
export const ROUTES = {
|
||||
@@ -14,7 +14,7 @@ export const ROUTES = {
|
||||
bundle: "/api/remote/bundle",
|
||||
/** Agent token. Body `HelperStatus`, reply `StatusReply`: the helper's readiness, sent on every change and at least every STATUS_EVERY_S while it runs. */
|
||||
status: "/api/remote/status",
|
||||
/** Lease secret. Body `Heartbeat`, reply `{ ok: true }`, or 410 when the lease is gone (expired, cancelled, re-queued). */
|
||||
/** Lease secret. Body `Heartbeat`, reply `{ ok: true }`, or 410 when the lease is gone (expired, cancelled, re-queued). Every lease route answers 410 for an ended lease, never 401. */
|
||||
heartbeat: "/api/remote/heartbeat",
|
||||
/** Lease secret. Body `Submit`, reply `SubmitReply`. */
|
||||
submit: "/api/remote/submit",
|
||||
@@ -57,8 +57,18 @@ export type Claim = {
|
||||
* paths are read back without it. Absolute, letters, digits and `. _ + @ -`, no `.` or `..` component. Absent: the fixed paths.
|
||||
*/
|
||||
root?: string;
|
||||
/**
|
||||
* Unique per claim attempt (8 to 64 characters of letters, digits, `-` and `_`). A claim repeated with the same id within
|
||||
* CLAIM_ID_TTL_S gets the same reply, so a helper whose reply was lost (reset, proxy error, timeout) retries safely.
|
||||
*/
|
||||
requestId: string;
|
||||
/** The claim comes from the helper's fast-lane slot: the server offers it only follow-ups of its sessions, gating calls and small-tier calls. */
|
||||
fastLane?: boolean;
|
||||
};
|
||||
|
||||
/** How long the server remembers a claim's `requestId` and its reply. */
|
||||
export const CLAIM_ID_TTL_S = 300;
|
||||
|
||||
/**
|
||||
* The plan usage a helper keeps in reserve, per window: it claims only while the remaining percent (100 - used) of every
|
||||
* window is above it. Set per user on the dashboard (0 to 90, default 20); a helper's local setting may only raise it.
|
||||
@@ -97,6 +107,12 @@ export type HelperStatus = {
|
||||
/** The reserve the helper enforces: the user's, raised by its local setting. */
|
||||
reserve: Reserve;
|
||||
usage?: UsageReading;
|
||||
/** Calls the helper runs at once: its `--parallel` slots plus the fast lane. */
|
||||
slots: number;
|
||||
/** Slots running a call now. */
|
||||
busy: number;
|
||||
/** The helper's last error talking to the server or running a call, until it recovers: what failed, in one line, and when (ISO time). */
|
||||
lastError?: { text: string; at: string };
|
||||
};
|
||||
/** The user's reserve, so a helper knows it before its first claim. */
|
||||
export type StatusReply = { ok: true; reserve: Reserve };
|
||||
@@ -117,13 +133,16 @@ export type HelperInfo = {
|
||||
models: Partial<Record<Tier, string>>;
|
||||
reserve: Reserve | null;
|
||||
usage: UsageReading | null;
|
||||
slots: number | null;
|
||||
busy: number | null;
|
||||
lastError: { text: string; at: string } | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* GET and PUT /api/me/settings (session routes): the signed-in user's own settings. `repos`: the repos their helpers take calls
|
||||
* from, empty for every repo. A PUT sends either field or both.
|
||||
*/
|
||||
export type UserSettings = { reserve: Reserve; repos: string[] };
|
||||
export type UserSettings = { reserve: Reserve; repos: string[]; /** The most calls the user's helpers run at once, all helpers together; null for no limit. */ maxCalls: number | null };
|
||||
/** The settings with `repoChoices`: the tracked repos with the pipeline on where the user has write permission, sorted. */
|
||||
export type UserSettingsReply = UserSettings & { repoChoices: string[] };
|
||||
|
||||
@@ -164,7 +183,14 @@ export type TaskBundle = {
|
||||
};
|
||||
};
|
||||
|
||||
export type Heartbeat = { /** The harness's last progress line, shown on the run. */ progress?: string };
|
||||
/**
|
||||
* Sent every HEARTBEAT_S from the claim until the submit or release. `preparing`: fetching the bundle and the code; the
|
||||
* call's time limit has not started, but preparing may take at most PREPARE_MAX_S. `running`: the harness runs; the first
|
||||
* `running` heartbeat starts the time limit.
|
||||
*/
|
||||
export type Heartbeat = { phase: "preparing" | "running"; /** The harness's last progress line, shown on the run. */ progress?: string };
|
||||
export const HEARTBEAT_S = 30;
|
||||
export const PREPARE_MAX_S = 15 * 60;
|
||||
|
||||
export type Usage = { inputTokens: number; outputTokens: number; cacheReadTokens?: number; cacheWriteTokens?: number };
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ describe("user-local remote calls", () => {
|
||||
db.prepare("INSERT INTO access (login, role) VALUES (?, 'maintainer')").run(login);
|
||||
callers[login] = { tokenId: createToken(db, login, "helper", false, true).row.id, login, role: "maintainer" };
|
||||
}
|
||||
const claim: Claim = { protocol: PROTOCOL_VERSION, helperVersion: "1.1.0", harness: "claude", harnessVersion: "2.1", tiers: { top: "opus" } };
|
||||
const claim: Claim = { requestId: "test-claim-0001", protocol: PROTOCOL_VERSION, helperVersion: "1.1.0", harness: "claude", harnessVersion: "2.1", tiers: { top: "opus" } };
|
||||
const canWrite = async () => true;
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const leaseFor = async (login: string) => {
|
||||
@@ -205,7 +205,7 @@ describe("user-local remote calls", () => {
|
||||
assert.ok(db.prepare("SELECT 1 FROM audit WHERE action = 'usage-reserve' AND login = 'bob'").get());
|
||||
assert.deepEqual(await claimCall(db, callers.bob!, claim, canWrite), { lease: null, retryAfter: CLAIM_RETRY_S, reserve: { fiveHour: 35, weekly: 10 } });
|
||||
assert.equal(remoteRoom(db, 0), 0, "an idle helper that never reported ready");
|
||||
const status = { harness: "claude", models: { top: "opus" }, reserve: { fiveHour: 35, weekly: 10 }, usage: { fiveHour: { usedPercent: 70, resetsAt: null }, weekly: null, at: new Date().toISOString() } };
|
||||
const status = { slots: 1, busy: 0, harness: "claude", models: { top: "opus" }, reserve: { fiveHour: 35, weekly: 10 }, usage: { fiveHour: { usedPercent: 70, resetsAt: null }, weekly: null, at: new Date().toISOString() } };
|
||||
storeStatus(db, callers.bob!.tokenId, "bob", parseStatus({ ...status, readiness: "ready" }));
|
||||
assert.equal(remoteRoom(db, 0), 1);
|
||||
storeStatus(db, callers.bob!.tokenId, "bob", parseStatus({ ...status, readiness: "quota-held", until: "2026-11-20T01:30:00.000Z", reason: "5-hour window 70% used" }));
|
||||
|
||||
@@ -65,7 +65,7 @@ describe("per-lease tools of remote calls", () => {
|
||||
ended: enqueueCall(db, { ...common, bundle: bundle(["items"]) }),
|
||||
};
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const r = await claimCall(db, caller, { protocol: PROTOCOL_VERSION, helperVersion: "1.0.0", harness: "claude", harnessVersion: "2", tiers: { top: "opus" } }, async () => true);
|
||||
const r = await claimCall(db, caller, { requestId: "test-claim-0001", protocol: PROTOCOL_VERSION, helperVersion: "1.0.0", harness: "claude", harnessVersion: "2", tiers: { top: "opus" } }, async () => true);
|
||||
const name = Object.entries(ids).find(([, id]) => id === r.lease?.id)![0];
|
||||
leases.set(name, r.lease!);
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ export const HELPER_VERSION = "1.1.0";
|
||||
// Wire format: a copy of src/remote/protocol.ts (the helper is served alone, so it keeps its own).
|
||||
|
||||
/** Must equal the server's; the server refuses a claim from a helper of another version. */
|
||||
export const PROTOCOL_VERSION = 2;
|
||||
export const PROTOCOL_VERSION = 3;
|
||||
|
||||
export const ROUTES = {
|
||||
claim: "/api/remote/claim",
|
||||
@@ -71,6 +71,8 @@ export const ROUTES = {
|
||||
* @property {string[]} [repos]
|
||||
* @property {number[]} [sessions]
|
||||
* @property {string} [root]
|
||||
* @property {string} requestId
|
||||
* @property {boolean} [fastLane]
|
||||
*/
|
||||
/** @typedef {{ fiveHour: number, weekly: number }} Reserve percent of each plan window kept free */
|
||||
/** @typedef {{ lease: null, retryAfter: number, reserve: Reserve, reason?: string, until?: number } | { lease: { id: number, secret: string, title: string, requiredHelper: string }, reserve: Reserve }} ClaimReply */
|
||||
@@ -86,8 +88,13 @@ export const ROUTES = {
|
||||
* @property {Partial<Record<Tier, string>>} models
|
||||
* @property {Reserve} reserve
|
||||
* @property {UsageReading} [usage]
|
||||
* @property {number} slots
|
||||
* @property {number} busy
|
||||
* @property {{ text: string, at: string }} [lastError]
|
||||
*/
|
||||
/** @typedef {{ ok: true, reserve: Reserve }} StatusReply */
|
||||
/** The calls this process runs at once and how many run now, for status reports (set by `work`). */
|
||||
const capacity = { slots: 1, busy: 0 };
|
||||
/**
|
||||
* @typedef {{ kind: "git", path: string, owner: string, repo: string, sha: string, ref?: string }
|
||||
* | { kind: "tarball", path: string, repo: string, sha: string }
|
||||
@@ -1997,7 +2004,7 @@ async function checkReady(cfg, opt = {}) {
|
||||
async function sendStatus(cfg, harness, st, usage) {
|
||||
if (!cfg.server || !cfg.agentToken) return;
|
||||
/** @type {HelperStatus} */
|
||||
const body = { readiness: st.readiness, ...(st.until !== null && { until: new Date(st.until).toISOString() }), ...(st.reason && { reason: redact(st.reason).slice(0, 300) }), harness, models: st.models, reserve: st.reserve, ...(usage && { usage }) };
|
||||
const body = { readiness: st.readiness, ...(st.until !== null && { until: new Date(st.until).toISOString() }), ...(st.reason && { reason: redact(st.reason).slice(0, 300) }), harness, models: st.models, reserve: st.reserve, ...(usage && { usage }), slots: capacity.slots, busy: capacity.busy };
|
||||
const key = JSON.stringify({ ...body, usage: undefined });
|
||||
const prev = readHelperStatus();
|
||||
if (prev.sentKey === key && prev.sentAt !== undefined && Date.now() - prev.sentAt < STATUS_EVERY_MS) return;
|
||||
@@ -2252,7 +2259,7 @@ async function claimOnce(cfg, slot) {
|
||||
const n = mac ? slot ?? pickSlot(slotBase()) : undefined;
|
||||
const root = n === undefined ? undefined : slotRoot(slotBase(), n);
|
||||
/** @type {Claim} */
|
||||
const claim = { protocol: PROTOCOL_VERSION, helperVersion: HELPER_VERSION, harness: adapter.id, harnessVersion: d.version, tiers, efforts: Object.fromEntries(Object.keys(tiers).map((t) => [t, adapter.maxEffort])), ...(cfg.repos && { repos: cfg.repos }), sessions: heldSessions(n), ...(root && { root }) };
|
||||
const claim = { requestId: randomBytes(16).toString("hex"), protocol: PROTOCOL_VERSION, helperVersion: HELPER_VERSION, harness: adapter.id, harnessVersion: d.version, tiers, efforts: Object.fromEntries(Object.keys(tiers).map((t) => [t, adapter.maxEffort])), ...(cfg.repos && { repos: cfg.repos }), sessions: heldSessions(n), ...(root && { root }) };
|
||||
/** @type {ClaimReply} */
|
||||
let reply;
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user