@nimbus-sh/worker 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/cirrus-npm-cjs.generated.d.ts +1 -1
- package/dist/cirrus-npm-cjs.generated.js +1 -1
- package/dist/facets/cirrus-real.d.ts.map +1 -1
- package/dist/facets/cirrus-real.js +6 -5
- package/dist/facets/compose.d.ts +148 -0
- package/dist/facets/compose.d.ts.map +1 -0
- package/dist/facets/compose.js +146 -0
- package/dist/facets/durable-images.d.ts +9 -5
- package/dist/facets/durable-images.d.ts.map +1 -1
- package/dist/facets/durable-images.js +17 -7
- package/dist/facets/esbuild-bundle-pool.d.ts +49 -0
- package/dist/facets/esbuild-bundle-pool.d.ts.map +1 -0
- package/dist/facets/esbuild-bundle-pool.js +122 -0
- package/dist/facets/exec-telemetry.d.ts +8 -0
- package/dist/facets/exec-telemetry.d.ts.map +1 -1
- package/dist/facets/manager.d.ts +240 -109
- package/dist/facets/manager.d.ts.map +1 -1
- package/dist/facets/manager.js +677 -342
- package/dist/facets/process.d.ts +20 -16
- package/dist/facets/process.d.ts.map +1 -1
- package/dist/facets/process.js +59 -28
- package/dist/facets/real-vite-fs-shim.js +2 -2
- package/dist/facets/real-vite-hmr.d.ts +3 -1
- package/dist/facets/real-vite-hmr.d.ts.map +1 -1
- package/dist/facets/real-vite-hmr.js +18 -8
- package/dist/facets/vite-dev-server.d.ts +25 -47
- package/dist/facets/vite-dev-server.d.ts.map +1 -1
- package/dist/facets/vite-dev-server.js +185 -219
- package/dist/facets/wasm-image-digest.d.ts +25 -0
- package/dist/facets/wasm-image-digest.d.ts.map +1 -0
- package/dist/facets/wasm-image-digest.js +25 -0
- package/dist/facets/wasm-swap-registry.d.ts +51 -92
- package/dist/facets/wasm-swap-registry.d.ts.map +1 -1
- package/dist/facets/wasm-swap-registry.js +68 -227
- package/dist/facets/ws-terminal.d.ts +9 -31
- package/dist/facets/ws-terminal.d.ts.map +1 -1
- package/dist/facets/ws-terminal.js +58 -51
- package/dist/git/network-facet.d.ts.map +1 -1
- package/dist/git/network-facet.js +6 -5
- package/dist/hosted/commands.d.ts +12 -0
- package/dist/hosted/commands.d.ts.map +1 -0
- package/dist/hosted/commands.js +1658 -0
- package/dist/hosted/runtime.d.ts +114 -0
- package/dist/hosted/runtime.d.ts.map +1 -0
- package/dist/hosted/runtime.js +288 -0
- package/dist/hosted/services.d.ts +40 -0
- package/dist/hosted/services.d.ts.map +1 -0
- package/dist/hosted/services.js +512 -0
- package/dist/loaders/child-process/spawn-pool.d.ts +3 -2
- package/dist/loaders/child-process/spawn-pool.d.ts.map +1 -1
- package/dist/loaders/child-process/spawn-pool.js +3 -2
- package/dist/loaders/generated-workers.d.ts +2 -2
- package/dist/loaders/generated-workers.d.ts.map +1 -1
- package/dist/loaders/generated-workers.js +3 -3
- package/dist/loaders/npm-resolve-preamble.d.ts +3 -6
- package/dist/loaders/npm-resolve-preamble.d.ts.map +1 -1
- package/dist/loaders/npm-resolve-preamble.js +34 -108
- package/dist/node-shims-artifact.generated.js +3 -3
- package/dist/npm/install-batch-facet.d.ts +3 -2
- package/dist/npm/install-batch-facet.d.ts.map +1 -1
- package/dist/npm/install-batch-facet.js +45 -15
- package/dist/npm/installer.d.ts +22 -17
- package/dist/npm/installer.d.ts.map +1 -1
- package/dist/npm/installer.js +209 -193
- package/dist/npm/pre-bundle-facet.d.ts +1 -1
- package/dist/npm/pre-bundle-facet.d.ts.map +1 -1
- package/dist/npm/pre-bundle-facet.js +1 -1
- package/dist/npm/resolve-facet.d.ts +6 -0
- package/dist/npm/resolve-facet.d.ts.map +1 -1
- package/dist/npm/resolve-one-facet.d.ts +21 -20
- package/dist/npm/resolve-one-facet.d.ts.map +1 -1
- package/dist/npm/resolve-one-facet.js +85 -84
- package/dist/npm/semver.d.ts +59 -0
- package/dist/npm/semver.d.ts.map +1 -0
- package/dist/npm/semver.js +226 -0
- package/dist/router/remote-api.js +31 -1
- package/dist/runtime/bash-repl.d.ts +1 -1
- package/dist/runtime/bash-repl.d.ts.map +1 -1
- package/dist/runtime/bash-repl.js +38 -4
- package/dist/runtime/bun-runner.js +1 -1
- package/dist/runtime/html-entrypoint.d.ts +7 -0
- package/dist/runtime/html-entrypoint.d.ts.map +1 -1
- package/dist/runtime/html-entrypoint.js +18 -2
- package/dist/runtime/node-runner.d.ts +4 -1
- package/dist/runtime/node-runner.d.ts.map +1 -1
- package/dist/runtime/node-runner.js +9 -2
- package/dist/runtime/node-shims.d.ts.map +1 -1
- package/dist/runtime/node-shims.js +305 -29
- package/dist/runtime/opencode-facet-runner.js +16 -16
- package/dist/runtime/package-manager.d.ts +35 -122
- package/dist/runtime/package-manager.d.ts.map +1 -1
- package/dist/runtime/package-manager.js +61 -596
- package/dist/runtime/process-logs-api.d.ts +1 -1
- package/dist/runtime/process-logs-api.d.ts.map +1 -1
- package/dist/runtime/process-logs-api.js +1 -1
- package/dist/runtime/python-repl.d.ts +2 -1
- package/dist/runtime/python-repl.d.ts.map +1 -1
- package/dist/runtime/python-repl.js +82 -59
- package/dist/runtime/repl-session.d.ts +9 -47
- package/dist/runtime/repl-session.d.ts.map +1 -1
- package/dist/runtime/repl-session.js +105 -105
- package/dist/runtime/runtime-catalog.d.ts +13 -0
- package/dist/runtime/runtime-catalog.d.ts.map +1 -1
- package/dist/runtime/runtime-catalog.js +88 -0
- package/dist/session/agent.d.ts +1 -21
- package/dist/session/agent.d.ts.map +1 -1
- package/dist/session/ai.d.ts +5 -1
- package/dist/session/ai.d.ts.map +1 -1
- package/dist/session/ai.js +7 -0
- package/dist/session/helpers.d.ts +38 -0
- package/dist/session/helpers.d.ts.map +1 -1
- package/dist/session/helpers.js +76 -0
- package/dist/session/hibernation.d.ts +2 -1
- package/dist/session/hibernation.d.ts.map +1 -1
- package/dist/session/hibernation.js +7 -4
- package/dist/session/init-phases.d.ts +1 -1
- package/dist/session/init-phases.d.ts.map +1 -1
- package/dist/session/init-phases.js +2 -12
- package/dist/session/init.d.ts +15 -36
- package/dist/session/init.d.ts.map +1 -1
- package/dist/session/init.js +50 -2327
- package/dist/session/loopback.d.ts +2 -29
- package/dist/session/loopback.d.ts.map +1 -1
- package/dist/session/loopback.js +3 -27
- package/dist/session/nimbus-session.d.ts +77 -34
- package/dist/session/nimbus-session.d.ts.map +1 -1
- package/dist/session/nimbus-session.js +126 -514
- package/dist/session/npm-install-port.d.ts +18 -0
- package/dist/session/npm-install-port.d.ts.map +1 -0
- package/dist/session/npm-install-port.js +37 -0
- package/dist/session/port-capability.d.ts +44 -0
- package/dist/session/port-capability.d.ts.map +1 -1
- package/dist/session/port-capability.js +110 -0
- package/dist/session/programmatic.d.ts +36 -43
- package/dist/session/programmatic.d.ts.map +1 -1
- package/dist/session/programmatic.js +109 -115
- package/dist/session/routes.d.ts +30 -17
- package/dist/session/routes.d.ts.map +1 -1
- package/dist/session/routes.js +42 -131
- package/dist/session/rpc.d.ts +15 -15
- package/dist/session/rpc.d.ts.map +1 -1
- package/dist/session/rpc.js +98 -49
- package/dist/session/serving-port.d.ts +27 -0
- package/dist/session/serving-port.d.ts.map +1 -0
- package/dist/session/serving-port.js +27 -0
- package/dist/session/start-real-vite.d.ts +12 -0
- package/dist/session/start-real-vite.d.ts.map +1 -1
- package/dist/session/start-real-vite.js +4 -4
- package/dist/session/supervisor-op.d.ts +4 -4
- package/dist/session/supervisor-op.d.ts.map +1 -1
- package/dist/session/supervisor-op.js +24 -10
- package/dist/session/supervisor-rpc.d.ts +7 -7
- package/dist/session/supervisor-rpc.d.ts.map +1 -1
- package/dist/session/supervisor-rpc.js +4 -0
- package/dist/session/vite-command.d.ts +18 -0
- package/dist/session/vite-command.d.ts.map +1 -0
- package/dist/session/vite-command.js +609 -0
- package/dist/session/ws.d.ts +61 -0
- package/dist/session/ws.d.ts.map +1 -1
- package/dist/session/ws.js +122 -12
- package/dist/shell/npm-bin-entrypoints.d.ts +0 -35
- package/dist/shell/npm-bin-entrypoints.d.ts.map +1 -1
- package/dist/shell/npm-bin-entrypoints.js +12 -85
- package/dist/workspace-host.d.ts +6 -0
- package/dist/workspace-host.d.ts.map +1 -0
- package/dist/workspace-host.js +5 -0
- package/dist/workspace.d.ts +2 -0
- package/dist/workspace.d.ts.map +1 -0
- package/dist/workspace.js +1 -0
- package/package.json +34 -9
- package/public/_assets/runtime/{node-shims-9e1380d9ee430fcc.js → node-shims-8f8c64edd2a1f0f5.js} +305 -29
- package/public/index.html +1 -1
- package/scripts/bundle-facet-workers.mjs +1 -1
- package/scripts/bundle-npm-cjs.mjs +2 -2
- package/dist/facets/on-demand-bundle-gate.d.ts +0 -65
- package/dist/facets/on-demand-bundle-gate.d.ts.map +0 -1
- package/dist/facets/on-demand-bundle-gate.js +0 -125
- package/dist/npm/install-args.d.ts +0 -21
- package/dist/npm/install-args.d.ts.map +0 -1
- package/dist/npm/install-args.js +0 -70
- package/dist/npm/npm-log.d.ts +0 -31
- package/dist/npm/npm-log.d.ts.map +0 -1
- package/dist/npm/npm-log.js +0 -51
|
@@ -0,0 +1,1658 @@
|
|
|
1
|
+
import { Shell, createCurlCommand, createNpmCommand, NPM_VERSION, createTopCommand, createWatchCommand, createHelpCommand, rehydrateGlobalPackages } from '@nimbus-sh/core/substrate/lifo/index.js';
|
|
2
|
+
import { createKillCommand } from '@nimbus-sh/core/substrate/lifo/commands/system/kill.js';
|
|
3
|
+
import { textSink } from '@nimbus-sh/core/_shared/bytes.js';
|
|
4
|
+
import { CRED_KERNEL, requireVfsCred } from '@nimbus-sh/core/runtime/os-contracts.js';
|
|
5
|
+
import { EsbuildService } from '@nimbus-sh/core/runtime/esbuild-service.js';
|
|
6
|
+
import { runFresh } from '../runtime/node-runner.js';
|
|
7
|
+
import { runBunScript, BUN_VERSION } from '../runtime/bun-runner.js';
|
|
8
|
+
import { buildRuntimeHandler, resolveRuntimeScriptPath } from '@nimbus-sh/core/runtime/runtime-registry.js';
|
|
9
|
+
import { normalizeVfsPath, parentVfsPath, resolveVfsPath } from '@nimbus-sh/core/vfs/path.js';
|
|
10
|
+
import { NimbusWrangler } from '../wrangler/nimbus-wrangler.js';
|
|
11
|
+
import { filterWranglerFlags, detectBundlerBin, checkNodeModulesGuard, detectUnsupportedWranglerConfig, refusedNextSubcommand, NEXT_REFUSAL_MESSAGE } from '../session/helpers.js';
|
|
12
|
+
import { createViteCommand } from '../session/vite-command.js';
|
|
13
|
+
import { HeredocHandler, LineEditorExtender } from '@nimbus-sh/core/shell/features.js';
|
|
14
|
+
import { registerShellEntrypointCommands } from '@nimbus-sh/core/shell/shell-entrypoints.js';
|
|
15
|
+
import { makeChshCommand } from '@nimbus-sh/core/substrate/lifo/shell/default-shell.js';
|
|
16
|
+
import { installNpmBinFallbackResolver } from '../shell/npm-bin-entrypoints.js';
|
|
17
|
+
import { createNpmInstallPort } from '../session/npm-install-port.js';
|
|
18
|
+
import { createRuntimeCommandHintResolver } from '../runtime/package-manager.js';
|
|
19
|
+
import { rpcExposeApp, rpcListApps, rpcRemoveApp, rpcRotateLink } from '../session/programmatic.js';
|
|
20
|
+
import { listInstalledRuntimes } from '@nimbus-sh/core/runtime/installed-runtimes.js';
|
|
21
|
+
import { notifyTerminalEvent } from '../runtime/process-logs-api.js';
|
|
22
|
+
import { stripAnsi } from '@nimbus-sh/core/runtime/process-logs.js';
|
|
23
|
+
import { NODE_VERSION } from '@nimbus-sh/core/constants.js';
|
|
24
|
+
import { VITE_CONFIG_KEY } from '../session/keys.js';
|
|
25
|
+
import { HeadlessTerminal } from '@nimbus-sh/core/substrate/lifo/index.js';
|
|
26
|
+
import { makeNimbusVerbHandler } from '@nimbus-sh/core/runtime/nimbus-command.js';
|
|
27
|
+
export async function registerHostedCommands(self, workspace) {
|
|
28
|
+
const sqliteFs = workspace.vfs;
|
|
29
|
+
const kernelFs = sqliteFs.as(CRED_KERNEL);
|
|
30
|
+
const kernel = workspace.kernel;
|
|
31
|
+
const shell = workspace.shell;
|
|
32
|
+
const registry = workspace.registry;
|
|
33
|
+
const processRegistry = kernel.processRegistry;
|
|
34
|
+
const env = workspace.env;
|
|
35
|
+
const terminal = self.terminal;
|
|
36
|
+
if (!terminal)
|
|
37
|
+
throw new Error('runtime terminal is not initialized');
|
|
38
|
+
const facetMgr = self.ensureFacetManager().manager;
|
|
39
|
+
const runAsProcess = shell.getRunAsHost();
|
|
40
|
+
const commandIdentityFor = (pid) => ({
|
|
41
|
+
pid,
|
|
42
|
+
get cred() { return self.processes.cred(pid); },
|
|
43
|
+
setUmask: (mask) => self.processes.setUmask(pid, mask),
|
|
44
|
+
runAs: runAsProcess,
|
|
45
|
+
});
|
|
46
|
+
self._setCpRegistry(registry);
|
|
47
|
+
registry.register('chsh', makeChshCommand({
|
|
48
|
+
isBashInstalled: (home) => listInstalledRuntimes(sqliteFs, home).some((runtime) => runtime.name === 'bash'),
|
|
49
|
+
}));
|
|
50
|
+
// ── Git integration (isomorphic-git) ──
|
|
51
|
+
// ctx + env are passed for clone/fetch/pull which run in a facet to avoid
|
|
52
|
+
// exhausting the supervisor DO's CPU budget on large repos. The command
|
|
53
|
+
// module (+ its ~106 KB network-facet dependency) is loaded lazily on the
|
|
54
|
+
// first `git` invocation so it stays out of the cold script-eval graph.
|
|
55
|
+
registry.register('git', async (ctx) => {
|
|
56
|
+
const { runGitCommand } = await import('../git/commands.js');
|
|
57
|
+
return runGitCommand(ctx, sqliteFs, self.ctx, self.env);
|
|
58
|
+
});
|
|
59
|
+
// ── runtime package manager: `nimbus install` package manager + runner registry.
|
|
60
|
+
//
|
|
61
|
+
// 1. Register the clang-runner factory FIRST so the rehydration step
|
|
62
|
+
// below can re-bind `clang` / `wasm-ld` from an already-installed
|
|
63
|
+
// manifest.
|
|
64
|
+
// 2. Register the `nimbus` shell verb (install/uninstall/list/available).
|
|
65
|
+
// 3. Rehydrate any previously-installed runtimes from VFS so their
|
|
66
|
+
// bins reappear in the registry after DO eviction or WS reconnect.
|
|
67
|
+
workspace.runtimes.registerRunner('clang-runner', (manifest, installRoot, binName, binKind) => async (ctx) => {
|
|
68
|
+
const { makeClangRunnerFactory } = await import('@nimbus-sh/core/runtime/clang-runner.js');
|
|
69
|
+
const { facetHostForManager } = await import('../runtime/facet-loader-host.js');
|
|
70
|
+
return await makeClangRunnerFactory({ facets: facetHostForManager(facetMgr), vfs: sqliteFs })(manifest, installRoot, binName, binKind)(ctx);
|
|
71
|
+
});
|
|
72
|
+
// Pyodide v1 — Python 3.13 via the same R2-package-manager
|
|
73
|
+
// substrate that ships clang. Manifest entrypoints `python` and
|
|
74
|
+
// `python3` both bind to this factory; the runner ferries
|
|
75
|
+
// pyodide.asm.wasm via LOADER modules-map and pyodide.asm.js +
|
|
76
|
+
// python_stdlib.zip via the loader-pool context channel.
|
|
77
|
+
//
|
|
78
|
+
// REPL-W1: wrap the one-shot factory so `python` with NO args (and
|
|
79
|
+
// no flags that would consume args) drops into an interactive
|
|
80
|
+
// REPL. The wrap is purely additive — args-bearing invocations
|
|
81
|
+
// pass through to the existing handler unchanged.
|
|
82
|
+
workspace.runtimes.registerRunner('cpython-runner', (manifest, installRoot, binName, binKind) => async function pythonReplOrOneShot(ctx) {
|
|
83
|
+
const argv = ctx.args || [];
|
|
84
|
+
// No args at all → REPL session. Hand off to runPythonRepl
|
|
85
|
+
// which builds its own IsolatePool (separate from the
|
|
86
|
+
// one-shot dispatch's pool) and drives a ReplSession.
|
|
87
|
+
if (argv.length === 0 && terminal) {
|
|
88
|
+
const { runPythonRepl } = await import('../runtime/python-repl.js');
|
|
89
|
+
return await runPythonRepl({
|
|
90
|
+
facetMgr,
|
|
91
|
+
vfs: sqliteFs,
|
|
92
|
+
terminal: terminal,
|
|
93
|
+
installRoot,
|
|
94
|
+
manifest,
|
|
95
|
+
// REPL-R7-1: thread the shell so ReplSession can drain
|
|
96
|
+
// shell.pasteQueue on attach (multi-line WS frames like
|
|
97
|
+
// `python\nexit(7)` would otherwise drop the tail input).
|
|
98
|
+
shell: shell,
|
|
99
|
+
// The supervisor derives the write credential from this; without
|
|
100
|
+
// it the prompt cannot write to the session filesystem.
|
|
101
|
+
pid: ctx.pid,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
// Args present (one-shot mode: -c, script, -m, -). Fall through
|
|
105
|
+
// to the canonical handler (imported lazily on first use).
|
|
106
|
+
const { makeCPythonRunnerFactory } = await import('@nimbus-sh/core/runtime/cpython-runner.js');
|
|
107
|
+
const { facetHostForManager } = await import('../runtime/facet-loader-host.js');
|
|
108
|
+
const { cpythonResidentStart } = await import('../runtime/cpython-resident.js');
|
|
109
|
+
return await makeCPythonRunnerFactory({
|
|
110
|
+
facets: facetHostForManager(facetMgr),
|
|
111
|
+
vfs: sqliteFs,
|
|
112
|
+
startResident: cpythonResidentStart(facetMgr),
|
|
113
|
+
})(manifest, installRoot, binName, binKind)(ctx);
|
|
114
|
+
});
|
|
115
|
+
// Ruby v1 — Ruby 3.3.4 via ruby.wasm 2.9.3-2.9.4. Same architecture
|
|
116
|
+
// as python-runner: ruby+stdlib.wasm rides via LOADER modules-map,
|
|
117
|
+
// bootstrap runs at child-facet module-init time, per-call
|
|
118
|
+
// __rubyRun drives rb-eval-string-protect with a wrapper that
|
|
119
|
+
// catches SystemExit. See src/runtime/ruby-runner.ts +
|
|
120
|
+
//
|
|
121
|
+
// REPL Stream A: wrap the one-shot factory so `ruby` with NO args
|
|
122
|
+
// drops into an interactive REPL. The wrap is purely additive —
|
|
123
|
+
// args-bearing invocations pass through to the existing handler.
|
|
124
|
+
workspace.runtimes.registerRunner('ruby-runner', (manifest, installRoot, binName, binKind) => async function rubyReplOrOneShot(ctx) {
|
|
125
|
+
const argv = ctx.args || [];
|
|
126
|
+
if (argv.length === 0 && terminal) {
|
|
127
|
+
const { runRubyRepl } = await import('../runtime/ruby-repl.js');
|
|
128
|
+
return await runRubyRepl({
|
|
129
|
+
facetMgr,
|
|
130
|
+
vfs: sqliteFs,
|
|
131
|
+
terminal: terminal,
|
|
132
|
+
installRoot,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
const { makeRubyRunnerFactory } = await import('@nimbus-sh/core/runtime/ruby-runner.js');
|
|
136
|
+
const { facetHostForManager } = await import('../runtime/facet-loader-host.js');
|
|
137
|
+
const { rubyResidentStart } = await import('../runtime/ruby-resident.js');
|
|
138
|
+
return await makeRubyRunnerFactory({
|
|
139
|
+
facets: facetHostForManager(facetMgr),
|
|
140
|
+
vfs: sqliteFs,
|
|
141
|
+
registry,
|
|
142
|
+
startResident: rubyResidentStart(facetMgr),
|
|
143
|
+
})(manifest, installRoot, binName, binKind)(ctx);
|
|
144
|
+
});
|
|
145
|
+
// GNU bash 5.2.37 (wasm32-wasi, asyncified) — dedicated facet
|
|
146
|
+
// runner driving the fork/pipe/exec/setjmp scheduler (fork M1-M3
|
|
147
|
+
// mechanisms). Interactive terminal invocations use the shared
|
|
148
|
+
// ReplSession line editor; -c, scripts, and piped stdin retain the
|
|
149
|
+
// canonical one-shot handler.
|
|
150
|
+
workspace.runtimes.registerRunner('bash-runner', (manifest, installRoot, binName, binKind) => async (ctx) => {
|
|
151
|
+
const argv = ctx.args || [];
|
|
152
|
+
const explicitInteractive = argv.includes('-i');
|
|
153
|
+
const terminalStdin = ctx.isFdTerminal?.(0) ?? !ctx.stdin;
|
|
154
|
+
if (terminal && (explicitInteractive || (argv.length === 0 && terminalStdin))) {
|
|
155
|
+
const { runBashRepl } = await import('../runtime/bash-repl.js');
|
|
156
|
+
return await runBashRepl({
|
|
157
|
+
facetMgr,
|
|
158
|
+
vfs: sqliteFs,
|
|
159
|
+
terminal: terminal,
|
|
160
|
+
installRoot,
|
|
161
|
+
manifest,
|
|
162
|
+
cred: ctx.cred,
|
|
163
|
+
env: ctx.env,
|
|
164
|
+
cwd: ctx.cwd || '/home/user',
|
|
165
|
+
shell: shell ?? undefined,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
const { makeBashRunnerFactory } = await import('@nimbus-sh/core/runtime/bash-runner.js');
|
|
169
|
+
const { facetHostForManager } = await import('../runtime/facet-loader-host.js');
|
|
170
|
+
return await makeBashRunnerFactory({ facets: facetHostForManager(facetMgr), vfs: sqliteFs })(manifest, installRoot, binName, binKind)(ctx);
|
|
171
|
+
});
|
|
172
|
+
{
|
|
173
|
+
// Cast registry to the minimal package-manager shape. CommandRegistry
|
|
174
|
+
// CommandRegistry has register(name, handler) which matches.
|
|
175
|
+
registry.register('nimbus', makeNimbusVerbHandler({
|
|
176
|
+
runtimes: workspace.runtimes,
|
|
177
|
+
vfs: kernelFs,
|
|
178
|
+
registry: registry,
|
|
179
|
+
// The application verbs are the session's own (programmatic.ts):
|
|
180
|
+
// the shell, the SDK and the Agent all reach the same policy.
|
|
181
|
+
apps: {
|
|
182
|
+
expose: (target, options) => rpcExposeApp(self, target, options),
|
|
183
|
+
list: () => rpcListApps(self),
|
|
184
|
+
rotateLink: (target) => rpcRotateLink(self, target),
|
|
185
|
+
remove: (target) => rpcRemoveApp(self, target),
|
|
186
|
+
},
|
|
187
|
+
warmRuntime: async (target, ctx) => {
|
|
188
|
+
// The runtime name, which is what `nimbus install python` installs
|
|
189
|
+
// — not the name the user typed. Left as 'python' through the
|
|
190
|
+
// migration, this matched only the superseded Pyodide entry, so the
|
|
191
|
+
// interpreter people actually install was never warmed and the
|
|
192
|
+
// first invocation after installing paid the wasm compile.
|
|
193
|
+
if (target.name !== 'cpython')
|
|
194
|
+
return;
|
|
195
|
+
ctx.stdout.write(`[${target.name}] warming runtime...\n`);
|
|
196
|
+
const stdout = { write(_s) { } };
|
|
197
|
+
const stderrText = [];
|
|
198
|
+
const stderr = { write: (s) => { stderrText.push(String(s)); } };
|
|
199
|
+
const py = await registry.resolve('python');
|
|
200
|
+
if (py) {
|
|
201
|
+
const pid = 'pid' in ctx ? ctx.pid : undefined;
|
|
202
|
+
const setUmask = 'setUmask' in ctx ? ctx.setUmask : undefined;
|
|
203
|
+
const runAs = 'runAs' in ctx ? ctx.runAs : undefined;
|
|
204
|
+
if (typeof pid !== 'number'
|
|
205
|
+
|| typeof setUmask !== 'function'
|
|
206
|
+
|| typeof runAs !== 'function'
|
|
207
|
+
|| kernel === null) {
|
|
208
|
+
throw new Error('python warm-up requires a process identity');
|
|
209
|
+
}
|
|
210
|
+
const cred = requireVfsCred('cred' in ctx ? ctx.cred : undefined, 'python warm-up');
|
|
211
|
+
const code = await py({
|
|
212
|
+
...ctx,
|
|
213
|
+
args: ['-c', 'pass'],
|
|
214
|
+
pid,
|
|
215
|
+
cred,
|
|
216
|
+
setUmask: (mask) => setUmask(mask),
|
|
217
|
+
runAs: (targetCred, argv) => runAs(targetCred, argv),
|
|
218
|
+
vfs: kernel.vfs,
|
|
219
|
+
signal: new AbortController().signal,
|
|
220
|
+
stdout,
|
|
221
|
+
stderr,
|
|
222
|
+
});
|
|
223
|
+
if (typeof code === 'number' && code !== 0) {
|
|
224
|
+
throw new Error(stderrText.join('').trim() || `python warm-up exited ${code}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const { warmPythonRepl } = await import('../runtime/python-repl.js');
|
|
228
|
+
await warmPythonRepl({
|
|
229
|
+
facetMgr,
|
|
230
|
+
vfs: sqliteFs,
|
|
231
|
+
installRoot: target.root,
|
|
232
|
+
manifest: target.manifest,
|
|
233
|
+
});
|
|
234
|
+
ctx.stdout.write('[python] ready\n');
|
|
235
|
+
},
|
|
236
|
+
}));
|
|
237
|
+
// Rehydration runs here even though the shell hasn't been built
|
|
238
|
+
// yet — that's fine: it accesses VFS + registry which are both
|
|
239
|
+
// already initialised. Runs O(installed-runtimes); typically 0
|
|
240
|
+
// on a fresh session.
|
|
241
|
+
try {
|
|
242
|
+
const rehydration = await workspace.runtimes.rehydrate();
|
|
243
|
+
if (rehydration.count > 0) {
|
|
244
|
+
// Surface to terminal via the standard MOTD-style line so
|
|
245
|
+
// users see what's been auto-rebound. Not an error path.
|
|
246
|
+
terminal?.write?.(`\x1b[2m[nimbus] rehydrated ${rehydration.count} runtime bin(s): ${rehydration.bins.join(', ')}\x1b[0m\r\n`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
catch { /* fail-soft: rehydration must not block session boot */ }
|
|
250
|
+
}
|
|
251
|
+
// ── node command: facet-based execution ─────────────────────────────
|
|
252
|
+
// Parses args, reads script from VFS, delegates to FacetManager.
|
|
253
|
+
// The facet creates a dynamic worker where new Function() is allowed
|
|
254
|
+
// during module startup.
|
|
255
|
+
// ── node command (runtime registry refactor: refactored to use runtime-registry) ──
|
|
256
|
+
//
|
|
257
|
+
// Behaviour preserved exactly:
|
|
258
|
+
// - primitive #1 nodeFlagSpan (--version/-v/-h scan only flags
|
|
259
|
+
// before script path)
|
|
260
|
+
// - primitive #1 shebang strip
|
|
261
|
+
// - .ts/.tsx/.jsx esbuild auto-transform
|
|
262
|
+
// - G4 binSpawn ctx propagation (when the .bin handler set
|
|
263
|
+
// ctx.__nimbusBinSpawn, runFresh reuses the caller's PID
|
|
264
|
+
// instead of double-spawning)
|
|
265
|
+
// - --watch/--inspect/--inspect-brk routing via runFresh →
|
|
266
|
+
// isLongRunningInvocation
|
|
267
|
+
//
|
|
268
|
+
// The registry encodes the shared shape; per-runtime overrides
|
|
269
|
+
// live in the spec object.
|
|
270
|
+
const nodeSpec = {
|
|
271
|
+
name: 'node',
|
|
272
|
+
// CLN-1b: was stale literal 'v20.0.0'; pull from src/constants.ts
|
|
273
|
+
// canonical (src/runtime/node-shims.ts already does the same).
|
|
274
|
+
version: NODE_VERSION,
|
|
275
|
+
helpText: 'Usage: node [options] [script.js] [arguments]\n' +
|
|
276
|
+
' node -e "code"\n\n' +
|
|
277
|
+
'Options:\n' +
|
|
278
|
+
' -e, --eval <code> Evaluate code\n' +
|
|
279
|
+
' -v, --version Print version\n' +
|
|
280
|
+
' -h, --help Print help\n' +
|
|
281
|
+
'\nExecution via DO Facets (isolated V8 isolate)',
|
|
282
|
+
run: (code, opts) => runFresh(facetMgr, code, opts),
|
|
283
|
+
supportsBinSpawn: true,
|
|
284
|
+
};
|
|
285
|
+
{
|
|
286
|
+
const oneShotNode = buildRuntimeHandler(nodeSpec, {
|
|
287
|
+
vfs: sqliteFs,
|
|
288
|
+
getEsbuild: () => {
|
|
289
|
+
if (!self.esbuildService) {
|
|
290
|
+
self.ensureSqliteFs();
|
|
291
|
+
self.esbuildService = new EsbuildService(kernelFs);
|
|
292
|
+
}
|
|
293
|
+
return self.esbuildService;
|
|
294
|
+
},
|
|
295
|
+
registry,
|
|
296
|
+
});
|
|
297
|
+
// REPL Stream A: no-args invocation → drop into REPL session.
|
|
298
|
+
registry.register('node', async function nodeReplOrOneShot(ctx) {
|
|
299
|
+
const argv = ctx.args || [];
|
|
300
|
+
if (argv.length === 0 && terminal) {
|
|
301
|
+
const { runNodeRepl } = await import('../runtime/node-repl.js');
|
|
302
|
+
return await runNodeRepl({ facetMgr, terminal: terminal });
|
|
303
|
+
}
|
|
304
|
+
return await oneShotNode(ctx);
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
// ── bun command (runtime registry refactor: refactored to use runtime-registry) ──
|
|
308
|
+
//
|
|
309
|
+
// Behaviour preserved exactly:
|
|
310
|
+
// - --version / --help
|
|
311
|
+
// - install / i / add → delegate to npm
|
|
312
|
+
// - run <script> → look up package.json#scripts and shell.execute
|
|
313
|
+
// - -e / --eval flow
|
|
314
|
+
// - script-path flow with .ts/.tsx/.jsx auto-transform
|
|
315
|
+
// - BUN_SHIM_PREAMBLE prepend (handled inside runBunScript itself)
|
|
316
|
+
//
|
|
317
|
+
// Bun does NOT use binSpawn ctx propagation today (its runFresh
|
|
318
|
+
// chain doesn't share PID state with the .bin handler — the .bin
|
|
319
|
+
// handler always dispatches through `node`, not `bun`). So
|
|
320
|
+
// supportsBinSpawn=false (default).
|
|
321
|
+
/** `scripts` from the cwd's package.json; empty when there is none. */
|
|
322
|
+
const readPackageScripts = (cwd) => {
|
|
323
|
+
try {
|
|
324
|
+
const pkg = JSON.parse(kernelFs.readFileString(cwd + '/package.json'));
|
|
325
|
+
const scripts = pkg?.scripts;
|
|
326
|
+
return scripts && typeof scripts === 'object' ? scripts : {};
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return {};
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
const bunSpec = {
|
|
333
|
+
name: 'bun',
|
|
334
|
+
version: BUN_VERSION,
|
|
335
|
+
helpText: 'Usage: bun [options] [script.[js|ts|tsx]] [args...]\n' +
|
|
336
|
+
' bun -e "code"\n' +
|
|
337
|
+
' bun install [pkg ...]\n' +
|
|
338
|
+
' bun run <script>\n\n' +
|
|
339
|
+
'Bun-runtime shim provides Bun.file/Bun.write/\n' +
|
|
340
|
+
'Bun.spawn/Bun.password/Bun.gunzip backed by Workers-native\n' +
|
|
341
|
+
'primitives. Bun.serve / Bun.sql / Bun.S3 throw with supported alternatives.\n' +
|
|
342
|
+
'Execution via DO Facets (isolated V8 isolate per call).',
|
|
343
|
+
run: (code, opts) => runBunScript(facetMgr, code, opts),
|
|
344
|
+
subcommands: {
|
|
345
|
+
// bun install / i / add → npm install (same VFS, same R2 caches).
|
|
346
|
+
install: async (ctx, reg) => {
|
|
347
|
+
const npmCmd = await reg.resolve('npm');
|
|
348
|
+
if (npmCmd) {
|
|
349
|
+
return await npmCmd({ ...ctx, args: ['install', ...(ctx.args || []).slice(1)] });
|
|
350
|
+
}
|
|
351
|
+
ctx.stderr.write('bun install: npm handler unavailable\n');
|
|
352
|
+
return 1;
|
|
353
|
+
},
|
|
354
|
+
i: async (ctx, reg) => {
|
|
355
|
+
const npmCmd = await reg.resolve('npm');
|
|
356
|
+
if (npmCmd) {
|
|
357
|
+
return await npmCmd({ ...ctx, args: ['install', ...(ctx.args || []).slice(1)] });
|
|
358
|
+
}
|
|
359
|
+
ctx.stderr.write('bun i: npm handler unavailable\n');
|
|
360
|
+
return 1;
|
|
361
|
+
},
|
|
362
|
+
add: async (ctx, reg) => {
|
|
363
|
+
const npmCmd = await reg.resolve('npm');
|
|
364
|
+
if (npmCmd) {
|
|
365
|
+
return await npmCmd({ ...ctx, args: ['install', ...(ctx.args || []).slice(1)] });
|
|
366
|
+
}
|
|
367
|
+
ctx.stderr.write('bun add: npm handler unavailable\n');
|
|
368
|
+
return 1;
|
|
369
|
+
},
|
|
370
|
+
// bun run <target> — a package.json script, or a file.
|
|
371
|
+
//
|
|
372
|
+
// Real bun's precedence, and the reason this is not just a script
|
|
373
|
+
// lookup: a path-shaped target (`./cli.ts`, `sub/x`, `.`) is ALWAYS
|
|
374
|
+
// a file and never consults scripts, while a bare name checks
|
|
375
|
+
// scripts first and only then falls back to a file. The file case
|
|
376
|
+
// delegates to the standard runtime flow, so `bun run ./cli.ts`
|
|
377
|
+
// and `bun cli.ts` execute through one path — TypeScript transform,
|
|
378
|
+
// facet dispatch and all.
|
|
379
|
+
run: async (ctx, _reg, runAsBun) => {
|
|
380
|
+
const args = ctx.args || [];
|
|
381
|
+
// bun's own run flags sit between the verb and the target.
|
|
382
|
+
let targetIdx = 1;
|
|
383
|
+
while (targetIdx < args.length && args[targetIdx].startsWith('-'))
|
|
384
|
+
targetIdx++;
|
|
385
|
+
const target = args[targetIdx];
|
|
386
|
+
const cwd = normalizeVfsPath(ctx.cwd || '/home/user');
|
|
387
|
+
const scripts = readPackageScripts(cwd);
|
|
388
|
+
if (!target) {
|
|
389
|
+
ctx.stdout.write('Usage: bun run [flags] <file or script>\n');
|
|
390
|
+
const names = Object.keys(scripts);
|
|
391
|
+
if (names.length) {
|
|
392
|
+
ctx.stdout.write(`\npackage.json scripts (${names.length} found):\n\n`);
|
|
393
|
+
for (const n of names)
|
|
394
|
+
ctx.stdout.write(` bun run ${n}\n ${scripts[n]}\n\n`);
|
|
395
|
+
}
|
|
396
|
+
return 0;
|
|
397
|
+
}
|
|
398
|
+
const pathShaped = target === '.' || target === '..' || target.includes('/');
|
|
399
|
+
const pkgScript = pathShaped ? undefined : scripts[target];
|
|
400
|
+
if (pkgScript) {
|
|
401
|
+
// Trailing args append to the script command; bun drops a single
|
|
402
|
+
// `--` separator between the script name and them.
|
|
403
|
+
const extra = args.slice(targetIdx + 1);
|
|
404
|
+
if (extra[0] === '--')
|
|
405
|
+
extra.shift();
|
|
406
|
+
const command = extra.length ? `${pkgScript} ${extra.join(' ')}` : pkgScript;
|
|
407
|
+
try {
|
|
408
|
+
const shellResult = await shell.execute(command, {
|
|
409
|
+
cwd: ctx.cwd,
|
|
410
|
+
env: ctx.env,
|
|
411
|
+
onStdout: textSink((d) => ctx.stdout.write(d)),
|
|
412
|
+
onStderr: textSink((d) => ctx.stderr.write(d)),
|
|
413
|
+
});
|
|
414
|
+
return shellResult.exitCode;
|
|
415
|
+
}
|
|
416
|
+
catch (e) {
|
|
417
|
+
ctx.stderr.write(`bun run: ${e?.message ?? String(e)}\n`);
|
|
418
|
+
return 1;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
const resolved = resolveRuntimeScriptPath(kernelFs, cwd, target, {
|
|
422
|
+
preferModuleField: true,
|
|
423
|
+
});
|
|
424
|
+
if (resolved === null) {
|
|
425
|
+
ctx.stderr.write(pathShaped
|
|
426
|
+
? `error: Module not found "${target}"\n`
|
|
427
|
+
: `error: Script not found "${target}"\n`);
|
|
428
|
+
return 1;
|
|
429
|
+
}
|
|
430
|
+
return runAsBun([...args.slice(1, targetIdx), '/' + resolved, ...args.slice(targetIdx + 1)]);
|
|
431
|
+
},
|
|
432
|
+
},
|
|
433
|
+
};
|
|
434
|
+
{
|
|
435
|
+
const oneShotBun = buildRuntimeHandler(bunSpec, {
|
|
436
|
+
vfs: sqliteFs,
|
|
437
|
+
getEsbuild: () => {
|
|
438
|
+
if (!self.esbuildService) {
|
|
439
|
+
self.ensureSqliteFs();
|
|
440
|
+
self.esbuildService = new EsbuildService(kernelFs);
|
|
441
|
+
}
|
|
442
|
+
return self.esbuildService;
|
|
443
|
+
},
|
|
444
|
+
registry,
|
|
445
|
+
});
|
|
446
|
+
// REPL Stream A: no-args invocation → drop into REPL session.
|
|
447
|
+
registry.register('bun', async function bunReplOrOneShot(ctx) {
|
|
448
|
+
const argv = ctx.args || [];
|
|
449
|
+
if (argv.length === 0 && terminal) {
|
|
450
|
+
const { runBunRepl } = await import('../runtime/bun-repl.js');
|
|
451
|
+
return await runBunRepl({ facetMgr, terminal: terminal });
|
|
452
|
+
}
|
|
453
|
+
return await oneShotBun(ctx);
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
// ── wasm-runner: native WebAssembly, on this session's facet host ──
|
|
457
|
+
//
|
|
458
|
+
// Bytes ride INSIDE the inner worker's code blob, the one phase where
|
|
459
|
+
// workerd permits wasm code generation; request-time
|
|
460
|
+
// WebAssembly.instantiate(bytes) is CSP-blocked and avoided.
|
|
461
|
+
//
|
|
462
|
+
// wasm-csp/findings.md — add(3,4)===7 in 11ms warm against the
|
|
463
|
+
// deployed Cloudflare fleet.
|
|
464
|
+
//
|
|
465
|
+
// Lazy: the wasm-runner module (WASI instance preamble + snapshot
|
|
466
|
+
// machinery) is imported on first `wasm-runner` invocation and the
|
|
467
|
+
// built handler memoized, so its module-eval cost stays off the cold
|
|
468
|
+
// Worker Startup Time path.
|
|
469
|
+
{
|
|
470
|
+
let wasmHandler = null;
|
|
471
|
+
registry.register('wasm-runner', async (ctx) => {
|
|
472
|
+
if (!wasmHandler) {
|
|
473
|
+
const { wasmRunnerSpec } = await import('@nimbus-sh/core/runtime/wasm-runner.js');
|
|
474
|
+
const { loaderFacetHost } = await import('../runtime/facet-loader-host.js');
|
|
475
|
+
const wasmSpec = wasmRunnerSpec({
|
|
476
|
+
// filesystem WASI: extended VFS surface for WASI file-IO. The
|
|
477
|
+
// wasm-runner snapshots a session subtree into the facet, flushes
|
|
478
|
+
// the diff back via this surface after _start returns.
|
|
479
|
+
vfs: sqliteFs,
|
|
480
|
+
facets: loaderFacetHost(self.env, self.ctx),
|
|
481
|
+
processes: self.processes,
|
|
482
|
+
});
|
|
483
|
+
wasmHandler = buildRuntimeHandler(wasmSpec, {
|
|
484
|
+
vfs: sqliteFs,
|
|
485
|
+
getEsbuild: () => {
|
|
486
|
+
if (!self.esbuildService) {
|
|
487
|
+
self.ensureSqliteFs();
|
|
488
|
+
self.esbuildService = new EsbuildService(kernelFs);
|
|
489
|
+
}
|
|
490
|
+
return self.esbuildService;
|
|
491
|
+
},
|
|
492
|
+
registry,
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
return await wasmHandler(ctx);
|
|
496
|
+
});
|
|
497
|
+
}
|
|
498
|
+
kernel.routeLoopback = (port, request) => self.routeLoopback(port, request);
|
|
499
|
+
try {
|
|
500
|
+
registry.register('curl', createCurlCommand(kernel));
|
|
501
|
+
}
|
|
502
|
+
catch { }
|
|
503
|
+
// ── df with SQLite stats + cache + process metrics ──────────────────
|
|
504
|
+
registry.register('df', async (ctx) => {
|
|
505
|
+
const stats = sqliteFs.getStats();
|
|
506
|
+
const pstats = facetMgr.stats;
|
|
507
|
+
const used = stats.usedBytes;
|
|
508
|
+
const cap = stats.capacityBytes;
|
|
509
|
+
const avail = cap - used;
|
|
510
|
+
const pct = ((used / cap) * 100).toFixed(0);
|
|
511
|
+
const fmt = (b) => {
|
|
512
|
+
if (b >= 1e9)
|
|
513
|
+
return (b / 1e9).toFixed(1) + 'G';
|
|
514
|
+
if (b >= 1e6)
|
|
515
|
+
return (b / 1e6).toFixed(1) + 'M';
|
|
516
|
+
if (b >= 1e3)
|
|
517
|
+
return (b / 1e3).toFixed(1) + 'K';
|
|
518
|
+
return b + 'B';
|
|
519
|
+
};
|
|
520
|
+
ctx.stdout.write('Filesystem Size Used Avail Use% Mounted on\n');
|
|
521
|
+
ctx.stdout.write('sqlite ' + fmt(cap).padStart(5) + ' ' + fmt(used).padStart(5) +
|
|
522
|
+
' ' + fmt(avail).padStart(5) + ' ' + pct.padStart(3) + '% /\n');
|
|
523
|
+
ctx.stdout.write('\nCache: ' + stats.cache.entries + '/' + stats.cache.maxEntries +
|
|
524
|
+
' slots | hit rate: ' + stats.cache.hitRate +
|
|
525
|
+
'% | evictions: ' + stats.cache.evictions + '\n');
|
|
526
|
+
ctx.stdout.write('Procs: ' + pstats.running + ' running, ' +
|
|
527
|
+
pstats.exited + ' exited, ' +
|
|
528
|
+
pstats.total + ' total (next PID: ' + pstats.nextPid + ')\n');
|
|
529
|
+
return 0;
|
|
530
|
+
});
|
|
531
|
+
// ── esbuild command: transform/bundle via esbuild facet ───────────────
|
|
532
|
+
// Lazy-creates the EsbuildService on first use (esbuild-wasm is ~10MB).
|
|
533
|
+
registry.register('esbuild', async (ctx) => {
|
|
534
|
+
const args = ctx.args || [];
|
|
535
|
+
if (args.includes('--version')) {
|
|
536
|
+
ctx.stdout.write('0.24.2 (esbuild-wasm, bundled)\n');
|
|
537
|
+
return 0;
|
|
538
|
+
}
|
|
539
|
+
if (args.includes('--help') || args.length === 0) {
|
|
540
|
+
ctx.stdout.write('Usage: esbuild [options] [entry points]\n\n');
|
|
541
|
+
ctx.stdout.write('Options:\n');
|
|
542
|
+
ctx.stdout.write(' --bundle Bundle all dependencies into output\n');
|
|
543
|
+
ctx.stdout.write(' --outfile=<path> Write output to a file\n');
|
|
544
|
+
ctx.stdout.write(' --outdir=<path> Write output to a directory\n');
|
|
545
|
+
ctx.stdout.write(' --format=esm|cjs Output format (default: esm)\n');
|
|
546
|
+
ctx.stdout.write(' --platform=browser|node Target platform\n');
|
|
547
|
+
ctx.stdout.write(' --minify Minify output\n');
|
|
548
|
+
ctx.stdout.write(' --sourcemap Generate source maps\n');
|
|
549
|
+
ctx.stdout.write(' --target=<target> JS target (default: esnext)\n');
|
|
550
|
+
ctx.stdout.write(' --loader=<loader> Force file loader (ts, tsx, jsx, css)\n');
|
|
551
|
+
ctx.stdout.write(' --version Show version\n');
|
|
552
|
+
ctx.stdout.write('\nPowered by esbuild-wasm (bundled in supervisor).\n');
|
|
553
|
+
return 0;
|
|
554
|
+
}
|
|
555
|
+
// Lazy-init esbuild service
|
|
556
|
+
if (!self.esbuildService) {
|
|
557
|
+
self.ensureSqliteFs();
|
|
558
|
+
self.esbuildService = new EsbuildService(kernelFs);
|
|
559
|
+
}
|
|
560
|
+
// Parse flags
|
|
561
|
+
const flags = {};
|
|
562
|
+
const entryPoints = [];
|
|
563
|
+
for (const arg of args) {
|
|
564
|
+
if (arg.startsWith('--')) {
|
|
565
|
+
const eqIdx = arg.indexOf('=');
|
|
566
|
+
if (eqIdx > 0) {
|
|
567
|
+
flags[arg.substring(2, eqIdx)] = arg.substring(eqIdx + 1);
|
|
568
|
+
}
|
|
569
|
+
else {
|
|
570
|
+
flags[arg.substring(2)] = 'true';
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
else {
|
|
574
|
+
entryPoints.push(arg);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
// Transform-only mode (single file, no --bundle)
|
|
578
|
+
if (entryPoints.length === 1 && !flags['bundle']) {
|
|
579
|
+
// Read the file and transform it
|
|
580
|
+
const filePath = resolveVfsPath(entryPoints[0], ctx.cwd || '/home/user');
|
|
581
|
+
let code;
|
|
582
|
+
try {
|
|
583
|
+
code = kernelFs.readFileString(filePath);
|
|
584
|
+
}
|
|
585
|
+
catch {
|
|
586
|
+
ctx.stderr.write(`esbuild: could not read file: ${entryPoints[0]}\n`);
|
|
587
|
+
return 1;
|
|
588
|
+
}
|
|
589
|
+
try {
|
|
590
|
+
ctx.stderr.write('Transforming...\n');
|
|
591
|
+
const result = await self.esbuildService.transform(code, {
|
|
592
|
+
loader: flags['loader'] || (() => {
|
|
593
|
+
const ext = filePath.split('.').pop()?.toLowerCase();
|
|
594
|
+
return { ts: 'ts', tsx: 'tsx', jsx: 'jsx', js: 'js', mts: 'ts', mjs: 'js', css: 'css', json: 'json' }[ext || ''];
|
|
595
|
+
})(),
|
|
596
|
+
format: flags['format'] || 'esm',
|
|
597
|
+
target: flags['target'] || 'esnext',
|
|
598
|
+
sourcemap: flags['sourcemap'] === 'true',
|
|
599
|
+
minify: flags['minify'] === 'true',
|
|
600
|
+
});
|
|
601
|
+
if (flags['outfile']) {
|
|
602
|
+
const outPath = resolveVfsPath(flags['outfile'], ctx.cwd || '/home/user');
|
|
603
|
+
const parent = parentVfsPath(outPath);
|
|
604
|
+
if (parent && !kernelFs.exists(parent))
|
|
605
|
+
kernelFs.mkdir(parent, { recursive: true });
|
|
606
|
+
kernelFs.writeFile(outPath, result.code);
|
|
607
|
+
ctx.stdout.write(` ${outPath} ${result.code.length} bytes\n`);
|
|
608
|
+
}
|
|
609
|
+
else {
|
|
610
|
+
ctx.stdout.write(result.code);
|
|
611
|
+
}
|
|
612
|
+
for (const w of result.warnings || []) {
|
|
613
|
+
ctx.stderr.write(`warning: ${w.text}\n`);
|
|
614
|
+
}
|
|
615
|
+
return 0;
|
|
616
|
+
}
|
|
617
|
+
catch (e) {
|
|
618
|
+
ctx.stderr.write(`esbuild error: ${e?.message || e}\n`);
|
|
619
|
+
return 1;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
// Bundle mode
|
|
623
|
+
if (entryPoints.length === 0) {
|
|
624
|
+
ctx.stderr.write('esbuild: no entry points specified\n');
|
|
625
|
+
return 1;
|
|
626
|
+
}
|
|
627
|
+
// Resolve entry points relative to cwd
|
|
628
|
+
const resolvedEntryPoints = entryPoints.map(ep => resolveVfsPath(ep, ctx.cwd || '/home/user'));
|
|
629
|
+
try {
|
|
630
|
+
ctx.stderr.write('Bundling...\n');
|
|
631
|
+
const result = await self.esbuildService.build(resolvedEntryPoints, {
|
|
632
|
+
bundle: flags['bundle'] === 'true',
|
|
633
|
+
format: flags['format'] || 'esm',
|
|
634
|
+
target: flags['target'] || 'esnext',
|
|
635
|
+
platform: flags['platform'] || 'browser',
|
|
636
|
+
outdir: flags['outfile'] ? undefined : (flags['outdir'] || '/dist'),
|
|
637
|
+
outfile: flags['outfile'],
|
|
638
|
+
sourcemap: flags['sourcemap'] === 'true',
|
|
639
|
+
minify: flags['minify'] === 'true',
|
|
640
|
+
external: flags['external']?.split(','),
|
|
641
|
+
});
|
|
642
|
+
for (const e of result.errors || []) {
|
|
643
|
+
ctx.stderr.write(`error: ${e.text}\n`);
|
|
644
|
+
}
|
|
645
|
+
for (const w of result.warnings || []) {
|
|
646
|
+
ctx.stderr.write(`warning: ${w.text}\n`);
|
|
647
|
+
}
|
|
648
|
+
if (result.errors?.length)
|
|
649
|
+
return 1;
|
|
650
|
+
// Write output files to VFS
|
|
651
|
+
for (const f of result.outputFiles || []) {
|
|
652
|
+
const outPath = normalizeVfsPath(f.path);
|
|
653
|
+
const parent = parentVfsPath(outPath);
|
|
654
|
+
if (parent && !kernelFs.exists(parent))
|
|
655
|
+
kernelFs.mkdir(parent, { recursive: true });
|
|
656
|
+
kernelFs.writeFile(outPath, f.contents);
|
|
657
|
+
ctx.stdout.write(` ${outPath} ${f.contents.length} bytes\n`);
|
|
658
|
+
}
|
|
659
|
+
ctx.stderr.write(`Done (${result.outputFiles?.length || 0} output files)\n`);
|
|
660
|
+
return 0;
|
|
661
|
+
}
|
|
662
|
+
catch (e) {
|
|
663
|
+
ctx.stderr.write(`esbuild error: ${e?.message || e}\n`);
|
|
664
|
+
return 1;
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
// ── vite command: start/stop the dev server ──────────────────────────
|
|
668
|
+
registry.register('vite', createViteCommand(self));
|
|
669
|
+
// ── nimbus-wrangler / wrangler command: Worker dev server ─────────────
|
|
670
|
+
//
|
|
671
|
+
// `wrangler` is registered as a transparent alias for `nimbus-wrangler`
|
|
672
|
+
// so projects with `"dev": "wrangler dev"` in package.json Just Work.
|
|
673
|
+
// The shared handler below takes an extra `invokedAs` flag so we can
|
|
674
|
+
// - print a one-shot "DO-in-DO mode" banner on the first wrangler
|
|
675
|
+
// invocation per session (so users know they're getting a compat
|
|
676
|
+
// layer, not real wrangler)
|
|
677
|
+
// - silently strip wrangler-specific flags (--ip, --port, etc.) that
|
|
678
|
+
// have no meaning inside a DO.
|
|
679
|
+
const wranglerHandler = (invokedAs) => async (ctx) => {
|
|
680
|
+
const rawArgs = ctx.args || [];
|
|
681
|
+
// Filter wrangler-only flags early (works for both invocation paths;
|
|
682
|
+
// a no-op for nimbus-wrangler since it doesn't accept them anyway).
|
|
683
|
+
const { args, ignored } = filterWranglerFlags(rawArgs);
|
|
684
|
+
if (args.includes('--help') || args.includes('-h') || args.length === 0) {
|
|
685
|
+
ctx.stdout.write(`Usage: ${invokedAs} dev [options]\n\n`);
|
|
686
|
+
ctx.stdout.write('Run your Cloudflare Worker locally on the actual CF runtime\n');
|
|
687
|
+
ctx.stdout.write('(DO-in-DO via env.LOADER — workerd in a workerd).\n\n');
|
|
688
|
+
ctx.stdout.write('Commands:\n');
|
|
689
|
+
ctx.stdout.write(' dev Start the dev server\n');
|
|
690
|
+
ctx.stdout.write(' stop Stop the dev server\n\n');
|
|
691
|
+
ctx.stdout.write('Options:\n');
|
|
692
|
+
ctx.stdout.write(' --root <dir> Project root (default: cwd)\n\n');
|
|
693
|
+
if (invokedAs === 'wrangler') {
|
|
694
|
+
ctx.stdout.write('Note: \x1b[2minside Nimbus, `wrangler` is an alias for\x1b[0m \x1b[36mnimbus-wrangler\x1b[0m.\n');
|
|
695
|
+
ctx.stdout.write('Most real-wrangler flags (--ip, --port, --local, --log-level, ...)\n');
|
|
696
|
+
ctx.stdout.write('are silently ignored because the DO provides its own routing.\n');
|
|
697
|
+
}
|
|
698
|
+
return 0;
|
|
699
|
+
}
|
|
700
|
+
if (args[0] === 'stop') {
|
|
701
|
+
if (self.nimbusWrangler?.isRunning) {
|
|
702
|
+
self.nimbusWrangler.stop();
|
|
703
|
+
ctx.stdout.write('\x1b[33mWorker dev server stopped.\x1b[0m\n');
|
|
704
|
+
}
|
|
705
|
+
else {
|
|
706
|
+
ctx.stdout.write('No Worker dev server running.\n');
|
|
707
|
+
}
|
|
708
|
+
return 0;
|
|
709
|
+
}
|
|
710
|
+
if (args[0] !== 'dev') {
|
|
711
|
+
ctx.stderr.write(`Unknown command: ${args[0]}. Use "${invokedAs} dev" or "${invokedAs} --help".\n`);
|
|
712
|
+
return 1;
|
|
713
|
+
}
|
|
714
|
+
// First-run banner — only when invoked as `wrangler`, and only once
|
|
715
|
+
// per session. Makes it OBVIOUS to the user that they're not running
|
|
716
|
+
// real wrangler, and that Nimbus is doing something different.
|
|
717
|
+
if (invokedAs === 'wrangler' && !self.wranglerAliasBannerShown) {
|
|
718
|
+
ctx.stdout.write('\x1b[2m\u2388 wrangler (Nimbus DO-in-DO mode) — bundling via esbuild-wasm, running via env.LOADER\x1b[0m\n');
|
|
719
|
+
self.wranglerAliasBannerShown = true;
|
|
720
|
+
}
|
|
721
|
+
// Report ignored flags (also one-shot — if user sees it once per
|
|
722
|
+
// session that's enough to spot a typo; no need to spam on rebuilds).
|
|
723
|
+
if (ignored.length > 0 && invokedAs === 'wrangler') {
|
|
724
|
+
ctx.stdout.write('\x1b[2m ignored wrangler flags: ' + ignored.join(' ') + '\x1b[0m\n');
|
|
725
|
+
}
|
|
726
|
+
// Lazy-init esbuild
|
|
727
|
+
if (!self.esbuildService) {
|
|
728
|
+
self.ensureSqliteFs();
|
|
729
|
+
self.esbuildService = new EsbuildService(kernelFs);
|
|
730
|
+
}
|
|
731
|
+
// Parse --root flag; default to the shell cwd so `npm run dev` from
|
|
732
|
+
// a project directory picks up that project's wrangler.jsonc.
|
|
733
|
+
let root = ctx.cwd || '/home/user';
|
|
734
|
+
for (let i = 1; i < args.length; i++) {
|
|
735
|
+
if (args[i] === '--root' && args[i + 1])
|
|
736
|
+
root = args[i + 1];
|
|
737
|
+
}
|
|
738
|
+
// Stop existing
|
|
739
|
+
if (self.nimbusWrangler?.isRunning)
|
|
740
|
+
self.nimbusWrangler.stop();
|
|
741
|
+
const vfsRoot = resolveVfsPath(root, ctx.cwd || '/home/user');
|
|
742
|
+
// Pre-flight: read the wrangler config ourselves and call out any
|
|
743
|
+
// binding fields nimbus-wrangler can't provide. NimbusWrangler will
|
|
744
|
+
// still try to bundle + load, but user sees up-front why their
|
|
745
|
+
// Worker may fail when it tries to access a missing binding.
|
|
746
|
+
const unsupportedFields = detectUnsupportedWranglerConfig(kernelFs, vfsRoot);
|
|
747
|
+
ctx.stdout.write('\n');
|
|
748
|
+
ctx.stdout.write('\x1b[1;35m ' + (invokedAs === 'wrangler' ? 'Wrangler' : 'Nimbus Wrangler') + ' Dev\x1b[0m\n\n');
|
|
749
|
+
if (unsupportedFields.length > 0) {
|
|
750
|
+
ctx.stderr.write('\x1b[33m\u26A0\x1b[0m \x1b[1mNimbus-incompatible wrangler.jsonc fields detected:\x1b[0m\n');
|
|
751
|
+
for (const f of unsupportedFields) {
|
|
752
|
+
ctx.stderr.write(' - \x1b[33m' + f + '\x1b[0m\n');
|
|
753
|
+
}
|
|
754
|
+
ctx.stderr.write(' These bindings are NOT provisioned inside nimbus-wrangler. Your Worker\n' +
|
|
755
|
+
' will get \x1b[2mundefined\x1b[0m when it tries to access them, which typically\n' +
|
|
756
|
+
' causes a runtime TypeError. The bundle will still build and load.\n' +
|
|
757
|
+
' \x1b[2mDeploy with real wrangler to get the real bindings.\x1b[0m\n\n');
|
|
758
|
+
}
|
|
759
|
+
self.nimbusWrangler = new NimbusWrangler({
|
|
760
|
+
vfs: kernelFs,
|
|
761
|
+
vfsEvents: sqliteFs.events,
|
|
762
|
+
esbuild: self.esbuildService,
|
|
763
|
+
env: self.env,
|
|
764
|
+
// Supervisor DO ctx — required for ctx.facets.get() when
|
|
765
|
+
// synthesizing durable_objects bindings on the inner Worker.
|
|
766
|
+
ctx: self.ctx,
|
|
767
|
+
root: vfsRoot,
|
|
768
|
+
onLog: (msg) => {
|
|
769
|
+
if (terminal) {
|
|
770
|
+
try {
|
|
771
|
+
terminal.write(msg);
|
|
772
|
+
}
|
|
773
|
+
catch { }
|
|
774
|
+
}
|
|
775
|
+
},
|
|
776
|
+
onHmrMessage: (msg) => {
|
|
777
|
+
if (terminal) {
|
|
778
|
+
try {
|
|
779
|
+
terminal.ws?.send(JSON.stringify({ type: 'hmr', data: msg }));
|
|
780
|
+
}
|
|
781
|
+
catch { }
|
|
782
|
+
}
|
|
783
|
+
},
|
|
784
|
+
});
|
|
785
|
+
const ok = await self.nimbusWrangler.start();
|
|
786
|
+
if (!ok) {
|
|
787
|
+
ctx.stderr.write(' \x1b[31mFailed to start Worker dev server.\x1b[0m\n');
|
|
788
|
+
return 1;
|
|
789
|
+
}
|
|
790
|
+
const cfg = self.nimbusWrangler.stats;
|
|
791
|
+
// runtime primitive support (P5): banner advertises the canonical
|
|
792
|
+
// `/__nimbus/worker/` route. The legacy `/worker/` URL is still
|
|
793
|
+
// accepted for one release (Sunset 2027-01-01) but new sessions
|
|
794
|
+
// are pointed at the namespaced form.
|
|
795
|
+
const workerBase = (self.sessionBasePath || '') + '/__nimbus/worker';
|
|
796
|
+
ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Worker: \x1b[36m' + workerBase + '/\x1b[0m\n');
|
|
797
|
+
ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Name: ' + cfg.name + '\n');
|
|
798
|
+
ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Entry: ' + cfg.main + '\n');
|
|
799
|
+
ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Root: ' + cfg.root + '\n');
|
|
800
|
+
ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Reload: on file change\n\n');
|
|
801
|
+
ctx.stdout.write(' \x1b[2mRun \x1b[0m' + invokedAs + ' stop\x1b[2m to stop.\x1b[0m\n\n');
|
|
802
|
+
return 0;
|
|
803
|
+
};
|
|
804
|
+
registry.register('nimbus-wrangler', wranglerHandler('nimbus-wrangler'));
|
|
805
|
+
registry.register('wrangler', wranglerHandler('wrangler'));
|
|
806
|
+
// ── npm-fast command: parallel npm install (v2 — batched writes) ────
|
|
807
|
+
registry.register('npm-fast', async (ctx) => {
|
|
808
|
+
const args = ctx.args || [];
|
|
809
|
+
if (args.includes('--help') || args.includes('-h') || args.length === 0) {
|
|
810
|
+
ctx.stdout.write('Usage: npm-fast install <packages...>\n\n');
|
|
811
|
+
ctx.stdout.write('Nimbus npm v2 — batched VFS writes, content-addressed cache.\n');
|
|
812
|
+
ctx.stdout.write('Handles 100+ dependency projects without crashing.\n');
|
|
813
|
+
return 0;
|
|
814
|
+
}
|
|
815
|
+
if (args[0] !== 'install' && args[0] !== 'i') {
|
|
816
|
+
ctx.stderr.write('Only "npm-fast install" is supported. Use "npm" for other commands.\n');
|
|
817
|
+
return 1;
|
|
818
|
+
}
|
|
819
|
+
const packages = args.slice(1).filter((a) => !a.startsWith('-'));
|
|
820
|
+
if (packages.length === 0) {
|
|
821
|
+
ctx.stderr.write('Specify packages to install: npm-fast install react react-dom\n');
|
|
822
|
+
return 1;
|
|
823
|
+
}
|
|
824
|
+
self.ensureSqliteFs();
|
|
825
|
+
const cwd = normalizeVfsPath(ctx.cwd || '/home/user');
|
|
826
|
+
// Ensure package.json exists
|
|
827
|
+
const pkgJsonPath = cwd + '/package.json';
|
|
828
|
+
if (!kernelFs.exists(pkgJsonPath)) {
|
|
829
|
+
kernelFs.writeFile(pkgJsonPath, '{"name":"project","version":"1.0.0","dependencies":{}}\n');
|
|
830
|
+
}
|
|
831
|
+
ctx.stdout.write('\x1b[36mNimbus npm v2 (batched writes)\x1b[0m\n');
|
|
832
|
+
await self.ensureNpmInstaller((msg) => {
|
|
833
|
+
ctx.stdout.write('[npm] ' + msg + '\n');
|
|
834
|
+
});
|
|
835
|
+
const result = await self.npmInstaller.install(cwd, { packages, pid: ctx.pid });
|
|
836
|
+
if (result.failed.length > 0) {
|
|
837
|
+
ctx.stderr.write('\x1b[31mFailed: ' + result.failed.join(', ') + '\x1b[0m\n');
|
|
838
|
+
}
|
|
839
|
+
// [HONEST INSTALL MESSAGE P0a] Yellow + "(N failed, see above)"
|
|
840
|
+
// when partial. Green only when failed.length === 0. Pre-fix the
|
|
841
|
+
// green line printed unconditionally — see user transcript line
|
|
842
|
+
// 831 ("added 264 packages" with 353 silent failures above).
|
|
843
|
+
const partial = result.failed.length > 0;
|
|
844
|
+
const color = partial ? '\x1b[33m' : '\x1b[32m';
|
|
845
|
+
const suffix = partial ? ` (${result.failed.length} failed, see above)` : '';
|
|
846
|
+
ctx.stdout.write(`\n${color}added ${result.installed.length} packages (${result.totalFiles} files) in ${(result.elapsed / 1000).toFixed(1)}s${suffix}\x1b[0m\n`);
|
|
847
|
+
if (result.cachedHits > 0) {
|
|
848
|
+
ctx.stdout.write(`\x1b[2m (${result.cachedHits} from cache)\x1b[0m\n`);
|
|
849
|
+
}
|
|
850
|
+
return result.failed.length > 0 ? 1 : 0;
|
|
851
|
+
});
|
|
852
|
+
HeredocHandler.install(shell, terminal);
|
|
853
|
+
// ── Readline-parity keybindings (Ctrl+K, Ctrl+W, Alt+B, Alt+F, Alt+D,
|
|
854
|
+
// Ctrl+Y, Ctrl+T, Ctrl+L, Ctrl+R, Alt+. , Ctrl+←/→, Alt+←/→, Linux
|
|
855
|
+
// Home/End variants, Ctrl+B/F/N/P, …). Installed AFTER Heredoc so
|
|
856
|
+
// its handleInput wrapper takes precedence when heredoc mode is
|
|
857
|
+
// active. ──
|
|
858
|
+
LineEditorExtender.install(shell, terminal);
|
|
859
|
+
// ── Wire npm/npx with shellExecute ──
|
|
860
|
+
const shellExecute = async (cmd, cmdCtx) => {
|
|
861
|
+
const stdin = cmdCtx.stdin && cmdCtx.stdin !== cmdCtx.terminalStdin
|
|
862
|
+
? await cmdCtx.stdin.readAll()
|
|
863
|
+
: undefined;
|
|
864
|
+
const result = await shell.execute(cmd, {
|
|
865
|
+
cwd: cmdCtx.cwd,
|
|
866
|
+
env: cmdCtx.env,
|
|
867
|
+
onStdout: textSink((d) => cmdCtx.stdout.write(d)),
|
|
868
|
+
onStderr: textSink((d) => cmdCtx.stderr.write(d)),
|
|
869
|
+
stdin,
|
|
870
|
+
terminalStdin: cmdCtx.terminalStdin,
|
|
871
|
+
// `npm run x` runs x on npm's own fds. Handing the nested execution a
|
|
872
|
+
// sink without saying where that sink leads would make every fd look
|
|
873
|
+
// redirected, and a runtime whose stdout is redirected stops streaming.
|
|
874
|
+
terminalFds: {
|
|
875
|
+
stdin: cmdCtx.isFdTerminal?.(0) ?? false,
|
|
876
|
+
stdout: cmdCtx.isFdTerminal?.(1) ?? false,
|
|
877
|
+
stderr: cmdCtx.isFdTerminal?.(2) ?? false,
|
|
878
|
+
},
|
|
879
|
+
commandContext: {
|
|
880
|
+
pid: cmdCtx.pid,
|
|
881
|
+
cred: cmdCtx.cred,
|
|
882
|
+
setUmask: cmdCtx.setUmask,
|
|
883
|
+
},
|
|
884
|
+
runAs: runAsProcess,
|
|
885
|
+
});
|
|
886
|
+
return result.exitCode;
|
|
887
|
+
};
|
|
888
|
+
const shellEntrypointExecutor = {
|
|
889
|
+
execute: async (cmd, options) => {
|
|
890
|
+
const parentPid = options?.commandContext?.['pid'];
|
|
891
|
+
if (typeof parentPid !== 'number') {
|
|
892
|
+
throw new Error('shell entrypoint requires a parent process');
|
|
893
|
+
}
|
|
894
|
+
const childProcess = self.processes.spawn('sh', ['sh'], options?.cwd || '/home/user', { parentPid });
|
|
895
|
+
let exitCode = 1;
|
|
896
|
+
try {
|
|
897
|
+
const identity = commandIdentityFor(childProcess.pid);
|
|
898
|
+
const terminal = new HeadlessTerminal();
|
|
899
|
+
const childShell = new Shell(terminal, kernel.vfs, registry, { ...env, ...(options?.env || {}) }, processRegistry, identity);
|
|
900
|
+
HeredocHandler.install(childShell, terminal);
|
|
901
|
+
if (options?.cwd)
|
|
902
|
+
childShell.setCwd(options.cwd);
|
|
903
|
+
const result = await childShell.execute(cmd, {
|
|
904
|
+
...options,
|
|
905
|
+
commandContext: {
|
|
906
|
+
...options?.commandContext,
|
|
907
|
+
pid: identity.pid,
|
|
908
|
+
cred: identity.cred,
|
|
909
|
+
setUmask: identity.setUmask,
|
|
910
|
+
},
|
|
911
|
+
runAs: runAsProcess,
|
|
912
|
+
});
|
|
913
|
+
exitCode = result.exitCode;
|
|
914
|
+
return result;
|
|
915
|
+
}
|
|
916
|
+
finally {
|
|
917
|
+
self.processes.exit(childProcess.pid, exitCode);
|
|
918
|
+
}
|
|
919
|
+
},
|
|
920
|
+
};
|
|
921
|
+
registerShellEntrypointCommands(registry, shellEntrypointExecutor, kernelFs);
|
|
922
|
+
// Shell scripts that execute through the local shell still need the same
|
|
923
|
+
// process-table and log-store contract as facet-backed processes.
|
|
924
|
+
const shellExecuteTracked = async (cmd, cmdCtx, opts = {}) => {
|
|
925
|
+
const entry = self.processes.spawn(cmd, [cmd], cmdCtx.cwd || '/home/user', { parentPid: cmdCtx.pid });
|
|
926
|
+
const pid = entry.pid;
|
|
927
|
+
if (opts.longRunning)
|
|
928
|
+
self.processes.setLongRunning(pid);
|
|
929
|
+
const startedAt = Date.now();
|
|
930
|
+
// Spawn banner — matches facet-manager.ts onSpawn format.
|
|
931
|
+
if (terminal) {
|
|
932
|
+
const label = opts.longRunning ? 'started (long-running)' : 'started';
|
|
933
|
+
terminal.write(`\x1b[2m[shell ${label}: pid=${pid} cmd="${cmd}"]\x1b[0m\r\n`);
|
|
934
|
+
}
|
|
935
|
+
// Structured spawn event for the tabs UI (mirrors the facet-manager
|
|
936
|
+
// onSpawn hook). Long-running shell commands like `vite` and
|
|
937
|
+
// `wrangler dev` trigger auto-open of a log tab.
|
|
938
|
+
notifyTerminalEvent(terminal, {
|
|
939
|
+
type: 'spawn', pid, command: cmd, longRunning: !!opts.longRunning, attachedTty: false,
|
|
940
|
+
});
|
|
941
|
+
// Wrap the caller-supplied streams so every chunk is both displayed
|
|
942
|
+
// AND captured in the ring buffer keyed by this PID.
|
|
943
|
+
const tee = (stream, target) => {
|
|
944
|
+
const toTarget = textSink((text) => target.write(text));
|
|
945
|
+
return (d) => {
|
|
946
|
+
try {
|
|
947
|
+
self.processes.appendOutputBytes(pid, stream, d);
|
|
948
|
+
}
|
|
949
|
+
catch { }
|
|
950
|
+
try {
|
|
951
|
+
toTarget(d);
|
|
952
|
+
}
|
|
953
|
+
catch { }
|
|
954
|
+
};
|
|
955
|
+
};
|
|
956
|
+
let exitCode = 1;
|
|
957
|
+
try {
|
|
958
|
+
const result = await shell.execute(cmd, {
|
|
959
|
+
cwd: cmdCtx.cwd,
|
|
960
|
+
env: cmdCtx.env,
|
|
961
|
+
onStdout: tee('stdout', cmdCtx.stdout),
|
|
962
|
+
onStderr: tee('stderr', cmdCtx.stderr),
|
|
963
|
+
// The tee is a sink, not a redirection: the script's fds are still
|
|
964
|
+
// whatever the caller's were, and a runtime asks that question before
|
|
965
|
+
// deciding whether it may stream past the shell.
|
|
966
|
+
terminalFds: {
|
|
967
|
+
stdin: cmdCtx.isFdTerminal?.(0) ?? false,
|
|
968
|
+
stdout: cmdCtx.isFdTerminal?.(1) ?? false,
|
|
969
|
+
stderr: cmdCtx.isFdTerminal?.(2) ?? false,
|
|
970
|
+
},
|
|
971
|
+
// Single spawn path for long-running handoff: a registry command
|
|
972
|
+
// (vite/wrangler/serve) ADOPTS this wrapper pid via the bin-spawn
|
|
973
|
+
// contract instead of allocating a second one, and suppresses its
|
|
974
|
+
// own `[started (long-running)]` notice.
|
|
975
|
+
commandContext: {
|
|
976
|
+
pid,
|
|
977
|
+
cred: entry.cred,
|
|
978
|
+
setUmask: (mask) => self.processes.setUmask(pid, mask),
|
|
979
|
+
...(opts.longRunning
|
|
980
|
+
? {
|
|
981
|
+
__nimbusBinSpawn: {
|
|
982
|
+
skipSpawn: true,
|
|
983
|
+
callerPid: pid,
|
|
984
|
+
command: cmd,
|
|
985
|
+
forceLongRunning: true,
|
|
986
|
+
},
|
|
987
|
+
}
|
|
988
|
+
: {}),
|
|
989
|
+
},
|
|
990
|
+
runAs: runAsProcess,
|
|
991
|
+
});
|
|
992
|
+
exitCode = result.exitCode;
|
|
993
|
+
}
|
|
994
|
+
catch (e) {
|
|
995
|
+
// Surface the error in the terminal and the ring buffer.
|
|
996
|
+
const msg = (e && (e.stack || e.message)) || String(e);
|
|
997
|
+
const line = 'shellExecuteTracked error: ' + msg + '\n';
|
|
998
|
+
try {
|
|
999
|
+
self.processes.appendOutput(pid, 'stderr', line);
|
|
1000
|
+
}
|
|
1001
|
+
catch { }
|
|
1002
|
+
try {
|
|
1003
|
+
cmdCtx.stderr.write(line);
|
|
1004
|
+
}
|
|
1005
|
+
catch { }
|
|
1006
|
+
exitCode = 1;
|
|
1007
|
+
}
|
|
1008
|
+
finally {
|
|
1009
|
+
// When a long-running script handed off to a live server (the registry
|
|
1010
|
+
// command adopted this pid and returned 0), the process stays running;
|
|
1011
|
+
// emitting an immediate exit would print a false `[shell exited]` and
|
|
1012
|
+
// flip the process to terminated in /api/processes. Mirror the npm-bin
|
|
1013
|
+
// resolver's `handedOffToLongRunningFacet` contract.
|
|
1014
|
+
const handedOffToLongRunningFacet = opts.longRunning === true && exitCode === 0;
|
|
1015
|
+
if (!handedOffToLongRunningFacet) {
|
|
1016
|
+
try {
|
|
1017
|
+
self.processes.exit(pid, exitCode);
|
|
1018
|
+
}
|
|
1019
|
+
catch { }
|
|
1020
|
+
try {
|
|
1021
|
+
if (!self.processes.getExit(pid)) {
|
|
1022
|
+
self.processes.markExit(pid, exitCode);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
catch { }
|
|
1026
|
+
// Structured exit for the tabs UI. Always fires (the UI doesn't
|
|
1027
|
+
// know which tabs are open, and client-side dedupe is trivial).
|
|
1028
|
+
// Include the command so the UI can backfill a tab for pids it
|
|
1029
|
+
// never saw a spawn event for (e.g. evals routed past onSpawn).
|
|
1030
|
+
notifyTerminalEvent(terminal, { type: 'exit', pid, code: exitCode, command: cmd });
|
|
1031
|
+
// Keep shell execution diagnostics on the same session helper used by
|
|
1032
|
+
// the rest of the process subsystem.
|
|
1033
|
+
try {
|
|
1034
|
+
self._emitShellExecDone(pid, cmd, exitCode, Date.now() - startedAt);
|
|
1035
|
+
}
|
|
1036
|
+
catch { }
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
return exitCode;
|
|
1040
|
+
};
|
|
1041
|
+
const runtimeCommandHint = createRuntimeCommandHintResolver(self.env);
|
|
1042
|
+
installNpmBinFallbackResolver(registry, {
|
|
1043
|
+
vfs: kernelFs,
|
|
1044
|
+
getCwd: () => shell?.cwd || '/home/user',
|
|
1045
|
+
processes: self.processes,
|
|
1046
|
+
getFacetManager: () => {
|
|
1047
|
+
self.ensureFacetManager();
|
|
1048
|
+
return facetMgr;
|
|
1049
|
+
},
|
|
1050
|
+
terminal: terminal,
|
|
1051
|
+
notifyTerminalEvent: (event) => notifyTerminalEvent(terminal, event),
|
|
1052
|
+
runtimeCommandHint,
|
|
1053
|
+
emitShellExecDone: (pid, command, exitCode, durationMs) => {
|
|
1054
|
+
try {
|
|
1055
|
+
self._emitShellExecDone(pid, command, exitCode, durationMs);
|
|
1056
|
+
}
|
|
1057
|
+
catch { }
|
|
1058
|
+
},
|
|
1059
|
+
});
|
|
1060
|
+
// Register core npm — the install work itself goes through the port,
|
|
1061
|
+
// which owns the NpmInstaller, prefix dirs and bin materialisation.
|
|
1062
|
+
const coreNpmCmd = createNpmCommand(registry, shellExecute, kernel, {
|
|
1063
|
+
installer: createNpmInstallPort(self),
|
|
1064
|
+
});
|
|
1065
|
+
registry.register('npm', async (ctx) => {
|
|
1066
|
+
const args = ctx.args || [];
|
|
1067
|
+
const sub = args[0];
|
|
1068
|
+
const cwdKey = normalizeVfsPath(ctx.cwd || '/home/user');
|
|
1069
|
+
// npm run <script> / npm test / npm start — parse package.json and execute
|
|
1070
|
+
if (sub === 'run' || sub === 'run-script' || sub === 'test' || sub === 'start') {
|
|
1071
|
+
const scriptName = sub === 'test' ? 'test' : sub === 'start' ? 'start' : args[1];
|
|
1072
|
+
if (!scriptName) {
|
|
1073
|
+
// npm run (no script) — list available scripts
|
|
1074
|
+
const pkgPath = cwdKey + '/package.json';
|
|
1075
|
+
try {
|
|
1076
|
+
const pkg = JSON.parse(kernelFs.readFileString(pkgPath));
|
|
1077
|
+
if (pkg.scripts && Object.keys(pkg.scripts).length > 0) {
|
|
1078
|
+
ctx.stdout.write('Lifecycle scripts:\n');
|
|
1079
|
+
for (const [name, cmd] of Object.entries(pkg.scripts)) {
|
|
1080
|
+
ctx.stdout.write(` ${name}\n ${cmd}\n`);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
else {
|
|
1084
|
+
ctx.stdout.write('No scripts found in package.json\n');
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
catch {
|
|
1088
|
+
ctx.stderr.write('npm ERR! no package.json found\n');
|
|
1089
|
+
return 1;
|
|
1090
|
+
}
|
|
1091
|
+
return 0;
|
|
1092
|
+
}
|
|
1093
|
+
const pkgPath = cwdKey + '/package.json';
|
|
1094
|
+
try {
|
|
1095
|
+
const pkg = JSON.parse(kernelFs.readFileString(pkgPath));
|
|
1096
|
+
const script = pkg.scripts?.[scriptName];
|
|
1097
|
+
if (!script) {
|
|
1098
|
+
ctx.stderr.write(`npm ERR! Missing script: "${scriptName}"\n`);
|
|
1099
|
+
if (pkg.scripts) {
|
|
1100
|
+
ctx.stderr.write('npm ERR! Available scripts:\n');
|
|
1101
|
+
for (const name of Object.keys(pkg.scripts))
|
|
1102
|
+
ctx.stderr.write(` - ${name}\n`);
|
|
1103
|
+
}
|
|
1104
|
+
return 1;
|
|
1105
|
+
}
|
|
1106
|
+
// ── node_modules preflight ────────────────────────────────────
|
|
1107
|
+
// If the script invokes a known bundler/framework CLI (vite, next,
|
|
1108
|
+
// webpack, tsc, ...) and node_modules is missing, HARD-FAIL before
|
|
1109
|
+
// running it — the tool would crash with a cryptic "command not
|
|
1110
|
+
// found" / "cannot find package" error that's less helpful.
|
|
1111
|
+
// For custom/unknown scripts (e.g. `echo hi`), emit a warning but
|
|
1112
|
+
// continue — the user's intent might not need deps at all.
|
|
1113
|
+
// Bypass with --force / --no-install-check in the script args, or
|
|
1114
|
+
// by setting NIMBUS_SKIP_INSTALL_CHECK=1 in env.
|
|
1115
|
+
const scriptArgs = args.slice(sub === 'run' || sub === 'run-script' ? 2 : 1);
|
|
1116
|
+
const bypassRunCheck = scriptArgs.includes('--force') ||
|
|
1117
|
+
scriptArgs.includes('--no-install-check') ||
|
|
1118
|
+
ctx.env?.NIMBUS_SKIP_INSTALL_CHECK === '1';
|
|
1119
|
+
if (!bypassRunCheck) {
|
|
1120
|
+
const guard = checkNodeModulesGuard(kernelFs, cwdKey);
|
|
1121
|
+
if (guard.missing) {
|
|
1122
|
+
const bundler = detectBundlerBin(script);
|
|
1123
|
+
if (bundler) {
|
|
1124
|
+
// Hard fail: script needs a bundler binary that lives in node_modules/.bin.
|
|
1125
|
+
ctx.stderr.write('\x1b[31m\u2718\x1b[0m \x1b[1mnode_modules/ not found\x1b[0m — ' +
|
|
1126
|
+
`script "${scriptName}" runs \x1b[36m${bundler}\x1b[0m which needs installed dependencies ` +
|
|
1127
|
+
`(${guard.depCount} declared).\n` +
|
|
1128
|
+
' Run \x1b[36mnpm install\x1b[0m first,\n' +
|
|
1129
|
+
' or re-run with \x1b[36mnpm run ' + scriptName + ' -- --force\x1b[0m to skip this check.\n');
|
|
1130
|
+
return 1;
|
|
1131
|
+
}
|
|
1132
|
+
// Soft warning: script might not need deps; let it try.
|
|
1133
|
+
ctx.stderr.write('\x1b[33m\u26A0\x1b[0m node_modules/ not found (' + guard.depCount + ' deps declared) — ' +
|
|
1134
|
+
'proceeding anyway. Run \x1b[36mnpm install\x1b[0m if the script fails.\n\n');
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
ctx.stdout.write(`\n> ${pkg.name || 'project'}@${pkg.version || '1.0.0'} ${scriptName}\n`);
|
|
1138
|
+
ctx.stdout.write(`> ${script}\n\n`);
|
|
1139
|
+
// ── Next.js loud-block (was W11 per-framework substrate) ──────
|
|
1140
|
+
//
|
|
1141
|
+
// runtime primitive support (P12): the previous wave shipped this as a
|
|
1142
|
+
// 45-line standalone module at src/frameworks/next.ts that
|
|
1143
|
+
// exported nothing but the strings used here. Per the
|
|
1144
|
+
// "no per-framework substrate" rule, the message is inlined
|
|
1145
|
+
// (the only thing the module did was hold these strings) and
|
|
1146
|
+
// the file is deleted.
|
|
1147
|
+
//
|
|
1148
|
+
// Next.js dev/start/build/export all need the same pipeline —
|
|
1149
|
+
// custom http.Server + child_process.fork with v8-IPC +
|
|
1150
|
+
// webpack/Turbopack — none of which Nimbus ships. We surface a
|
|
1151
|
+
// deterministic refusal rather than letting the script hang or
|
|
1152
|
+
// (build) reset the isolate during spawn. The block remains a
|
|
1153
|
+
// one-off symbol-detection guard, NOT a generic per-framework
|
|
1154
|
+
// code path. Any future similar guard belongs alongside this
|
|
1155
|
+
// one — not in its own src/frameworks/<name>.ts file.
|
|
1156
|
+
const refused = refusedNextSubcommand(scriptName, script, pkg, scriptArgs);
|
|
1157
|
+
if (refused) {
|
|
1158
|
+
ctx.stderr.write(NEXT_REFUSAL_MESSAGE);
|
|
1159
|
+
return 127;
|
|
1160
|
+
}
|
|
1161
|
+
const scriptTrim = script.trim();
|
|
1162
|
+
const longRunning = scriptName === 'dev' || scriptName === 'start' ||
|
|
1163
|
+
scriptName === 'serve' || scriptName === 'watch';
|
|
1164
|
+
return await shellExecuteTracked(scriptTrim, {
|
|
1165
|
+
...ctx,
|
|
1166
|
+
env: { ...ctx.env, npm_lifecycle_event: scriptName, npm_package_name: pkg.name || '' },
|
|
1167
|
+
}, { longRunning });
|
|
1168
|
+
}
|
|
1169
|
+
catch (e) {
|
|
1170
|
+
ctx.stderr.write(`npm ERR! ${e?.message || e}\n`);
|
|
1171
|
+
return 1;
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
// npm ls — list installed packages
|
|
1175
|
+
if (sub === 'ls' || sub === 'list') {
|
|
1176
|
+
const pkgPath = cwdKey + '/package.json';
|
|
1177
|
+
const nmDir = cwdKey + '/node_modules';
|
|
1178
|
+
try {
|
|
1179
|
+
const pkg = JSON.parse(kernelFs.readFileString(pkgPath));
|
|
1180
|
+
ctx.stdout.write(`${pkg.name || 'project'}@${pkg.version || '1.0.0'} ${ctx.cwd}\n`);
|
|
1181
|
+
const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
|
|
1182
|
+
const names = Object.keys(deps);
|
|
1183
|
+
for (let i = 0; i < names.length; i++) {
|
|
1184
|
+
const isLast = i === names.length - 1;
|
|
1185
|
+
const prefix = isLast ? '└── ' : '├── ';
|
|
1186
|
+
const name = names[i];
|
|
1187
|
+
let version = deps[name];
|
|
1188
|
+
// Try to read actual installed version
|
|
1189
|
+
try {
|
|
1190
|
+
const installed = JSON.parse(kernelFs.readFileString(nmDir + '/' + name + '/package.json'));
|
|
1191
|
+
version = installed.version;
|
|
1192
|
+
}
|
|
1193
|
+
catch { }
|
|
1194
|
+
ctx.stdout.write(`${prefix}${name}@${version}\n`);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
catch {
|
|
1198
|
+
ctx.stderr.write('npm ERR! no package.json found\n');
|
|
1199
|
+
return 1;
|
|
1200
|
+
}
|
|
1201
|
+
return 0;
|
|
1202
|
+
}
|
|
1203
|
+
// npm init / npm init -y
|
|
1204
|
+
if (sub === 'init') {
|
|
1205
|
+
const cwd = cwdKey;
|
|
1206
|
+
const pkgPath = cwd + '/package.json';
|
|
1207
|
+
if (kernelFs.exists(pkgPath) && !args.includes('-y') && !args.includes('--yes')) {
|
|
1208
|
+
ctx.stderr.write('package.json already exists. Use -y to overwrite.\n');
|
|
1209
|
+
return 1;
|
|
1210
|
+
}
|
|
1211
|
+
const name = cwd.split('/').pop() || 'project';
|
|
1212
|
+
const pkg = {
|
|
1213
|
+
name, version: '1.0.0', description: '', main: 'index.js',
|
|
1214
|
+
type: 'module',
|
|
1215
|
+
scripts: { dev: 'vite', build: 'vite build', preview: 'vite preview', test: 'echo "no test"' },
|
|
1216
|
+
keywords: [], author: '', license: 'MIT', dependencies: {}, devDependencies: {},
|
|
1217
|
+
};
|
|
1218
|
+
kernelFs.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
1219
|
+
ctx.stdout.write('Wrote to ' + pkgPath + '\n');
|
|
1220
|
+
return 0;
|
|
1221
|
+
}
|
|
1222
|
+
// npm uninstall <pkg>
|
|
1223
|
+
if (sub === 'uninstall' || sub === 'un' || sub === 'remove' || sub === 'rm') {
|
|
1224
|
+
const packages = args.slice(1).filter(a => !a.startsWith('-'));
|
|
1225
|
+
if (packages.length === 0) {
|
|
1226
|
+
ctx.stderr.write('Usage: npm uninstall <pkg>\n');
|
|
1227
|
+
return 1;
|
|
1228
|
+
}
|
|
1229
|
+
const nmDir = cwdKey + '/node_modules';
|
|
1230
|
+
for (const pkg of packages) {
|
|
1231
|
+
const pkgDir = nmDir + '/' + pkg;
|
|
1232
|
+
// Recursively delete package directory
|
|
1233
|
+
const deleteRecursive = (dir) => {
|
|
1234
|
+
try {
|
|
1235
|
+
for (const e of kernelFs.readdir(dir)) {
|
|
1236
|
+
const fp = dir + '/' + e.name;
|
|
1237
|
+
if (e.type === 'directory')
|
|
1238
|
+
deleteRecursive(fp);
|
|
1239
|
+
else
|
|
1240
|
+
try {
|
|
1241
|
+
kernelFs.unlink(fp);
|
|
1242
|
+
}
|
|
1243
|
+
catch { }
|
|
1244
|
+
}
|
|
1245
|
+
try {
|
|
1246
|
+
kernelFs.rmdir(dir);
|
|
1247
|
+
}
|
|
1248
|
+
catch { }
|
|
1249
|
+
}
|
|
1250
|
+
catch { }
|
|
1251
|
+
};
|
|
1252
|
+
deleteRecursive(pkgDir);
|
|
1253
|
+
ctx.stdout.write('removed ' + pkg + '\n');
|
|
1254
|
+
}
|
|
1255
|
+
// Update package.json
|
|
1256
|
+
const pkgPath = cwdKey + '/package.json';
|
|
1257
|
+
try {
|
|
1258
|
+
const pkgJson = JSON.parse(kernelFs.readFileString(pkgPath));
|
|
1259
|
+
for (const pkg of packages) {
|
|
1260
|
+
delete pkgJson.dependencies?.[pkg];
|
|
1261
|
+
delete pkgJson.devDependencies?.[pkg];
|
|
1262
|
+
}
|
|
1263
|
+
kernelFs.writeFile(pkgPath, JSON.stringify(pkgJson, null, 2) + '\n');
|
|
1264
|
+
}
|
|
1265
|
+
catch { }
|
|
1266
|
+
return 0;
|
|
1267
|
+
}
|
|
1268
|
+
// ── npm create <pkg> / npm init <pkg> → npx create-<pkg> ─────────
|
|
1269
|
+
//
|
|
1270
|
+
// Per the npm spec, `npm create X args...` and `npm init X args...`
|
|
1271
|
+
// (when X is supplied) are sugar for invoking the `create-X`
|
|
1272
|
+
// initializer package via npx. Specifically:
|
|
1273
|
+
//
|
|
1274
|
+
// npm create foo args... → npx create-foo args...
|
|
1275
|
+
// npm create foo@1.2 args... → npx create-foo@1.2 args...
|
|
1276
|
+
// npm create @scope/foo args... → npx @scope/create-foo args...
|
|
1277
|
+
// npm create @scope args... → npx @scope/create args...
|
|
1278
|
+
//
|
|
1279
|
+
// `npm init` (no args) is a different beast — it scaffolds a
|
|
1280
|
+
// package.json interactively. The `sub === 'init'` branch above
|
|
1281
|
+
// handles the no-arg case; here we only intercept the
|
|
1282
|
+
// initializer-package case (1+ args after `init`).
|
|
1283
|
+
//
|
|
1284
|
+
// Without this routing, `npm create vite@latest mvp -- --template
|
|
1285
|
+
// react-ts` hits the base npm dispatch which only knows
|
|
1286
|
+
// {init, install/i/add, uninstall/remove/rm/un, list/ls,
|
|
1287
|
+
// run/run-script, start, test, info/view/show, search, version}
|
|
1288
|
+
// — and emits "npm: unknown command 'create'". Every modern
|
|
1289
|
+
// framework's `create-*` flow (create-vite, create-next-app
|
|
1290
|
+
// routed via "npm create", create-cloudflare, create-astro, etc.)
|
|
1291
|
+
// depends on this.
|
|
1292
|
+
//
|
|
1293
|
+
// This is a primitive: one fix, every framework wins.
|
|
1294
|
+
if (sub === 'create' || (sub === 'init' && args.length >= 2 && !args[1].startsWith('-'))) {
|
|
1295
|
+
const arg1 = args[1];
|
|
1296
|
+
if (!arg1) {
|
|
1297
|
+
ctx.stderr.write('npm create: missing package name\n');
|
|
1298
|
+
ctx.stderr.write('Usage: npm create <pkg> [args...]\n');
|
|
1299
|
+
return 1;
|
|
1300
|
+
}
|
|
1301
|
+
// Parse pkg + version. Scope-aware:
|
|
1302
|
+
// @scope → @scope/create
|
|
1303
|
+
// @scope/foo → @scope/create-foo
|
|
1304
|
+
// foo → create-foo
|
|
1305
|
+
// foo@1.2.3 → create-foo@1.2.3
|
|
1306
|
+
// foo@latest → create-foo@latest
|
|
1307
|
+
function rewriteToCreatePkg(spec) {
|
|
1308
|
+
// Strip an optional version range and re-append after the rewrite.
|
|
1309
|
+
const atIdx = spec.lastIndexOf('@');
|
|
1310
|
+
const hasVersion = atIdx > 0; // a leading @ is the scope; not a version
|
|
1311
|
+
const bare = hasVersion ? spec.slice(0, atIdx) : spec;
|
|
1312
|
+
const version = hasVersion ? spec.slice(atIdx) : '';
|
|
1313
|
+
let pkg;
|
|
1314
|
+
if (bare.startsWith('@')) {
|
|
1315
|
+
const slash = bare.indexOf('/');
|
|
1316
|
+
if (slash < 0) {
|
|
1317
|
+
// @scope → @scope/create
|
|
1318
|
+
pkg = bare + '/create';
|
|
1319
|
+
}
|
|
1320
|
+
else {
|
|
1321
|
+
// @scope/foo → @scope/create-foo
|
|
1322
|
+
const scope = bare.slice(0, slash);
|
|
1323
|
+
const name = bare.slice(slash + 1);
|
|
1324
|
+
pkg = scope + '/create-' + name;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
else {
|
|
1328
|
+
pkg = 'create-' + bare;
|
|
1329
|
+
}
|
|
1330
|
+
return pkg + version;
|
|
1331
|
+
}
|
|
1332
|
+
const createPkg = rewriteToCreatePkg(arg1);
|
|
1333
|
+
const passThrough = args.slice(2);
|
|
1334
|
+
// `npm create` accepts an optional `--` separator to push the
|
|
1335
|
+
// remaining args to the create script; npx doesn't need a
|
|
1336
|
+
// separator (positional args after the package name go to the
|
|
1337
|
+
// package). We strip a single literal `--` token if present so
|
|
1338
|
+
// `npm create vite@latest mvp -- --template react-ts` becomes
|
|
1339
|
+
// `npx --yes create-vite@latest mvp --template react-ts`.
|
|
1340
|
+
const stripped = passThrough.filter((a, i, arr) => !(a === '--' && i < arr.length - 1) && !(a === '--' && arr.indexOf('--') === i));
|
|
1341
|
+
// Inform the user what we're routing to — matches npm's own
|
|
1342
|
+
// visible "npx" line so the create flow is honest.
|
|
1343
|
+
ctx.stdout.write(`> npx --yes ${createPkg}${stripped.length ? ' ' + stripped.join(' ') : ''}\n`);
|
|
1344
|
+
// Dispatch through the npx registry entry. `--yes` skips the
|
|
1345
|
+
// "Ok to proceed? (y)" prompt.
|
|
1346
|
+
const npxHandler = await registry.resolve('npx');
|
|
1347
|
+
if (!npxHandler) {
|
|
1348
|
+
ctx.stderr.write('npm create: npx command unavailable\n');
|
|
1349
|
+
return 1;
|
|
1350
|
+
}
|
|
1351
|
+
return await npxHandler({
|
|
1352
|
+
...ctx,
|
|
1353
|
+
args: ['--yes', createPkg, ...stripped],
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
// Fall through to core npm for other subcommands
|
|
1357
|
+
return coreNpmCmd(ctx);
|
|
1358
|
+
});
|
|
1359
|
+
// npx: check registered commands first, then resolve/install through
|
|
1360
|
+
// Nimbus's NpmInstaller and execute the package bin via the Node runtime.
|
|
1361
|
+
registry.register('npx', async (ctx) => {
|
|
1362
|
+
const npxArgs = ctx.args || [];
|
|
1363
|
+
const { describeNpxSelfInvocation, formatNpxHelp, getNpxCommandArgs, getNpxCommandWord, resolveNpxBinary, } = await import('../npm/npx-install.js');
|
|
1364
|
+
const selfInvocation = describeNpxSelfInvocation(npxArgs);
|
|
1365
|
+
if (selfInvocation === 'missing') {
|
|
1366
|
+
ctx.stderr.write('Usage: npx <command> [args...]\n');
|
|
1367
|
+
return 1;
|
|
1368
|
+
}
|
|
1369
|
+
if (selfInvocation === 'version') {
|
|
1370
|
+
ctx.stdout.write(NPM_VERSION + '\n');
|
|
1371
|
+
return 0;
|
|
1372
|
+
}
|
|
1373
|
+
if (selfInvocation === 'help') {
|
|
1374
|
+
ctx.stdout.write(formatNpxHelp());
|
|
1375
|
+
return 0;
|
|
1376
|
+
}
|
|
1377
|
+
const cmd = getNpxCommandWord(npxArgs);
|
|
1378
|
+
// Check if it's a built-in command (vite, esbuild, etc.)
|
|
1379
|
+
const resolved = cmd ? await registry.resolve(cmd) : null;
|
|
1380
|
+
if (resolved) {
|
|
1381
|
+
return await resolved({ ...ctx, args: getNpxCommandArgs(npxArgs) });
|
|
1382
|
+
}
|
|
1383
|
+
// Nimbus-native npx install + run path. Routes package installation
|
|
1384
|
+
// through NpmInstaller's full-packument resolver.
|
|
1385
|
+
await self.ensureNpmInstaller((msg) => ctx.stdout.write('[npm] ' + msg + '\n'));
|
|
1386
|
+
self.ensureSqliteFs();
|
|
1387
|
+
const installer = self.npmInstaller;
|
|
1388
|
+
const resolveResult = await resolveNpxBinary(installer, sqliteFs.as(requireVfsCred('cred' in ctx ? ctx.cred : undefined, 'npx')), ctx.cwd || '/home/user', npxArgs, (msg) => ctx.stdout.write(msg + '\n'), ctx.pid);
|
|
1389
|
+
if (resolveResult.ok && resolveResult.binPath) {
|
|
1390
|
+
const nodeCmd = await registry.resolve('node');
|
|
1391
|
+
if (nodeCmd) {
|
|
1392
|
+
return await nodeCmd({
|
|
1393
|
+
...ctx,
|
|
1394
|
+
args: [resolveResult.binPath, ...(resolveResult.binArgs || [])],
|
|
1395
|
+
__nimbusBundleProfile: resolveResult.bundleProfile,
|
|
1396
|
+
});
|
|
1397
|
+
}
|
|
1398
|
+
ctx.stderr.write('npx: node runtime is not registered\n');
|
|
1399
|
+
return 1;
|
|
1400
|
+
}
|
|
1401
|
+
ctx.stderr.write((resolveResult.error || 'npx: could not resolve binary') + '\n');
|
|
1402
|
+
return 1;
|
|
1403
|
+
});
|
|
1404
|
+
// ── Register process commands (enhanced with facet process tracking) ──
|
|
1405
|
+
registry.register('ps', async (ctx) => {
|
|
1406
|
+
// Pids are generation-strided (see PID_GEN_STRIDE) so they can be 7+
|
|
1407
|
+
// digits; size the column to the widest pid in this listing.
|
|
1408
|
+
const procs = self.processes.getAll();
|
|
1409
|
+
const pidWidth = Math.max(3, ...procs.map((p) => String(p.pid).length));
|
|
1410
|
+
ctx.stdout.write(` ${'PID'.padStart(pidWidth)} STATUS COMMAND\n`);
|
|
1411
|
+
for (const proc of procs) {
|
|
1412
|
+
// Prefer log-store exit info over ProcessTable's: the store has
|
|
1413
|
+
// the authoritative code and survives reap. For `running`, rely
|
|
1414
|
+
// on ProcessTable (store has no "running" concept).
|
|
1415
|
+
let status;
|
|
1416
|
+
if (proc.state === 'running') {
|
|
1417
|
+
status = '\x1b[32mrunning\x1b[0m';
|
|
1418
|
+
}
|
|
1419
|
+
else if (proc.state === 'killed') {
|
|
1420
|
+
status = `\x1b[33mkilled(${proc.exitCode ?? 137})\x1b[0m`;
|
|
1421
|
+
}
|
|
1422
|
+
else {
|
|
1423
|
+
// 'exited' — distinguish clean vs crashed.
|
|
1424
|
+
const code = proc.exitCode ?? 0;
|
|
1425
|
+
status = code === 0
|
|
1426
|
+
? `\x1b[2mexited(0)\x1b[0m`
|
|
1427
|
+
: `\x1b[31mcrashed(${code})\x1b[0m`;
|
|
1428
|
+
}
|
|
1429
|
+
ctx.stdout.write(` ${String(proc.pid).padStart(pidWidth)} ${status.padEnd(26)} ${proc.command}\n`);
|
|
1430
|
+
}
|
|
1431
|
+
// Show vite dev server
|
|
1432
|
+
if (self.viteDevServer?.isRunning) {
|
|
1433
|
+
ctx.stdout.write(` \x1b[33m${'---'.padStart(pidWidth)}\x1b[0m \x1b[32mrunning\x1b[0m vite dev server (${self.viteBasePath}/)\n`);
|
|
1434
|
+
}
|
|
1435
|
+
if (self.processes.getAll().length === 0 && !self.viteDevServer?.isRunning) {
|
|
1436
|
+
ctx.stdout.write(' (no processes)\n');
|
|
1437
|
+
}
|
|
1438
|
+
return 0;
|
|
1439
|
+
});
|
|
1440
|
+
// ── `logs <pid>` — tail per-process ring buffer ──
|
|
1441
|
+
// Flags:
|
|
1442
|
+
// -f / --follow stream new chunks until the process exits
|
|
1443
|
+
// -n / --lines N number of lines from the tail (default 200)
|
|
1444
|
+
// --bytes N max bytes from the tail (overrides --lines)
|
|
1445
|
+
// --plain strip ANSI escapes on output (keeps buffer raw)
|
|
1446
|
+
registry.register('logs', async (ctx) => {
|
|
1447
|
+
const args = ctx.args || [];
|
|
1448
|
+
const follow = args.includes('-f') || args.includes('--follow');
|
|
1449
|
+
const plain = args.includes('--plain');
|
|
1450
|
+
let lines = 200;
|
|
1451
|
+
let bytes;
|
|
1452
|
+
for (let i = 0; i < args.length; i++) {
|
|
1453
|
+
const a = args[i];
|
|
1454
|
+
if ((a === '-n' || a === '--lines') && args[i + 1]) {
|
|
1455
|
+
const n = parseInt(args[i + 1], 10);
|
|
1456
|
+
if (!isNaN(n) && n > 0)
|
|
1457
|
+
lines = n;
|
|
1458
|
+
i++;
|
|
1459
|
+
}
|
|
1460
|
+
else if (a === '--bytes' && args[i + 1]) {
|
|
1461
|
+
const n = parseInt(args[i + 1], 10);
|
|
1462
|
+
if (!isNaN(n) && n > 0)
|
|
1463
|
+
bytes = n;
|
|
1464
|
+
i++;
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
const pidArg = args.find(a => /^\d+$/.test(a));
|
|
1468
|
+
if (!pidArg) {
|
|
1469
|
+
ctx.stderr.write('usage: logs [-f] [-n LINES | --bytes N] [--plain] <pid>\n');
|
|
1470
|
+
return 1;
|
|
1471
|
+
}
|
|
1472
|
+
const pid = parseInt(pidArg, 10);
|
|
1473
|
+
if (!self.processes.hasLogs(pid)) {
|
|
1474
|
+
ctx.stderr.write(`no logs for pid ${pid}\n`);
|
|
1475
|
+
return 1;
|
|
1476
|
+
}
|
|
1477
|
+
// Paint a single chunk for live-stream (follow-mode) rendering.
|
|
1478
|
+
// `--plain` strips ANSI per chunk — safe for live output because
|
|
1479
|
+
// individual streamed chunks from the RPC layer never split an
|
|
1480
|
+
// escape sequence (the RPC boundary always delivers a complete
|
|
1481
|
+
// write call). Backfill is different (see below).
|
|
1482
|
+
const renderChunk = (c) => {
|
|
1483
|
+
let data = c.data;
|
|
1484
|
+
if (plain)
|
|
1485
|
+
data = stripAnsi(data);
|
|
1486
|
+
if (c.stream === 'stderr' && !plain) {
|
|
1487
|
+
return `\x1b[31m${data}\x1b[0m`;
|
|
1488
|
+
}
|
|
1489
|
+
return data;
|
|
1490
|
+
};
|
|
1491
|
+
// Backfill. Concatenate same-stream consecutive chunks BEFORE
|
|
1492
|
+
// stripping so that any ANSI escape split across chunk boundaries
|
|
1493
|
+
// (by the 4 KB splitter inside ProcessLogStore) gets rejoined and
|
|
1494
|
+
// stripped cleanly instead of leaking `1m` / `[31m` fragments.
|
|
1495
|
+
const tailOpts = bytes !== undefined ? { bytes } : { lines };
|
|
1496
|
+
const chunks = self.processes.tailLogs(pid, tailOpts);
|
|
1497
|
+
let group = [];
|
|
1498
|
+
const flushGroup = () => {
|
|
1499
|
+
if (group.length === 0)
|
|
1500
|
+
return;
|
|
1501
|
+
const stream = group[0].stream;
|
|
1502
|
+
let data = group.map(c => c.data).join('');
|
|
1503
|
+
if (plain)
|
|
1504
|
+
data = stripAnsi(data);
|
|
1505
|
+
if (stream === 'stderr' && !plain) {
|
|
1506
|
+
ctx.stdout.write(`\x1b[31m${data}\x1b[0m`);
|
|
1507
|
+
}
|
|
1508
|
+
else {
|
|
1509
|
+
ctx.stdout.write(data);
|
|
1510
|
+
}
|
|
1511
|
+
group = [];
|
|
1512
|
+
};
|
|
1513
|
+
for (const c of chunks) {
|
|
1514
|
+
if (group.length > 0 && group[group.length - 1].stream !== c.stream) {
|
|
1515
|
+
flushGroup();
|
|
1516
|
+
}
|
|
1517
|
+
group.push(c);
|
|
1518
|
+
}
|
|
1519
|
+
flushGroup();
|
|
1520
|
+
if (!follow) {
|
|
1521
|
+
// Footer only when process has exited already.
|
|
1522
|
+
const exit = self.processes.getExit(pid);
|
|
1523
|
+
if (exit) {
|
|
1524
|
+
ctx.stdout.write(`\r\n\x1b[2m[process exited with code ${exit.code}${exit.reason ? ` (${exit.reason})` : ''}]\x1b[0m\r\n`);
|
|
1525
|
+
}
|
|
1526
|
+
return 0;
|
|
1527
|
+
}
|
|
1528
|
+
// Follow mode: subscribe to live appends, poll for exit.
|
|
1529
|
+
const entry = self.processes.get(pid);
|
|
1530
|
+
const alreadyExited = !entry || entry.state !== 'running' || self.processes.getExit(pid);
|
|
1531
|
+
if (alreadyExited) {
|
|
1532
|
+
const exit = self.processes.getExit(pid);
|
|
1533
|
+
if (exit) {
|
|
1534
|
+
ctx.stdout.write(`\r\n\x1b[2m[process exited with code ${exit.code}${exit.reason ? ` (${exit.reason})` : ''}]\x1b[0m\r\n`);
|
|
1535
|
+
}
|
|
1536
|
+
return 0;
|
|
1537
|
+
}
|
|
1538
|
+
return await new Promise((resolve) => {
|
|
1539
|
+
let done = false;
|
|
1540
|
+
const finish = (code) => {
|
|
1541
|
+
if (done)
|
|
1542
|
+
return;
|
|
1543
|
+
done = true;
|
|
1544
|
+
unsub();
|
|
1545
|
+
unsubExit();
|
|
1546
|
+
resolve(code);
|
|
1547
|
+
};
|
|
1548
|
+
const unsub = self.processes.subscribeLogs(pid, (c) => {
|
|
1549
|
+
ctx.stdout.write(renderChunk(c));
|
|
1550
|
+
});
|
|
1551
|
+
const unsubExit = self.processes.subscribeExit(pid, (exit) => {
|
|
1552
|
+
ctx.stdout.write(`\r\n\x1b[2m[process exited with code ${exit.code}${exit.reason ? ` (${exit.reason})` : ''}]\x1b[0m\r\n`);
|
|
1553
|
+
finish(0);
|
|
1554
|
+
});
|
|
1555
|
+
// TOCTOU: the process may have exited between our `alreadyExited`
|
|
1556
|
+
// check above and these subscribe calls. Re-check now that the
|
|
1557
|
+
// exit subscriber is wired — if exit already set, the subscribe
|
|
1558
|
+
// callback never fires, so synthesize the footer ourselves.
|
|
1559
|
+
const exitNow = self.processes.getExit(pid);
|
|
1560
|
+
if (exitNow) {
|
|
1561
|
+
ctx.stdout.write(`\r\n\x1b[2m[process exited with code ${exitNow.code}${exitNow.reason ? ` (${exitNow.reason})` : ''}]\x1b[0m\r\n`);
|
|
1562
|
+
finish(0);
|
|
1563
|
+
return;
|
|
1564
|
+
}
|
|
1565
|
+
// If ctx exposes an AbortSignal (Ctrl+C wired by the shell),
|
|
1566
|
+
// honor it. Otherwise, follow-mode ends only on process exit.
|
|
1567
|
+
if (ctx.signal && typeof ctx.signal.addEventListener === 'function') {
|
|
1568
|
+
ctx.signal.addEventListener('abort', () => finish(130));
|
|
1569
|
+
}
|
|
1570
|
+
});
|
|
1571
|
+
});
|
|
1572
|
+
registry.register('jobs', async (ctx) => {
|
|
1573
|
+
const running = self.processes.getRunning();
|
|
1574
|
+
if (running.length === 0 && !self.viteDevServer?.isRunning) {
|
|
1575
|
+
ctx.stdout.write('No background jobs.\n');
|
|
1576
|
+
return 0;
|
|
1577
|
+
}
|
|
1578
|
+
for (let i = 0; i < running.length; i++) {
|
|
1579
|
+
ctx.stdout.write(`[${i + 1}] Running ${running[i].command} (pid ${running[i].pid})\n`);
|
|
1580
|
+
}
|
|
1581
|
+
if (self.viteDevServer?.isRunning) {
|
|
1582
|
+
ctx.stdout.write(`[${running.length + 1}] Running vite dev server\n`);
|
|
1583
|
+
}
|
|
1584
|
+
return 0;
|
|
1585
|
+
});
|
|
1586
|
+
const shellKillCommand = createKillCommand(processRegistry);
|
|
1587
|
+
registry.register('kill', async (ctx) => {
|
|
1588
|
+
const pidArg = ctx.args[0];
|
|
1589
|
+
if (!pidArg) {
|
|
1590
|
+
ctx.stderr.write('Usage: kill <pid>\n');
|
|
1591
|
+
return 1;
|
|
1592
|
+
}
|
|
1593
|
+
if (pidArg.startsWith('-') || pidArg.startsWith('%')) {
|
|
1594
|
+
return shellKillCommand(ctx);
|
|
1595
|
+
}
|
|
1596
|
+
const pid = parseInt(pidArg);
|
|
1597
|
+
if (isNaN(pid)) {
|
|
1598
|
+
ctx.stderr.write('kill: invalid pid\n');
|
|
1599
|
+
return 1;
|
|
1600
|
+
}
|
|
1601
|
+
if (processRegistry.get(pid)) {
|
|
1602
|
+
return shellKillCommand(ctx);
|
|
1603
|
+
}
|
|
1604
|
+
// runtime primitive support (P11): if the target is the vite shim PID
|
|
1605
|
+
// (registered by P5's long-running spawn), tear down the
|
|
1606
|
+
// in-process viteDevServer / cirrusReal too — facetManager.kill
|
|
1607
|
+
// only handles real Worker-Loader facets, and would leave the
|
|
1608
|
+
// shim running with its port registered against a dead PID.
|
|
1609
|
+
if (self._viteShimPid === pid) {
|
|
1610
|
+
try {
|
|
1611
|
+
if (self.cirrusReal?.isRunning) {
|
|
1612
|
+
self.cirrusReal.stop(self.ctx);
|
|
1613
|
+
self.cirrusReal = null;
|
|
1614
|
+
}
|
|
1615
|
+
if (self.viteDevServer?.isRunning) {
|
|
1616
|
+
self.viteDevServer.stop();
|
|
1617
|
+
self.viteDevServer = null;
|
|
1618
|
+
try {
|
|
1619
|
+
await self.ctx.storage.delete(VITE_CONFIG_KEY);
|
|
1620
|
+
}
|
|
1621
|
+
catch { }
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
catch (e) {
|
|
1625
|
+
ctx.stderr.write('kill: while stopping vite shim: ' + (e?.message || e) + '\n');
|
|
1626
|
+
}
|
|
1627
|
+
try {
|
|
1628
|
+
self.portRegistry.unregisterByPid(pid);
|
|
1629
|
+
}
|
|
1630
|
+
catch { }
|
|
1631
|
+
try {
|
|
1632
|
+
self.processes.kill(pid);
|
|
1633
|
+
}
|
|
1634
|
+
catch { }
|
|
1635
|
+
notifyTerminalEvent(terminal, {
|
|
1636
|
+
type: 'exit', pid, code: 137, command: 'vite',
|
|
1637
|
+
});
|
|
1638
|
+
self._viteShimPid = null;
|
|
1639
|
+
self._viteShimPort = null;
|
|
1640
|
+
ctx.stdout.write(`Process ${pid} killed.\n`);
|
|
1641
|
+
return 0;
|
|
1642
|
+
}
|
|
1643
|
+
if (facetMgr?.kill(pid)) {
|
|
1644
|
+
ctx.stdout.write(`Process ${pid} killed.\n`);
|
|
1645
|
+
return 0;
|
|
1646
|
+
}
|
|
1647
|
+
ctx.stderr.write(`kill: no such process: ${pid}\n`);
|
|
1648
|
+
return 1;
|
|
1649
|
+
});
|
|
1650
|
+
registry.register('top', createTopCommand(processRegistry));
|
|
1651
|
+
registry.register('watch', createWatchCommand(registry));
|
|
1652
|
+
registry.register('help', createHelpCommand(registry));
|
|
1653
|
+
// ── Rehydrate globally-installed npm packages ──
|
|
1654
|
+
try {
|
|
1655
|
+
rehydrateGlobalPackages(kernel.vfs, registry);
|
|
1656
|
+
}
|
|
1657
|
+
catch { }
|
|
1658
|
+
}
|