@sixb/cli 0.2.4 → 0.2.6

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 (63) hide show
  1. package/README.md +2 -0
  2. package/dist/commands/agent.d.ts.map +1 -1
  3. package/dist/commands/api.d.ts.map +1 -1
  4. package/dist/commands/app.d.ts.map +1 -1
  5. package/dist/commands/db-migrate.d.ts +2 -0
  6. package/dist/commands/db-migrate.d.ts.map +1 -1
  7. package/dist/commands/dev-runner.d.ts.map +1 -1
  8. package/dist/commands/run.d.ts +15 -0
  9. package/dist/commands/run.d.ts.map +1 -0
  10. package/dist/commands/worker-group.d.ts.map +1 -1
  11. package/dist/commands/worker.d.ts.map +1 -1
  12. package/dist/lib/command-line.d.ts +12 -2
  13. package/dist/lib/command-line.d.ts.map +1 -1
  14. package/dist/lib/deploy-source.d.ts +2 -0
  15. package/dist/lib/deploy-source.d.ts.map +1 -1
  16. package/dist/lib/role-lifecycle.d.ts +8 -1
  17. package/dist/lib/role-lifecycle.d.ts.map +1 -1
  18. package/dist/lib/runtime.d.ts +4 -2
  19. package/dist/lib/runtime.d.ts.map +1 -1
  20. package/dist/lib/storage-migration.d.ts +7 -0
  21. package/dist/lib/storage-migration.d.ts.map +1 -1
  22. package/dist/lib/worker-concurrency.d.ts.map +1 -1
  23. package/dist/lib/worker-registry.d.ts +4 -1
  24. package/dist/lib/worker-registry.d.ts.map +1 -1
  25. package/dist/runner/computer-connection.d.ts.map +1 -1
  26. package/dist/tui/app.d.ts +2 -0
  27. package/dist/tui/app.d.ts.map +1 -1
  28. package/dist/tui/format.d.ts +7 -2
  29. package/dist/tui/format.d.ts.map +1 -1
  30. package/dist/tui/moves.d.ts +62 -0
  31. package/dist/tui/moves.d.ts.map +1 -0
  32. package/dist/tui/parts.d.ts.map +1 -1
  33. package/dist/tui/settings.d.ts +2 -0
  34. package/dist/tui/settings.d.ts.map +1 -1
  35. package/dist/tui/transcript.d.ts +13 -6
  36. package/dist/tui/transcript.d.ts.map +1 -1
  37. package/dist/ui/screens.d.ts +8 -0
  38. package/dist/ui/screens.d.ts.map +1 -1
  39. package/package.json +22 -21
  40. package/src/commands/agent.ts +17 -5
  41. package/src/commands/api.ts +20 -10
  42. package/src/commands/app.ts +15 -7
  43. package/src/commands/db-migrate.ts +25 -1
  44. package/src/commands/dev-runner.ts +2 -1
  45. package/src/commands/run.ts +221 -0
  46. package/src/commands/worker-group.ts +36 -9
  47. package/src/commands/worker.ts +27 -9
  48. package/src/index.tsx +15 -1
  49. package/src/lib/command-line.ts +41 -5
  50. package/src/lib/deploy-source.ts +5 -0
  51. package/src/lib/role-lifecycle.ts +48 -8
  52. package/src/lib/runtime.ts +19 -3
  53. package/src/lib/storage-migration.ts +33 -1
  54. package/src/lib/worker-concurrency.ts +1 -0
  55. package/src/lib/worker-registry.ts +35 -5
  56. package/src/runner/computer-connection.ts +7 -1
  57. package/src/tui/app.tsx +191 -43
  58. package/src/tui/format.ts +132 -7
  59. package/src/tui/moves.ts +221 -0
  60. package/src/tui/parts.ts +7 -0
  61. package/src/tui/settings.ts +5 -0
  62. package/src/tui/transcript.tsx +54 -15
  63. package/src/ui/screens.ts +23 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sixb/cli",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Command-line interface for Sixb projects",
5
5
  "keywords": [
6
6
  "sixb",
@@ -31,31 +31,32 @@
31
31
  "dependencies": {
32
32
  "@opentui/core": "0.6.6",
33
33
  "@opentui/react": "0.6.6",
34
- "@sixb/agent": "0.2.4",
35
- "@sixb/agent-worker": "0.2.4",
36
- "@sixb/app": "^0.2.4",
37
- "@sixb/client": "^0.2.3",
38
- "@sixb/core": "0.2.4",
39
- "@sixb/cli-core": "^0.2.3",
40
- "@sixb/lake-worker": "0.2.4",
41
- "@sixb/orchestrator": "0.2.4",
42
- "@sixb/pipeline-worker": "0.2.4",
43
- "@sixb/projection-worker": "0.2.4",
44
- "@sixb/rules-worker": "0.2.4",
34
+ "@sixb/agent": "0.2.6",
35
+ "@sixb/agent-worker": "0.2.6",
36
+ "@sixb/app": "^0.2.6",
37
+ "@sixb/client": "^0.2.6",
38
+ "@sixb/core": "0.2.6",
39
+ "@sixb/cli-core": "^0.2.4",
40
+ "@sixb/lake-worker": "0.2.6",
41
+ "@sixb/orchestrator": "0.2.6",
42
+ "@sixb/pipeline-worker": "0.2.6",
43
+ "@sixb/projection-worker": "0.2.6",
44
+ "@sixb/render-worker": "0.2.6",
45
+ "@sixb/rules-worker": "0.2.6",
45
46
  "@sixb/sandboxes-local": "^0.2.0",
46
- "@sixb/server": "0.2.4",
47
- "@sixb/sync-worker": "0.2.4",
48
- "@sixb/workflow-worker": "0.2.4",
49
- "create-sixb": "^0.2.0",
47
+ "@sixb/server": "0.2.6",
48
+ "@sixb/sync-worker": "0.2.6",
49
+ "@sixb/workflow-worker": "0.2.6",
50
+ "create-sixb": "^0.2.1",
50
51
  "react": "^19.2.0"
51
52
  },
52
53
  "devDependencies": {
53
- "@sixb/deploy-ssh": "0.2.0",
54
+ "@sixb/deploy-ssh": "0.2.6",
54
55
  "@sixb/desktop": "0.2.1",
55
- "@sixb/ducklake": "0.2.4",
56
- "@sixb/pg": "0.2.4",
57
- "@sixb/queues-bullmq": "0.2.3",
58
- "@sixb/sqlite": "0.2.4",
56
+ "@sixb/ducklake": "0.2.5",
57
+ "@sixb/pg": "0.2.6",
58
+ "@sixb/queues-bullmq": "0.2.5",
59
+ "@sixb/sqlite": "0.2.6",
59
60
  "@types/bun": "latest",
60
61
  "@types/react": "^19.0.0",
61
62
  "typescript": "^5.7.0"
@@ -92,7 +92,7 @@ export async function runAgent(options: {
92
92
  const place = thread.computer
93
93
  if (onComputer && !place) {
94
94
  throw new Error(
95
- "[SixbCLI] This conversation has no folder yet: open it with sixb in its folder, and press ctrl+f."
95
+ "[SixbCLI] This conversation has no folder yet: open it with sixb in its folder, and press ctrl+g twice."
96
96
  )
97
97
  }
98
98
  const here = onComputer && place?.id === (await thisComputerId()) && place.folder === folder
@@ -127,6 +127,9 @@ export async function runAgent(options: {
127
127
  },
128
128
  throwOnError: true,
129
129
  })
130
+ if (!posted.run) {
131
+ throw new Error("[SixbCli] A sent message started no turn: the thread already had one.")
132
+ }
130
133
  let runId: string | null = posted.run.id
131
134
  if (options.detach) {
132
135
  if (onComputer && !thread.computer?.online) step(tone.faint(waitingNote(thread.computer)))
@@ -142,7 +145,14 @@ export async function runAgent(options: {
142
145
  stop.signal.addEventListener("abort", stopWatching, { once: true })
143
146
  const nobody =
144
147
  onComputer && runnerUntilHeld(connection, thread.id, runId, runner, watching.signal)
145
- followed = await follow(connection, runId, options.json, stop.signal, nobody || undefined)
148
+ followed = await follow(
149
+ connection,
150
+ runId,
151
+ options.json,
152
+ stop.signal,
153
+ nobody || undefined,
154
+ onComputer ? place?.folder : undefined
155
+ )
146
156
  stopWatching()
147
157
  stop.signal.removeEventListener("abort", stopWatching)
148
158
  if (followed === "offline") {
@@ -236,14 +246,16 @@ function printSent(threadId: string, runId: string, json: boolean): void {
236
246
 
237
247
  /**
238
248
  * Show a turn's steps as they finish, until it ends, the stream fails, the person stops waiting,
239
- * or `nobody` says nothing will run it. Rejects when `nobody` does.
249
+ * or `nobody` says nothing will run it. Rejects when `nobody` does. `folder` is the one a
250
+ * computer's turns work in.
240
251
  */
241
252
  async function follow(
242
253
  connection: Connection,
243
254
  runId: string,
244
255
  json: boolean,
245
256
  signal: AbortSignal,
246
- nobody?: Promise<"unclaimed" | "offline" | null>
257
+ nobody?: Promise<"unclaimed" | "offline" | null>,
258
+ folder?: string
247
259
  ): Promise<"finished" | "stopped" | "failed" | "unclaimed" | "offline"> {
248
260
  let live = liveRun(runId)
249
261
  const shown = new Set<string>()
@@ -276,7 +288,7 @@ async function follow(
276
288
  for (const part of live.parts) {
277
289
  if (part.kind !== "tool" || part.state === "running" || shown.has(part.id)) continue
278
290
  shown.add(part.id)
279
- const line = toolLine(part)
291
+ const line = toolLine(part, undefined, folder)
280
292
  const mark = line.held
281
293
  ? tone.warn(glyph.live)
282
294
  : line.failed || part.state === "error"
@@ -1,10 +1,11 @@
1
1
  import { stat } from "node:fs/promises"
2
2
  import { resolve } from "node:path"
3
+ import { ACTION_RUN_DRAIN_TIMEOUT_MS } from "@sixb/core/internal/actions"
3
4
  import { createSixbServer, requestTimingOptionsFromEnv, type SixbServer } from "@sixb/server"
4
5
  import { apiDocsUrl, apiEventsUrl, apiUrl, resolveBrowserTopology } from "../lib/browser-topology"
5
6
  import type { LoadedSixbHost } from "../lib/loadSixb"
6
7
  import { builtAppOutdir, loadProductionSixb } from "../lib/production"
7
- import { runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
8
+ import { resolveDrainTimeoutMs, runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
8
9
  import { stopSixbProviders } from "../lib/runtime"
9
10
  import { migrateStorageForRole } from "../lib/storage-migration"
10
11
  import { printStopping, renderCliError, renderStatic, roleView, startTask } from "../ui"
@@ -95,18 +96,27 @@ export async function runApi(options: ApiOptions = {}) {
95
96
  })
96
97
  )
97
98
 
98
- await runUntilSignal(async () => {
99
- app.stop()
100
- printStopping("api")
101
- await stopQuietly(() => server?.stop() ?? Promise.resolve())
102
- if (sixb) {
103
- await stopSixbProviders(sixb)
99
+ await runUntilSignal(
100
+ async (signal) => {
101
+ app.stop()
102
+ printStopping("api")
103
+ const timeoutMs =
104
+ signal === "SIGTERM" ? resolveDrainTimeoutMs(ACTION_RUN_DRAIN_TIMEOUT_MS) : 0
105
+ await stopQuietly(() => server?.stop({ timeoutMs }) ?? Promise.resolve())
106
+ if (sixb) {
107
+ await stopSixbProviders(sixb)
108
+ }
109
+ sixb = null
110
+ },
111
+ {
112
+ onInterrupt: () => {
113
+ void stopQuietly(() => server?.stop({ timeoutMs: 0 }) ?? Promise.resolve())
114
+ },
104
115
  }
105
- sixb = null
106
- })
116
+ )
107
117
  } catch (error) {
108
118
  app.stop()
109
- await stopQuietly(() => server?.stop() ?? Promise.resolve())
119
+ await stopQuietly(() => server?.stop({ timeoutMs: 0 }) ?? Promise.resolve())
110
120
  if (sixb) {
111
121
  await stopSixbProviders(sixb)
112
122
  }
@@ -7,7 +7,7 @@ import {
7
7
  resolveProductionPaths,
8
8
  resolveRuntimeEntry,
9
9
  } from "../lib/production"
10
- import { runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
10
+ import { resolveDrainTimeoutMs, runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
11
11
  import { printStopping, renderCliError, renderStatic, roleView, startTask } from "../ui"
12
12
 
13
13
  export interface AppOptions {
@@ -65,14 +65,22 @@ export async function runApp(options: AppOptions = {}) {
65
65
  })
66
66
  )
67
67
 
68
- await runUntilSignal(async () => {
69
- app.stop()
70
- printStopping("app")
71
- await stopQuietly(() => customAppServer?.stop() ?? Promise.resolve())
72
- })
68
+ await runUntilSignal(
69
+ async (signal) => {
70
+ app.stop()
71
+ printStopping("app")
72
+ const timeoutMs = signal === "SIGTERM" ? resolveDrainTimeoutMs(5_000) : 0
73
+ await stopQuietly(() => customAppServer?.stop({ timeoutMs }) ?? Promise.resolve())
74
+ },
75
+ {
76
+ onInterrupt: () => {
77
+ void stopQuietly(() => customAppServer?.stop({ timeoutMs: 0 }) ?? Promise.resolve())
78
+ },
79
+ }
80
+ )
73
81
  } catch (error) {
74
82
  app.stop()
75
- await stopQuietly(() => customAppServer?.stop() ?? Promise.resolve())
83
+ await stopQuietly(() => customAppServer?.stop({ timeoutMs: 0 }) ?? Promise.resolve())
76
84
  await renderCliError(error)
77
85
  process.exit(1)
78
86
  }
@@ -2,16 +2,40 @@ import { migrateStorage } from "@sixb/core"
2
2
  import { loadSixbFromEntry } from "../lib/loadSixb"
3
3
  import { resolveRuntimeEntry } from "../lib/production"
4
4
  import { stopSixbProviders } from "../lib/runtime"
5
- import { dbMigrateView, renderStatic, withTask } from "../ui"
5
+ import { findPendingMigrations } from "../lib/storage-migration"
6
+ import { dbMigrateCheckView, dbMigrateView, renderStatic, withTask } from "../ui"
7
+
8
+ /**
9
+ * `--check` exits with this code when `sixb db migrate` would change the schema. Not 2, which
10
+ * every command uses for a usage error, such as an option an older `sixb` does not know.
11
+ */
12
+ const MIGRATIONS_PENDING_EXIT_CODE = 3
6
13
 
7
14
  export interface DbMigrateOptions {
8
15
  entry?: string
16
+ /** Only report whether migrations are pending, without running them. */
17
+ check?: boolean
9
18
  }
10
19
 
11
20
  export async function runDbMigrate(options: DbMigrateOptions = {}) {
12
21
  const entry = await resolveRuntimeEntry({ entry: options.entry })
13
22
  const sixb = await withTask("db migrate", "Loading project", () => loadSixbFromEntry(entry))
14
23
 
24
+ if (options.check) {
25
+ try {
26
+ const pending = await withTask("db migrate", "Reading the storage schema", () =>
27
+ findPendingMigrations(sixb.storage)
28
+ )
29
+ await renderStatic(dbMigrateCheckView({ projectId: sixb.id, pending }))
30
+
31
+ // A deploy reads the code: the release it is about to start needs the services stopped.
32
+ if (pending.length > 0) process.exitCode = MIGRATIONS_PENDING_EXIT_CODE
33
+ } finally {
34
+ await stopSixbProviders(sixb)
35
+ }
36
+ return
37
+ }
38
+
15
39
  try {
16
40
  const result = await withTask("db migrate", "Migrating storage", () =>
17
41
  migrateStorage(sixb.storage, {
@@ -134,7 +134,7 @@ export async function runDevRuntime(options: DevOptions = {}) {
134
134
  step("Starting server")
135
135
  return server.start()
136
136
  },
137
- stop: () => server.stop(),
137
+ stop: () => server.stop({ timeoutMs: 0 }),
138
138
  },
139
139
  agentApiBaseUrl: topology.apiPublicOrigin,
140
140
  workerConcurrency,
@@ -161,6 +161,7 @@ export async function runDevRuntime(options: DevOptions = {}) {
161
161
  { type: "workflow", worker: runtime.workflowWorker },
162
162
  { type: "sync", worker: runtime.syncWorker },
163
163
  { type: "lake", worker: runtime.lakeWorker },
164
+ { type: "render", worker: runtime.renderWorker },
164
165
  ].flatMap(({ type, worker }) => (worker ? [{ type, concurrency: worker.concurrency }] : [])),
165
166
  warnings: devApp.warning ? [devApp.warning, ...runtime.warnings] : runtime.warnings,
166
167
  }
@@ -0,0 +1,221 @@
1
+ import { readFile, stat } from "node:fs/promises"
2
+ import { isAbsolute, relative, resolve, sep } from "node:path"
3
+ import { createInterface } from "node:readline/promises"
4
+ import { pathToFileURL } from "node:url"
5
+ import { checkStorageSchema } from "@sixb/core"
6
+ import { listProjectModules } from "@sixb/core/internal/bootstrap"
7
+ import { bindScript } from "@sixb/core/internal/runtime"
8
+ import { loadDeployConfig } from "../lib/deploy-config"
9
+ import { headCommit } from "../lib/deploy-source"
10
+ import { SixbCliError } from "../lib/errors"
11
+ import { loadSixbFromEntry } from "../lib/loadSixb"
12
+ import { stopSixbProviders } from "../lib/runtime"
13
+ import { withTask } from "../ui"
14
+ import { glyph, tone } from "../ui/theme"
15
+
16
+ export interface RunScriptOptions {
17
+ readonly script: string
18
+ /** Everything after the script's path, passed to it untouched. */
19
+ readonly args: readonly string[]
20
+ readonly entry?: string
21
+ readonly deployed?: boolean
22
+ readonly yes?: boolean
23
+ readonly cwd?: string
24
+ }
25
+
26
+ /**
27
+ * `sixb run`: calls a script's default export with the project's SDK, here or, with `deployed`, on
28
+ * the deployment. Resolves with the exit code the command should end with.
29
+ */
30
+ export async function runScriptCommand(options: RunScriptOptions): Promise<number> {
31
+ const cwd = options.cwd ?? process.cwd()
32
+ if (options.deployed && options.entry) {
33
+ throw new SixbCliError("[SixbRun] --entry applies to a run here, not to a deployed one.", {
34
+ remediation: "The deployment runs with the configuration it was deployed with.",
35
+ })
36
+ }
37
+ const script = await projectScript(cwd, options.script)
38
+ return options.deployed ? runOnDeployment(cwd, script, options) : runHere(cwd, script, options)
39
+ }
40
+
41
+ interface ProjectScript {
42
+ readonly file: string
43
+ /** Relative to the project, with forward slashes: what the execution records. */
44
+ readonly path: string
45
+ }
46
+
47
+ async function projectScript(cwd: string, script: string): Promise<ProjectScript> {
48
+ const file = resolve(cwd, script)
49
+ const entry = await stat(file).catch(() => null)
50
+ if (!entry?.isFile()) throw new SixbCliError(`[SixbRun] No script at ${script}.`)
51
+
52
+ const path = relative(cwd, file)
53
+ if (path.startsWith("..") || isAbsolute(path)) {
54
+ throw new SixbCliError(`[SixbRun] ${script} is outside the project.`, {
55
+ remediation:
56
+ "Move it into the project, such as into scripts/, and run sixb run from the project's directory.",
57
+ })
58
+ }
59
+ const projectPath = path.split(sep).join("/")
60
+ // Sixb imports every module in these folders as a definition, and a script is not one.
61
+ const modules = await listProjectModules(cwd)
62
+ if (modules.some((module) => module.path.split(sep).join("/") === projectPath)) {
63
+ throw new SixbCliError(`[SixbRun] ${projectPath} is in a folder Sixb loads definitions from.`, {
64
+ remediation: "Move it outside the definition folders, such as into scripts/.",
65
+ })
66
+ }
67
+ return { file, path: projectPath }
68
+ }
69
+
70
+ async function runHere(
71
+ cwd: string,
72
+ script: ProjectScript,
73
+ options: RunScriptOptions
74
+ ): Promise<number> {
75
+ // The source entry, even where a build exists: the script imports the project's source modules,
76
+ // and loading the same files keeps one copy of each.
77
+ const entry = resolve(cwd, options.entry ?? "sixb.config.ts")
78
+ if (!(await Bun.file(entry).exists())) {
79
+ throw new SixbCliError(`[SixbRun] No ${relative(cwd, entry)} here.`, {
80
+ remediation: "Run sixb run from the project's directory, or pass --entry.",
81
+ })
82
+ }
83
+
84
+ const host = await loadSixbFromEntry(entry)
85
+ const stop = interruptOnSignals()
86
+ try {
87
+ // Before anything can fail: closing the host must not publish the running instance's events.
88
+ const bound = bindScript(host, script.path)
89
+
90
+ // Awaited here, as `sixb check` does: `checkReadiness()` serves a probe that polls, so its first
91
+ // answer only starts this check and reports it in progress.
92
+ const schema = await checkStorageSchema(host.storage)
93
+ if (!schema.ok) {
94
+ throw new SixbCliError(`[SixbRun] ${host.id}'s storage is not usable: ${schema.reason}`)
95
+ }
96
+
97
+ const module = (await import(pathToFileURL(script.file).href)) as { readonly default?: unknown }
98
+ if (typeof module.default !== "function") {
99
+ throw new SixbCliError(`[SixbRun] ${script.path} has no default export to run.`, {
100
+ remediation:
101
+ "Export a function: `export default async function ({ sixb, args, signal }: ScriptContext) { ... }`.",
102
+ })
103
+ }
104
+
105
+ if (stop.signal.aborted) return 130
106
+ say(`${tone.muted(glyph.prompt)} ${tone.strong(script.path)} ${tone.muted(`on ${host.id}`)}`)
107
+ const started = performance.now()
108
+ try {
109
+ await bound.run({ main: module.default, args: options.args, signal: stop.signal })
110
+ } catch (error) {
111
+ // A script that stops by throwing once its signal aborts, as `throwIfAborted()` does, was
112
+ // stopped; any other throw is its own failure, and its stack is what its author needs.
113
+ if (!stop.signal.aborted) {
114
+ console.error(error)
115
+ say(`${tone.fail(glyph.fail)} ${script.path} failed after ${seconds(started)}`)
116
+ return 1
117
+ }
118
+ }
119
+
120
+ if (stop.signal.aborted) {
121
+ say(`${tone.warn(glyph.warn)} ${script.path} stopped after ${seconds(started)}`)
122
+ return 130
123
+ }
124
+ say(`${tone.ok(glyph.ok)} ${script.path} finished in ${seconds(started)}`)
125
+ return 0
126
+ } finally {
127
+ stop.dispose()
128
+ await stopSixbProviders(host)
129
+ }
130
+ }
131
+
132
+ /**
133
+ * The first Ctrl-C or SIGTERM aborts the script's `signal`; a second one exits at once. A hangup,
134
+ * such as a closed SSH connection, exits at once: nobody is left to read the output or press
135
+ * Ctrl-C again. Either way, writes already committed stay committed.
136
+ */
137
+ function interruptOnSignals(): { readonly signal: AbortSignal; dispose(): void } {
138
+ const controller = new AbortController()
139
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const
140
+ const onSignal = (signal: (typeof signals)[number]) => {
141
+ if (signal === "SIGHUP") process.exit(129)
142
+ if (controller.signal.aborted) process.exit(130)
143
+ say(tone.muted("Stopping the script. Press Ctrl-C again to exit at once."))
144
+ controller.abort(new Error(`[SixbRun] Stopped by ${signal}.`))
145
+ }
146
+ for (const signal of signals) process.on(signal, onSignal)
147
+ return {
148
+ signal: controller.signal,
149
+ dispose: () => {
150
+ for (const signal of signals) process.off(signal, onSignal)
151
+ },
152
+ }
153
+ }
154
+
155
+ async function runOnDeployment(
156
+ cwd: string,
157
+ script: ProjectScript,
158
+ options: RunScriptOptions
159
+ ): Promise<number> {
160
+ const { config } = await loadDeployConfig(cwd)
161
+ const { target } = config
162
+ if (!target.run) {
163
+ throw new SixbCliError(`[SixbRun] A ${target.kind} deployment cannot run scripts.`)
164
+ }
165
+
166
+ const status = await withTask("run", `Asking ${target.location}`, () =>
167
+ target.status({ name: config.name })
168
+ )
169
+ if (!status.release) {
170
+ throw new SixbCliError(
171
+ `[SixbRun] Nothing named ${config.name} is deployed on ${target.location} yet.`,
172
+ { remediation: "Deploy it first: sixb deploy." }
173
+ )
174
+ }
175
+
176
+ const deployed = status.release.commit
177
+ const head = await headCommit(cwd)
178
+ const question =
179
+ `Run ${tone.strong(script.path)} on ${tone.strong(config.name)} ${tone.muted(`(${target.kind} ${target.location})`)}?\n` +
180
+ tone.muted(
181
+ ` Its imports resolve against the deployed ${deployed.slice(0, 12)}` +
182
+ (head && head !== deployed ? `; your HEAD is ${head.slice(0, 12)}.` : ".")
183
+ )
184
+ if (!(await confirm(question, options.yes === true))) {
185
+ say(tone.muted("Not run."))
186
+ return 1
187
+ }
188
+
189
+ return target.run(
190
+ {
191
+ path: script.path,
192
+ source: new Uint8Array(await readFile(script.file)),
193
+ args: options.args,
194
+ },
195
+ { name: config.name }
196
+ )
197
+ }
198
+
199
+ /** Asks before a deployed run. Without a terminal there is nobody to ask, so only `--yes` proceeds. */
200
+ async function confirm(question: string, yes: boolean): Promise<boolean> {
201
+ if (yes) return true
202
+ if (!process.stdin.isTTY) {
203
+ throw new SixbCliError("[SixbRun] Running on the deployment needs a yes.", {
204
+ remediation: "Pass --yes to run without being asked.",
205
+ })
206
+ }
207
+
208
+ say(question)
209
+ const prompt = createInterface({ input: process.stdin, output: process.stderr })
210
+ const answer = await prompt.question("Run it? [y/N] ").finally(() => prompt.close())
211
+ return answer.trim().toLowerCase() === "y"
212
+ }
213
+
214
+ /** On standard error, so a script run here has standard output to itself. */
215
+ function say(line: string): void {
216
+ process.stderr.write(`${line}\n`)
217
+ }
218
+
219
+ function seconds(started: number): string {
220
+ return `${((performance.now() - started) / 1000).toFixed(1)}s`
221
+ }
@@ -1,6 +1,10 @@
1
1
  import { type LoadedSixbHost, loadSixbFromEntry } from "../lib/loadSixb"
2
2
  import { resolveRuntimeEntry } from "../lib/production"
3
- import { runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
3
+ import { resolveDrainTimeoutMs, runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
4
+
5
+ // Leaves 10 s inside the default 70 s kill timeout for abort finalization and provider shutdown.
6
+ const DEFAULT_WORKER_DRAIN_TIMEOUT_MS = 60_000
7
+
4
8
  import { recordApiPublicOrigin, stopSixbProviders, waitForWorkerFailure } from "../lib/runtime"
5
9
  import { assertShareableProviders } from "../lib/shareable-providers"
6
10
  import { migrateStorageForRole } from "../lib/storage-migration"
@@ -57,8 +61,18 @@ export async function runWorkerGroup(options: WorkerGroupOptions = {}) {
57
61
  let sixb: LoadedSixbHost | null = null
58
62
  let workers: QueueWorkerProcess[] = []
59
63
 
60
- async function stopWorkersAndProviders() {
61
- await Promise.all(workers.map((worker) => stopQuietly(() => worker.stop())))
64
+ async function stopWorkersAndProviders(drainTimeoutMs?: number) {
65
+ await Promise.all(
66
+ workers.map((worker) =>
67
+ stopQuietly(async () => {
68
+ if (drainTimeoutMs !== undefined) {
69
+ await worker.drain(drainTimeoutMs)
70
+ } else {
71
+ await worker.stop()
72
+ }
73
+ })
74
+ )
75
+ )
62
76
  if (sixb) {
63
77
  await stopSixbProviders(sixb)
64
78
  }
@@ -127,12 +141,25 @@ export async function runWorkerGroup(options: WorkerGroupOptions = {}) {
127
141
  )
128
142
 
129
143
  await Promise.race([
130
- runUntilSignal(async () => {
131
- app.stop()
132
- printStopping("worker-group")
133
- await stopWorkersAndProviders()
134
- sixb = null
135
- }),
144
+ runUntilSignal(
145
+ async (signal) => {
146
+ app.stop()
147
+ printStopping("worker-group")
148
+ const drainTimeoutMs =
149
+ signal === "SIGTERM"
150
+ ? resolveDrainTimeoutMs(DEFAULT_WORKER_DRAIN_TIMEOUT_MS)
151
+ : undefined
152
+ await stopWorkersAndProviders(drainTimeoutMs)
153
+ sixb = null
154
+ },
155
+ {
156
+ onInterrupt: () => {
157
+ for (const worker of workers) {
158
+ void stopQuietly(() => worker.stop())
159
+ }
160
+ },
161
+ }
162
+ ),
136
163
  ...workers.map(waitForWorkerFailure),
137
164
  ])
138
165
  } catch (error) {
@@ -1,7 +1,11 @@
1
1
  import { SixbCliError } from "../lib/errors"
2
2
  import { type LoadedSixbHost, loadSixbFromEntry } from "../lib/loadSixb"
3
3
  import { resolveRuntimeEntry } from "../lib/production"
4
- import { runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
4
+ import { resolveDrainTimeoutMs, runUntilSignal, stopQuietly } from "../lib/role-lifecycle"
5
+
6
+ // Leaves 10 s inside the default 70 s kill timeout for abort finalization and provider shutdown.
7
+ const DEFAULT_WORKER_DRAIN_TIMEOUT_MS = 60_000
8
+
5
9
  import { recordApiPublicOrigin, stopSixbProviders, waitForWorkerFailure } from "../lib/runtime"
6
10
  import { assertShareableProviders } from "../lib/shareable-providers"
7
11
  import { migrateStorageForRole } from "../lib/storage-migration"
@@ -97,15 +101,29 @@ export async function runWorker(options: WorkerOptions = {}) {
97
101
  )
98
102
 
99
103
  await Promise.race([
100
- runUntilSignal(async () => {
101
- app.stop()
102
- printStopping("worker")
103
- await stopQuietly(() => worker?.stop() ?? Promise.resolve())
104
- if (sixb) {
105
- await stopSixbProviders(sixb)
104
+ runUntilSignal(
105
+ async (signal) => {
106
+ app.stop()
107
+ printStopping("worker")
108
+ if (signal === "SIGTERM") {
109
+ const timeoutMs = resolveDrainTimeoutMs(DEFAULT_WORKER_DRAIN_TIMEOUT_MS)
110
+ await stopQuietly(async () => {
111
+ await worker?.drain(timeoutMs)
112
+ })
113
+ } else {
114
+ await stopQuietly(() => worker?.stop() ?? Promise.resolve())
115
+ }
116
+ if (sixb) {
117
+ await stopSixbProviders(sixb)
118
+ }
119
+ sixb = null
120
+ },
121
+ {
122
+ onInterrupt: () => {
123
+ void stopQuietly(() => worker?.stop() ?? Promise.resolve())
124
+ },
106
125
  }
107
- sixb = null
108
- }),
126
+ ),
109
127
  waitForWorkerFailure(worker),
110
128
  ])
111
129
  } catch (error) {
package/src/index.tsx CHANGED
@@ -358,6 +358,20 @@ async function main(): Promise<void> {
358
358
  break
359
359
  }
360
360
 
361
+ case "run": {
362
+ const { runScriptCommand } = await import("./commands/run")
363
+ const [script = "", ...scriptArgs] = positionals
364
+ const exitCode = await runScriptCommand({
365
+ script,
366
+ args: scriptArgs,
367
+ entry: getFlag("entry"),
368
+ deployed: hasFlag("deployed"),
369
+ yes: hasFlag("yes"),
370
+ })
371
+ // Whatever the script left running, such as a timer or a socket, must not keep it alive.
372
+ return process.exit(exitCode)
373
+ }
374
+
361
375
  case "db:prepare": {
362
376
  const { runDbPrepare } = await import("./commands/db-prepare")
363
377
  await runDbPrepare({ entry: getFlag("entry") })
@@ -366,7 +380,7 @@ async function main(): Promise<void> {
366
380
 
367
381
  case "db:migrate": {
368
382
  const { runDbMigrate } = await import("./commands/db-migrate")
369
- await runDbMigrate({ entry: getFlag("entry") })
383
+ await runDbMigrate({ entry: getFlag("entry"), check: hasFlag("check") })
370
384
  break
371
385
  }
372
386