| 1 | /** @jsxImportSource hono/jsx */ |
| 2 | import type { FC } from "hono/jsx"; |
| 3 | import { requireRecentSignIn, type AppContext } from "../auth/principal.js"; |
| 4 | import type { Env } from "../env.js"; |
| 5 | import type { Account } from "../lib/directory.js"; |
| 6 | import { HttpError } from "../lib/util.js"; |
| 7 | import { KCheckbox, KRadio } from "../web/kumo.js"; |
| 8 | import { Form, Time, act, post, prm, type WebApp } from "../web/ui.js"; |
| 9 | import { isProvider, ModelKeys, PROVIDERS, type ModelKeyInfo, type Provider } from "./keys.js"; |
| 10 | import { orgUsageReport, type OrgUsageLine } from "./ledger.js"; |
| 11 | import { DEFAULT_POLICY, MONTHLY_TOKENS_MAX, MONTHLY_TOKENS_MIN, orgPolicy, orgSpend, parsePolicy, savePolicy, spendMonth, type KeysPolicy, type OrgSpend, type StoredPolicy } from "./org-policy.js"; |
| 12 | import { MAX_RUNNING_MAX, MAX_RUNNING_MIN } from "./project.js"; |
| 13 | import { RUNTIMES, type RuntimeId } from "./runtimes.js"; |
| 14 | import { requirePersonSession } from "./tasks.js"; |
| 15 | import { UsageCells } from "./tasks-web.js"; |
| 16 | import { formatTokens } from "./usage.js"; |
| 17 | |
| 18 | /** |
| 19 | * Phase 5b on an organization's Settings tab (owners only): its agent policy, its model keys and what they paid |
| 20 | * for. The REST API has the same under /orgs/{org}/diffinery (agentic/api.ts). |
| 21 | */ |
| 22 | |
| 23 | export interface OrgAgentData { |
| 24 | policy: StoredPolicy; |
| 25 | keys: ModelKeyInfo[]; |
| 26 | usage: { days: number; lines: OrgUsageLine[] }; |
| 27 | spend: OrgSpend[]; |
| 28 | } |
| 29 | |
| 30 | export async function orgAgentData(env: Env, orgId: string): Promise<OrgAgentData> { |
| 31 | const [policy, keys, usage, spend] = await Promise.all([orgPolicy(env, orgId), new ModelKeys(env).list(orgId), orgUsageReport(env, orgId), orgSpend(env, orgId)]); |
| 32 | return { policy, keys, usage, spend }; |
| 33 | } |
| 34 | |
| 35 | const KEYS_LABEL: Record<KeysPolicy, { label: string; description: string }> = { |
| 36 | personal: { label: "Each person's own keys", description: "The default: people run agents with their own keys, as anywhere else." }, |
| 37 | either: { label: "The organization's keys, when it has them", description: "Members' runs use the organization's key for the provider they need, otherwise their own. Outside collaborators always use their own." }, |
| 38 | organization: { label: "Only the organization's keys", description: "Personal keys are never used in the organization's repositories. Only members can run agents here; outside collaborators can't." }, |
| 39 | }; |
| 40 | |
| 41 | export const OrgAgentSettings: FC<{ org: Account; data: OrgAgentData; t: string }> = ({ org, data, t }) => { |
| 42 | const base = `/${org.login}/-/org`; |
| 43 | const p = data.policy; |
| 44 | const keys = new Map(data.keys.map((k) => [k.provider, k])); |
| 45 | const cap = p.memberMonthlyTokens; |
| 46 | return ( |
| 47 | <> |
| 48 | <h2 id="agent-policy">Agents</h2> |
| 49 | <Form action={`${base}/agent-policy`} t={t} class="box"> |
| 50 | <div class="head"> |
| 51 | <h2>Agent policy</h2> |
| 52 | {p.updatedAt ? ( |
| 53 | <span class="muted small"> |
| 54 | Changed by {p.updatedBy ?? "someone"} <Time at={p.updatedAt} /> |
| 55 | </span> |
| 56 | ) : ( |
| 57 | <span class="badge">Defaults</span> |
| 58 | )} |
| 59 | </div> |
| 60 | <div class="body"> |
| 61 | <p class="muted"> |
| 62 | How agents may work in {org.login}'s repositories, and whose key pays. With nothing changed, members use their own keys and everything is allowed. See <a href="/docs/agents/organizations">Agents in organizations</a>. |
| 63 | </p> |
| 64 | <div class="field"> |
| 65 | <label>Whose key pays</label> |
| 66 | <KRadio name="keys" label="Whose key pays" value={p.keys} items={(Object.keys(KEYS_LABEL) as KeysPolicy[]).map((k) => ({ value: k, label: KEYS_LABEL[k].label, description: KEYS_LABEL[k].description }))} /> |
| 67 | <div class="hint">A task keeps whose key pays from when it starts. Every model request checks again that the person is still a member, the repository still the organization's, and the key still allowed; if not, the task stops.</div> |
| 68 | </div> |
| 69 | <div class="field"> |
| 70 | <label>Allowed runtimes</label> |
| 71 | {(Object.keys(RUNTIMES) as RuntimeId[]).map((r) => ( |
| 72 | <div> |
| 73 | <KCheckbox name="runtimes" value={r} checked={p.runtimes.includes(r)} label={RUNTIMES[r].name} /> |
| 74 | </div> |
| 75 | ))} |
| 76 | </div> |
| 77 | <div class="field"> |
| 78 | <label>Allowed providers</label> |
| 79 | {(Object.keys(PROVIDERS) as Provider[]).map((x) => ( |
| 80 | <div> |
| 81 | <KCheckbox name="providers" value={x} checked={p.providers.includes(x)} label={PROVIDERS[x].name} /> |
| 82 | </div> |
| 83 | ))} |
| 84 | <div class="hint">Checked when tasks, reviews, coordinators and terminals start, and on every model request.</div> |
| 85 | </div> |
| 86 | <div class="field"> |
| 87 | <label for="org-max-running">Most tasks at once per repository</label> |
| 88 | <input id="org-max-running" name="max_running" type="number" min={MAX_RUNNING_MIN} max={MAX_RUNNING_MAX} step={1} required style="max-width:8em" value={String(p.maxRunning)} /> |
| 89 | <div class="hint"> |
| 90 | From {MAX_RUNNING_MIN} to {MAX_RUNNING_MAX}. Each project's own "tasks at once" is held to it; more wait in the queue. |
| 91 | </div> |
| 92 | </div> |
| 93 | <div class="field"> |
| 94 | <label>Web terminals</label> |
| 95 | <div> |
| 96 | <KCheckbox name="terminals" checked={p.terminals} label="Allow web terminals" /> |
| 97 | </div> |
| 98 | <div> |
| 99 | <KCheckbox name="terminal_tasks" checked={p.terminalTasks} label="Let terminals run agent tasks" /> |
| 100 | </div> |
| 101 | <div class="hint">Turning terminals off closes none that are open, but no new ones open and no new tasks start in them.</div> |
| 102 | </div> |
| 103 | <div class="field"> |
| 104 | <label>Agent review</label> |
| 105 | <KCheckbox name="review" checked={p.review} label="Allow agent review" /> |
| 106 | <div class="hint">Turning it off stops new reviews; repository admins' settings stay for when it's on again.</div> |
| 107 | </div> |
| 108 | <div class="field"> |
| 109 | <label for="org-monthly">Monthly tokens per person on the organization's keys</label> |
| 110 | <input id="org-monthly" name="member_monthly_tokens" type="number" min={MONTHLY_TOKENS_MIN} max={MONTHLY_TOKENS_MAX} step={1} style="max-width:14em" value={cap === null ? "" : String(cap)} placeholder="No limit" /> |
| 111 | <div class="hint"> |
| 112 | Leave empty for no limit. Each request books what it may use before it goes to the provider; past the limit the person's runs on the organization's keys stop until next month (UTC). Cache reads count a tenth, as in budgets. |
| 113 | </div> |
| 114 | </div> |
| 115 | <button class="btn primary">Save agent policy</button> |
| 116 | </div> |
| 117 | </Form> |
| 118 | |
| 119 | <div class="box" id="model-keys"> |
| 120 | <div class="head"> |
| 121 | <h2>Model keys</h2> |
| 122 | <span class="badge">{data.keys.length ? `${data.keys.length} saved` : "None"}</span> |
| 123 | </div> |
| 124 | <div class="body"> |
| 125 | <p class="muted"> |
| 126 | Keys the organization pays with, when its policy says so. Only owners see or change them, and every owner gets an email when one is added. Diffinery keeps them encrypted, never shows them again, and never puts them in a sandbox, container or terminal: the model proxy adds the key to each request itself. Use dedicated keys with a spending limit. |
| 127 | </p> |
| 128 | {(Object.keys(PROVIDERS) as Provider[]).map((id) => { |
| 129 | const info = PROVIDERS[id]; |
| 130 | const k = keys.get(id); |
| 131 | return ( |
| 132 | <div class="mb"> |
| 133 | <div class="row"> |
| 134 | <b class="grow">{info.name}</b> |
| 135 | {k ? ( |
| 136 | <> |
| 137 | <span class="mono">…{k.hint}</span> |
| 138 | <span class="muted small"> |
| 139 | terms accepted by {k.optedInBy ?? "an owner"} <Time at={k.optedInAt} /> |
| 140 | </span> |
| 141 | <Form action={`${base}/model-keys/${id}/delete`} t={t} class="inline" confirm={`Delete ${org.login}'s ${info.name} key? Running tasks that use it stop getting model access.`}> |
| 142 | <button class="btn sm danger">Delete</button> |
| 143 | </Form> |
| 144 | </> |
| 145 | ) : ( |
| 146 | <span class="muted small">No key</span> |
| 147 | )} |
| 148 | </div> |
| 149 | <details> |
| 150 | <summary class="small">{k ? "Replace" : "Add a key"}</summary> |
| 151 | <Form action={`${base}/model-keys/${id}`} t={t}> |
| 152 | <div class="field"> |
| 153 | <label for={`org-key-${id}`}>{org.login}'s {info.name} API key</label> |
| 154 | <input id={`org-key-${id}`} name="key" type="password" autocomplete="off" required placeholder={id === "anthropic" ? "sk-ant-…" : id === "openrouter" ? "sk-or-…" : "sk-…"} /> |
| 155 | <div class="hint"> |
| 156 | Create one at <a href={info.keysUrl} rel="noopener noreferrer" target="_blank">{info.keysUrl.replace("https://", "")}</a>. |
| 157 | </div> |
| 158 | </div> |
| 159 | <div class="field"> |
| 160 | <KCheckbox |
| 161 | name="accept" |
| 162 | label={ |
| 163 | <> |
| 164 | {org.login} uses {info.name} through Diffinery under its own {info.name} account and its terms ({info.terms.map((x, i) => ( |
| 165 | <> |
| 166 | {i ? ", " : ""} |
| 167 | <a href={x.url} rel="noopener noreferrer" target="_blank"> |
| 168 | {x.label} |
| 169 | </a> |
| 170 | </> |
| 171 | ))} |
| 172 | ), which I accept for it. Usage is billed to its account. Diffinery only provides the ability. |
| 173 | </> |
| 174 | } |
| 175 | /> |
| 176 | </div> |
| 177 | <button class="btn primary">{k ? "Replace key" : "Save key"}</button> |
| 178 | </Form> |
| 179 | </details> |
| 180 | </div> |
| 181 | ); |
| 182 | })} |
| 183 | </div> |
| 184 | </div> |
| 185 | |
| 186 | <div class="box" id="org-usage"> |
| 187 | <div class="head"> |
| 188 | <h2>Paid with the organization's keys</h2> |
| 189 | </div> |
| 190 | <div class="body"> |
| 191 | <h3>This month ({spendMonth()}, UTC)</h3> |
| 192 | {data.spend.length ? ( |
| 193 | <div class="xscroll"> |
| 194 | <table class="tbl"> |
| 195 | <thead> |
| 196 | <tr> |
| 197 | <th>Person</th> |
| 198 | <th class="r">Tokens</th> |
| 199 | <th class="r">Allowance</th> |
| 200 | </tr> |
| 201 | </thead> |
| 202 | <tbody> |
| 203 | {data.spend.map((x) => ( |
| 204 | <tr> |
| 205 | <td>{x.login ? <a href={`/${x.login}`}>{x.login}</a> : <span class="muted">Deleted account</span>}</td> |
| 206 | <td class="r">{formatTokens(x.tokens)}</td> |
| 207 | <td class="r">{cap === null ? "No limit" : `${Math.min(100, Math.round((x.tokens / cap) * 100))}% of ${formatTokens(cap)}`}</td> |
| 208 | </tr> |
| 209 | ))} |
| 210 | </tbody> |
| 211 | </table> |
| 212 | </div> |
| 213 | ) : ( |
| 214 | <p class="muted">Nobody has used the organization's keys this month.</p> |
| 215 | )} |
| 216 | <h3 class="mt">Runs in the last {data.usage.days} days</h3> |
| 217 | {data.usage.lines.length ? ( |
| 218 | <div class="xscroll"> |
| 219 | <table class="tbl"> |
| 220 | <thead> |
| 221 | <tr> |
| 222 | <th>Repository</th> |
| 223 | <th>Person</th> |
| 224 | <th>For</th> |
| 225 | <th class="r">Runs</th> |
| 226 | <th class="r">Requests</th> |
| 227 | <th class="r">Input</th> |
| 228 | <th class="r">Output</th> |
| 229 | <th class="r">Cache read / write</th> |
| 230 | <th class="r">Cost</th> |
| 231 | </tr> |
| 232 | </thead> |
| 233 | <tbody> |
| 234 | {data.usage.lines.map((l) => ( |
| 235 | <tr> |
| 236 | <td>{l.repository ? <a href={`/${l.repository}/tasks`}>{l.repository}</a> : <span class="muted">Unknown</span>}</td> |
| 237 | <td>{l.person ?? <span class="muted">Deleted account</span>}</td> |
| 238 | <td>{l.kind === "task" ? "Tasks" : l.kind === "review" ? "Agent reviews" : "Coordinator"}</td> |
| 239 | <td class="r">{l.runs}</td> |
| 240 | <UsageCells u={l} /> |
| 241 | </tr> |
| 242 | ))} |
| 243 | </tbody> |
| 244 | </table> |
| 245 | </div> |
| 246 | ) : ( |
| 247 | <p class="muted">No runs used the organization's keys in the last {data.usage.days} days.</p> |
| 248 | )} |
| 249 | <p class="muted small mt"> |
| 250 | Diffinery counts each request from the provider's answer. Tokens this month are weighted as budgets weigh them (a cache read counts a tenth). Also at <code>GET /api/v3/orgs/{org.login}/diffinery/model-usage</code>. |
| 251 | </p> |
| 252 | </div> |
| 253 | </div> |
| 254 | </> |
| 255 | ); |
| 256 | }; |
| 257 | |
| 258 | // ---------------------------------------------------------------- posts |
| 259 | |
| 260 | /** An owner of the organization (or a site admin, audited as themselves) in a browser session. */ |
| 261 | async function orgOwner(c: AppContext) { |
| 262 | const me = requirePersonSession(c); |
| 263 | const dir = c.get("dir"); |
| 264 | const org = await dir.accountByLogin(prm(c, "owner")); |
| 265 | if (!org || org.kind !== "org" || org.status === "disabled") throw new HttpError(404, "not found"); |
| 266 | const role = await dir.orgRole(org.id, me.id); |
| 267 | if (role !== "owner" && !me.site_admin) throw new HttpError(403, "organization owners only"); |
| 268 | return { me, org, dir, asSiteAdmin: role !== "owner", back: `/${org.login}?tab=settings` }; |
| 269 | } |
| 270 | |
| 271 | export function registerOrgAgents(web: WebApp): void { |
| 272 | post(web, "/:owner/-/org/agent-policy", async (c, f) => { |
| 273 | const { me, org, dir, back } = await orgOwner(c); |
| 274 | return act( |
| 275 | c, |
| 276 | `${back}#agent-policy`, |
| 277 | async () => { |
| 278 | const monthly = f.s("member_monthly_tokens").trim(); |
| 279 | const p = parsePolicy( |
| 280 | { |
| 281 | keys: f.s("keys") || DEFAULT_POLICY.keys, |
| 282 | runtimes: f.all("runtimes"), |
| 283 | providers: f.all("providers"), |
| 284 | max_running: f.s("max_running"), |
| 285 | terminals: f.all("terminals").length > 0, |
| 286 | terminal_tasks: f.all("terminal_tasks").length > 0, |
| 287 | review: f.all("review").length > 0, |
| 288 | member_monthly_tokens: monthly === "" ? null : monthly, |
| 289 | }, |
| 290 | await orgPolicy(c.env, org.id), |
| 291 | ); |
| 292 | await savePolicy(c.env, dir, org, me, p, (x) => c.executionCtx.waitUntil(x)); |
| 293 | }, |
| 294 | "Agent policy saved.", |
| 295 | ); |
| 296 | }); |
| 297 | |
| 298 | post(web, "/:owner/-/org/model-keys/:provider", async (c, f) => { |
| 299 | const { me, org, dir, asSiteAdmin, back } = await orgOwner(c); |
| 300 | const provider = prm(c, "provider"); |
| 301 | if (!isProvider(provider)) throw new HttpError(404, "not found"); |
| 302 | return act( |
| 303 | c, |
| 304 | `${back}#model-keys`, |
| 305 | async () => { |
| 306 | requireRecentSignIn(c, back); |
| 307 | const k = await new ModelKeys(c.env).set(org, provider, f.s("key"), f.all("accept").length > 0, me); |
| 308 | c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.model_key.set", target: org.login, detail: { provider, hint: k.hint, opted_in_at: k.optedInAt, ...(asSiteAdmin ? { site_admin: true } : {}) } })); |
| 309 | }, |
| 310 | `${org.login}'s ${PROVIDERS[provider].name} key saved.`, |
| 311 | ); |
| 312 | }); |
| 313 | |
| 314 | post(web, "/:owner/-/org/model-keys/:provider/delete", async (c) => { |
| 315 | const { me, org, dir, asSiteAdmin, back } = await orgOwner(c); |
| 316 | const provider = prm(c, "provider"); |
| 317 | if (!isProvider(provider)) throw new HttpError(404, "not found"); |
| 318 | return act( |
| 319 | c, |
| 320 | `${back}#model-keys`, |
| 321 | async () => { |
| 322 | requireRecentSignIn(c, back); |
| 323 | await new ModelKeys(c.env).delete(org.id, provider); |
| 324 | c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: "org.model_key.delete", target: org.login, detail: { provider, ...(asSiteAdmin ? { site_admin: true } : {}) } })); |
| 325 | }, |
| 326 | `${org.login}'s ${PROVIDERS[provider].name} key deleted.`, |
| 327 | ); |
| 328 | }); |
| 329 | } |