dev3000 0.0.189 → 0.0.192

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