@spunto/build 0.25.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spunto/build",
3
- "version": "0.25.0",
3
+ "version": "0.27.0",
4
4
  "description": "Spunto's shared Build engine — the devcontainer image protocol and VS Code extension registry clients, with no database, no HTTP framework and no UI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -113,6 +113,21 @@ export const FEATURE_ENTRYPOINTS_FILE = "/etc/mp-feature-entrypoints"
113
113
  */
114
114
  export const FEATURE_ENTRYPOINTS_STAGING_FILE = "/tmp/mp-feature-entrypoints"
115
115
 
116
+ /**
117
+ * The lifecycle commands features declare (devcontainer spec: `onCreateCommand`,
118
+ * `postCreateCommand`, `postStartCommand` in a devcontainer-feature.json), one file per hook named
119
+ * after it, one command per line in install order. The image build writes them; the setup runs
120
+ * them before the project's own (`postCreateCommand` once, `postStartCommand` at every start) — how
121
+ * docker-in-docker waits for its daemon without the setup knowing anything about Docker.
122
+ */
123
+ export const FEATURE_HOOKS_DIR = "/etc/mp-feature-hooks"
124
+
125
+ /** Where the hooks of each feature are accumulated during the build, like the entrypoints. */
126
+ export const FEATURE_HOOKS_STAGING_DIR = "/tmp/mp-feature-hooks"
127
+
128
+ /** The feature lifecycle hooks the setup runs, in the order the spec runs them. */
129
+ export const FEATURE_HOOKS = ["onCreateCommand", "postCreateCommand", "postStartCommand"] as const
130
+
116
131
  /**
117
132
  * Extensions the image build could not install, one id per line. Left in the image so a worker can
118
133
  * tell what is missing without anyone re-reading the build log — see `EXTENSION_FAILED_MARKER` in
@@ -4,6 +4,9 @@ import {
4
4
  EXTENSIONS_DIR,
5
5
  FEATURE_ENTRYPOINTS_FILE,
6
6
  FEATURE_ENTRYPOINTS_STAGING_FILE,
7
+ FEATURE_HOOKS,
8
+ FEATURE_HOOKS_DIR,
9
+ FEATURE_HOOKS_STAGING_DIR,
7
10
  workerStatusPath,
8
11
  } from "../naming/index"
9
12
  import { stepEndLine, stepStartLine, type BuildStep, type BuildStepKind } from "../steps/build-steps"
@@ -380,6 +383,28 @@ function mkStatus(
380
383
  return JSON.stringify({ phase, repos, postCreate, postStart } satisfies SetupStatus)
381
384
  }
382
385
 
386
+ /**
387
+ * Run the lifecycle commands the features declared for `hook` (FEATURE_HOOKS_DIR, written by the
388
+ * image build), in install order, as the user, from /workspace — before the project's own. One that
389
+ * fails is said and the next runs: a feature's hook is a courtesy (docker-in-docker waiting for its
390
+ * daemon), not the project's command, and a box set up without it is better than no box.
391
+ * stdin from /dev/null: `su` would otherwise read the rest of the list as its input.
392
+ */
393
+ function featureHookLines(hook: (typeof FEATURE_HOOKS)[number], username: string): string[] {
394
+ const file = `${FEATURE_HOOKS_DIR}/${hook}`
395
+ return [
396
+ "",
397
+ `if [ -s ${file} ]; then`,
398
+ ` echo "--- Running the features' ${hook} ---"`,
399
+ " while IFS= read -r _hc; do",
400
+ ' [ -n "$_hc" ] || continue',
401
+ ' echo "Running: $_hc"',
402
+ ` su ${username} -c "cd /workspace && $_hc" < /dev/null 2>&1 || echo " (exited $?, continuing)"`,
403
+ ` done < ${file}`,
404
+ "fi",
405
+ ]
406
+ }
407
+
383
408
  function banner(title: string): string[] {
384
409
  return [
385
410
  "",
@@ -431,6 +456,17 @@ function buildFeatureInstallScript(ociRef: string, options?: Record<string, stri
431
456
  ` echo "$_EP" >> ${FEATURE_ENTRYPOINTS_STAGING_FILE}`,
432
457
  ` echo "[feature] ${featureId}: registered entrypoint $_EP"`,
433
458
  ` fi`,
459
+ // Its lifecycle hooks, in their string form — the array and object forms are said and skipped
460
+ // (read with grep, like the entrypoint: no JSON tool is guaranteed in the image being built).
461
+ ` for _h in ${FEATURE_HOOKS.join(" ")}; do`,
462
+ ` _HC=$(grep -o "\\"$_h\\"[[:space:]]*:[[:space:]]*\\"[^\\"]*\\"" "$_FEAT_DIR/devcontainer-feature.json" | head -1 | cut -d'"' -f4)`,
463
+ ` if [ -n "$_HC" ]; then`,
464
+ ` mkdir -p ${FEATURE_HOOKS_STAGING_DIR} && echo "$_HC" >> "${FEATURE_HOOKS_STAGING_DIR}/$_h"`,
465
+ ` echo "[feature] ${featureId}: registered $_h $_HC"`,
466
+ ` elif grep -q "\\"$_h\\"[[:space:]]*:[[:space:]]*[[{]" "$_FEAT_DIR/devcontainer-feature.json"; then`,
467
+ ` echo "[feature] ${featureId}: $_h ignored — only its string form is run"`,
468
+ ` fi`,
469
+ ` done`,
434
470
  `fi`,
435
471
  `cd /`,
436
472
  `rm -rf "$_FEAT_DIR"`,
@@ -447,6 +483,15 @@ function buildFeatureInstallScript(ociRef: string, options?: Record<string, stri
447
483
  function buildLocalFeatureInstallScript(featureId: string, scriptFile: string): string | null {
448
484
  const scriptContent = localFeatureScript(scriptFile)
449
485
  if (!scriptContent) return null
486
+ return buildInlineFeatureInstallScript(featureId, scriptContent)
487
+ }
488
+
489
+ /**
490
+ * A feature whose install script the caller hands over as text — embedded in the recipe like a
491
+ * local one. What an app that serves its own feature gives (Spunto IDE's `ide.feature`, RFC 0059):
492
+ * no registry in between, and the recipe's text, so its key, moves with the script.
493
+ */
494
+ function buildInlineFeatureInstallScript(featureId: string, scriptContent: string): string {
450
495
  const encoded = b64(scriptContent)
451
496
  return [
452
497
  `echo "[feature] ${featureId}: running local install script..."`,
@@ -468,11 +513,15 @@ function buildLocalFeatureInstallScript(featureId: string, scriptFile: string):
468
513
  export type ResolvedFeature = { id: string; script: string; ociRef?: string }
469
514
 
470
515
  function resolveFeatures(
471
- features: { id: string; ociRef?: string; options?: Record<string, string> }[],
516
+ features: { id: string; ociRef?: string; options?: Record<string, string>; script?: string }[],
472
517
  warnId?: string,
473
518
  ): ResolvedFeature[] {
474
519
  const resolved: ResolvedFeature[] = []
475
520
  for (const f of features) {
521
+ if (f.script) {
522
+ resolved.push({ id: f.id, script: buildInlineFeatureInstallScript(f.id, f.script) })
523
+ continue
524
+ }
476
525
  const known = AVAILABLE_FEATURES.find((af) => af.id === f.id)
477
526
  if (known?.localScript) {
478
527
  const script = buildLocalFeatureInstallScript(f.id, known.localScript)
@@ -555,8 +604,14 @@ function commonUtilsOptions(): Record<string, string> {
555
604
  * Not strict: a base image where tmux won't install must still produce a usable worker, exactly as
556
605
  * the best-effort blocks it replaces did.
557
606
  */
558
- function spuntoPackOptions(params: { sshGatewayPublicKey?: string }): Record<string, string> {
559
- return { installSshd: params.sshGatewayPublicKey ? "true" : "false" }
607
+ function spuntoPackOptions(params: { sshGatewayPublicKey?: string; codeServerInPack?: boolean }): Record<string, string> {
608
+ return {
609
+ installSshd: params.sshGatewayPublicKey ? "true" : "false",
610
+ // A platform that installs the IDE apart (`spunto-ide`, Spunto's IDE app — RFC 0059) keeps the
611
+ // pack to its plumbing: tmux, dtach, sshd. Left out otherwise, so the recipe of a caller that
612
+ // never asks (spunto-lite) stays the same text.
613
+ ...(params.codeServerInPack === false ? { installCodeServer: "false" } : {}),
614
+ }
560
615
  }
561
616
 
562
617
  // The system-wide tmux configuration (mouse, OSC 52 clipboard, 50k scrollback, warm status bar)
@@ -689,21 +744,30 @@ export function defaultVscodeUserSettings(opts?: {
689
744
  * 1 → the hand-written blocks (vscode user, code-server, tmux, dtach, sshd).
690
745
  * 2 → common-utils + spunto-pack.
691
746
  * 3 → spunto-pack 1.1: the IDE wears Spunto's name, icons and themes (coderhammer/features).
747
+ * 4 → the IDE out of the pack (`codeServerInPack: false`): code-server comes from `spunto-ide`,
748
+ * the feature of an IDE app, and only in the image of a project that has one (RFC 0059).
749
+ * 5 → the features' lifecycle hooks are kept in the image (FEATURE_HOOKS_DIR) for the setup to run.
692
750
  */
693
- export const IMAGE_RECIPE_VERSION = 3
751
+ export const IMAGE_RECIPE_VERSION = 5
694
752
 
695
753
  export function buildImageScript(params: {
696
- features: { id: string; ociRef?: string; options?: Record<string, string> }[]
754
+ /** `script`: the feature's install script itself, embedded as is (an app that serves its own). */
755
+ features: { id: string; ociRef?: string; options?: Record<string, string>; script?: string }[]
697
756
  vscodeExtensions?: string[]
698
757
  sshGatewayPublicKey?: string
699
- /** Project-level DinD opt-in (base image bakes Docker itself, no feature). See projects.dind. */
700
- dind?: boolean
701
758
  /**
702
759
  * Org setting (organizations.extensionsGallery): raw code-server gallery blob the
703
760
  * `--install-extension` calls below resolve ids against. Absent/unusable = Open VSX.
704
761
  */
705
762
  extensionsGallery?: string | null
706
- }): { script: string; hasDinD: boolean; resolvedFeatures: ResolvedFeature[]; steps: BuildStep[] } {
763
+ /**
764
+ * Whether spunto-pack installs code-server, as it does by default. `false`: the pack is plumbing
765
+ * only (tmux, dtach, sshd), and code-server comes from a feature of the caller's — Spunto's IDE
766
+ * app puts `spunto-ide` among `features` for a project that has an IDE (RFC 0059). Extensions are
767
+ * then installed only if one of the features brought a code-server.
768
+ */
769
+ codeServerInPack?: boolean
770
+ }): { script: string; resolvedFeatures: ResolvedFeature[]; steps: BuildStep[] } {
707
771
  const lines: string[] = ["set -e"]
708
772
 
709
773
  // Every block of the build declares itself, so the UI can show the whole plan upfront and light
@@ -760,7 +824,6 @@ export function buildImageScript(params: {
760
824
  'command -v curl >/dev/null 2>&1 || echo "[build] WARNING: curl unavailable — feature installs will fail"',
761
825
  ])
762
826
 
763
- const hasDinD = params.features.some((f) => f.id === "docker-in-docker") || !!params.dind
764
827
  // The two features every worker image is made of, ahead of whatever the project picked. The user
765
828
  // can select common-utils in the picker too — its options are then merged over ours rather than
766
829
  // installed a second time.
@@ -785,8 +848,8 @@ export function buildImageScript(params: {
785
848
  }
786
849
 
787
850
  // Save entrypoints to a durable location. Append (not overwrite) + dedup so an entrypoint
788
- // already baked into the base image (e.g. a dockerd starter for projects.dind, see
789
- // images/worker-base) survives alongside any registered by features installed here.
851
+ // already baked into the base image survives alongside any registered by features installed here.
852
+ // The features' lifecycle hooks the same way, in install order (deduplicated, never sorted).
790
853
  const finalizeBody = [
791
854
  "if [ -f " + FEATURE_ENTRYPOINTS_STAGING_FILE + " ]; then",
792
855
  " touch " + FEATURE_ENTRYPOINTS_FILE,
@@ -795,6 +858,15 @@ export function buildImageScript(params: {
795
858
  " rm -f " + FEATURE_ENTRYPOINTS_STAGING_FILE,
796
859
  ' echo "[build] Entrypoints saved to ' + FEATURE_ENTRYPOINTS_FILE + '"',
797
860
  "fi",
861
+ "if [ -d " + FEATURE_HOOKS_STAGING_DIR + " ]; then",
862
+ " mkdir -p " + FEATURE_HOOKS_DIR,
863
+ " for _h in " + FEATURE_HOOKS_STAGING_DIR + "/*; do",
864
+ ' _t="' + FEATURE_HOOKS_DIR + '/$(basename "$_h")"',
865
+ ' cat "$_h" >> "$_t" && awk \'!seen[$0]++\' "$_t" > "$_t.tmp" && mv "$_t.tmp" "$_t"',
866
+ " done",
867
+ " rm -rf " + FEATURE_HOOKS_STAGING_DIR,
868
+ ' echo "[build] Feature lifecycle hooks saved to ' + FEATURE_HOOKS_DIR + '"',
869
+ "fi",
798
870
  ]
799
871
 
800
872
  // Install VS Code extensions to a system path (not in /home, which is per-worker)
@@ -818,6 +890,18 @@ export function buildImageScript(params: {
818
890
  )
819
891
  }
820
892
  extLines.push('echo "[build] Extensions installed"')
893
+ // code-server from a feature of the caller's (`codeServerInPack: false`): said plainly when none
894
+ // brought it, rather than one "command not found" per extension.
895
+ if (params.codeServerInPack === false) {
896
+ extLines.splice(
897
+ 0,
898
+ 0,
899
+ "if ! command -v code-server >/dev/null 2>&1; then",
900
+ ' echo "[build] No code-server in this image (no IDE feature) — VS Code extensions skipped"',
901
+ "else",
902
+ )
903
+ extLines.push("fi")
904
+ }
821
905
  const n = params.vscodeExtensions.length
822
906
  block("extensions", "VS Code extensions", "extensions", `${n} extension${n > 1 ? "s" : ""} · ${registry}`, extLines)
823
907
  }
@@ -841,7 +925,7 @@ export function buildImageScript(params: {
841
925
  'echo "[build] Image build complete"',
842
926
  ])
843
927
 
844
- return { script: lines.join("\n"), hasDinD, resolvedFeatures, steps }
928
+ return { script: lines.join("\n"), resolvedFeatures, steps }
845
929
  }
846
930
 
847
931
  // ─── 2. buildSetupScript ──────────────────────────────────────────────────────
@@ -856,7 +940,6 @@ export type SetupScriptParams = {
856
940
  repositories: { id: string; provider: string; project: string; workspacePath: string; installationId?: number; cloneUrl?: string; branch?: string }[]
857
941
  features: { id: string; ociRef?: string; options?: Record<string, string> }[] | null
858
942
  vscodeExtensions?: string[] | null
859
- dind?: boolean | null
860
943
  postCreateCommand: string | null
861
944
  postStartCommand?: string | null
862
945
  }
@@ -1128,43 +1211,32 @@ export function buildSetupScript(params: SetupScriptParams): { script: string }
1128
1211
  push("", `chown -R ${username}:${username} /workspace`)
1129
1212
  }
1130
1213
 
1131
- // ── 6. postCreateCommand ──────────────────────────────────────────────────
1132
- // Feature entrypoints (e.g. dockerd) are normally started in buildStartScript,
1133
- // but postCreateCommand runs before that. Start them here so commands like
1134
- // `docker run` work during postCreate. Also wait for the Docker socket if
1135
- // docker-in-docker is present.
1136
- // `project.dind` makes DinD available without the docker-in-docker feature (baked into the base
1137
- // image, see images/worker-base) — treat it like the feature for entrypoint start + docker wait.
1138
- const hasDinDFeature = (project.features?.some((f) => f.id === "docker-in-docker") ?? false) || !!project.dind
1214
+ // ── 6. Entrypoints, then the features' create hooks ──────────────────────
1215
+ // Entrypoints are normally started by buildStartScript, but what runs before it — the features'
1216
+ // hooks, the project's postCreate — may need them (dockerd). Started here when the image has any.
1139
1217
  // `_MP_EP_STARTED` tells the every-start block of the same run (buildWorkerScript inlines both in
1140
1218
  // one shell) not to start them a second time: the docker-in-docker feature's entrypoint doesn't
1141
1219
  // check for a running daemon, and a second dockerd fails on the volume store lock — after having
1142
1220
  // replaced the first one's socket, leaving Docker unreachable for postStart and everything after.
1143
- if (project.postCreateCommand && ((project.features && project.features.length > 0) || project.dind)) {
1144
- push(
1145
- "",
1146
- "if [ -f " + FEATURE_ENTRYPOINTS_FILE + " ]; then",
1147
- " _MP_EP_STARTED=1",
1148
- ' echo "--- Starting feature entrypoints for postCreate ---"',
1149
- " while IFS= read -r _ep; do",
1150
- ' if [ -f "$_ep" ]; then',
1151
- ' echo "Starting entrypoint: $_ep"',
1152
- ' "$_ep" &',
1153
- " fi",
1154
- " done < " + FEATURE_ENTRYPOINTS_FILE,
1155
- "fi",
1156
- )
1157
- if (hasDinDFeature) {
1158
- push(
1159
- 'echo "Waiting for Docker daemon..."',
1160
- "for _i in $(seq 1 30); do",
1161
- " docker info >/dev/null 2>&1 && break",
1162
- " sleep 1",
1163
- "done",
1164
- 'docker info >/dev/null 2>&1 && echo "Docker daemon ready" || echo "Docker daemon not ready after 30s, continuing anyway"',
1165
- )
1166
- }
1167
- }
1221
+ // Nothing here knows Docker: docker-in-docker waits for its own daemon in its postCreateCommand.
1222
+ push(
1223
+ "",
1224
+ "if [ -f " + FEATURE_ENTRYPOINTS_FILE + " ]; then",
1225
+ " _MP_EP_STARTED=1",
1226
+ ' echo "--- Starting feature entrypoints ---"',
1227
+ " while IFS= read -r _ep; do",
1228
+ ' if [ -f "$_ep" ]; then',
1229
+ ' echo "Starting entrypoint: $_ep"',
1230
+ ' "$_ep" &',
1231
+ " fi",
1232
+ " done < " + FEATURE_ENTRYPOINTS_FILE,
1233
+ "fi",
1234
+ `if [ ! -f "${homeDir}/.mp-feature-hooks-done" ]; then`,
1235
+ ...featureHookLines("onCreateCommand", username).map((l) => (l ? " " + l : l)),
1236
+ ...featureHookLines("postCreateCommand", username).map((l) => (l ? " " + l : l)),
1237
+ ` touch "${homeDir}/.mp-feature-hooks-done"`,
1238
+ "fi",
1239
+ )
1168
1240
 
1169
1241
  if (project.postCreateCommand) {
1170
1242
  const postCreateDir = project.repositories.length === 1
@@ -1210,7 +1282,6 @@ export type StartScriptParams = {
1210
1282
  name?: string
1211
1283
  features: { id: string; ociRef?: string; options?: Record<string, string> }[] | null
1212
1284
  vscodeExtensions?: string[] | null
1213
- dind?: boolean | null
1214
1285
  postCreateCommand: string | null
1215
1286
  postStartCommand: string | null
1216
1287
  repositories: { project: string; workspacePath: string }[]
@@ -1229,6 +1300,14 @@ export type StartScriptParams = {
1229
1300
  * assume). For a box where 8080 is taken by the host itself — a Blaxel sandbox's own API.
1230
1301
  */
1231
1302
  idePort?: number
1303
+ /**
1304
+ * Whether the box has an IDE to start — code-server, as it always had. `false`: a project without
1305
+ * an IDE app (RFC 0059) — no extensions copied, no editor settings, no code-server loop; the
1306
+ * terminal (tmux/dtach, the agent's) is not the IDE's and stays.
1307
+ */
1308
+ ide?: boolean
1309
+ /** Settings the IDE app adds to the seeded defaults (`ide.config` → `userSettings`), over them. */
1310
+ ideUserSettings?: Record<string, unknown>
1232
1311
  }
1233
1312
 
1234
1313
  /** code-server's port when the caller doesn't say otherwise. */
@@ -1240,16 +1319,16 @@ function idePortOf(port: number | undefined): number {
1240
1319
  return port
1241
1320
  }
1242
1321
 
1243
- export function buildStartScript(params: StartScriptParams): { script: string; hasDinD: boolean } {
1322
+ export function buildStartScript(params: StartScriptParams): { script: string } {
1244
1323
  const { project, sshGatewayPublicKey, colorTabsByProject, extensionsGallery } = params
1245
1324
  const idePort = idePortOf(params.idePort)
1325
+ const ide = params.ide !== false
1246
1326
  const homeDir = "/home/vscode"
1247
1327
  const username = "vscode"
1248
1328
 
1249
1329
  const features = project.features ?? []
1250
1330
  const hasPostCreate = !!project.postCreateCommand
1251
1331
  const hasPostStart = !!project.postStartCommand
1252
- const hasDinD = features.some((f) => f.id === "docker-in-docker") || !!project.dind
1253
1332
 
1254
1333
  const allReposDone: RS[] = project.repositories.map((r) => ({ name: r.project, state: "done" }))
1255
1334
 
@@ -1333,132 +1412,124 @@ export function buildStartScript(params: StartScriptParams): { script: string; h
1333
1412
  "done",
1334
1413
  )
1335
1414
 
1336
- // ── 4. Copy prebuilt extensions ───────────────────────────────────────────
1337
- push(
1338
- "",
1339
- 'if [ -d ' + EXTENSIONS_DIR + ' ] && [ "$(ls -A ' + EXTENSIONS_DIR + ' 2>/dev/null)" ]; then',
1340
- ` mkdir -p ${homeDir}/.local/share/code-server/extensions`,
1341
- ` cp -rn ${EXTENSIONS_DIR}/. ${homeDir}/.local/share/code-server/extensions/ 2>/dev/null || true`,
1342
- ` chown -R ${username}:${username} ${homeDir}/.local`,
1343
- "fi",
1344
- )
1345
-
1346
- // ── 4b. Seed code-server user settings (no-clobber, stays user-overridable) ─
1347
- // Reordered window.title + per-project window color make parallel worker tabs
1348
- // tellable apart at a glance (see defaultVscodeUserSettings). Written no-clobber
1349
- // (guarded on the file, not `cp -n`) so a user's own settings.json survives restarts.
1350
- const vscodeSettings = JSON.stringify(
1351
- defaultVscodeUserSettings({ projectName: project.name, colorByProject: colorTabsByProject }),
1352
- null,
1353
- 2,
1354
- )
1355
- push(
1356
- "",
1357
- `mkdir -p ${homeDir}/.local/share/code-server/User`,
1358
- `if [ ! -f ${homeDir}/.local/share/code-server/User/settings.json ]; then`,
1359
- ` echo ${JSON.stringify(b64(vscodeSettings))} | base64 -d > ${homeDir}/.local/share/code-server/User/settings.json`,
1360
- ` chown -R ${username}:${username} ${homeDir}/.local`,
1361
- "fi",
1362
- )
1363
-
1364
- // ── 4c. Restore the user's PORT secret for code-server's own terminal panel ─
1365
- // code-server reads $PORT to override --bind-addr (see § 5 below), so its
1366
- // whole process tree — including the integrated terminal it spawns — inherits
1367
- // PORT=<idePort> unless corrected. `terminal.integrated.env.linux` lets VS Code
1368
- // inject env overrides into terminals it spawns without touching the server
1369
- // process itself, so a `PORT` project secret still reaches the user's shell.
1370
- // Uses code-server's own bundled node (guaranteed present regardless of the
1371
- // devcontainer base image) since jq/node aren't guaranteed there.
1372
- const seedTerminalPortEnv = [
1373
- "const fs = require('fs')",
1374
- "const path = process.env.MP_SETTINGS_PATH",
1375
- "let settings = {}",
1376
- "try { settings = JSON.parse(fs.readFileSync(path, 'utf8')) } catch {}",
1377
- "settings['terminal.integrated.env.linux'] = { ...settings['terminal.integrated.env.linux'], PORT: process.env.MP_ORIGINAL_PORT }",
1378
- "fs.writeFileSync(path, JSON.stringify(settings, null, 2))",
1379
- ].join("\n")
1380
- const seedTerminalPortEnvEncoded = b64(seedTerminalPortEnv)
1381
-
1382
- push(
1383
- "",
1384
- 'if [ -n "${PORT:-}" ]; then',
1385
- " _mp_cs_bin=$(command -v code-server 2>/dev/null || true)",
1386
- ' if [ -n "$_mp_cs_bin" ]; then',
1387
- ' _mp_cs_bin=$(readlink -f "$_mp_cs_bin" 2>/dev/null || echo "$_mp_cs_bin")',
1388
- ' _mp_cs_node="$(dirname "$(dirname "$_mp_cs_bin")")/lib/node"',
1389
- ' if [ -x "$_mp_cs_node" ]; then',
1390
- ` mkdir -p ${homeDir}/.local/share/code-server/User`,
1391
- ` echo ${JSON.stringify(seedTerminalPortEnvEncoded)} | base64 -d > ${homeDir}/.mp_seed_terminal_port.js`,
1392
- ` MP_ORIGINAL_PORT="$PORT" MP_SETTINGS_PATH="${homeDir}/.local/share/code-server/User/settings.json" "$_mp_cs_node" ${homeDir}/.mp_seed_terminal_port.js`,
1393
- ` rm -f ${homeDir}/.mp_seed_terminal_port.js`,
1394
- ` chown -R ${username}:${username} ${homeDir}/.local`,
1395
- " fi",
1396
- " fi",
1397
- "fi",
1398
- )
1415
+ // ── 4–5. The IDE: code-server, its extensions and settings (none without an IDE app) ───
1416
+ if (ide) {
1417
+ // ── 4. Copy prebuilt extensions ───────────────────────────────────────────
1418
+ push(
1419
+ "",
1420
+ 'if [ -d ' + EXTENSIONS_DIR + ' ] && [ "$(ls -A ' + EXTENSIONS_DIR + ' 2>/dev/null)" ]; then',
1421
+ ` mkdir -p ${homeDir}/.local/share/code-server/extensions`,
1422
+ ` cp -rn ${EXTENSIONS_DIR}/. ${homeDir}/.local/share/code-server/extensions/ 2>/dev/null || true`,
1423
+ ` chown -R ${username}:${username} ${homeDir}/.local`,
1424
+ "fi",
1425
+ )
1399
1426
 
1400
- // ── 5. Start code-server as vscode ────────────────────────────────────────
1401
- // Write the restart-loop to a temp script so quoting stays clean.
1402
- // Single-quoted heredoc: $VARS are NOT expanded here, they expand when the script runs
1403
- // (env is inherited from the start script via `su vscode` without -l).
1404
- // Write the restart-loop using base64 to avoid heredoc issues in DinD contexts
1405
- // where dockerd startup can affect /tmp mount visibility for child processes.
1406
- // Script lives in home dir (persistent volume) rather than /tmp.
1407
- const codeServerLoop = [
1408
- "#!/bin/bash",
1409
- "export SHELL=$(command -v zsh 2>/dev/null || echo /bin/bash)",
1410
- // Makes the editor's own Extensions view search the same registry the picker and the image
1411
- // build used (org setting — see lib/extension-registry.ts). Nothing when the org is on Open VSX.
1412
- ...galleryExport(extensionsGallery),
1413
- // The IDE is Spunto's, not Coder's (spunto-pack rebrands the files): the name in the title,
1414
- // no "Deploy code-server for your team" on the welcome page, no "code-server vX is out"
1415
- // notification. Each flag only if this code-server knows it — an unknown one stops it dead.
1416
- '_mp_cs_flags=""',
1417
- "for _f in --app-name --disable-getting-started-override --disable-update-check; do",
1418
- ' code-server --help 2>/dev/null | grep -q -- "$_f" || continue',
1419
- ' case "$_f" in --app-name) _mp_cs_flags="$_mp_cs_flags --app-name Spunto" ;; *) _mp_cs_flags="$_mp_cs_flags $_f" ;; esac',
1420
- "done",
1421
- "while true; do",
1422
- ' VSCODE_PROXY_URI="${PUBLIC_PROTOCOL}://${WORKER_SLUG}-{{port}}.${BASE_DOMAIN}" \\',
1423
- // PORT is overridden here (not unset globally) so a project secret named
1424
- // PORT can't make code-server bind elsewhere. This also leaks PORT=<idePort>
1425
- // into code-server's own process tree (its integrated terminal included) —
1426
- // § 4c above restores the original value for that terminal specifically.
1427
- // apps/agent/src/terminal.ts (dashboard's separate terminal feature) is a
1428
- // different process tree entirely and was never affected.
1429
- ` PORT=${idePort} code-server --bind-addr 0.0.0.0:${idePort} --auth none $_mp_cs_flags /workspace 2>&1`,
1430
- ' echo "[start] code-server exited ($?), restarting in 3s..."',
1431
- " sleep 3",
1432
- "done",
1433
- ].join("\n")
1434
- const codeServerEncoded = b64(codeServerLoop)
1427
+ // ── 4b. Seed code-server user settings (no-clobber, stays user-overridable) ─
1428
+ // Reordered window.title + per-project window color make parallel worker tabs
1429
+ // tellable apart at a glance (see defaultVscodeUserSettings). Written no-clobber
1430
+ // (guarded on the file, not `cp -n`) so a user's own settings.json survives restarts.
1431
+ const vscodeSettings = JSON.stringify(
1432
+ { ...defaultVscodeUserSettings({ projectName: project.name, colorByProject: colorTabsByProject }), ...params.ideUserSettings },
1433
+ null,
1434
+ 2,
1435
+ )
1436
+ push(
1437
+ "",
1438
+ `mkdir -p ${homeDir}/.local/share/code-server/User`,
1439
+ `if [ ! -f ${homeDir}/.local/share/code-server/User/settings.json ]; then`,
1440
+ ` echo ${JSON.stringify(b64(vscodeSettings))} | base64 -d > ${homeDir}/.local/share/code-server/User/settings.json`,
1441
+ ` chown -R ${username}:${username} ${homeDir}/.local`,
1442
+ "fi",
1443
+ )
1435
1444
 
1436
- push(
1437
- ...banner("START: CODE-SERVER"),
1438
- `echo ${JSON.stringify(codeServerEncoded)} | base64 -d > ${homeDir}/.mp_codeserver.sh`,
1439
- `chmod +x ${homeDir}/.mp_codeserver.sh`,
1440
- `su ${username} -s /bin/bash -c "${homeDir}/.mp_codeserver.sh" &`,
1441
- )
1445
+ // ── 4c. Restore the user's PORT secret for code-server's own terminal panel ─
1446
+ // code-server reads $PORT to override --bind-addr (see § 5 below), so its
1447
+ // whole process tree — including the integrated terminal it spawns — inherits
1448
+ // PORT=<idePort> unless corrected. `terminal.integrated.env.linux` lets VS Code
1449
+ // inject env overrides into terminals it spawns without touching the server
1450
+ // process itself, so a `PORT` project secret still reaches the user's shell.
1451
+ // Uses code-server's own bundled node (guaranteed present regardless of the
1452
+ // devcontainer base image) since jq/node aren't guaranteed there.
1453
+ const seedTerminalPortEnv = [
1454
+ "const fs = require('fs')",
1455
+ "const path = process.env.MP_SETTINGS_PATH",
1456
+ "let settings = {}",
1457
+ "try { settings = JSON.parse(fs.readFileSync(path, 'utf8')) } catch {}",
1458
+ "settings['terminal.integrated.env.linux'] = { ...settings['terminal.integrated.env.linux'], PORT: process.env.MP_ORIGINAL_PORT }",
1459
+ "fs.writeFileSync(path, JSON.stringify(settings, null, 2))",
1460
+ ].join("\n")
1461
+ const seedTerminalPortEnvEncoded = b64(seedTerminalPortEnv)
1442
1462
 
1443
- // ── 6. postStartCommand ───────────────────────────────────────────────────
1444
- // Wait for Docker if feature entrypoints were started — regardless of whether
1445
- // the project explicitly lists docker-in-docker. Some images have Docker in
1446
- // the base image or via a differently-named feature. Strategy: give the socket
1447
- // up to 5s to appear; if it shows up, wait up to 30s for the daemon to be ready.
1448
- if (project.postStartCommand) {
1449
1463
  push(
1450
1464
  "",
1451
- "if [ -f " + FEATURE_ENTRYPOINTS_FILE + " ]; then",
1452
- " for _i in 1 2 3 4 5; do [ -S /var/run/docker.sock ] && break || sleep 1; done",
1453
- " if [ -S /var/run/docker.sock ]; then",
1454
- ' echo "Waiting for Docker daemon..."',
1455
- " for _i in $(seq 1 30); do docker info >/dev/null 2>&1 && break; sleep 1; done",
1456
- ' docker info >/dev/null 2>&1 && echo "Docker daemon ready" || echo "Docker daemon not ready, continuing"',
1465
+ 'if [ -n "${PORT:-}" ]; then',
1466
+ " _mp_cs_bin=$(command -v code-server 2>/dev/null || true)",
1467
+ ' if [ -n "$_mp_cs_bin" ]; then',
1468
+ ' _mp_cs_bin=$(readlink -f "$_mp_cs_bin" 2>/dev/null || echo "$_mp_cs_bin")',
1469
+ ' _mp_cs_node="$(dirname "$(dirname "$_mp_cs_bin")")/lib/node"',
1470
+ ' if [ -x "$_mp_cs_node" ]; then',
1471
+ ` mkdir -p ${homeDir}/.local/share/code-server/User`,
1472
+ ` echo ${JSON.stringify(seedTerminalPortEnvEncoded)} | base64 -d > ${homeDir}/.mp_seed_terminal_port.js`,
1473
+ ` MP_ORIGINAL_PORT="$PORT" MP_SETTINGS_PATH="${homeDir}/.local/share/code-server/User/settings.json" "$_mp_cs_node" ${homeDir}/.mp_seed_terminal_port.js`,
1474
+ ` rm -f ${homeDir}/.mp_seed_terminal_port.js`,
1475
+ ` chown -R ${username}:${username} ${homeDir}/.local`,
1476
+ " fi",
1457
1477
  " fi",
1458
1478
  "fi",
1459
1479
  )
1480
+
1481
+ // ── 5. Start code-server as vscode ────────────────────────────────────────
1482
+ // Write the restart-loop to a temp script so quoting stays clean.
1483
+ // Single-quoted heredoc: $VARS are NOT expanded here, they expand when the script runs
1484
+ // (env is inherited from the start script via `su vscode` without -l).
1485
+ // Write the restart-loop using base64 to avoid heredoc issues in DinD contexts
1486
+ // where dockerd startup can affect /tmp mount visibility for child processes.
1487
+ // Script lives in home dir (persistent volume) rather than /tmp.
1488
+ const codeServerLoop = [
1489
+ "#!/bin/bash",
1490
+ "export SHELL=$(command -v zsh 2>/dev/null || echo /bin/bash)",
1491
+ // Makes the editor's own Extensions view search the same registry the picker and the image
1492
+ // build used (org setting — see lib/extension-registry.ts). Nothing when the org is on Open VSX.
1493
+ ...galleryExport(extensionsGallery),
1494
+ // The IDE is Spunto's, not Coder's (spunto-pack rebrands the files): the name in the title,
1495
+ // no "Deploy code-server for your team" on the welcome page, no "code-server vX is out"
1496
+ // notification. Each flag only if this code-server knows it — an unknown one stops it dead.
1497
+ '_mp_cs_flags=""',
1498
+ "for _f in --app-name --disable-getting-started-override --disable-update-check; do",
1499
+ ' code-server --help 2>/dev/null | grep -q -- "$_f" || continue',
1500
+ ' case "$_f" in --app-name) _mp_cs_flags="$_mp_cs_flags --app-name Spunto" ;; *) _mp_cs_flags="$_mp_cs_flags $_f" ;; esac',
1501
+ "done",
1502
+ "while true; do",
1503
+ ' VSCODE_PROXY_URI="${PUBLIC_PROTOCOL}://${WORKER_SLUG}-{{port}}.${BASE_DOMAIN}" \\',
1504
+ // PORT is overridden here (not unset globally) so a project secret named
1505
+ // PORT can't make code-server bind elsewhere. This also leaks PORT=<idePort>
1506
+ // into code-server's own process tree (its integrated terminal included) —
1507
+ // § 4c above restores the original value for that terminal specifically.
1508
+ // apps/agent/src/terminal.ts (dashboard's separate terminal feature) is a
1509
+ // different process tree entirely and was never affected.
1510
+ ` PORT=${idePort} code-server --bind-addr 0.0.0.0:${idePort} --auth none $_mp_cs_flags /workspace 2>&1`,
1511
+ ' echo "[start] code-server exited ($?), restarting in 3s..."',
1512
+ " sleep 3",
1513
+ "done",
1514
+ ].join("\n")
1515
+ const codeServerEncoded = b64(codeServerLoop)
1516
+
1517
+ push(
1518
+ ...banner("START: CODE-SERVER"),
1519
+ `echo ${JSON.stringify(codeServerEncoded)} | base64 -d > ${homeDir}/.mp_codeserver.sh`,
1520
+ `chmod +x ${homeDir}/.mp_codeserver.sh`,
1521
+ `su ${username} -s /bin/bash -c "${homeDir}/.mp_codeserver.sh" &`,
1522
+ )
1460
1523
  }
1461
1524
 
1525
+ // No IDE: nothing else would keep the script — and so the project's process, which the agent
1526
+ // reports as `running` only while it lives — waiting at the end. A sleeper does, in its place.
1527
+ if (!ide) push("", "while true; do sleep 3600; done &")
1528
+
1529
+ // ── 6. The features' postStart hooks, then the project's postStartCommand ─
1530
+ // At every start, before the project's: docker-in-docker waits there for its daemon.
1531
+ push(...featureHookLines("postStartCommand", username))
1532
+
1462
1533
  if (project.postStartCommand) {
1463
1534
  const postStartDir = project.repositories.length === 1
1464
1535
  ? `/workspace/${project.repositories[0].workspacePath}`
@@ -1485,7 +1556,7 @@ export function buildStartScript(params: StartScriptParams): { script: string; h
1485
1556
  push("_MP_DONE=1")
1486
1557
  push("", "wait")
1487
1558
 
1488
- return { script: lines.join("\n"), hasDinD }
1559
+ return { script: lines.join("\n") }
1489
1560
  }
1490
1561
 
1491
1562
  // ─── buildWorkerScript ────────────────────────────────────────────────────────
@@ -1523,14 +1594,13 @@ export type SetupPhase = {
1523
1594
  // now). Ends by signalling readiness (`.mp-container-up`) then `wait`. Blocks are duplicated from
1524
1595
  // buildStartScript on purpose: the legacy path stays byte-identical (prod default) until it's
1525
1596
  // deleted once WORKER_SETUP_ORCHESTRATOR=agent becomes the default. See RFC 0017 §2.1.
1526
- export function buildContainerScript(params: StartScriptParams): { script: string; hasDinD: boolean } {
1597
+ export function buildContainerScript(params: StartScriptParams): { script: string } {
1527
1598
  const { project, sshGatewayPublicKey, colorTabsByProject, extensionsGallery } = params
1528
1599
  const idePort = idePortOf(params.idePort)
1529
1600
  const homeDir = "/home/vscode"
1530
1601
  const username = "vscode"
1531
1602
 
1532
1603
  const features = project.features ?? []
1533
- const hasDinD = features.some((f) => f.id === "docker-in-docker") || !!project.dind
1534
1604
 
1535
1605
  const lines: string[] = ["set -e", "export HOME=/home/vscode"]
1536
1606
  const push = (...l: string[]) => lines.push(...l)
@@ -1688,7 +1758,7 @@ export function buildContainerScript(params: StartScriptParams): { script: strin
1688
1758
  "wait",
1689
1759
  )
1690
1760
 
1691
- return { script: lines.join("\n"), hasDinD }
1761
+ return { script: lines.join("\n") }
1692
1762
  }
1693
1763
 
1694
1764
  export function buildWorkerScript(params: {
@@ -2028,22 +2098,12 @@ export function buildSetupPlan(params: SetupScriptParams): {
2028
2098
 
2029
2099
  // ── postCreate ──────────────────────────────────────────────────────────────
2030
2100
  if (project.postCreateCommand) {
2031
- const hasDinDFeature = (project.features?.some((f) => f.id === "docker-in-docker") ?? false) || !!project.dind
2032
2101
  const postCreateDir = project.repositories.length === 1
2033
2102
  ? `/workspace/${project.repositories[0].workspacePath}`
2034
2103
  : "/workspace"
2035
- const l: string[] = ["set -e"]
2036
- // Feature entrypoints are started by the passive CMD; just wait for the Docker daemon here.
2037
- if (hasDinDFeature) {
2038
- l.push(
2039
- 'echo "Waiting for Docker daemon..."',
2040
- "for _i in $(seq 1 30); do",
2041
- " docker info >/dev/null 2>&1 && break",
2042
- " sleep 1",
2043
- "done",
2044
- 'docker info >/dev/null 2>&1 && echo "Docker daemon ready" || echo "Docker daemon not ready after 30s, continuing anyway"',
2045
- )
2046
- }
2104
+ // Feature entrypoints are started by the passive CMD; the features' own create hooks come first
2105
+ // (docker-in-docker waits there for its daemon).
2106
+ const l: string[] = ["set -e", ...featureHookLines("onCreateCommand", username), ...featureHookLines("postCreateCommand", username)]
2047
2107
  l.push(...banner("SETUP: POST CREATE"))
2048
2108
  const cmdEncoded = b64(project.postCreateCommand)
2049
2109
  l.push(
@@ -2072,18 +2132,7 @@ export function buildSetupPlan(params: SetupScriptParams): {
2072
2132
  const postStartDir = project.repositories.length === 1
2073
2133
  ? `/workspace/${project.repositories[0].workspacePath}`
2074
2134
  : "/workspace"
2075
- const l: string[] = ["set -e",
2076
- // Same defensive Docker wait as legacy: some images ship Docker under a different name.
2077
- "if [ -f " + FEATURE_ENTRYPOINTS_FILE + " ]; then",
2078
- " for _i in 1 2 3 4 5; do [ -S /var/run/docker.sock ] && break || sleep 1; done",
2079
- " if [ -S /var/run/docker.sock ]; then",
2080
- ' echo "Waiting for Docker daemon..."',
2081
- " for _i in $(seq 1 30); do docker info >/dev/null 2>&1 && break; sleep 1; done",
2082
- ' docker info >/dev/null 2>&1 && echo "Docker daemon ready" || echo "Docker daemon not ready, continuing"',
2083
- " fi",
2084
- "fi",
2085
- ...banner("START: POST START"),
2086
- ]
2135
+ const l: string[] = ["set -e", ...featureHookLines("postStartCommand", username), ...banner("START: POST START")]
2087
2136
  const cmdEncoded = b64(project.postStartCommand)
2088
2137
  l.push(
2089
2138
  `echo "--- Running postStartCommand ---"`,
package/src/spec/index.ts CHANGED
@@ -89,7 +89,6 @@ export const SpecProjectSchema = z.object({
89
89
  features: z.array(SpecFeatureSchema).default([]),
90
90
  vscodeExtensions: z.array(z.string()).default([]),
91
91
  prewarmImages: z.array(z.string()).default([]),
92
- dind: z.boolean().default(false),
93
92
  postCreateCommand: z.string().nullable().optional(),
94
93
  postStartCommand: z.string().nullable().optional(),
95
94
  repositories: z.array(SpecRepositorySchema).default([]),