@nimbus-sh/worker 0.7.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.
Files changed (74) hide show
  1. package/dist/facets/manager.d.ts.map +1 -1
  2. package/dist/facets/manager.js +16 -5
  3. package/dist/facets/real-vite-hmr.d.ts +3 -1
  4. package/dist/facets/real-vite-hmr.d.ts.map +1 -1
  5. package/dist/facets/real-vite-hmr.js +18 -8
  6. package/dist/facets/ws-terminal.d.ts +9 -31
  7. package/dist/facets/ws-terminal.d.ts.map +1 -1
  8. package/dist/facets/ws-terminal.js +58 -51
  9. package/dist/hosted/commands.d.ts +12 -0
  10. package/dist/hosted/commands.d.ts.map +1 -0
  11. package/dist/hosted/commands.js +1658 -0
  12. package/dist/hosted/runtime.d.ts +114 -0
  13. package/dist/hosted/runtime.d.ts.map +1 -0
  14. package/dist/hosted/runtime.js +288 -0
  15. package/dist/hosted/services.d.ts +40 -0
  16. package/dist/hosted/services.d.ts.map +1 -0
  17. package/dist/hosted/services.js +512 -0
  18. package/dist/runtime/bash-repl.d.ts +1 -1
  19. package/dist/runtime/bash-repl.d.ts.map +1 -1
  20. package/dist/runtime/bash-repl.js +38 -4
  21. package/dist/runtime/bun-runner.js +1 -1
  22. package/dist/runtime/node-runner.d.ts +1 -1
  23. package/dist/runtime/node-runner.d.ts.map +1 -1
  24. package/dist/runtime/node-runner.js +2 -2
  25. package/dist/runtime/opencode-facet-runner.js +14 -14
  26. package/dist/runtime/package-manager.d.ts +35 -122
  27. package/dist/runtime/package-manager.d.ts.map +1 -1
  28. package/dist/runtime/package-manager.js +61 -596
  29. package/dist/runtime/process-logs-api.d.ts +1 -1
  30. package/dist/runtime/process-logs-api.d.ts.map +1 -1
  31. package/dist/runtime/process-logs-api.js +1 -1
  32. package/dist/runtime/python-repl.d.ts +2 -1
  33. package/dist/runtime/python-repl.d.ts.map +1 -1
  34. package/dist/runtime/python-repl.js +82 -59
  35. package/dist/runtime/repl-session.d.ts +9 -47
  36. package/dist/runtime/repl-session.d.ts.map +1 -1
  37. package/dist/runtime/repl-session.js +105 -105
  38. package/dist/runtime/runtime-catalog.d.ts +13 -0
  39. package/dist/runtime/runtime-catalog.d.ts.map +1 -1
  40. package/dist/runtime/runtime-catalog.js +88 -0
  41. package/dist/session/agent.d.ts +1 -21
  42. package/dist/session/agent.d.ts.map +1 -1
  43. package/dist/session/ai.d.ts +5 -1
  44. package/dist/session/ai.d.ts.map +1 -1
  45. package/dist/session/ai.js +7 -0
  46. package/dist/session/hibernation.d.ts +2 -1
  47. package/dist/session/hibernation.d.ts.map +1 -1
  48. package/dist/session/hibernation.js +7 -4
  49. package/dist/session/init.d.ts +1 -36
  50. package/dist/session/init.d.ts.map +1 -1
  51. package/dist/session/init.js +17 -1773
  52. package/dist/session/loopback.d.ts +2 -29
  53. package/dist/session/loopback.d.ts.map +1 -1
  54. package/dist/session/loopback.js +3 -27
  55. package/dist/session/nimbus-session.d.ts +22 -13
  56. package/dist/session/nimbus-session.d.ts.map +1 -1
  57. package/dist/session/nimbus-session.js +67 -484
  58. package/dist/session/npm-install-port.d.ts +3 -1
  59. package/dist/session/npm-install-port.d.ts.map +1 -1
  60. package/dist/session/programmatic.d.ts +5 -38
  61. package/dist/session/programmatic.d.ts.map +1 -1
  62. package/dist/session/programmatic.js +16 -48
  63. package/dist/session/rpc.d.ts.map +1 -1
  64. package/dist/session/rpc.js +1 -2
  65. package/dist/session/supervisor-op.d.ts +2 -2
  66. package/dist/session/supervisor-op.d.ts.map +1 -1
  67. package/dist/session/supervisor-op.js +11 -3
  68. package/dist/workspace-host.d.ts +6 -0
  69. package/dist/workspace-host.d.ts.map +1 -0
  70. package/dist/workspace-host.js +5 -0
  71. package/dist/workspace.d.ts +2 -0
  72. package/dist/workspace.d.ts.map +1 -0
  73. package/dist/workspace.js +1 -0
  74. package/package.json +16 -11
@@ -1,78 +1,28 @@
1
- /**
2
- * session/init.ts — initSession boot + shell-command registrations.
3
- *
4
- * Why this is one big function and not a class:
5
- * initSession runs once per /ws upgrade and walks the session
6
- * through Phase R (rehydrate from SQL), Phase B (compose the
7
- * workspace + register the session's commands), Phase W (attach
8
- * terminal), and (cold-only) Phase O (MOTD + framework hint). The
9
- * phases share lots of locals (vfs, kernel, registry, shell) and
10
- * ordering matters strictly — there's no interesting reuse boundary
11
- * that a class decomposition would expose.
12
- *
13
- * What it no longer does is COMPOSE the operating system. The kernel,
14
- * the provider mounts, the command registry, the coreutils, the exec
15
- * resolver, the default environment and the shell come from
16
- * `NimbusWorkspace` (@nimbus-sh/core/workspace), which an embedder off
17
- * Cloudflare builds the same way. What stays here is everything that
18
- * only makes sense with a socket, a Durable Object and a product behind
19
- * it: the terminal and its scrollback, the phase machine, the persisted
20
- * shell state, npm, git, vite, wrangler and the facet-backed runtimes.
21
- *
22
- * The function is intentionally written so that a reader sees:
23
- * 1. setPhase('rehydrate') ...
24
- * 2. setPhase('build') ... (~95% of the LOC)
25
- * 3. setPhase('online') if (cold)
26
- * 4. self._b4Phase = 'hydrated'
27
- *
28
- * `self` is typed as InitHost, a narrow view of SessionInternal plus readonly
29
- * ctx/env, so this module can use the session internals it owns without
30
- * depending on the full Durable Object class surface.
31
- *
32
- * Imports and class delegators on NimbusSession preserve back-compat:
33
- * - acceptShellWebSocket → self.initSession(ws) (S7 will extract).
34
- * - The class still has `initSession(ws)` as a delegator method.
35
- */
36
- import { Shell, createCurlCommand, createNpmCommand, NPM_VERSION, createTopCommand, createWatchCommand, createHelpCommand, rehydrateGlobalPackages, } from '@nimbus-sh/core/substrate/lifo/index.js';
37
- import { createKillCommand } from '@nimbus-sh/core/substrate/lifo/commands/system/kill.js';
38
- import { textSink } from '@nimbus-sh/core/_shared/bytes.js';
1
+ import { registerHostedCommands } from '../hosted/commands.js';
2
+ import { runtimeCatalogSource } from '../runtime/runtime-catalog.js';
39
3
  import { NimbusWorkspace } from '@nimbus-sh/core/workspace';
40
- import { CRED_KERNEL, requireVfsCred } from '@nimbus-sh/core/runtime/os-contracts.js';
4
+ import { CRED_KERNEL } from '@nimbus-sh/core/runtime/os-contracts.js';
41
5
  import { WebSocketTerminal } from '../facets/ws-terminal.js';
42
- import { EsbuildService } from '@nimbus-sh/core/runtime/esbuild-service.js';
43
- import { runFresh } from '../runtime/node-runner.js';
44
- import { runBunScript, BUN_VERSION } from '../runtime/bun-runner.js';
45
- import { buildRuntimeHandler, resolveRuntimeScriptPath, } from '@nimbus-sh/core/runtime/runtime-registry.js';
46
- import { normalizeVfsPath, parentVfsPath, resolveVfsPath, stripLeadingSlashes } from '@nimbus-sh/core/vfs/path.js';
6
+ import { parentVfsPath, stripLeadingSlashes } from '@nimbus-sh/core/vfs/path.js';
47
7
  import { errorText } from '@nimbus-sh/core/_shared/error-text.js';
48
- import { NimbusWrangler } from '../wrangler/nimbus-wrangler.js';
49
- import { filterWranglerFlags, detectBundlerBin, checkNodeModulesGuard, detectUnsupportedWranglerConfig, refusedNextSubcommand, NEXT_REFUSAL_MESSAGE, } from './helpers.js';
50
- import { createViteCommand } from './vite-command.js';
51
- import { HeredocHandler, LineEditorExtender } from '@nimbus-sh/core/shell/features.js';
52
- import { registerShellEntrypointCommands } from '@nimbus-sh/core/shell/shell-entrypoints.js';
53
- import { makeChshCommand } from '@nimbus-sh/core/substrate/lifo/shell/default-shell.js';
54
- import { installNpmBinFallbackResolver } from '../shell/npm-bin-entrypoints.js';
55
- import { createNpmInstallPort } from './npm-install-port.js';
56
- import { makeNimbusVerbHandler, createRuntimeCommandHintResolver, } from '../runtime/package-manager.js';
57
- import { rpcExposeApp, rpcListApps, rpcRemoveApp, rpcRotateLink } from './programmatic.js';
58
- import { listInstalledRuntimes, rehydrateInstalledRuntimes, registerRunnerFactory, } from '@nimbus-sh/core/runtime/installed-runtimes.js';
8
+ // Runtime factories (clang/python/ruby/bash/wasm) are imported lazily at
9
+ // first-use inside their registered handlers — see the registrations below.
10
+ // Keeping them off the top-level import graph shaves their module-eval cost
11
+ // (zod, embedded socket-kernel/shim sources, wasm loaders) out of the
12
+ // one-time Worker Startup Time paid on every fresh-isolate cold run.
59
13
  // Runtime factories (clang/python/ruby/bash/wasm) are imported lazily at
60
14
  // first-use inside their registered handlers — see the registrations below.
61
15
  // Keeping them off the top-level import graph shaves their module-eval cost
62
16
  // (zod, embedded socket-kernel/shim sources, wasm loaders) out of the
63
17
  // one-time Worker Startup Time paid on every fresh-isolate cold run.
64
18
  import { hasSeededProject, SEED_PROJECT_DIR, SEED_PROJECT_NAME, SEED_PROJECT_TILDE } from '@nimbus-sh/core/vfs/seed-project.js';
65
- import { notifyTerminalEvent } from '../runtime/process-logs-api.js';
66
19
  import { generation } from '@nimbus-sh/fabric/generation.js';
67
- import { stripAnsi } from '@nimbus-sh/core/runtime/process-logs.js';
68
- import { DEFAULT_MOUNT_POINTS, NODE_VERSION, } from '@nimbus-sh/core/constants.js';
69
- import { ensureSessionStateSchema, loadShellState, stampHydratedAt, countSessionStateKeys, loadKernelMounts, persistKernelMounts, loadScrollback, } from './state-store.js';
20
+ import { DEFAULT_MOUNT_POINTS } from '@nimbus-sh/core/constants.js';
21
+ import { ensureSessionStateSchema, loadShellState, stampHydratedAt, countSessionStateKeys, loadKernelMounts, persistKernelMounts, loadScrollback } from './state-store.js';
70
22
  import { recordRecoveryEvent } from '@nimbus-sh/platform/oom-discriminator.js';
71
23
  import { sessionAiEnv } from './ai.js';
72
- import { routeSessionLoopback } from './loopback.js';
73
24
  import { setPhase } from './init-phases.js';
74
25
  import { shellTerminalTee } from './ws.js';
75
- import { VITE_CONFIG_KEY } from './keys.js';
76
26
  function quoteShellArgument(value) {
77
27
  return `'${value.replace(/'/g, `'\\''`)}'`;
78
28
  }
@@ -217,61 +167,6 @@ export async function initSession(self, ws, options = {}) {
217
167
  if (self.shellProcessPid !== null) {
218
168
  self.processes.exit(self.shellProcessPid, 0);
219
169
  }
220
- const shellProcess = self.processes.spawn('sh', ['sh'], persisted.cwd || '/home/user');
221
- self.shellProcessPid = shellProcess.pid;
222
- const runAsProcess = async (parent, cred, argv) => {
223
- if (argv.length === 0)
224
- return 0;
225
- const child = self.processes.spawn(argv.join(' '), argv, parent.cwd, { parentPid: parent.pid, cred });
226
- const activeShell = self.shell;
227
- if (!activeShell) {
228
- self.processes.exit(child.pid, 1);
229
- throw new Error('shell is not initialized');
230
- }
231
- const identity = commandIdentityFor(child.pid);
232
- let exitCode = 1;
233
- try {
234
- const stdin = parent.stdin && parent.stdin !== parent.terminalStdin
235
- ? await parent.stdin.readAll()
236
- : undefined;
237
- const result = await activeShell.execute(argv.map(quoteShellArgument).join(' '), {
238
- cwd: parent.cwd,
239
- env: parent.env,
240
- stdin,
241
- terminalStdin: parent.terminalStdin,
242
- signal: parent.signal,
243
- isolateShellState: true,
244
- terminalFds: {
245
- stdin: parent.isFdTerminal?.(0) ?? false,
246
- stdout: parent.isFdTerminal?.(1) ?? false,
247
- stderr: parent.isFdTerminal?.(2) ?? false,
248
- },
249
- onStdout: textSink((data) => parent.stdout.write(data)),
250
- onStderr: textSink((data) => parent.stderr.write(data)),
251
- commandContext: {
252
- pid: identity.pid,
253
- cred: identity.cred,
254
- setUmask: identity.setUmask,
255
- },
256
- runAs: runAsProcess,
257
- });
258
- exitCode = result.exitCode;
259
- return exitCode;
260
- }
261
- finally {
262
- self.processes.exit(child.pid, exitCode);
263
- }
264
- };
265
- const commandIdentityFor = (pid) => ({
266
- pid,
267
- get cred() {
268
- return self.processes.cred(pid);
269
- },
270
- setUmask(mask) {
271
- self.processes.setUmask(pid, mask);
272
- },
273
- runAs: runAsProcess,
274
- });
275
170
  // ── The workspace: one recipe for kernel + mounts + shell + coreutils ──
276
171
  //
277
172
  // No `facets`: the session registers its own runtime factories below,
@@ -287,8 +182,11 @@ export async function initSession(self, ws, options = {}) {
287
182
  mounts: mountPoints,
288
183
  env: envOverlay,
289
184
  terminal: self.terminal,
290
- identity: commandIdentityFor(shellProcess.pid),
185
+ processes: self.processes,
186
+ runtimeSource: runtimeCatalogSource(self.env),
291
187
  });
188
+ self.runtimeWorkspace = workspace;
189
+ self.shellProcessPid = workspace.shellProcessPid;
292
190
  self.kernel = workspace.kernel;
293
191
  self.shell = workspace.shell;
294
192
  const kernel = workspace.kernel;
@@ -431,834 +329,6 @@ export async function initSession(self, ws, options = {}) {
431
329
  // W8: hand the registry to the cp broker so child_process.spawn from
432
330
  // a parent facet can resolve and dispatch commands the same way the
433
331
  // shell does.
434
- self._setCpRegistry(registry);
435
- registry.register('chsh', makeChshCommand({
436
- isBashInstalled: (home) => listInstalledRuntimes(sqliteFs, home).some((runtime) => runtime.name === 'bash'),
437
- }));
438
- // ── Git integration (isomorphic-git) ──
439
- // ctx + env are passed for clone/fetch/pull which run in a facet to avoid
440
- // exhausting the supervisor DO's CPU budget on large repos. The command
441
- // module (+ its ~106 KB network-facet dependency) is loaded lazily on the
442
- // first `git` invocation so it stays out of the cold script-eval graph.
443
- registry.register('git', async (ctx) => {
444
- const { runGitCommand } = await import('../git/commands.js');
445
- return runGitCommand(ctx, sqliteFs, self.ctx, self.env);
446
- });
447
- // ── runtime package manager: `nimbus install` package manager + runner registry.
448
- //
449
- // 1. Register the clang-runner factory FIRST so the rehydration step
450
- // below can re-bind `clang` / `wasm-ld` from an already-installed
451
- // manifest.
452
- // 2. Register the `nimbus` shell verb (install/uninstall/list/available).
453
- // 3. Rehydrate any previously-installed runtimes from VFS so their
454
- // bins reappear in the registry after DO eviction or WS reconnect.
455
- registerRunnerFactory('clang-runner', (manifest, installRoot, binName, binKind) => async (ctx) => {
456
- const { makeClangRunnerFactory } = await import('@nimbus-sh/core/runtime/clang-runner.js');
457
- const { facetHostForManager } = await import('../runtime/facet-loader-host.js');
458
- return await makeClangRunnerFactory({ facets: facetHostForManager(facetMgr), vfs: sqliteFs })(manifest, installRoot, binName, binKind)(ctx);
459
- });
460
- // Pyodide v1 — Python 3.13 via the same R2-package-manager
461
- // substrate that ships clang. Manifest entrypoints `python` and
462
- // `python3` both bind to this factory; the runner ferries
463
- // pyodide.asm.wasm via LOADER modules-map and pyodide.asm.js +
464
- // python_stdlib.zip via the loader-pool context channel.
465
- //
466
- // REPL-W1: wrap the one-shot factory so `python` with NO args (and
467
- // no flags that would consume args) drops into an interactive
468
- // REPL. The wrap is purely additive — args-bearing invocations
469
- // pass through to the existing handler unchanged.
470
- registerRunnerFactory('cpython-runner', (manifest, installRoot, binName, binKind) => async function pythonReplOrOneShot(ctx) {
471
- const argv = ctx.args || [];
472
- // No args at all → REPL session. Hand off to runPythonRepl
473
- // which builds its own IsolatePool (separate from the
474
- // one-shot dispatch's pool) and drives a ReplSession.
475
- if (argv.length === 0 && self.terminal) {
476
- const { runPythonRepl } = await import('../runtime/python-repl.js');
477
- return await runPythonRepl({
478
- facetMgr,
479
- vfs: sqliteFs,
480
- terminal: self.terminal,
481
- installRoot,
482
- manifest,
483
- // REPL-R7-1: thread the shell so ReplSession can drain
484
- // shell.pasteQueue on attach (multi-line WS frames like
485
- // `python\nexit(7)` would otherwise drop the tail input).
486
- shell: self.shell,
487
- // The supervisor derives the write credential from this; without
488
- // it the prompt cannot write to the session filesystem.
489
- pid: ctx.pid,
490
- });
491
- }
492
- // Args present (one-shot mode: -c, script, -m, -). Fall through
493
- // to the canonical handler (imported lazily on first use).
494
- const { makeCPythonRunnerFactory } = await import('@nimbus-sh/core/runtime/cpython-runner.js');
495
- const { facetHostForManager } = await import('../runtime/facet-loader-host.js');
496
- const { cpythonResidentStart } = await import('../runtime/cpython-resident.js');
497
- return await makeCPythonRunnerFactory({
498
- facets: facetHostForManager(facetMgr),
499
- vfs: sqliteFs,
500
- startResident: cpythonResidentStart(facetMgr),
501
- })(manifest, installRoot, binName, binKind)(ctx);
502
- });
503
- // Ruby v1 — Ruby 3.3.4 via ruby.wasm 2.9.3-2.9.4. Same architecture
504
- // as python-runner: ruby+stdlib.wasm rides via LOADER modules-map,
505
- // bootstrap runs at child-facet module-init time, per-call
506
- // __rubyRun drives rb-eval-string-protect with a wrapper that
507
- // catches SystemExit. See src/runtime/ruby-runner.ts +
508
- //
509
- // REPL Stream A: wrap the one-shot factory so `ruby` with NO args
510
- // drops into an interactive REPL. The wrap is purely additive —
511
- // args-bearing invocations pass through to the existing handler.
512
- registerRunnerFactory('ruby-runner', (manifest, installRoot, binName, binKind) => async function rubyReplOrOneShot(ctx) {
513
- const argv = ctx.args || [];
514
- if (argv.length === 0 && self.terminal) {
515
- const { runRubyRepl } = await import('../runtime/ruby-repl.js');
516
- return await runRubyRepl({
517
- facetMgr,
518
- vfs: sqliteFs,
519
- terminal: self.terminal,
520
- installRoot,
521
- });
522
- }
523
- const { makeRubyRunnerFactory } = await import('@nimbus-sh/core/runtime/ruby-runner.js');
524
- const { facetHostForManager } = await import('../runtime/facet-loader-host.js');
525
- const { rubyResidentStart } = await import('../runtime/ruby-resident.js');
526
- return await makeRubyRunnerFactory({
527
- facets: facetHostForManager(facetMgr),
528
- vfs: sqliteFs,
529
- registry,
530
- startResident: rubyResidentStart(facetMgr),
531
- })(manifest, installRoot, binName, binKind)(ctx);
532
- });
533
- // GNU bash 5.2.37 (wasm32-wasi, asyncified) — dedicated facet
534
- // runner driving the fork/pipe/exec/setjmp scheduler (fork M1-M3
535
- // mechanisms). Interactive terminal invocations use the shared
536
- // ReplSession line editor; -c, scripts, and piped stdin retain the
537
- // canonical one-shot handler.
538
- registerRunnerFactory('bash-runner', (manifest, installRoot, binName, binKind) => async (ctx) => {
539
- const argv = ctx.args || [];
540
- const explicitInteractive = argv.includes('-i');
541
- const terminalStdin = ctx.isFdTerminal?.(0) ?? !ctx.stdin;
542
- if (self.terminal && (explicitInteractive || (argv.length === 0 && terminalStdin))) {
543
- const { runBashRepl } = await import('../runtime/bash-repl.js');
544
- return await runBashRepl({
545
- facetMgr,
546
- vfs: sqliteFs,
547
- terminal: self.terminal,
548
- installRoot,
549
- manifest,
550
- cred: ctx.cred,
551
- env: ctx.env,
552
- cwd: ctx.cwd || '/home/user',
553
- shell: self.shell ?? undefined,
554
- });
555
- }
556
- const { makeBashRunnerFactory } = await import('@nimbus-sh/core/runtime/bash-runner.js');
557
- const { facetHostForManager } = await import('../runtime/facet-loader-host.js');
558
- return await makeBashRunnerFactory({ facets: facetHostForManager(facetMgr), vfs: sqliteFs })(manifest, installRoot, binName, binKind)(ctx);
559
- });
560
- {
561
- // Cast registry to the minimal package-manager shape. CommandRegistry
562
- // CommandRegistry has register(name, handler) which matches.
563
- const pkgRegistry = registry;
564
- const nimbusGetHome = () => {
565
- // Shell env carries HOME; fall back to Nimbus's default home.
566
- const envHome = (self.shell && self.shell.env && self.shell.env.HOME)
567
- ? self.shell.env.HOME
568
- : '/home/user';
569
- return envHome;
570
- };
571
- registry.register('nimbus', makeNimbusVerbHandler({
572
- env: self.env,
573
- vfs: sqliteFs,
574
- registry: pkgRegistry,
575
- getHome: nimbusGetHome,
576
- // The application verbs are the session's own (programmatic.ts):
577
- // the shell, the SDK and the Agent all reach the same policy.
578
- apps: {
579
- expose: (target, options) => rpcExposeApp(self, target, options),
580
- list: () => rpcListApps(self),
581
- rotateLink: (target) => rpcRotateLink(self, target),
582
- remove: (target) => rpcRemoveApp(self, target),
583
- },
584
- warmRuntime: async (target, ctx) => {
585
- // The runtime name, which is what `nimbus install python` installs
586
- // — not the name the user typed. Left as 'python' through the
587
- // migration, this matched only the superseded Pyodide entry, so the
588
- // interpreter people actually install was never warmed and the
589
- // first invocation after installing paid the wasm compile.
590
- if (target.name !== 'cpython')
591
- return;
592
- ctx.stdout.write(`[${target.name}] warming runtime...\n`);
593
- const stdout = { write(_s) { } };
594
- const stderrText = [];
595
- const stderr = { write: (s) => { stderrText.push(String(s)); } };
596
- const py = await registry.resolve('python');
597
- if (py) {
598
- const pid = 'pid' in ctx ? ctx.pid : undefined;
599
- const setUmask = 'setUmask' in ctx ? ctx.setUmask : undefined;
600
- const runAs = 'runAs' in ctx ? ctx.runAs : undefined;
601
- if (typeof pid !== 'number'
602
- || typeof setUmask !== 'function'
603
- || typeof runAs !== 'function'
604
- || self.kernel === null) {
605
- throw new Error('python warm-up requires a process identity');
606
- }
607
- const cred = requireVfsCred('cred' in ctx ? ctx.cred : undefined, 'python warm-up');
608
- const code = await py({
609
- ...ctx,
610
- args: ['-c', 'pass'],
611
- pid,
612
- cred,
613
- setUmask: (mask) => setUmask(mask),
614
- runAs: (targetCred, argv) => runAs(targetCred, argv),
615
- vfs: self.kernel.vfs,
616
- signal: new AbortController().signal,
617
- stdout,
618
- stderr,
619
- });
620
- if (typeof code === 'number' && code !== 0) {
621
- throw new Error(stderrText.join('').trim() || `python warm-up exited ${code}`);
622
- }
623
- }
624
- const { warmPythonRepl } = await import('../runtime/python-repl.js');
625
- await warmPythonRepl({
626
- facetMgr,
627
- vfs: sqliteFs,
628
- installRoot: target.root,
629
- manifest: target.manifest,
630
- });
631
- ctx.stdout.write('[python] ready\n');
632
- },
633
- }));
634
- // Rehydration runs here even though the shell hasn't been built
635
- // yet — that's fine: it accesses VFS + registry which are both
636
- // already initialised. Runs O(installed-runtimes); typically 0
637
- // on a fresh session.
638
- try {
639
- const rehydration = rehydrateInstalledRuntimes(sqliteFs, pkgRegistry, nimbusGetHome());
640
- if (rehydration.count > 0) {
641
- // Surface to terminal via the standard MOTD-style line so
642
- // users see what's been auto-rebound. Not an error path.
643
- self.terminal?.write?.(`\x1b[2m[nimbus] rehydrated ${rehydration.count} runtime bin(s): ${rehydration.bins.join(', ')}\x1b[0m\r\n`);
644
- }
645
- }
646
- catch { /* fail-soft: rehydration must not block session boot */ }
647
- }
648
- // ── node command: facet-based execution ─────────────────────────────
649
- // Parses args, reads script from VFS, delegates to FacetManager.
650
- // The facet creates a dynamic worker where new Function() is allowed
651
- // during module startup.
652
- // ── node command (runtime registry refactor: refactored to use runtime-registry) ──
653
- //
654
- // Behaviour preserved exactly:
655
- // - primitive #1 nodeFlagSpan (--version/-v/-h scan only flags
656
- // before script path)
657
- // - primitive #1 shebang strip
658
- // - .ts/.tsx/.jsx esbuild auto-transform
659
- // - G4 binSpawn ctx propagation (when the .bin handler set
660
- // ctx.__nimbusBinSpawn, runFresh reuses the caller's PID
661
- // instead of double-spawning)
662
- // - --watch/--inspect/--inspect-brk routing via runFresh →
663
- // isLongRunningInvocation
664
- //
665
- // The registry encodes the shared shape; per-runtime overrides
666
- // live in the spec object.
667
- const nodeSpec = {
668
- name: 'node',
669
- // CLN-1b: was stale literal 'v20.0.0'; pull from src/constants.ts
670
- // canonical (src/runtime/node-shims.ts already does the same).
671
- version: NODE_VERSION,
672
- helpText: 'Usage: node [options] [script.js] [arguments]\n' +
673
- ' node -e "code"\n\n' +
674
- 'Options:\n' +
675
- ' -e, --eval <code> Evaluate code\n' +
676
- ' -v, --version Print version\n' +
677
- ' -h, --help Print help\n' +
678
- '\nExecution via DO Facets (isolated V8 isolate)',
679
- run: (code, opts) => runFresh(facetMgr, code, opts),
680
- supportsBinSpawn: true,
681
- };
682
- {
683
- const oneShotNode = buildRuntimeHandler(nodeSpec, {
684
- vfs: sqliteFs,
685
- getEsbuild: () => {
686
- if (!self.esbuildService) {
687
- self.ensureSqliteFs();
688
- self.esbuildService = new EsbuildService(kernelFs);
689
- }
690
- return self.esbuildService;
691
- },
692
- registry,
693
- });
694
- // REPL Stream A: no-args invocation → drop into REPL session.
695
- registry.register('node', async function nodeReplOrOneShot(ctx) {
696
- const argv = ctx.args || [];
697
- if (argv.length === 0 && self.terminal) {
698
- const { runNodeRepl } = await import('../runtime/node-repl.js');
699
- return await runNodeRepl({ facetMgr, terminal: self.terminal });
700
- }
701
- return await oneShotNode(ctx);
702
- });
703
- }
704
- // ── bun command (runtime registry refactor: refactored to use runtime-registry) ──
705
- //
706
- // Behaviour preserved exactly:
707
- // - --version / --help
708
- // - install / i / add → delegate to npm
709
- // - run <script> → look up package.json#scripts and shell.execute
710
- // - -e / --eval flow
711
- // - script-path flow with .ts/.tsx/.jsx auto-transform
712
- // - BUN_SHIM_PREAMBLE prepend (handled inside runBunScript itself)
713
- //
714
- // Bun does NOT use binSpawn ctx propagation today (its runFresh
715
- // chain doesn't share PID state with the .bin handler — the .bin
716
- // handler always dispatches through `node`, not `bun`). So
717
- // supportsBinSpawn=false (default).
718
- /** `scripts` from the cwd's package.json; empty when there is none. */
719
- const readPackageScripts = (cwd) => {
720
- try {
721
- const pkg = JSON.parse(kernelFs.readFileString(cwd + '/package.json'));
722
- const scripts = pkg?.scripts;
723
- return scripts && typeof scripts === 'object' ? scripts : {};
724
- }
725
- catch {
726
- return {};
727
- }
728
- };
729
- const bunSpec = {
730
- name: 'bun',
731
- version: BUN_VERSION,
732
- helpText: 'Usage: bun [options] [script.[js|ts|tsx]] [args...]\n' +
733
- ' bun -e "code"\n' +
734
- ' bun install [pkg ...]\n' +
735
- ' bun run <script>\n\n' +
736
- 'Bun-runtime shim provides Bun.file/Bun.write/\n' +
737
- 'Bun.spawn/Bun.password/Bun.gunzip backed by Workers-native\n' +
738
- 'primitives. Bun.serve / Bun.sql / Bun.S3 throw with supported alternatives.\n' +
739
- 'Execution via DO Facets (isolated V8 isolate per call).',
740
- run: (code, opts) => runBunScript(facetMgr, code, opts),
741
- subcommands: {
742
- // bun install / i / add → npm install (same VFS, same R2 caches).
743
- install: async (ctx, reg) => {
744
- const npmCmd = await reg.resolve('npm');
745
- if (npmCmd) {
746
- return await npmCmd({ ...ctx, args: ['install', ...(ctx.args || []).slice(1)] });
747
- }
748
- ctx.stderr.write('bun install: npm handler unavailable\n');
749
- return 1;
750
- },
751
- i: async (ctx, reg) => {
752
- const npmCmd = await reg.resolve('npm');
753
- if (npmCmd) {
754
- return await npmCmd({ ...ctx, args: ['install', ...(ctx.args || []).slice(1)] });
755
- }
756
- ctx.stderr.write('bun i: npm handler unavailable\n');
757
- return 1;
758
- },
759
- add: async (ctx, reg) => {
760
- const npmCmd = await reg.resolve('npm');
761
- if (npmCmd) {
762
- return await npmCmd({ ...ctx, args: ['install', ...(ctx.args || []).slice(1)] });
763
- }
764
- ctx.stderr.write('bun add: npm handler unavailable\n');
765
- return 1;
766
- },
767
- // bun run <target> — a package.json script, or a file.
768
- //
769
- // Real bun's precedence, and the reason this is not just a script
770
- // lookup: a path-shaped target (`./cli.ts`, `sub/x`, `.`) is ALWAYS
771
- // a file and never consults scripts, while a bare name checks
772
- // scripts first and only then falls back to a file. The file case
773
- // delegates to the standard runtime flow, so `bun run ./cli.ts`
774
- // and `bun cli.ts` execute through one path — TypeScript transform,
775
- // facet dispatch and all.
776
- run: async (ctx, _reg, runAsBun) => {
777
- const args = ctx.args || [];
778
- // bun's own run flags sit between the verb and the target.
779
- let targetIdx = 1;
780
- while (targetIdx < args.length && args[targetIdx].startsWith('-'))
781
- targetIdx++;
782
- const target = args[targetIdx];
783
- const cwd = normalizeVfsPath(ctx.cwd || '/home/user');
784
- const scripts = readPackageScripts(cwd);
785
- if (!target) {
786
- ctx.stdout.write('Usage: bun run [flags] <file or script>\n');
787
- const names = Object.keys(scripts);
788
- if (names.length) {
789
- ctx.stdout.write(`\npackage.json scripts (${names.length} found):\n\n`);
790
- for (const n of names)
791
- ctx.stdout.write(` bun run ${n}\n ${scripts[n]}\n\n`);
792
- }
793
- return 0;
794
- }
795
- const pathShaped = target === '.' || target === '..' || target.includes('/');
796
- const pkgScript = pathShaped ? undefined : scripts[target];
797
- if (pkgScript) {
798
- // Trailing args append to the script command; bun drops a single
799
- // `--` separator between the script name and them.
800
- const extra = args.slice(targetIdx + 1);
801
- if (extra[0] === '--')
802
- extra.shift();
803
- const command = extra.length ? `${pkgScript} ${extra.join(' ')}` : pkgScript;
804
- try {
805
- const shellResult = await shell.execute(command, {
806
- cwd: ctx.cwd,
807
- env: ctx.env,
808
- onStdout: textSink((d) => ctx.stdout.write(d)),
809
- onStderr: textSink((d) => ctx.stderr.write(d)),
810
- });
811
- return shellResult.exitCode;
812
- }
813
- catch (e) {
814
- ctx.stderr.write(`bun run: ${e?.message ?? String(e)}\n`);
815
- return 1;
816
- }
817
- }
818
- const resolved = resolveRuntimeScriptPath(kernelFs, cwd, target, {
819
- preferModuleField: true,
820
- });
821
- if (resolved === null) {
822
- ctx.stderr.write(pathShaped
823
- ? `error: Module not found "${target}"\n`
824
- : `error: Script not found "${target}"\n`);
825
- return 1;
826
- }
827
- return runAsBun([...args.slice(1, targetIdx), '/' + resolved, ...args.slice(targetIdx + 1)]);
828
- },
829
- },
830
- };
831
- {
832
- const oneShotBun = buildRuntimeHandler(bunSpec, {
833
- vfs: sqliteFs,
834
- getEsbuild: () => {
835
- if (!self.esbuildService) {
836
- self.ensureSqliteFs();
837
- self.esbuildService = new EsbuildService(kernelFs);
838
- }
839
- return self.esbuildService;
840
- },
841
- registry,
842
- });
843
- // REPL Stream A: no-args invocation → drop into REPL session.
844
- registry.register('bun', async function bunReplOrOneShot(ctx) {
845
- const argv = ctx.args || [];
846
- if (argv.length === 0 && self.terminal) {
847
- const { runBunRepl } = await import('../runtime/bun-repl.js');
848
- return await runBunRepl({ facetMgr, terminal: self.terminal });
849
- }
850
- return await oneShotBun(ctx);
851
- });
852
- }
853
- // ── wasm-runner: native WebAssembly, on this session's facet host ──
854
- //
855
- // Bytes ride INSIDE the inner worker's code blob, the one phase where
856
- // workerd permits wasm code generation; request-time
857
- // WebAssembly.instantiate(bytes) is CSP-blocked and avoided.
858
- //
859
- // wasm-csp/findings.md — add(3,4)===7 in 11ms warm against the
860
- // deployed Cloudflare fleet.
861
- //
862
- // Lazy: the wasm-runner module (WASI instance preamble + snapshot
863
- // machinery) is imported on first `wasm-runner` invocation and the
864
- // built handler memoized, so its module-eval cost stays off the cold
865
- // Worker Startup Time path.
866
- {
867
- let wasmHandler = null;
868
- registry.register('wasm-runner', async (ctx) => {
869
- if (!wasmHandler) {
870
- const { wasmRunnerSpec } = await import('@nimbus-sh/core/runtime/wasm-runner.js');
871
- const { loaderFacetHost } = await import('../runtime/facet-loader-host.js');
872
- const wasmSpec = wasmRunnerSpec({
873
- // filesystem WASI: extended VFS surface for WASI file-IO. The
874
- // wasm-runner snapshots a session subtree into the facet, flushes
875
- // the diff back via this surface after _start returns.
876
- vfs: sqliteFs,
877
- facets: loaderFacetHost(self.env, self.ctx),
878
- processes: self.processes,
879
- });
880
- wasmHandler = buildRuntimeHandler(wasmSpec, {
881
- vfs: sqliteFs,
882
- getEsbuild: () => {
883
- if (!self.esbuildService) {
884
- self.ensureSqliteFs();
885
- self.esbuildService = new EsbuildService(kernelFs);
886
- }
887
- return self.esbuildService;
888
- },
889
- registry,
890
- });
891
- }
892
- return await wasmHandler(ctx);
893
- });
894
- }
895
- kernel.routeLoopback = (port, request) => routeSessionLoopback(self, port, request);
896
- try {
897
- registry.register('curl', createCurlCommand(kernel));
898
- }
899
- catch { }
900
- // ── df with SQLite stats + cache + process metrics ──────────────────
901
- registry.register('df', async (ctx) => {
902
- const stats = sqliteFs.getStats();
903
- const pstats = facetMgr.stats;
904
- const used = stats.usedBytes;
905
- const cap = stats.capacityBytes;
906
- const avail = cap - used;
907
- const pct = ((used / cap) * 100).toFixed(0);
908
- const fmt = (b) => {
909
- if (b >= 1e9)
910
- return (b / 1e9).toFixed(1) + 'G';
911
- if (b >= 1e6)
912
- return (b / 1e6).toFixed(1) + 'M';
913
- if (b >= 1e3)
914
- return (b / 1e3).toFixed(1) + 'K';
915
- return b + 'B';
916
- };
917
- ctx.stdout.write('Filesystem Size Used Avail Use% Mounted on\n');
918
- ctx.stdout.write('sqlite ' + fmt(cap).padStart(5) + ' ' + fmt(used).padStart(5) +
919
- ' ' + fmt(avail).padStart(5) + ' ' + pct.padStart(3) + '% /\n');
920
- ctx.stdout.write('\nCache: ' + stats.cache.entries + '/' + stats.cache.maxEntries +
921
- ' slots | hit rate: ' + stats.cache.hitRate +
922
- '% | evictions: ' + stats.cache.evictions + '\n');
923
- ctx.stdout.write('Procs: ' + pstats.running + ' running, ' +
924
- pstats.exited + ' exited, ' +
925
- pstats.total + ' total (next PID: ' + pstats.nextPid + ')\n');
926
- return 0;
927
- });
928
- // ── esbuild command: transform/bundle via esbuild facet ───────────────
929
- // Lazy-creates the EsbuildService on first use (esbuild-wasm is ~10MB).
930
- registry.register('esbuild', async (ctx) => {
931
- const args = ctx.args || [];
932
- if (args.includes('--version')) {
933
- ctx.stdout.write('0.24.2 (esbuild-wasm, bundled)\n');
934
- return 0;
935
- }
936
- if (args.includes('--help') || args.length === 0) {
937
- ctx.stdout.write('Usage: esbuild [options] [entry points]\n\n');
938
- ctx.stdout.write('Options:\n');
939
- ctx.stdout.write(' --bundle Bundle all dependencies into output\n');
940
- ctx.stdout.write(' --outfile=<path> Write output to a file\n');
941
- ctx.stdout.write(' --outdir=<path> Write output to a directory\n');
942
- ctx.stdout.write(' --format=esm|cjs Output format (default: esm)\n');
943
- ctx.stdout.write(' --platform=browser|node Target platform\n');
944
- ctx.stdout.write(' --minify Minify output\n');
945
- ctx.stdout.write(' --sourcemap Generate source maps\n');
946
- ctx.stdout.write(' --target=<target> JS target (default: esnext)\n');
947
- ctx.stdout.write(' --loader=<loader> Force file loader (ts, tsx, jsx, css)\n');
948
- ctx.stdout.write(' --version Show version\n');
949
- ctx.stdout.write('\nPowered by esbuild-wasm (bundled in supervisor).\n');
950
- return 0;
951
- }
952
- // Lazy-init esbuild service
953
- if (!self.esbuildService) {
954
- self.ensureSqliteFs();
955
- self.esbuildService = new EsbuildService(kernelFs);
956
- }
957
- // Parse flags
958
- const flags = {};
959
- const entryPoints = [];
960
- for (const arg of args) {
961
- if (arg.startsWith('--')) {
962
- const eqIdx = arg.indexOf('=');
963
- if (eqIdx > 0) {
964
- flags[arg.substring(2, eqIdx)] = arg.substring(eqIdx + 1);
965
- }
966
- else {
967
- flags[arg.substring(2)] = 'true';
968
- }
969
- }
970
- else {
971
- entryPoints.push(arg);
972
- }
973
- }
974
- // Transform-only mode (single file, no --bundle)
975
- if (entryPoints.length === 1 && !flags['bundle']) {
976
- // Read the file and transform it
977
- const filePath = resolveVfsPath(entryPoints[0], ctx.cwd || '/home/user');
978
- let code;
979
- try {
980
- code = kernelFs.readFileString(filePath);
981
- }
982
- catch {
983
- ctx.stderr.write(`esbuild: could not read file: ${entryPoints[0]}\n`);
984
- return 1;
985
- }
986
- try {
987
- ctx.stderr.write('Transforming...\n');
988
- const result = await self.esbuildService.transform(code, {
989
- loader: flags['loader'] || (() => {
990
- const ext = filePath.split('.').pop()?.toLowerCase();
991
- return { ts: 'ts', tsx: 'tsx', jsx: 'jsx', js: 'js', mts: 'ts', mjs: 'js', css: 'css', json: 'json' }[ext || ''];
992
- })(),
993
- format: flags['format'] || 'esm',
994
- target: flags['target'] || 'esnext',
995
- sourcemap: flags['sourcemap'] === 'true',
996
- minify: flags['minify'] === 'true',
997
- });
998
- if (flags['outfile']) {
999
- const outPath = resolveVfsPath(flags['outfile'], ctx.cwd || '/home/user');
1000
- const parent = parentVfsPath(outPath);
1001
- if (parent && !kernelFs.exists(parent))
1002
- kernelFs.mkdir(parent, { recursive: true });
1003
- kernelFs.writeFile(outPath, result.code);
1004
- ctx.stdout.write(` ${outPath} ${result.code.length} bytes\n`);
1005
- }
1006
- else {
1007
- ctx.stdout.write(result.code);
1008
- }
1009
- for (const w of result.warnings || []) {
1010
- ctx.stderr.write(`warning: ${w.text}\n`);
1011
- }
1012
- return 0;
1013
- }
1014
- catch (e) {
1015
- ctx.stderr.write(`esbuild error: ${e?.message || e}\n`);
1016
- return 1;
1017
- }
1018
- }
1019
- // Bundle mode
1020
- if (entryPoints.length === 0) {
1021
- ctx.stderr.write('esbuild: no entry points specified\n');
1022
- return 1;
1023
- }
1024
- // Resolve entry points relative to cwd
1025
- const resolvedEntryPoints = entryPoints.map(ep => resolveVfsPath(ep, ctx.cwd || '/home/user'));
1026
- try {
1027
- ctx.stderr.write('Bundling...\n');
1028
- const result = await self.esbuildService.build(resolvedEntryPoints, {
1029
- bundle: flags['bundle'] === 'true',
1030
- format: flags['format'] || 'esm',
1031
- target: flags['target'] || 'esnext',
1032
- platform: flags['platform'] || 'browser',
1033
- outdir: flags['outfile'] ? undefined : (flags['outdir'] || '/dist'),
1034
- outfile: flags['outfile'],
1035
- sourcemap: flags['sourcemap'] === 'true',
1036
- minify: flags['minify'] === 'true',
1037
- external: flags['external']?.split(','),
1038
- });
1039
- for (const e of result.errors || []) {
1040
- ctx.stderr.write(`error: ${e.text}\n`);
1041
- }
1042
- for (const w of result.warnings || []) {
1043
- ctx.stderr.write(`warning: ${w.text}\n`);
1044
- }
1045
- if (result.errors?.length)
1046
- return 1;
1047
- // Write output files to VFS
1048
- for (const f of result.outputFiles || []) {
1049
- const outPath = normalizeVfsPath(f.path);
1050
- const parent = parentVfsPath(outPath);
1051
- if (parent && !kernelFs.exists(parent))
1052
- kernelFs.mkdir(parent, { recursive: true });
1053
- kernelFs.writeFile(outPath, f.contents);
1054
- ctx.stdout.write(` ${outPath} ${f.contents.length} bytes\n`);
1055
- }
1056
- ctx.stderr.write(`Done (${result.outputFiles?.length || 0} output files)\n`);
1057
- return 0;
1058
- }
1059
- catch (e) {
1060
- ctx.stderr.write(`esbuild error: ${e?.message || e}\n`);
1061
- return 1;
1062
- }
1063
- });
1064
- // ── vite command: start/stop the dev server ──────────────────────────
1065
- registry.register('vite', createViteCommand(self));
1066
- // ── nimbus-wrangler / wrangler command: Worker dev server ─────────────
1067
- //
1068
- // `wrangler` is registered as a transparent alias for `nimbus-wrangler`
1069
- // so projects with `"dev": "wrangler dev"` in package.json Just Work.
1070
- // The shared handler below takes an extra `invokedAs` flag so we can
1071
- // - print a one-shot "DO-in-DO mode" banner on the first wrangler
1072
- // invocation per session (so users know they're getting a compat
1073
- // layer, not real wrangler)
1074
- // - silently strip wrangler-specific flags (--ip, --port, etc.) that
1075
- // have no meaning inside a DO.
1076
- const wranglerHandler = (invokedAs) => async (ctx) => {
1077
- const rawArgs = ctx.args || [];
1078
- // Filter wrangler-only flags early (works for both invocation paths;
1079
- // a no-op for nimbus-wrangler since it doesn't accept them anyway).
1080
- const { args, ignored } = filterWranglerFlags(rawArgs);
1081
- if (args.includes('--help') || args.includes('-h') || args.length === 0) {
1082
- ctx.stdout.write(`Usage: ${invokedAs} dev [options]\n\n`);
1083
- ctx.stdout.write('Run your Cloudflare Worker locally on the actual CF runtime\n');
1084
- ctx.stdout.write('(DO-in-DO via env.LOADER — workerd in a workerd).\n\n');
1085
- ctx.stdout.write('Commands:\n');
1086
- ctx.stdout.write(' dev Start the dev server\n');
1087
- ctx.stdout.write(' stop Stop the dev server\n\n');
1088
- ctx.stdout.write('Options:\n');
1089
- ctx.stdout.write(' --root <dir> Project root (default: cwd)\n\n');
1090
- if (invokedAs === 'wrangler') {
1091
- ctx.stdout.write('Note: \x1b[2minside Nimbus, `wrangler` is an alias for\x1b[0m \x1b[36mnimbus-wrangler\x1b[0m.\n');
1092
- ctx.stdout.write('Most real-wrangler flags (--ip, --port, --local, --log-level, ...)\n');
1093
- ctx.stdout.write('are silently ignored because the DO provides its own routing.\n');
1094
- }
1095
- return 0;
1096
- }
1097
- if (args[0] === 'stop') {
1098
- if (self.nimbusWrangler?.isRunning) {
1099
- self.nimbusWrangler.stop();
1100
- ctx.stdout.write('\x1b[33mWorker dev server stopped.\x1b[0m\n');
1101
- }
1102
- else {
1103
- ctx.stdout.write('No Worker dev server running.\n');
1104
- }
1105
- return 0;
1106
- }
1107
- if (args[0] !== 'dev') {
1108
- ctx.stderr.write(`Unknown command: ${args[0]}. Use "${invokedAs} dev" or "${invokedAs} --help".\n`);
1109
- return 1;
1110
- }
1111
- // First-run banner — only when invoked as `wrangler`, and only once
1112
- // per session. Makes it OBVIOUS to the user that they're not running
1113
- // real wrangler, and that Nimbus is doing something different.
1114
- if (invokedAs === 'wrangler' && !self.wranglerAliasBannerShown) {
1115
- ctx.stdout.write('\x1b[2m\u2388 wrangler (Nimbus DO-in-DO mode) — bundling via esbuild-wasm, running via env.LOADER\x1b[0m\n');
1116
- self.wranglerAliasBannerShown = true;
1117
- }
1118
- // Report ignored flags (also one-shot — if user sees it once per
1119
- // session that's enough to spot a typo; no need to spam on rebuilds).
1120
- if (ignored.length > 0 && invokedAs === 'wrangler') {
1121
- ctx.stdout.write('\x1b[2m ignored wrangler flags: ' + ignored.join(' ') + '\x1b[0m\n');
1122
- }
1123
- // Lazy-init esbuild
1124
- if (!self.esbuildService) {
1125
- self.ensureSqliteFs();
1126
- self.esbuildService = new EsbuildService(kernelFs);
1127
- }
1128
- // Parse --root flag; default to the shell cwd so `npm run dev` from
1129
- // a project directory picks up that project's wrangler.jsonc.
1130
- let root = ctx.cwd || '/home/user';
1131
- for (let i = 1; i < args.length; i++) {
1132
- if (args[i] === '--root' && args[i + 1])
1133
- root = args[i + 1];
1134
- }
1135
- // Stop existing
1136
- if (self.nimbusWrangler?.isRunning)
1137
- self.nimbusWrangler.stop();
1138
- const vfsRoot = resolveVfsPath(root, ctx.cwd || '/home/user');
1139
- // Pre-flight: read the wrangler config ourselves and call out any
1140
- // binding fields nimbus-wrangler can't provide. NimbusWrangler will
1141
- // still try to bundle + load, but user sees up-front why their
1142
- // Worker may fail when it tries to access a missing binding.
1143
- const unsupportedFields = detectUnsupportedWranglerConfig(kernelFs, vfsRoot);
1144
- ctx.stdout.write('\n');
1145
- ctx.stdout.write('\x1b[1;35m ' + (invokedAs === 'wrangler' ? 'Wrangler' : 'Nimbus Wrangler') + ' Dev\x1b[0m\n\n');
1146
- if (unsupportedFields.length > 0) {
1147
- ctx.stderr.write('\x1b[33m\u26A0\x1b[0m \x1b[1mNimbus-incompatible wrangler.jsonc fields detected:\x1b[0m\n');
1148
- for (const f of unsupportedFields) {
1149
- ctx.stderr.write(' - \x1b[33m' + f + '\x1b[0m\n');
1150
- }
1151
- ctx.stderr.write(' These bindings are NOT provisioned inside nimbus-wrangler. Your Worker\n' +
1152
- ' will get \x1b[2mundefined\x1b[0m when it tries to access them, which typically\n' +
1153
- ' causes a runtime TypeError. The bundle will still build and load.\n' +
1154
- ' \x1b[2mDeploy with real wrangler to get the real bindings.\x1b[0m\n\n');
1155
- }
1156
- self.nimbusWrangler = new NimbusWrangler({
1157
- vfs: kernelFs,
1158
- vfsEvents: sqliteFs.events,
1159
- esbuild: self.esbuildService,
1160
- env: self.env,
1161
- // Supervisor DO ctx — required for ctx.facets.get() when
1162
- // synthesizing durable_objects bindings on the inner Worker.
1163
- ctx: self.ctx,
1164
- root: vfsRoot,
1165
- onLog: (msg) => {
1166
- if (self.terminal) {
1167
- try {
1168
- self.terminal.write(msg);
1169
- }
1170
- catch { }
1171
- }
1172
- },
1173
- onHmrMessage: (msg) => {
1174
- if (self.terminal) {
1175
- try {
1176
- self.terminal.ws.send(JSON.stringify({ type: 'hmr', data: msg }));
1177
- }
1178
- catch { }
1179
- }
1180
- },
1181
- });
1182
- const ok = await self.nimbusWrangler.start();
1183
- if (!ok) {
1184
- ctx.stderr.write(' \x1b[31mFailed to start Worker dev server.\x1b[0m\n');
1185
- return 1;
1186
- }
1187
- const cfg = self.nimbusWrangler.stats;
1188
- // runtime primitive support (P5): banner advertises the canonical
1189
- // `/__nimbus/worker/` route. The legacy `/worker/` URL is still
1190
- // accepted for one release (Sunset 2027-01-01) but new sessions
1191
- // are pointed at the namespaced form.
1192
- const workerBase = (self.sessionBasePath || '') + '/__nimbus/worker';
1193
- ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Worker: \x1b[36m' + workerBase + '/\x1b[0m\n');
1194
- ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Name: ' + cfg.name + '\n');
1195
- ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Entry: ' + cfg.main + '\n');
1196
- ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Root: ' + cfg.root + '\n');
1197
- ctx.stdout.write(' \x1b[32m\u279C\x1b[0m Reload: on file change\n\n');
1198
- ctx.stdout.write(' \x1b[2mRun \x1b[0m' + invokedAs + ' stop\x1b[2m to stop.\x1b[0m\n\n');
1199
- return 0;
1200
- };
1201
- registry.register('nimbus-wrangler', wranglerHandler('nimbus-wrangler'));
1202
- registry.register('wrangler', wranglerHandler('wrangler'));
1203
- // ── npm-fast command: parallel npm install (v2 — batched writes) ────
1204
- registry.register('npm-fast', async (ctx) => {
1205
- const args = ctx.args || [];
1206
- if (args.includes('--help') || args.includes('-h') || args.length === 0) {
1207
- ctx.stdout.write('Usage: npm-fast install <packages...>\n\n');
1208
- ctx.stdout.write('Nimbus npm v2 — batched VFS writes, content-addressed cache.\n');
1209
- ctx.stdout.write('Handles 100+ dependency projects without crashing.\n');
1210
- return 0;
1211
- }
1212
- if (args[0] !== 'install' && args[0] !== 'i') {
1213
- ctx.stderr.write('Only "npm-fast install" is supported. Use "npm" for other commands.\n');
1214
- return 1;
1215
- }
1216
- const packages = args.slice(1).filter((a) => !a.startsWith('-'));
1217
- if (packages.length === 0) {
1218
- ctx.stderr.write('Specify packages to install: npm-fast install react react-dom\n');
1219
- return 1;
1220
- }
1221
- self.ensureSqliteFs();
1222
- const cwd = normalizeVfsPath(ctx.cwd || '/home/user');
1223
- // Ensure package.json exists
1224
- const pkgJsonPath = cwd + '/package.json';
1225
- if (!kernelFs.exists(pkgJsonPath)) {
1226
- kernelFs.writeFile(pkgJsonPath, '{"name":"project","version":"1.0.0","dependencies":{}}\n');
1227
- }
1228
- ctx.stdout.write('\x1b[36mNimbus npm v2 (batched writes)\x1b[0m\n');
1229
- await self.ensureNpmInstaller((msg) => {
1230
- ctx.stdout.write('[npm] ' + msg + '\n');
1231
- });
1232
- const result = await self.npmInstaller.install(cwd, { packages, pid: ctx.pid });
1233
- if (result.failed.length > 0) {
1234
- ctx.stderr.write('\x1b[31mFailed: ' + result.failed.join(', ') + '\x1b[0m\n');
1235
- }
1236
- // [HONEST INSTALL MESSAGE P0a] Yellow + "(N failed, see above)"
1237
- // when partial. Green only when failed.length === 0. Pre-fix the
1238
- // green line printed unconditionally — see user transcript line
1239
- // 831 ("added 264 packages" with 353 silent failures above).
1240
- const partial = result.failed.length > 0;
1241
- const color = partial ? '\x1b[33m' : '\x1b[32m';
1242
- const suffix = partial ? ` (${result.failed.length} failed, see above)` : '';
1243
- ctx.stdout.write(`\n${color}added ${result.installed.length} packages (${result.totalFiles} files) in ${(result.elapsed / 1000).toFixed(1)}s${suffix}\x1b[0m\n`);
1244
- if (result.cachedHits > 0) {
1245
- ctx.stdout.write(`\x1b[2m (${result.cachedHits} from cache)\x1b[0m\n`);
1246
- }
1247
- return result.failed.length > 0 ? 1 : 0;
1248
- });
1249
- // Primitive #7: patch NIMBUS_SESSION_ID into the live shell env.
1250
- // sessionBasePath is "/s/<sid>" set by the X-Nimbus-Base header on
1251
- // the first /ws upgrade — by the time initSession runs (after the
1252
- // ws handshake), it's populated. Older /ws-pre-base callers see
1253
- // an empty string, which is the safe placeholder (no false id).
1254
- //
1255
- // We patch the live env (not the overlay the workspace was built
1256
- // from) so persisted shell state on warm-rejoin still picks up the
1257
- // SAME session id — the DO's name is stable across hibernation
1258
- // cycles. Any user `export NIMBUS_SESSION_ID=...` would have been
1259
- // persisted to persisted.env and the overlay's spread would have
1260
- // overridden the empty placeholder; we only set when the live env
1261
- // is empty (don't clobber a user-set value).
1262
332
  const sessionIdFromBase = (self.sessionBasePath || '').replace(/^\/s\//, '');
1263
333
  if (sessionIdFromBase) {
1264
334
  // Shell.env is declared private but mutable at runtime — there's
@@ -1273,825 +343,13 @@ export async function initSession(self, ws, options = {}) {
1273
343
  shellAny.env.NIMBUS_SESSION_ID = sessionIdFromBase;
1274
344
  }
1275
345
  }
1276
- // Rehydrate cwd if persisted. The Shell ctor defaults this.cwd to
1277
- // env.HOME, and restoring after construction is safe because no
1278
- // interactive command has run yet.
1279
346
  if (persisted.cwd) {
1280
347
  try {
1281
348
  self.shell.setCwd(persisted.cwd);
1282
349
  }
1283
350
  catch { /* fail-soft */ }
1284
351
  }
1285
- installShellExecutionFeatures(self.shell, self.terminal);
1286
- // ── Readline-parity keybindings (Ctrl+K, Ctrl+W, Alt+B, Alt+F, Alt+D,
1287
- // Ctrl+Y, Ctrl+T, Ctrl+L, Ctrl+R, Alt+. , Ctrl+←/→, Alt+←/→, Linux
1288
- // Home/End variants, Ctrl+B/F/N/P, …). Installed AFTER Heredoc so
1289
- // its handleInput wrapper takes precedence when heredoc mode is
1290
- // active. ──
1291
- LineEditorExtender.install(self.shell, self.terminal);
1292
- // ── Wire npm/npx with shellExecute ──
1293
- const shell = self.shell;
1294
- const shellExecute = async (cmd, cmdCtx) => {
1295
- const stdin = cmdCtx.stdin && cmdCtx.stdin !== cmdCtx.terminalStdin
1296
- ? await cmdCtx.stdin.readAll()
1297
- : undefined;
1298
- const result = await shell.execute(cmd, {
1299
- cwd: cmdCtx.cwd,
1300
- env: cmdCtx.env,
1301
- onStdout: textSink((d) => cmdCtx.stdout.write(d)),
1302
- onStderr: textSink((d) => cmdCtx.stderr.write(d)),
1303
- stdin,
1304
- terminalStdin: cmdCtx.terminalStdin,
1305
- // `npm run x` runs x on npm's own fds. Handing the nested execution a
1306
- // sink without saying where that sink leads would make every fd look
1307
- // redirected, and a runtime whose stdout is redirected stops streaming.
1308
- terminalFds: {
1309
- stdin: cmdCtx.isFdTerminal?.(0) ?? false,
1310
- stdout: cmdCtx.isFdTerminal?.(1) ?? false,
1311
- stderr: cmdCtx.isFdTerminal?.(2) ?? false,
1312
- },
1313
- commandContext: {
1314
- pid: cmdCtx.pid,
1315
- cred: cmdCtx.cred,
1316
- setUmask: cmdCtx.setUmask,
1317
- },
1318
- runAs: runAsProcess,
1319
- });
1320
- return result.exitCode;
1321
- };
1322
- const shellEntrypointExecutor = {
1323
- execute: async (cmd, options) => {
1324
- const parentPid = options?.commandContext?.['pid'];
1325
- if (typeof parentPid !== 'number') {
1326
- throw new Error('shell entrypoint requires a parent process');
1327
- }
1328
- const childProcess = self.processes.spawn('sh', ['sh'], options?.cwd || '/home/user', { parentPid });
1329
- let exitCode = 1;
1330
- try {
1331
- const identity = commandIdentityFor(childProcess.pid);
1332
- const kernel = self.kernel;
1333
- if (kernel === null)
1334
- throw new Error('shell kernel is not initialized');
1335
- const terminal = createHeadlessTerminal();
1336
- const childShell = new Shell(terminal, kernel.vfs, registry, { ...env, ...(options?.env || {}) }, processRegistry, identity);
1337
- installShellExecutionFeatures(childShell, terminal);
1338
- if (options?.cwd)
1339
- childShell.setCwd(options.cwd);
1340
- const result = await childShell.execute(cmd, {
1341
- ...options,
1342
- commandContext: {
1343
- ...options?.commandContext,
1344
- pid: identity.pid,
1345
- cred: identity.cred,
1346
- setUmask: identity.setUmask,
1347
- },
1348
- runAs: runAsProcess,
1349
- });
1350
- exitCode = result.exitCode;
1351
- return result;
1352
- }
1353
- finally {
1354
- self.processes.exit(childProcess.pid, exitCode);
1355
- }
1356
- },
1357
- };
1358
- registerShellEntrypointCommands(registry, shellEntrypointExecutor, kernelFs);
1359
- // Shell scripts that execute through the local shell still need the same
1360
- // process-table and log-store contract as facet-backed processes.
1361
- const shellExecuteTracked = async (cmd, cmdCtx, opts = {}) => {
1362
- const entry = self.processes.spawn(cmd, [cmd], cmdCtx.cwd || '/home/user', { parentPid: cmdCtx.pid });
1363
- const pid = entry.pid;
1364
- if (opts.longRunning)
1365
- self.processes.setLongRunning(pid);
1366
- const startedAt = Date.now();
1367
- // Spawn banner — matches facet-manager.ts onSpawn format.
1368
- if (self.terminal) {
1369
- const label = opts.longRunning ? 'started (long-running)' : 'started';
1370
- self.terminal.write(`\x1b[2m[shell ${label}: pid=${pid} cmd="${cmd}"]\x1b[0m\r\n`);
1371
- }
1372
- // Structured spawn event for the tabs UI (mirrors the facet-manager
1373
- // onSpawn hook). Long-running shell commands like `vite` and
1374
- // `wrangler dev` trigger auto-open of a log tab.
1375
- notifyTerminalEvent(self.terminal, {
1376
- type: 'spawn', pid, command: cmd, longRunning: !!opts.longRunning, attachedTty: false,
1377
- });
1378
- // Wrap the caller-supplied streams so every chunk is both displayed
1379
- // AND captured in the ring buffer keyed by this PID.
1380
- const tee = (stream, target) => {
1381
- const toTarget = textSink((text) => target.write(text));
1382
- return (d) => {
1383
- try {
1384
- self.processes.appendOutputBytes(pid, stream, d);
1385
- }
1386
- catch { }
1387
- try {
1388
- toTarget(d);
1389
- }
1390
- catch { }
1391
- };
1392
- };
1393
- let exitCode = 1;
1394
- try {
1395
- const result = await shell.execute(cmd, {
1396
- cwd: cmdCtx.cwd,
1397
- env: cmdCtx.env,
1398
- onStdout: tee('stdout', cmdCtx.stdout),
1399
- onStderr: tee('stderr', cmdCtx.stderr),
1400
- // The tee is a sink, not a redirection: the script's fds are still
1401
- // whatever the caller's were, and a runtime asks that question before
1402
- // deciding whether it may stream past the shell.
1403
- terminalFds: {
1404
- stdin: cmdCtx.isFdTerminal?.(0) ?? false,
1405
- stdout: cmdCtx.isFdTerminal?.(1) ?? false,
1406
- stderr: cmdCtx.isFdTerminal?.(2) ?? false,
1407
- },
1408
- // Single spawn path for long-running handoff: a registry command
1409
- // (vite/wrangler/serve) ADOPTS this wrapper pid via the bin-spawn
1410
- // contract instead of allocating a second one, and suppresses its
1411
- // own `[started (long-running)]` notice.
1412
- commandContext: {
1413
- pid,
1414
- cred: entry.cred,
1415
- setUmask: (mask) => self.processes.setUmask(pid, mask),
1416
- ...(opts.longRunning
1417
- ? {
1418
- __nimbusBinSpawn: {
1419
- skipSpawn: true,
1420
- callerPid: pid,
1421
- command: cmd,
1422
- forceLongRunning: true,
1423
- },
1424
- }
1425
- : {}),
1426
- },
1427
- runAs: runAsProcess,
1428
- });
1429
- exitCode = result.exitCode;
1430
- }
1431
- catch (e) {
1432
- // Surface the error in the terminal and the ring buffer.
1433
- const msg = (e && (e.stack || e.message)) || String(e);
1434
- const line = 'shellExecuteTracked error: ' + msg + '\n';
1435
- try {
1436
- self.processes.appendOutput(pid, 'stderr', line);
1437
- }
1438
- catch { }
1439
- try {
1440
- cmdCtx.stderr.write(line);
1441
- }
1442
- catch { }
1443
- exitCode = 1;
1444
- }
1445
- finally {
1446
- // When a long-running script handed off to a live server (the registry
1447
- // command adopted this pid and returned 0), the process stays running;
1448
- // emitting an immediate exit would print a false `[shell exited]` and
1449
- // flip the process to terminated in /api/processes. Mirror the npm-bin
1450
- // resolver's `handedOffToLongRunningFacet` contract.
1451
- const handedOffToLongRunningFacet = opts.longRunning === true && exitCode === 0;
1452
- if (!handedOffToLongRunningFacet) {
1453
- try {
1454
- self.processes.exit(pid, exitCode);
1455
- }
1456
- catch { }
1457
- try {
1458
- if (!self.processes.getExit(pid)) {
1459
- self.processes.markExit(pid, exitCode);
1460
- }
1461
- }
1462
- catch { }
1463
- // Structured exit for the tabs UI. Always fires (the UI doesn't
1464
- // know which tabs are open, and client-side dedupe is trivial).
1465
- // Include the command so the UI can backfill a tab for pids it
1466
- // never saw a spawn event for (e.g. evals routed past onSpawn).
1467
- notifyTerminalEvent(self.terminal, { type: 'exit', pid, code: exitCode, command: cmd });
1468
- // Keep shell execution diagnostics on the same session helper used by
1469
- // the rest of the process subsystem.
1470
- try {
1471
- self._emitShellExecDone(pid, cmd, exitCode, Date.now() - startedAt);
1472
- }
1473
- catch { }
1474
- }
1475
- }
1476
- return exitCode;
1477
- };
1478
- const runtimeCommandHint = createRuntimeCommandHintResolver(self.env);
1479
- installNpmBinFallbackResolver(registry, {
1480
- vfs: kernelFs,
1481
- getCwd: () => self.shell?.cwd || '/home/user',
1482
- processes: self.processes,
1483
- getFacetManager: () => {
1484
- self.ensureFacetManager();
1485
- return self.facetManager;
1486
- },
1487
- terminal: self.terminal,
1488
- notifyTerminalEvent: (event) => notifyTerminalEvent(self.terminal, event),
1489
- runtimeCommandHint,
1490
- emitShellExecDone: (pid, command, exitCode, durationMs) => {
1491
- try {
1492
- self._emitShellExecDone(pid, command, exitCode, durationMs);
1493
- }
1494
- catch { }
1495
- },
1496
- });
1497
- // Register core npm — the install work itself goes through the port,
1498
- // which owns the NpmInstaller, prefix dirs and bin materialisation.
1499
- const coreNpmCmd = createNpmCommand(registry, shellExecute, kernel, {
1500
- installer: createNpmInstallPort(self),
1501
- });
1502
- registry.register('npm', async (ctx) => {
1503
- const args = ctx.args || [];
1504
- const sub = args[0];
1505
- const cwdKey = normalizeVfsPath(ctx.cwd || '/home/user');
1506
- // npm run <script> / npm test / npm start — parse package.json and execute
1507
- if (sub === 'run' || sub === 'run-script' || sub === 'test' || sub === 'start') {
1508
- const scriptName = sub === 'test' ? 'test' : sub === 'start' ? 'start' : args[1];
1509
- if (!scriptName) {
1510
- // npm run (no script) — list available scripts
1511
- const pkgPath = cwdKey + '/package.json';
1512
- try {
1513
- const pkg = JSON.parse(kernelFs.readFileString(pkgPath));
1514
- if (pkg.scripts && Object.keys(pkg.scripts).length > 0) {
1515
- ctx.stdout.write('Lifecycle scripts:\n');
1516
- for (const [name, cmd] of Object.entries(pkg.scripts)) {
1517
- ctx.stdout.write(` ${name}\n ${cmd}\n`);
1518
- }
1519
- }
1520
- else {
1521
- ctx.stdout.write('No scripts found in package.json\n');
1522
- }
1523
- }
1524
- catch {
1525
- ctx.stderr.write('npm ERR! no package.json found\n');
1526
- return 1;
1527
- }
1528
- return 0;
1529
- }
1530
- const pkgPath = cwdKey + '/package.json';
1531
- try {
1532
- const pkg = JSON.parse(kernelFs.readFileString(pkgPath));
1533
- const script = pkg.scripts?.[scriptName];
1534
- if (!script) {
1535
- ctx.stderr.write(`npm ERR! Missing script: "${scriptName}"\n`);
1536
- if (pkg.scripts) {
1537
- ctx.stderr.write('npm ERR! Available scripts:\n');
1538
- for (const name of Object.keys(pkg.scripts))
1539
- ctx.stderr.write(` - ${name}\n`);
1540
- }
1541
- return 1;
1542
- }
1543
- // ── node_modules preflight ────────────────────────────────────
1544
- // If the script invokes a known bundler/framework CLI (vite, next,
1545
- // webpack, tsc, ...) and node_modules is missing, HARD-FAIL before
1546
- // running it — the tool would crash with a cryptic "command not
1547
- // found" / "cannot find package" error that's less helpful.
1548
- // For custom/unknown scripts (e.g. `echo hi`), emit a warning but
1549
- // continue — the user's intent might not need deps at all.
1550
- // Bypass with --force / --no-install-check in the script args, or
1551
- // by setting NIMBUS_SKIP_INSTALL_CHECK=1 in env.
1552
- const scriptArgs = args.slice(sub === 'run' || sub === 'run-script' ? 2 : 1);
1553
- const bypassRunCheck = scriptArgs.includes('--force') ||
1554
- scriptArgs.includes('--no-install-check') ||
1555
- ctx.env?.NIMBUS_SKIP_INSTALL_CHECK === '1';
1556
- if (!bypassRunCheck) {
1557
- const guard = checkNodeModulesGuard(kernelFs, cwdKey);
1558
- if (guard.missing) {
1559
- const bundler = detectBundlerBin(script);
1560
- if (bundler) {
1561
- // Hard fail: script needs a bundler binary that lives in node_modules/.bin.
1562
- ctx.stderr.write('\x1b[31m\u2718\x1b[0m \x1b[1mnode_modules/ not found\x1b[0m — ' +
1563
- `script "${scriptName}" runs \x1b[36m${bundler}\x1b[0m which needs installed dependencies ` +
1564
- `(${guard.depCount} declared).\n` +
1565
- ' Run \x1b[36mnpm install\x1b[0m first,\n' +
1566
- ' or re-run with \x1b[36mnpm run ' + scriptName + ' -- --force\x1b[0m to skip this check.\n');
1567
- return 1;
1568
- }
1569
- // Soft warning: script might not need deps; let it try.
1570
- ctx.stderr.write('\x1b[33m\u26A0\x1b[0m node_modules/ not found (' + guard.depCount + ' deps declared) — ' +
1571
- 'proceeding anyway. Run \x1b[36mnpm install\x1b[0m if the script fails.\n\n');
1572
- }
1573
- }
1574
- ctx.stdout.write(`\n> ${pkg.name || 'project'}@${pkg.version || '1.0.0'} ${scriptName}\n`);
1575
- ctx.stdout.write(`> ${script}\n\n`);
1576
- // ── Next.js loud-block (was W11 per-framework substrate) ──────
1577
- //
1578
- // runtime primitive support (P12): the previous wave shipped this as a
1579
- // 45-line standalone module at src/frameworks/next.ts that
1580
- // exported nothing but the strings used here. Per the
1581
- // "no per-framework substrate" rule, the message is inlined
1582
- // (the only thing the module did was hold these strings) and
1583
- // the file is deleted.
1584
- //
1585
- // Next.js dev/start/build/export all need the same pipeline —
1586
- // custom http.Server + child_process.fork with v8-IPC +
1587
- // webpack/Turbopack — none of which Nimbus ships. We surface a
1588
- // deterministic refusal rather than letting the script hang or
1589
- // (build) reset the isolate during spawn. The block remains a
1590
- // one-off symbol-detection guard, NOT a generic per-framework
1591
- // code path. Any future similar guard belongs alongside this
1592
- // one — not in its own src/frameworks/<name>.ts file.
1593
- const refused = refusedNextSubcommand(scriptName, script, pkg, scriptArgs);
1594
- if (refused) {
1595
- ctx.stderr.write(NEXT_REFUSAL_MESSAGE);
1596
- return 127;
1597
- }
1598
- const scriptTrim = script.trim();
1599
- const longRunning = scriptName === 'dev' || scriptName === 'start' ||
1600
- scriptName === 'serve' || scriptName === 'watch';
1601
- return await shellExecuteTracked(scriptTrim, {
1602
- ...ctx,
1603
- env: { ...ctx.env, npm_lifecycle_event: scriptName, npm_package_name: pkg.name || '' },
1604
- }, { longRunning });
1605
- }
1606
- catch (e) {
1607
- ctx.stderr.write(`npm ERR! ${e?.message || e}\n`);
1608
- return 1;
1609
- }
1610
- }
1611
- // npm ls — list installed packages
1612
- if (sub === 'ls' || sub === 'list') {
1613
- const pkgPath = cwdKey + '/package.json';
1614
- const nmDir = cwdKey + '/node_modules';
1615
- try {
1616
- const pkg = JSON.parse(kernelFs.readFileString(pkgPath));
1617
- ctx.stdout.write(`${pkg.name || 'project'}@${pkg.version || '1.0.0'} ${ctx.cwd}\n`);
1618
- const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
1619
- const names = Object.keys(deps);
1620
- for (let i = 0; i < names.length; i++) {
1621
- const isLast = i === names.length - 1;
1622
- const prefix = isLast ? '└── ' : '├── ';
1623
- const name = names[i];
1624
- let version = deps[name];
1625
- // Try to read actual installed version
1626
- try {
1627
- const installed = JSON.parse(kernelFs.readFileString(nmDir + '/' + name + '/package.json'));
1628
- version = installed.version;
1629
- }
1630
- catch { }
1631
- ctx.stdout.write(`${prefix}${name}@${version}\n`);
1632
- }
1633
- }
1634
- catch {
1635
- ctx.stderr.write('npm ERR! no package.json found\n');
1636
- return 1;
1637
- }
1638
- return 0;
1639
- }
1640
- // npm init / npm init -y
1641
- if (sub === 'init') {
1642
- const cwd = cwdKey;
1643
- const pkgPath = cwd + '/package.json';
1644
- if (kernelFs.exists(pkgPath) && !args.includes('-y') && !args.includes('--yes')) {
1645
- ctx.stderr.write('package.json already exists. Use -y to overwrite.\n');
1646
- return 1;
1647
- }
1648
- const name = cwd.split('/').pop() || 'project';
1649
- const pkg = {
1650
- name, version: '1.0.0', description: '', main: 'index.js',
1651
- type: 'module',
1652
- scripts: { dev: 'vite', build: 'vite build', preview: 'vite preview', test: 'echo "no test"' },
1653
- keywords: [], author: '', license: 'MIT', dependencies: {}, devDependencies: {},
1654
- };
1655
- kernelFs.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
1656
- ctx.stdout.write('Wrote to ' + pkgPath + '\n');
1657
- return 0;
1658
- }
1659
- // npm uninstall <pkg>
1660
- if (sub === 'uninstall' || sub === 'un' || sub === 'remove' || sub === 'rm') {
1661
- const packages = args.slice(1).filter(a => !a.startsWith('-'));
1662
- if (packages.length === 0) {
1663
- ctx.stderr.write('Usage: npm uninstall <pkg>\n');
1664
- return 1;
1665
- }
1666
- const nmDir = cwdKey + '/node_modules';
1667
- for (const pkg of packages) {
1668
- const pkgDir = nmDir + '/' + pkg;
1669
- // Recursively delete package directory
1670
- const deleteRecursive = (dir) => {
1671
- try {
1672
- for (const e of kernelFs.readdir(dir)) {
1673
- const fp = dir + '/' + e.name;
1674
- if (e.type === 'directory')
1675
- deleteRecursive(fp);
1676
- else
1677
- try {
1678
- kernelFs.unlink(fp);
1679
- }
1680
- catch { }
1681
- }
1682
- try {
1683
- kernelFs.rmdir(dir);
1684
- }
1685
- catch { }
1686
- }
1687
- catch { }
1688
- };
1689
- deleteRecursive(pkgDir);
1690
- ctx.stdout.write('removed ' + pkg + '\n');
1691
- }
1692
- // Update package.json
1693
- const pkgPath = cwdKey + '/package.json';
1694
- try {
1695
- const pkgJson = JSON.parse(kernelFs.readFileString(pkgPath));
1696
- for (const pkg of packages) {
1697
- delete pkgJson.dependencies?.[pkg];
1698
- delete pkgJson.devDependencies?.[pkg];
1699
- }
1700
- kernelFs.writeFile(pkgPath, JSON.stringify(pkgJson, null, 2) + '\n');
1701
- }
1702
- catch { }
1703
- return 0;
1704
- }
1705
- // ── npm create <pkg> / npm init <pkg> → npx create-<pkg> ─────────
1706
- //
1707
- // Per the npm spec, `npm create X args...` and `npm init X args...`
1708
- // (when X is supplied) are sugar for invoking the `create-X`
1709
- // initializer package via npx. Specifically:
1710
- //
1711
- // npm create foo args... → npx create-foo args...
1712
- // npm create foo@1.2 args... → npx create-foo@1.2 args...
1713
- // npm create @scope/foo args... → npx @scope/create-foo args...
1714
- // npm create @scope args... → npx @scope/create args...
1715
- //
1716
- // `npm init` (no args) is a different beast — it scaffolds a
1717
- // package.json interactively. The `sub === 'init'` branch above
1718
- // handles the no-arg case; here we only intercept the
1719
- // initializer-package case (1+ args after `init`).
1720
- //
1721
- // Without this routing, `npm create vite@latest mvp -- --template
1722
- // react-ts` hits the base npm dispatch which only knows
1723
- // {init, install/i/add, uninstall/remove/rm/un, list/ls,
1724
- // run/run-script, start, test, info/view/show, search, version}
1725
- // — and emits "npm: unknown command 'create'". Every modern
1726
- // framework's `create-*` flow (create-vite, create-next-app
1727
- // routed via "npm create", create-cloudflare, create-astro, etc.)
1728
- // depends on this.
1729
- //
1730
- // This is a primitive: one fix, every framework wins.
1731
- if (sub === 'create' || (sub === 'init' && args.length >= 2 && !args[1].startsWith('-'))) {
1732
- const arg1 = args[1];
1733
- if (!arg1) {
1734
- ctx.stderr.write('npm create: missing package name\n');
1735
- ctx.stderr.write('Usage: npm create <pkg> [args...]\n');
1736
- return 1;
1737
- }
1738
- // Parse pkg + version. Scope-aware:
1739
- // @scope → @scope/create
1740
- // @scope/foo → @scope/create-foo
1741
- // foo → create-foo
1742
- // foo@1.2.3 → create-foo@1.2.3
1743
- // foo@latest → create-foo@latest
1744
- function rewriteToCreatePkg(spec) {
1745
- // Strip an optional version range and re-append after the rewrite.
1746
- const atIdx = spec.lastIndexOf('@');
1747
- const hasVersion = atIdx > 0; // a leading @ is the scope; not a version
1748
- const bare = hasVersion ? spec.slice(0, atIdx) : spec;
1749
- const version = hasVersion ? spec.slice(atIdx) : '';
1750
- let pkg;
1751
- if (bare.startsWith('@')) {
1752
- const slash = bare.indexOf('/');
1753
- if (slash < 0) {
1754
- // @scope → @scope/create
1755
- pkg = bare + '/create';
1756
- }
1757
- else {
1758
- // @scope/foo → @scope/create-foo
1759
- const scope = bare.slice(0, slash);
1760
- const name = bare.slice(slash + 1);
1761
- pkg = scope + '/create-' + name;
1762
- }
1763
- }
1764
- else {
1765
- pkg = 'create-' + bare;
1766
- }
1767
- return pkg + version;
1768
- }
1769
- const createPkg = rewriteToCreatePkg(arg1);
1770
- const passThrough = args.slice(2);
1771
- // `npm create` accepts an optional `--` separator to push the
1772
- // remaining args to the create script; npx doesn't need a
1773
- // separator (positional args after the package name go to the
1774
- // package). We strip a single literal `--` token if present so
1775
- // `npm create vite@latest mvp -- --template react-ts` becomes
1776
- // `npx --yes create-vite@latest mvp --template react-ts`.
1777
- const stripped = passThrough.filter((a, i, arr) => !(a === '--' && i < arr.length - 1) && !(a === '--' && arr.indexOf('--') === i));
1778
- // Inform the user what we're routing to — matches npm's own
1779
- // visible "npx" line so the create flow is honest.
1780
- ctx.stdout.write(`> npx --yes ${createPkg}${stripped.length ? ' ' + stripped.join(' ') : ''}\n`);
1781
- // Dispatch through the npx registry entry. `--yes` skips the
1782
- // "Ok to proceed? (y)" prompt.
1783
- const npxHandler = await registry.resolve('npx');
1784
- if (!npxHandler) {
1785
- ctx.stderr.write('npm create: npx command unavailable\n');
1786
- return 1;
1787
- }
1788
- return await npxHandler({
1789
- ...ctx,
1790
- args: ['--yes', createPkg, ...stripped],
1791
- });
1792
- }
1793
- // Fall through to core npm for other subcommands
1794
- return coreNpmCmd(ctx);
1795
- });
1796
- // npx: check registered commands first, then resolve/install through
1797
- // Nimbus's NpmInstaller and execute the package bin via the Node runtime.
1798
- registry.register('npx', async (ctx) => {
1799
- const npxArgs = ctx.args || [];
1800
- const { describeNpxSelfInvocation, formatNpxHelp, getNpxCommandArgs, getNpxCommandWord, resolveNpxBinary, } = await import('../npm/npx-install.js');
1801
- const selfInvocation = describeNpxSelfInvocation(npxArgs);
1802
- if (selfInvocation === 'missing') {
1803
- ctx.stderr.write('Usage: npx <command> [args...]\n');
1804
- return 1;
1805
- }
1806
- if (selfInvocation === 'version') {
1807
- ctx.stdout.write(NPM_VERSION + '\n');
1808
- return 0;
1809
- }
1810
- if (selfInvocation === 'help') {
1811
- ctx.stdout.write(formatNpxHelp());
1812
- return 0;
1813
- }
1814
- const cmd = getNpxCommandWord(npxArgs);
1815
- // Check if it's a built-in command (vite, esbuild, etc.)
1816
- const resolved = cmd ? await registry.resolve(cmd) : null;
1817
- if (resolved) {
1818
- return await resolved({ ...ctx, args: getNpxCommandArgs(npxArgs) });
1819
- }
1820
- // Nimbus-native npx install + run path. Routes package installation
1821
- // through NpmInstaller's full-packument resolver.
1822
- await self.ensureNpmInstaller((msg) => ctx.stdout.write('[npm] ' + msg + '\n'));
1823
- self.ensureSqliteFs();
1824
- const installer = self.npmInstaller;
1825
- const resolveResult = await resolveNpxBinary(installer, self.sqliteFs.as(requireVfsCred('cred' in ctx ? ctx.cred : undefined, 'npx')), ctx.cwd || '/home/user', npxArgs, (msg) => ctx.stdout.write(msg + '\n'), ctx.pid);
1826
- if (resolveResult.ok && resolveResult.binPath) {
1827
- const nodeCmd = await registry.resolve('node');
1828
- if (nodeCmd) {
1829
- return await nodeCmd({
1830
- ...ctx,
1831
- args: [resolveResult.binPath, ...(resolveResult.binArgs || [])],
1832
- __nimbusBundleProfile: resolveResult.bundleProfile,
1833
- });
1834
- }
1835
- ctx.stderr.write('npx: node runtime is not registered\n');
1836
- return 1;
1837
- }
1838
- ctx.stderr.write((resolveResult.error || 'npx: could not resolve binary') + '\n');
1839
- return 1;
1840
- });
1841
- // ── Register process commands (enhanced with facet process tracking) ──
1842
- registry.register('ps', async (ctx) => {
1843
- // Pids are generation-strided (see PID_GEN_STRIDE) so they can be 7+
1844
- // digits; size the column to the widest pid in this listing.
1845
- const procs = self.processes.getAll();
1846
- const pidWidth = Math.max(3, ...procs.map((p) => String(p.pid).length));
1847
- ctx.stdout.write(` ${'PID'.padStart(pidWidth)} STATUS COMMAND\n`);
1848
- for (const proc of procs) {
1849
- // Prefer log-store exit info over ProcessTable's: the store has
1850
- // the authoritative code and survives reap. For `running`, rely
1851
- // on ProcessTable (store has no "running" concept).
1852
- let status;
1853
- if (proc.state === 'running') {
1854
- status = '\x1b[32mrunning\x1b[0m';
1855
- }
1856
- else if (proc.state === 'killed') {
1857
- status = `\x1b[33mkilled(${proc.exitCode ?? 137})\x1b[0m`;
1858
- }
1859
- else {
1860
- // 'exited' — distinguish clean vs crashed.
1861
- const code = proc.exitCode ?? 0;
1862
- status = code === 0
1863
- ? `\x1b[2mexited(0)\x1b[0m`
1864
- : `\x1b[31mcrashed(${code})\x1b[0m`;
1865
- }
1866
- ctx.stdout.write(` ${String(proc.pid).padStart(pidWidth)} ${status.padEnd(26)} ${proc.command}\n`);
1867
- }
1868
- // Show vite dev server
1869
- if (self.viteDevServer?.isRunning) {
1870
- ctx.stdout.write(` \x1b[33m${'---'.padStart(pidWidth)}\x1b[0m \x1b[32mrunning\x1b[0m vite dev server (${self.viteBasePath}/)\n`);
1871
- }
1872
- if (self.processes.getAll().length === 0 && !self.viteDevServer?.isRunning) {
1873
- ctx.stdout.write(' (no processes)\n');
1874
- }
1875
- return 0;
1876
- });
1877
- // ── `logs <pid>` — tail per-process ring buffer ──
1878
- // Flags:
1879
- // -f / --follow stream new chunks until the process exits
1880
- // -n / --lines N number of lines from the tail (default 200)
1881
- // --bytes N max bytes from the tail (overrides --lines)
1882
- // --plain strip ANSI escapes on output (keeps buffer raw)
1883
- registry.register('logs', async (ctx) => {
1884
- const args = ctx.args || [];
1885
- const follow = args.includes('-f') || args.includes('--follow');
1886
- const plain = args.includes('--plain');
1887
- let lines = 200;
1888
- let bytes;
1889
- for (let i = 0; i < args.length; i++) {
1890
- const a = args[i];
1891
- if ((a === '-n' || a === '--lines') && args[i + 1]) {
1892
- const n = parseInt(args[i + 1], 10);
1893
- if (!isNaN(n) && n > 0)
1894
- lines = n;
1895
- i++;
1896
- }
1897
- else if (a === '--bytes' && args[i + 1]) {
1898
- const n = parseInt(args[i + 1], 10);
1899
- if (!isNaN(n) && n > 0)
1900
- bytes = n;
1901
- i++;
1902
- }
1903
- }
1904
- const pidArg = args.find(a => /^\d+$/.test(a));
1905
- if (!pidArg) {
1906
- ctx.stderr.write('usage: logs [-f] [-n LINES | --bytes N] [--plain] <pid>\n');
1907
- return 1;
1908
- }
1909
- const pid = parseInt(pidArg, 10);
1910
- if (!self.processes.hasLogs(pid)) {
1911
- ctx.stderr.write(`no logs for pid ${pid}\n`);
1912
- return 1;
1913
- }
1914
- // Paint a single chunk for live-stream (follow-mode) rendering.
1915
- // `--plain` strips ANSI per chunk — safe for live output because
1916
- // individual streamed chunks from the RPC layer never split an
1917
- // escape sequence (the RPC boundary always delivers a complete
1918
- // write call). Backfill is different (see below).
1919
- const renderChunk = (c) => {
1920
- let data = c.data;
1921
- if (plain)
1922
- data = stripAnsi(data);
1923
- if (c.stream === 'stderr' && !plain) {
1924
- return `\x1b[31m${data}\x1b[0m`;
1925
- }
1926
- return data;
1927
- };
1928
- // Backfill. Concatenate same-stream consecutive chunks BEFORE
1929
- // stripping so that any ANSI escape split across chunk boundaries
1930
- // (by the 4 KB splitter inside ProcessLogStore) gets rejoined and
1931
- // stripped cleanly instead of leaking `1m` / `[31m` fragments.
1932
- const tailOpts = bytes !== undefined ? { bytes } : { lines };
1933
- const chunks = self.processes.tailLogs(pid, tailOpts);
1934
- let group = [];
1935
- const flushGroup = () => {
1936
- if (group.length === 0)
1937
- return;
1938
- const stream = group[0].stream;
1939
- let data = group.map(c => c.data).join('');
1940
- if (plain)
1941
- data = stripAnsi(data);
1942
- if (stream === 'stderr' && !plain) {
1943
- ctx.stdout.write(`\x1b[31m${data}\x1b[0m`);
1944
- }
1945
- else {
1946
- ctx.stdout.write(data);
1947
- }
1948
- group = [];
1949
- };
1950
- for (const c of chunks) {
1951
- if (group.length > 0 && group[group.length - 1].stream !== c.stream) {
1952
- flushGroup();
1953
- }
1954
- group.push(c);
1955
- }
1956
- flushGroup();
1957
- if (!follow) {
1958
- // Footer only when process has exited already.
1959
- const exit = self.processes.getExit(pid);
1960
- if (exit) {
1961
- ctx.stdout.write(`\r\n\x1b[2m[process exited with code ${exit.code}${exit.reason ? ` (${exit.reason})` : ''}]\x1b[0m\r\n`);
1962
- }
1963
- return 0;
1964
- }
1965
- // Follow mode: subscribe to live appends, poll for exit.
1966
- const entry = self.processes.get(pid);
1967
- const alreadyExited = !entry || entry.state !== 'running' || self.processes.getExit(pid);
1968
- if (alreadyExited) {
1969
- const exit = self.processes.getExit(pid);
1970
- if (exit) {
1971
- ctx.stdout.write(`\r\n\x1b[2m[process exited with code ${exit.code}${exit.reason ? ` (${exit.reason})` : ''}]\x1b[0m\r\n`);
1972
- }
1973
- return 0;
1974
- }
1975
- return await new Promise((resolve) => {
1976
- let done = false;
1977
- const finish = (code) => {
1978
- if (done)
1979
- return;
1980
- done = true;
1981
- unsub();
1982
- unsubExit();
1983
- resolve(code);
1984
- };
1985
- const unsub = self.processes.subscribeLogs(pid, (c) => {
1986
- ctx.stdout.write(renderChunk(c));
1987
- });
1988
- const unsubExit = self.processes.subscribeExit(pid, (exit) => {
1989
- ctx.stdout.write(`\r\n\x1b[2m[process exited with code ${exit.code}${exit.reason ? ` (${exit.reason})` : ''}]\x1b[0m\r\n`);
1990
- finish(0);
1991
- });
1992
- // TOCTOU: the process may have exited between our `alreadyExited`
1993
- // check above and these subscribe calls. Re-check now that the
1994
- // exit subscriber is wired — if exit already set, the subscribe
1995
- // callback never fires, so synthesize the footer ourselves.
1996
- const exitNow = self.processes.getExit(pid);
1997
- if (exitNow) {
1998
- ctx.stdout.write(`\r\n\x1b[2m[process exited with code ${exitNow.code}${exitNow.reason ? ` (${exitNow.reason})` : ''}]\x1b[0m\r\n`);
1999
- finish(0);
2000
- return;
2001
- }
2002
- // If ctx exposes an AbortSignal (Ctrl+C wired by the shell),
2003
- // honor it. Otherwise, follow-mode ends only on process exit.
2004
- if (ctx.signal && typeof ctx.signal.addEventListener === 'function') {
2005
- ctx.signal.addEventListener('abort', () => finish(130));
2006
- }
2007
- });
2008
- });
2009
- registry.register('jobs', async (ctx) => {
2010
- const running = self.processes.getRunning();
2011
- if (running.length === 0 && !self.viteDevServer?.isRunning) {
2012
- ctx.stdout.write('No background jobs.\n');
2013
- return 0;
2014
- }
2015
- for (let i = 0; i < running.length; i++) {
2016
- ctx.stdout.write(`[${i + 1}] Running ${running[i].command} (pid ${running[i].pid})\n`);
2017
- }
2018
- if (self.viteDevServer?.isRunning) {
2019
- ctx.stdout.write(`[${running.length + 1}] Running vite dev server\n`);
2020
- }
2021
- return 0;
2022
- });
2023
- const shellKillCommand = createKillCommand(processRegistry);
2024
- registry.register('kill', async (ctx) => {
2025
- const pidArg = ctx.args[0];
2026
- if (!pidArg) {
2027
- ctx.stderr.write('Usage: kill <pid>\n');
2028
- return 1;
2029
- }
2030
- if (pidArg.startsWith('-') || pidArg.startsWith('%')) {
2031
- return shellKillCommand(ctx);
2032
- }
2033
- const pid = parseInt(pidArg);
2034
- if (isNaN(pid)) {
2035
- ctx.stderr.write('kill: invalid pid\n');
2036
- return 1;
2037
- }
2038
- if (processRegistry.get(pid)) {
2039
- return shellKillCommand(ctx);
2040
- }
2041
- // runtime primitive support (P11): if the target is the vite shim PID
2042
- // (registered by P5's long-running spawn), tear down the
2043
- // in-process viteDevServer / cirrusReal too — facetManager.kill
2044
- // only handles real Worker-Loader facets, and would leave the
2045
- // shim running with its port registered against a dead PID.
2046
- if (self._viteShimPid === pid) {
2047
- try {
2048
- if (self.cirrusReal?.isRunning) {
2049
- self.cirrusReal.stop(self.ctx);
2050
- self.cirrusReal = null;
2051
- }
2052
- if (self.viteDevServer?.isRunning) {
2053
- self.viteDevServer.stop();
2054
- self.viteDevServer = null;
2055
- try {
2056
- await self.ctx.storage.delete(VITE_CONFIG_KEY);
2057
- }
2058
- catch { }
2059
- }
2060
- }
2061
- catch (e) {
2062
- ctx.stderr.write('kill: while stopping vite shim: ' + (e?.message || e) + '\n');
2063
- }
2064
- try {
2065
- self.portRegistry.unregisterByPid(pid);
2066
- }
2067
- catch { }
2068
- try {
2069
- self.processes.kill(pid);
2070
- }
2071
- catch { }
2072
- notifyTerminalEvent(self.terminal, {
2073
- type: 'exit', pid, code: 137, command: 'vite',
2074
- });
2075
- self._viteShimPid = null;
2076
- self._viteShimPort = null;
2077
- ctx.stdout.write(`Process ${pid} killed.\n`);
2078
- return 0;
2079
- }
2080
- if (self.facetManager?.kill(pid)) {
2081
- ctx.stdout.write(`Process ${pid} killed.\n`);
2082
- return 0;
2083
- }
2084
- ctx.stderr.write(`kill: no such process: ${pid}\n`);
2085
- return 1;
2086
- });
2087
- registry.register('top', createTopCommand(processRegistry));
2088
- registry.register('watch', createWatchCommand(registry));
2089
- registry.register('help', createHelpCommand(registry));
2090
- // ── Rehydrate globally-installed npm packages ──
2091
- try {
2092
- rehydrateGlobalPackages(self.kernel.vfs, registry);
2093
- }
2094
- catch { }
352
+ await registerHostedCommands(self, workspace);
2095
353
  // ── Phase O: one-shot online output [B'.1] ─────────────────────────
2096
354
  //
2097
355
  // Only emit cold-start UI (MOTD, starter-app hint, framework-detect)
@@ -2224,19 +482,5 @@ export async function initSession(self, ws, options = {}) {
2224
482
  });
2225
483
  if (options.resume === 'wake')
2226
484
  await started;
2227
- ws.send(JSON.stringify({ type: 'ready' }));
2228
- }
2229
- function installShellExecutionFeatures(shell, terminal) {
2230
- HeredocHandler.install(shell, terminal);
2231
- }
2232
- function createHeadlessTerminal() {
2233
- return {
2234
- cols: 80,
2235
- rows: 24,
2236
- write() { },
2237
- writeln() { },
2238
- onData() { },
2239
- focus() { },
2240
- clear() { },
2241
- };
485
+ ws?.send(JSON.stringify({ type: 'ready' }));
2242
486
  }