slatebox 0.0.0-stage → 0.1.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 +151 -2
- package/bin/slatebox.mjs +9 -0
- package/package.json +41 -4
- package/src/agent-prompt.mjs +64 -0
- package/src/ai/settings-adapter.mjs +198 -0
- package/src/answers.mjs +489 -0
- package/src/cli.mjs +477 -0
- package/src/errors.mjs +23 -0
- package/src/image.mjs +138 -0
- package/src/interview.mjs +170 -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 +59 -0
- package/src/runner.mjs +50 -0
- package/src/secret-values.mjs +40 -0
- package/src/secrets.mjs +119 -0
- package/src/targets/docker.mjs +685 -0
- package/src/targets/export.mjs +73 -0
- package/src/targets/hosts.mjs +202 -0
- package/src/targets/k8s.mjs +366 -0
- package/src/yaml.mjs +293 -0
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
// `slatebox`: install and run your own Slatebox, and (delegated to the
|
|
2
|
+
// slatebox-mcp package) work with slates. main() takes its streams and
|
|
3
|
+
// environment as arguments and returns the exit code, so tests run it in
|
|
4
|
+
// process.
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
6
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
7
|
+
import { createRequire } from 'node:module'
|
|
8
|
+
import { fileURLToPath } from 'node:url'
|
|
9
|
+
import { parseArgs } from 'node:util'
|
|
10
|
+
import { AGENT_PROMPT } from './agent-prompt.mjs'
|
|
11
|
+
import { aiEnv, aiTestScript, normalizeProvider } from './ai/settings-adapter.mjs'
|
|
12
|
+
import { ANSWER_FLAGS, collect, flagsFromEnv, parseProviderSpec, resolveAnswers } from './answers.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 { listRecords, readRecord, slateboxHome, writeRecord } from './record.mjs'
|
|
20
|
+
import { makeRunner } from './runner.mjs'
|
|
21
|
+
import { Redactor } from './secrets.mjs'
|
|
22
|
+
import { applyDocker, backupDocker, defaultLocalPort, execNode, readSecretDocker, restoreDocker, statusDocker, uninstallDocker } from './targets/docker.mjs'
|
|
23
|
+
import { exportFiles } from './targets/export.mjs'
|
|
24
|
+
import { applyK8s, backupK8s, execNodeK8s, readSecretK8s, restoreK8s, statusK8s, uninstallK8s } from './targets/k8s.mjs'
|
|
25
|
+
import { parse as parseYaml } from './yaml.mjs'
|
|
26
|
+
|
|
27
|
+
const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
|
|
28
|
+
|
|
29
|
+
const INSTALLER_COMMANDS = ['install', 'plan', 'status', 'upgrade', 'backup', 'restore', 'uninstall', 'ai', 'secrets', 'agent-prompt', 'installs', 'help']
|
|
30
|
+
|
|
31
|
+
export const HELP = `slatebox ${PKG.version}: run your own Slatebox.
|
|
32
|
+
|
|
33
|
+
npx slatebox on the machine of your choice: asks a few questions,
|
|
34
|
+
shows a plan, installs (the same as slatebox install)
|
|
35
|
+
npx slatebox --dry-run the questions and the plan only; nothing changes
|
|
36
|
+
npx slatebox agent-prompt instructions for a coding agent to do it for you
|
|
37
|
+
|
|
38
|
+
Install and run:
|
|
39
|
+
slatebox install [local|ssh <user@host>|k8s|export] [flags]
|
|
40
|
+
slatebox plan [same flags] print the plan only; changes nothing
|
|
41
|
+
slatebox status address, version, health, AI and SSO, last backup
|
|
42
|
+
slatebox upgrade [--to <image>] fetch the install's image tag again (or --to), back up,
|
|
43
|
+
upgrade, check health, roll back on failure
|
|
44
|
+
slatebox backup [--to <dir>] a complete backup now
|
|
45
|
+
slatebox restore <file.gz>
|
|
46
|
+
slatebox uninstall [--delete-data --confirm <name>] data is kept unless you say otherwise
|
|
47
|
+
slatebox ai list | add "<spec>" | remove <id> | use <id> | off | test [id]
|
|
48
|
+
slatebox secrets path | reveal <NAME> where secrets are kept; reveal prints one to a terminal
|
|
49
|
+
slatebox installs the installs this computer made
|
|
50
|
+
slatebox agent-prompt
|
|
51
|
+
|
|
52
|
+
Install flags (each also SLATEBOX_INSTALL_<NAME> in the environment; flags win,
|
|
53
|
+
then --answers, then the environment. Consent never comes from the environment:
|
|
54
|
+
--yes, --install-docker and --new-encryption-key are typed each time):
|
|
55
|
+
--name <id> several installs can live side by side (default slatebox)
|
|
56
|
+
--answers <file> YAML or JSON answers (see agent-prompt); never holds secrets
|
|
57
|
+
--target local|ssh|k8s|export --host user@host --ssh-port N --identity <key>
|
|
58
|
+
--ssh-option <opt> passed to ssh -o (repeatable) --install-docker (only with consent)
|
|
59
|
+
--domain <name> HTTPS with automatic certificates --url <address> --port <n>
|
|
60
|
+
--listen <ip> this computer only: 127.0.0.1 (default) or 0.0.0.0 for every interface
|
|
61
|
+
--admin-email <email>
|
|
62
|
+
--ai none | --ai-provider "kind=<openai|anthropic|deepinfra|openrouter|groq|together|mistral|ollama|lmstudio|openai-compatible>,model=<m>,url=<endpoint>,key=env:<VAR>"
|
|
63
|
+
(repeat for several, then --ai-default <id>; there is no default provider)
|
|
64
|
+
--sso --sso-only --sso-admin open|closed
|
|
65
|
+
--backups default|<dir>|s3://bucket/prefix|off --backup-schedule "0 3 * * *" --backup-keep 14
|
|
66
|
+
--size small|team|large --mail-url-from env:<VAR> --mail-from "Slatebox <b@example.com>"
|
|
67
|
+
--k8s-context <ctx> --namespace <ns> --route none|ingress|gateway --ingress-class <c>
|
|
68
|
+
--gateway-ref <ns/name> --tls-issuer ClusterIssuer/<name> --storage-class <sc>
|
|
69
|
+
--format compose|manifests|helm --out <dir> (target export)
|
|
70
|
+
--image <ref> --image-archive <file.tar> (a local build instead of the public image)
|
|
71
|
+
|
|
72
|
+
--new-encryption-key replace a lost SLATEBOX_KEY_ENCRYPTION_KEY over existing data
|
|
73
|
+
(keys people saved become unreadable; refused without it)
|
|
74
|
+
|
|
75
|
+
Global: --yes (after a person approved the plan) --json (NDJSON events on stdout)
|
|
76
|
+
--agent auto|yes|no --debug --health-timeout <seconds> (default 600)
|
|
77
|
+
|
|
78
|
+
Exit codes: 0 done or nothing to change; 2 bad flags or answers; 3 an answer or a
|
|
79
|
+
confirmation is needed and nobody can be asked; 4 a precondition failed;
|
|
80
|
+
5 the change failed and was rolled back; 6 the rollback failed too (commands
|
|
81
|
+
attached); 7 cancelled.
|
|
82
|
+
|
|
83
|
+
Slates (from slatebox-mcp, fetched when first used): slatebox exec | describe
|
|
84
|
+
`
|
|
85
|
+
|
|
86
|
+
// Agents that announce themselves in the environment.
|
|
87
|
+
const AGENT_ENV = ['AI_AGENT', 'CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'GEMINI_CLI', 'CURSOR_AGENT', 'CLINE_ACTIVE', 'AIDER_MODEL', 'OPENCODE']
|
|
88
|
+
|
|
89
|
+
export function detectAgent(env) {
|
|
90
|
+
return AGENT_ENV.some(name => env[name] && env[name] !== '0' && env[name] !== 'false')
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function parse(argv) {
|
|
94
|
+
const options = {
|
|
95
|
+
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
|
|
96
|
+
yes: { type: 'boolean', short: 'y' }, json: { type: 'boolean' }, agent: { type: 'string' }, debug: { type: 'boolean' },
|
|
97
|
+
answers: { type: 'string' }, home: { type: 'string' }, 'image-archive': { type: 'string' }, 'health-timeout': { type: 'string' },
|
|
98
|
+
'dry-run': { type: 'boolean' }, 'show-secrets': { type: 'boolean' }, 'delete-data': { type: 'boolean' }, confirm: { type: 'string' },
|
|
99
|
+
to: { type: 'string' }, 'force-stdout': { type: 'boolean' }, 'new-encryption-key': { type: 'boolean' },
|
|
100
|
+
}
|
|
101
|
+
for (const [flag, type] of Object.entries(ANSWER_FLAGS)) {
|
|
102
|
+
options[flag] = type === 'multiple' ? { type: 'string', multiple: true } : { type }
|
|
103
|
+
}
|
|
104
|
+
return parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true, strict: true })
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The slate commands (exec, describe, ...) belong to the slatebox-mcp package.
|
|
108
|
+
// It is not a dependency: both packages name a `slatebox` command, and npx
|
|
109
|
+
// would link two. A sibling checkout or an installed copy is used when there
|
|
110
|
+
// is one; otherwise npx fetches this exact version (a range would install
|
|
111
|
+
// whatever 0.3.x is newest on first use, unasked).
|
|
112
|
+
export const SLATE_PACKAGE = 'slatebox-mcp@0.3.5'
|
|
113
|
+
|
|
114
|
+
function slateCli() {
|
|
115
|
+
try { return createRequire(import.meta.url).resolve('slatebox-mcp/src/slatebox.js') } catch { /* not installed */ }
|
|
116
|
+
const sibling = fileURLToPath(new URL('../../slatebox-mcp/src/slatebox.js', import.meta.url))
|
|
117
|
+
return existsSync(sibling) ? sibling : null
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function delegate(argv, io) {
|
|
121
|
+
const path = slateCli()
|
|
122
|
+
const [cmd, args] = path ? [process.execPath, [path, ...argv]] : [process.platform === 'win32' ? 'npx.cmd' : 'npx', ['--yes', '--package', SLATE_PACKAGE, 'slatebox', ...argv]]
|
|
123
|
+
return new Promise(resolve => {
|
|
124
|
+
const child = spawn(cmd, args, { env: io.env, stdio: ['pipe', 'pipe', 'pipe'] })
|
|
125
|
+
child.on('error', () => {
|
|
126
|
+
io.stderr.write(`Unknown command ${argv[0]}. See slatebox --help. (Slate commands need ${SLATE_PACKAGE}: npx -p ${SLATE_PACKAGE} slatebox ${argv[0]})\n`)
|
|
127
|
+
resolve(EXIT.USAGE)
|
|
128
|
+
})
|
|
129
|
+
child.stdout.on('data', chunk => io.stdout.write(chunk))
|
|
130
|
+
child.stderr.on('data', chunk => io.stderr.write(chunk))
|
|
131
|
+
if (io.stdin && io.stdin !== process.stdin) io.stdin.pipe?.(child.stdin)
|
|
132
|
+
else if (io.stdin === process.stdin && !process.stdin.isTTY) process.stdin.pipe(child.stdin)
|
|
133
|
+
else child.stdin.end()
|
|
134
|
+
child.on('close', code => resolve(code ?? 1))
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function readAnswersFile(path) {
|
|
139
|
+
if (!path) return undefined
|
|
140
|
+
let text
|
|
141
|
+
try { text = readFileSync(path, 'utf8') } catch (error) { throw new InstallError(EXIT.USAGE, `Cannot read the answers file ${path}: ${error.code || error.message}`) }
|
|
142
|
+
try {
|
|
143
|
+
const parsed = parseYaml(text)
|
|
144
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('it is not a map of answers')
|
|
145
|
+
if (parsed.version !== undefined && parsed.version !== 1) throw new Error(`version ${parsed.version} is not supported (this installer reads version 1)`)
|
|
146
|
+
return parsed
|
|
147
|
+
} catch (error) {
|
|
148
|
+
throw new InstallError(EXIT.USAGE, `The answers file ${path} is not valid: ${error.message}`)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* @param {string[]} argv arguments after "slatebox"
|
|
154
|
+
* @param {{env?: object, stdin?: any, stdout?: any, stderr?: any, run?: Function, fetch?: Function}} io
|
|
155
|
+
* @returns {Promise<number>} exit code
|
|
156
|
+
*/
|
|
157
|
+
export async function main(argv, io = {}) {
|
|
158
|
+
io = { env: process.env, stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, ...io }
|
|
159
|
+
io.platform ??= process.platform
|
|
160
|
+
io.cwd ??= process.cwd()
|
|
161
|
+
const [command] = argv
|
|
162
|
+
if (command && !command.startsWith('-') && !INSTALLER_COMMANDS.includes(command)) return delegate(argv, io)
|
|
163
|
+
let parsed
|
|
164
|
+
try {
|
|
165
|
+
parsed = parse(argv)
|
|
166
|
+
} catch (error) {
|
|
167
|
+
io.stderr.write(`${error.message}\nSee slatebox --help.\n`)
|
|
168
|
+
if (argv.includes('--json')) io.stdout.write(JSON.stringify({ event: 'error', id: 'usage', status: 'failed', exitCode: EXIT.USAGE, message: error.message }) + '\n')
|
|
169
|
+
return EXIT.USAGE
|
|
170
|
+
}
|
|
171
|
+
const envFlags = flagsFromEnv(io.env)
|
|
172
|
+
const flags = { ...envFlags, ...parsed.values }
|
|
173
|
+
const positionals = parsed.positionals
|
|
174
|
+
if (flags.version) { io.stdout.write(`${PKG.version}\n`); return 0 }
|
|
175
|
+
if (flags.help || positionals[0] === 'help') { io.stdout.write(HELP); return 0 }
|
|
176
|
+
// Plain `npx slatebox` is the guided install on this machine.
|
|
177
|
+
if (!positionals.length) positionals.unshift('install')
|
|
178
|
+
|
|
179
|
+
const agentMode = flags.agent === 'yes' || (flags.agent !== 'no' && detectAgent(io.env))
|
|
180
|
+
const tty = Boolean(io.stdin.isTTY && io.stderr.isTTY)
|
|
181
|
+
const interactive = tty && !agentMode
|
|
182
|
+
const json = flags.json ?? agentMode
|
|
183
|
+
const redactor = new Redactor()
|
|
184
|
+
const out = new Output({ stdout: io.stdout, stderr: io.stderr, json, debug: Boolean(flags.debug), redactor })
|
|
185
|
+
const ctx = {
|
|
186
|
+
env: io.env, stdin: io.stdin, stdout: io.stdout, stderr: io.stderr, flags, version: PKG.version,
|
|
187
|
+
home: slateboxHome(io.env, flags.home), redactor, out, run: io.run || makeRunner(out), fetch: io.fetch || globalThis.fetch,
|
|
188
|
+
interactive, tty, agentMode, json, yes: Boolean(flags.yes), healthTimeout: Number(flags['health-timeout'] || 600),
|
|
189
|
+
cliFlags: parsed.values, platform: io.platform, cwd: io.cwd,
|
|
190
|
+
}
|
|
191
|
+
if (interactive) ctx.prompt = createPrompt({ input: io.stdin, output: io.stderr })
|
|
192
|
+
ctx.emitPlan = plan => {
|
|
193
|
+
out.event({ event: 'plan', ...plan })
|
|
194
|
+
const text = formatPlan(plan)
|
|
195
|
+
if (json) io.stderr.write(redactor.redact(text) + '\n')
|
|
196
|
+
else out.say(`\n${text}\n`)
|
|
197
|
+
}
|
|
198
|
+
ctx.confirm = async plan => {
|
|
199
|
+
if (ctx.yes) return
|
|
200
|
+
if (ctx.interactive) {
|
|
201
|
+
const local = plan.target === 'local' || plan.target === 'export'
|
|
202
|
+
if (await ctx.prompt.confirm('Apply this plan?', { default: local })) return
|
|
203
|
+
throw new InstallError(EXIT.CANCELLED, 'Cancelled; nothing was changed.')
|
|
204
|
+
}
|
|
205
|
+
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 })
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
const result = await dispatch(ctx, positionals, flags)
|
|
210
|
+
ctx.prompt?.close()
|
|
211
|
+
return result ?? 0
|
|
212
|
+
} catch (error) {
|
|
213
|
+
ctx.prompt?.close()
|
|
214
|
+
if (!(error instanceof InstallError)) {
|
|
215
|
+
out.event({ event: 'error', id: 'internal', status: 'failed', exitCode: 1, message: error.message })
|
|
216
|
+
io.stderr.write(redactor.redact(`✗ ${error.message}\n${flags.debug ? `${error.stack}\n` : ''}`))
|
|
217
|
+
return 1
|
|
218
|
+
}
|
|
219
|
+
const name = Object.entries(EXIT).find(([, code]) => code === error.exitCode)?.[0]?.toLowerCase().replace(/_/g, '-') || 'error'
|
|
220
|
+
out.event({ event: 'error', id: name, status: 'failed', exitCode: error.exitCode, message: error.message, ...error.details })
|
|
221
|
+
io.stderr.write(redactor.redact(`${error.exitCode === EXIT.NEEDS_INPUT ? '?' : '✗'} ${error.message}\n`))
|
|
222
|
+
if (error.details?.missing?.length && !json) {
|
|
223
|
+
for (const item of error.details.missing) io.stderr.write(` - ${item.field}: ${item.question}${item.flag ? ` (${item.flag})` : ''}\n`)
|
|
224
|
+
}
|
|
225
|
+
if (error.details?.fields?.length && !json) {
|
|
226
|
+
for (const item of error.details.fields) io.stderr.write(` - ${item.field}: ${item.message}\n`)
|
|
227
|
+
}
|
|
228
|
+
return error.exitCode
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function requireRecord(ctx, flags) {
|
|
233
|
+
const name = flags.name || 'slatebox'
|
|
234
|
+
const record = readRecord(ctx.home, name)
|
|
235
|
+
if (!record) {
|
|
236
|
+
const known = listRecords(ctx.home).map(item => item.name)
|
|
237
|
+
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.'}`)
|
|
238
|
+
}
|
|
239
|
+
return record
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The image an upgrade goes to: --to, else this package's release image for an
|
|
244
|
+
* install of the public image, else the install's own tag fetched again (a
|
|
245
|
+
* private registry stays a private registry).
|
|
246
|
+
*/
|
|
247
|
+
function upgradeImage(record, flags) {
|
|
248
|
+
if (flags.to || flags.image) return flags.to || flags.image
|
|
249
|
+
const current = record.imageRef || record.image
|
|
250
|
+
if (!current || current.startsWith(`${DEFAULT_REPOSITORY}:`) || current.startsWith(`${DEFAULT_REPOSITORY}@`)) return DEFAULT_IMAGE
|
|
251
|
+
if (isTag(current)) return current
|
|
252
|
+
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>.`)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function finish(ctx, done, lines = []) {
|
|
256
|
+
ctx.out.event({ event: 'done', ...done })
|
|
257
|
+
for (const line of lines) ctx.out.say(line)
|
|
258
|
+
return 0
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async function prepareAnswers(ctx, flags, positionals) {
|
|
262
|
+
const target = positionals[1] && ['local', 'ssh', 'k8s', 'export'].includes(positionals[1]) ? positionals[1] : undefined
|
|
263
|
+
const host = target === 'ssh' ? positionals[2] : undefined
|
|
264
|
+
const file = readAnswersFile(flags.answers)
|
|
265
|
+
// Only flags typed on the command line here; collect() adds the environment below the answers file.
|
|
266
|
+
const cliFlags = { ...Object.fromEntries(Object.entries(ctx.cliFlags).filter(([key]) => key in ANSWER_FLAGS)), ...(target ? { target } : {}), ...(host ? { host } : {}) }
|
|
267
|
+
const name = cliFlags.name || file?.name || flags.name || 'slatebox'
|
|
268
|
+
const record = readRecord(ctx.home, name)
|
|
269
|
+
let partial = collect({ record, env: ctx.env, file, flags: cliFlags })
|
|
270
|
+
if (ctx.interactive) {
|
|
271
|
+
const kube = await ctx.run('kubectl', ['config', 'current-context']).catch(() => null)
|
|
272
|
+
ctx.currentContext = kube?.code === 0 ? kube.stdout.trim() : null
|
|
273
|
+
ctx.freePort = partial.address?.port ?? await defaultLocalPort()
|
|
274
|
+
partial = await interview(ctx, partial)
|
|
275
|
+
}
|
|
276
|
+
const freePort = (partial.target ?? 'local') === 'local' && partial.address?.port === undefined && !partial.address?.url ? await defaultLocalPort() : undefined
|
|
277
|
+
const { answers, missing, errors } = resolveAnswers(partial, { freePort, cwd: ctx.cwd, home: ctx.env.HOME })
|
|
278
|
+
if (errors.length) throw new InstallError(EXIT.USAGE, `Some answers are not valid: ${errors.map(error => error.field).join(', ')}.`, { fields: errors })
|
|
279
|
+
if (missing.length) throw new InstallError(EXIT.NEEDS_INPUT, `Some answers are needed: ${missing.map(item => item.field).join(', ')}.`, { missing })
|
|
280
|
+
return { answers, record, explicitContext: Boolean(cliFlags['k8s-context'] || file?.k8s?.context || record?.k8s?.context) }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function applyTarget(ctx, answers, options) {
|
|
284
|
+
if (answers.target === 'k8s') return applyK8s(ctx, answers, options)
|
|
285
|
+
if (answers.target === 'export') return exportFiles(ctx, answers, options)
|
|
286
|
+
return applyDocker(ctx, answers, { ...options, archive: ctx.flags['image-archive'] })
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function closing(ctx, done) {
|
|
290
|
+
if (done.nothingToChange) return [`Nothing to change: ${done.name} is running at ${done.address}.`]
|
|
291
|
+
if (done.target === 'export') return [`Wrote ${done.files.length} files to ${done.dir}. Nothing was applied.`]
|
|
292
|
+
const lines = ['', `Slatebox is running at ${done.address}`]
|
|
293
|
+
if (done.keyGenerated) {
|
|
294
|
+
lines.push('', `Your key encryption key is stored in ${done.secretsFile}. Back it up with your password manager now.`,
|
|
295
|
+
'Backups do not contain it, and without it people\'s saved AI keys cannot be read after a restore.')
|
|
296
|
+
}
|
|
297
|
+
lines.push(`Install record: ${done.installRecord}`, `Day two: slatebox status | upgrade | backup | ai --name ${done.name}`)
|
|
298
|
+
return lines
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function showSecretOnce(ctx, record, name) {
|
|
302
|
+
if (ctx.json || !(ctx.stdout.isTTY || ctx.flags['force-stdout'])) {
|
|
303
|
+
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).')
|
|
304
|
+
}
|
|
305
|
+
const value = record.target === 'k8s' ? await readSecretK8s(ctx, record, name) : await readSecretDocker(ctx, record, name)
|
|
306
|
+
if (!value) throw new InstallError(EXIT.PRECONDITION, `${name} is not set for "${record.name}".`)
|
|
307
|
+
ctx.stdout.write(`${value}\n`)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function dispatch(ctx, positionals, flags) {
|
|
311
|
+
const [command, sub, ...rest] = positionals
|
|
312
|
+
switch (command) {
|
|
313
|
+
case 'agent-prompt':
|
|
314
|
+
ctx.stdout.write(AGENT_PROMPT)
|
|
315
|
+
return 0
|
|
316
|
+
case 'installs': {
|
|
317
|
+
const records = listRecords(ctx.home)
|
|
318
|
+
ctx.out.event({ event: 'done', installs: records.map(record => ({ name: record.name, target: record.target, address: record.address?.url, state: record.state })) })
|
|
319
|
+
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})`}`)
|
|
320
|
+
if (!records.length) ctx.out.say('No installs made from this computer yet.')
|
|
321
|
+
return 0
|
|
322
|
+
}
|
|
323
|
+
case 'plan':
|
|
324
|
+
case 'install': {
|
|
325
|
+
const { answers, record, explicitContext } = await prepareAnswers(ctx, flags, positionals)
|
|
326
|
+
const planOnly = command === 'plan' || Boolean(flags['dry-run'])
|
|
327
|
+
const done = await applyTarget(ctx, answers, { record, planOnly, explicitContext })
|
|
328
|
+
if (done.planned) {
|
|
329
|
+
ctx.out.event({ event: 'done', planned: true, name: answers.name, target: answers.target })
|
|
330
|
+
if (!ctx.json) ctx.out.say(`Nothing was changed. To apply: slatebox install ${flags.answers ? `--answers ${flags.answers} ` : ''}... (the same answers)${ctx.interactive ? '' : ' --yes'}`)
|
|
331
|
+
return 0
|
|
332
|
+
}
|
|
333
|
+
finish(ctx, done, closing(ctx, done))
|
|
334
|
+
if (flags['show-secrets'] && done.keyGenerated) await showSecretOnce(ctx, ctx.record, 'SLATEBOX_KEY_ENCRYPTION_KEY')
|
|
335
|
+
return 0
|
|
336
|
+
}
|
|
337
|
+
case 'upgrade': {
|
|
338
|
+
const record = requireRecord(ctx, flags)
|
|
339
|
+
const { answers, errors } = resolveAnswers(collect({ record }), {})
|
|
340
|
+
if (errors.length) throw new InstallError(EXIT.USAGE, 'The install record is not valid.', { fields: errors })
|
|
341
|
+
const imageRef = upgradeImage(record, flags)
|
|
342
|
+
const done = await applyTarget(ctx, answers, { record, imageRef, explicitContext: true, refresh: true })
|
|
343
|
+
return finish(ctx, done, done.nothingToChange ? [`Already up to date: ${done.name} runs ${done.imageDigest}.`] : ['', `Upgraded. Slatebox is running at ${done.address} (${done.imageDigest}).`])
|
|
344
|
+
}
|
|
345
|
+
case 'status': {
|
|
346
|
+
const record = requireRecord(ctx, flags)
|
|
347
|
+
const status = record.target === 'k8s' ? await statusK8s(ctx, record) : await statusDocker(ctx, record)
|
|
348
|
+
ctx.out.event({ event: 'done', ...status })
|
|
349
|
+
if (!ctx.json) {
|
|
350
|
+
for (const [label, value] of Object.entries({ Name: status.name, Where: status.where, Address: status.address, Health: status.health, 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' })) {
|
|
351
|
+
ctx.out.say(`${label.padEnd(12)} ${value}`)
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return status.health === 'healthy' ? 0 : EXIT.PRECONDITION
|
|
355
|
+
}
|
|
356
|
+
case 'backup': {
|
|
357
|
+
const record = requireRecord(ctx, flags)
|
|
358
|
+
const result = record.target === 'k8s' ? await backupK8s(ctx, record, { to: flags.to }) : await backupDocker(ctx, record, { to: flags.to })
|
|
359
|
+
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).'])
|
|
360
|
+
}
|
|
361
|
+
case 'restore': {
|
|
362
|
+
const record = requireRecord(ctx, flags)
|
|
363
|
+
const archive = sub
|
|
364
|
+
if (!archive || !existsSync(archive)) throw new InstallError(EXIT.USAGE, 'Name the backup file: slatebox restore <file.gz>')
|
|
365
|
+
const where = record.target === 'k8s' ? `context ${record.k8s.context}, namespace ${record.k8s.namespace}` : record.target === 'ssh' ? record.ssh.host : 'this computer'
|
|
366
|
+
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: [] }
|
|
367
|
+
ctx.emitPlan(plan)
|
|
368
|
+
await ctx.confirm(plan)
|
|
369
|
+
const result = record.target === 'k8s' ? await restoreK8s(ctx, record, archive) : await restoreDocker(ctx, record, archive)
|
|
370
|
+
return finish(ctx, { name: record.name, ...result }, [`Restored ${archive}. Slatebox is ready.`])
|
|
371
|
+
}
|
|
372
|
+
case 'uninstall': {
|
|
373
|
+
const record = requireRecord(ctx, flags)
|
|
374
|
+
const deleteData = Boolean(flags['delete-data'])
|
|
375
|
+
if (deleteData) {
|
|
376
|
+
let typed = flags.confirm
|
|
377
|
+
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 })
|
|
378
|
+
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 })
|
|
379
|
+
}
|
|
380
|
+
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.'] : [], notes: deleteData ? [] : ['The data volume and the secrets are kept; install again with the same --name to get it back.'], changes: [] }
|
|
381
|
+
ctx.emitPlan(plan)
|
|
382
|
+
await ctx.confirm(plan)
|
|
383
|
+
const result = record.target === 'k8s' ? await uninstallK8s(ctx, record, { deleteData }) : await uninstallDocker(ctx, record, { deleteData })
|
|
384
|
+
if (deleteData) {
|
|
385
|
+
const { rmSync } = await import('node:fs')
|
|
386
|
+
const { installDir } = await import('./record.mjs')
|
|
387
|
+
rmSync(installDir(ctx.home, record.name), { recursive: true, force: true })
|
|
388
|
+
} else {
|
|
389
|
+
writeRecord(ctx.home, { ...record, state: 'uninstalled' })
|
|
390
|
+
}
|
|
391
|
+
return finish(ctx, { name: record.name, ...result }, [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}`])
|
|
392
|
+
}
|
|
393
|
+
case 'ai':
|
|
394
|
+
return aiCommand(ctx, flags, sub, rest)
|
|
395
|
+
case 'secrets': {
|
|
396
|
+
const record = requireRecord(ctx, flags)
|
|
397
|
+
if (sub === 'reveal') {
|
|
398
|
+
if (!rest[0]) throw new InstallError(EXIT.USAGE, 'Name the secret: slatebox secrets reveal SLATEBOX_KEY_ENCRYPTION_KEY')
|
|
399
|
+
await showSecretOnce(ctx, record, rest[0])
|
|
400
|
+
return 0
|
|
401
|
+
}
|
|
402
|
+
ctx.out.event({ event: 'done', name: record.name, secretsLocation: record.secretsLocation, secrets: Object.keys(record.secretRefs || {}) })
|
|
403
|
+
if (!ctx.json) ctx.out.say(`${record.secretsLocation}\nHolds: ${Object.keys(record.secretRefs || {}).join(', ')}`)
|
|
404
|
+
return 0
|
|
405
|
+
}
|
|
406
|
+
default:
|
|
407
|
+
throw new InstallError(EXIT.USAGE, `Unknown command ${command}. See slatebox --help.`)
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// ------------------------------------------------------------------ ai
|
|
412
|
+
|
|
413
|
+
async function aiCommand(ctx, flags, sub, rest) {
|
|
414
|
+
const record = requireRecord(ctx, flags)
|
|
415
|
+
const ai = structuredClone(record.ai)
|
|
416
|
+
const providers = ai.mode === 'providers' ? ai.providers : []
|
|
417
|
+
if (!sub || sub === 'list') {
|
|
418
|
+
ctx.out.event({ event: 'done', name: record.name, ai: record.ai })
|
|
419
|
+
if (!ctx.json) {
|
|
420
|
+
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"')
|
|
421
|
+
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}`)
|
|
422
|
+
}
|
|
423
|
+
return 0
|
|
424
|
+
}
|
|
425
|
+
if (sub === 'test') {
|
|
426
|
+
const chosen = rest[0] ? providers.find(provider => provider.id === rest[0]) : providers.find(provider => provider.id === ai.default) || providers[0]
|
|
427
|
+
if (!chosen) throw new InstallError(EXIT.PRECONDITION, rest[0] ? `No AI provider "${rest[0]}".` : 'AI is off for this install.')
|
|
428
|
+
const multi = Object.keys(record.secretRefs || {}).some(name => name.startsWith('SLATEBOX_AI_KEY_')) || providers.length > 1
|
|
429
|
+
const located = aiEnv({ mode: 'providers', providers: [chosen], default: chosen.id }, multi ? { settings: ['SLATEBOX_AI_PROVIDERS'] } : null, { target: record.target })
|
|
430
|
+
const provider = normalizeProvider(chosen)
|
|
431
|
+
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
|
|
432
|
+
const keyEnv = provider.keyFrom === 'none' ? '' : multi ? Object.keys(located.secrets)[0] : 'SLATEBOX_AI_KEY'
|
|
433
|
+
ctx.out.step('ai-test', 'start', `Testing ${chosen.id} from inside the container (${baseUrl})`)
|
|
434
|
+
const run = record.target === 'k8s' ? execNodeK8s : execNode
|
|
435
|
+
const result = await run(ctx, record, aiTestScript(), [baseUrl, provider.model || '', keyEnv])
|
|
436
|
+
let report
|
|
437
|
+
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()}`) }
|
|
438
|
+
ctx.out.event({ event: 'done', name: record.name, provider: chosen.id, ...report })
|
|
439
|
+
if (!ctx.json) {
|
|
440
|
+
ctx.out.say(`Endpoint: ${report.baseUrl}`)
|
|
441
|
+
ctx.out.say(`Models: ${Array.isArray(report.models) ? report.models.slice(0, 8).join(', ') || '(none listed)' : report.models}`)
|
|
442
|
+
ctx.out.say(`Tool calls: ${report.toolCalls === null ? '-' : report.toolCalls ? 'yes' : 'no'}`)
|
|
443
|
+
ctx.out.say(`tool_choice: ${report.toolChoiceHonoured === null ? '-' : report.toolChoiceHonoured ? 'honoured' : 'ignored (Slatebox falls back to plain text for this model)'}`)
|
|
444
|
+
ctx.out.say(`Latency: ${report.latencyMs ?? '-'} ms`)
|
|
445
|
+
if (report.error) ctx.out.say(`Problem: ${report.error}`)
|
|
446
|
+
}
|
|
447
|
+
return report.error ? EXIT.PRECONDITION : 0
|
|
448
|
+
}
|
|
449
|
+
if (sub === 'add') {
|
|
450
|
+
if (!rest[0]) throw new InstallError(EXIT.USAGE, 'Usage: slatebox ai add "kind=openai,model=gpt-5-mini,key=env:OPENAI_API_KEY"')
|
|
451
|
+
const added = parseProviderSpec(rest[0])
|
|
452
|
+
if (providers.some(provider => provider.id === added.id)) throw new InstallError(EXIT.USAGE, `There is already a provider "${added.id}"; give another id=.`)
|
|
453
|
+
ai.mode = 'providers'
|
|
454
|
+
ai.providers = [...providers, added]
|
|
455
|
+
if (flags['ai-default']) ai.default = flags['ai-default']
|
|
456
|
+
else if (ai.providers.length === 1) ai.default = added.id
|
|
457
|
+
} else if (sub === 'remove') {
|
|
458
|
+
if (!providers.some(provider => provider.id === rest[0])) throw new InstallError(EXIT.USAGE, `No AI provider "${rest[0]}".`)
|
|
459
|
+
ai.providers = providers.filter(provider => provider.id !== rest[0])
|
|
460
|
+
if (!ai.providers.length) { ai.mode = 'none'; delete ai.providers; delete ai.default }
|
|
461
|
+
else if (ai.default === rest[0]) ai.default = ai.providers.length === 1 ? ai.providers[0].id : undefined
|
|
462
|
+
} else if (sub === 'use') {
|
|
463
|
+
if (!providers.some(provider => provider.id === rest[0])) throw new InstallError(EXIT.USAGE, `No AI provider "${rest[0]}".`)
|
|
464
|
+
ai.default = rest[0]
|
|
465
|
+
} else if (sub === 'off') {
|
|
466
|
+
ai.mode = 'none'
|
|
467
|
+
delete ai.providers
|
|
468
|
+
delete ai.default
|
|
469
|
+
} else {
|
|
470
|
+
throw new InstallError(EXIT.USAGE, 'Usage: slatebox ai list | add "<spec>" | remove <id> | use <id> | off | test [id]')
|
|
471
|
+
}
|
|
472
|
+
const { answers, errors } = resolveAnswers(collect({ record: { ...record, ai } }), {})
|
|
473
|
+
if (errors.length) throw new InstallError(EXIT.USAGE, `That AI change is not valid: ${errors.map(error => `${error.field} (${error.message})`).join('; ')}`, { fields: errors })
|
|
474
|
+
// Same image, new settings: the change path, with its plan, health check and rollback.
|
|
475
|
+
const done = await applyTarget(ctx, answers, { record, imageRef: record.imageRef, explicitContext: true })
|
|
476
|
+
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}.`])
|
|
477
|
+
}
|
package/src/errors.mjs
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Exit codes, as documented in README.md and printed by `slatebox --help`.
|
|
2
|
+
export const EXIT = Object.freeze({
|
|
3
|
+
OK: 0,
|
|
4
|
+
USAGE: 2, // bad flags or answers; details list each field
|
|
5
|
+
NEEDS_INPUT: 3, // a missing answer or a confirmation, and nobody to ask
|
|
6
|
+
PRECONDITION: 4, // no Docker, no kube context, CPU, port taken, image unavailable, not available yet
|
|
7
|
+
ROLLED_BACK: 5, // changes applied, health failed, rolled back cleanly
|
|
8
|
+
ROLLBACK_FAILED: 6, // a person must act; details carry the commands
|
|
9
|
+
CANCELLED: 7,
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
export class InstallError extends Error {
|
|
13
|
+
/**
|
|
14
|
+
* @param {number} exitCode one of EXIT
|
|
15
|
+
* @param {string} message what happened and what to do, in plain words
|
|
16
|
+
* @param {object} [details] machine-readable extras for --json (fields, missing, commands)
|
|
17
|
+
*/
|
|
18
|
+
constructor(exitCode, message, details = {}) {
|
|
19
|
+
super(message)
|
|
20
|
+
this.exitCode = exitCode
|
|
21
|
+
this.details = details
|
|
22
|
+
}
|
|
23
|
+
}
|
package/src/image.mjs
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Which image to run, pinned to something that cannot change underneath an
|
|
2
|
+
// install, and what that image accepts.
|
|
3
|
+
import { capabilitiesFromProbe, LEGACY_SETTINGS } from './ai/settings-adapter.mjs'
|
|
4
|
+
import { EXIT, InstallError } from './errors.mjs'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Each release of this package installs one image: the public multi-arch
|
|
8
|
+
* index on GHCR, by its digest, so `npx slatebox@x.y.z install` always
|
|
9
|
+
* installs the same bytes. Give --image or --image-archive to install a local
|
|
10
|
+
* build instead (self-host/build-image.sh).
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_REPOSITORY = 'ghcr.io/slatebox/slatebox'
|
|
13
|
+
export const PINNED_TAG = '0.1.0'
|
|
14
|
+
export const PINNED_DIGEST = 'sha256:94f761bd8153ca9b9d9ef1ecd4af9faddf318427f7495c3af8492bb2a1d22d4f'
|
|
15
|
+
export const DEFAULT_IMAGE = PINNED_DIGEST ? `${DEFAULT_REPOSITORY}@${PINNED_DIGEST}` : `${DEFAULT_REPOSITORY}:${PINNED_TAG}`
|
|
16
|
+
|
|
17
|
+
/** Does this reference name a registry (so a digest reference can be pulled elsewhere)? */
|
|
18
|
+
export function hasRegistry(ref) {
|
|
19
|
+
const first = ref.split('/')[0]
|
|
20
|
+
return ref.includes('/') && (first.includes('.') || first.includes(':') || first === 'localhost')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const repositoryOf = ref => ref.replace(/@sha256:[a-f0-9]{64}$/, '').replace(/:[^/:]+$/, '')
|
|
24
|
+
|
|
25
|
+
/** A tag (it can move), as opposed to a digest reference or an image ID. */
|
|
26
|
+
export const isTag = ref => !ref.includes('@sha256:') && !/^sha256:[a-f0-9]{64}$/.test(ref)
|
|
27
|
+
|
|
28
|
+
/** The image as it is on the host now, or null. Never pulls. */
|
|
29
|
+
export async function inspectImage(docker, ref) {
|
|
30
|
+
const inspected = await docker(['image', 'inspect', '--format', '{{json .}}', ref])
|
|
31
|
+
return inspected.code === 0 ? JSON.parse(inspected.stdout) : null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The pinned description of an inspected image. */
|
|
35
|
+
export function pinImage(wanted, info) {
|
|
36
|
+
const id = info.Id
|
|
37
|
+
let pinned = id
|
|
38
|
+
if (wanted.includes('@sha256:')) pinned = wanted
|
|
39
|
+
else if (hasRegistry(wanted)) {
|
|
40
|
+
const repository = repositoryOf(wanted)
|
|
41
|
+
pinned = (info.RepoDigests || []).find(digest => digest.startsWith(`${repository}@`)) || id
|
|
42
|
+
}
|
|
43
|
+
return { ref: wanted, pinned, id, created: info.Created, labels: info.Config?.Labels || {}, architecture: info.Architecture || null }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function unavailable(wanted, why) {
|
|
47
|
+
return new InstallError(EXIT.PRECONDITION,
|
|
48
|
+
`The image ${wanted} is not available: ${why}\n` +
|
|
49
|
+
(wanted.startsWith(DEFAULT_REPOSITORY) ? 'The public image needs no login: check that this machine can reach ghcr.io (or that the --to version exists), then try again. To install a local build instead, give --image <name> or --image-archive <file.tar>.' : 'Check the name, or log in to its registry with docker login.'),
|
|
50
|
+
{ image: wanted })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* For an upgrade: fetch a tag again, because a cached tag says nothing about
|
|
55
|
+
* what the registry has now. When the registry cannot be reached and a copy is
|
|
56
|
+
* already on the host, that copy is used and the person is told.
|
|
57
|
+
*/
|
|
58
|
+
export async function refreshTag(docker, ref, step) {
|
|
59
|
+
if (!isTag(ref)) return
|
|
60
|
+
step('image', 'start', `Fetching ${ref} to see whether it is newer`)
|
|
61
|
+
const pulled = await docker(['pull', ref], { timeout: 60 * 60_000 })
|
|
62
|
+
if (pulled.code === 0) return
|
|
63
|
+
const why = pulled.stderr.trim().split('\n').pop()
|
|
64
|
+
if (!(await inspectImage(docker, ref))) throw unavailable(ref, why)
|
|
65
|
+
step('image', 'warn', `${ref} could not be pulled (${why}); using the copy already on the host.`)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const ARCH = { x86_64: 'amd64', amd64: 'amd64', aarch64: 'arm64', arm64: 'arm64' }
|
|
69
|
+
export const normalArch = arch => ARCH[String(arch || '').trim()] || String(arch || '').trim() || null
|
|
70
|
+
|
|
71
|
+
/** Refuse an image built for another processor than the host's (or the cluster nodes'). */
|
|
72
|
+
export function checkArch(image, hostArch, where) {
|
|
73
|
+
const want = normalArch(image.architecture)
|
|
74
|
+
const have = [].concat(hostArch || []).map(normalArch).filter(Boolean)
|
|
75
|
+
if (!want || !have.length || have.includes(want)) return
|
|
76
|
+
throw new InstallError(EXIT.PRECONDITION, `The image ${image.ref} is built for ${want}, but ${where} is ${[...new Set(have)].join(' and ')}. Use an image built for ${[...new Set(have)].join(' or ')} (docker buildx build --platform linux/${have[0]}).`)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Make the image available to a Docker host and pin it.
|
|
81
|
+
* @param {(args: string[], options?: object) => Promise<{code:number,stdout:string,stderr:string}>} docker docker on the target host
|
|
82
|
+
* @param {{ref?: string, archive?: string, loadArchive?: (file: string) => Promise<{code:number,stdout:string,stderr:string}>, step: Function}} options
|
|
83
|
+
* @returns {Promise<{ref: string, pinned: string, id: string, created?: string, labels: object}>}
|
|
84
|
+
*/
|
|
85
|
+
export async function resolveImage(docker, { ref, archive, loadArchive, step }) {
|
|
86
|
+
let wanted = ref || DEFAULT_IMAGE
|
|
87
|
+
if (archive) {
|
|
88
|
+
step('image', 'start', `Loading the image from ${archive}`)
|
|
89
|
+
const loaded = await loadArchive(archive)
|
|
90
|
+
if (loaded.code !== 0) throw new InstallError(EXIT.PRECONDITION, `The image archive ${archive} could not be loaded: ${loaded.stderr.trim()}`)
|
|
91
|
+
const named = /Loaded image: (\S+)/.exec(loaded.stdout)
|
|
92
|
+
const id = /Loaded image ID: (sha256:[a-f0-9]{64})/.exec(loaded.stdout)
|
|
93
|
+
if (!ref) wanted = named?.[1] || id?.[1]
|
|
94
|
+
if (!wanted) throw new InstallError(EXIT.PRECONDITION, `The image archive ${archive} did not name an image.`)
|
|
95
|
+
}
|
|
96
|
+
let info = await inspectImage(docker, wanted)
|
|
97
|
+
if (!info) {
|
|
98
|
+
step('image', 'start', `Pulling ${wanted}`)
|
|
99
|
+
const pulled = await docker(['pull', wanted], { timeout: 60 * 60_000 })
|
|
100
|
+
if (pulled.code !== 0) throw unavailable(wanted, pulled.stderr.trim().split('\n').pop())
|
|
101
|
+
info = await inspectImage(docker, wanted)
|
|
102
|
+
if (!info) throw new InstallError(EXIT.PRECONDITION, `The image ${wanted} was pulled but cannot be inspected.`)
|
|
103
|
+
}
|
|
104
|
+
return pinImage(wanted, info)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** What the image accepts, read from the image (no network, nothing kept). */
|
|
108
|
+
export async function probeImage(docker, image) {
|
|
109
|
+
const base = ['run', '--rm', '--network', 'none']
|
|
110
|
+
const settingsJson = await docker([...base, '--entrypoint', '/opt/slatebox/bin/slatebox', image, 'settings', '--json'])
|
|
111
|
+
if (settingsJson.code === 0) {
|
|
112
|
+
const caps = capabilitiesFromProbe({ settingsJson: settingsJson.stdout })
|
|
113
|
+
if (caps) return caps
|
|
114
|
+
}
|
|
115
|
+
// Older images: the usage text lists the commands, and configure.mjs refuses
|
|
116
|
+
// an unknown SLATEBOX_ name with the list of every name it accepts.
|
|
117
|
+
const usage = settingsJson.stderr
|
|
118
|
+
const configure = await docker([...base, '-e', 'SLATEBOX_INSTALLER_PROBE=1', '--entrypoint', 'node', image, '/opt/slatebox/lib/configure.mjs'])
|
|
119
|
+
const caps = capabilitiesFromProbe({ configureOutput: configure.stdout + configure.stderr, usage })
|
|
120
|
+
if (!caps) {
|
|
121
|
+
throw new InstallError(EXIT.PRECONDITION, `${image} does not look like a Slatebox image (it does not list its settings). Give the one-container image, ghcr.io/slatebox/slatebox.`)
|
|
122
|
+
}
|
|
123
|
+
return caps
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** MongoDB 8.0 needs AVX (x86-64) or ARMv8.2-A; the image's own mongod is the authority. */
|
|
127
|
+
export async function checkCpu(docker, image) {
|
|
128
|
+
const result = await docker(['run', '--rm', '--network', 'none', '--entrypoint', 'mongod', image, '--version'])
|
|
129
|
+
if (/exec format error/i.test(result.stderr)) {
|
|
130
|
+
throw new InstallError(EXIT.PRECONDITION, `${image} is built for another processor architecture than this host ("exec format error"). Use an image built for this host's architecture.`)
|
|
131
|
+
}
|
|
132
|
+
if (result.code === 132 || /Illegal instruction/i.test(result.stderr)) {
|
|
133
|
+
throw new InstallError(EXIT.PRECONDITION, 'This processor cannot run MongoDB 8.0, which Slatebox includes: it needs AVX on Intel/AMD (2011 or newer) or ARMv8.2-A on ARM (Raspberry Pi 5, Graviton 2, Apple silicon).')
|
|
134
|
+
}
|
|
135
|
+
return result.code === 0
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export const FALLBACK_CAPABILITIES = Object.freeze({ settings: [...LEGACY_SETTINGS], commands: ['backup', 'restore', 'password-link', 'health', 'version', 'sso'], source: 'assumed' })
|