Files
loki/scripts/write-tenant-engines.ts
CatoandClaude Fable 5.1 9c84c929e4 feat(engines): your own key builds when you say so; welcome builds, then the plan's, then your own; capacity you can read (#1347)
* feat(settings): your own key builds, when you say so — a key marked for building reaches your private builder

Track 1, PR 6 of docs/architecture/private-builders.md.

- user_model_keys.for_building (migration 0123), off by default; one
  switch per key in Settings → AI, offered only on keys that can drive an
  agent CLI (config/build-engines.ts: Anthropic → ANTHROPIC_API_KEY for
  Claude Code, OpenAI → Codex, xAI → Grok, Google → Gemini CLI) and only
  to an account with a builder on the cloud.
- scripts/write-tenant-engines.ts (root on the box, from the reconcile
  timer) opens the marked keys with the app's sealing secret and writes
  them to /etc/loki/runners/<short>.env; a unit whose file changed is
  drain-restarted, so the key reaches its next agent without ending a
  session mid-task. No route ever returns an opened key.
- Records: changelog {#your-engine}; roadmap milestones ticked.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* fix(settings): the building switch sits in one row with its sentence

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* feat(engines): welcome builds, then the plan's, then your own — and capacity you can read

Track 2 (2.1, 2.2, 2.5) and Track 4.1 of docs/master-plan-2026-10.md.

- users.build_engine (migration 0124): "own" by default — the person's
  sign-in or a key marked for building, never counted — or "loki": Loki's
  key within WELCOME_BUILDS (3, config/welcome-changes.ts) and the plan's
  PLAN_LIMITS.buildsMonthly (10 / 40 / 100). Every run records which
  engine paid for it (payload.engine); welcome and plan builds are counted
  from that marker. A dispatch past the last build is refused with the way
  forward (code engine-exhausted), and the kickoff screen shows it with
  one tap to Settings. Loki's welcome spending stops for everyone at
  WELCOME_MONTHLY_CAP_CHF (20), at CHF_PER_USD, a hand-set rate.
- The box writes Loki's key (LOKI_BUILD_ENGINE_ANTHROPIC_KEY from the
  app's env) into a tenant's unit only while they chose Loki's engine and
  have builds left; otherwise their own marked keys.
- Settings → AI: "Your engine for building", one Segmented choice with the
  numbers; /api/settings/build-engine. The kickoff's no-builder copy says
  the operator switches a private builder on per account.
- System → Capacity: how long work waited for a builder in the last day
  per channel (median, worst), this month's builds, tokens and cost per
  account, and welcome spend against its cap.
- /pricing and the whitepaper (0.3.3) state the builds a month on Loki's
  engine and the rule. Records: changelog {#welcome-changes}
  {#capacity-card}; roadmap milestones ticked.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

* style(engines): format resolve.ts the way prettier wants it

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-20 12:55:35 +02:00

69 lines
2.9 KiB
TypeScript

/**
* Write each private builder's engine keys into its unit env file.
*
* Runs ON the box as root (reconcile-tenants.sh, every minute), with the
* database and BYOK_SEAL_SECRET from the app's env — the two things a tenant
* unit never holds. For every account with users.private_builder it opens
* the keys that account marked "also for building" (user_model_keys
* .for_building, Settings → Your engine) and writes them as the agent CLIs'
* own variables (config/build-engines.ts) to /etc/loki/runners/<short>.env,
* root-owned, mode 0600, which systemd reads into that tenant's unit and
* the agent environment allowlist lets through (agent-env.ts). Nothing else
* goes into that file. Prints the short id of every tenant whose file
* changed, one per line, so the caller can drain-restart just those units.
*
* tsx scripts/write-tenant-engines.ts [--dir /etc/loki/runners]
*/
import fs from "fs";
import path from "path";
import { db } from "@/db";
import { users } from "@/db/schema";
import { eq } from "drizzle-orm";
import { listBuildEngineKeys } from "@/db/queries/user-model-keys";
import { tenantShortId } from "@/lib/agent-execution/box-workspace-path";
import { renderEnvFile } from "@/lib/tenant-engines-env";
import { resolveRunEngine } from "@/lib/build-engine/resolve";
import { LOKI_BUILD_ENGINE_KEY_VAR } from "@/config/welcome-changes";
function readArgs(argv: string[]): { dir: string } {
const i = argv.indexOf("--dir");
return { dir: i >= 0 && argv[i + 1] ? argv[i + 1] : "/etc/loki/runners" };
}
async function main(): Promise<void> {
const { dir } = readArgs(process.argv.slice(2));
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
const tenants = await db
.select({ id: users.id })
.from(users)
.where(eq(users.privateBuilder, true));
// Loki's own key, for a tenant who chose Loki's engine and still has builds
// on it (lib/build-engine/resolve.ts). Set in the app's env on the box; a
// server without it has no Loki engine, and the settings screen says so.
const lokiKey = process.env[LOKI_BUILD_ENGINE_KEY_VAR]?.trim() || null;
for (const t of tenants) {
const short = tenantShortId(t.id);
const file = path.join(dir, `${short}.env`);
const engine = await resolveRunEngine(t.id);
const keys =
engine.choice === "loki"
? engine.ok && lokiKey
? [{ env: "ANTHROPIC_API_KEY", value: lokiKey }]
: []
: await listBuildEngineKeys(t.id);
const next = renderEnvFile(keys);
const prev = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null;
if (prev === next) continue;
fs.writeFileSync(`${file}.tmp`, next, { mode: 0o600 });
fs.renameSync(`${file}.tmp`, file);
fs.chmodSync(file, 0o600);
console.log(short);
}
process.exit(0);
}
main().catch((e) => {
console.error("[tenant-engines] failed:", e instanceof Error ? e.message : e);
process.exit(1);
});