@sixb/cli 0.1.25 → 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.
Files changed (109) hide show
  1. package/README.md +5 -5
  2. package/dist/commands/agent.d.ts +16 -0
  3. package/dist/commands/agent.d.ts.map +1 -0
  4. package/dist/commands/api.d.ts.map +1 -1
  5. package/dist/commands/check.d.ts.map +1 -1
  6. package/dist/commands/deploy.d.ts.map +1 -1
  7. package/dist/commands/dev-runner.d.ts +0 -1
  8. package/dist/commands/dev-runner.d.ts.map +1 -1
  9. package/dist/commands/dev.d.ts.map +1 -1
  10. package/dist/commands/env.d.ts +31 -0
  11. package/dist/commands/env.d.ts.map +1 -0
  12. package/dist/commands/worker-group.d.ts +0 -1
  13. package/dist/commands/worker-group.d.ts.map +1 -1
  14. package/dist/commands/worker.d.ts +0 -1
  15. package/dist/commands/worker.d.ts.map +1 -1
  16. package/dist/lib/command-line.d.ts +41 -6
  17. package/dist/lib/command-line.d.ts.map +1 -1
  18. package/dist/lib/deploy-release.d.ts +2 -0
  19. package/dist/lib/deploy-release.d.ts.map +1 -1
  20. package/dist/lib/deploy-source.d.ts +2 -0
  21. package/dist/lib/deploy-source.d.ts.map +1 -1
  22. package/dist/lib/env-config.d.ts +17 -0
  23. package/dist/lib/env-config.d.ts.map +1 -0
  24. package/dist/lib/env-file.d.ts +16 -0
  25. package/dist/lib/env-file.d.ts.map +1 -0
  26. package/dist/lib/github-ci.d.ts.map +1 -1
  27. package/dist/lib/hidden-prompt.d.ts +19 -0
  28. package/dist/lib/hidden-prompt.d.ts.map +1 -0
  29. package/dist/lib/runtime.d.ts +0 -1
  30. package/dist/lib/runtime.d.ts.map +1 -1
  31. package/dist/lib/worker-registry.d.ts +0 -1
  32. package/dist/lib/worker-registry.d.ts.map +1 -1
  33. package/dist/tui/app.d.ts +27 -0
  34. package/dist/tui/app.d.ts.map +1 -0
  35. package/dist/tui/brand.d.ts +7 -0
  36. package/dist/tui/brand.d.ts.map +1 -0
  37. package/dist/tui/computer.d.ts +8 -0
  38. package/dist/tui/computer.d.ts.map +1 -0
  39. package/dist/tui/connection.d.ts +45 -0
  40. package/dist/tui/connection.d.ts.map +1 -0
  41. package/dist/tui/context.d.ts +13 -0
  42. package/dist/tui/context.d.ts.map +1 -0
  43. package/dist/tui/format.d.ts +118 -0
  44. package/dist/tui/format.d.ts.map +1 -0
  45. package/dist/tui/index.d.ts +12 -0
  46. package/dist/tui/index.d.ts.map +1 -0
  47. package/dist/tui/markdown.d.ts +18 -0
  48. package/dist/tui/markdown.d.ts.map +1 -0
  49. package/dist/tui/palette.d.ts +25 -0
  50. package/dist/tui/palette.d.ts.map +1 -0
  51. package/dist/tui/parts.d.ts +74 -0
  52. package/dist/tui/parts.d.ts.map +1 -0
  53. package/dist/tui/runner.d.ts +75 -0
  54. package/dist/tui/runner.d.ts.map +1 -0
  55. package/dist/tui/settings.d.ts +56 -0
  56. package/dist/tui/settings.d.ts.map +1 -0
  57. package/dist/tui/slash.d.ts +14 -0
  58. package/dist/tui/slash.d.ts.map +1 -0
  59. package/dist/tui/theme.d.ts +39 -0
  60. package/dist/tui/theme.d.ts.map +1 -0
  61. package/dist/tui/transcript.d.ts +52 -0
  62. package/dist/tui/transcript.d.ts.map +1 -0
  63. package/dist/tui/ui.d.ts +42 -0
  64. package/dist/tui/ui.d.ts.map +1 -0
  65. package/dist/ui/deploy-screens.d.ts +3 -1
  66. package/dist/ui/deploy-screens.d.ts.map +1 -1
  67. package/dist/ui/env-screens.d.ts +37 -0
  68. package/dist/ui/env-screens.d.ts.map +1 -0
  69. package/package.json +19 -17
  70. package/src/commands/agent.ts +344 -0
  71. package/src/commands/api.ts +2 -1
  72. package/src/commands/check.ts +5 -1
  73. package/src/commands/deploy.ts +29 -3
  74. package/src/commands/dev-runner.ts +3 -5
  75. package/src/commands/dev.ts +3 -0
  76. package/src/commands/env.ts +422 -0
  77. package/src/commands/worker-group.ts +0 -4
  78. package/src/commands/worker.ts +0 -4
  79. package/src/index.tsx +95 -5
  80. package/src/lib/command-line.ts +111 -16
  81. package/src/lib/deploy-release.ts +3 -11
  82. package/src/lib/deploy-source.ts +10 -0
  83. package/src/lib/env-config.ts +96 -0
  84. package/src/lib/env-file.ts +104 -0
  85. package/src/lib/github-ci.ts +3 -1
  86. package/src/lib/hidden-prompt.ts +97 -0
  87. package/src/lib/runtime.ts +0 -2
  88. package/src/lib/worker-registry.ts +0 -2
  89. package/src/tui/app.tsx +1334 -0
  90. package/src/tui/brand.tsx +51 -0
  91. package/src/tui/computer.ts +91 -0
  92. package/src/tui/connection.ts +149 -0
  93. package/src/tui/context.tsx +149 -0
  94. package/src/tui/format.ts +477 -0
  95. package/src/tui/index.tsx +364 -0
  96. package/src/tui/markdown.ts +91 -0
  97. package/src/tui/palette.tsx +183 -0
  98. package/src/tui/parts.ts +274 -0
  99. package/src/tui/runner.ts +256 -0
  100. package/src/tui/settings.ts +176 -0
  101. package/src/tui/slash.ts +32 -0
  102. package/src/tui/theme.ts +111 -0
  103. package/src/tui/transcript.tsx +637 -0
  104. package/src/tui/ui.tsx +177 -0
  105. package/src/ui/deploy-screens.ts +12 -1
  106. package/src/ui/env-screens.ts +81 -0
  107. package/dist/lib/agent-turn-timeout.d.ts +0 -8
  108. package/dist/lib/agent-turn-timeout.d.ts.map +0 -1
  109. package/src/lib/agent-turn-timeout.ts +0 -46
@@ -0,0 +1,422 @@
1
+ import { readFile, writeFile } from "node:fs/promises"
2
+ import { join, resolve } from "node:path"
3
+ import { createInterface } from "node:readline/promises"
4
+ import { pathToFileURL } from "node:url"
5
+ import {
6
+ type EnvConfig,
7
+ type EnvName,
8
+ type EnvSource,
9
+ EnvSourceUnreachableError,
10
+ type EnvVarRule,
11
+ } from "@sixb/core/env"
12
+ import {
13
+ ENV_CONFIG_FILE,
14
+ envVarNeeded,
15
+ loadEnvConfig,
16
+ missingEnvError,
17
+ missingEnvSentence,
18
+ missingEnvVars,
19
+ VAR_NAME_PATTERN,
20
+ } from "../lib/env-config"
21
+ import { isGeneratedEnvFile, readEnvFile, writeEnvFile } from "../lib/env-file"
22
+ import { errorMessage, SixbCliError } from "../lib/errors"
23
+ import { promptHidden } from "../lib/hidden-prompt"
24
+ import { renderStatic } from "../ui"
25
+ import {
26
+ type EnvStatusCell,
27
+ envInitView,
28
+ envKeptView,
29
+ envPulledView,
30
+ envSetView,
31
+ envStatusView,
32
+ } from "../ui/env-screens"
33
+ import { canRunLive } from "../ui/live/can-run-live"
34
+
35
+ const ENV_NAMES: readonly EnvName[] = ["dev", "prod"]
36
+ const DOPPLER_PACKAGE = "@sixb/env-doppler"
37
+
38
+ // ─── pull ────────────────────────────────────────────────────────────────────
39
+
40
+ export async function runEnvPull(options: {
41
+ readonly env?: string
42
+ readonly tokenFile?: string
43
+ readonly force?: boolean
44
+ readonly cwd?: string
45
+ }): Promise<void> {
46
+ const cwd = options.cwd ?? process.cwd()
47
+ const env = parseEnvName(options.env ?? "dev")
48
+
49
+ // A server has a token file. Refusing everyone else keeps prod values off laptops by default.
50
+ if (env === "prod" && options.tokenFile === undefined) {
51
+ throw new SixbCliError("[SixbEnv] Prod values stay on servers, so they can't be pulled here.", {
52
+ remediation: "Read a value in your source's dashboard, or change one with `sixb env set`.",
53
+ })
54
+ }
55
+
56
+ // A server deploying a commit whose `sixb.env.ts` has no source, such as a rollback.
57
+ if (options.tokenFile !== undefined) {
58
+ const deployed = await loadEnvConfig(cwd)
59
+ if (deployed && !deployed.source) {
60
+ await renderStatic(envKeptView({ env, reason: "This commit's sixb.env.ts has no source." }))
61
+ return
62
+ }
63
+ }
64
+
65
+ const { config, source } = await requireSource(cwd)
66
+ const token = options.tokenFile === undefined ? undefined : await readToken(options.tokenFile)
67
+ const pulled = await pullEnv({
68
+ cwd,
69
+ config,
70
+ source,
71
+ env,
72
+ ...(token === undefined ? {} : { token }),
73
+ force: options.force === true,
74
+ })
75
+
76
+ await renderStatic(
77
+ pulled.kept
78
+ ? envKeptView({ env, reason: pulled.reason })
79
+ : envPulledView({ env, count: Object.keys(pulled.values).length })
80
+ )
81
+ }
82
+
83
+ type PullResult =
84
+ | { readonly kept: false; readonly values: Readonly<Record<string, string>> }
85
+ | { readonly kept: true; readonly reason: string }
86
+
87
+ async function pullEnv(input: {
88
+ readonly cwd: string
89
+ readonly config: EnvConfig
90
+ readonly source: EnvSource
91
+ readonly env: EnvName
92
+ readonly token?: string
93
+ readonly force?: boolean
94
+ }): Promise<PullResult> {
95
+ const { config, source, env, token } = input
96
+ const path = join(input.cwd, ".env")
97
+
98
+ let values: Readonly<Record<string, string>>
99
+ try {
100
+ values = await source.read(env, token === undefined ? {} : { token })
101
+ } catch (error) {
102
+ // A server riding out an outage, so it can still take a hotfix. A refusal never reaches this:
103
+ // a revoked token must stop the deploy.
104
+ const riding = token !== undefined && error instanceof EnvSourceUnreachableError
105
+ if (riding && (await isCompleteGeneratedEnv(path, config, env))) {
106
+ return { kept: true, reason: errorMessage(error) }
107
+ }
108
+ throw error
109
+ }
110
+
111
+ const missing = missingEnvVars(config, values, env)
112
+ if (missing.length > 0) {
113
+ throw new SixbCliError(`[SixbEnv] ${env} is missing ${missing.join(", ")}.`, {
114
+ remediation: missing.map((name) => `sixb env set ${name} --env ${env}`).join("\n"),
115
+ })
116
+ }
117
+
118
+ if (!input.force) await refuseToLoseValues(path, values)
119
+ await writeEnvFile(path, values, env)
120
+ return { kept: false, values }
121
+ }
122
+
123
+ async function isCompleteGeneratedEnv(
124
+ path: string,
125
+ config: EnvConfig,
126
+ env: EnvName
127
+ ): Promise<boolean> {
128
+ if (!(await isGeneratedEnvFile(path))) return false
129
+ return missingEnvVars(config, await readEnvFile(path), env).length === 0
130
+ }
131
+
132
+ /** A hand-written `.env` may hold the only copy of a value, so it's replaced only on request. */
133
+ async function refuseToLoseValues(
134
+ path: string,
135
+ values: Readonly<Record<string, string>>
136
+ ): Promise<void> {
137
+ if (!(await Bun.file(path).exists()) || (await isGeneratedEnvFile(path))) return
138
+
139
+ const current = await readEnvFile(path)
140
+ const different = Object.keys(current)
141
+ .filter((name) => current[name] !== values[name])
142
+ .sort()
143
+ if (different.length > 0) {
144
+ throw new SixbCliError(
145
+ `[SixbEnv] This .env was written by hand, and the source has something else for ${different.join(", ")}.`,
146
+ {
147
+ remediation:
148
+ "Move what you want to keep to the source or .env.local, then delete the file or pass --force.",
149
+ }
150
+ )
151
+ }
152
+ }
153
+
154
+ async function readToken(path: string): Promise<string> {
155
+ const text = await readFile(path, "utf8").catch(() => {
156
+ throw new SixbCliError(`[SixbEnv] Could not read the token file ${path}.`)
157
+ })
158
+ const token = text.trim()
159
+ if (!token) throw new SixbCliError(`[SixbEnv] The token file ${path} is empty.`)
160
+ return token
161
+ }
162
+
163
+ // ─── dev ─────────────────────────────────────────────────────────────────────
164
+
165
+ /** Before `sixb dev`: stops on a missing variable, offering to pull when there's a source. */
166
+ export async function assertDevEnv(cwd: string): Promise<void> {
167
+ const config = await loadEnvConfig(cwd)
168
+ if (!config) return
169
+
170
+ const missing = missingEnvVars(config, process.env, "dev")
171
+ if (missing.length === 0) return
172
+ if (!config.source || !canRunLive()) throw missingEnvError(config, missing)
173
+
174
+ process.stderr.write(`\n${missingEnvSentence(missing)}\n`)
175
+ const prompt = createInterface({ input: process.stdin, output: process.stderr })
176
+ const answer = await prompt.question("Pull from dev now? (Y/n) ").finally(() => prompt.close())
177
+ if (/^n/i.test(answer.trim())) throw missingEnvError(config, missing)
178
+
179
+ await pullIntoThisProcess(cwd, config, config.source)
180
+ }
181
+
182
+ /**
183
+ * Bun read `.env` when this process started, and the processes `sixb dev` starts inherit what it
184
+ * read. So a pull also has to update this process, or they run on the old values. `.env.local`
185
+ * still wins, as it does when Bun loads the files itself. A variable exported in the shell loses
186
+ * here, which only happens on the rare start that pulls.
187
+ */
188
+ export async function pullIntoThisProcess(
189
+ cwd: string,
190
+ config: EnvConfig,
191
+ source: EnvSource
192
+ ): Promise<void> {
193
+ const pulled = await pullEnv({ cwd, config, source, env: "dev" })
194
+ if (pulled.kept) return
195
+
196
+ const localPath = join(cwd, ".env.local")
197
+ const local = (await Bun.file(localPath).exists()) ? await readEnvFile(localPath) : {}
198
+ Object.assign(process.env, pulled.values, local)
199
+
200
+ await renderStatic(envPulledView({ env: "dev", count: Object.keys(pulled.values).length }))
201
+
202
+ const stillMissing = missingEnvVars(config, process.env, "dev")
203
+ if (stillMissing.length > 0) throw missingEnvError(config, stillMissing)
204
+ }
205
+
206
+ // ─── set ─────────────────────────────────────────────────────────────────────
207
+
208
+ export async function runEnvSet(options: {
209
+ readonly name: string
210
+ readonly env: string | undefined
211
+ readonly cwd?: string
212
+ }): Promise<void> {
213
+ const cwd = options.cwd ?? process.cwd()
214
+ const { name } = options
215
+ // Never quoted: `sixb env set KEY=value` is an easy slip, and this may be a CI log.
216
+ if (!VAR_NAME_PATTERN.test(name)) {
217
+ throw new SixbCliError("[SixbEnv] That is not a variable name.", {
218
+ remediation:
219
+ "Name the variable alone, then give the value at the prompt or on standard input.",
220
+ })
221
+ }
222
+ const env = parseEnvName(options.env)
223
+ const { config, source } = await requireSource(cwd)
224
+
225
+ // Never an argument: arguments land in shell history and in the process list.
226
+ const value = process.stdin.isTTY
227
+ ? await promptHidden("Value:")
228
+ : (await Bun.stdin.text()).replace(/\r?\n$/, "")
229
+ if (value === "") throw new SixbCliError(`[SixbEnv] ${name} needs a value.`)
230
+
231
+ await source.write(env, { [name]: value })
232
+ await renderStatic(envSetView({ name, env, declared: name in config.vars }))
233
+ }
234
+
235
+ // ─── status ──────────────────────────────────────────────────────────────────
236
+
237
+ export async function runEnvStatus(options: { readonly cwd?: string } = {}): Promise<void> {
238
+ const { config, source } = await requireSource(options.cwd ?? process.cwd())
239
+
240
+ const [dev, prod] = await Promise.allSettled(ENV_NAMES.map((env) => source.names(env)))
241
+ // Someone may only have access to dev. With neither, the failure is what to show.
242
+ if (dev?.status === "rejected" && prod?.status === "rejected") throw dev.reason
243
+
244
+ const devNames = dev?.status === "fulfilled" ? new Set(dev.value) : null
245
+ const prodNames = prod?.status === "fulfilled" ? new Set(prod.value) : null
246
+ const names = new Set([...Object.keys(config.vars), ...(devNames ?? []), ...(prodNames ?? [])])
247
+
248
+ const cell = (env: EnvName, found: ReadonlySet<string> | null, name: string): EnvStatusCell => {
249
+ if (!found) return "unknown"
250
+ if (found.has(name)) return "set"
251
+ return envVarNeeded(config.vars[name] ?? "optional", env) ? "missing" : "unneeded"
252
+ }
253
+ const rows = [...names].sort().map((name) => ({
254
+ name,
255
+ dev: cell("dev", devNames, name),
256
+ prod: cell("prod", prodNames, name),
257
+ declared: name in config.vars,
258
+ }))
259
+ const missing = rows.flatMap((row) => [row.dev, row.prod]).filter((c) => c === "missing").length
260
+
261
+ await renderStatic(envStatusView({ rows, missing }))
262
+ if (missing > 0) process.exitCode = 1
263
+ }
264
+
265
+ // ─── init ────────────────────────────────────────────────────────────────────
266
+
267
+ export async function runEnvInit(options: {
268
+ readonly project: string
269
+ readonly dev?: string
270
+ readonly prod?: string
271
+ readonly cwd?: string
272
+ }): Promise<void> {
273
+ const cwd = options.cwd ?? process.cwd()
274
+ const configPath = join(cwd, ENV_CONFIG_FILE)
275
+ if (await Bun.file(configPath).exists()) {
276
+ throw new SixbCliError(`[SixbEnv] ${ENV_CONFIG_FILE} already exists.`)
277
+ }
278
+
279
+ const files = [
280
+ ["dev", options.dev],
281
+ ["prod", options.prod],
282
+ ] as const
283
+ const given = files.flatMap(([env, file]) => (file === undefined ? [] : [{ env, file }]))
284
+ if (given.length === 0) {
285
+ throw new SixbCliError("[SixbEnv] Say where the current values are.", {
286
+ remediation: "sixb env init <project> --dev .env --prod .env.prod",
287
+ })
288
+ }
289
+
290
+ const source = await loadDopplerSource(cwd, options.project)
291
+ const uploads = await Promise.all(
292
+ given.map(async ({ env, file }) => {
293
+ const path = resolve(cwd, file)
294
+ if (!(await Bun.file(path).exists())) {
295
+ throw new SixbCliError(`[SixbEnv] ${file} does not exist.`)
296
+ }
297
+ return { env, values: uploadableValues(await readEnvFile(path), file) }
298
+ })
299
+ )
300
+
301
+ // Check every environment before writing to any, so a conflict changes nothing. Running this
302
+ // again after a failed upload finds the same values, which aren't a conflict.
303
+ for (const { env, values } of uploads) {
304
+ const existing = await source.read(env)
305
+ const conflicts = Object.keys(values).filter(
306
+ (name) => name in existing && existing[name] !== values[name]
307
+ )
308
+ if (conflicts.length > 0) {
309
+ throw new SixbCliError(
310
+ `[SixbEnv] ${options.project} already has other values in ${env} for ${conflicts.sort().join(", ")}.`,
311
+ {
312
+ remediation:
313
+ "Change them in your source's dashboard, or edit the file, and run this again.",
314
+ }
315
+ )
316
+ }
317
+ }
318
+ for (const { env, values } of uploads) await source.write(env, values)
319
+
320
+ const vars = declaredVars(uploads)
321
+ await writeFile(configPath, renderEnvConfig(options.project, vars))
322
+ await renderStatic(
323
+ envInitView({
324
+ uploaded: uploads.map(({ env, values }) => ({ env, count: Object.keys(values).length })),
325
+ names: Object.keys(vars).length,
326
+ })
327
+ )
328
+ }
329
+
330
+ /**
331
+ * The first guess at each rule. A name with a value in dev and in prod, when each was given, is
332
+ * `required`; one with a value in prod alone is `prod`. Anything else, such as a name only dev has,
333
+ * would fail a deploy if it were required, so it starts `optional`.
334
+ */
335
+ function declaredVars(
336
+ uploads: readonly { readonly env: EnvName; readonly values: Record<string, string> }[]
337
+ ): Record<string, EnvVarRule> {
338
+ const names = uploads.flatMap(({ values }) => Object.keys(values))
339
+ const dev = uploads.find(({ env }) => env === "dev")?.values
340
+ const prod = uploads.find(({ env }) => env === "prod")?.values
341
+
342
+ return Object.fromEntries(
343
+ [...new Set(names)].sort().map((name): [string, EnvVarRule] => {
344
+ if (dev?.[name] && (!prod || prod[name])) return [name, "required"]
345
+ return [name, prod?.[name] ? "prod" : "optional"]
346
+ })
347
+ )
348
+ }
349
+
350
+ /**
351
+ * What a file can upload. A name `sixb.env.ts` couldn't declare stops this before anything is sent.
352
+ * `DOPPLER_*` is how this machine reaches Doppler, not a value of the project.
353
+ */
354
+ function uploadableValues(
355
+ values: Readonly<Record<string, string>>,
356
+ file: string
357
+ ): Record<string, string> {
358
+ const invalid = Object.keys(values).filter((name) => !VAR_NAME_PATTERN.test(name))
359
+ if (invalid.length > 0) {
360
+ throw new SixbCliError(
361
+ `[SixbEnv] ${file} has names that aren't variable names: ${invalid.sort().join(", ")}.`,
362
+ { remediation: "Rename them or remove them, and run this again." }
363
+ )
364
+ }
365
+ return Object.fromEntries(Object.entries(values).filter(([name]) => !name.startsWith("DOPPLER_")))
366
+ }
367
+
368
+ function renderEnvConfig(project: string, vars: Readonly<Record<string, EnvVarRule>>): string {
369
+ const lines = Object.entries(vars).map(([name, rule]) => ` ${name}: "${rule}",`)
370
+ return [
371
+ 'import { defineEnv } from "@sixb/core/env"',
372
+ `import { doppler } from "${DOPPLER_PACKAGE}"`,
373
+ "",
374
+ "export default defineEnv({",
375
+ ` source: doppler({ project: ${JSON.stringify(project)} }),`,
376
+ " vars: {",
377
+ ...lines,
378
+ " },",
379
+ "})",
380
+ "",
381
+ ].join("\n")
382
+ }
383
+
384
+ /** `sixb.env.ts` doesn't exist yet to load a source from, so this finds the project's own copy. */
385
+ async function loadDopplerSource(cwd: string, project: string): Promise<EnvSource> {
386
+ let path: string
387
+ try {
388
+ path = Bun.resolveSync(DOPPLER_PACKAGE, cwd)
389
+ } catch {
390
+ throw new SixbCliError(`[SixbEnv] This project doesn't have ${DOPPLER_PACKAGE} yet.`, {
391
+ remediation: `bun add ${DOPPLER_PACKAGE}`,
392
+ })
393
+ }
394
+ const module = (await import(pathToFileURL(path).href)) as {
395
+ readonly doppler: (options: { readonly project: string }) => EnvSource
396
+ }
397
+ return module.doppler({ project })
398
+ }
399
+
400
+ // ─── shared ──────────────────────────────────────────────────────────────────
401
+
402
+ function parseEnvName(value: string | undefined): EnvName {
403
+ if (value === "dev" || value === "prod") return value
404
+ throw new SixbCliError("[SixbEnv] Choose an environment: --env dev or --env prod.")
405
+ }
406
+
407
+ async function requireSource(
408
+ cwd: string
409
+ ): Promise<{ readonly config: EnvConfig; readonly source: EnvSource }> {
410
+ const config = await loadEnvConfig(cwd)
411
+ if (!config) {
412
+ throw new SixbCliError(`[SixbEnv] No ${ENV_CONFIG_FILE} in ${cwd}.`, {
413
+ remediation: "sixb env init <project> --dev .env --prod .env.prod",
414
+ })
415
+ }
416
+ if (!config.source) {
417
+ throw new SixbCliError(`[SixbEnv] ${ENV_CONFIG_FILE} has no \`source\`.`, {
418
+ remediation: `Add one, such as \`source: doppler({ project: "shop" })\` from ${DOPPLER_PACKAGE}.`,
419
+ })
420
+ }
421
+ return { config, source: config.source }
422
+ }
@@ -1,4 +1,3 @@
1
- import { resolveAgentTurnTimeoutMs } from "../lib/agent-turn-timeout"
2
1
  import { type LoadedSixbHost, loadSixbFromEntry } from "../lib/loadSixb"
3
2
  import { resolveRuntimeEntry } from "../lib/production"
4
3
  import { runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
@@ -32,7 +31,6 @@ export interface WorkerGroupOptions {
32
31
  noMigrate?: boolean
33
32
  workerTypes?: readonly string[]
34
33
  apiPublicOrigin?: string
35
- agentTurnTimeout?: string
36
34
  concurrency?: readonly string[]
37
35
  vectorConcurrency?: string
38
36
  subagentConcurrency?: string
@@ -45,7 +43,6 @@ export async function runWorkerGroup(options: WorkerGroupOptions = {}) {
45
43
  // Validate explicit worker types before loading the runtime so an unknown type
46
44
  // fails fast, just like `sixb worker`.
47
45
  const requestedTypes = (options.workerTypes ?? []).map(resolveWorkerTypeToStart)
48
- const agentTurnTimeoutMs = resolveAgentTurnTimeoutMs(options.agentTurnTimeout)
49
46
  const workerConcurrency = resolveWorkerConcurrency(options.concurrency)
50
47
  const vectorConcurrency = resolveVectorConcurrency(options.vectorConcurrency)
51
48
  const subagents = resolveSubagentConcurrency({
@@ -98,7 +95,6 @@ export async function runWorkerGroup(options: WorkerGroupOptions = {}) {
98
95
  workers = workerTypes.map((workerType) =>
99
96
  createWorkerForType(host, workerType, {
100
97
  agentApiBaseUrl: options.apiPublicOrigin,
101
- agentTurnTimeoutMs,
102
98
  workerConcurrency,
103
99
  vectorConcurrency,
104
100
  ...subagents,
@@ -1,4 +1,3 @@
1
- import { resolveAgentTurnTimeoutMs } from "../lib/agent-turn-timeout"
2
1
  import { SixbCliError } from "../lib/errors"
3
2
  import { type LoadedSixbHost, loadSixbFromEntry } from "../lib/loadSixb"
4
3
  import { resolveRuntimeEntry } from "../lib/production"
@@ -25,7 +24,6 @@ export interface WorkerOptions {
25
24
  noMigrate?: boolean
26
25
  workerType?: string
27
26
  apiPublicOrigin?: string
28
- agentTurnTimeout?: string
29
27
  concurrency?: string
30
28
  vectorConcurrency?: string
31
29
  subagentConcurrency?: string
@@ -36,7 +34,6 @@ export async function runWorker(options: WorkerOptions = {}) {
36
34
  process.env.NODE_ENV = "production"
37
35
 
38
36
  const workerType = resolveWorkerTypeToStart(options.workerType)
39
- const agentTurnTimeoutMs = resolveAgentTurnTimeoutMs(options.agentTurnTimeout)
40
37
  const workerConcurrency = resolveSingleWorkerConcurrency(workerType, options.concurrency)
41
38
  const vectorConcurrency = resolveVectorConcurrency(options.vectorConcurrency)
42
39
  const subagents = resolveSubagentConcurrency({
@@ -79,7 +76,6 @@ export async function runWorker(options: WorkerOptions = {}) {
79
76
 
80
77
  worker = createWorkerForType(sixb, workerType, {
81
78
  agentApiBaseUrl: options.apiPublicOrigin,
82
- agentTurnTimeoutMs,
83
79
  workerConcurrency,
84
80
  vectorConcurrency,
85
81
  ...subagents,
package/src/index.tsx CHANGED
@@ -23,6 +23,7 @@ const args = process.argv.slice(2)
23
23
  const MINIMUM_BUN_VERSION = "1.4.2"
24
24
 
25
25
  assertSupportedBunVersion()
26
+ assertBunCheckRanTheChecker()
26
27
 
27
28
  const VERSION = `sixb v${await readPackageVersion()}`
28
29
 
@@ -42,6 +43,22 @@ function assertSupportedBunVersion(): void {
42
43
  process.exit(1)
43
44
  }
44
45
 
46
+ /**
47
+ * A project's `typecheck` script runs `bun check --no-script`. Bun before 1.4.3 has no type
48
+ * checker, so it runs the project's `check` script — this command — with the flag instead, and an
49
+ * unknown-option error would not say why.
50
+ */
51
+ function assertBunCheckRanTheChecker(): void {
52
+ if (args[0] !== "check" || !args.includes("--no-script")) return
53
+ if (compareVersions(Bun.version, "1.4.3") >= 0) return
54
+
55
+ console.error(
56
+ `[Sixb] Bun ${Bun.version} has no type checker, so \`bun check\` ran the project's \`check\` ` +
57
+ "script instead. Run `bun upgrade` and try again."
58
+ )
59
+ process.exit(1)
60
+ }
61
+
45
62
  /** Numeric compare of the leading `major.minor.patch`, ignoring any prerelease suffix. */
46
63
  function compareVersions(left: string, right: string): number {
47
64
  const parse = (value: string) =>
@@ -70,6 +87,17 @@ async function readPackageVersion(): Promise<string> {
70
87
  }
71
88
 
72
89
  async function main(): Promise<void> {
90
+ // `sixb` alone, in a terminal: the full-screen app. Anywhere else it prints its help.
91
+ if (args.length === 0) {
92
+ const { canRunLive } = await import("./ui/live/can-run-live")
93
+ if (canRunLive()) {
94
+ const { runTui } = await import("./tui")
95
+ await runTui({ version: VERSION })
96
+ // Its turns ended and its session closed, or their wait ran out: nothing is left to wait for,
97
+ // and whatever the app leaves running would keep the terminal from its prompt.
98
+ process.exit()
99
+ }
100
+ }
73
101
  const parsed = parseCliArgs(args)
74
102
  if (parsed.kind === "version") {
75
103
  const { renderVersion } = await import("./ui")
@@ -106,7 +134,6 @@ async function main(): Promise<void> {
106
134
  apiHost: getFlag("api-host"),
107
135
  apiPublicOrigin: getFlag("api-public-origin"),
108
136
  appPublicOrigin: getFlag("app-public-origin"),
109
- agentTurnTimeout: getFlag("agent-turn-timeout"),
110
137
  concurrency: getFlags("concurrency"),
111
138
  vectorConcurrency: getFlag("vector-concurrency"),
112
139
  subagentConcurrency: getFlag("subagent-concurrency"),
@@ -123,7 +150,6 @@ async function main(): Promise<void> {
123
150
  noMigrate: hasFlag("no-migrate"),
124
151
  workerType: positionals[0],
125
152
  apiPublicOrigin: getFlag("api-public-origin"),
126
- agentTurnTimeout: getFlag("agent-turn-timeout"),
127
153
  concurrency: getFlag("concurrency"),
128
154
  vectorConcurrency: getFlag("vector-concurrency"),
129
155
  subagentConcurrency: getFlag("subagent-concurrency"),
@@ -139,7 +165,6 @@ async function main(): Promise<void> {
139
165
  noMigrate: hasFlag("no-migrate"),
140
166
  workerTypes: positionals,
141
167
  apiPublicOrigin: getFlag("api-public-origin"),
142
- agentTurnTimeout: getFlag("agent-turn-timeout"),
143
168
  concurrency: getFlags("concurrency"),
144
169
  vectorConcurrency: getFlag("vector-concurrency"),
145
170
  subagentConcurrency: getFlag("subagent-concurrency"),
@@ -193,6 +218,20 @@ async function main(): Promise<void> {
193
218
  break
194
219
  }
195
220
 
221
+ case "agent": {
222
+ const { runAgent } = await import("./commands/agent")
223
+ await runAgent({
224
+ text: positionals,
225
+ thread: getFlag("thread"),
226
+ cloud: hasFlag("cloud"),
227
+ approvalMode: getFlag("approval-mode"),
228
+ json: hasFlag("json"),
229
+ apiUrl: getFlag("api-url"),
230
+ profile: getFlag("profile"),
231
+ })
232
+ break
233
+ }
234
+
196
235
  case "status": {
197
236
  const { runStatus } = await import("./commands/status")
198
237
  await runStatus({
@@ -335,6 +374,42 @@ async function main(): Promise<void> {
335
374
  break
336
375
  }
337
376
 
377
+ case "env:init": {
378
+ const { runEnvInit } = await import("./commands/env")
379
+ const dev = getFlag("dev")
380
+ const prod = getFlag("prod")
381
+ await runEnvInit({
382
+ project: positionals[0] ?? "",
383
+ ...(dev === undefined ? {} : { dev }),
384
+ ...(prod === undefined ? {} : { prod }),
385
+ })
386
+ break
387
+ }
388
+
389
+ case "env:pull": {
390
+ const { runEnvPull } = await import("./commands/env")
391
+ const env = getFlag("env")
392
+ const tokenFile = getFlag("token-file")
393
+ await runEnvPull({
394
+ ...(env === undefined ? {} : { env }),
395
+ ...(tokenFile === undefined ? {} : { tokenFile }),
396
+ force: hasFlag("force"),
397
+ })
398
+ break
399
+ }
400
+
401
+ case "env:set": {
402
+ const { runEnvSet } = await import("./commands/env")
403
+ await runEnvSet({ name: positionals[0] ?? "", env: getFlag("env") })
404
+ break
405
+ }
406
+
407
+ case "env:status": {
408
+ const { runEnvStatus } = await import("./commands/env")
409
+ await runEnvStatus()
410
+ break
411
+ }
412
+
338
413
  case "deploy": {
339
414
  const { runDeploy } = await import("./commands/deploy")
340
415
  await runDeploy({ dryRun: hasFlag("dry-run"), json: hasFlag("json"), ref: getFlag("ref") })
@@ -427,7 +502,7 @@ main().catch(async (error) => {
427
502
  function cliExitCode(error: unknown): number {
428
503
  if (error instanceof CliUsageError) return error.exitCode
429
504
  if (error instanceof CliError) return error.exitCode
430
- if (error instanceof SixbApiError) return 3
505
+ if (isApiError(error)) return 3
431
506
  if (errorMessage(error).startsWith("Usage:")) return 2
432
507
  return 1
433
508
  }
@@ -443,7 +518,7 @@ function cliErrorBody(error: unknown): {
443
518
  if (error instanceof CliUsageError) {
444
519
  return { code: "invalid_arguments", message: error.message, hint: error.help.usage }
445
520
  }
446
- if (error instanceof SixbApiError) {
521
+ if (isApiError(error)) {
447
522
  return {
448
523
  code: "api_error",
449
524
  ...(error.status === undefined ? {} : { status: error.status }),
@@ -456,6 +531,21 @@ function cliErrorBody(error: unknown): {
456
531
  }
457
532
  }
458
533
 
534
+ /**
535
+ * The CLI's own API error, or the one `@sixb/client` throws on `throwOnError`: another class, known
536
+ * by its shape. The client is not imported here, so a command that never calls the API never loads it.
537
+ */
538
+ function isApiError(
539
+ error: unknown
540
+ ): error is { readonly status?: number; readonly message: string } {
541
+ if (error instanceof SixbApiError) return true
542
+ return (
543
+ error instanceof Error &&
544
+ error.name === "SixbApiError" &&
545
+ typeof (error as { status?: unknown }).status === "number"
546
+ )
547
+ }
548
+
459
549
  function assertNever(value: never): never {
460
550
  throw new Error(`[SixbCLI] Command '${String(value)}' has no handler.`)
461
551
  }