@paperclipai/plugin-daytona 2026.1012.0 → 2026.1012.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { Daytona, DaytonaNotFoundError, DaytonaTimeoutError } from "@daytonaio/sdk";
4
- import { decodeChannelBytes, definePlugin, NOOP_PLUGIN_TRACER, PluginEnvironmentCreationCleanupError, readEnvironmentCreationCleanupError } from "@paperclipai/plugin-sdk";
4
+ import { decodeChannelBytes, definePlugin, NOOP_PLUGIN_TRACER, PluginEnvironmentCreationCleanupError, readEnvironmentCreationCleanupError, withEnvironmentSyncTransferStep, preserveEnvironmentSyncErrorDiagnostic } from "@paperclipai/plugin-sdk";
5
5
  import { performSyncIn, performSyncOut, withProviderSpan } from "./file-sync.js";
6
6
  import { DEFAULT_DAYTONA_OPERATION_TIMEOUT_MS } from "./manifest.js";
7
7
  // The Claude `setup-token` login pseudo-terminal (PTY) session for this provider.
@@ -29,6 +29,10 @@ let timingNow = () => Date.now();
29
29
  // read the tracer through `getPluginTracer()`. Before `setup` runs (or in a
30
30
  // test) the tracer is a no-op, so a span never throws.
31
31
  let pluginContext = null;
32
+ // Provider deadlines and terminal close failures do not prove remote work
33
+ // stopped. Until those paths provide complete cleanup receipts, only a worker
34
+ // which has never contacted the provider can opt into automatic idle sleep.
35
+ let providerUsed = false;
32
36
  /**
33
37
  * Return the plugin tracer. It is the injected `ctx.tracer` after `setup`, or a
34
38
  * no-op before it. A provider span opened through it records only when tracing
@@ -174,6 +178,7 @@ function resolveApiKey(config) {
174
178
  return envApiKey;
175
179
  }
176
180
  function createDaytonaClient(config) {
181
+ providerUsed = true;
177
182
  const clientConfig = {
178
183
  apiKey: resolveApiKey(config),
179
184
  };
@@ -735,6 +740,8 @@ async function createSandbox(params, config, options = {}) {
735
740
  });
736
741
  }
737
742
  catch (createError) {
743
+ // Observe the create failure before compensating deletion can stall or fail.
744
+ const diagnostic = options.onCreateFailure?.();
738
745
  try {
739
746
  // A not-found lookup after an uncertain create is not a deletion receipt:
740
747
  // the provider may still materialize the request. Keep the name in the
@@ -742,7 +749,7 @@ async function createSandbox(params, config, options = {}) {
742
749
  await destroyFailedCreation(config, cleanup);
743
750
  }
744
751
  catch (cleanupError) {
745
- throw new PluginEnvironmentCreationCleanupError([createError, cleanupError], `Daytona sandbox creation failed; cleanup could not be confirmed for ${name}`, cleanup);
752
+ throw new PluginEnvironmentCreationCleanupError([createError, cleanupError], `Daytona sandbox creation failed; cleanup could not be confirmed for ${name}`, cleanup, diagnostic);
746
753
  }
747
754
  throw createError;
748
755
  }
@@ -786,6 +793,25 @@ async function destroyFailedCreation(config, cleanup, requireDurableObservation
786
793
  }
787
794
  await withLivenessTimeout("sandbox.failedCreateDelete", 15_000, () => orphan.delete(10, true));
788
795
  }
796
+ // Daytona states reported as-is after a create deadline; any other is `other`.
797
+ const REPORTED_CREATE_STATES = new Set([
798
+ "creating", "pending_build", "building_snapshot", "pulling_snapshot", "starting", "started", "error", "build_failed",
799
+ ]);
800
+ // One read-only lookup of the provisional creation name, so a create deadline
801
+ // records where the provider left the allocation. It neither deletes nor
802
+ // records an observed ID: the host-owned cleanup envelope is unchanged.
803
+ async function observeCreateState(config, cleanup) {
804
+ try {
805
+ const sandbox = await withLivenessTimeout("sandbox.createStateLookup", 5_000, () => createDaytonaClient(config).get(cleanup.providerLeaseId));
806
+ if (!sandbox || sandbox.name !== cleanup.providerLeaseId || typeof sandbox.state !== "string" ||
807
+ Object.entries(cleanup.labels).some(([key, value]) => sandbox.labels?.[key] !== value))
808
+ return "unavailable";
809
+ return REPORTED_CREATE_STATES.has(sandbox.state) ? sandbox.state : "other";
810
+ }
811
+ catch (error) {
812
+ return error instanceof DaytonaNotFoundError ? "absent" : "unavailable";
813
+ }
814
+ }
789
815
  // Non-secret provider/account fingerprint. Uses the *resolved* key (config or
790
816
  // DAYTONA_API_KEY env fallback) so an env-provided credential is still scoped,
791
817
  // but only its sha256 digest — never the key itself — enters the cache key (C1/C6).
@@ -1204,6 +1230,7 @@ const sandboxHandleSessionStore = (() => {
1204
1230
  * Not used in production.
1205
1231
  */
1206
1232
  export function __resetDaytonaSandboxHandleCacheForTest() {
1233
+ providerUsed = false;
1207
1234
  sandboxHandleCache.reset();
1208
1235
  sandboxHandleTeardownGates.reset();
1209
1236
  sandboxHandleActivityGates.reset();
@@ -1505,6 +1532,56 @@ class SessionCommandDeadlineError extends Error {
1505
1532
  }
1506
1533
  class SessionObservationTimeoutError extends Error {
1507
1534
  }
1535
+ function createCommandDeadline(timeoutMs) {
1536
+ if (timeoutMs === undefined || timeoutMs === 0)
1537
+ return undefined;
1538
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) {
1539
+ throw new Error("Invalid session command timeout");
1540
+ }
1541
+ let expired = false;
1542
+ const dueAt = Date.now() + timeoutMs;
1543
+ const controller = new AbortController();
1544
+ const timer = setTimeout(() => {
1545
+ expired = true;
1546
+ controller.abort();
1547
+ }, timeoutMs);
1548
+ return {
1549
+ expired: () => expired,
1550
+ remainingMs: () => Math.max(0, dueAt - Date.now()),
1551
+ race: async (action) => {
1552
+ if (expired)
1553
+ throw new SessionCommandDeadlineError();
1554
+ let rejectDeadline;
1555
+ const deadline = new Promise((_resolve, reject) => { rejectDeadline = reject; });
1556
+ const onAbort = () => rejectDeadline(new SessionCommandDeadlineError());
1557
+ controller.signal.addEventListener("abort", onAbort, { once: true });
1558
+ try {
1559
+ return await Promise.race([action(), deadline]);
1560
+ }
1561
+ finally {
1562
+ // Retain only active observations. A shared pending promise would keep
1563
+ // every finished poll and its result until a long command ends.
1564
+ controller.signal.removeEventListener("abort", onAbort);
1565
+ }
1566
+ },
1567
+ clear: () => clearTimeout(timer),
1568
+ };
1569
+ }
1570
+ function withinCommandDeadline(deadline, action) {
1571
+ return deadline ? deadline.race(action) : action();
1572
+ }
1573
+ async function sleepWithinCommandDeadline(deadline, delayMs) {
1574
+ if (!deadline)
1575
+ return await sleep(delayMs);
1576
+ let timer;
1577
+ try {
1578
+ await deadline.race(() => new Promise((resolve) => { timer = setTimeout(resolve, delayMs); }));
1579
+ }
1580
+ finally {
1581
+ if (timer !== undefined)
1582
+ clearTimeout(timer);
1583
+ }
1584
+ }
1508
1585
  async function beforeSessionDeadline(deadlineMs, action) {
1509
1586
  const remainingMs = deadlineMs - Date.now();
1510
1587
  if (remainingMs <= 0)
@@ -1523,13 +1600,20 @@ async function beforeSessionDeadline(deadlineMs, action) {
1523
1600
  clearTimeout(timer);
1524
1601
  }
1525
1602
  }
1526
- // A provider operation timeout bounds one observation, not a healthy stream's
1527
- // lifetime. The caller's RPC/run guard and session teardown own that lifetime.
1528
- async function observeSessionCommand(timeoutMs, action) {
1603
+ // A provider operation timeout bounds one observation. An explicit command
1604
+ // deadline also bounds the stream; existing callers retain their run/Stop guard.
1605
+ async function observeSessionCommand(timeoutMs, action, commandDeadline) {
1529
1606
  try {
1607
+ // Use the earlier shared command timer instead of leaving a longer
1608
+ // observation timer alive after the command has already settled.
1609
+ if (commandDeadline && commandDeadline.remainingMs() <= timeoutMs) {
1610
+ return await commandDeadline.race(action);
1611
+ }
1530
1612
  return await beforeSessionDeadline(Date.now() + timeoutMs, action);
1531
1613
  }
1532
1614
  catch (error) {
1615
+ if (commandDeadline?.expired())
1616
+ throw new SessionCommandDeadlineError();
1533
1617
  if (error instanceof SessionCommandDeadlineError || error instanceof DaytonaTimeoutError) {
1534
1618
  throw new SessionObservationTimeoutError();
1535
1619
  }
@@ -1540,7 +1624,7 @@ async function observeSessionCommand(timeoutMs, action) {
1540
1624
  // The stream buffer drops a replayed prefix by byte offset on a reconnect.
1541
1625
  // Rejected streams and clean closes use bounded reconnects, then polling.
1542
1626
  // An idle socket goes directly to polling, including one that never settles.
1543
- async function runSessionLogStream(sandbox, sessionId, commandId, timeoutMs, buffer) {
1627
+ async function runSessionLogStream(sandbox, sessionId, commandId, timeoutMs, buffer, commandDeadline) {
1544
1628
  let reconnects = 0;
1545
1629
  let pollUntilExit = false;
1546
1630
  while (true) {
@@ -1554,7 +1638,7 @@ async function runSessionLogStream(sandbox, sessionId, commandId, timeoutMs, buf
1554
1638
  idleTimer = setTimeout(signalIdle, SESSION_LOG_STREAM_IDLE_MS);
1555
1639
  };
1556
1640
  const receive = (stream, chunk) => {
1557
- if (!acceptingOutput || !chunk)
1641
+ if (!acceptingOutput || commandDeadline?.expired() || !chunk)
1558
1642
  return;
1559
1643
  armIdleTimer();
1560
1644
  if (stream === "stdout")
@@ -1564,10 +1648,10 @@ async function runSessionLogStream(sandbox, sessionId, commandId, timeoutMs, buf
1564
1648
  };
1565
1649
  try {
1566
1650
  armIdleTimer();
1567
- const outcome = await Promise.race([
1651
+ const outcome = await withinCommandDeadline(commandDeadline, () => Promise.race([
1568
1652
  sandbox.process.getSessionCommandLogs(sessionId, commandId, (chunk) => receive("stdout", chunk), (chunk) => receive("stderr", chunk)).then(() => "closed"),
1569
1653
  idle,
1570
- ]);
1654
+ ]));
1571
1655
  if (outcome === "idle") {
1572
1656
  // Do not wait for the abandoned socket or open another one. The SDK
1573
1657
  // exposes no cancellation handle. Fence its callbacks before the
@@ -1577,7 +1661,9 @@ async function runSessionLogStream(sandbox, sessionId, commandId, timeoutMs, buf
1577
1661
  streamClosed = true;
1578
1662
  pollUntilExit = true;
1579
1663
  }
1580
- catch {
1664
+ catch (error) {
1665
+ if (error instanceof SessionCommandDeadlineError)
1666
+ throw error;
1581
1667
  // The command can still be running after a log transport failure.
1582
1668
  }
1583
1669
  finally {
@@ -1587,7 +1673,7 @@ async function runSessionLogStream(sandbox, sessionId, commandId, timeoutMs, buf
1587
1673
  clearTimeout(idleTimer);
1588
1674
  }
1589
1675
  if (streamClosed) {
1590
- const exitCode = await readSessionExitCode(sandbox, sessionId, commandId, timeoutMs);
1676
+ const exitCode = await readSessionExitCode(sandbox, sessionId, commandId, timeoutMs, commandDeadline);
1591
1677
  if (exitCode !== null)
1592
1678
  return { exitCode, pollUntilExit, buffer };
1593
1679
  }
@@ -1602,14 +1688,14 @@ async function runSessionLogStream(sandbox, sessionId, commandId, timeoutMs, buf
1602
1688
  // available within one poll, so the first read almost always holds it. Add a
1603
1689
  // small bounded retry with backoff only for the rare case where the first read
1604
1690
  // has no code yet. Return null when no read holds a numeric code.
1605
- async function readSessionExitCode(sandbox, sessionId, commandId, timeoutMs) {
1606
- const first = await observeSessionCommand(timeoutMs, () => sandbox.process.getSessionCommand(sessionId, commandId));
1691
+ async function readSessionExitCode(sandbox, sessionId, commandId, timeoutMs, commandDeadline) {
1692
+ const first = await observeSessionCommand(timeoutMs, () => sandbox.process.getSessionCommand(sessionId, commandId), commandDeadline);
1607
1693
  if (typeof first.exitCode === "number") {
1608
1694
  return first.exitCode;
1609
1695
  }
1610
1696
  for (const delayMs of SESSION_EXIT_CODE_RETRY_DELAYS_MS) {
1611
- await sleep(delayMs);
1612
- const status = await observeSessionCommand(timeoutMs, () => sandbox.process.getSessionCommand(sessionId, commandId));
1697
+ await sleepWithinCommandDeadline(commandDeadline, delayMs);
1698
+ const status = await observeSessionCommand(timeoutMs, () => sandbox.process.getSessionCommand(sessionId, commandId), commandDeadline);
1613
1699
  if (typeof status.exitCode === "number") {
1614
1700
  return status.exitCode;
1615
1701
  }
@@ -1645,6 +1731,7 @@ async function executeInSession(sandbox, sessionId, params, config) {
1645
1731
  // attributed to the provider boundary.
1646
1732
  let execStart = null;
1647
1733
  let confirmedExitCode = null;
1734
+ let commandDeadline;
1648
1735
  const streamBuffer = createSessionStreamBuffer((stream, text) => pluginContext?.execution.log(stream, text));
1649
1736
  try {
1650
1737
  if (stdinPath) {
@@ -1661,7 +1748,8 @@ async function executeInSession(sandbox, sessionId, params, config) {
1661
1748
  // subshell, not the persistent session shell.
1662
1749
  const command = `( ${loginScript} )`;
1663
1750
  execStart = timingNow();
1664
- const dispatched = await sandbox.process.executeSessionCommand(sessionId, { command, runAsync: true }, timeoutSeconds);
1751
+ commandDeadline = createCommandDeadline(params.commandTimeoutMs);
1752
+ const dispatched = await withinCommandDeadline(commandDeadline, () => sandbox.process.executeSessionCommand(sessionId, { command, runAsync: true }, timeoutSeconds));
1665
1753
  const commandId = dispatched.cmdId;
1666
1754
  // Log-stream path. A session command always tries the stream first: it
1667
1755
  // streams stdout and stderr from the callback log form, then reads the exit
@@ -1672,12 +1760,12 @@ async function executeInSession(sandbox, sessionId, params, config) {
1672
1760
  // call. The host routes it to the runner log sink by the host-issued
1673
1761
  // invocation id. This is a no-op when no plugin context is set (a direct
1674
1762
  // test call) or when the host has no active execute route.
1675
- const streamResult = await runSessionLogStream(sandbox, sessionId, commandId, effectiveTimeoutMs, streamBuffer);
1763
+ const streamResult = await runSessionLogStream(sandbox, sessionId, commandId, effectiveTimeoutMs, streamBuffer, commandDeadline);
1676
1764
  if (streamResult.exitCode !== null) {
1677
1765
  confirmedExitCode = streamResult.exitCode;
1678
1766
  // A log socket can close before the process emits its final bytes. Even
1679
1767
  // a now-visible exit code does not prove the streamed prefix is complete.
1680
- const logs = await observeSessionCommand(effectiveTimeoutMs, () => sandbox.process.getSessionCommandLogs(sessionId, commandId));
1768
+ const logs = await observeSessionCommand(effectiveTimeoutMs, () => sandbox.process.getSessionCommandLogs(sessionId, commandId), commandDeadline);
1681
1769
  streamBuffer.resetConnectionCursors();
1682
1770
  streamBuffer.onStdout(logs?.stdout ?? "");
1683
1771
  streamBuffer.onStderr(logs?.stderr ?? "");
@@ -1702,8 +1790,8 @@ async function executeInSession(sandbox, sessionId, params, config) {
1702
1790
  const observe = async (action) => {
1703
1791
  try {
1704
1792
  return await (streamResult.pollUntilExit
1705
- ? observeSessionCommand(effectiveTimeoutMs, action)
1706
- : beforeSessionDeadline(deadlineMs, action));
1793
+ ? observeSessionCommand(effectiveTimeoutMs, action, commandDeadline)
1794
+ : commandDeadline ? commandDeadline.race(action) : beforeSessionDeadline(deadlineMs, action));
1707
1795
  }
1708
1796
  catch (error) {
1709
1797
  if (error instanceof DaytonaTimeoutError)
@@ -1733,12 +1821,13 @@ async function executeInSession(sandbox, sessionId, params, config) {
1733
1821
  // Full log snapshots are heavier than a status read. Limit fallback
1734
1822
  // traffic to one snapshot per second. Failed-stream fallback retains
1735
1823
  // its original deadline, including the time spent waiting between reads.
1736
- await sleep(streamResult.pollUntilExit ? SESSION_LOG_POLL_INTERVAL_MS
1824
+ await sleepWithinCommandDeadline(commandDeadline, streamResult.pollUntilExit ? SESSION_LOG_POLL_INTERVAL_MS
1737
1825
  : Math.max(0, Math.min(SESSION_LOG_POLL_INTERVAL_MS, deadlineMs - Date.now())));
1738
1826
  }
1739
1827
  }
1740
1828
  catch (error) {
1741
- if (error instanceof SessionObservationTimeoutError) {
1829
+ if (error instanceof SessionObservationTimeoutError ||
1830
+ (error instanceof SessionCommandDeadlineError && confirmedExitCode !== null)) {
1742
1831
  // Preserve undecided decoder suffixes in the partial result, without
1743
1832
  // injecting a possibly incomplete character into the live protocol.
1744
1833
  streamBuffer.finish(false);
@@ -1746,7 +1835,7 @@ async function executeInSession(sandbox, sessionId, params, config) {
1746
1835
  exitCode: null,
1747
1836
  timedOut: true,
1748
1837
  stdout: streamBuffer.stdout,
1749
- stderr: `${streamBuffer.stderr}Session log observation timed out after ${Math.round(effectiveTimeoutMs / 1000)} s; ${confirmedExitCode === null ? "command exit remains unconfirmed" : "final output may be incomplete"}.\n`,
1838
+ stderr: `${streamBuffer.stderr}Session log observation timed out after ${Math.round((commandDeadline?.expired() ? params.commandTimeoutMs : effectiveTimeoutMs) / 1000)} s; ${confirmedExitCode === null ? "command exit remains unconfirmed" : "final output may be incomplete"}.\n`,
1750
1839
  metadata: {
1751
1840
  ...(execStart != null ? { durationMs: timingNow() - execStart } : {}),
1752
1841
  timeoutScope: "session_log_observation",
@@ -1760,7 +1849,7 @@ async function executeInSession(sandbox, sessionId, params, config) {
1760
1849
  const timeoutMessage = gitNet
1761
1850
  ? `Git network operation timed out after ${Math.round(effectiveTimeoutMs / 1000)} s — the remote may be unreachable or noninteractive credentials are not configured.`
1762
1851
  : error instanceof SessionCommandDeadlineError
1763
- ? `Command timed out after ${Math.round(effectiveTimeoutMs / 1000)} s.`
1852
+ ? `Command timed out after ${Math.round((commandDeadline?.expired() ? params.commandTimeoutMs : effectiveTimeoutMs) / 1000)} s.`
1764
1853
  : error.message.trim();
1765
1854
  const durationMs = execStart != null ? timingNow() - execStart : undefined;
1766
1855
  return {
@@ -1774,6 +1863,7 @@ async function executeInSession(sandbox, sessionId, params, config) {
1774
1863
  throw error;
1775
1864
  }
1776
1865
  finally {
1866
+ commandDeadline?.clear();
1777
1867
  if (stdinPath) {
1778
1868
  await sandbox.fs.deleteFile(stdinPath).catch(() => undefined);
1779
1869
  }
@@ -1812,6 +1902,10 @@ const plugin = definePlugin({
1812
1902
  async onHealth() {
1813
1903
  return { status: "ok", message: "Daytona sandbox provider plugin healthy" };
1814
1904
  },
1905
+ async onIdleDrain() {
1906
+ return providerUsed || daytonaLoginPtyByRoute.size > 0 || daytonaDuplexChannelByRoute.size > 0
1907
+ ? "present" : "none";
1908
+ },
1815
1909
  async onEnvironmentValidateConfig(params) {
1816
1910
  const config = parseDriverConfig(params.config);
1817
1911
  const errors = [];
@@ -1917,24 +2011,48 @@ const plugin = definePlugin({
1917
2011
  // One budget covers creation, setup, and inline cleanup. The host leaves
1918
2012
  // 30 seconds beyond this deadline to receive/journal the cleanup record.
1919
2013
  const budgetMs = config.timeoutMs > 0 ? config.timeoutMs : DEFAULT_DAYTONA_OPERATION_TIMEOUT_MS;
1920
- const deadline = Date.now() + budgetMs;
2014
+ const startedAt = Date.now();
2015
+ const deadline = startedAt + budgetMs;
1921
2016
  let expired = false;
1922
2017
  let phase = "create";
2018
+ let cleanupInProgress = false;
2019
+ let firstFailure;
2020
+ const observeFailure = () => {
2021
+ // Cleanup may consume the rest of the budget. Keep the original failed
2022
+ // step and time, rather than attributing that failure to its cleanup.
2023
+ return firstFailure ??= {
2024
+ phase,
2025
+ elapsedMs: Math.max(0, Math.min(604_800_000, Date.now() - startedAt)),
2026
+ budgetMs,
2027
+ };
2028
+ };
1923
2029
  let cleanup;
1924
2030
  const timeoutFailure = () => {
2031
+ const diagnostic = observeFailure();
1925
2032
  expired = true;
1926
- const cause = new Error(`Daytona lease acquisition exceeded ${budgetMs} ms during ${phase}`);
2033
+ const cause = new Error(`Daytona lease acquisition exceeded ${budgetMs} ms during ${cleanupInProgress ? "cleanup" : phase}`);
1927
2034
  return cleanup
1928
- ? new PluginEnvironmentCreationCleanupError([cause], "Daytona lease acquisition timed out; allocation cleanup is pending", { ...cleanup, labels: { ...cleanup.labels } })
2035
+ ? new PluginEnvironmentCreationCleanupError([cause], "Daytona lease acquisition timed out; allocation cleanup is pending", { ...cleanup, labels: { ...cleanup.labels } }, diagnostic)
1929
2036
  : cause;
1930
2037
  };
1931
2038
  const assertActive = () => {
1932
2039
  if (expired || Date.now() >= deadline)
1933
2040
  throw timeoutFailure();
1934
2041
  };
2042
+ const deadlineFailure = async () => {
2043
+ // Only a create that has neither resolved nor rejected is still pending.
2044
+ const createPending = phase === "create" && firstFailure === undefined ? cleanup : undefined;
2045
+ const diagnostic = observeFailure();
2046
+ // Stop late setup before the lookup, so a late create cannot be admitted.
2047
+ expired = true;
2048
+ if (createPending)
2049
+ diagnostic.providerState = await observeCreateState(config, createPending);
2050
+ return timeoutFailure();
2051
+ };
1935
2052
  const acquire = async () => {
1936
2053
  const sandbox = await createSandbox(params, config, {
1937
2054
  onCreateAttempt: (attempt) => { cleanup = attempt; },
2055
+ onCreateFailure: observeFailure,
1938
2056
  });
1939
2057
  try {
1940
2058
  assertActive();
@@ -1996,16 +2114,17 @@ const plugin = definePlugin({
1996
2114
  };
1997
2115
  }
1998
2116
  catch (error) {
2117
+ const diagnostic = observeFailure();
1999
2118
  // After timeout the host owns the durable cleanup record. A late SDK
2000
2119
  // completion must not admit this lease or start another setup phase.
2001
2120
  if (!expired) {
2002
- phase = "cleanup";
2121
+ cleanupInProgress = true;
2003
2122
  try {
2004
2123
  await sandbox.delete(toTimeoutSeconds(Math.max(1, deadline - Date.now())));
2005
2124
  }
2006
2125
  catch (cleanupError) {
2007
2126
  if (cleanup) {
2008
- throw new PluginEnvironmentCreationCleanupError([error, cleanupError], "Daytona lease setup failed; allocation cleanup is pending", { ...cleanup, labels: { ...cleanup.labels } });
2127
+ throw new PluginEnvironmentCreationCleanupError([error, cleanupError], "Daytona lease setup failed; allocation cleanup is pending", { ...cleanup, labels: { ...cleanup.labels } }, diagnostic);
2009
2128
  }
2010
2129
  throw error;
2011
2130
  }
@@ -2014,11 +2133,14 @@ const plugin = definePlugin({
2014
2133
  }
2015
2134
  };
2016
2135
  let timer;
2136
+ let timedOut = false;
2017
2137
  try {
2018
2138
  return await Promise.race([
2019
- acquire(),
2139
+ // After the deadline only the timer settles the call: a late create
2140
+ // rejection cannot replace the timeout's ownership and observation.
2141
+ acquire().catch((error) => timedOut ? new Promise(() => undefined) : Promise.reject(error)),
2020
2142
  new Promise((_resolve, reject) => {
2021
- timer = setTimeout(() => reject(timeoutFailure()), budgetMs);
2143
+ timer = setTimeout(() => { timedOut = true; void deadlineFailure().then(reject); }, budgetMs);
2022
2144
  }),
2023
2145
  ]);
2024
2146
  }
@@ -2718,8 +2840,11 @@ const plugin = definePlugin({
2718
2840
  };
2719
2841
  try {
2720
2842
  return await withSandboxActivityGate(scope, async () => {
2721
- const sandbox = await getSandbox(scope, { bypassTeardownGate: true });
2722
- await ensureSandboxStarted(sandbox, timeoutSeconds);
2843
+ const sandbox = await withEnvironmentSyncTransferStep("sandbox_access", async () => {
2844
+ const resolved = await getSandbox(scope, { bypassTeardownGate: true });
2845
+ await ensureSandboxStarted(resolved, timeoutSeconds);
2846
+ return resolved;
2847
+ });
2723
2848
  const result = await performSyncOut({
2724
2849
  sandbox,
2725
2850
  operations: params.operations,
@@ -2736,7 +2861,7 @@ const plugin = definePlugin({
2736
2861
  // unexported workspace bytes no longer exist. Convert the SDK class to a
2737
2862
  // stable cross-worker message; every other error remains retryable.
2738
2863
  if (error instanceof DaytonaNotFoundError) {
2739
- throw new Error("daytona_sandbox_not_found");
2864
+ throw preserveEnvironmentSyncErrorDiagnostic(new Error("daytona_sandbox_not_found"), error);
2740
2865
  }
2741
2866
  throw error;
2742
2867
  }