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 +21 -0
- package/README.md +231 -2
- package/bin/slatebox.mjs +9 -0
- package/package.json +44 -4
- package/src/agent-prompt.mjs +79 -0
- package/src/ai/settings-adapter.mjs +198 -0
- package/src/answers.mjs +513 -0
- package/src/cli.mjs +711 -0
- package/src/cloud.mjs +261 -0
- package/src/errors.mjs +23 -0
- package/src/image.mjs +141 -0
- package/src/interview.mjs +199 -0
- package/src/move.mjs +447 -0
- package/src/output.mjs +51 -0
- package/src/plan.mjs +51 -0
- package/src/prompt.mjs +87 -0
- package/src/record.mjs +46 -0
- package/src/render/compose.mjs +47 -0
- package/src/render/helm.mjs +78 -0
- package/src/render/k8s.mjs +204 -0
- package/src/render/settings.mjs +67 -0
- package/src/runner.mjs +50 -0
- package/src/secret-values.mjs +45 -0
- package/src/secrets.mjs +124 -0
- package/src/setup-link.mjs +88 -0
- package/src/targets/address.mjs +281 -0
- package/src/targets/docker.mjs +797 -0
- package/src/targets/export.mjs +73 -0
- package/src/targets/hosts.mjs +202 -0
- package/src/targets/k8s.mjs +405 -0
- package/src/yaml.mjs +293 -0
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
// `slatebox`: the one Slatebox command. It installs and runs your own Slatebox (with a free team
|
|
2
|
+
// address, your own domain, or this computer only), and runs agent scripts against any Slatebox
|
|
3
|
+
// (exec, describe and the MCP server, from the slatebox-mcp package, in this same process).
|
|
4
|
+
// main() takes its streams and environment as arguments and returns the exit code, so tests run
|
|
5
|
+
// it in process.
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { parseArgs } from 'node:util'
|
|
9
|
+
import { AGENT_PROMPT } from './agent-prompt.mjs'
|
|
10
|
+
import { aiEnv, aiTestScript, normalizeProvider } from './ai/settings-adapter.mjs'
|
|
11
|
+
import { ANSWER_FLAGS, collect, flagsFromEnv, parseProviderSpec, resolveAnswers } from './answers.mjs'
|
|
12
|
+
import { CREDENTIALS_FILE, readCredentials, teamHost } from './cloud.mjs'
|
|
13
|
+
import { EXIT, InstallError } from './errors.mjs'
|
|
14
|
+
import { interview } from './interview.mjs'
|
|
15
|
+
import { Output } from './output.mjs'
|
|
16
|
+
import { DEFAULT_IMAGE, DEFAULT_REPOSITORY, isTag } from './image.mjs'
|
|
17
|
+
import { formatPlan } from './plan.mjs'
|
|
18
|
+
import { createPrompt } from './prompt.mjs'
|
|
19
|
+
import { installDir, listRecords, readRecord, slateboxHome, writeRecord } from './record.mjs'
|
|
20
|
+
import { makeRunner } from './runner.mjs'
|
|
21
|
+
import { Redactor } from './secrets.mjs'
|
|
22
|
+
import { finishRename, releaseTeamAddress, renameTeamAddress, rotateTeamAddress, teamStatus } from './targets/address.mjs'
|
|
23
|
+
import { applyDocker, backupDocker, defaultLocalPort, execNode, LOG_SERVICES, logsDocker, readSecretDocker, restoreDocker, setupLinkDocker, statusDocker, uninstallDocker } from './targets/docker.mjs'
|
|
24
|
+
import { exportFiles } from './targets/export.mjs'
|
|
25
|
+
import { applyK8s, backupK8s, execNodeK8s, readSecretK8s, restoreK8s, setupLinkK8s, statusK8s, uninstallK8s } from './targets/k8s.mjs'
|
|
26
|
+
import { setupLines } from './setup-link.mjs'
|
|
27
|
+
import { exportTeamFile, importTeamFile, inviteMovedPeople, moveTeam } from './move.mjs'
|
|
28
|
+
import { parse as parseYaml } from './yaml.mjs'
|
|
29
|
+
|
|
30
|
+
const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
31
|
+
|
|
32
|
+
// Every word `slatebox` takes. An unknown word is exit 2 with a suggestion; nothing is fetched or
|
|
33
|
+
// run for it.
|
|
34
|
+
export const COMMANDS = Object.freeze([
|
|
35
|
+
{ name: 'install', usage: 'install [--team-address <name> | --domain <host> | --local] [target]', summary: 'install, or change, your own Slatebox (safe to run again)' },
|
|
36
|
+
{ name: 'status', usage: 'status [--json]', summary: 'health, address, tunnel, setup, version, AI and SSO, last backup' },
|
|
37
|
+
{ name: 'setup-link', usage: 'setup-link', summary: 'a new one-time link that creates the first admin (ends the last one)' },
|
|
38
|
+
{ name: 'logs', usage: 'logs [-f] [--service app|relay|mongo|proxy|tunnel|sso] [--since 10m]', summary: 'the container\'s log' },
|
|
39
|
+
{ name: 'upgrade', usage: 'upgrade [--to <image>]', summary: 'back up, upgrade, check health, roll back on failure' },
|
|
40
|
+
{ name: 'rename', usage: 'rename <new-name>', summary: 'move the team address to https://<new-name>.slatebox.team' },
|
|
41
|
+
{ name: 'address', usage: 'address [release | rotate]', summary: 'the team address: show it, give it back, or get a new tunnel token' },
|
|
42
|
+
{ name: 'uninstall', usage: 'uninstall [--keep-address] [--delete-data --confirm <name>]', summary: 'stop and remove (alias: remove); data is kept unless you say otherwise' },
|
|
43
|
+
{ name: 'backup', usage: 'backup [--to <dir>]', summary: 'a complete backup now' },
|
|
44
|
+
{ name: 'restore', usage: 'restore <file.gz>', summary: 'replace everything with a backup' },
|
|
45
|
+
{ name: 'ai', usage: 'ai list | add "<spec>" | remove <id> | use <id> | off | test [id]', summary: 'agent providers for this install' },
|
|
46
|
+
{ name: 'migrate', usage: 'migrate --to cloud | --from cloud [--invite|--no-invite] [--keep-archive|--delete-archive] | migrate invite <move id> --to cloud|<url>', summary: 'move your team between your own Slatebox and Slatebox Cloud' },
|
|
47
|
+
{ name: 'import', usage: 'import --from cloud | <file> [--to cloud|<url>]', summary: 'bring a team in (from Slatebox Cloud, or a team export file)' },
|
|
48
|
+
{ name: 'export', usage: 'export [--from cloud|<url>] [--out <file>]', summary: 'a team export file of everything your team owns' },
|
|
49
|
+
{ name: 'secrets', usage: 'secrets path | reveal <NAME>', summary: 'where secrets are kept; reveal prints one to a terminal' },
|
|
50
|
+
{ name: 'installs', usage: 'installs', summary: 'the installs this computer made' },
|
|
51
|
+
{ name: 'plan', usage: 'plan [install flags]', summary: 'print the plan only; changes nothing' },
|
|
52
|
+
{ name: 'agent-prompt', usage: 'agent-prompt', summary: 'instructions for a coding agent to install it for you' },
|
|
53
|
+
{ name: 'exec', usage: 'exec <file> | - | -e <code> [--preview] [--remote]', summary: 'run an agent script against your Slatebox (SLATEBOX_API_TOKEN)' },
|
|
54
|
+
{ name: 'describe', usage: 'describe [query] [--method <name>]', summary: 'the methods an exec script can call' },
|
|
55
|
+
{ name: 'mcp', usage: 'mcp [--http --port <n>]', summary: 'start the MCP server (the same as slatebox-mcp)' },
|
|
56
|
+
{ name: 'help', usage: 'help', summary: 'this text' },
|
|
57
|
+
])
|
|
58
|
+
const ALIASES = Object.freeze({ remove: 'uninstall' })
|
|
59
|
+
const SLATE_COMMANDS = new Set(['exec', 'describe', 'mcp'])
|
|
60
|
+
const COMMAND_NAMES = new Set(COMMANDS.map(command => command.name))
|
|
61
|
+
|
|
62
|
+
const commandList = () => COMMANDS.map(({ usage, summary }) => {
|
|
63
|
+
const left = ` slatebox ${usage}`
|
|
64
|
+
return left.length < 40 ? `${left.padEnd(41)}${summary}` : `${left}\n${' '.repeat(41)}${summary}`
|
|
65
|
+
}).join('\n')
|
|
66
|
+
|
|
67
|
+
export const HELP = `slatebox ${PKG.version}: run your own Slatebox, and work with any Slatebox from a script.
|
|
68
|
+
|
|
69
|
+
npx slatebox install asks where your team opens it (a free team address at
|
|
70
|
+
https://<name>.slatebox.team, your own domain, or this
|
|
71
|
+
computer only), shows a plan, installs
|
|
72
|
+
npx slatebox install --team-address acme --yes the same without questions (you still sign
|
|
73
|
+
in once in your browser to claim the address)
|
|
74
|
+
npx slatebox install --domain boards.example.com your own domain (Caddy HTTPS, or --url and your proxy)
|
|
75
|
+
npx slatebox --dry-run the questions and the plan only; nothing changes
|
|
76
|
+
npx slatebox agent-prompt instructions for a coding agent to do it for you
|
|
77
|
+
|
|
78
|
+
Commands:
|
|
79
|
+
${commandList()}
|
|
80
|
+
|
|
81
|
+
Install flags (each also SLATEBOX_INSTALL_<NAME> in the environment; flags win,
|
|
82
|
+
then --answers, then the environment. Consent never comes from the environment:
|
|
83
|
+
--yes, --install-docker and --new-encryption-key are typed each time):
|
|
84
|
+
--team-address <name> claim https://<name>.slatebox.team (3-32 characters: a-z, 0-9, hyphens)
|
|
85
|
+
--local this computer only (http://localhost), no team address
|
|
86
|
+
--name <id> several installs can live side by side (default slatebox)
|
|
87
|
+
--answers <file> YAML or JSON answers (see agent-prompt); never holds secrets
|
|
88
|
+
--target local|ssh|k8s|export --host user@host --ssh-port N --identity <key>
|
|
89
|
+
--ssh-option <opt> passed to ssh -o (repeatable) --install-docker (only with consent)
|
|
90
|
+
--domain <name> HTTPS with automatic certificates --url <address> --port <n>
|
|
91
|
+
--listen <ip> this computer only: 127.0.0.1 (default) or 0.0.0.0 for every interface
|
|
92
|
+
--admin-email <email>
|
|
93
|
+
--ai none | --ai-provider "kind=<openai|anthropic|deepinfra|openrouter|groq|together|mistral|ollama|lmstudio|openai-compatible>,model=<m>,url=<endpoint>,key=env:<VAR>"
|
|
94
|
+
(repeat for several, then --ai-default <id>; there is no default provider)
|
|
95
|
+
--sso --sso-only --sso-admin open|closed
|
|
96
|
+
--backups default|<dir>|s3://bucket/prefix|off --backup-schedule "0 3 * * *" --backup-keep 14
|
|
97
|
+
--size small|team|large --mail-url-from env:<VAR> --mail-from "Slatebox <b@example.com>"
|
|
98
|
+
--k8s-context <ctx> --namespace <ns> --route none|ingress|gateway --ingress-class <c>
|
|
99
|
+
--gateway-ref <ns/name> --tls-issuer ClusterIssuer/<name> --storage-class <sc>
|
|
100
|
+
--format compose|manifests|helm --out <dir> (target export)
|
|
101
|
+
--image <ref> --image-archive <file.tar> (a local build instead of the public image)
|
|
102
|
+
|
|
103
|
+
--new-encryption-key replace a lost SLATEBOX_KEY_ENCRYPTION_KEY over existing data
|
|
104
|
+
(keys people saved become unreadable; refused without it)
|
|
105
|
+
|
|
106
|
+
Moving a team (slatebox migrate --to cloud | --from cloud, import, export): your own server's
|
|
107
|
+
address is --from/--to <url>, SLATEBOX_BASE_URL, or the install made here (--name); its access
|
|
108
|
+
token is SLATEBOX_API_TOKEN (asked for at a terminal). Slatebox Cloud signs you in with a code in
|
|
109
|
+
your browser (it asks to "move your team"), or takes SLATEBOX_CLOUD_TOKEN. Nothing is visible on
|
|
110
|
+
the other side until you confirm. Then you are asked once to send invitations to the other members
|
|
111
|
+
(yes by default; --invite / --no-invite answer ahead; a script sends none without --invite; later:
|
|
112
|
+
slatebox migrate invite <move id> --to cloud|<url>), and whether to delete the archive from this
|
|
113
|
+
computer (no by default; --delete-archive, --keep-archive). --replace-waiting discards a move
|
|
114
|
+
already waiting.
|
|
115
|
+
|
|
116
|
+
Team addresses: the sign-in is a code you approve in your browser (Slatebox Cloud), every time
|
|
117
|
+
a name is claimed, moved or reconnected. SLATEBOX_CLOUD_URL or --cloud-url points at another
|
|
118
|
+
Slatebox Cloud. The install credential stays in
|
|
119
|
+
~/.slatebox/installs/<name>/credentials.json (mode 0600).
|
|
120
|
+
|
|
121
|
+
Global: --yes (after a person approved the plan) --json (NDJSON events on stdout)
|
|
122
|
+
--agent auto|yes|no --debug --health-timeout <seconds> (default 600)
|
|
123
|
+
|
|
124
|
+
Exit codes: 0 done or nothing to change; 2 bad flags or answers; 3 an answer or a
|
|
125
|
+
confirmation is needed and nobody can be asked; 4 a precondition failed;
|
|
126
|
+
5 the change failed and was rolled back; 6 the rollback failed too (commands
|
|
127
|
+
attached); 7 cancelled. (exec has its own: slatebox exec --help.)
|
|
128
|
+
`
|
|
129
|
+
|
|
130
|
+
// Agents that announce themselves in the environment.
|
|
131
|
+
const AGENT_ENV = ['AI_AGENT', 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'GEMINI_CLI', 'CURSOR_AGENT', 'CLINE_ACTIVE', 'AIDER_MODEL', 'OPENCODE']
|
|
132
|
+
|
|
133
|
+
export function detectAgent(env) {
|
|
134
|
+
return AGENT_ENV.some(name => env[name] && env[name] !== '0' && env[name] !== 'false')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function parse(argv) {
|
|
138
|
+
const options = {
|
|
139
|
+
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
|
|
140
|
+
yes: { type: 'boolean', short: 'y' }, json: { type: 'boolean' }, agent: { type: 'string' }, debug: { type: 'boolean' },
|
|
141
|
+
answers: { type: 'string' }, home: { type: 'string' }, 'image-archive': { type: 'string' }, 'health-timeout': { type: 'string' },
|
|
142
|
+
'dry-run': { type: 'boolean' }, 'show-secrets': { type: 'boolean' }, 'delete-data': { type: 'boolean' }, confirm: { type: 'string' },
|
|
143
|
+
to: { type: 'string' }, 'force-stdout': { type: 'boolean' }, 'new-encryption-key': { type: 'boolean' },
|
|
144
|
+
'cloud-url': { type: 'string' }, 'keep-address': { type: 'boolean' }, follow: { type: 'boolean', short: 'f' },
|
|
145
|
+
service: { type: 'string' }, since: { type: 'string' },
|
|
146
|
+
from: { type: 'string' }, out: { type: 'string' }, invite: { type: 'boolean' }, 'keep-archive': { type: 'boolean' },
|
|
147
|
+
passphrase: { type: 'string' }, 'replace-waiting': { type: 'boolean' }, 'delete-archive': { type: 'boolean' }, email: { type: 'string' },
|
|
148
|
+
}
|
|
149
|
+
for (const [flag, type] of Object.entries(ANSWER_FLAGS)) {
|
|
150
|
+
options[flag] = type === 'multiple' ? { type: 'string', multiple: true } : { type }
|
|
151
|
+
}
|
|
152
|
+
return parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true, strict: true })
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The closest command to a mistyped word, for "did you mean". */
|
|
156
|
+
export function suggest(word) {
|
|
157
|
+
const distance = (a, b) => {
|
|
158
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i)
|
|
159
|
+
for (let i = 1; i <= a.length; i++) {
|
|
160
|
+
let previous = row[0]
|
|
161
|
+
row[0] = i
|
|
162
|
+
for (let j = 1; j <= b.length; j++) {
|
|
163
|
+
const current = row[j]
|
|
164
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1))
|
|
165
|
+
previous = current
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return row[b.length]
|
|
169
|
+
}
|
|
170
|
+
const names = [...COMMAND_NAMES, ...Object.keys(ALIASES)]
|
|
171
|
+
const best = names.map(name => ({ name, d: distance(word.toLowerCase(), name) })).sort((a, b) => a.d - b.d)[0]
|
|
172
|
+
return best && best.d <= Math.max(1, Math.floor(word.length / 3)) ? best.name : null
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// exec, describe and mcp are slatebox-mcp's, a dependency of this package, run in this process.
|
|
176
|
+
async function slateCommand(argv, io) {
|
|
177
|
+
let commands
|
|
178
|
+
try {
|
|
179
|
+
commands = argv[0] === 'mcp' ? await import('slatebox-mcp/mcp') : await import('slatebox-mcp/commands')
|
|
180
|
+
} catch (error) {
|
|
181
|
+
io.stderr.write(`slatebox ${argv[0]} needs the slatebox-mcp package next to this one, and it could not be loaded (${error.code || error.message}). Reinstall: npm i -g slatebox\n`)
|
|
182
|
+
return EXIT.PRECONDITION
|
|
183
|
+
}
|
|
184
|
+
if (argv[0] === 'mcp') {
|
|
185
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
186
|
+
io.stdout.write('Usage: slatebox mcp [--base-url ORIGIN] [--typed-tools on|off] [--http [--port N]]\nThe same as slatebox-mcp: SLATEBOX_API_TOKEN is your personal access token.\n')
|
|
187
|
+
return 0
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
await commands.startMcp(argv.slice(1), { env: io.env, stderr: io.stderr })
|
|
191
|
+
return 0
|
|
192
|
+
} catch (error) {
|
|
193
|
+
io.stderr.write(`Slatebox MCP could not start: ${error.message}\n`)
|
|
194
|
+
return error.name === 'UsageError' || error.constructor?.name === 'UsageError' ? EXIT.USAGE : 1
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return commands.run(argv, { env: io.env, stdin: io.stdin, stdout: io.stdout, stderr: io.stderr, name: 'slatebox' })
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Plain `slatebox`: the commands, and at a terminal an offer to install. Never installs unasked. */
|
|
201
|
+
async function bare(io) {
|
|
202
|
+
const tty = Boolean(io.stdin.isTTY && io.stderr.isTTY) && !detectAgent(io.env)
|
|
203
|
+
const text = `slatebox ${PKG.version}: one container with the app, live editing and the database.\n\nCommands:\n${commandList()}\n\nMore: slatebox help\n`
|
|
204
|
+
if (!tty) {
|
|
205
|
+
io.stdout.write(text)
|
|
206
|
+
return 0
|
|
207
|
+
}
|
|
208
|
+
io.stderr.write(`${text}\n`)
|
|
209
|
+
const prompt = createPrompt({ input: io.stdin, output: io.stderr })
|
|
210
|
+
let yes
|
|
211
|
+
try { yes = await prompt.confirm('Install Slatebox on this computer?', { default: true }) } catch { yes = false } finally { prompt.close() }
|
|
212
|
+
if (!yes) {
|
|
213
|
+
io.stderr.write('Nothing was changed. When you are ready: npx slatebox install\n')
|
|
214
|
+
return 0
|
|
215
|
+
}
|
|
216
|
+
return main(['install'], io)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function readAnswersFile(path) {
|
|
220
|
+
if (!path) return undefined
|
|
221
|
+
let text
|
|
222
|
+
try { text = readFileSync(path, 'utf8') } catch (error) { throw new InstallError(EXIT.USAGE, `Cannot read the answers file ${path}: ${error.code || error.message}`) }
|
|
223
|
+
try {
|
|
224
|
+
const parsed = parseYaml(text)
|
|
225
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('it is not a map of answers')
|
|
226
|
+
if (parsed.version !== undefined && parsed.version !== 1) throw new Error(`version ${parsed.version} is not supported (this installer reads version 1)`)
|
|
227
|
+
return parsed
|
|
228
|
+
} catch (error) {
|
|
229
|
+
throw new InstallError(EXIT.USAGE, `The answers file ${path} is not valid: ${error.message}`)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* @param {string[]} argv arguments after "slatebox"
|
|
235
|
+
* @param {{env?: object, stdin?: any, stdout?: any, stderr?: any, run?: Function, fetch?: Function}} io
|
|
236
|
+
* @returns {Promise<number>} exit code
|
|
237
|
+
*/
|
|
238
|
+
export async function main(argv, io = {}) {
|
|
239
|
+
io = { env: process.env, stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, ...io }
|
|
240
|
+
io.platform ??= process.platform
|
|
241
|
+
io.cwd ??= process.cwd()
|
|
242
|
+
if (!argv.length) return bare(io)
|
|
243
|
+
if (ALIASES[argv[0]]) argv = [ALIASES[argv[0]], ...argv.slice(1)]
|
|
244
|
+
const [command] = argv
|
|
245
|
+
if (SLATE_COMMANDS.has(command)) return slateCommand(argv, io)
|
|
246
|
+
if (command && !command.startsWith('-') && !COMMAND_NAMES.has(command)) {
|
|
247
|
+
const near = suggest(command)
|
|
248
|
+
const message = `Unknown command ${command}.${near ? ` Did you mean slatebox ${near}?` : ''} See slatebox help.`
|
|
249
|
+
io.stderr.write(`${message}\n`)
|
|
250
|
+
if (argv.includes('--json')) io.stdout.write(JSON.stringify({ event: 'error', id: 'usage', status: 'failed', exitCode: EXIT.USAGE, message, ...(near ? { suggestion: near } : {}) }) + '\n')
|
|
251
|
+
return EXIT.USAGE
|
|
252
|
+
}
|
|
253
|
+
let parsed
|
|
254
|
+
try {
|
|
255
|
+
parsed = parse(argv)
|
|
256
|
+
} catch (error) {
|
|
257
|
+
io.stderr.write(`${error.message}\nSee slatebox --help.\n`)
|
|
258
|
+
if (argv.includes('--json')) io.stdout.write(JSON.stringify({ event: 'error', id: 'usage', status: 'failed', exitCode: EXIT.USAGE, message: error.message }) + '\n')
|
|
259
|
+
return EXIT.USAGE
|
|
260
|
+
}
|
|
261
|
+
const envFlags = flagsFromEnv(io.env)
|
|
262
|
+
const flags = { ...envFlags, ...parsed.values }
|
|
263
|
+
const positionals = parsed.positionals
|
|
264
|
+
if (flags.version) { io.stdout.write(`${PKG.version}\n`); return 0 }
|
|
265
|
+
if (flags.help || positionals[0] === 'help') { io.stdout.write(HELP); return 0 }
|
|
266
|
+
// Flags with no command (`npx slatebox --dry-run`, `--answers x --yes`) are the install.
|
|
267
|
+
if (!positionals.length) positionals.unshift('install')
|
|
268
|
+
|
|
269
|
+
const agentMode = flags.agent === 'yes' || (flags.agent !== 'no' && detectAgent(io.env))
|
|
270
|
+
const tty = Boolean(io.stdin.isTTY && io.stderr.isTTY)
|
|
271
|
+
const interactive = tty && !agentMode
|
|
272
|
+
const json = flags.json ?? agentMode
|
|
273
|
+
const redactor = new Redactor()
|
|
274
|
+
const out = new Output({ stdout: io.stdout, stderr: io.stderr, json, debug: Boolean(flags.debug), redactor })
|
|
275
|
+
const ctx = {
|
|
276
|
+
env: io.env, stdin: io.stdin, stdout: io.stdout, stderr: io.stderr, flags, version: PKG.version,
|
|
277
|
+
home: slateboxHome(io.env, flags.home), redactor, out, run: io.run || makeRunner(out), fetch: io.fetch || globalThis.fetch,
|
|
278
|
+
interactive, tty, agentMode, json, yes: Boolean(flags.yes), healthTimeout: Number(flags['health-timeout'] || 600),
|
|
279
|
+
cliFlags: parsed.values, platform: io.platform, cwd: io.cwd,
|
|
280
|
+
openBrowser: io.openBrowser, sleep: io.sleep, deviceLabel: io.deviceLabel, spawn: io.spawn,
|
|
281
|
+
teamHealthAttempts: io.teamHealthAttempts, teamHealthDelay: io.teamHealthDelay,
|
|
282
|
+
}
|
|
283
|
+
if (interactive) ctx.prompt = createPrompt({ input: io.stdin, output: io.stderr })
|
|
284
|
+
ctx.emitPlan = plan => {
|
|
285
|
+
out.event({ event: 'plan', ...plan })
|
|
286
|
+
const text = formatPlan(plan)
|
|
287
|
+
if (json) io.stderr.write(redactor.redact(text) + '\n')
|
|
288
|
+
else out.say(`\n${text}\n`)
|
|
289
|
+
}
|
|
290
|
+
ctx.confirm = async plan => {
|
|
291
|
+
if (ctx.yes) return
|
|
292
|
+
if (ctx.interactive) {
|
|
293
|
+
const local = plan.target === 'local' || plan.target === 'export'
|
|
294
|
+
if (await ctx.prompt.confirm('Apply this plan?', { default: local })) return
|
|
295
|
+
throw new InstallError(EXIT.CANCELLED, 'Cancelled; nothing was changed.')
|
|
296
|
+
}
|
|
297
|
+
throw new InstallError(EXIT.NEEDS_INPUT, 'This plan needs a yes. Show it to the person; once they agree, run the same command with --yes.', { needsConfirmation: true })
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
try {
|
|
301
|
+
const result = await dispatch(ctx, positionals, flags)
|
|
302
|
+
ctx.prompt?.close()
|
|
303
|
+
return result ?? 0
|
|
304
|
+
} catch (error) {
|
|
305
|
+
ctx.prompt?.close()
|
|
306
|
+
if (!(error instanceof InstallError)) {
|
|
307
|
+
out.event({ event: 'error', id: 'internal', status: 'failed', exitCode: 1, message: error.message })
|
|
308
|
+
io.stderr.write(redactor.redact(`✗ ${error.message}\n${flags.debug ? `${error.stack}\n` : ''}`))
|
|
309
|
+
return 1
|
|
310
|
+
}
|
|
311
|
+
const name = Object.entries(EXIT).find(([, code]) => code === error.exitCode)?.[0]?.toLowerCase().replace(/_/g, '-') || 'error'
|
|
312
|
+
out.event({ event: 'error', id: name, status: 'failed', exitCode: error.exitCode, message: error.message, ...error.details })
|
|
313
|
+
io.stderr.write(redactor.redact(`${error.exitCode === EXIT.NEEDS_INPUT ? '?' : '✗'} ${error.message}\n`))
|
|
314
|
+
if (error.details?.missing?.length && !json) {
|
|
315
|
+
for (const item of error.details.missing) io.stderr.write(` - ${item.field}: ${item.question}${item.flag ? ` (${item.flag})` : ''}\n`)
|
|
316
|
+
}
|
|
317
|
+
if (error.details?.fields?.length && !json) {
|
|
318
|
+
for (const item of error.details.fields) io.stderr.write(` - ${item.field}: ${item.message}\n`)
|
|
319
|
+
}
|
|
320
|
+
return error.exitCode
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function requireRecord(ctx, flags) {
|
|
325
|
+
const name = flags.name || 'slatebox'
|
|
326
|
+
const record = readRecord(ctx.home, name)
|
|
327
|
+
if (!record) {
|
|
328
|
+
const known = listRecords(ctx.home).map(item => item.name)
|
|
329
|
+
throw new InstallError(EXIT.PRECONDITION, `There is no install named "${name}" made from this computer.${known.length ? ` Installs here: ${known.join(', ')} (use --name).` : ' Run slatebox install first.'}`)
|
|
330
|
+
}
|
|
331
|
+
return record
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* The image an upgrade goes to: --to, else this package's release image for an
|
|
336
|
+
* install of the public image, else the install's own tag fetched again (a
|
|
337
|
+
* private registry stays a private registry).
|
|
338
|
+
*/
|
|
339
|
+
function upgradeImage(record, flags) {
|
|
340
|
+
if (flags.to || flags.image) return flags.to || flags.image
|
|
341
|
+
const current = record.imageRef || record.image
|
|
342
|
+
if (!current || current.startsWith(`${DEFAULT_REPOSITORY}:`) || current.startsWith(`${DEFAULT_REPOSITORY}@`)) return DEFAULT_IMAGE
|
|
343
|
+
if (isTag(current)) return current
|
|
344
|
+
throw new InstallError(EXIT.USAGE, `"${record.name}" runs ${current}, which is pinned and cannot get newer by itself. Name the new image: slatebox upgrade --to <image>.`)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function finish(ctx, done, lines = []) {
|
|
348
|
+
ctx.out.event({ event: 'done', ...done })
|
|
349
|
+
// { terminal } lines carry a setup link: straight to the terminal, past the redactor (setup-link.mjs).
|
|
350
|
+
for (const line of lines) {
|
|
351
|
+
if (typeof line === 'string') ctx.out.say(line)
|
|
352
|
+
else ctx.stderr.write(`${line.terminal}\n`)
|
|
353
|
+
}
|
|
354
|
+
return 0
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function prepareAnswers(ctx, flags, positionals) {
|
|
358
|
+
const target = positionals[1] && ['local', 'ssh', 'k8s', 'export'].includes(positionals[1]) ? positionals[1] : undefined
|
|
359
|
+
const host = target === 'ssh' ? positionals[2] : undefined
|
|
360
|
+
const file = readAnswersFile(flags.answers)
|
|
361
|
+
// Only flags typed on the command line here; collect() adds the environment below the answers file.
|
|
362
|
+
const cliFlags = { ...Object.fromEntries(Object.entries(ctx.cliFlags).filter(([key]) => key in ANSWER_FLAGS)), ...(target ? { target } : {}), ...(host ? { host } : {}) }
|
|
363
|
+
const name = cliFlags.name || file?.name || flags.name || 'slatebox'
|
|
364
|
+
const record = readRecord(ctx.home, name)
|
|
365
|
+
let partial = collect({ record, env: ctx.env, file, flags: cliFlags })
|
|
366
|
+
if (ctx.interactive) {
|
|
367
|
+
const kube = await ctx.run('kubectl', ['config', 'current-context']).catch(() => null)
|
|
368
|
+
ctx.currentContext = kube?.code === 0 ? kube.stdout.trim() : null
|
|
369
|
+
ctx.freePort = partial.address?.port ?? await defaultLocalPort()
|
|
370
|
+
partial = await interview(ctx, partial)
|
|
371
|
+
}
|
|
372
|
+
const freePort = (partial.target ?? 'local') === 'local' && partial.address?.port === undefined && !partial.address?.url ? await defaultLocalPort() : undefined
|
|
373
|
+
const { answers, missing, errors } = resolveAnswers(partial, { freePort, cwd: ctx.cwd, home: ctx.env.HOME })
|
|
374
|
+
if (errors.length) throw new InstallError(EXIT.USAGE, `Some answers are not valid: ${errors.map(error => error.field).join(', ')}.`, { fields: errors })
|
|
375
|
+
if (missing.length) throw new InstallError(EXIT.NEEDS_INPUT, `Some answers are needed: ${missing.map(item => item.field).join(', ')}.`, { missing })
|
|
376
|
+
return { answers, record, explicitContext: Boolean(cliFlags['k8s-context'] || file?.k8s?.context || record?.k8s?.context) }
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function applyTarget(ctx, answers, options) {
|
|
380
|
+
if (answers.target === 'k8s') return applyK8s(ctx, answers, options)
|
|
381
|
+
if (answers.target === 'export') return exportFiles(ctx, answers, options)
|
|
382
|
+
return applyDocker(ctx, answers, { ...options, archive: ctx.flags['image-archive'] })
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function closing(ctx, done) {
|
|
386
|
+
if (done.nothingToChange) return [`Nothing to change: ${done.name} is running at ${done.address}.${done.teamAddress ? ' (slatebox upgrade gets a newer image.)' : ''}`, ...setupLines(ctx, done.name)]
|
|
387
|
+
if (done.target === 'export') return [`Wrote ${done.files.length} files to ${done.dir}. Nothing was applied.`]
|
|
388
|
+
const lines = ['', `Slatebox is running at ${done.address}`, ...setupLines(ctx, done.name)]
|
|
389
|
+
if (done.teamAddress) {
|
|
390
|
+
lines.push('', `On this computer it also answers at ${done.localAddress}.`,
|
|
391
|
+
'', `Keep a copy of ${installDir(ctx.home, done.name)}/ (keys and the team-address credential).`)
|
|
392
|
+
}
|
|
393
|
+
if (done.keyGenerated) {
|
|
394
|
+
lines.push('', `Your key encryption key is stored in ${done.secretsFile}. Back it up with your password manager now.`,
|
|
395
|
+
'Backups do not contain it, and without it people\'s saved AI keys cannot be read after a restore.')
|
|
396
|
+
}
|
|
397
|
+
lines.push(`Install record: ${done.installRecord}`, `Next: slatebox status slatebox logs slatebox upgrade slatebox uninstall${done.name === 'slatebox' ? '' : ` (--name ${done.name})`}`)
|
|
398
|
+
return lines
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// install --from cloud: the server is new and has no admin yet, so the team comes over once the
|
|
402
|
+
// person has made the first account (the setup link above) and an access token there.
|
|
403
|
+
function fromCloudLines(done) {
|
|
404
|
+
if (done.target === 'export') return []
|
|
405
|
+
return [
|
|
406
|
+
'', 'To bring your team over from Slatebox Cloud:',
|
|
407
|
+
' 1. Open the setup link above and create your account.',
|
|
408
|
+
` 2. In ${done.address}, open Profile → Developer and make an access token with "Move a team here".`,
|
|
409
|
+
` 3. Run: SLATEBOX_API_TOKEN=<that token> npx slatebox import --from cloud${done.name === 'slatebox' ? '' : ` --name ${done.name}`}`,
|
|
410
|
+
' (you sign in to Slatebox Cloud in your browser; nothing is copied until you confirm)',
|
|
411
|
+
]
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function showSecretOnce(ctx, record, name) {
|
|
415
|
+
if (ctx.json || !(ctx.stdout.isTTY || ctx.flags['force-stdout'])) {
|
|
416
|
+
throw new InstallError(EXIT.USAGE, 'Secrets are printed only to a terminal, never with --json or into a pipe (add --force-stdout if you really mean to).')
|
|
417
|
+
}
|
|
418
|
+
const value = record.target === 'k8s' ? await readSecretK8s(ctx, record, name) : await readSecretDocker(ctx, record, name)
|
|
419
|
+
if (!value) throw new InstallError(EXIT.PRECONDITION, `${name} is not set for "${record.name}".`)
|
|
420
|
+
ctx.stdout.write(`${value}\n`)
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async function dispatch(ctx, positionals, flags) {
|
|
424
|
+
const [command, sub, ...rest] = positionals
|
|
425
|
+
switch (command) {
|
|
426
|
+
case 'agent-prompt':
|
|
427
|
+
ctx.stdout.write(AGENT_PROMPT)
|
|
428
|
+
return 0
|
|
429
|
+
case 'migrate': {
|
|
430
|
+
if (sub === 'invite') return inviteMovedPeople(ctx, { id: rest[0], to: flags.to })
|
|
431
|
+
if (sub) throw new InstallError(EXIT.USAGE, `Unknown: slatebox migrate ${sub}. Use slatebox migrate --to cloud, --from cloud, or slatebox migrate invite <move id> --to cloud|<url>.`)
|
|
432
|
+
if (!flags.to && !flags.from) throw new InstallError(EXIT.USAGE, 'Say which way: slatebox migrate --to cloud (your own server to Slatebox Cloud) or slatebox migrate --from cloud (Slatebox Cloud to your own server).')
|
|
433
|
+
return moveTeam(ctx, { from: flags.from, to: flags.to })
|
|
434
|
+
}
|
|
435
|
+
case 'import': {
|
|
436
|
+
if (sub) return importTeamFile(ctx, { file: sub, to: flags.to })
|
|
437
|
+
if (!flags.from) throw new InstallError(EXIT.USAGE, 'Import from where? slatebox import --from cloud, or slatebox import <file.sbxteam>.')
|
|
438
|
+
return moveTeam(ctx, { from: flags.from, to: flags.to })
|
|
439
|
+
}
|
|
440
|
+
case 'export':
|
|
441
|
+
return exportTeamFile(ctx, { from: flags.from, out: flags.out })
|
|
442
|
+
case 'installs': {
|
|
443
|
+
const records = listRecords(ctx.home)
|
|
444
|
+
ctx.out.event({ event: 'done', installs: records.map(record => ({ name: record.name, target: record.target, address: record.address?.url, state: record.state })) })
|
|
445
|
+
if (!ctx.json) for (const record of records) ctx.out.say(`${record.name.padEnd(16)} ${String(record.target).padEnd(7)} ${record.address?.url || ''} ${record.state === 'installed' ? '' : `(${record.state})`}`)
|
|
446
|
+
if (!records.length) ctx.out.say('No installs made from this computer yet.')
|
|
447
|
+
return 0
|
|
448
|
+
}
|
|
449
|
+
case 'plan':
|
|
450
|
+
case 'install': {
|
|
451
|
+
const { answers, record, explicitContext } = await prepareAnswers(ctx, flags, positionals)
|
|
452
|
+
const planOnly = command === 'plan' || Boolean(flags['dry-run'])
|
|
453
|
+
const done = await applyTarget(ctx, answers, { record, planOnly, explicitContext })
|
|
454
|
+
if (done.planned) {
|
|
455
|
+
ctx.out.event({ event: 'done', planned: true, name: answers.name, target: answers.target })
|
|
456
|
+
if (!ctx.json) ctx.out.say(`Nothing was changed. To apply: slatebox install ${flags.answers ? `--answers ${flags.answers} ` : ''}... (the same answers)${ctx.interactive ? '' : ' --yes'}`)
|
|
457
|
+
return 0
|
|
458
|
+
}
|
|
459
|
+
finish(ctx, done, [...closing(ctx, done), ...(flags.from === 'cloud' ? fromCloudLines(done) : [])])
|
|
460
|
+
if (flags['show-secrets'] && done.keyGenerated) await showSecretOnce(ctx, ctx.record, 'SLATEBOX_KEY_ENCRYPTION_KEY')
|
|
461
|
+
return 0
|
|
462
|
+
}
|
|
463
|
+
case 'upgrade': {
|
|
464
|
+
const record = requireRecord(ctx, flags)
|
|
465
|
+
const { answers, errors } = resolveAnswers(collect({ record }), {})
|
|
466
|
+
if (errors.length) throw new InstallError(EXIT.USAGE, 'The install record is not valid.', { fields: errors })
|
|
467
|
+
const imageRef = upgradeImage(record, flags)
|
|
468
|
+
const done = await applyTarget(ctx, answers, { record, imageRef, explicitContext: true, refresh: true })
|
|
469
|
+
return finish(ctx, done, done.nothingToChange ? [`Already up to date: ${done.name} runs ${done.imageDigest}.`] : ['', `Upgraded. Slatebox is running at ${done.address} (${done.imageDigest}).`])
|
|
470
|
+
}
|
|
471
|
+
case 'status': {
|
|
472
|
+
const record = requireRecord(ctx, flags)
|
|
473
|
+
const status = record.target === 'k8s' ? await statusK8s(ctx, record) : await statusDocker(ctx, record)
|
|
474
|
+
if (record.address?.team) status.teamAddress = await teamStatus(ctx, record)
|
|
475
|
+
ctx.out.event({ event: 'done', ...status })
|
|
476
|
+
if (!ctx.json) {
|
|
477
|
+
for (const [label, value] of Object.entries({ Name: status.name, Where: status.where, Address: status.address, ...(status.teamAddress ? { 'Team address': teamLine(status) } : {}), Health: status.health, ...(status.setup === 'waiting for the first admin' ? { Setup: `waiting for the first admin: ${record.name === 'slatebox' ? 'slatebox setup-link' : `slatebox setup-link --name ${record.name}`} prints a one-time link` } : {}), Version: status.version ? `app ${status.version.app}, engine ${status.version.engine}` : '-', Image: status.imageDigest, AI: status.ai, SSO: status.sso, 'Last backup': status.lastBackup || 'none yet' })) {
|
|
478
|
+
ctx.out.say(`${label.padEnd(12)} ${value}`)
|
|
479
|
+
}
|
|
480
|
+
if (status.tunnel?.connectors > 1) ctx.out.warn(`The tunnel has ${status.tunnel.connectors} connectors. If you did not start a second copy of this install, someone may hold its tunnel token: slatebox address rotate`)
|
|
481
|
+
}
|
|
482
|
+
return status.health === 'healthy' ? 0 : EXIT.PRECONDITION
|
|
483
|
+
}
|
|
484
|
+
case 'setup-link': {
|
|
485
|
+
const record = requireRecord(ctx, flags)
|
|
486
|
+
// As good as an admin password: a terminal only, never --json or a pipe, unless --force-stdout.
|
|
487
|
+
if (ctx.json || !(ctx.stdout.isTTY || flags['force-stdout'])) {
|
|
488
|
+
throw new InstallError(EXIT.USAGE, 'The setup link is printed only to a terminal, never with --json or into a pipe (add --force-stdout if you really mean to).')
|
|
489
|
+
}
|
|
490
|
+
const link = record.target === 'k8s' ? await setupLinkK8s(ctx, record) : await setupLinkDocker(ctx, record)
|
|
491
|
+
if (link.setUp) throw new InstallError(EXIT.PRECONDITION, `"${record.name}" is already set up: its administrator invites people from the Team page. A lost password: docker exec ${record.name} slatebox password-link <email>`)
|
|
492
|
+
if (!link.url) throw new InstallError(EXIT.PRECONDITION, `No setup link could be made (${link.error}). Is "${record.name}" running an image from 0.2.0 on? slatebox status; slatebox upgrade`)
|
|
493
|
+
ctx.stdout.write(`${link.url}\n`)
|
|
494
|
+
ctx.stderr.write('Open it to create the first account: the server administrator and the owner of the first team.\nIt works once, expires in 24 hours, and the link before it no longer works.\n')
|
|
495
|
+
return 0
|
|
496
|
+
}
|
|
497
|
+
case 'backup': {
|
|
498
|
+
const record = requireRecord(ctx, flags)
|
|
499
|
+
const result = record.target === 'k8s' ? await backupK8s(ctx, record, { to: flags.to }) : await backupDocker(ctx, record, { to: flags.to })
|
|
500
|
+
return finish(ctx, { name: record.name, ...result }, [`Backup written to ${result.file}${result.where === 'this computer' ? '' : ` on ${result.where}`}.`, 'It does not contain SLATEBOX_KEY_ENCRYPTION_KEY: keep that with it (slatebox secrets path).'])
|
|
501
|
+
}
|
|
502
|
+
case 'restore': {
|
|
503
|
+
const record = requireRecord(ctx, flags)
|
|
504
|
+
const archive = sub
|
|
505
|
+
if (!archive || !existsSync(archive)) throw new InstallError(EXIT.USAGE, 'Name the backup file: slatebox restore <file.gz>')
|
|
506
|
+
const where = record.target === 'k8s' ? `context ${record.k8s.context}, namespace ${record.k8s.namespace}` : record.target === 'ssh' ? record.ssh.host : 'this computer'
|
|
507
|
+
const plan = { action: 'restore', target: record.target, name: record.name, where, address: record.address.url, files: [{ path: archive, note: 'the backup to restore' }], commands: [`slatebox restore < ${archive} (inside the ${record.target === 'k8s' ? 'pod' : 'container'})`], objects: [], ports: [], secretsLocation: record.secretsLocation, warnings: [`This replaces every slate, account and stored file of "${record.name}" with the contents of ${archive}. Anything made since that backup is lost. Take a backup first (slatebox backup) if you may want it back.`], notes: ['The backup does not hold SLATEBOX_KEY_ENCRYPTION_KEY: saved keys are readable only if this install still has the key it had when the backup was taken.'], changes: [] }
|
|
508
|
+
ctx.emitPlan(plan)
|
|
509
|
+
await ctx.confirm(plan)
|
|
510
|
+
const result = record.target === 'k8s' ? await restoreK8s(ctx, record, archive) : await restoreDocker(ctx, record, archive)
|
|
511
|
+
return finish(ctx, { name: record.name, ...result }, [`Restored ${archive}. Slatebox is ready.`])
|
|
512
|
+
}
|
|
513
|
+
case 'uninstall': {
|
|
514
|
+
const record = requireRecord(ctx, flags)
|
|
515
|
+
const deleteData = Boolean(flags['delete-data'])
|
|
516
|
+
const release = Boolean(record.address?.team) && !flags['keep-address'] && Boolean(readCredentials(ctx.home, record.name))
|
|
517
|
+
if (deleteData) {
|
|
518
|
+
let typed = flags.confirm
|
|
519
|
+
if (!typed && ctx.interactive) typed = await ctx.prompt.text(`This deletes every slate and account of "${record.name}". Type its name to confirm`, { optional: true })
|
|
520
|
+
if (typed !== record.name) throw new InstallError(ctx.interactive ? EXIT.CANCELLED : EXIT.NEEDS_INPUT, `Deleting data needs the install's name typed back: --confirm ${record.name}. Nothing was changed.`, { needsConfirmation: true })
|
|
521
|
+
}
|
|
522
|
+
const plan = { action: 'uninstall', target: record.target, name: record.name, where: record.target === 'ssh' ? record.ssh.host : record.target === 'k8s' ? record.k8s.context : 'this computer', address: record.address.url, files: [], commands: [], objects: [], ports: [], secretsLocation: record.secretsLocation, warnings: [...(deleteData ? ['Data, secrets and backups next to the install will be deleted.'] : []), ...(release ? [`${teamHost(record.address.team)} is released (held for your account for 30 days, then anyone may claim it). Keep it with --keep-address.`] : [])], notes: deleteData ? [] : ['The data volume and the secrets are kept; install again with the same --name to get it back.'], changes: [] }
|
|
523
|
+
ctx.emitPlan(plan)
|
|
524
|
+
await ctx.confirm(plan)
|
|
525
|
+
const result = record.target === 'k8s' ? await uninstallK8s(ctx, record, { deleteData }) : await uninstallDocker(ctx, record, { deleteData })
|
|
526
|
+
let released = null
|
|
527
|
+
if (release) {
|
|
528
|
+
released = await releaseTeamAddress(ctx, record, { offlineOk: true })
|
|
529
|
+
if (released.released) ctx.out.step('address', 'ok', `Released ${released.host} (held for your account for 30 days, then anyone may claim it)`)
|
|
530
|
+
else ctx.out.step('address', 'warn', `${released.why} ${released.host} is still yours; release it later with: slatebox address release${record.name === 'slatebox' ? '' : ` --name ${record.name}`} (the credential is kept for that). Unused addresses are released by Slatebox Cloud after 24 hours without a connection anyway.`)
|
|
531
|
+
}
|
|
532
|
+
const keepCredential = released && !released.released
|
|
533
|
+
if (deleteData) {
|
|
534
|
+
const dir = installDir(ctx.home, record.name)
|
|
535
|
+
if (keepCredential) {
|
|
536
|
+
for (const entry of existsSync(dir) ? readdirSync(dir) : []) if (entry !== CREDENTIALS_FILE) rmSync(join(dir, entry), { recursive: true, force: true })
|
|
537
|
+
} else rmSync(dir, { recursive: true, force: true })
|
|
538
|
+
} else {
|
|
539
|
+
writeRecord(ctx.home, { ...record, ...(released?.released ? { address: localAddress(record) } : {}), state: 'uninstalled' })
|
|
540
|
+
}
|
|
541
|
+
const summary = { name: record.name, ...result, ...(released ? { addressReleased: released.released } : {}) }
|
|
542
|
+
return finish(ctx, summary, [deleteData ? `Removed "${record.name}" and its data.` : `Removed "${record.name}". Kept: ${result.volume} and ${result.secretsFile}. To delete them too: slatebox uninstall --name ${record.name} --delete-data --confirm ${record.name}`])
|
|
543
|
+
}
|
|
544
|
+
case 'logs': {
|
|
545
|
+
const record = requireRecord(ctx, flags)
|
|
546
|
+
if (flags.service && !LOG_SERVICES.includes(flags.service)) throw new InstallError(EXIT.USAGE, `--service is one of ${LOG_SERVICES.join(', ')}.`)
|
|
547
|
+
if (flags.since && !/^\d+[smhd]?$|^\d{4}-\d{2}-\d{2}/.test(flags.since)) throw new InstallError(EXIT.USAGE, '--since is a duration like 10m or 2h, or a date.')
|
|
548
|
+
if (record.target === 'k8s') {
|
|
549
|
+
const args = ['--context', record.k8s.context, 'logs', '-n', record.k8s.namespace, `${record.name}-0`, '-c', 'slatebox', ...(flags.since ? ['--since', flags.since] : ['--tail', '500'])]
|
|
550
|
+
const result = await ctx.run('kubectl', args, { timeout: 120_000 })
|
|
551
|
+
if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `kubectl logs failed: ${result.stderr.trim().split('\n').pop()}`)
|
|
552
|
+
for (const line of result.stdout.split('\n')) if (line && (!flags.service || line.startsWith(`[${flags.service}] `))) ctx.stdout.write(`${ctx.redactor.redact(line)}\n`)
|
|
553
|
+
return 0
|
|
554
|
+
}
|
|
555
|
+
await logsDocker(ctx, record, { follow: Boolean(flags.follow), service: flags.service, since: flags.since })
|
|
556
|
+
return 0
|
|
557
|
+
}
|
|
558
|
+
case 'rename': {
|
|
559
|
+
const record = requireRecord(ctx, flags)
|
|
560
|
+
if (!record.address?.team) throw new InstallError(EXIT.USAGE, `"${record.name}" has no team address. Add one with: slatebox install --team-address <name>`)
|
|
561
|
+
if (!sub) throw new InstallError(EXIT.USAGE, 'Name the new address: slatebox rename <new-name>')
|
|
562
|
+
const renamed = await renameTeamAddress(ctx, record, sub.toLowerCase())
|
|
563
|
+
ctx.out.step('address', 'ok', `${renamed.host} is yours; moving "${record.name}" to it`)
|
|
564
|
+
const done = await reapply(ctx, { ...record, address: { ...record.address, team: renamed.name, url: undefined } })
|
|
565
|
+
const finished = await finishRename(ctx, { ...record, address: { ...record.address, team: renamed.name } })
|
|
566
|
+
if (finished.done) ctx.out.step('address', 'ok', `${teamHost(renamed.previousName)} no longer points here (held for your account for 30 days)`)
|
|
567
|
+
else ctx.out.step('address', 'warn', `Could not tell Slatebox Cloud the move is done (${finished.why}); the old address is dropped by itself within 24 hours.`)
|
|
568
|
+
return finish(ctx, { ...done, previousAddress: `https://${teamHost(renamed.previousName)}` }, ['', `Slatebox is now at ${done.address}`])
|
|
569
|
+
}
|
|
570
|
+
case 'address': {
|
|
571
|
+
const record = readRecord(ctx.home, flags.name || 'slatebox')
|
|
572
|
+
if (!sub || sub === 'status') {
|
|
573
|
+
const current = requireRecord(ctx, flags)
|
|
574
|
+
if (!current.address?.team) {
|
|
575
|
+
ctx.out.event({ event: 'done', name: current.name, teamAddress: null, address: current.address.url })
|
|
576
|
+
ctx.out.say(`"${current.name}" has no team address; it is at ${current.address.url}. Add one with: slatebox install --team-address <name>`)
|
|
577
|
+
return 0
|
|
578
|
+
}
|
|
579
|
+
const team = await teamStatus(ctx, current)
|
|
580
|
+
ctx.out.event({ event: 'done', name: current.name, teamAddress: team })
|
|
581
|
+
if (!ctx.json) ctx.out.say(`${team.host}: ${team.status}${team.suspension?.notice ? ` (${team.suspension.notice})` : ''}`)
|
|
582
|
+
return team.status === 'active' ? 0 : EXIT.PRECONDITION
|
|
583
|
+
}
|
|
584
|
+
if (sub === 'release') {
|
|
585
|
+
// Works from the credential alone, so an address left over after an offline uninstall can still be given back.
|
|
586
|
+
const target = record || { name: flags.name || 'slatebox', address: {} }
|
|
587
|
+
const released = await releaseTeamAddress(ctx, target)
|
|
588
|
+
ctx.out.step('address', 'ok', `Released ${released.host} (held for your account for 30 days, then anyone may claim it)`)
|
|
589
|
+
if (record && record.state !== 'uninstalled' && record.address?.team) {
|
|
590
|
+
const done = await reapply(ctx, { ...record, address: localAddress(record) })
|
|
591
|
+
return finish(ctx, { ...done, addressReleased: true }, ['', `"${record.name}" now answers only at ${done.address}.`])
|
|
592
|
+
}
|
|
593
|
+
if (record?.address?.team) writeRecord(ctx.home, { ...record, address: localAddress(record) })
|
|
594
|
+
if (!record && existsSync(installDir(ctx.home, target.name)) && !readdirSync(installDir(ctx.home, target.name)).length) rmSync(installDir(ctx.home, target.name), { recursive: true, force: true })
|
|
595
|
+
return finish(ctx, { name: target.name, addressReleased: true }, [])
|
|
596
|
+
}
|
|
597
|
+
if (sub === 'rotate') {
|
|
598
|
+
const current = requireRecord(ctx, flags)
|
|
599
|
+
if (!current.address?.team) throw new InstallError(EXIT.USAGE, `"${current.name}" has no team address.`)
|
|
600
|
+
await rotateTeamAddress(ctx, current)
|
|
601
|
+
ctx.out.step('address', 'ok', 'New tunnel secret: every connector holding the old token was dropped')
|
|
602
|
+
const done = await reapply(ctx, current)
|
|
603
|
+
return finish(ctx, { ...done, rotated: true }, ['', `${done.address} now uses the new tunnel token.`])
|
|
604
|
+
}
|
|
605
|
+
throw new InstallError(EXIT.USAGE, 'Usage: slatebox address [status | release | rotate]')
|
|
606
|
+
}
|
|
607
|
+
case 'ai':
|
|
608
|
+
return aiCommand(ctx, flags, sub, rest)
|
|
609
|
+
case 'secrets': {
|
|
610
|
+
const record = requireRecord(ctx, flags)
|
|
611
|
+
if (sub === 'reveal') {
|
|
612
|
+
if (!rest[0]) throw new InstallError(EXIT.USAGE, 'Name the secret: slatebox secrets reveal SLATEBOX_KEY_ENCRYPTION_KEY')
|
|
613
|
+
await showSecretOnce(ctx, record, rest[0])
|
|
614
|
+
return 0
|
|
615
|
+
}
|
|
616
|
+
ctx.out.event({ event: 'done', name: record.name, secretsLocation: record.secretsLocation, secrets: Object.keys(record.secretRefs || {}) })
|
|
617
|
+
if (!ctx.json) ctx.out.say(`${record.secretsLocation}\nHolds: ${Object.keys(record.secretRefs || {}).join(', ')}`)
|
|
618
|
+
return 0
|
|
619
|
+
}
|
|
620
|
+
default:
|
|
621
|
+
throw new InstallError(EXIT.USAGE, `Unknown command ${command}. See slatebox --help.`)
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function teamLine(status) {
|
|
626
|
+
const team = status.teamAddress
|
|
627
|
+
const connections = status.tunnel?.ready ? `, ${status.tunnel.connections} connection${status.tunnel.connections === 1 ? '' : 's'}` : status.tunnel?.state === 'failed' ? ', tunnel refused by Cloudflare' : status.tunnel ? ', tunnel not connected' : ''
|
|
628
|
+
return `https://${team.host} (${team.status}${connections})${team.suspension?.notice ? `: ${team.suspension.notice}` : ''}`
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** The install's address without its team address: this computer only (or the server's own address). */
|
|
632
|
+
function localAddress(record) {
|
|
633
|
+
if (record.target === 'k8s') return { url: `http://localhost:7070` }
|
|
634
|
+
const port = record.address?.port ?? 7070
|
|
635
|
+
return { url: undefined, port, listen: record.address?.listen ?? '127.0.0.1', team: null }
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** Apply an install record again (same image), after its address or tunnel token changed. */
|
|
639
|
+
async function reapply(ctx, record) {
|
|
640
|
+
const { answers, errors } = resolveAnswers(collect({ record }), {})
|
|
641
|
+
if (errors.length) throw new InstallError(EXIT.USAGE, `The install record is not valid: ${errors.map(error => `${error.field} (${error.message})`).join('; ')}`, { fields: errors })
|
|
642
|
+
return applyTarget(ctx, answers, { record, imageRef: record.imageRef, explicitContext: true })
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// ------------------------------------------------------------------ ai
|
|
646
|
+
|
|
647
|
+
async function aiCommand(ctx, flags, sub, rest) {
|
|
648
|
+
const record = requireRecord(ctx, flags)
|
|
649
|
+
const ai = structuredClone(record.ai)
|
|
650
|
+
const providers = ai.mode === 'providers' ? ai.providers : []
|
|
651
|
+
if (!sub || sub === 'list') {
|
|
652
|
+
ctx.out.event({ event: 'done', name: record.name, ai: record.ai })
|
|
653
|
+
if (!ctx.json) {
|
|
654
|
+
if (!providers.length) ctx.out.say('AI is off. Add a provider: slatebox ai add "kind=openai,model=gpt-5-mini,key=env:OPENAI_API_KEY"')
|
|
655
|
+
for (const provider of providers) ctx.out.say(`${provider.id === ai.default ? '*' : ' '} ${provider.id.padEnd(14)} ${provider.kind.padEnd(18)} ${provider.model || ''} ${provider.baseUrl || ''} key: ${provider.keyFrom}`)
|
|
656
|
+
}
|
|
657
|
+
return 0
|
|
658
|
+
}
|
|
659
|
+
if (sub === 'test') {
|
|
660
|
+
const chosen = rest[0] ? providers.find(provider => provider.id === rest[0]) : providers.find(provider => provider.id === ai.default) || providers[0]
|
|
661
|
+
if (!chosen) throw new InstallError(EXIT.PRECONDITION, rest[0] ? `No AI provider "${rest[0]}".` : 'AI is off for this install.')
|
|
662
|
+
const multi = Object.keys(record.secretRefs || {}).some(name => name.startsWith('SLATEBOX_AI_KEY_')) || providers.length > 1
|
|
663
|
+
const located = aiEnv({ mode: 'providers', providers: [chosen], default: chosen.id }, multi ? { settings: ['SLATEBOX_AI_PROVIDERS'] } : null, { target: record.target })
|
|
664
|
+
const provider = normalizeProvider(chosen)
|
|
665
|
+
const baseUrl = provider.kind === 'deepinfra' ? 'https://api.deepinfra.com/v1/openai' : multi ? JSON.parse(located.env.SLATEBOX_AI_PROVIDERS)[0].baseUrl : located.env.SLATEBOX_AI_URL
|
|
666
|
+
const keyEnv = provider.keyFrom === 'none' ? '' : multi ? Object.keys(located.secrets)[0] : 'SLATEBOX_AI_KEY'
|
|
667
|
+
ctx.out.step('ai-test', 'start', `Testing ${chosen.id} from inside the container (${baseUrl})`)
|
|
668
|
+
const run = record.target === 'k8s' ? execNodeK8s : execNode
|
|
669
|
+
const result = await run(ctx, record, aiTestScript(), [baseUrl, provider.model || '', keyEnv])
|
|
670
|
+
let report
|
|
671
|
+
try { report = JSON.parse(result.stdout.trim().split('\n').pop()) } catch { throw new InstallError(EXIT.PRECONDITION, `The test could not run in the container: ${result.stderr.trim().split('\n').pop()}`) }
|
|
672
|
+
ctx.out.event({ event: 'done', name: record.name, provider: chosen.id, ...report })
|
|
673
|
+
if (!ctx.json) {
|
|
674
|
+
ctx.out.say(`Endpoint: ${report.baseUrl}`)
|
|
675
|
+
ctx.out.say(`Models: ${Array.isArray(report.models) ? report.models.slice(0, 8).join(', ') || '(none listed)' : report.models}`)
|
|
676
|
+
ctx.out.say(`Tool calls: ${report.toolCalls === null ? '-' : report.toolCalls ? 'yes' : 'no'}`)
|
|
677
|
+
ctx.out.say(`tool_choice: ${report.toolChoiceHonoured === null ? '-' : report.toolChoiceHonoured ? 'honoured' : 'ignored (Slatebox falls back to plain text for this model)'}`)
|
|
678
|
+
ctx.out.say(`Latency: ${report.latencyMs ?? '-'} ms`)
|
|
679
|
+
if (report.error) ctx.out.say(`Problem: ${report.error}`)
|
|
680
|
+
}
|
|
681
|
+
return report.error ? EXIT.PRECONDITION : 0
|
|
682
|
+
}
|
|
683
|
+
if (sub === 'add') {
|
|
684
|
+
if (!rest[0]) throw new InstallError(EXIT.USAGE, 'Usage: slatebox ai add "kind=openai,model=gpt-5-mini,key=env:OPENAI_API_KEY"')
|
|
685
|
+
const added = parseProviderSpec(rest[0])
|
|
686
|
+
if (providers.some(provider => provider.id === added.id)) throw new InstallError(EXIT.USAGE, `There is already a provider "${added.id}"; give another id=.`)
|
|
687
|
+
ai.mode = 'providers'
|
|
688
|
+
ai.providers = [...providers, added]
|
|
689
|
+
if (flags['ai-default']) ai.default = flags['ai-default']
|
|
690
|
+
else if (ai.providers.length === 1) ai.default = added.id
|
|
691
|
+
} else if (sub === 'remove') {
|
|
692
|
+
if (!providers.some(provider => provider.id === rest[0])) throw new InstallError(EXIT.USAGE, `No AI provider "${rest[0]}".`)
|
|
693
|
+
ai.providers = providers.filter(provider => provider.id !== rest[0])
|
|
694
|
+
if (!ai.providers.length) { ai.mode = 'none'; delete ai.providers; delete ai.default }
|
|
695
|
+
else if (ai.default === rest[0]) ai.default = ai.providers.length === 1 ? ai.providers[0].id : undefined
|
|
696
|
+
} else if (sub === 'use') {
|
|
697
|
+
if (!providers.some(provider => provider.id === rest[0])) throw new InstallError(EXIT.USAGE, `No AI provider "${rest[0]}".`)
|
|
698
|
+
ai.default = rest[0]
|
|
699
|
+
} else if (sub === 'off') {
|
|
700
|
+
ai.mode = 'none'
|
|
701
|
+
delete ai.providers
|
|
702
|
+
delete ai.default
|
|
703
|
+
} else {
|
|
704
|
+
throw new InstallError(EXIT.USAGE, 'Usage: slatebox ai list | add "<spec>" | remove <id> | use <id> | off | test [id]')
|
|
705
|
+
}
|
|
706
|
+
const { answers, errors } = resolveAnswers(collect({ record: { ...record, ai } }), {})
|
|
707
|
+
if (errors.length) throw new InstallError(EXIT.USAGE, `That AI change is not valid: ${errors.map(error => `${error.field} (${error.message})`).join('; ')}`, { fields: errors })
|
|
708
|
+
// Same image, new settings: the change path, with its plan, health check and rollback.
|
|
709
|
+
const done = await applyTarget(ctx, answers, { record, imageRef: record.imageRef, explicitContext: true })
|
|
710
|
+
return finish(ctx, done, done.nothingToChange ? ['Nothing to change.'] : [`AI is now ${answers.ai.mode === 'none' ? 'off' : `${answers.ai.providers.map(provider => provider.id).join(', ')} (default ${answers.ai.default})`} for ${answers.name}.`])
|
|
711
|
+
}
|