@computesdk/runloop 1.3.55 → 1.3.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +326 -86
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +327 -87
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as _computesdk_provider from '@computesdk/provider';
|
|
2
2
|
import { Runloop, RunloopSDK } from '@runloop/api-client';
|
|
3
|
+
import { Snapshot } from 'computesdk';
|
|
3
4
|
|
|
4
5
|
type RunloopSandbox = Runloop.DevboxView & {
|
|
5
6
|
client: RunloopSDK;
|
|
@@ -57,6 +58,6 @@ interface CreateBlueprintTemplateOptions {
|
|
|
57
58
|
/**
|
|
58
59
|
* Create a Runloop provider instance using the factory pattern
|
|
59
60
|
*/
|
|
60
|
-
declare const runloop: (config: RunloopConfig) => _computesdk_provider.Provider<RunloopSandbox, Runloop.Blueprints.BlueprintView,
|
|
61
|
+
declare const runloop: (config: RunloopConfig) => _computesdk_provider.Provider<RunloopSandbox, Runloop.Blueprints.BlueprintView, Snapshot>;
|
|
61
62
|
|
|
62
63
|
export { type CreateBlueprintTemplateOptions, type RunloopConfig, runloop };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as _computesdk_provider from '@computesdk/provider';
|
|
2
2
|
import { Runloop, RunloopSDK } from '@runloop/api-client';
|
|
3
|
+
import { Snapshot } from 'computesdk';
|
|
3
4
|
|
|
4
5
|
type RunloopSandbox = Runloop.DevboxView & {
|
|
5
6
|
client: RunloopSDK;
|
|
@@ -57,6 +58,6 @@ interface CreateBlueprintTemplateOptions {
|
|
|
57
58
|
/**
|
|
58
59
|
* Create a Runloop provider instance using the factory pattern
|
|
59
60
|
*/
|
|
60
|
-
declare const runloop: (config: RunloopConfig) => _computesdk_provider.Provider<RunloopSandbox, Runloop.Blueprints.BlueprintView,
|
|
61
|
+
declare const runloop: (config: RunloopConfig) => _computesdk_provider.Provider<RunloopSandbox, Runloop.Blueprints.BlueprintView, Snapshot>;
|
|
61
62
|
|
|
62
63
|
export { type CreateBlueprintTemplateOptions, type RunloopConfig, runloop };
|
package/dist/index.js
CHANGED
|
@@ -25,6 +25,7 @@ __export(index_exports, {
|
|
|
25
25
|
module.exports = __toCommonJS(index_exports);
|
|
26
26
|
var import_api_client = require("@runloop/api-client");
|
|
27
27
|
var import_provider = require("@computesdk/provider");
|
|
28
|
+
var import_node_path = require("path");
|
|
28
29
|
var clientCache = /* @__PURE__ */ new WeakMap();
|
|
29
30
|
function resolveApiKey(config) {
|
|
30
31
|
return config.apiKey || typeof process !== "undefined" && process.env?.RUNLOOP_API_KEY || "";
|
|
@@ -48,9 +49,286 @@ function getRunloopClient(config) {
|
|
|
48
49
|
function longPollOptions(timeoutMs) {
|
|
49
50
|
return timeoutMs ? { longPoll: { timeoutMs } } : void 0;
|
|
50
51
|
}
|
|
51
|
-
function
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
function quotePosixShellToken(value) {
|
|
53
|
+
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
54
|
+
}
|
|
55
|
+
function assertSafeRemovalPath(value) {
|
|
56
|
+
const normalized = import_node_path.posix.normalize(value);
|
|
57
|
+
if (value.length === 0 || normalized === "/" || normalized === "." || normalized === ".." || normalized.startsWith("../")) {
|
|
58
|
+
throw new Error(`Refusing to remove unsafe path: ${JSON.stringify(value)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function buildCommand(command, options) {
|
|
62
|
+
let fullCommand = command;
|
|
63
|
+
if (options?.env && Object.keys(options.env).length > 0) {
|
|
64
|
+
const envPrefix = Object.entries(options.env).map(([key, value]) => {
|
|
65
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
|
|
66
|
+
throw new Error(`Invalid environment variable name: ${JSON.stringify(key)}`);
|
|
67
|
+
}
|
|
68
|
+
return `${key}=${quotePosixShellToken(String(value))}`;
|
|
69
|
+
}).join(" ");
|
|
70
|
+
fullCommand = `${envPrefix} ${fullCommand}`;
|
|
71
|
+
}
|
|
72
|
+
if (options?.cwd) {
|
|
73
|
+
fullCommand = `cd -- ${quotePosixShellToken(options.cwd)} && ${fullCommand}`;
|
|
74
|
+
}
|
|
75
|
+
if (options?.background) {
|
|
76
|
+
fullCommand = `nohup sh -lc ${quotePosixShellToken(fullCommand)} >/dev/null 2>&1 &`;
|
|
77
|
+
}
|
|
78
|
+
return fullCommand;
|
|
79
|
+
}
|
|
80
|
+
function isHttpNotFound(error) {
|
|
81
|
+
return typeof error === "object" && error !== null && "status" in error && error.status === 404;
|
|
82
|
+
}
|
|
83
|
+
var READDIR_ENTRY_SCRIPT = [
|
|
84
|
+
"for entry; do",
|
|
85
|
+
" name=${entry##*/}",
|
|
86
|
+
' if [ -d "$entry" ]; then type=directory; else type=file; fi',
|
|
87
|
+
' encoded=$(printf %s "$name" | base64 | tr -d "\\n")',
|
|
88
|
+
' size=$(stat -c %s -- "$entry") || exit',
|
|
89
|
+
' modified=$(stat -c %Y -- "$entry") || exit',
|
|
90
|
+
' printf "%s\\t%s\\t%s\\t%s\\n" "$encoded" "$type" "$size" "$modified"',
|
|
91
|
+
"done"
|
|
92
|
+
].join("\n");
|
|
93
|
+
function buildReaddirCommand(path) {
|
|
94
|
+
const findRoot = path.startsWith("-") ? `./${path}` : path;
|
|
95
|
+
return [
|
|
96
|
+
`find -- ${quotePosixShellToken(findRoot)} -mindepth 1 -maxdepth 1 -exec sh -c`,
|
|
97
|
+
quotePosixShellToken(READDIR_ENTRY_SCRIPT),
|
|
98
|
+
"sh {} +"
|
|
99
|
+
].join(" ");
|
|
100
|
+
}
|
|
101
|
+
function parseReaddirOutput(stdout) {
|
|
102
|
+
return stdout.split("\n").filter(Boolean).map((line) => {
|
|
103
|
+
const [encodedName, type, rawSize, rawModified] = line.split(" ");
|
|
104
|
+
const size = Number(rawSize);
|
|
105
|
+
const modifiedSeconds = Number(rawModified);
|
|
106
|
+
if (!encodedName || type !== "file" && type !== "directory" || !Number.isFinite(size) || !Number.isFinite(modifiedSeconds)) {
|
|
107
|
+
throw new Error(`Malformed Runloop directory entry: ${JSON.stringify(line)}`);
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
name: Buffer.from(encodedName, "base64").toString("utf8"),
|
|
111
|
+
type,
|
|
112
|
+
size,
|
|
113
|
+
modified: new Date(modifiedSeconds * 1e3)
|
|
114
|
+
};
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
function mapStatus(status) {
|
|
118
|
+
switch (status) {
|
|
119
|
+
case "scheduled":
|
|
120
|
+
case "queued":
|
|
121
|
+
case "provisioning":
|
|
122
|
+
case "initializing":
|
|
123
|
+
case "resuming":
|
|
124
|
+
case "running":
|
|
125
|
+
return "running";
|
|
126
|
+
case "suspending":
|
|
127
|
+
case "suspended":
|
|
128
|
+
case "shutdown":
|
|
129
|
+
return "stopped";
|
|
130
|
+
case "failure":
|
|
131
|
+
return "error";
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
async function collectPaginated(source, limit) {
|
|
135
|
+
if (limit !== void 0 && limit <= 0) return [];
|
|
136
|
+
const results = [];
|
|
137
|
+
for await (const item of source) {
|
|
138
|
+
results.push(item);
|
|
139
|
+
if (limit !== void 0 && results.length >= limit) break;
|
|
140
|
+
}
|
|
141
|
+
return results;
|
|
142
|
+
}
|
|
143
|
+
function normalizeSnapshot(snapshot) {
|
|
144
|
+
return {
|
|
145
|
+
id: snapshot.id,
|
|
146
|
+
provider: "runloop",
|
|
147
|
+
createdAt: new Date(snapshot.create_time_ms),
|
|
148
|
+
metadata: {
|
|
149
|
+
name: snapshot.name ?? null,
|
|
150
|
+
sourceDevboxId: snapshot.source_devbox_id,
|
|
151
|
+
sourceBlueprintId: snapshot.source_blueprint_id ?? null,
|
|
152
|
+
sizeBytes: snapshot.size_bytes ?? null,
|
|
153
|
+
commitMessage: snapshot.commit_message ?? null,
|
|
154
|
+
userMetadata: snapshot.metadata ?? {}
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function emitMissingOutput(emitted, complete, callback) {
|
|
159
|
+
if (!callback || !complete || emitted.includes(complete)) return;
|
|
160
|
+
if (!emitted) {
|
|
161
|
+
callback(complete);
|
|
162
|
+
} else if (complete.startsWith(emitted)) {
|
|
163
|
+
callback(complete.slice(emitted.length));
|
|
164
|
+
} else if (!complete.includes(emitted)) {
|
|
165
|
+
callback(complete);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async function streamExecutionOutput(openStream, onChunk, signal, isActive) {
|
|
169
|
+
try {
|
|
170
|
+
const stream = await openStream();
|
|
171
|
+
for await (const chunk of stream) {
|
|
172
|
+
if (signal.aborted) break;
|
|
173
|
+
if (isActive()) onChunk(chunk.output);
|
|
174
|
+
}
|
|
175
|
+
} catch {
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function bestEffortKillExecution(sandbox, executionId) {
|
|
179
|
+
let killTimer;
|
|
180
|
+
try {
|
|
181
|
+
await Promise.race([
|
|
182
|
+
sandbox.client.api.devboxes.executions.kill(
|
|
183
|
+
sandbox.id,
|
|
184
|
+
executionId,
|
|
185
|
+
{ kill_process_group: true }
|
|
186
|
+
).catch(() => void 0),
|
|
187
|
+
new Promise((resolve) => {
|
|
188
|
+
killTimer = setTimeout(resolve, 1e3);
|
|
189
|
+
})
|
|
190
|
+
]);
|
|
191
|
+
} finally {
|
|
192
|
+
if (killTimer) clearTimeout(killTimer);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
async function executeCommand(sandbox, command, options) {
|
|
196
|
+
const startTime = Date.now();
|
|
197
|
+
const devbox = sandbox.client.devbox.fromId(sandbox.id);
|
|
198
|
+
const fullCommand = buildCommand(command, options);
|
|
199
|
+
let callbacksActive = true;
|
|
200
|
+
const executionParams = {
|
|
201
|
+
...options?.onStdout ? { stdout: (chunk) => callbacksActive && options.onStdout?.(chunk) } : {},
|
|
202
|
+
...options?.onStderr ? { stderr: (chunk) => callbacksActive && options.onStderr?.(chunk) } : {}
|
|
203
|
+
};
|
|
204
|
+
const toCommandResult = async (result) => ({
|
|
205
|
+
stdout: await result.stdout(),
|
|
206
|
+
stderr: await result.stderr(),
|
|
207
|
+
exitCode: result.exitCode ?? -1,
|
|
208
|
+
durationMs: Date.now() - startTime
|
|
209
|
+
});
|
|
210
|
+
if (options?.timeout === void 0) {
|
|
211
|
+
try {
|
|
212
|
+
const result = await devbox.cmd.exec(fullCommand, executionParams);
|
|
213
|
+
return await toCommandResult(result);
|
|
214
|
+
} finally {
|
|
215
|
+
callbacksActive = false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const timeoutMs = options.timeout;
|
|
219
|
+
const deadline = startTime + Math.max(0, timeoutMs);
|
|
220
|
+
const monitorController = new AbortController();
|
|
221
|
+
let streamedStdout = "";
|
|
222
|
+
let streamedStderr = "";
|
|
223
|
+
let execution;
|
|
224
|
+
let resultPromise;
|
|
225
|
+
let streamPromises = [];
|
|
226
|
+
let executionCompleted = false;
|
|
227
|
+
let timer;
|
|
228
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
229
|
+
timer = setTimeout(() => {
|
|
230
|
+
resolve("timeout");
|
|
231
|
+
monitorController.abort();
|
|
232
|
+
}, Math.max(0, deadline - Date.now()));
|
|
233
|
+
});
|
|
234
|
+
const timeoutResult = () => ({
|
|
235
|
+
stdout: streamedStdout,
|
|
236
|
+
stderr: streamedStderr,
|
|
237
|
+
exitCode: 124,
|
|
238
|
+
durationMs: Date.now() - startTime
|
|
239
|
+
});
|
|
240
|
+
try {
|
|
241
|
+
const executionPromise = devbox.cmd.execAsync(fullCommand);
|
|
242
|
+
const creationOutcome = await Promise.race([
|
|
243
|
+
executionPromise.then((createdExecution) => ({ execution: createdExecution })),
|
|
244
|
+
timeoutPromise
|
|
245
|
+
]);
|
|
246
|
+
if (creationOutcome === "timeout") {
|
|
247
|
+
callbacksActive = false;
|
|
248
|
+
void executionPromise.then((lateExecution) => bestEffortKillExecution(sandbox, lateExecution.executionId)).catch(() => void 0);
|
|
249
|
+
return timeoutResult();
|
|
250
|
+
}
|
|
251
|
+
const activeExecution = creationOutcome.execution;
|
|
252
|
+
execution = activeExecution;
|
|
253
|
+
streamPromises = [
|
|
254
|
+
streamExecutionOutput(
|
|
255
|
+
() => sandbox.client.api.devboxes.executions.streamStdoutUpdates(
|
|
256
|
+
sandbox.id,
|
|
257
|
+
activeExecution.executionId,
|
|
258
|
+
{},
|
|
259
|
+
{ signal: monitorController.signal }
|
|
260
|
+
),
|
|
261
|
+
(chunk) => {
|
|
262
|
+
streamedStdout += chunk;
|
|
263
|
+
options.onStdout?.(chunk);
|
|
264
|
+
},
|
|
265
|
+
monitorController.signal,
|
|
266
|
+
() => callbacksActive
|
|
267
|
+
),
|
|
268
|
+
streamExecutionOutput(
|
|
269
|
+
() => sandbox.client.api.devboxes.executions.streamStderrUpdates(
|
|
270
|
+
sandbox.id,
|
|
271
|
+
activeExecution.executionId,
|
|
272
|
+
{},
|
|
273
|
+
{ signal: monitorController.signal }
|
|
274
|
+
),
|
|
275
|
+
(chunk) => {
|
|
276
|
+
streamedStderr += chunk;
|
|
277
|
+
options.onStderr?.(chunk);
|
|
278
|
+
},
|
|
279
|
+
monitorController.signal,
|
|
280
|
+
() => callbacksActive
|
|
281
|
+
)
|
|
282
|
+
];
|
|
283
|
+
resultPromise = activeExecution.result({ signal: monitorController.signal });
|
|
284
|
+
const outcome = await Promise.race([
|
|
285
|
+
resultPromise.then((result) => ({ result })),
|
|
286
|
+
timeoutPromise
|
|
287
|
+
]);
|
|
288
|
+
if (outcome === "timeout") {
|
|
289
|
+
callbacksActive = false;
|
|
290
|
+
monitorController.abort();
|
|
291
|
+
await Promise.all([
|
|
292
|
+
bestEffortKillExecution(sandbox, execution.executionId),
|
|
293
|
+
Promise.allSettled([resultPromise, ...streamPromises])
|
|
294
|
+
]);
|
|
295
|
+
return timeoutResult();
|
|
296
|
+
}
|
|
297
|
+
executionCompleted = true;
|
|
298
|
+
monitorController.abort();
|
|
299
|
+
await Promise.allSettled(streamPromises);
|
|
300
|
+
const commandResult = await toCommandResult(outcome.result);
|
|
301
|
+
emitMissingOutput(streamedStdout, commandResult.stdout, options.onStdout);
|
|
302
|
+
emitMissingOutput(streamedStderr, commandResult.stderr, options.onStderr);
|
|
303
|
+
return commandResult;
|
|
304
|
+
} catch (error) {
|
|
305
|
+
callbacksActive = false;
|
|
306
|
+
monitorController.abort();
|
|
307
|
+
await Promise.all([
|
|
308
|
+
executionCompleted || !execution ? Promise.resolve() : bestEffortKillExecution(sandbox, execution.executionId),
|
|
309
|
+
Promise.allSettled([
|
|
310
|
+
...resultPromise ? [resultPromise] : [],
|
|
311
|
+
...streamPromises
|
|
312
|
+
])
|
|
313
|
+
]);
|
|
314
|
+
throw error;
|
|
315
|
+
} finally {
|
|
316
|
+
if (timer) clearTimeout(timer);
|
|
317
|
+
callbacksActive = false;
|
|
318
|
+
monitorController.abort();
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
async function runCommandWithErrors(sandbox, command, options) {
|
|
322
|
+
try {
|
|
323
|
+
return await executeCommand(sandbox, command, options);
|
|
324
|
+
} catch (error) {
|
|
325
|
+
if (error instanceof Error && error.message.includes("Syntax error")) {
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
throw new Error(
|
|
329
|
+
`Runloop execution failed: ${error instanceof Error ? error.message : String(error)}`
|
|
330
|
+
);
|
|
331
|
+
}
|
|
54
332
|
}
|
|
55
333
|
var runloop = (0, import_provider.defineProvider)({
|
|
56
334
|
name: "runloop",
|
|
@@ -75,7 +353,7 @@ var runloop = (0, import_provider.defineProvider)({
|
|
|
75
353
|
...providerOptions
|
|
76
354
|
} = options || {};
|
|
77
355
|
const effectiveTimeout = optTimeout ?? timeout;
|
|
78
|
-
const keepAliveSeconds = effectiveTimeout ? Math.ceil(effectiveTimeout / 1e3) : 1800;
|
|
356
|
+
const keepAliveSeconds = effectiveTimeout !== void 0 ? Math.ceil(effectiveTimeout / 1e3) : 1800;
|
|
79
357
|
let devboxParams = {
|
|
80
358
|
launch_parameters: {
|
|
81
359
|
keep_alive_time_seconds: keepAliveSeconds,
|
|
@@ -121,72 +399,36 @@ var runloop = (0, import_provider.defineProvider)({
|
|
|
121
399
|
sandbox: { ...devbox, client },
|
|
122
400
|
sandboxId
|
|
123
401
|
};
|
|
124
|
-
} catch {
|
|
125
|
-
return null;
|
|
402
|
+
} catch (error) {
|
|
403
|
+
if (isHttpNotFound(error)) return null;
|
|
404
|
+
throw error;
|
|
126
405
|
}
|
|
127
406
|
},
|
|
128
407
|
list: async (config) => {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
sandboxId: devbox.id
|
|
136
|
-
}));
|
|
137
|
-
} catch {
|
|
138
|
-
return [];
|
|
139
|
-
}
|
|
408
|
+
const client = getRunloopClient(config);
|
|
409
|
+
const devboxes = await collectPaginated(client.api.devboxes.list());
|
|
410
|
+
return devboxes.map((devbox) => ({
|
|
411
|
+
sandbox: { ...devbox, client },
|
|
412
|
+
sandboxId: devbox.id
|
|
413
|
+
}));
|
|
140
414
|
},
|
|
141
415
|
destroy: async (config, sandboxId) => {
|
|
142
416
|
try {
|
|
143
417
|
const client = getRunloopClient(config);
|
|
144
418
|
await client.api.devboxes.shutdown(sandboxId);
|
|
145
|
-
} catch {
|
|
146
|
-
}
|
|
147
|
-
},
|
|
148
|
-
runCommand: async (sandbox, command, options) => {
|
|
149
|
-
const startTime = Date.now();
|
|
150
|
-
const devbox = sandbox;
|
|
151
|
-
const client = sandbox.client;
|
|
152
|
-
try {
|
|
153
|
-
let fullCommand = command;
|
|
154
|
-
if (options?.env && Object.keys(options.env).length > 0) {
|
|
155
|
-
const envPrefix = Object.entries(options.env).map(([k, v]) => `${k}="${(0, import_provider.escapeShellArg)(String(v))}"`).join(" ");
|
|
156
|
-
fullCommand = `${envPrefix} ${fullCommand}`;
|
|
157
|
-
}
|
|
158
|
-
if (options?.cwd) {
|
|
159
|
-
fullCommand = `cd "${(0, import_provider.escapeShellArg)(options.cwd)}" && ${fullCommand}`;
|
|
160
|
-
}
|
|
161
|
-
if (options?.background) {
|
|
162
|
-
fullCommand = `nohup ${fullCommand} > /dev/null 2>&1 &`;
|
|
163
|
-
}
|
|
164
|
-
const executionResult = await client.api.devboxes.executeAndAwaitCompletion(devbox.id, {
|
|
165
|
-
command: fullCommand,
|
|
166
|
-
optimistic_timeout: optimisticTimeoutSeconds(options?.timeout)
|
|
167
|
-
}, longPollOptions(options?.timeout));
|
|
168
|
-
return {
|
|
169
|
-
stdout: executionResult.stdout || "",
|
|
170
|
-
stderr: executionResult.stderr || "",
|
|
171
|
-
exitCode: executionResult.exit_status || 0,
|
|
172
|
-
durationMs: Date.now() - startTime
|
|
173
|
-
};
|
|
174
419
|
} catch (error) {
|
|
175
|
-
if (
|
|
176
|
-
throw error;
|
|
177
|
-
}
|
|
178
|
-
throw new Error(
|
|
179
|
-
`Runloop execution failed: ${error instanceof Error ? error.message : String(error)}`
|
|
180
|
-
);
|
|
420
|
+
if (!isHttpNotFound(error)) throw error;
|
|
181
421
|
}
|
|
182
422
|
},
|
|
423
|
+
runCommand: runCommandWithErrors,
|
|
424
|
+
streamCommand: runCommandWithErrors,
|
|
183
425
|
getInfo: async (sandbox) => {
|
|
184
|
-
const devbox = sandbox;
|
|
185
|
-
const keepAliveSecs = devbox.launch_parameters
|
|
426
|
+
const devbox = await sandbox.client.api.devboxes.retrieve(sandbox.id);
|
|
427
|
+
const keepAliveSecs = devbox.launch_parameters?.keep_alive_time_seconds;
|
|
186
428
|
return {
|
|
187
429
|
id: devbox.id || "runloop-unknown",
|
|
188
430
|
provider: "runloop",
|
|
189
|
-
status: devbox.status,
|
|
431
|
+
status: mapStatus(devbox.status),
|
|
190
432
|
createdAt: new Date(devbox.create_time_ms || Date.now()),
|
|
191
433
|
// keep_alive_time_seconds is in seconds; SandboxInfo.timeout is in milliseconds
|
|
192
434
|
timeout: keepAliveSecs ? keepAliveSecs * 1e3 : 3e5,
|
|
@@ -211,42 +453,36 @@ var runloop = (0, import_provider.defineProvider)({
|
|
|
211
453
|
}
|
|
212
454
|
},
|
|
213
455
|
filesystem: {
|
|
214
|
-
readFile: async (sandbox, path
|
|
215
|
-
|
|
216
|
-
if (result.exitCode !== 0) throw new Error(`File not found or unreadable: ${result.stderr}`);
|
|
217
|
-
return Buffer.from(result.stdout, "base64").toString("utf8");
|
|
456
|
+
readFile: async (sandbox, path) => {
|
|
457
|
+
return sandbox.client.devbox.fromId(sandbox.id).file.read({ file_path: path });
|
|
218
458
|
},
|
|
219
|
-
writeFile: async (sandbox, path, content
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
459
|
+
writeFile: async (sandbox, path, content) => {
|
|
460
|
+
const result = await sandbox.client.devbox.fromId(sandbox.id).file.write({
|
|
461
|
+
file_path: path,
|
|
462
|
+
contents: content
|
|
463
|
+
});
|
|
464
|
+
if (result.exit_status !== 0) {
|
|
465
|
+
throw new Error(
|
|
466
|
+
`Failed to write file ${path}: ${result.stderr || `exit ${result.exit_status}`}`
|
|
467
|
+
);
|
|
468
|
+
}
|
|
223
469
|
},
|
|
224
470
|
mkdir: async (sandbox, path, runCommand) => {
|
|
225
|
-
const result = await runCommand(sandbox, `mkdir -p
|
|
471
|
+
const result = await runCommand(sandbox, `mkdir -p -- ${quotePosixShellToken(path)}`);
|
|
226
472
|
if (result.exitCode !== 0) throw new Error(`Failed to create directory ${path}: ${result.stderr}`);
|
|
227
473
|
},
|
|
228
474
|
readdir: async (sandbox, path, runCommand) => {
|
|
229
|
-
const result = await runCommand(sandbox,
|
|
475
|
+
const result = await runCommand(sandbox, buildReaddirCommand(path));
|
|
230
476
|
if (result.exitCode !== 0) throw new Error(`Failed to list directory ${path}: ${result.stderr}`);
|
|
231
|
-
|
|
232
|
-
return lines.map((line) => {
|
|
233
|
-
const parts = line.trim().split(/\s+/);
|
|
234
|
-
const name = parts[parts.length - 1];
|
|
235
|
-
const isDirectory = line.startsWith("d");
|
|
236
|
-
return {
|
|
237
|
-
name,
|
|
238
|
-
type: isDirectory ? "directory" : "file",
|
|
239
|
-
size: parseInt(parts[4]) || 0,
|
|
240
|
-
modified: /* @__PURE__ */ new Date()
|
|
241
|
-
};
|
|
242
|
-
});
|
|
477
|
+
return parseReaddirOutput(result.stdout || "");
|
|
243
478
|
},
|
|
244
479
|
exists: async (sandbox, path, runCommand) => {
|
|
245
|
-
const result = await runCommand(sandbox, `test -e
|
|
480
|
+
const result = await runCommand(sandbox, `test -e ${quotePosixShellToken(path)}`);
|
|
246
481
|
return result.exitCode === 0;
|
|
247
482
|
},
|
|
248
483
|
remove: async (sandbox, path, runCommand) => {
|
|
249
|
-
|
|
484
|
+
assertSafeRemovalPath(path);
|
|
485
|
+
const result = await runCommand(sandbox, `rm -rf -- ${quotePosixShellToken(path)}`);
|
|
250
486
|
if (result.exitCode !== 0) throw new Error(`Failed to remove ${path}: ${result.stderr}`);
|
|
251
487
|
}
|
|
252
488
|
},
|
|
@@ -260,9 +496,8 @@ var runloop = (0, import_provider.defineProvider)({
|
|
|
260
496
|
list: async (config, options) => {
|
|
261
497
|
const client = getRunloopClient(config);
|
|
262
498
|
const listParams = {};
|
|
263
|
-
if (options?.limit) listParams.limit = options.limit;
|
|
264
|
-
|
|
265
|
-
return response.blueprints || [];
|
|
499
|
+
if (options?.limit !== void 0) listParams.limit = options.limit;
|
|
500
|
+
return collectPaginated(client.api.blueprints.list(listParams), options?.limit);
|
|
266
501
|
},
|
|
267
502
|
delete: async (config, blueprintId) => {
|
|
268
503
|
const client = getRunloopClient(config);
|
|
@@ -275,14 +510,19 @@ var runloop = (0, import_provider.defineProvider)({
|
|
|
275
510
|
const snapshotParams = {};
|
|
276
511
|
if (options?.name) snapshotParams.name = options.name;
|
|
277
512
|
if (options?.metadata) snapshotParams.metadata = options.metadata;
|
|
278
|
-
|
|
513
|
+
const snapshot = await client.api.devboxes.snapshotDisk(sandboxId, snapshotParams);
|
|
514
|
+
return normalizeSnapshot(snapshot);
|
|
279
515
|
},
|
|
280
516
|
list: async (config, options) => {
|
|
281
517
|
const client = getRunloopClient(config);
|
|
282
518
|
const listParams = {};
|
|
283
|
-
if (options?.limit) listParams.limit = options.limit;
|
|
284
|
-
|
|
285
|
-
|
|
519
|
+
if (options?.limit !== void 0) listParams.limit = options.limit;
|
|
520
|
+
if (options?.sandboxId) listParams.devbox_id = options.sandboxId;
|
|
521
|
+
const snapshots = await collectPaginated(
|
|
522
|
+
client.api.devboxes.listDiskSnapshots(listParams),
|
|
523
|
+
options?.limit
|
|
524
|
+
);
|
|
525
|
+
return snapshots.map(normalizeSnapshot);
|
|
286
526
|
},
|
|
287
527
|
delete: async (config, snapshotId) => {
|
|
288
528
|
const client = getRunloopClient(config);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Runloop Provider - Factory-based Implementation\n *\n * Full-featured provider with filesystem support using the factory pattern.\n * Reduces ~400 lines of boilerplate to ~100 lines of core logic.\n */\n\nimport { RunloopSDK, type Runloop } from \"@runloop/api-client\";\nimport { defineProvider, escapeShellArg } from \"@computesdk/provider\";\nimport type {\n CommandResult,\n SandboxInfo,\n CreateSnapshotOptions,\n ListSnapshotsOptions,\n RunCommandOptions,\n} from \"@computesdk/provider\";\nimport type {\n CreateSandboxOptions,\n FileEntry,\n} from \"computesdk\";\n\n// Define Runloop-specific types\ntype RunloopSnapshot = Runloop.DevboxSnapshotView;\ntype RunloopTemplate = Runloop.BlueprintView;\ntype RunloopSandbox = Runloop.DevboxView & { client: RunloopSDK };\ntype RunloopCreateWaitOptions = Parameters<RunloopSDK[\"api\"][\"devboxes\"][\"createAndAwaitRunning\"]>[1];\ntype RunloopExecuteWaitOptions = Parameters<RunloopSDK[\"api\"][\"devboxes\"][\"executeAndAwaitCompletion\"]>[2];\n\ntype CommandRunner = (\n sandbox: RunloopSandbox,\n command: string,\n options?: RunCommandOptions\n) => Promise<CommandResult>;\n\n/**\n * Runloop-specific configuration options\n */\nexport interface RunloopConfig {\n /** Runloop API key - if not provided, will fallback to RUNLOOP_API_KEY environment variable */\n apiKey?: string;\n /** Execution timeout in milliseconds */\n timeout?: number;\n}\n\nconst clientCache = new WeakMap<RunloopConfig, RunloopSDK>();\n\nfunction resolveApiKey(config: RunloopConfig): string {\n return (\n config.apiKey ||\n (typeof process !== \"undefined\" && process.env?.RUNLOOP_API_KEY) ||\n \"\"\n );\n}\n\nfunction getRunloopClient(config: RunloopConfig): RunloopSDK {\n const apiKey = resolveApiKey(config);\n if (!apiKey) {\n throw new Error(\n `Missing Runloop API key. Provide 'apiKey' in config or set RUNLOOP_API_KEY environment variable. Get your API key from https://runloop.ai/`\n );\n }\n\n const cached = clientCache.get(config);\n if (cached) return cached;\n\n const client = new RunloopSDK({\n bearerToken: apiKey,\n http2: true,\n });\n clientCache.set(config, client);\n return client;\n}\n\nfunction longPollOptions<TOptions>(timeoutMs?: number): TOptions | undefined {\n return timeoutMs ? ({ longPoll: { timeoutMs } } as TOptions) : undefined;\n}\n\nfunction optimisticTimeoutSeconds(timeoutMs?: number): number {\n if (!timeoutMs) return 25;\n return Math.max(1, Math.min(25, Math.ceil(timeoutMs / 1000)));\n}\n\n/**\n * Runloop-specific blueprint creation options\n */\nexport interface CreateBlueprintTemplateOptions {\n /** Name of the blueprint template */\n name: string;\n /** Custom Dockerfile content */\n dockerfile?: string;\n /** System setup commands to run during blueprint creation */\n systemSetupCommands?: string[];\n /** Launch commands to run when starting a devbox from this blueprint */\n launchCommands?: string[];\n /** File mounts as key-value pairs (path -> content) */\n fileMounts?: Record<string, string>;\n /** Code repository mounts */\n codeMounts?: Array<{\n repoName: string;\n repoOwner: string;\n token?: string;\n installCommand?: string;\n }>;\n /** Resource size for devboxes created from this blueprint */\n resourceSize?:\n | \"X_SMALL\"\n | \"SMALL\"\n | \"MEDIUM\"\n | \"LARGE\"\n | \"X_LARGE\"\n | \"XX_LARGE\"\n | \"CUSTOM_SIZE\";\n /** CPU architecture */\n architecture?: \"x86_64\" | \"arm64\";\n /** Custom CPU cores (requires CUSTOM_SIZE) */\n customCpuCores?: number;\n /** Custom memory in GB (requires CUSTOM_SIZE) */\n customMemoryGb?: number;\n /** Custom disk size (requires CUSTOM_SIZE) */\n customDiskSize?: number;\n /** Available ports for the devbox */\n availablePorts?: number[];\n /** Action to take when devbox is idle */\n afterIdle?: { action: string; timeSeconds: number };\n /** Keep alive time in seconds */\n keepAliveTimeSeconds?: number;\n}\n\n/**\n * Create a Runloop provider instance using the factory pattern\n */\nexport const runloop = defineProvider<\n RunloopSandbox,\n RunloopConfig,\n RunloopTemplate,\n RunloopSnapshot\n>({\n name: \"runloop\",\n methods: {\n sandbox: {\n create: async (config: RunloopConfig, options?: CreateSandboxOptions) => {\n const timeout = config.timeout;\n\n try {\n const client = getRunloopClient(config);\n\n const {\n timeout: optTimeout,\n envs,\n name,\n metadata,\n templateId,\n snapshotId,\n sandboxId: optSandboxId,\n ports: _ports,\n namespace: _namespace,\n directory: _directory,\n launch_parameters: optLaunchParameters,\n ...providerOptions\n } = options || {};\n\n const effectiveTimeout = optTimeout ?? timeout;\n const keepAliveSeconds = effectiveTimeout\n ? Math.ceil(effectiveTimeout / 1000)\n : 1800;\n\n let devboxParams: Runloop.DevboxCreateParams = {\n launch_parameters: {\n keep_alive_time_seconds: keepAliveSeconds,\n ...(optLaunchParameters as Partial<Runloop.DevboxCreateParams['launch_parameters']> | undefined),\n },\n name: name || optSandboxId,\n metadata,\n environment_variables: envs,\n ...providerOptions,\n };\n\n // snapshotId is the canonical cross-provider field — map it directly to snapshot_id.\n // templateId is kept for backwards compatibility: bpt_ prefix → blueprint_id, snp_ prefix → snapshot_id.\n if (snapshotId) {\n devboxParams.snapshot_id = snapshotId;\n } else if (templateId) {\n if (templateId.startsWith(\"bpt_\")) {\n devboxParams.blueprint_id = templateId;\n } else if (templateId.startsWith(\"snp_\")) {\n devboxParams.snapshot_id = templateId;\n }\n }\n\n const dbx = await client.api.devboxes.createAndAwaitRunning(\n devboxParams,\n longPollOptions<RunloopCreateWaitOptions>(effectiveTimeout),\n );\n\n const runloopSandbox: RunloopSandbox = {\n ...dbx,\n client: client\n };\n\n return {\n sandbox: runloopSandbox,\n sandboxId: dbx.id,\n };\n } catch (error) {\n throw new Error(\n `Failed to create Runloop devbox: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n },\n\n getById: async (config: RunloopConfig, sandboxId: string) => {\n try {\n const client = getRunloopClient(config);\n const devbox = await client.api.devboxes.retrieve(sandboxId);\n return {\n sandbox: { ...devbox, client } as RunloopSandbox,\n sandboxId,\n };\n } catch {\n return null;\n }\n },\n\n list: async (config: RunloopConfig) => {\n try {\n const client = getRunloopClient(config);\n const response = await client.api.devboxes.list();\n const devboxes = response.devboxes || [];\n\n return devboxes.map((devbox) => ({\n sandbox: { ...devbox, client } as RunloopSandbox,\n sandboxId: devbox.id,\n }));\n } catch {\n return [];\n }\n },\n\n destroy: async (config: RunloopConfig, sandboxId: string) => {\n try {\n const client = getRunloopClient(config);\n await client.api.devboxes.shutdown(sandboxId);\n } catch {\n // Devbox might already be destroyed or doesn't exist\n }\n },\n\n runCommand: async (\n sandbox: RunloopSandbox,\n command: string,\n options?: RunCommandOptions\n ): Promise<CommandResult> => {\n const startTime = Date.now();\n const devbox = sandbox;\n const client = sandbox.client;\n\n try {\n let fullCommand = command;\n\n if (options?.env && Object.keys(options.env).length > 0) {\n const envPrefix = Object.entries(options.env)\n .map(([k, v]) => `${k}=\"${escapeShellArg(String(v))}\"`)\n .join(' ');\n fullCommand = `${envPrefix} ${fullCommand}`;\n }\n\n if (options?.cwd) {\n fullCommand = `cd \"${escapeShellArg(options.cwd)}\" && ${fullCommand}`;\n }\n\n if (options?.background) {\n fullCommand = `nohup ${fullCommand} > /dev/null 2>&1 &`;\n }\n\n const executionResult =\n await client.api.devboxes.executeAndAwaitCompletion(devbox.id, {\n command: fullCommand,\n optimistic_timeout: optimisticTimeoutSeconds(options?.timeout),\n }, longPollOptions<RunloopExecuteWaitOptions>(options?.timeout));\n\n return {\n stdout: executionResult.stdout || \"\",\n stderr: executionResult.stderr || \"\",\n exitCode: executionResult.exit_status || 0,\n durationMs: Date.now() - startTime,\n };\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Syntax error\")) {\n throw error;\n }\n throw new Error(\n `Runloop execution failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n },\n\n getInfo: async (sandbox): Promise<SandboxInfo> => {\n const devbox = sandbox;\n const keepAliveSecs = devbox.launch_parameters.keep_alive_time_seconds;\n\n return {\n id: devbox.id || \"runloop-unknown\",\n provider: \"runloop\",\n status: devbox.status as 'running' | 'stopped' | 'error',\n createdAt: new Date(devbox.create_time_ms || Date.now()),\n // keep_alive_time_seconds is in seconds; SandboxInfo.timeout is in milliseconds\n timeout: keepAliveSecs ? keepAliveSecs * 1000 : 300000,\n metadata: {\n runloopDevboxId: devbox.id,\n templateId: devbox.blueprint_id || devbox.snapshot_id,\n runtime: 'node',\n ...devbox.metadata,\n },\n };\n },\n\n getUrl: async (\n sandbox: RunloopSandbox,\n options: { port: number }\n ): Promise<string> => {\n const devbox = sandbox;\n const client = sandbox.client;\n\n try {\n const tunnel = await client.api.devboxes.enableTunnel(devbox.id);\n return `https://${options.port}-${tunnel.tunnel_key}.tunnel.runloop.ai`;\n } catch (error) {\n throw new Error(\n `Failed to get Runloop URL for port ${options.port}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n },\n\n filesystem: {\n readFile: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<string> => {\n const result = await runCommand(sandbox, `test -f \"${path}\" && base64 < \"${path}\" | tr -d '\\\\n'`);\n if (result.exitCode !== 0) throw new Error(`File not found or unreadable: ${result.stderr}`);\n return Buffer.from(result.stdout, 'base64').toString('utf8');\n },\n\n writeFile: async (sandbox: RunloopSandbox, path: string, content: string, runCommand: CommandRunner): Promise<void> => {\n const encoded = Buffer.from(content).toString('base64');\n const result = await runCommand(sandbox, `sh -c 'echo \"${encoded}\" | base64 -d > \"${path}\"'`);\n if (result.exitCode !== 0) throw new Error(`Failed to write file ${path}: ${result.stderr}`);\n },\n\n mkdir: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const result = await runCommand(sandbox, `mkdir -p \"${path}\"`);\n if (result.exitCode !== 0) throw new Error(`Failed to create directory ${path}: ${result.stderr}`);\n },\n\n readdir: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const result = await runCommand(sandbox, `ls -la \"${path}\"`);\n if (result.exitCode !== 0) throw new Error(`Failed to list directory ${path}: ${result.stderr}`);\n\n const lines = (result.stdout || \"\")\n .split(\"\\n\")\n .filter((line: string) => line.trim() && !line.startsWith(\"total\"));\n\n return lines.map((line: string) => {\n const parts = line.trim().split(/\\s+/);\n const name = parts[parts.length - 1];\n const isDirectory = line.startsWith(\"d\");\n return {\n name,\n type: isDirectory ? 'directory' as const : 'file' as const,\n size: parseInt(parts[4]) || 0,\n modified: new Date(),\n };\n });\n },\n\n exists: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const result = await runCommand(sandbox, `test -e \"${path}\"`);\n return result.exitCode === 0;\n },\n\n remove: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const result = await runCommand(sandbox, `rm -rf \"${path}\"`);\n if (result.exitCode !== 0) throw new Error(`Failed to remove ${path}: ${result.stderr}`);\n },\n },\n\n getInstance: (sandbox: RunloopSandbox): RunloopSandbox => sandbox,\n },\n\n template: {\n create: async (config: RunloopConfig, options: CreateBlueprintTemplateOptions | Runloop.BlueprintCreateParams) => {\n const client = getRunloopClient(config);\n return client.api.blueprints.create(options);\n },\n\n list: async (config: RunloopConfig, options?: { limit?: number }) => {\n const client = getRunloopClient(config);\n const listParams: any = {};\n if (options?.limit) listParams.limit = options.limit;\n const response = await client.api.blueprints.list(listParams);\n return response.blueprints || [];\n },\n\n delete: async (config: RunloopConfig, blueprintId: string) => {\n const client = getRunloopClient(config);\n await client.api.blueprints.delete(blueprintId);\n },\n },\n\n snapshot: {\n create: async (config: RunloopConfig, sandboxId: string, options?: CreateSnapshotOptions) => {\n const client = getRunloopClient(config);\n const snapshotParams: any = {};\n if (options?.name) snapshotParams.name = options.name;\n if (options?.metadata) snapshotParams.metadata = options.metadata;\n return client.api.devboxes.snapshotDisk(sandboxId, snapshotParams);\n },\n\n list: async (config: RunloopConfig, options?: ListSnapshotsOptions) => {\n const client = getRunloopClient(config);\n const listParams: any = {};\n if (options?.limit) listParams.limit = options.limit;\n const response = await client.api.devboxes.listDiskSnapshots(listParams);\n return response.snapshots || [];\n },\n\n delete: async (config: RunloopConfig, snapshotId: string) => {\n const client = getRunloopClient(config);\n await client.api.devboxes.deleteDiskSnapshot(snapshotId);\n },\n },\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,wBAAyC;AACzC,sBAA+C;AAoC/C,IAAM,cAAc,oBAAI,QAAmC;AAE3D,SAAS,cAAc,QAA+B;AACpD,SACE,OAAO,UACN,OAAO,YAAY,eAAe,QAAQ,KAAK,mBAChD;AAEJ;AAEA,SAAS,iBAAiB,QAAmC;AAC3D,QAAM,SAAS,cAAc,MAAM;AACnC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAS,YAAY,IAAI,MAAM;AACrC,MAAI,OAAQ,QAAO;AAEnB,QAAM,SAAS,IAAI,6BAAW;AAAA,IAC5B,aAAa;AAAA,IACb,OAAO;AAAA,EACT,CAAC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ACtC,eAAO,OAAO,IAAI,WAAW,OAAO,OAAO;AAAA,MAC7C;AAAA,MAEA,MAAM,OAAO,QAAuB,YAAiC;AACnE,cAAM,SAAS,iBAAiB,MAAM;AACtC,cAAM,aAAkB,CAAC;AACzB,YAAI,SAAS,MAAO,YAAW,QAAQ,QAAQ;AAC/C,cAAM,WAAW,MAAM,OAAO,IAAI,WAAW,KAAK,UAAU;AAC5D,eAAO,SAAS,cAAc,CAAC;AAAA,MACjC;AAAA,MAEA,QAAQ,OAAO,QAAuB,gBAAwB;AAC5D,cAAM,SAAS,iBAAiB,MAAM;AACtC,cAAM,OAAO,IAAI,WAAW,OAAO,WAAW;AAAA,MAChD;AAAA,IACF;AAAA,IAEA,UAAU;AAAA,MACR,QAAQ,OAAO,QAAuB,WAAmB,YAAoC;AAC3F,cAAM,SAAS,iBAAiB,MAAM;AACtC,cAAM,iBAAsB,CAAC;AAC7B,YAAI,SAAS,KAAM,gBAAe,OAAO,QAAQ;AACjD,YAAI,SAAS,SAAU,gBAAe,WAAW,QAAQ;AACzD,eAAO,OAAO,IAAI,SAAS,aAAa,WAAW,cAAc;AAAA,MACnE;AAAA,MAEA,MAAM,OAAO,QAAuB,YAAmC;AACrE,cAAM,SAAS,iBAAiB,MAAM;AACtC,cAAM,aAAkB,CAAC;AACzB,YAAI,SAAS,MAAO,YAAW,QAAQ,QAAQ;AAC/C,cAAM,WAAW,MAAM,OAAO,IAAI,SAAS,kBAAkB,UAAU;AACvE,eAAO,SAAS,aAAa,CAAC;AAAA,MAChC;AAAA,MAEA,QAAQ,OAAO,QAAuB,eAAuB;AAC3D,cAAM,SAAS,iBAAiB,MAAM;AACtC,cAAM,OAAO,IAAI,SAAS,mBAAmB,UAAU;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Runloop Provider - Factory-based Implementation\n *\n * Full-featured provider with filesystem support using the factory pattern.\n * Reduces ~400 lines of boilerplate to ~100 lines of core logic.\n */\n\nimport { RunloopSDK, type Runloop } from \"@runloop/api-client\";\nimport { defineProvider } from \"@computesdk/provider\";\nimport { posix as posixPath } from \"node:path\";\nimport type {\n CommandResult,\n SandboxInfo,\n CreateSnapshotOptions,\n ListSnapshotsOptions,\n RunCommandOptions,\n} from \"@computesdk/provider\";\nimport type {\n CreateSandboxOptions,\n FileEntry,\n Snapshot,\n} from \"computesdk\";\n\n// Define Runloop-specific types\ntype RunloopTemplate = Runloop.BlueprintView;\ntype RunloopSandbox = Runloop.DevboxView & { client: RunloopSDK };\ntype RunloopCreateWaitOptions = Parameters<RunloopSDK[\"api\"][\"devboxes\"][\"createAndAwaitRunning\"]>[1];\n\ntype CommandRunner = (\n sandbox: RunloopSandbox,\n command: string,\n options?: RunCommandOptions\n) => Promise<CommandResult>;\n\n/**\n * Runloop-specific configuration options\n */\nexport interface RunloopConfig {\n /** Runloop API key - if not provided, will fallback to RUNLOOP_API_KEY environment variable */\n apiKey?: string;\n /** Execution timeout in milliseconds */\n timeout?: number;\n}\n\nconst clientCache = new WeakMap<RunloopConfig, RunloopSDK>();\n\nfunction resolveApiKey(config: RunloopConfig): string {\n return (\n config.apiKey ||\n (typeof process !== \"undefined\" && process.env?.RUNLOOP_API_KEY) ||\n \"\"\n );\n}\n\nfunction getRunloopClient(config: RunloopConfig): RunloopSDK {\n const apiKey = resolveApiKey(config);\n if (!apiKey) {\n throw new Error(\n `Missing Runloop API key. Provide 'apiKey' in config or set RUNLOOP_API_KEY environment variable. Get your API key from https://runloop.ai/`\n );\n }\n\n const cached = clientCache.get(config);\n if (cached) return cached;\n\n const client = new RunloopSDK({\n bearerToken: apiKey,\n http2: true,\n });\n clientCache.set(config, client);\n return client;\n}\n\nfunction longPollOptions<TOptions>(timeoutMs?: number): TOptions | undefined {\n return timeoutMs ? ({ longPoll: { timeoutMs } } as TOptions) : undefined;\n}\n\nfunction quotePosixShellToken(value: string): string {\n return `'${value.replace(/'/g, `'\"'\"'`)}'`;\n}\n\nfunction assertSafeRemovalPath(value: string): void {\n const normalized = posixPath.normalize(value);\n if (value.length === 0 || normalized === \"/\" || normalized === \".\" ||\n normalized === \"..\" || normalized.startsWith(\"../\")) {\n throw new Error(`Refusing to remove unsafe path: ${JSON.stringify(value)}`);\n }\n}\n\nfunction buildCommand(command: string, options?: RunCommandOptions): string {\n let fullCommand = command;\n\n if (options?.env && Object.keys(options.env).length > 0) {\n const envPrefix = Object.entries(options.env)\n .map(([key, value]) => {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n throw new Error(`Invalid environment variable name: ${JSON.stringify(key)}`);\n }\n return `${key}=${quotePosixShellToken(String(value))}`;\n })\n .join(\" \");\n fullCommand = `${envPrefix} ${fullCommand}`;\n }\n\n if (options?.cwd) {\n fullCommand = `cd -- ${quotePosixShellToken(options.cwd)} && ${fullCommand}`;\n }\n\n if (options?.background) {\n fullCommand = `nohup sh -lc ${quotePosixShellToken(fullCommand)} >/dev/null 2>&1 &`;\n }\n\n return fullCommand;\n}\n\nfunction isHttpNotFound(error: unknown): boolean {\n return typeof error === \"object\" && error !== null &&\n \"status\" in error && error.status === 404;\n}\n\nconst READDIR_ENTRY_SCRIPT = [\n \"for entry; do\",\n ' name=${entry##*/}',\n ' if [ -d \"$entry\" ]; then type=directory; else type=file; fi',\n ' encoded=$(printf %s \"$name\" | base64 | tr -d \"\\\\n\")',\n ' size=$(stat -c %s -- \"$entry\") || exit',\n ' modified=$(stat -c %Y -- \"$entry\") || exit',\n ' printf \"%s\\\\t%s\\\\t%s\\\\t%s\\\\n\" \"$encoded\" \"$type\" \"$size\" \"$modified\"',\n \"done\",\n].join(\"\\n\");\n\nfunction buildReaddirCommand(path: string): string {\n const findRoot = path.startsWith(\"-\") ? `./${path}` : path;\n return [\n `find -- ${quotePosixShellToken(findRoot)} -mindepth 1 -maxdepth 1 -exec sh -c`,\n quotePosixShellToken(READDIR_ENTRY_SCRIPT),\n \"sh {} +\",\n ].join(\" \");\n}\n\nfunction parseReaddirOutput(stdout: string): FileEntry[] {\n return stdout\n .split(\"\\n\")\n .filter(Boolean)\n .map((line) => {\n const [encodedName, type, rawSize, rawModified] = line.split(\"\\t\");\n const size = Number(rawSize);\n const modifiedSeconds = Number(rawModified);\n if (!encodedName || (type !== \"file\" && type !== \"directory\") ||\n !Number.isFinite(size) || !Number.isFinite(modifiedSeconds)) {\n throw new Error(`Malformed Runloop directory entry: ${JSON.stringify(line)}`);\n }\n return {\n name: Buffer.from(encodedName, \"base64\").toString(\"utf8\"),\n type,\n size,\n modified: new Date(modifiedSeconds * 1000),\n };\n });\n}\n\nfunction mapStatus(status: Runloop.DevboxView[\"status\"]): SandboxInfo[\"status\"] {\n switch (status) {\n case \"scheduled\":\n case \"queued\":\n case \"provisioning\":\n case \"initializing\":\n case \"resuming\":\n case \"running\":\n return \"running\";\n case \"suspending\":\n case \"suspended\":\n case \"shutdown\":\n return \"stopped\";\n case \"failure\":\n return \"error\";\n }\n}\n\nasync function collectPaginated<T>(\n source: AsyncIterable<T>,\n limit?: number,\n): Promise<T[]> {\n if (limit !== undefined && limit <= 0) return [];\n\n const results: T[] = [];\n for await (const item of source) {\n results.push(item);\n if (limit !== undefined && results.length >= limit) break;\n }\n return results;\n}\n\nfunction normalizeSnapshot(snapshot: Runloop.DevboxSnapshotView): Snapshot {\n return {\n id: snapshot.id,\n provider: \"runloop\",\n createdAt: new Date(snapshot.create_time_ms),\n metadata: {\n name: snapshot.name ?? null,\n sourceDevboxId: snapshot.source_devbox_id,\n sourceBlueprintId: snapshot.source_blueprint_id ?? null,\n sizeBytes: snapshot.size_bytes ?? null,\n commitMessage: snapshot.commit_message ?? null,\n userMetadata: snapshot.metadata ?? {},\n },\n };\n}\n\nfunction emitMissingOutput(\n emitted: string,\n complete: string,\n callback: ((chunk: string) => void) | undefined,\n): void {\n if (!callback || !complete || emitted.includes(complete)) return;\n if (!emitted) {\n callback(complete);\n } else if (complete.startsWith(emitted)) {\n callback(complete.slice(emitted.length));\n } else if (!complete.includes(emitted)) {\n callback(complete);\n }\n}\n\nasync function streamExecutionOutput(\n openStream: () => Promise<AsyncIterable<{ output: string }>>,\n onChunk: (chunk: string) => void,\n signal: AbortSignal,\n isActive: () => boolean,\n): Promise<void> {\n try {\n const stream = await openStream();\n for await (const chunk of stream) {\n if (signal.aborted) break;\n if (isActive()) onChunk(chunk.output);\n }\n } catch {\n // Streaming is best effort, matching the native SDK callback behavior.\n }\n}\n\nasync function bestEffortKillExecution(\n sandbox: RunloopSandbox,\n executionId: string,\n): Promise<void> {\n let killTimer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n sandbox.client.api.devboxes.executions.kill(\n sandbox.id,\n executionId,\n { kill_process_group: true },\n ).catch(() => undefined),\n new Promise<void>((resolve) => {\n killTimer = setTimeout(resolve, 1_000);\n }),\n ]);\n } finally {\n if (killTimer) clearTimeout(killTimer);\n }\n}\n\nasync function executeCommand(\n sandbox: RunloopSandbox,\n command: string,\n options?: RunCommandOptions,\n): Promise<CommandResult> {\n const startTime = Date.now();\n const devbox = sandbox.client.devbox.fromId(sandbox.id);\n const fullCommand = buildCommand(command, options);\n let callbacksActive = true;\n const executionParams = {\n ...(options?.onStdout\n ? { stdout: (chunk: string) => callbacksActive && options.onStdout?.(chunk) }\n : {}),\n ...(options?.onStderr\n ? { stderr: (chunk: string) => callbacksActive && options.onStderr?.(chunk) }\n : {}),\n };\n\n const toCommandResult = async (result: Awaited<ReturnType<typeof devbox.cmd.exec>>): Promise<CommandResult> => ({\n stdout: await result.stdout(),\n stderr: await result.stderr(),\n exitCode: result.exitCode ?? -1,\n durationMs: Date.now() - startTime,\n });\n\n if (options?.timeout === undefined) {\n try {\n const result = await devbox.cmd.exec(fullCommand, executionParams);\n return await toCommandResult(result);\n } finally {\n callbacksActive = false;\n }\n }\n\n const timeoutMs = options.timeout;\n const deadline = startTime + Math.max(0, timeoutMs);\n const monitorController = new AbortController();\n let streamedStdout = \"\";\n let streamedStderr = \"\";\n let execution: Awaited<ReturnType<typeof devbox.cmd.execAsync>> | undefined;\n let resultPromise: ReturnType<Awaited<ReturnType<typeof devbox.cmd.execAsync>>[\"result\"]> | undefined;\n let streamPromises: Promise<void>[] = [];\n let executionCompleted = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => {\n resolve(\"timeout\");\n monitorController.abort();\n }, Math.max(0, deadline - Date.now()));\n });\n const timeoutResult = (): CommandResult => ({\n stdout: streamedStdout,\n stderr: streamedStderr,\n exitCode: 124,\n durationMs: Date.now() - startTime,\n });\n\n try {\n // Keep creation alive after the caller's deadline. Aborting this non-idempotent\n // request can hide an execution that the server already accepted, leaving no ID\n // available for cleanup. The caller still returns at the deadline; if creation\n // resolves later, the timeout branch below kills the remote process group.\n const executionPromise = devbox.cmd.execAsync(fullCommand);\n const creationOutcome = await Promise.race([\n executionPromise.then((createdExecution) => ({ execution: createdExecution })),\n timeoutPromise,\n ]);\n\n if (creationOutcome === \"timeout\") {\n callbacksActive = false;\n void executionPromise\n .then((lateExecution) => bestEffortKillExecution(sandbox, lateExecution.executionId))\n .catch(() => undefined);\n return timeoutResult();\n }\n\n const activeExecution = creationOutcome.execution;\n execution = activeExecution;\n streamPromises = [\n streamExecutionOutput(\n () => sandbox.client.api.devboxes.executions.streamStdoutUpdates(\n sandbox.id,\n activeExecution.executionId,\n {},\n { signal: monitorController.signal },\n ),\n (chunk) => {\n streamedStdout += chunk;\n options.onStdout?.(chunk);\n },\n monitorController.signal,\n () => callbacksActive,\n ),\n streamExecutionOutput(\n () => sandbox.client.api.devboxes.executions.streamStderrUpdates(\n sandbox.id,\n activeExecution.executionId,\n {},\n { signal: monitorController.signal },\n ),\n (chunk) => {\n streamedStderr += chunk;\n options.onStderr?.(chunk);\n },\n monitorController.signal,\n () => callbacksActive,\n ),\n ];\n resultPromise = activeExecution.result({ signal: monitorController.signal });\n const outcome = await Promise.race([\n resultPromise.then((result) => ({ result })),\n timeoutPromise,\n ]);\n\n if (outcome === \"timeout\") {\n callbacksActive = false;\n monitorController.abort();\n await Promise.all([\n bestEffortKillExecution(sandbox, execution.executionId),\n Promise.allSettled([resultPromise, ...streamPromises]),\n ]);\n return timeoutResult();\n }\n\n executionCompleted = true;\n monitorController.abort();\n await Promise.allSettled(streamPromises);\n const commandResult = await toCommandResult(outcome.result);\n emitMissingOutput(streamedStdout, commandResult.stdout, options.onStdout);\n emitMissingOutput(streamedStderr, commandResult.stderr, options.onStderr);\n return commandResult;\n } catch (error) {\n callbacksActive = false;\n monitorController.abort();\n await Promise.all([\n executionCompleted || !execution\n ? Promise.resolve()\n : bestEffortKillExecution(sandbox, execution.executionId),\n Promise.allSettled([\n ...(resultPromise ? [resultPromise] : []),\n ...streamPromises,\n ]),\n ]);\n throw error;\n } finally {\n if (timer) clearTimeout(timer);\n callbacksActive = false;\n monitorController.abort();\n }\n}\n\nasync function runCommandWithErrors(\n sandbox: RunloopSandbox,\n command: string,\n options?: RunCommandOptions,\n): Promise<CommandResult> {\n try {\n return await executeCommand(sandbox, command, options);\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Syntax error\")) {\n throw error;\n }\n throw new Error(\n `Runloop execution failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\n/**\n * Runloop-specific blueprint creation options\n */\nexport interface CreateBlueprintTemplateOptions {\n /** Name of the blueprint template */\n name: string;\n /** Custom Dockerfile content */\n dockerfile?: string;\n /** System setup commands to run during blueprint creation */\n systemSetupCommands?: string[];\n /** Launch commands to run when starting a devbox from this blueprint */\n launchCommands?: string[];\n /** File mounts as key-value pairs (path -> content) */\n fileMounts?: Record<string, string>;\n /** Code repository mounts */\n codeMounts?: Array<{\n repoName: string;\n repoOwner: string;\n token?: string;\n installCommand?: string;\n }>;\n /** Resource size for devboxes created from this blueprint */\n resourceSize?:\n | \"X_SMALL\"\n | \"SMALL\"\n | \"MEDIUM\"\n | \"LARGE\"\n | \"X_LARGE\"\n | \"XX_LARGE\"\n | \"CUSTOM_SIZE\";\n /** CPU architecture */\n architecture?: \"x86_64\" | \"arm64\";\n /** Custom CPU cores (requires CUSTOM_SIZE) */\n customCpuCores?: number;\n /** Custom memory in GB (requires CUSTOM_SIZE) */\n customMemoryGb?: number;\n /** Custom disk size (requires CUSTOM_SIZE) */\n customDiskSize?: number;\n /** Available ports for the devbox */\n availablePorts?: number[];\n /** Action to take when devbox is idle */\n afterIdle?: { action: string; timeSeconds: number };\n /** Keep alive time in seconds */\n keepAliveTimeSeconds?: number;\n}\n\n/**\n * Create a Runloop provider instance using the factory pattern\n */\nexport const runloop = defineProvider<\n RunloopSandbox,\n RunloopConfig,\n RunloopTemplate,\n Snapshot\n>({\n name: \"runloop\",\n methods: {\n sandbox: {\n create: async (config: RunloopConfig, options?: CreateSandboxOptions) => {\n const timeout = config.timeout;\n\n try {\n const client = getRunloopClient(config);\n\n const {\n timeout: optTimeout,\n envs,\n name,\n metadata,\n templateId,\n snapshotId,\n sandboxId: optSandboxId,\n ports: _ports,\n namespace: _namespace,\n directory: _directory,\n launch_parameters: optLaunchParameters,\n ...providerOptions\n } = options || {};\n\n const effectiveTimeout = optTimeout ?? timeout;\n const keepAliveSeconds = effectiveTimeout !== undefined\n ? Math.ceil(effectiveTimeout / 1000)\n : 1800;\n\n let devboxParams: Runloop.DevboxCreateParams = {\n launch_parameters: {\n keep_alive_time_seconds: keepAliveSeconds,\n ...optLaunchParameters,\n } as Runloop.DevboxCreateParams[\"launch_parameters\"],\n name: name || optSandboxId,\n metadata,\n environment_variables: envs,\n ...providerOptions,\n };\n\n // snapshotId is the canonical cross-provider field — map it directly to snapshot_id.\n // templateId is kept for backwards compatibility: bpt_ prefix → blueprint_id, snp_ prefix → snapshot_id.\n if (snapshotId) {\n devboxParams.snapshot_id = snapshotId;\n } else if (templateId) {\n if (templateId.startsWith(\"bpt_\")) {\n devboxParams.blueprint_id = templateId;\n } else if (templateId.startsWith(\"snp_\")) {\n devboxParams.snapshot_id = templateId;\n }\n }\n\n const dbx = await client.api.devboxes.createAndAwaitRunning(\n devboxParams,\n longPollOptions<RunloopCreateWaitOptions>(effectiveTimeout),\n );\n\n const runloopSandbox: RunloopSandbox = {\n ...dbx,\n client: client\n };\n\n return {\n sandbox: runloopSandbox,\n sandboxId: dbx.id,\n };\n } catch (error) {\n throw new Error(\n `Failed to create Runloop devbox: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n },\n\n getById: async (config: RunloopConfig, sandboxId: string) => {\n try {\n const client = getRunloopClient(config);\n const devbox = await client.api.devboxes.retrieve(sandboxId);\n return {\n sandbox: { ...devbox, client } as RunloopSandbox,\n sandboxId,\n };\n } catch (error) {\n if (isHttpNotFound(error)) return null;\n throw error;\n }\n },\n\n list: async (config: RunloopConfig) => {\n const client = getRunloopClient(config);\n const devboxes = await collectPaginated(client.api.devboxes.list());\n\n return devboxes.map((devbox) => ({\n sandbox: { ...devbox, client } as RunloopSandbox,\n sandboxId: devbox.id,\n }));\n },\n\n destroy: async (config: RunloopConfig, sandboxId: string) => {\n try {\n const client = getRunloopClient(config);\n await client.api.devboxes.shutdown(sandboxId);\n } catch (error) {\n if (!isHttpNotFound(error)) throw error;\n }\n },\n\n runCommand: runCommandWithErrors,\n\n streamCommand: runCommandWithErrors,\n\n getInfo: async (sandbox: RunloopSandbox): Promise<SandboxInfo> => {\n const devbox = await sandbox.client.api.devboxes.retrieve(sandbox.id);\n const keepAliveSecs = devbox.launch_parameters?.keep_alive_time_seconds;\n\n return {\n id: devbox.id || \"runloop-unknown\",\n provider: \"runloop\",\n status: mapStatus(devbox.status),\n createdAt: new Date(devbox.create_time_ms || Date.now()),\n // keep_alive_time_seconds is in seconds; SandboxInfo.timeout is in milliseconds\n timeout: keepAliveSecs ? keepAliveSecs * 1000 : 300000,\n metadata: {\n runloopDevboxId: devbox.id,\n templateId: devbox.blueprint_id || devbox.snapshot_id,\n runtime: 'node',\n ...devbox.metadata,\n },\n };\n },\n\n getUrl: async (\n sandbox: RunloopSandbox,\n options: { port: number }\n ): Promise<string> => {\n const devbox = sandbox;\n const client = sandbox.client;\n\n try {\n const tunnel = await client.api.devboxes.enableTunnel(devbox.id);\n return `https://${options.port}-${tunnel.tunnel_key}.tunnel.runloop.ai`;\n } catch (error) {\n throw new Error(\n `Failed to get Runloop URL for port ${options.port}: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n },\n\n filesystem: {\n readFile: async (sandbox: RunloopSandbox, path: string): Promise<string> => {\n return sandbox.client.devbox.fromId(sandbox.id).file.read({ file_path: path });\n },\n\n writeFile: async (sandbox: RunloopSandbox, path: string, content: string): Promise<void> => {\n const result = await sandbox.client.devbox.fromId(sandbox.id).file.write({\n file_path: path,\n contents: content,\n });\n if (result.exit_status !== 0) {\n throw new Error(\n `Failed to write file ${path}: ${result.stderr || `exit ${result.exit_status}`}`,\n );\n }\n },\n\n mkdir: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n const result = await runCommand(sandbox, `mkdir -p -- ${quotePosixShellToken(path)}`);\n if (result.exitCode !== 0) throw new Error(`Failed to create directory ${path}: ${result.stderr}`);\n },\n\n readdir: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<FileEntry[]> => {\n const result = await runCommand(sandbox, buildReaddirCommand(path));\n if (result.exitCode !== 0) throw new Error(`Failed to list directory ${path}: ${result.stderr}`);\n\n return parseReaddirOutput(result.stdout || \"\");\n },\n\n exists: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<boolean> => {\n const result = await runCommand(sandbox, `test -e ${quotePosixShellToken(path)}`);\n return result.exitCode === 0;\n },\n\n remove: async (sandbox: RunloopSandbox, path: string, runCommand: CommandRunner): Promise<void> => {\n assertSafeRemovalPath(path);\n const result = await runCommand(sandbox, `rm -rf -- ${quotePosixShellToken(path)}`);\n if (result.exitCode !== 0) throw new Error(`Failed to remove ${path}: ${result.stderr}`);\n },\n },\n\n getInstance: (sandbox: RunloopSandbox): RunloopSandbox => sandbox,\n },\n\n template: {\n create: async (config: RunloopConfig, options: CreateBlueprintTemplateOptions | Runloop.BlueprintCreateParams) => {\n const client = getRunloopClient(config);\n return client.api.blueprints.create(options);\n },\n\n list: async (config: RunloopConfig, options?: { limit?: number }) => {\n const client = getRunloopClient(config);\n const listParams: Runloop.BlueprintListParams = {};\n if (options?.limit !== undefined) listParams.limit = options.limit;\n return collectPaginated(client.api.blueprints.list(listParams), options?.limit);\n },\n\n delete: async (config: RunloopConfig, blueprintId: string) => {\n const client = getRunloopClient(config);\n await client.api.blueprints.delete(blueprintId);\n },\n },\n\n snapshot: {\n create: async (config: RunloopConfig, sandboxId: string, options?: CreateSnapshotOptions) => {\n const client = getRunloopClient(config);\n const snapshotParams: Runloop.DevboxSnapshotDiskParams = {};\n if (options?.name) snapshotParams.name = options.name;\n if (options?.metadata) snapshotParams.metadata = options.metadata;\n const snapshot = await client.api.devboxes.snapshotDisk(sandboxId, snapshotParams);\n return normalizeSnapshot(snapshot);\n },\n\n list: async (config: RunloopConfig, options?: ListSnapshotsOptions) => {\n const client = getRunloopClient(config);\n const listParams: Runloop.DevboxListDiskSnapshotsParams = {};\n if (options?.limit !== undefined) listParams.limit = options.limit;\n if (options?.sandboxId) listParams.devbox_id = options.sandboxId;\n const snapshots = await collectPaginated(\n client.api.devboxes.listDiskSnapshots(listParams),\n options?.limit,\n );\n return snapshots.map(normalizeSnapshot);\n },\n\n delete: async (config: RunloopConfig, snapshotId: string) => {\n const client = getRunloopClient(config);\n await client.api.devboxes.deleteDiskSnapshot(snapshotId);\n },\n },\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,wBAAyC;AACzC,sBAA+B;AAC/B,uBAAmC;AAmCnC,IAAM,cAAc,oBAAI,QAAmC;AAE3D,SAAS,cAAc,QAA+B;AACpD,SACE,OAAO,UACN,OAAO,YAAY,eAAe,QAAQ,KAAK,mBAChD;AAEJ;AAEA,S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