@microvac/plugin-daytona 0.0.0-stage → 0.1.0-rc.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -2
- package/dist/archive-stream-window.test.d.ts +2 -0
- package/dist/archive-stream-window.test.d.ts.map +1 -0
- package/dist/archive-stream-window.test.js +93 -0
- package/dist/archive-stream-window.test.js.map +1 -0
- package/dist/archive-stream.d.ts +10 -0
- package/dist/archive-stream.d.ts.map +1 -0
- package/dist/archive-stream.js +159 -0
- package/dist/archive-stream.js.map +1 -0
- package/dist/archive-stream.test.d.ts +2 -0
- package/dist/archive-stream.test.d.ts.map +1 -0
- package/dist/archive-stream.test.js +121 -0
- package/dist/archive-stream.test.js.map +1 -0
- package/dist/duplex-close-deadline.test.d.ts +2 -0
- package/dist/duplex-close-deadline.test.d.ts.map +1 -0
- package/dist/duplex-close-deadline.test.js +106 -0
- package/dist/duplex-close-deadline.test.js.map +1 -0
- package/dist/duplex-command-stream.d.ts +98 -0
- package/dist/duplex-command-stream.d.ts.map +1 -0
- package/dist/duplex-command-stream.js +218 -0
- package/dist/duplex-command-stream.js.map +1 -0
- package/dist/duplex-command-stream.live.test.d.ts +2 -0
- package/dist/duplex-command-stream.live.test.d.ts.map +1 -0
- package/dist/duplex-command-stream.live.test.js +324 -0
- package/dist/duplex-command-stream.live.test.js.map +1 -0
- package/dist/duplex-command-stream.test.d.ts +2 -0
- package/dist/duplex-command-stream.test.d.ts.map +1 -0
- package/dist/duplex-command-stream.test.js +519 -0
- package/dist/duplex-command-stream.test.js.map +1 -0
- package/dist/file-sync-capacity.live.test.d.ts +2 -0
- package/dist/file-sync-capacity.live.test.d.ts.map +1 -0
- package/dist/file-sync-capacity.live.test.js +122 -0
- package/dist/file-sync-capacity.live.test.js.map +1 -0
- package/dist/file-sync-capacity.test.d.ts +2 -0
- package/dist/file-sync-capacity.test.d.ts.map +1 -0
- package/dist/file-sync-capacity.test.js +337 -0
- package/dist/file-sync-capacity.test.js.map +1 -0
- package/dist/file-sync-diagnostics.test.d.ts +2 -0
- package/dist/file-sync-diagnostics.test.d.ts.map +1 -0
- package/dist/file-sync-diagnostics.test.js +165 -0
- package/dist/file-sync-diagnostics.test.js.map +1 -0
- package/dist/file-sync.d.ts +80 -0
- package/dist/file-sync.d.ts.map +1 -0
- package/dist/file-sync.js +1362 -0
- package/dist/file-sync.js.map +1 -0
- package/dist/file-sync.test.d.ts +2 -0
- package/dist/file-sync.test.d.ts.map +1 -0
- package/dist/file-sync.test.js +1214 -0
- package/dist/file-sync.test.js.map +1 -0
- package/dist/idle-activity.d.ts +40 -0
- package/dist/idle-activity.d.ts.map +1 -0
- package/dist/idle-activity.js +145 -0
- package/dist/idle-activity.js.map +1 -0
- package/dist/idle-activity.test.d.ts +2 -0
- package/dist/idle-activity.test.d.ts.map +1 -0
- package/dist/idle-activity.test.js +159 -0
- package/dist/idle-activity.test.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/lease-tracing.d.ts +7 -0
- package/dist/lease-tracing.d.ts.map +1 -0
- package/dist/lease-tracing.js +31 -0
- package/dist/lease-tracing.js.map +1 -0
- package/dist/lease-tracing.test.d.ts +2 -0
- package/dist/lease-tracing.test.d.ts.map +1 -0
- package/dist/lease-tracing.test.js +298 -0
- package/dist/lease-tracing.test.js.map +1 -0
- package/dist/login-pty.d.ts +162 -0
- package/dist/login-pty.d.ts.map +1 -0
- package/dist/login-pty.js +258 -0
- package/dist/login-pty.js.map +1 -0
- package/dist/login-pty.test.d.ts +2 -0
- package/dist/login-pty.test.d.ts.map +1 -0
- package/dist/login-pty.test.js +319 -0
- package/dist/login-pty.test.js.map +1 -0
- package/dist/manifest.d.ts +5 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/manifest.js +189 -0
- package/dist/manifest.js.map +1 -0
- package/dist/one-shot-exec-deadline.test.d.ts +2 -0
- package/dist/one-shot-exec-deadline.test.d.ts.map +1 -0
- package/dist/one-shot-exec-deadline.test.js +73 -0
- package/dist/one-shot-exec-deadline.test.js.map +1 -0
- package/dist/plugin.d.ts +103 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +3572 -0
- package/dist/plugin.js.map +1 -0
- package/dist/plugin.test.d.ts +2 -0
- package/dist/plugin.test.d.ts.map +1 -0
- package/dist/plugin.test.js +7276 -0
- package/dist/plugin.test.js.map +1 -0
- package/dist/pty-chunked-input.d.ts +48 -0
- package/dist/pty-chunked-input.d.ts.map +1 -0
- package/dist/pty-chunked-input.js +74 -0
- package/dist/pty-chunked-input.js.map +1 -0
- package/dist/pty-chunked-input.test.d.ts +2 -0
- package/dist/pty-chunked-input.test.d.ts.map +1 -0
- package/dist/pty-chunked-input.test.js +115 -0
- package/dist/pty-chunked-input.test.js.map +1 -0
- package/dist/runner-ingress.sdk-integration.d.ts +2 -0
- package/dist/runner-ingress.sdk-integration.d.ts.map +1 -0
- package/dist/runner-ingress.sdk-integration.js +87 -0
- package/dist/runner-ingress.sdk-integration.js.map +1 -0
- package/dist/session-command-completion.test.d.ts +2 -0
- package/dist/session-command-completion.test.d.ts.map +1 -0
- package/dist/session-command-completion.test.js +251 -0
- package/dist/session-command-completion.test.js.map +1 -0
- package/dist/session-stream-exit.d.ts +13 -0
- package/dist/session-stream-exit.d.ts.map +1 -0
- package/dist/session-stream-exit.js +48 -0
- package/dist/session-stream-exit.js.map +1 -0
- package/dist/tar-listing.test.d.ts +2 -0
- package/dist/tar-listing.test.d.ts.map +1 -0
- package/dist/tar-listing.test.js +220 -0
- package/dist/tar-listing.test.js.map +1 -0
- package/dist/worker.d.ts +3 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +5 -0
- package/dist/worker.js.map +1 -0
- package/package.json +42 -4
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,3572 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { Daytona, DaytonaNotFoundError, DaytonaTimeoutError } from "@daytonaio/sdk";
|
|
4
|
+
import { decodeChannelBytes, definePlugin, NOOP_PLUGIN_TRACER, PluginEnvironmentAcquisitionError, PluginEnvironmentCreationCleanupError, PluginEnvironmentRunnerIngressError, PluginEnvironmentStopError, readEnvironmentCreationCleanupError, withEnvironmentSyncTransferStep, preserveEnvironmentSyncErrorDiagnostic } from "@paperclipai/plugin-sdk";
|
|
5
|
+
import { performSyncIn, performSyncOut, withProviderSpan } from "./file-sync.js";
|
|
6
|
+
import { DEFAULT_DAYTONA_OPERATION_TIMEOUT_MS } from "./manifest.js";
|
|
7
|
+
import { withLeaseSpan, leaseStateAttributes } from "./lease-tracing.js";
|
|
8
|
+
import { observeSessionStreamExit } from "./session-stream-exit.js";
|
|
9
|
+
import { DaytonaIdleActivity, trackDaytonaHooks } from "./idle-activity.js";
|
|
10
|
+
// The Claude `setup-token` login pseudo-terminal (PTY) session for this provider.
|
|
11
|
+
// The session runs the login command on a real pseudo-terminal, streams the
|
|
12
|
+
// terminal output, and delivers the delayed browser code plus the Enter byte. A
|
|
13
|
+
// later phase binds the opener to `sandbox.process` and wraps it with the
|
|
14
|
+
// `createLoginPtyTransport` factory from `@paperclipai/adapter-utils` to
|
|
15
|
+
// build the transport the login runner drives.
|
|
16
|
+
export { createDaytonaLoginPtySessionOpener, openDaytonaLoginPtySession, createDaytonaLoginHomeFs, } from "./login-pty.js";
|
|
17
|
+
import { openDaytonaLoginPtySession as openLoginPtySession, createDaytonaLoginHomeFs, } from "./login-pty.js";
|
|
18
|
+
// The Daytona duplex command stream for the sandbox callback bridge. The channel
|
|
19
|
+
// runs the gateway command on a raw pseudo-terminal, streams the frames, and
|
|
20
|
+
// accepts host input. The worker resolves the sandbox by the provider lease id,
|
|
21
|
+
// registers the channel under the host route id, and streams the data and the
|
|
22
|
+
// exit through `ctx.duplexChannel`.
|
|
23
|
+
export { createDaytonaDuplexChannelSessionOpener, openDaytonaDuplexChannelSession, buildDuplexChannelLaunchWrapper, } from "./duplex-command-stream.js";
|
|
24
|
+
import { openDaytonaDuplexChannelSession as openDuplexChannelSession } from "./duplex-command-stream.js";
|
|
25
|
+
// Injectable monotonic clock for provider-boundary timing (Open Q1). Defaults
|
|
26
|
+
// to the real wall clock; `plugin.test.ts` overrides it via
|
|
27
|
+
// `setDaytonaTimingClockForTest` so the measured `durationMs`/`getDurationMs`
|
|
28
|
+
// are deterministic. The timing path never calls `Date.now()` directly.
|
|
29
|
+
let timingNow = () => Date.now();
|
|
30
|
+
// The plugin context, hoisted to a module variable in `setup(ctx)`. The
|
|
31
|
+
// lifecycle hooks and the file-sync helpers have no closure over `ctx`, so they
|
|
32
|
+
// read the tracer through `getPluginTracer()`. Before `setup` runs (or in a
|
|
33
|
+
// test) the tracer is a no-op, so a span never throws.
|
|
34
|
+
let pluginContext = null;
|
|
35
|
+
// A deadline does not settle the underlying request. Keep both that request
|
|
36
|
+
// and its allocation until completion and scoped provider cleanup are proven.
|
|
37
|
+
const idleActivity = new DaytonaIdleActivity();
|
|
38
|
+
/**
|
|
39
|
+
* Return the plugin tracer. It is the injected `ctx.tracer` after `setup`, or a
|
|
40
|
+
* no-op before it. A provider span opened through it records only when tracing
|
|
41
|
+
* is on and an active host trace context is present.
|
|
42
|
+
*/
|
|
43
|
+
export function getPluginTracer() {
|
|
44
|
+
return pluginContext?.tracer ?? NOOP_PLUGIN_TRACER;
|
|
45
|
+
}
|
|
46
|
+
function traceLeaseStep(name, work, attributes) {
|
|
47
|
+
return withLeaseSpan(getPluginTracer(), name, work, attributes);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Test seam: set the module-level plugin context, and return a restore function.
|
|
51
|
+
* `plugin.test.ts` uses it to inject a recording tracer without running `setup`.
|
|
52
|
+
*/
|
|
53
|
+
export function __setDaytonaPluginContextForTest(ctx) {
|
|
54
|
+
const previous = pluginContext;
|
|
55
|
+
pluginContext = ctx;
|
|
56
|
+
return () => {
|
|
57
|
+
pluginContext = previous;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Test seam: override the provider-timing clock and return a restore function.
|
|
62
|
+
* Not used in production, where the default wall clock always applies.
|
|
63
|
+
*/
|
|
64
|
+
export function setDaytonaTimingClockForTest(now) {
|
|
65
|
+
const previous = timingNow;
|
|
66
|
+
timingNow = now;
|
|
67
|
+
return () => {
|
|
68
|
+
timingNow = previous;
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// Injectable clock for the handle cache's freshness bookkeeping, deliberately
|
|
72
|
+
// kept separate from the provider-timing clock so tests can advance virtual time
|
|
73
|
+
// past a lease's auto-stop interval without perturbing the `getDurationMs` /
|
|
74
|
+
// `durationMs` measurements that ride on `timingNow`.
|
|
75
|
+
let handleFreshnessNow = () => Date.now();
|
|
76
|
+
/**
|
|
77
|
+
* Test seam: override the handle-cache freshness clock and return a restore
|
|
78
|
+
* function. Not used in production, where the default wall clock always applies.
|
|
79
|
+
*/
|
|
80
|
+
export function setDaytonaHandleFreshnessClockForTest(now) {
|
|
81
|
+
const previous = handleFreshnessNow;
|
|
82
|
+
handleFreshnessNow = now;
|
|
83
|
+
return () => {
|
|
84
|
+
handleFreshnessNow = previous;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
const WORKSPACE_SENTINEL_RELATIVE_PATH = ".paperclip-runtime/reusable-sandbox-lease.json";
|
|
88
|
+
// Quota-safety defaults (minutes). Daytona counts *stopped* sandboxes against
|
|
89
|
+
// the storage quota; only *archived* sandboxes move to cold object storage and
|
|
90
|
+
// stop counting. Without these, stopped/leaked sandboxes accumulate until the
|
|
91
|
+
// org quota fills. We apply sane defaults so every sandbox eventually leaves the
|
|
92
|
+
// quota on its own even when our own cleanup fails or never runs (crashed runs,
|
|
93
|
+
// failed lease destroys, orphaned probes). All three stay overridable per
|
|
94
|
+
// environment; an explicit 0/-1 in config is preserved.
|
|
95
|
+
//
|
|
96
|
+
// - autoStop: stop idle *running* sandboxes (frees CPU/RAM, starts the archive clock).
|
|
97
|
+
// - autoArchive: archive *stopped* sandboxes so they leave the disk quota.
|
|
98
|
+
// - autoDelete: backstop reaper for sandboxes nobody resumes.
|
|
99
|
+
const DEFAULT_AUTO_STOP_INTERVAL_MINUTES = 15;
|
|
100
|
+
// The host keeps a warm paperclip_runner on a reusable sandbox for
|
|
101
|
+
// `runnerIdleTimeoutMs` after a turn (host default 300000 ms). If Daytona's
|
|
102
|
+
// idle auto-stop fires at the same moment, a follow-up that arrives at the end
|
|
103
|
+
// of the warm window resumes a sandbox the provider is stopping and the resume
|
|
104
|
+
// is refused. Derive the provider auto-stop from the warm window so the
|
|
105
|
+
// provider backstop always fires strictly after the host's own idle handling:
|
|
106
|
+
// effective auto-stop >= ceil(warm idle) + this margin. Idle sandboxes still
|
|
107
|
+
// stop; only the backstop moves later by the margin.
|
|
108
|
+
export const DEFAULT_WARM_RUNNER_IDLE_TIMEOUT_MS = 300_000;
|
|
109
|
+
export const WARM_IDLE_AUTO_STOP_MARGIN_MINUTES = 5;
|
|
110
|
+
// A remote runner keeps working while its controller is offline, but Daytona
|
|
111
|
+
// counts only SDK and lifecycle events as activity. With no controller there are
|
|
112
|
+
// none, so an auto-stop shorter than the host's reconnect grace stops the
|
|
113
|
+
// sandbox (and kills the runner) while the host would still reattach it. The
|
|
114
|
+
// host forwards its grace for runner leases; the provider backstop then fires
|
|
115
|
+
// only after the grace plus this margin. Idle sandboxes still stop.
|
|
116
|
+
/**
|
|
117
|
+
* Host-owned floors (ms) the provider auto-stop must outlive: the warm runner
|
|
118
|
+
* idle window and the remote runner reconnect grace.
|
|
119
|
+
*/
|
|
120
|
+
function hostAutoStopFloorsMs(config) {
|
|
121
|
+
return [config.warmIdleTimeoutMs, config.runnerReconnectGraceMs]
|
|
122
|
+
.filter((value) => value != null && value > 0);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Effective Daytona auto-stop (minutes) for a sandbox. An explicit 0 (disabled)
|
|
126
|
+
* is preserved. A sandbox never auto-stops before a host-owned window (the warm
|
|
127
|
+
* idle window of a warm reusable lease, or the remote runner reconnect grace)
|
|
128
|
+
* plus {@link WARM_IDLE_AUTO_STOP_MARGIN_MINUTES}.
|
|
129
|
+
*/
|
|
130
|
+
export function effectiveAutoStopIntervalMinutes(config) {
|
|
131
|
+
const configured = config.autoStopInterval;
|
|
132
|
+
const floorsMs = hostAutoStopFloorsMs(config);
|
|
133
|
+
if (configured === 0 || floorsMs.length === 0)
|
|
134
|
+
return configured;
|
|
135
|
+
const floor = Math.ceil(Math.max(...floorsMs) / 60_000) + WARM_IDLE_AUTO_STOP_MARGIN_MINUTES;
|
|
136
|
+
return Math.max(configured ?? DEFAULT_AUTO_STOP_INTERVAL_MINUTES, floor);
|
|
137
|
+
}
|
|
138
|
+
function parseWarmIdleTimeoutMs(raw) {
|
|
139
|
+
// Only a reusable lease can host a warm runner.
|
|
140
|
+
if (raw.reuseLease !== true)
|
|
141
|
+
return null;
|
|
142
|
+
// The host forwards the run's resolved warm window (environment or agent
|
|
143
|
+
// setting) only when the run actually keeps a warm runner.
|
|
144
|
+
const forwarded = parseOptionalInteger(raw.warmRunnerIdleTimeoutMs);
|
|
145
|
+
if (forwarded != null && forwarded > 0)
|
|
146
|
+
return forwarded;
|
|
147
|
+
// An environment that itself selects a warm runner (no host forwarding, for
|
|
148
|
+
// example a legacy warm lifecycle) uses its own window. Inherit and per_turn
|
|
149
|
+
// apply no floor: the host forwards the window when the run is warm.
|
|
150
|
+
if (raw.runnerLifecycleMode !== "warm")
|
|
151
|
+
return null;
|
|
152
|
+
const configured = parseOptionalInteger(raw.runnerIdleTimeoutMs);
|
|
153
|
+
return configured != null && configured > 0 ? configured : DEFAULT_WARM_RUNNER_IDLE_TIMEOUT_MS;
|
|
154
|
+
}
|
|
155
|
+
const DEFAULT_AUTO_ARCHIVE_INTERVAL_MINUTES = 60;
|
|
156
|
+
const DEFAULT_AUTO_DELETE_INTERVAL_MINUTES = 7 * 24 * 60; // 7 days
|
|
157
|
+
// Sandboxes released with `archiveOnRelease` (test/probe runs) are archived so
|
|
158
|
+
// operators can inspect them from the Daytona dashboard, then expired by
|
|
159
|
+
// Daytona itself after this interval (counted from the stop that precedes the
|
|
160
|
+
// archive) so debugging copies don't accumulate.
|
|
161
|
+
const ARCHIVE_ON_RELEASE_AUTO_DELETE_MINUTES = 60;
|
|
162
|
+
// Fail-fast cap for git network operations (push, fetch, pull, ls-remote, etc.)
|
|
163
|
+
// so a stalled remote or missing credential never consumes the full 900 s adapter
|
|
164
|
+
// RPC ceiling; callers always see an actionable error within this window.
|
|
165
|
+
const GIT_NETWORK_TIMEOUT_MS = 120_000;
|
|
166
|
+
// Per-call bound on the provider liveness read (`sandbox.refreshData()`). The
|
|
167
|
+
// Daytona SDK gives this metadata read no timeout, so a silently unresponsive
|
|
168
|
+
// sandbox connection leaves it pending with no error. The plugin then stalls
|
|
169
|
+
// until the outer host-to-worker RPC backstop fires, which is a general ceiling,
|
|
170
|
+
// not a fast, specific detector. This bound turns that silent hang into a fast,
|
|
171
|
+
// clear error. It is configurable through `livenessTimeoutMs`; a value of 0 or
|
|
172
|
+
// less disables the extra bound.
|
|
173
|
+
const DEFAULT_LIVENESS_TIMEOUT_MS = 30_000;
|
|
174
|
+
// Bound on the optional resume-time auto-stop update, so a slow provider
|
|
175
|
+
// write cannot consume the host's resume budget.
|
|
176
|
+
const AUTO_STOP_UPDATE_TIMEOUT_MS = 5_000;
|
|
177
|
+
// Extra margin added to the SDK start/recover timeout when the plugin wraps
|
|
178
|
+
// those lifecycle calls in its own per-call bound. The SDK call already carries
|
|
179
|
+
// a `timeoutSeconds` deadline; the wrapper is a backstop for a connection-level
|
|
180
|
+
// hang that the SDK deadline can miss. The margin lets the SDK deadline fire
|
|
181
|
+
// first on a normal slow start, so the wrapper only fires on a true hang.
|
|
182
|
+
const LIVENESS_START_TIMEOUT_MARGIN_MS = 5_000;
|
|
183
|
+
// Noninteractive git credential defaults injected into every Daytona one-shot
|
|
184
|
+
// command so that git operations never stall waiting for a terminal prompt.
|
|
185
|
+
// Callers can override any of these via the env parameter.
|
|
186
|
+
const NONINTERACTIVE_GIT_ENV = {
|
|
187
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
188
|
+
GCM_INTERACTIVE: "Never",
|
|
189
|
+
GIT_ASKPASS: "echo",
|
|
190
|
+
SSH_ASKPASS: "echo",
|
|
191
|
+
SSH_ASKPASS_REQUIRE: "force",
|
|
192
|
+
};
|
|
193
|
+
const DEFAULT_SSH_ACCESS_MINUTES = 60;
|
|
194
|
+
const DAYTONA_SSH_GATEWAY_HOST = "ssh.app.daytona.io";
|
|
195
|
+
function parseOptionalString(value) {
|
|
196
|
+
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
197
|
+
}
|
|
198
|
+
function parseOptionalInteger(value) {
|
|
199
|
+
if (value == null || value === "")
|
|
200
|
+
return null;
|
|
201
|
+
const parsed = Number(value);
|
|
202
|
+
return Number.isFinite(parsed) ? Math.trunc(parsed) : null;
|
|
203
|
+
}
|
|
204
|
+
function parseOptionalNumber(value) {
|
|
205
|
+
if (value == null || value === "")
|
|
206
|
+
return null;
|
|
207
|
+
const parsed = Number(value);
|
|
208
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
209
|
+
}
|
|
210
|
+
function parsePositiveInteger(value) {
|
|
211
|
+
const parsed = parseOptionalInteger(value);
|
|
212
|
+
return parsed != null && parsed > 0 ? parsed : null;
|
|
213
|
+
}
|
|
214
|
+
function parseDriverConfig(raw) {
|
|
215
|
+
const timeoutMs = Number(raw.timeoutMs ?? DEFAULT_DAYTONA_OPERATION_TIMEOUT_MS);
|
|
216
|
+
const livenessTimeoutMs = Number(raw.livenessTimeoutMs ?? DEFAULT_LIVENESS_TIMEOUT_MS);
|
|
217
|
+
return {
|
|
218
|
+
apiKey: parseOptionalString(raw.apiKey),
|
|
219
|
+
apiUrl: parseOptionalString(raw.apiUrl),
|
|
220
|
+
target: parseOptionalString(raw.target),
|
|
221
|
+
snapshot: parseOptionalString(raw.snapshot),
|
|
222
|
+
image: parseOptionalString(raw.image),
|
|
223
|
+
language: parseOptionalString(raw.language),
|
|
224
|
+
timeoutMs: Number.isFinite(timeoutMs) ? Math.trunc(timeoutMs) : DEFAULT_DAYTONA_OPERATION_TIMEOUT_MS,
|
|
225
|
+
livenessTimeoutMs: Number.isFinite(livenessTimeoutMs) ? Math.trunc(livenessTimeoutMs) : DEFAULT_LIVENESS_TIMEOUT_MS,
|
|
226
|
+
cpu: parseOptionalNumber(raw.cpu),
|
|
227
|
+
memory: parseOptionalNumber(raw.memory),
|
|
228
|
+
disk: parseOptionalNumber(raw.disk),
|
|
229
|
+
gpu: parseOptionalNumber(raw.gpu),
|
|
230
|
+
autoStopInterval: parseOptionalInteger(raw.autoStopInterval) ?? DEFAULT_AUTO_STOP_INTERVAL_MINUTES,
|
|
231
|
+
autoArchiveInterval: parseOptionalInteger(raw.autoArchiveInterval) ?? DEFAULT_AUTO_ARCHIVE_INTERVAL_MINUTES,
|
|
232
|
+
autoDeleteInterval: parseOptionalInteger(raw.autoDeleteInterval) ?? DEFAULT_AUTO_DELETE_INTERVAL_MINUTES,
|
|
233
|
+
ttlMinutes: raw.ttlMinutes == null || raw.ttlMinutes === "" ? null : Number(raw.ttlMinutes),
|
|
234
|
+
reuseLease: raw.reuseLease === true,
|
|
235
|
+
archiveOnRelease: raw.archiveOnRelease === true,
|
|
236
|
+
warmIdleTimeoutMs: parseWarmIdleTimeoutMs(raw),
|
|
237
|
+
runnerReconnectGraceMs: parsePositiveInteger(raw.runnerReconnectGraceMs),
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
function resolveApiKey(config) {
|
|
241
|
+
if (config.apiKey) {
|
|
242
|
+
return config.apiKey;
|
|
243
|
+
}
|
|
244
|
+
const envApiKey = process.env.DAYTONA_API_KEY?.trim() ?? "";
|
|
245
|
+
if (!envApiKey) {
|
|
246
|
+
throw new Error("Daytona sandbox environments require an API key in config or DAYTONA_API_KEY.");
|
|
247
|
+
}
|
|
248
|
+
return envApiKey;
|
|
249
|
+
}
|
|
250
|
+
function createDaytonaClient(config) {
|
|
251
|
+
const clientConfig = {
|
|
252
|
+
apiKey: resolveApiKey(config),
|
|
253
|
+
};
|
|
254
|
+
if (config.apiUrl)
|
|
255
|
+
clientConfig.apiUrl = config.apiUrl;
|
|
256
|
+
if (config.target)
|
|
257
|
+
clientConfig.target = config.target;
|
|
258
|
+
return new Daytona(clientConfig);
|
|
259
|
+
}
|
|
260
|
+
function buildResources(config) {
|
|
261
|
+
if (config.cpu == null && config.memory == null && config.disk == null && config.gpu == null) {
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
cpu: config.cpu ?? undefined,
|
|
266
|
+
memory: config.memory ?? undefined,
|
|
267
|
+
disk: config.disk ?? undefined,
|
|
268
|
+
gpu: config.gpu ?? undefined,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
function buildCreateParams(config, labels) {
|
|
272
|
+
const base = {
|
|
273
|
+
labels,
|
|
274
|
+
language: config.language ?? undefined,
|
|
275
|
+
autoStopInterval: effectiveAutoStopIntervalMinutes(config) ?? undefined,
|
|
276
|
+
autoArchiveInterval: config.autoArchiveInterval ?? undefined,
|
|
277
|
+
autoDeleteInterval: config.autoDeleteInterval ?? undefined,
|
|
278
|
+
...(config.ttlMinutes != null ? { ttlMinutes: config.ttlMinutes } : {}),
|
|
279
|
+
};
|
|
280
|
+
if (config.image) {
|
|
281
|
+
return {
|
|
282
|
+
...base,
|
|
283
|
+
image: config.image,
|
|
284
|
+
resources: buildResources(config),
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
return {
|
|
288
|
+
...base,
|
|
289
|
+
snapshot: config.snapshot ?? undefined,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
function hasResourceRequest(config) {
|
|
293
|
+
return config.cpu != null || config.memory != null || config.disk != null || config.gpu != null;
|
|
294
|
+
}
|
|
295
|
+
function validateResourceRequest(config) {
|
|
296
|
+
if (!hasResourceRequest(config) || config.image)
|
|
297
|
+
return null;
|
|
298
|
+
return "Daytona resource settings require image-backed sandbox creation; snapshot/default sandbox creation cannot override CPU, memory, disk, or GPU.";
|
|
299
|
+
}
|
|
300
|
+
function validateRuntimeResourceRequest(config) {
|
|
301
|
+
// A snapshot bakes in its own resource allocation, so resources are dropped at
|
|
302
|
+
// create time (see buildCreateParams) rather than failing the run when a custom
|
|
303
|
+
// image snapshot is layered over a base config that carries CPU/memory/disk/GPU.
|
|
304
|
+
if (!hasResourceRequest(config) || config.image || config.snapshot)
|
|
305
|
+
return null;
|
|
306
|
+
return "Daytona resource settings require image-backed sandbox creation; default sandbox creation cannot override CPU, memory, disk, or GPU.";
|
|
307
|
+
}
|
|
308
|
+
function validateCreationTtl(config) {
|
|
309
|
+
return config.ttlMinutes != null && (!Number.isSafeInteger(config.ttlMinutes) || config.ttlMinutes <= 0)
|
|
310
|
+
? "ttlMinutes must be a positive integer when configured."
|
|
311
|
+
: null;
|
|
312
|
+
}
|
|
313
|
+
function buildSandboxLabels(input) {
|
|
314
|
+
return {
|
|
315
|
+
"paperclip-provider": "daytona",
|
|
316
|
+
"paperclip-company-id": input.companyId,
|
|
317
|
+
"paperclip-environment-id": input.environmentId,
|
|
318
|
+
"paperclip-reuse-lease": input.reuseLease ? "true" : "false",
|
|
319
|
+
...(input.runId ? { "paperclip-run-id": input.runId } : {}),
|
|
320
|
+
...(input.setupSessionId ? { "paperclip-setup-session-id": input.setupSessionId } : {}),
|
|
321
|
+
...(input.purpose ? { "paperclip-purpose": input.purpose } : {}),
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
function toTimeoutSeconds(timeoutMs) {
|
|
325
|
+
return Math.max(1, Math.ceil(timeoutMs / 1000));
|
|
326
|
+
}
|
|
327
|
+
function resolveSyncTimeoutSeconds(config, minimumTimeoutMs) {
|
|
328
|
+
if (minimumTimeoutMs !== undefined && (!Number.isSafeInteger(minimumTimeoutMs)
|
|
329
|
+
|| minimumTimeoutMs <= 0 || minimumTimeoutMs > 30 * 60_000)) {
|
|
330
|
+
throw new RangeError("Invalid sandbox sync timeout");
|
|
331
|
+
}
|
|
332
|
+
return toTimeoutSeconds(Math.max(config.timeoutMs, minimumTimeoutMs ?? 0));
|
|
333
|
+
}
|
|
334
|
+
function resolveTimeoutMs(paramsTimeoutMs, config) {
|
|
335
|
+
return paramsTimeoutMs != null && Number.isFinite(paramsTimeoutMs) && paramsTimeoutMs > 0
|
|
336
|
+
? Math.trunc(paramsTimeoutMs)
|
|
337
|
+
: config.timeoutMs;
|
|
338
|
+
}
|
|
339
|
+
function formatErrorMessage(error) {
|
|
340
|
+
return error instanceof Error ? error.message : String(error);
|
|
341
|
+
}
|
|
342
|
+
/** The pinned SDK stores response statusCode as data; never read messages or headers. */
|
|
343
|
+
function creationHttpStatus(error) {
|
|
344
|
+
try {
|
|
345
|
+
if (!error || typeof error !== "object")
|
|
346
|
+
return undefined;
|
|
347
|
+
const status = Object.getOwnPropertyDescriptor(error, "statusCode")?.value;
|
|
348
|
+
return typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599
|
|
349
|
+
? status : undefined;
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
return undefined;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const DAYTONA_TRANSPORT_FAILURES = new Set(["DaytonaConnectionError", "DaytonaConnectionTimeoutError"]);
|
|
356
|
+
class DaytonaTransportFailure extends Error {
|
|
357
|
+
code;
|
|
358
|
+
constructor(cause) {
|
|
359
|
+
super(cause.message, { cause });
|
|
360
|
+
this.name = "DaytonaTransportFailure";
|
|
361
|
+
this.code = cause.name === "DaytonaConnectionTimeoutError" ? "ETIMEDOUT" : "CONNECTION_FAILED";
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
function withTransportFailureCode(error) {
|
|
365
|
+
return error instanceof Error && DAYTONA_TRANSPORT_FAILURES.has(error.name) ? new DaytonaTransportFailure(error) : error;
|
|
366
|
+
}
|
|
367
|
+
async function acquireRunnerIngress(phase, operation) {
|
|
368
|
+
try {
|
|
369
|
+
return await operation();
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
const httpStatus = creationHttpStatus(error);
|
|
373
|
+
if (httpStatus !== undefined && httpStatus >= 400) {
|
|
374
|
+
throw new PluginEnvironmentRunnerIngressError({ phase, httpStatus });
|
|
375
|
+
}
|
|
376
|
+
throw error;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
function isRecord(value) {
|
|
380
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
381
|
+
}
|
|
382
|
+
function stableStringify(value) {
|
|
383
|
+
if (Array.isArray(value)) {
|
|
384
|
+
return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
|
|
385
|
+
}
|
|
386
|
+
if (isRecord(value)) {
|
|
387
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
|
|
388
|
+
}
|
|
389
|
+
return JSON.stringify(value) ?? "null";
|
|
390
|
+
}
|
|
391
|
+
function isValidUrl(value) {
|
|
392
|
+
try {
|
|
393
|
+
new URL(value);
|
|
394
|
+
return true;
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
return false;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
// A per-call liveness bound elapsed before the wrapped provider call returned.
|
|
401
|
+
// The message names the operation and the bound so an operator sees at once
|
|
402
|
+
// that the sandbox connection is unresponsive, not that the operation is slow.
|
|
403
|
+
class SandboxLivenessTimeoutError extends Error {
|
|
404
|
+
code = "ETIMEDOUT";
|
|
405
|
+
constructor(operation, timeoutMs) {
|
|
406
|
+
super(`Daytona sandbox liveness call "${operation}" did not respond within ${timeoutMs} ms; `
|
|
407
|
+
+ "the sandbox connection is unresponsive.");
|
|
408
|
+
this.name = "SandboxLivenessTimeoutError";
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
// Race a provider call against a per-call deadline. A value of 0 or less turns
|
|
412
|
+
// the bound off and runs the call unwrapped. The timer is always cleared, so a
|
|
413
|
+
// call that resolves before the deadline leaks no pending timer. A call that
|
|
414
|
+
// never resolves stays pending after the deadline rejects, but it holds no
|
|
415
|
+
// timer and produces no unhandled rejection.
|
|
416
|
+
async function withLivenessTimeout(operation, timeoutMs, run) {
|
|
417
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
418
|
+
return idleActivity.track(run);
|
|
419
|
+
}
|
|
420
|
+
let timer;
|
|
421
|
+
const deadline = new Promise((_, reject) => {
|
|
422
|
+
timer = setTimeout(() => reject(new SandboxLivenessTimeoutError(operation, timeoutMs)), timeoutMs);
|
|
423
|
+
});
|
|
424
|
+
try {
|
|
425
|
+
return await Promise.race([idleActivity.track(run), deadline]);
|
|
426
|
+
}
|
|
427
|
+
finally {
|
|
428
|
+
if (timer !== undefined)
|
|
429
|
+
clearTimeout(timer);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/** A dead bridge must not prevent provider-level termination. Stop/delete is
|
|
433
|
+
* the receipt boundary; timing out this drain is never termination evidence. */
|
|
434
|
+
async function drainSandboxBeforeTermination(sandbox, scope) {
|
|
435
|
+
const timeoutMs = Math.max(1, Math.min(scope.config.livenessTimeoutMs || 10_000, 10_000));
|
|
436
|
+
const steps = [
|
|
437
|
+
["sandbox.activityDrain", () => sandboxHandleActivityGates.waitForIdle(scope)],
|
|
438
|
+
["sandbox.sessionTeardown", () => teardownSession(sandbox, scope)],
|
|
439
|
+
["sandbox.channelTeardown", () => closeDaytonaDuplexChannelsForLease(scope.providerLeaseId)],
|
|
440
|
+
];
|
|
441
|
+
for (const [operation, action] of steps) {
|
|
442
|
+
try {
|
|
443
|
+
await withLivenessTimeout(operation, timeoutMs, action);
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
// Each cleanup is independent; one hung bridge must not retain other routes.
|
|
447
|
+
console.warn("Sandbox bridge cleanup failed; continuing provider termination.");
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
async function terminateAtProvider(scope, operation, action) {
|
|
452
|
+
const timeoutMs = scope.config.timeoutMs > 0 ? scope.config.timeoutMs : DEFAULT_DAYTONA_OPERATION_TIMEOUT_MS;
|
|
453
|
+
return withLivenessTimeout(operation, timeoutMs + LIVENESS_START_TIMEOUT_MARGIN_MS, action);
|
|
454
|
+
}
|
|
455
|
+
// Start (or recover) a sandbox that is not running. Every restart path goes
|
|
456
|
+
// through here with the lease scope, because a restart destroys every Daytona
|
|
457
|
+
// process session. The stored session id for the lease is dropped before the
|
|
458
|
+
// restart, so the next command opens a fresh session instead of sending a dead
|
|
459
|
+
// id and failing with "session not found". A running sandbox keeps its live
|
|
460
|
+
// session, so the id is left in place when no restart happens.
|
|
461
|
+
const SANDBOX_TRANSITION_STATES = new Set([
|
|
462
|
+
"starting", "stopping", "restoring", "archiving", "creating", "pending_build", "pulling_snapshot", "building_snapshot", "resizing",
|
|
463
|
+
]);
|
|
464
|
+
const SANDBOX_TRANSITION_POLL_MS = 1_000;
|
|
465
|
+
function isSandboxStateChangeInProgress(error) {
|
|
466
|
+
return /state change in progress/i.test(error instanceof Error ? error.message : String(error));
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* How long a sandbox may stay `stopping` before a start forces the stop. The
|
|
470
|
+
* host stops an idle sandbox gracefully with a 30 s budget, so a stop still
|
|
471
|
+
* pending after this is stuck, typically on a process that ignores SIGTERM.
|
|
472
|
+
* Daytona can leave such a sandbox `stopping` for many minutes.
|
|
473
|
+
*/
|
|
474
|
+
export const STUCK_STOPPING_FORCE_AFTER_MS = 30_000;
|
|
475
|
+
const STUCK_STOPPING_FORCE_STOP_SECONDS = 30;
|
|
476
|
+
/**
|
|
477
|
+
* One forced stop per stuck stop, whichever caller sends it. A confirmed start
|
|
478
|
+
* ends the episode early (see {@link endForcedStopEpisode}).
|
|
479
|
+
*/
|
|
480
|
+
export const FORCED_STOP_COOLDOWN_MS = 10 * 60_000;
|
|
481
|
+
// Forced stops are owned by the sandbox, not by a caller. Several callers can
|
|
482
|
+
// wait on one stuck sandbox at once (execute, sync, realize, resume). Only one
|
|
483
|
+
// of them sends the forced stop, and no caller starts the sandbox while that
|
|
484
|
+
// request is unsettled: a late stop would otherwise kill a sandbox another
|
|
485
|
+
// caller has just restarted. The entry outlives its liveness timeout until
|
|
486
|
+
// the SDK request itself settles.
|
|
487
|
+
const forcedSandboxStops = new Map();
|
|
488
|
+
function forcedStopInFlight(key) {
|
|
489
|
+
return forcedSandboxStops.get(key)?.pending ?? null;
|
|
490
|
+
}
|
|
491
|
+
// A confirmed start ends the stuck stop. A later stuck stop is a new episode
|
|
492
|
+
// and may be forced at once. An unsettled request still blocks every start.
|
|
493
|
+
function endForcedStopEpisode(key) {
|
|
494
|
+
if (forcedSandboxStops.get(key)?.pending === null)
|
|
495
|
+
forcedSandboxStops.delete(key);
|
|
496
|
+
}
|
|
497
|
+
function claimForcedStop(key, now) {
|
|
498
|
+
const previous = forcedSandboxStops.get(key);
|
|
499
|
+
if (previous && (previous.pending || now - previous.issuedAt < FORCED_STOP_COOLDOWN_MS))
|
|
500
|
+
return false;
|
|
501
|
+
forcedSandboxStops.set(key, { issuedAt: now, pending: null });
|
|
502
|
+
return true;
|
|
503
|
+
}
|
|
504
|
+
async function sendForcedStop(sandbox, key, deadline) {
|
|
505
|
+
const remainingSeconds = Math.max(1, Math.floor((deadline - Date.now()) / 1_000));
|
|
506
|
+
const stopSeconds = Math.min(STUCK_STOPPING_FORCE_STOP_SECONDS, remainingSeconds);
|
|
507
|
+
const entry = forcedSandboxStops.get(key);
|
|
508
|
+
// `request` settles only when the SDK call does, even past the liveness bound.
|
|
509
|
+
const request = Promise.resolve().then(() => sandbox.stop(stopSeconds, true));
|
|
510
|
+
entry.pending = request.then(() => undefined, () => undefined)
|
|
511
|
+
.finally(() => { if (forcedSandboxStops.get(key) === entry)
|
|
512
|
+
entry.pending = null; });
|
|
513
|
+
try {
|
|
514
|
+
await traceLeaseStep("lease.force_stop", () => withLivenessTimeout("sandbox.stop", stopSeconds * 1_000 + LIVENESS_START_TIMEOUT_MARGIN_MS, () => request));
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
// Keep waiting within the same deadline; the next read reports the state.
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
async function waitOutSandboxTransition(sandbox, scope, deadline, readTimeoutMs) {
|
|
521
|
+
const key = sandboxHandleCacheKey(scope);
|
|
522
|
+
const mustWait = () => SANDBOX_TRANSITION_STATES.has(sandbox.state ?? "") || forcedStopInFlight(key) !== null;
|
|
523
|
+
if (!mustWait())
|
|
524
|
+
return;
|
|
525
|
+
await traceLeaseStep("lease.wait_transition", async () => {
|
|
526
|
+
let stoppingSince = null;
|
|
527
|
+
while (mustWait() && Date.now() + SANDBOX_TRANSITION_POLL_MS < deadline) {
|
|
528
|
+
stoppingSince = sandbox.state === "stopping" ? stoppingSince ?? Date.now() : null;
|
|
529
|
+
// The sandbox is about to be started, so killing what holds the stop
|
|
530
|
+
// loses nothing a graceful stop would keep: the disk survives a stop.
|
|
531
|
+
// A refusal leaves the plain wait unchanged.
|
|
532
|
+
if (stoppingSince !== null && Date.now() - stoppingSince >= STUCK_STOPPING_FORCE_AFTER_MS
|
|
533
|
+
&& claimForcedStop(key, Date.now())) {
|
|
534
|
+
await sendForcedStop(sandbox, key, deadline);
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
const pending = forcedStopInFlight(key);
|
|
538
|
+
await Promise.race([
|
|
539
|
+
new Promise(resolve => setTimeout(resolve, SANDBOX_TRANSITION_POLL_MS)),
|
|
540
|
+
...(pending ? [pending] : []),
|
|
541
|
+
]);
|
|
542
|
+
await withLivenessTimeout("sandbox.refreshData", Math.min(readTimeoutMs, Math.max(1, deadline - Date.now())), () => sandbox.refreshData());
|
|
543
|
+
}
|
|
544
|
+
}, leaseStateAttributes(sandbox.state));
|
|
545
|
+
}
|
|
546
|
+
async function ensureSandboxStarted(sandbox, timeoutSeconds, scope) {
|
|
547
|
+
if (sandbox.state === "started")
|
|
548
|
+
return;
|
|
549
|
+
sandboxHandleSessionStore.clear(scope);
|
|
550
|
+
const deadline = Date.now() + timeoutSeconds * 1_000;
|
|
551
|
+
const readTimeoutMs = Math.min(scope.config.livenessTimeoutMs, 30_000);
|
|
552
|
+
for (;;) {
|
|
553
|
+
await waitOutSandboxTransition(sandbox, scope, deadline, readTimeoutMs);
|
|
554
|
+
if (SANDBOX_TRANSITION_STATES.has(sandbox.state ?? "") || forcedStopInFlight(sandboxHandleCacheKey(scope))
|
|
555
|
+
|| Date.now() >= deadline) {
|
|
556
|
+
throw new Error(`Daytona sandbox ${sandbox.id} is still ${sandbox.state ?? "changing state"} at its start deadline`);
|
|
557
|
+
}
|
|
558
|
+
const remainingSeconds = Math.max(1, Math.ceil((deadline - Date.now()) / 1_000));
|
|
559
|
+
try {
|
|
560
|
+
await startSettledSandbox(sandbox, remainingSeconds, scope);
|
|
561
|
+
endForcedStopEpisode(sandboxHandleCacheKey(scope));
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
catch (error) {
|
|
565
|
+
if (!isSandboxStateChangeInProgress(error) || Date.now() + SANDBOX_TRANSITION_POLL_MS >= deadline)
|
|
566
|
+
throw error;
|
|
567
|
+
await new Promise(resolve => setTimeout(resolve, SANDBOX_TRANSITION_POLL_MS));
|
|
568
|
+
await withLivenessTimeout("sandbox.refreshData", Math.min(readTimeoutMs, Math.max(1, deadline - Date.now())), () => sandbox.refreshData());
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
async function startSettledSandbox(sandbox, timeoutSeconds, scope) {
|
|
573
|
+
if (sandbox.state === "started")
|
|
574
|
+
return;
|
|
575
|
+
sandboxHandleSessionStore.clear(scope);
|
|
576
|
+
// Bound the lifecycle call just past its own SDK deadline. A normal slow start
|
|
577
|
+
// finishes within `timeoutSeconds`; only a connection-level hang the SDK
|
|
578
|
+
// deadline misses reaches this wrapper bound.
|
|
579
|
+
const startBoundMs = timeoutSeconds * 1_000 + LIVENESS_START_TIMEOUT_MARGIN_MS;
|
|
580
|
+
if (sandbox.state === "error") {
|
|
581
|
+
if (sandbox.recoverable) {
|
|
582
|
+
await traceLeaseStep("lease.recover", () => withLivenessTimeout("sandbox.recover", startBoundMs, () => sandbox.recover(timeoutSeconds)), leaseStateAttributes(sandbox.state));
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
throw new Error(`Daytona sandbox ${sandbox.id} is in an unrecoverable error state: ${sandbox.errorReason ?? "unknown error"}`);
|
|
586
|
+
}
|
|
587
|
+
await traceLeaseStep("lease.start", () => withLivenessTimeout("sandbox.start", startBoundMs, () => sandbox.start(timeoutSeconds)), leaseStateAttributes(sandbox.state));
|
|
588
|
+
}
|
|
589
|
+
function hasMissingSandboxContainer(sandbox) {
|
|
590
|
+
if (sandbox.state !== "error" || sandbox.recoverable !== false || typeof sandbox.errorReason !== "string")
|
|
591
|
+
return false;
|
|
592
|
+
if (typeof sandbox.id !== "string" || !sandbox.id)
|
|
593
|
+
return false;
|
|
594
|
+
return sandbox.errorReason ===
|
|
595
|
+
`not found: failed to inspect sandbox container ${sandbox.id}: Error response from daemon: No such container: ${sandbox.id}`;
|
|
596
|
+
}
|
|
597
|
+
async function resolveSandboxWorkingDirectory(sandbox, create = true) {
|
|
598
|
+
const root = (await sandbox.getWorkDir())?.trim()
|
|
599
|
+
|| (await sandbox.getUserHomeDir())?.trim()
|
|
600
|
+
|| "/home/daytona";
|
|
601
|
+
const remoteCwd = path.posix.join(root, "paperclip-workspace");
|
|
602
|
+
if (create)
|
|
603
|
+
await sandbox.fs.createFolder(remoteCwd, "755");
|
|
604
|
+
return remoteCwd;
|
|
605
|
+
}
|
|
606
|
+
async function detectSandboxShellCommand(sandbox, timeoutSeconds) {
|
|
607
|
+
try {
|
|
608
|
+
const result = await sandbox.process.executeCommand("if command -v bash >/dev/null 2>&1; then printf bash; else printf sh; fi", undefined, undefined, timeoutSeconds);
|
|
609
|
+
return result.result?.trim() === "bash" ? "bash" : "sh";
|
|
610
|
+
}
|
|
611
|
+
catch {
|
|
612
|
+
return "sh";
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
function parseProbeInteger(value) {
|
|
616
|
+
const trimmed = value?.trim() ?? "";
|
|
617
|
+
if (!/^\d+$/.test(trimmed)) {
|
|
618
|
+
return null;
|
|
619
|
+
}
|
|
620
|
+
const parsed = Number.parseInt(trimmed, 10);
|
|
621
|
+
return Number.isInteger(parsed) ? parsed : null;
|
|
622
|
+
}
|
|
623
|
+
function workspaceSentinelToken(input) {
|
|
624
|
+
if ((!input.config.reuseLease && !input.params.runId) || !input.params.agentId || (!input.params.executionWorkspaceId && !input.params.issueId)) {
|
|
625
|
+
return null;
|
|
626
|
+
}
|
|
627
|
+
return createHash("sha256")
|
|
628
|
+
.update(stableStringify({
|
|
629
|
+
provider: "daytona",
|
|
630
|
+
...(!input.config.reuseLease ? { ephemeralRunId: input.params.runId, ephemeralProviderLeaseId: input.providerLeaseId } : {}),
|
|
631
|
+
companyId: input.params.companyId,
|
|
632
|
+
environmentId: input.params.environmentId,
|
|
633
|
+
agentId: input.params.agentId,
|
|
634
|
+
executionWorkspaceId: input.params.executionWorkspaceId,
|
|
635
|
+
...(input.params.executionWorkspaceId ? {} : { projectlessIssueId: input.params.issueId }),
|
|
636
|
+
adapterType: input.params.adapterType ?? null,
|
|
637
|
+
image: input.config.image,
|
|
638
|
+
snapshot: input.config.snapshot,
|
|
639
|
+
target: input.config.target,
|
|
640
|
+
// Include resource-shaping inputs so changing the requested allocation
|
|
641
|
+
// expires old reusable leases and forces a fresh sandbox instead of
|
|
642
|
+
// reusing a previously provisioned (e.g. one-CPU) sandbox.
|
|
643
|
+
cpu: input.config.cpu,
|
|
644
|
+
memory: input.config.memory,
|
|
645
|
+
disk: input.config.disk,
|
|
646
|
+
gpu: input.config.gpu,
|
|
647
|
+
}))
|
|
648
|
+
.digest("hex");
|
|
649
|
+
}
|
|
650
|
+
function workspaceSentinelPath(remoteCwd) {
|
|
651
|
+
return path.posix.join(remoteCwd, WORKSPACE_SENTINEL_RELATIVE_PATH);
|
|
652
|
+
}
|
|
653
|
+
async function writeWorkspaceSentinel(input) {
|
|
654
|
+
const sentinelPath = workspaceSentinelPath(input.remoteCwd);
|
|
655
|
+
const token = workspaceSentinelToken({ params: input.params, config: input.config, providerLeaseId: input.sandbox.id });
|
|
656
|
+
if (!token) {
|
|
657
|
+
return { path: sentinelPath, token: null, result: "skipped" };
|
|
658
|
+
}
|
|
659
|
+
await input.sandbox.fs.createFolder(path.posix.dirname(sentinelPath), "755");
|
|
660
|
+
const content = Buffer.from(JSON.stringify({
|
|
661
|
+
version: 1,
|
|
662
|
+
token,
|
|
663
|
+
companyId: input.params.companyId,
|
|
664
|
+
environmentId: input.params.environmentId,
|
|
665
|
+
agentId: input.params.agentId,
|
|
666
|
+
executionWorkspaceId: input.params.executionWorkspaceId,
|
|
667
|
+
...(input.params.executionWorkspaceId ? {} : { projectlessIssueId: input.params.issueId }),
|
|
668
|
+
adapterType: input.params.adapterType ?? null,
|
|
669
|
+
provider: "daytona",
|
|
670
|
+
writtenAt: new Date().toISOString(),
|
|
671
|
+
}, null, 2), "utf8");
|
|
672
|
+
await input.sandbox.fs.uploadFile(content, sentinelPath, input.timeoutSeconds);
|
|
673
|
+
return { path: sentinelPath, token, result: "written",
|
|
674
|
+
allocationFiles: { providerLeaseId: input.sandbox.id, remoteCwd: input.remoteCwd,
|
|
675
|
+
files: [{ relativePath: WORKSPACE_SENTINEL_RELATIVE_PATH, sha256: createHash("sha256").update(content).digest("hex") }] },
|
|
676
|
+
...(!input.config.reuseLease ? { runId: input.params.runId, providerLeaseId: input.sandbox.id } : {}) };
|
|
677
|
+
}
|
|
678
|
+
async function verifyWorkspaceSentinel(input) {
|
|
679
|
+
const metadataSentinel = isRecord(input.leaseMetadata?.workspaceSentinel)
|
|
680
|
+
? input.leaseMetadata.workspaceSentinel
|
|
681
|
+
: null;
|
|
682
|
+
const sentinelPath = typeof metadataSentinel?.path === "string"
|
|
683
|
+
? metadataSentinel.path
|
|
684
|
+
: workspaceSentinelPath(input.remoteCwd);
|
|
685
|
+
const binding = typeof metadataSentinel?.runId === "string" && typeof metadataSentinel?.providerLeaseId === "string"
|
|
686
|
+
? { runId: metadataSentinel.runId, providerLeaseId: metadataSentinel.providerLeaseId } : {};
|
|
687
|
+
const expectedToken = typeof metadataSentinel?.token === "string" ? metadataSentinel.token : null;
|
|
688
|
+
if (!expectedToken) {
|
|
689
|
+
return { path: sentinelPath, token: null, result: "missing" };
|
|
690
|
+
}
|
|
691
|
+
const result = await input.sandbox.process.executeCommand(`cat ${shellQuote(sentinelPath)}`, undefined, undefined, input.timeoutSeconds);
|
|
692
|
+
if (result.exitCode !== 0) {
|
|
693
|
+
return { path: sentinelPath, token: expectedToken, result: "missing" };
|
|
694
|
+
}
|
|
695
|
+
try {
|
|
696
|
+
const parsed = JSON.parse(result.result ?? result.artifacts?.stdout ?? "");
|
|
697
|
+
const actualToken = isRecord(parsed) && typeof parsed.token === "string" ? parsed.token : null;
|
|
698
|
+
return {
|
|
699
|
+
path: sentinelPath,
|
|
700
|
+
token: expectedToken,
|
|
701
|
+
...binding,
|
|
702
|
+
result: actualToken === expectedToken ? "matched" : "mismatch",
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
catch {
|
|
706
|
+
return { path: sentinelPath, token: expectedToken, result: "mismatch" };
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
function leaseMetadata(input) {
|
|
710
|
+
return {
|
|
711
|
+
provider: "daytona",
|
|
712
|
+
shellCommand: input.shellCommand,
|
|
713
|
+
sandboxId: input.sandbox.id,
|
|
714
|
+
sandboxName: input.sandbox.name,
|
|
715
|
+
sandboxState: input.sandboxState ?? input.sandbox.state ?? null,
|
|
716
|
+
image: input.config.image,
|
|
717
|
+
snapshot: input.config.snapshot,
|
|
718
|
+
...(input.snapshotIdentity ? { snapshotIdentity: input.snapshotIdentity } : {}),
|
|
719
|
+
target: input.sandbox.target,
|
|
720
|
+
timeoutMs: input.config.timeoutMs,
|
|
721
|
+
...(input.config.ttlMinutes != null ? { ttlMinutes: input.config.ttlMinutes } : {}),
|
|
722
|
+
reuseLease: input.config.reuseLease,
|
|
723
|
+
// Persisted so the release path (which rebuilds config from lease
|
|
724
|
+
// metadata) still knows to archive instead of delete.
|
|
725
|
+
...(input.config.archiveOnRelease ? { archiveOnRelease: true } : {}),
|
|
726
|
+
remoteCwd: input.remoteCwd,
|
|
727
|
+
resumedLease: input.resumedLease,
|
|
728
|
+
...(input.resumedLease
|
|
729
|
+
? { resumedFromState: input.resumedFromState ?? null }
|
|
730
|
+
: {}),
|
|
731
|
+
// Record the resources Paperclip attempted to request so future diagnosis
|
|
732
|
+
// can compare requested allocation against what Daytona provisioned.
|
|
733
|
+
...(input.config.cpu != null ? { cpu: input.config.cpu } : {}),
|
|
734
|
+
...(input.config.memory != null ? { memory: input.config.memory } : {}),
|
|
735
|
+
...(input.config.disk != null ? { disk: input.config.disk } : {}),
|
|
736
|
+
...(input.config.gpu != null ? { gpu: input.config.gpu } : {}),
|
|
737
|
+
...(input.workspaceSentinel ? { workspaceSentinel: input.workspaceSentinel } : {}),
|
|
738
|
+
...(input.workspaceSentinel?.allocationFiles ? { workspaceAllocationFiles: input.workspaceSentinel.allocationFiles } : {}),
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
function shellQuote(value) {
|
|
742
|
+
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
743
|
+
}
|
|
744
|
+
function resolveConnectionExpiresInMinutes(value) {
|
|
745
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
746
|
+
return DEFAULT_SSH_ACCESS_MINUTES;
|
|
747
|
+
return Math.min(24 * 60, Math.max(1, Math.trunc(value)));
|
|
748
|
+
}
|
|
749
|
+
function expiresAtForMinutes(minutes) {
|
|
750
|
+
return new Date(Date.now() + minutes * 60_000).toISOString();
|
|
751
|
+
}
|
|
752
|
+
async function configureSandboxExpiry(input) {
|
|
753
|
+
const creationExpiry = input.preserveCreationExpiry ? input.sandbox.autoDestroyAt : undefined;
|
|
754
|
+
const creationExpiryMs = creationExpiry ? Date.parse(creationExpiry) : Number.NaN;
|
|
755
|
+
const requestedMs = input.requestedExpiresAt ? Date.parse(input.requestedExpiresAt) : Number.NaN;
|
|
756
|
+
if (!Number.isFinite(requestedMs))
|
|
757
|
+
return Number.isFinite(creationExpiryMs) ? creationExpiry : null;
|
|
758
|
+
if (Number.isFinite(creationExpiryMs) && creationExpiryMs <= requestedMs)
|
|
759
|
+
return creationExpiry;
|
|
760
|
+
// Round DOWN so the provider destroy time never lands after the deadline.
|
|
761
|
+
const ttlMinutes = Math.floor((requestedMs - input.nowMs) / 60_000);
|
|
762
|
+
if (ttlMinutes < 1)
|
|
763
|
+
return null;
|
|
764
|
+
await input.sandbox.setTtl(ttlMinutes);
|
|
765
|
+
await input.sandbox.refreshData();
|
|
766
|
+
const autoDestroyAt = input.sandbox.autoDestroyAt;
|
|
767
|
+
return typeof autoDestroyAt === "string" && autoDestroyAt.trim().length > 0
|
|
768
|
+
? autoDestroyAt.trim()
|
|
769
|
+
: null;
|
|
770
|
+
}
|
|
771
|
+
function sanitizeSnapshotName(value, fallback) {
|
|
772
|
+
const cleaned = (value ?? fallback)
|
|
773
|
+
.trim()
|
|
774
|
+
.toLowerCase()
|
|
775
|
+
.replace(/[^a-z0-9._-]+/g, "-")
|
|
776
|
+
.replace(/^-+|-+$/g, "")
|
|
777
|
+
.slice(0, 96);
|
|
778
|
+
return cleaned || fallback;
|
|
779
|
+
}
|
|
780
|
+
function withSetupSourceTemplate(config, params) {
|
|
781
|
+
if (!params.sourceTemplateRef)
|
|
782
|
+
return config;
|
|
783
|
+
const sourceKind = params.sourceTemplateKind ?? "snapshot";
|
|
784
|
+
if (sourceKind === "image") {
|
|
785
|
+
return {
|
|
786
|
+
...config,
|
|
787
|
+
image: params.sourceTemplateRef,
|
|
788
|
+
snapshot: null,
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
if (sourceKind !== "snapshot") {
|
|
792
|
+
throw new Error(`Daytona interactive setup can start from image or snapshot templates only, not ${sourceKind}.`);
|
|
793
|
+
}
|
|
794
|
+
return {
|
|
795
|
+
...config,
|
|
796
|
+
snapshot: params.sourceTemplateRef,
|
|
797
|
+
image: null,
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
async function createSshConnection(sandbox, expiresInMinutes) {
|
|
801
|
+
const createSshAccess = sandbox.createSshAccess;
|
|
802
|
+
if (typeof createSshAccess !== "function") {
|
|
803
|
+
throw new Error("Daytona interactive setup requires @daytonaio/sdk Sandbox.createSshAccess support.");
|
|
804
|
+
}
|
|
805
|
+
const fallbackExpiresAt = expiresAtForMinutes(expiresInMinutes);
|
|
806
|
+
const access = await createSshAccess.call(sandbox, expiresInMinutes);
|
|
807
|
+
const token = typeof access.token === "string" && access.token.trim().length > 0
|
|
808
|
+
? access.token.trim()
|
|
809
|
+
: null;
|
|
810
|
+
const commandFromAccess = typeof access.command === "string" && access.command.trim().length > 0
|
|
811
|
+
? access.command.trim()
|
|
812
|
+
: typeof access.sshCommand === "string" && access.sshCommand.trim().length > 0
|
|
813
|
+
? access.sshCommand.trim()
|
|
814
|
+
: null;
|
|
815
|
+
const command = commandFromAccess ?? (token ? `ssh ${token}@${DAYTONA_SSH_GATEWAY_HOST}` : null);
|
|
816
|
+
if (!command) {
|
|
817
|
+
throw new Error("Daytona SSH access did not return a token or SSH command.");
|
|
818
|
+
}
|
|
819
|
+
const expiresAt = typeof access.expiresAt === "string" && access.expiresAt.trim().length > 0
|
|
820
|
+
? access.expiresAt.trim()
|
|
821
|
+
: fallbackExpiresAt;
|
|
822
|
+
return {
|
|
823
|
+
connectionSummary: {
|
|
824
|
+
type: "ssh",
|
|
825
|
+
username: "token",
|
|
826
|
+
hostRedacted: true,
|
|
827
|
+
portRedacted: true,
|
|
828
|
+
commandRedacted: true,
|
|
829
|
+
expiresAt,
|
|
830
|
+
metadata: {
|
|
831
|
+
provider: "daytona",
|
|
832
|
+
expiresInMinutes,
|
|
833
|
+
},
|
|
834
|
+
},
|
|
835
|
+
connectionPayload: {
|
|
836
|
+
type: "ssh",
|
|
837
|
+
command,
|
|
838
|
+
token,
|
|
839
|
+
expiresAt,
|
|
840
|
+
metadata: {
|
|
841
|
+
provider: "daytona",
|
|
842
|
+
sensitive: true,
|
|
843
|
+
},
|
|
844
|
+
},
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
function interactiveSetupMetadata(input) {
|
|
848
|
+
return {
|
|
849
|
+
provider: "daytona",
|
|
850
|
+
sandboxId: input.sandbox.id,
|
|
851
|
+
sandboxState: input.sandbox.state ?? null,
|
|
852
|
+
shellCommand: input.shellCommand,
|
|
853
|
+
imageConfigured: Boolean(input.config.image),
|
|
854
|
+
snapshotConfigured: Boolean(input.config.snapshot),
|
|
855
|
+
sourceTemplateRefRedacted: Boolean(input.sourceTemplateRef),
|
|
856
|
+
target: input.sandbox.target,
|
|
857
|
+
timeoutMs: input.config.timeoutMs,
|
|
858
|
+
remoteCwd: input.remoteCwd,
|
|
859
|
+
connectionRedacted: true,
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
function isValidShellEnvKey(value) {
|
|
863
|
+
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(value);
|
|
864
|
+
}
|
|
865
|
+
const GIT_NETWORK_SUBCOMMANDS = new Set(["push", "fetch", "pull", "ls-remote", "clone"]);
|
|
866
|
+
function isGitNetworkCommand(command, args) {
|
|
867
|
+
if (path.basename(command) !== "git")
|
|
868
|
+
return false;
|
|
869
|
+
// Find the first positional arg (the git subcommand), skipping flags and their values.
|
|
870
|
+
let i = 0;
|
|
871
|
+
while (i < args.length) {
|
|
872
|
+
const arg = args[i];
|
|
873
|
+
if (arg === "-C" || arg === "-c" || arg === "--git-dir" || arg === "--work-tree") {
|
|
874
|
+
i += 2;
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
if (arg.startsWith("-")) {
|
|
878
|
+
i++;
|
|
879
|
+
continue;
|
|
880
|
+
}
|
|
881
|
+
if (GIT_NETWORK_SUBCOMMANDS.has(arg))
|
|
882
|
+
return true;
|
|
883
|
+
if (arg === "remote") {
|
|
884
|
+
const next = args.slice(i + 1).find(a => !a.startsWith("-"));
|
|
885
|
+
return next === "update";
|
|
886
|
+
}
|
|
887
|
+
if (arg === "submodule") {
|
|
888
|
+
const next = args.slice(i + 1).find(a => !a.startsWith("-"));
|
|
889
|
+
return next === "update";
|
|
890
|
+
}
|
|
891
|
+
return false;
|
|
892
|
+
}
|
|
893
|
+
return false;
|
|
894
|
+
}
|
|
895
|
+
// Build the one-shot exec command. Daytona's `executeCommand` runs the script
|
|
896
|
+
// in a non-login shell, so it does not source `/etc/profile` on its own. The
|
|
897
|
+
// Daytona reference image puts `node`, `claude`, and the other CLIs on the PATH
|
|
898
|
+
// through `/etc/profile.d/00-restore-env.sh`, which only `/etc/profile` sources.
|
|
899
|
+
// So the wrapper sources the login profiles itself; a non-login shell is then
|
|
900
|
+
// enough to resolve the CLIs. The wrapper no longer sources `nvm.sh`; the
|
|
901
|
+
// sandbox image supplies `node` on the PATH. See the sandbox runtime
|
|
902
|
+
// requirements document.
|
|
903
|
+
function buildLoginShellScript(input) {
|
|
904
|
+
const callerEnv = input.env ?? {};
|
|
905
|
+
for (const key of Object.keys(callerEnv)) {
|
|
906
|
+
if (!isValidShellEnvKey(key)) {
|
|
907
|
+
throw new Error(`Invalid sandbox environment variable key: ${key}`);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
// Caller env takes priority over noninteractive git credential defaults
|
|
911
|
+
const env = { ...NONINTERACTIVE_GIT_ENV, ...callerEnv };
|
|
912
|
+
const envArgs = Object.entries(env)
|
|
913
|
+
.filter((entry) => typeof entry[1] === "string")
|
|
914
|
+
.map(([key, value]) => `${key}=${shellQuote(value)}`);
|
|
915
|
+
const commandParts = [shellQuote(input.command), ...input.args.map(shellQuote)].join(" ");
|
|
916
|
+
const redirectedCommand = input.stdinPath
|
|
917
|
+
? `${commandParts} < ${shellQuote(input.stdinPath)}`
|
|
918
|
+
: commandParts;
|
|
919
|
+
// Each `executeCommand` call runs in its own shell, so we don't `exec`-
|
|
920
|
+
// replace it; running the command as the last `&&`-chained line is enough to
|
|
921
|
+
// surface the right exit code.
|
|
922
|
+
const finalLine = envArgs.length > 0
|
|
923
|
+
? `env ${envArgs.join(" ")} ${redirectedCommand}`
|
|
924
|
+
: redirectedCommand;
|
|
925
|
+
const lines = [
|
|
926
|
+
'if [ -f /etc/profile ]; then . /etc/profile >/dev/null 2>&1 || true; fi',
|
|
927
|
+
'if [ -f "$HOME/.profile" ]; then . "$HOME/.profile" >/dev/null 2>&1 || true; fi',
|
|
928
|
+
// .bash_profile typically sources .bashrc itself; only source .bashrc
|
|
929
|
+
// directly when no .bash_profile exists to avoid double-running setup.
|
|
930
|
+
'if [ -f "$HOME/.bash_profile" ]; then . "$HOME/.bash_profile" >/dev/null 2>&1 || true; elif [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" >/dev/null 2>&1 || true; fi',
|
|
931
|
+
'if [ -f "$HOME/.zprofile" ]; then . "$HOME/.zprofile" >/dev/null 2>&1 || true; fi',
|
|
932
|
+
];
|
|
933
|
+
if (input.cwd) {
|
|
934
|
+
lines.push(`cd ${shellQuote(input.cwd)}`);
|
|
935
|
+
}
|
|
936
|
+
lines.push(finalLine);
|
|
937
|
+
return lines.join(" && ");
|
|
938
|
+
}
|
|
939
|
+
// The workspace remote dir is the confinement root for native file sync. It is
|
|
940
|
+
// recorded on the lease metadata at acquire/resume time; require it so a sync can
|
|
941
|
+
// never run without a concrete root to confine every sandbox path against.
|
|
942
|
+
function resolveSyncRemoteDir(lease) {
|
|
943
|
+
const remoteCwd = lease.metadata?.remoteCwd;
|
|
944
|
+
if (typeof remoteCwd === "string" && remoteCwd.trim().length > 0) {
|
|
945
|
+
return remoteCwd.trim();
|
|
946
|
+
}
|
|
947
|
+
throw new Error("Daytona file sync requires a workspace remote dir on the lease metadata.");
|
|
948
|
+
}
|
|
949
|
+
async function createSandbox(params, config, options = {}) {
|
|
950
|
+
const resourceRequestError = validateCreationTtl(config) ?? validateRuntimeResourceRequest(config);
|
|
951
|
+
if (resourceRequestError) {
|
|
952
|
+
throw new Error(resourceRequestError);
|
|
953
|
+
}
|
|
954
|
+
const client = createDaytonaClient(config);
|
|
955
|
+
let createConfig = config;
|
|
956
|
+
if ("resolveSnapshotIdentity" in params && params.resolveSnapshotIdentity && config.snapshot && !config.image) {
|
|
957
|
+
// This read happens only during explicit qualification. The SDK does not
|
|
958
|
+
// bound snapshot.get; a timed-out read must never continue into allocation.
|
|
959
|
+
const snapshot = await withLivenessTimeout("snapshot.identity", Math.min(config.timeoutMs || 10_000, 10_000), () => client.snapshot.get(config.snapshot));
|
|
960
|
+
if (!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(snapshot.id ?? "")
|
|
961
|
+
|| !snapshot.name || !snapshot.organizationId || !snapshot.createdAt
|
|
962
|
+
|| (config.snapshot !== snapshot.id && config.snapshot !== snapshot.name)
|
|
963
|
+
|| !Number.isFinite(Date.parse(String(snapshot.createdAt)))) {
|
|
964
|
+
throw new Error("Daytona did not return an immutable snapshot identity. Retry the connection probe or select Legacy runner.");
|
|
965
|
+
}
|
|
966
|
+
const identity = { provider: "daytona", requestedRef: config.snapshot,
|
|
967
|
+
id: snapshot.id, name: snapshot.name, organizationId: snapshot.organizationId, createdAt: new Date(snapshot.createdAt).toISOString() };
|
|
968
|
+
createConfig = { ...config, snapshot: identity.id };
|
|
969
|
+
options.onSnapshotIdentity?.(identity);
|
|
970
|
+
}
|
|
971
|
+
// The SDK can create a sandbox and then throw while waiting for it to start.
|
|
972
|
+
// Keep an attempt-specific provider name so that failure cannot lose ownership.
|
|
973
|
+
const attemptId = "creationOperationId" in params && params.creationOperationId ? params.creationOperationId : randomUUID();
|
|
974
|
+
if (!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(attemptId))
|
|
975
|
+
throw new Error("Invalid creation operation identity");
|
|
976
|
+
const name = `paperclip-create-${attemptId}`;
|
|
977
|
+
const labels = { ...buildSandboxLabels({
|
|
978
|
+
companyId: params.companyId,
|
|
979
|
+
environmentId: params.environmentId,
|
|
980
|
+
runId: "runId" in params ? params.runId : undefined,
|
|
981
|
+
setupSessionId: "sessionId" in params ? params.sessionId : undefined,
|
|
982
|
+
purpose: options.purpose,
|
|
983
|
+
reuseLease: config.reuseLease,
|
|
984
|
+
}), "paperclip-create-attempt": attemptId };
|
|
985
|
+
// The SDK mutates params.labels (for example, code-toolbox-language).
|
|
986
|
+
// Preserve our immutable ownership snapshot for validation and retry.
|
|
987
|
+
const createParams = { ...buildCreateParams(createConfig, { ...labels }), name };
|
|
988
|
+
const cleanup = {
|
|
989
|
+
providerLeaseId: name, companyId: params.companyId, environmentId: params.environmentId,
|
|
990
|
+
...("runId" in params ? { runId: params.runId } : {}),
|
|
991
|
+
attemptId, labels, accountFingerprint: sandboxAccountDiscriminator(config),
|
|
992
|
+
};
|
|
993
|
+
options.onCreateAttempt?.(cleanup);
|
|
994
|
+
const allocation = idleActivity.resource(providerActivityKey(params, config, name), true);
|
|
995
|
+
try {
|
|
996
|
+
const sandbox = await idleActivity.track(() => client.create(createParams, {
|
|
997
|
+
timeout: toTimeoutSeconds(config.timeoutMs),
|
|
998
|
+
}));
|
|
999
|
+
idleActivity.observe(allocation, providerActivityKey(params, config, sandbox.id));
|
|
1000
|
+
if (config.ttlMinutes != null) {
|
|
1001
|
+
cleanup.observedProviderLeaseId = sandbox.id;
|
|
1002
|
+
await confirmCreationTtl(sandbox, config);
|
|
1003
|
+
}
|
|
1004
|
+
return sandbox;
|
|
1005
|
+
}
|
|
1006
|
+
catch (createError) {
|
|
1007
|
+
if (options.claimCleanup && !options.claimCleanup())
|
|
1008
|
+
throw createError;
|
|
1009
|
+
// Observe the create failure before compensating deletion can stall or fail.
|
|
1010
|
+
const diagnostic = options.onCreateFailure?.();
|
|
1011
|
+
let removedState;
|
|
1012
|
+
try {
|
|
1013
|
+
// A not-found lookup after an uncertain create is not a deletion receipt:
|
|
1014
|
+
// the provider may still materialize the request. Keep the name in the
|
|
1015
|
+
// error so cleanup can be reconciled rather than declaring success.
|
|
1016
|
+
removedState = await destroyFailedCreation(config, cleanup, params.driverKey);
|
|
1017
|
+
}
|
|
1018
|
+
catch (cleanupError) {
|
|
1019
|
+
const status = creationHttpStatus(createError);
|
|
1020
|
+
throw new PluginEnvironmentCreationCleanupError([createError, cleanupError], `Daytona sandbox creation failed${status === undefined ? "" : ` (HTTP ${status})`}; cleanup could not be confirmed for ${name}`, cleanup, diagnostic);
|
|
1021
|
+
}
|
|
1022
|
+
if (removedState === "error" && diagnostic && creationHttpStatus(createError) === undefined) {
|
|
1023
|
+
throw new PluginEnvironmentAcquisitionError("Daytona could not start the sandbox; it was removed.", { ...diagnostic, providerState: "error" }, createError);
|
|
1024
|
+
}
|
|
1025
|
+
throw createError;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
async function confirmCreationTtl(sandbox, config) {
|
|
1029
|
+
if (config.ttlMinutes == null)
|
|
1030
|
+
return;
|
|
1031
|
+
await withLivenessTimeout("sandbox.refreshData", config.livenessTimeoutMs, () => sandbox.refreshData());
|
|
1032
|
+
const expiry = Date.parse(sandbox.autoDestroyAt ?? "");
|
|
1033
|
+
const nowMs = Date.now();
|
|
1034
|
+
if (!Number.isFinite(expiry) || expiry <= nowMs || expiry > nowMs + config.ttlMinutes * 60_000) {
|
|
1035
|
+
throw new Error("Daytona did not confirm the configured creation TTL.");
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
// Resolve by the immutable creation name, not through the admitted-lease cache:
|
|
1039
|
+
// the SDK's returned sandbox ID differs from this provisional name. Persist a
|
|
1040
|
+
// verified provider ID before host-driven deletion. Its later absence is then
|
|
1041
|
+
// conclusive, even if the deletion receipt or database update was lost.
|
|
1042
|
+
async function destroyFailedCreation(config, cleanup, driverKey, requireDurableObservation = false) {
|
|
1043
|
+
if (cleanup.providerLeaseId !== `paperclip-create-${cleanup.attemptId}` ||
|
|
1044
|
+
cleanup.accountFingerprint !== sandboxAccountDiscriminator(config) ||
|
|
1045
|
+
cleanup.labels["paperclip-provider"] !== "daytona" ||
|
|
1046
|
+
cleanup.labels["paperclip-create-attempt"] !== cleanup.attemptId ||
|
|
1047
|
+
cleanup.labels["paperclip-company-id"] !== cleanup.companyId ||
|
|
1048
|
+
cleanup.labels["paperclip-environment-id"] !== cleanup.environmentId ||
|
|
1049
|
+
(cleanup.runId !== undefined && cleanup.labels["paperclip-run-id"] !== cleanup.runId)) {
|
|
1050
|
+
throw new Error("Failed-create sandbox ownership does not match");
|
|
1051
|
+
}
|
|
1052
|
+
const identity = { driverKey, companyId: cleanup.companyId, environmentId: cleanup.environmentId };
|
|
1053
|
+
const allocation = idleActivity.resource(providerActivityKey(identity, config, cleanup.providerLeaseId), true);
|
|
1054
|
+
if (cleanup.observedProviderLeaseId) {
|
|
1055
|
+
idleActivity.observe(allocation, providerActivityKey(identity, config, cleanup.observedProviderLeaseId));
|
|
1056
|
+
}
|
|
1057
|
+
const client = createDaytonaClient(config);
|
|
1058
|
+
let orphan;
|
|
1059
|
+
const observationProof = idleActivity.proof(providerActivityKey(identity, config, cleanup.observedProviderLeaseId ?? cleanup.providerLeaseId));
|
|
1060
|
+
try {
|
|
1061
|
+
orphan = await withLivenessTimeout("sandbox.failedCreateLookup", 10_000, () => client.get(cleanup.observedProviderLeaseId ?? cleanup.providerLeaseId));
|
|
1062
|
+
}
|
|
1063
|
+
catch (error) {
|
|
1064
|
+
// A name that has never been observed may still materialize. An ID already
|
|
1065
|
+
// observed with exact ownership cannot materialize as a new allocation.
|
|
1066
|
+
if (cleanup.observedProviderLeaseId && error instanceof DaytonaNotFoundError) {
|
|
1067
|
+
idleActivity.confirm(observationProof, true);
|
|
1068
|
+
return undefined;
|
|
1069
|
+
}
|
|
1070
|
+
throw error;
|
|
1071
|
+
}
|
|
1072
|
+
if ((cleanup.observedProviderLeaseId && orphan.id !== cleanup.observedProviderLeaseId) ||
|
|
1073
|
+
orphan.name !== cleanup.providerLeaseId || Object.entries(cleanup.labels).some(([key, value]) => orphan.labels?.[key] !== value)) {
|
|
1074
|
+
throw new Error("Failed-create sandbox ownership does not match");
|
|
1075
|
+
}
|
|
1076
|
+
if (!cleanup.observedProviderLeaseId) {
|
|
1077
|
+
cleanup.observedProviderLeaseId = orphan.id;
|
|
1078
|
+
if (requireDurableObservation) {
|
|
1079
|
+
// No destructive call yet: the host journals the observation and retries.
|
|
1080
|
+
throw new PluginEnvironmentCreationCleanupError([], "Persist observed sandbox identity before cleanup", cleanup);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
idleActivity.observe(allocation, providerActivityKey(identity, config, orphan.id));
|
|
1084
|
+
const deletionProof = idleActivity.proof(providerActivityKey(identity, config, orphan.id));
|
|
1085
|
+
const observedState = typeof orphan.state === "string" && REPORTED_CREATE_STATES.has(orphan.state)
|
|
1086
|
+
? orphan.state : undefined;
|
|
1087
|
+
await withLivenessTimeout("sandbox.failedCreateDelete", 15_000, () => orphan.delete(10, true));
|
|
1088
|
+
idleActivity.confirm(deletionProof);
|
|
1089
|
+
return observedState;
|
|
1090
|
+
}
|
|
1091
|
+
// Daytona states reported as-is after a create deadline; any other is `other`.
|
|
1092
|
+
const REPORTED_CREATE_STATES = new Set([
|
|
1093
|
+
"creating", "pending_build", "building_snapshot", "pulling_snapshot", "starting", "started", "error", "build_failed",
|
|
1094
|
+
]);
|
|
1095
|
+
// One read-only lookup of the provisional creation name, so a create deadline
|
|
1096
|
+
// records where the provider left the allocation. It neither deletes nor
|
|
1097
|
+
// records an observed ID: the host-owned cleanup envelope is unchanged.
|
|
1098
|
+
async function lookupCreation(config, cleanup) {
|
|
1099
|
+
try {
|
|
1100
|
+
const sandbox = await withLivenessTimeout("sandbox.createStateLookup", 5_000, () => createDaytonaClient(config).get(cleanup.providerLeaseId));
|
|
1101
|
+
if (!sandbox || sandbox.name !== cleanup.providerLeaseId || typeof sandbox.state !== "string" ||
|
|
1102
|
+
Object.entries(cleanup.labels).some(([key, value]) => sandbox.labels?.[key] !== value))
|
|
1103
|
+
return { state: "unavailable" };
|
|
1104
|
+
return { state: REPORTED_CREATE_STATES.has(sandbox.state) ? sandbox.state : "other", sandbox };
|
|
1105
|
+
}
|
|
1106
|
+
catch (error) {
|
|
1107
|
+
return { state: error instanceof DaytonaNotFoundError ? "absent" : "unavailable" };
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
async function observeCreateState(config, cleanup) {
|
|
1111
|
+
return (await lookupCreation(config, cleanup)).state;
|
|
1112
|
+
}
|
|
1113
|
+
const DAYTONA_CREATE_ATTEMPT_MS = 90_000;
|
|
1114
|
+
const DAYTONA_ACQUIRE_ATTEMPT_BUDGET_MS = 180_000;
|
|
1115
|
+
const SNAPSHOT_PREPARATION_STATES = new Set([
|
|
1116
|
+
"pending_build", "building_snapshot", "pulling_snapshot",
|
|
1117
|
+
]);
|
|
1118
|
+
function providerActivityKey(identity, config, providerLeaseId) {
|
|
1119
|
+
return sandboxHandleCacheKey({ ...identity, config, providerLeaseId });
|
|
1120
|
+
}
|
|
1121
|
+
function confirmedTermination(scope, state, proof) {
|
|
1122
|
+
idleActivity.confirm(proof);
|
|
1123
|
+
return { providerLeaseId: scope.providerLeaseId, state };
|
|
1124
|
+
}
|
|
1125
|
+
// Non-secret provider/account fingerprint. Uses the *resolved* key (config or
|
|
1126
|
+
// DAYTONA_API_KEY env fallback) so an env-provided credential is still scoped,
|
|
1127
|
+
// but only its sha256 digest — never the key itself — enters the cache key (C1/C6).
|
|
1128
|
+
function sandboxAccountDiscriminator(config) {
|
|
1129
|
+
const resolvedApiKey = config.apiKey ?? process.env.DAYTONA_API_KEY?.trim() ?? null;
|
|
1130
|
+
return createHash("sha256")
|
|
1131
|
+
.update(stableStringify({
|
|
1132
|
+
apiUrl: config.apiUrl,
|
|
1133
|
+
// Target is a creation placement hint, not account identity: the SDK
|
|
1134
|
+
// resolves existing sandboxes by ID. Lease metadata fills an omitted
|
|
1135
|
+
// target with the actual region, which must not split admission state.
|
|
1136
|
+
apiKey: resolvedApiKey,
|
|
1137
|
+
}))
|
|
1138
|
+
.digest("hex");
|
|
1139
|
+
}
|
|
1140
|
+
function sandboxHandleCacheKey(scope) {
|
|
1141
|
+
return stableStringify({
|
|
1142
|
+
driverKey: scope.driverKey,
|
|
1143
|
+
companyId: scope.companyId,
|
|
1144
|
+
environmentId: scope.environmentId,
|
|
1145
|
+
providerLeaseId: scope.providerLeaseId,
|
|
1146
|
+
account: sandboxAccountDiscriminator(scope.config),
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
function assertHandleMatchesLease(sandbox, providerLeaseId) {
|
|
1150
|
+
// C2: a handle must never stand in for a different sandbox than the lease
|
|
1151
|
+
// asked for. Belt-and-suspenders against a provider that returns a renamed or
|
|
1152
|
+
// substituted sandbox, and against any future key collision.
|
|
1153
|
+
if (sandbox.id !== providerLeaseId) {
|
|
1154
|
+
throw new Error(`Daytona sandbox handle mismatch: handle ${sandbox.id} does not belong to lease ${providerLeaseId}.`);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
// A cached `Sandbox` carries the provider state captured when it was last
|
|
1158
|
+
// fetched/refreshed. Daytona auto-stops an idle sandbox after `autoStopInterval`
|
|
1159
|
+
// minutes, at which point that snapshot ("started") no longer matches reality
|
|
1160
|
+
// and `ensureSandboxStarted` would wrongly skip the restart, sending every
|
|
1161
|
+
// subsequent exec/sync at a stopped sandbox. Before reusing a handle that has
|
|
1162
|
+
// gone untouched for this fraction of the auto-stop interval we re-read the live
|
|
1163
|
+
// state so the restart decision is made against the truth. Reusing a handle for
|
|
1164
|
+
// an operation resets Daytona's idle clock, so an actively-used lease stays well
|
|
1165
|
+
// inside the window and never pays the refresh — only a lease resumed after an
|
|
1166
|
+
// idle gap does.
|
|
1167
|
+
const STALE_HANDLE_REFRESH_SAFETY_FRACTION = 0.5;
|
|
1168
|
+
function staleHandleRefreshThresholdMs(autoStopIntervalMinutes) {
|
|
1169
|
+
// Auto-stop disabled (0 / null): the provider never stops the sandbox out from
|
|
1170
|
+
// under a live handle, so the started snapshot stays valid until we evict it
|
|
1171
|
+
// and no refresh is warranted.
|
|
1172
|
+
if (autoStopIntervalMinutes == null || autoStopIntervalMinutes <= 0)
|
|
1173
|
+
return null;
|
|
1174
|
+
return Math.floor(autoStopIntervalMinutes * 60_000 * STALE_HANDLE_REFRESH_SAFETY_FRACTION);
|
|
1175
|
+
}
|
|
1176
|
+
const sandboxHandleTeardownGates = (() => {
|
|
1177
|
+
const gates = new Map();
|
|
1178
|
+
function begin(scope) {
|
|
1179
|
+
idleActivity.resource(sandboxHandleCacheKey(scope));
|
|
1180
|
+
const key = sandboxHandleCacheKey(scope);
|
|
1181
|
+
const existing = gates.get(key);
|
|
1182
|
+
if (existing) {
|
|
1183
|
+
existing.refCount += 1;
|
|
1184
|
+
return existing;
|
|
1185
|
+
}
|
|
1186
|
+
let release;
|
|
1187
|
+
const gate = {
|
|
1188
|
+
promise: new Promise((resolve) => {
|
|
1189
|
+
release = resolve;
|
|
1190
|
+
}),
|
|
1191
|
+
release: () => release(),
|
|
1192
|
+
refCount: 1,
|
|
1193
|
+
};
|
|
1194
|
+
gates.set(key, gate);
|
|
1195
|
+
return gate;
|
|
1196
|
+
}
|
|
1197
|
+
function current(scope) {
|
|
1198
|
+
return gates.get(sandboxHandleCacheKey(scope)) ?? null;
|
|
1199
|
+
}
|
|
1200
|
+
function end(scope, gate) {
|
|
1201
|
+
const key = sandboxHandleCacheKey(scope);
|
|
1202
|
+
gate.refCount -= 1;
|
|
1203
|
+
if (gate.refCount > 0)
|
|
1204
|
+
return;
|
|
1205
|
+
if (gates.get(key) === gate) {
|
|
1206
|
+
gates.delete(key);
|
|
1207
|
+
}
|
|
1208
|
+
gate.release();
|
|
1209
|
+
}
|
|
1210
|
+
function reset() {
|
|
1211
|
+
gates.clear();
|
|
1212
|
+
}
|
|
1213
|
+
return { begin, current, end, reset };
|
|
1214
|
+
})();
|
|
1215
|
+
const sandboxHandleActivityGates = (() => {
|
|
1216
|
+
const gates = new Map();
|
|
1217
|
+
async function begin(scope) {
|
|
1218
|
+
const key = sandboxHandleCacheKey(scope);
|
|
1219
|
+
const existing = gates.get(key);
|
|
1220
|
+
if (existing) {
|
|
1221
|
+
existing.refCount += 1;
|
|
1222
|
+
return existing;
|
|
1223
|
+
}
|
|
1224
|
+
let release;
|
|
1225
|
+
const gate = {
|
|
1226
|
+
promise: new Promise((resolve) => {
|
|
1227
|
+
release = resolve;
|
|
1228
|
+
}),
|
|
1229
|
+
release: () => release(),
|
|
1230
|
+
refCount: 1,
|
|
1231
|
+
};
|
|
1232
|
+
gates.set(key, gate);
|
|
1233
|
+
return gate;
|
|
1234
|
+
}
|
|
1235
|
+
async function waitForIdle(scope) {
|
|
1236
|
+
const gate = gates.get(sandboxHandleCacheKey(scope));
|
|
1237
|
+
if (!gate)
|
|
1238
|
+
return;
|
|
1239
|
+
await gate.promise;
|
|
1240
|
+
}
|
|
1241
|
+
function end(scope, gate) {
|
|
1242
|
+
const key = sandboxHandleCacheKey(scope);
|
|
1243
|
+
gate.refCount -= 1;
|
|
1244
|
+
if (gate.refCount > 0)
|
|
1245
|
+
return;
|
|
1246
|
+
if (gates.get(key) === gate) {
|
|
1247
|
+
gates.delete(key);
|
|
1248
|
+
}
|
|
1249
|
+
gate.release();
|
|
1250
|
+
}
|
|
1251
|
+
function reset() {
|
|
1252
|
+
gates.clear();
|
|
1253
|
+
}
|
|
1254
|
+
function isActive(scope) {
|
|
1255
|
+
return gates.has(sandboxHandleCacheKey(scope));
|
|
1256
|
+
}
|
|
1257
|
+
return { begin, waitForIdle, isActive, end, reset };
|
|
1258
|
+
})();
|
|
1259
|
+
const sandboxHandleLeaseAdmissionStates = (() => {
|
|
1260
|
+
const states = new Map();
|
|
1261
|
+
function key(scope) {
|
|
1262
|
+
return sandboxHandleCacheKey(scope);
|
|
1263
|
+
}
|
|
1264
|
+
function open(scope) {
|
|
1265
|
+
states.set(key(scope), false);
|
|
1266
|
+
}
|
|
1267
|
+
function close(scope) {
|
|
1268
|
+
states.set(key(scope), true);
|
|
1269
|
+
}
|
|
1270
|
+
function isClosed(scope) {
|
|
1271
|
+
return states.get(key(scope)) === true;
|
|
1272
|
+
}
|
|
1273
|
+
function reset() {
|
|
1274
|
+
states.clear();
|
|
1275
|
+
}
|
|
1276
|
+
return { open, close, isClosed, reset };
|
|
1277
|
+
})();
|
|
1278
|
+
async function withSandboxActivityGate(scope, fn, options = {}) {
|
|
1279
|
+
while (true) {
|
|
1280
|
+
if (!options.allowClosed && sandboxHandleLeaseAdmissionStates.isClosed(scope)) {
|
|
1281
|
+
throw new Error(`Daytona sandbox lease ${scope.providerLeaseId} is no longer active.`);
|
|
1282
|
+
}
|
|
1283
|
+
const teardownGate = sandboxHandleTeardownGates.current(scope);
|
|
1284
|
+
if (teardownGate) {
|
|
1285
|
+
if (options.traceLeaseWait)
|
|
1286
|
+
await traceLeaseStep("lease.wait_for_teardown", () => teardownGate.promise);
|
|
1287
|
+
else
|
|
1288
|
+
await teardownGate.promise;
|
|
1289
|
+
if (!options.allowClosed && sandboxHandleLeaseAdmissionStates.isClosed(scope)) {
|
|
1290
|
+
throw new Error(`Daytona sandbox lease ${scope.providerLeaseId} is no longer active.`);
|
|
1291
|
+
}
|
|
1292
|
+
continue;
|
|
1293
|
+
}
|
|
1294
|
+
const activityGate = await sandboxHandleActivityGates.begin(scope);
|
|
1295
|
+
try {
|
|
1296
|
+
// A teardown can still begin between the initial check above and the
|
|
1297
|
+
// activity-gate admission. If that happens, back out and wait for the
|
|
1298
|
+
// teardown to finish instead of proceeding into a race with cleanup.
|
|
1299
|
+
if (sandboxHandleTeardownGates.current(scope)) {
|
|
1300
|
+
continue;
|
|
1301
|
+
}
|
|
1302
|
+
if (!options.allowClosed && sandboxHandleLeaseAdmissionStates.isClosed(scope)) {
|
|
1303
|
+
throw new Error(`Daytona sandbox lease ${scope.providerLeaseId} is no longer active.`);
|
|
1304
|
+
}
|
|
1305
|
+
idleActivity.resource(sandboxHandleCacheKey(scope));
|
|
1306
|
+
return await fn();
|
|
1307
|
+
}
|
|
1308
|
+
finally {
|
|
1309
|
+
sandboxHandleActivityGates.end(scope, activityGate);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
const sandboxHandleCache = (() => {
|
|
1314
|
+
const entries = new Map();
|
|
1315
|
+
function markFresh(scope) {
|
|
1316
|
+
const entry = entries.get(sandboxHandleCacheKey(scope));
|
|
1317
|
+
if (entry) {
|
|
1318
|
+
entry.verifiedAtMs = handleFreshnessNow();
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
async function get(scope, options = {}) {
|
|
1322
|
+
const key = sandboxHandleCacheKey(scope);
|
|
1323
|
+
const entry = entries.get(key);
|
|
1324
|
+
if (entry) {
|
|
1325
|
+
// The warm handle cache holds an entry, so this lookup serves the handle
|
|
1326
|
+
// without a `client.get` round trip. Report the cache decision now.
|
|
1327
|
+
options.onCacheDecision?.(true);
|
|
1328
|
+
const sandbox = await entry.sandbox;
|
|
1329
|
+
// Re-assert on every hit; evict + fail closed on any mismatch (C2).
|
|
1330
|
+
try {
|
|
1331
|
+
assertHandleMatchesLease(sandbox, scope.providerLeaseId);
|
|
1332
|
+
}
|
|
1333
|
+
catch (error) {
|
|
1334
|
+
entries.delete(key);
|
|
1335
|
+
throw error;
|
|
1336
|
+
}
|
|
1337
|
+
// Refresh the live provider state if the handle may have been auto-stopped
|
|
1338
|
+
// since we last confirmed it, so the cached `state` snapshot can't hide a
|
|
1339
|
+
// provider-initiated stop from `ensureSandboxStarted`. A failed refresh
|
|
1340
|
+
// means the handle is no longer trustworthy — evict and fail closed.
|
|
1341
|
+
const thresholdMs = staleHandleRefreshThresholdMs(scope.config.autoStopInterval);
|
|
1342
|
+
if (thresholdMs != null && handleFreshnessNow() - entry.verifiedAtMs >= thresholdMs) {
|
|
1343
|
+
try {
|
|
1344
|
+
await withLivenessTimeout("sandbox.refreshData", scope.config.livenessTimeoutMs, () => sandbox.refreshData());
|
|
1345
|
+
}
|
|
1346
|
+
catch (error) {
|
|
1347
|
+
entries.delete(key);
|
|
1348
|
+
throw error;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
return sandbox;
|
|
1352
|
+
}
|
|
1353
|
+
// The warm handle cache holds no entry, so this lookup calls `client.get`.
|
|
1354
|
+
// Report the cache decision now, before the single-flight populate.
|
|
1355
|
+
options.onCacheDecision?.(false);
|
|
1356
|
+
// Single-flight: the first miss stores the in-flight promise under the
|
|
1357
|
+
// composite key so concurrent misses on the same lease share one `client.get`
|
|
1358
|
+
// instead of double-fetching. The promise lives only under this key (C5).
|
|
1359
|
+
const populate = (async () => {
|
|
1360
|
+
const client = createDaytonaClient(scope.config);
|
|
1361
|
+
const sandbox = await client.get(scope.providerLeaseId);
|
|
1362
|
+
assertHandleMatchesLease(sandbox, scope.providerLeaseId);
|
|
1363
|
+
return sandbox;
|
|
1364
|
+
})();
|
|
1365
|
+
const populated = { sandbox: populate, verifiedAtMs: handleFreshnessNow() };
|
|
1366
|
+
entries.set(key, populated);
|
|
1367
|
+
try {
|
|
1368
|
+
const sandbox = await populate;
|
|
1369
|
+
return sandbox;
|
|
1370
|
+
}
|
|
1371
|
+
catch (error) {
|
|
1372
|
+
// A rejected populate (NotFound, network, id mismatch) must never remain
|
|
1373
|
+
// cached (C4/C5). Guard against clobbering a newer entry under the key.
|
|
1374
|
+
if (entries.get(key) === populated) {
|
|
1375
|
+
entries.delete(key);
|
|
1376
|
+
}
|
|
1377
|
+
throw error;
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
// Seed the cache with a handle the caller already holds (e.g. the fresh handle
|
|
1381
|
+
// from `createSandbox` on a cold acquire), so the next `get` under the same
|
|
1382
|
+
// scope reuses it instead of paying a real `client.get`. The seed must land
|
|
1383
|
+
// under the exact composite key the reader uses, or the reader misses and the
|
|
1384
|
+
// saved round trip is lost. Assert the handle belongs to the lease so a caller
|
|
1385
|
+
// that builds a wrong scope fails loudly here instead of caching a foreign
|
|
1386
|
+
// handle.
|
|
1387
|
+
function seed(scope, sandbox) {
|
|
1388
|
+
assertHandleMatchesLease(sandbox, scope.providerLeaseId);
|
|
1389
|
+
entries.set(sandboxHandleCacheKey(scope), {
|
|
1390
|
+
sandbox: Promise.resolve(sandbox),
|
|
1391
|
+
verifiedAtMs: handleFreshnessNow(),
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
function clear(scope) {
|
|
1395
|
+
entries.delete(sandboxHandleCacheKey(scope));
|
|
1396
|
+
}
|
|
1397
|
+
function reset() {
|
|
1398
|
+
entries.clear();
|
|
1399
|
+
}
|
|
1400
|
+
// Resolve a cached sandbox by its provider lease id alone. The
|
|
1401
|
+
// login pseudo-terminal open carries only the provider lease id, not the full
|
|
1402
|
+
// scope, so this scans the cached handles for the one whose `sandbox.id`
|
|
1403
|
+
// matches. The lease was cached on acquire in the same worker, so the scan is
|
|
1404
|
+
// a hit for a live login lease. It returns null when no cached handle matches,
|
|
1405
|
+
// so the caller fails closed.
|
|
1406
|
+
async function findByProviderLeaseId(providerLeaseId) {
|
|
1407
|
+
if (!providerLeaseId)
|
|
1408
|
+
return null;
|
|
1409
|
+
for (const entry of entries.values()) {
|
|
1410
|
+
let sandbox;
|
|
1411
|
+
try {
|
|
1412
|
+
sandbox = await entry.sandbox;
|
|
1413
|
+
}
|
|
1414
|
+
catch {
|
|
1415
|
+
continue;
|
|
1416
|
+
}
|
|
1417
|
+
if (sandbox.id === providerLeaseId)
|
|
1418
|
+
return sandbox;
|
|
1419
|
+
}
|
|
1420
|
+
return null;
|
|
1421
|
+
}
|
|
1422
|
+
return { get, seed, clear, reset, markFresh, findByProviderLeaseId };
|
|
1423
|
+
})();
|
|
1424
|
+
// Preview credentials can rotate without a sandbox restart, so they must not
|
|
1425
|
+
// define endpoint generation. Daytona's lifecycle revision does: refreshData
|
|
1426
|
+
// updates `updatedAt` after stop/start. When Daytona does not expose a
|
|
1427
|
+
// lifecycle revision, the in-memory generation remains stable for the worker.
|
|
1428
|
+
const runnerIngressGenerationStore = (() => {
|
|
1429
|
+
const entries = new Map();
|
|
1430
|
+
function get(sandbox) {
|
|
1431
|
+
const revision = sandbox.updatedAt ?? sandbox.createdAt ?? null;
|
|
1432
|
+
const current = entries.get(sandbox.id);
|
|
1433
|
+
if (current && current.revision === revision)
|
|
1434
|
+
return current.generation;
|
|
1435
|
+
const generation = createHash("sha256")
|
|
1436
|
+
.update(`${sandbox.id}\0${revision ?? randomUUID()}`)
|
|
1437
|
+
.digest("hex");
|
|
1438
|
+
entries.set(sandbox.id, { revision, generation });
|
|
1439
|
+
return generation;
|
|
1440
|
+
}
|
|
1441
|
+
function reset() {
|
|
1442
|
+
entries.clear();
|
|
1443
|
+
}
|
|
1444
|
+
return { get, reset };
|
|
1445
|
+
})();
|
|
1446
|
+
// Advisory writable-set store. It holds, per lease scope, the sandbox
|
|
1447
|
+
// directories that a sync operation declared read-write (`access: "rw"`). The
|
|
1448
|
+
// store is advisory and best-effort in-memory state: it adds no security (the
|
|
1449
|
+
// ephemeral sandbox stays the only boundary). The store is keyed the same way
|
|
1450
|
+
// as `sandboxHandleCache`, by `sandboxHandleCacheKey(scope)`.
|
|
1451
|
+
//
|
|
1452
|
+
// The command path no longer reads this set. The provider dropped the advisory
|
|
1453
|
+
// `bwrap` wrapper that once bound these directories read-write for real-time
|
|
1454
|
+
// feedback (see `DIRECTORY-CONSTRAINT-FINDINGS.md`). The store still records the
|
|
1455
|
+
// read-write set, so a future isolation wrapper for the session can consume it
|
|
1456
|
+
// without a new sync change.
|
|
1457
|
+
const sandboxHandleWritableDirs = (() => {
|
|
1458
|
+
const dirsByKey = new Map();
|
|
1459
|
+
// Record the read-write destination directory of every `access: "rw"`
|
|
1460
|
+
// mapping. Skip read-only mappings (`access` absent or `"ro"`). Read-only is
|
|
1461
|
+
// the safe default for an advisory signal.
|
|
1462
|
+
//
|
|
1463
|
+
// A workspace, git-history, or asset mapping uploads a tar archive, so its
|
|
1464
|
+
// `targetPath` is the staging archive under the runtime root, not the directory
|
|
1465
|
+
// that the post-upload extract command fills. For those mappings the author
|
|
1466
|
+
// sets `writablePath` to the final destination directory, so this records the
|
|
1467
|
+
// real read-write destination, not the staging parent. When `writablePath` is
|
|
1468
|
+
// absent the mapping writes `targetPath` in place, so the parent directory of
|
|
1469
|
+
// `targetPath` is the destination.
|
|
1470
|
+
function recordWritableTargets(scope, operations) {
|
|
1471
|
+
const key = sandboxHandleCacheKey(scope);
|
|
1472
|
+
for (const operation of operations) {
|
|
1473
|
+
for (const mapping of operation.files) {
|
|
1474
|
+
if (mapping.access !== "rw")
|
|
1475
|
+
continue;
|
|
1476
|
+
let dirs = dirsByKey.get(key);
|
|
1477
|
+
if (!dirs) {
|
|
1478
|
+
dirs = new Set();
|
|
1479
|
+
dirsByKey.set(key, dirs);
|
|
1480
|
+
}
|
|
1481
|
+
dirs.add(mapping.writablePath ?? path.posix.dirname(mapping.targetPath));
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
function get(scope) {
|
|
1486
|
+
return dirsByKey.get(sandboxHandleCacheKey(scope)) ?? new Set();
|
|
1487
|
+
}
|
|
1488
|
+
function reset() {
|
|
1489
|
+
dirsByKey.clear();
|
|
1490
|
+
}
|
|
1491
|
+
return { recordWritableTargets, get, reset };
|
|
1492
|
+
})();
|
|
1493
|
+
// Per-lease Daytona session-id store. It holds, per lease scope, the id of the
|
|
1494
|
+
// one persistent session the exec hook opened for that lease. The store is
|
|
1495
|
+
// keyed the same way as `sandboxHandleCache`, by `sandboxHandleCacheKey(scope)`.
|
|
1496
|
+
// The exec hook creates one session on a cache miss and records its id here. The
|
|
1497
|
+
// teardown hooks delete the session and clear the id. A resume clears the id,
|
|
1498
|
+
// because a restarted sandbox loses its session shell, so the next exec must
|
|
1499
|
+
// open a fresh session. The store is process-memory only; it holds an id string,
|
|
1500
|
+
// never a handle, a credential, or a command.
|
|
1501
|
+
const sandboxHandleSessionStore = (() => {
|
|
1502
|
+
const idByKey = new Map();
|
|
1503
|
+
// In-flight session creates, keyed the same way as `idByKey`. A create records
|
|
1504
|
+
// its promise here for the time it runs, then removes it. The map lets two
|
|
1505
|
+
// overlapping first commands for one lease share one create. See `runSingle`.
|
|
1506
|
+
const pendingByKey = new Map();
|
|
1507
|
+
function get(scope) {
|
|
1508
|
+
return idByKey.get(sandboxHandleCacheKey(scope));
|
|
1509
|
+
}
|
|
1510
|
+
function set(scope, sessionId) {
|
|
1511
|
+
idByKey.set(sandboxHandleCacheKey(scope), sessionId);
|
|
1512
|
+
}
|
|
1513
|
+
function clear(scope) {
|
|
1514
|
+
idByKey.delete(sandboxHandleCacheKey(scope));
|
|
1515
|
+
}
|
|
1516
|
+
// Single-flight guard for the first-command session create. Two overlapping
|
|
1517
|
+
// first commands for one lease must open at most one live session. The first
|
|
1518
|
+
// caller runs `create` and records its in-flight promise; every concurrent
|
|
1519
|
+
// caller awaits the same promise instead of a second `create`. The store keeps
|
|
1520
|
+
// the promise only while `create` runs, then removes it, so a later command
|
|
1521
|
+
// (for example, after a resume clears the id) can open a fresh session. A
|
|
1522
|
+
// failed `create` removes the promise too, so the next command retries.
|
|
1523
|
+
function runSingle(scope, create) {
|
|
1524
|
+
const key = sandboxHandleCacheKey(scope);
|
|
1525
|
+
const inFlight = pendingByKey.get(key);
|
|
1526
|
+
if (inFlight)
|
|
1527
|
+
return inFlight;
|
|
1528
|
+
const promise = create();
|
|
1529
|
+
pendingByKey.set(key, promise);
|
|
1530
|
+
const settle = () => {
|
|
1531
|
+
pendingByKey.delete(key);
|
|
1532
|
+
};
|
|
1533
|
+
promise.then(settle, settle);
|
|
1534
|
+
return promise;
|
|
1535
|
+
}
|
|
1536
|
+
function reset() {
|
|
1537
|
+
idByKey.clear();
|
|
1538
|
+
pendingByKey.clear();
|
|
1539
|
+
}
|
|
1540
|
+
return { get, set, clear, runSingle, reset };
|
|
1541
|
+
})();
|
|
1542
|
+
/**
|
|
1543
|
+
* Test seam: clear the process-scoped handle cache between tests so a handle
|
|
1544
|
+
* memoized under a reused composite key in one test never leaks into the next.
|
|
1545
|
+
* Not used in production.
|
|
1546
|
+
*/
|
|
1547
|
+
export function __resetDaytonaSandboxHandleCacheForTest() {
|
|
1548
|
+
idleActivity.resetForTest();
|
|
1549
|
+
sandboxHandleCache.reset();
|
|
1550
|
+
sandboxHandleTeardownGates.reset();
|
|
1551
|
+
sandboxHandleActivityGates.reset();
|
|
1552
|
+
sandboxHandleLeaseAdmissionStates.reset();
|
|
1553
|
+
sandboxHandleWritableDirs.reset();
|
|
1554
|
+
forcedSandboxStops.clear();
|
|
1555
|
+
sandboxHandleSessionStore.reset();
|
|
1556
|
+
runnerIngressGenerationStore.reset();
|
|
1557
|
+
retiredDaytonaDuplexChannelByRoute.clear();
|
|
1558
|
+
}
|
|
1559
|
+
/**
|
|
1560
|
+
* Test seam: read the advisory writable directories recorded for a sync scope.
|
|
1561
|
+
* The caller passes the same `onEnvironmentSyncIn` inputs, so this rebuilds the
|
|
1562
|
+
* exact scope key the hook used. Not used in production.
|
|
1563
|
+
*/
|
|
1564
|
+
export function __getDaytonaWritableDirsForTest(input) {
|
|
1565
|
+
const scope = {
|
|
1566
|
+
driverKey: input.driverKey,
|
|
1567
|
+
companyId: input.companyId,
|
|
1568
|
+
environmentId: input.environmentId,
|
|
1569
|
+
providerLeaseId: input.lease.providerLeaseId ?? "",
|
|
1570
|
+
config: parseDriverConfig(input.config),
|
|
1571
|
+
};
|
|
1572
|
+
return [...sandboxHandleWritableDirs.get(scope)];
|
|
1573
|
+
}
|
|
1574
|
+
async function getSandbox(scope, options = {}) {
|
|
1575
|
+
return await sandboxHandleCache.get(scope, options);
|
|
1576
|
+
}
|
|
1577
|
+
async function getSandboxOrNull(scope, options = {}) {
|
|
1578
|
+
const proof = idleActivity.proof(sandboxHandleCacheKey(scope));
|
|
1579
|
+
try {
|
|
1580
|
+
return await getSandbox(scope, options);
|
|
1581
|
+
}
|
|
1582
|
+
catch (error) {
|
|
1583
|
+
if (error instanceof DaytonaNotFoundError) {
|
|
1584
|
+
idleActivity.confirm(proof, true);
|
|
1585
|
+
return null;
|
|
1586
|
+
}
|
|
1587
|
+
throw error;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
function evictSandboxHandle(scope) {
|
|
1591
|
+
sandboxHandleCache.clear(scope);
|
|
1592
|
+
}
|
|
1593
|
+
// Return the persistent session id for a lease, and open one session on a cache
|
|
1594
|
+
// miss. The exec hook calls this once per command. The first call opens the
|
|
1595
|
+
// session through `createSession` and records its id; every later call returns
|
|
1596
|
+
// the stored id, so one lease runs every command in one persistent shell. The
|
|
1597
|
+
// provider never falls back to a one-shot command to open a session.
|
|
1598
|
+
//
|
|
1599
|
+
// Leak bound: the Daytona SDK exposes NO per-session TTL. `createSession` takes
|
|
1600
|
+
// only a session id, and there is no session update or expiry field. Two
|
|
1601
|
+
// backstops bound the session against a leak. First, `teardownSession` runs a
|
|
1602
|
+
// guaranteed `deleteSession` in every teardown hook's `try/finally`. Second, the
|
|
1603
|
+
// sandbox-level `autoStopInterval` (15 minutes idle by default) stops the
|
|
1604
|
+
// sandbox and, with it, every session; the `autoArchiveInterval` and
|
|
1605
|
+
// `autoDeleteInterval` intervals then reap the sandbox. A session is a shell
|
|
1606
|
+
// inside its sandbox and cannot outlive it.
|
|
1607
|
+
async function getOrCreateSession(sandbox, scope) {
|
|
1608
|
+
const existing = sandboxHandleSessionStore.get(scope);
|
|
1609
|
+
if (existing)
|
|
1610
|
+
return existing;
|
|
1611
|
+
// Single-flight the first-command create. Two overlapping first commands for
|
|
1612
|
+
// one lease share one create promise, so the lease opens at most one live
|
|
1613
|
+
// session. The guard checks and starts the create in one synchronous step, so
|
|
1614
|
+
// no second command can slip in between the store read and the create start.
|
|
1615
|
+
return sandboxHandleSessionStore.runSingle(scope, async () => {
|
|
1616
|
+
const sessionId = `paperclip-${randomUUID()}`;
|
|
1617
|
+
// Wrap the session create in a short `session.open` provider span. The span
|
|
1618
|
+
// carries no session id and no command text, only the provider family. The
|
|
1619
|
+
// host maps the name to `sandbox.daytona.session.open`.
|
|
1620
|
+
// `session.open` span: create the one persistent Daytona session for a lease,
|
|
1621
|
+
// on the first in-run command — `sandbox.process.createSession`.
|
|
1622
|
+
await withProviderSpan({
|
|
1623
|
+
name: "session.open",
|
|
1624
|
+
run: () => sandbox.process.createSession(sessionId),
|
|
1625
|
+
});
|
|
1626
|
+
sandboxHandleSessionStore.set(scope, sessionId);
|
|
1627
|
+
return sessionId;
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
// Delete the persistent session for a lease and clear its stored id. Each
|
|
1631
|
+
// teardown hook calls this inside its `try/finally`, so a failed delete never
|
|
1632
|
+
// skips the rest of teardown. A failed delete logs the session id and the error
|
|
1633
|
+
// loudly and does not throw past teardown; the sandbox stop or delete that
|
|
1634
|
+
// follows removes the session shell anyway, and the sandbox-level
|
|
1635
|
+
// `autoStopInterval` / `autoDeleteInterval` / `autoArchiveInterval` backstops
|
|
1636
|
+
// bound any residual state (the session API exposes no per-session TTL). The
|
|
1637
|
+
// store id is always cleared, so no orphan id survives.
|
|
1638
|
+
async function teardownSession(sandbox, scope) {
|
|
1639
|
+
const sessionId = sandboxHandleSessionStore.get(scope);
|
|
1640
|
+
if (!sessionId)
|
|
1641
|
+
return;
|
|
1642
|
+
// Retire the captured identity before awaiting the provider. A late response
|
|
1643
|
+
// must not clear a new session created after this lease is resumed.
|
|
1644
|
+
sandboxHandleSessionStore.clear(scope);
|
|
1645
|
+
try {
|
|
1646
|
+
// Wrap the session delete in a short `session.close` provider span. The
|
|
1647
|
+
// host maps the name to `sandbox.daytona.session.close`.
|
|
1648
|
+
// `session.close` span: delete that persistent session on lease release —
|
|
1649
|
+
// `sandbox.process.deleteSession`.
|
|
1650
|
+
await withProviderSpan({
|
|
1651
|
+
name: "session.close",
|
|
1652
|
+
run: () => sandbox.process.deleteSession(sessionId),
|
|
1653
|
+
});
|
|
1654
|
+
}
|
|
1655
|
+
catch (error) {
|
|
1656
|
+
console.error(`Failed to delete Daytona session ${sessionId} during teardown: ${formatErrorMessage(error)}`);
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
// One-shot command execution via Daytona's `process.executeCommand`. This is the
|
|
1660
|
+
// fallback path the exec hook uses when the session model is off. The command
|
|
1661
|
+
// runs plain as the unprivileged sandbox user; the provider no longer wraps a
|
|
1662
|
+
// user command with the advisory `bwrap` wrapper on any path.
|
|
1663
|
+
//
|
|
1664
|
+
// `executeCommand` returns combined stdout+stderr in `result`. We surface that
|
|
1665
|
+
// as `stdout` and leave `stderr` empty; callers that grep for error messages
|
|
1666
|
+
// still see them in `stdout`.
|
|
1667
|
+
async function executeOneShot(sandbox, params, config) {
|
|
1668
|
+
const gitNet = isGitNetworkCommand(params.command, params.args ?? []);
|
|
1669
|
+
const timeoutMs = resolveTimeoutMs(params.timeoutMs, config);
|
|
1670
|
+
const effectiveTimeoutMs = gitNet ? Math.min(timeoutMs, GIT_NETWORK_TIMEOUT_MS) : timeoutMs;
|
|
1671
|
+
const timeoutSeconds = toTimeoutSeconds(effectiveTimeoutMs);
|
|
1672
|
+
const stdinPath = params.stdin != null ? `/tmp/paperclip-stdin-${randomUUID()}` : null;
|
|
1673
|
+
// Marks the start of the `executeCommand` REST round-trip. Hoisted out of the
|
|
1674
|
+
// try so the timeout path below can still attribute the exec wall-time it spent
|
|
1675
|
+
// before the SDK aborted — a slow failed exec is exactly what we want to
|
|
1676
|
+
// measure. Stays null until we are about to call `executeCommand`, so a timeout
|
|
1677
|
+
// during the earlier `uploadFile` step honestly reports no `durationMs`.
|
|
1678
|
+
let execStart = null;
|
|
1679
|
+
try {
|
|
1680
|
+
if (stdinPath) {
|
|
1681
|
+
await sandbox.fs.uploadFile(Buffer.from(params.stdin ?? "", "utf8"), stdinPath, timeoutSeconds);
|
|
1682
|
+
}
|
|
1683
|
+
// Run the plain login-shell script as the unprivileged sandbox user. The
|
|
1684
|
+
// provider no longer wraps a user command with the advisory `bwrap` wrapper.
|
|
1685
|
+
const command = buildLoginShellScript({
|
|
1686
|
+
command: params.command,
|
|
1687
|
+
args: params.args ?? [],
|
|
1688
|
+
cwd: params.cwd,
|
|
1689
|
+
env: params.env,
|
|
1690
|
+
stdinPath: stdinPath ?? undefined,
|
|
1691
|
+
});
|
|
1692
|
+
// Pass cwd undefined: `buildLoginShellScript` already injects the `cd` after
|
|
1693
|
+
// it sources the login profiles, when params.cwd is set. The Daytona
|
|
1694
|
+
// executor's own cwd argument runs before that profile sourcing, which is
|
|
1695
|
+
// the wrong order (a profile could reset the caller env).
|
|
1696
|
+
// Time only the `executeCommand` REST round-trip so the caller can
|
|
1697
|
+
// attribute a step's exec time to the provider boundary through the
|
|
1698
|
+
// free-form `metadata.durationMs`.
|
|
1699
|
+
execStart = timingNow();
|
|
1700
|
+
const result = await withLivenessTimeout("process.executeCommand", timeoutSeconds * 1_000 + LIVENESS_START_TIMEOUT_MARGIN_MS, () => sandbox.process.executeCommand(command, undefined, undefined, timeoutSeconds));
|
|
1701
|
+
const durationMs = timingNow() - execStart;
|
|
1702
|
+
return {
|
|
1703
|
+
exitCode: typeof result.exitCode === "number" ? result.exitCode : 1,
|
|
1704
|
+
timedOut: false,
|
|
1705
|
+
stdout: result.result ?? result.artifacts?.stdout ?? "",
|
|
1706
|
+
stderr: "",
|
|
1707
|
+
metadata: { durationMs },
|
|
1708
|
+
};
|
|
1709
|
+
}
|
|
1710
|
+
catch (error) {
|
|
1711
|
+
if (error instanceof SandboxLivenessTimeoutError && execStart != null) {
|
|
1712
|
+
return {
|
|
1713
|
+
exitCode: null,
|
|
1714
|
+
timedOut: true,
|
|
1715
|
+
stdout: "",
|
|
1716
|
+
stderr: `${error.message}\n`,
|
|
1717
|
+
metadata: {
|
|
1718
|
+
durationMs: timingNow() - execStart,
|
|
1719
|
+
timeoutScope: "provider_exec_request",
|
|
1720
|
+
commandExitConfirmed: false,
|
|
1721
|
+
},
|
|
1722
|
+
};
|
|
1723
|
+
}
|
|
1724
|
+
if (error instanceof DaytonaTimeoutError) {
|
|
1725
|
+
const timeoutMessage = gitNet
|
|
1726
|
+
? `Git network operation timed out after ${Math.round(effectiveTimeoutMs / 1000)} s — the remote may be unreachable or noninteractive credentials are not configured.`
|
|
1727
|
+
: error.message.trim();
|
|
1728
|
+
// Preserve provider-boundary exec attribution on the timeout path: if the
|
|
1729
|
+
// SDK aborted the `executeCommand` call itself, report how long it ran
|
|
1730
|
+
// before timing out so slow failed startup exec is attributed to the
|
|
1731
|
+
// provider, not silently dropped.
|
|
1732
|
+
const durationMs = execStart != null ? timingNow() - execStart : undefined;
|
|
1733
|
+
return {
|
|
1734
|
+
exitCode: null,
|
|
1735
|
+
timedOut: true,
|
|
1736
|
+
stdout: "",
|
|
1737
|
+
stderr: `${timeoutMessage}\n`,
|
|
1738
|
+
...(durationMs != null ? { metadata: { durationMs } } : {}),
|
|
1739
|
+
};
|
|
1740
|
+
}
|
|
1741
|
+
throw error;
|
|
1742
|
+
}
|
|
1743
|
+
finally {
|
|
1744
|
+
if (stdinPath) {
|
|
1745
|
+
await withLivenessTimeout("fs.deleteFile", LIVENESS_START_TIMEOUT_MARGIN_MS, () => sandbox.fs.deleteFile(stdinPath)).catch(() => undefined);
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
// Fallback reads full log snapshots as well as status. Limit the heavier
|
|
1750
|
+
// polling path while keeping output available to interactive commands.
|
|
1751
|
+
const SESSION_LOG_POLL_INTERVAL_MS = 1000;
|
|
1752
|
+
const SESSION_INITIAL_STATUS_TIMEOUT_MS = 500;
|
|
1753
|
+
// A socket can stay open after it stops delivering output. Switch to saved
|
|
1754
|
+
// logs after this much silence; silence never proves that the command exited.
|
|
1755
|
+
const SESSION_LOG_STREAM_IDLE_MS = 15_000;
|
|
1756
|
+
function sleep(ms) {
|
|
1757
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1758
|
+
}
|
|
1759
|
+
// Backoff delays for the exit-code read after the log stream ends. The live
|
|
1760
|
+
// spike measured the exit code available within one poll (91-202 ms), so the
|
|
1761
|
+
// first read almost always holds the code. These delays cover the rare case
|
|
1762
|
+
// where the first read has no code yet.
|
|
1763
|
+
const SESSION_EXIT_CODE_RETRY_DELAYS_MS = [50, 100, 200];
|
|
1764
|
+
// A bounded reconnect for the log stream. The SDK resolves on WebSocket close,
|
|
1765
|
+
// which does not prove that the command exited. A reconnect replays the log
|
|
1766
|
+
// from byte 0; the stream buffer drops the replayed prefix by byte offset.
|
|
1767
|
+
// After this many reconnects the dispatch falls back to
|
|
1768
|
+
// the poll path.
|
|
1769
|
+
const MAX_SESSION_STREAM_RECONNECTS = 1;
|
|
1770
|
+
// Buffers the stdout and stderr of one session command from the callback log
|
|
1771
|
+
// stream, and drops a replayed prefix by byte offset.
|
|
1772
|
+
//
|
|
1773
|
+
// The Daytona callback stream replays the whole log from byte 0 after a
|
|
1774
|
+
// reconnect (it does not resume from an offset and does not omit earlier
|
|
1775
|
+
// bytes). So the buffer tracks the byte count it already holds per stream and
|
|
1776
|
+
// drops any replayed bytes that fall before that count. The dedupe runs at the
|
|
1777
|
+
// byte level, because Daytona replays the log byte-for-byte. The SDK keeps each
|
|
1778
|
+
// multibyte UTF-8 character whole per chunk and per stream, so the delivered
|
|
1779
|
+
// byte count always lands on a character boundary and the byte-offset split is
|
|
1780
|
+
// safe.
|
|
1781
|
+
//
|
|
1782
|
+
// The buffer stores each new tail as a separate chunk and joins the chunks one
|
|
1783
|
+
// time at read. It does not copy the earlier output on each append, so total
|
|
1784
|
+
// buffering work stays linear in the output size, not quadratic.
|
|
1785
|
+
function createSessionStreamBuffer(onNewTail) {
|
|
1786
|
+
const createStream = () => ({
|
|
1787
|
+
chunks: [], length: 0, connectionBytes: 0, pendingReplacement: "", previousReplacement: null,
|
|
1788
|
+
});
|
|
1789
|
+
const streams = {
|
|
1790
|
+
stdout: createStream(),
|
|
1791
|
+
stderr: createStream(),
|
|
1792
|
+
};
|
|
1793
|
+
function append(streamName, stream, chunk, final = false, publish = true) {
|
|
1794
|
+
// The SDK flushes an incomplete UTF-8 character as U+FFFD on socket close.
|
|
1795
|
+
// Do not publish that suffix or count its replacement bytes until a replay
|
|
1796
|
+
// confirms it. A real final U+FFFD is flushed at confirmed command exit.
|
|
1797
|
+
const text = stream.pendingReplacement + chunk;
|
|
1798
|
+
stream.pendingReplacement = final ? "" : (text.match(/\uFFFD+$/u)?.[0] ?? "");
|
|
1799
|
+
const buf = Buffer.from(text.slice(0, text.length - stream.pendingReplacement.length), "utf8");
|
|
1800
|
+
const start = stream.connectionBytes;
|
|
1801
|
+
stream.connectionBytes = start + buf.length;
|
|
1802
|
+
if (stream.previousReplacement && stream.connectionBytes > stream.previousReplacement.offset) {
|
|
1803
|
+
stream.previousReplacement = null;
|
|
1804
|
+
}
|
|
1805
|
+
// The whole chunk falls before the delivered byte count, so it is a replay.
|
|
1806
|
+
if (start + buf.length <= stream.length) {
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
// Keep only the new tail. When the whole chunk is new, `start >=
|
|
1810
|
+
// stream.length` and the tail is the whole chunk. When the chunk straddles
|
|
1811
|
+
// the delivered byte count, the tail starts after the replayed prefix.
|
|
1812
|
+
const tail = start >= stream.length ? buf : buf.subarray(stream.length - start);
|
|
1813
|
+
stream.chunks.push(tail);
|
|
1814
|
+
stream.length += tail.length;
|
|
1815
|
+
// Deliver only the genuinely new tail to the live sink, so a replayed
|
|
1816
|
+
// prefix on a reconnect never reaches the host twice.
|
|
1817
|
+
if (publish && onNewTail && tail.length > 0) {
|
|
1818
|
+
onNewTail(streamName, tail.toString("utf8"));
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
return {
|
|
1822
|
+
onStdout: (chunk) => append("stdout", streams.stdout, chunk),
|
|
1823
|
+
onStderr: (chunk) => append("stderr", streams.stderr, chunk),
|
|
1824
|
+
// Reset the per-connection read cursors after a reconnect, so the replayed
|
|
1825
|
+
// prefix drops against the already-delivered byte count.
|
|
1826
|
+
resetConnectionCursors() {
|
|
1827
|
+
for (const stream of Object.values(streams)) {
|
|
1828
|
+
if (stream.pendingReplacement &&
|
|
1829
|
+
(!stream.previousReplacement || stream.connectionBytes > stream.previousReplacement.offset ||
|
|
1830
|
+
(stream.connectionBytes === stream.previousReplacement.offset &&
|
|
1831
|
+
stream.pendingReplacement.length > stream.previousReplacement.text.length))) {
|
|
1832
|
+
stream.previousReplacement = { offset: stream.connectionBytes, text: stream.pendingReplacement };
|
|
1833
|
+
}
|
|
1834
|
+
stream.pendingReplacement = "";
|
|
1835
|
+
stream.connectionBytes = 0;
|
|
1836
|
+
}
|
|
1837
|
+
},
|
|
1838
|
+
finish(publish = true) {
|
|
1839
|
+
for (const name of ["stdout", "stderr"]) {
|
|
1840
|
+
const stream = streams[name];
|
|
1841
|
+
if (stream.previousReplacement?.offset === stream.connectionBytes &&
|
|
1842
|
+
stream.previousReplacement.text.length > stream.pendingReplacement.length) {
|
|
1843
|
+
stream.pendingReplacement = stream.previousReplacement.text;
|
|
1844
|
+
}
|
|
1845
|
+
append(name, stream, "", true, publish);
|
|
1846
|
+
// A short terminal snapshot must not discard a genuine trailing
|
|
1847
|
+
// replacement character already received from a longer stream.
|
|
1848
|
+
const previous = stream.previousReplacement;
|
|
1849
|
+
if (previous && previous.offset >= stream.length) {
|
|
1850
|
+
stream.connectionBytes = previous.offset;
|
|
1851
|
+
append(name, stream, previous.text, true, publish);
|
|
1852
|
+
}
|
|
1853
|
+
stream.previousReplacement = null;
|
|
1854
|
+
}
|
|
1855
|
+
},
|
|
1856
|
+
get stdout() {
|
|
1857
|
+
return Buffer.concat(streams.stdout.chunks).toString("utf8");
|
|
1858
|
+
},
|
|
1859
|
+
get stderr() {
|
|
1860
|
+
return Buffer.concat(streams.stderr.chunks).toString("utf8");
|
|
1861
|
+
},
|
|
1862
|
+
};
|
|
1863
|
+
}
|
|
1864
|
+
class SessionCommandDeadlineError extends Error {
|
|
1865
|
+
}
|
|
1866
|
+
class SessionObservationTimeoutError extends Error {
|
|
1867
|
+
}
|
|
1868
|
+
function createCommandDeadline(timeoutMs) {
|
|
1869
|
+
if (timeoutMs === undefined || timeoutMs === 0)
|
|
1870
|
+
return undefined;
|
|
1871
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) {
|
|
1872
|
+
throw new Error("Invalid session command timeout");
|
|
1873
|
+
}
|
|
1874
|
+
let expired = false;
|
|
1875
|
+
const dueAt = Date.now() + timeoutMs;
|
|
1876
|
+
const controller = new AbortController();
|
|
1877
|
+
const timer = setTimeout(() => {
|
|
1878
|
+
expired = true;
|
|
1879
|
+
controller.abort();
|
|
1880
|
+
}, timeoutMs);
|
|
1881
|
+
return {
|
|
1882
|
+
expired: () => expired,
|
|
1883
|
+
remainingMs: () => Math.max(0, dueAt - Date.now()),
|
|
1884
|
+
race: async (action) => {
|
|
1885
|
+
if (expired)
|
|
1886
|
+
throw new SessionCommandDeadlineError();
|
|
1887
|
+
let rejectDeadline;
|
|
1888
|
+
const deadline = new Promise((_resolve, reject) => { rejectDeadline = reject; });
|
|
1889
|
+
const onAbort = () => rejectDeadline(new SessionCommandDeadlineError());
|
|
1890
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
1891
|
+
try {
|
|
1892
|
+
return await Promise.race([action(), deadline]);
|
|
1893
|
+
}
|
|
1894
|
+
finally {
|
|
1895
|
+
// Retain only active observations. A shared pending promise would keep
|
|
1896
|
+
// every finished poll and its result until a long command ends.
|
|
1897
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
1898
|
+
}
|
|
1899
|
+
},
|
|
1900
|
+
clear: () => clearTimeout(timer),
|
|
1901
|
+
};
|
|
1902
|
+
}
|
|
1903
|
+
function withinCommandDeadline(deadline, action) {
|
|
1904
|
+
return deadline ? deadline.race(() => idleActivity.track(action)) : idleActivity.track(action);
|
|
1905
|
+
}
|
|
1906
|
+
async function sleepWithinCommandDeadline(deadline, delayMs) {
|
|
1907
|
+
if (!deadline)
|
|
1908
|
+
return await sleep(delayMs);
|
|
1909
|
+
let timer;
|
|
1910
|
+
try {
|
|
1911
|
+
await deadline.race(() => new Promise((resolve) => { timer = setTimeout(resolve, delayMs); }));
|
|
1912
|
+
}
|
|
1913
|
+
finally {
|
|
1914
|
+
if (timer !== undefined)
|
|
1915
|
+
clearTimeout(timer);
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
async function beforeSessionDeadline(deadlineMs, action) {
|
|
1919
|
+
const remainingMs = deadlineMs - Date.now();
|
|
1920
|
+
if (remainingMs <= 0)
|
|
1921
|
+
throw new SessionCommandDeadlineError();
|
|
1922
|
+
let timer;
|
|
1923
|
+
try {
|
|
1924
|
+
return await Promise.race([
|
|
1925
|
+
idleActivity.track(action),
|
|
1926
|
+
new Promise((_resolve, reject) => {
|
|
1927
|
+
timer = setTimeout(() => reject(new SessionCommandDeadlineError()), remainingMs);
|
|
1928
|
+
}),
|
|
1929
|
+
]);
|
|
1930
|
+
}
|
|
1931
|
+
finally {
|
|
1932
|
+
if (timer !== undefined)
|
|
1933
|
+
clearTimeout(timer);
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
// A provider operation timeout bounds one observation. An explicit command
|
|
1937
|
+
// deadline also bounds the stream; existing callers retain their run/Stop guard.
|
|
1938
|
+
async function observeSessionCommand(timeoutMs, action, commandDeadline) {
|
|
1939
|
+
try {
|
|
1940
|
+
// Use the earlier shared command timer instead of leaving a longer
|
|
1941
|
+
// observation timer alive after the command has already settled.
|
|
1942
|
+
if (commandDeadline && commandDeadline.remainingMs() <= timeoutMs) {
|
|
1943
|
+
return await commandDeadline.race(() => idleActivity.track(action));
|
|
1944
|
+
}
|
|
1945
|
+
return await beforeSessionDeadline(Date.now() + timeoutMs, action);
|
|
1946
|
+
}
|
|
1947
|
+
catch (error) {
|
|
1948
|
+
if (commandDeadline?.expired())
|
|
1949
|
+
throw new SessionCommandDeadlineError();
|
|
1950
|
+
if (error instanceof SessionCommandDeadlineError || error instanceof DaytonaTimeoutError) {
|
|
1951
|
+
throw new SessionObservationTimeoutError();
|
|
1952
|
+
}
|
|
1953
|
+
throw error;
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
// Stream stdout and stderr of one session command from the callback log form.
|
|
1957
|
+
// The stream buffer drops a replayed prefix by byte offset on a reconnect.
|
|
1958
|
+
// Rejected streams and clean closes use bounded reconnects, then polling.
|
|
1959
|
+
// An idle socket goes directly to polling, including one that never settles.
|
|
1960
|
+
async function runSessionLogStream(sandbox, sessionId, commandId, timeoutMs, buffer, commandDeadline) {
|
|
1961
|
+
let reconnects = 0;
|
|
1962
|
+
let pollUntilExit = false;
|
|
1963
|
+
while (true) {
|
|
1964
|
+
let streamClosed = false;
|
|
1965
|
+
let acceptingOutput = true;
|
|
1966
|
+
let exitObservation;
|
|
1967
|
+
let idleTimer;
|
|
1968
|
+
let signalIdle;
|
|
1969
|
+
const idle = new Promise((resolve) => { signalIdle = () => resolve("idle"); });
|
|
1970
|
+
const armIdleTimer = () => {
|
|
1971
|
+
clearTimeout(idleTimer);
|
|
1972
|
+
idleTimer = setTimeout(signalIdle, SESSION_LOG_STREAM_IDLE_MS);
|
|
1973
|
+
};
|
|
1974
|
+
const receive = (stream, chunk) => {
|
|
1975
|
+
if (!acceptingOutput || commandDeadline?.expired() || !chunk)
|
|
1976
|
+
return;
|
|
1977
|
+
armIdleTimer();
|
|
1978
|
+
if (stream === "stdout")
|
|
1979
|
+
buffer.onStdout(chunk);
|
|
1980
|
+
else
|
|
1981
|
+
buffer.onStderr(chunk);
|
|
1982
|
+
};
|
|
1983
|
+
try {
|
|
1984
|
+
armIdleTimer();
|
|
1985
|
+
const observed = await withinCommandDeadline(commandDeadline, () => {
|
|
1986
|
+
exitObservation = observeSessionStreamExit(Promise.race([
|
|
1987
|
+
idleActivity.track(() => sandbox.process.getSessionCommandLogs(sessionId, commandId, (chunk) => receive("stdout", chunk), (chunk) => receive("stderr", chunk))).then(() => "closed"),
|
|
1988
|
+
idle,
|
|
1989
|
+
]), async () => {
|
|
1990
|
+
const status = await observeSessionCommand(Math.min(timeoutMs, SESSION_INITIAL_STATUS_TIMEOUT_MS), () => sandbox.process.getSessionCommand(sessionId, commandId), commandDeadline);
|
|
1991
|
+
return typeof status.exitCode === "number" ? status.exitCode : null;
|
|
1992
|
+
});
|
|
1993
|
+
return exitObservation.result;
|
|
1994
|
+
});
|
|
1995
|
+
if (observed.kind === "exit")
|
|
1996
|
+
return { exitCode: observed.exitCode, pollUntilExit: false, buffer };
|
|
1997
|
+
const outcome = observed.value;
|
|
1998
|
+
if (outcome === "idle") {
|
|
1999
|
+
// Do not wait for the abandoned socket or open another one. The SDK
|
|
2000
|
+
// exposes no cancellation handle. Fence its callbacks before the
|
|
2001
|
+
// snapshot path resets the buffer's byte cursors.
|
|
2002
|
+
return { exitCode: null, pollUntilExit: true, buffer };
|
|
2003
|
+
}
|
|
2004
|
+
streamClosed = true;
|
|
2005
|
+
pollUntilExit = true;
|
|
2006
|
+
}
|
|
2007
|
+
catch (error) {
|
|
2008
|
+
if (error instanceof SessionCommandDeadlineError)
|
|
2009
|
+
throw error;
|
|
2010
|
+
// The command can still be running after a log transport failure.
|
|
2011
|
+
}
|
|
2012
|
+
finally {
|
|
2013
|
+
// The SDK exposes no cancellation handle for this socket. Session
|
|
2014
|
+
// teardown owns closing it; late data cannot change a settled execution.
|
|
2015
|
+
acceptingOutput = false;
|
|
2016
|
+
exitObservation?.stop();
|
|
2017
|
+
clearTimeout(idleTimer);
|
|
2018
|
+
}
|
|
2019
|
+
if (streamClosed) {
|
|
2020
|
+
const exitCode = await readSessionExitCode(sandbox, sessionId, commandId, timeoutMs, commandDeadline);
|
|
2021
|
+
if (exitCode !== null)
|
|
2022
|
+
return { exitCode, pollUntilExit, buffer };
|
|
2023
|
+
}
|
|
2024
|
+
if (reconnects >= MAX_SESSION_STREAM_RECONNECTS) {
|
|
2025
|
+
return { exitCode: null, pollUntilExit, buffer };
|
|
2026
|
+
}
|
|
2027
|
+
reconnects += 1;
|
|
2028
|
+
buffer.resetConnectionCursors();
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
// Read the exit code one time after the log stream ends. The exit code is
|
|
2032
|
+
// available within one poll, so the first read almost always holds it. Add a
|
|
2033
|
+
// small bounded retry with backoff only for the rare case where the first read
|
|
2034
|
+
// has no code yet. Return null when no read holds a numeric code.
|
|
2035
|
+
async function readSessionExitCode(sandbox, sessionId, commandId, timeoutMs, commandDeadline) {
|
|
2036
|
+
const first = await observeSessionCommand(timeoutMs, () => sandbox.process.getSessionCommand(sessionId, commandId), commandDeadline);
|
|
2037
|
+
if (typeof first.exitCode === "number") {
|
|
2038
|
+
return first.exitCode;
|
|
2039
|
+
}
|
|
2040
|
+
for (const delayMs of SESSION_EXIT_CODE_RETRY_DELAYS_MS) {
|
|
2041
|
+
await sleepWithinCommandDeadline(commandDeadline, delayMs);
|
|
2042
|
+
const status = await observeSessionCommand(timeoutMs, () => sandbox.process.getSessionCommand(sessionId, commandId), commandDeadline);
|
|
2043
|
+
if (typeof status.exitCode === "number") {
|
|
2044
|
+
return status.exitCode;
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
return null;
|
|
2048
|
+
}
|
|
2049
|
+
// Dispatch one user command into the persistent session and return its true
|
|
2050
|
+
// stdout and stderr.
|
|
2051
|
+
//
|
|
2052
|
+
// The Daytona session is one persistent shell. A top-level `exit N` inside a
|
|
2053
|
+
// session command ends that shell, so the next command then fails with "session
|
|
2054
|
+
// process has exited". To stop a user `exit` from reaching the session shell,
|
|
2055
|
+
// the dispatch wraps the whole login-shell script in a subshell `( ... )`. A
|
|
2056
|
+
// user `exit` then ends only the subshell and reports its exit code, and the
|
|
2057
|
+
// session shell stays alive. The provider passes the caller cwd and env inside
|
|
2058
|
+
// the login-shell script on every command, so it never relies on implicit state
|
|
2059
|
+
// that leaks between commands.
|
|
2060
|
+
//
|
|
2061
|
+
// The SDK exposes no built-in wait for a session command, so the dispatch runs
|
|
2062
|
+
// the command with `runAsync: true` and polls `getSessionCommand` until the exit
|
|
2063
|
+
// code is set. It then reads true `stdout` and `stderr` from
|
|
2064
|
+
// `getSessionCommandLogs`, because the synchronous response fields are optional.
|
|
2065
|
+
// The `runAsync: true` path also avoids the known `runAsync: false` login-shell
|
|
2066
|
+
// hang.
|
|
2067
|
+
async function executeInSession(sandbox, sessionId, params, config) {
|
|
2068
|
+
const gitNet = isGitNetworkCommand(params.command, params.args ?? []);
|
|
2069
|
+
const timeoutMs = resolveTimeoutMs(params.timeoutMs, config);
|
|
2070
|
+
const effectiveTimeoutMs = gitNet ? Math.min(timeoutMs, GIT_NETWORK_TIMEOUT_MS) : timeoutMs;
|
|
2071
|
+
const timeoutSeconds = toTimeoutSeconds(effectiveTimeoutMs);
|
|
2072
|
+
const stdinPath = params.stdin != null ? `/tmp/paperclip-stdin-${randomUUID()}` : null;
|
|
2073
|
+
// Marks the start of the session dispatch and poll. The timeout paths report
|
|
2074
|
+
// the exec wall-time spent before the abort, so a slow command is still
|
|
2075
|
+
// attributed to the provider boundary.
|
|
2076
|
+
let execStart = null;
|
|
2077
|
+
let confirmedExitCode = null;
|
|
2078
|
+
let commandDeadline;
|
|
2079
|
+
const streamBuffer = createSessionStreamBuffer((stream, text) => pluginContext?.execution.log(stream, text));
|
|
2080
|
+
try {
|
|
2081
|
+
if (stdinPath) {
|
|
2082
|
+
await sandbox.fs.uploadFile(Buffer.from(params.stdin ?? "", "utf8"), stdinPath, timeoutSeconds);
|
|
2083
|
+
}
|
|
2084
|
+
const loginScript = buildLoginShellScript({
|
|
2085
|
+
command: params.command,
|
|
2086
|
+
args: params.args ?? [],
|
|
2087
|
+
cwd: params.cwd,
|
|
2088
|
+
env: params.env,
|
|
2089
|
+
stdinPath: stdinPath ?? undefined,
|
|
2090
|
+
});
|
|
2091
|
+
// Subshell wrap: a top-level `exit` in the user command exits only the
|
|
2092
|
+
// subshell, not the persistent session shell.
|
|
2093
|
+
const command = `( ${loginScript} )`;
|
|
2094
|
+
execStart = timingNow();
|
|
2095
|
+
commandDeadline = createCommandDeadline(params.commandTimeoutMs);
|
|
2096
|
+
const dispatched = await withinCommandDeadline(commandDeadline, () => sandbox.process.executeSessionCommand(sessionId, { command, runAsync: true }, timeoutSeconds));
|
|
2097
|
+
const commandId = dispatched.cmdId;
|
|
2098
|
+
let initialExitCode = null;
|
|
2099
|
+
try {
|
|
2100
|
+
const status = await observeSessionCommand(Math.min(effectiveTimeoutMs, SESSION_INITIAL_STATUS_TIMEOUT_MS), () => sandbox.process.getSessionCommand(sessionId, commandId), commandDeadline);
|
|
2101
|
+
if (typeof status.exitCode === "number")
|
|
2102
|
+
initialExitCode = status.exitCode;
|
|
2103
|
+
}
|
|
2104
|
+
catch (error) {
|
|
2105
|
+
if (error instanceof SessionCommandDeadlineError)
|
|
2106
|
+
throw error;
|
|
2107
|
+
}
|
|
2108
|
+
// Log-stream path. A session command always tries the stream first: it
|
|
2109
|
+
// streams stdout and stderr from the callback log form, then reads the exit
|
|
2110
|
+
// code. A log socket closing without a recorded exit leaves the command
|
|
2111
|
+
// running, so reconnect and then poll the same command without replaying it.
|
|
2112
|
+
//
|
|
2113
|
+
// Emit each genuinely new output chunk to the host during the active execute
|
|
2114
|
+
// call. The host routes it to the runner log sink by the host-issued
|
|
2115
|
+
// invocation id. This is a no-op when no plugin context is set (a direct
|
|
2116
|
+
// test call) or when the host has no active execute route.
|
|
2117
|
+
const streamResult = initialExitCode !== null
|
|
2118
|
+
? { exitCode: initialExitCode, pollUntilExit: false, buffer: streamBuffer }
|
|
2119
|
+
: await runSessionLogStream(sandbox, sessionId, commandId, effectiveTimeoutMs, streamBuffer, commandDeadline);
|
|
2120
|
+
if (streamResult.exitCode !== null) {
|
|
2121
|
+
confirmedExitCode = streamResult.exitCode;
|
|
2122
|
+
// A log socket can close before the process emits its final bytes. Even
|
|
2123
|
+
// a now-visible exit code does not prove the streamed prefix is complete.
|
|
2124
|
+
const logs = await observeSessionCommand(effectiveTimeoutMs, () => sandbox.process.getSessionCommandLogs(sessionId, commandId), commandDeadline);
|
|
2125
|
+
streamBuffer.resetConnectionCursors();
|
|
2126
|
+
streamBuffer.onStdout(logs?.stdout ?? "");
|
|
2127
|
+
streamBuffer.onStderr(logs?.stderr ?? "");
|
|
2128
|
+
streamBuffer.finish();
|
|
2129
|
+
const durationMs = timingNow() - execStart;
|
|
2130
|
+
return {
|
|
2131
|
+
exitCode: streamResult.exitCode,
|
|
2132
|
+
timedOut: false,
|
|
2133
|
+
stdout: streamResult.buffer.stdout,
|
|
2134
|
+
stderr: streamResult.buffer.stderr,
|
|
2135
|
+
metadata: { durationMs },
|
|
2136
|
+
};
|
|
2137
|
+
}
|
|
2138
|
+
// Keep forwarding output while waiting for the actual command exit. ACP
|
|
2139
|
+
// peers may need a tool response before they can finish the command. Waiting
|
|
2140
|
+
// for exit before reading logs would strand those peers after a stream loss.
|
|
2141
|
+
// A closed or idle log socket does not end the command's lifetime. Bound
|
|
2142
|
+
// each recovery read independently; the caller still owns stop/teardown.
|
|
2143
|
+
// Preserve the legacy budget starting at fallback entry when both stream
|
|
2144
|
+
// attempts fail, including a stream that fails after running for hours.
|
|
2145
|
+
const deadlineMs = Date.now() + effectiveTimeoutMs;
|
|
2146
|
+
const observe = async (action) => {
|
|
2147
|
+
try {
|
|
2148
|
+
return await (streamResult.pollUntilExit
|
|
2149
|
+
? observeSessionCommand(effectiveTimeoutMs, action, commandDeadline)
|
|
2150
|
+
: commandDeadline ? commandDeadline.race(action) : beforeSessionDeadline(deadlineMs, action));
|
|
2151
|
+
}
|
|
2152
|
+
catch (error) {
|
|
2153
|
+
if (error instanceof DaytonaTimeoutError)
|
|
2154
|
+
throw new SessionObservationTimeoutError();
|
|
2155
|
+
throw error;
|
|
2156
|
+
}
|
|
2157
|
+
};
|
|
2158
|
+
while (true) {
|
|
2159
|
+
const status = await observe(() => sandbox.process.getSessionCommand(sessionId, commandId));
|
|
2160
|
+
if (typeof status.exitCode === "number")
|
|
2161
|
+
confirmedExitCode = status.exitCode;
|
|
2162
|
+
const logs = await observe(() => sandbox.process.getSessionCommandLogs(sessionId, commandId));
|
|
2163
|
+
streamResult.buffer.resetConnectionCursors();
|
|
2164
|
+
streamResult.buffer.onStdout(logs.stdout ?? "");
|
|
2165
|
+
streamResult.buffer.onStderr(logs.stderr ?? "");
|
|
2166
|
+
if (confirmedExitCode !== null) {
|
|
2167
|
+
streamResult.buffer.finish();
|
|
2168
|
+
const durationMs = timingNow() - execStart;
|
|
2169
|
+
return {
|
|
2170
|
+
exitCode: confirmedExitCode,
|
|
2171
|
+
timedOut: false,
|
|
2172
|
+
stdout: streamResult.buffer.stdout,
|
|
2173
|
+
stderr: streamResult.buffer.stderr,
|
|
2174
|
+
metadata: { durationMs },
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
// Full log snapshots are heavier than a status read. Limit fallback
|
|
2178
|
+
// traffic to one snapshot per second. Failed-stream fallback retains
|
|
2179
|
+
// its original deadline, including the time spent waiting between reads.
|
|
2180
|
+
await sleepWithinCommandDeadline(commandDeadline, streamResult.pollUntilExit ? SESSION_LOG_POLL_INTERVAL_MS
|
|
2181
|
+
: Math.max(0, Math.min(SESSION_LOG_POLL_INTERVAL_MS, deadlineMs - Date.now())));
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
catch (error) {
|
|
2185
|
+
if (error instanceof SessionObservationTimeoutError ||
|
|
2186
|
+
(error instanceof SessionCommandDeadlineError && confirmedExitCode !== null)) {
|
|
2187
|
+
// Preserve undecided decoder suffixes in the partial result, without
|
|
2188
|
+
// injecting a possibly incomplete character into the live protocol.
|
|
2189
|
+
streamBuffer.finish(false);
|
|
2190
|
+
return {
|
|
2191
|
+
exitCode: null,
|
|
2192
|
+
timedOut: true,
|
|
2193
|
+
stdout: streamBuffer.stdout,
|
|
2194
|
+
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`,
|
|
2195
|
+
metadata: {
|
|
2196
|
+
...(execStart != null ? { durationMs: timingNow() - execStart } : {}),
|
|
2197
|
+
timeoutScope: "session_log_observation",
|
|
2198
|
+
commandExitConfirmed: confirmedExitCode !== null,
|
|
2199
|
+
...(confirmedExitCode !== null ? { observedExitCode: confirmedExitCode } : {}),
|
|
2200
|
+
},
|
|
2201
|
+
};
|
|
2202
|
+
}
|
|
2203
|
+
if (error instanceof DaytonaTimeoutError || error instanceof SessionCommandDeadlineError) {
|
|
2204
|
+
streamBuffer.finish(false);
|
|
2205
|
+
const timeoutMessage = gitNet
|
|
2206
|
+
? `Git network operation timed out after ${Math.round(effectiveTimeoutMs / 1000)} s — the remote may be unreachable or noninteractive credentials are not configured.`
|
|
2207
|
+
: error instanceof SessionCommandDeadlineError
|
|
2208
|
+
? `Command timed out after ${Math.round((commandDeadline?.expired() ? params.commandTimeoutMs : effectiveTimeoutMs) / 1000)} s.`
|
|
2209
|
+
: error.message.trim();
|
|
2210
|
+
const durationMs = execStart != null ? timingNow() - execStart : undefined;
|
|
2211
|
+
return {
|
|
2212
|
+
exitCode: null,
|
|
2213
|
+
timedOut: true,
|
|
2214
|
+
stdout: streamBuffer.stdout,
|
|
2215
|
+
stderr: `${streamBuffer.stderr}${timeoutMessage}\n`,
|
|
2216
|
+
...(durationMs != null ? { metadata: { durationMs } } : {}),
|
|
2217
|
+
};
|
|
2218
|
+
}
|
|
2219
|
+
throw error;
|
|
2220
|
+
}
|
|
2221
|
+
finally {
|
|
2222
|
+
commandDeadline?.clear();
|
|
2223
|
+
if (stdinPath) {
|
|
2224
|
+
await sandbox.fs.deleteFile(stdinPath).catch(() => undefined);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
const daytonaLoginPtyByRoute = new Map();
|
|
2229
|
+
const daytonaLoginPtyBySession = new Map();
|
|
2230
|
+
function forgetDaytonaLoginPty(entry) {
|
|
2231
|
+
daytonaLoginPtyByRoute.delete(entry.hostRouteId);
|
|
2232
|
+
daytonaLoginPtyBySession.delete(entry.workerSessionId);
|
|
2233
|
+
}
|
|
2234
|
+
const daytonaDuplexChannelByRoute = new Map();
|
|
2235
|
+
const daytonaDuplexChannelBySession = new Map();
|
|
2236
|
+
const retiredDaytonaDuplexChannelByRoute = new Map();
|
|
2237
|
+
const MAX_RETIRED_DAYTONA_DUPLEX_CHANNELS = 4096;
|
|
2238
|
+
function forgetDaytonaDuplexChannel(entry) {
|
|
2239
|
+
daytonaDuplexChannelByRoute.delete(entry.hostRouteId);
|
|
2240
|
+
daytonaDuplexChannelBySession.delete(entry.workerSessionId);
|
|
2241
|
+
}
|
|
2242
|
+
function closeDaytonaDuplexChannel(entry) {
|
|
2243
|
+
forgetDaytonaDuplexChannel(entry);
|
|
2244
|
+
const closed = Promise.resolve().then(() => entry.session.close());
|
|
2245
|
+
if (retiredDaytonaDuplexChannelByRoute.size >= MAX_RETIRED_DAYTONA_DUPLEX_CHANNELS) {
|
|
2246
|
+
retiredDaytonaDuplexChannelByRoute.delete(retiredDaytonaDuplexChannelByRoute.keys().next().value);
|
|
2247
|
+
}
|
|
2248
|
+
retiredDaytonaDuplexChannelByRoute.set(entry.hostRouteId, { workerSessionId: entry.workerSessionId, closed });
|
|
2249
|
+
return closed;
|
|
2250
|
+
}
|
|
2251
|
+
// Close every open duplex channel that belongs to one provider lease and drop its
|
|
2252
|
+
// entry. The lease teardown hooks (release, destroy, resume) call this, so a
|
|
2253
|
+
// channel never outlives the sandbox that carries it. The close kills the child
|
|
2254
|
+
// and releases the pseudo-terminal socket, so no live channel survives the
|
|
2255
|
+
// teardown. The stored identifiers are always cleared, so no orphan id survives.
|
|
2256
|
+
async function closeDaytonaDuplexChannelsForLease(providerLeaseId) {
|
|
2257
|
+
const matches = [...daytonaDuplexChannelByRoute.values()].filter((entry) => entry.providerLeaseId === providerLeaseId);
|
|
2258
|
+
await Promise.allSettled(matches.map(closeDaytonaDuplexChannel));
|
|
2259
|
+
}
|
|
2260
|
+
const STOP_RECOVERY_TIMEOUT_SECONDS = 20;
|
|
2261
|
+
const STOPPABLE_AFTER_RECOVERY_STATES = new Set(["started", "stopped", "archived"]);
|
|
2262
|
+
function erroredAfterRecovery(sandbox) {
|
|
2263
|
+
return new PluginEnvironmentStopError(sandbox.recoverable === false ? "resource_unrecoverable" : "recovery_failed");
|
|
2264
|
+
}
|
|
2265
|
+
async function refreshedSandbox(sandbox, timeoutMs) {
|
|
2266
|
+
try {
|
|
2267
|
+
await withLivenessTimeout("sandbox.refreshData", timeoutMs, () => sandbox.refreshData());
|
|
2268
|
+
return true;
|
|
2269
|
+
}
|
|
2270
|
+
catch {
|
|
2271
|
+
return false;
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
async function recoverSandboxForStop(sandbox, timeoutSeconds, readTimeoutMs) {
|
|
2275
|
+
if (sandbox.recoverable !== true)
|
|
2276
|
+
throw new PluginEnvironmentStopError("resource_unrecoverable");
|
|
2277
|
+
try {
|
|
2278
|
+
await withLivenessTimeout("sandbox.recover", timeoutSeconds * 1_000 + LIVENESS_START_TIMEOUT_MARGIN_MS, () => sandbox.recover(timeoutSeconds));
|
|
2279
|
+
}
|
|
2280
|
+
catch {
|
|
2281
|
+
if (!await refreshedSandbox(sandbox, readTimeoutMs))
|
|
2282
|
+
throw new PluginEnvironmentStopError("recovery_incomplete");
|
|
2283
|
+
}
|
|
2284
|
+
if (sandbox.state === "error")
|
|
2285
|
+
throw erroredAfterRecovery(sandbox);
|
|
2286
|
+
if (!STOPPABLE_AFTER_RECOVERY_STATES.has(sandbox.state ?? ""))
|
|
2287
|
+
throw new PluginEnvironmentStopError("recovery_incomplete");
|
|
2288
|
+
}
|
|
2289
|
+
async function stopLease(params) {
|
|
2290
|
+
if (!params.providerLeaseId)
|
|
2291
|
+
throw new Error("Daytona stop requires an exact sandbox identity");
|
|
2292
|
+
const config = parseDriverConfig(params.config);
|
|
2293
|
+
const scope = { driverKey: params.driverKey, companyId: params.companyId,
|
|
2294
|
+
environmentId: params.environmentId, providerLeaseId: params.providerLeaseId, config };
|
|
2295
|
+
const teardownGate = sandboxHandleTeardownGates.begin(scope);
|
|
2296
|
+
sandboxHandleLeaseAdmissionStates.close(scope);
|
|
2297
|
+
const cleanupProof = idleActivity.proof(sandboxHandleCacheKey(scope));
|
|
2298
|
+
try {
|
|
2299
|
+
const sandbox = await getSandboxOrNull(scope, { bypassTeardownGate: true });
|
|
2300
|
+
// Daytona reports the exact sandbox as not found: it is gone, so nothing
|
|
2301
|
+
// runs there and nothing is retained. Destroy reports the same receipt.
|
|
2302
|
+
if (!sandbox)
|
|
2303
|
+
return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
|
2304
|
+
evictSandboxHandle(scope);
|
|
2305
|
+
// Provider auto-delete can destroy a stopped sandbox without an explicit
|
|
2306
|
+
// delete call. Confirm the provider disabled it before stopping saved work;
|
|
2307
|
+
// the SDK setter also updates a local field, which is not sufficient proof.
|
|
2308
|
+
const deadline = Math.min(config.livenessTimeoutMs, 30_000);
|
|
2309
|
+
await withLivenessTimeout("sandbox.setAutoDeleteInterval", deadline, () => sandbox.setAutoDeleteInterval(-1));
|
|
2310
|
+
await withLivenessTimeout("sandbox.refreshData", deadline, () => sandbox.refreshData());
|
|
2311
|
+
if (sandbox.autoDeleteInterval !== -1)
|
|
2312
|
+
throw new Error("Daytona retention policy was not confirmed");
|
|
2313
|
+
const stopSeconds = Math.min(toTimeoutSeconds(config.timeoutMs), 30);
|
|
2314
|
+
const recovering = sandbox.state === "error";
|
|
2315
|
+
if (recovering)
|
|
2316
|
+
await recoverSandboxForStop(sandbox, Math.min(stopSeconds, STOP_RECOVERY_TIMEOUT_SECONDS), deadline);
|
|
2317
|
+
// An archive already has no live process and retains its filesystem.
|
|
2318
|
+
// Daytona rejects Stop in this state; leave the confirmed archive cold.
|
|
2319
|
+
if (sandbox.state !== "stopped" && sandbox.state !== "archived") {
|
|
2320
|
+
try {
|
|
2321
|
+
await terminateAtProvider(scope, "sandbox.stop", () => sandbox.stop(stopSeconds));
|
|
2322
|
+
}
|
|
2323
|
+
catch (error) {
|
|
2324
|
+
if (recovering && await refreshedSandbox(sandbox, deadline) && sandbox.state === "error") {
|
|
2325
|
+
throw erroredAfterRecovery(sandbox);
|
|
2326
|
+
}
|
|
2327
|
+
throw error;
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
sandboxHandleSessionStore.clear(scope);
|
|
2331
|
+
await closeDaytonaDuplexChannelsForLease(params.providerLeaseId);
|
|
2332
|
+
return confirmedTermination(scope, "stopped", cleanupProof);
|
|
2333
|
+
}
|
|
2334
|
+
finally {
|
|
2335
|
+
sandboxHandleTeardownGates.end(scope, teardownGate);
|
|
2336
|
+
evictSandboxHandle(scope);
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
const plugin = definePlugin(trackDaytonaHooks({
|
|
2340
|
+
async setup(ctx) {
|
|
2341
|
+
// Hoist the context to a module variable so the lifecycle hooks and the
|
|
2342
|
+
// file-sync helpers can read `ctx.tracer` — they have no closure over `ctx`.
|
|
2343
|
+
pluginContext = ctx;
|
|
2344
|
+
ctx.logger.info("Daytona sandbox provider plugin ready");
|
|
2345
|
+
},
|
|
2346
|
+
async onHealth() {
|
|
2347
|
+
return { status: "ok", message: "Daytona sandbox provider plugin healthy" };
|
|
2348
|
+
},
|
|
2349
|
+
async onIdleDrain() {
|
|
2350
|
+
return idleActivity.present() || daytonaLoginPtyByRoute.size > 0 || daytonaDuplexChannelByRoute.size > 0
|
|
2351
|
+
? "present" : "none";
|
|
2352
|
+
},
|
|
2353
|
+
async onEnvironmentValidateConfig(params) {
|
|
2354
|
+
const config = parseDriverConfig(params.config);
|
|
2355
|
+
const errors = [];
|
|
2356
|
+
if (typeof params.config.image === "string" && params.config.image.trim().length === 0) {
|
|
2357
|
+
errors.push("Daytona image cannot be empty.");
|
|
2358
|
+
}
|
|
2359
|
+
if (typeof params.config.snapshot === "string" && params.config.snapshot.trim().length === 0) {
|
|
2360
|
+
errors.push("Daytona snapshot cannot be empty.");
|
|
2361
|
+
}
|
|
2362
|
+
if (config.image && config.snapshot) {
|
|
2363
|
+
errors.push("Daytona sandbox environments must set either image or snapshot, not both.");
|
|
2364
|
+
}
|
|
2365
|
+
if (config.apiUrl && !isValidUrl(config.apiUrl)) {
|
|
2366
|
+
errors.push("apiUrl must be a valid URL.");
|
|
2367
|
+
}
|
|
2368
|
+
if (config.timeoutMs < 1 || config.timeoutMs > 86_400_000) {
|
|
2369
|
+
errors.push("timeoutMs must be between 1 and 86400000.");
|
|
2370
|
+
}
|
|
2371
|
+
// A value of 0 or less disables the extra bound on purpose; reject only a
|
|
2372
|
+
// value above the outer RPC ceiling, which would make the bound useless.
|
|
2373
|
+
if (config.livenessTimeoutMs > 86_400_000) {
|
|
2374
|
+
errors.push("livenessTimeoutMs must be less than or equal to 86400000.");
|
|
2375
|
+
}
|
|
2376
|
+
if (config.autoStopInterval != null && config.autoStopInterval < 0) {
|
|
2377
|
+
errors.push("autoStopInterval must be greater than or equal to 0.");
|
|
2378
|
+
}
|
|
2379
|
+
if (config.autoArchiveInterval != null && config.autoArchiveInterval < 0) {
|
|
2380
|
+
errors.push("autoArchiveInterval must be greater than or equal to 0.");
|
|
2381
|
+
}
|
|
2382
|
+
if (config.autoDeleteInterval != null && config.autoDeleteInterval < -1) {
|
|
2383
|
+
errors.push("autoDeleteInterval must be greater than or equal to -1.");
|
|
2384
|
+
}
|
|
2385
|
+
if (!config.apiKey && !(process.env.DAYTONA_API_KEY?.trim())) {
|
|
2386
|
+
errors.push("Daytona sandbox environments require an API key in config or DAYTONA_API_KEY.");
|
|
2387
|
+
}
|
|
2388
|
+
const ttlError = validateCreationTtl(config);
|
|
2389
|
+
if (ttlError)
|
|
2390
|
+
errors.push(ttlError);
|
|
2391
|
+
const resourceRequestError = validateResourceRequest(config);
|
|
2392
|
+
if (resourceRequestError) {
|
|
2393
|
+
errors.push(resourceRequestError);
|
|
2394
|
+
}
|
|
2395
|
+
for (const [key, value] of Object.entries({
|
|
2396
|
+
cpu: config.cpu,
|
|
2397
|
+
memory: config.memory,
|
|
2398
|
+
disk: config.disk,
|
|
2399
|
+
gpu: config.gpu,
|
|
2400
|
+
})) {
|
|
2401
|
+
if (value != null && value <= 0) {
|
|
2402
|
+
errors.push(`${key} must be greater than 0 when provided.`);
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
if (errors.length > 0) {
|
|
2406
|
+
return { ok: false, errors };
|
|
2407
|
+
}
|
|
2408
|
+
// The warm idle window and reconnect grace are host-owned; keep them out of
|
|
2409
|
+
// the saved provider config.
|
|
2410
|
+
const { warmIdleTimeoutMs: _warmIdleTimeoutMs, runnerReconnectGraceMs: _runnerReconnectGraceMs, ...normalizedConfig } = config;
|
|
2411
|
+
return {
|
|
2412
|
+
ok: true,
|
|
2413
|
+
normalizedConfig,
|
|
2414
|
+
};
|
|
2415
|
+
},
|
|
2416
|
+
async onEnvironmentProbe(params) {
|
|
2417
|
+
const config = parseDriverConfig(params.config);
|
|
2418
|
+
try {
|
|
2419
|
+
const sandbox = await createSandbox(params, config);
|
|
2420
|
+
try {
|
|
2421
|
+
const remoteCwd = await resolveSandboxWorkingDirectory(sandbox);
|
|
2422
|
+
const shellCommand = await detectSandboxShellCommand(sandbox, toTimeoutSeconds(config.timeoutMs));
|
|
2423
|
+
return {
|
|
2424
|
+
ok: true,
|
|
2425
|
+
summary: `Connected to Daytona sandbox ${sandbox.name}.`,
|
|
2426
|
+
metadata: {
|
|
2427
|
+
provider: "daytona",
|
|
2428
|
+
shellCommand,
|
|
2429
|
+
sandboxId: sandbox.id,
|
|
2430
|
+
sandboxName: sandbox.name,
|
|
2431
|
+
target: sandbox.target,
|
|
2432
|
+
image: config.image,
|
|
2433
|
+
snapshot: config.snapshot,
|
|
2434
|
+
timeoutMs: config.timeoutMs,
|
|
2435
|
+
reuseLease: config.reuseLease,
|
|
2436
|
+
remoteCwd,
|
|
2437
|
+
},
|
|
2438
|
+
};
|
|
2439
|
+
}
|
|
2440
|
+
finally {
|
|
2441
|
+
const proof = idleActivity.proof(providerActivityKey(params, config, sandbox.id));
|
|
2442
|
+
await sandbox.delete(toTimeoutSeconds(config.timeoutMs), true).then(() => idleActivity.confirm(proof), () => undefined);
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
catch (error) {
|
|
2446
|
+
return {
|
|
2447
|
+
ok: false,
|
|
2448
|
+
summary: "Daytona sandbox probe failed.",
|
|
2449
|
+
metadata: {
|
|
2450
|
+
provider: "daytona",
|
|
2451
|
+
image: config.image,
|
|
2452
|
+
snapshot: config.snapshot,
|
|
2453
|
+
timeoutMs: config.timeoutMs,
|
|
2454
|
+
reuseLease: config.reuseLease,
|
|
2455
|
+
error: formatErrorMessage(error),
|
|
2456
|
+
},
|
|
2457
|
+
};
|
|
2458
|
+
}
|
|
2459
|
+
},
|
|
2460
|
+
async onEnvironmentAcquireLease(params) {
|
|
2461
|
+
const config = parseDriverConfig(params.config);
|
|
2462
|
+
let snapshotIdentity;
|
|
2463
|
+
// One budget covers creation, setup, and inline cleanup. The host leaves
|
|
2464
|
+
// 30 seconds beyond this deadline to receive/journal the cleanup record.
|
|
2465
|
+
const budgetMs = Math.min(config.timeoutMs > 0 ? config.timeoutMs : DEFAULT_DAYTONA_OPERATION_TIMEOUT_MS, DAYTONA_ACQUIRE_ATTEMPT_BUDGET_MS);
|
|
2466
|
+
const createCapMs = Math.min(DAYTONA_CREATE_ATTEMPT_MS, budgetMs);
|
|
2467
|
+
let allocationClaim;
|
|
2468
|
+
const startedAt = Date.now();
|
|
2469
|
+
const deadline = startedAt + budgetMs;
|
|
2470
|
+
let expired = false;
|
|
2471
|
+
let phase = "create";
|
|
2472
|
+
let cleanupInProgress = false;
|
|
2473
|
+
let firstFailure;
|
|
2474
|
+
const observeFailure = () => {
|
|
2475
|
+
// Cleanup may consume the rest of the budget. Keep the original failed
|
|
2476
|
+
// step and time, rather than attributing that failure to its cleanup.
|
|
2477
|
+
return firstFailure ??= {
|
|
2478
|
+
phase,
|
|
2479
|
+
elapsedMs: Math.max(0, Math.min(604_800_000, Date.now() - startedAt)),
|
|
2480
|
+
budgetMs,
|
|
2481
|
+
};
|
|
2482
|
+
};
|
|
2483
|
+
let cleanup;
|
|
2484
|
+
const timeoutFailure = () => {
|
|
2485
|
+
const diagnostic = observeFailure();
|
|
2486
|
+
expired = true;
|
|
2487
|
+
const cause = new Error(`Daytona lease acquisition exceeded ${budgetMs} ms during ${cleanupInProgress ? "cleanup" : phase}`);
|
|
2488
|
+
return cleanup
|
|
2489
|
+
? new PluginEnvironmentCreationCleanupError([cause], "Daytona lease acquisition timed out; allocation cleanup is pending", { ...cleanup, labels: { ...cleanup.labels } }, diagnostic)
|
|
2490
|
+
: cause;
|
|
2491
|
+
};
|
|
2492
|
+
const assertActive = () => {
|
|
2493
|
+
if (expired || Date.now() >= deadline)
|
|
2494
|
+
throw timeoutFailure();
|
|
2495
|
+
};
|
|
2496
|
+
const deadlineFailure = async () => {
|
|
2497
|
+
// Only a create that has neither resolved nor rejected is still pending.
|
|
2498
|
+
const createPending = phase === "create" && firstFailure === undefined ? cleanup : undefined;
|
|
2499
|
+
const diagnostic = observeFailure();
|
|
2500
|
+
// Stop late setup before the lookup, so a late create cannot be admitted.
|
|
2501
|
+
expired = true;
|
|
2502
|
+
if (createPending)
|
|
2503
|
+
diagnostic.providerState = await observeCreateState(config, createPending);
|
|
2504
|
+
return timeoutFailure();
|
|
2505
|
+
};
|
|
2506
|
+
const createWithinCap = async (creating) => {
|
|
2507
|
+
let createdBeforeDecision = false;
|
|
2508
|
+
creating.then(() => { createdBeforeDecision = true; }, () => undefined);
|
|
2509
|
+
let capTimer;
|
|
2510
|
+
const capReached = await Promise.race([
|
|
2511
|
+
creating.then(() => false, () => false),
|
|
2512
|
+
new Promise(resolve => { capTimer = setTimeout(() => resolve(true), Math.max(0, startedAt + createCapMs - Date.now())); }),
|
|
2513
|
+
]).finally(() => clearTimeout(capTimer));
|
|
2514
|
+
if (!capReached || !cleanup || expired || phase !== "create" || firstFailure)
|
|
2515
|
+
return creating;
|
|
2516
|
+
const elapsedMs = Math.max(createCapMs, Date.now() - startedAt);
|
|
2517
|
+
const observed = await lookupCreation(config, cleanup);
|
|
2518
|
+
if (expired || createdBeforeDecision || allocationClaim === "cleanup" || firstFailure)
|
|
2519
|
+
return creating;
|
|
2520
|
+
if (observed.state === "started" && observed.sandbox) {
|
|
2521
|
+
allocationClaim = "adopted";
|
|
2522
|
+
cleanup.observedProviderLeaseId = observed.sandbox.id;
|
|
2523
|
+
idleActivity.observe(idleActivity.resource(providerActivityKey(params, config, cleanup.providerLeaseId), true), providerActivityKey(params, config, observed.sandbox.id));
|
|
2524
|
+
return observed.sandbox;
|
|
2525
|
+
}
|
|
2526
|
+
if (SNAPSHOT_PREPARATION_STATES.has(observed.state))
|
|
2527
|
+
return creating;
|
|
2528
|
+
firstFailure = { phase: "create", elapsedMs, budgetMs: createCapMs, providerState: observed.state };
|
|
2529
|
+
expired = true;
|
|
2530
|
+
throw timeoutFailure();
|
|
2531
|
+
};
|
|
2532
|
+
const acquire = async () => {
|
|
2533
|
+
const creating = traceLeaseStep("lease.create", () => createSandbox(params, config, {
|
|
2534
|
+
onCreateAttempt: (attempt) => { assertActive(); cleanup = attempt; },
|
|
2535
|
+
onCreateFailure: observeFailure,
|
|
2536
|
+
onSnapshotIdentity: identity => { snapshotIdentity = identity; },
|
|
2537
|
+
claimCleanup: () => {
|
|
2538
|
+
if (allocationClaim === "adopted")
|
|
2539
|
+
return false;
|
|
2540
|
+
allocationClaim = "cleanup";
|
|
2541
|
+
return true;
|
|
2542
|
+
},
|
|
2543
|
+
}));
|
|
2544
|
+
const sandbox = createCapMs < budgetMs ? await createWithinCap(creating) : await creating;
|
|
2545
|
+
try {
|
|
2546
|
+
if (allocationClaim === "adopted")
|
|
2547
|
+
await confirmCreationTtl(sandbox, config);
|
|
2548
|
+
assertActive();
|
|
2549
|
+
if (cleanup)
|
|
2550
|
+
cleanup.observedProviderLeaseId = sandbox.id;
|
|
2551
|
+
phase = "workspace";
|
|
2552
|
+
const remoteCwd = await traceLeaseStep("lease.workspace", () => resolveSandboxWorkingDirectory(sandbox));
|
|
2553
|
+
assertActive();
|
|
2554
|
+
phase = "shell";
|
|
2555
|
+
const shellCommand = await traceLeaseStep("lease.shell", () => detectSandboxShellCommand(sandbox, toTimeoutSeconds(Math.max(1, deadline - Date.now()))));
|
|
2556
|
+
assertActive();
|
|
2557
|
+
// Configure a provider-side destroy time at or before a caller deadline, so
|
|
2558
|
+
// an abandoned sandbox self-destroys even if Paperclip is down. The lease
|
|
2559
|
+
// carries the real provider expiry (or none) as evidence of the bound.
|
|
2560
|
+
phase = "expiry";
|
|
2561
|
+
const expiresAt = await traceLeaseStep("lease.expiry", () => configureSandboxExpiry({
|
|
2562
|
+
sandbox,
|
|
2563
|
+
requestedExpiresAt: params.requestedExpiresAt,
|
|
2564
|
+
nowMs: Date.now(),
|
|
2565
|
+
preserveCreationExpiry: config.ttlMinutes != null,
|
|
2566
|
+
}));
|
|
2567
|
+
assertActive();
|
|
2568
|
+
phase = "sentinel";
|
|
2569
|
+
const workspaceSentinel = await traceLeaseStep("lease.sentinel", () => writeWorkspaceSentinel({
|
|
2570
|
+
sandbox,
|
|
2571
|
+
remoteCwd,
|
|
2572
|
+
params,
|
|
2573
|
+
config,
|
|
2574
|
+
timeoutSeconds: toTimeoutSeconds(Math.max(1, deadline - Date.now())),
|
|
2575
|
+
}));
|
|
2576
|
+
assertActive();
|
|
2577
|
+
sandboxHandleLeaseAdmissionStates.open({
|
|
2578
|
+
driverKey: params.driverKey,
|
|
2579
|
+
companyId: params.companyId,
|
|
2580
|
+
environmentId: params.environmentId,
|
|
2581
|
+
providerLeaseId: sandbox.id,
|
|
2582
|
+
config,
|
|
2583
|
+
});
|
|
2584
|
+
// Seed the handle cache with the fresh handle under the exact scope that
|
|
2585
|
+
// `onEnvironmentRealizeWorkspace` reads (providerLeaseId === sandbox.id).
|
|
2586
|
+
// Realize then reuses this handle instead of paying a real `client.get`.
|
|
2587
|
+
sandboxHandleCache.seed({
|
|
2588
|
+
driverKey: params.driverKey,
|
|
2589
|
+
companyId: params.companyId,
|
|
2590
|
+
environmentId: params.environmentId,
|
|
2591
|
+
providerLeaseId: sandbox.id,
|
|
2592
|
+
config,
|
|
2593
|
+
}, sandbox);
|
|
2594
|
+
return {
|
|
2595
|
+
providerLeaseId: sandbox.id,
|
|
2596
|
+
expiresAt,
|
|
2597
|
+
metadata: leaseMetadata({
|
|
2598
|
+
config,
|
|
2599
|
+
sandbox,
|
|
2600
|
+
shellCommand,
|
|
2601
|
+
remoteCwd,
|
|
2602
|
+
resumedLease: false,
|
|
2603
|
+
workspaceSentinel,
|
|
2604
|
+
snapshotIdentity,
|
|
2605
|
+
}),
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
catch (error) {
|
|
2609
|
+
const diagnostic = observeFailure();
|
|
2610
|
+
// After timeout the host owns the durable cleanup record. A late SDK
|
|
2611
|
+
// completion must not admit this lease or start another setup phase.
|
|
2612
|
+
if (!expired) {
|
|
2613
|
+
cleanupInProgress = true;
|
|
2614
|
+
try {
|
|
2615
|
+
const proof = idleActivity.proof(providerActivityKey(params, config, sandbox.id));
|
|
2616
|
+
await traceLeaseStep("lease.cleanup", () => sandbox.delete(toTimeoutSeconds(Math.max(1, deadline - Date.now())), true));
|
|
2617
|
+
idleActivity.confirm(proof);
|
|
2618
|
+
}
|
|
2619
|
+
catch (cleanupError) {
|
|
2620
|
+
if (cleanup) {
|
|
2621
|
+
throw new PluginEnvironmentCreationCleanupError([error, cleanupError], "Daytona lease setup failed; allocation cleanup is pending", { ...cleanup, labels: { ...cleanup.labels } }, diagnostic);
|
|
2622
|
+
}
|
|
2623
|
+
throw error;
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
throw error;
|
|
2627
|
+
}
|
|
2628
|
+
};
|
|
2629
|
+
let timer;
|
|
2630
|
+
let timedOut = false;
|
|
2631
|
+
try {
|
|
2632
|
+
return await Promise.race([
|
|
2633
|
+
// After the deadline only the timer settles the call: a late create
|
|
2634
|
+
// rejection cannot replace the timeout's ownership and observation.
|
|
2635
|
+
idleActivity.track(acquire).catch((error) => timedOut ? new Promise(() => undefined)
|
|
2636
|
+
: Promise.reject(withTransportFailureCode(error))),
|
|
2637
|
+
new Promise((_resolve, reject) => {
|
|
2638
|
+
timer = setTimeout(() => { timedOut = true; void deadlineFailure().then(reject); }, budgetMs);
|
|
2639
|
+
}),
|
|
2640
|
+
]);
|
|
2641
|
+
}
|
|
2642
|
+
finally {
|
|
2643
|
+
clearTimeout(timer);
|
|
2644
|
+
}
|
|
2645
|
+
},
|
|
2646
|
+
async onEnvironmentResumeLease(params) {
|
|
2647
|
+
const config = parseDriverConfig(params.config);
|
|
2648
|
+
const requestedCwd = params.requestedCwd;
|
|
2649
|
+
if (requestedCwd !== undefined && (typeof requestedCwd !== "string" || requestedCwd.includes("\0")
|
|
2650
|
+
|| !path.posix.isAbsolute(requestedCwd) || path.posix.normalize(requestedCwd) !== requestedCwd
|
|
2651
|
+
|| params.leaseMetadata?.remoteCwd !== requestedCwd)) {
|
|
2652
|
+
throw new Error("The requested directory does not match the recorded Daytona workspace directory.");
|
|
2653
|
+
}
|
|
2654
|
+
if (params.leaseMetadata?.reuseLease === false) {
|
|
2655
|
+
const sentinel = isRecord(params.leaseMetadata.workspaceSentinel) ? params.leaseMetadata.workspaceSentinel : null;
|
|
2656
|
+
const intent = isRecord(params.leaseMetadata.nativeWorkspaceExportResume) ? params.leaseMetadata.nativeWorkspaceExportResume : null;
|
|
2657
|
+
// Ephemeral recovery is bound at acquisition. Never mint proof during
|
|
2658
|
+
// resume, accept a copied sentinel for a replacement, or waive legacy proof.
|
|
2659
|
+
if (typeof sentinel?.token !== "string" || !sentinel.token || typeof sentinel.runId !== "string" || !sentinel.runId
|
|
2660
|
+
|| sentinel.providerLeaseId !== params.providerLeaseId || params.leaseMetadata.sandboxId !== params.providerLeaseId
|
|
2661
|
+
|| (intent && intent.runId !== sentinel.runId)) {
|
|
2662
|
+
return { providerLeaseId: null, metadata: { expired: true, workspaceSentinel: { result: "mismatch" } } };
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
const scope = {
|
|
2666
|
+
driverKey: params.driverKey,
|
|
2667
|
+
companyId: params.companyId,
|
|
2668
|
+
environmentId: params.environmentId,
|
|
2669
|
+
providerLeaseId: params.providerLeaseId,
|
|
2670
|
+
config,
|
|
2671
|
+
};
|
|
2672
|
+
// A confirmed stop may precede completion of an old SDK request. Do not
|
|
2673
|
+
// restart its sandbox under that request; it could still write or execute.
|
|
2674
|
+
if (sandboxHandleLeaseAdmissionStates.isClosed(scope) && sandboxHandleActivityGates.isActive(scope)) {
|
|
2675
|
+
throw new Error("The stopped Daytona sandbox is still settling cancelled work. Retry shortly.");
|
|
2676
|
+
}
|
|
2677
|
+
return await withSandboxActivityGate(scope, async () => {
|
|
2678
|
+
const sandbox = await traceLeaseStep("lease.lookup", () => getSandboxOrNull(scope, { bypassTeardownGate: true }));
|
|
2679
|
+
if (!sandbox) {
|
|
2680
|
+
return { providerLeaseId: null, metadata: { expired: true } };
|
|
2681
|
+
}
|
|
2682
|
+
// Daytona can retain the API record after losing its container. Confirm
|
|
2683
|
+
// the exact provider report again before allowing the host's existing
|
|
2684
|
+
// backup-guarded replacement path. Unknown errors preserve the lease.
|
|
2685
|
+
if (hasMissingSandboxContainer(sandbox)) {
|
|
2686
|
+
try {
|
|
2687
|
+
await traceLeaseStep("lease.refresh", () => withLivenessTimeout("sandbox.refreshData", config.livenessTimeoutMs, () => sandbox.refreshData()));
|
|
2688
|
+
assertHandleMatchesLease(sandbox, params.providerLeaseId);
|
|
2689
|
+
}
|
|
2690
|
+
catch (error) {
|
|
2691
|
+
evictSandboxHandle(scope);
|
|
2692
|
+
if (error instanceof DaytonaNotFoundError) {
|
|
2693
|
+
return { providerLeaseId: null, metadata: { expired: true } };
|
|
2694
|
+
}
|
|
2695
|
+
throw error;
|
|
2696
|
+
}
|
|
2697
|
+
if (hasMissingSandboxContainer(sandbox)) {
|
|
2698
|
+
evictSandboxHandle(scope);
|
|
2699
|
+
return { providerLeaseId: null, metadata: { expired: true } };
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
// A stopped sandbox loses its session shell, so the stored session id is
|
|
2703
|
+
// stale after a real restart. Clear the id only when the sandbox is not
|
|
2704
|
+
// already running, and clear it before the restart. A stopped sandbox has
|
|
2705
|
+
// no live session, so the clear drops a dead id and a later command opens
|
|
2706
|
+
// a fresh session. A running sandbox keeps its live session, so the resume
|
|
2707
|
+
// leaves the id in place; a concurrent command still finds it and teardown
|
|
2708
|
+
// deletes one session. An unconditional clear would drop the id of a live
|
|
2709
|
+
// session and leak its shell until sandbox reaping.
|
|
2710
|
+
if (sandbox.state !== "started") {
|
|
2711
|
+
sandboxHandleSessionStore.clear(scope);
|
|
2712
|
+
// A stopped sandbox loses its pseudo-terminals, so a stored duplex channel
|
|
2713
|
+
// is dead after a real restart. Close and drop every channel on this lease
|
|
2714
|
+
// before the restart, so no stale channel id survives the resume.
|
|
2715
|
+
await traceLeaseStep("lease.channel_cleanup", () => closeDaytonaDuplexChannelsForLease(params.providerLeaseId));
|
|
2716
|
+
}
|
|
2717
|
+
const resumedFromState = sandbox.state ?? null;
|
|
2718
|
+
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs), scope);
|
|
2719
|
+
// A sandbox created before a host floor (or under a shorter warm window
|
|
2720
|
+
// or reconnect grace) keeps its old auto-stop. Raise it on resume so the
|
|
2721
|
+
// provider backstop cannot race the host's warm idle window or a later
|
|
2722
|
+
// controller outage. Best effort: the host's bounded resume retry still
|
|
2723
|
+
// covers a refused resume.
|
|
2724
|
+
const autoStopInterval = effectiveAutoStopIntervalMinutes(config);
|
|
2725
|
+
const currentAutoStop = sandbox.autoStopInterval;
|
|
2726
|
+
if (autoStopInterval != null && autoStopInterval > 0 && hostAutoStopFloorsMs(config).length > 0
|
|
2727
|
+
&& typeof currentAutoStop === "number" && currentAutoStop > 0 && currentAutoStop < autoStopInterval) {
|
|
2728
|
+
await withLivenessTimeout("sandbox.setAutostopInterval", Math.max(1, Math.min(config.livenessTimeoutMs > 0 ? config.livenessTimeoutMs : AUTO_STOP_UPDATE_TIMEOUT_MS, AUTO_STOP_UPDATE_TIMEOUT_MS)), () => Promise.resolve().then(() => sandbox.setAutostopInterval(autoStopInterval))).catch(() => undefined);
|
|
2729
|
+
}
|
|
2730
|
+
try {
|
|
2731
|
+
return await traceLeaseStep("lease.verify", async () => {
|
|
2732
|
+
const remoteCwd = await traceLeaseStep("lease.workspace", () => resolveSandboxWorkingDirectory(sandbox, false));
|
|
2733
|
+
// C3: a resumed lease must clear the workspace sentinel before it is
|
|
2734
|
+
// trusted, even when the handle came from the cache. On any non-match we
|
|
2735
|
+
// evict the cached handle and expire the lease so a stale/foreign sandbox
|
|
2736
|
+
// is never reused on the subsequent (sentinel-skipping) exec path.
|
|
2737
|
+
const workspaceSentinel = await traceLeaseStep("lease.sentinel", () => verifyWorkspaceSentinel({
|
|
2738
|
+
sandbox,
|
|
2739
|
+
remoteCwd,
|
|
2740
|
+
leaseMetadata: params.leaseMetadata,
|
|
2741
|
+
timeoutSeconds: toTimeoutSeconds(config.timeoutMs),
|
|
2742
|
+
}));
|
|
2743
|
+
if (workspaceSentinel.result !== "matched") {
|
|
2744
|
+
evictSandboxHandle(scope);
|
|
2745
|
+
return {
|
|
2746
|
+
providerLeaseId: null,
|
|
2747
|
+
metadata: { expired: true, workspaceSentinel },
|
|
2748
|
+
};
|
|
2749
|
+
}
|
|
2750
|
+
const shellCommand = await traceLeaseStep("lease.shell", () => detectSandboxShellCommand(sandbox, toTimeoutSeconds(config.timeoutMs)));
|
|
2751
|
+
sandboxHandleCache.markFresh(scope);
|
|
2752
|
+
sandboxHandleLeaseAdmissionStates.open(scope);
|
|
2753
|
+
return {
|
|
2754
|
+
providerLeaseId: sandbox.id,
|
|
2755
|
+
metadata: leaseMetadata({
|
|
2756
|
+
config,
|
|
2757
|
+
sandbox,
|
|
2758
|
+
shellCommand,
|
|
2759
|
+
remoteCwd: requestedCwd ?? remoteCwd,
|
|
2760
|
+
resumedLease: true,
|
|
2761
|
+
resumedFromState,
|
|
2762
|
+
sandboxState: "started",
|
|
2763
|
+
workspaceSentinel,
|
|
2764
|
+
}),
|
|
2765
|
+
};
|
|
2766
|
+
});
|
|
2767
|
+
}
|
|
2768
|
+
catch (error) {
|
|
2769
|
+
evictSandboxHandle(scope);
|
|
2770
|
+
// A timeout, rate limit, or provider 5xx does not prove this sandbox is
|
|
2771
|
+
// lost. Preserve the exact resource and let the host retry its recorded
|
|
2772
|
+
// lease; replacement is permitted only after an explicit not-found or
|
|
2773
|
+
// an immutable workspace identity mismatch.
|
|
2774
|
+
throw error;
|
|
2775
|
+
}
|
|
2776
|
+
}, { allowClosed: true, traceLeaseWait: true });
|
|
2777
|
+
},
|
|
2778
|
+
onEnvironmentStopLease: stopLease,
|
|
2779
|
+
async onEnvironmentReleaseLease(params) {
|
|
2780
|
+
if (!params.providerLeaseId)
|
|
2781
|
+
return;
|
|
2782
|
+
if (params.resourceDisposition === "stop_and_retain")
|
|
2783
|
+
return stopLease(params);
|
|
2784
|
+
const config = parseDriverConfig(params.config);
|
|
2785
|
+
const scope = {
|
|
2786
|
+
driverKey: params.driverKey,
|
|
2787
|
+
companyId: params.companyId,
|
|
2788
|
+
environmentId: params.environmentId,
|
|
2789
|
+
providerLeaseId: params.providerLeaseId,
|
|
2790
|
+
config,
|
|
2791
|
+
};
|
|
2792
|
+
// C4: the lease's handle must not outlive its teardown. A teardown gate
|
|
2793
|
+
// blocks fresh cache reads while cleanup is in flight so overlapping
|
|
2794
|
+
// exec/sync calls cannot reacquire the same sandbox mid-stop/delete.
|
|
2795
|
+
const teardownGate = sandboxHandleTeardownGates.begin(scope);
|
|
2796
|
+
sandboxHandleLeaseAdmissionStates.close(scope);
|
|
2797
|
+
let cleanupProof = idleActivity.proof(sandboxHandleCacheKey(scope));
|
|
2798
|
+
try {
|
|
2799
|
+
const sandbox = await getSandboxOrNull(scope, { bypassTeardownGate: true });
|
|
2800
|
+
if (!sandbox)
|
|
2801
|
+
return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
|
2802
|
+
evictSandboxHandle(scope);
|
|
2803
|
+
if (params.cancelActiveWork) {
|
|
2804
|
+
// Graceful release waits for activity below. Stop must not wait on the
|
|
2805
|
+
// command it is cancelling. Admission is already closed for this lease.
|
|
2806
|
+
const timeoutSeconds = Math.min(toTimeoutSeconds(config.timeoutMs), 30);
|
|
2807
|
+
await withLivenessTimeout("sandbox.refreshData", Math.min(config.livenessTimeoutMs, 30_000), () => sandbox.refreshData());
|
|
2808
|
+
if (sandbox.state !== "stopped")
|
|
2809
|
+
await sandbox.stop(timeoutSeconds);
|
|
2810
|
+
sandboxHandleSessionStore.clear(scope);
|
|
2811
|
+
await closeDaytonaDuplexChannelsForLease(params.providerLeaseId);
|
|
2812
|
+
return confirmedTermination(scope, "stopped", cleanupProof);
|
|
2813
|
+
}
|
|
2814
|
+
await drainSandboxBeforeTermination(sandbox, scope);
|
|
2815
|
+
cleanupProof = idleActivity.proof(sandboxHandleCacheKey(scope));
|
|
2816
|
+
// A cached stopped state is not a receipt: the resource could have been
|
|
2817
|
+
// resumed since the handle was cached. Read provider state at this boundary.
|
|
2818
|
+
await withLivenessTimeout("sandbox.refreshData", config.livenessTimeoutMs, () => sandbox.refreshData());
|
|
2819
|
+
if (config.reuseLease) {
|
|
2820
|
+
if (sandbox.state !== "stopped") {
|
|
2821
|
+
try {
|
|
2822
|
+
await terminateAtProvider(scope, "sandbox.stop", () => sandbox.stop(toTimeoutSeconds(config.timeoutMs)));
|
|
2823
|
+
}
|
|
2824
|
+
catch (error) {
|
|
2825
|
+
console.warn(`Failed to stop Daytona sandbox during lease release: ${formatErrorMessage(error)}. Attempting delete instead.`);
|
|
2826
|
+
await terminateAtProvider(scope, "sandbox.delete", () => sandbox.delete(toTimeoutSeconds(config.timeoutMs), true));
|
|
2827
|
+
return confirmedTermination(scope, "destroyed", cleanupProof);
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2830
|
+
return confirmedTermination(scope, "stopped", cleanupProof);
|
|
2831
|
+
}
|
|
2832
|
+
if (config.archiveOnRelease) {
|
|
2833
|
+
try {
|
|
2834
|
+
if (sandbox.state !== "stopped") {
|
|
2835
|
+
await terminateAtProvider(scope, "sandbox.stop", () => sandbox.stop(toTimeoutSeconds(config.timeoutMs)));
|
|
2836
|
+
}
|
|
2837
|
+
await sandbox.setAutoDeleteInterval(ARCHIVE_ON_RELEASE_AUTO_DELETE_MINUTES);
|
|
2838
|
+
await sandbox.archive();
|
|
2839
|
+
return confirmedTermination(scope, "stopped", cleanupProof);
|
|
2840
|
+
}
|
|
2841
|
+
catch (error) {
|
|
2842
|
+
console.warn(`Failed to archive Daytona sandbox during lease release: ${formatErrorMessage(error)}. Falling back to delete.`);
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
await terminateAtProvider(scope, "sandbox.delete", () => sandbox.delete(toTimeoutSeconds(config.timeoutMs), true));
|
|
2846
|
+
return confirmedTermination(scope, "destroyed", cleanupProof);
|
|
2847
|
+
}
|
|
2848
|
+
finally {
|
|
2849
|
+
sandboxHandleTeardownGates.end(scope, teardownGate);
|
|
2850
|
+
evictSandboxHandle(scope);
|
|
2851
|
+
}
|
|
2852
|
+
},
|
|
2853
|
+
async onEnvironmentInspectLease(params) {
|
|
2854
|
+
// An environment-variable fallback may have changed accounts since this
|
|
2855
|
+
// historical allocation. Inspection requires explicitly scoped credentials.
|
|
2856
|
+
if (typeof params.config.apiKey !== "string" || !params.config.apiKey.trim()) {
|
|
2857
|
+
return { providerLeaseId: params.providerLeaseId, state: "unknown" };
|
|
2858
|
+
}
|
|
2859
|
+
const config = parseDriverConfig(params.config);
|
|
2860
|
+
if (!config.apiUrl && (process.env.DAYTONA_API_URL?.trim() || process.env.DAYTONA_SERVER_URL?.trim())) {
|
|
2861
|
+
return { providerLeaseId: params.providerLeaseId, state: "unknown" };
|
|
2862
|
+
}
|
|
2863
|
+
if (params.creationOperation !== undefined) {
|
|
2864
|
+
const { id: attemptId, runId } = params.creationOperation;
|
|
2865
|
+
if (![attemptId, runId].every(value => typeof value === "string" && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value))) {
|
|
2866
|
+
throw new Error("Invalid creation operation identity");
|
|
2867
|
+
}
|
|
2868
|
+
const name = `paperclip-create-${attemptId}`;
|
|
2869
|
+
try {
|
|
2870
|
+
const sandbox = await withLivenessTimeout("sandbox.creationLookup", 10_000, () => createDaytonaClient(config).get(name));
|
|
2871
|
+
const labels = {
|
|
2872
|
+
"paperclip-provider": "daytona", "paperclip-create-attempt": attemptId,
|
|
2873
|
+
"paperclip-company-id": params.companyId, "paperclip-environment-id": params.environmentId,
|
|
2874
|
+
"paperclip-run-id": runId,
|
|
2875
|
+
};
|
|
2876
|
+
if (sandbox.name !== name || Object.entries(labels).some(([key, value]) => sandbox.labels?.[key] !== value)) {
|
|
2877
|
+
throw new Error("Creation operation ownership does not match");
|
|
2878
|
+
}
|
|
2879
|
+
return { providerLeaseId: name, state: "active", creationCleanup: {
|
|
2880
|
+
providerLeaseId: name, observedProviderLeaseId: sandbox.id, companyId: params.companyId,
|
|
2881
|
+
environmentId: params.environmentId, runId: labels["paperclip-run-id"], attemptId,
|
|
2882
|
+
accountFingerprint: sandboxAccountDiscriminator(config), labels,
|
|
2883
|
+
} };
|
|
2884
|
+
}
|
|
2885
|
+
catch (error) {
|
|
2886
|
+
if (error instanceof DaytonaNotFoundError)
|
|
2887
|
+
return { providerLeaseId: name, state: "unknown" };
|
|
2888
|
+
throw error;
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
const proof = idleActivity.proof(providerActivityKey(params, config, params.providerLeaseId));
|
|
2892
|
+
// Read directly from the provider. The setup-status path and cached lease
|
|
2893
|
+
// reconnect path can start a stopped sandbox, so neither is an observation.
|
|
2894
|
+
try {
|
|
2895
|
+
const sandbox = await createDaytonaClient(config).get(params.providerLeaseId);
|
|
2896
|
+
if (sandbox.id !== params.providerLeaseId)
|
|
2897
|
+
return { providerLeaseId: params.providerLeaseId, state: "unknown" };
|
|
2898
|
+
if (sandbox.state === "stopped" || sandbox.state === "archived") {
|
|
2899
|
+
idleActivity.confirm(proof, true);
|
|
2900
|
+
}
|
|
2901
|
+
return { providerLeaseId: sandbox.id, state: sandbox.state === "stopped" ? "stopped" : "active" };
|
|
2902
|
+
}
|
|
2903
|
+
catch (error) {
|
|
2904
|
+
if (error instanceof DaytonaNotFoundError) {
|
|
2905
|
+
idleActivity.confirm(proof, true);
|
|
2906
|
+
return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
|
2907
|
+
}
|
|
2908
|
+
throw error;
|
|
2909
|
+
}
|
|
2910
|
+
},
|
|
2911
|
+
async onEnvironmentDestroyLease(params) {
|
|
2912
|
+
if (!params.providerLeaseId)
|
|
2913
|
+
return;
|
|
2914
|
+
const config = parseDriverConfig(params.config);
|
|
2915
|
+
if (params.leaseMetadata?.failedCreateCleanup !== undefined) {
|
|
2916
|
+
const cleanup = readEnvironmentCreationCleanupError({ data: {
|
|
2917
|
+
schema: "paperclip/environment-creation-cleanup/v1", cleanup: params.leaseMetadata.failedCreateCleanup,
|
|
2918
|
+
} });
|
|
2919
|
+
if (!cleanup || cleanup.companyId !== params.companyId || cleanup.environmentId !== params.environmentId ||
|
|
2920
|
+
cleanup.providerLeaseId !== params.providerLeaseId) {
|
|
2921
|
+
throw new Error("Failed-create sandbox cleanup scope does not match");
|
|
2922
|
+
}
|
|
2923
|
+
await destroyFailedCreation(config, cleanup, params.driverKey, true);
|
|
2924
|
+
return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
|
2925
|
+
}
|
|
2926
|
+
const scope = {
|
|
2927
|
+
driverKey: params.driverKey,
|
|
2928
|
+
companyId: params.companyId,
|
|
2929
|
+
environmentId: params.environmentId,
|
|
2930
|
+
providerLeaseId: params.providerLeaseId,
|
|
2931
|
+
config,
|
|
2932
|
+
};
|
|
2933
|
+
// C4: the teardown gate blocks fresh cache reads while delete is in flight
|
|
2934
|
+
// so overlapping exec/sync calls cannot reacquire the same sandbox mid-teardown.
|
|
2935
|
+
const teardownGate = sandboxHandleTeardownGates.begin(scope);
|
|
2936
|
+
sandboxHandleLeaseAdmissionStates.close(scope);
|
|
2937
|
+
try {
|
|
2938
|
+
const sandbox = await getSandboxOrNull(scope, { bypassTeardownGate: true });
|
|
2939
|
+
if (!sandbox)
|
|
2940
|
+
return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
|
2941
|
+
evictSandboxHandle(scope);
|
|
2942
|
+
await drainSandboxBeforeTermination(sandbox, scope);
|
|
2943
|
+
const cleanupProof = idleActivity.proof(sandboxHandleCacheKey(scope));
|
|
2944
|
+
await terminateAtProvider(scope, "sandbox.delete", () => sandbox.delete(toTimeoutSeconds(config.timeoutMs), true));
|
|
2945
|
+
return confirmedTermination(scope, "destroyed", cleanupProof);
|
|
2946
|
+
}
|
|
2947
|
+
finally {
|
|
2948
|
+
sandboxHandleTeardownGates.end(scope, teardownGate);
|
|
2949
|
+
evictSandboxHandle(scope);
|
|
2950
|
+
}
|
|
2951
|
+
},
|
|
2952
|
+
async onEnvironmentRealizeWorkspace(params) {
|
|
2953
|
+
const config = parseDriverConfig(params.config);
|
|
2954
|
+
const remoteCwd = typeof params.lease.metadata?.remoteCwd === "string" &&
|
|
2955
|
+
params.lease.metadata.remoteCwd.trim().length > 0
|
|
2956
|
+
? params.lease.metadata.remoteCwd.trim()
|
|
2957
|
+
: params.workspace.remotePath ?? params.workspace.localPath ?? "/paperclip-workspace";
|
|
2958
|
+
if (params.lease.providerLeaseId) {
|
|
2959
|
+
const scope = {
|
|
2960
|
+
driverKey: params.driverKey,
|
|
2961
|
+
companyId: params.companyId,
|
|
2962
|
+
environmentId: params.environmentId,
|
|
2963
|
+
providerLeaseId: params.lease.providerLeaseId,
|
|
2964
|
+
config,
|
|
2965
|
+
};
|
|
2966
|
+
await withSandboxActivityGate(scope, async () => {
|
|
2967
|
+
const sandbox = await getSandbox(scope, { bypassTeardownGate: true });
|
|
2968
|
+
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs), scope);
|
|
2969
|
+
await sandbox.fs.createFolder(remoteCwd, "755");
|
|
2970
|
+
});
|
|
2971
|
+
}
|
|
2972
|
+
return {
|
|
2973
|
+
cwd: remoteCwd,
|
|
2974
|
+
metadata: {
|
|
2975
|
+
provider: "daytona",
|
|
2976
|
+
remoteCwd,
|
|
2977
|
+
},
|
|
2978
|
+
};
|
|
2979
|
+
},
|
|
2980
|
+
async onEnvironmentStartInteractiveSetup(params) {
|
|
2981
|
+
const baseConfig = parseDriverConfig(params.config);
|
|
2982
|
+
const config = withSetupSourceTemplate(baseConfig, params);
|
|
2983
|
+
const sandbox = await createSandbox(params, config, { purpose: "interactive_setup" });
|
|
2984
|
+
try {
|
|
2985
|
+
const remoteCwd = await resolveSandboxWorkingDirectory(sandbox);
|
|
2986
|
+
const shellCommand = await detectSandboxShellCommand(sandbox, toTimeoutSeconds(config.timeoutMs));
|
|
2987
|
+
const connection = await createSshConnection(sandbox, resolveConnectionExpiresInMinutes(params.connectionExpiresInMinutes));
|
|
2988
|
+
sandboxHandleLeaseAdmissionStates.open({
|
|
2989
|
+
driverKey: params.driverKey,
|
|
2990
|
+
companyId: params.companyId,
|
|
2991
|
+
environmentId: params.environmentId,
|
|
2992
|
+
providerLeaseId: sandbox.id,
|
|
2993
|
+
config,
|
|
2994
|
+
});
|
|
2995
|
+
return {
|
|
2996
|
+
providerLeaseId: sandbox.id,
|
|
2997
|
+
status: "waiting_for_user",
|
|
2998
|
+
expiresAt: params.expiresAt ?? connection.connectionPayload?.expiresAt ?? null,
|
|
2999
|
+
...connection,
|
|
3000
|
+
metadata: interactiveSetupMetadata({
|
|
3001
|
+
config,
|
|
3002
|
+
sandbox,
|
|
3003
|
+
shellCommand,
|
|
3004
|
+
remoteCwd,
|
|
3005
|
+
sourceTemplateRef: params.sourceTemplateRef,
|
|
3006
|
+
}),
|
|
3007
|
+
};
|
|
3008
|
+
}
|
|
3009
|
+
catch (error) {
|
|
3010
|
+
const proof = idleActivity.proof(providerActivityKey(params, config, sandbox.id));
|
|
3011
|
+
await sandbox.delete(toTimeoutSeconds(config.timeoutMs), true).then(() => idleActivity.confirm(proof), () => undefined);
|
|
3012
|
+
throw error;
|
|
3013
|
+
}
|
|
3014
|
+
},
|
|
3015
|
+
async onEnvironmentGetInteractiveSetup(params) {
|
|
3016
|
+
const config = parseDriverConfig(params.config);
|
|
3017
|
+
if (!params.providerLeaseId) {
|
|
3018
|
+
return {
|
|
3019
|
+
providerLeaseId: null,
|
|
3020
|
+
status: "missing",
|
|
3021
|
+
connectionSummary: null,
|
|
3022
|
+
connectionPayload: null,
|
|
3023
|
+
metadata: {
|
|
3024
|
+
provider: "daytona",
|
|
3025
|
+
missing: true,
|
|
3026
|
+
},
|
|
3027
|
+
};
|
|
3028
|
+
}
|
|
3029
|
+
const scope = {
|
|
3030
|
+
driverKey: params.driverKey,
|
|
3031
|
+
companyId: params.companyId,
|
|
3032
|
+
environmentId: params.environmentId,
|
|
3033
|
+
providerLeaseId: params.providerLeaseId,
|
|
3034
|
+
config,
|
|
3035
|
+
};
|
|
3036
|
+
return await withSandboxActivityGate(scope, async () => {
|
|
3037
|
+
const sandbox = await getSandboxOrNull(scope, { bypassTeardownGate: true });
|
|
3038
|
+
if (!sandbox) {
|
|
3039
|
+
return {
|
|
3040
|
+
providerLeaseId: null,
|
|
3041
|
+
status: "missing",
|
|
3042
|
+
connectionSummary: null,
|
|
3043
|
+
connectionPayload: null,
|
|
3044
|
+
metadata: {
|
|
3045
|
+
provider: "daytona",
|
|
3046
|
+
missing: true,
|
|
3047
|
+
},
|
|
3048
|
+
};
|
|
3049
|
+
}
|
|
3050
|
+
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs), scope);
|
|
3051
|
+
const remoteCwd = await resolveSandboxWorkingDirectory(sandbox);
|
|
3052
|
+
const shellCommand = await detectSandboxShellCommand(sandbox, toTimeoutSeconds(config.timeoutMs));
|
|
3053
|
+
const connection = params.includeConnectionPayload === true
|
|
3054
|
+
? await createSshConnection(sandbox, resolveConnectionExpiresInMinutes(params.connectionExpiresInMinutes))
|
|
3055
|
+
: {
|
|
3056
|
+
connectionSummary: {
|
|
3057
|
+
type: "ssh",
|
|
3058
|
+
username: "token",
|
|
3059
|
+
hostRedacted: true,
|
|
3060
|
+
portRedacted: true,
|
|
3061
|
+
commandRedacted: true,
|
|
3062
|
+
metadata: {
|
|
3063
|
+
provider: "daytona",
|
|
3064
|
+
},
|
|
3065
|
+
},
|
|
3066
|
+
connectionPayload: null,
|
|
3067
|
+
};
|
|
3068
|
+
return {
|
|
3069
|
+
providerLeaseId: sandbox.id,
|
|
3070
|
+
status: "waiting_for_user",
|
|
3071
|
+
...connection,
|
|
3072
|
+
metadata: interactiveSetupMetadata({
|
|
3073
|
+
config,
|
|
3074
|
+
sandbox,
|
|
3075
|
+
shellCommand,
|
|
3076
|
+
remoteCwd,
|
|
3077
|
+
}),
|
|
3078
|
+
};
|
|
3079
|
+
});
|
|
3080
|
+
},
|
|
3081
|
+
async onEnvironmentCaptureTemplate(params) {
|
|
3082
|
+
const config = parseDriverConfig(params.config);
|
|
3083
|
+
if (!params.providerLeaseId) {
|
|
3084
|
+
throw new Error("Cannot capture a Daytona template without a setup sandbox lease.");
|
|
3085
|
+
}
|
|
3086
|
+
const scope = {
|
|
3087
|
+
driverKey: params.driverKey,
|
|
3088
|
+
companyId: params.companyId,
|
|
3089
|
+
environmentId: params.environmentId,
|
|
3090
|
+
providerLeaseId: params.providerLeaseId,
|
|
3091
|
+
config,
|
|
3092
|
+
};
|
|
3093
|
+
return await withSandboxActivityGate(scope, async () => {
|
|
3094
|
+
const sandbox = await getSandbox(scope, { bypassTeardownGate: true });
|
|
3095
|
+
const createSnapshot = sandbox._experimental_createSnapshot;
|
|
3096
|
+
if (typeof createSnapshot !== "function") {
|
|
3097
|
+
throw new Error("Daytona template capture requires @daytonaio/sdk Sandbox._experimental_createSnapshot support.");
|
|
3098
|
+
}
|
|
3099
|
+
const templateRef = sanitizeSnapshotName(params.templateLabel, `paperclip-${params.environmentId}-${randomUUID().slice(0, 8)}`);
|
|
3100
|
+
const timeoutMs = typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) && params.timeoutMs > 0
|
|
3101
|
+
? Math.trunc(params.timeoutMs)
|
|
3102
|
+
: config.timeoutMs;
|
|
3103
|
+
await createSnapshot.call(sandbox, templateRef, toTimeoutSeconds(timeoutMs));
|
|
3104
|
+
return {
|
|
3105
|
+
templateKind: "snapshot",
|
|
3106
|
+
templateRef,
|
|
3107
|
+
metadata: {
|
|
3108
|
+
provider: "daytona",
|
|
3109
|
+
sandboxId: sandbox.id,
|
|
3110
|
+
capturedAt: new Date().toISOString(),
|
|
3111
|
+
sourceTemplateRefRedacted: Boolean(params.sourceTemplateRef),
|
|
3112
|
+
previousTemplateRefRedacted: Boolean(params.previousTemplateRef),
|
|
3113
|
+
timeoutMs,
|
|
3114
|
+
},
|
|
3115
|
+
};
|
|
3116
|
+
});
|
|
3117
|
+
},
|
|
3118
|
+
async onEnvironmentCancelInteractiveSetup(params) {
|
|
3119
|
+
const config = parseDriverConfig(params.config);
|
|
3120
|
+
if (!params.providerLeaseId) {
|
|
3121
|
+
return {
|
|
3122
|
+
status: "missing",
|
|
3123
|
+
metadata: {
|
|
3124
|
+
provider: "daytona",
|
|
3125
|
+
missing: true,
|
|
3126
|
+
reason: params.reason ?? null,
|
|
3127
|
+
},
|
|
3128
|
+
};
|
|
3129
|
+
}
|
|
3130
|
+
const scope = {
|
|
3131
|
+
driverKey: params.driverKey,
|
|
3132
|
+
companyId: params.companyId,
|
|
3133
|
+
environmentId: params.environmentId,
|
|
3134
|
+
providerLeaseId: params.providerLeaseId,
|
|
3135
|
+
config,
|
|
3136
|
+
};
|
|
3137
|
+
// C4: cancelling an interactive-setup lease deletes the sandbox, so the
|
|
3138
|
+
// teardown gate blocks fresh cache reads while delete is in flight.
|
|
3139
|
+
const teardownGate = sandboxHandleTeardownGates.begin(scope);
|
|
3140
|
+
sandboxHandleLeaseAdmissionStates.close(scope);
|
|
3141
|
+
try {
|
|
3142
|
+
const sandbox = await getSandboxOrNull(scope, { bypassTeardownGate: true });
|
|
3143
|
+
if (!sandbox) {
|
|
3144
|
+
return {
|
|
3145
|
+
status: "missing",
|
|
3146
|
+
metadata: {
|
|
3147
|
+
provider: "daytona",
|
|
3148
|
+
missing: true,
|
|
3149
|
+
reason: params.reason ?? null,
|
|
3150
|
+
},
|
|
3151
|
+
};
|
|
3152
|
+
}
|
|
3153
|
+
evictSandboxHandle(scope);
|
|
3154
|
+
await sandboxHandleActivityGates.waitForIdle(scope);
|
|
3155
|
+
await teardownSession(sandbox, scope);
|
|
3156
|
+
const proof = idleActivity.proof(sandboxHandleCacheKey(scope));
|
|
3157
|
+
await sandbox.delete(toTimeoutSeconds(config.timeoutMs), true);
|
|
3158
|
+
idleActivity.confirm(proof);
|
|
3159
|
+
return {
|
|
3160
|
+
status: params.reason === "timed_out" ? "timed_out" : "cancelled",
|
|
3161
|
+
metadata: {
|
|
3162
|
+
provider: "daytona",
|
|
3163
|
+
sandboxId: sandbox.id,
|
|
3164
|
+
reason: params.reason ?? null,
|
|
3165
|
+
},
|
|
3166
|
+
};
|
|
3167
|
+
}
|
|
3168
|
+
finally {
|
|
3169
|
+
sandboxHandleTeardownGates.end(scope, teardownGate);
|
|
3170
|
+
evictSandboxHandle(scope);
|
|
3171
|
+
}
|
|
3172
|
+
},
|
|
3173
|
+
async onEnvironmentDeleteTemplate(params) {
|
|
3174
|
+
const templateKind = params.templateKind ?? "snapshot";
|
|
3175
|
+
if (templateKind !== "snapshot") {
|
|
3176
|
+
throw new Error(`Daytona can delete snapshot templates only, not ${templateKind}.`);
|
|
3177
|
+
}
|
|
3178
|
+
const config = parseDriverConfig(params.config);
|
|
3179
|
+
const client = createDaytonaClient(config);
|
|
3180
|
+
const snapshotService = client.snapshot;
|
|
3181
|
+
if (typeof snapshotService?.get !== "function" || typeof snapshotService.delete !== "function") {
|
|
3182
|
+
throw new Error("Daytona template deletion requires @daytonaio/sdk snapshot.get/delete support.");
|
|
3183
|
+
}
|
|
3184
|
+
const snapshot = await snapshotService.get(params.templateRef);
|
|
3185
|
+
await snapshotService.delete(snapshot);
|
|
3186
|
+
return {
|
|
3187
|
+
deleted: true,
|
|
3188
|
+
metadata: {
|
|
3189
|
+
provider: "daytona",
|
|
3190
|
+
templateKind: "snapshot",
|
|
3191
|
+
templateRefRedacted: true,
|
|
3192
|
+
reason: params.reason ?? null,
|
|
3193
|
+
},
|
|
3194
|
+
};
|
|
3195
|
+
},
|
|
3196
|
+
async onEnvironmentExecute(params) {
|
|
3197
|
+
if (!params.lease.providerLeaseId) {
|
|
3198
|
+
return {
|
|
3199
|
+
exitCode: 1,
|
|
3200
|
+
timedOut: false,
|
|
3201
|
+
stdout: "",
|
|
3202
|
+
stderr: "No provider lease ID available for execution.",
|
|
3203
|
+
};
|
|
3204
|
+
}
|
|
3205
|
+
const config = parseDriverConfig(params.config);
|
|
3206
|
+
const providerLeaseId = params.lease.providerLeaseId;
|
|
3207
|
+
return await withSandboxActivityGate({
|
|
3208
|
+
driverKey: params.driverKey,
|
|
3209
|
+
companyId: params.companyId,
|
|
3210
|
+
environmentId: params.environmentId,
|
|
3211
|
+
providerLeaseId,
|
|
3212
|
+
config,
|
|
3213
|
+
}, async () => {
|
|
3214
|
+
// Time the sandbox handle lookup (Open Q1) separately from the
|
|
3215
|
+
// `executeCommand` round-trip so telemetry can split the per-call get cost
|
|
3216
|
+
// from the exec cost. With the per-lease handle cache this collapses to ~0
|
|
3217
|
+
// on a hit (no `client.get` REST round-trip), but the field stays present so
|
|
3218
|
+
// `providerGetMs` remains observable — and still captures the occasional
|
|
3219
|
+
// freshness refresh the cache issues after an idle gap. `ensureSandboxStarted`
|
|
3220
|
+
// is a no-op for an already-started sandbox, so it is excluded from the get
|
|
3221
|
+
// measurement.
|
|
3222
|
+
const getStart = timingNow();
|
|
3223
|
+
// Decide the explicit `cache_hit` flag at the true cache decision: the
|
|
3224
|
+
// handle lookup reports whether the warm cache served the handle or the
|
|
3225
|
+
// lookup called `client.get`. This replaces the old `providerGetMs == 0`
|
|
3226
|
+
// proxy. The default `false` covers the theoretical case where the lookup
|
|
3227
|
+
// reports nothing.
|
|
3228
|
+
let cacheHit = false;
|
|
3229
|
+
const sandbox = await getSandbox({
|
|
3230
|
+
driverKey: params.driverKey,
|
|
3231
|
+
companyId: params.companyId,
|
|
3232
|
+
environmentId: params.environmentId,
|
|
3233
|
+
providerLeaseId,
|
|
3234
|
+
config,
|
|
3235
|
+
}, {
|
|
3236
|
+
bypassTeardownGate: true,
|
|
3237
|
+
onCacheDecision: (hit) => {
|
|
3238
|
+
cacheHit = hit;
|
|
3239
|
+
},
|
|
3240
|
+
});
|
|
3241
|
+
const getDurationMs = timingNow() - getStart;
|
|
3242
|
+
const scope = {
|
|
3243
|
+
driverKey: params.driverKey,
|
|
3244
|
+
companyId: params.companyId,
|
|
3245
|
+
environmentId: params.environmentId,
|
|
3246
|
+
providerLeaseId,
|
|
3247
|
+
config,
|
|
3248
|
+
};
|
|
3249
|
+
// A provider restart destroys Daytona process sessions; the start helper
|
|
3250
|
+
// drops the stale session id so runnerd recovery opens a new session
|
|
3251
|
+
// instead of retrying a dead one for its whole grace.
|
|
3252
|
+
await ensureSandboxStarted(sandbox, toTimeoutSeconds(resolveTimeoutMs(params.timeoutMs, config)), scope);
|
|
3253
|
+
// Dispatch the command. A normal command runs in the persistent session:
|
|
3254
|
+
// the provider opens the one session on a cache miss and runs every command
|
|
3255
|
+
// in it. The provider never falls back to a one-shot command to open a
|
|
3256
|
+
// session; a cache miss creates one.
|
|
3257
|
+
//
|
|
3258
|
+
// A `bypassSession` command runs one-shot and does NOT open the session.
|
|
3259
|
+
// The host sets this flag on a pre-run command (the workspace provision
|
|
3260
|
+
// command) that runs before the run opens its trace root. Opening the
|
|
3261
|
+
// session there would emit a `session.open` span with no run parent, and
|
|
3262
|
+
// the span backend would drop it. With the bypass the session opens on the
|
|
3263
|
+
// first in-run command, whose open span parents to the run trace.
|
|
3264
|
+
let result;
|
|
3265
|
+
if (!params.bypassSession) {
|
|
3266
|
+
const sessionId = await getOrCreateSession(sandbox, scope);
|
|
3267
|
+
result = await executeInSession(sandbox, sessionId, params, config);
|
|
3268
|
+
}
|
|
3269
|
+
else {
|
|
3270
|
+
result = await executeOneShot(sandbox, params, config);
|
|
3271
|
+
}
|
|
3272
|
+
if (!result.timedOut) {
|
|
3273
|
+
sandboxHandleCache.markFresh(scope);
|
|
3274
|
+
}
|
|
3275
|
+
return {
|
|
3276
|
+
...result,
|
|
3277
|
+
metadata: { ...(result.metadata ?? {}), getDurationMs, cacheHit },
|
|
3278
|
+
};
|
|
3279
|
+
});
|
|
3280
|
+
},
|
|
3281
|
+
async onEnvironmentRunnerIngressEndpoint(params) {
|
|
3282
|
+
if (params.port !== 43_127) {
|
|
3283
|
+
throw new Error("Daytona runner ingress must use fixed port 43127.");
|
|
3284
|
+
}
|
|
3285
|
+
if (!/^\/api\/runner\/v1\/connect\/[^/?#]+$/.test(params.path)) {
|
|
3286
|
+
throw new Error("Daytona runner ingress path is invalid.");
|
|
3287
|
+
}
|
|
3288
|
+
const providerLeaseId = params.lease.providerLeaseId;
|
|
3289
|
+
if (!providerLeaseId) {
|
|
3290
|
+
throw new Error("Daytona runner ingress requires a provider lease id.");
|
|
3291
|
+
}
|
|
3292
|
+
const config = parseDriverConfig(params.config);
|
|
3293
|
+
const scope = {
|
|
3294
|
+
driverKey: params.driverKey,
|
|
3295
|
+
companyId: params.companyId,
|
|
3296
|
+
environmentId: params.environmentId,
|
|
3297
|
+
providerLeaseId,
|
|
3298
|
+
config,
|
|
3299
|
+
};
|
|
3300
|
+
return await withSandboxActivityGate(scope, async () => {
|
|
3301
|
+
const sandbox = await acquireRunnerIngress("sandbox_lookup", () => getSandbox(scope));
|
|
3302
|
+
await acquireRunnerIngress("sandbox_start", () => ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs), scope));
|
|
3303
|
+
await acquireRunnerIngress("sandbox_refresh", () => withLivenessTimeout("sandbox.refreshData", config.livenessTimeoutMs, () => sandbox.refreshData()));
|
|
3304
|
+
const preview = await acquireRunnerIngress("private_preview", () => sandbox.getPreviewLink(params.port));
|
|
3305
|
+
if (!isRecord(preview) || typeof preview.url !== "string" || typeof preview.token !== "string") {
|
|
3306
|
+
throw new Error("Daytona returned an incomplete private preview endpoint.");
|
|
3307
|
+
}
|
|
3308
|
+
const url = new URL(preview.url);
|
|
3309
|
+
if (url.protocol !== "https:" ||
|
|
3310
|
+
url.username ||
|
|
3311
|
+
url.password ||
|
|
3312
|
+
url.search ||
|
|
3313
|
+
url.hash) {
|
|
3314
|
+
throw new Error("Daytona returned an invalid private preview URL.");
|
|
3315
|
+
}
|
|
3316
|
+
url.protocol = "wss:";
|
|
3317
|
+
url.pathname = `${url.pathname.replace(/\/$/, "")}${params.path}`;
|
|
3318
|
+
return {
|
|
3319
|
+
kind: "authenticated_websocket",
|
|
3320
|
+
websocketUrl: url.toString(),
|
|
3321
|
+
secretHeaders: [
|
|
3322
|
+
{ name: "X-Daytona-Preview-Token", value: preview.token },
|
|
3323
|
+
],
|
|
3324
|
+
generation: runnerIngressGenerationStore.get(sandbox),
|
|
3325
|
+
};
|
|
3326
|
+
});
|
|
3327
|
+
},
|
|
3328
|
+
// Opt-in native inbound transfer. Defining this hook (with onEnvironmentSyncOut)
|
|
3329
|
+
// makes the worker advertise `environmentSyncIn`/`environmentSyncOut`, so the
|
|
3330
|
+
// host runner routes Daytona workspace/asset transfers through the SDK's batch
|
|
3331
|
+
// `uploadFiles` (plus host-side tarballs for directories) instead of the
|
|
3332
|
+
// base64-over-exec fallback. Providers that do not define these keep the
|
|
3333
|
+
// byte-identical fallback.
|
|
3334
|
+
async onEnvironmentSyncIn(params) {
|
|
3335
|
+
if (!params.lease.providerLeaseId) {
|
|
3336
|
+
throw new Error("Daytona syncIn requires a provider lease ID.");
|
|
3337
|
+
}
|
|
3338
|
+
const config = parseDriverConfig(params.config);
|
|
3339
|
+
const remoteDir = resolveSyncRemoteDir(params.lease);
|
|
3340
|
+
const timeoutSeconds = resolveSyncTimeoutSeconds(config, params.minimumTimeoutMs);
|
|
3341
|
+
const scope = {
|
|
3342
|
+
driverKey: params.driverKey,
|
|
3343
|
+
companyId: params.companyId,
|
|
3344
|
+
environmentId: params.environmentId,
|
|
3345
|
+
providerLeaseId: params.lease.providerLeaseId,
|
|
3346
|
+
config,
|
|
3347
|
+
};
|
|
3348
|
+
// Collect the advisory read-write destinations for this scope. This records
|
|
3349
|
+
// intent only; it does not change the transfer below.
|
|
3350
|
+
sandboxHandleWritableDirs.recordWritableTargets(scope, params.operations);
|
|
3351
|
+
return await withSandboxActivityGate(scope, async () => {
|
|
3352
|
+
const sandbox = await getSandbox(scope, { bypassTeardownGate: true });
|
|
3353
|
+
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs), scope);
|
|
3354
|
+
const result = await performSyncIn({
|
|
3355
|
+
sandbox,
|
|
3356
|
+
operations: params.operations,
|
|
3357
|
+
remoteDir,
|
|
3358
|
+
timeoutSeconds,
|
|
3359
|
+
commandTimeoutSeconds: toTimeoutSeconds(config.timeoutMs),
|
|
3360
|
+
});
|
|
3361
|
+
sandboxHandleCache.markFresh(scope);
|
|
3362
|
+
return result;
|
|
3363
|
+
});
|
|
3364
|
+
},
|
|
3365
|
+
// Opt-in native outbound transfer. See onEnvironmentSyncIn.
|
|
3366
|
+
async onEnvironmentSyncOut(params) {
|
|
3367
|
+
if (!params.lease.providerLeaseId) {
|
|
3368
|
+
throw new Error("Daytona syncOut requires a provider lease ID.");
|
|
3369
|
+
}
|
|
3370
|
+
const config = parseDriverConfig(params.config);
|
|
3371
|
+
const remoteDir = resolveSyncRemoteDir(params.lease);
|
|
3372
|
+
const timeoutSeconds = resolveSyncTimeoutSeconds(config, params.minimumTimeoutMs);
|
|
3373
|
+
const scope = {
|
|
3374
|
+
driverKey: params.driverKey,
|
|
3375
|
+
companyId: params.companyId,
|
|
3376
|
+
environmentId: params.environmentId,
|
|
3377
|
+
providerLeaseId: params.lease.providerLeaseId,
|
|
3378
|
+
config,
|
|
3379
|
+
};
|
|
3380
|
+
try {
|
|
3381
|
+
return await withSandboxActivityGate(scope, async () => {
|
|
3382
|
+
const sandbox = await withEnvironmentSyncTransferStep("sandbox_access", async () => {
|
|
3383
|
+
const resolved = await getSandbox(scope, { bypassTeardownGate: true });
|
|
3384
|
+
await ensureSandboxStarted(resolved, toTimeoutSeconds(config.timeoutMs), scope);
|
|
3385
|
+
return resolved;
|
|
3386
|
+
});
|
|
3387
|
+
const result = await performSyncOut({
|
|
3388
|
+
sandbox,
|
|
3389
|
+
operations: params.operations,
|
|
3390
|
+
remoteDir,
|
|
3391
|
+
timeoutSeconds,
|
|
3392
|
+
onArchiveRecovery: () => pluginContext?.logger.info("Workspace export omitted unsafe links; retrying with confined entries."),
|
|
3393
|
+
});
|
|
3394
|
+
sandboxHandleCache.markFresh(scope);
|
|
3395
|
+
return result;
|
|
3396
|
+
});
|
|
3397
|
+
}
|
|
3398
|
+
catch (error) {
|
|
3399
|
+
// A deleted Daytona sandbox is the one provider failure that proves its
|
|
3400
|
+
// unexported workspace bytes no longer exist. Convert the SDK class to a
|
|
3401
|
+
// stable cross-worker message; every other error remains retryable.
|
|
3402
|
+
if (error instanceof DaytonaNotFoundError) {
|
|
3403
|
+
throw preserveEnvironmentSyncErrorDiagnostic(new Error("daytona_sandbox_not_found"), error);
|
|
3404
|
+
}
|
|
3405
|
+
throw error;
|
|
3406
|
+
}
|
|
3407
|
+
},
|
|
3408
|
+
// Open one live login pseudo-terminal. Resolve the cached sandbox by the
|
|
3409
|
+
// provider lease id, revalidate the host launch descriptor, create the session
|
|
3410
|
+
// home with one `mkdir -p` command, run the fixed login command on a real
|
|
3411
|
+
// pseudo-terminal, and register the session under the host route id. Stream the
|
|
3412
|
+
// raw output and the exit through `ctx.loginPty`, bound to the returned worker
|
|
3413
|
+
// session id. Fail closed when no cached sandbox matches the lease.
|
|
3414
|
+
async onLoginPtyOpen(params) {
|
|
3415
|
+
const sandbox = await sandboxHandleCache.findByProviderLeaseId(params.providerLeaseId);
|
|
3416
|
+
if (!sandbox) {
|
|
3417
|
+
throw new Error("Daytona login pseudo-terminal: no cached sandbox resolves the provider lease.");
|
|
3418
|
+
}
|
|
3419
|
+
const homeFs = createDaytonaLoginHomeFs(sandbox.process);
|
|
3420
|
+
const session = await openLoginPtySession(sandbox.process, homeFs, { loginCommandKey: params.loginCommandKey, sessionHome: params.sessionHome });
|
|
3421
|
+
const workerSessionId = `pty-${randomUUID()}`;
|
|
3422
|
+
const entry = {
|
|
3423
|
+
hostRouteId: params.hostRouteId,
|
|
3424
|
+
workerSessionId,
|
|
3425
|
+
session,
|
|
3426
|
+
};
|
|
3427
|
+
daytonaLoginPtyByRoute.set(params.hostRouteId, entry);
|
|
3428
|
+
daytonaLoginPtyBySession.set(workerSessionId, entry);
|
|
3429
|
+
// Register the output listener before the first input, so no early output
|
|
3430
|
+
// chunk is lost. The client stamps the host route identifier and the worker
|
|
3431
|
+
// session identifier, so the host can hold more than one concurrent login
|
|
3432
|
+
// pseudo-terminal on this worker and binds the output to its own route.
|
|
3433
|
+
session.onData((chunk) => {
|
|
3434
|
+
pluginContext?.loginPty.output(params.hostRouteId, workerSessionId, chunk);
|
|
3435
|
+
});
|
|
3436
|
+
// Forward the child exit one time. The host resolves the login run on it.
|
|
3437
|
+
void session.wait().then((result) => pluginContext?.loginPty.exit(params.hostRouteId, workerSessionId, result.exitCode), () => pluginContext?.loginPty.exit(params.hostRouteId, workerSessionId, null));
|
|
3438
|
+
return { workerSessionId };
|
|
3439
|
+
},
|
|
3440
|
+
// Write delayed input to an open login pseudo-terminal, keyed by the worker
|
|
3441
|
+
// session id. Drop the input for an unknown session.
|
|
3442
|
+
async onLoginPtyInput(params) {
|
|
3443
|
+
const entry = daytonaLoginPtyBySession.get(params.workerSessionId);
|
|
3444
|
+
if (!entry)
|
|
3445
|
+
return;
|
|
3446
|
+
entry.session.write(params.data);
|
|
3447
|
+
},
|
|
3448
|
+
// Stop an open login pseudo-terminal child, keyed by the worker session id.
|
|
3449
|
+
async onLoginPtyStop(params) {
|
|
3450
|
+
const entry = daytonaLoginPtyBySession.get(params.workerSessionId);
|
|
3451
|
+
if (!entry)
|
|
3452
|
+
return;
|
|
3453
|
+
entry.session.kill();
|
|
3454
|
+
},
|
|
3455
|
+
// Close an open login pseudo-terminal by the host route id and acknowledge the
|
|
3456
|
+
// close with the same identifier. The close is idempotent: it returns the
|
|
3457
|
+
// acknowledgement even when the entry is already gone, so the host confirms the
|
|
3458
|
+
// terminal is closed. The worker never keys the close on the worker session id.
|
|
3459
|
+
async onLoginPtyClose(params) {
|
|
3460
|
+
const entry = daytonaLoginPtyByRoute.get(params.hostRouteId);
|
|
3461
|
+
if (entry) {
|
|
3462
|
+
forgetDaytonaLoginPty(entry);
|
|
3463
|
+
await entry.session.close().catch(() => undefined);
|
|
3464
|
+
}
|
|
3465
|
+
return { hostRouteId: params.hostRouteId };
|
|
3466
|
+
},
|
|
3467
|
+
// Open one persistent duplex channel. Resolve the cached sandbox by the provider
|
|
3468
|
+
// lease id, run the gateway command on a raw pseudo-terminal, and register the
|
|
3469
|
+
// channel under the host route id. Stream the raw data and the exit through
|
|
3470
|
+
// `ctx.duplexChannel`, bound to the returned worker session id. Fail closed when
|
|
3471
|
+
// no cached sandbox matches the lease.
|
|
3472
|
+
async onDuplexChannelOpen(params) {
|
|
3473
|
+
if (daytonaDuplexChannelByRoute.has(params.hostRouteId) || retiredDaytonaDuplexChannelByRoute.has(params.hostRouteId)) {
|
|
3474
|
+
throw new Error("Daytona duplex channel: host route has already been used.");
|
|
3475
|
+
}
|
|
3476
|
+
const sandbox = await sandboxHandleCache.findByProviderLeaseId(params.providerLeaseId);
|
|
3477
|
+
if (!sandbox) {
|
|
3478
|
+
throw new Error("Daytona duplex channel: no cached sandbox resolves the provider lease.");
|
|
3479
|
+
}
|
|
3480
|
+
const session = await openDuplexChannelSession(sandbox.process, params.command);
|
|
3481
|
+
const workerSessionId = `duplex-${randomUUID()}`;
|
|
3482
|
+
const entry = {
|
|
3483
|
+
hostRouteId: params.hostRouteId,
|
|
3484
|
+
workerSessionId,
|
|
3485
|
+
providerLeaseId: params.providerLeaseId,
|
|
3486
|
+
session,
|
|
3487
|
+
};
|
|
3488
|
+
daytonaDuplexChannelByRoute.set(params.hostRouteId, entry);
|
|
3489
|
+
daytonaDuplexChannelBySession.set(workerSessionId, entry);
|
|
3490
|
+
// Register the data listener before the first write, so no early data chunk is
|
|
3491
|
+
// lost. The client echoes the host route id and the worker session id, so the
|
|
3492
|
+
// host routes the data to the exact live pair.
|
|
3493
|
+
session.onData((chunk) => {
|
|
3494
|
+
pluginContext?.duplexChannel.data(entry.hostRouteId, workerSessionId, chunk);
|
|
3495
|
+
});
|
|
3496
|
+
// Forward the child exit one time. The host resolves the open route on it. A
|
|
3497
|
+
// numeric exit code is a real process exit; a resolved transport close carries
|
|
3498
|
+
// `transportClosed`, so the host keeps the two apart in the loss taxonomy. A
|
|
3499
|
+
// rejected wait is not a resolved transport close, so it reports no code and no
|
|
3500
|
+
// transport-close mark.
|
|
3501
|
+
void session.wait().then((result) => pluginContext?.duplexChannel.exit(entry.hostRouteId, workerSessionId, result.exitCode, result.transportClosed), () => pluginContext?.duplexChannel.exit(entry.hostRouteId, workerSessionId, null));
|
|
3502
|
+
// Echo the host route id on the reply, so the host binds the exact pair.
|
|
3503
|
+
return { hostRouteId: params.hostRouteId, workerSessionId };
|
|
3504
|
+
},
|
|
3505
|
+
// Write host input to an open duplex channel. Act only on the exact live pair.
|
|
3506
|
+
// A write whose pair does not match the bound entry applies no bytes.
|
|
3507
|
+
//
|
|
3508
|
+
// `params.data` arrives in the wire-safe base64 form (JSON carries no binary
|
|
3509
|
+
// type; see `ChannelBytesWireValue` in the plugin SDK's protocol.ts). Decode it
|
|
3510
|
+
// back to raw bytes before it reaches the pseudo-terminal. A malformed value
|
|
3511
|
+
// decodes to `null`; the worker applies no bytes rather than sending an empty
|
|
3512
|
+
// write to the sandbox.
|
|
3513
|
+
async onDuplexChannelWrite(params) {
|
|
3514
|
+
const entry = daytonaDuplexChannelBySession.get(params.workerSessionId);
|
|
3515
|
+
if (!entry || entry.hostRouteId !== params.hostRouteId)
|
|
3516
|
+
return;
|
|
3517
|
+
const data = decodeChannelBytes(params.data);
|
|
3518
|
+
if (data === null)
|
|
3519
|
+
return;
|
|
3520
|
+
entry.session.write(data);
|
|
3521
|
+
},
|
|
3522
|
+
// Stop an open duplex channel child. Act only on the exact live pair. A stop
|
|
3523
|
+
// whose pair does not match the bound entry stops nothing.
|
|
3524
|
+
async onDuplexChannelStop(params) {
|
|
3525
|
+
const entry = daytonaDuplexChannelBySession.get(params.workerSessionId);
|
|
3526
|
+
if (!entry || entry.hostRouteId !== params.hostRouteId)
|
|
3527
|
+
return;
|
|
3528
|
+
entry.session.kill();
|
|
3529
|
+
},
|
|
3530
|
+
// Close an open duplex channel by the host route id and acknowledge the close.
|
|
3531
|
+
// The host route id is the authoritative close key, so a pre-bind close with a
|
|
3532
|
+
// lost open reply still closes the channel. On a bound close the acknowledgement
|
|
3533
|
+
// echoes the worker session id too, so the host verifies the exact pair. The
|
|
3534
|
+
// close is idempotent: it returns the acknowledgement even when the entry is
|
|
3535
|
+
// already gone, so the host confirms the channel is closed.
|
|
3536
|
+
async onDuplexChannelClose(params) {
|
|
3537
|
+
const entry = daytonaDuplexChannelByRoute.get(params.hostRouteId);
|
|
3538
|
+
if (entry) {
|
|
3539
|
+
const boundWorkerSessionId = entry.workerSessionId;
|
|
3540
|
+
await closeDaytonaDuplexChannel(entry).catch(() => undefined);
|
|
3541
|
+
return { hostRouteId: params.hostRouteId, workerSessionId: boundWorkerSessionId };
|
|
3542
|
+
}
|
|
3543
|
+
const retired = retiredDaytonaDuplexChannelByRoute.get(params.hostRouteId);
|
|
3544
|
+
if (retired) {
|
|
3545
|
+
await retired.closed;
|
|
3546
|
+
return { hostRouteId: params.hostRouteId, workerSessionId: retired.workerSessionId };
|
|
3547
|
+
}
|
|
3548
|
+
return { hostRouteId: params.hostRouteId };
|
|
3549
|
+
},
|
|
3550
|
+
// Close every open login pseudo-terminal and every open duplex channel on an
|
|
3551
|
+
// orderly shutdown, then drain the sandbox handle cache, so a graceful shutdown
|
|
3552
|
+
// holds no live terminal and no live channel.
|
|
3553
|
+
async onShutdown() {
|
|
3554
|
+
const openSessions = [...daytonaLoginPtyByRoute.values()];
|
|
3555
|
+
daytonaLoginPtyByRoute.clear();
|
|
3556
|
+
daytonaLoginPtyBySession.clear();
|
|
3557
|
+
for (const entry of openSessions) {
|
|
3558
|
+
await entry.session.close().catch(() => undefined);
|
|
3559
|
+
}
|
|
3560
|
+
const openChannels = [...daytonaDuplexChannelByRoute.values()];
|
|
3561
|
+
daytonaDuplexChannelByRoute.clear();
|
|
3562
|
+
daytonaDuplexChannelBySession.clear();
|
|
3563
|
+
retiredDaytonaDuplexChannelByRoute.clear();
|
|
3564
|
+
for (const entry of openChannels) {
|
|
3565
|
+
await entry.session.close().catch(() => undefined);
|
|
3566
|
+
}
|
|
3567
|
+
sandboxHandleCache.reset();
|
|
3568
|
+
runnerIngressGenerationStore.reset();
|
|
3569
|
+
},
|
|
3570
|
+
}, idleActivity));
|
|
3571
|
+
export default plugin;
|
|
3572
|
+
//# sourceMappingURL=plugin.js.map
|