dev3000 0.0.188 → 0.0.191

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 (159) hide show
  1. package/README.md +84 -12
  2. package/dist/cdp-monitor.d.ts +10 -0
  3. package/dist/cdp-monitor.d.ts.map +1 -1
  4. package/dist/cdp-monitor.js +28 -4
  5. package/dist/cdp-monitor.js.map +1 -1
  6. package/dist/runtime/bridge.d.ts +2 -0
  7. package/dist/runtime/bridge.d.ts.map +1 -1
  8. package/dist/runtime/bridge.js +74 -0
  9. package/dist/runtime/bridge.js.map +1 -1
  10. package/dist/runtime/browser-events.d.ts +3 -2
  11. package/dist/runtime/browser-events.d.ts.map +1 -1
  12. package/dist/runtime/browser-events.js +11 -53
  13. package/dist/runtime/browser-events.js.map +1 -1
  14. package/dist/runtime/browser-metrics.d.ts +147 -0
  15. package/dist/runtime/browser-metrics.d.ts.map +1 -0
  16. package/dist/runtime/browser-metrics.js +243 -0
  17. package/dist/runtime/browser-metrics.js.map +1 -0
  18. package/dist/runtime/chrome-isolation.d.ts +3 -2
  19. package/dist/runtime/chrome-isolation.d.ts.map +1 -1
  20. package/dist/runtime/chrome-isolation.js +23 -35
  21. package/dist/runtime/chrome-isolation.js.map +1 -1
  22. package/dist/runtime/cli.js +63 -2
  23. package/dist/runtime/cli.js.map +1 -1
  24. package/dist/runtime/desktop-mcp.d.ts +216 -0
  25. package/dist/runtime/desktop-mcp.d.ts.map +1 -0
  26. package/dist/runtime/desktop-mcp.js +258 -0
  27. package/dist/runtime/desktop-mcp.js.map +1 -0
  28. package/dist/runtime/git-identity.d.ts +17 -0
  29. package/dist/runtime/git-identity.d.ts.map +1 -0
  30. package/dist/runtime/git-identity.js +41 -0
  31. package/dist/runtime/git-identity.js.map +1 -0
  32. package/dist/runtime/github-publish.d.ts +31 -0
  33. package/dist/runtime/github-publish.d.ts.map +1 -0
  34. package/dist/runtime/github-publish.js +237 -0
  35. package/dist/runtime/github-publish.js.map +1 -0
  36. package/dist/runtime/harness.d.ts +14 -3
  37. package/dist/runtime/harness.d.ts.map +1 -1
  38. package/dist/runtime/harness.js +55 -7
  39. package/dist/runtime/harness.js.map +1 -1
  40. package/dist/runtime/mcp-stdio.d.ts +17 -0
  41. package/dist/runtime/mcp-stdio.d.ts.map +1 -0
  42. package/dist/runtime/mcp-stdio.js +99 -0
  43. package/dist/runtime/mcp-stdio.js.map +1 -0
  44. package/dist/runtime/network-evidence.d.ts +28 -0
  45. package/dist/runtime/network-evidence.d.ts.map +1 -0
  46. package/dist/runtime/network-evidence.js +291 -0
  47. package/dist/runtime/network-evidence.js.map +1 -0
  48. package/dist/runtime/runtime.d.ts +4 -0
  49. package/dist/runtime/runtime.d.ts.map +1 -1
  50. package/dist/runtime/runtime.js +48 -17
  51. package/dist/runtime/runtime.js.map +1 -1
  52. package/dist/runtime/sandbox-agent.d.ts +5 -0
  53. package/dist/runtime/sandbox-agent.d.ts.map +1 -1
  54. package/dist/runtime/sandbox-agent.js +32 -0
  55. package/dist/runtime/sandbox-agent.js.map +1 -1
  56. package/dist/runtime/sandbox-cleanup.d.ts +14 -0
  57. package/dist/runtime/sandbox-cleanup.d.ts.map +1 -0
  58. package/dist/runtime/sandbox-cleanup.js +49 -0
  59. package/dist/runtime/sandbox-cleanup.js.map +1 -0
  60. package/dist/runtime/sandbox-command.d.ts +1 -0
  61. package/dist/runtime/sandbox-command.d.ts.map +1 -1
  62. package/dist/runtime/sandbox-command.js +38 -8
  63. package/dist/runtime/sandbox-command.js.map +1 -1
  64. package/dist/runtime/sandbox-context.d.ts +5 -0
  65. package/dist/runtime/sandbox-context.d.ts.map +1 -0
  66. package/dist/runtime/sandbox-context.js +42 -0
  67. package/dist/runtime/sandbox-context.js.map +1 -0
  68. package/dist/runtime/sandbox-fx-resume.d.ts +11 -0
  69. package/dist/runtime/sandbox-fx-resume.d.ts.map +1 -0
  70. package/dist/runtime/sandbox-fx-resume.js +45 -0
  71. package/dist/runtime/sandbox-fx-resume.js.map +1 -0
  72. package/dist/runtime/sandbox-gateway.d.ts +17 -0
  73. package/dist/runtime/sandbox-gateway.d.ts.map +1 -0
  74. package/dist/runtime/sandbox-gateway.js +34 -0
  75. package/dist/runtime/sandbox-gateway.js.map +1 -0
  76. package/dist/runtime/sandbox-github.d.ts +10 -0
  77. package/dist/runtime/sandbox-github.d.ts.map +1 -0
  78. package/dist/runtime/sandbox-github.js +35 -0
  79. package/dist/runtime/sandbox-github.js.map +1 -0
  80. package/dist/runtime/sandbox-local-harness.d.ts +34 -0
  81. package/dist/runtime/sandbox-local-harness.d.ts.map +1 -0
  82. package/dist/runtime/sandbox-local-harness.js +138 -0
  83. package/dist/runtime/sandbox-local-harness.js.map +1 -0
  84. package/dist/runtime/sandbox-preview.d.ts +14 -0
  85. package/dist/runtime/sandbox-preview.d.ts.map +1 -0
  86. package/dist/runtime/sandbox-preview.js +96 -0
  87. package/dist/runtime/sandbox-preview.js.map +1 -0
  88. package/dist/runtime/sandbox-process.d.ts +11 -0
  89. package/dist/runtime/sandbox-process.d.ts.map +1 -0
  90. package/dist/runtime/sandbox-process.js +77 -0
  91. package/dist/runtime/sandbox-process.js.map +1 -0
  92. package/dist/runtime/sandbox-proxy.d.ts +2 -0
  93. package/dist/runtime/sandbox-proxy.d.ts.map +1 -1
  94. package/dist/runtime/sandbox-proxy.js +75 -20
  95. package/dist/runtime/sandbox-proxy.js.map +1 -1
  96. package/dist/runtime/sandbox-recovery.d.ts +4 -0
  97. package/dist/runtime/sandbox-recovery.d.ts.map +1 -0
  98. package/dist/runtime/sandbox-recovery.js +36 -0
  99. package/dist/runtime/sandbox-recovery.js.map +1 -0
  100. package/dist/runtime/sandbox-sessions.d.ts +8 -1
  101. package/dist/runtime/sandbox-sessions.d.ts.map +1 -1
  102. package/dist/runtime/sandbox-sessions.js +20 -2
  103. package/dist/runtime/sandbox-sessions.js.map +1 -1
  104. package/dist/runtime/sandbox-setup.d.ts +4 -0
  105. package/dist/runtime/sandbox-setup.d.ts.map +1 -0
  106. package/dist/runtime/sandbox-setup.js +56 -0
  107. package/dist/runtime/sandbox-setup.js.map +1 -0
  108. package/dist/runtime/sandbox-shell.d.ts +27 -0
  109. package/dist/runtime/sandbox-shell.d.ts.map +1 -0
  110. package/dist/runtime/sandbox-shell.js +169 -0
  111. package/dist/runtime/sandbox-shell.js.map +1 -0
  112. package/dist/runtime/sandbox-watch.d.ts +11 -0
  113. package/dist/runtime/sandbox-watch.d.ts.map +1 -0
  114. package/dist/runtime/sandbox-watch.js +30 -0
  115. package/dist/runtime/sandbox-watch.js.map +1 -0
  116. package/dist/runtime/sandbox-workspace.d.ts +125 -0
  117. package/dist/runtime/sandbox-workspace.d.ts.map +1 -0
  118. package/dist/runtime/sandbox-workspace.js +205 -0
  119. package/dist/runtime/sandbox-workspace.js.map +1 -0
  120. package/dist/runtime/sandbox.d.ts +21 -2
  121. package/dist/runtime/sandbox.d.ts.map +1 -1
  122. package/dist/runtime/sandbox.js +435 -198
  123. package/dist/runtime/sandbox.js.map +1 -1
  124. package/dist/runtime/session.d.ts +1 -1
  125. package/dist/runtime/session.d.ts.map +1 -1
  126. package/dist/runtime/session.js +3 -3
  127. package/dist/runtime/session.js.map +1 -1
  128. package/dist/runtime/terminal.d.ts +19 -0
  129. package/dist/runtime/terminal.d.ts.map +1 -0
  130. package/dist/runtime/terminal.js +60 -0
  131. package/dist/runtime/terminal.js.map +1 -0
  132. package/dist/runtime/workspace-client.d.ts +2 -0
  133. package/dist/runtime/workspace-client.d.ts.map +1 -0
  134. package/dist/runtime/workspace-client.js +42 -0
  135. package/dist/runtime/workspace-client.js.map +1 -0
  136. package/package.json +2 -1
  137. package/scripts/eve/README.md +341 -0
  138. package/scripts/eve/agent/agent.ts +12 -0
  139. package/scripts/eve/agent/channels/eve.ts +23 -0
  140. package/scripts/eve/agent/instructions.md +53 -0
  141. package/scripts/eve/agent/sandbox.ts +34 -0
  142. package/scripts/eve/build-cache.mjs +18 -0
  143. package/scripts/eve/build-cache.test.mjs +32 -0
  144. package/scripts/eve/client.mjs +229 -0
  145. package/scripts/eve/connection.mjs +89 -0
  146. package/scripts/eve/conversation.mjs +91 -0
  147. package/scripts/eve/conversation.test.mjs +113 -0
  148. package/scripts/eve/fixture-agent.ts +101 -0
  149. package/scripts/eve/images.mjs +84 -0
  150. package/scripts/eve/launch.mjs +277 -0
  151. package/scripts/eve/model-command.mjs +21 -0
  152. package/scripts/eve/reconnect.mjs +22 -0
  153. package/scripts/eve/reconnect.test.mjs +41 -0
  154. package/scripts/eve/settings.mjs +33 -0
  155. package/scripts/eve/supervisor.mjs +41 -0
  156. package/scripts/eve/tui-client.mjs +234 -0
  157. package/scripts/eve/tui-input.mjs +114 -0
  158. package/scripts/eve/verify.mjs +575 -0
  159. package/skills/d3k/SKILL.md +48 -5
@@ -1,4 +1,3 @@
1
- import { spawn } from "node:child_process";
2
1
  import { createHash, randomBytes, randomUUID } from "node:crypto";
3
2
  import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
4
3
  import { mkdir, writeFile } from "node:fs/promises";
@@ -6,72 +5,33 @@ import { createServer } from "node:net";
6
5
  import { homedir, tmpdir } from "node:os";
7
6
  import { dirname, join, posix, resolve } from "node:path";
8
7
  import { fileURLToPath } from "node:url";
9
- import { parseEnv } from "node:util";
10
8
  import { Sandbox } from "@vercel/sandbox";
11
9
  import { CDPMonitor } from "../cdp-monitor.js";
12
10
  import { isPortlessHostnameHeld, preparePortlessRuntime, registerPortlessAlias, removePortlessAlias } from "../portless.js";
13
11
  import { connectCompanion } from "./bridge.js";
14
12
  import { portlessCertificatePin, sandboxChromePath } from "./chrome-isolation.js";
15
- import { harnessInvocation, harnessSkill } from "./harness.js";
13
+ import { harnessInvocation, harnessSkill, runHarnessProcess } from "./harness.js";
16
14
  import { startLocalProxy } from "./local-proxy.js";
17
- import { prepareSandboxFx, SANDBOX_AGENT_BIN, SANDBOX_AGENT_DIRECTORY, SANDBOX_TOOLS } from "./sandbox-agent.js";
18
- import { listSandboxSessions, readSandboxSession, saveSandboxSession } from "./sandbox-sessions.js";
15
+ import { configureSandboxFxGateway, prepareSandboxFx, SANDBOX_AGENT_BIN, SANDBOX_AGENT_DIRECTORY, SANDBOX_TOOLS } from "./sandbox-agent.js";
16
+ import { closeSandboxResources } from "./sandbox-cleanup.js";
17
+ import { DEFAULT_SANDBOX_TIMEOUT_MINUTES } from "./sandbox-command.js";
18
+ import { sandboxFxContext } from "./sandbox-context.js";
19
+ import { discoverLegacyFxWorkspace } from "./sandbox-fx-resume.js";
20
+ import { createSandboxGateway } from "./sandbox-gateway.js";
21
+ import { callSandboxGithub } from "./sandbox-github.js";
22
+ import { createLocalSandboxWorkspace, launchLocalSandboxHarness } from "./sandbox-local-harness.js";
23
+ import { sandboxPreviewLink } from "./sandbox-preview.js";
24
+ import { runSandboxCli } from "./sandbox-process.js";
25
+ import { sandboxRecovery } from "./sandbox-recovery.js";
26
+ import { listSandboxSessions, readSandboxSession, sandboxFxWorkspace, saveSandboxSession } from "./sandbox-sessions.js";
27
+ import { dependencyCacheScript, distributionFingerprint } from "./sandbox-setup.js";
28
+ import { runSandboxShell, SandboxShellDisconnected } from "./sandbox-shell.js";
29
+ import { watchSandboxRuntime } from "./sandbox-watch.js";
30
+ import { finishTerminalCleanup, holdTerminalForCleanup } from "./terminal.js";
19
31
  const REMOTE_TOOLS = SANDBOX_TOOLS;
20
32
  const REMOTE_ENTRY = `${REMOTE_TOOLS}/node_modules/dev3000/dist/runtime/cli.js`;
21
33
  const APP_PORT = 3000;
22
34
  const BRIDGE_PORT = 9223;
23
- /** No shell interpolation. Bounded captured output also keeps credential-bearing CLI output out of logs. */
24
- async function run(binary, args, options = {}) {
25
- return new Promise((resolveRun, reject) => {
26
- if (options.signal?.aborted) {
27
- reject(new Error("Session ended"));
28
- return;
29
- }
30
- const child = spawn(binary, args, {
31
- cwd: options.cwd,
32
- env: options.env,
33
- stdio: options.inherit ? "inherit" : [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
34
- });
35
- let killTimer;
36
- const abort = () => {
37
- child.kill("SIGTERM");
38
- killTimer = setTimeout(() => child.kill("SIGKILL"), 1000);
39
- killTimer.unref();
40
- };
41
- options.signal?.addEventListener("abort", abort, { once: true });
42
- const cleanup = () => {
43
- options.signal?.removeEventListener("abort", abort);
44
- if (killTimer)
45
- clearTimeout(killTimer);
46
- };
47
- let stdout = "";
48
- let stderr = "";
49
- child.stdout?.on("data", (chunk) => {
50
- stdout += chunk.toString();
51
- if (stdout.length > 4 * 1024 * 1024)
52
- child.kill();
53
- });
54
- child.stderr?.on("data", (chunk) => {
55
- stderr = (stderr + chunk.toString()).slice(-8192);
56
- });
57
- child.on("error", (error) => {
58
- cleanup();
59
- reject(error);
60
- });
61
- child.stdin?.on("error", () => { }); // Early CLI exits still report their bounded stderr below.
62
- if (options.input !== undefined)
63
- child.stdin?.end(options.input);
64
- child.on("exit", (code) => {
65
- cleanup();
66
- if (options.signal?.aborted)
67
- resolveRun(stdout);
68
- else if (code === 0)
69
- resolveRun(stdout);
70
- else
71
- reject(new Error(`${binary} ${args[0]} failed: ${stderr || `exit ${code}`}`));
72
- });
73
- });
74
- }
75
35
  export function sandboxWorkdir(rootDirectory, repositoryRoot = "/vercel/sandbox") {
76
36
  const root = posix.resolve(repositoryRoot, rootDirectory || ".");
77
37
  if (root !== repositoryRoot && !root.startsWith(`${repositoryRoot}/`))
@@ -90,10 +50,15 @@ async function freePort() {
90
50
  await new Promise((resolveClose) => server.close(() => resolveClose()));
91
51
  return address.port;
92
52
  }
93
- export async function launchSandbox(options) {
53
+ export async function launchSandbox(options, lifecycle = {}) {
54
+ const localHarness = !!options.harness && options.harnessLocation !== "sandbox";
55
+ const timeoutMinutes = Number(options.timeout ?? DEFAULT_SANDBOX_TIMEOUT_MINUTES);
56
+ const expiresAt = Date.now() + timeoutMinutes * 60000;
94
57
  const scope = options.scope ? ["--scope", options.scope] : [];
95
- const log = (message) => console.error(`[d3k sandbox] ${message}`);
96
- const isolatedBrowserPath = await sandboxChromePath(log);
58
+ const log = (message) => {
59
+ console.error(`[d3k sandbox] ${message}`);
60
+ lifecycle.log?.(message);
61
+ };
97
62
  const temporary = mkdtempSync(join(tmpdir(), "d3k-sandbox-"));
98
63
  let localProxy;
99
64
  let localRoute;
@@ -101,6 +66,9 @@ export async function launchSandbox(options) {
101
66
  let sandbox;
102
67
  let browser;
103
68
  let companion;
69
+ let gateway;
70
+ let fxBinary;
71
+ let fxContextInstalled = false;
104
72
  let savedSession;
105
73
  let remoteStarted = false;
106
74
  let originalPorts;
@@ -109,27 +77,45 @@ export async function launchSandbox(options) {
109
77
  let remoteWorkdir = "/vercel/sandbox";
110
78
  let finish = () => { };
111
79
  const shellAbort = new AbortController();
80
+ const run = (binary, args, config) => runSandboxCli(binary, args, { signal: shellAbort.signal, timeoutMs: 60000, ...config });
81
+ const watchAbort = new AbortController();
82
+ let shellActive = false;
112
83
  const ended = new Promise((resolveEnd) => {
113
84
  finish = () => {
114
85
  browser?.prepareShutdown();
115
86
  companion?.close();
87
+ watchAbort.abort();
116
88
  shellAbort.abort();
117
89
  resolveEnd();
118
90
  };
119
91
  });
120
- const onSignal = () => {
92
+ const onSignal = (signal) => {
93
+ if (closing)
94
+ return;
95
+ if (!signalReceived)
96
+ log(`Received ${signal}; closing session`);
121
97
  signalReceived = true;
122
98
  finish();
123
99
  };
124
- process.on("SIGINT", onSignal);
125
- process.on("SIGTERM", onSignal);
100
+ const onAbort = () => onSignal("SIGTERM");
101
+ if (lifecycle.signal)
102
+ lifecycle.signal.addEventListener("abort", onAbort, { once: true });
103
+ else {
104
+ process.on("SIGINT", onSignal);
105
+ process.on("SIGTERM", onSignal);
106
+ }
126
107
  try {
108
+ if (lifecycle.signal?.aborted)
109
+ return;
127
110
  const routing = preparePortlessRuntime(`${options.hostname || options.project.toLowerCase().replace(/[^a-z0-9-]/g, "-")}.d3k`);
128
111
  if (!routing.runtime)
129
112
  throw new Error(routing.error || "Canonical Portless is required");
130
113
  localRoute = routing.runtime;
131
114
  if (isPortlessHostnameHeld(localRoute.name))
132
115
  throw new Error(`${localRoute.url} is already in use; stop that session or choose another --hostname`);
116
+ const isolatedBrowserPath = sandboxChromePath(log);
117
+ if (signalReceived)
118
+ return;
133
119
  log(`Resolving ${options.project} through Vercel CLI`);
134
120
  const project = JSON.parse(await run("vercel", ["api", `/v9/projects/${encodeURIComponent(options.project)}`, ...scope, "--raw"], {
135
121
  cwd: temporary
@@ -148,8 +134,8 @@ export async function launchSandbox(options) {
148
134
  if (options.attach) {
149
135
  // Read configured routes before resuming: resume responses may also contain reserved system ports.
150
136
  // The first command below resumes compute automatically after user ports have been configured.
151
- sandbox = await Sandbox.get({ ...credentials, name: options.attach });
152
- await sandbox.update({ timeout: Number(options.timeout || 30) * 60000 });
137
+ sandbox = await Sandbox.get({ ...credentials, name: options.attach, signal: shellAbort.signal });
138
+ await sandbox.update({ timeout: timeoutMinutes * 60000 });
153
139
  const ports = sandbox.routes.map((route) => route.port);
154
140
  if (!ports.includes(APP_PORT) || !ports.includes(BRIDGE_PORT)) {
155
141
  originalPorts = ports;
@@ -159,20 +145,22 @@ export async function launchSandbox(options) {
159
145
  else {
160
146
  if (project.link?.type !== "github" || !project.link.org || !project.link.repo)
161
147
  throw new Error("This project needs a linked GitHub repository");
148
+ const repository = `${project.link.org}/${project.link.repo}`;
162
149
  log("Creating a sandbox and cloning the linked public repository remotely");
163
150
  sandbox = await Sandbox.create({
164
151
  ...credentials,
152
+ signal: shellAbort.signal,
165
153
  ...(options.name ? { name: options.name } : {}),
166
154
  ...(options.region ? { region: options.region } : {}),
167
- timeout: Number(options.timeout || 30) * 60000,
155
+ timeout: timeoutMinutes * 60000,
168
156
  ports: [APP_PORT, BRIDGE_PORT],
169
157
  source: {
170
158
  type: "git",
171
- url: `https://github.com/${project.link.org}/${project.link.repo}.git`,
159
+ url: `https://github.com/${repository}.git`,
172
160
  ...(options.branch ? { revision: options.branch } : {})
173
161
  }
174
162
  }).catch((error) => {
175
- throw new Error(`${error instanceof Error ? error.message : "Could not create the source sandbox"}. Automatic cloning currently requires a public GitHub repository. For a private repository, use --attach <name> with an existing sandbox that already contains the checkout.`, { cause: error });
163
+ throw new Error(`Could not create the sandbox from ${repository}${options.branch ? ` at ${options.branch}` : ""}: ${error instanceof Error ? error.message : "Unknown creation error"}. Check Sandbox access, connectivity, and that the repository and requested revision are publicly accessible. This failure does not establish that the repository is private. No existing checkout was reused.`, { cause: error });
176
164
  });
177
165
  }
178
166
  log(`Sandbox ${sandbox.name} is running`);
@@ -198,20 +186,41 @@ export async function launchSandbox(options) {
198
186
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
199
187
  if (!existsSync(join(packageRoot, "dist/runtime/cli.js")))
200
188
  throw new Error("Build d3k before starting a sandbox from a source checkout");
201
- const archive = join(temporary, "dev3000.tgz");
202
- await run("bun", ["pm", "pack", "--filename", archive, "--quiet"], { cwd: packageRoot });
203
- const mkdirResult = await sandbox.runCommand("mkdir", ["-p", REMOTE_TOOLS]);
204
- if (mkdirResult.exitCode !== 0)
205
- throw new Error("Could not prepare remote d3k tools directory");
206
- await sandbox.writeFiles([{ path: `${REMOTE_TOOLS}/dev3000.tgz`, content: readFileSync(archive) }]);
207
- log("Installing d3k in the sandbox");
208
- const installTools = await sandbox.runCommand({
209
- cmd: "bun",
210
- args: ["add", "--cwd", REMOTE_TOOLS, `${REMOTE_TOOLS}/dev3000.tgz`],
211
- timeoutMs: 180000
189
+ const distribution = distributionFingerprint(packageRoot);
190
+ const distributionMarker = `${REMOTE_TOOLS}/distribution.sha256`;
191
+ const cachedTools = await sandbox.runCommand({
192
+ cmd: "node",
193
+ args: [
194
+ "-e",
195
+ "const fs=require('node:fs');const [marker,hash,entry]=process.argv.slice(1);process.exit(fs.existsSync(entry)&&fs.existsSync(marker)&&fs.readFileSync(marker,'utf8')===hash?0:10)",
196
+ distributionMarker,
197
+ distribution,
198
+ REMOTE_ENTRY
199
+ ]
212
200
  });
213
- if (installTools.exitCode !== 0)
214
- throw new Error(`Remote d3k install failed: ${(await installTools.stderr()).slice(-4000)}`);
201
+ if (cachedTools.exitCode === 0)
202
+ log("Reusing installed sandbox d3k (unchanged distribution)");
203
+ else {
204
+ const archive = join(temporary, "dev3000.tgz");
205
+ await run("bun", ["pm", "pack", "--filename", archive, "--quiet"], { cwd: packageRoot });
206
+ const mkdirResult = await sandbox.runCommand("mkdir", ["-p", REMOTE_TOOLS]);
207
+ if (mkdirResult.exitCode !== 0)
208
+ throw new Error("Could not prepare remote d3k tools directory");
209
+ const invalidated = await sandbox.runCommand("rm", ["-f", distributionMarker]);
210
+ if (invalidated.exitCode !== 0)
211
+ throw new Error("Could not invalidate the remote d3k install marker");
212
+ await sandbox.writeFiles([{ path: `${REMOTE_TOOLS}/dev3000.tgz`, content: readFileSync(archive) }]);
213
+ log("Installing d3k in the sandbox (distribution changed or missing)");
214
+ const installTools = await sandbox.runCommand({
215
+ cmd: "bun",
216
+ args: ["add", "--cwd", REMOTE_TOOLS, `${REMOTE_TOOLS}/dev3000.tgz`],
217
+ timeoutMs: 180000,
218
+ signal: shellAbort.signal
219
+ });
220
+ if (installTools.exitCode !== 0)
221
+ throw new Error(`Remote d3k install failed: ${(await installTools.stderr()).slice(-4000)}`);
222
+ await sandbox.writeFiles([{ path: distributionMarker, content: Buffer.from(distribution) }]);
223
+ }
215
224
  const existing = await sandbox.runCommand({ cmd: "node", args: [REMOTE_ENTRY, "status"], cwd: workdir });
216
225
  if (existing.exitCode === 0 && JSON.parse(await existing.stdout()).running) {
217
226
  if (typeof options.resume !== "string")
@@ -241,6 +250,22 @@ export async function launchSandbox(options) {
241
250
  const previous = typeof options.resume === "string"
242
251
  ? readSandboxSession(options.resume)
243
252
  : listSandboxSessions().find((record) => record.project === project.id && record.team === project.accountId && record.sandbox === sandbox?.name);
253
+ let fxWorkspace = previous?.fxWorkspace;
254
+ if (localHarness &&
255
+ options.harness === "fx" &&
256
+ typeof options.resume === "string" &&
257
+ previous?.harness === "fx" &&
258
+ previous.harnessLocation !== "sandbox" &&
259
+ !fxWorkspace) {
260
+ try {
261
+ fxWorkspace = await discoverLegacyFxWorkspace(previous, listSandboxSessions(), (args) => run("fx", args, { timeoutMs: 10000 }));
262
+ }
263
+ catch {
264
+ // Older fx versions may not expose machine-readable session discovery.
265
+ }
266
+ if (!fxWorkspace)
267
+ throw new Error("Cannot identify this older sandbox's fx workspace safely. Use fx sessions --all to locate its conversation before resuming.");
268
+ }
244
269
  const branchResult = await sandbox.runCommand({ cmd: "git", args: ["branch", "--show-current"], cwd: workdir });
245
270
  const now = new Date().toISOString();
246
271
  savedSession = {
@@ -257,32 +282,31 @@ export async function launchSandbox(options) {
257
282
  branch: branchResult.exitCode === 0 ? (await branchResult.stdout()).trim() || undefined : undefined,
258
283
  command: options.command || project.devCommand || undefined,
259
284
  installCommand: options.installCommand,
260
- timeout: options.timeout || "30",
285
+ timeout: String(timeoutMinutes),
261
286
  fx: options.fx !== false,
287
+ gateway: options.gateway !== false,
288
+ gatewayBudget: options.gatewayBudget,
289
+ gatewayBudgetConfigured: true,
262
290
  harness: options.harness,
291
+ harnessLocation: options.harnessLocation || "local",
292
+ fxWorkspace,
263
293
  ownsSandbox: previous?.ownsSandbox ?? !options.attach,
264
294
  createdAt: previous?.createdAt || now,
265
295
  lastUsedAt: now,
266
296
  launcherPid: process.pid
267
297
  };
298
+ if (localHarness && options.harness === "fx")
299
+ savedSession.fxWorkspace = sandboxFxWorkspace(savedSession);
268
300
  saveSandboxSession(savedSession);
269
301
  log("Loading Development environment through Vercel CLI");
270
- const envPath = join(temporary, "development.env");
271
- await run("vercel", [
272
- "env",
273
- "pull",
274
- envPath,
275
- "--project",
276
- project.id,
277
- "--scope",
278
- project.accountId,
279
- "--environment",
280
- "development",
281
- "--yes"
282
- ], { cwd: temporary });
283
- const development = readFileSync(envPath, "utf8");
284
- rmSync(envPath);
285
- const appEnv = Object.fromEntries(Object.entries(parseEnv(development)).filter((entry) => typeof entry[1] === "string"));
302
+ // Use the same resolved Development-env endpoint as `vercel env pull`,
303
+ // keeping the values in memory rather than writing an env file on the laptop.
304
+ const development = JSON.parse(await run("vercel", ["api", `/v3/env/pull/${project.id}/development`, "--scope", project.accountId, "--raw"], {
305
+ cwd: temporary
306
+ }));
307
+ if (!development.env || typeof development.env !== "object")
308
+ throw new Error("Could not load Development environment");
309
+ const appEnv = Object.fromEntries(Object.entries(development.env).filter((entry) => typeof entry[1] === "string"));
286
310
  // A development OIDC token manages infrastructure; it does not belong in app/agent environment.
287
311
  delete appEnv.VERCEL_OIDC_TOKEN;
288
312
  delete appEnv.VERCEL_TOKEN;
@@ -295,21 +319,45 @@ export async function launchSandbox(options) {
295
319
  if (legacyCleanup.exitCode !== 0)
296
320
  throw new Error("Could not remove legacy sandbox harness credentials");
297
321
  const setup = options.installCommand || project.installCommand || "bun install";
298
- log(`Installing project dependencies: ${setup}`);
299
- const installed = await sandbox.runCommand({
300
- cmd: "sh",
301
- args: ["-c", setup],
322
+ const dependencyMarker = `${REMOTE_TOOLS}/dependencies-${createHash("sha256").update(workdir).digest("hex")}.sha256`;
323
+ const dependencySeed = createHash("sha256")
324
+ .update(setup)
325
+ .update(JSON.stringify(Object.entries(appEnv).sort()))
326
+ .digest("hex");
327
+ const setupSandbox = sandbox;
328
+ const dependencyCache = (mode) => setupSandbox.runCommand({
329
+ cmd: "node",
330
+ args: ["-e", dependencyCacheScript, mode, dependencyMarker, dependencySeed],
302
331
  cwd: workdir,
303
- env: appEnv,
304
- timeoutMs: 300000
332
+ signal: shellAbort.signal
305
333
  });
306
- if (installed.exitCode !== 0)
307
- throw new Error(`Project dependency installation failed: ${(await installed.stderr()).slice(-4000)}`);
334
+ const cachedDependencies = await dependencyCache("check");
335
+ if (cachedDependencies.exitCode === 0)
336
+ log("Reusing project dependencies (manifests, lockfiles and install settings unchanged)");
337
+ else {
338
+ log(`Installing project dependencies: ${setup}`);
339
+ const invalidated = await sandbox.runCommand("rm", ["-f", dependencyMarker]);
340
+ if (invalidated.exitCode !== 0)
341
+ throw new Error("Could not invalidate the dependency install marker");
342
+ const installed = await sandbox.runCommand({
343
+ cmd: "sh",
344
+ args: ["-c", setup],
345
+ cwd: workdir,
346
+ env: appEnv,
347
+ timeoutMs: 300000,
348
+ signal: shellAbort.signal
349
+ });
350
+ if (installed.exitCode !== 0)
351
+ throw new Error(`Project dependency installation failed: ${(await installed.stderr()).slice(-4000)}`);
352
+ const recorded = await dependencyCache("save");
353
+ if (recorded.exitCode !== 0)
354
+ throw new Error("Could not record successful dependency setup");
355
+ }
308
356
  if (signalReceived)
309
357
  return;
310
- if (options.fx !== false && options.shell !== false) {
311
- log("Preparing fx; authenticate the harness in the sandbox before use");
312
- await prepareSandboxFx(sandbox);
358
+ if (!localHarness && options.fx !== false && options.shell !== false) {
359
+ log("Preparing fx");
360
+ fxBinary = await prepareSandboxFx(sandbox);
313
361
  }
314
362
  if (signalReceived)
315
363
  return;
@@ -321,105 +369,278 @@ export async function launchSandbox(options) {
321
369
  aliasRegistered = true;
322
370
  const bridgeUrl = `${sandbox.domain(BRIDGE_PORT).replace(/^https:/, "wss:")}/bridge`;
323
371
  const pairingToken = randomBytes(32).toString("hex");
324
- const config = { appUrl, serverPort: APP_PORT, bridgePort: BRIDGE_PORT, token: pairingToken, proxyToken };
372
+ const preview = options.preview
373
+ ? { origin: new URL(upstreamUrl).origin, token: randomBytes(32).toString("hex"), expiresAt }
374
+ : undefined;
375
+ const config = { appUrl, serverPort: APP_PORT, bridgePort: BRIDGE_PORT, token: pairingToken, proxyToken, preview };
325
376
  const args = [REMOTE_ENTRY, "sandbox-serve", "--startup-timeout", "300000"];
326
377
  const command = options.command || project.devCommand;
327
378
  if (command)
328
379
  args.push("--command", command);
329
- log("Starting the remote dev server and browser bridge");
330
- const remote = await sandbox.runCommand({
380
+ const runtimeSandbox = sandbox;
381
+ const runRemote = () => runtimeSandbox.runCommand({
331
382
  cmd: "node",
332
383
  args,
333
384
  cwd: workdir,
334
385
  env: appEnv,
335
386
  stdin: true,
336
- detached: true
387
+ detached: true,
388
+ signal: shellAbort.signal
337
389
  });
390
+ log("Starting the remote dev server and browser bridge");
391
+ let remote = await runRemote();
338
392
  let remoteExit;
339
- void remote
340
- .wait()
341
- .then((result) => {
342
- remoteExit = result.exitCode;
343
- finish();
344
- })
345
- .catch(() => {
346
- remoteExit = -1;
347
- finish();
348
- });
349
- await remote.writeStdin(JSON.stringify(config));
350
- await remote.closeStdin();
351
- remoteStarted = true;
393
+ let workspaceReady = false;
394
+ let generationAbort = new AbortController();
395
+ const monitorRemote = async () => {
396
+ generationAbort.abort();
397
+ generationAbort = new AbortController();
398
+ remoteExit = undefined;
399
+ const current = remote;
400
+ void watchSandboxRuntime({
401
+ status: (signal) => runtimeSandbox.getCommand(current.cmdId, { signal }),
402
+ signal: AbortSignal.any([watchAbort.signal, generationAbort.signal]),
403
+ log,
404
+ onExit: (code) => {
405
+ if (current !== remote)
406
+ return;
407
+ remoteExit = code;
408
+ log(`Remote dev runtime exited (code ${code})`);
409
+ if (workspaceReady)
410
+ log("Keeping your agent and browser open. Use sandbox_recover to restore the dev runtime and bridge; your edits are preserved.");
411
+ else if (shellActive)
412
+ log("Keeping your coding shell open. Exit it and use the resume command to restore the dev server and browser.");
413
+ else
414
+ finish();
415
+ }
416
+ });
417
+ await current.writeStdin(JSON.stringify(config));
418
+ await current.closeStdin();
419
+ remoteStarted = true;
420
+ };
421
+ await monitorRemote();
422
+ const readStatus = async () => {
423
+ const result = await runtimeSandbox.runCommand({
424
+ cmd: "node",
425
+ args: [REMOTE_ENTRY, "status"],
426
+ cwd: workdir,
427
+ timeoutMs: 10000,
428
+ signal: shellAbort.signal
429
+ });
430
+ if (result.exitCode !== 0)
431
+ throw new Error("Could not read remote runtime status");
432
+ return JSON.parse(await result.stdout());
433
+ };
434
+ const waitReady = async () => {
435
+ const deadline = Date.now() + 300000;
436
+ while (!signalReceived && Date.now() < deadline) {
437
+ const state = await readStatus();
438
+ if (state.ready && state.browserConnected)
439
+ return state;
440
+ if (remoteExit !== undefined)
441
+ throw new Error(`Remote runtime exited during startup: ${(await remote.stderr()).slice(-4000)}`);
442
+ await new Promise((resolveWait) => setTimeout(resolveWait, 1500));
443
+ }
444
+ throw new Error(signalReceived ? "Session ended" : "Sandbox runtime did not become ready within five minutes");
445
+ };
446
+ const recover = sandboxRecovery(async () => {
447
+ const state = await readStatus();
448
+ if (state.ready && state.browserConnected)
449
+ return { restarted: false, evidenceGap: false, status: state };
450
+ log("Recovering the dev runtime and browser bridge in the existing sandbox; no clone or install");
451
+ // Stop only our managed runtime; do not kill other builds or agent processes.
452
+ generationAbort.abort();
453
+ if (state.running) {
454
+ const stopped = await runtimeSandbox.runCommand({
455
+ cmd: "node",
456
+ args: [REMOTE_ENTRY, "stop"],
457
+ cwd: workdir,
458
+ timeoutMs: 10000,
459
+ signal: shellAbort.signal
460
+ });
461
+ if (stopped.exitCode !== 0)
462
+ throw new Error("Could not stop the unhealthy dev runtime");
463
+ const deadline = Date.now() + 15000;
464
+ while ((await readStatus()).running) {
465
+ if (Date.now() > deadline)
466
+ throw new Error("Previous dev runtime did not finish stopping");
467
+ await new Promise((resolveWait) => setTimeout(resolveWait, 300));
468
+ }
469
+ }
470
+ if (signalReceived)
471
+ throw new Error("Session ended");
472
+ remote = await runRemote();
473
+ await monitorRemote();
474
+ const status = await waitReady();
475
+ log("Dev runtime and browser bridge recovered. Old in-memory evidence is lost; reread status before testing.");
476
+ return { restarted: true, evidenceGap: true, status };
477
+ }, shellAbort.signal);
352
478
  // The profile key uses remote project identity, never the caller's local cwd.
353
479
  const key = createHash("sha256").update(`${project.accountId}/${project.id}`).digest("hex").slice(0, 20);
354
480
  const directory = join(homedir(), ".d3k", "sandboxes", key);
355
481
  await mkdir(directory, { recursive: true, mode: 0o700 });
356
482
  await writeFile(join(directory, "session.json"), JSON.stringify({ project: project.id, team: project.accountId, name: sandbox.name, appUrl }), { mode: 0o600 });
357
483
  const chromePort = await freePort();
484
+ if (signalReceived)
485
+ return;
358
486
  browser = new CDPMonitor(join(directory, "chrome-profile"), (_source, message) => {
359
487
  if (message.startsWith("[CDP]"))
360
488
  log(message);
361
489
  }, false, isolatedBrowserPath, undefined, undefined, 60000, chromePort, options.headless);
362
490
  browser.requireFilesystemIsolation(await portlessCertificatePin(appUrl));
363
- browser.setOnWindowClosedCallback(onSignal);
491
+ browser.setOnWindowClosedCallback(() => {
492
+ if (!closing && !signalReceived)
493
+ log("Local browser window closed; closing session");
494
+ if (closing)
495
+ return;
496
+ signalReceived = true;
497
+ finish();
498
+ });
364
499
  await browser.start();
365
500
  companion = connectCompanion({
366
501
  url: bridgeUrl,
367
502
  token: pairingToken,
368
503
  chromePort,
504
+ github: (args, signal) => callSandboxGithub(project.link?.type === "github" ? `${project.link.org}/${project.link.repo}` : "", args, {
505
+ cwd: temporary,
506
+ signal
507
+ }),
369
508
  onState: (connected) => {
370
509
  if (!closing && !signalReceived)
371
- log(connected ? "Local Chrome connected" : "Browser disconnected; reconnecting");
510
+ log(connected
511
+ ? "Local Chrome connected"
512
+ : remoteExit === undefined
513
+ ? "Browser disconnected; reconnecting"
514
+ : "Dev runtime is stopped; use sandbox_recover");
372
515
  }
373
516
  });
374
- const deadline = Date.now() + 300000;
375
- let ready = false;
376
- while (!signalReceived && Date.now() < deadline) {
377
- const status = await sandbox.runCommand({ cmd: "node", args: [REMOTE_ENTRY, "status"], cwd: workdir });
378
- if (status.exitCode === 0) {
379
- const state = JSON.parse(await status.stdout());
380
- if (state.ready && state.browserConnected) {
381
- ready = true;
382
- break;
383
- }
384
- }
385
- if (remoteExit !== undefined) {
386
- throw new Error(`Remote runtime exited during startup: ${(await remote.stderr()).slice(-4000)}`);
387
- }
388
- await new Promise((resolveWait) => setTimeout(resolveWait, 1500));
389
- }
517
+ await waitReady();
390
518
  if (signalReceived)
391
519
  return;
392
- if (!ready)
393
- throw new Error("Sandbox runtime did not become ready within five minutes");
520
+ workspaceReady = localHarness || !!lifecycle.onReady;
394
521
  log(`Ready: ${appUrl}`);
395
522
  log(`Sandbox: ${sandbox.name}. Shell directory: ${workdir}`);
523
+ if (lifecycle.onReady) {
524
+ const call = await createLocalSandboxWorkspace({
525
+ directory: join(temporary, "control"),
526
+ sandbox,
527
+ workdir,
528
+ appUrl,
529
+ signal: shellAbort.signal,
530
+ chromePort,
531
+ sessionId: savedSession.id,
532
+ recover,
533
+ repository: project.link?.type === "github" ? `${project.link.org}/${project.link.repo}` : undefined
534
+ });
535
+ if (signalReceived)
536
+ return;
537
+ lifecycle.onReady({
538
+ session: savedSession,
539
+ call,
540
+ ...(preview
541
+ ? { preview: { url: sandboxPreviewLink(preview), expiresAt: new Date(expiresAt).toISOString() } }
542
+ : {})
543
+ });
544
+ }
396
545
  if (options.shell !== false && process.stdin.isTTY) {
546
+ if ((fxBinary || (localHarness && options.harness === "fx")) &&
547
+ options.gateway !== false &&
548
+ (!options.harness || options.harness === "fx")) {
549
+ log(`Connecting fx to the project's team Gateway (${options.gatewayBudget === "none" ? "no session spending cap" : `$${options.gatewayBudget || "5"} session budget`})`);
550
+ try {
551
+ gateway = await createSandboxGateway((binary, args, config) => run(binary, args, { ...config, cwd: temporary, isolated: true, timeoutMs: 10000 }), {
552
+ projectId: project.id,
553
+ teamId: project.accountId,
554
+ sessionId: savedSession.id,
555
+ minutes: timeoutMinutes,
556
+ budget: options.gatewayBudget === "none" ? undefined : Number(options.gatewayBudget || 5)
557
+ });
558
+ if (!localHarness && fxBinary)
559
+ await configureSandboxFxGateway(sandbox, fxBinary, gateway);
560
+ }
561
+ catch {
562
+ throw new Error("Could not configure sandbox Gateway authentication. Check team API-key permissions or use --no-gateway for manual authentication.");
563
+ }
564
+ }
565
+ if (localHarness && options.harness) {
566
+ if (remoteExit !== undefined)
567
+ throw new Error(`Remote runtime exited before the harness opened (code ${remoteExit})`);
568
+ log(`Starting local ${options.harness}; project files and commands stay in ${workdir}`);
569
+ shellActive = true;
570
+ if (options.harness === "eve") {
571
+ log("Eve: remote agent with a local terminal client; up to 30 minutes of model access");
572
+ log("Use /detach, then Enter to reconnect. Ctrl-C at the reconnect prompt exits and stops Eve.");
573
+ await runHarnessProcess("bun", [fileURLToPath(new URL("../../scripts/eve/launch.mjs", import.meta.url)), "--resume", savedSession.id], { cwd: temporary, signal: shellAbort.signal });
574
+ return;
575
+ }
576
+ await launchLocalSandboxHarness({
577
+ harness: options.harness,
578
+ directory: options.harness === "fx" ? sandboxFxWorkspace(savedSession) : join(temporary, "control"),
579
+ resume: typeof options.resume === "string" && previous?.harness === "fx" && previous.harnessLocation !== "sandbox",
580
+ sandbox,
581
+ workdir,
582
+ appUrl,
583
+ signal: shellAbort.signal,
584
+ gateway,
585
+ chromePort,
586
+ sessionId: savedSession.id,
587
+ recover,
588
+ repository: project.link?.type === "github" ? `${project.link.org}/${project.link.repo}` : undefined
589
+ });
590
+ return;
591
+ }
397
592
  const path = await sandbox.runCommand({ cmd: "printenv", args: ["PATH"] });
398
593
  if (path.exitCode !== 0)
399
594
  throw new Error("Could not resolve remote shell PATH");
400
595
  const contextDirectory = `${REMOTE_TOOLS}/harness-context`;
401
596
  const skillPath = `${contextDirectory}/.fx/skills/d3k/SKILL.md`;
402
- if (options.harness) {
597
+ const harnessContext = { workdir, appUrl };
598
+ if (options.harness || fxBinary) {
403
599
  const prepared = await sandbox.runCommand({ cmd: "mkdir", args: ["-p", `${contextDirectory}/.fx/skills/d3k`] });
404
600
  if (prepared.exitCode !== 0)
405
601
  throw new Error("Could not prepare harness skill context");
406
- await sandbox.writeFiles([{ path: skillPath, content: Buffer.from(harnessSkill()) }]);
602
+ await sandbox.writeFiles([{ path: skillPath, content: Buffer.from(harnessSkill(harnessContext)) }]);
603
+ }
604
+ if (fxBinary && (!options.harness || options.harness === "fx")) {
605
+ await sandboxFxContext(sandbox, harnessContext);
606
+ fxContextInstalled = true;
607
+ }
608
+ const invocation = options.harness
609
+ ? harnessInvocation(options.harness, skillPath, contextDirectory, harnessContext, typeof options.resume === "string" && previous?.harness === "fx" && previous.harnessLocation === "sandbox")
610
+ : undefined;
611
+ if (remoteExit !== undefined)
612
+ throw new Error(`Remote runtime exited before the shell opened (code ${remoteExit})`);
613
+ shellActive = true;
614
+ try {
615
+ const exitCode = await runSandboxShell({
616
+ sandbox,
617
+ cwd: workdir,
618
+ execution: invocation
619
+ ? [options.harness === "fx" && fxBinary ? `${SANDBOX_AGENT_BIN}/fx` : invocation.binary, ...invocation.args]
620
+ : ["/bin/bash", "--noprofile", "--norc", "-i"],
621
+ env: {
622
+ PATH: `${options.fx !== false ? `${SANDBOX_AGENT_BIN}:` : ""}${REMOTE_TOOLS}/node_modules/.bin:${(await path.stdout()).trim()}`
623
+ },
624
+ signal: shellAbort.signal
625
+ });
626
+ if (exitCode !== undefined) {
627
+ log(`Remote ${options.harness || "shell"} exited (code ${exitCode})`);
628
+ if (exitCode !== 0)
629
+ throw new Error(`Remote ${options.harness || "shell"} exited (code ${exitCode})`);
630
+ }
631
+ }
632
+ catch (error) {
633
+ if (signalReceived)
634
+ return;
635
+ if (!(error instanceof SandboxShellDisconnected))
636
+ throw error;
637
+ log(error.message);
638
+ log("The terminal disconnected; keeping the sandbox and browser running. No agent command was replayed.");
639
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
640
+ log(`Reconnect from another terminal: vercel sandbox connect ${quote(sandbox.name)} --project ${quote(project.id)} --scope ${quote(project.accountId)} --workdir ${quote(workdir)}`);
641
+ log(`Your saved session is ${savedSession.id}. Press Ctrl+C here when you want to close it.`);
642
+ await ended;
407
643
  }
408
- const invocation = options.harness ? harnessInvocation(options.harness, skillPath, contextDirectory) : undefined;
409
- await run("vercel", [
410
- "sandbox",
411
- invocation ? "exec" : "connect",
412
- sandbox.name,
413
- "--project",
414
- project.id,
415
- "--scope",
416
- project.accountId,
417
- "--workdir",
418
- workdir,
419
- "--env",
420
- `PATH=${options.fx !== false ? `${SANDBOX_AGENT_BIN}:` : ""}${REMOTE_TOOLS}/node_modules/.bin:${(await path.stdout()).trim()}`,
421
- ...(invocation ? ["--interactive", "--", invocation.binary, ...invocation.args] : [])
422
- ], { inherit: true, env: { ...process.env, VERCEL_OIDC_TOKEN: token }, signal: shellAbort.signal });
423
644
  }
424
645
  else {
425
646
  log(options.attach
@@ -431,51 +652,67 @@ export async function launchSandbox(options) {
431
652
  }
432
653
  }
433
654
  finally {
434
- if (!closing) {
435
- closing = true;
436
- companion?.close();
437
- if (aliasRegistered && localRoute) {
655
+ const releaseTerminal = lifecycle.onReady ? () => { } : holdTerminalForCleanup();
656
+ try {
657
+ lifecycle.onClosing?.();
658
+ watchAbort.abort();
659
+ if (!closing) {
660
+ closing = true;
661
+ signalReceived = true;
662
+ browser?.prepareShutdown();
663
+ companion?.close();
664
+ log("Closing session…");
665
+ if (gateway)
666
+ log(`Session Gateway key expires at ${new Date(gateway.expiresAt).toLocaleString(undefined, { timeZoneName: "short" })}`);
667
+ if (aliasRegistered && localRoute) {
668
+ try {
669
+ removePortlessAlias(localRoute);
670
+ }
671
+ catch {
672
+ log("Could not remove the local proxy route");
673
+ }
674
+ }
675
+ await closeSandboxResources({
676
+ closeProxy: localProxy?.close.bind(localProxy),
677
+ closeBrowser: browser?.shutdown.bind(browser),
678
+ sandbox,
679
+ ownsSandbox: !options.attach || (typeof options.resume === "string" && savedSession?.ownsSandbox === true),
680
+ fxContextInstalled,
681
+ remoteStarted,
682
+ remoteWorkdir,
683
+ originalPorts,
684
+ log
685
+ });
686
+ }
687
+ rmSync(temporary, { recursive: true, force: true });
688
+ if (savedSession) {
689
+ savedSession.closedAt = new Date().toISOString();
690
+ delete savedSession.launcherPid;
438
691
  try {
439
- removePortlessAlias(localRoute);
692
+ saveSandboxSession(savedSession);
440
693
  }
441
694
  catch {
442
- log("Could not remove the local proxy route");
695
+ log("Could not update saved session metadata");
443
696
  }
444
697
  }
445
- await localProxy?.close();
446
- await browser?.shutdown().catch(() => { });
447
- if (sandbox) {
448
- if (options.harness)
449
- await sandbox.runCommand({ cmd: "rm", args: ["-rf", `${REMOTE_TOOLS}/harness-context`] }).catch(() => { });
450
- if (remoteStarted)
451
- await sandbox
452
- .runCommand({ cmd: "node", args: [REMOTE_ENTRY, "stop"], cwd: remoteWorkdir, timeoutMs: 10000 })
453
- .catch(() => { });
454
- // An attached sandbox belongs to its existing owner. Only stop sandboxes created by this invocation.
455
- if (!options.attach || (typeof options.resume === "string" && savedSession?.ownsSandbox))
456
- await sandbox
457
- .stop()
458
- .catch(() => log(`Could not stop sandbox ${sandbox?.name}; stop it with vercel sandbox stop`));
459
- else if (originalPorts)
460
- await sandbox.update({ ports: originalPorts }).catch(() => log("Could not restore attached sandbox ports"));
461
- }
698
+ if (remoteStarted)
699
+ log("Session closed");
462
700
  }
463
- process.off("SIGINT", onSignal);
464
- process.off("SIGTERM", onSignal);
465
- rmSync(temporary, { recursive: true, force: true });
466
- if (savedSession) {
467
- savedSession.closedAt = new Date().toISOString();
468
- delete savedSession.launcherPid;
701
+ finally {
469
702
  try {
470
- saveSandboxSession(savedSession);
703
+ const resume = savedSession ? `Resume this sandbox: d3k --resume ${savedSession.id}` : undefined;
704
+ // Keep signal handlers through restoration and output flushing. A late Ctrl-C
705
+ // must not interrupt the final line. MCP stdout belongs exclusively to JSON-RPC.
706
+ await finishTerminalCleanup(releaseTerminal, lifecycle.onReady ? undefined : resume);
707
+ if (lifecycle.onReady && resume)
708
+ log(resume);
471
709
  }
472
- catch {
473
- log("Could not update saved session metadata");
710
+ finally {
711
+ process.off("SIGINT", onSignal);
712
+ process.off("SIGTERM", onSignal);
713
+ lifecycle.signal?.removeEventListener("abort", onAbort);
474
714
  }
475
- console.log(`Resume this sandbox: d3k --resume ${savedSession.id}`);
476
715
  }
477
- if (remoteStarted)
478
- log("Session closed");
479
716
  }
480
717
  }
481
718
  //# sourceMappingURL=sandbox.js.map