@sylphx/sdk 0.19.3 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -3
- package/dist/index.d.ts +843 -23
- package/dist/index.mjs +766 -15
- package/dist/index.mjs.map +1 -1
- package/dist/nextjs/index.mjs +31 -25
- package/dist/nextjs/index.mjs.map +1 -1
- package/dist/react/index.d.ts +32 -2
- package/dist/react/index.mjs +92 -9
- package/dist/react/index.mjs.map +1 -1
- package/dist/server/index.d.ts +36 -7
- package/dist/server/index.mjs +31 -29
- package/dist/server/index.mjs.map +1 -1
- package/dist/tasks.d.ts +1463 -0
- package/dist/tasks.mjs +1907 -0
- package/dist/tasks.mjs.map +1 -0
- package/package.json +10 -4
package/dist/index.mjs
CHANGED
|
@@ -15,10 +15,11 @@ function detectSdkPlatform() {
|
|
|
15
15
|
if (typeof runtimeGlobal.EdgeRuntime !== "undefined") return "edge";
|
|
16
16
|
return "node";
|
|
17
17
|
}
|
|
18
|
-
var SDK_API_PATH, DEFAULT_SDK_API_HOST, SDK_VERSION, SDK_PLATFORM, DEFAULT_TIMEOUT_MS, SANDBOX_CREATE_TIMEOUT_MS, SESSION_TOKEN_LIFETIME_SECONDS, SESSION_TOKEN_LIFETIME_MS, REFRESH_TOKEN_LIFETIME_SECONDS, FLAGS_CACHE_TTL_MS, FLAGS_STALE_WHILE_REVALIDATE_MS, MAX_RETRY_DELAY_MS, BASE_RETRY_DELAY_MS, ANALYTICS_SESSION_TIMEOUT_MS, WEBHOOK_MAX_AGE_MS, WEBHOOK_CLOCK_SKEW_MS, PKCE_CODE_TTL_MS, JOBS_DLQ_MAX_AGE_MS, SESSION_REPLAY_MAX_DURATION_MS, FLAGS_EXPOSURE_DEDUPE_WINDOW_MS, CLICK_ID_EXPIRY_MS, STALE_TIME_FREQUENT_MS, STALE_TIME_MODERATE_MS, STALE_TIME_STABLE_MS, STALE_TIME_STATS_MS, NEW_USER_THRESHOLD_MS, STORAGE_MULTIPART_THRESHOLD_BYTES, STORAGE_DEFAULT_MAX_SIZE_BYTES, STORAGE_AVATAR_MAX_SIZE_BYTES, STORAGE_LARGE_MAX_SIZE_BYTES, JWK_CACHE_TTL_MS, CIRCUIT_BREAKER_FAILURE_THRESHOLD, CIRCUIT_BREAKER_WINDOW_MS, CIRCUIT_BREAKER_OPEN_DURATION_MS, ETAG_CACHE_MAX_ENTRIES, ETAG_CACHE_TTL_MS;
|
|
18
|
+
var ENV_SECRET_URL, SDK_API_PATH, DEFAULT_SDK_API_HOST, SDK_VERSION, SDK_PLATFORM, DEFAULT_TIMEOUT_MS, SANDBOX_CREATE_TIMEOUT_MS, SESSION_TOKEN_LIFETIME_SECONDS, SESSION_TOKEN_LIFETIME_MS, REFRESH_TOKEN_LIFETIME_SECONDS, FLAGS_CACHE_TTL_MS, FLAGS_STALE_WHILE_REVALIDATE_MS, MAX_RETRY_DELAY_MS, BASE_RETRY_DELAY_MS, ANALYTICS_SESSION_TIMEOUT_MS, WEBHOOK_MAX_AGE_MS, WEBHOOK_CLOCK_SKEW_MS, PKCE_CODE_TTL_MS, JOBS_DLQ_MAX_AGE_MS, SESSION_REPLAY_MAX_DURATION_MS, FLAGS_EXPOSURE_DEDUPE_WINDOW_MS, CLICK_ID_EXPIRY_MS, STALE_TIME_FREQUENT_MS, STALE_TIME_MODERATE_MS, STALE_TIME_STABLE_MS, STALE_TIME_STATS_MS, NEW_USER_THRESHOLD_MS, STORAGE_MULTIPART_THRESHOLD_BYTES, STORAGE_DEFAULT_MAX_SIZE_BYTES, STORAGE_AVATAR_MAX_SIZE_BYTES, STORAGE_LARGE_MAX_SIZE_BYTES, JWK_CACHE_TTL_MS, CIRCUIT_BREAKER_FAILURE_THRESHOLD, CIRCUIT_BREAKER_WINDOW_MS, CIRCUIT_BREAKER_OPEN_DURATION_MS, ETAG_CACHE_MAX_ENTRIES, ETAG_CACHE_TTL_MS;
|
|
19
19
|
var init_constants = __esm({
|
|
20
20
|
"src/constants.ts"() {
|
|
21
21
|
"use strict";
|
|
22
|
+
ENV_SECRET_URL = "SYLPHX_SECRET_URL";
|
|
22
23
|
SDK_API_PATH = `/v1`;
|
|
23
24
|
DEFAULT_SDK_API_HOST = "api.sylphx.com";
|
|
24
25
|
SDK_VERSION = "0.5.0";
|
|
@@ -170,10 +171,11 @@ function getErrorDetails2(error, fallbackMessage = "An unknown error occurred")
|
|
|
170
171
|
}
|
|
171
172
|
function getSafeErrorMessage(error, fallback = "Something went wrong. Please try again.") {
|
|
172
173
|
const errorCode = getSafeErrorKey(error);
|
|
173
|
-
if (errorCode && SAFE_ERROR_MESSAGES
|
|
174
|
+
if (errorCode && Object.hasOwn(SAFE_ERROR_MESSAGES, errorCode))
|
|
175
|
+
return SAFE_ERROR_MESSAGES[errorCode];
|
|
174
176
|
if (error && typeof error === "object") {
|
|
175
177
|
const coded = error;
|
|
176
|
-
if (coded.data?.code && SAFE_ERROR_MESSAGES
|
|
178
|
+
if (coded.data?.code && Object.hasOwn(SAFE_ERROR_MESSAGES, coded.data.code)) {
|
|
177
179
|
return SAFE_ERROR_MESSAGES[coded.data.code];
|
|
178
180
|
}
|
|
179
181
|
}
|
|
@@ -1401,6 +1403,13 @@ async function getWorkspace(config, workspaceId) {
|
|
|
1401
1403
|
);
|
|
1402
1404
|
return result.workspace;
|
|
1403
1405
|
}
|
|
1406
|
+
async function getWorkspaceCapacity(config, workspaceId) {
|
|
1407
|
+
const result = await callApi(
|
|
1408
|
+
config,
|
|
1409
|
+
`/workspaces/${encodeURIComponent(workspaceId)}/capacity`
|
|
1410
|
+
);
|
|
1411
|
+
return result.snapshot;
|
|
1412
|
+
}
|
|
1404
1413
|
async function createWorkspace(config, input) {
|
|
1405
1414
|
const result = await callApi(config, "/workspaces", {
|
|
1406
1415
|
method: "POST",
|
|
@@ -1421,6 +1430,36 @@ async function forkWorkspace(config, sourceWorkspaceId, input = {}) {
|
|
|
1421
1430
|
);
|
|
1422
1431
|
return result.workspace;
|
|
1423
1432
|
}
|
|
1433
|
+
async function pinWorkspace(config, workspaceId, input = {}) {
|
|
1434
|
+
return callApi(
|
|
1435
|
+
config,
|
|
1436
|
+
`/workspaces/${encodeURIComponent(workspaceId)}/pins`,
|
|
1437
|
+
{
|
|
1438
|
+
method: "POST",
|
|
1439
|
+
body: input
|
|
1440
|
+
}
|
|
1441
|
+
);
|
|
1442
|
+
}
|
|
1443
|
+
async function reclaimWorkspace(config, workspaceId, input = {}) {
|
|
1444
|
+
return callApi(
|
|
1445
|
+
config,
|
|
1446
|
+
`/workspaces/${encodeURIComponent(workspaceId)}/reclaim`,
|
|
1447
|
+
{
|
|
1448
|
+
method: "POST",
|
|
1449
|
+
body: input
|
|
1450
|
+
}
|
|
1451
|
+
);
|
|
1452
|
+
}
|
|
1453
|
+
async function reclaimWorkspaceSubpath(config, workspaceId, input) {
|
|
1454
|
+
return callApi(
|
|
1455
|
+
config,
|
|
1456
|
+
`/workspaces/${encodeURIComponent(workspaceId)}/subpath-reclaims`,
|
|
1457
|
+
{
|
|
1458
|
+
method: "POST",
|
|
1459
|
+
body: input
|
|
1460
|
+
}
|
|
1461
|
+
);
|
|
1462
|
+
}
|
|
1424
1463
|
async function deleteWorkspace(config, workspaceId) {
|
|
1425
1464
|
await callApi(config, `/workspaces/${encodeURIComponent(workspaceId)}`, {
|
|
1426
1465
|
method: "DELETE"
|
|
@@ -1522,8 +1561,8 @@ var COMPUTE_VCPU_ACTIVE_RATE_MICRODOLLARS = 400;
|
|
|
1522
1561
|
var COMPUTE_VCPU_IDLE_RATE_MICRODOLLARS = 50;
|
|
1523
1562
|
var COMPUTE_RAM_RATE_MICRODOLLARS = 167;
|
|
1524
1563
|
var BUILD_MINUTE_PRICES = {
|
|
1525
|
-
standard:
|
|
1526
|
-
// $0.
|
|
1564
|
+
standard: 6e3,
|
|
1565
|
+
// $0.006/min — ADR-2571 (GitHub 2026 floor)
|
|
1527
1566
|
large: 3e4,
|
|
1528
1567
|
// $0.030/min
|
|
1529
1568
|
xlarge: 126e3,
|
|
@@ -1591,7 +1630,7 @@ var INSTANCE_TYPE_ALIASES = {
|
|
|
1591
1630
|
"performance-xl": "2xl"
|
|
1592
1631
|
};
|
|
1593
1632
|
function resolveCanonicalInstanceType(id) {
|
|
1594
|
-
return INSTANCE_TYPE_ALIASES[id]
|
|
1633
|
+
return Object.hasOwn(INSTANCE_TYPE_ALIASES, id) ? INSTANCE_TYPE_ALIASES[id] : id;
|
|
1595
1634
|
}
|
|
1596
1635
|
var INSTANCE_TYPES = {
|
|
1597
1636
|
// ---- Canonical T-shirt sizes (ADR-034) ----
|
|
@@ -1844,7 +1883,7 @@ function resolveMaxInstances(id) {
|
|
|
1844
1883
|
}
|
|
1845
1884
|
var DEFAULT_MAX_INSTANCES = 10;
|
|
1846
1885
|
function isValidInstanceType(id) {
|
|
1847
|
-
return id
|
|
1886
|
+
return Object.hasOwn(INSTANCE_TYPES, id);
|
|
1848
1887
|
}
|
|
1849
1888
|
function validateInstanceTypeForPlan(id, plan) {
|
|
1850
1889
|
const canonicalId = resolveCanonicalInstanceType(id);
|
|
@@ -5058,6 +5097,24 @@ async function putWithRetry(url, body, headers, signal, onProgress) {
|
|
|
5058
5097
|
}
|
|
5059
5098
|
throw lastErr;
|
|
5060
5099
|
}
|
|
5100
|
+
function fileFromCompletion(completion, options, blob) {
|
|
5101
|
+
const now = /* @__PURE__ */ new Date();
|
|
5102
|
+
return {
|
|
5103
|
+
id: completion.fileId,
|
|
5104
|
+
filename: options.filename ?? (isFile(blob) ? blob.name : void 0) ?? "upload.bin",
|
|
5105
|
+
contentType: options.contentType ?? (blob.type || "application/octet-stream"),
|
|
5106
|
+
size: completion.size,
|
|
5107
|
+
checksumSha256: completion.checksumSha256,
|
|
5108
|
+
etag: completion.etag,
|
|
5109
|
+
visibility: options.visibility ?? "private",
|
|
5110
|
+
folder: options.folder ?? null,
|
|
5111
|
+
metadata: options.metadata ?? {},
|
|
5112
|
+
url: completion.url,
|
|
5113
|
+
isDeleted: false,
|
|
5114
|
+
createdAt: now,
|
|
5115
|
+
updatedAt: now
|
|
5116
|
+
};
|
|
5117
|
+
}
|
|
5061
5118
|
async function uploadsCreate(config, blob, options) {
|
|
5062
5119
|
const signal = options.signal;
|
|
5063
5120
|
if (signal?.aborted) throw toAbortError();
|
|
@@ -5124,7 +5181,7 @@ async function runSinglePart(config, blob, session, options, idempotencyKey) {
|
|
|
5124
5181
|
}
|
|
5125
5182
|
);
|
|
5126
5183
|
clearResume(String(session.uploadId));
|
|
5127
|
-
return
|
|
5184
|
+
return fileFromCompletion(completion, options, blob);
|
|
5128
5185
|
}
|
|
5129
5186
|
async function runMultipart(config, blob, session, options, idempotencyKey) {
|
|
5130
5187
|
const { onProgress, signal } = options;
|
|
@@ -5169,10 +5226,7 @@ async function runMultipart(config, blob, session, options, idempotencyKey) {
|
|
|
5169
5226
|
}
|
|
5170
5227
|
);
|
|
5171
5228
|
clearResume(String(session.uploadId));
|
|
5172
|
-
return
|
|
5173
|
-
}
|
|
5174
|
-
async function fetchFile(config, fileId) {
|
|
5175
|
-
return callApi(config, PATHS.file(fileId), { method: "GET" });
|
|
5229
|
+
return fileFromCompletion(completion, options, blob);
|
|
5176
5230
|
}
|
|
5177
5231
|
async function uploadsAbort(config, uploadId) {
|
|
5178
5232
|
await withRetry(() => callApi(config, PATHS.upload(uploadId), { method: "DELETE" }), {
|
|
@@ -5572,6 +5626,24 @@ var TriggersClient = {
|
|
|
5572
5626
|
publishEvent
|
|
5573
5627
|
};
|
|
5574
5628
|
|
|
5629
|
+
// src/lib/tasks/connection.ts
|
|
5630
|
+
init_constants();
|
|
5631
|
+
function resolveTaskServerConnectionUrl(options = {}) {
|
|
5632
|
+
const explicit = options.explicitConnectionUrl?.trim();
|
|
5633
|
+
if (explicit) return explicit;
|
|
5634
|
+
if (typeof process === "undefined") return null;
|
|
5635
|
+
return process.env[ENV_SECRET_URL]?.trim() || null;
|
|
5636
|
+
}
|
|
5637
|
+
function requireTaskServerConnectionUrl(options = {}) {
|
|
5638
|
+
const connectionUrl = resolveTaskServerConnectionUrl(options);
|
|
5639
|
+
if (!connectionUrl) {
|
|
5640
|
+
throw new Error(
|
|
5641
|
+
`[sylphx/tasks] No server connection URL found. Set ${ENV_SECRET_URL} env var or pass config to trigger options.`
|
|
5642
|
+
);
|
|
5643
|
+
}
|
|
5644
|
+
return connectionUrl;
|
|
5645
|
+
}
|
|
5646
|
+
|
|
5575
5647
|
// src/lib/tasks/handler.ts
|
|
5576
5648
|
import { createHmac, timingSafeEqual } from "crypto";
|
|
5577
5649
|
var StepCompleteSignal = class {
|
|
@@ -5581,6 +5653,23 @@ var StepCompleteSignal = class {
|
|
|
5581
5653
|
}
|
|
5582
5654
|
_isStepCompleteSignal = true;
|
|
5583
5655
|
};
|
|
5656
|
+
var StepSideEffectStartSignal = class {
|
|
5657
|
+
constructor(stepName, effectKey, externalService) {
|
|
5658
|
+
this.stepName = stepName;
|
|
5659
|
+
this.effectKey = effectKey;
|
|
5660
|
+
this.externalService = externalService;
|
|
5661
|
+
}
|
|
5662
|
+
_isStepSideEffectStartSignal = true;
|
|
5663
|
+
};
|
|
5664
|
+
var StepSideEffectCompleteSignal = class {
|
|
5665
|
+
constructor(stepName, effectKey, handle, result) {
|
|
5666
|
+
this.stepName = stepName;
|
|
5667
|
+
this.effectKey = effectKey;
|
|
5668
|
+
this.handle = handle;
|
|
5669
|
+
this.result = result;
|
|
5670
|
+
}
|
|
5671
|
+
_isStepSideEffectCompleteSignal = true;
|
|
5672
|
+
};
|
|
5584
5673
|
var StepSleepSignal = class {
|
|
5585
5674
|
constructor(stepName, duration) {
|
|
5586
5675
|
this.stepName = stepName;
|
|
@@ -5596,7 +5685,7 @@ var StepWaitEventSignal = class {
|
|
|
5596
5685
|
}
|
|
5597
5686
|
_isStepWaitEventSignal = true;
|
|
5598
5687
|
};
|
|
5599
|
-
function createStepContext(completedSteps, resolvedWaits) {
|
|
5688
|
+
function createStepContext(completedSteps, resolvedWaits, sideEffectReceipts = /* @__PURE__ */ new Map()) {
|
|
5600
5689
|
return {
|
|
5601
5690
|
/**
|
|
5602
5691
|
* Execute a named step.
|
|
@@ -5611,6 +5700,27 @@ function createStepContext(completedSteps, resolvedWaits) {
|
|
|
5611
5700
|
const result = await fn();
|
|
5612
5701
|
throw new StepCompleteSignal(name, result);
|
|
5613
5702
|
},
|
|
5703
|
+
async sideEffect(stepName, effectKey, externalService, fn) {
|
|
5704
|
+
const receipt = sideEffectReceipts.get(sideEffectReceiptKey(stepName, effectKey));
|
|
5705
|
+
if (!receipt) {
|
|
5706
|
+
throw new StepSideEffectStartSignal(stepName, effectKey, externalService);
|
|
5707
|
+
}
|
|
5708
|
+
if (receipt.externalService !== externalService) {
|
|
5709
|
+
throw new Error(
|
|
5710
|
+
`Side-effect external service mismatch for ${stepName}/${effectKey}: receipt=${receipt.externalService} handler=${externalService}`
|
|
5711
|
+
);
|
|
5712
|
+
}
|
|
5713
|
+
if (receipt.completedAt) {
|
|
5714
|
+
return receipt.result;
|
|
5715
|
+
}
|
|
5716
|
+
const outcome = await fn(receipt.idempotencyKey);
|
|
5717
|
+
throw new StepSideEffectCompleteSignal(
|
|
5718
|
+
stepName,
|
|
5719
|
+
effectKey,
|
|
5720
|
+
normalizeOptionalStepKey(outcome.handle),
|
|
5721
|
+
outcome.result
|
|
5722
|
+
);
|
|
5723
|
+
},
|
|
5614
5724
|
/**
|
|
5615
5725
|
* Sleep for the given duration.
|
|
5616
5726
|
*
|
|
@@ -5651,6 +5761,13 @@ function createStepContext(completedSteps, resolvedWaits) {
|
|
|
5651
5761
|
}
|
|
5652
5762
|
};
|
|
5653
5763
|
}
|
|
5764
|
+
function normalizeOptionalStepKey(value) {
|
|
5765
|
+
const trimmed = value?.trim();
|
|
5766
|
+
return trimmed ? trimmed.slice(0, 500) : void 0;
|
|
5767
|
+
}
|
|
5768
|
+
function sideEffectReceiptKey(stepName, effectKey) {
|
|
5769
|
+
return `${stepName}\0${effectKey}`;
|
|
5770
|
+
}
|
|
5654
5771
|
function verifySignature(body, signature, secret) {
|
|
5655
5772
|
try {
|
|
5656
5773
|
const hmac = createHmac("sha256", secret).update(body, "utf8").digest("hex");
|
|
@@ -5731,7 +5848,11 @@ function createTasksHandler(taskDefs, options = {}) {
|
|
|
5731
5848
|
for (const wait of context?.waits ?? []) {
|
|
5732
5849
|
resolvedWaits.set(wait.name, wait.result ?? void 0);
|
|
5733
5850
|
}
|
|
5734
|
-
const
|
|
5851
|
+
const sideEffectReceipts = /* @__PURE__ */ new Map();
|
|
5852
|
+
for (const receipt of context?.sideEffects ?? []) {
|
|
5853
|
+
sideEffectReceipts.set(sideEffectReceiptKey(receipt.stepName, receipt.effectKey), receipt);
|
|
5854
|
+
}
|
|
5855
|
+
const stepCtx = createStepContext(completedSteps, resolvedWaits, sideEffectReceipts);
|
|
5735
5856
|
try {
|
|
5736
5857
|
const result = await taskDef.handler(payload, { step: stepCtx });
|
|
5737
5858
|
return Response.json({ status: "complete", result });
|
|
@@ -5744,6 +5865,25 @@ function createTasksHandler(taskDefs, options = {}) {
|
|
|
5744
5865
|
result: signal.result
|
|
5745
5866
|
});
|
|
5746
5867
|
}
|
|
5868
|
+
if (err instanceof StepSideEffectStartSignal || err?._isStepSideEffectStartSignal) {
|
|
5869
|
+
const signal = err;
|
|
5870
|
+
return Response.json({
|
|
5871
|
+
status: "side_effect_start",
|
|
5872
|
+
stepName: signal.stepName,
|
|
5873
|
+
effectKey: signal.effectKey,
|
|
5874
|
+
externalService: signal.externalService
|
|
5875
|
+
});
|
|
5876
|
+
}
|
|
5877
|
+
if (err instanceof StepSideEffectCompleteSignal || err?._isStepSideEffectCompleteSignal) {
|
|
5878
|
+
const signal = err;
|
|
5879
|
+
return Response.json({
|
|
5880
|
+
status: "side_effect_complete",
|
|
5881
|
+
stepName: signal.stepName,
|
|
5882
|
+
effectKey: signal.effectKey,
|
|
5883
|
+
handle: signal.handle ?? null,
|
|
5884
|
+
result: signal.result
|
|
5885
|
+
});
|
|
5886
|
+
}
|
|
5747
5887
|
if (err instanceof StepSleepSignal || err?._isStepSleepSignal) {
|
|
5748
5888
|
const signal = err;
|
|
5749
5889
|
return Response.json({
|
|
@@ -5777,6 +5917,191 @@ function createTasksHandler(taskDefs, options = {}) {
|
|
|
5777
5917
|
return { GET, POST };
|
|
5778
5918
|
}
|
|
5779
5919
|
|
|
5920
|
+
// src/lib/tasks/serve.ts
|
|
5921
|
+
var triggerSyncDone = false;
|
|
5922
|
+
var triggerSyncPromise = null;
|
|
5923
|
+
async function syncTriggers(tasks, options) {
|
|
5924
|
+
const connectionUrl = resolveTaskServerConnectionUrl({
|
|
5925
|
+
explicitConnectionUrl: options.connectionUrl
|
|
5926
|
+
});
|
|
5927
|
+
if (!connectionUrl) {
|
|
5928
|
+
return;
|
|
5929
|
+
}
|
|
5930
|
+
const tasksWithTriggers = tasks.filter((t) => t._trigger);
|
|
5931
|
+
if (tasksWithTriggers.length === 0) return;
|
|
5932
|
+
const config = createServerClient(connectionUrl);
|
|
5933
|
+
const results = await Promise.allSettled(
|
|
5934
|
+
tasksWithTriggers.flatMap((t) => {
|
|
5935
|
+
const promises = [];
|
|
5936
|
+
if (t._trigger?.cron) {
|
|
5937
|
+
promises.push(
|
|
5938
|
+
TriggersClient.create(config, {
|
|
5939
|
+
name: `${t.id}:cron`,
|
|
5940
|
+
source: { type: "cron", expression: t._trigger.cron },
|
|
5941
|
+
target: { type: "task", taskName: t.id },
|
|
5942
|
+
idempotencyKey: `task:${t.id}:cron:${t._trigger.cron}`
|
|
5943
|
+
}).catch((err) => {
|
|
5944
|
+
if (err?.status === 409 || err?.message?.includes("already exists")) return;
|
|
5945
|
+
throw err;
|
|
5946
|
+
})
|
|
5947
|
+
);
|
|
5948
|
+
}
|
|
5949
|
+
if (t._trigger?.event) {
|
|
5950
|
+
promises.push(
|
|
5951
|
+
TriggersClient.create(config, {
|
|
5952
|
+
name: `${t.id}:event:${t._trigger.event}`,
|
|
5953
|
+
source: { type: "event", eventName: t._trigger.event },
|
|
5954
|
+
target: { type: "task", taskName: t.id },
|
|
5955
|
+
idempotencyKey: `task:${t.id}:event:${t._trigger.event}`
|
|
5956
|
+
}).catch((err) => {
|
|
5957
|
+
if (err?.status === 409 || err?.message?.includes("already exists")) return;
|
|
5958
|
+
throw err;
|
|
5959
|
+
})
|
|
5960
|
+
);
|
|
5961
|
+
}
|
|
5962
|
+
return promises;
|
|
5963
|
+
})
|
|
5964
|
+
);
|
|
5965
|
+
for (const result of results) {
|
|
5966
|
+
if (result.status === "rejected") {
|
|
5967
|
+
console.warn("[sylphx/tasks] Warning: trigger sync failed", result.reason);
|
|
5968
|
+
}
|
|
5969
|
+
}
|
|
5970
|
+
}
|
|
5971
|
+
function serve(options) {
|
|
5972
|
+
const functionModeTasks = options.tasks.filter((t) => !t._machine && t._run != null);
|
|
5973
|
+
const defs = functionModeTasks.map((t) => ({
|
|
5974
|
+
name: t.id,
|
|
5975
|
+
handler: t._run
|
|
5976
|
+
}));
|
|
5977
|
+
const handlerOptions = {
|
|
5978
|
+
signingSecret: options.signingSecret
|
|
5979
|
+
};
|
|
5980
|
+
const { GET: baseGET, POST: basePOST } = createTasksHandler(defs, handlerOptions);
|
|
5981
|
+
function ensureTriggerSync() {
|
|
5982
|
+
if (triggerSyncDone || triggerSyncPromise) return;
|
|
5983
|
+
triggerSyncPromise = syncTriggers(options.tasks, options).then(() => {
|
|
5984
|
+
triggerSyncDone = true;
|
|
5985
|
+
}).catch((err) => {
|
|
5986
|
+
triggerSyncPromise = null;
|
|
5987
|
+
console.warn("[sylphx/tasks] Trigger sync error:", err);
|
|
5988
|
+
});
|
|
5989
|
+
}
|
|
5990
|
+
return {
|
|
5991
|
+
async GET(req) {
|
|
5992
|
+
ensureTriggerSync();
|
|
5993
|
+
return baseGET(req);
|
|
5994
|
+
},
|
|
5995
|
+
async POST(req) {
|
|
5996
|
+
ensureTriggerSync();
|
|
5997
|
+
return basePOST(req);
|
|
5998
|
+
}
|
|
5999
|
+
};
|
|
6000
|
+
}
|
|
6001
|
+
|
|
6002
|
+
// src/lib/tasks/task.ts
|
|
6003
|
+
function resolveConfig(options) {
|
|
6004
|
+
if (options?.config) return options.config;
|
|
6005
|
+
const connectionUrl = requireTaskServerConnectionUrl();
|
|
6006
|
+
return createServerClient(connectionUrl);
|
|
6007
|
+
}
|
|
6008
|
+
async function pollUntilComplete(config, taskRunId, timeoutMs) {
|
|
6009
|
+
const deadline = Date.now() + timeoutMs;
|
|
6010
|
+
let delay = 500;
|
|
6011
|
+
while (Date.now() < deadline) {
|
|
6012
|
+
const run = await callApi(
|
|
6013
|
+
config,
|
|
6014
|
+
`/tasks/${taskRunId}`,
|
|
6015
|
+
{ method: "GET" }
|
|
6016
|
+
);
|
|
6017
|
+
if (run.status === "completed") return run.result;
|
|
6018
|
+
if (run.status === "failed" || run.status === "cancelled") {
|
|
6019
|
+
throw new Error(run.error ?? `Task run ${taskRunId} ${run.status}`);
|
|
6020
|
+
}
|
|
6021
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
6022
|
+
delay = Math.min(delay * 1.5, 5e3);
|
|
6023
|
+
}
|
|
6024
|
+
throw new Error(`Task run ${taskRunId} timed out after ${timeoutMs}ms`);
|
|
6025
|
+
}
|
|
6026
|
+
async function dispatchTask(id, payload, machine, options) {
|
|
6027
|
+
const config = resolveConfig(options);
|
|
6028
|
+
const body = {
|
|
6029
|
+
taskName: id,
|
|
6030
|
+
payload
|
|
6031
|
+
};
|
|
6032
|
+
if (options?.idempotencyKey) body.idempotencyKey = options.idempotencyKey;
|
|
6033
|
+
if (options?.delay) body.delay = options.delay;
|
|
6034
|
+
if (options?.scheduledFor) body.scheduledFor = options.scheduledFor.toISOString();
|
|
6035
|
+
if (options?.maxAttempts) body.maxAttempts = options.maxAttempts;
|
|
6036
|
+
if (options?.queue) body.queue = options.queue;
|
|
6037
|
+
if (machine) body.machine = machine;
|
|
6038
|
+
const result = await callApi(config, "/tasks/trigger", {
|
|
6039
|
+
method: "POST",
|
|
6040
|
+
body
|
|
6041
|
+
});
|
|
6042
|
+
const runId = result.taskRunId;
|
|
6043
|
+
const defaultTimeoutMs = machine ? 24 * 3600 * 1e3 : 3e5;
|
|
6044
|
+
return {
|
|
6045
|
+
id: runId,
|
|
6046
|
+
status: result.status,
|
|
6047
|
+
waitForCompletion(waitOptions) {
|
|
6048
|
+
return pollUntilComplete(config, runId, waitOptions?.timeoutMs ?? defaultTimeoutMs);
|
|
6049
|
+
},
|
|
6050
|
+
async cancel() {
|
|
6051
|
+
const cancelled = await callApi(config, `/tasks/${runId}/cancel`, {
|
|
6052
|
+
method: "POST"
|
|
6053
|
+
});
|
|
6054
|
+
return cancelled.success;
|
|
6055
|
+
}
|
|
6056
|
+
};
|
|
6057
|
+
}
|
|
6058
|
+
function task(config) {
|
|
6059
|
+
return {
|
|
6060
|
+
id: config.id,
|
|
6061
|
+
_trigger: config.trigger,
|
|
6062
|
+
_machine: config.machine,
|
|
6063
|
+
_run: config.run,
|
|
6064
|
+
async trigger(payload, options) {
|
|
6065
|
+
return dispatchTask(config.id, payload, config.machine, options);
|
|
6066
|
+
},
|
|
6067
|
+
async triggerAndWait(payload, options) {
|
|
6068
|
+
const handle = await dispatchTask(
|
|
6069
|
+
config.id,
|
|
6070
|
+
payload,
|
|
6071
|
+
config.machine,
|
|
6072
|
+
options
|
|
6073
|
+
);
|
|
6074
|
+
return handle.waitForCompletion();
|
|
6075
|
+
},
|
|
6076
|
+
async batchTrigger(payloads, options) {
|
|
6077
|
+
const handles = await Promise.all(
|
|
6078
|
+
payloads.map((p) => dispatchTask(config.id, p, config.machine, options))
|
|
6079
|
+
);
|
|
6080
|
+
return { runs: handles };
|
|
6081
|
+
}
|
|
6082
|
+
};
|
|
6083
|
+
}
|
|
6084
|
+
function taskStub(id) {
|
|
6085
|
+
return {
|
|
6086
|
+
id,
|
|
6087
|
+
_machine: void 0,
|
|
6088
|
+
_run: void 0,
|
|
6089
|
+
async trigger(payload, options) {
|
|
6090
|
+
return dispatchTask(id, payload, void 0, options);
|
|
6091
|
+
},
|
|
6092
|
+
async triggerAndWait(payload, options) {
|
|
6093
|
+
const handle = await dispatchTask(id, payload, void 0, options);
|
|
6094
|
+
return handle.waitForCompletion();
|
|
6095
|
+
},
|
|
6096
|
+
async batchTrigger(payloads, options) {
|
|
6097
|
+
const handles = await Promise.all(
|
|
6098
|
+
payloads.map((p) => dispatchTask(id, p, void 0, options))
|
|
6099
|
+
);
|
|
6100
|
+
return { runs: handles };
|
|
6101
|
+
}
|
|
6102
|
+
};
|
|
6103
|
+
}
|
|
6104
|
+
|
|
5780
6105
|
// src/lib/tasks/api-functions.ts
|
|
5781
6106
|
async function scheduleTask(config, input) {
|
|
5782
6107
|
return callApi(config, "/tasks/schedule", {
|
|
@@ -5787,6 +6112,9 @@ async function scheduleTask(config, input) {
|
|
|
5787
6112
|
async function getTask(config, taskId) {
|
|
5788
6113
|
return callApi(config, `/tasks/${taskId}`, { method: "GET" });
|
|
5789
6114
|
}
|
|
6115
|
+
async function getTaskRun(config, runId) {
|
|
6116
|
+
return callApi(config, `/tasks/${runId}`, { method: "GET" });
|
|
6117
|
+
}
|
|
5790
6118
|
async function cancelTask(config, taskId) {
|
|
5791
6119
|
const result = await callApi(config, `/tasks/${taskId}/cancel`, {
|
|
5792
6120
|
method: "POST"
|
|
@@ -6987,6 +7315,28 @@ var SandboxWatch = class {
|
|
|
6987
7315
|
if (!res.ok) throw new Error(`watch.remove failed: ${await res.text()}`);
|
|
6988
7316
|
}
|
|
6989
7317
|
};
|
|
7318
|
+
var SandboxCapabilities = class {
|
|
7319
|
+
constructor(endpoint, token) {
|
|
7320
|
+
this.endpoint = endpoint;
|
|
7321
|
+
this.token = token;
|
|
7322
|
+
}
|
|
7323
|
+
authHeader() {
|
|
7324
|
+
return { Authorization: `Bearer ${this.token}` };
|
|
7325
|
+
}
|
|
7326
|
+
/**
|
|
7327
|
+
* Fetch the typed capability catalog for this sandbox image.
|
|
7328
|
+
*
|
|
7329
|
+
* Use this before selecting heavyweight toolchain paths. For example,
|
|
7330
|
+
* default sandboxes report Android emulator/device-test as `not-local`, so
|
|
7331
|
+
* agents can hand APK/AAB artifacts to a managed device runtime instead of
|
|
7332
|
+
* filling `/workspace` with emulator images.
|
|
7333
|
+
*/
|
|
7334
|
+
async get() {
|
|
7335
|
+
const res = await fetch(`${this.endpoint}/capabilities`, { headers: this.authHeader() });
|
|
7336
|
+
if (!res.ok) throw new Error(`capabilities.get failed (${res.status}): ${await res.text()}`);
|
|
7337
|
+
return await res.json();
|
|
7338
|
+
}
|
|
7339
|
+
};
|
|
6990
7340
|
var SandboxBrowser = class {
|
|
6991
7341
|
constructor(endpoint, token) {
|
|
6992
7342
|
this.endpoint = endpoint;
|
|
@@ -7204,6 +7554,8 @@ var SandboxClient = class _SandboxClient {
|
|
|
7204
7554
|
processes;
|
|
7205
7555
|
/** Filesystem watch management (direct to exec-server) */
|
|
7206
7556
|
watch;
|
|
7557
|
+
/** Typed capability catalog (direct to exec-server) */
|
|
7558
|
+
capabilities;
|
|
7207
7559
|
/** Persistent headful browser sessions (direct to exec-server — ADR-205) */
|
|
7208
7560
|
browser;
|
|
7209
7561
|
/** Persistent desktop (computer-use) sessions (direct to exec-server — ADR-207) */
|
|
@@ -7216,6 +7568,7 @@ var SandboxClient = class _SandboxClient {
|
|
|
7216
7568
|
this.files = endpoint && token ? new SandboxFiles(endpoint, token) : null;
|
|
7217
7569
|
this.processes = endpoint && token ? new SandboxProcesses(endpoint, token) : null;
|
|
7218
7570
|
this.watch = endpoint && token ? new SandboxWatch(endpoint, token) : null;
|
|
7571
|
+
this.capabilities = endpoint && token ? new SandboxCapabilities(endpoint, token) : null;
|
|
7219
7572
|
this.browser = endpoint && token ? new SandboxBrowser(endpoint, token) : null;
|
|
7220
7573
|
this.computer = endpoint && token ? new SandboxComputer(endpoint, token) : null;
|
|
7221
7574
|
}
|
|
@@ -7441,7 +7794,224 @@ var SandboxClient = class _SandboxClient {
|
|
|
7441
7794
|
}
|
|
7442
7795
|
};
|
|
7443
7796
|
|
|
7797
|
+
// src/artifacts.ts
|
|
7798
|
+
var ArtifactClient = {
|
|
7799
|
+
/**
|
|
7800
|
+
* Publish a self-contained HTML document to a safe, shareable URL. Returns a
|
|
7801
|
+
* signed expiring link by default (`access: 'signed-link'`) — click-to-view, no
|
|
7802
|
+
* login, leaked links decay; `public` for a durable URL. On success returns
|
|
7803
|
+
* `{ id, url, expiresAt?, version }`; on failure a structured `error` with a
|
|
7804
|
+
* `code` (e.g. `blocked_unsafe`) and `diagnostics`.
|
|
7805
|
+
*
|
|
7806
|
+
* **Update in place (ADR-2564 v2):** pass `artifactId` (the `id` from a prior
|
|
7807
|
+
* publish) to REVISE that artifact — the id and the shareable URL are preserved
|
|
7808
|
+
* and `version` increments. The caller must own the artifact (`forbidden`
|
|
7809
|
+
* otherwise), it must still exist (`not_found`), and it must be a versioned
|
|
7810
|
+
* artifact (`conflict` for pre-versioning artifacts). Omit `artifactId` to
|
|
7811
|
+
* create a fresh artifact.
|
|
7812
|
+
*/
|
|
7813
|
+
async publish(config, request) {
|
|
7814
|
+
return callApi(config, "/artifacts", { method: "POST", body: request });
|
|
7815
|
+
},
|
|
7816
|
+
/**
|
|
7817
|
+
* List the calling project's published artifacts, newest-first. Returns
|
|
7818
|
+
* metadata only — `{ artifacts: [{ id, title?, access, currentVersion,
|
|
7819
|
+
* createdAt, updatedAt, expiresAt? }] }`.
|
|
7820
|
+
*
|
|
7821
|
+
* Excludes soft-deleted artifacts by default. Pass `{ includeDeleted: true }`
|
|
7822
|
+
* to ALSO list tombstoned ones (each carrying `deleted: true` + `deletedAt`),
|
|
7823
|
+
* so you can find a soft-deleted artifact's id and {@link ArtifactClient.restore}
|
|
7824
|
+
* it before the grace-window cleanup erases it.
|
|
7825
|
+
*/
|
|
7826
|
+
async list(config, options = {}) {
|
|
7827
|
+
return callApi(config, "/artifacts", {
|
|
7828
|
+
method: "GET",
|
|
7829
|
+
...options.includeDeleted ? { query: { include_deleted: "true" } } : {}
|
|
7830
|
+
});
|
|
7831
|
+
},
|
|
7832
|
+
/**
|
|
7833
|
+
* Get one artifact's metadata and its immutable version history. Throws
|
|
7834
|
+
* `NOT_FOUND` if the artifact does not exist (or is soft-deleted), `FORBIDDEN`
|
|
7835
|
+
* if it belongs to another project.
|
|
7836
|
+
*/
|
|
7837
|
+
async get(config, id) {
|
|
7838
|
+
return callApi(config, `/artifacts/${encodeURIComponent(id)}`, {
|
|
7839
|
+
method: "GET"
|
|
7840
|
+
});
|
|
7841
|
+
},
|
|
7842
|
+
/**
|
|
7843
|
+
* Get an artifact's CURRENT HTML source so you can EDIT it, then re-{@link
|
|
7844
|
+
* ArtifactClient.publish} with `artifactId` to update it in place — instead of
|
|
7845
|
+
* rewriting it blind from a fresh session. Returns `{ id, version, html }`.
|
|
7846
|
+
* Throws `NOT_FOUND` if it does not exist (or is soft-deleted), `FORBIDDEN` if
|
|
7847
|
+
* it belongs to another project. `get` returns metadata only; this returns the
|
|
7848
|
+
* bytes.
|
|
7849
|
+
*/
|
|
7850
|
+
async getContent(config, id) {
|
|
7851
|
+
return callApi(config, `/artifacts/${encodeURIComponent(id)}/content`, {
|
|
7852
|
+
method: "GET"
|
|
7853
|
+
});
|
|
7854
|
+
},
|
|
7855
|
+
/**
|
|
7856
|
+
* Soft-delete an artifact (reversible). The shareable URL begins returning
|
|
7857
|
+
* `410 Gone`; the bytes are retained until a later grace-window cleanup, so
|
|
7858
|
+
* {@link ArtifactClient.restore} can bring it back. Throws `NOT_FOUND` /
|
|
7859
|
+
* `FORBIDDEN` as for {@link ArtifactClient.get}.
|
|
7860
|
+
*/
|
|
7861
|
+
async delete(config, id) {
|
|
7862
|
+
return callApi(config, `/artifacts/${encodeURIComponent(id)}`, {
|
|
7863
|
+
method: "DELETE"
|
|
7864
|
+
});
|
|
7865
|
+
},
|
|
7866
|
+
/**
|
|
7867
|
+
* Restore a soft-deleted artifact. Pass `version` to roll a prior version
|
|
7868
|
+
* FORWARD as a new current version (history is never rewritten) — the returned
|
|
7869
|
+
* `version` is then the new current. Omit it to simply clear the tombstone.
|
|
7870
|
+
*/
|
|
7871
|
+
async restore(config, id, options = {}) {
|
|
7872
|
+
return callApi(config, `/artifacts/${encodeURIComponent(id)}/restore`, {
|
|
7873
|
+
method: "POST",
|
|
7874
|
+
body: options.version !== void 0 ? { version: options.version } : {}
|
|
7875
|
+
});
|
|
7876
|
+
},
|
|
7877
|
+
/**
|
|
7878
|
+
* Re-mint a fresh signed share link (a new capability URL + TTL) for an
|
|
7879
|
+
* artifact — e.g. to extend or rotate a link. Returns `{ url, expiresAt? }`.
|
|
7880
|
+
* For a `public` artifact the durable URL is returned as-is. Pass `ttlSeconds`
|
|
7881
|
+
* to set the new link's lifetime (clamped to the allowed window).
|
|
7882
|
+
*/
|
|
7883
|
+
async reshare(config, id, options = {}) {
|
|
7884
|
+
return callApi(config, `/artifacts/${encodeURIComponent(id)}/reshare`, {
|
|
7885
|
+
method: "POST",
|
|
7886
|
+
body: options.ttlSeconds !== void 0 ? { ttlSeconds: options.ttlSeconds } : {}
|
|
7887
|
+
});
|
|
7888
|
+
}
|
|
7889
|
+
};
|
|
7890
|
+
|
|
7891
|
+
// src/render.ts
|
|
7892
|
+
var RenderClient = {
|
|
7893
|
+
/**
|
|
7894
|
+
* Render a chart (`engine: 'vega-lite'`, Vega-Lite JSON in `spec`) or a diagram
|
|
7895
|
+
* (`engine: 'graphviz'`, DOT in `spec`) to an image. The engine validates and
|
|
7896
|
+
* repairs the spec before rendering; on success returns base64 image bytes, on
|
|
7897
|
+
* failure a structured `error` with a `code` and `diagnostics`.
|
|
7898
|
+
*/
|
|
7899
|
+
async render(config, request) {
|
|
7900
|
+
return callApi(config, "/render", { method: "POST", body: request });
|
|
7901
|
+
}
|
|
7902
|
+
};
|
|
7903
|
+
|
|
7904
|
+
// src/wallet.ts
|
|
7905
|
+
var WalletClient = {
|
|
7906
|
+
/** Mint a grant block of credits for an end user. */
|
|
7907
|
+
async grant(config, request) {
|
|
7908
|
+
return callApi(config, "/wallet/grants", { method: "POST", body: request });
|
|
7909
|
+
},
|
|
7910
|
+
/** Get an end user's derived balance (`available = posted − reserved`). */
|
|
7911
|
+
async getBalance(config, request) {
|
|
7912
|
+
return callApi(config, "/wallet/balance", { method: "POST", body: request });
|
|
7913
|
+
},
|
|
7914
|
+
/** Reserve credits (two-phase hold with a mandatory TTL). */
|
|
7915
|
+
async reserve(config, request) {
|
|
7916
|
+
return callApi(config, "/wallet/reservations", { method: "POST", body: request });
|
|
7917
|
+
},
|
|
7918
|
+
/** Capture a reservation (≤ reserved; releases the remainder). */
|
|
7919
|
+
async consume(config, request) {
|
|
7920
|
+
return callApi(config, "/wallet/reservations/consume", {
|
|
7921
|
+
method: "POST",
|
|
7922
|
+
body: request
|
|
7923
|
+
});
|
|
7924
|
+
},
|
|
7925
|
+
/** Release a reservation (return the held credits). */
|
|
7926
|
+
async release(config, request) {
|
|
7927
|
+
return callApi(config, "/wallet/reservations/release", {
|
|
7928
|
+
method: "POST",
|
|
7929
|
+
body: request
|
|
7930
|
+
});
|
|
7931
|
+
},
|
|
7932
|
+
/** Void/claw back a specific grant block (audited ledger entry). */
|
|
7933
|
+
async voidGrant(config, request) {
|
|
7934
|
+
return callApi(config, "/wallet/grants/void", { method: "POST", body: request });
|
|
7935
|
+
}
|
|
7936
|
+
};
|
|
7937
|
+
|
|
7938
|
+
// src/device-sessions.ts
|
|
7939
|
+
var projectSessionsPath = (projectId) => `/projects/${encodeURIComponent(projectId)}/device-sessions`;
|
|
7940
|
+
var sessionPath = (sessionId, suffix = "") => `/device-sessions/${encodeURIComponent(sessionId)}${suffix}`;
|
|
7941
|
+
var DeviceSessionClient = {
|
|
7942
|
+
/** Boot a long-lived interactive device session in a project (poll to `ready`). */
|
|
7943
|
+
async create(config, projectId, body) {
|
|
7944
|
+
return callApi(config, projectSessionsPath(projectId), {
|
|
7945
|
+
method: "POST",
|
|
7946
|
+
body
|
|
7947
|
+
});
|
|
7948
|
+
},
|
|
7949
|
+
/** List interactive device sessions for a project. */
|
|
7950
|
+
async list(config, projectId, query) {
|
|
7951
|
+
return callApi(config, projectSessionsPath(projectId), {
|
|
7952
|
+
query: query ? { environmentId: query.environmentId, status: query.status, limit: query.limit } : void 0
|
|
7953
|
+
});
|
|
7954
|
+
},
|
|
7955
|
+
/** Get one device session by id — poll for `booting` → `ready`. */
|
|
7956
|
+
async get(config, sessionId) {
|
|
7957
|
+
return callApi(config, sessionPath(sessionId));
|
|
7958
|
+
},
|
|
7959
|
+
/** Install an APK handle (`http(s)://`, `s3://`, or a storage key) onto the device. */
|
|
7960
|
+
async install(config, sessionId, body) {
|
|
7961
|
+
return callApi(config, sessionPath(sessionId, "/install"), {
|
|
7962
|
+
method: "POST",
|
|
7963
|
+
body
|
|
7964
|
+
});
|
|
7965
|
+
},
|
|
7966
|
+
/** Send an input event (tap / swipe / key / text) — how the agent acts on the device. */
|
|
7967
|
+
async input(config, sessionId, body) {
|
|
7968
|
+
return callApi(config, sessionPath(sessionId, "/input"), {
|
|
7969
|
+
method: "POST",
|
|
7970
|
+
body
|
|
7971
|
+
});
|
|
7972
|
+
},
|
|
7973
|
+
/** Launch an installed app (defaults to the most-recently installed package). */
|
|
7974
|
+
async launch(config, sessionId, body = {}) {
|
|
7975
|
+
return callApi(config, sessionPath(sessionId, "/launch"), {
|
|
7976
|
+
method: "POST",
|
|
7977
|
+
body
|
|
7978
|
+
});
|
|
7979
|
+
},
|
|
7980
|
+
/** Capture a PNG screenshot — how the agent "sees" the device (base64 always present). */
|
|
7981
|
+
async screenshot(config, sessionId) {
|
|
7982
|
+
return callApi(config, sessionPath(sessionId, "/screenshot"));
|
|
7983
|
+
},
|
|
7984
|
+
/** Read recent logcat output from the device session. */
|
|
7985
|
+
async logcat(config, sessionId, query) {
|
|
7986
|
+
return callApi(config, sessionPath(sessionId, "/logcat"), {
|
|
7987
|
+
query: query ? { lines: query.lines } : void 0
|
|
7988
|
+
});
|
|
7989
|
+
},
|
|
7990
|
+
/**
|
|
7991
|
+
* Mint a short-lived signed descriptor for a browser to join the session's live
|
|
7992
|
+
* WebRTC view (ADR-2566). Requires the session to be booted stream-capable
|
|
7993
|
+
* (`create` with `stream: true`).
|
|
7994
|
+
*/
|
|
7995
|
+
async streamConnect(config, sessionId, body = {}) {
|
|
7996
|
+
return callApi(config, sessionPath(sessionId, "/stream"), {
|
|
7997
|
+
method: "POST",
|
|
7998
|
+
body
|
|
7999
|
+
});
|
|
8000
|
+
},
|
|
8001
|
+
/** Terminate a device session and release its device. */
|
|
8002
|
+
async delete(config, sessionId) {
|
|
8003
|
+
return callApi(config, sessionPath(sessionId), { method: "DELETE" });
|
|
8004
|
+
}
|
|
8005
|
+
};
|
|
8006
|
+
|
|
7444
8007
|
// src/workers.ts
|
|
8008
|
+
var TERMINAL_AGGREGATE_STATUSES = /* @__PURE__ */ new Set([
|
|
8009
|
+
"succeeded",
|
|
8010
|
+
"failed",
|
|
8011
|
+
"partial",
|
|
8012
|
+
"cancelled",
|
|
8013
|
+
"timed_out"
|
|
8014
|
+
]);
|
|
7445
8015
|
var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
7446
8016
|
"succeeded",
|
|
7447
8017
|
"failed",
|
|
@@ -7450,6 +8020,9 @@ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
|
7450
8020
|
]);
|
|
7451
8021
|
var DEFAULT_POLL_INTERVAL_MS = 3e3;
|
|
7452
8022
|
var DEFAULT_WAIT_TIMEOUT_MS = 72e5;
|
|
8023
|
+
function runImageSourceBody(options) {
|
|
8024
|
+
return options.image !== void 0 ? { image: options.image } : { imageFromService: options.imageFromService };
|
|
8025
|
+
}
|
|
7453
8026
|
var RunHandle = class {
|
|
7454
8027
|
id;
|
|
7455
8028
|
config;
|
|
@@ -7542,6 +8115,98 @@ var RunHandle = class {
|
|
|
7542
8115
|
await callApi(this.config, `/workers/${this.id}`, { method: "DELETE" });
|
|
7543
8116
|
}
|
|
7544
8117
|
};
|
|
8118
|
+
var DistributedRunHandle = class {
|
|
8119
|
+
id;
|
|
8120
|
+
/** Submitted shard count — used to request + render the N-shard aggregate. */
|
|
8121
|
+
parallelism;
|
|
8122
|
+
config;
|
|
8123
|
+
completionMode;
|
|
8124
|
+
constructor(id, config, parallelism, completionMode) {
|
|
8125
|
+
this.id = id;
|
|
8126
|
+
this.config = config;
|
|
8127
|
+
this.parallelism = parallelism;
|
|
8128
|
+
this.completionMode = completionMode;
|
|
8129
|
+
}
|
|
8130
|
+
// --------------------------------------------------------------------------
|
|
8131
|
+
// Status (aggregate)
|
|
8132
|
+
// --------------------------------------------------------------------------
|
|
8133
|
+
/**
|
|
8134
|
+
* Get the current aggregate status + per-shard drill-down for this run.
|
|
8135
|
+
*
|
|
8136
|
+
* Hits `GET /runs/:id?view=distributed` — the additive superset of the
|
|
8137
|
+
* single-shard read model — passing the submitted `parallelism` so the platform
|
|
8138
|
+
* lays the observed status out across the N indexed shards.
|
|
8139
|
+
*/
|
|
8140
|
+
async status() {
|
|
8141
|
+
const run = await callApi(this.config, `/workers/${this.id}`, {
|
|
8142
|
+
method: "GET",
|
|
8143
|
+
query: {
|
|
8144
|
+
view: "distributed",
|
|
8145
|
+
parallelism: this.parallelism,
|
|
8146
|
+
completionMode: this.completionMode
|
|
8147
|
+
}
|
|
8148
|
+
});
|
|
8149
|
+
return run.distributed;
|
|
8150
|
+
}
|
|
8151
|
+
// --------------------------------------------------------------------------
|
|
8152
|
+
// Shards (per-shard drill-down)
|
|
8153
|
+
// --------------------------------------------------------------------------
|
|
8154
|
+
/** Get the per-shard status list (index, status, exitCode, timings). */
|
|
8155
|
+
async shards() {
|
|
8156
|
+
const distributed = await this.status();
|
|
8157
|
+
return [...distributed.shards];
|
|
8158
|
+
}
|
|
8159
|
+
// --------------------------------------------------------------------------
|
|
8160
|
+
// Wait (poll to aggregate terminal)
|
|
8161
|
+
// --------------------------------------------------------------------------
|
|
8162
|
+
/**
|
|
8163
|
+
* Poll until the aggregate reaches a terminal state (succeeded, failed,
|
|
8164
|
+
* partial, cancelled, timed_out) and return the final {@link DistributedRun}.
|
|
8165
|
+
*
|
|
8166
|
+
* @param options.pollIntervalMs - How often to poll in ms (default: 3000)
|
|
8167
|
+
* @param options.timeoutMs - Max time to wait before throwing (default: 2h)
|
|
8168
|
+
* @throws Error if the wait timeout is exceeded
|
|
8169
|
+
*/
|
|
8170
|
+
async wait(options) {
|
|
8171
|
+
const pollMs = options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
8172
|
+
const maxWaitMs = options?.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
8173
|
+
const deadline = Date.now() + maxWaitMs;
|
|
8174
|
+
while (true) {
|
|
8175
|
+
const distributed = await this.status();
|
|
8176
|
+
if (TERMINAL_AGGREGATE_STATUSES.has(distributed.status)) {
|
|
8177
|
+
return distributed;
|
|
8178
|
+
}
|
|
8179
|
+
if (Date.now() >= deadline) {
|
|
8180
|
+
throw new Error(
|
|
8181
|
+
`Distributed run ${this.id} did not complete within ${maxWaitMs}ms (current status: ${distributed.status})`
|
|
8182
|
+
);
|
|
8183
|
+
}
|
|
8184
|
+
await sleep2(pollMs);
|
|
8185
|
+
}
|
|
8186
|
+
}
|
|
8187
|
+
// --------------------------------------------------------------------------
|
|
8188
|
+
// Logs (per-shard)
|
|
8189
|
+
// --------------------------------------------------------------------------
|
|
8190
|
+
/**
|
|
8191
|
+
* Fetch captured logs for one shard (default: shard 0).
|
|
8192
|
+
*
|
|
8193
|
+
* @param options.shard - Shard index (0..parallelism-1). Defaults to 0.
|
|
8194
|
+
*/
|
|
8195
|
+
async logs(options) {
|
|
8196
|
+
const shard = options?.shard ?? 0;
|
|
8197
|
+
return callApi(this.config, `/workers/${this.id}/logs`, {
|
|
8198
|
+
method: "GET",
|
|
8199
|
+
query: { shard, parallelism: this.parallelism }
|
|
8200
|
+
});
|
|
8201
|
+
}
|
|
8202
|
+
// --------------------------------------------------------------------------
|
|
8203
|
+
// Cancel (whole set)
|
|
8204
|
+
// --------------------------------------------------------------------------
|
|
8205
|
+
/** Cancel the whole run (all shards). */
|
|
8206
|
+
async cancel() {
|
|
8207
|
+
await callApi(this.config, `/workers/${this.id}`, { method: "DELETE" });
|
|
8208
|
+
}
|
|
8209
|
+
};
|
|
7545
8210
|
var RunsClient = {
|
|
7546
8211
|
// --------------------------------------------------------------------------
|
|
7547
8212
|
// Run
|
|
@@ -7567,7 +8232,7 @@ var RunsClient = {
|
|
|
7567
8232
|
const run = await callApi(config, "/runs", {
|
|
7568
8233
|
method: "POST",
|
|
7569
8234
|
body: {
|
|
7570
|
-
|
|
8235
|
+
...runImageSourceBody(options),
|
|
7571
8236
|
command: options.command,
|
|
7572
8237
|
env: options.env,
|
|
7573
8238
|
machine: options.machine ?? "standard",
|
|
@@ -7578,6 +8243,78 @@ var RunsClient = {
|
|
|
7578
8243
|
return new RunHandle(run.id, config);
|
|
7579
8244
|
},
|
|
7580
8245
|
// --------------------------------------------------------------------------
|
|
8246
|
+
// Run distributed (multi-shard fan-out)
|
|
8247
|
+
// --------------------------------------------------------------------------
|
|
8248
|
+
/**
|
|
8249
|
+
* Spawn a Distributed Run — one logical job fanned out to N indexed shards —
|
|
8250
|
+
* and return a {@link DistributedRunHandle} (ADR distributed-batch-compute).
|
|
8251
|
+
*
|
|
8252
|
+
* The platform owns sharding, gang start (all shards admitted together or
|
|
8253
|
+
* none), the per-org concurrency budget, and the aggregate/per-shard rollup.
|
|
8254
|
+
* Each shard self-selects its partition from the injected
|
|
8255
|
+
* `SYLPHX_SHARD_INDEX` (0..parallelism-1) + `SYLPHX_SHARD_COUNT` env vars — no
|
|
8256
|
+
* coordinator code for the embarrassingly-parallel case.
|
|
8257
|
+
*
|
|
8258
|
+
* `parallelism: 1` is equivalent to {@link RunsClient.run} (the single-shard
|
|
8259
|
+
* N=1 case); the single-shard `run()` ergonomic path is unchanged.
|
|
8260
|
+
*
|
|
8261
|
+
* @example
|
|
8262
|
+
* ```typescript
|
|
8263
|
+
* const run = await RunsClient.runDistributed(config, {
|
|
8264
|
+
* image: 'ghcr.io/acme/trainer:sha-abc123',
|
|
8265
|
+
* command: ['python', 'train.py'],
|
|
8266
|
+
* parallelism: 16,
|
|
8267
|
+
* machine: 'large',
|
|
8268
|
+
* })
|
|
8269
|
+
* const result = await run.wait()
|
|
8270
|
+
* if (result.status !== 'succeeded') {
|
|
8271
|
+
* const failed = result.shards.filter((s) => s.status === 'failed')
|
|
8272
|
+
* throw new Error(`${failed.length}/${run.parallelism} shards failed`)
|
|
8273
|
+
* }
|
|
8274
|
+
* ```
|
|
8275
|
+
*/
|
|
8276
|
+
async runDistributed(config, options) {
|
|
8277
|
+
const sharded = options.parallelism > 1;
|
|
8278
|
+
const completionMode = options.completionMode ?? "Indexed";
|
|
8279
|
+
const run = await callApi(config, "/runs", {
|
|
8280
|
+
method: "POST",
|
|
8281
|
+
body: {
|
|
8282
|
+
...runImageSourceBody(options),
|
|
8283
|
+
command: options.command,
|
|
8284
|
+
env: options.env,
|
|
8285
|
+
machine: options.machine ?? "standard",
|
|
8286
|
+
timeoutSeconds: options.timeoutSeconds ?? 3600,
|
|
8287
|
+
volumeMounts: options.volumeMounts,
|
|
8288
|
+
parallelism: options.parallelism,
|
|
8289
|
+
...sharded ? {
|
|
8290
|
+
completionMode,
|
|
8291
|
+
gangScheduling: options.gangScheduling ?? true,
|
|
8292
|
+
...options.backoffLimitPerIndex === void 0 ? {} : { backoffLimitPerIndex: options.backoffLimitPerIndex }
|
|
8293
|
+
} : {}
|
|
8294
|
+
}
|
|
8295
|
+
});
|
|
8296
|
+
return new DistributedRunHandle(run.id, config, options.parallelism, completionMode);
|
|
8297
|
+
},
|
|
8298
|
+
// --------------------------------------------------------------------------
|
|
8299
|
+
// Get (distributed)
|
|
8300
|
+
// --------------------------------------------------------------------------
|
|
8301
|
+
/**
|
|
8302
|
+
* Get a {@link DistributedRunHandle} for an existing distributed run by ID.
|
|
8303
|
+
*
|
|
8304
|
+
* Pass the `parallelism` the run was created with so the handle requests +
|
|
8305
|
+
* renders the correct N-shard aggregate. Useful for resuming monitoring (e.g.
|
|
8306
|
+
* a CLI `runs get <id> --parallelism N`) across processes.
|
|
8307
|
+
*
|
|
8308
|
+
* @example
|
|
8309
|
+
* ```typescript
|
|
8310
|
+
* const handle = RunsClient.runDistributedFromId(config, storedRunId, 16)
|
|
8311
|
+
* const result = await handle.wait()
|
|
8312
|
+
* ```
|
|
8313
|
+
*/
|
|
8314
|
+
runDistributedFromId(config, runId, parallelism, completionMode = "Indexed") {
|
|
8315
|
+
return new DistributedRunHandle(runId, config, parallelism, completionMode);
|
|
8316
|
+
},
|
|
8317
|
+
// --------------------------------------------------------------------------
|
|
7581
8318
|
// Get
|
|
7582
8319
|
// --------------------------------------------------------------------------
|
|
7583
8320
|
/**
|
|
@@ -7950,6 +8687,7 @@ var functions = {
|
|
|
7950
8687
|
};
|
|
7951
8688
|
export {
|
|
7952
8689
|
ACHIEVEMENT_TIER_CONFIG,
|
|
8690
|
+
ArtifactClient,
|
|
7953
8691
|
AuthenticationError,
|
|
7954
8692
|
AuthorizationError,
|
|
7955
8693
|
BILLING_ALLOWED_ROLES,
|
|
@@ -7978,6 +8716,8 @@ export {
|
|
|
7978
8716
|
DEFAULT_POINTS_REWARD,
|
|
7979
8717
|
DISCOUNT_DURATION_MONTHS,
|
|
7980
8718
|
DISCOUNT_PERCENT,
|
|
8719
|
+
DeviceSessionClient,
|
|
8720
|
+
DistributedRunHandle,
|
|
7981
8721
|
ERROR_CODE_STATUS,
|
|
7982
8722
|
FREE_COMPUTE_HOURS,
|
|
7983
8723
|
FREE_STORAGE_GB,
|
|
@@ -8006,11 +8746,13 @@ export {
|
|
|
8006
8746
|
PREMIUM_TRIAL_DAYS,
|
|
8007
8747
|
RETRYABLE_CODES,
|
|
8008
8748
|
RateLimitError,
|
|
8749
|
+
RenderClient,
|
|
8009
8750
|
RunHandle,
|
|
8010
8751
|
RunsClient,
|
|
8011
8752
|
SERVICE_METRICS,
|
|
8012
8753
|
STORAGE_PRICE_PER_GB_MONTH_MICRODOLLARS,
|
|
8013
8754
|
SandboxBrowser,
|
|
8755
|
+
SandboxCapabilities,
|
|
8014
8756
|
SandboxClient,
|
|
8015
8757
|
SandboxComputer,
|
|
8016
8758
|
SandboxFiles,
|
|
@@ -8023,6 +8765,7 @@ export {
|
|
|
8023
8765
|
TimeoutError,
|
|
8024
8766
|
TriggersClient,
|
|
8025
8767
|
ValidationError,
|
|
8768
|
+
WalletClient,
|
|
8026
8769
|
RunHandle as WorkerHandle,
|
|
8027
8770
|
WorkersClient,
|
|
8028
8771
|
acceptAllConsents,
|
|
@@ -8179,6 +8922,7 @@ export {
|
|
|
8179
8922
|
getStreak,
|
|
8180
8923
|
getSubscription,
|
|
8181
8924
|
getTask,
|
|
8925
|
+
getTaskRun,
|
|
8182
8926
|
getUser,
|
|
8183
8927
|
getUserByEmail,
|
|
8184
8928
|
getUserConsents,
|
|
@@ -8191,6 +8935,7 @@ export {
|
|
|
8191
8935
|
getWebhookDelivery,
|
|
8192
8936
|
getWebhookStats,
|
|
8193
8937
|
getWorkspace,
|
|
8938
|
+
getWorkspaceCapacity,
|
|
8194
8939
|
hasAllPermissions,
|
|
8195
8940
|
hasAnyPermission,
|
|
8196
8941
|
hasBillingAccess,
|
|
@@ -8264,6 +9009,7 @@ export {
|
|
|
8264
9009
|
parseUserAgent,
|
|
8265
9010
|
password,
|
|
8266
9011
|
pauseCron,
|
|
9012
|
+
pinWorkspace,
|
|
8267
9013
|
platformAuth,
|
|
8268
9014
|
campaigns as pushCampaigns,
|
|
8269
9015
|
segments as pushSegments,
|
|
@@ -8271,6 +9017,8 @@ export {
|
|
|
8271
9017
|
rateLimits,
|
|
8272
9018
|
realtime,
|
|
8273
9019
|
realtimeEmit,
|
|
9020
|
+
reclaimWorkspace,
|
|
9021
|
+
reclaimWorkspaceSubpath,
|
|
8274
9022
|
recordStreakActivity,
|
|
8275
9023
|
recoverStreak,
|
|
8276
9024
|
redeemPromo,
|
|
@@ -8313,6 +9061,7 @@ export {
|
|
|
8313
9061
|
sendEmailToUser,
|
|
8314
9062
|
sendPush,
|
|
8315
9063
|
sendTemplatedEmail,
|
|
9064
|
+
serve,
|
|
8316
9065
|
sessions,
|
|
8317
9066
|
setConsents,
|
|
8318
9067
|
setEnvVar,
|
|
@@ -8328,6 +9077,8 @@ export {
|
|
|
8328
9077
|
submitScore,
|
|
8329
9078
|
suspendUser,
|
|
8330
9079
|
switchOrg,
|
|
9080
|
+
task,
|
|
9081
|
+
taskStub,
|
|
8331
9082
|
toPublicMachineSize,
|
|
8332
9083
|
toSylphxError,
|
|
8333
9084
|
track,
|