@selvajs/selva 4.21.0-beta.7 → 4.21.0-beta.9

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 (126) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/assets/0.CqqJCiiV.css +2 -0
  3. package/build/client/_app/immutable/assets/0.CqqJCiiV.css.br +0 -0
  4. package/build/client/_app/immutable/assets/0.CqqJCiiV.css.gz +0 -0
  5. package/build/client/_app/immutable/chunks/{BepzH9eI.js → DptnDNFA.js} +60 -55
  6. package/build/client/_app/immutable/chunks/DptnDNFA.js.br +0 -0
  7. package/build/client/_app/immutable/chunks/{BepzH9eI.js.gz → DptnDNFA.js.gz} +0 -0
  8. package/build/client/_app/immutable/chunks/DvJo0Zn0.js +1 -0
  9. package/build/client/_app/immutable/chunks/DvJo0Zn0.js.br +1 -0
  10. package/build/client/_app/immutable/chunks/DvJo0Zn0.js.gz +0 -0
  11. package/build/client/_app/immutable/entry/{app.Cmuegtgc.js → app.GRcSFliG.js} +2 -2
  12. package/build/client/_app/immutable/entry/app.GRcSFliG.js.br +0 -0
  13. package/build/client/_app/immutable/entry/app.GRcSFliG.js.gz +0 -0
  14. package/build/client/_app/immutable/nodes/15._hpTnSzc.js +36 -0
  15. package/build/client/_app/immutable/nodes/15._hpTnSzc.js.br +0 -0
  16. package/build/client/_app/immutable/nodes/15._hpTnSzc.js.gz +0 -0
  17. package/build/client/_app/immutable/nodes/21.DpKe0-GH.js +1 -0
  18. package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.br +0 -0
  19. package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.gz +0 -0
  20. package/build/client/_app/immutable/nodes/{25.D6EkgNRa.js → 25.BacveQsm.js} +1 -1
  21. package/build/client/_app/immutable/nodes/25.BacveQsm.js.br +0 -0
  22. package/build/client/_app/immutable/nodes/25.BacveQsm.js.gz +0 -0
  23. package/build/client/_app/version.json +1 -1
  24. package/build/client/_app/version.json.br +0 -0
  25. package/build/client/_app/version.json.gz +0 -0
  26. package/build/server/.vite/manifest.json +16 -27
  27. package/build/server/_app/immutable/assets/_layout.CqqJCiiV.css +2 -0
  28. package/build/server/chunks/api-errors.js +18 -3
  29. package/build/server/chunks/api-errors.js.map +1 -1
  30. package/build/server/chunks/boot.server.js +1 -1
  31. package/build/server/chunks/bootHealth.server.js +23 -23
  32. package/build/server/chunks/bootHealth.server.js.map +1 -1
  33. package/build/server/chunks/computeRateLimit.server.js +1 -1
  34. package/build/server/chunks/delete-with-blobs.js +1 -1
  35. package/build/server/chunks/engine.server.js +50 -3
  36. package/build/server/chunks/engine.server.js.map +1 -1
  37. package/build/server/chunks/grasshopper.js +1 -1
  38. package/build/server/chunks/handlers.js +4 -4
  39. package/build/server/chunks/handlers.js.map +1 -1
  40. package/build/server/chunks/http2.js +1 -1
  41. package/build/server/chunks/instance.js +3 -3
  42. package/build/server/chunks/internal.js +1 -1
  43. package/build/server/chunks/{abort-Bfrdupaj.js → keepalive-vtcjhAV3.js} +6 -3
  44. package/build/server/chunks/keepalive-vtcjhAV3.js.map +1 -0
  45. package/build/server/chunks/package.js +2 -1
  46. package/build/server/chunks/package.js.map +1 -1
  47. package/build/server/chunks/permissions.server.js +1 -1
  48. package/build/server/chunks/providers.server.js +142 -18
  49. package/build/server/chunks/providers.server.js.map +1 -1
  50. package/build/server/chunks/resolve-server.js +1 -1
  51. package/build/server/chunks/schema-extraction.js +75 -8
  52. package/build/server/chunks/schema-extraction.js.map +1 -1
  53. package/build/server/chunks/server-config-write.js +6 -6
  54. package/build/server/chunks/server-config-write.js.map +1 -1
  55. package/build/server/chunks/serverStats.server.js +1 -1
  56. package/build/server/chunks/solve.server.js +4 -5
  57. package/build/server/chunks/solve.server.js.map +1 -1
  58. package/build/server/chunks/sveltekit.js +3 -4
  59. package/build/server/chunks/sveltekit.js.map +1 -1
  60. package/build/server/chunks/update-outcome.js +11 -0
  61. package/build/server/chunks/update-outcome.js.map +1 -1
  62. package/build/server/chunks/updateCheck.server.js +23 -11
  63. package/build/server/chunks/updateCheck.server.js.map +1 -1
  64. package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +1 -1
  65. package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +1 -1
  66. package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +1 -1
  67. package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +3 -2
  68. package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js.map +1 -1
  69. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +32 -1
  70. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js.map +1 -1
  71. package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +1 -1
  72. package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +1 -1
  73. package/build/server/entries/endpoints/api/admin/users/_server.ts.js +1 -1
  74. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +1 -1
  75. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +10 -5
  76. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js.map +1 -1
  77. package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +2 -2
  78. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +3 -3
  79. package/build/server/entries/endpoints/mcp/_server.ts.js +38 -9
  80. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  81. package/build/server/entries/hooks.server.js +1 -1
  82. package/build/server/entries/pages/admin/compute/_page.server.ts.js +1 -2
  83. package/build/server/entries/pages/admin/compute/_page.server.ts.js.map +1 -1
  84. package/build/server/entries/pages/admin/system/_page.server.ts.js +8 -3
  85. package/build/server/entries/pages/admin/system/_page.server.ts.js.map +1 -1
  86. package/build/server/entries/pages/admin/system/_page.svelte.js +18 -2
  87. package/build/server/entries/pages/admin/system/_page.svelte.js.map +1 -1
  88. package/build/server/entries/pages/library/_guid_/_page.server.ts.js +198 -99
  89. package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
  90. package/build/server/entries/pages/library/_guid_/_page.svelte.js +462 -30
  91. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  92. package/build/server/entries/pages/projects/_page.svelte.js +2 -0
  93. package/build/server/entries/pages/projects/_page.svelte.js.map +1 -1
  94. package/build/server/manifest-full.js +1 -1
  95. package/build/server/manifest.js +1 -1
  96. package/build/server/nodes/0.js +2 -2
  97. package/build/server/nodes/15.js +1 -1
  98. package/build/server/nodes/21.js +1 -1
  99. package/build/server/nodes/25.js +1 -1
  100. package/build/server/server.js +1 -1
  101. package/package.json +14 -11
  102. package/templates/.env.example +5 -3
  103. package/build/client/_app/immutable/assets/0.2jDm0bqh.css +0 -2
  104. package/build/client/_app/immutable/assets/0.2jDm0bqh.css.br +0 -0
  105. package/build/client/_app/immutable/assets/0.2jDm0bqh.css.gz +0 -0
  106. package/build/client/_app/immutable/chunks/BepzH9eI.js.br +0 -0
  107. package/build/client/_app/immutable/chunks/BmoT9ksD.js +0 -1
  108. package/build/client/_app/immutable/chunks/BmoT9ksD.js.br +0 -1
  109. package/build/client/_app/immutable/chunks/BmoT9ksD.js.gz +0 -0
  110. package/build/client/_app/immutable/entry/app.Cmuegtgc.js.br +0 -0
  111. package/build/client/_app/immutable/entry/app.Cmuegtgc.js.gz +0 -0
  112. package/build/client/_app/immutable/nodes/15.BXIV1QfS.js +0 -32
  113. package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.br +0 -0
  114. package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.gz +0 -0
  115. package/build/client/_app/immutable/nodes/21.DvC40Ypm.js +0 -1
  116. package/build/client/_app/immutable/nodes/21.DvC40Ypm.js.br +0 -0
  117. package/build/client/_app/immutable/nodes/21.DvC40Ypm.js.gz +0 -0
  118. package/build/client/_app/immutable/nodes/25.D6EkgNRa.js.br +0 -0
  119. package/build/client/_app/immutable/nodes/25.D6EkgNRa.js.gz +0 -0
  120. package/build/server/_app/immutable/assets/_layout.2jDm0bqh.css +0 -2
  121. package/build/server/chunks/abort-Bfrdupaj.js.map +0 -1
  122. package/build/server/chunks/computeLimits.js +0 -33
  123. package/build/server/chunks/computeLimits.js.map +0 -1
  124. /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js → 0.Ds0zeDAg.js} +0 -0
  125. /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.br → 0.Ds0zeDAg.js.br} +0 -0
  126. /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.gz → 0.Ds0zeDAg.js.gz} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":["join","readFileSync"],"sources":["../../../../../../../../src/lib/server/updateRunner.server.ts","../../../../../../../../src/routes/api/admin/system/update/+server.ts"],"sourcesContent":["/**\n * Generates the bash the self-update POST route spawns: a tiny daemonizing\n * launcher plus the runner script that actually stops/updates/starts/health-\n * checks the deployment. Split out of the route file because SvelteKit's\n * route-file validator only allows HTTP-verb exports (and `_`-prefixed ones) —\n * these are plain functions the runner-script contract tests import directly.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findDeploymentDir } from './selfUpdate.server.js';\nimport { channelTag, type ReleaseChannel } from './releaseChannel.server.js';\n\nexport function readRuntimeVersion(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(dir, 'node_modules', '@selvajs', 'selva', 'package.json'), 'utf8')\n\t\t);\n\t\treturn typeof pkg.version === 'string' ? pkg.version : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// No caller currently passes untrusted input (plan.cwd is from\n// process.cwd(), npm package names are hardcoded), but defensive quoting is\n// cheap.\nexport function shellQuote(s: string): string {\n\treturn `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Wraps the actual update commands in a tiny \"launcher\" that daemonizes them.\n//\n// THE PROBLEM: `pm2 stop selva-compute` (which the runner has to call) uses\n// tree-kill, which walks /proc parent-child relationships from\n// selva-compute's PID and SIGKILLs every descendant. Node's\n// `{ detached: true }` + `child.unref()` puts the spawned bash in a new\n// session/process group but does NOT change the parent-child relationship —\n// so tree-kill still finds and kills it, and the app never restarts.\n//\n// THE FIX: write the update commands to a tempfile and launch them via\n// `setsid bash ... &`, then have the launcher exit. The runner's PPID becomes\n// 1 (init) the moment the launcher exits, so it's no longer a descendant of\n// selva-compute and tree-kill can't reach it.\n//\n// Output: the launcher's prelude lines are echoed via tee into\n// UPDATE_LOG_PATH and through stdout (visible to SSE while the connection is\n// still up); the runner appends its output to the same log file; the\n// frontend tolerates the SSE blackout by polling the log file.\nexport function buildLauncher(\n\trunnerScript: string,\n\tlogPath: string,\n\tprelude: string[] = []\n): string {\n\tconst echoes = prelude.map((line) => `echo ${shellQuote(line)}`).join('\\n');\n\t// Note: runner script is embedded via a QUOTED heredoc so no variable\n\t// expansion happens — the runner text is written verbatim.\n\treturn `\nLOGFILE=${shellQuote(logPath)}\nRUNNER=/tmp/selva-update-runner.sh\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n: > \"$LOGFILE\"\n\ncat > \"$RUNNER\" <<'__SELVA_RUNNER_EOF__'\n${runnerScript}\n__SELVA_RUNNER_EOF__\nchmod +x \"$RUNNER\"\n\ntrap '' PIPE\nexec > >(tee --output-error=warn-nopipe -a \"$LOGFILE\" 2>/dev/null) 2>&1\n${echoes}\n\n# Daemonize the runner so PM2's tree-kill of selva-compute can't reach it.\n# setsid puts it in a new session; the trailing & + disown + launcher exit\n# leaves the runner with PPID=1 once we're gone. stdin/stdout/stderr are\n# fully detached from this process (and from selva-compute's pipes).\nsetsid bash \"$RUNNER\" </dev/null >>\"$LOGFILE\" 2>&1 &\nRUNNER_PID=$!\ndisown\necho \"[INFO] Update runner started (PID $RUNNER_PID, log: $LOGFILE)\"\n\n# Small pause so the runner has time to print its first line before SSE\n# closes — otherwise the frontend's first poll might see no progress.\nsleep 1\nexit 0\n`;\n}\n\n// Bash script the daemonized runner executes. Flow:\n//\n// 1. pre-flight — query the registry; if already on latest, exit clean\n// WITHOUT touching the running app.\n// 2. pm2 sync — `pm2 update` if the daemon and CLI versions drifted.\n// 3. pm2 stop — stop selva-compute before npm overwrites build/, so\n// in-flight requests can't hit ERR_MODULE_NOT_FOUND\n// from chunk-hash churn under their feet.\n// 4. npm update — refresh @selvajs/* (--prefer-online bypasses the\n// packument cache, already baked into npmArgs).\n// 5. pm2 start — from ecosystem.config.cjs (not `pm2 start name`,\n// which requires the process to already be in pm2's\n// in-memory list — fragile after `pm2 update`).\n// 6. health probe — poll /api/health for up to 30s.\n// 7. rollback — on failure: npm install the prior version, restart.\n// 8. EXIT trap — last-resort: if anything above leaves the app\n// offline (crash, kill, network blip), unconditionally\n// try `pm2 start ecosystem.config.cjs` before exiting\n// so the customer's site doesn't stay dark.\n//\n// Embedded into the launcher via a quoted heredoc, so this whole string is\n// written verbatim — interpolated values must be shell-quoted at JS time.\nexport function buildNpmRunnerScript(\n\tnpmArgs: string[],\n\tversionBefore: string | undefined,\n\tecosystemPath: string,\n\ttag: string\n): string {\n\tconst npmCommand = ['npm', ...npmArgs].map(shellQuote).join(' ');\n\t// Empty string when versionBefore is undefined — bash sees `BEFORE=\"\"`\n\t// and skips the rollback path (you can't roll back to nothing).\n\tconst before = shellQuote(versionBefore ?? '');\n\tconst ecosystem = shellQuote(ecosystemPath);\n\t// The npm dist-tag the chosen channel resolves to (`latest` / `beta`). The\n\t// pre-flight and no-change warning query this tag, so they don't misfire on\n\t// a beta channel (where the channel's published version is a pre-release the\n\t// default `latest` query would never see) or on a revert (where the target\n\t// stable version is OLDER than the installed beta).\n\tconst distTag = shellQuote(tag);\n\n\treturn `#!/bin/bash\nset -o pipefail\nBEFORE=${before}\nECOSYSTEM=${ecosystem}\nTAG=${distTag}\n\n# Resolve the deployment-local pm2 explicitly instead of trusting PATH.\n# The runner is re-launched via \\`setsid bash\\` from a tempfile, so it inherits\n# whatever environment the spawning process had. When the update is triggered\n# from the admin UI that happens to include node_modules/.bin; from cron or a\n# bare shell it does not, and every pm2 call below — including the EXIT trap's\n# last-resort restart — fails with \"command not found\" and the app stays dark.\nPM2=\"$(dirname \"$ECOSYSTEM\")/node_modules/.bin/pm2\"\n[ -x \"$PM2\" ] || PM2=pm2\n\n# Under systemd, \\`pm2 update\\` kills and respawns the daemon. systemd sees its\n# unit's main process die and, with the default KillMode=control-group,\n# SIGTERMs everything in the cgroup — including this runner. setsid escapes\n# PM2's tree-kill but NOT the cgroup, so the runner never runs \\`pm2 update\\`\n# when this is true.\npm2_under_systemd() {\n grep -qs 'pm2.*\\\\.service' /proc/self/cgroup 2>/dev/null\n}\n\n# Waits for selva-compute to leave the transitional 'stopping' state.\n#\n# \\`pm2 stop\\` sends SIGINT and returns without waiting for the process to die.\n# The SvelteKit node adapter then drains in-flight requests before exiting, and\n# PM2 only escalates to SIGKILL after kill_timeout (10s in the scaffolded\n# ecosystem). For that whole window the process table entry has a name and an\n# id but no live pid — \\`pm2 start\\` resolves the name, converts to a restart,\n# finds nothing to restart, and pm2's own table printer crashes on\n# \\`undefined.pm2_env\\`. Polling here keeps the rest of the script out of that\n# window entirely.\n#\n# The drain reliably takes the full timeout when the update was triggered from\n# the admin UI: that page is fed by an SSE stream this very process serves, and\n# an open SSE stream never completes on its own.\n# Prints exactly one word. Callers compare it against 'online' / 'stopping', so\n# a probe that emits two tokens on failure (the inline catch AND a shell\n# fallback both firing) would silently never match either. Node's catch is the\n# single failure path; fd 0 rather than /dev/stdin because the latter isn't a\n# readable pipe everywhere.\napp_status() {\n \"$PM2\" jlist 2>/dev/null | node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === 'selva-compute');\n process.stdout.write(app ? app.pm2_env.status : 'missing');\n } catch { process.stdout.write('error'); }\n \" 2>/dev/null\n}\n\nwait_until_stopped() {\n for i in $(seq 1 20); do\n STATUS=$(app_status)\n if [ \"$STATUS\" != \"stopping\" ]; then\n return 0\n fi\n echo \"[INFO] selva-compute still draining (attempt $i/20) — waiting for SIGKILL escalation\"\n sleep 1\n done\n echo \"[WARN] selva-compute stuck in 'stopping' after 20s — continuing anyway\"\n return 1\n}\n\n# \\`pm2 start <ecosystem>\\` converts to a restart-by-id when an entry of the same\n# name is already in the table. If that entry is stale the restart fails and no\n# amount of retrying the same command helps — the name has to be dropped first\n# so the start registers a fresh process. Deleting a stopped entry is safe: the\n# ecosystem file is the source of truth for how to bring it back.\nstart_app() {\n if \"$PM2\" start \"$ECOSYSTEM\" --update-env; then\n return 0\n fi\n echo \"[WARN] pm2 start failed — dropping the stale process entry and retrying\"\n \"$PM2\" delete selva-compute >/dev/null 2>&1 || true\n \"$PM2\" start \"$ECOSYSTEM\" --update-env\n}\n\n# Last-resort safety net. If the script exits with the app NOT online for\n# any reason (crash, kill -9, network blip, npm hang past timeout), try to\n# bring it back from ecosystem.config.cjs before exiting. Leaving the app\n# down is the worst possible outcome of an update.\non_exit() {\n CODE=$?\n STATUS=$(app_status)\n # A 'stopping' entry is mid-drain, not down. Restarting it now hits the same\n # dead-id window that brought us here; wait for the entry to settle first.\n if [ \"$STATUS\" = \"stopping\" ]; then\n wait_until_stopped\n STATUS=$(app_status)\n fi\n if [ \"$STATUS\" != \"online\" ]; then\n echo \"[RECOVER] selva-compute is '$STATUS' — starting from ecosystem.config.cjs\"\n start_app >/dev/null 2>&1 || \\\\\n echo \"[RECOVER] pm2 start failed — manual intervention required: cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 delete selva-compute; ./node_modules/.bin/pm2 start ecosystem.config.cjs\"\n fi\n # Terminal marker: the restarted app's outcome reconciler greps this to turn\n # the run into an audit event (selfUpdate.server.ts). Keep the format stable.\n echo \"[EXIT] code=$CODE\"\n}\ntrap on_exit EXIT\n\n# A killed runner must not look like a finished one.\n#\n# \\`$?\\` inside an EXIT trap reports the last completed command, NOT the signal.\n# When systemd SIGTERMs the whole cgroup, the EXIT trap still runs and records\n# \\`code=0\\` — so deriveOutcome takes the exit-0 success branch and tells the\n# operator \"Updated X → Y. The app is back online.\" while npm never ran and\n# the deployment is unchanged. Catching the signal makes the recorded code\n# truthful; 143/130 are the conventional 128+signal values.\non_signal() {\n SIG=$1\n echo \"[FATAL] KILLED: runner received SIG$SIG before finishing.\"\n echo \"[FATAL] Nothing was installed by this run. If the app is down, recover with:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && pm2 start ecosystem.config.cjs --update-env\"\n echo \"[FATAL] A systemd-supervised pm2 can do this when 'pm2 update' recycles the daemon.\"\n exit $2\n}\ntrap 'on_signal TERM 143' TERM\ntrap 'on_signal INT 130' INT\ntrap 'on_signal HUP 129' HUP\n\n# ---------------------------------------------------------------------------\n# 1. Pre-flight: skip the whole cycle if there's nothing to install.\n# ---------------------------------------------------------------------------\n# Without this, clicking \"Update\" on an already-current instance triggers a\n# full stop/install/start cycle and a downtime window for no reason.\necho \"[STEP] Checking npm registry for the '$TAG' channel version\"\nLATEST=$(npm view \"@selvajs/selva@$TAG\" version --silent 2>/dev/null || echo \"\")\nif [ -z \"$LATEST\" ]; then\n echo \"[WARN] Could not query npm registry — proceeding with update attempt anyway\"\nelif [ -n \"$BEFORE\" ] && [ \"$LATEST\" = \"$BEFORE\" ]; then\n echo \"[INFO] Already on the '$TAG' channel version ($BEFORE)\"\n echo \"[DONE] Nothing to do\"\n exit 0\nelse\n # May be a forward update OR a revert (target older than installed) — either\n # way the installed version differs from what this channel publishes.\n echo \"[INFO] Target ($TAG): $BEFORE → $LATEST\"\nfi\n\n# ---------------------------------------------------------------------------\n# 1b. Node engine pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# npm only treats an engine mismatch as fatal under engine-strict=true, which\n# no deployment sets. So a release requiring a newer Node installs\n# \"successfully\", pm2 starts, and /api/health returns 200 (it touches nothing\n# Node-version specific) — a false green that skips rollback entirely. Warn\n# here so a CLI-driven run sees it too; the admin UI blocks earlier.\nREQUIRED_NODE=$(npm view \"@selvajs/selva@$TAG\" engines.node --silent 2>/dev/null | tr -d '\"' | tr -d \"'\")\nRUNNING_NODE=$(node -p 'process.versions.node' 2>/dev/null)\nif [ -n \"$REQUIRED_NODE\" ] && [ -n \"$RUNNING_NODE\" ]; then\n # Compare majors only — the ranges we publish are all \\`>=X\\` forms.\n REQ_MAJOR=$(echo \"$REQUIRED_NODE\" | grep -o '[0-9]\\\\+' | head -1)\n RUN_MAJOR=$(echo \"$RUNNING_NODE\" | cut -d. -f1)\n if [ -n \"$REQ_MAJOR\" ] && [ \"$RUN_MAJOR\" -lt \"$REQ_MAJOR\" ] 2>/dev/null; then\n echo \"[WARN] ENGINE_MISMATCH: @selvajs/selva@$LATEST requires Node $REQUIRED_NODE but this host runs v$RUNNING_NODE\"\n echo \"[WARN] npm will install it anyway (engine-strict is off) and the health probe will pass,\"\n echo \"[WARN] but routes using newer Node APIs will fail at request time. Upgrade Node on this host.\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.\n# ---------------------------------------------------------------------------\n# After a global pm2 upgrade the daemon keeps running its original version\n# while the CLI moves forward. Process commands then talk to a stale daemon\n# and the symptom is \"stop works, start never lands\". \\`pm2 update\\` dumps\n# processes, kills the daemon, respawns on the current CLI, restores the\n# dump. Doing it before we touch anything keeps the rest of the script\n# talking to a coherent daemon.\necho \"[STEP] Checking PM2 daemon/CLI version sync\"\nPING_OUT=$(\"$PM2\" ping 2>&1)\nif echo \"$PING_OUT\" | grep -q \"out-of-date\"; then\n # pm2 prints both versions alongside the warning. Which is newer decides\n # whether \\`pm2 update\\` can help — see the direction check below.\n DAEMON_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"In memory PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n LOCAL_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"Local PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n DAEMON_MAJOR=\\${DAEMON_V%%.*}\n LOCAL_MAJOR=\\${LOCAL_V%%.*}\n\n # A daemon NEWER than the deployment-local CLI means a foreign global pm2 owns\n # it. \\`pm2 update\\` would DOWNGRADE the daemon and feed it a dump it can't read,\n # losing the process table — selva-compute never gets re-registered. That is an\n # operator problem, not something this script can repair, so stop before we\n # take the app down.\n if [ -n \"$DAEMON_MAJOR\" ] && [ -n \"$LOCAL_MAJOR\" ] && [ \"$DAEMON_MAJOR\" -gt \"$LOCAL_MAJOR\" ] 2>/dev/null; then\n echo \"[FATAL] PM2_SKEW: the running daemon (v$DAEMON_V) is NEWER than this deployment's pm2 (v$LOCAL_V).\"\n echo \"[FATAL] A global pm2 owns the daemon. Running 'pm2 update' would downgrade it and drop\"\n echo \"[FATAL] the process table. Resolve manually before updating:\"\n echo \"[FATAL] which -a pm2 && pm2 -v && pm2 ping\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 8\n fi\n\n if pm2_under_systemd; then\n echo \"[FATAL] SYSTEMD_PM2: this deployment's PM2 is supervised by systemd, and the daemon\"\n echo \"[FATAL] needs a resync. Running 'pm2 update' here would restart the systemd unit and\"\n echo \"[FATAL] kill this runner mid-update. Resync manually from a shell, then retry:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 update\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 9\n fi\n\n echo \"[STEP] PM2 daemon is out-of-date — running 'pm2 update' to resync\"\n if ! \"$PM2\" update; then\n echo \"[FATAL] pm2 update failed — aborting before stopping the running app\"\n exit 1\n fi\n echo \"[INFO] PM2 daemon resynced\"\nfi\n\n# ---------------------------------------------------------------------------\n# 3. Stop selva-compute BEFORE npm rewrites build/.\n# ---------------------------------------------------------------------------\n# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on\n# every request. Letting npm rewrite build/ while the old process still\n# serves traffic means in-flight requests hit ERR_MODULE_NOT_FOUND for chunks\n# whose hash just changed under their feet. Stopping first is a brief\n# downtime window (~1-2s longer than restart-in-place) for a much smaller\n# blast radius.\n#\n# This is also where the SSE connection to the frontend dies — selva-compute\n# IS the SSE server. From here on, the user sees output via the log-file\n# polling fallback in the admin UI, not over SSE.\necho \"[STEP] Stopping selva-compute\"\nif ! \"$PM2\" stop selva-compute; then\n echo \"[WARN] pm2 stop failed — selva-compute may not be running yet. Continuing.\"\nfi\n\n# pm2 stop returns before the process is actually gone. Everything below —\n# npm rewriting build/, then the restart — must happen outside the drain window.\nwait_until_stopped\n\n# ---------------------------------------------------------------------------\n# 4. Run npm update.\n# ---------------------------------------------------------------------------\necho \"[STEP] Updating @selvajs/* packages\"\nif ! ${npmCommand}; then\n echo \"[FATAL] npm update failed — EXIT trap will restart the previous build\"\n exit 1\nfi\n\nAFTER=$(node -e \"try{console.log(require('./node_modules/@selvajs/selva/package.json').version)}catch(e){}\" 2>/dev/null)\necho \"[INFO] New @selvajs/selva: \\${AFTER:-unknown}\"\n\nif [ -n \"$BEFORE\" ] && [ \"$BEFORE\" = \"$AFTER\" ]; then\n echo \"[WARN] No version change ($BEFORE). Your npm cache may be stale.\"\n echo \"[WARN] Recover with:\"\n echo \"[WARN] npm cache clean --force\"\n echo \"[WARN] rm -rf node_modules package-lock.json\"\n echo \"[WARN] npm install --prefer-online\"\nfi\n\n# ---------------------------------------------------------------------------\n# 4b. Move pm2 onto the version the new CLI pins.\n# ---------------------------------------------------------------------------\n# Only \\`selva migrate\\` rewrites package.json, so without this a release that\n# bumps pm2 needs a manual migrate on every host. The pin is read from the CLI\n# just installed: its devDependencies.pm2 is what a fresh scaffold gets. The\n# app is stopped, so swapping the daemon here adds no downtime. A failure\n# leaves the old pm2 running the app: warn, never abort. A rollback below\n# keeps the new pm2: reinstalling the old one would leave the daemon newer\n# than the CLI, the one skew \\`pm2 update\\` cannot repair.\nPM2_DECLARED=$(node -p \"require('./package.json').dependencies?.pm2 ?? ''\" 2>/dev/null)\nPM2_PIN=$(node -p \"require('./node_modules/@selvajs/cli/package.json').devDependencies?.pm2 ?? ''\" 2>/dev/null)\nif [ -n \"$PM2_PIN\" ] && [ \"$PM2_PIN\" != \"$PM2_DECLARED\" ]; then\n echo \"[STEP] Moving pm2 \\${PM2_DECLARED:-(none)} → $PM2_PIN, the version this release pins\"\n if npm install --save --save-exact --prefer-online \"pm2@$PM2_PIN\"; then\n if pm2_under_systemd; then\n echo \"[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version.\"\n echo \"[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n echo \"[WARN] Let it finish: interrupting it leaves selva-compute unregistered.\"\n elif ! \"$PM2\" update; then\n echo \"[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2.\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n fi\n else\n echo \"[WARN] PM2_PIN_FAILED: could not install pm2@$PM2_PIN — the previous pm2 still runs the app.\"\n echo \"[WARN] Retry from a shell: cd $(dirname \"$ECOSYSTEM\") && npx selva migrate\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 5. Start selva-compute with the new build.\n# ---------------------------------------------------------------------------\n# Start from ecosystem.config.cjs, NOT \\`pm2 start selva-compute\\` — the latter\n# requires selva-compute to already be in pm2's in-memory process list, which\n# a \\`pm2 update\\` (step 2) isn't guaranteed to preserve.\necho \"[STEP] Starting selva-compute with new build\"\nif ! start_app; then\n echo \"[FATAL] pm2 start failed — investigate with \\\\\\`pm2 logs selva-compute\\\\\\`\"\n exit 2\nfi\n\n# ---------------------------------------------------------------------------\n# 6. Health probe the new process.\n# ---------------------------------------------------------------------------\n# Read PORT from .env the same way scripts/update.sh does, so non-default\n# ports are respected.\nPORT=$(grep \"^PORT=\" .env 2>/dev/null \\\\\n | head -1 \\\\\n | cut -d'=' -f2 \\\\\n | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^[\"'\"'\"']//' -e 's/[\"'\"'\"']$//' -e 's/[[:space:]]*#.*//')\nPORT=\\${PORT:-3000}\n\necho \"[STEP] Health-probing the new process on port $PORT\"\nHEALTHY=0\nfor i in $(seq 1 15); do\n sleep 2\n CODE=$(curl -sS -o /tmp/selva-health.$$ -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\n if [ \"$CODE\" = \"200\" ]; then\n HEALTHY=1\n echo \"[INFO] Health probe passed after \\${i} attempt(s)\"\n rm -f /tmp/selva-health.$$\n break\n fi\n echo \"[INFO] Probe attempt $i/15: HTTP $CODE — retrying\"\ndone\n\nif [ \"$HEALTHY\" = \"1\" ]; then\n echo \"[DONE] Update complete\"\n exit 0\nfi\n\n# ---------------------------------------------------------------------------\n# 7. Rollback path.\n# ---------------------------------------------------------------------------\necho \"[FATAL] New process failed health check after 30s\"\nif [ -f /tmp/selva-health.$$ ]; then\n BODY=$(cat /tmp/selva-health.$$)\n echo \"[FATAL] Last response body:\"\n echo \"$BODY\"\n\n # Name the cause before rolling back. /api/health reports WHY it is degraded\n # in a structured body, but a rollback that only prints raw JSON reads to an\n # operator as \"the update just failed\" — they retry, hit the identical\n # failure, and never learn the database is the thing that needs attention.\n # Each branch below emits a stable marker deriveOutcome keys on.\n # Match on the keys unique to each report rather than a bare \\`\"ok\":false\\`,\n # which appears in whichever sub-report failed and would misattribute one\n # cause to the other. \\`expected\\` only ever appears in schemaVersion;\n # \\`plaintextFound\\`/\\`failures\\` only in atRestSecrets.\n if echo \"$BODY\" | grep -q '\"expected\":'; then\n EXPECTED=$(echo \"$BODY\" | grep -o '\"expected\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n ACTUAL=$(echo \"$BODY\" | grep -o '\"actual\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n echo \"[FATAL] SCHEMA_SKEW: @selvajs/selva@\\${AFTER:-$LATEST} expects database migration head \\${EXPECTED:-(unknown)},\"\n echo \"[FATAL] but this database is at \\${ACTUAL:-(unavailable)}. The new version is fine — its migrations\"\n echo \"[FATAL] were never applied. Retrying the update WILL fail again in exactly the same way.\"\n echo \"[FATAL] The update does not apply migrations itself: they are not reversible, so an\"\n echo \"[FATAL] auto-migrate followed by a rollback would leave code and database on different heads.\"\n echo \"[FATAL] Apply them yourself, then re-run the update:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\")\"\n echo \"[FATAL] npm install --prefer-online @selvajs/supabase-provider@$TAG\"\n echo \"[FATAL] npx selva-supabase\"\n echo \"[FATAL] npx supabase db push\"\n echo \"[FATAL] The provider install is not optional: the migration SQL ships inside that\"\n echo \"[FATAL] package, and the update only moves @selvajs/cli and @selvajs/selva — so a sync\"\n echo \"[FATAL] without it copies 0 files and the push reports 'up to date' having done nothing.\"\n echo \"[FATAL] If db push asks for credentials, see docs/self-hosting/providers/supabase.md\"\n echo \"[FATAL] — it needs a Supabase ACCOUNT credential (supabase login, or SUPABASE_ACCESS_TOKEN),\"\n echo \"[FATAL] which is not any of the three keys in .env.\"\n elif echo \"$BODY\" | grep -qE '\"plaintextFound\":true|\"failures\":\\\\[[^]]'; then\n echo \"[FATAL] AT_REST_SECRETS: stored compute server API keys could not be decrypted under the\"\n echo \"[FATAL] current SELVA_AT_REST_KEY. This is a configuration problem on this host, not a\"\n echo \"[FATAL] fault in the new version — retrying the update will fail the same way.\"\n echo \"[FATAL] Re-enter the affected keys at /admin/compute, or restore the original\"\n echo \"[FATAL] SELVA_AT_REST_KEY, then re-run the update.\"\n else\n echo \"[FATAL] The health endpoint did not report a known cause. Inspect the body above and\"\n echo \"[FATAL] \\\\\\`pm2 logs selva-compute\\\\\\` for what the new version failed on.\"\n fi\n\n rm -f /tmp/selva-health.$$\nfi\n\nif [ -z \"$BEFORE\" ]; then\n echo \"[FATAL] No prior version recorded — cannot roll back automatically.\"\n echo \"[FATAL] EXIT trap will attempt to restart the current build anyway.\"\n exit 3\nfi\n\necho \"[STEP] Rolling back @selvajs/selva to $BEFORE\"\n\"$PM2\" stop selva-compute >/dev/null 2>&1 || true\nwait_until_stopped >/dev/null 2>&1\n# Restore @selvajs/cli alongside the runtime: the forward step installs both at\n# the channel tag, so reverting only the runtime leaves a version pair that was\n# never released together.\nif ! npm install --save \"@selvajs/cli@$BEFORE\" \"@selvajs/selva@$BEFORE\"; then\n echo \"[FATAL] Rollback npm install failed — EXIT trap will retry restart.\"\n exit 4\nfi\n\nstart_app || true\nsleep 3\nROLLBACK_CODE=$(curl -sS -o /dev/null -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\nif [ \"$ROLLBACK_CODE\" = \"200\" ]; then\n echo \"[DONE] Rolled back to $BEFORE — previous version is online\"\n exit 5\nfi\n\necho \"[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)\"\necho \"[FATAL] Manual recovery required. Check: pm2 logs selva-compute\"\nexit 6\n`;\n}\n\n// Selva self-updates as a CLI-scaffolded npm deployment: the deployment dir\n// holds a package.json that depends on @selvajs/selva, and update means\n// `npm install @selvajs/*@<tag>` + pm2 restart. Deployment-dir detection\n// (cwd-upward probe, `INSTALL_DIR` override) lives in `selfUpdate.server.ts`,\n// shared with the outcome reconciler and the log path.\nexport type UpdatePlan = { cwd: string; args: string[] };\n\n// Only the CLI and the runtime move. Provider code is bundled into\n// @selvajs/selva; @selvajs/supabase-provider carries just the migration SQL,\n// which the operator installs and pushes before updating.\n//\n// `npm install` pins to the channel's dist-tag rather than using `npm\n// update`, because `update` only ever moves FORWARD within the installed\n// semver range — it can't switch dist-tags or DOWNGRADE. Pinning to @latest /\n// @beta makes one command serve every transition: forward stable bumps,\n// beta→newer-beta, and the revert case (beta→stable lands on an older version).\n//\n// --save persists the resolved version into package.json so the next plain\n// install is reproducible; --prefer-online forces npm to revalidate cached\n// packuments against the registry — without it, npm's packument cache (5+\n// min TTL) can silently no-op right after publish.\nexport function npmInstallArgs(channel: ReleaseChannel): string[] {\n\tconst tag = channelTag(channel);\n\treturn ['install', '--save', '--prefer-online', `@selvajs/cli@${tag}`, `@selvajs/selva@${tag}`];\n}\n\nexport function detectUpdatePlan(\n\tenv: Record<string, string | undefined>,\n\tchannel: ReleaseChannel\n): UpdatePlan | null {\n\tconst dir = findDeploymentDir(env);\n\treturn dir ? { cwd: dir, args: npmInstallArgs(channel) } : null;\n}\n","import { spawn } from 'child_process';\nimport { join } from 'path';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { env } from '#lib/server/env.js';\nimport { json } from '@sveltejs/kit';\nimport { actorFrom } from '@selvajs/platform';\nimport type { RequestHandler } from './$types';\nimport { requirePermission } from '#lib/server/access.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\nimport { checkForUpdate } from '#lib/server/updateCheck.server.js';\nimport { readChannel, channelTag } from '#lib/server/releaseChannel.server.js';\nimport { getEventSink, getErrorReporter } from '#lib/server/providers.server.js';\nimport {\n\tfindDeploymentDir,\n\tstartUpdateOutcomeReconciler,\n\tupdateLogPath,\n\tupdateStatePath,\n\ttype PendingUpdateState\n} from '#lib/server/selfUpdate.server.js';\nimport {\n\treadRuntimeVersion,\n\tbuildLauncher,\n\tbuildNpmRunnerScript,\n\tdetectUpdatePlan\n} from '#lib/server/updateRunner.server.js';\n\n// Where the bash wrapper mirrors all script output (`updateLogPath` — in the\n// deployment dir so it survives reboots, audit O2). The SSE stream dies the\n// moment `pm2 stop selva-compute` succeeds (selva-compute IS the SSE server),\n// so the frontend loses visibility into everything that happens after — npm\n// update output, pm2 start result, health-probe results, rollback decisions.\n// The script keeps writing to this file regardless. Once the new selva-compute\n// process is back up, the frontend polls GET on this same route to fetch the\n// full log and reveal what happened during the blackout. One log per update —\n// the wrapper truncates at start, so we never carry stale content forward.\n// The runner's `[EXIT] code=N` marker in the same log also drives the\n// post-restart audit-event reconciliation (`selfUpdate.server.ts`).\n\n// Strip ANSI escape codes from terminal output\nfunction stripAnsi(str: string): string {\n\t// eslint-disable-next-line no-control-regex\n\treturn str.replace(/\\x1B\\[[0-9;]*[mGKHF]/g, '');\n}\n\n// POST - Run update and stream output via Server-Sent Events.\n//\n// Runs `npm update @selvajs/*` then restarts via ecosystem.config.cjs. The\n// runner script handles stop / update / start / health-probe / rollback with\n// an EXIT trap that keeps the app online no matter how it exits.\nexport const POST: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst channel = readChannel();\n\tconst plan = detectUpdatePlan(env, channel);\n\tif (!plan) {\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror:\n\t\t\t\t\t\"Couldn't determine how to update this deployment. \" +\n\t\t\t\t\t'Expected node_modules/@selvajs/selva (CLI scaffold) in the cwd ' +\n\t\t\t\t\t'or a parent directory.'\n\t\t\t}),\n\t\t\t{ status: 500, headers: { 'Content-Type': 'application/json' } }\n\t\t);\n\t}\n\n\t// Capture the runtime version BEFORE we touch anything, so we can:\n\t// (a) detect a no-op update and warn, (b) roll back to the prior version\n\t// if the new process fails to come up healthy.\n\tconst versionBefore = readRuntimeVersion(plan.cwd);\n\tconst actorId = locals.ctx ? actorFrom(locals.ctx) : 'system';\n\n\t// Audit trail (O2): `started` now; the terminal event is emitted by the\n\t// outcome reconciler after the app restarts (this process is killed\n\t// mid-update). The state file is the reconciler's emission token.\n\tconst pending: PendingUpdateState = {\n\t\tstartedAt: new Date().toISOString(),\n\t\tactorId,\n\t\tchannel,\n\t\tfromVersion: versionBefore\n\t};\n\ttry {\n\t\twriteFileSync(updateStatePath(plan.cwd), JSON.stringify(pending, null, '\\t'));\n\t} catch (err) {\n\t\tlocals.log.error('Could not persist pending-update state', {\n\t\t\tcomponent: 'selfUpdate',\n\t\t\terr: renderThrown(err)\n\t\t});\n\t}\n\tawait getEventSink().emit({\n\t\ttype: 'system.update.started',\n\t\tchannel,\n\t\tfromVersion: versionBefore,\n\t\tactorId\n\t});\n\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tconst encoder = new TextEncoder();\n\n\t\t\tfunction sendEvent(type: string, data: Record<string, unknown>) {\n\t\t\t\tconst message = `data: ${JSON.stringify({ type, ...data })}\\n\\n`;\n\t\t\t\tcontroller.enqueue(encoder.encode(message));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Prelude lines are passed to the bash wrapper rather than\n\t\t\t\t// sendEvent'd directly so they end up in both the SSE stream\n\t\t\t\t// (via bash stdout) AND the log file (via tee). Without this,\n\t\t\t\t// the frontend's blackout-recovery file fetch would clobber\n\t\t\t\t// these lines when it replaces its buffer with the file content.\n\t\t\t\tconst prelude = [\n\t\t\t\t\t`[INFO] Updating deployment (cwd: ${plan.cwd}, channel: ${channel})`,\n\t\t\t\t\t...(versionBefore ? [`[INFO] Current @selvajs/selva: ${versionBefore}`] : [])\n\t\t\t\t];\n\n\t\t\t\t// Spawn the launcher detached. The launcher writes the actual\n\t\t\t\t// runner script to disk, daemonizes it (setsid + & + exit),\n\t\t\t\t// and quits — leaving the runner with PPID=1 so PM2's tree-kill\n\t\t\t\t// of selva-compute can't reach it. See buildLauncher for the\n\t\t\t\t// full rationale.\n\t\t\t\t//\n\t\t\t\t// The runner is buildNpmRunnerScript — pre-flights the version\n\t\t\t\t// check, then stop / npm update / start / health probe /\n\t\t\t\t// rollback, with an EXIT trap that ensures the app is online no\n\t\t\t\t// matter how the script exits.\n\t\t\t\tconst runnerScript = buildNpmRunnerScript(\n\t\t\t\t\tplan.args,\n\t\t\t\t\tversionBefore,\n\t\t\t\t\tjoin(plan.cwd, 'ecosystem.config.cjs'),\n\t\t\t\t\tchannelTag(channel)\n\t\t\t\t);\n\t\t\t\tconst cmd = 'bash';\n\t\t\t\tconst args = ['-c', buildLauncher(runnerScript, updateLogPath(plan.cwd), prelude)];\n\n\t\t\t\t// Prepend the deployment's node_modules/.bin to PATH so the bash\n\t\t\t\t// script finds the project-local pm2 (and any other tooling\n\t\t\t\t// installed as a deployment dependency). Without this the script\n\t\t\t\t// inherits the SvelteKit process's PATH, which on most servers\n\t\t\t\t// doesn't include node_modules/.bin — so `pm2` resolves to\n\t\t\t\t// whatever's globally installed, or fails outright if no global\n\t\t\t\t// pm2 exists. Both are wrong: we want the project-local pm2 so\n\t\t\t\t// daemon and CLI stay aligned. Mirrors the local-only resolution\n\t\t\t\t// in @selvajs/cli's pm2Bin().\n\t\t\t\tconst localBin = join(plan.cwd, 'node_modules', '.bin');\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: plan.cwd,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tPATH: `${localBin}:${process.env.PATH ?? ''}`,\n\n\t\t\t\t\t\tHOME: process.env.HOME,\n\t\t\t\t\t\tINSTALL_DIR: plan.cwd\n\t\t\t\t\t},\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: ['ignore', 'pipe', 'pipe']\n\t\t\t\t});\n\t\t\t\tchild.unref();\n\n\t\t\t\t// Covers the outcomes that DON'T restart this process (pre-flight\n\t\t\t\t// \"already up to date\", early failures): this process is still\n\t\t\t\t// alive to reconcile them. A real update kills this process; the\n\t\t\t\t// restarted one re-arms the reconciler from hooks.server.ts.\n\t\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\t\tdeploymentDir: plan.cwd,\n\t\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t\t});\n\n\t\t\t\t// Kill the process if it runs longer than 15 minutes.\n\t\t\t\t// The child is detached (its own process group), so signal the\n\t\t\t\t// whole group via negative pid — otherwise descendants (pnpm,\n\t\t\t\t// node, pm2) outlive the bash wrapper.\n\t\t\t\tconst timeout = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (child.pid) process.kill(-child.pid, 'SIGTERM');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// group already gone — nothing to do\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendEvent('log', { data: '[FATAL] Update timed out after 15 minutes' });\n\t\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t},\n\t\t\t\t\t15 * 60 * 1000\n\t\t\t\t);\n\n\t\t\t\t// Stream stdout\n\t\t\t\tlet restarting = false;\n\t\t\t\tchild.stdout.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\t// Detect both stopProcessId (pm2 restart) and restartProcessId (pm2 reload)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!restarting &&\n\t\t\t\t\t\t\t\t(clean.includes('Applying action stopProcessId') ||\n\t\t\t\t\t\t\t\t\tclean.includes('Applying action restartProcessId'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\trestarting = true;\n\t\t\t\t\t\t\t\tsendEvent('restarting', { data: clean });\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsendEvent('log', { data: clean });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Stream stderr\n\t\t\t\tchild.stderr.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\tsendEvent('log', { data: `[ERROR] ${clean}` });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Handle process exit\n\t\t\t\tchild.on('close', (code) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('exit', { code: code ?? -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\n\t\t\t\t// Handle errors\n\t\t\t\tchild.on('error', (err) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('log', { data: `[FATAL] ${err.message}` });\n\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tsendEvent('log', { data: `[FATAL] Failed to spawn process: ${err}` });\n\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}\n\t});\n\n\treturn new Response(stream, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive'\n\t\t}\n\t});\n};\n\n// GET — two jobs, selected by query param:\n//\n// ?check=1 → query the npm registry and report whether a newer\n// @selvajs/selva is published. JSON: { current, latest,\n// updateAvailable }. The admin page calls this on load to show\n// an \"update available\" badge. Degrades gracefully: if the\n// registry is unreachable, latest is null and updateAvailable\n// is false (we never block the page on npm).\n//\n// (default) → read the tee'd update log so the frontend can recover the\n// chunk of output that happened during the SSE blackout (between\n// `pm2 stop` killing this process and the new selva-compute\n// coming back online). Empty body if no update has run yet.\n// Polled by the admin UI during the post-restart wait.\nexport const GET: RequestHandler = async ({ locals, url, fetch }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tif (url.searchParams.get('check') !== null) {\n\t\treturn json(await checkForUpdate(fetch, readChannel()), {\n\t\t\theaders: { 'Cache-Control': 'no-store' }\n\t\t});\n\t}\n\n\tlet body = '';\n\ttry {\n\t\tbody = readFileSync(updateLogPath(findDeploymentDir(env)), 'utf8');\n\t} catch {\n\t\t// Log doesn't exist (no update has run yet). Empty body is correct —\n\t\t// the frontend treats no content as \"nothing to show yet\".\n\t}\n\treturn new Response(body, {\n\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AAY;CACb,EACD,CAAC;AACF;AAgBA,IAAa,MAAsB,OAAO,EAAE,QAAQ,KAAK,YAAY;CACpE,kBAAkB,QAAQ,gBAAgB;CAE1C,IAAI,IAAI,aAAa,IAAI,OAAO,MAAM,MACrC,OAAO,KAAK,MAAM,eAAe,OAAO,YAAY,CAAC,GAAG,EACvD,SAAS,EAAE,iBAAiB,WAAW,EACxC,CAAC;CAGF,IAAI,OAAO;CACX,IAAI;EACH,OAAOC,eAAa,cAAc,kBAAkB,GAAG,CAAC,GAAG,MAAM;CAClE,QAAQ,CAGR;CACA,OAAO,IAAI,SAAS,MAAM,EACzB,SAAS;EACR,gBAAgB;EAChB,iBAAiB;CAClB,EACD,CAAC;AACF"}
1
+ {"version":3,"file":"_server.ts.js","names":["join","readFileSync"],"sources":["../../../../../../../../src/lib/server/updateRunner.server.ts","../../../../../../../../src/routes/api/admin/system/update/+server.ts"],"sourcesContent":["/**\n * Generates the bash the self-update POST route spawns: a tiny daemonizing\n * launcher plus the runner script that actually stops/updates/starts/health-\n * checks the deployment. Split out of the route file because SvelteKit's\n * route-file validator only allows HTTP-verb exports (and `_`-prefixed ones) —\n * these are plain functions the runner-script contract tests import directly.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findDeploymentDir } from './selfUpdate.server.js';\nimport { channelTag, type ReleaseChannel } from './releaseChannel.server.js';\n\nexport function readRuntimeVersion(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(dir, 'node_modules', '@selvajs', 'selva', 'package.json'), 'utf8')\n\t\t);\n\t\treturn typeof pkg.version === 'string' ? pkg.version : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// No caller currently passes untrusted input (plan.cwd is from\n// process.cwd(), npm package names are hardcoded), but defensive quoting is\n// cheap.\nexport function shellQuote(s: string): string {\n\treturn `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Wraps the actual update commands in a tiny \"launcher\" that daemonizes them.\n//\n// THE PROBLEM: `pm2 stop selva-compute` (which the runner has to call) uses\n// tree-kill, which walks /proc parent-child relationships from\n// selva-compute's PID and SIGKILLs every descendant. Node's\n// `{ detached: true }` + `child.unref()` puts the spawned bash in a new\n// session/process group but does NOT change the parent-child relationship —\n// so tree-kill still finds and kills it, and the app never restarts.\n//\n// THE FIX: write the update commands to a tempfile and launch them via\n// `setsid bash ... &`, then have the launcher exit. The runner's PPID becomes\n// 1 (init) the moment the launcher exits, so it's no longer a descendant of\n// selva-compute and tree-kill can't reach it.\n//\n// Output: the launcher's prelude lines are echoed via tee into\n// UPDATE_LOG_PATH and through stdout (visible to SSE while the connection is\n// still up); the runner appends its output to the same log file; the\n// frontend tolerates the SSE blackout by polling the log file.\nexport function buildLauncher(\n\trunnerScript: string,\n\tlogPath: string,\n\tprelude: string[] = []\n): string {\n\tconst echoes = prelude.map((line) => `echo ${shellQuote(line)}`).join('\\n');\n\t// Note: runner script is embedded via a QUOTED heredoc so no variable\n\t// expansion happens — the runner text is written verbatim.\n\treturn `\nLOGFILE=${shellQuote(logPath)}\nRUNNER=/tmp/selva-update-runner.sh\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n: > \"$LOGFILE\"\n\ncat > \"$RUNNER\" <<'__SELVA_RUNNER_EOF__'\n${runnerScript}\n__SELVA_RUNNER_EOF__\nchmod +x \"$RUNNER\"\n\ntrap '' PIPE\nexec > >(tee --output-error=warn-nopipe -a \"$LOGFILE\" 2>/dev/null) 2>&1\n${echoes}\n\n# Daemonize the runner so PM2's tree-kill of selva-compute can't reach it.\n# setsid puts it in a new session; the trailing & + disown + launcher exit\n# leaves the runner with PPID=1 once we're gone. stdin/stdout/stderr are\n# fully detached from this process (and from selva-compute's pipes).\nsetsid bash \"$RUNNER\" </dev/null >>\"$LOGFILE\" 2>&1 &\nRUNNER_PID=$!\ndisown\necho \"[INFO] Update runner started (PID $RUNNER_PID, log: $LOGFILE)\"\n\n# Small pause so the runner has time to print its first line before SSE\n# closes — otherwise the frontend's first poll might see no progress.\nsleep 1\nexit 0\n`;\n}\n\n// Bash script the daemonized runner executes. Flow:\n//\n// 1. pre-flight — query the registry; if already on latest, exit clean\n// WITHOUT touching the running app. Refuse a target\n// that cannot read this deployment's data.\n// 2. pm2 sync — `pm2 update` if the daemon and CLI versions drifted.\n// 3. pm2 stop — stop selva-compute before npm overwrites build/, so\n// in-flight requests can't hit ERR_MODULE_NOT_FOUND\n// from chunk-hash churn under their feet.\n// 4. npm update — refresh @selvajs/* (--prefer-online bypasses the\n// packument cache, already baked into npmArgs).\n// 5. pm2 start — from ecosystem.config.cjs (not `pm2 start name`,\n// which requires the process to already be in pm2's\n// in-memory list — fragile after `pm2 update`).\n// 6. health probe — poll /api/health for up to 30s.\n// 7. rollback — on failure: npm install the prior version, restart.\n// 8. EXIT trap — last-resort: if anything above leaves the app\n// offline (crash, kill, network blip), unconditionally\n// try `pm2 start ecosystem.config.cjs` before exiting\n// so the customer's site doesn't stay dark.\n//\n// Embedded into the launcher via a quoted heredoc, so this whole string is\n// written verbatim — interpolated values must be shell-quoted at JS time.\nexport function buildNpmRunnerScript(\n\tnpmArgs: string[],\n\tversionBefore: string | undefined,\n\tecosystemPath: string,\n\ttag: string\n): string {\n\tconst npmCommand = ['npm', ...npmArgs].map(shellQuote).join(' ');\n\t// Empty string when versionBefore is undefined — bash sees `BEFORE=\"\"`\n\t// and skips the rollback path (you can't roll back to nothing).\n\tconst before = shellQuote(versionBefore ?? '');\n\tconst ecosystem = shellQuote(ecosystemPath);\n\t// The npm dist-tag the chosen channel resolves to (`latest` / `beta`). The\n\t// pre-flight and no-change warning query this tag, so they don't misfire on\n\t// a beta channel (where the channel's published version is a pre-release the\n\t// default `latest` query would never see) or on a revert (where the target\n\t// stable version is OLDER than the installed beta).\n\tconst distTag = shellQuote(tag);\n\n\treturn `#!/bin/bash\nset -o pipefail\nBEFORE=${before}\nECOSYSTEM=${ecosystem}\nTAG=${distTag}\n\n# Resolve the deployment-local pm2 explicitly instead of trusting PATH.\n# The runner is re-launched via \\`setsid bash\\` from a tempfile, so it inherits\n# whatever environment the spawning process had. When the update is triggered\n# from the admin UI that happens to include node_modules/.bin; from cron or a\n# bare shell it does not, and every pm2 call below — including the EXIT trap's\n# last-resort restart — fails with \"command not found\" and the app stays dark.\nPM2=\"$(dirname \"$ECOSYSTEM\")/node_modules/.bin/pm2\"\n[ -x \"$PM2\" ] || PM2=pm2\n\n# Under systemd, \\`pm2 update\\` kills and respawns the daemon. systemd sees its\n# unit's main process die and, with the default KillMode=control-group,\n# SIGTERMs everything in the cgroup — including this runner. setsid escapes\n# PM2's tree-kill but NOT the cgroup, so the runner never runs \\`pm2 update\\`\n# when this is true.\npm2_under_systemd() {\n grep -qs 'pm2.*\\\\.service' /proc/self/cgroup 2>/dev/null\n}\n\n# Waits for selva-compute to leave the transitional 'stopping' state.\n#\n# \\`pm2 stop\\` sends SIGINT and returns without waiting for the process to die.\n# The SvelteKit node adapter then drains in-flight requests before exiting, and\n# PM2 only escalates to SIGKILL after kill_timeout (10s in the scaffolded\n# ecosystem). For that whole window the process table entry has a name and an\n# id but no live pid — \\`pm2 start\\` resolves the name, converts to a restart,\n# finds nothing to restart, and pm2's own table printer crashes on\n# \\`undefined.pm2_env\\`. Polling here keeps the rest of the script out of that\n# window entirely.\n#\n# The drain reliably takes the full timeout when the update was triggered from\n# the admin UI: that page is fed by an SSE stream this very process serves, and\n# an open SSE stream never completes on its own.\n# Prints exactly one word. Callers compare it against 'online' / 'stopping', so\n# a probe that emits two tokens on failure (the inline catch AND a shell\n# fallback both firing) would silently never match either. Node's catch is the\n# single failure path; fd 0 rather than /dev/stdin because the latter isn't a\n# readable pipe everywhere.\napp_status() {\n \"$PM2\" jlist 2>/dev/null | node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === 'selva-compute');\n process.stdout.write(app ? app.pm2_env.status : 'missing');\n } catch { process.stdout.write('error'); }\n \" 2>/dev/null\n}\n\nwait_until_stopped() {\n for i in $(seq 1 20); do\n STATUS=$(app_status)\n if [ \"$STATUS\" != \"stopping\" ]; then\n return 0\n fi\n echo \"[INFO] selva-compute still draining (attempt $i/20) — waiting for SIGKILL escalation\"\n sleep 1\n done\n echo \"[WARN] selva-compute stuck in 'stopping' after 20s — continuing anyway\"\n return 1\n}\n\n# \\`pm2 start <ecosystem>\\` converts to a restart-by-id when an entry of the same\n# name is already in the table. If that entry is stale the restart fails and no\n# amount of retrying the same command helps — the name has to be dropped first\n# so the start registers a fresh process. Deleting a stopped entry is safe: the\n# ecosystem file is the source of truth for how to bring it back.\nstart_app() {\n if \"$PM2\" start \"$ECOSYSTEM\" --update-env; then\n return 0\n fi\n echo \"[WARN] pm2 start failed — dropping the stale process entry and retrying\"\n \"$PM2\" delete selva-compute >/dev/null 2>&1 || true\n \"$PM2\" start \"$ECOSYSTEM\" --update-env\n}\n\n# Last-resort safety net. If the script exits with the app NOT online for\n# any reason (crash, kill -9, network blip, npm hang past timeout), try to\n# bring it back from ecosystem.config.cjs before exiting. Leaving the app\n# down is the worst possible outcome of an update.\non_exit() {\n CODE=$?\n STATUS=$(app_status)\n # A 'stopping' entry is mid-drain, not down. Restarting it now hits the same\n # dead-id window that brought us here; wait for the entry to settle first.\n if [ \"$STATUS\" = \"stopping\" ]; then\n wait_until_stopped\n STATUS=$(app_status)\n fi\n if [ \"$STATUS\" != \"online\" ]; then\n echo \"[RECOVER] selva-compute is '$STATUS' — starting from ecosystem.config.cjs\"\n start_app >/dev/null 2>&1 || \\\\\n echo \"[RECOVER] pm2 start failed — manual intervention required: cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 delete selva-compute; ./node_modules/.bin/pm2 start ecosystem.config.cjs\"\n fi\n # Terminal marker: the restarted app's outcome reconciler greps this to turn\n # the run into an audit event (selfUpdate.server.ts). Keep the format stable.\n echo \"[EXIT] code=$CODE\"\n}\ntrap on_exit EXIT\n\n# A killed runner must not look like a finished one.\n#\n# \\`$?\\` inside an EXIT trap reports the last completed command, NOT the signal.\n# When systemd SIGTERMs the whole cgroup, the EXIT trap still runs and records\n# \\`code=0\\` — so deriveOutcome takes the exit-0 success branch and tells the\n# operator \"Updated X → Y. The app is back online.\" while npm never ran and\n# the deployment is unchanged. Catching the signal makes the recorded code\n# truthful; 143/130 are the conventional 128+signal values.\non_signal() {\n SIG=$1\n echo \"[FATAL] KILLED: runner received SIG$SIG before finishing.\"\n echo \"[FATAL] Nothing was installed by this run. If the app is down, recover with:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && pm2 start ecosystem.config.cjs --update-env\"\n echo \"[FATAL] A systemd-supervised pm2 can do this when 'pm2 update' recycles the daemon.\"\n exit $2\n}\ntrap 'on_signal TERM 143' TERM\ntrap 'on_signal INT 130' INT\ntrap 'on_signal HUP 129' HUP\n\n# ---------------------------------------------------------------------------\n# 1. Pre-flight: skip the whole cycle if there's nothing to install.\n# ---------------------------------------------------------------------------\n# Without this, clicking \"Update\" on an already-current instance triggers a\n# full stop/install/start cycle and a downtime window for no reason.\necho \"[STEP] Checking npm registry for the '$TAG' channel version\"\nLATEST=$(npm view \"@selvajs/selva@$TAG\" version --silent 2>/dev/null || echo \"\")\nif [ -z \"$LATEST\" ]; then\n echo \"[WARN] Could not query npm registry — proceeding with update attempt anyway\"\nelif [ -n \"$BEFORE\" ] && [ \"$LATEST\" = \"$BEFORE\" ]; then\n echo \"[INFO] Already on the '$TAG' channel version ($BEFORE)\"\n echo \"[DONE] Nothing to do\"\n exit 0\nelse\n # May be a forward update OR a revert (target older than installed) — either\n # way the installed version differs from what this channel publishes.\n echo \"[INFO] Target ($TAG): $BEFORE → $LATEST\"\nfi\n\n# ---------------------------------------------------------------------------\n# 1b. Node engine pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# npm only treats an engine mismatch as fatal under engine-strict=true, which\n# no deployment sets. So a release requiring a newer Node installs\n# \"successfully\", pm2 starts, and /api/health returns 200 (it touches nothing\n# Node-version specific) — a false green that skips rollback entirely. Warn\n# here so a CLI-driven run sees it too; the admin UI blocks earlier.\nREQUIRED_NODE=$(npm view \"@selvajs/selva@$TAG\" engines.node --silent 2>/dev/null | tr -d '\"' | tr -d \"'\")\nRUNNING_NODE=$(node -p 'process.versions.node' 2>/dev/null)\nif [ -n \"$REQUIRED_NODE\" ] && [ -n \"$RUNNING_NODE\" ]; then\n # Compare majors only — the ranges we publish are all \\`>=X\\` forms.\n REQ_MAJOR=$(echo \"$REQUIRED_NODE\" | grep -o '[0-9]\\\\+' | head -1)\n RUN_MAJOR=$(echo \"$RUNNING_NODE\" | cut -d. -f1)\n if [ -n \"$REQ_MAJOR\" ] && [ \"$RUN_MAJOR\" -lt \"$REQ_MAJOR\" ] 2>/dev/null; then\n echo \"[WARN] ENGINE_MISMATCH: @selvajs/selva@$LATEST requires Node $REQUIRED_NODE but this host runs v$RUNNING_NODE\"\n echo \"[WARN] npm will install it anyway (engine-strict is off) and the health probe will pass,\"\n echo \"[WARN] but routes using newer Node APIs will fail at request time. Upgrade Node on this host.\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 1c. Data format pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# A release with a lower data format than the installed one cannot read what\n# this deployment has already stored (dataFormat.server.ts). It would boot, fail\n# its health check and roll back: two outages for nothing. Installed by hand it\n# leaves stored Compute API keys unreadable. A release that declares no format\n# is format 1. Skipped when the registry gave no answer: the target is unknown.\nINSTALLED_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$INSTALLED_FORMAT\" in ''|*[!0-9]*) INSTALLED_FORMAT=1 ;; esac\nif [ -n \"$LATEST\" ] && TARGET_FORMAT=$(npm view \"@selvajs/selva@$TAG\" selva.dataFormat --silent 2>/dev/null); then\n TARGET_FORMAT=$(echo \"$TARGET_FORMAT\" | tr -d '\"' | tr -d \"'\" | tr -d '[:space:]')\n case \"$TARGET_FORMAT\" in ''|*[!0-9]*) TARGET_FORMAT=1 ;; esac\n if [ \"$TARGET_FORMAT\" -lt \"$INSTALLED_FORMAT\" ]; then\n echo \"[FATAL] DATA_FORMAT: @selvajs/selva@$LATEST reads data format $TARGET_FORMAT, but this deployment is on format $INSTALLED_FORMAT.\"\n echo \"[FATAL] It could not read what the installed version has stored, such as Compute API keys.\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n echo \"[FATAL] To go back anyway: docs/self-hosting/deployment/admin.md, 'Going back to an older release'.\"\n exit 10\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.\n# ---------------------------------------------------------------------------\n# After a global pm2 upgrade the daemon keeps running its original version\n# while the CLI moves forward. Process commands then talk to a stale daemon\n# and the symptom is \"stop works, start never lands\". \\`pm2 update\\` dumps\n# processes, kills the daemon, respawns on the current CLI, restores the\n# dump. Doing it before we touch anything keeps the rest of the script\n# talking to a coherent daemon.\necho \"[STEP] Checking PM2 daemon/CLI version sync\"\nPING_OUT=$(\"$PM2\" ping 2>&1)\nif echo \"$PING_OUT\" | grep -q \"out-of-date\"; then\n # pm2 prints both versions alongside the warning. Which is newer decides\n # whether \\`pm2 update\\` can help — see the direction check below.\n DAEMON_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"In memory PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n LOCAL_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"Local PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n DAEMON_MAJOR=\\${DAEMON_V%%.*}\n LOCAL_MAJOR=\\${LOCAL_V%%.*}\n\n # A daemon NEWER than the deployment-local CLI means a foreign global pm2 owns\n # it. \\`pm2 update\\` would DOWNGRADE the daemon and feed it a dump it can't read,\n # losing the process table — selva-compute never gets re-registered. That is an\n # operator problem, not something this script can repair, so stop before we\n # take the app down.\n if [ -n \"$DAEMON_MAJOR\" ] && [ -n \"$LOCAL_MAJOR\" ] && [ \"$DAEMON_MAJOR\" -gt \"$LOCAL_MAJOR\" ] 2>/dev/null; then\n echo \"[FATAL] PM2_SKEW: the running daemon (v$DAEMON_V) is NEWER than this deployment's pm2 (v$LOCAL_V).\"\n echo \"[FATAL] A global pm2 owns the daemon. Running 'pm2 update' would downgrade it and drop\"\n echo \"[FATAL] the process table. Resolve manually before updating:\"\n echo \"[FATAL] which -a pm2 && pm2 -v && pm2 ping\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 8\n fi\n\n if pm2_under_systemd; then\n echo \"[FATAL] SYSTEMD_PM2: this deployment's PM2 is supervised by systemd, and the daemon\"\n echo \"[FATAL] needs a resync. Running 'pm2 update' here would restart the systemd unit and\"\n echo \"[FATAL] kill this runner mid-update. Resync manually from a shell, then retry:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 update\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 9\n fi\n\n echo \"[STEP] PM2 daemon is out-of-date — running 'pm2 update' to resync\"\n if ! \"$PM2\" update; then\n echo \"[FATAL] pm2 update failed — aborting before stopping the running app\"\n exit 1\n fi\n echo \"[INFO] PM2 daemon resynced\"\nfi\n\n# ---------------------------------------------------------------------------\n# 3. Stop selva-compute BEFORE npm rewrites build/.\n# ---------------------------------------------------------------------------\n# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on\n# every request. Letting npm rewrite build/ while the old process still\n# serves traffic means in-flight requests hit ERR_MODULE_NOT_FOUND for chunks\n# whose hash just changed under their feet. Stopping first is a brief\n# downtime window (~1-2s longer than restart-in-place) for a much smaller\n# blast radius.\n#\n# This is also where the SSE connection to the frontend dies — selva-compute\n# IS the SSE server. From here on, the user sees output via the log-file\n# polling fallback in the admin UI, not over SSE.\necho \"[STEP] Stopping selva-compute\"\nif ! \"$PM2\" stop selva-compute; then\n echo \"[WARN] pm2 stop failed — selva-compute may not be running yet. Continuing.\"\nfi\n\n# pm2 stop returns before the process is actually gone. Everything below —\n# npm rewriting build/, then the restart — must happen outside the drain window.\nwait_until_stopped\n\n# ---------------------------------------------------------------------------\n# 4. Run npm update.\n# ---------------------------------------------------------------------------\necho \"[STEP] Updating @selvajs/* packages\"\nif ! ${npmCommand}; then\n echo \"[FATAL] npm update failed — EXIT trap will restart the previous build\"\n exit 1\nfi\n\nAFTER=$(node -e \"try{console.log(require('./node_modules/@selvajs/selva/package.json').version)}catch(e){}\" 2>/dev/null)\necho \"[INFO] New @selvajs/selva: \\${AFTER:-unknown}\"\n\nif [ -n \"$BEFORE\" ] && [ \"$BEFORE\" = \"$AFTER\" ]; then\n echo \"[WARN] No version change ($BEFORE). Your npm cache may be stale.\"\n echo \"[WARN] Recover with:\"\n echo \"[WARN] npm cache clean --force\"\n echo \"[WARN] rm -rf node_modules package-lock.json\"\n echo \"[WARN] npm install --prefer-online\"\nfi\n\n# ---------------------------------------------------------------------------\n# 4b. Move pm2 onto the version the new CLI pins.\n# ---------------------------------------------------------------------------\n# Only \\`selva migrate\\` rewrites package.json, so without this a release that\n# bumps pm2 needs a manual migrate on every host. The pin is read from the CLI\n# just installed: its devDependencies.pm2 is what a fresh scaffold gets. The\n# app is stopped, so swapping the daemon here adds no downtime. A failure\n# leaves the old pm2 running the app: warn, never abort. A rollback below\n# keeps the new pm2: reinstalling the old one would leave the daemon newer\n# than the CLI, the one skew \\`pm2 update\\` cannot repair.\nPM2_DECLARED=$(node -p \"require('./package.json').dependencies?.pm2 ?? ''\" 2>/dev/null)\nPM2_PIN=$(node -p \"require('./node_modules/@selvajs/cli/package.json').devDependencies?.pm2 ?? ''\" 2>/dev/null)\nif [ -n \"$PM2_PIN\" ] && [ \"$PM2_PIN\" != \"$PM2_DECLARED\" ]; then\n echo \"[STEP] Moving pm2 \\${PM2_DECLARED:-(none)} → $PM2_PIN, the version this release pins\"\n if npm install --save --save-exact --prefer-online \"pm2@$PM2_PIN\"; then\n if pm2_under_systemd; then\n echo \"[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version.\"\n echo \"[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n echo \"[WARN] Let it finish: interrupting it leaves selva-compute unregistered.\"\n elif ! \"$PM2\" update; then\n echo \"[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2.\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n fi\n else\n echo \"[WARN] PM2_PIN_FAILED: could not install pm2@$PM2_PIN — the previous pm2 still runs the app.\"\n echo \"[WARN] Retry from a shell: cd $(dirname \"$ECOSYSTEM\") && npx selva migrate\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 5. Start selva-compute with the new build.\n# ---------------------------------------------------------------------------\n# Start from ecosystem.config.cjs, NOT \\`pm2 start selva-compute\\` — the latter\n# requires selva-compute to already be in pm2's in-memory process list, which\n# a \\`pm2 update\\` (step 2) isn't guaranteed to preserve.\necho \"[STEP] Starting selva-compute with new build\"\nif ! start_app; then\n echo \"[FATAL] pm2 start failed — investigate with \\\\\\`pm2 logs selva-compute\\\\\\`\"\n exit 2\nfi\n\n# ---------------------------------------------------------------------------\n# 6. Health probe the new process.\n# ---------------------------------------------------------------------------\n# Read PORT from .env the same way scripts/update.sh does, so non-default\n# ports are respected.\nPORT=$(grep \"^PORT=\" .env 2>/dev/null \\\\\n | head -1 \\\\\n | cut -d'=' -f2 \\\\\n | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^[\"'\"'\"']//' -e 's/[\"'\"'\"']$//' -e 's/[[:space:]]*#.*//')\nPORT=\\${PORT:-3000}\n\necho \"[STEP] Health-probing the new process on port $PORT\"\nHEALTHY=0\nfor i in $(seq 1 15); do\n sleep 2\n CODE=$(curl -sS -o /tmp/selva-health.$$ -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\n if [ \"$CODE\" = \"200\" ]; then\n HEALTHY=1\n echo \"[INFO] Health probe passed after \\${i} attempt(s)\"\n rm -f /tmp/selva-health.$$\n break\n fi\n echo \"[INFO] Probe attempt $i/15: HTTP $CODE — retrying\"\ndone\n\nif [ \"$HEALTHY\" = \"1\" ]; then\n echo \"[DONE] Update complete\"\n exit 0\nfi\n\n# ---------------------------------------------------------------------------\n# 7. Rollback path.\n# ---------------------------------------------------------------------------\necho \"[FATAL] New process failed health check after 30s\"\nif [ -f /tmp/selva-health.$$ ]; then\n BODY=$(cat /tmp/selva-health.$$)\n echo \"[FATAL] Last response body:\"\n echo \"$BODY\"\n\n # Name the cause before rolling back. /api/health reports WHY it is degraded\n # in a structured body, but a rollback that only prints raw JSON reads to an\n # operator as \"the update just failed\" — they retry, hit the identical\n # failure, and never learn the database is the thing that needs attention.\n # Each branch below emits a stable marker deriveOutcome keys on.\n # Match on the keys unique to each report rather than a bare \\`\"ok\":false\\`,\n # which appears in whichever sub-report failed and would misattribute one\n # cause to the other. \\`expected\\` only ever appears in schemaVersion;\n # \\`plaintextFound\\`/\\`failures\\` only in atRestSecrets.\n if echo \"$BODY\" | grep -q '\"expected\":'; then\n EXPECTED=$(echo \"$BODY\" | grep -o '\"expected\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n ACTUAL=$(echo \"$BODY\" | grep -o '\"actual\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n echo \"[FATAL] SCHEMA_SKEW: @selvajs/selva@\\${AFTER:-$LATEST} expects database migration head \\${EXPECTED:-(unknown)},\"\n echo \"[FATAL] but this database is at \\${ACTUAL:-(unavailable)}. The new version is fine — its migrations\"\n echo \"[FATAL] were never applied. Retrying the update WILL fail again in exactly the same way.\"\n echo \"[FATAL] The update does not apply migrations itself: they are not reversible, so an\"\n echo \"[FATAL] auto-migrate followed by a rollback would leave code and database on different heads.\"\n echo \"[FATAL] Apply them yourself, then re-run the update:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\")\"\n echo \"[FATAL] npm install --prefer-online @selvajs/supabase-provider@$TAG\"\n echo \"[FATAL] npx selva-supabase\"\n echo \"[FATAL] npx supabase db push\"\n echo \"[FATAL] The provider install is not optional: the migration SQL ships inside that\"\n echo \"[FATAL] package, and the update only moves @selvajs/cli and @selvajs/selva — so a sync\"\n echo \"[FATAL] without it copies 0 files and the push reports 'up to date' having done nothing.\"\n echo \"[FATAL] If db push asks for credentials, see docs/self-hosting/providers/supabase.md\"\n echo \"[FATAL] — it needs a Supabase ACCOUNT credential (supabase login, or SUPABASE_ACCESS_TOKEN),\"\n echo \"[FATAL] which is not any of the three keys in .env.\"\n elif echo \"$BODY\" | grep -qE '\"plaintextFound\":true|\"failures\":\\\\[[^]]'; then\n echo \"[FATAL] AT_REST_SECRETS: stored compute server API keys could not be decrypted under the\"\n echo \"[FATAL] current SELVA_AT_REST_KEY. This is a configuration problem on this host, not a\"\n echo \"[FATAL] fault in the new version — retrying the update will fail the same way.\"\n echo \"[FATAL] Re-enter the affected keys at /admin/compute, or restore the original\"\n echo \"[FATAL] SELVA_AT_REST_KEY, then re-run the update.\"\n else\n echo \"[FATAL] The health endpoint did not report a known cause. Inspect the body above and\"\n echo \"[FATAL] \\\\\\`pm2 logs selva-compute\\\\\\` for what the new version failed on.\"\n fi\n\n rm -f /tmp/selva-health.$$\nfi\n\nif [ -z \"$BEFORE\" ]; then\n echo \"[FATAL] No prior version recorded — cannot roll back automatically.\"\n echo \"[FATAL] EXIT trap will attempt to restart the current build anyway.\"\n exit 3\nfi\n\n# The failed version has already booted, so it may have rewritten stored data in\n# a format $BEFORE cannot read. Rolling back is still the better outcome; say so.\nAFTER_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$AFTER_FORMAT\" in ''|*[!0-9]*) AFTER_FORMAT=1 ;; esac\nif [ \"$AFTER_FORMAT\" -gt \"$INSTALLED_FORMAT\" ]; then\n echo \"[WARN] DATA_FORMAT_ROLLBACK: the failed version stores data format $AFTER_FORMAT; $BEFORE reads format $INSTALLED_FORMAT.\"\n echo \"[WARN] If Compute API keys fail to load after this rollback, re-enter them at /admin/compute.\"\nfi\n\necho \"[STEP] Rolling back @selvajs/selva to $BEFORE\"\n\"$PM2\" stop selva-compute >/dev/null 2>&1 || true\nwait_until_stopped >/dev/null 2>&1\n# Restore @selvajs/cli alongside the runtime: the forward step installs both at\n# the channel tag, so reverting only the runtime leaves a version pair that was\n# never released together.\nif ! npm install --save \"@selvajs/cli@$BEFORE\" \"@selvajs/selva@$BEFORE\"; then\n echo \"[FATAL] Rollback npm install failed — EXIT trap will retry restart.\"\n exit 4\nfi\n\nstart_app || true\nsleep 3\nROLLBACK_CODE=$(curl -sS -o /dev/null -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\nif [ \"$ROLLBACK_CODE\" = \"200\" ]; then\n echo \"[DONE] Rolled back to $BEFORE — previous version is online\"\n exit 5\nfi\n\necho \"[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)\"\necho \"[FATAL] Manual recovery required. Check: pm2 logs selva-compute\"\nexit 6\n`;\n}\n\n// Selva self-updates as a CLI-scaffolded npm deployment: the deployment dir\n// holds a package.json that depends on @selvajs/selva, and update means\n// `npm install @selvajs/*@<tag>` + pm2 restart. Deployment-dir detection\n// (cwd-upward probe, `INSTALL_DIR` override) lives in `selfUpdate.server.ts`,\n// shared with the outcome reconciler and the log path.\nexport type UpdatePlan = { cwd: string; args: string[] };\n\n// Only the CLI and the runtime move. Provider code is bundled into\n// @selvajs/selva; @selvajs/supabase-provider carries just the migration SQL,\n// which the operator installs and pushes before updating.\n//\n// `npm install` pins to the channel's dist-tag rather than using `npm\n// update`, because `update` only ever moves FORWARD within the installed\n// semver range — it can't switch dist-tags or DOWNGRADE. Pinning to @latest /\n// @beta makes one command serve every transition: forward stable bumps,\n// beta→newer-beta, and the revert case (beta→stable lands on an older version).\n//\n// --save persists the resolved version into package.json so the next plain\n// install is reproducible; --prefer-online forces npm to revalidate cached\n// packuments against the registry — without it, npm's packument cache (5+\n// min TTL) can silently no-op right after publish.\nexport function npmInstallArgs(channel: ReleaseChannel): string[] {\n\tconst tag = channelTag(channel);\n\treturn ['install', '--save', '--prefer-online', `@selvajs/cli@${tag}`, `@selvajs/selva@${tag}`];\n}\n\nexport function detectUpdatePlan(\n\tenv: Record<string, string | undefined>,\n\tchannel: ReleaseChannel\n): UpdatePlan | null {\n\tconst dir = findDeploymentDir(env);\n\treturn dir ? { cwd: dir, args: npmInstallArgs(channel) } : null;\n}\n","import { spawn } from 'child_process';\nimport { join } from 'path';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { env } from '#lib/server/env.js';\nimport { json } from '@sveltejs/kit';\nimport { actorFrom } from '@selvajs/platform';\nimport type { RequestHandler } from './$types';\nimport { requirePermission } from '#lib/server/access.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\nimport { checkForUpdate } from '#lib/server/updateCheck.server.js';\nimport { readChannel, channelTag } from '#lib/server/releaseChannel.server.js';\nimport { getEventSink, getErrorReporter } from '#lib/server/providers.server.js';\nimport {\n\tfindDeploymentDir,\n\tstartUpdateOutcomeReconciler,\n\tupdateLogPath,\n\tupdateStatePath,\n\ttype PendingUpdateState\n} from '#lib/server/selfUpdate.server.js';\nimport {\n\treadRuntimeVersion,\n\tbuildLauncher,\n\tbuildNpmRunnerScript,\n\tdetectUpdatePlan\n} from '#lib/server/updateRunner.server.js';\n\n// Where the bash wrapper mirrors all script output (`updateLogPath` — in the\n// deployment dir so it survives reboots, audit O2). The SSE stream dies the\n// moment `pm2 stop selva-compute` succeeds (selva-compute IS the SSE server),\n// so the frontend loses visibility into everything that happens after — npm\n// update output, pm2 start result, health-probe results, rollback decisions.\n// The script keeps writing to this file regardless. Once the new selva-compute\n// process is back up, the frontend polls GET on this same route to fetch the\n// full log and reveal what happened during the blackout. One log per update —\n// the wrapper truncates at start, so we never carry stale content forward.\n// The runner's `[EXIT] code=N` marker in the same log also drives the\n// post-restart audit-event reconciliation (`selfUpdate.server.ts`).\n\n// Strip ANSI escape codes from terminal output\nfunction stripAnsi(str: string): string {\n\t// eslint-disable-next-line no-control-regex\n\treturn str.replace(/\\x1B\\[[0-9;]*[mGKHF]/g, '');\n}\n\n// POST - Run update and stream output via Server-Sent Events.\n//\n// Runs `npm update @selvajs/*` then restarts via ecosystem.config.cjs. The\n// runner script handles stop / update / start / health-probe / rollback with\n// an EXIT trap that keeps the app online no matter how it exits.\nexport const POST: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst channel = readChannel();\n\tconst plan = detectUpdatePlan(env, channel);\n\tif (!plan) {\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror:\n\t\t\t\t\t\"Couldn't determine how to update this deployment. \" +\n\t\t\t\t\t'Expected node_modules/@selvajs/selva (CLI scaffold) in the cwd ' +\n\t\t\t\t\t'or a parent directory.'\n\t\t\t}),\n\t\t\t{ status: 500, headers: { 'Content-Type': 'application/json' } }\n\t\t);\n\t}\n\n\t// Capture the runtime version BEFORE we touch anything, so we can:\n\t// (a) detect a no-op update and warn, (b) roll back to the prior version\n\t// if the new process fails to come up healthy.\n\tconst versionBefore = readRuntimeVersion(plan.cwd);\n\tconst actorId = locals.ctx ? actorFrom(locals.ctx) : 'system';\n\n\t// Audit trail (O2): `started` now; the terminal event is emitted by the\n\t// outcome reconciler after the app restarts (this process is killed\n\t// mid-update). The state file is the reconciler's emission token.\n\tconst pending: PendingUpdateState = {\n\t\tstartedAt: new Date().toISOString(),\n\t\tactorId,\n\t\tchannel,\n\t\tfromVersion: versionBefore\n\t};\n\ttry {\n\t\twriteFileSync(updateStatePath(plan.cwd), JSON.stringify(pending, null, '\\t'));\n\t} catch (err) {\n\t\tlocals.log.error('Could not persist pending-update state', {\n\t\t\tcomponent: 'selfUpdate',\n\t\t\terr: renderThrown(err)\n\t\t});\n\t}\n\tawait getEventSink().emit({\n\t\ttype: 'system.update.started',\n\t\tchannel,\n\t\tfromVersion: versionBefore,\n\t\tactorId\n\t});\n\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tconst encoder = new TextEncoder();\n\n\t\t\tfunction sendEvent(type: string, data: Record<string, unknown>) {\n\t\t\t\tconst message = `data: ${JSON.stringify({ type, ...data })}\\n\\n`;\n\t\t\t\tcontroller.enqueue(encoder.encode(message));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Prelude lines are passed to the bash wrapper rather than\n\t\t\t\t// sendEvent'd directly so they end up in both the SSE stream\n\t\t\t\t// (via bash stdout) AND the log file (via tee). Without this,\n\t\t\t\t// the frontend's blackout-recovery file fetch would clobber\n\t\t\t\t// these lines when it replaces its buffer with the file content.\n\t\t\t\tconst prelude = [\n\t\t\t\t\t`[INFO] Updating deployment (cwd: ${plan.cwd}, channel: ${channel})`,\n\t\t\t\t\t...(versionBefore ? [`[INFO] Current @selvajs/selva: ${versionBefore}`] : [])\n\t\t\t\t];\n\n\t\t\t\t// Spawn the launcher detached. The launcher writes the actual\n\t\t\t\t// runner script to disk, daemonizes it (setsid + & + exit),\n\t\t\t\t// and quits — leaving the runner with PPID=1 so PM2's tree-kill\n\t\t\t\t// of selva-compute can't reach it. See buildLauncher for the\n\t\t\t\t// full rationale.\n\t\t\t\t//\n\t\t\t\t// The runner is buildNpmRunnerScript — pre-flights the version\n\t\t\t\t// check, then stop / npm update / start / health probe /\n\t\t\t\t// rollback, with an EXIT trap that ensures the app is online no\n\t\t\t\t// matter how the script exits.\n\t\t\t\tconst runnerScript = buildNpmRunnerScript(\n\t\t\t\t\tplan.args,\n\t\t\t\t\tversionBefore,\n\t\t\t\t\tjoin(plan.cwd, 'ecosystem.config.cjs'),\n\t\t\t\t\tchannelTag(channel)\n\t\t\t\t);\n\t\t\t\tconst cmd = 'bash';\n\t\t\t\tconst args = ['-c', buildLauncher(runnerScript, updateLogPath(plan.cwd), prelude)];\n\n\t\t\t\t// Prepend the deployment's node_modules/.bin to PATH so the bash\n\t\t\t\t// script finds the project-local pm2 (and any other tooling\n\t\t\t\t// installed as a deployment dependency). Without this the script\n\t\t\t\t// inherits the SvelteKit process's PATH, which on most servers\n\t\t\t\t// doesn't include node_modules/.bin — so `pm2` resolves to\n\t\t\t\t// whatever's globally installed, or fails outright if no global\n\t\t\t\t// pm2 exists. Both are wrong: we want the project-local pm2 so\n\t\t\t\t// daemon and CLI stay aligned. Mirrors the local-only resolution\n\t\t\t\t// in @selvajs/cli's pm2Bin().\n\t\t\t\tconst localBin = join(plan.cwd, 'node_modules', '.bin');\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: plan.cwd,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tPATH: `${localBin}:${process.env.PATH ?? ''}`,\n\n\t\t\t\t\t\tHOME: process.env.HOME,\n\t\t\t\t\t\tINSTALL_DIR: plan.cwd\n\t\t\t\t\t},\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: ['ignore', 'pipe', 'pipe']\n\t\t\t\t});\n\t\t\t\tchild.unref();\n\n\t\t\t\t// Covers the outcomes that DON'T restart this process (pre-flight\n\t\t\t\t// \"already up to date\", early failures): this process is still\n\t\t\t\t// alive to reconcile them. A real update kills this process; the\n\t\t\t\t// restarted one re-arms the reconciler from hooks.server.ts.\n\t\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\t\tdeploymentDir: plan.cwd,\n\t\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t\t});\n\n\t\t\t\t// Kill the process if it runs longer than 15 minutes.\n\t\t\t\t// The child is detached (its own process group), so signal the\n\t\t\t\t// whole group via negative pid — otherwise descendants (pnpm,\n\t\t\t\t// node, pm2) outlive the bash wrapper.\n\t\t\t\tconst timeout = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (child.pid) process.kill(-child.pid, 'SIGTERM');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// group already gone — nothing to do\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendEvent('log', { data: '[FATAL] Update timed out after 15 minutes' });\n\t\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t},\n\t\t\t\t\t15 * 60 * 1000\n\t\t\t\t);\n\n\t\t\t\t// Stream stdout\n\t\t\t\tlet restarting = false;\n\t\t\t\tchild.stdout.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\t// Detect both stopProcessId (pm2 restart) and restartProcessId (pm2 reload)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!restarting &&\n\t\t\t\t\t\t\t\t(clean.includes('Applying action stopProcessId') ||\n\t\t\t\t\t\t\t\t\tclean.includes('Applying action restartProcessId'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\trestarting = true;\n\t\t\t\t\t\t\t\tsendEvent('restarting', { data: clean });\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsendEvent('log', { data: clean });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Stream stderr\n\t\t\t\tchild.stderr.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\tsendEvent('log', { data: `[ERROR] ${clean}` });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Handle process exit\n\t\t\t\tchild.on('close', (code) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('exit', { code: code ?? -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\n\t\t\t\t// Handle errors\n\t\t\t\tchild.on('error', (err) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('log', { data: `[FATAL] ${err.message}` });\n\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tsendEvent('log', { data: `[FATAL] Failed to spawn process: ${err}` });\n\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}\n\t});\n\n\treturn new Response(stream, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive'\n\t\t}\n\t});\n};\n\n// GET — two jobs, selected by query param:\n//\n// ?check=1 → query the npm registry and report whether a newer\n// @selvajs/selva is published. JSON: { current, latest,\n// updateAvailable }. The admin page calls this on load to show\n// an \"update available\" badge. Degrades gracefully: if the\n// registry is unreachable, latest is null and updateAvailable\n// is false (we never block the page on npm).\n//\n// (default) → read the tee'd update log so the frontend can recover the\n// chunk of output that happened during the SSE blackout (between\n// `pm2 stop` killing this process and the new selva-compute\n// coming back online). Empty body if no update has run yet.\n// Polled by the admin UI during the post-restart wait.\nexport const GET: RequestHandler = async ({ locals, url, fetch }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tif (url.searchParams.get('check') !== null) {\n\t\treturn json(await checkForUpdate(fetch, readChannel()), {\n\t\t\theaders: { 'Cache-Control': 'no-store' }\n\t\t});\n\t}\n\n\tlet body = '';\n\ttry {\n\t\tbody = readFileSync(updateLogPath(findDeploymentDir(env)), 'utf8');\n\t} catch {\n\t\t// Log doesn't exist (no update has run yet). Empty body is correct —\n\t\t// the frontend treats no content as \"nothing to show yet\".\n\t}\n\treturn new Response(body, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/plain; charset=utf-8',\n\t\t\t'Cache-Control': 'no-store'\n\t\t}\n\t});\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,KAAiC;CACnE,IAAI;EACH,MAAM,MAAM,KAAK,MAChB,aAAa,KAAK,KAAK,gBAAgB,YAAY,SAAS,cAAc,GAAG,MAAM,CACpF;EACA,OAAO,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU,KAAA;CACxD,QAAQ;EACP;CACD;AACD;AAKA,SAAgB,WAAW,GAAmB;CAC7C,OAAO,IAAI,EAAE,QAAQ,MAAM,OAAO,EAAE;AACrC;AAoBA,SAAgB,cACf,cACA,SACA,UAAoB,CAAC,GACZ;CACT,MAAM,SAAS,QAAQ,KAAK,SAAS,QAAQ,WAAW,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;CAG1E,OAAO;UACE,WAAW,OAAO,EAAE;;;;;;EAM5B,aAAa;;;;;;EAMb,OAAO;;;;;;;;;;;;;;;;AAgBT;AAyBA,SAAgB,qBACf,SACA,eACA,eACA,KACS;CACT,MAAM,aAAa,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG;CAY/D,OAAO;;SATQ,WAAW,iBAAiB,EAWnC,EAAO;YAVG,WAAW,aAWlB,EAAU;MALL,WAAW,GAMtB,EAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AC;EACF,SAAS,KAAK;GACb,UAAU,OAAO,EAAE,MAAM,oCAAoC,MAAM,CAAC;GACpE,UAAU,QAAQ,EAAE,MAAM,GAAG,CAAC;GAC9B,WAAW,MAAM;EAClB;CACD,EACD,CAAC;CAED,OAAO,IAAI,SAAS,QAAQ,EAC3B,SAAS;EACR,gBAAgB;EAChB,iBAAiB;EACjB,YAAY;CACb,EACD,CAAC;AACF;AAgBA,IAAa,MAAsB,OAAO,EAAE,QAAQ,KAAK,YAAY;CACpE,kBAAkB,QAAQ,gBAAgB;CAE1C,IAAI,IAAI,aAAa,IAAI,OAAO,MAAM,MACrC,OAAO,KAAK,MAAM,eAAe,OAAO,YAAY,CAAC,GAAG,EACvD,SAAS,EAAE,iBAAiB,WAAW,EACxC,CAAC;CAGF,IAAI,OAAO;CACX,IAAI;EACH,OAAOC,eAAa,cAAc,kBAAkB,GAAG,CAAC,GAAG,MAAM;CAClE,QAAQ,CAGR;CACA,OAAO,IAAI,SAAS,MAAM,EACzB,SAAS;EACR,gBAAgB;EAChB,iBAAiB;CAClB,EACD,CAAC;AACF"}
@@ -1,4 +1,4 @@
1
- import { U as actorFrom, g as getPermissionStore, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../../chunks/providers.server.js";
1
+ import { K as actorFrom, g as getPermissionStore, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../../chunks/providers.server.js";
2
2
  import { b as requireManageInstanceUsers, k as ApiErrorCode, r as assertCanGrantPlatformPermissions } from "../../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../../chunks/context.js";
4
4
  import { U as requireParams, z as parseBody } from "../../../../../../chunks/api.js";
@@ -1,4 +1,4 @@
1
- import { T as providers, U as actorFrom, r as getAuthProvider, u as getEventSink } from "../../../../../../../chunks/providers.server.js";
1
+ import { K as actorFrom, T as providers, r as getAuthProvider, u as getEventSink } from "../../../../../../../chunks/providers.server.js";
2
2
  import { b as requireManageInstanceUsers, k as ApiErrorCode } from "../../../../../../../chunks/access.js";
3
3
  import { U as requireParams } from "../../../../../../../chunks/api.js";
4
4
  import { J as revokeUserApiTokens } from "../../../../../../../chunks/handlers.js";
@@ -1,4 +1,4 @@
1
- import { U as actorFrom, g as getPermissionStore, h as getOrganizationProvider, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../chunks/providers.server.js";
1
+ import { K as actorFrom, g as getPermissionStore, h as getOrganizationProvider, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../chunks/providers.server.js";
2
2
  import { b as requireManageInstanceUsers, k as ApiErrorCode, r as assertCanGrantPlatformPermissions } from "../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../chunks/context.js";
4
4
  import { z as parseBody } from "../../../../../chunks/api.js";
@@ -1,4 +1,4 @@
1
- import { B as classifyAssetPath, G as definitionPaths, x as getStorageProvider } from "../../../../../chunks/providers.server.js";
1
+ import { J as definitionPaths, U as classifyAssetPath, x as getStorageProvider } from "../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, n as accessDepsFromConfig } from "../../../../../chunks/access.js";
3
3
  import { t as COVER_IMAGE_CONTENT_TYPES } from "../../../../../chunks/types2.js";
4
4
  import { r as GuidSchema } from "../../../../../chunks/schemas.js";
@@ -1,13 +1,18 @@
1
+ import { L as respondWithKeepalive, z as wantsKeepalive } from "../../../../../chunks/providers.server.js";
1
2
  import { k as ApiErrorCode } from "../../../../../chunks/access.js";
2
3
  import { g as SolveModeSchema } from "../../../../../chunks/api.js";
3
- import { t as apiError } from "../../../../../chunks/api-errors.js";
4
- import { n as COMPUTE_REQUEST_MAX_BYTES } from "../../../../../chunks/computeLimits.js";
4
+ import { n as errorResponse, t as apiError } from "../../../../../chunks/api-errors.js";
5
+ import { a as computeRequestCap } from "../../../../../chunks/engine.server.js";
5
6
  import { l as requireMaxBodySize } from "../../../../../chunks/admin-auth.server.js";
6
7
  import { n as tryResolveShareToken } from "../../../../../chunks/resolve.server.js";
7
8
  import { n as runSolve, t as mapSolveError } from "../../../../../chunks/solve.server.js";
8
9
  // src/routes/api/v1/compute/+server.ts
9
- var POST = async ({ request, locals, url }) => {
10
- requireMaxBodySize(request, COMPUTE_REQUEST_MAX_BYTES);
10
+ var POST = (event) => {
11
+ if (!wantsKeepalive(event.request)) return solve(event);
12
+ return respondWithKeepalive(solve(event).catch((err) => errorResponse(err, event.locals.log)));
13
+ };
14
+ async function solve({ request, locals, url }) {
15
+ requireMaxBodySize(request, computeRequestCap());
11
16
  const loadStart = performance.now();
12
17
  const prepMarks = [];
13
18
  let prevMark = performance.now();
@@ -58,7 +63,7 @@ var POST = async ({ request, locals, url }) => {
58
63
  } catch (err) {
59
64
  mapSolveError(err, locals);
60
65
  }
61
- };
66
+ }
62
67
  export { POST };
63
68
 
64
69
  //# sourceMappingURL=_server.ts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/v1/compute/+server.ts"],"sourcesContent":["import type { RequestHandler } from './$types';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { COMPUTE_REQUEST_MAX_BYTES } from '#lib/server/computeLimits.js';\nimport { requireMaxBodySize } from '#lib/server/admin-auth.server.js';\nimport { tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { runSolve, mapSolveError, type SolveAccess } from '#lib/server/compute/solve.server.js';\nimport { SolveModeSchema } from '@selvajs/server/api';\n\ninterface ComputeRequest {\n\t/** Read for a remote `definitionUrl` only: a stored definition's inputs come from its schema. */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tdefinitionUrl: string;\n\t/** Spec §6 channel selector. Defaults to 'live'. 'draft' requires editor. */\n\tchannel?: 'live' | 'draft';\n\t/**\n\t * Explicit version pick (versioning tab \"Run\"). Solves this exact version\n\t * instead of the channel pointer; editor-only, never share-token accessible.\n\t */\n\tversionId?: string;\n\t/** The caller's open live-event stream; see `SolveParams.streamId`. */\n\tstreamId?: string;\n\t/** See `SolveBodySchema.mode`. */\n\tmode?: string;\n}\n\n// The URL-addressed solve: takes an arbitrary `definitionUrl`, and is the only\n// route that accepts a share token. The solve mechanics it shares with\n// `/api/v1/definitions/{guid}/solve` live in `solve.server.ts`; what stays here\n// is the body shape and the share-token branch, which must NOT reach the\n// definition-addressed route.\n\nexport const POST: RequestHandler = async ({ request, locals, url }) => {\n\t// Reject oversized payloads before buffering.\n\trequireMaxBodySize(request, COMPUTE_REQUEST_MAX_BYTES);\n\n\t// DEBUG (SELVA_FLAG_COMPUTE_DEBUG): start of server-side work. The solve metric's\n\t// `durationMs` wraps ONLY scheduler.solve, so everything before it (auth, DB reads,\n\t// definition fetch, input tree build) and the response serialization after it are\n\t// otherwise invisible. `runSolve` continues these marks and logs the breakdown.\n\tconst loadStart = performance.now();\n\tconst prepMarks: [string, number][] = [];\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\ttry {\n\t\tconst body: ComputeRequest = await request.json();\n\t\tmark('body');\n\n\t\tconst { inputs, values } = body;\n\t\tconst definitionUrl = body.definitionUrl;\n\t\tconst channel: 'live' | 'draft' = body.channel ?? 'live';\n\t\tconst explicitVersionId = body.versionId ?? null;\n\n\t\tif (!values || !definitionUrl) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t'Missing required fields: values or definitionUrl'\n\t\t\t);\n\t\t}\n\t\tconst mode = SolveModeSchema.default('full').safeParse(body.mode);\n\t\tif (!mode.success) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid mode: ${String(body.mode)}. Must be 'preview' or 'full'.`\n\t\t\t);\n\t\t}\n\t\tif (channel !== 'live' && channel !== 'draft') {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid channel: ${channel}. Must be 'live' or 'draft'.`\n\t\t\t);\n\t\t}\n\n\t\t// Share-link tokens (spec §7); null for remote definitions or no token.\n\t\tconst isLocal = definitionUrl.startsWith('local:');\n\t\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\t\t// Explicit-version solves are editor-only, so don't resolve a share token\n\t\t// for them — force the logged-in editor gate instead.\n\t\tconst sharedAccess =\n\t\t\tisLocal && guid && !explicitVersionId\n\t\t\t\t? await tryResolveShareToken(request, url, guid, channel, { requireSolve: true })\n\t\t\t\t: null;\n\t\tmark('shareToken');\n\n\t\tif (!sharedAccess && (!locals.ctx || !locals.user)) {\n\t\t\tapiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\t\t}\n\n\t\t// Rate-limit bucket per caller: `share:{linkId}` for token solves so an\n\t\t// anonymous crowd on one public link can't drain the owner's budget.\n\t\tconst access: SolveAccess = sharedAccess\n\t\t\t? {\n\t\t\t\t\tkind: 'share',\n\t\t\t\t\tctx: sharedAccess.ctx,\n\t\t\t\t\tlink: sharedAccess.link,\n\t\t\t\t\trateLimitKey: `share:${sharedAccess.link.id}`\n\t\t\t\t}\n\t\t\t: { kind: 'user', ctx: locals.ctx!, rateLimitKey: `user:${locals.user!.id}` };\n\n\t\treturn await runSolve({\n\t\t\taccess,\n\t\t\tdefinitionUrl,\n\t\t\tinputs,\n\t\t\tvalues,\n\t\t\tchannel,\n\t\t\tversionId: explicitVersionId,\n\t\t\trequest,\n\t\t\tlocals,\n\t\t\tloadStart,\n\t\t\tprepMarks,\n\t\t\tstreamId: typeof body.streamId === 'string' ? body.streamId : null,\n\t\t\tsolveMode: mode.data\n\t\t});\n\t} catch (err) {\n\t\tmapSolveError(err, locals);\n\t}\n};\n"],"mappings":";;;;;;;;AAgCA,IAAa,OAAuB,OAAO,EAAE,SAAS,QAAQ,UAAU;CAEvE,mBAAmB,SAAS,yBAAyB;CAMrD,MAAM,YAAY,YAAY,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;GACX;GACA;GACA;GACA;GACA,UAAU,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;GAC9D,WAAW,KAAK;EACjB,CAAC;CACF,SAAS,KAAK;EACb,cAAc,KAAK,MAAM;CAC1B;AACD"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/v1/compute/+server.ts"],"sourcesContent":["import type { RequestEvent, RequestHandler } from './$types';\nimport { apiError, ApiErrorCode, errorResponse } from '#lib/server/api-errors.js';\nimport { computeRequestCap } from '#lib/server/compute/engine.server.js';\nimport { requireMaxBodySize } from '#lib/server/admin-auth.server.js';\nimport { tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { runSolve, mapSolveError, type SolveAccess } from '#lib/server/compute/solve.server.js';\nimport { SolveModeSchema } from '@selvajs/server/api';\nimport { respondWithKeepalive, wantsKeepalive } from '@selvajs/solve/server';\n\ninterface ComputeRequest {\n\t/** Read for a remote `definitionUrl` only: a stored definition's inputs come from its schema. */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tdefinitionUrl: string;\n\t/** Spec §6 channel selector. Defaults to 'live'. 'draft' requires editor. */\n\tchannel?: 'live' | 'draft';\n\t/**\n\t * Explicit version pick (versioning tab \"Run\"). Solves this exact version\n\t * instead of the channel pointer; editor-only, never share-token accessible.\n\t */\n\tversionId?: string;\n\t/** The caller's open live-event stream; see `SolveParams.streamId`. */\n\tstreamId?: string;\n\t/** See `SolveBodySchema.mode`. */\n\tmode?: string;\n}\n\n// The URL-addressed solve: takes an arbitrary `definitionUrl`, and is the only\n// route that accepts a share token. The solve mechanics it shares with\n// `/api/v1/definitions/{guid}/solve` live in `solve.server.ts`; what stays here\n// is the body shape and the share-token branch, which must NOT reach the\n// definition-addressed route.\n//\n// The web app asks for keep-alive, so a solve longer than the reverse proxy's read timeout\n// still lands. Errors then travel inside the 200, which is why they become responses here.\n\nexport const POST: RequestHandler = (event) => {\n\tif (!wantsKeepalive(event.request)) return solve(event);\n\treturn respondWithKeepalive(solve(event).catch((err) => errorResponse(err, event.locals.log)));\n};\n\nasync function solve({ request, locals, url }: RequestEvent): Promise<Response> {\n\t// Reject oversized payloads before buffering.\n\trequireMaxBodySize(request, computeRequestCap());\n\n\t// DEBUG (SELVA_FLAG_COMPUTE_DEBUG): start of server-side work. The solve metric's\n\t// `durationMs` wraps ONLY scheduler.solve, so everything before it (auth, DB reads,\n\t// definition fetch, input tree build) and the response serialization after it are\n\t// otherwise invisible. `runSolve` continues these marks and logs the breakdown.\n\tconst loadStart = performance.now();\n\tconst prepMarks: [string, number][] = [];\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\ttry {\n\t\tconst body: ComputeRequest = await request.json();\n\t\tmark('body');\n\n\t\tconst { inputs, values } = body;\n\t\tconst definitionUrl = body.definitionUrl;\n\t\tconst channel: 'live' | 'draft' = body.channel ?? 'live';\n\t\tconst explicitVersionId = body.versionId ?? null;\n\n\t\tif (!values || !definitionUrl) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t'Missing required fields: values or definitionUrl'\n\t\t\t);\n\t\t}\n\t\tconst mode = SolveModeSchema.default('full').safeParse(body.mode);\n\t\tif (!mode.success) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid mode: ${String(body.mode)}. Must be 'preview' or 'full'.`\n\t\t\t);\n\t\t}\n\t\tif (channel !== 'live' && channel !== 'draft') {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid channel: ${channel}. Must be 'live' or 'draft'.`\n\t\t\t);\n\t\t}\n\n\t\t// Share-link tokens (spec §7); null for remote definitions or no token.\n\t\tconst isLocal = definitionUrl.startsWith('local:');\n\t\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\t\t// Explicit-version solves are editor-only, so don't resolve a share token\n\t\t// for them — force the logged-in editor gate instead.\n\t\tconst sharedAccess =\n\t\t\tisLocal && guid && !explicitVersionId\n\t\t\t\t? await tryResolveShareToken(request, url, guid, channel, { requireSolve: true })\n\t\t\t\t: null;\n\t\tmark('shareToken');\n\n\t\tif (!sharedAccess && (!locals.ctx || !locals.user)) {\n\t\t\tapiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\t\t}\n\n\t\t// Rate-limit bucket per caller: `share:{linkId}` for token solves so an\n\t\t// anonymous crowd on one public link can't drain the owner's budget.\n\t\tconst access: SolveAccess = sharedAccess\n\t\t\t? {\n\t\t\t\t\tkind: 'share',\n\t\t\t\t\tctx: sharedAccess.ctx,\n\t\t\t\t\tlink: sharedAccess.link,\n\t\t\t\t\trateLimitKey: `share:${sharedAccess.link.id}`\n\t\t\t\t}\n\t\t\t: { kind: 'user', ctx: locals.ctx!, rateLimitKey: `user:${locals.user!.id}` };\n\n\t\treturn await runSolve({\n\t\t\taccess,\n\t\t\tdefinitionUrl,\n\t\t\tinputs,\n\t\t\tvalues,\n\t\t\tchannel,\n\t\t\tversionId: explicitVersionId,\n\t\t\trequest,\n\t\t\tlocals,\n\t\t\tloadStart,\n\t\t\tprepMarks,\n\t\t\tstreamId: typeof body.streamId === 'string' ? body.streamId : null,\n\t\t\tsolveMode: mode.data\n\t\t});\n\t} catch (err) {\n\t\tmapSolveError(err, locals);\n\t}\n}\n"],"mappings":";;;;;;;;;AAoCA,IAAa,QAAwB,UAAU;CAC9C,IAAI,CAAC,eAAe,MAAM,OAAO,GAAG,OAAO,MAAM,KAAK;CACtD,OAAO,qBAAqB,MAAM,KAAK,CAAC,CAAC,OAAO,QAAQ,cAAc,KAAK,MAAM,OAAO,GAAG,CAAC,CAAC;AAC9F;AAEA,eAAe,MAAM,EAAE,SAAS,QAAQ,OAAwC;CAE/E,mBAAmB,SAAS,kBAAkB,CAA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ACA;GACA;GACA;GACA;GACA,WAAW;GACX;GACA;GACA;GACA;GACA,UAAU,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;GAC9D,WAAW,KAAK;EACjB,CAAC;CACF,SAAS,KAAK;EACb,cAAc,KAAK,MAAM;CAC1B;AACD"}
@@ -1,12 +1,12 @@
1
1
  import { E as scoped, k as ApiErrorCode, l as requireCanCreateDefinition } from "../../../../../../chunks/access.js";
2
2
  import { N as assertScope } from "../../../../../../chunks/api.js";
3
- import { a as ComputeServerUnconfiguredError, i as postSchemaFormData, n as assertCamelCaseSchema, t as SchemaExtractionError } from "../../../../../../chunks/schema-extraction.js";
3
+ import { n as assertCamelCaseSchema, o as postSchemaFormData, t as SchemaExtractionError, u as ComputeServerUnconfiguredError } from "../../../../../../chunks/schema-extraction.js";
4
4
  import "../../../../../../chunks/compute.js";
5
5
  import "../../../../../../chunks/definitions.js";
6
6
  import { r as withApiRateLimit } from "../../../../../../chunks/sveltekit.js";
7
7
  import { t as apiError } from "../../../../../../chunks/api-errors.js";
8
8
  import { t as asHttpError } from "../../../../../../chunks/access2.server.js";
9
- import { a as MAX_DEFINITION_FILE_SIZE } from "../../../../../../chunks/computeLimits.js";
9
+ import { g as MAX_DEFINITION_FILE_SIZE } from "../../../../../../chunks/engine.server.js";
10
10
  import { t as serverResolver } from "../../../../../../chunks/serverResolver.server.js";
11
11
  import { l as requireMaxBodySize } from "../../../../../../chunks/admin-auth.server.js";
12
12
  // src/routes/api/v1/compute/schema/+server.ts
@@ -1,10 +1,10 @@
1
- import { P as acceptsGzip } from "../../../../../../../chunks/providers.server.js";
1
+ import { F as acceptsGzip } from "../../../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode } from "../../../../../../../chunks/access.js";
3
3
  import { C as idempotencyCallerId, E as runIdempotent, S as createApiIdempotencyStore, T as requestFingerprint, U as requireParams, h as SolveBodySchema, w as readIdempotencyKey, z as parseBody } from "../../../../../../../chunks/api.js";
4
4
  import { r as withApiRateLimit } from "../../../../../../../chunks/sveltekit.js";
5
- import { n as handleApiError, t as apiError } from "../../../../../../../chunks/api-errors.js";
5
+ import { r as handleApiError, t as apiError } from "../../../../../../../chunks/api-errors.js";
6
6
  import { i as requireCaller } from "../../../../../../../chunks/http2.js";
7
- import { n as COMPUTE_REQUEST_MAX_BYTES } from "../../../../../../../chunks/computeLimits.js";
7
+ import { p as COMPUTE_REQUEST_MAX_BYTES } from "../../../../../../../chunks/engine.server.js";
8
8
  import { l as requireMaxBodySize } from "../../../../../../../chunks/admin-auth.server.js";
9
9
  import { n as runSolve, t as mapSolveError } from "../../../../../../../chunks/solve.server.js";
10
10
  var solveIdempotencyStore = createApiIdempotencyStore(3e5);
@@ -6,7 +6,7 @@ import { r as GuidSchema } from "../../../chunks/schemas.js";
6
6
  import { s as resourceMetadataUrl } from "../../../chunks/oauth.js";
7
7
  import { i as oauthServer } from "../../../chunks/server2.js";
8
8
  import { t as publicUrl } from "../../../chunks/origin.js";
9
- import { i as getInputItems } from "../../../chunks/abort-Bfrdupaj.js";
9
+ import { o as getInputItems } from "../../../chunks/keepalive-vtcjhAV3.js";
10
10
  import { t as buildOpenApiDocument } from "../../../chunks/openapi.js";
11
11
  import { z } from "zod";
12
12
  import * as z$1 from "zod/v4";
@@ -20449,6 +20449,9 @@ function sleep(ms, signal) {
20449
20449
  function errorText(err) {
20450
20450
  return err instanceof Error ? err.message : String(err);
20451
20451
  }
20452
+ // ../mcp/src/app.ts
20453
+ /** The MIME type a client renders as an MCP App view rather than reading as text. */
20454
+ var MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
20452
20455
  // ../mcp/src/spec.ts
20453
20456
  var METHODS = /* @__PURE__ */ new Set([
20454
20457
  "get",
@@ -20659,6 +20662,7 @@ function createMcpServer(options) {
20659
20662
  const spec = indexOperations(options.openapi);
20660
20663
  const tools = resolveTools(options.tools, spec);
20661
20664
  for (const r of options.resources ?? []) checkCalls(`resource ${r.uri}`, r.calls, spec);
20665
+ checkViews(tools, options.resources ?? []);
20662
20666
  /** `visible` limits which tools this request sees; undefined means all of them. */
20663
20667
  function build(apiKey, fetch = options.fetch, visible) {
20664
20668
  const clientOptions = {
@@ -20668,6 +20672,12 @@ function createMcpServer(options) {
20668
20672
  };
20669
20673
  const keys = [apiKey, ...options.apiKey ? [options.apiKey] : []];
20670
20674
  const redact = (text) => keys.reduce((out, key) => out.split(key).join("[redacted]"), text);
20675
+ const redactValue = (value) => {
20676
+ if (typeof value === "string") return keys.some((k) => value.includes(k)) ? redact(value) : value;
20677
+ if (Array.isArray(value)) return value.map(redactValue);
20678
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k, v]) => [redact(k), redactValue(v)]));
20679
+ return value;
20680
+ };
20671
20681
  function toResult(out) {
20672
20682
  return {
20673
20683
  content: [{
@@ -20678,7 +20688,8 @@ function createMcpServer(options) {
20678
20688
  data,
20679
20689
  mimeType
20680
20690
  }))],
20681
- ...out.structured && { structuredContent: JSON.parse(redact(JSON.stringify(out.structured))) }
20691
+ ...out.structured && { structuredContent: JSON.parse(redact(JSON.stringify(out.structured))) },
20692
+ ...out.meta && { _meta: redactValue(out.meta) }
20682
20693
  };
20683
20694
  }
20684
20695
  function errorResult(text) {
@@ -20712,7 +20723,11 @@ function createMcpServer(options) {
20712
20723
  annotations: {
20713
20724
  title: def.title,
20714
20725
  ...annotations
20715
- }
20726
+ },
20727
+ ...def.ui && { _meta: {
20728
+ ui: def.ui,
20729
+ "ui/resourceUri": def.ui.resourceUri
20730
+ } }
20716
20731
  })) }));
20717
20732
  server.setRequestHandler("tools/call", async (req, ctx) => {
20718
20733
  const resolved = tools.get(req.params.name);
@@ -20760,27 +20775,30 @@ function createMcpServer(options) {
20760
20775
  ...ended,
20761
20776
  calls,
20762
20777
  argumentBytes: sizes(req.params.arguments),
20763
- responseBytes: result ? jsonLength(result.content) + jsonLength(result.structuredContent) : 0
20778
+ responseBytes: result ? jsonLength(result.content) + jsonLength(result.structuredContent) + jsonLength(result._meta) : 0
20764
20779
  });
20765
20780
  }
20766
20781
  });
20767
20782
  if (options.resources?.length) {
20768
20783
  const resources = options.resources;
20769
- server.setRequestHandler("resources/list", () => ({ resources: resources.map(({ uri, name, description, mimeType }) => ({
20784
+ server.setRequestHandler("resources/list", () => ({ resources: resources.map(({ uri, name, description, mimeType, meta }) => ({
20770
20785
  uri,
20771
20786
  name,
20772
20787
  description,
20773
- mimeType
20788
+ mimeType,
20789
+ ...meta && { _meta: meta }
20774
20790
  })) }));
20775
20791
  server.setRequestHandler("resources/read", async (req) => {
20776
20792
  const resource = resources.find((r) => r.uri === req.params.uri);
20777
20793
  if (!resource) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Unknown resource ${req.params.uri}`);
20778
20794
  const api = createApiClient(spec, clientOptions, new Set(resource.calls));
20779
20795
  const text = redact(await resource.read(api));
20796
+ const { uri, mimeType, meta } = resource;
20780
20797
  return { contents: [{
20781
- uri: resource.uri,
20782
- mimeType: resource.mimeType,
20783
- text
20798
+ uri,
20799
+ mimeType,
20800
+ text,
20801
+ ...meta && { _meta: meta }
20784
20802
  }] };
20785
20803
  });
20786
20804
  }
@@ -20980,6 +20998,16 @@ function resolveTools(defs, spec) {
20980
20998
  }
20981
20999
  return tools;
20982
21000
  }
21001
+ function checkViews(tools, resources) {
21002
+ const views = new Set(resources.filter((r) => r.mimeType === MCP_APP_MIME_TYPE).map((r) => r.uri));
21003
+ for (const { def } of tools.values()) if (def.ui && !views.has(def.ui.resourceUri)) throw new Error(`Tool ${def.name} shows ${def.ui.resourceUri}, which no appResource serves`);
21004
+ const all = [...tools.values()];
21005
+ const appOnly = (t) => t.def.ui?.visibility?.includes("model") === false;
21006
+ for (const parent of all.filter((t) => t.def.ui && !appOnly(t))) for (const child of all.filter((t) => appOnly(t) && t.def.ui.resourceUri === parent.def.ui.resourceUri)) {
21007
+ const missing = child.actions.filter((a) => !parent.actions.includes(a));
21008
+ if (missing.length) throw new Error(`App tool ${child.def.name} needs \`${missing.join("`, `")}\`, which ${parent.def.name} does not; a key that can call ${parent.def.name} could not load its view`);
21009
+ }
21010
+ }
20983
21011
  function checkCalls(owner, calls, spec) {
20984
21012
  for (const id of calls) {
20985
21013
  const op = spec.get(id);
@@ -21023,6 +21051,7 @@ function describe(err, hint) {
21023
21051
  ].join("\n");
21024
21052
  return err instanceof Error ? err.message : String(err);
21025
21053
  }
21054
+ new URL("../dist/views/solve.html", import.meta.url);
21026
21055
  // src/lib/server/mcp/tools.ts
21027
21056
  /**
21028
21057
  * Selva's MCP tools: find a definition, read its inputs, solve it, read back numbers,