@convilyn/sdk 0.2.0 → 0.4.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.
@@ -1,10 +1,16 @@
1
1
  // src/errors.ts
2
+ var CONVILYN_ERROR_BRAND = /* @__PURE__ */ Symbol.for("@convilyn/sdk.ConvilynError");
2
3
  var ConvilynError = class extends Error {
4
+ /** @internal brand marker — see {@link isConvilynError} */
5
+ [CONVILYN_ERROR_BRAND] = true;
3
6
  constructor(message) {
4
7
  super(message);
5
8
  this.name = "ConvilynError";
6
9
  }
7
10
  };
11
+ function isConvilynError(err) {
12
+ return typeof err === "object" && err !== null && err[CONVILYN_ERROR_BRAND] === true;
13
+ }
8
14
  var AuthError = class extends ConvilynError {
9
15
  constructor(message) {
10
16
  super(message);
@@ -105,14 +111,22 @@ var GoalJobTimeoutError = class extends ConvilynError {
105
111
  jobSpecId;
106
112
  elapsed;
107
113
  timeout;
114
+ /**
115
+ * `'total'` — the overall `timeout` budget lapsed; `'idle'` —
116
+ * `idleTimeout` lapsed with no status/progress change (the job may still
117
+ * be healthy on a long phase; `retrieve()` before assuming failure).
118
+ */
119
+ reason;
108
120
  constructor(opts) {
121
+ const reason = opts.reason ?? "total";
109
122
  super(
110
- `GoalJob ${opts.jobSpecId} did not reach a terminal status within ${opts.timeout}s (elapsed ${opts.elapsed.toFixed(1)}s)`
123
+ reason === "idle" ? `GoalJob ${opts.jobSpecId} showed no status/progress change for ${opts.timeout}s (elapsed ${opts.elapsed.toFixed(1)}s total)` : `GoalJob ${opts.jobSpecId} did not reach a terminal status within ${opts.timeout}s (elapsed ${opts.elapsed.toFixed(1)}s)`
111
124
  );
112
125
  this.name = "GoalJobTimeoutError";
113
126
  this.jobSpecId = opts.jobSpecId;
114
127
  this.elapsed = opts.elapsed;
115
128
  this.timeout = opts.timeout;
129
+ this.reason = reason;
116
130
  }
117
131
  };
118
132
  var WebSocketError = class extends ConvilynError {
@@ -324,7 +338,7 @@ function emitSoftLimitWarning(opts) {
324
338
  }
325
339
 
326
340
  // src/version.ts
327
- var VERSION = "0.2.0";
341
+ var VERSION = "0.4.0";
328
342
 
329
343
  // src/internal/auth.ts
330
344
  var ENV_API_KEY = "CONVILYN_API_KEY";
@@ -755,6 +769,29 @@ function parseGoalJob(wire) {
755
769
  completedAt: toDateOrNull(wire.completedAt)
756
770
  };
757
771
  }
772
+ function parseArtifact(wire) {
773
+ return {
774
+ artifactId: String(wire.artifactId),
775
+ fileName: String(wire.fileName),
776
+ mimeType: String(wire.mimeType),
777
+ sizeBytes: Number(wire.sizeBytes ?? 0),
778
+ downloadUrl: wire.downloadUrl ?? null,
779
+ artifactType: wire.artifactType ?? null,
780
+ platform: wire.platform ?? null,
781
+ metadata: isRecord2(wire.metadata) ? wire.metadata : null,
782
+ isPrimary: Boolean(wire.isPrimary ?? false),
783
+ description: String(wire.description ?? "")
784
+ };
785
+ }
786
+ function parseArtifactDownload(wire) {
787
+ return {
788
+ downloadUrl: String(wire.downloadUrl),
789
+ fileName: String(wire.fileName),
790
+ sizeBytes: Number(wire.sizeBytes ?? 0),
791
+ mimeType: String(wire.mimeType),
792
+ expiresAt: toDate(wire.expiresAt)
793
+ };
794
+ }
758
795
  function parseGoalEvent(wire) {
759
796
  return {
760
797
  type: wire.type,
@@ -807,6 +844,27 @@ function parseWorkflowSearchPage(wire) {
807
844
  cursor: wire.cursor ?? null
808
845
  };
809
846
  }
847
+ function parseCatalogWorkflow(wire) {
848
+ return {
849
+ workflowId: String(wire.workflowId),
850
+ name: String(wire.name),
851
+ description: String(wire.description ?? ""),
852
+ icon: wire.icon ?? null,
853
+ supportedInputTypes: Array.isArray(wire.supportedInputTypes) ? wire.supportedInputTypes.map(String) : [],
854
+ supportedInputFormats: Array.isArray(wire.supportedInputFormats) ? wire.supportedInputFormats.map(String) : null,
855
+ category: String(wire.category ?? "goal_lane"),
856
+ requiredSlotCount: Number(wire.requiredSlotCount ?? 0),
857
+ subcategory: wire.subcategory ?? null,
858
+ skuGroup: wire.skuGroup ?? null,
859
+ status: String(wire.status ?? "active"),
860
+ supportedLocales: Array.isArray(wire.supportedLocales) ? wire.supportedLocales.map(String) : null,
861
+ maxInputSizeBytes: wire.maxInputSizeBytes ?? null,
862
+ minFileCount: wire.minFileCount ?? null,
863
+ tier: wire.tier ?? null,
864
+ // Tri-state: only an explicit false blocks a Free-tier run; absent stays null.
865
+ freeTierAllowed: wire.freeTierAllowed ?? null
866
+ };
867
+ }
810
868
  function parseLikeResponse(wire) {
811
869
  return {
812
870
  liked: Boolean(wire.liked),
@@ -892,6 +950,52 @@ var Account = class {
892
950
  }
893
951
  };
894
952
 
953
+ // src/internal/download.ts
954
+ var MAX_DOWNLOAD_BYTES = 2 * 1024 ** 3;
955
+ async function downloadUrlToPath(http, url, to, maxBytes = MAX_DOWNLOAD_BYTES) {
956
+ const { lstat, open, unlink } = await import('fs/promises');
957
+ const st = await lstat(to).catch(() => null);
958
+ if (st?.isSymbolicLink()) {
959
+ throw new Error(
960
+ `Refusing to write to ${JSON.stringify(to)}: target is a symlink. Remove it or choose a non-symlink destination.`
961
+ );
962
+ }
963
+ const response = await http.externalGet(url);
964
+ const body = response.body;
965
+ const handle = await open(to, "w");
966
+ let written = 0;
967
+ try {
968
+ if (body == null) {
969
+ const bytes = new Uint8Array(await response.arrayBuffer());
970
+ written = bytes.byteLength;
971
+ if (written > maxBytes) {
972
+ throw new Error(`Download exceeds the ${maxBytes}-byte cap`);
973
+ }
974
+ await handle.write(bytes);
975
+ } else {
976
+ const reader = body.getReader();
977
+ for (; ; ) {
978
+ const { done, value } = await reader.read();
979
+ if (done) {
980
+ break;
981
+ }
982
+ written += value.byteLength;
983
+ if (written > maxBytes) {
984
+ await reader.cancel().catch(() => void 0);
985
+ throw new Error(`Download exceeds the ${maxBytes}-byte cap`);
986
+ }
987
+ await handle.write(value);
988
+ }
989
+ }
990
+ } catch (error) {
991
+ await handle.close().catch(() => void 0);
992
+ await unlink(to).catch(() => void 0);
993
+ throw error;
994
+ }
995
+ await handle.close();
996
+ return to;
997
+ }
998
+
895
999
  // src/resources/convert.ts
896
1000
  var DEFAULT_POLL_INTERVAL = 1;
897
1001
  var DEFAULT_POLL_TIMEOUT = 300;
@@ -987,17 +1091,7 @@ var Convert = class {
987
1091
  /** Download the first result file to `to` (Node) and return that path. */
988
1092
  async downloadTo(job, { to }) {
989
1093
  const url = await this.downloadUrl(job);
990
- const { lstat, writeFile } = await import('fs/promises');
991
- const st = await lstat(to).catch(() => null);
992
- if (st?.isSymbolicLink()) {
993
- throw new Error(
994
- `Refusing to write to ${JSON.stringify(to)}: target is a symlink. Remove it or choose a non-symlink destination.`
995
- );
996
- }
997
- const response = await this.#http.externalGet(url);
998
- const bytes = new Uint8Array(await response.arrayBuffer());
999
- await writeFile(to, bytes);
1000
- return to;
1094
+ return downloadUrlToPath(this.#http, url, to);
1001
1095
  }
1002
1096
  // ── private ────────────────────────────────────────────────────
1003
1097
  #resolveSource(options) {
@@ -1152,6 +1246,19 @@ var Files = class {
1152
1246
  const contentType = options.contentType ?? guessContentType(filename);
1153
1247
  return this.#uploadWithBody(bytes, filename, contentType);
1154
1248
  }
1249
+ /**
1250
+ * Delete an uploaded file's cloud copy (storage object + metadata record).
1251
+ *
1252
+ * Only the uploader can delete; a missing or unowned `fileId` surfaces as
1253
+ * a 404 `APIError` and a file attached to a still-running job as a 409
1254
+ * (`FILE_IN_USE`). The platform deletes input files automatically ~1 hour
1255
+ * after upload anyway — call this when you want the cloud copy gone
1256
+ * deterministically the moment your workflow is done (e.g. privacy-
1257
+ * sensitive documents on an edge device). Port of Python `files.delete`.
1258
+ */
1259
+ async delete(fileId) {
1260
+ await this.#http.request("DELETE", `/api/v1/files/${fileId}`);
1261
+ }
1155
1262
  async #uploadWithBody(body, filename, contentType) {
1156
1263
  const size = body.byteLength;
1157
1264
  const presign = await this.#presign(filename, size, contentType);
@@ -1352,7 +1459,8 @@ var Goals = class {
1352
1459
  return this.#waitLoop(
1353
1460
  jobSpecId,
1354
1461
  options.timeout ?? DEFAULT_POLL_TIMEOUT2,
1355
- options.pollInterval ?? DEFAULT_POLL_INTERVAL2
1462
+ options.pollInterval ?? DEFAULT_POLL_INTERVAL2,
1463
+ options.idleTimeout ?? null
1356
1464
  );
1357
1465
  }
1358
1466
  /** Shortcut: {@link start} then {@link wait}. */
@@ -1360,7 +1468,8 @@ var Goals = class {
1360
1468
  const job = await this.start(options);
1361
1469
  return this.wait(job.jobSpecId, {
1362
1470
  timeout: options.timeout,
1363
- pollInterval: options.pollInterval
1471
+ pollInterval: options.pollInterval,
1472
+ idleTimeout: options.idleTimeout
1364
1473
  });
1365
1474
  }
1366
1475
  /** Answer a single slot the agent is waiting on (sugar over {@link fillSlots}). */
@@ -1390,9 +1499,17 @@ var Goals = class {
1390
1499
  });
1391
1500
  return parseGoalJob(await response.json());
1392
1501
  }
1393
- /** Confirm a slots-filled job, queueing it for execution. */
1502
+ /**
1503
+ * Confirm a slots-filled job, queueing it for execution.
1504
+ *
1505
+ * `expectedVersion` is optional — the server re-reads the current version
1506
+ * at submit time regardless, so most callers should simply omit it. The
1507
+ * request always carries a JSON object (`{}` when empty): older backend
1508
+ * builds declare the confirm body as a required parameter and reject a
1509
+ * body-less POST with 422 before the handler runs.
1510
+ */
1394
1511
  async confirm(jobSpecId, options = {}) {
1395
- const json = options.expectedVersion != null ? { expectedVersion: options.expectedVersion } : void 0;
1512
+ const json = options.expectedVersion != null ? { expectedVersion: options.expectedVersion } : {};
1396
1513
  await this.#http.request("POST", `/api/v1/jobs/goal/${jobSpecId}/confirm`, { json });
1397
1514
  return this.#pollOnce(jobSpecId);
1398
1515
  }
@@ -1410,6 +1527,41 @@ var Goals = class {
1410
1527
  await this.#http.request("POST", `/api/v1/jobs/goal/${jobSpecId}/retry`, { json: body });
1411
1528
  return this.#pollOnce(jobSpecId);
1412
1529
  }
1530
+ /**
1531
+ * List a completed job's output artifacts with fresh download URLs.
1532
+ *
1533
+ * Available once the job is terminal-successful (`completed` or `partial`);
1534
+ * any other status surfaces the backend's 400 as an `APIError`. Each
1535
+ * artifact's `downloadUrl` is presigned and valid for one hour — re-call
1536
+ * this method for fresh URLs rather than persisting one.
1537
+ */
1538
+ async artifacts(jobSpecId) {
1539
+ const response = await this.#http.request("GET", `/api/v1/jobs/goal/${jobSpecId}/artifacts`);
1540
+ const payload = await response.json();
1541
+ const rows = Array.isArray(payload.artifacts) ? payload.artifacts : [];
1542
+ return rows.map((row) => parseArtifact(row));
1543
+ }
1544
+ /**
1545
+ * Mint a fresh presigned download URL for one artifact. Prefer this over
1546
+ * reusing a stale {@link Artifact.downloadUrl} when more than an hour may
1547
+ * have passed since {@link artifacts}.
1548
+ */
1549
+ async downloadArtifactUrl(jobSpecId, artifactId) {
1550
+ const response = await this.#http.request(
1551
+ "GET",
1552
+ `/api/v1/jobs/goal/${jobSpecId}/artifacts/${artifactId}/download`
1553
+ );
1554
+ return parseArtifactDownload(await response.json());
1555
+ }
1556
+ /**
1557
+ * Download one artifact to `to` (Node) and return that path. Mints a fresh
1558
+ * presigned URL first, then streams the body to disk (shares the size-cap
1559
+ * and symlink-refusal contract with `convert.downloadTo`).
1560
+ */
1561
+ async downloadArtifactTo(jobSpecId, artifactId, { to }) {
1562
+ const info = await this.downloadArtifactUrl(jobSpecId, artifactId);
1563
+ return downloadUrlToPath(this.#http, info.downloadUrl, to);
1564
+ }
1413
1565
  /**
1414
1566
  * Stream goal execution events for a job. Opens a WebSocket, subscribes,
1415
1567
  * then yields each {@link GoalEvent} in order; the iterator ends (and the
@@ -1464,11 +1616,13 @@ var Goals = class {
1464
1616
  const response = await this.#http.request("GET", `/api/v1/jobs/goal/${jobSpecId}`);
1465
1617
  return parseGoalJob(await response.json());
1466
1618
  }
1467
- async #waitLoop(jobSpecId, timeout, initialInterval) {
1619
+ async #waitLoop(jobSpecId, timeout, initialInterval, idleTimeout) {
1468
1620
  const start = this.#now() / 1e3;
1469
1621
  let interval = initialInterval;
1470
1622
  let staleCount = 0;
1471
1623
  let lastProgress = -1;
1624
+ let lastStatus = null;
1625
+ let lastChange = start;
1472
1626
  for (; ; ) {
1473
1627
  const job = await this.#pollOnce(jobSpecId);
1474
1628
  if (isGoalJobTerminal(job)) {
@@ -1477,6 +1631,10 @@ var Goals = class {
1477
1631
  if (goalJobNeedsInput(job)) {
1478
1632
  return job;
1479
1633
  }
1634
+ if (job.status !== lastStatus) {
1635
+ lastStatus = job.status;
1636
+ lastChange = this.#now() / 1e3;
1637
+ }
1480
1638
  if (job.progress === lastProgress) {
1481
1639
  staleCount += 1;
1482
1640
  if (staleCount >= STALE_PROGRESS_BACKOFF_AFTER2) {
@@ -1485,12 +1643,17 @@ var Goals = class {
1485
1643
  }
1486
1644
  } else {
1487
1645
  lastProgress = job.progress;
1646
+ lastChange = this.#now() / 1e3;
1488
1647
  staleCount = 0;
1489
1648
  }
1490
- const elapsed = this.#now() / 1e3 - start;
1649
+ const now = this.#now() / 1e3;
1650
+ const elapsed = now - start;
1491
1651
  if (elapsed + interval > timeout) {
1492
1652
  throw new GoalJobTimeoutError({ jobSpecId, elapsed, timeout });
1493
1653
  }
1654
+ if (idleTimeout != null && now - lastChange + interval > idleTimeout) {
1655
+ throw new GoalJobTimeoutError({ jobSpecId, elapsed, timeout: idleTimeout, reason: "idle" });
1656
+ }
1494
1657
  await this.#sleep(interval);
1495
1658
  }
1496
1659
  }
@@ -1538,6 +1701,20 @@ var Workflows = class {
1538
1701
  constructor(http) {
1539
1702
  this.#http = http;
1540
1703
  }
1704
+ /**
1705
+ * List the platform's built-in AI-workflow catalog.
1706
+ *
1707
+ * Distinct from {@link search}, which browses the user-published community
1708
+ * marketplace — the catalog is the curated set of built-in workflows
1709
+ * runnable directly via `goals.start({ workflowId })`. Anonymous callers
1710
+ * are allowed; deprecated entries are filtered out server-side.
1711
+ */
1712
+ async catalog() {
1713
+ const response = await this.#http.request("GET", "/api/v1/workflows/catalog");
1714
+ const payload = await response.json();
1715
+ const rows = Array.isArray(payload.workflows) ? payload.workflows : [];
1716
+ return rows.map((row) => parseCatalogWorkflow(row));
1717
+ }
1541
1718
  /** Browse the public community listing (one page + a `cursor`). */
1542
1719
  async search(options = {}) {
1543
1720
  const params = {
@@ -1608,6 +1785,9 @@ var Convilyn = class {
1608
1785
  #http;
1609
1786
  constructor(options = {}) {
1610
1787
  const auth = options.auth ?? resolveAuth(options.apiKey);
1788
+ if (options.timeout !== void 0 && options.timeout <= 0) {
1789
+ throw new TypeError(`timeout must be a positive number of seconds (got ${options.timeout})`);
1790
+ }
1611
1791
  this.#http = new HttpClient({
1612
1792
  auth,
1613
1793
  baseUrl: options.baseUrl,
@@ -1639,12 +1819,15 @@ function resolveRetryPolicy(maxRetries, retryPolicy) {
1639
1819
  if (maxRetries == null) {
1640
1820
  return new ExponentialBackoffRetry();
1641
1821
  }
1642
- if (maxRetries <= 0) {
1822
+ if (maxRetries < 0) {
1823
+ throw new TypeError(`maxRetries must be >= 0 (got ${maxRetries})`);
1824
+ }
1825
+ if (maxRetries === 0) {
1643
1826
  return new NoRetry();
1644
1827
  }
1645
1828
  return new ExponentialBackoffRetry({ maxAttempts: maxRetries });
1646
1829
  }
1647
1830
 
1648
- export { APIError, AuthError, AutoThrottleConfig, CONVERT_JOB_TERMINAL_STATUSES, Convilyn, ConvilynError, DEFAULT_BASE_URL, ExponentialBackoffRetry, GOAL_EVENT_TERMINAL_TYPES, GOAL_EVENT_TYPES, GOAL_JOB_TERMINAL_STATUSES, GoalJobFailedError, GoalJobTimeoutError, HttpClient, JobFailedError, JobTimeoutError, NoRetry, PlanRequiredError, QuotaExceededError, RateLimitError, RetryExhaustedError, S3UploadError, VERSION, WebSocketError, goalJobNeedsInput, guessContentType, isConvertJobTerminal, isGoalEventTerminal, isGoalEventType, isGoalJobTerminal, resolveAuth };
1649
- //# sourceMappingURL=chunk-UJHZKIP6.js.map
1650
- //# sourceMappingURL=chunk-UJHZKIP6.js.map
1831
+ export { APIError, AuthError, AutoThrottleConfig, CONVERT_JOB_TERMINAL_STATUSES, Convilyn, ConvilynError, DEFAULT_BASE_URL, ExponentialBackoffRetry, GOAL_EVENT_TERMINAL_TYPES, GOAL_EVENT_TYPES, GOAL_JOB_TERMINAL_STATUSES, GoalJobFailedError, GoalJobTimeoutError, HttpClient, JobFailedError, JobTimeoutError, NoRetry, PlanRequiredError, QuotaExceededError, RateLimitError, RetryExhaustedError, S3UploadError, VERSION, WebSocketError, goalJobNeedsInput, guessContentType, isConvertJobTerminal, isConvilynError, isGoalEventTerminal, isGoalEventType, isGoalJobTerminal, resolveAuth };
1832
+ //# sourceMappingURL=chunk-Z5IPYRO3.js.map
1833
+ //# sourceMappingURL=chunk-Z5IPYRO3.js.map