67 lines
2.3 KiB
TypeScript
67 lines
2.3 KiB
TypeScript
import type { FastifyInstance } from "fastify";
|
|
import type { AppConfig } from "../config.js";
|
|
import { loadSettings, saveSettings, type Settings } from "../settings/settings-store.js";
|
|
import { listWorkspaces, type ListModelsFn } from "./meta.js";
|
|
import { getPrincipal } from "../auth/auth.js";
|
|
import type { PrincipalContext } from "../auth/principal.js";
|
|
|
|
/** Merge stored settings over env/first-workspace defaults. */
|
|
export function effectiveSettings(cfg: AppConfig, stored: Settings): Settings {
|
|
const workspaces = listWorkspaces(cfg.harnessDir);
|
|
return {
|
|
workspace: stored.workspace ?? (workspaces[0]?.name),
|
|
provider: stored.provider ?? cfg.defaults.provider,
|
|
model: stored.model ?? cfg.defaults.model,
|
|
thinking: stored.thinking ?? cfg.defaults.thinking,
|
|
};
|
|
}
|
|
|
|
export function settingsRoutes(
|
|
app: FastifyInstance,
|
|
deps: {
|
|
cfg: AppConfig; listModels: ListModelsFn;
|
|
getSettings: (principal: PrincipalContext) => Promise<Settings>;
|
|
saveSettings: (principal: PrincipalContext, settings: Settings) => Promise<void>;
|
|
},
|
|
): void {
|
|
app.get("/settings", async (req, reply) => {
|
|
try {
|
|
return await deps.getSettings(getPrincipal(req));
|
|
} catch {
|
|
return reply.code(503).send({ error: "settings storage is unavailable" });
|
|
}
|
|
});
|
|
|
|
app.put("/settings", async (req, reply) => {
|
|
const b = (req.body ?? {}) as Settings;
|
|
if (b.model) {
|
|
let available: { provider: string; id: string }[] = [];
|
|
try {
|
|
available = await deps.listModels();
|
|
} catch {
|
|
available = [];
|
|
}
|
|
// Only validate when Pi gave us a non-empty list; otherwise allow (degraded).
|
|
if (available.length > 0 && !available.some(
|
|
(candidate) => candidate.provider === b.provider && candidate.id === b.model,
|
|
)) {
|
|
return reply.code(400).send({
|
|
error: `Unknown model: ${b.provider ?? "unknown"}/${b.model}`,
|
|
});
|
|
}
|
|
}
|
|
const next: Settings = {
|
|
workspace: b.workspace,
|
|
provider: b.provider,
|
|
model: b.model,
|
|
thinking: b.thinking,
|
|
};
|
|
try {
|
|
await deps.saveSettings(getPrincipal(req), next);
|
|
return effectiveSettings(deps.cfg, next);
|
|
} catch {
|
|
return reply.code(503).send({ error: "settings storage is unavailable" });
|
|
}
|
|
});
|
|
}
|