slatebox 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tim Heckel and Slatebox contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,232 @@
1
- # Temporary Holding Version
1
+ # slatebox
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run your own Slatebox with one command, on the machine of your choice:
4
+
5
+ ```sh
6
+ npx slatebox install
7
+ ```
8
+
9
+ Pick a team address and sign in; Slatebox runs at `https://<name>.slatebox.team`
10
+ with no DNS, ports or certificates. Or choose your own domain, or this computer
11
+ only. It asks a few short questions (Enter takes the default), shows a plan of
12
+ everything it will write, run and create, and installs once you say yes. Then
13
+ it prints the address and a one-time setup link: nobody can sign up until the
14
+ first admin exists, and the person who opens the link creates that account (the
15
+ server administrator and the owner of the first team). The link works once and
16
+ expires in 24 hours; `slatebox setup-link` prints a new one at a terminal and
17
+ ends the last. `npx slatebox --dry-run` asks the same questions and
18
+ prints the plan without changing anything. You need Node.js 22.13 or newer, and
19
+ Docker (or Podman with its Docker compatibility on) on whatever runs Slatebox.
20
+ Plain `npx slatebox` lists the commands.
21
+
22
+ ### A team address
23
+
24
+ ```sh
25
+ npx slatebox install --team-address acme --yes
26
+ ```
27
+
28
+ `acme.slatebox.team` is claimed for your Slatebox account when you approve a
29
+ short code in your browser (like `gh auth login`). The container then connects
30
+ out to Cloudflare through a secure tunnel, which carries HTTPS and live
31
+ editing: nothing is opened on your machine or router, and the container starts
32
+ again when the machine does. Names are 3 to 32 characters (a-z, 0-9, hyphens).
33
+ An account holds up to 3. Your address is public; your slates are not.
34
+
35
+ The install keeps one credential for the address, on this computer only:
36
+ `~/.slatebox/installs/<name>/credentials.json` (mode 0600). It can fetch the
37
+ tunnel token again and give the address back, and nothing else.
38
+
39
+ ```sh
40
+ slatebox status # includes the address and the tunnel's connections
41
+ slatebox setup-link # a new one-time link for the first admin (ends the last one)
42
+ slatebox rename acme-boards # move to https://acme-boards.slatebox.team (sign-in)
43
+ slatebox address rotate # a new tunnel token; any copy of the old one stops working
44
+ slatebox address release # give the address back; Slatebox keeps running on this computer
45
+ slatebox uninstall # also gives the address back, unless --keep-address
46
+ ```
47
+
48
+ A released name is held for your account for 30 days. Slatebox Cloud releases
49
+ an address that never connected within 24 hours, and one unused for 90 days.
50
+ To leave the team address for your own domain, run
51
+ `npx slatebox install --domain boards.example.com`.
52
+
53
+ Slatebox is one container: the app, the live collaboration relay, MongoDB and
54
+ Keycloak for single sign-on (off until you turn it on). It is free, and single
55
+ sign-on is free.
56
+
57
+ | Where | How |
58
+ | --- | --- |
59
+ | This computer | `npx slatebox install` (the default). A team address, your own domain, or `--local` for `http://localhost` on a free port from 7070. |
60
+ | A Linux server | `npx slatebox install ssh root@203.0.113.5 --team-address acme`, or `--domain boards.example.com`. With a domain, HTTPS certificates are obtained and renewed automatically (point DNS at the server, open ports 80 and 443); without one, `http://<server>:7070`. Docker is installed only if you add `--install-docker`. |
61
+ | Kubernetes | `npx slatebox install k8s --route ingress --domain boards.example.com --tls-issuer ClusterIssuer/letsencrypt`. Uses kubectl and your current context (a context whose name looks like production must be named with `--k8s-context`). One StatefulSet with a volume, a Service, an optional Ingress or Gateway API HTTPRoute, a Secret, and a backups sidecar. |
62
+ | Files only | `npx slatebox install export --format compose\|manifests\|helm --out ./slatebox-deploy` for GitOps. Nothing is applied. |
63
+
64
+ ## AI is yours to choose
65
+
66
+ Slatebox is not tied to any AI provider, and the installer never picks one
67
+ for you. Answer "none for now", or give any mix: OpenAI, Anthropic, DeepInfra,
68
+ OpenRouter, Groq, Together, Mistral, or any OpenAI-compatible endpoint you run
69
+ (Ollama, vLLM, LM Studio, a company gateway) with its model.
70
+
71
+ ```sh
72
+ npx slatebox install --ai none
73
+ npx slatebox install --ai-provider "kind=openai,model=gpt-5-mini,key=env:OPENAI_API_KEY"
74
+ npx slatebox install --ai-provider "id=local,kind=ollama,model=qwen3:8b" \
75
+ --ai-provider "kind=anthropic,model=claude-sonnet-4-5,key=env:ANTHROPIC_API_KEY" --ai-default local
76
+ slatebox ai add "kind=groq,model=llama-3.3-70b-versatile,key=env:GROQ_API_KEY"
77
+ slatebox ai test # from inside the container: models, tool calls, tool_choice, latency
78
+ slatebox ai use local | remove groq | off | list
79
+ ```
80
+
81
+ Keys are never written in flags or answers files: give `env:NAME`,
82
+ `file:/path`, or `prompt` (typed, hidden). An endpoint on `localhost` is
83
+ reached from the container as `host.docker.internal`. Images that take one
84
+ provider at a time are told so plainly when you give several.
85
+
86
+ ## For agents
87
+
88
+ `npx slatebox agent-prompt` prints the brief an agent follows. In short: an
89
+ answers file, `slatebox plan --answers slatebox.yaml --json`, show the plan to
90
+ the person, then `slatebox install --answers slatebox.yaml --yes --json`.
91
+ With no terminal (or `--agent yes`, or an agent detected from the
92
+ environment), nothing is ever asked: a missing answer is exit code 3 with each
93
+ question, its choices and the flag that answers it.
94
+
95
+ Every flag has an environment form, `SLATEBOX_INSTALL_<FLAG>`. Flags win, then
96
+ the answers file, then the environment. Consent is the exception: `--yes`,
97
+ `--install-docker`, `--new-encryption-key`, `--delete-data` and `--confirm`
98
+ count only when typed on the command line, never from the environment or an
99
+ answers file, so a variable left exported in a shell or a CI job approves
100
+ nothing.
101
+
102
+ An answers file is treated as untrusted input: ssh options are limited to a
103
+ short allow-list (no `ProxyCommand`, `LocalCommand`, or host-key checking off),
104
+ host, user, folder, image, schedule and S3 URL are checked before anything runs,
105
+ and a value that looks like a key where a variable name belongs is refused
106
+ without being repeated.
107
+
108
+ | Exit | Meaning |
109
+ | --- | --- |
110
+ | 0 | Done, or nothing to change |
111
+ | 2 | Bad flags or answers; the `error` event lists each field |
112
+ | 3 | An answer or a confirmation is needed and nobody can be asked; the event lists the questions |
113
+ | 4 | A precondition failed: no Docker, no kube access, CPU too old, port taken, image unavailable |
114
+ | 5 | The change failed its health check and was rolled back cleanly |
115
+ | 6 | The rollback failed too; the event carries the commands a person must run |
116
+ | 7 | Cancelled |
117
+
118
+ With `--json`, stdout is one JSON event per line (`plan`, `step`, `done`,
119
+ `error`); text for people goes to stderr.
120
+
121
+ ## After the install
122
+
123
+ ```sh
124
+ slatebox status # address, health, version, AI, SSO, last backup
125
+ slatebox logs [-f] [--service tunnel] # the container's log, every line redacted
126
+ slatebox upgrade # back up, upgrade, check health, roll back (with the backup) on failure
127
+ slatebox backup [--to ./backups] # a complete backup now
128
+ slatebox restore slatebox-backup.gz
129
+ slatebox secrets path # where SLATEBOX_KEY_ENCRYPTION_KEY and your keys are kept
130
+ slatebox secrets reveal SLATEBOX_KEY_ENCRYPTION_KEY # to a terminal only, never with --json
131
+ slatebox uninstall # keeps data; --delete-data --confirm <name> removes it (alias: remove)
132
+ slatebox installs # every install this computer made (--name picks one)
133
+ ```
134
+
135
+ The installer generates `SLATEBOX_KEY_ENCRYPTION_KEY` once and stores it
136
+ outside the data: `~/.slatebox/installs/<name>/secrets.env` (mode 0600) on this
137
+ computer, `/opt/slatebox/secrets.env` (root, 0600) on a server, or the Secret
138
+ `<name>-env` on Kubernetes. Back it up: backups do not contain it, and without
139
+ it the AI keys people saved cannot be read after a restore. Re-running the
140
+ installer never makes a new one.
141
+
142
+ ## Move your team to Slatebox Cloud, or back
143
+
144
+ ```sh
145
+ npx slatebox migrate --to cloud # your own server's team → Slatebox Cloud
146
+ npx slatebox import --from cloud # your Slatebox Cloud team → your own server
147
+ npx slatebox install --from cloud # a new server, then the steps to bring your Cloud team over
148
+ npx slatebox export --out acme.sbxteam --passphrase prompt # a team export file
149
+ npx slatebox import acme.sbxteam --to cloud --passphrase prompt
150
+ ```
151
+
152
+ The command exports everything your team owns from one side (you need to be a team admin
153
+ there), and moves it to the other side, where you own your team or are in no team yet. It
154
+ moves slates and boards, smart components, versions, comments, presentations, files, the
155
+ brand kit, and library items (sent to the other side's review queue). People arrive as
156
+ placeholders. Once the move is live you are asked once, "Send invitations to the N other
157
+ members now?" (yes by default; `--invite` / `--no-invite` answer ahead; a script invites
158
+ nobody without `--invite`). Later: `npx slatebox migrate invite <move id> --to cloud`. Someone
159
+ who already has an account on the other side accepts an invitation to join there. Passwords,
160
+ keys, access tokens and connected agents never move.
161
+
162
+ You see the report before anything is visible on the other side, and nothing goes live until
163
+ you confirm. The team stays where it was until you remove it there.
164
+
165
+ - **Your own server:** its address is `--from`/`--to <url>`, `SLATEBOX_BASE_URL`, or the install
166
+ this computer made (`--name`). Its access token is `SLATEBOX_API_TOKEN` (make one in Profile →
167
+ Developer with "Export everything my team owns" and "Move a team here"). At a terminal you are
168
+ asked for it, with hidden input.
169
+ - **Slatebox Cloud:** you sign in with a code in your browser (the page says "Move your team";
170
+ the sign-in works for the move only, for an hour), or set `SLATEBOX_CLOUD_TOKEN`.
171
+ - **The archive** is encrypted with a passphrase made for this move, in `~/.slatebox/moves/`
172
+ (mode 0600). Once the move is live you are asked whether to delete it (no by default; the
173
+ command to delete it is printed). `--delete-archive` deletes it, `--keep-archive` keeps it,
174
+ without asking.
175
+ - An older server than the archive stops the move with "update that server"; the archive is kept.
176
+ - `--replace-waiting` discards a move that is already waiting on the other side.
177
+
178
+ ## Safety
179
+
180
+ - A plan is always shown first. On a server or a cluster nothing changes
181
+ without a yes (`--yes` skips only the question; the plan is still printed).
182
+ - `--yes` never deletes data and never installs system software: those need
183
+ `--delete-data --confirm <name>` and `--install-docker`. Deleting data over
184
+ SSH removes only the files the installer wrote, in a folder holding its
185
+ `.slatebox-install` marker.
186
+ - `plan`, and `install` before its yes, only look: nothing is pulled, loaded or
187
+ started on the host. `upgrade` fetches the image tag first, because whether it
188
+ is newer is what its plan is about.
189
+ - On this computer Slatebox is published on 127.0.0.1 only. `--listen 0.0.0.0`
190
+ opens it to the network (Docker's port rules bypass ufw, so do this only
191
+ behind something you trust). A server over SSH listens on every interface.
192
+ - The key encryption key is never made again over existing data: if the data
193
+ volume, StatefulSet or volume claim exists and its key cannot be read, the
194
+ installer stops (exit 4) unless you add `--new-encryption-key`.
195
+ - Upgrades back up first and roll back on failure; on Kubernetes the rollback
196
+ puts back the previous settings and Secret, not only the image. An upgrade
197
+ of a stopped install says in its plan that there is no backup to fall back to.
198
+ - Native Windows is not supported for this computer or SSH; use WSL 2.
199
+ - Secrets never appear in output, logs, answers files, install records or
200
+ command lines (`ps` can read those); they travel on standard input or in
201
+ 0600 files.
202
+ - Re-running with the same answers changes nothing.
203
+ - Nothing phones home. The installer contacts the image registry, Slatebox
204
+ Cloud only when you ask for a team address, and only with your consent
205
+ get.docker.com; Slatebox itself contacts Cloudflare's tunnel when it has a
206
+ team address, the certificate authority when you give a domain, and the AI
207
+ endpoints you configure.
208
+
209
+ ## Which image
210
+
211
+ Each release of this package installs one public image,
212
+ `ghcr.io/slatebox/slatebox`, by its digest (this release: `0.2.1`, which adds
213
+ the team-address tunnel, the setup link and team moves). It needs
214
+ no registry login. To install a local build instead, give `--image <name>`
215
+ (or `--image-archive slatebox.tar` for a server).
216
+
217
+ ## With an agent
218
+
219
+ Connect the Slatebox MCP server (`npx -y slatebox-mcp`) to Claude, ChatGPT,
220
+ Claude Code or another agent and say "install Slatebox on my server". Its
221
+ `install_slatebox` prompt and tool walk you through the choices and end with
222
+ the exact `npx slatebox` command to run on that machine. The agent never runs
223
+ anything on your server itself; once you have run the command, it checks the
224
+ address answers.
225
+
226
+ ## Slates
227
+
228
+ `slatebox exec`, `slatebox describe` and `slatebox mcp` (scripts and agents
229
+ against any Slatebox) come from the slatebox-mcp package, which this package
230
+ installs with it. If you installed slatebox-mcp 0.3 globally, which also named
231
+ a `slatebox` command, replace it with:
232
+ `npm rm -g slatebox-mcp && npm i -g slatebox slatebox-mcp`.
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.mjs'
3
+
4
+ const [major, minor] = process.versions.node.split('.').map(Number)
5
+ if (major < 22 || (major === 22 && minor < 13)) {
6
+ process.stderr.write(`slatebox needs Node.js 22.13 or newer (this is ${process.versions.node}).\n`)
7
+ process.exit(4)
8
+ }
9
+ process.exitCode = await main(process.argv.slice(2))
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "slatebox",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Run your own Slatebox with one command: npx slatebox install. Gives it a free team address (https://<name>.slatebox.team) with no DNS, ports or certificates, or uses your own domain; installs on Docker here, a server over SSH, Kubernetes, or writes the files. Also runs agent scripts against any Slatebox (slatebox exec).",
5
+ "keywords": [
6
+ "slatebox",
7
+ "self-host",
8
+ "installer",
9
+ "docker",
10
+ "kubernetes",
11
+ "helm",
12
+ "whiteboard",
13
+ "open-source"
14
+ ],
15
+ "homepage": "https://docs.slatebox.com/installation/",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Slatebox/slatebox.git",
19
+ "directory": "packages/slatebox"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/Slatebox/slatebox/issues"
23
+ },
24
+ "license": "MIT",
25
+ "type": "module",
26
+ "bin": {
27
+ "slatebox": "bin/slatebox.mjs"
28
+ },
29
+ "files": [
30
+ "bin",
31
+ "src",
32
+ "README.md",
33
+ "LICENSE.md"
34
+ ],
35
+ "scripts": {
36
+ "test": "node --test --test-concurrency=1 test/*.test.mjs",
37
+ "test:integration": "node --test --test-concurrency=1 test/integration/*.test.mjs",
38
+ "prepublishOnly": "SLATEBOX_PUBLISH=1 npm test"
39
+ },
40
+ "engines": {
41
+ "node": ">=22.13"
42
+ },
43
+ "dependencies": {
44
+ "slatebox-mcp": "0.4.0"
45
+ }
46
+ }
@@ -0,0 +1,79 @@
1
+ // The brief `slatebox agent-prompt` prints, for a coding agent asked to
2
+ // install Slatebox for a person. The same text belongs in the docs and llms.txt.
3
+ export const AGENT_PROMPT = `# Install Slatebox with an agent
4
+
5
+ You are installing Slatebox, a self-hosted team canvas, for a person. Use the
6
+ \`slatebox\` command from npm. It never prompts when run by an agent; it tells
7
+ you what it still needs. Follow these steps exactly.
8
+
9
+ 1. **Ask the person** (do not guess):
10
+ - Where: this computer (Docker), a Linux server over SSH (user@host), or
11
+ Kubernetes (which kube context and namespace). Or only write the files.
12
+ - The address: a free team address (https://<name>.slatebox.team: no DNS,
13
+ ports or certificates; the person signs in once in their browser to claim
14
+ it), a domain name for HTTPS, or a port.
15
+ - The admin email (required for a server or a cluster).
16
+ - AI: none for now, or which providers. Slatebox works with any provider and
17
+ has no default: OpenAI, Anthropic, DeepInfra, OpenRouter, Groq, Together,
18
+ Mistral, or any OpenAI-compatible endpoint they run (Ollama, vLLM, LM
19
+ Studio) with its model. Keys are never typed into files or flags: ask the
20
+ person to export each key in an environment variable and give its name.
21
+ - Single sign-on (bundled Keycloak): on or off.
22
+ 2. **Write an answers file** \`slatebox.yaml\` (no secrets in it):
23
+
24
+ \`\`\`yaml
25
+ version: 1
26
+ target: local # local | ssh | k8s | export
27
+ adminEmail: ops@example.com
28
+ ai:
29
+ mode: providers # or: none
30
+ providers:
31
+ - { id: openai, kind: openai, model: gpt-5-mini, keyFrom: "env:OPENAI_API_KEY" }
32
+ - { id: local, kind: openai-compatible, baseUrl: "http://ollama.internal:11434/v1", model: "qwen3:8b" }
33
+ default: local
34
+ sso: { enabled: false }
35
+ # ssh: { host: 203.0.113.5, user: root } with target: ssh
36
+ # address: { team: acme } a team address, https://acme.slatebox.team
37
+ # address: { domain: boards.example.com } for HTTPS on a server or a cluster route
38
+ # k8s: { context: my-cluster, namespace: slatebox, route: ingress, ingressClass: nginx, tlsIssuer: { kind: ClusterIssuer, name: letsencrypt } }
39
+ \`\`\`
40
+ 3. **Plan**: \`npx -y slatebox@latest plan --answers slatebox.yaml --json\`.
41
+ It changes nothing. Read the \`plan\` event.
42
+ - Exit 2: fix the fields listed in the \`error\` event.
43
+ - Exit 3: answers are missing; the event lists each \`field\`, its
44
+ \`question\`, \`choices\` and the \`flag\` to answer it. Ask the person.
45
+ - Exit 4: a precondition failed (no Docker, no access, port taken, an
46
+ unknown SSH host key, a missing key encryption key). Tell the person what
47
+ the message says; do not work around it: never add --install-docker or
48
+ --new-encryption-key without asking, never turn off ssh host-key
49
+ checking, and never export SLATEBOX_INSTALL_YES (it is ignored).
50
+ 4. **Show the plan to the person and get an explicit yes.** It lists every
51
+ file, command, object and port, and where the secrets are kept.
52
+ With a team address the short form is
53
+ \`npx slatebox install --team-address <name> --yes\` (add \`--ai none\` or the
54
+ providers the person chose). Exit 3 with \`id: "address-unavailable"\` lists free
55
+ \`suggestions\`: ask the person to pick one.
56
+ 5. **Install**: \`npx -y slatebox@latest install --answers slatebox.yaml --yes --json\`.
57
+ For a team address a \`sign-in\` event carries \`verificationUri\` and \`userCode\`:
58
+ show both to the person and ask them to approve it in their browser; the
59
+ command waits. Never approve it yourself.
60
+ Report \`done.address\` from the last line. Do not print or copy any secret;
61
+ the output never contains one. Tell the person where the key encryption key
62
+ is stored (\`done.secretsFile\`) and that they must back it up themselves.
63
+ Nobody can sign up until the first admin exists. Tell the person to run
64
+ \`slatebox setup-link\` in their own terminal: it prints a one-time link
65
+ (24 hours, single use) that creates the first account, the server
66
+ administrator. Never run it yourself or ask for the link: it is as good as
67
+ an admin password.
68
+ 6. **If it fails**: exit 5 means the change was rolled back and the previous
69
+ state is running; exit 6 means a person must act: show them
70
+ \`error.commands\` and stop.
71
+ 7. **Later**: \`slatebox status --json\`, \`slatebox upgrade --yes --json\`,
72
+ \`slatebox ai add "kind=...,model=...,key=env:VAR" --yes --json\`,
73
+ \`slatebox backup\`. Never run \`uninstall --delete-data\` unless the person
74
+ asked for their data to be deleted.
75
+
76
+ Nothing the installer runs sends data anywhere except pulling the image (and,
77
+ with consent, installing Docker from get.docker.com, the certificate authority
78
+ when a domain is given, and Slatebox Cloud when a team address is asked for).
79
+ `
@@ -0,0 +1,198 @@
1
+ // AI providers as the installer stores them, and as the image takes them.
2
+ //
3
+ // The installer never picks a provider. A person gives any mix: a cloud key
4
+ // (OpenAI, Anthropic, DeepInfra, OpenRouter, Groq, Together, Mistral) or an
5
+ // OpenAI-compatible endpoint they run (Ollama, LM Studio, vLLM, a gateway).
6
+ // Every kind but DeepInfra is stored as an OpenAI-compatible endpoint with its
7
+ // address filled in, so the image needs to know only two kinds.
8
+ //
9
+ // Images differ in what they accept, and the installer asks the image (see
10
+ // image.mjs probeImage). An image that lists SLATEBOX_AI_PROVIDERS takes a
11
+ // JSON list and one key variable per provider; an older image takes one
12
+ // provider as SLATEBOX_AI_KEY / SLATEBOX_AI_URL / SLATEBOX_AI_MODEL. Key values
13
+ // are never written here: secrets hold references (env:NAME, file:/path,
14
+ // prompt) that secret-values.mjs reads only when it writes the secrets file.
15
+ import { EXIT, InstallError } from '../errors.mjs'
16
+
17
+ /** The settings every one-container image so far accepts. */
18
+ export const LEGACY_SETTINGS = Object.freeze([
19
+ 'SLATEBOX_URL', 'SLATEBOX_HTTPS', 'SLATEBOX_ACME_CA', 'SLATEBOX_MAIL_URL', 'SLATEBOX_MAIL_FROM',
20
+ 'SLATEBOX_AI_KEY', 'SLATEBOX_AI_URL', 'SLATEBOX_AI_MODEL', 'SLATEBOX_SETTINGS', 'SLATEBOX_SSO', 'SLATEBOX_SSO_ONLY',
21
+ 'SLATEBOX_SSO_ADMIN', 'SLATEBOX_KEY_ENCRYPTION_KEY', 'MONGO_URL', 'MONGO_OPLOG_URL',
22
+ ])
23
+
24
+ /** Each kind a person may name, with the address it stands for. */
25
+ export const PRESETS = Object.freeze({
26
+ openai: Object.freeze({ kind: 'openai-compatible', label: 'OpenAI', baseUrl: 'https://api.openai.com/v1', needsKey: true }),
27
+ anthropic: Object.freeze({ kind: 'openai-compatible', label: 'Anthropic', baseUrl: 'https://api.anthropic.com/v1', needsKey: true }),
28
+ deepinfra: Object.freeze({ kind: 'deepinfra', label: 'DeepInfra', baseUrl: 'https://api.deepinfra.com/v1/openai', needsKey: true }),
29
+ openrouter: Object.freeze({ kind: 'openai-compatible', label: 'OpenRouter', baseUrl: 'https://openrouter.ai/api/v1', needsKey: true }),
30
+ groq: Object.freeze({ kind: 'openai-compatible', label: 'Groq', baseUrl: 'https://api.groq.com/openai/v1', needsKey: true }),
31
+ together: Object.freeze({ kind: 'openai-compatible', label: 'Together', baseUrl: 'https://api.together.xyz/v1', needsKey: true }),
32
+ mistral: Object.freeze({ kind: 'openai-compatible', label: 'Mistral', baseUrl: 'https://api.mistral.ai/v1', needsKey: true }),
33
+ ollama: Object.freeze({ kind: 'openai-compatible', label: 'Ollama', baseUrl: 'http://localhost:11434/v1', needsKey: false }),
34
+ lmstudio: Object.freeze({ kind: 'openai-compatible', label: 'LM Studio', baseUrl: 'http://localhost:1234/v1', needsKey: false }),
35
+ 'openai-compatible': Object.freeze({ kind: 'openai-compatible', label: 'OpenAI-compatible endpoint', baseUrl: null, needsKey: false }),
36
+ })
37
+
38
+ export const PROVIDER_KINDS = Object.freeze(Object.keys(PRESETS))
39
+
40
+ /**
41
+ * One provider in its stored form: DeepInfra stays DeepInfra; every other kind
42
+ * becomes an OpenAI-compatible endpoint with its address. `vendor` keeps the
43
+ * kind the person named (for labels and the key check). Idempotent.
44
+ */
45
+ export function normalizeProvider(provider) {
46
+ const preset = PRESETS[provider?.kind]
47
+ if (!preset) return { ...provider }
48
+ const keyFrom = provider.keyFrom ?? 'none'
49
+ if (preset.kind === 'deepinfra') {
50
+ return { id: provider.id || 'deepinfra', kind: 'deepinfra', ...(provider.model ? { model: provider.model } : {}), keyFrom }
51
+ }
52
+ const vendor = provider.vendor ?? (provider.kind === 'openai-compatible' ? undefined : provider.kind)
53
+ const out = { id: provider.id || provider.kind, kind: 'openai-compatible', baseUrl: provider.baseUrl ?? preset.baseUrl ?? undefined }
54
+ if (out.baseUrl === undefined) delete out.baseUrl
55
+ if (provider.model) out.model = provider.model
56
+ out.keyFrom = keyFrom
57
+ if (provider.toolChoice) out.toolChoice = provider.toolChoice
58
+ if (vendor) out.vendor = vendor
59
+ return out
60
+ }
61
+
62
+ /** Whether this provider cannot work without a key. */
63
+ export function needsKey(provider) {
64
+ return Boolean(PRESETS[provider?.vendor ?? provider?.kind]?.needsKey)
65
+ }
66
+
67
+ export function providerLabel(provider) {
68
+ return PRESETS[provider?.vendor ?? provider?.kind]?.label ?? provider?.kind ?? 'AI'
69
+ }
70
+
71
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '::1', '[::1]'])
72
+
73
+ // An endpoint on this computer is reached from inside the container through
74
+ // Docker's host gateway. On Kubernetes "localhost" is the pod itself: refused.
75
+ function locate(baseUrl, target, notes) {
76
+ let url
77
+ try { url = new URL(baseUrl) } catch { return { baseUrl, gateway: false } }
78
+ if (!LOOPBACK.has(url.hostname)) return { baseUrl, gateway: false }
79
+ if (target === 'k8s' || target === 'export-k8s') {
80
+ throw new InstallError(EXIT.USAGE, `The AI endpoint ${baseUrl} is on localhost, which inside a pod is the pod itself. Give the endpoint's Service address, for example http://ollama.ai.svc:11434/v1.`)
81
+ }
82
+ url.hostname = 'host.docker.internal'
83
+ const located = url.href.replace(/\/$/, baseUrl.endsWith('/') ? '/' : '')
84
+ notes.push(`${baseUrl} is on this computer: the container reaches it as ${located} (host.docker.internal). Make sure the endpoint listens on an address Docker can reach, not only 127.0.0.1.`)
85
+ return { baseUrl: located, gateway: true }
86
+ }
87
+
88
+ const keyVariable = id => `SLATEBOX_AI_KEY_${id.toUpperCase().replace(/[^A-Z0-9]/g, '_')}`
89
+
90
+ /**
91
+ * The settings and secret references for the AI answers, in the form this image takes.
92
+ * @param {{mode: string, providers?: object[], default?: string}} ai
93
+ * @param {{settings: string[]}|null} caps what the image accepts (null: an older image)
94
+ * @param {{target: string}} where
95
+ * @returns {{env: Record<string,string>, secrets: Record<string,string>, notes: string[], hostGateway: boolean}}
96
+ */
97
+ export function aiEnv(ai, caps, { target } = {}) {
98
+ const out = { env: {}, secrets: {}, notes: [], hostGateway: false }
99
+ if (!ai || ai.mode !== 'providers' || !ai.providers?.length) return out
100
+ const providers = ai.providers.map(normalizeProvider)
101
+ const multi = Boolean(caps?.settings?.includes('SLATEBOX_AI_PROVIDERS'))
102
+ if (!multi) {
103
+ if (providers.length > 1) {
104
+ throw new InstallError(EXIT.USAGE, `This Slatebox image supports one AI provider at a time; ${providers.length} were given (${providers.map(provider => provider.id).join(', ')}). Keep one, or use a newer image.`)
105
+ }
106
+ const [provider] = providers
107
+ if (provider.kind === 'deepinfra') {
108
+ if (provider.keyFrom !== 'none') out.secrets.SLATEBOX_AI_KEY = provider.keyFrom
109
+ return out
110
+ }
111
+ const { baseUrl, gateway } = locate(provider.baseUrl, target, out.notes)
112
+ out.hostGateway = gateway
113
+ out.env.SLATEBOX_AI_URL = baseUrl
114
+ if (provider.model) out.env.SLATEBOX_AI_MODEL = provider.model
115
+ if (provider.keyFrom !== 'none') out.secrets.SLATEBOX_AI_KEY = provider.keyFrom
116
+ return out
117
+ }
118
+ const list = providers.map(provider => {
119
+ const entry = { id: provider.id, kind: provider.kind }
120
+ if (provider.kind !== 'deepinfra') {
121
+ const { baseUrl, gateway } = locate(provider.baseUrl, target, out.notes)
122
+ if (gateway) out.hostGateway = true
123
+ entry.baseUrl = baseUrl
124
+ }
125
+ if (provider.model) entry.model = provider.model
126
+ if (provider.toolChoice) entry.toolChoice = provider.toolChoice
127
+ if (provider.keyFrom !== 'none') {
128
+ entry.keyEnv = keyVariable(provider.id)
129
+ out.secrets[entry.keyEnv] = provider.keyFrom
130
+ }
131
+ return entry
132
+ })
133
+ out.env.SLATEBOX_AI_PROVIDERS = JSON.stringify(list)
134
+ if (ai.default) out.env.SLATEBOX_AI_DEFAULT = ai.default
135
+ return out
136
+ }
137
+
138
+ /**
139
+ * What an image accepts, from `slatebox settings --json`, or (older images)
140
+ * from configure.mjs refusing an unknown setting and the command usage text.
141
+ * @returns {{settings: string[], commands: string[], source: string}|null}
142
+ */
143
+ export function capabilitiesFromProbe({ settingsJson, configureOutput, usage } = {}) {
144
+ if (settingsJson) {
145
+ try {
146
+ const parsed = JSON.parse(settingsJson)
147
+ if (Array.isArray(parsed?.settings)) {
148
+ return { settings: parsed.settings.map(String), commands: Array.isArray(parsed.commands) ? parsed.commands.map(String) : [], source: 'settings --json' }
149
+ }
150
+ } catch { /* fall through to the probe */ }
151
+ }
152
+ const listed = /The settings are: (.+?) \(in capitals\)/.exec(configureOutput || '')
153
+ if (!listed) return null
154
+ const settings = listed[1].split(',').map(name => name.trim()).filter(Boolean)
155
+ const commands = []
156
+ for (const match of String(usage || '').matchAll(/docker exec \S+ slatebox ([a-z][a-z-]*)/g)) {
157
+ if (!commands.includes(match[1])) commands.push(match[1])
158
+ }
159
+ return { settings, commands, source: 'probe' }
160
+ }
161
+
162
+ /**
163
+ * A script run with node inside the container, arguments [baseUrl, model, keyEnv]:
164
+ * lists models, asks for one forced tool call, and prints one JSON line. The
165
+ * key is read from the container's environment, never passed as an argument.
166
+ */
167
+ export function aiTestScript() {
168
+ return `
169
+ const [baseUrl, model, keyEnv] = process.argv.slice(2)
170
+ const key = keyEnv ? process.env[keyEnv] : ''
171
+ const headers = { 'content-type': 'application/json', ...(key ? { authorization: 'Bearer ' + key } : {}) }
172
+ const root = baseUrl.replace(/\\/$/, '')
173
+ const report = { baseUrl, models: [], toolCalls: null, toolChoiceHonoured: null, latencyMs: null }
174
+ try {
175
+ const listed = await fetch(root + '/models', { headers, signal: AbortSignal.timeout(15000) })
176
+ report.models = listed.ok ? ((await listed.json()).data || []).map(m => m.id).filter(Boolean) : 'HTTP ' + listed.status
177
+ if (model) {
178
+ const started = Date.now()
179
+ // The same probe as the image's own \`slatebox ai check\`: one forced call of a ping tool.
180
+ const tool = { type: 'function', function: { name: 'ping', description: 'Call this tool to answer.', parameters: { type: 'object', properties: { ok: { type: 'boolean' } }, required: ['ok'] } } }
181
+ const answer = await fetch(root + '/chat/completions', {
182
+ method: 'POST', headers, signal: AbortSignal.timeout(60000),
183
+ body: JSON.stringify({ model, messages: [{ role: 'user', content: 'Call the ping tool with ok set to true.' }], tools: [tool], tool_choice: { type: 'function', function: { name: 'ping' } }, max_tokens: 64 }),
184
+ })
185
+ report.latencyMs = Date.now() - started
186
+ if (!answer.ok) report.error = 'chat completions answered HTTP ' + answer.status
187
+ else {
188
+ const calls = (await answer.json()).choices?.[0]?.message?.tool_calls || []
189
+ report.toolCalls = calls.length > 0
190
+ report.toolChoiceHonoured = calls.some(call => call.function?.name === 'ping')
191
+ }
192
+ }
193
+ } catch (error) {
194
+ report.error = error.name === 'TimeoutError' ? 'the endpoint did not answer in time' : String(error.cause?.code || error.message)
195
+ }
196
+ console.log(JSON.stringify(report))
197
+ `
198
+ }