Public: anyone can read this; the crew can change it.
Connect any AI: one list of connections with presets, Test before save, and who pays (#16428) #16432
Check · Review · Land · Live done — Landed and live in production.
talk-connections-a → main 0 commits 3 threads · 3 unresolved
docs/features/blocked-by.md +1 −1
| @@ -36,7 +36,7 @@ A button on a page posts the ask as a form to the page's own route, with the act | ||
| 36 | 36 | A reader who cannot change it is offered one action, and there are two, by who holds the control: |
| 37 | 37 | |
| 38 | 38 | - **The host of this forge** (a name its gate has not opened): `POST /api/v1/reach/asks`, `docs/features/ask-to-reach.md`. |
| 39 | - **An admin of this forge, or of one repository**: `POST /api/v1/asks/admin { want, subject }` (`src/actions/ask_admin.ts`). `want` is one of a fixed list (`WANTS`, `src/actions/blocked_words.ts`): a model grant, a model account, a spend ceiling, a model key, a private destination, an email verified, membership, the telemetry grant, an agent, a repository's crew. Each names the exact control, with the page's own anchor on the field (`/settings/accounts/bob#f-grant`, `/settings/crew#crew-key`). | |
| 39 | - **An admin of this forge, or of one repository**: `POST /api/v1/asks/admin { want, subject }` (`src/actions/ask_admin.ts`). `want` is one of a fixed list (`WANTS`, `src/actions/blocked_words.ts`): a model grant, a model account, a spend ceiling, a model key, a private destination, an email verified, membership, the telemetry grant, an agent, a host for a person's own model connection, a repository's crew. Each names the exact control, with the page's own anchor on the field (`/settings/accounts/bob#f-grant`, `/settings/crew#crew-key`). | |
| 40 | 40 | |
| 41 | 41 | What happens when a person presses the button: |
| 42 | 42 |
docs/features/connections.md added +72
| @@ -0,0 +1,72 @@ | ||
| 1 | --- | |
| 2 | topic: Bring your own AI | |
| 3 | row: Connections | |
| 4 | --- | |
| 5 | ||
| 6 | # Connections | |
| 7 | ||
| 8 | Settings, Connect your AI (`/settings/model`) lists every model backend you can use as one list: | |
| 9 | your own connections first, then the forge's. Each row says its protocol (Anthropic or | |
| 10 | OpenAI-compatible), its address, whose it is, who pays, how many models its last test listed, and that | |
| 11 | test's words, with a status badge (working, not working, not tested yet), Test and Remove. | |
| 12 | ||
| 13 | **Add a connection** takes a kind (OpenRouter, OpenAI, Anthropic, LiteLLM, Ollama, vLLM, LM Studio, or | |
| 14 | another OpenAI-compatible server), a name, a base URL (empty takes the kind's own) and a key. The key | |
| 15 | is sealed on the forge, never shown again, and sent only to the address it was saved for. | |
| 16 | ||
| 17 | Saving tests first, and keeps nothing that does not answer: | |
| 18 | ||
| 19 | 1. `GET <base>/models` lists the models (prices too, where the server gives them). | |
| 20 | 2. One model is asked for a one-token reply. | |
| 21 | 3. It is asked to call one tool, answering in at most 32 tokens; a model that does not is saved | |
| 22 | with words saying Talk needs one that does. | |
| 23 | ||
| 24 | On the forge's own network the probe's prompt is long (about 3,000 tokens), as Talk's is: a server | |
| 25 | that reads under half of it (Ollama's default context keeps 2,048 tokens of a prompt) is said, with | |
| 26 | the fix (a context of 32,768 tokens or more; Ollama: `OLLAMA_CONTEXT_LENGTH=32768`), and nothing is | |
| 27 | saved. A server on the internet is asked with a short prompt, since its tokens cost money. | |
| 28 | ||
| 29 | **Reasoning effort** (none, minimal, low, medium, high, or not asked) is kept with the connection and | |
| 30 | sent as `reasoning_effort` with its test's calls and its Talk turns. A small local model is often | |
| 31 | fastest at low. | |
| 32 | ||
| 33 | Each call has 10 seconds. What the test sent and heard is not kept: only the models listed and the | |
| 34 | result's words. | |
| 35 | ||
| 36 | A person's tests run one at a time: while one of theirs runs, another is refused at once ("One of your tests is still running"), and the next goes as soon as it ends. The forge's own connections are tested again only by an admin. | |
| 37 | ||
| 38 | ## Whose it is, and who pays | |
| 39 | ||
| 40 | Whose a connection is, is stored with it when it is added and never changes: granting the forge's own to an admin's repositories keeps it the forge's. | |
| 41 | ||
| 42 | - **Yours**: spends your key, never the forge's credit. Its address must be public https, and the | |
| 43 | forge reaches it only through its outbound guard (`src/kernel/outbound.ts`): the name is resolved and | |
| 44 | refused if it points at a private, loopback or LAN address, the vetted address is pinned for the | |
| 45 | call, and a redirect is never followed. You may keep eight. | |
| 46 | A forge that runs in a cell reaches the internet only through its egress gate, so a person's own | |
| 47 | connection may be on the hosts its `forge.json` `egress` declares for them: openrouter.ai, | |
| 48 | api.openai.com and api.anthropic.com (the add form names them). Another host is refused by the | |
| 49 | gate before anything is saved, and the form says so with the ask to allow it, which an admin | |
| 50 | answers by adding the host to `forge.json` `egress`. | |
| 51 | - **The forge's**: added by an admin (the "The forge's own" box), and following today's credit, grants | |
| 52 | and budgets unchanged. Only these may be on a private address or plain http: a model on the forge's | |
| 53 | own machine or network, such as Ollama at `http://…:11434/v1`. A redirect is still never followed. | |
| 54 | ||
| 55 | The forge's own credential (the row "The forge's own") is listed and cannot be removed here. | |
| 56 | ||
| 57 | ## Removing | |
| 58 | ||
| 59 | Remove opens the confirm page, which asks for the connection's name typed exactly. Its sealed key is | |
| 60 | deleted, and its grants go with it. | |
| 61 | ||
| 62 | ## In the terminal | |
| 63 | ||
| 64 | The Model budget screen lists the same connections. `n` adds one (kind, name, base URL, then the key | |
| 65 | typed masked; an admin ends the key with `!` to make it the forge's own), `t` tests one again by name, | |
| 66 | and `x` removes one with its name typed exactly. | |
| 67 | ||
| 68 | ## What is unchanged | |
| 69 | ||
| 70 | Every subscription from before connections is the Anthropic connection it was: the migration only adds | |
| 71 | columns, and a crew run still picks only Anthropic accounts. Choosing a connection's model in Talk is | |
| 72 | the next step. |
forge.json +2
| @@ -1,6 +1,8 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "egress": [ |
| 3 | 3 | "api.anthropic.com", |
| 4 | "api.openai.com", | |
| 5 | "openrouter.ai", | |
| 4 | 6 | "api.github.com", |
| 5 | 7 | "github.com", |
| 6 | 8 | "api.stripe.com", |
src/actions/ask_admin.ts +5
| @@ -67,6 +67,11 @@ function subjectOf(app: App, asker: User, want: Want, raw: string): Result<{ sub | ||
| 67 | 67 | const kind = wantDef(want).subject; |
| 68 | 68 | const text = raw.replace(/[^\x20-\x7e]/g, "").trim().slice(0, 300); |
| 69 | 69 | if (kind === "none") return ok({ subject: "", repoId: null }); |
| 70 | // A host name (a model connection's, `model_host`): dotted, lower case, nothing else. | |
| 71 | if (kind === "host") { | |
| 72 | const host = text.toLowerCase(); | |
| 73 | return /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/.test(host) ? ok({ subject: host, repoId: null }) : err("no_subject"); | |
| 74 | } | |
| 70 | 75 | if (kind === "account") { |
| 71 | 76 | const who = getUserByName(app.db, text); |
| 72 | 77 | return who === undefined || who.removedAt !== null ? err("no_subject") : ok({ subject: who.username, repoId: null }); |
src/actions/blocked_words.ts +18 −1
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | import type { App } from "../app.ts"; |
| 17 | 17 | import { canAdmin, getRepo, type Repo } from "../core/repos.ts"; |
| 18 | 18 | import type { User } from "../core/users.ts"; |
| 19 | import { reachableHostsSentence } from "../core/connections.ts"; | |
| 19 | 20 | import { blockedBy, type Blocked } from "../kernel/blocked.ts"; |
| 20 | 21 | |
| 21 | 22 | /** Where an ask to whoever can is sent, and where a person reads how theirs stand. */ |
| @@ -30,7 +31,7 @@ interface WantDef { | ||
| 30 | 31 | * What the subject is: nothing, an account's name, or `owner/name` (with a detail after a |
| 31 | 32 | * space). |
| 32 | 33 | */ |
| 33 | readonly subject: "none" | "account" | "repo"; | |
| 34 | readonly subject: "none" | "account" | "repo" | "host"; | |
| 34 | 35 | /** The exact control, for one who can change it. */ |
| 35 | 36 | readonly control: (subject: string) => { readonly href: string; readonly label: string }; |
| 36 | 37 | /** What they can do about it, after "can". */ |
| @@ -145,6 +146,14 @@ export const WANTS = { | ||
| 145 | 146 | ask: "Ask an admin to add an agent", |
| 146 | 147 | asks: () => "asks for an agent: this forge has none, so there is no crew", |
| 147 | 148 | }, |
| 149 | model_host: { | |
| 150 | audience: "forge", | |
| 151 | subject: "host", | |
| 152 | control: (s) => ({ href: "/settings/model#connections", label: `Allow ${s} in this forge's forge.json egress` }), | |
| 153 | can: "allow it", | |
| 154 | ask: "Ask an admin to allow it", | |
| 155 | asks: (s) => `asks for this forge to reach ${s} for their own model connection`, | |
| 156 | }, | |
| 148 | 157 | repo_crew: { |
| 149 | 158 | audience: "repo", |
| 150 | 159 | subject: "repo", |
| @@ -199,6 +208,14 @@ export function wayTo(app: App, reader: User | undefined, want: Want, says: stri | ||
| 199 | 208 | }); |
| 200 | 209 | } |
| 201 | 210 | |
| 211 | /** | |
| 212 | * A person's own model connection on a host the forge's egress gate refuses: the hosts it can reach, | |
| 213 | * and the ask to allow this one (`core/connections.ts` `OWN_HOSTS`). | |
| 214 | */ | |
| 215 | export function modelHostBlocked(app: App, reader: User | undefined, host: string): Blocked { | |
| 216 | return wayTo(app, reader, "model_host", reachableHostsSentence(host), host); | |
| 217 | } | |
| 218 | ||
| 202 | 219 | /** A forge with no agent has no crew to hand work to: an admin adds one on Settings, Crew. */ |
| 203 | 220 | export function noAgentsBlocked(app: App, reader: User | undefined): Blocked { |
| 204 | 221 | return wayTo(app, reader, "agents", "No agents exist on this forge yet."); |
src/actions/connections.ts added +365
| @@ -0,0 +1,365 @@ | ||
| 1 | /** | |
| 2 | * Testing a connection (Connect your AI): list its models, ask for one token, and ask it to call one | |
| 3 | * tool, each bounded in time and tokens. Nothing a test sends or hears is kept but its words and the | |
| 4 | * models listed. A person's own connection is reached only through the outbound guard (public https, | |
| 5 | * no redirects, the address pinned); the forge's own may be on a private address, and is still | |
| 6 | * never followed to a redirect: a key goes only to the host it was saved for. | |
| 7 | */ | |
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { | |
| 11 | parseConnectionBase, | |
| 12 | connectionFor, | |
| 13 | connectionKey, | |
| 14 | recordTest, | |
| 15 | saveConnection, | |
| 16 | reachableHostsSentence, | |
| 17 | type Connection, | |
| 18 | type ConnectionError, | |
| 19 | type Effort, | |
| 20 | type ConnectionModel, | |
| 21 | type Protocol, | |
| 22 | } from "../core/connections.ts"; | |
| 23 | import type { User } from "../core/users.ts"; | |
| 24 | import { GateRefusedError, outboundFetch, type OutboundOptions } from "../kernel/outbound.ts"; | |
| 25 | import { cutLine } from "../crew/openai_runner.ts"; | |
| 26 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 27 | ||
| 28 | /** Each call of a test gets this long. */ | |
| 29 | export const TEST_CALL_MS = 10_000; | |
| 30 | /** The tool probe may answer with at most this many tokens; the ping with one. */ | |
| 31 | export const PROBE_TOKENS = 32; | |
| 32 | ||
| 33 | export interface TestInput { | |
| 34 | readonly protocol: Protocol; | |
| 35 | readonly base: string; | |
| 36 | readonly key: string; | |
| 37 | /** The forge's own, which may be on a private address. */ | |
| 38 | readonly privateOk: boolean; | |
| 39 | /** The reasoning effort to ask for (`reasoning_effort`); "" or absent asks none. */ | |
| 40 | readonly effort?: Effort | "" | undefined; | |
| 41 | } | |
| 42 | ||
| 43 | /** | |
| 44 | * How long the tool probe's prompt is on a server on the forge's own network, in characters: about | |
| 45 | * 3,000 tokens, past the 2,048 Ollama keeps of its default 4,096-token context, so a server that | |
| 46 | * would cut Talk's prompt cuts this one too and the test says so. A server on the internet is | |
| 47 | * asked with a short prompt, since its tokens cost money. | |
| 48 | */ | |
| 49 | export const PROBE_PAD_CHARS = 12_000; | |
| 50 | ||
| 51 | export interface TestResult { | |
| 52 | readonly working: boolean; | |
| 53 | /** "412 models listed · one-token reply in 0.6 s · called a tool", or what went wrong. */ | |
| 54 | readonly said: string; | |
| 55 | readonly models: readonly ConnectionModel[]; | |
| 56 | readonly tools: boolean; | |
| 57 | /** The host the forge's egress gate refused: a person's own connection on an undeclared host. */ | |
| 58 | readonly refusedHost?: string; | |
| 59 | } | |
| 60 | ||
| 61 | /** What a call may be refused or fail with, as words for the row. */ | |
| 62 | const why = (e: unknown): string => | |
| 63 | (e instanceof Error ? e.message : String(e)).slice(0, 160); | |
| 64 | ||
| 65 | /** One call, bounded, never followed to a redirect, through the guard unless the forge's own on a private address. */ | |
| 66 | async function call( | |
| 67 | input: TestInput, | |
| 68 | path: string, | |
| 69 | init: RequestInit, | |
| 70 | guard: OutboundOptions, | |
| 71 | ): Promise<Response> { | |
| 72 | const url = `${input.base}${path}`; | |
| 73 | const signal = AbortSignal.timeout(TEST_CALL_MS); | |
| 74 | // The forge's own may be on its private network (an admin added it so); anyone's own is guarded. | |
| 75 | const res = input.privateOk | |
| 76 | ? await fetch(url, { ...init, redirect: "manual", signal }) | |
| 77 | : await outboundFetch(url, { ...init, redirect: "manual", signal }, guard); | |
| 78 | if (res.status >= 300 && res.status < 400) | |
| 79 | throw new Error("it answered with a redirect; the key was not sent on"); | |
| 80 | return res; | |
| 81 | } | |
| 82 | ||
| 83 | const headersFor = (input: TestInput): Record<string, string> => | |
| 84 | input.protocol === "anthropic" | |
| 85 | ? { | |
| 86 | "content-type": "application/json", | |
| 87 | "anthropic-version": "2023-06-01", | |
| 88 | ...(input.key === "" ? {} : { "x-api-key": input.key }), | |
| 89 | } | |
| 90 | : { | |
| 91 | "content-type": "application/json", | |
| 92 | ...(input.key === "" ? {} : { authorization: `Bearer ${input.key}` }), | |
| 93 | }; | |
| 94 | ||
| 95 | /** The provider's own words for a refusal, or its status. */ | |
| 96 | async function refusal(res: Response): Promise<string> { | |
| 97 | const text = (await res.text().catch(() => "")).slice(0, 2000); | |
| 98 | try { | |
| 99 | const said = ( | |
| 100 | JSON.parse(text) as { error?: { message?: unknown } | string } | |
| 101 | ).error; | |
| 102 | const words = | |
| 103 | typeof said === "string" | |
| 104 | ? said | |
| 105 | : typeof said?.message === "string" | |
| 106 | ? said.message | |
| 107 | : ""; | |
| 108 | if (words !== "") return `${String(res.status)}: ${words.slice(0, 160)}`; | |
| 109 | } catch { | |
| 110 | // Not JSON: the status says it. | |
| 111 | } | |
| 112 | return `it answered ${String(res.status)}`; | |
| 113 | } | |
| 114 | ||
| 115 | /** A price per token, as OpenRouter's listing gives it, per million. */ | |
| 116 | const perMillion = (v: unknown): number | undefined => { | |
| 117 | const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN; | |
| 118 | return Number.isFinite(n) && n >= 0 | |
| 119 | ? Math.round(n * 1e6 * 1000) / 1000 | |
| 120 | : undefined; | |
| 121 | }; | |
| 122 | ||
| 123 | /** Test a connection: its models, a one-token reply, and one tool call. Never throws. */ | |
| 124 | export async function testConnection( | |
| 125 | input: TestInput, | |
| 126 | guard: OutboundOptions = {}, | |
| 127 | ): Promise<TestResult> { | |
| 128 | const openai = input.protocol === "openai"; | |
| 129 | let models: ConnectionModel[] = []; | |
| 130 | try { | |
| 131 | const listed = await call( | |
| 132 | input, | |
| 133 | openai ? "/models" : "/v1/models", | |
| 134 | { headers: headersFor(input) }, | |
| 135 | guard, | |
| 136 | ); | |
| 137 | if (!listed.ok) | |
| 138 | return { | |
| 139 | working: false, | |
| 140 | said: `The models were not listed: ${await refusal(listed)}.`, | |
| 141 | models: [], | |
| 142 | tools: false, | |
| 143 | }; | |
| 144 | const body = (await listed.json()) as { | |
| 145 | data?: { | |
| 146 | id?: unknown; | |
| 147 | pricing?: { prompt?: unknown; completion?: unknown }; | |
| 148 | }[]; | |
| 149 | }; | |
| 150 | models = (body.data ?? []).flatMap((m) => { | |
| 151 | if (typeof m.id !== "string" || m.id === "") return []; | |
| 152 | const inUsd = perMillion(m.pricing?.prompt); | |
| 153 | const outUsd = perMillion(m.pricing?.completion); | |
| 154 | return [ | |
| 155 | { | |
| 156 | id: m.id, | |
| 157 | ...(inUsd === undefined ? {} : { inUsd }), | |
| 158 | ...(outUsd === undefined ? {} : { outUsd }), | |
| 159 | }, | |
| 160 | ]; | |
| 161 | }); | |
| 162 | } catch (e) { | |
| 163 | // The forge's own gate said no, before the server was asked: the person is told which hosts it reaches. | |
| 164 | if (e instanceof GateRefusedError) return { working: false, said: reachableHostsSentence(e.host), models: [], tools: false, refusedHost: e.host }; | |
| 165 | return { | |
| 166 | working: false, | |
| 167 | said: `It did not answer: ${why(e)}.`, | |
| 168 | models: [], | |
| 169 | tools: false, | |
| 170 | }; | |
| 171 | } | |
| 172 | if (models.length === 0) | |
| 173 | return { | |
| 174 | working: false, | |
| 175 | said: "It answered, but listed no models.", | |
| 176 | models, | |
| 177 | tools: false, | |
| 178 | }; | |
| 179 | const model = models[0]!.id; | |
| 180 | const effort = openai && input.effort !== undefined && input.effort !== "" ? { reasoning_effort: input.effort } : {}; | |
| 181 | const ask = (extra: Record<string, unknown>, maxTokens: number) => | |
| 182 | call( | |
| 183 | input, | |
| 184 | openai ? "/chat/completions" : "/v1/messages", | |
| 185 | { | |
| 186 | method: "POST", | |
| 187 | headers: headersFor(input), | |
| 188 | body: JSON.stringify({ model, max_tokens: maxTokens, ...effort, ...extra }), | |
| 189 | }, | |
| 190 | guard, | |
| 191 | ); | |
| 192 | const started = performance.now(); | |
| 193 | try { | |
| 194 | const ping = await ask( | |
| 195 | { messages: [{ role: "user", content: "Reply with ok." }] }, | |
| 196 | 1, | |
| 197 | ); | |
| 198 | if (!ping.ok) | |
| 199 | return { | |
| 200 | working: false, | |
| 201 | said: `${String(models.length)} models listed, but ${model} did not reply: ${await refusal(ping)}.`, | |
| 202 | models, | |
| 203 | tools: false, | |
| 204 | }; | |
| 205 | await ping.body?.cancel(); | |
| 206 | } catch (e) { | |
| 207 | return { | |
| 208 | working: false, | |
| 209 | said: `${String(models.length)} models listed, but ${model} did not reply: ${why(e)}.`, | |
| 210 | models, | |
| 211 | tools: false, | |
| 212 | }; | |
| 213 | } | |
| 214 | const seconds = ((performance.now() - started) / 1000).toFixed(1); | |
| 215 | let tools = false; | |
| 216 | let cut: string | undefined; | |
| 217 | // On the forge's own network the probe carries a long prompt, as Talk's is: a cut one is said. | |
| 218 | const pad = input.privateOk ? [{ role: "system", content: `Notes to keep in mind. ${"The forge keeps every note. ".repeat(PROBE_PAD_CHARS / 27)}` }] : []; | |
| 219 | try { | |
| 220 | const probe = await ask( | |
| 221 | openai | |
| 222 | ? { | |
| 223 | messages: [...pad, { role: "user", content: "Call the ping tool." }], | |
| 224 | tools: [ | |
| 225 | { | |
| 226 | type: "function", | |
| 227 | function: { | |
| 228 | name: "ping", | |
| 229 | description: "Answers pong.", | |
| 230 | parameters: { type: "object", properties: {} }, | |
| 231 | }, | |
| 232 | }, | |
| 233 | ], | |
| 234 | } | |
| 235 | : { | |
| 236 | messages: [{ role: "user", content: "Call the ping tool." }], | |
| 237 | tools: [ | |
| 238 | { | |
| 239 | name: "ping", | |
| 240 | description: "Answers pong.", | |
| 241 | input_schema: { type: "object", properties: {} }, | |
| 242 | }, | |
| 243 | ], | |
| 244 | }, | |
| 245 | PROBE_TOKENS, | |
| 246 | ); | |
| 247 | if (probe.ok) { | |
| 248 | const said = (await probe.json()) as { | |
| 249 | choices?: { message?: { tool_calls?: unknown[] } }[]; | |
| 250 | content?: { type?: unknown }[]; | |
| 251 | usage?: { prompt_tokens?: number }; | |
| 252 | }; | |
| 253 | // As the runner judges it (`cutLine`): the server read under half the prompt it was sent. | |
| 254 | const sent = Math.round(JSON.stringify(pad).length / 4); | |
| 255 | const read = said.usage?.prompt_tokens ?? 0; | |
| 256 | if (pad.length > 0 && read > 0 && read < sent / 2) cut = cutLine(read, sent); | |
| 257 | tools = openai | |
| 258 | ? (said.choices?.[0]?.message?.tool_calls?.length ?? 0) > 0 | |
| 259 | : (said.content ?? []).some((c) => c.type === "tool_use"); | |
| 260 | } | |
| 261 | } catch { | |
| 262 | // A model that cannot call a tool still talks; the words say so. | |
| 263 | } | |
| 264 | if (cut !== undefined) return { working: false, said: `${String(models.length)} models listed, but ${cut.charAt(0).toLowerCase()}${cut.slice(1)}`, models, tools }; | |
| 265 | return { | |
| 266 | working: true, | |
| 267 | said: `${String(models.length)} models listed · a one-token reply in ${seconds} s · ${tools ? "called a tool" : "did not call a tool: Talk needs one that does"}`, | |
| 268 | models, | |
| 269 | tools, | |
| 270 | }; | |
| 271 | } | |
| 272 | ||
| 273 | /** | |
| 274 | * Each person's tests run one at a time, per forge: a test is three outbound calls of up to | |
| 275 | * `TEST_CALL_MS`, so one person can never keep more than one going. Not a pace: the next starts as | |
| 276 | * soon as the last ends. | |
| 277 | */ | |
| 278 | const testing = new WeakMap<Database, Set<string>>(); | |
| 279 | ||
| 280 | /** `run` as `user`'s one test in flight, or "busy" while another of theirs runs. */ | |
| 281 | async function oneAtATime<T>(app: App, user: User, run: () => Promise<T>): Promise<T | "busy"> { | |
| 282 | let running = testing.get(app.db); | |
| 283 | if (running === undefined) testing.set(app.db, (running = new Set())); | |
| 284 | if (running.has(user.id)) return "busy"; | |
| 285 | running.add(user.id); | |
| 286 | try { | |
| 287 | return await run(); | |
| 288 | } finally { | |
| 289 | running.delete(user.id); | |
| 290 | } | |
| 291 | } | |
| 292 | ||
| 293 | /** Add a connection: test it, and save it only when it answers (verify, then save). */ | |
| 294 | export async function addConnection( | |
| 295 | app: App, | |
| 296 | user: User, | |
| 297 | input: { | |
| 298 | name: string; | |
| 299 | protocol: Protocol; | |
| 300 | base: string; | |
| 301 | key: string; | |
| 302 | scope: "yours" | "forge"; | |
| 303 | effort?: Effort | "" | undefined; | |
| 304 | }, | |
| 305 | guard: OutboundOptions = {}, | |
| 306 | ): Promise< | |
| 307 | | Result<{ connection: Connection; test: TestResult }, ConnectionError | "forbidden"> | |
| 308 | | { readonly ok: false; readonly error: "not_working"; readonly said: string } | |
| 309 | | { readonly ok: false; readonly error: "host_refused"; readonly host: string } | |
| 310 | > { | |
| 311 | if (input.scope === "forge" && !user.isAdmin) return err("forbidden"); | |
| 312 | const base = parseConnectionBase(input.base, input.scope === "forge"); | |
| 313 | if (!base.ok) return err(base.error); | |
| 314 | const test = await oneAtATime(app, user, () => | |
| 315 | testConnection( | |
| 316 | { | |
| 317 | protocol: input.protocol, | |
| 318 | base: base.value, | |
| 319 | key: input.key.trim(), | |
| 320 | privateOk: input.scope === "forge", | |
| 321 | effort: input.effort, | |
| 322 | }, | |
| 323 | guard, | |
| 324 | ), | |
| 325 | ); | |
| 326 | if (test === "busy") return err("busy"); | |
| 327 | // Nothing is kept of one that did not answer; its words go back to the person who asked. | |
| 328 | if (test.refusedHost !== undefined) return { ok: false, error: "host_refused", host: test.refusedHost }; | |
| 329 | if (!test.working) return { ok: false, error: "not_working", said: test.said }; | |
| 330 | const saved = saveConnection(app.db, app.config.dataDir, { | |
| 331 | ...input, | |
| 332 | base: base.value, | |
| 333 | userId: user.id, | |
| 334 | models: test.models, | |
| 335 | said: test.said, | |
| 336 | }); | |
| 337 | return saved.ok ? ok({ connection: saved.value, test }) : err(saved.error); | |
| 338 | } | |
| 339 | ||
| 340 | /** | |
| 341 | * Test a saved connection again, and keep what it found: the person's own, or the forge's for an | |
| 342 | * admin alone. Undefined when it is neither; "busy" while another test of theirs runs. | |
| 343 | */ | |
| 344 | export async function retestConnection( | |
| 345 | app: App, | |
| 346 | user: User, | |
| 347 | connectionId: string, | |
| 348 | guard: OutboundOptions = {}, | |
| 349 | ): Promise<TestResult | "busy" | undefined> { | |
| 350 | const c = connectionFor(app.db, user.id, connectionId); | |
| 351 | if (c !== undefined && c.scope === "forge" && !user.isAdmin) return undefined; | |
| 352 | const key = | |
| 353 | c === undefined | |
| 354 | ? undefined | |
| 355 | : connectionKey(app.db, app.config.dataDir, connectionId); | |
| 356 | if (c === undefined || c.base === null || key === undefined) return undefined; | |
| 357 | const test = await oneAtATime(app, user, () => testConnection({ protocol: c.protocol, base: c.base!, key, privateOk: c.privateOk, effort: c.effort }, guard)); | |
| 358 | if (test === "busy") return test; | |
| 359 | recordTest(app.db, connectionId, { | |
| 360 | working: test.working, | |
| 361 | said: test.said, | |
| 362 | ...(test.models.length === 0 ? {} : { models: test.models }), | |
| 363 | }); | |
| 364 | return test; | |
| 365 | } |
src/core/connections.ts added +456
| @@ -0,0 +1,456 @@ | ||
| 1 | /** | |
MEDIUM, security (data across users). Ownership is derived from grants, not stored. |
||
| 2 | * Connections (Connect your AI): every model backend a person may use, in one list. A connection | |
| 3 | * is a subscription row (`core/subscriptions.ts`) with a protocol: `anthropic` (every row before | |
| 4 | * connections, and Claude's own) or `openai`, any OpenAI-compatible server (OpenRouter, Ollama, | |
| 5 | * vLLM, LM Studio, LiteLLM, OpenAI). Two scopes, and who pays follows the scope: | |
| 6 | * | |
| 7 | * - yours: added by a person, granted to their own repositories only, and spending their own key, | |
| 8 | * never the forge's credit. Its base URL must be public https (`parseConnectionBase`), and the | |
| 9 | * forge reaches it only through the outbound guard (`kernel/outbound.ts`). | |
| 10 | * - the forge's: added by an admin, following today's credit, grants and budgets unchanged. Only | |
| 11 | * these may be on a private, loopback or LAN address (`private_ok`): a model on the forge's own | |
| 12 | * machine or network. | |
| 13 | * | |
| 14 | * A key is sealed at rest, typed once and never shown again, and sent only to the host it was saved | |
| 15 | * for. What a test learned is kept as the models listed and the result's words, nothing more. | |
| 16 | * Plain data; the network is `actions/connections.ts`'s. | |
| 17 | */ | |
| 18 | import type { Database } from "bun:sqlite"; | |
| 19 | import { id } from "../kernel/id.ts"; | |
| 20 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 21 | import { open, seal } from "../kernel/secret.ts"; | |
| 22 | import { | |
| 23 | EVERYONE, | |
| 24 | isPublicGatewayName, | |
| 25 | isSubscriptionName, | |
| 26 | listGrants, | |
| 27 | normalizeToken, | |
| 28 | PLATFORM, | |
| 29 | setGrants, | |
| 30 | subscriptionAad, | |
| 31 | } from "./subscriptions.ts"; | |
| 32 | ||
| 33 | export type Protocol = "anthropic" | "openai"; | |
| 34 | ||
| 35 | /** A model a connection serves, as its last test listed it; prices per million tokens when it said. */ | |
| 36 | export interface ConnectionModel { | |
| 37 | readonly id: string; | |
| 38 | readonly inUsd?: number; | |
| 39 | readonly outUsd?: number; | |
| 40 | } | |
| 41 | ||
| 42 | export interface Connection { | |
| 43 | readonly id: string; | |
| 44 | readonly name: string; | |
| 45 | readonly protocol: Protocol; | |
| 46 | /** The base URL calls go to; for the forge's own Anthropic token, none. */ | |
| 47 | readonly base: string | null; | |
| 48 | /** Whose it is: the person's own, or the forge's. */ | |
| 49 | readonly scope: "yours" | "forge"; | |
| 50 | /** It may be on a private address: only the forge's. */ | |
| 51 | readonly privateOk: boolean; | |
| 52 | readonly models: readonly ConnectionModel[]; | |
| 53 | /** The models Talk and the crew may use; empty means every model listed. */ | |
| 54 | readonly chosen: readonly string[]; | |
| 55 | readonly testedAt: string | null; | |
| 56 | /** The last test's verdict; undefined when never tested. */ | |
| 57 | readonly working: boolean | undefined; | |
| 58 | readonly testSaid: string; | |
| 59 | /** The reasoning effort its turns and tests ask for (`reasoning_effort`); "" asks none. */ | |
| 60 | readonly effort: Effort | ""; | |
| 61 | } | |
| 62 | ||
| 63 | /** The reasoning efforts an OpenAI-compatible server may be asked for, as the runner sends them. */ | |
| 64 | export const EFFORTS = ["none", "minimal", "low", "medium", "high"] as const; | |
| 65 | export type Effort = (typeof EFFORTS)[number]; | |
| 66 | ||
| 67 | /** A typed effort as a connection keeps it: one of `EFFORTS`, or "" for none asked; undefined when it is neither. */ | |
| 68 | export const effortOf = (raw: string): Effort | "" | undefined => { | |
| 69 | const e = raw.trim().toLowerCase(); | |
| 70 | return e === "" ? "" : (EFFORTS as readonly string[]).includes(e) ? (e as Effort) : undefined; | |
| 71 | }; | |
| 72 | ||
| 73 | /** A preset fills the protocol and base URL; the person gives the name and key. */ | |
| 74 | export const CONNECTION_PRESETS: readonly { | |
| 75 | readonly id: string; | |
| 76 | readonly label: string; | |
| 77 | readonly protocol: Protocol; | |
| 78 | readonly base: string; | |
| 79 | readonly local?: true; | |
| 80 | }[] = [ | |
| 81 | { | |
| 82 | id: "openrouter", | |
| 83 | label: "OpenRouter", | |
| 84 | protocol: "openai", | |
| 85 | base: "https://openrouter.ai/api/v1", | |
| 86 | }, | |
| 87 | { | |
| 88 | id: "openai", | |
| 89 | label: "OpenAI", | |
| 90 | protocol: "openai", | |
| 91 | base: "https://api.openai.com/v1", | |
| 92 | }, | |
| 93 | { | |
| 94 | id: "anthropic", | |
| 95 | label: "Anthropic", | |
| 96 | protocol: "anthropic", | |
| 97 | base: "https://api.anthropic.com", | |
| 98 | }, | |
| 99 | { id: "litellm", label: "LiteLLM", protocol: "openai", base: "" }, | |
| 100 | { | |
| 101 | id: "ollama", | |
| 102 | label: "Ollama", | |
| 103 | protocol: "openai", | |
| 104 | base: "http://localhost:11434/v1", | |
| 105 | local: true, | |
| 106 | }, | |
| 107 | { | |
| 108 | id: "vllm", | |
| 109 | label: "vLLM", | |
| 110 | protocol: "openai", | |
| 111 | base: "http://localhost:8000/v1", | |
| 112 | local: true, | |
| 113 | }, | |
| 114 | { | |
| 115 | id: "lmstudio", | |
| 116 | label: "LM Studio", | |
| 117 | protocol: "openai", | |
| 118 | base: "http://localhost:1234/v1", | |
| 119 | local: true, | |
| 120 | }, | |
| 121 | ]; | |
| 122 | ||
| 123 | export const BASE_MAX = 200; | |
| 124 | const TOKEN_MAX = 4096; | |
| 125 | /** At most this many models are kept from a listing. */ | |
| 126 | export const MODELS_KEPT = 500; | |
| 127 | /** A person may keep at most this many connections of their own. */ | |
| 128 | export const OWN_MAX = 8; | |
| 129 | ||
| 130 | export type ConnectionError = | |
| 131 | | "invalid_name" | |
| 132 | | "name_taken" | |
| 133 | | "invalid_base" | |
| 134 | | "private_base" | |
| 135 | | "invalid_key" | |
| 136 | | "too_many" | |
| 137 | | "busy"; | |
| 138 | ||
| 139 | /** | |
| 140 | * A base URL as one connection may use it. Anyone's: https, no credentials, query or hash, and a | |
| 141 | * public name (`isPublicGatewayName`: never an address, localhost or a private suffix). The forge's | |
| 142 | * own may also be plain http and private: `forge` says the caller is an admin adding the forge's. | |
| 143 | * Trailing slashes go; the path is kept (`/v1` included: an OpenAI-compatible base ends there). | |
| 144 | */ | |
| 145 | export function parseConnectionBase( | |
| 146 | raw: string, | |
| 147 | forge: boolean, | |
| 148 | ): Result<string, "invalid_base" | "private_base"> { | |
| 149 | const trimmed = raw.trim(); | |
| 150 | if (trimmed === "" || trimmed.length > BASE_MAX) return err("invalid_base"); | |
| 151 | let url: URL; | |
| 152 | try { | |
| 153 | url = new URL(trimmed); | |
| 154 | } catch { | |
| 155 | return err("invalid_base"); | |
| 156 | } | |
| 157 | if (url.protocol !== "https:" && url.protocol !== "http:") | |
| 158 | return err("invalid_base"); | |
| 159 | if ( | |
| 160 | url.username !== "" || | |
| 161 | url.password !== "" || | |
| 162 | url.search !== "" || | |
| 163 | url.hash !== "" || | |
| 164 | url.hostname === "" | |
| 165 | ) | |
| 166 | return err("invalid_base"); | |
| 167 | const open = url.protocol === "https:" && isPublicGatewayName(url.hostname); | |
| 168 | if (!open && !forge) return err("private_base"); | |
| 169 | const path = url.pathname.replace(/\/+$/, ""); | |
| 170 | return ok(`${url.protocol}//${url.host}${path}`); | |
| 171 | } | |
| 172 | ||
| 173 | interface Row { | |
| 174 | id: string; | |
| 175 | name: string; | |
| 176 | protocol: string; | |
| 177 | api_base: string | null; | |
| 178 | created_by: string | null; | |
| 179 | private_ok: number; | |
| 180 | models: string; | |
| 181 | chosen: string; | |
| 182 | tested_at: string | null; | |
| 183 | test_ok: number | null; | |
| 184 | test_said: string; | |
| 185 | effort: string; | |
| 186 | } | |
| 187 | ||
| 188 | const COLUMNS = | |
| 189 | "id, name, protocol, api_base, created_by, private_ok, models, chosen, tested_at, test_ok, test_said, effort"; | |
| 190 | ||
| 191 | const parsed = <T>(text: string, fallback: T): T => { | |
| 192 | try { | |
| 193 | return JSON.parse(text) as T; | |
| 194 | } catch { | |
| 195 | return fallback; | |
| 196 | } | |
| 197 | }; | |
| 198 | ||
| 199 | /** The person's own connections are the ones they made and granted to themselves. */ | |
| 200 | /** | |
| 201 | * Whose each connection is: its creator's when its stored scope is 'yours', nobody's (the forge's) | |
| 202 | * when 'forge'. A row from before the scope was stored ('') reads as it always did: its creator's | |
| 203 | * own when they granted it to their own repositories, else the forge's. A grant made later never | |
| 204 | * moves a connection between the two. | |
| 205 | */ | |
| 206 | function ownersOf(db: Database): Map<string, string | null> { | |
| 207 | const legacy = new Set( | |
| 208 | db | |
| 209 | .query<{ id: string }, [string]>("SELECT s.id FROM subscription s JOIN subscription_grant g ON g.subscription_id = s.id WHERE s.scope = '' AND s.created_by IS NOT NULL AND g.scope_id = s.created_by AND g.agent_id = ?1") | |
| 210 | .all(EVERYONE) | |
| 211 | .map((r) => r.id), | |
| 212 | ); | |
| 213 | const out = new Map<string, string | null>(); | |
| 214 | for (const r of db.query<{ id: string; scope: string; created_by: string | null }, []>("SELECT id, scope, created_by FROM subscription").all()) | |
| 215 | out.set(r.id, r.scope === "yours" || (r.scope === "" && legacy.has(r.id)) ? r.created_by : null); | |
| 216 | return out; | |
| 217 | } | |
| 218 | ||
| 219 | /** How many connections of their own `userId` keeps. */ | |
| 220 | const ownCount = (db: Database, userId: string): number => [...ownersOf(db).values()].filter((o) => o === userId).length; | |
| 221 | ||
| 222 | const toConnection = (r: Row, own: boolean): Connection => ({ | |
| 223 | id: r.id, | |
| 224 | name: r.id === PLATFORM ? "The forge's own" : r.name, | |
| 225 | protocol: r.protocol === "openai" ? "openai" : "anthropic", | |
| 226 | base: r.api_base, | |
| 227 | scope: own ? "yours" : "forge", | |
| 228 | privateOk: r.private_ok === 1, | |
| 229 | models: parsed<ConnectionModel[]>(r.models, []), | |
| 230 | chosen: parsed<string[]>(r.chosen, []), | |
| 231 | testedAt: r.tested_at, | |
| 232 | working: r.test_ok === null ? undefined : r.test_ok === 1, | |
| 233 | testSaid: r.test_said, | |
| 234 | effort: effortOf(r.effort) ?? "", | |
| 235 | }); | |
| 236 | ||
| 237 | /** | |
| 238 | * Every connection `userId` may use, theirs first, then the forge's (the forge's own token included). | |
| 239 | * Another person's own connection is never listed. | |
| 240 | */ | |
| 241 | export function listConnections(db: Database, userId: string): Connection[] { | |
| 242 | const owners = ownersOf(db); | |
| 243 | const rows = db | |
| 244 | .query< | |
| 245 | Row, | |
| 246 | [] | |
| 247 | >(`SELECT ${COLUMNS} FROM subscription ORDER BY created_at, id`) | |
| 248 | .all(); | |
| 249 | const mine = rows.filter((r) => owners.get(r.id) === userId).map((r) => toConnection(r, true)); | |
| 250 | // Another person's own is never listed: only the forge's, nobody's own. | |
| 251 | const forge = rows.filter((r) => (owners.get(r.id) ?? null) === null).map((r) => toConnection(r, false)); | |
| 252 | return [...mine, ...forge]; | |
| 253 | } | |
| 254 | ||
| 255 | /** One connection `userId` may use, by id. */ | |
| 256 | export function connectionFor( | |
| 257 | db: Database, | |
| 258 | userId: string, | |
| 259 | connectionId: string, | |
| 260 | ): Connection | undefined { | |
| 261 | return listConnections(db, userId).find((c) => c.id === connectionId); | |
| 262 | } | |
| 263 | ||
| 264 | /** The key a connection's calls carry, opened only for a call; "" for none (a local server). */ | |
| 265 | export function connectionKey( | |
| 266 | db: Database, | |
| 267 | dataDir: string, | |
| 268 | connectionId: string, | |
| 269 | ): string | undefined { | |
| 270 | const row = db | |
| 271 | .query< | |
| 272 | { token_enc: string }, | |
| 273 | [string] | |
| 274 | >("SELECT token_enc FROM subscription WHERE id = ?1 AND id <> 'platform'") | |
| 275 | .get(connectionId); | |
| 276 | if (row === null) return undefined; | |
| 277 | // A local server that takes no key keeps none: nothing is sealed. | |
| 278 | if (row.token_enc === "") return ""; | |
| 279 | const opened = open(dataDir, row.token_enc, subscriptionAad(connectionId)); | |
| 280 | return opened.ok ? opened.value : undefined; | |
| 281 | } | |
| 282 | ||
| 283 | /** | |
| 284 | * Save a connection a test has passed (`actions/connections.ts` asks first). Yours: granted to your | |
| 285 | * own repositories only, and spending your key. The forge's: no grant (an admin grants it on the | |
| 286 | * subscriptions page, as any account), and private addresses allowed. | |
| 287 | */ | |
| 288 | export function saveConnection( | |
| 289 | db: Database, | |
| 290 | dataDir: string, | |
| 291 | input: { | |
| 292 | name: string; | |
| 293 | protocol: Protocol; | |
| 294 | base: string; | |
| 295 | key: string; | |
| 296 | scope: "yours" | "forge"; | |
| 297 | userId: string; | |
| 298 | models: readonly ConnectionModel[]; | |
| 299 | said: string; | |
| 300 | effort?: Effort | "" | undefined; | |
| 301 | }, | |
| 302 | ): Result<Connection, ConnectionError> { | |
| 303 | const name = input.name.trim(); | |
| 304 | if (!isSubscriptionName(name)) return err("invalid_name"); | |
| 305 | const base = parseConnectionBase(input.base, input.scope === "forge"); | |
| 306 | if (!base.ok) return err(base.error); | |
| 307 | const key = normalizeToken(input.key); | |
| 308 | if (key.length > TOKEN_MAX || /\0/.test(key)) return err("invalid_key"); | |
| 309 | // Anthropic's own takes a key; an OpenAI-compatible local server may take none. | |
| 310 | if (key === "" && (input.protocol === "anthropic" || input.scope === "yours")) | |
| 311 | return err("invalid_key"); | |
| 312 | if ( | |
| 313 | db | |
| 314 | .query< | |
| 315 | { n: number }, | |
| 316 | [string] | |
| 317 | >("SELECT COUNT(*) AS n FROM subscription WHERE name = ?1 COLLATE NOCASE") | |
| 318 | .get(name)!.n > 0 | |
| 319 | ) | |
| 320 | return err("name_taken"); | |
| 321 | if (input.scope === "yours" && ownCount(db, input.userId) >= OWN_MAX) | |
| 322 | return err("too_many"); | |
| 323 | const connectionId = id(); | |
| 324 | const now = new Date().toISOString(); | |
| 325 | db.query( | |
| 326 | `INSERT INTO subscription (id, name, kind, token_enc, api_base, created_by, protocol, models, chosen, tested_at, test_ok, test_said, private_ok, effort, scope) | |
| 327 | VALUES (?1, ?2, 'api_key', ?3, ?4, ?5, ?6, ?7, '[]', ?8, 1, ?9, ?10, ?11, ?12)`, | |
| 328 | ).run( | |
| 329 | connectionId, | |
| 330 | name, | |
| 331 | key === "" ? "" : seal(dataDir, key, subscriptionAad(connectionId)), | |
| 332 | base.value, | |
| 333 | input.userId, | |
| 334 | input.protocol, | |
| 335 | JSON.stringify(input.models.slice(0, MODELS_KEPT)), | |
| 336 | now, | |
| 337 | input.said, | |
| 338 | input.scope === "forge" ? 1 : 0, | |
| 339 | input.effort ?? "", | |
| 340 | input.scope, | |
| 341 | ); | |
| 342 | if (input.scope === "yours") | |
| 343 | setGrants(db, input.userId, EVERYONE, [ | |
| 344 | ...listGrants(db, input.userId) | |
| 345 | .filter((g) => g.agentId === EVERYONE) | |
| 346 | .map((g) => g.subscriptionId), | |
| 347 | connectionId, | |
| 348 | ]); | |
| 349 | return ok(connectionFor(db, input.userId, connectionId)!); | |
| 350 | } | |
| 351 | ||
| 352 | /** What a test of a saved connection found: its verdict and words, and the models it listed. */ | |
| 353 | export function recordTest( | |
| 354 | db: Database, | |
| 355 | connectionId: string, | |
| 356 | result: { | |
| 357 | readonly working: boolean; | |
| 358 | readonly said: string; | |
| 359 | readonly models?: readonly ConnectionModel[]; | |
| 360 | }, | |
| 361 | ): void { | |
| 362 | db.query( | |
| 363 | "UPDATE subscription SET tested_at = ?2, test_ok = ?3, test_said = ?4, models = COALESCE(?5, models) WHERE id = ?1", | |
| 364 | ).run( | |
| 365 | connectionId, | |
| 366 | new Date().toISOString(), | |
| 367 | result.working ? 1 : 0, | |
| 368 | result.said.slice(0, 300), | |
| 369 | result.models === undefined | |
| 370 | ? null | |
| 371 | : JSON.stringify(result.models.slice(0, MODELS_KEPT)), | |
| 372 | ); | |
| 373 | } | |
| 374 | ||
| 375 | /** Remove a connection: a person their own; an admin the forge's. Its grants go with it. */ | |
| 376 | export function removeConnection( | |
| 377 | db: Database, | |
| 378 | user: { id: string; isAdmin: boolean }, | |
| 379 | connectionId: string, | |
| 380 | ): boolean { | |
| 381 | const c = connectionFor(db, user.id, connectionId); | |
| 382 | if ( | |
| 383 | c === undefined || | |
| 384 | c.id === PLATFORM || | |
| 385 | (c.scope === "forge" && !user.isAdmin) | |
| 386 | ) | |
| 387 | return false; | |
| 388 | db.transaction(() => { | |
| 389 | db.query("DELETE FROM subscription_grant WHERE subscription_id = ?1").run( | |
| 390 | connectionId, | |
| 391 | ); | |
| 392 | db.query("DELETE FROM subscription WHERE id = ?1").run(connectionId); | |
| 393 | })(); | |
| 394 | return true; | |
| 395 | } | |
| 396 | ||
| 397 | /** Who pays for a connection's turns, in the row's own words. */ | |
| 398 | export const payerWords = (c: Connection): string => | |
| 399 | c.scope === "yours" | |
| 400 | ? "spends your key, never the forge's credit" | |
| 401 | : "the forge's credit and budgets"; | |
| 402 | ||
| 403 | /** The words a connection's status badge says. */ | |
| 404 | export const statusWords = (c: Connection): string => | |
| 405 | c.working === undefined | |
| 406 | ? c.protocol === "anthropic" | |
| 407 | ? "not tested" | |
| 408 | : "not tested yet" | |
| 409 | : c.working | |
| 410 | ? "working" | |
| 411 | : "not working"; | |
| 412 | ||
| 413 | /** Why an added connection was not kept, in the person's words. */ | |
| 414 | export const CONNECTION_REFUSED: Readonly<Record<string, string>> = { | |
| 415 | invalid_name: | |
| 416 | "Give the connection a name: letters, digits, spaces, dots, dashes; at most 40.", | |
| 417 | name_taken: "A connection by that name is here already.", | |
| 418 | invalid_base: | |
| 419 | "That base URL is not one: https://host/path, with no user, query or fragment.", | |
| 420 | private_base: | |
| 421 | "Your own connection must be a public https address. A model on this forge's own machine or network can only be one of the forge's own connections.", | |
| 422 | invalid_key: "Give the connection's key.", | |
| 423 | too_many: "You have eight connections of your own; remove one first.", | |
| 424 | busy: "One of your tests is still running; try this when it ends.", | |
| 425 | forbidden: "Only an admin adds the forge's connections.", | |
| 426 | }; | |
| 427 | ||
| 428 | /** | |
| 429 | * Whether a person may read a connection's address and test words: their own, or any for an admin. | |
| 430 | * The forge's own may sit on its private network, and its errors may name it; another person reads | |
| 431 | * its name, protocol, payer, status and model count only. | |
| 432 | */ | |
| 433 | export const detailsFor = (c: Connection, user: { readonly isAdmin: boolean }): { readonly base: string; readonly said: string } | undefined => | |
| 434 | c.scope === "yours" || user.isAdmin ? { base: c.base ?? "the forge's environment", said: c.testSaid } : undefined; | |
| 435 | ||
| 436 | /** | |
| 437 | * The hosts a person's own connection may be on when the forge runs in a cell: the presets' public | |
| 438 | * ones, each declared in `forge.json` `egress` (`test/connections.test.ts` holds them to it). Any | |
| 439 | * other host is refused by the forge's egress gate, and the add form says so before saving. | |
| 440 | */ | |
| 441 | export const OWN_HOSTS: readonly string[] = [...new Set(CONNECTION_PRESETS.filter((p) => p.local !== true && p.base.startsWith("https://")).map((p) => new URL(p.base).hostname))]; | |
| 442 | ||
| 443 | /** `a`, `a and b`, `a, b and c`. */ | |
| 444 | const listed = (xs: readonly string[]): string => (xs.length <= 1 ? (xs[0] ?? "") : `${xs.slice(0, -1).join(", ")} and ${xs.at(-1)!}`); | |
| 445 | ||
| 446 | /** What the forge says when its gate refused a person's own connection's host. */ | |
| 447 | export const reachableHostsSentence = (host: string): string => `This forge can reach ${listed(OWN_HOSTS)} for your own connections, not ${host}.`; | |
| 448 | ||
| 449 | /** The protocol a connection of the kind Other speaks: any server with the chat completions API. */ | |
| 450 | export const OTHER_PROTOCOL: Protocol = "openai"; | |
| 451 | ||
| 452 | /** What a page or the terminal calls a protocol, in no vendor's name (the picker alone names them). */ | |
| 453 | export const protocolWords = (p: Protocol): string => (p === "openai" ? "Chat completions API" : "Messages API"); | |
| 454 | ||
| 455 | /** The kind picker's last choice. */ | |
| 456 | export const OTHER_KIND = "Other (a chat completions API)"; |
src/core/migration-pins/20261125180000-connections.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 555e18942216cbc13de47947b6e9d1673634ab390fd490e3adc7dea8983dca3c |
src/core/migration-pins/20261125190500-connection-effort.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 022abb95d2b0525a63a1506326130edf4bcf6610143ac15a6cd464408b9320e1 |
src/core/migration-pins/20261125201000-connection-scope.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 7b00c18f4c8df3fd806c8458d6dd9d6f192daed4ccb15ec387d283882988de97 |
src/core/migrations/20261125180000-connections.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | // Connections (Connect your AI): a subscription is a connection to a model backend. Its protocol | |
| 2 | // (`anthropic`, as every row before this, or `openai` for an OpenAI-compatible server), the models | |
| 3 | // its last test listed and the ones chosen for Talk and the crew (JSON), that test's time, verdict | |
| 4 | // and words, and whether it may be on a private address (only for the forge's own, added by an | |
| 5 | // admin). Additive: every existing row keeps working as the Anthropic connection it was. | |
| 6 | export default ` | |
| 7 | ALTER TABLE subscription ADD COLUMN protocol TEXT NOT NULL DEFAULT 'anthropic'; | |
| 8 | ALTER TABLE subscription ADD COLUMN models TEXT NOT NULL DEFAULT '[]'; | |
| 9 | ALTER TABLE subscription ADD COLUMN chosen TEXT NOT NULL DEFAULT '[]'; | |
| 10 | ALTER TABLE subscription ADD COLUMN tested_at TEXT; | |
| 11 | ALTER TABLE subscription ADD COLUMN test_ok INTEGER; | |
| 12 | ALTER TABLE subscription ADD COLUMN test_said TEXT NOT NULL DEFAULT ''; | |
| 13 | ALTER TABLE subscription ADD COLUMN private_ok INTEGER NOT NULL DEFAULT 0; | |
| 14 | `; |
src/core/migrations/20261125190500-connection-effort.ts added +5
| @@ -0,0 +1,5 @@ | ||
| 1 | // Connections (core/connections.ts): the reasoning effort a connection's tests and Talk turns ask | |
| 2 | // for, sent as reasoning_effort ('' asks none, as before). Additive. | |
| 3 | export default ` | |
| 4 | ALTER TABLE subscription ADD COLUMN effort TEXT NOT NULL DEFAULT ''; | |
| 5 | `; |
src/core/migrations/20261125201000-connection-scope.ts added +6
| @@ -0,0 +1,6 @@ | ||
| 1 | // Connections (core/connections.ts): whose a connection is, stored on its row rather than read from | |
| 2 | // its grants: 'yours' (a person's own, spending their key) or 'forge' (the forge's, on its credit). | |
| 3 | // A row from before this keeps '' and is read as it was, by the grant its creator gave it. Additive. | |
| 4 | export default ` | |
| 5 | ALTER TABLE subscription ADD COLUMN scope TEXT NOT NULL DEFAULT ''; | |
| 6 | `; |
src/core/model_grant.ts +6 −2
| @@ -112,7 +112,7 @@ export function ownSubscription(db: Database, userId: string): Subscription | un | ||
| 112 | 112 | .query<{ id: string }, [string, string]>( |
| 113 | 113 | `SELECT s.id FROM subscription s |
| 114 | 114 | JOIN subscription_grant g ON g.subscription_id = s.id |
| 115 | WHERE s.created_by = ?1 AND g.scope_id = ?1 AND g.agent_id = ?2 | |
| 115 | WHERE s.created_by = ?1 AND g.scope_id = ?1 AND g.agent_id = ?2 AND s.protocol = 'anthropic' AND s.scope <> 'forge' | |
| 116 | 116 | ORDER BY s.created_at, s.id LIMIT 1`, |
| 117 | 117 | ) |
| 118 | 118 | .get(userId, EVERYONE); |
| @@ -136,7 +136,11 @@ export function addOwnSubscription( | ||
| 136 | 136 | apiBase: input.apiBase, |
| 137 | 137 | createdBy: user.id, |
| 138 | 138 | }); |
| 139 | if (added.ok) setGrants(db, user.id, EVERYONE, [added.value.id]); | |
| 139 | if (added.ok) { | |
| 140 | // The account's own: so it stays theirs whatever is granted later (`core/connections.ts`). | |
| 141 | db.query("UPDATE subscription SET scope = 'yours' WHERE id = ?1").run(added.value.id); | |
| 142 | setGrants(db, user.id, EVERYONE, [added.value.id]); | |
| 143 | } | |
| 140 | 144 | return added; |
| 141 | 145 | } |
| 142 | 146 |
src/core/subscriptions.ts +5 −1
| @@ -306,7 +306,7 @@ export function credentialEnvOf( | ||
| 306 | 306 | export function accountCredential(db: Database, dataDir: string, subscriptionId: string): Record<string, string> | undefined { |
| 307 | 307 | const row = db |
| 308 | 308 | .query<{ kind: string; token_enc: string; api_base: string | null }, [string]>( |
| 309 | "SELECT kind, token_enc, api_base FROM subscription WHERE id = ?1 AND id <> 'platform'", | |
| 309 | "SELECT kind, token_enc, api_base FROM subscription WHERE id = ?1 AND id <> 'platform' AND protocol = 'anthropic'", | |
| 310 | 310 | ) |
| 311 | 311 | .get(subscriptionId); |
| 312 | 312 | if (row === null || !gatewayUsable(row.api_base)) return undefined; |
| @@ -361,6 +361,8 @@ export function addSubscription( | ||
| 361 | 361 | apiBase, |
| 362 | 362 | input.createdBy ?? null, |
| 363 | 363 | ); |
| 364 | // An account added here is the forge's (`core/connections.ts`); a person's own sets its scope after. | |
| 365 | db.query("UPDATE subscription SET scope = 'forge' WHERE id = ?1").run(subscriptionId); | |
| 364 | 366 | return ok(getSubscription(db, subscriptionId)!); |
| 365 | 367 | } |
| 366 | 368 | |
| @@ -652,6 +654,8 @@ export function pickSubscription( | ||
| 652 | 654 | ${COMMITTED} AS spent_usd |
| 653 | 655 | FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id |
| 654 | 656 | WHERE g.scope_id IN (?1, ?2) AND g.agent_id IN (?3, '') AND s.id <> 'platform' |
| 657 | -- A crew run speaks Anthropic's protocol; another connection is Talk's (core/connections.ts). | |
| 658 | AND s.protocol = 'anthropic' | |
| 655 | 659 | ORDER BY (g.scope_id = ?1) DESC, (g.agent_id = ?3) DESC, |
| 656 | 660 | s.last_used_at IS NOT NULL, s.last_used_at, s.name COLLATE NOCASE`, |
| 657 | 661 | ) |
src/http/marks/settings.json +3
| @@ -126,6 +126,9 @@ | ||
| 126 | 126 | "/settings/people": "admin", |
| 127 | 127 | "/settings/people/:username/role": "admin", |
| 128 | 128 | "/settings/model": "open", |
| 129 | "/settings/model/connections": "open", | |
| 130 | "/settings/model/connections/:id/test": "open", | |
| 131 | "/settings/model/connections/:id/remove": "open", | |
| 129 | 132 | "/settings/accounts/:username/model": "admin", |
| 130 | 133 | "/settings/accounts/:username/ceiling": "admin", |
| 131 | 134 | "/settings/accounts/:username": "admin", |
src/http/settings_routes.ts +4
| @@ -86,6 +86,7 @@ import { | ||
| 86 | 86 | } from "../web/pages/subscriptions.ts"; |
| 87 | 87 | import { peoplePage, roleAct } from "../web/pages/people.ts"; |
| 88 | 88 | import { ceilingAct, grantAct, modelAdd, modelPage } from "../web/pages/model.ts"; |
| 89 | import { connectionAdd, connectionRemove, connectionRetest } from "../web/pages/connections.ts"; | |
| 89 | 90 | import { |
| 90 | 91 | everydayCreate, |
| 91 | 92 | everydayPage, |
| @@ -311,6 +312,9 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 311 | 312 | router.add("POST", "/settings/people/:username/role", roleAct); |
| 312 | 313 | router.add("GET", "/settings/model", modelPage); |
| 313 | 314 | router.add("POST", "/settings/model", modelAdd); |
| 315 | router.add("POST", "/settings/model/connections", connectionAdd); | |
| 316 | router.add("POST", "/settings/model/connections/:id/test", connectionRetest); | |
| 317 | router.add("POST", "/settings/model/connections/:id/remove", connectionRemove); | |
| 314 | 318 | router.add("POST", "/settings/accounts/:username/model", grantAct); |
| 315 | 319 | router.add("POST", "/settings/accounts/:username/ceiling", ceilingAct); |
| 316 | 320 | router.add("GET", "/settings/accounts/:username", personSignInsPage); |
src/tui/screens/model.ts +123 −2
| @@ -22,7 +22,11 @@ import { binding } from "../app/keys.ts"; | ||
| 22 | 22 | import { style } from "../term/style.ts"; |
| 23 | 23 | import { truncate } from "../term/width.ts"; |
| 24 | 24 | import type { Session } from "../session.ts"; |
| 25 | import { blank, later, promptScreen } from "./common.ts"; | |
| 25 | import { blank, later, promptScreen, runAsync } from "./common.ts"; | |
| 26 | import { addConnection, retestConnection } from "../../actions/connections.ts"; | |
| 27 | import { modelHostBlocked } from "../../actions/blocked_words.ts"; | |
| 28 | import { blockedText } from "../../kernel/blocked.ts"; | |
| 29 | import { CONNECTION_PRESETS, CONNECTION_REFUSED, OTHER_PROTOCOL, detailsFor, EFFORTS, effortOf, type Effort, listConnections, payerWords, removeConnection, statusWords } from "../../core/connections.ts"; | |
| 26 | 30 | import type { PaletteEntry } from "./entries.ts"; |
| 27 | 31 | |
| 28 | 32 | /** The signed-in person's budget line, and `a` to add their own subscription. */ |
| @@ -30,14 +34,20 @@ export function modelScreen(f: Session, ctx: Ctx): Screen { | ||
| 30 | 34 | let note = ""; |
| 31 | 35 | const screen: Screen = { |
| 32 | 36 | title: "Connect your AI", |
| 33 | keys: [binding(["a"], "add your subscription"), binding(["esc"], "back")], | |
| 37 | keys: [binding(["a"], "add your subscription"), binding(["n"], "add a connection"), binding(["t"], "test a connection"), binding(["x"], "remove a connection"), binding(["esc"], "back")], | |
| 34 | 38 | render(area, s) { |
| 35 | 39 | const c = ctx.theme.c; |
| 36 | 40 | const user = f.user; |
| 37 | 41 | const own = user === undefined ? undefined : ownSubscription(f.app.db, user.id); |
| 42 | // Every connection the person may use, as the page lists them (`core/connections.ts`). | |
| 43 | const all = user === undefined ? [] : listConnections(f.app.db, user.id); | |
| 38 | 44 | const lines = [ |
| 39 | 45 | user === undefined ? "Sign in to see your model budget." : budgetLine(f.app.db, user, new Date()), |
| 40 | 46 | own === undefined ? "a adds your own subscription, for your own repositories." : `Your subscription: ${own.name}`, |
| 47 | "", | |
| 48 | "Connections (n adds one, t tests one, x removes one):", | |
| 49 | ...all.map((c) => ` ${c.name} · ${statusWords(c)} · ${payerWords(c)}${c.models.length === 0 ? "" : ` · ${String(c.models.length)} models`}${(detailsFor(c, user!)?.said ?? "") === "" ? "" : ` · ${detailsFor(c, user!)?.said}`}`), | |
| 50 | "", | |
| 41 | 51 | note, |
| 42 | 52 | ]; |
| 43 | 53 | lines.forEach((l, i) => |
| @@ -45,6 +55,11 @@ export function modelScreen(f: Session, ctx: Ctx): Screen { | ||
| 45 | 55 | ); |
| 46 | 56 | }, |
| 47 | 57 | key(e) { |
| 58 | const user = f.user; | |
| 59 | if (!e.ctrl && !e.alt && user !== undefined && (e.key === "n" || e.key === "t" || e.key === "x")) { | |
| 60 | ctx.push(e.key === "n" ? addConnectionPrompt(f, ctx, screen, (said) => (note = said)) : namedConnectionPrompt(f, ctx, screen, e.key === "t" ? "test" : "remove", (said) => (note = said))); | |
| 61 | return true; | |
| 62 | } | |
| 48 | 63 | if (e.ctrl || e.alt || e.key !== "a") return false; |
| 49 | 64 | ctx.push( |
| 50 | 65 | promptScreen(ctx, screen, { |
| @@ -72,6 +87,112 @@ export function modelScreen(f: Session, ctx: Ctx): Screen { | ||
| 72 | 87 | return screen; |
| 73 | 88 | } |
| 74 | 89 | |
| 90 | /** | |
| 91 | * Add a connection, as the page's form: its kind (a preset), name, base URL (empty takes the | |
| 92 | * kind's), reasoning effort and key, typed masked. Tested before it is saved; an admin's may be the | |
| 93 | * forge's own. One prompt after another, each the next step's. | |
| 94 | */ | |
| 95 | function addConnectionPrompt(f: Session, ctx: Ctx, parent: Screen, said: (words: string) => void): Screen { | |
| 96 | const kinds = CONNECTION_PRESETS.map((p) => p.id).join(", "); | |
| 97 | let preset: (typeof CONNECTION_PRESETS)[number] | undefined; | |
| 98 | let name = ""; | |
| 99 | let base = ""; | |
| 100 | let effort: Effort | "" = ""; | |
| 101 | const admin = f.user?.isAdmin === true; | |
| 102 | const keyStep = (): Screen => | |
| 103 | promptScreen(ctx, parent, { | |
| 104 | title: `Add ${name}`, | |
| 105 | label: admin ? "key, sealed (end with ! for the forge's)" : "key (sealed, sent only to this address)", | |
| 106 | mask: true, | |
| 107 | onSubmit: (key) => { | |
| 108 | const forge = admin && key.endsWith("!"); | |
| 109 | runAsync(ctx, async () => { | |
| 110 | const added = await addConnection(f.app, f.user!, { name, protocol: preset?.protocol ?? OTHER_PROTOCOL, base: base === "" ? (preset?.base ?? "") : base, key: forge ? key.slice(0, -1) : key, scope: forge ? "forge" : "yours", effort }); | |
| 111 | said( | |
| 112 | added.ok | |
| 113 | ? `${added.value.connection.name} is connected: ${added.value.test.said}.` | |
| 114 | : added.error === "host_refused" | |
| 115 | ? blockedText(modelHostBlocked(f.app, f.user, added.host)) | |
| 116 | : added.error === "not_working" | |
| 117 | ? `Nothing was saved: ${added.said}` | |
| 118 | : (CONNECTION_REFUSED[added.error] ?? added.error), | |
| 119 | ); | |
| 120 | ctx.invalidate(); | |
| 121 | }); | |
| 122 | return undefined; | |
| 123 | }, | |
| 124 | }); | |
| 125 | const effortStep = (): Screen => | |
| 126 | promptScreen(ctx, parent, { | |
| 127 | title: `Add ${name}`, | |
| 128 | label: `reasoning effort: empty, or ${EFFORTS.join(", ")}`, | |
| 129 | onSubmit: (raw) => { | |
| 130 | const picked = effortOf(raw); | |
| 131 | if (picked === undefined) return `Empty, or one of: ${EFFORTS.join(", ")}.`; | |
| 132 | effort = picked; | |
| 133 | return later(ctx, keyStep); | |
| 134 | }, | |
| 135 | }); | |
| 136 | const baseStep = (): Screen => | |
| 137 | promptScreen(ctx, parent, { | |
| 138 | title: `Add ${name}`, | |
| 139 | label: `base URL (empty for ${preset?.base || "none"})`, | |
| 140 | onSubmit: (raw) => { | |
| 141 | base = raw.trim(); | |
| 142 | return later(ctx, effortStep); | |
| 143 | }, | |
| 144 | }); | |
| 145 | const nameStep = (): Screen => | |
| 146 | promptScreen(ctx, parent, { | |
| 147 | title: "Add a connection", | |
| 148 | label: "name", | |
| 149 | onSubmit: (raw) => { | |
| 150 | name = raw.trim(); | |
| 151 | return later(ctx, baseStep); | |
| 152 | }, | |
| 153 | }); | |
| 154 | return promptScreen(ctx, parent, { | |
| 155 | title: "Add a connection", | |
| 156 | label: `kind: ${kinds}, or other`, | |
| 157 | onSubmit: (kind) => { | |
| 158 | preset = CONNECTION_PRESETS.find((p) => p.id === kind.trim().toLowerCase()); | |
| 159 | if (preset === undefined && kind.trim().toLowerCase() !== "other") return `One of: ${kinds}, other.`; | |
| 160 | return later(ctx, nameStep); | |
| 161 | }, | |
| 162 | }); | |
| 163 | } | |
| 164 | ||
| 165 | /** Test or remove a connection by its name; removing asks for the name exactly, as the page's confirm does. */ | |
| 166 | function namedConnectionPrompt(f: Session, ctx: Ctx, parent: Screen, what: "test" | "remove", said: (words: string) => void): Screen { | |
| 167 | return promptScreen(ctx, parent, { | |
| 168 | title: what === "test" ? "Test a connection" : "Remove a connection", | |
| 169 | label: what === "test" ? "its name" : "its name, typed exactly", | |
| 170 | onSubmit: (name) => { | |
| 171 | const c = listConnections(f.app.db, f.user!.id).find((x) => x.name === name.trim()); | |
| 172 | if (c === undefined) return "No connection here by that name."; | |
| 173 | if (what === "remove") { | |
| 174 | if (!removeConnection(f.app.db, f.user!, c.id)) return "Not one you may remove."; | |
| 175 | said(`${c.name} is removed; its key is gone from this forge.`); | |
| 176 | return undefined; | |
| 177 | } | |
| 178 | runAsync(ctx, async () => { | |
| 179 | const test = await retestConnection(f.app, f.user!, c.id); | |
| 180 | said( | |
| 181 | test === undefined | |
| 182 | ? "It could not be tested." | |
| 183 | : test === "busy" | |
| 184 | ? CONNECTION_REFUSED["busy"]! | |
| 185 | : test.refusedHost !== undefined | |
| 186 | ? blockedText(modelHostBlocked(f.app, f.user, test.refusedHost)) | |
| 187 | : `${c.name}: ${test.said}`, | |
| 188 | ); | |
| 189 | ctx.invalidate(); | |
| 190 | }); | |
| 191 | return undefined; | |
| 192 | }, | |
| 193 | }); | |
| 194 | } | |
| 195 | ||
| 75 | 196 | /** Admin: an account's name, then dollars a month (`none` takes the grant back). */ |
| 76 | 197 | export function modelGrantPrompt(f: Session, ctx: Ctx, parent: Screen): Screen { |
| 77 | 198 | return promptScreen(ctx, parent, { |
src/web/pages/connections.ts added +253
| @@ -0,0 +1,253 @@ | ||
| 1 | /** | |
Design, principles 1 and 8: the block says the same thing three times. The intro says 'typed once, sealed, never shown again'. The Key hint says 'Sealed on this forge and sent only to this address'. Another hint says 'spends your key, never the forge's credit'. The closing paragraph then repeats what Test and save does. Keep one confident sentence under the heading and drop the other hints, since the row already states who pays. Principle 3: the row meta joins everything with ' · ' and breaks with |
||
| 2 | * Connections on Connect your AI (`/settings/model`): every model backend the person may use, in | |
| 3 | * one list (`core/connections.ts`), each a row saying whose it is, who pays, its last test and its | |
| 4 | * models, with Test and Remove; and Add a connection, which tests before it saves (a key that does | |
| 5 | * not answer is never kept). Everything is a form post, so it works with the script off. | |
| 6 | */ | |
| 7 | import { addConnection, retestConnection } from "../../actions/connections.ts"; | |
| 8 | import { | |
| 9 | CONNECTION_PRESETS, | |
| 10 | CONNECTION_REFUSED, | |
| 11 | connectionFor, | |
| 12 | detailsFor, | |
| 13 | EFFORTS, | |
| 14 | effortOf, | |
| 15 | OTHER_KIND, | |
| 16 | OTHER_PROTOCOL, | |
| 17 | OWN_HOSTS, | |
| 18 | protocolWords, | |
| 19 | listConnections, | |
| 20 | payerWords, | |
| 21 | removeConnection, | |
| 22 | statusWords, | |
| 23 | type Connection, | |
| 24 | } from "../../core/connections.ts"; | |
| 25 | import { PLATFORM } from "../../core/subscriptions.ts"; | |
| 26 | import type { User } from "../../core/users.ts"; | |
| 27 | import type { Ctx } from "../../http/context.ts"; | |
| 28 | import { notFoundPage } from "../chrome.ts"; | |
| 29 | import { modelHostBlocked } from "../../actions/blocked_words.ts"; | |
| 30 | import { blockedFlash } from "../blocked.ts"; | |
| 31 | import { field, readForm } from "../form.ts"; | |
| 32 | import { html, type Html } from "../html.ts"; | |
| 33 | import { flashTo } from "../layout.ts"; | |
| 34 | import { badge, btn, confirmAction, row, rowList } from "../ui.ts"; | |
| 35 | ||
| 36 | const BACK = "/settings/model"; | |
| 37 | ||
| 38 | /** One connection: what it is and who pays on one line, its last test as a fact, Test and Remove. */ | |
| 39 | function connectionRow(c: Connection, user: User): Html { | |
| 40 | const may = c.id !== PLATFORM && (c.scope === "yours" || user.isAdmin); | |
| 41 | const tone = | |
| 42 | c.working === undefined | |
| 43 | ? undefined | |
| 44 | : c.working | |
| 45 | ? ("success" as const) | |
| 46 | : ("danger" as const); | |
| 47 | return row({ | |
| 48 | title: c.name, | |
| 49 | meta: html`${[protocolWords(c.protocol), detailsFor(c, user)?.base ?? "on the forge", payerWords(c), ...(c.effort === "" ? [] : [`effort ${c.effort}`]), ...(c.models.length === 0 ? [] : [`${String(c.models.length)} models`])].join(" · ")}`, | |
| 50 | ...((detailsFor(c, user)?.said ?? "") === "" ? {} : { facts: [{ label: "Last test", value: html`${detailsFor(c, user)!.said}` }] }), | |
| 51 | trail: html`${badge( | |
| 52 | statusWords(c), | |
| 53 | tone === undefined ? {} : { tone }, | |
| 54 | )}${may && c.base !== null | |
| 55 | ? html` <form | |
| 56 | method="post" | |
| 57 | action="${BACK}/connections/${c.id}/test" | |
| 58 | class="inline" | |
| 59 | > | |
| 60 | ${btn("Test", { | |
| 61 | size: "sm", | |
| 62 | variant: "ghost", | |
| 63 | label: `Test ${c.name}`, | |
| 64 | })} | |
| 65 | </form> | |
| 66 | ${confirmAction({ | |
| 67 | action: `${BACK}/connections/${c.id}/remove`, | |
| 68 | verb: "Remove", | |
| 69 | size: "sm", | |
| 70 | label: `Remove ${c.name}`, | |
| 71 | })}` | |
| 72 | : null}`, | |
| 73 | }); | |
| 74 | } | |
| 75 | ||
| 76 | /** The list and the add form, for the Connect your AI page. */ | |
| 77 | export function connectionsBlock(ctx: Ctx, user: User): Html { | |
| 78 | const all = listConnections(ctx.app.db, user.id); | |
| 79 | return html`<section class="settings-block" id="connections"> | |
| 80 | <h2>Connections</h2> | |
| 81 | <p class="muted"> | |
| 82 | Every model you can use, yours and the forge's. A connection is tested | |
| 83 | before it is saved, its key sealed and sent only to its own address; your | |
| 84 | own reach ${OWN_HOSTS.join(", ")} from this forge. | |
| 85 | </p> | |
| 86 | ${rowList(all.map((c) => connectionRow(c, user)), { bare: true })} | |
| 87 | <form class="stack" method="post" action="${BACK}/connections"> | |
| 88 | <h3>Add a connection</h3> | |
| 89 | <div class="field"> | |
| 90 | <label for="c-preset">Kind</label> | |
| 91 | <select class="input" id="c-preset" name="preset"> | |
| 92 | ${CONNECTION_PRESETS.map( | |
| 93 | (p) => | |
| 94 | html`<option value="${p.id}" data-base="${p.base}"> | |
| 95 | ${p.label}${p.local === true | |
| 96 | ? " (the forge's own network)" | |
| 97 | : ""} | |
| 98 | </option>`, | |
| 99 | )} | |
| 100 | <option value="other">${OTHER_KIND}</option> | |
| 101 | </select> | |
| 102 | </div> | |
| 103 | <div class="field"> | |
| 104 | <label for="c-name">Name</label | |
| 105 | ><input | |
| 106 | class="input" | |
| 107 | id="c-name" | |
| 108 | name="name" | |
| 109 | required | |
| 110 | maxlength="40" | |
| 111 | autocomplete="off" | |
| 112 | placeholder="OpenRouter" | |
| 113 | /> | |
| 114 | </div> | |
| 115 | <div class="field"> | |
| 116 | <label for="c-base">Base URL</label | |
| 117 | ><input | |
| 118 | class="input" | |
| 119 | id="c-base" | |
| 120 | name="base" | |
| 121 | type="url" | |
| 122 | maxlength="200" | |
| 123 | autocomplete="off" | |
| 124 | spellcheck="false" | |
| 125 | placeholder="empty: the kind's own" | |
| 126 | /> | |
| 127 | </div> | |
| 128 | <div class="field"> | |
| 129 | <label for="c-key">Key</label | |
| 130 | ><input | |
| 131 | class="input" | |
| 132 | id="c-key" | |
| 133 | name="key" | |
| 134 | type="password" | |
| 135 | autocomplete="off" | |
| 136 | spellcheck="false" | |
| 137 | /> | |
| 138 | </div> | |
| 139 | <div class="field"> | |
| 140 | <label for="c-effort">Reasoning effort</label> | |
| 141 | <select class="input" id="c-effort" name="effort"> | |
| 142 | <option value="">Not asked</option> | |
| 143 | ${EFFORTS.map((e) => html`<option value="${e}">${e}</option>`)} | |
| 144 | </select> | |
| 145 | </div> | |
| 146 | ${user.isAdmin | |
| 147 | ? html`<label class="check" | |
| 148 | ><input type="checkbox" name="forge" value="1" /> The forge's own: | |
| 149 | for everyone the forge grants it to, on its credit and budgets; may | |
| 150 | be on this machine or network</label | |
| 151 | >` | |
| 152 | : null} | |
| 153 | <div>${btn("Test and save", { variant: "primary", size: "sm" })}</div> | |
| 154 | </form> | |
| 155 | </section>`; | |
| 156 | } | |
| 157 | ||
| 158 | // POST /settings/model/connections | |
| 159 | export async function connectionAdd(ctx: Ctx): Promise<Response> { | |
| 160 | const user = ctx.auth.user; | |
| 161 | if (user === undefined) return notFoundPage(ctx); | |
| 162 | const form = await readForm(ctx, "admin"); | |
| 163 | if (form instanceof Response) return form; | |
| 164 | const preset = CONNECTION_PRESETS.find((p) => p.id === field(form, "preset")); | |
| 165 | const added = await addConnection(ctx.app, user, { | |
| 166 | name: field(form, "name"), | |
| 167 | protocol: preset?.protocol ?? OTHER_PROTOCOL, | |
| 168 | base: | |
| 169 | field(form, "base").trim() === "" | |
| 170 | ? (preset?.base ?? "") | |
| 171 | : field(form, "base"), | |
| 172 | key: field(form, "key"), | |
| 173 | scope: field(form, "forge") === "1" ? "forge" : "yours", | |
| 174 | effort: effortOf(field(form, "effort")) ?? "", | |
| 175 | }); | |
| 176 | // Refused by the forge's own egress gate: which hosts it reaches, and the ask to allow this one. | |
| 177 | if (!added.ok && added.error === "host_refused") return flashTo(ctx, BACK, blockedFlash(modelHostBlocked(ctx.app, user, added.host), "danger")); | |
| 178 | if (added.ok) | |
| 179 | return flashTo(ctx, BACK, { | |
| 180 | message: `${added.value.connection.name} is connected: ${added.value.test.said}.`, | |
| 181 | }); | |
| 182 | return flashTo(ctx, BACK, { | |
| 183 | tone: "danger", | |
| 184 | message: | |
| 185 | added.error === "not_working" | |
| 186 | ? `Nothing was saved: ${added.said}` | |
| 187 | : (CONNECTION_REFUSED[added.error] ?? added.error), | |
| 188 | }); | |
| 189 | } | |
| 190 | ||
| 191 | // POST /settings/model/connections/:id/test | |
| 192 | export async function connectionRetest(ctx: Ctx): Promise<Response> { | |
| 193 | const user = ctx.auth.user; | |
| 194 | if (user === undefined) return notFoundPage(ctx); | |
| 195 | const form = await readForm(ctx, "admin"); | |
| 196 | if (form instanceof Response) return form; | |
| 197 | const c = connectionFor(ctx.app.db, user.id, ctx.params["id"] ?? ""); | |
| 198 | if (c === undefined || (c.scope === "forge" && !user.isAdmin)) | |
| 199 | return notFoundPage(ctx); | |
| 200 | const test = await retestConnection(ctx.app, user, c.id); | |
| 201 | if (test === "busy") return flashTo(ctx, BACK, { tone: "danger", message: CONNECTION_REFUSED["busy"]! }); | |
| 202 | if (test?.refusedHost !== undefined) return flashTo(ctx, BACK, blockedFlash(modelHostBlocked(ctx.app, user, test.refusedHost), "danger")); | |
| 203 | return flashTo( | |
| 204 | ctx, | |
| 205 | BACK, | |
| 206 | test === undefined | |
| 207 | ? { tone: "danger", message: "It could not be tested." } | |
| 208 | : test.working | |
| 209 | ? { message: `${c.name}: ${test.said}.` } | |
| 210 | : { tone: "danger", message: `${c.name}: ${test.said}` }, | |
| 211 | ); | |
| 212 | } | |
| 213 | ||
| 214 | // POST /settings/model/connections/:id/remove (from the confirm page, with its name typed) | |
| 215 | export async function connectionRemove(ctx: Ctx): Promise<Response> { | |
| 216 | const user = ctx.auth.user; | |
| 217 | if (user === undefined) return notFoundPage(ctx); | |
| 218 | const form = await readForm(ctx, "admin"); | |
| 219 | if (form instanceof Response) return form; | |
| 220 | const c = connectionFor(ctx.app.db, user.id, ctx.params["id"] ?? ""); | |
| 221 | if (c === undefined) return notFoundPage(ctx); | |
| 222 | if (field(form, "confirm") !== c.name) | |
| 223 | return flashTo(ctx, BACK, { | |
| 224 | tone: "danger", | |
| 225 | message: `Type ${c.name} exactly to remove it. Nothing was removed.`, | |
| 226 | }); | |
| 227 | return removeConnection(ctx.app.db, user, c.id) | |
| 228 | ? flashTo(ctx, BACK, { | |
| 229 | message: `${c.name} is removed; its key is gone from this forge.`, | |
| 230 | }) | |
| 231 | : notFoundPage(ctx); | |
| 232 | } | |
| 233 | ||
| 234 | /** The confirm page's words for removing a connection: its name, typed. */ | |
| 235 | export function removeWords( | |
| 236 | ctx: Ctx, | |
| 237 | connectionId: string, | |
| 238 | ): { verb: string; title: string; detail: string; phrase: string } | undefined { | |
| 239 | const user = ctx.auth.user; | |
| 240 | const c = | |
| 241 | user === undefined | |
| 242 | ? undefined | |
| 243 | : connectionFor(ctx.app.db, user.id, connectionId); | |
| 244 | return c === undefined | |
| 245 | ? undefined | |
| 246 | : { | |
| 247 | verb: "Remove", | |
| 248 | title: `Remove ${c.name}?`, | |
| 249 | detail: | |
| 250 | "Its sealed key is deleted from this forge, and Talk and the crew stop using its models.", | |
| 251 | phrase: c.name, | |
| 252 | }; | |
| 253 | } |
src/web/pages/model.ts +3 −1
| @@ -29,6 +29,7 @@ import { html, type Html } from "../html.ts"; | ||
| 29 | 29 | import { flashTo, page } from "../layout.ts"; |
| 30 | 30 | import { btn, row } from "../ui.ts"; |
| 31 | 31 | import { accountOnly, accountSections } from "./origins.ts"; |
| 32 | import { connectionsBlock } from "./connections.ts"; | |
| 32 | 33 | |
| 33 | 34 | // GET /settings/model |
| 34 | 35 | export function modelPage(ctx: Ctx): Response { |
| @@ -78,7 +79,8 @@ export function modelPage(ctx: Ctx): Response { | ||
| 78 | 79 | meta: html`${budget}`, |
| 79 | 80 | })}</ul>`} |
| 80 | 81 | ${form} |
| 81 | </section>`, | |
| 82 | </section> | |
| 83 | ${connectionsBlock(ctx, user)}`, | |
| 82 | 84 | "Account settings", |
| 83 | 85 | )}`, |
| 84 | 86 | }); |
src/web/pages/search.ts +6
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | * that was never meant to be confirmed. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { removeWords } from "./connections.ts"; | |
| 13 | 14 | import { ARCHIVE_DETAIL, RESTORE_DETAIL, archiveTitle, restoreTitle } from "../../core/archive-words.ts"; |
| 14 | 15 | import { cappedQuery, echoed, queryTooLong, QUERY_TRIMMED_NOTE } from "../../core/query_limit.ts"; |
| 15 | 16 | import { returnTo, withReturn } from "../return_to.ts"; |
| @@ -607,6 +608,11 @@ const DESTRUCTIVE: { | ||
| 607 | 608 | pattern: RegExp; |
| 608 | 609 | describe: (m: RegExpMatchArray, ctx: Ctx) => Destructive; |
| 609 | 610 | }[] = [ |
| 611 | { | |
| 612 | // A connection on Connect your AI: its name, typed back (`pages/connections.ts`). | |
| 613 | pattern: /^\/settings\/model\/connections\/([0-9a-z]+)\/remove$/, | |
| 614 | describe: (m, ctx) => removeWords(ctx, m[1] ?? "") ?? { verb: "Remove", title: "Remove this connection?", detail: "It is not one you may remove.", phrase: "remove" }, | |
| 615 | }, | |
| 610 | 616 | { |
| 611 | 617 | pattern: /^\/([^/]+)\/([^/]+)\/offers\/(\d+)\/withdraw$/, |
| 612 | 618 | describe: (m) => ({ |
src/web/ui.ts +11 −6
| @@ -952,14 +952,19 @@ export function messageText(text: string): Html { | ||
| 952 | 952 | return html`<div class="prose" data-text="message"><pre>${text}</pre></div>`; |
| 953 | 953 | } |
| 954 | 954 | |
| 955 | /** | |
| 956 | * The one list of rows: in a card (`listCard`), or bare on a settings page, read as lines | |
| 957 | * (principle 7), when `bare` is set. | |
| 958 | */ | |
| 959 | export function rowList(rows: Html[], o: { bind?: string | undefined; more?: number | undefined; bare?: boolean } = {}): Html { | |
| 960 | return html`<ul class="list${o.bare === true ? " setting-list" : ""}"${listAttr(o.bind, o.more)}> | |
| 961 | ${rows} | |
| 962 | </ul>`; | |
| 963 | } | |
| 964 | ||
| 955 | 965 | /** A card wrapping a `<ul class="list">` — the shape every listing takes. */ |
| 956 | 966 | export function listCard(rows: Html[], o: CardOptions = {}): Html { |
| 957 | return card( | |
| 958 | html`<ul class="list"${listAttr(o.bind, o.more)}> | |
| 959 | ${rows} | |
| 960 | </ul>`, | |
| 961 | { ...o, pad: false }, | |
| 962 | ); | |
| 967 | return card(rowList(rows, { bind: o.bind, more: o.more }), { ...o, pad: false }); | |
| 963 | 968 | } |
| 964 | 969 | |
| 965 | 970 | export interface DisclosureOptions { |
test/ask-admin.test.ts +2 −2
| @@ -40,8 +40,8 @@ const who = (name: "admin" | "member" | "newcomer" | "agent") => | ||
| 40 | 40 | world.viewers[name].user!; |
| 41 | 41 | |
| 42 | 42 | /** A subject each want can be asked with on the seeded forge. */ |
| 43 | const subjectFor = (kind: "none" | "account" | "repo"): string => | |
| 44 | kind === "none" ? "" : kind === "account" ? "bob" : "bob/notes 10.0.0.5:5432"; | |
| 43 | const subjectFor = (kind: "none" | "account" | "repo" | "host"): string => | |
| 44 | kind === "none" ? "" : kind === "account" ? "bob" : kind === "host" ? "models.example.com" : "bob/notes 10.0.0.5:5432"; | |
| 45 | 45 | |
| 46 | 46 | test("for a reader who can change it, every control is a page they can open that holds the field the link names", async () => { |
| 47 | 47 | const missing: string[] = []; |
test/connections.test.ts added +446
| @@ -0,0 +1,446 @@ | ||
| 1 | /** | |
| 2 | * Connections (Connect your AI), against a canned OpenAI-compatible server: tested before saved, | |
| 3 | * the test bounded and kept only as words and models; who pays follows whose it is; a person's own | |
| 4 | * connection reaches only public https through the outbound guard, while a private address is for | |
| 5 | * the forge's own, added by an admin; a key never follows a redirect; the list shows a person their | |
| 6 | * own and the forge's, never another person's; removing takes the name typed; and a subscription | |
| 7 | * from before connections is the same Anthropic connection it was. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { | |
| 14 | addConnection, | |
| 15 | PROBE_PAD_CHARS, | |
| 16 | PROBE_TOKENS, | |
| 17 | retestConnection, | |
| 18 | testConnection, | |
| 19 | } from "../src/actions/connections.ts"; | |
| 20 | import { createApp, type App } from "../src/app.ts"; | |
| 21 | import { | |
| 22 | listConnections, | |
| 23 | parseConnectionBase, | |
| 24 | OWN_HOSTS, | |
| 25 | payerWords, | |
| 26 | removeConnection, | |
| 27 | saveConnection, | |
| 28 | } from "../src/core/connections.ts"; | |
| 29 | import { | |
| 30 | accountCredential, | |
| 31 | EVERYONE, | |
| 32 | setGrants, | |
| 33 | addSubscription, | |
| 34 | pickSubscription, | |
| 35 | PLATFORM, | |
| 36 | } from "../src/core/subscriptions.ts"; | |
| 37 | import { ownSubscription } from "../src/core/model_grant.ts"; | |
| 38 | import { modelHostBlocked } from "../src/actions/blocked_words.ts"; | |
| 39 | import { blockedText } from "../src/kernel/blocked.ts"; | |
| 40 | import { createSession } from "../src/core/sessions.ts"; | |
| 41 | import { createUser, type User } from "../src/core/users.ts"; | |
| 42 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 43 | import { promote } from "./helpers/members.ts"; | |
| 44 | ||
| 45 | let dir: string; | |
| 46 | let app: App; | |
| 47 | let servers: Servers; | |
| 48 | let admin: User; | |
| 49 | let bob: User; | |
| 50 | let carol: User; | |
| 51 | const heard: { | |
| 52 | path: string; | |
| 53 | auth: string | null; | |
| 54 | body: Record<string, unknown> | undefined; | |
| 55 | }[] = []; | |
| 56 | let canned: ReturnType<typeof Bun.serve>; | |
| 57 | let elsewhere: ReturnType<typeof Bun.serve>; | |
| 58 | let elsewhereHits = 0; | |
| 59 | ||
| 60 | beforeAll(async () => { | |
| 61 | // A canned OpenAI-compatible server: two models (one priced as OpenRouter lists it), a one-token | |
| 62 | // reply, and a tool call when asked with tools. `/moved/` answers every call with a redirect. | |
| 63 | elsewhere = Bun.serve({ | |
| 64 | port: 0, | |
| 65 | hostname: "127.0.0.1", | |
| 66 | fetch: () => { | |
| 67 | elsewhereHits++; | |
| 68 | return new Response("{}"); | |
| 69 | }, | |
| 70 | }); | |
| 71 | canned = Bun.serve({ | |
| 72 | port: 0, | |
| 73 | hostname: "127.0.0.1", | |
| 74 | async fetch(req) { | |
| 75 | const url = new URL(req.url); | |
| 76 | const body = | |
| 77 | req.method === "POST" | |
| 78 | ? ((await req.json()) as Record<string, unknown>) | |
| 79 | : undefined; | |
| 80 | heard.push({ | |
| 81 | path: url.pathname, | |
| 82 | auth: req.headers.get("authorization"), | |
| 83 | body, | |
| 84 | }); | |
| 85 | // `/cut/`: a server that keeps a small context, reading 100 tokens of any prompt with tools. | |
| 86 | if (url.pathname === "/cut/v1/models") return Response.json({ data: [{ id: "qwen3:4b" }] }); | |
| 87 | if (url.pathname === "/cut/v1/chat/completions") | |
| 88 | return Response.json({ choices: [{ message: { role: "assistant", content: "ok" } }], usage: { prompt_tokens: body?.["tools"] === undefined ? 12 : 100, completion_tokens: 1 } }); | |
| 89 | if (url.pathname.startsWith("/moved/")) | |
| 90 | return new Response(null, { | |
| 91 | status: 302, | |
| 92 | headers: { | |
| 93 | location: `http://127.0.0.1:${String(elsewhere.port)}/v1/models`, | |
| 94 | }, | |
| 95 | }); | |
| 96 | if (url.pathname === "/v1/models") | |
| 97 | return Response.json({ | |
| 98 | data: [ | |
| 99 | { | |
| 100 | id: "canned/small", | |
| 101 | pricing: { prompt: "0.0000002", completion: "0.0000008" }, | |
| 102 | }, | |
| 103 | { id: "canned/large" }, | |
| 104 | ], | |
| 105 | }); | |
| 106 | if (url.pathname === "/v1/chat/completions") | |
| 107 | return Response.json( | |
| 108 | body?.["tools"] !== undefined | |
| 109 | ? { | |
| 110 | choices: [ | |
| 111 | { | |
| 112 | message: { | |
| 113 | role: "assistant", | |
| 114 | tool_calls: [ | |
| 115 | { | |
| 116 | id: "c1", | |
| 117 | type: "function", | |
| 118 | function: { name: "ping", arguments: "{}" }, | |
| 119 | }, | |
| 120 | ], | |
| 121 | }, | |
| 122 | }, | |
| 123 | ], | |
| 124 | } | |
| 125 | : { choices: [{ message: { role: "assistant", content: "ok" } }] }, | |
| 126 | ); | |
| 127 | return new Response("not here", { status: 404 }); | |
| 128 | }, | |
| 129 | }); | |
| 130 | dir = await mkdtemp(join(tmpdir(), "forge-connections-")); | |
| 131 | app = createApp({ dataDir: dir, port: 0 }); | |
| 132 | servers = await serve(app); | |
| 133 | const person = async (username: string, first = false) => { | |
| 134 | const made = await createUser(app.db, { | |
| 135 | origin: "seed", | |
| 136 | trusted: true, | |
| 137 | username, | |
| 138 | email: `${username}@forge.local`, | |
| 139 | password: "a-good-passphrase", | |
| 140 | adminIfFirst: first, | |
| 141 | }); | |
| 142 | if (!made.ok) throw new Error(made.error); | |
| 143 | promote(app.db, made.value); | |
| 144 | return made.value; | |
| 145 | }; | |
| 146 | admin = await person("keeper", true); | |
| 147 | bob = await person("bob"); | |
| 148 | carol = await person("carol"); | |
| 149 | }); | |
| 150 | afterAll(async () => { | |
| 151 | canned.stop(true); | |
| 152 | elsewhere.stop(true); | |
| 153 | servers.stop(); | |
| 154 | app.close(); | |
| 155 | await rm(dir, { recursive: true, force: true }); | |
| 156 | }); | |
| 157 | ||
| 158 | const base = () => `http://127.0.0.1:${String(canned.port)}/v1`; | |
| 159 | /** The guard as a test may loosen it: plain http and loopback allowed, nothing else changed. */ | |
| 160 | const loopback = { plain: true, allow: ["127.0.0.1"] }; | |
| 161 | ||
| 162 | describe("adding", () => { | |
| 163 | test("the forge's own, on this machine: tested (models, one token, a tool), then saved; the forge's credit pays", async () => { | |
| 164 | const before = heard.length; | |
| 165 | const added = await addConnection(app, admin, { | |
| 166 | name: "Spark", | |
| 167 | protocol: "openai", | |
| 168 | base: base(), | |
| 169 | key: "", | |
| 170 | scope: "forge", | |
| 171 | }); | |
| 172 | if (!added.ok) throw new Error(added.error); | |
| 173 | expect(added.value.test.said).toMatch( | |
| 174 | /^2 models listed · a one-token reply in [\d.]+ s · called a tool$/, | |
| 175 | ); | |
| 176 | const c = added.value.connection; | |
| 177 | expect([c.scope, c.privateOk, c.models.map((m) => m.id)]).toEqual([ | |
| 178 | "forge", | |
| 179 | true, | |
| 180 | ["canned/small", "canned/large"], | |
| 181 | ]); | |
| 182 | expect(c.models[0]).toEqual({ | |
| 183 | id: "canned/small", | |
| 184 | inUsd: 0.2, | |
| 185 | outUsd: 0.8, | |
| 186 | }); | |
| 187 | expect(payerWords(c)).toBe("the forge's credit and budgets"); | |
| 188 | // Bounded: the ping asks for one token, the probe at most PROBE_TOKENS; nothing of either is kept. | |
| 189 | const asked = heard | |
| 190 | .slice(before) | |
| 191 | .filter((h) => h.path === "/v1/chat/completions") | |
| 192 | .map((h) => h.body?.["max_tokens"]); | |
| 193 | expect(asked).toEqual([1, PROBE_TOKENS]); | |
| 194 | const row = app.db | |
| 195 | .query< | |
| 196 | Record<string, unknown>, | |
| 197 | [string] | |
| 198 | >("SELECT * FROM subscription WHERE id = ?1") | |
| 199 | .get(c.id)!; | |
| 200 | expect(JSON.stringify(row)).not.toContain("Reply with ok"); | |
| 201 | expect(JSON.stringify(row)).not.toContain("tool_calls"); | |
| 202 | }); | |
| 203 | ||
| 204 | test("a person's own: never a private address, nor a public name that resolves to one; nothing reaches the server", async () => { | |
| 205 | const before = heard.length; | |
| 206 | expect(parseConnectionBase("http://127.0.0.1:11434/v1", false)).toEqual({ | |
| 207 | ok: false, | |
| 208 | error: "private_base", | |
| 209 | }); | |
| 210 | expect(parseConnectionBase("https://spark.local/v1", false)).toEqual({ | |
| 211 | ok: false, | |
| 212 | error: "private_base", | |
| 213 | }); | |
| 214 | expect(parseConnectionBase("http://127.0.0.1:11434/v1", true)).toEqual({ | |
| 215 | ok: true, | |
| 216 | value: "http://127.0.0.1:11434/v1", | |
| 217 | }); | |
| 218 | const own = await addConnection(app, bob, { | |
| 219 | name: "Mine", | |
| 220 | protocol: "openai", | |
| 221 | base: base(), | |
| 222 | key: "sk-bob", | |
| 223 | scope: "yours", | |
| 224 | }); | |
| 225 | expect(own).toEqual({ ok: false, error: "private_base" }); | |
| 226 | const sneaky = await addConnection( | |
| 227 | app, | |
| 228 | bob, | |
| 229 | { | |
| 230 | name: "Sneaky", | |
| 231 | protocol: "openai", | |
| 232 | base: "https://models.example.com/v1", | |
| 233 | key: "sk-bob", | |
| 234 | scope: "yours", | |
| 235 | }, | |
| 236 | { resolve: async () => ["10.0.0.5"] }, | |
| 237 | ); | |
| 238 | expect(sneaky).toMatchObject({ ok: false, error: "not_working" }); | |
| 239 | expect(heard.length).toBe(before); | |
| 240 | expect(listConnections(app.db, bob.id).map((c) => c.name)).not.toContain( | |
| 241 | "Sneaky", | |
| 242 | ); | |
| 243 | // Only an admin adds the forge's. | |
| 244 | expect( | |
| 245 | await addConnection(app, bob, { | |
| 246 | name: "Spark2", | |
| 247 | protocol: "openai", | |
| 248 | base: base(), | |
| 249 | key: "", | |
| 250 | scope: "forge", | |
| 251 | }), | |
| 252 | ).toEqual({ ok: false, error: "forbidden" }); | |
| 253 | }); | |
| 254 | ||
| 255 | test("a person's own goes through the guard: the key reaches the vetted host, and the crew never spends it as the forge's", async () => { | |
| 256 | const before = heard.length; | |
| 257 | // The guard, loosened as a test may (plain http, this loopback address), still does the call. | |
| 258 | const test = await testConnection({ protocol: "openai", base: base(), key: "sk-bob", privateOk: false }, loopback); | |
| 259 | expect(test.working).toBe(true); | |
| 260 | expect(heard.slice(before).map((h) => h.auth)).toEqual(["Bearer sk-bob", "Bearer sk-bob", "Bearer sk-bob"]); | |
| 261 | // Without that loosening the same call is refused before anything is sent. | |
| 262 | const refused = await testConnection({ protocol: "openai", base: base(), key: "sk-bob", privateOk: false }); | |
| 263 | expect(refused.working).toBe(false); | |
| 264 | expect(heard.length).toBe(before + 3); | |
| 265 | // Saved as bob's own: listed to bob with "spends your key"; a crew run on bob's repositories still | |
| 266 | // finds no Anthropic account to spend (never the forge's credit), and bob's own subscription line is unchanged. | |
| 267 | const mine = saveConnection(app.db, app.config.dataDir, { name: "Bobs", protocol: "openai", base: "https://bobs.example.com/v1", key: "sk-bob", scope: "yours", userId: bob.id, models: [{ id: "m" }], said: "1 models listed" }); | |
| 268 | if (!mine.ok) throw new Error(mine.error); | |
| 269 | expect([mine.value.scope, payerWords(mine.value)]).toEqual(["yours", "spends your key, never the forge's credit"]); | |
| 270 | expect(pickSubscription(app.db, app.config.dataDir, { repoId: "r", ownerId: bob.id, agentId: "a" }, new Date())).toEqual({ kind: "none" }); | |
| 271 | expect(ownSubscription(app.db, bob.id)).toBeUndefined(); | |
| 272 | }); | |
| 273 | ||
| 274 | test("a key goes only to the host it was saved for: a redirect is not followed", async () => { | |
| 275 | const hits = elsewhereHits; | |
| 276 | const moved = await addConnection(app, admin, { | |
| 277 | name: "Moved", | |
| 278 | protocol: "openai", | |
| 279 | base: `http://127.0.0.1:${String(canned.port)}/moved/v1`, | |
| 280 | key: "sk-forge", | |
| 281 | scope: "forge", | |
| 282 | }); | |
| 283 | expect(moved).toMatchObject({ ok: false, error: "not_working", said: "It did not answer: it answered with a redirect; the key was not sent on." }); | |
| 284 | expect(elsewhereHits).toBe(hits); | |
| 285 | }); | |
| 286 | }); | |
| 287 | ||
| 288 | describe("the forge's egress gate", () => { | |
| 289 | test("every preset host a person's own connection may use is declared in forge.json egress", async () => { | |
| 290 | const egress = ((await Bun.file("forge.json").json()) as { egress: string[] }).egress; | |
| 291 | expect(OWN_HOSTS).toEqual(["openrouter.ai", "api.openai.com", "api.anthropic.com"]); | |
| 292 | expect(OWN_HOSTS.filter((h) => !egress.includes(h))).toEqual([]); | |
| 293 | }); | |
| 294 | ||
| 295 | test("a host the gate refuses is said before anything is saved: the hosts it reaches, and the ask to allow this one", async () => { | |
| 296 | // A stand-in for the cell's gate: every CONNECT refused as the real one refuses it. | |
| 297 | const words = "refused by this forge: models.example.com:443 is not in this app's forge.json egress"; | |
| 298 | const gate = Bun.listen<undefined>({ | |
| 299 | hostname: "127.0.0.1", | |
| 300 | port: 0, | |
| 301 | socket: { data: (s) => void s.end(`HTTP/1.1 403 ${words}\r\nX-Forge-Egress: refused\r\nContent-Length: ${String(words.length)}\r\n\r\n${words}`), open() {}, close() {} }, | |
| 302 | }); | |
| 303 | try { | |
| 304 | const added = await addConnection(app, bob, { name: "Elsewhere", protocol: "openai", base: "https://models.example.com/v1", key: "sk-bob", scope: "yours" }, { proxy: `http://127.0.0.1:${String(gate.port)}` }); | |
| 305 | expect(added).toEqual({ ok: false, error: "host_refused", host: "models.example.com" }); | |
| 306 | expect(listConnections(app.db, bob.id).some((c) => c.name === "Elsewhere")).toBe(false); | |
| 307 | const way = modelHostBlocked(app, bob, "models.example.com"); | |
| 308 | expect(blockedText(way)).toStartWith("This forge can reach openrouter.ai, api.openai.com and api.anthropic.com for your own connections, not models.example.com."); | |
| 309 | expect(way.ask).toMatchObject({ body: { want: "model_host", subject: "models.example.com" } }); | |
| 310 | // An admin is shown the control instead. | |
| 311 | expect(modelHostBlocked(app, admin, "models.example.com").link?.href).toBe("/settings/model#connections"); | |
| 312 | } finally { | |
| 313 | gate.stop(true); | |
| 314 | } | |
| 315 | }); | |
| 316 | }); | |
| 317 | ||
| 318 | describe("the probe as Talk will be asked", () => { | |
| 319 | test("on the forge's own network the probe's prompt is long: a server that reads under half of it is said, and nothing is saved", async () => { | |
| 320 | const cut = await addConnection(app, admin, { name: "Small", protocol: "openai", base: `http://127.0.0.1:${String(canned.port)}/cut/v1`, key: "", scope: "forge" }); | |
| 321 | expect(cut).toMatchObject({ ok: false, error: "not_working" }); | |
| 322 | expect("said" in cut ? cut.said : "").toMatch(/^1 models listed, but the model's endpoint read 100 tokens of a prompt of about [\d,]+, so it answered without part of it\. Give the model a context of 32,768 tokens or more/); | |
| 323 | expect(listConnections(app.db, admin.id).some((c) => c.name === "Small")).toBe(false); | |
| 324 | }); | |
| 325 | ||
| 326 | test("a reasoning effort is kept with the connection and sent with each call of its test", async () => { | |
| 327 | const before = heard.length; | |
| 328 | const added = await addConnection(app, admin, { name: "Spark low", protocol: "openai", base: base(), key: "", scope: "forge", effort: "low" }); | |
| 329 | if (!added.ok) throw new Error(added.error); | |
| 330 | expect(added.value.connection.effort).toBe("low"); | |
| 331 | expect(heard.slice(before).filter((h) => h.path === "/v1/chat/completions").map((h) => h.body?.["reasoning_effort"])).toEqual(["low", "low"]); | |
| 332 | // On the forge's own network the probe carries the long prompt (one on the internet a short one). | |
| 333 | const asked = heard.slice(before).filter((h) => h.path === "/v1/chat/completions").at(-1)!; | |
| 334 | expect(JSON.stringify(asked.body).length).toBeGreaterThan(PROBE_PAD_CHARS); | |
| 335 | expect(removeConnection(app.db, admin, added.value.connection.id)).toBe(true); | |
| 336 | }); | |
| 337 | }); | |
| 338 | ||
| 339 | describe("the list, a test again, and removing", () => { | |
| 340 | test("a person sees their own and the forge's; a test again keeps only its words; removing takes the name typed", async () => { | |
| 341 | const mine = { value: listConnections(app.db, bob.id).find((c) => c.name === "Bobs")! }; | |
| 342 | const names = (u: User) => listConnections(app.db, u.id).map((c) => `${c.name}:${c.scope}`); | |
| 343 | // Theirs first, then the forge's; another person's own is never listed, not even as the forge's. | |
| 344 | expect(names(bob)).toEqual(["Bobs:yours", "The forge's own:forge", "Spark:forge"]); | |
| 345 | expect(names(carol)).toEqual(["The forge's own:forge", "Spark:forge"]); | |
| 346 | // A test again of the forge's. | |
| 347 | const spark = listConnections(app.db, admin.id).find( | |
| 348 | (c) => c.name === "Spark", | |
| 349 | )!; | |
| 350 | const again = await retestConnection(app, admin, spark.id); | |
| 351 | expect(again !== undefined && again !== "busy" && again.working).toBe(true); | |
| 352 | // The forge's own is tested again by an admin alone. | |
| 353 | expect(await retestConnection(app, bob, spark.id)).toBeUndefined(); | |
| 354 | // The page: the row says whose and who pays; the confirm page asks for the name. | |
| 355 | const cookie = { | |
| 356 | cookie: `forge_session=${createSession(app.db, bob.id).token}`, | |
| 357 | }; | |
| 358 | const page = await ( | |
| 359 | await fetch(`${servers.url}/settings/model`, { headers: cookie }) | |
| 360 | ).text(); | |
| 361 | expect(page).toContain("spends your key, never the forge's credit"); | |
| 362 | expect(page).toContain("the forge's credit and budgets"); | |
| 363 | // The forge's own sits on its private network: bob reads its name, never its address or its test's words. | |
| 364 | expect(page).toContain("Spark"); | |
| 365 | expect(page).not.toContain(base()); | |
| 366 | expect(page).not.toContain("called a tool"); | |
| 367 | const confirm = await ( | |
| 368 | await fetch( | |
| 369 | `${servers.url}/-/confirm?to=${encodeURIComponent(`/settings/model/connections/${mine.value.id}/remove`)}`, | |
| 370 | { headers: cookie }, | |
| 371 | ) | |
| 372 | ).text(); | |
| 373 | expect(confirm).toContain("Type Bobs to continue"); | |
| 374 | const post = (who: User, name: string) => | |
| 375 | fetch( | |
| 376 | `${servers.url}/settings/model/connections/${mine.value.id}/remove`, | |
| 377 | { | |
| 378 | method: "POST", | |
| 379 | redirect: "manual", | |
| 380 | headers: { | |
| 381 | cookie: `forge_session=${createSession(app.db, who.id).token}`, | |
| 382 | origin: servers.url, | |
| 383 | "content-type": "application/x-www-form-urlencoded", | |
| 384 | }, | |
| 385 | body: new URLSearchParams({ confirm: name }), | |
| 386 | }, | |
| 387 | ); | |
| 388 | await post(bob, "bobs"); | |
| 389 | expect(names(bob)).toContain("Bobs:yours"); | |
| 390 | // Another person cannot reach it at all. | |
| 391 | const theirs = await post(carol, "Bobs"); | |
| 392 | expect(theirs.status).toBe(404); | |
| 393 | await post(bob, "Bobs"); | |
| 394 | expect(names(bob)).not.toContain("Bobs:yours"); | |
| 395 | }); | |
| 396 | }); | |
| 397 | ||
| 398 | describe("whose a connection is, and one test at a time", () => { | |
| 399 | test("a connection's scope is stored: the forge's stays the forge's when its admin grants it to their own repositories", async () => { | |
| 400 | const spark = listConnections(app.db, admin.id).find((c) => c.name === "Spark")!; | |
| 401 | setGrants(app.db, admin.id, EVERYONE, [spark.id]); | |
| 402 | expect(listConnections(app.db, admin.id).find((c) => c.id === spark.id)?.scope).toBe("forge"); | |
| 403 | const seen = listConnections(app.db, carol.id).find((c) => c.id === spark.id); | |
| 404 | expect([seen?.scope, seen === undefined ? "" : payerWords(seen)]).toEqual(["forge", "the forge's credit and budgets"]); | |
| 405 | setGrants(app.db, admin.id, EVERYONE, []); | |
| 406 | }); | |
| 407 | ||
| 408 | test("one person's tests run one at a time: a second while the first runs is refused at once, and the next after it goes", async () => { | |
| 409 | const input = { protocol: "openai" as const, base: base(), key: "", scope: "forge" as const }; | |
| 410 | const [first, second] = await Promise.all([addConnection(app, admin, { ...input, name: "Once" }), addConnection(app, admin, { ...input, name: "Twice" })]); | |
| 411 | expect(first.ok).toBe(true); | |
| 412 | expect(second).toEqual({ ok: false, error: "busy" }); | |
| 413 | // A test again holds an add too; once it ended, the next goes. | |
| 414 | const spark = listConnections(app.db, admin.id).find((c) => c.name === "Spark")!; | |
| 415 | const [mine, again] = await Promise.all([retestConnection(app, admin, spark.id), addConnection(app, admin, { ...input, name: "Twice" })]); | |
| 416 | expect(mine !== undefined && mine !== "busy" && mine.working).toBe(true); | |
| 417 | expect(again).toEqual({ ok: false, error: "busy" }); | |
| 418 | expect((await addConnection(app, admin, { ...input, name: "Twice" })).ok).toBe(true); | |
| 419 | for (const name of ["Once", "Twice"]) removeConnection(app.db, admin, listConnections(app.db, admin.id).find((c) => c.name === name)!.id); | |
| 420 | }); | |
| 421 | }); | |
| 422 | ||
| 423 | describe("before connections", () => { | |
| 424 | test("a subscription added the old way is the same Anthropic connection, and its run's credential is unchanged", () => { | |
| 425 | const old = addSubscription(app.db, app.config.dataDir, { | |
| 426 | name: "work", | |
| 427 | token: "sk-ant-api03-old", | |
| 428 | createdBy: admin.id, | |
| 429 | }); | |
| 430 | if (!old.ok) throw new Error(old.error); | |
| 431 | const c = listConnections(app.db, admin.id).find( | |
| 432 | (x) => x.id === old.value.id, | |
| 433 | ); | |
| 434 | expect([c?.protocol, c?.base, c?.working]).toEqual([ | |
| 435 | "anthropic", | |
| 436 | null, | |
| 437 | undefined, | |
| 438 | ]); | |
| 439 | expect(accountCredential(app.db, app.config.dataDir, old.value.id)).toEqual( | |
| 440 | { ANTHROPIC_API_KEY: "sk-ant-api03-old" }, | |
| 441 | ); | |
| 442 | expect( | |
| 443 | listConnections(app.db, admin.id).some((x) => x.id === PLATFORM), | |
| 444 | ).toBe(true); | |
| 445 | }); | |
| 446 | }); |
test/data-browser.test.ts +2
| @@ -60,6 +60,8 @@ const AUDITED_CLEAR: string[] = [ | ||
| 60 | 60 | // When a secret start was last written: a timestamp, not the value. |
| 61 | 61 | "secret_start.value_updated_at", |
| 62 | 62 | "subscription.resting_said", |
| 63 | // A connection's last test, in words: what answered, never a key (core/connections.ts). | |
| 64 | "subscription.test_said", | |
| 63 | 65 | "subscription_limit.said", |
| 64 | 66 | "user_key.blob", |
| 65 | 67 | "webhook_ping.payload", |
test/egress-literals.test.ts −1
| @@ -32,7 +32,6 @@ const NOT_CALLED: Record<string, string> = { | ||
| 32 | 32 | "git.open-platform.sh": "placeholder in the follow-upstream form", |
| 33 | 33 | "jsonfeed.org": "the JSON Feed version URI, a name and not a request", |
| 34 | 34 | "ntfy.sh": "placeholder in the account notification field", |
| 35 | "openrouter.ai": "example text for the model endpoint field; the endpoint itself is the admin's configuration", | |
| 36 | 35 | "schema.org": "the JSON-LD @context, a name and not a request", |
| 37 | 36 | "specification.website": "section links in release and preview reports", |
| 38 | 37 | "www.espodev.com": LINK, |
test/model-page-shape.test.ts +6 −2
| @@ -25,8 +25,12 @@ const signIn = async (username: string) => { | ||
| 25 | 25 | }); |
| 26 | 26 | return (r.headers.get("set-cookie") ?? "").split(";")[0]!; |
| 27 | 27 | }; |
| 28 | const get = async (cookie: string) => | |
| 29 | (await fetch(`${servers.url}/settings/model`, { headers: { cookie } })).text(); | |
| 28 | /** The budget block: the page up to its Connections block (`pages/connections.ts`), which lists its own rows. */ | |
| 29 | const get = async (cookie: string) => { | |
| 30 | const page = await (await fetch(`${servers.url}/settings/model`, { headers: { cookie } })).text(); | |
| 31 | expect(page).toContain("<h2>Connections</h2>"); | |
| 32 | return page.split("<section class=\"settings-block\" id=\"connections\">")[0]!; | |
| 33 | }; | |
| 30 | 34 | const noCard = (body: string) => expect(body).not.toMatch(/class="(?:[^"]*\s)?card(?:\s[^"]*)?"/); |
| 31 | 35 | const heading = /<section class="settings-block"[^>]*>\s*<h2>Your model budget<\/h2>/; |
| 32 | 36 |
test/outbound-guard.test.ts +8
| @@ -26,6 +26,7 @@ import { join } from "node:path"; | ||
| 26 | 26 | import { TLSSocket } from "node:tls"; |
| 27 | 27 | import { createApp, type App } from "../src/app.ts"; |
| 28 | 28 | import { vetClone } from "../src/actions/migrate.ts"; |
| 29 | import { testConnection } from "../src/actions/connections.ts"; | |
| 29 | 30 | import { probeCertificate } from "../src/apps/certificate.ts"; |
| 30 | 31 | import { statusOf } from "../src/apps/parity_probe.ts"; |
| 31 | 32 | import { createRepo } from "../src/core/repos.ts"; |
| @@ -107,6 +108,13 @@ let repoId = ""; | ||
| 107 | 108 | let hooks = 0; |
| 108 | 109 | |
| 109 | 110 | const SITES: readonly Site[] = [ |
| 111 | { | |
| 112 | file: "src/actions/connections.ts", | |
| 113 | what: "a person's own model connection, tested before it is saved", | |
| 114 | fetches: true, | |
| 115 | names: true, | |
| 116 | refused: async (t) => (await testConnection({ protocol: "openai", base: `https://${t.host}/v1`, key: "k", privateOk: false }, { resolve: t.resolve })).said.includes(REFUSED_SENTENCE), | |
| 117 | }, | |
| 110 | 118 | { |
| 111 | 119 | file: "src/core/web_page.ts", |
| 112 | 120 | what: "a page fetch_url reads for Talk or the terminal", |
test/outbound-sweep.test.ts +1
| @@ -42,6 +42,7 @@ const ALLOWED: Record<string, { count: number; why: string }> = { | ||
| 42 | 42 | "src/system/footing.ts": { count: 1, why: "the Kubernetes API from the pod's service account" }, |
| 43 | 43 | "src/cluster/jobs.ts": { count: 1, why: "the Kubernetes API from the pod's service account" }, |
| 44 | 44 | "src/crew/openai_runner.ts": { count: 1, why: "the model endpoint from operator configuration" }, |
| 45 | "src/actions/connections.ts": { count: 1, why: "a model server an admin added as the forge's own connection, on its private network by design; a person's own goes through outboundFetch" }, | |
| 45 | 46 | "src/crew/openai_mcp.ts": { count: 1, why: "only the turn's own --mcp-config server: the forge's own /mcp, on the local URL the forge itself wrote into that config (conversation.ts, mcpConfig)" }, |
| 46 | 47 | "src/crew/decide.ts": { count: 1, why: "the model endpoint from operator configuration" }, |
| 47 | 48 | "src/spawn/live.ts": { count: 1, why: "a child forge's own URL, minted by this forge" }, |
test/tui-connections.test.ts added +203
| @@ -0,0 +1,203 @@ | ||
| 1 | /** | |
| 2 | * Connections in the terminal, as on Connect your AI: an admin adds the forge's own on this | |
| 3 | * machine (tested against a canned OpenAI-compatible server, the key typed masked), tests it again | |
| 4 | * and removes it with its name typed exactly; a person's own on a private address is refused with | |
| 5 | * the page's words, and nothing is saved. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App as Forge } from "../src/app.ts"; | |
| 12 | import { listConnections } from "../src/core/connections.ts"; | |
| 13 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 14 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 15 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 16 | import type { TuiIdentity } from "../src/tui/session.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | import { settleApp, settleUntil } from "./helpers/tui.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | describe("connections in the terminal", () => { | |
| 23 | let dataDir: string; | |
| 24 | let forge: Forge; | |
| 25 | let canned: ReturnType<typeof Bun.serve>; | |
| 26 | ||
| 27 | function boot(username: string) { | |
| 28 | const terminal = headlessTerminal(160, 40); | |
| 29 | const user = getUserByName(forge.db, username)!; | |
| 30 | const identity: TuiIdentity = { | |
| 31 | sshUsername: "t", | |
| 32 | remoteAddress: "127.0.0.1", | |
| 33 | user, | |
| 34 | }; | |
| 35 | const { app } = createForgeApp(forge, identity, { | |
| 36 | terminal, | |
| 37 | exitHooks: false, | |
| 38 | }); | |
| 39 | app.start(); | |
| 40 | const key = (k: string) => | |
| 41 | app.dispatch({ | |
| 42 | type: "key", | |
| 43 | key: k, | |
| 44 | ctrl: false, | |
| 45 | alt: false, | |
| 46 | shift: false, | |
| 47 | }); | |
| 48 | return { | |
| 49 | text: () => app.screen.toText(), | |
| 50 | press: async (k: string) => { | |
| 51 | key(k); | |
| 52 | await settleApp(app); | |
| 53 | }, | |
| 54 | ctrl: async (k: string) => { | |
| 55 | app.dispatch({ | |
| 56 | type: "key", | |
| 57 | key: k, | |
| 58 | ctrl: true, | |
| 59 | alt: false, | |
| 60 | shift: false, | |
| 61 | }); | |
| 62 | await settleApp(app); | |
| 63 | }, | |
| 64 | type: async (t: string) => { | |
| 65 | for (const ch of t) key(ch); | |
| 66 | await settleApp(app); | |
| 67 | }, | |
| 68 | until: (what: string) => settleUntil(app, what, { timeoutMs: 4_000 }), | |
| 69 | stop: () => app.stop(), | |
| 70 | }; | |
| 71 | } | |
| 72 | ||
| 73 | beforeAll(async () => { | |
| 74 | canned = Bun.serve({ | |
| 75 | port: 0, | |
| 76 | hostname: "127.0.0.1", | |
| 77 | async fetch(req) { | |
| 78 | const path = new URL(req.url).pathname; | |
| 79 | if (path === "/v1/models") | |
| 80 | return Response.json({ | |
| 81 | data: [{ id: "canned/small" }, { id: "canned/large" }], | |
| 82 | }); | |
| 83 | const body = (await req.json()) as { tools?: unknown }; | |
| 84 | return Response.json({ | |
| 85 | choices: [ | |
| 86 | { | |
| 87 | message: | |
| 88 | body.tools === undefined | |
| 89 | ? { content: "ok" } | |
| 90 | : { | |
| 91 | tool_calls: [ | |
| 92 | { | |
| 93 | id: "c", | |
| 94 | type: "function", | |
| 95 | function: { name: "ping", arguments: "{}" }, | |
| 96 | }, | |
| 97 | ], | |
| 98 | }, | |
| 99 | }, | |
| 100 | ], | |
| 101 | }); | |
| 102 | }, | |
| 103 | }); | |
| 104 | dataDir = await mkdtemp(join(tmpdir(), "forge-tui-connections-")); | |
| 105 | forge = createApp({ dataDir, port: 0 }); | |
| 106 | for (const [username, adminIfFirst] of [ | |
| 107 | ["alice", true], | |
| 108 | ["bob", false], | |
| 109 | ] as const) { | |
| 110 | const made = await createUser(forge.db, { | |
| 111 | origin: "seed", | |
| 112 | trusted: true, | |
| 113 | username, | |
| 114 | email: `${username}@forge.local`, | |
| 115 | password: "a-good-passphrase", | |
| 116 | adminIfFirst, | |
| 117 | }); | |
| 118 | if (!made.ok) throw new Error(made.error); | |
| 119 | } | |
| 120 | }); | |
| 121 | afterAll(async () => { | |
| 122 | canned.stop(true); | |
| 123 | forge.close(); | |
| 124 | await rm(dataDir, { recursive: true, force: true }); | |
| 125 | }); | |
| 126 | ||
| 127 | const open = async (h: ReturnType<typeof boot>) => { | |
| 128 | await h.ctrl("k"); | |
| 129 | await h.type("Model budget"); | |
| 130 | await h.until("what your crew may spend"); | |
| 131 | await h.press("enter"); | |
| 132 | await h.until("Connections (n adds one"); | |
| 133 | }; | |
| 134 | ||
| 135 | test("an admin adds the forge's own, tests it again, and removes it with the name typed", async () => { | |
| 136 | const h = boot("alice"); | |
| 137 | await open(h); | |
| 138 | await h.press("n"); | |
| 139 | await h.type("other"); | |
| 140 | await h.press("enter"); | |
| 141 | await h.until("name"); | |
| 142 | await h.type("Spark"); | |
| 143 | await h.press("enter"); | |
| 144 | await h.until("base URL"); | |
| 145 | await h.type(`http://127.0.0.1:${String(canned.port)}/v1`); | |
| 146 | await h.press("enter"); | |
| 147 | await h.until("reasoning effort"); | |
| 148 | await h.type("low"); | |
| 149 | await h.press("enter"); | |
| 150 | await h.until("end with ! for the forge"); | |
| 151 | await h.type("sk-spark!"); | |
| 152 | await h.press("enter"); | |
| 153 | await h.until("Spark is connected: 2 models listed"); | |
| 154 | expect(h.text()).not.toContain("sk-spark"); | |
| 155 | expect(h.text()).toContain( | |
| 156 | "Spark · working · the forge's credit and budgets · 2 models", | |
| 157 | ); | |
| 158 | await h.press("t"); | |
| 159 | await h.type("Spark"); | |
| 160 | await h.press("enter"); | |
| 161 | await h.until("Spark: 2 models listed"); | |
| 162 | await h.press("x"); | |
| 163 | await h.type("spark"); | |
| 164 | await h.press("enter"); | |
| 165 | await h.until("No connection here by that name."); | |
| 166 | await h.press("esc"); | |
| 167 | await h.press("x"); | |
| 168 | await h.type("Spark"); | |
| 169 | await h.press("enter"); | |
| 170 | await h.until("Spark is removed"); | |
| 171 | expect( | |
| 172 | listConnections(forge.db, getUserByName(forge.db, "alice")!.id).map( | |
| 173 | (c) => c.name, | |
| 174 | ), | |
| 175 | ).toEqual(["The forge's own"]); | |
| 176 | h.stop(); | |
| 177 | }); | |
| 178 | ||
| 179 | test("a person's own on a private address is refused, and nothing is saved", async () => { | |
| 180 | const h = boot("bob"); | |
| 181 | await open(h); | |
| 182 | await h.press("n"); | |
| 183 | await h.type("ollama"); | |
| 184 | await h.press("enter"); | |
| 185 | await h.until("name"); | |
| 186 | await h.type("Mine"); | |
| 187 | await h.press("enter"); | |
| 188 | await h.until("base URL"); | |
| 189 | await h.press("enter"); | |
| 190 | await h.until("reasoning effort"); | |
| 191 | await h.press("enter"); | |
| 192 | await h.until("sent only to this address"); | |
| 193 | await h.type("k"); | |
| 194 | await h.press("enter"); | |
| 195 | await h.until("must be a public https address"); | |
| 196 | expect( | |
| 197 | listConnections(forge.db, getUserByName(forge.db, "bob")!.id).map( | |
| 198 | (c) => c.name, | |
| 199 | ), | |
| 200 | ).toEqual(["The forge's own"]); | |
| 201 | h.stop(); | |
| 202 | }); | |
| 203 | }); |
test/ui-spec/rowList.test.ts added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | import { test } from "bun:test"; | |
| 2 | import { html } from "../../src/web/html.ts"; | |
| 3 | import { row, rowList } from "../../src/web/ui.ts"; | |
| 4 | import { expectAccessible } from "./helper.ts"; | |
| 5 | ||
| 6 | test("rowList: rows as one list, in a card's place or bare on a settings page", () => { | |
| 7 | const rows = [row({ title: "Spark", meta: html`the forge's` }), row({ title: "Mine", meta: html`yours` })]; | |
| 8 | expectAccessible(rowList(rows)); | |
| 9 | expectAccessible(rowList(rows, { bare: true })); | |
| 10 | }); |
MEDIUM, denial of service.
addConnectionandretestConnectioneach make up to three outbound calls of 10 seconds. Any signed-in person can post them back to back, and no per-identity limit applies. A person could keep the forge's outbound path and a worker busy this way, or hammer a third-party host from the forge's address. Rate-limit them on the user id, for example a few tests a minute, and say 'try again in a minute' in the words. Add a test that the limit holds.