slatebox 0.1.0 → 0.2.1

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/src/cli.mjs CHANGED
@@ -1,57 +1,92 @@
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'
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, rmdirSync, rmSync } from 'node:fs'
7
+ import { join } from 'node:path'
9
8
  import { parseArgs } from 'node:util'
10
9
  import { AGENT_PROMPT } from './agent-prompt.mjs'
11
10
  import { aiEnv, aiTestScript, normalizeProvider } from './ai/settings-adapter.mjs'
12
11
  import { ANSWER_FLAGS, collect, flagsFromEnv, parseProviderSpec, resolveAnswers } from './answers.mjs'
12
+ import { CREDENTIALS_FILE, readCredentials, teamHost } from './cloud.mjs'
13
13
  import { EXIT, InstallError } from './errors.mjs'
14
14
  import { interview } from './interview.mjs'
15
15
  import { Output } from './output.mjs'
16
16
  import { DEFAULT_IMAGE, DEFAULT_REPOSITORY, isTag } from './image.mjs'
17
17
  import { formatPlan } from './plan.mjs'
18
18
  import { createPrompt } from './prompt.mjs'
19
- import { listRecords, readRecord, slateboxHome, writeRecord } from './record.mjs'
19
+ import { installDir, listRecords, readRecord, slateboxHome, writeRecord } from './record.mjs'
20
20
  import { makeRunner } from './runner.mjs'
21
21
  import { Redactor } from './secrets.mjs'
22
- import { applyDocker, backupDocker, defaultLocalPort, execNode, readSecretDocker, restoreDocker, statusDocker, uninstallDocker } from './targets/docker.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'
23
24
  import { exportFiles } from './targets/export.mjs'
24
- import { applyK8s, backupK8s, execNodeK8s, readSecretK8s, restoreK8s, statusK8s, uninstallK8s } from './targets/k8s.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'
25
28
  import { parse as parseYaml } from './yaml.mjs'
26
29
 
27
30
  const PKG = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
28
31
 
29
- const INSTALLER_COMMANDS = ['install', 'plan', 'status', 'upgrade', 'backup', 'restore', 'uninstall', 'ai', 'secrets', 'agent-prompt', 'installs', 'help']
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))
30
61
 
31
- export const HELP = `slatebox ${PKG.version}: run your own Slatebox.
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')
32
66
 
33
- npx slatebox on the machine of your choice: asks a few questions,
34
- shows a plan, installs (the same as slatebox install)
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: anything not
73
+ given takes its default (this computer, no admin email,
74
+ AI off: add a model later with slatebox ai add, no SSO,
75
+ daily backups, size small, no mail). You still approve one
76
+ code in your browser to claim the address (opened for you
77
+ at a terminal)
78
+ npx slatebox install --domain boards.example.com your own domain (Caddy HTTPS, or --url and your proxy)
35
79
  npx slatebox --dry-run the questions and the plan only; nothing changes
36
80
  npx slatebox agent-prompt instructions for a coding agent to do it for you
37
81
 
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
82
+ Commands:
83
+ ${commandList()}
51
84
 
52
85
  Install flags (each also SLATEBOX_INSTALL_<NAME> in the environment; flags win,
53
86
  then --answers, then the environment. Consent never comes from the environment:
54
87
  --yes, --install-docker and --new-encryption-key are typed each time):
88
+ --team-address <name> claim https://<name>.slatebox.team (3-32 characters: a-z, 0-9, hyphens)
89
+ --local this computer only (http://localhost), no team address
55
90
  --name <id> several installs can live side by side (default slatebox)
56
91
  --answers <file> YAML or JSON answers (see agent-prompt); never holds secrets
57
92
  --target local|ssh|k8s|export --host user@host --ssh-port N --identity <key>
@@ -60,7 +95,9 @@ then --answers, then the environment. Consent never comes from the environment:
60
95
  --listen <ip> this computer only: 127.0.0.1 (default) or 0.0.0.0 for every interface
61
96
  --admin-email <email>
62
97
  --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)
98
+ (repeat for several, then --ai-default <id>; there is no default provider:
99
+ without --yes it is asked, or exit 3 with nobody to ask; with --yes and
100
+ no AI answer, AI is off: add a model later with slatebox ai add)
64
101
  --sso --sso-only --sso-admin open|closed
65
102
  --backups default|<dir>|s3://bucket/prefix|off --backup-schedule "0 3 * * *" --backup-keep 14
66
103
  --size small|team|large --mail-url-from env:<VAR> --mail-from "Slatebox <b@example.com>"
@@ -72,15 +109,30 @@ then --answers, then the environment. Consent never comes from the environment:
72
109
  --new-encryption-key replace a lost SLATEBOX_KEY_ENCRYPTION_KEY over existing data
73
110
  (keys people saved become unreadable; refused without it)
74
111
 
75
- Global: --yes (after a person approved the plan) --json (NDJSON events on stdout)
112
+ Moving a team (slatebox migrate --to cloud | --from cloud, import, export): your own server's
113
+ address is --from/--to <url>, SLATEBOX_BASE_URL, or the install made here (--name); its access
114
+ token is SLATEBOX_API_TOKEN (asked for at a terminal). Slatebox Cloud signs you in with a code in
115
+ your browser (it asks to "move your team"), or takes SLATEBOX_CLOUD_TOKEN. Nothing is visible on
116
+ the other side until you confirm. Then you are asked once to send invitations to the other members
117
+ (yes by default; --invite / --no-invite answer ahead; a script sends none without --invite; later:
118
+ slatebox migrate invite <move id> --to cloud|<url>), and whether to delete the archive from this
119
+ computer (no by default; --delete-archive, --keep-archive). --replace-waiting discards a move
120
+ already waiting.
121
+
122
+ Team addresses: the sign-in is a code you approve in your browser (Slatebox Cloud), every time
123
+ a name is claimed, moved or reconnected. SLATEBOX_CLOUD_URL or --cloud-url points at another
124
+ Slatebox Cloud. The install credential stays in
125
+ ~/.slatebox/installs/<name>/credentials.json (mode 0600).
126
+
127
+ Global: --yes (after a person approved the plan; asks nothing, takes the defaults for what is
128
+ not given; answers with no default, such as --host or a server's --admin-email, are
129
+ still exit 3) --json (NDJSON events on stdout)
76
130
  --agent auto|yes|no --debug --health-timeout <seconds> (default 600)
77
131
 
78
132
  Exit codes: 0 done or nothing to change; 2 bad flags or answers; 3 an answer or a
79
133
  confirmation is needed and nobody can be asked; 4 a precondition failed;
80
134
  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
135
+ attached); 7 cancelled. (exec has its own: slatebox exec --help.)
84
136
  `
85
137
 
86
138
  // Agents that announce themselves in the environment.
@@ -97,6 +149,10 @@ function parse(argv) {
97
149
  answers: { type: 'string' }, home: { type: 'string' }, 'image-archive': { type: 'string' }, 'health-timeout': { type: 'string' },
98
150
  'dry-run': { type: 'boolean' }, 'show-secrets': { type: 'boolean' }, 'delete-data': { type: 'boolean' }, confirm: { type: 'string' },
99
151
  to: { type: 'string' }, 'force-stdout': { type: 'boolean' }, 'new-encryption-key': { type: 'boolean' },
152
+ 'cloud-url': { type: 'string' }, 'keep-address': { type: 'boolean' }, follow: { type: 'boolean', short: 'f' },
153
+ service: { type: 'string' }, since: { type: 'string' },
154
+ from: { type: 'string' }, out: { type: 'string' }, invite: { type: 'boolean' }, 'keep-archive': { type: 'boolean' },
155
+ passphrase: { type: 'string' }, 'replace-waiting': { type: 'boolean' }, 'delete-archive': { type: 'boolean' }, email: { type: 'string' },
100
156
  }
101
157
  for (const [flag, type] of Object.entries(ANSWER_FLAGS)) {
102
158
  options[flag] = type === 'multiple' ? { type: 'string', multiple: true } : { type }
@@ -104,35 +160,68 @@ function parse(argv) {
104
160
  return parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true, strict: true })
105
161
  }
106
162
 
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
163
+ /** The closest command to a mistyped word, for "did you mean". */
164
+ export function suggest(word) {
165
+ const distance = (a, b) => {
166
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i)
167
+ for (let i = 1; i <= a.length; i++) {
168
+ let previous = row[0]
169
+ row[0] = i
170
+ for (let j = 1; j <= b.length; j++) {
171
+ const current = row[j]
172
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1))
173
+ previous = current
174
+ }
175
+ }
176
+ return row[b.length]
177
+ }
178
+ const names = [...COMMAND_NAMES, ...Object.keys(ALIASES)]
179
+ const best = names.map(name => ({ name, d: distance(word.toLowerCase(), name) })).sort((a, b) => a.d - b.d)[0]
180
+ return best && best.d <= Math.max(1, Math.floor(word.length / 3)) ? best.name : null
181
+ }
182
+
183
+ // exec, describe and mcp are slatebox-mcp's, a dependency of this package, run in this process.
184
+ async function slateCommand(argv, io) {
185
+ let commands
186
+ try {
187
+ commands = argv[0] === 'mcp' ? await import('slatebox-mcp/mcp') : await import('slatebox-mcp/commands')
188
+ } catch (error) {
189
+ 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`)
190
+ return EXIT.PRECONDITION
191
+ }
192
+ if (argv[0] === 'mcp') {
193
+ if (argv.includes('--help') || argv.includes('-h')) {
194
+ io.stdout.write(commands.mcpHelp ? commands.mcpHelp('slatebox mcp') : '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')
195
+ return 0
196
+ }
197
+ try {
198
+ await commands.startMcp(argv.slice(1), { env: io.env, stderr: io.stderr })
199
+ return 0
200
+ } catch (error) {
201
+ io.stderr.write(`Slatebox MCP could not start: ${error.message}\n`)
202
+ return error.name === 'UsageError' || error.constructor?.name === 'UsageError' ? EXIT.USAGE : 1
203
+ }
204
+ }
205
+ return commands.run(argv, { env: io.env, stdin: io.stdin, stdout: io.stdout, stderr: io.stderr, name: 'slatebox' })
118
206
  }
119
207
 
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
- })
208
+ /** Plain `slatebox`: the commands, and at a terminal an offer to install. Never installs unasked. */
209
+ async function bare(io) {
210
+ const tty = Boolean(io.stdin.isTTY && io.stderr.isTTY) && !detectAgent(io.env)
211
+ const text = `slatebox ${PKG.version}: one container with the app, live editing and the database.\n\nCommands:\n${commandList()}\n\nMore: slatebox help\n`
212
+ if (!tty) {
213
+ io.stdout.write(text)
214
+ return 0
215
+ }
216
+ io.stderr.write(`${text}\n`)
217
+ const prompt = createPrompt({ input: io.stdin, output: io.stderr })
218
+ let yes
219
+ try { yes = await prompt.confirm('Install Slatebox on this computer?', { default: true }) } catch { yes = false } finally { prompt.close() }
220
+ if (!yes) {
221
+ io.stderr.write('Nothing was changed. When you are ready: npx slatebox install\n')
222
+ return 0
223
+ }
224
+ return main(['install'], io)
136
225
  }
137
226
 
138
227
  function readAnswersFile(path) {
@@ -158,8 +247,17 @@ export async function main(argv, io = {}) {
158
247
  io = { env: process.env, stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, ...io }
159
248
  io.platform ??= process.platform
160
249
  io.cwd ??= process.cwd()
250
+ if (!argv.length) return bare(io)
251
+ if (ALIASES[argv[0]]) argv = [ALIASES[argv[0]], ...argv.slice(1)]
161
252
  const [command] = argv
162
- if (command && !command.startsWith('-') && !INSTALLER_COMMANDS.includes(command)) return delegate(argv, io)
253
+ if (SLATE_COMMANDS.has(command)) return slateCommand(argv, io)
254
+ if (command && !command.startsWith('-') && !COMMAND_NAMES.has(command)) {
255
+ const near = suggest(command)
256
+ const message = `Unknown command ${command}.${near ? ` Did you mean slatebox ${near}?` : ''} See slatebox help.`
257
+ io.stderr.write(`${message}\n`)
258
+ if (argv.includes('--json')) io.stdout.write(JSON.stringify({ event: 'error', id: 'usage', status: 'failed', exitCode: EXIT.USAGE, message, ...(near ? { suggestion: near } : {}) }) + '\n')
259
+ return EXIT.USAGE
260
+ }
163
261
  let parsed
164
262
  try {
165
263
  parsed = parse(argv)
@@ -173,7 +271,7 @@ export async function main(argv, io = {}) {
173
271
  const positionals = parsed.positionals
174
272
  if (flags.version) { io.stdout.write(`${PKG.version}\n`); return 0 }
175
273
  if (flags.help || positionals[0] === 'help') { io.stdout.write(HELP); return 0 }
176
- // Plain `npx slatebox` is the guided install on this machine.
274
+ // Flags with no command (`npx slatebox --dry-run`, `--answers x --yes`) are the install.
177
275
  if (!positionals.length) positionals.unshift('install')
178
276
 
179
277
  const agentMode = flags.agent === 'yes' || (flags.agent !== 'no' && detectAgent(io.env))
@@ -187,8 +285,12 @@ export async function main(argv, io = {}) {
187
285
  home: slateboxHome(io.env, flags.home), redactor, out, run: io.run || makeRunner(out), fetch: io.fetch || globalThis.fetch,
188
286
  interactive, tty, agentMode, json, yes: Boolean(flags.yes), healthTimeout: Number(flags['health-timeout'] || 600),
189
287
  cliFlags: parsed.values, platform: io.platform, cwd: io.cwd,
288
+ openBrowser: io.openBrowser, sleep: io.sleep, deviceLabel: io.deviceLabel, spawn: io.spawn,
289
+ teamHealthAttempts: io.teamHealthAttempts, teamHealthDelay: io.teamHealthDelay,
290
+ uid: io.uid, schedulerTimeout: io.schedulerTimeout,
190
291
  }
191
292
  if (interactive) ctx.prompt = createPrompt({ input: io.stdin, output: io.stderr })
293
+
192
294
  ctx.emitPlan = plan => {
193
295
  out.event({ event: 'plan', ...plan })
194
296
  const text = formatPlan(plan)
@@ -254,7 +356,11 @@ function upgradeImage(record, flags) {
254
356
 
255
357
  function finish(ctx, done, lines = []) {
256
358
  ctx.out.event({ event: 'done', ...done })
257
- for (const line of lines) ctx.out.say(line)
359
+ // { terminal } lines carry a setup link: straight to the terminal, past the redactor (setup-link.mjs).
360
+ for (const line of lines) {
361
+ if (typeof line === 'string') ctx.out.say(line)
362
+ else ctx.stderr.write(`${line.terminal}\n`)
363
+ }
258
364
  return 0
259
365
  }
260
366
 
@@ -267,14 +373,15 @@ async function prepareAnswers(ctx, flags, positionals) {
267
373
  const name = cliFlags.name || file?.name || flags.name || 'slatebox'
268
374
  const record = readRecord(ctx.home, name)
269
375
  let partial = collect({ record, env: ctx.env, file, flags: cliFlags })
270
- if (ctx.interactive) {
376
+ // --yes asks nothing: what is not given takes its default (resolveAnswers with { yes }).
377
+ if (ctx.interactive && !ctx.yes) {
271
378
  const kube = await ctx.run('kubectl', ['config', 'current-context']).catch(() => null)
272
379
  ctx.currentContext = kube?.code === 0 ? kube.stdout.trim() : null
273
380
  ctx.freePort = partial.address?.port ?? await defaultLocalPort()
274
381
  partial = await interview(ctx, partial)
275
382
  }
276
383
  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 })
384
+ const { answers, missing, errors } = resolveAnswers(partial, { freePort, cwd: ctx.cwd, home: ctx.env.HOME, yes: ctx.yes })
278
385
  if (errors.length) throw new InstallError(EXIT.USAGE, `Some answers are not valid: ${errors.map(error => error.field).join(', ')}.`, { fields: errors })
279
386
  if (missing.length) throw new InstallError(EXIT.NEEDS_INPUT, `Some answers are needed: ${missing.map(item => item.field).join(', ')}.`, { missing })
280
387
  return { answers, record, explicitContext: Boolean(cliFlags['k8s-context'] || file?.k8s?.context || record?.k8s?.context) }
@@ -286,18 +393,39 @@ async function applyTarget(ctx, answers, options) {
286
393
  return applyDocker(ctx, answers, { ...options, archive: ctx.flags['image-archive'] })
287
394
  }
288
395
 
396
+ function runningLines(ctx, done) {
397
+ return ['', `Slatebox is running at ${done.address}`, ...setupLines(ctx, done.name)]
398
+ }
399
+
289
400
  function closing(ctx, done) {
290
- if (done.nothingToChange) return [`Nothing to change: ${done.name} is running at ${done.address}.`]
401
+ 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)]
291
402
  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}`]
403
+ const lines = ctx.announced ? [] : runningLines(ctx, done)
404
+ if (done.teamAddress) {
405
+ lines.push('', `On this computer it also answers at ${done.localAddress}.`,
406
+ '', `Keep a copy of ${installDir(ctx.home, done.name)}/ (keys and the team-address credential).`)
407
+ }
293
408
  if (done.keyGenerated) {
294
409
  lines.push('', `Your key encryption key is stored in ${done.secretsFile}. Back it up with your password manager now.`,
295
410
  'Backups do not contain it, and without it people\'s saved AI keys cannot be read after a restore.')
296
411
  }
297
- lines.push(`Install record: ${done.installRecord}`, `Day two: slatebox status | upgrade | backup | ai --name ${done.name}`)
412
+ lines.push(`Install record: ${done.installRecord}`, `Next: slatebox status slatebox logs slatebox upgrade slatebox uninstall${done.name === 'slatebox' ? '' : ` (--name ${done.name})`}`)
298
413
  return lines
299
414
  }
300
415
 
416
+ // install --from cloud: the server is new and has no admin yet, so the team comes over once the
417
+ // person has made the first account (the setup link above) and an access token there.
418
+ function fromCloudLines(done) {
419
+ if (done.target === 'export') return []
420
+ return [
421
+ '', 'To bring your team over from Slatebox Cloud:',
422
+ ' 1. Open the setup link above and create your account.',
423
+ ` 2. In ${done.address}, open Profile → Developer and make an access token with "Move a team here".`,
424
+ ` 3. Run: SLATEBOX_API_TOKEN=<that token> npx slatebox import --from cloud${done.name === 'slatebox' ? '' : ` --name ${done.name}`}`,
425
+ ' (you sign in to Slatebox Cloud in your browser; nothing is copied until you confirm)',
426
+ ]
427
+ }
428
+
301
429
  async function showSecretOnce(ctx, record, name) {
302
430
  if (ctx.json || !(ctx.stdout.isTTY || ctx.flags['force-stdout'])) {
303
431
  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).')
@@ -313,6 +441,19 @@ async function dispatch(ctx, positionals, flags) {
313
441
  case 'agent-prompt':
314
442
  ctx.stdout.write(AGENT_PROMPT)
315
443
  return 0
444
+ case 'migrate': {
445
+ if (sub === 'invite') return inviteMovedPeople(ctx, { id: rest[0], to: flags.to })
446
+ 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>.`)
447
+ 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).')
448
+ return moveTeam(ctx, { from: flags.from, to: flags.to })
449
+ }
450
+ case 'import': {
451
+ if (sub) return importTeamFile(ctx, { file: sub, to: flags.to })
452
+ if (!flags.from) throw new InstallError(EXIT.USAGE, 'Import from where? slatebox import --from cloud, or slatebox import <file.sbxteam>.')
453
+ return moveTeam(ctx, { from: flags.from, to: flags.to })
454
+ }
455
+ case 'export':
456
+ return exportTeamFile(ctx, { from: flags.from, out: flags.out })
316
457
  case 'installs': {
317
458
  const records = listRecords(ctx.home)
318
459
  ctx.out.event({ event: 'done', installs: records.map(record => ({ name: record.name, target: record.target, address: record.address?.url, state: record.state })) })
@@ -324,13 +465,23 @@ async function dispatch(ctx, positionals, flags) {
324
465
  case 'install': {
325
466
  const { answers, record, explicitContext } = await prepareAnswers(ctx, flags, positionals)
326
467
  const planOnly = command === 'plan' || Boolean(flags['dry-run'])
468
+ // The address and setup link, printed the moment the install is healthy (before the backup
469
+ // schedule), and not again at the end.
470
+ ctx.announce = healthy => {
471
+ if (ctx.announced || healthy.target === 'export') return
472
+ ctx.announced = true
473
+ for (const line of runningLines(ctx, healthy)) {
474
+ if (typeof line === 'string') ctx.out.say(line)
475
+ else ctx.stderr.write(`${line.terminal}\n`)
476
+ }
477
+ }
327
478
  const done = await applyTarget(ctx, answers, { record, planOnly, explicitContext })
328
479
  if (done.planned) {
329
480
  ctx.out.event({ event: 'done', planned: true, name: answers.name, target: answers.target })
330
481
  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
482
  return 0
332
483
  }
333
- finish(ctx, done, closing(ctx, done))
484
+ finish(ctx, done, [...closing(ctx, done), ...(flags.from === 'cloud' ? fromCloudLines(done) : [])])
334
485
  if (flags['show-secrets'] && done.keyGenerated) await showSecretOnce(ctx, ctx.record, 'SLATEBOX_KEY_ENCRYPTION_KEY')
335
486
  return 0
336
487
  }
@@ -345,14 +496,29 @@ async function dispatch(ctx, positionals, flags) {
345
496
  case 'status': {
346
497
  const record = requireRecord(ctx, flags)
347
498
  const status = record.target === 'k8s' ? await statusK8s(ctx, record) : await statusDocker(ctx, record)
499
+ if (record.address?.team) status.teamAddress = await teamStatus(ctx, record)
348
500
  ctx.out.event({ event: 'done', ...status })
349
501
  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' })) {
502
+ 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' })) {
351
503
  ctx.out.say(`${label.padEnd(12)} ${value}`)
352
504
  }
505
+ 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`)
353
506
  }
354
507
  return status.health === 'healthy' ? 0 : EXIT.PRECONDITION
355
508
  }
509
+ case 'setup-link': {
510
+ const record = requireRecord(ctx, flags)
511
+ // As good as an admin password: a terminal only, never --json or a pipe, unless --force-stdout.
512
+ if (ctx.json || !(ctx.stdout.isTTY || flags['force-stdout'])) {
513
+ 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).')
514
+ }
515
+ const link = record.target === 'k8s' ? await setupLinkK8s(ctx, record) : await setupLinkDocker(ctx, record)
516
+ 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>`)
517
+ 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`)
518
+ ctx.stdout.write(`${link.url}\n`)
519
+ 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')
520
+ return 0
521
+ }
356
522
  case 'backup': {
357
523
  const record = requireRecord(ctx, flags)
358
524
  const result = record.target === 'k8s' ? await backupK8s(ctx, record, { to: flags.to }) : await backupDocker(ctx, record, { to: flags.to })
@@ -372,23 +538,100 @@ async function dispatch(ctx, positionals, flags) {
372
538
  case 'uninstall': {
373
539
  const record = requireRecord(ctx, flags)
374
540
  const deleteData = Boolean(flags['delete-data'])
541
+ const release = Boolean(record.address?.team) && !flags['keep-address'] && Boolean(readCredentials(ctx.home, record.name))
375
542
  if (deleteData) {
376
543
  let typed = flags.confirm
377
544
  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
545
  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
546
  }
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: [] }
547
+ 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: [] }
381
548
  ctx.emitPlan(plan)
382
549
  await ctx.confirm(plan)
383
550
  const result = record.target === 'k8s' ? await uninstallK8s(ctx, record, { deleteData }) : await uninstallDocker(ctx, record, { deleteData })
551
+ let released = null
552
+ if (release) {
553
+ released = await releaseTeamAddress(ctx, record, { offlineOk: true })
554
+ if (released.released) ctx.out.step('address', 'ok', `Released ${released.host} (held for your account for 30 days, then anyone may claim it)`)
555
+ 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.`)
556
+ }
557
+ const keepCredential = released && !released.released
384
558
  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 })
559
+ const dir = installDir(ctx.home, record.name)
560
+ if (keepCredential) {
561
+ for (const entry of existsSync(dir) ? readdirSync(dir) : []) if (entry !== CREDENTIALS_FILE) rmSync(join(dir, entry), { recursive: true, force: true })
562
+ } else {
563
+ rmSync(dir, { recursive: true, force: true })
564
+ // The installs folder goes too once nothing else is in it.
565
+ try { rmdirSync(join(ctx.home, 'installs')) } catch { /* another install, or files of someone else's */ }
566
+ }
388
567
  } else {
389
- writeRecord(ctx.home, { ...record, state: 'uninstalled' })
568
+ writeRecord(ctx.home, { ...record, ...(released?.released ? { address: localAddress(record) } : {}), state: 'uninstalled' })
390
569
  }
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}`])
570
+ const summary = { name: record.name, ...result, ...(released ? { addressReleased: released.released } : {}) }
571
+ 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}`])
572
+ }
573
+ case 'logs': {
574
+ const record = requireRecord(ctx, flags)
575
+ if (flags.service && !LOG_SERVICES.includes(flags.service)) throw new InstallError(EXIT.USAGE, `--service is one of ${LOG_SERVICES.join(', ')}.`)
576
+ 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.')
577
+ if (record.target === 'k8s') {
578
+ const args = ['--context', record.k8s.context, 'logs', '-n', record.k8s.namespace, `${record.name}-0`, '-c', 'slatebox', ...(flags.since ? ['--since', flags.since] : ['--tail', '500'])]
579
+ const result = await ctx.run('kubectl', args, { timeout: 120_000 })
580
+ if (result.code !== 0) throw new InstallError(EXIT.PRECONDITION, `kubectl logs failed: ${result.stderr.trim().split('\n').pop()}`)
581
+ for (const line of result.stdout.split('\n')) if (line && (!flags.service || line.startsWith(`[${flags.service}] `))) ctx.stdout.write(`${ctx.redactor.redact(line)}\n`)
582
+ return 0
583
+ }
584
+ await logsDocker(ctx, record, { follow: Boolean(flags.follow), service: flags.service, since: flags.since })
585
+ return 0
586
+ }
587
+ case 'rename': {
588
+ const record = requireRecord(ctx, flags)
589
+ if (!record.address?.team) throw new InstallError(EXIT.USAGE, `"${record.name}" has no team address. Add one with: slatebox install --team-address <name>`)
590
+ if (!sub) throw new InstallError(EXIT.USAGE, 'Name the new address: slatebox rename <new-name>')
591
+ const renamed = await renameTeamAddress(ctx, record, sub.toLowerCase())
592
+ ctx.out.step('address', 'ok', `${renamed.host} is yours; moving "${record.name}" to it`)
593
+ const done = await reapply(ctx, { ...record, address: { ...record.address, team: renamed.name, url: undefined } })
594
+ const finished = await finishRename(ctx, { ...record, address: { ...record.address, team: renamed.name } })
595
+ if (finished.done) ctx.out.step('address', 'ok', `${teamHost(renamed.previousName)} no longer points here (held for your account for 30 days)`)
596
+ 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.`)
597
+ return finish(ctx, { ...done, previousAddress: `https://${teamHost(renamed.previousName)}` }, ['', `Slatebox is now at ${done.address}`])
598
+ }
599
+ case 'address': {
600
+ const record = readRecord(ctx.home, flags.name || 'slatebox')
601
+ if (!sub || sub === 'status') {
602
+ const current = requireRecord(ctx, flags)
603
+ if (!current.address?.team) {
604
+ ctx.out.event({ event: 'done', name: current.name, teamAddress: null, address: current.address.url })
605
+ ctx.out.say(`"${current.name}" has no team address; it is at ${current.address.url}. Add one with: slatebox install --team-address <name>`)
606
+ return 0
607
+ }
608
+ const team = await teamStatus(ctx, current)
609
+ ctx.out.event({ event: 'done', name: current.name, teamAddress: team })
610
+ if (!ctx.json) ctx.out.say(`${team.host}: ${team.status}${team.suspension?.notice ? ` (${team.suspension.notice})` : ''}`)
611
+ return team.status === 'active' ? 0 : EXIT.PRECONDITION
612
+ }
613
+ if (sub === 'release') {
614
+ // Works from the credential alone, so an address left over after an offline uninstall can still be given back.
615
+ const target = record || { name: flags.name || 'slatebox', address: {} }
616
+ const released = await releaseTeamAddress(ctx, target)
617
+ ctx.out.step('address', 'ok', `Released ${released.host} (held for your account for 30 days, then anyone may claim it)`)
618
+ if (record && record.state !== 'uninstalled' && record.address?.team) {
619
+ const done = await reapply(ctx, { ...record, address: localAddress(record) })
620
+ return finish(ctx, { ...done, addressReleased: true }, ['', `"${record.name}" now answers only at ${done.address}.`])
621
+ }
622
+ if (record?.address?.team) writeRecord(ctx.home, { ...record, address: localAddress(record) })
623
+ 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 })
624
+ return finish(ctx, { name: target.name, addressReleased: true }, [])
625
+ }
626
+ if (sub === 'rotate') {
627
+ const current = requireRecord(ctx, flags)
628
+ if (!current.address?.team) throw new InstallError(EXIT.USAGE, `"${current.name}" has no team address.`)
629
+ await rotateTeamAddress(ctx, current)
630
+ ctx.out.step('address', 'ok', 'New tunnel secret: every connector holding the old token was dropped')
631
+ const done = await reapply(ctx, current)
632
+ return finish(ctx, { ...done, rotated: true }, ['', `${done.address} now uses the new tunnel token.`])
633
+ }
634
+ throw new InstallError(EXIT.USAGE, 'Usage: slatebox address [status | release | rotate]')
392
635
  }
393
636
  case 'ai':
394
637
  return aiCommand(ctx, flags, sub, rest)
@@ -408,6 +651,26 @@ async function dispatch(ctx, positionals, flags) {
408
651
  }
409
652
  }
410
653
 
654
+ function teamLine(status) {
655
+ const team = status.teamAddress
656
+ 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' : ''
657
+ return `https://${team.host} (${team.status}${connections})${team.suspension?.notice ? `: ${team.suspension.notice}` : ''}`
658
+ }
659
+
660
+ /** The install's address without its team address: this computer only (or the server's own address). */
661
+ function localAddress(record) {
662
+ if (record.target === 'k8s') return { url: `http://localhost:7070` }
663
+ const port = record.address?.port ?? 7070
664
+ return { url: undefined, port, listen: record.address?.listen ?? '127.0.0.1', team: null }
665
+ }
666
+
667
+ /** Apply an install record again (same image), after its address or tunnel token changed. */
668
+ async function reapply(ctx, record) {
669
+ const { answers, errors } = resolveAnswers(collect({ record }), {})
670
+ if (errors.length) throw new InstallError(EXIT.USAGE, `The install record is not valid: ${errors.map(error => `${error.field} (${error.message})`).join('; ')}`, { fields: errors })
671
+ return applyTarget(ctx, answers, { record, imageRef: record.imageRef, explicitContext: true })
672
+ }
673
+
411
674
  // ------------------------------------------------------------------ ai
412
675
 
413
676
  async function aiCommand(ctx, flags, sub, rest) {